blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9b357b6d7800948216c20643a92aeb63f7d27d5f | ezequielln87/python | /introducao_python/sp4 - lista insert(append).py | 264 | 3.6875 | 4 | def ValorLista():
for i in range(1,5):
lista.append(int(input(f'Digite o valor da sua prova {i}')))
def Media():
s=0
for i in range(len(lista)):
s = s + lista[i]
m = s / 4
return m
lista = []
ValorLista()
m = Media()
print(m) |
2bd57fc193ccc586c19b096c926eb294609d3d34 | ChinhNguyenVan/pythonbasic | /List.py | 1,558 | 3.625 | 4 | # 1, List là gì? và khai báo list trong Python.
# List trong Python là một dạng dữ liệu cho phép lưu trữ nhiều kiểu dữ liệu khác nhau trong nó,
# và chũng ta có thể truy xuất đến các phần tử bên trong nó thông qua vị trí của phần tử đó trong list.
# Ở đây, nếu như bạn nào đã tìm hiểu qua một ngôn ngữ nào đó thì có thể coi list trong Python
# như một mảng tuần tự trong các ngôn ngữ khác.
# Để khai báo một list trong Python thì chúng ta sử dụng cặp dấu [] và bên trong là các giá trị của list.
# [value1, value2,..., valueN]
# Trong đó: value1, value2,..., valueN là các giá trị của list.
# VD: Mình sẽ khai báo 1 list chứa tên các học sinh.
name = ['NGUYEN VAN CHINH', 'VO VAN LINH', 'NGUYEN VAN TU','NGUYEN XUAN HAO']
# 2, Truy cập đến các giá trị trong list.
name = ['NGUYEN VAN CHINH', 'VO VAN LINH', 'NGUYEN VAN TU','NGUYEN XUAN HAO']
print(name[-1])
print(name[-2])
print(name[0])
print(name[1])
#list[start:end]
print(name[0:1])
print(name[0:2])
print(name[-4:-1])
# 3, Sửa đổi và xóa bỏ giá trị phần tử trong list.
name1 = ['MAI NANG LEN', 'LUNG THI LINH', 'NONG MANH ONG','VU THI LAN']
#Update
name1[2] = 'HOANG THUY LINH'
print(name1)
#Delete
del name1[1]
print(name1)
# 4, List lồng nhau.
#Do list có thể chứa nhiều kiểu dữ liệu khác nhau lên
# chúng ta hoàn toàn có thể khai báo một list chứa một hoặc nhiều list khác nhau.
FullName=[name,name1]
print(FullName)
name2=[1,'hello','loto',[2,'Linh Tinh','Love']]
print(name2)
|
eb3cb03e43570cfb2fef8785a50024f22cfee62e | YovchoGandjurov/Python-Fundamentals | /01. Functions. Debugging and Troubleshooting code/02.Sign_of_Integer_Number.py | 225 | 4.0625 | 4 | n = int(input())
def string(n):
if n > 0:
print('The number', n, 'is positive.')
if n < 0:
print('The number', n, 'is negative.')
if n == 0:
print('The number', n, 'is zero.')
string(n)
|
e3c857cb45f59fe1de6d15f69d28c40fb8d00704 | sanjugr/substitutionCipher | /decryption/decryption.py | 7,785 | 3.703125 | 4 | #Decryption
from flask import Flask,render_template, request
from constants import *
import re
##-----------get cipher text from from txtfile----------------------##
def getCipherText(filename):
file = open(filename,'r') # r means read and w means write
cipherText = file.read()
cipherText = re.sub("[^a-zA-Z]+", "", cipherText)
return cipherText.lower()
##---------- To get the initial putative key by analyzing the frequency in cipher text----------##
def getFirstKey(cipherText):
frequencyOfCipherArray = [0 for x in range(rowLen)]
newKey = [0 for x in range(rowLen)]
englishFrequencyList = list(englishFrequency)
for i in range(0,26):
frequencyOfCipherArray[i]=cipherText.count(numberSpaceList[i])# pushing the count of each alphabets into an array
print("The initial frequecy of ciper text letters from a -z is shown below : " )
print(frequencyOfCipherArray)
#print("\n\rThe largest frequencies are replaced by -1 and its position is added with the most frequent letters in english language: ")
for j in range(0, rowLen):
flag = 0
for k in range (0, rowLen):
if frequencyOfCipherArray[flag] <= frequencyOfCipherArray[k]:
flag = k
chartemp = englishFrequencyList[j]
newKey[numberSpace.index(chartemp)] = numberSpace[flag]
frequencyOfCipherArray[flag]= -1# replace the max frequency value with -1 so that the next biggest value will be taken
#print(frequencyOfCipherArray)# to see its getting replaced after each step
return "".join(newKey)
##----------- converts the cipher text into initial plain text with the key generated from above function-------##
def getInitialPlainText(message, key=None):
newPlainList = []
for char in message:
newPlainList.append(key[numberSpace.index(char)]) # Appending the ciphered text into the new list
return "".join(newPlainList) #Returning the initial plain text corresponding to the cipher text
#---------This below function returns the diagram frequency matrix numbers for any text string as input----##.
def getDiagramFrequency(plainText):
diagramMatrix = [[0 for x in range(rowLen)] for y in range(colLen)] #matrix for storing the diagram of particular language
diagramFrequencyMatrix = [[0 for x in range(rowLen)] for y in range(colLen)]
planTextLength = len(plainText)
value = planTextLength/ float(SenLength)
for i in range(0,rowLen):
for j in range(0,colLen):
a=numberSpaceList[i]
b=numberSpaceList[j]
newArray=[a,b] #geting the values aa,ab ac etc
diagramMatrix[i][j]= "".join(newArray) # initializing the initial diagram frequency matrix
a = plainText.count(diagramMatrix[i][j])
diagramFrequencyMatrix[i][j] = a
for i in range(0,rowLen):
for j in range(0,colLen):
diagramFrequencyMatrix[i][j]=round(diagramFrequencyMatrix[i][j]/ float(value))
return diagramFrequencyMatrix
##--------The below function returns the score computed with a standard english diagram frequency matrix---------##
def getScore(matrix):
score = 0
for i in range(0,rowLen):
for j in range(0,colLen):
score+= abs(matrix[i][j]-englishDiagramMatrix[i][j])
return score
##------------The below function is to swap the given rows and column of a given matrix----------------------##
def swapRowColOfMatrix(matrix, pos1, pos2):
tempRow = 0
tempCol= 0
matrixTemp = [[0 for x in range(rowLen)] for y in range(colLen)]
matrixTemp= copyMatrixValues(matrix)
#swapping rows first
for j in range(0, colLen):
tempRow = matrixTemp[pos1][j]
matrixTemp[pos1][j]=matrixTemp[pos2][j]
matrixTemp[pos2][j]=tempRow
#swapping the column
for i in range(0, rowLen):
tempCol = matrixTemp[i][pos1]
matrixTemp[i][pos1]=matrixTemp[i][pos2]
matrixTemp[i][pos2]=tempCol
return matrixTemp
##------------------The below function is to swap the characters in key position-------------------##
def swapKeyCharacters(key, pos1, pos2):
keyList = list(key)
temp = keyList[pos1]
keyList[pos1]=keyList[pos2]
keyList[pos2] = temp
return "".join(keyList)
#-----------------The below function is to copy the matrix values into a new matrix
def copyMatrixValues(inputMatrix):
matrixCopy= [[0 for x in range(rowLen)] for y in range(colLen)]
for i in range(0,rowLen):
for j in range(0,colLen):
matrixCopy[i][j] = inputMatrix[i][j]
return matrixCopy
##----------The below fuction is to compute the iterations and get the final key for the plain text----------------##
def getFinalKey(D, key):
score = getScore(D)
for k in range(0, 5):
for i in range(0, 26):
for j in range(0, 26-i):
D2= copyMatrixValues(D)
D2=swapRowColOfMatrix(D, j, j+i)
scoreTemp = getScore(D2)
if(scoreTemp <= score):
D=copyMatrixValues(D2)
key = swapKeyCharacters(key, j, j+i)
score = scoreTemp
return key
#-------the below function is used to decrypt the ciper text by giving the key and cipher as inputs
def decrypt(cipher, key=None):
if key is not None:
newDecryptedList = []
for char in cipher:
newDecryptedList.append(numberSpace[key.index(char)])
return "".join(newDecryptedList)
#######---------------------------------MAIN FUNCTION(Can be used if we are getting the input cipher text from a text file)---------------------------######################3
def main():
cipherText = getCipherText("cipher3.txt")
#cipherText = getCipherText("cipher2.txt")
initialKey = getFirstKey(cipherText)
print("\n\rThe first Key generated from analyzing the cipher text : ")
print(initialKey)
print("\n\r The cipher text is")
print(cipherText)
print("\n\rThe initial Plan Text : ")
initialPlainText = decrypt(cipherText, initialKey)
print(initialPlainText)
print("\n\rThe Diagram Frequency matrix of initial plain text : ")
D=getDiagramFrequency(initialPlainText)
print (D)
finalKey = getFinalKey(D, initialKey)
print("The final key after crypto analysis is :" +finalKey)
print("The final decrypted message is : ")
print(decrypt(cipherText, finalKey))
#----Main Function(To be used if the input is taken from a webpage)--------##
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/decryptText', methods=['POST'])
def decryptText():
if request.method =="POST":
cipherText= request.form["cipherText_input"]
cipherText = re.sub("[^a-zA-Z]+", "", cipherText)
initialKey = getFirstKey(cipherText)
print("\n\rThe first Key generated from analyzing the cipher text : ")
print(initialKey)
print("\n\r The cipher text is")
print(cipherText)
print("\n\rThe initial Plan Text : ")
initialPlainText = decrypt(cipherText, initialKey)
print(initialPlainText)
print("\n\rThe Diagram Frequency matrix of initial plain text : ")
D=getDiagramFrequency(initialPlainText)
print (D)
finalKey = getFinalKey(D, initialKey)
print("The final key after crypto analysis is :" +finalKey)
print("The final decrypted message is : ")
finalDecryptedText = decrypt(cipherText, finalKey)
print(finalDecryptedText)
return render_template('decryption.html', finalDecryptedText=finalDecryptedText,finalKey=finalKey,cipherText= cipherText )
if (__name__ =="__main__"):
app.debug=True
app.run(port=5001)
|
e5577b2dbe37b24b583eb798d2780bbbbc0f3515 | mansal3/MATPLOT-TUTORIAL | /My_Matplot.py | 2,394 | 4.5 | 4 | #MATPLOT
#Matplot is the python pakcage used for 2D data graphics,It is used for Data Visualisation
# One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data
# in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.
#
# Various Types of Plot:
# Histogram
# Barplot
# Scatter plot
# Hexagonal bin plot
# Area plot
# pieplot
from matplotlib import pyplot as plt
plt.plot([1,2,3],[4,5,1])
plt.show()
#now lets add some style in our graoh
from matplotlib import pyplot as plt
plt.plot([1,2,3],[4,5,1])
plt.title("line graph")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend()
plt.show()
# #add color and other style
# from matplotlib import style
# style.use('ggplot')
# x=[2,3,4,5,6]
# y=[5,6,7,3,5]
#
# x1=[3,4,6,2]
# y1=[2,6,7,3,1,3,4]
# plt.plot(x,y,'g',label="line1",linewidth=5)
# plt.plot(x1,y1,'c',label="line2",linewidth=5)
# plt.title("line graph")
# plt.xlabel("x-axis")
# plt.ylabel("y-axis")
# plt.show()
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [ 5 , 2 , 9 , 4 , 7 ]
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot the bar
plt.bar ( x , y )
# function to show the plot
plt.show ()
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot histogram
plt.hist ( y )
# Function to show the plot
plt.show ()
# x-axis values
x = [ 5 , 2 , 9 , 4 , 7 ]
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot scatter
plt.scatter ( x , y )
# function to show the plot
plt.show ()
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot histogram
plt.hist ( y )
# Function to show the plot
plt.show ()
# x-axis values
x = [ 5 , 2 , 9 , 4 , 7 ]
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot scatter
plt.stackplot ( x , y )
# function to show the plot
plt.show ()
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot histogram
plt.hist ( y )
# Function to show the plot
plt.show ()
# x-axis values
x = [ 5 , 2 , 9 , 4 , 7 ]
# Y-axis values
y = [ 10 , 5 , 8 , 4 , 2 ]
# Function to plot scatter
plt.pie ( x , y )
# function to show the plot
plt.show () |
d04e20eaf762609335be72f0420e8cc20ae261c3 | balmydawn/- | /Base/Day03/Exercises/习题4.py | 317 | 3.625 | 4 | # 晚饭后你负责刷掉家里的 10 个碗,当刷到第 5 个碗时停止刷碗
bowl = 1
while bowl <= 10:
if bowl ==5:
print('终于可以不刷了,我都刷到第5个碗了!')
break
else:
print('我在刷第 %d 个碗了,我不想刷了' % bowl)
bowl = bowl + 1
|
41b98e9128854c318b4fea7abae02bb6078c42c6 | Njokosi/python | /HackerRank/Interview Preparation Kit/arrays/2D Arrays -DS.py | 1,813 | 3.796875 | 4 | """
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
An hourglass in is a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in . An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. The array will always be .
Example
-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0
The hourglass sums are:
-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
The highest hourglass sum is from the hourglass beginning at row , column :
0 4 3
1
8 6 6
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Function Description
Complete the function hourglassSum in the editor below.
hourglassSum has the following parameter(s):
int arr[6][6]: an array of integers
Returns
int: the maximum hourglass sum
Input Format
Each of the lines of inputs contains space-separated integers .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
"""
# Complete the hourglassSum function below.
mat = []
for _ in range(6):
mat.extend([list(map(int, input().strip().split()))])
def calculate_sum(i, j):
return mat[i][j] + mat[i][j + 1] + mat[i][j + 2] + \
mat[i + 1][j + 1] + \
mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]
hourglass_sums = []
for row in range(4):
for col in range(4):
hourglass_sum = calculate_sum(row, col)
hourglass_sums.append(hourglass_sum)
print(max(hourglass_sums))
|
2afaf9dae216b398786d05529539d8513e649612 | nspavlo/AlgorithmsPython | /Algorithms/FizzBuzz.py | 657 | 3.921875 | 4 | import unittest
def fizzbuzz(n: int) -> str:
if n % 15 == 0:
return "fizz buzz"
elif n % 3 == 0:
return "fizz"
elif n % 5 == 0:
return "buzz"
else:
return str(n)
class TestFizzBuzz(unittest.TestCase):
def test_one(self):
sut = fizzbuzz(1)
self.assertEqual(sut, "1")
def test_divisible_by_three(self):
sut = fizzbuzz(3)
self.assertEqual(sut, "fizz")
def test_divisible_by_five(self):
sut = fizzbuzz(5)
self.assertEqual(sut, "buzz")
def test_divisible_by_fifteen(self):
sut = fizzbuzz(15)
self.assertEqual(sut, "fizz buzz")
|
bad4c4ccd699d0e1e6ce0f256df21f921a26eaec | ugwls/PRACTICAL_FILE | /32.py | 1,482 | 3.96875 | 4 | # Write a menu driven program where you are getting product
# related details in a file product.txt. menu options are
# 1. Add Details, 2. Search Details, 3. Show Details, 4. Exit
def add():
with open('product.txt', "a") as f:
a = int(input('Enter how many record to add: '))
for _ in range(0, a):
id = int(input('Enter product id: '))
name = input('Enter product name: ')
temp = (id, name)
f.write(f'{temp} \n')
print('product added successfully')
input('Press ENTER to continue...')
def see():
with open("product.txt", "r") as f:
d = f.readlines()
d = [x.strip('\n') for x in d]
for i in d:
print(i)
input('Press ENTER to continue...')
def Search():
with open("product.txt", "r")as f:
d = f.readlines()
d = [eval(x.strip('\n')) for x in d]
name = input('Enter product name to Search: ')
for i in range(0, len(d) - 1):
if d[i][1] == name:
print(f'productinfo is {d[i]}')
k = True
while k == True:
print('''
1. Add Details
2. Search Details
3. Show Details
4. Exit
''')
option = int(input('Enter your option(1/4): '))
if option == 1:
add()
elif option == 2:
Search()
elif option == 3:
see()
elif option == 4:
f = open('product.txt')
f.seek(0)
f.close()
k = False
else:
print("Invalid Option!")
continue
|
c7b70e3f5a19b843e7689fd4127f6c07d03f71c4 | shen-huang/selfteaching-python-camp | /exercises/1901090014/d4_exercise_control_flow.py | 285 | 3.78125 | 4 | for i in range(1,10):
for j in range(1,i+1):
d=i*j
print('%d*%d=%2d'% (i,j,d),end=" ")
print()
print()
a=1
while a<10 :
if a%2==1:
b=1
while b<=a:
print ('%d*%d=%2d'% (a,b,a*b),end=" ")
b=b+1
a=a+1
print()
|
8e659cf0a4f318f4612322cbbed181e008e89771 | jacobgarrison4/Python | /palindrome.py | 282 | 3.890625 | 4 | def palindrome(word):
ct1 = 0
ct2 = -1
while ct1 < (len(word)/2):
if len(word) < 2:
return True
elif word[ct1] == word[ct2]:
ct1 += 1
ct2 -= 1
return True
else:
return False
|
feb209a1bc6a3d1880fd63ab6c6301e1c569d4ad | Draymonder/Practices-on-Pyhton | /Day_7/slots.py | 711 | 3.84375 | 4 | from types import MethodType
class Student(object):
# 用__slots__变量限制能添加的属性
__slots__ = ("name", "age", "set_age") # 只对当前类实例有用,不能用于继承类
def set_age(self, age):
self.age = age
s1 = Student()
s1.name = "Chengkang" #动态绑定属性
s1.set_age = MethodType(set_age, s1)#动态绑定方法
s1.set_age(24) #调用方法
print('%s: %s' % (s1.name, s1.age)) # Output:Chengkang: 24
# 对其他对象不起作用
s2 = Student()
#s2.set_age(25) 报错'Student' object has no attribute 'set_age'
# 解决办法:给类绑定方法
Student.set_age = set_age
s3 = Student()
s3.set_age(23)
s2.set_age(25)
print(s2.age + s3.age) # Output: 48
|
52dd3fbb6e6358dc00e49c48e3a2a9896642d204 | yzwy1988/cloud | /python经典100例/JCP060.py | 824 | 3.625 | 4 | '''
60
Ŀͼۺӡ
1.
2.Դ룺
̲֪ӦȲд
#include "graphics.h"
#define LEFT 0
#define TOP 0
#define RIGHT 639
#define BOTTOM 479
#define LINES 400
#define MAXCOLOR 15
main()
{
int driver,mode,error;
int x1,y1;
int x2,y2;
int dx1,dy1,dx2,dy2,i=1;
int count=0;
int color=0;
driver=VGA;
mode=VGAHI;
initgraph(&driver,&mode,"");
x1=x2=y1=y2=10;
dx1=dy1=2;
dx2=dy2=3;
while(!kbhit())
{
line(x1,y1,x2,y2);
x1+=dx1;y1+=dy1;
x2+=dx2;y2+dy2;
if(x1<=LEFT||x1>=RIGHT)
dx1=-dx1;
if(y1<=TOP||y1>=BOTTOM)
dy1=-dy1;
if(x2<=LEFT||x2>=RIGHT)
dx2=-dx2;
if(y2<=TOP||y2>=BOTTOM)
dy2=-dy2;
if(++count>LINES)
{
setcolor(color);
color=(color>=MAXCOLOR)?0:++color;
}
}
closegraph();
}
''
|
6b90cfc5e34945c3cd37d7834796f9f2c0378fa0 | tashakim/puzzles_python | /growingqueue.py | 1,464 | 3.984375 | 4 | class MyQueue():
def __init__(self, cap):
self._capacity = cap
self._queue = [None]*cap
self._size = 0
self._head = self._tail = 0
def size(self):
return self._size
def is_empty(self):
return self._size == 0
def enqueue(self, item):
self._queue[self._head] = item
print("\nAdded ", item, " to queue.\n")
if(self._size < self._capacity and self._head < self._capacity -1):
self._head +=1
self._size +=1
elif(self._size < self._capacity and self._head == self._capacity -1):
self._head = 0
self._size +=1
elif(self._size == self._capacity):
self._queue[self._head] = item
self._size +=1
self._capacity = self._capacity*2
self._newqueue = []*self._capacity
for i in range(self._capacity):
self._newqueue[(i+self._capacity)%self._tail] = self._queue[i]
self._queue = self._newqueue
self._head = self._size -1
self._tail = 0
return
def dequeue(self):
popped = self._queue[self._tail]
self._tail += 1
return popped
def front(self):
return self._head
def capacity(self):
return self._capacity
if __name__ == "__main__":
q = MyQueue(3)
print("Is queue empty? : ",q.is_empty())
print("Capacity of queue is : ", q.capacity())
q.enqueue(1)
print("size of queue is : ", q.size())
q.enqueue(1)
q.enqueue(1)
print("size of queue is : ", q.size())
q.enqueue(1)
print("size of new queue is : ", q.size())
print(q._head)
print("capacity of new queue is : ", q.capacity())
|
00c1865d3960c31376414670b6604c34805d3c82 | dobryi/Algorithms | /sorting/selection_sort.py | 474 | 3.5 | 4 | import random
def selection_sort(seq):
n = len(seq)
for i in range(n):
min_i = i
for j in range(i + 1, n):
if seq[j] < seq[min_i]:
min_i = j
if min_i != i:
seq[min_i], seq[i] = seq[i], seq[min_i]
return seq
test_seq = [random.randint(-20, 20) for _ in range(20)]
print(test_seq)
sorted_test_seq = selection_sort(test_seq.copy())
print(sorted_test_seq)
assert sorted_test_seq == sorted(test_seq)
|
d66bd909530175f7ef1f78f3293dd82ff848be0f | danielhp02/language-revision | /code/objects.py | 8,019 | 3.828125 | 4 | # -*- coding: utf-8 -*-
from random import sample
import sys
import inout
import readline
class Noun(object):
def __init__(self, english, language, translation, gender):
self.english = english
self.language = language
self.translation = translation
self.gender = gender
self.type = "noun"
class Verb(object):
def __init__(self, english, language, translation, pastParticiple, auxVerb):
self.english = english
self.language = language
self.translation = translation
self.pastParticiple = pastParticiple
self.auxVerb = auxVerb
self.type = "verb"
class Adjective(object):
def __init__(self, english, language, translation):
self.english = english
self.language = language
self.translation = translation
self.type = "adjective"
class WordSet(object):
def __init__(self, language, topic, words):
self.language = language
self.topic = topic
self.words = words
class Question(object):
def __init__(self, record_history, colour):
self.record_history = record_history
self.colour = colour
def eraseFromMemory(self):
inout.remove_history_items(1)
def ask(self, textIn):
textIn = input(inout.coloured(textIn + ' ', self.colour, True)).lower()
if self.record_history is False: self.eraseFromMemory()
return textIn
class Quiz(object):
def __init__(self):
self.score = 0
self.exit = False
def randomise(self, length):
return sample(range(length), len(range(length)))
def displayScore(self, divisor, length):
self.score /= divisor
highestPossibleScore = str(length)
if self.score < 10:
print(inout.coloured("Round over! Your score that round was " + '%.2g'%(self.score) + " out of " + highestPossibleScore + ", " +'%0.4g'%(self.score/int(highestPossibleScore)*100) + "%.\n", 'cyan'))
elif self.score < 100:
print(inout.coloured("Round over! Your score that round was " + '%.3g'%(self.score) + " out of " + highestPossibleScore + ", " +'%0.4g'%(self.score/int(highestPossibleScore)*100) + "%.\n", 'cyan'))
elif self.score < 1000:
print(inout.coloured("Round over! Your score that round was " + '%.4g'%(self.score) + " out of " + highestPossibleScore + ", " +'%0.4g'%(self.score/int(highestPossibleScore)*100) + "%.\n", 'cyan'))
self.score = 0
def displayQuestionLetter(self, letter):
print(inout.coloured("{})".format(letter), "cyan"), end=' ')
def translationQuestion(self, word, letter=None, score=1):
if self.exit is False:
if letter is not None: self.displayQuestionLetter(letter)
textIn = input(inout.coloured("What is '{}' in English? ".format(word.translation), 'cyan', True)).lower()
if textIn == "exit":
self.exit = True
elif textIn == word.english:
print(inout.coloured("Correct!", 'green'))
self.score += score
else:
print(inout.coloured("Incorrect! The answer was " + word.english + ".", 'red'))
if len(textIn) > 0: inout.remove_history_items(1)
def genderQuestion(self, noun, letter=None, score=1):
if self.exit is False:
if letter is not None: self.displayQuestionLetter(letter)
textIn = input(inout.coloured("What is the gender of '" + noun.translation + "'? ", 'cyan', True)).lower()
if textIn == 'exit':
self.exit = True
elif textIn == noun.gender:
print(inout.coloured("Correct!", 'green'))
self.score += score
else:
print(inout.coloured("Incorrect! The answer was " + noun.gender + ".", 'red'))
if len(textIn) > 0: inout.remove_history_items(1)
def pastParticipleQuestion(self, verb, letter=None, score=1):
if self.exit is False:
if letter is not None: self.displayQuestionLetter(letter)
textIn = input(inout.coloured("What is the past participle of '" + verb.translation + "'? ", 'cyan', True)).lower()
if textIn == 'exit':
self.exit = True
elif textIn == verb.pastParticiple:
print(inout.coloured("Correct!", 'green'))
self.score += score
else:
print(inout.coloured("Incorrect! The answer was " + verb.pastParticiple + ".", 'red'))
if len(textIn) > 0: inout.remove_history_items(1)
def auxiliaryVerbQuestion(self, verb, letter=None, score=1):
auxiliaryVerbs = ['haben', 'sein'] if verb.language == 'german' else ['avoir', 'être'] # Shift-AltGr-6 release e for ê
if self.exit is False:
if letter is not None: self.displayQuestionLetter(letter)
textIn = input(inout.coloured("Does '" + verb.pastParticiple + "' use " + auxiliaryVerbs[0] + " or " + auxiliaryVerbs[1] +"? ", 'cyan', True)).lower()
if textIn == 'exit':
self.exit = True
elif textIn == verb.auxVerb:
print(inout.coloured("Correct!", 'green'))
self.score += score
else:
print(inout.coloured("Incorrect! The answer was " + verb.auxVerb + ".", 'red'))
if len(textIn) > 0: inout.remove_history_items(1)
def vocab(self, aSet, quizLength=0): # 0 is no length limit
quizLength = int(quizLength)
deck = self.randomise(len(aSet.words))
if quizLength > 0: deck = deck[:quizLength]
numberOfQuestions = len(deck)
while self.exit is False:
try:
index = deck.pop()
questionNumber = numberOfQuestions - len(deck)
except IndexError:
self.displayScore(1, numberOfQuestions)
self.exit = False
return
print(inout.coloured("Question " + str(questionNumber) + ":", 'cyan'))
if aSet.words[index].type == "noun":
self.translationQuestion(aSet.words[index], "a", 0.5)
self.genderQuestion(aSet.words[index], "b", 0.5)
else:
self.translationQuestion(aSet.words[index])
print()
self.exit = False
def nouns(self, aSet, quizLength=0):
quizLength = int(quizLength)
nouns = [w for w in aSet.words if w.type == "noun"]
deck = self.randomise(len(nouns))
numberOfQuestions = len(deck)
while self.exit is False:
try:
index = deck.pop()
questionNumber = numberOfQuestions - len(deck)
except IndexError:
self.displayScore(2, numberOfQuestions)
self.exit = False
return
print(inout.coloured("Question " + str(questionNumber) + ":", 'cyan'))
self.translationQuestion(nouns[index], 'a')
self.genderQuestion(nouns[index], 'b')
print()
self.exit = False
def verbs(self, aSet, quizLength=0): # At the moment, this is for past prticiples. A conjugation quiz will be added soon
quizLength = int(quizLength)
verbs = [w for w in aSet.words if w.type == "verb"]
deck = self.randomise(len(verbs))
numberOfQuestions = len(deck)
while self.exit is False:
try:
index = deck.pop()
questionNumber = numberOfQuestions - len(deck)
except IndexError:
self.displayScore(3, numberOfQuestions)
self.exit = False
return
print(inout.coloured("Question " + str(questionNumber) + ":", 'cyan'))
self.pastParticipleQuestion(verbs[index], 'a')
self.auxiliaryVerbQuestion(verbs[index], 'b')
self.translationQuestion(verbs[index], 'c')
print()
self.exit = False
|
639115df9f0028e40e5931459614e5e52996f362 | NathanMuniz/Exercises-Python | /Desafio/ex034.py | 264 | 3.796875 | 4 | salario = float(input('Qual o salario do funsionario R$'))
s = salario * 10 / 100
v = salario * 15 / 100
if salario > 1250.00:
salari = salario + s
else:
salari = salario + v
print('quem ganhava R${:.2f} vai recever R${:.2f} '.format(salario, salari))
|
79bbcd303bbd53297606b2125b9f75880f760aee | JackNeus/bookish-waddle | /tasks/multi_util.py | 975 | 3.734375 | 4 | from collections import defaultdict
# items is a list of (key, value, size)
# will return a list of tuples of the form ([value1, value2, ...], key)
def partition(items, max_partition_size):
partitions = []
current_partition = list()
current_partition_key = None
current_partition_size = 0
items.sort(key = lambda x: x[0])
for item in items:
key, value, size = item
# This guarantees that even items with size > max_partition_size will
# make it into a partition.
if key != current_partition_key or current_partition_size + size > max_partition_size:
if len(current_partition) > 0:
partitions.append((current_partition, current_partition_key))
current_partition = [value]
current_partition_key = key
current_partition_size = size
else:
current_partition.append(value)
current_partition_size += size
if len(current_partition) > 0:
partitions.append((current_partition, current_partition_key))
return partitions
# TODO: unit tests |
d6e9bff249fc7bf3d27086ba4fb6bc1fb037b06b | LilySu/Python_Practice | /Binary_Search_Tree/Binary_Search_Tree_Practice_November_20.py | 1,407 | 3.890625 | 4 | class BST:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if self.data == data:
return
if data < self.data:
if self.left:
self.left.add_child(data)
else:
self.left = BST(data)
else:
if self.right:
self.right.add_child(data)
else:
self.right = BST(data)
def traverse_tree(self):
elements = []
if self.left:
elements += self.left.traverse_tree()
elements.append(self.data)
if self.right:
elements += self.right.traverse_tree()
return elements
def search(self, data):
if data == self.data:
return True
elif data < self.data:
if self.left:
return self.left.search(data)
else:
return False
else:
if self.right:
return self.right.search(data)
else:
return False
def build_tree(elements):
r = BST(elements[0])
for i in range(1, len(elements)):
r.add_child(elements[i])
return r
if __name__ == "__main__":
elements = [294, 18, 98, 65, 2]
tree = build_tree(elements)
print(tree.traverse_tree())
print(tree.search(17)) |
e1da6219da10c8846f7dd47fdbbdf6a069862d26 | danpinto97/HealthTechHack | /model.py | 5,152 | 3.90625 | 4 | import sqlite3
import datetime
class User(object):
'''User class which is our model'''
def __init__(self, user_id, dosage_left, days_since_last_dose):
self.user_id = user_id
self.dosage_left = dosage_left
self.days_since_last_dose = days_since_last_dose
def set_user_id(self, _id):
self.user_id = _id
def get_user_id(self):
return self.user_id
def set_dosage_left(self, dosage):
self.dosage_left = dosage
def get_dosage_left(self):
return self.dosage_left
def set_days_since_last_dose(self, num_days):
self.days_since_last_dose = num_days
def get_days_since_last_dose(self):
return self.days_since_last_dose
def decrement_dosage_left(self):
self.dosage_left = self.dosage_left - 1
def decrement_days_since_last_dose(self):
self.days_since_last_dose = self.days_since_last_dose - 1
def print_attributes(self):
return ("User ID: %s \nDosage Left: %s \nDays Since Last Dosage: %s \n" % (
self.user_id, self.dosage_left, self.days_since_last_dose))
def answer_form(self, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10):
"""
Stores a users answers to the form questions in addition to their days since last dosage
and dosage left and timestamp.
"""
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("INSERT INTO user_symptoms VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (self.user_id, self.dosage_left, self.days_since_last_dose, datetime.datetime.now(), Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10))
conn.commit()
def user_response(self):
"""
Stores a user and their injection and dosage left in the user database
"""
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("INSERT INTO user VALUES (?, ?, ?, ?)", (self.user_id, self.dosage_left, self.days_since_last_dose, datetime.datetime.now()))
conn.commit()
def reup(self,dosage):
"""
Stores a user and their injection and dosage left IF they have updated their amount of dosage left
"""
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("INSERT INTO user VALUES (?, ?, ?, ?)", (self.user_id, dosage, self.days_since_last_dose, datetime.datetime.now()))
conn.commit()
def just_dosed(self):
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("INSERT INTO user VALUES (?, ?, ?, ?)", (self.user_id, self.dosage_left-1, 0, datetime.datetime.now()))
conn.commit()
def last_medication_date(self):
"""
Returns latest day in which a patient was medicated.
"""
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user WHERE user_id is ? ORDER BY time DESC LIMIT 1", self.user_id)
data = c.fetchall()
print(data)
def last_dose_from_db(self):
'''
Returns difference in days since last injection. We should store this in a db after completed.
'''
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user WHERE user_id is ? ORDER BY time DESC LIMIT 1", self.user_id)
data = c.fetchall()
previous_date = data[0][3]
previous_date = datetime.datetime.strptime(previous_date, '%Y-%m-%d %H:%M:%S.%f')
d = datetime.datetime.today() - previous_date
return d.days
def get_remaining_inj_from_db(self):
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user WHERE user_id is ? ORDER BY time DESC LIMIT 1", self.user_id)
data = c.fetchall()
return data[0][1]
def get_indi_sym(self):
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user_symptoms WHERE user_id is ?", self.user_id)
data = c.fetchall()
return data
@classmethod
def get_recent_user_from_id(self, id):
"""
Returns latest day in which a patient was medicated.
"""
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user WHERE user_id is ? ORDER BY time DESC LIMIT 1", id)
data = c.fetchall()
return User(id, data[0][1], data[0][2])
@classmethod
def get_sym(self):
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user_symptoms")
data = c.fetchall()
print(data)
@classmethod
def get_users(self):
db = 'hth.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT * FROM user")
data = c.fetchall()
print(data)
if __name__ == '__main__':
#new_user = User("2", 1, 0)
# new_user.print_attributes()
# new_user.user_response()
User.get_users()
#new_user.last_dose_from_db()
|
a0675a518eda4c678a2536500d1a2b45cee1ee3b | ayush879/python | /it.py | 245 | 3.78125 | 4 | my_list=[4,7,0,3]
my_iter=iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)
x=iter([1,2,3])
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())
|
cfe51adb850339cc9e8089e50bd80aa5783fba61 | aariandhanani/AarianDhananiGameDesign | /creatingScreen.py | 639 | 3.546875 | 4 | import pygame
# Drawing with Pygame
# ask the user to give you a color
# create the window with that color
# What is the width and height of the window
pygame.init()
screen = pygame.display.set_mode((800,600)) # this is a tuple
# screen.fill((R,G,B))
black = (0,0,0)
screen.fill((255,117,117))
pygame.display.flip()
pygame.display.set_caption("Testing pygame")
run = True
while run:
pygame.time.delay(1000)
screen.fill((130,117,255))
pygame.display.update()
for event1 in pygame.event.get():
print(event1)
if event1.type == pygame.QUIT:
run = False
pygame.time.delay(50)
pygame.quit()
|
49de10e7791c48f83e4b5dfd26b337433d8d1e3d | Beta-23/PythonResources | /main.py | 643 | 4.03125 | 4 | # Write your code below this line
print("Welcome to the Band Name Generator.")
street = input("What's name of the city you grew up in?\n")
pet = input("What's your pet's name?\n")
print("Your band name could be " + street + " " + pet)
n = 6
if n > 2:
print("Larger than 2")
else:
print("Smaller than 2")
age = 13
if age > 16:
print("Can drive")
else:
print("Don't drive")
weather = "sunny"
if weather == "rain":
print("bring umbrella")
elif weather == "sunny":
print("bring sunglasses")
elif weather == "snow":
print("bring gloves")
print("Let's Go " + input("GitHub Universe2020 is happening today! What's your name?")) |
f4e9d789fc051d715cbe3f4f11caafecb729c3e8 | PhillipWitkin/neural_network_solver | /Neuron.py | 1,342 | 3.765625 | 4 | import copy
import math
import random
class Neuron:
INPUT1 = "InputNode1"
INPUT2 = "InputNode2"
FORWARDS = "forwards"
BACKWARDS = "backwards"
def __init__(self, name):
# self.sigmoid = 0
self.yValue = Neuron.random_number()
self.threshold = Neuron.random_number()
self.delta = 0
self.ahead_of_nodes = []
self.behind_nodes = []
self.weight_to_nodes = {}
self.name = name
def add_node_ahead(self, *args):
for node in args:
self.behind_nodes.append(node)
def add_node_behind(self, *args):
for node in args:
self.ahead_of_nodes.append(node)
def get_weight_to_node(self, to_node):
return self.weight_to_nodes.get(to_node.name)
def set_weight_to_node(self, to_node, value):
self.weight_to_nodes[to_node.name] = value
def display_weights(self):
# output = self.name
for name, value in self.weight_to_nodes.items():
print(self.name + " to " + name + " = " + str(value))
# provides a random number for weights and thresholds
@staticmethod
def random_number():
max = 2.4/2
min = -2.4/2
return min + (max - min)*random.random()
@staticmethod
def sigmoid(num):
return 1 / (1 + math.exp(-num))
|
fdd0a7f44a7210d056a8bba7f57724c8d468d2e8 | noamt/presentations | /python-peculiarities/source/MultiplicationComplication.py | 163 | 3.828125 | 4 | # https://codegolf.stackexchange.com/a/11480
multiplication = []
for i in range(10):
multiplication.append(i * (i + 1))
for x in multiplication:
print(x) |
be28b10fb14811905e2af3b0c8688c496b1dd100 | tom3108/Python-basic-exercises. | /number 26.py | 183 | 3.5625 | 4 | def histogram (tup):
empt = ""
for t in tup:
empt += (t * "@") + "\n"
return empt
print(histogram((2,1,5)))
print("------------------")
print(histogram((4,1,5))) |
c649ac55397ebb727fe8b77daad7b757f903bba7 | Peterquilll/interview_questions | /chapter1/compress.py | 619 | 3.90625 | 4 | def compress(string):
compressed_string = []
count_consecutive = 0
i = 0
while i < len(string):
count_consecutive += 1
if (i + 1 >= len(string) or string[i] != string[i +1]):
compressed_string.append(string[i])
compressed_string.append(count_consecutive)
count_consecutive = 0
i += 1
if len(compressed_string) < len(string):
return compressed_string
else:
return String
def main():
string = "abbbccddddd"
result = compress(string)
print(result)
if __name__ == '__main__':
main()
|
110b70d581d798d17b85a08aab5b3afd3664f84e | roque-brito/ICC-USP-Coursera | /icc_pt2/week1/ExeProg_01/exercicio2.py | 1,260 | 3.796875 | 4 | ''' Escreva a função soma_matrizes(m1, m2) que recebe 2 matrizes e devolve uma matriz
que represente sua soma caso as matrizes tenham dimensões iguais. Caso contrário,
a função deve devolver False. '''
# ======================================================================================
def dimensoes(matriz):
m = len(matriz) # número de linhas
for i in range(len(matriz)):
linha = matriz[i]
n = len(linha)
return (m, n)
def teste_dimensoes(m1, m2):
teste_m1 = dimensoes(m1)
teste_m2 = dimensoes(m2)
if teste_m1 != teste_m2:
return False
else:
return True
def soma_matrizes(m1, m2):
teste = teste_dimensoes(m1, m2)
if teste == True:
matriz_soma = []
for i in range(len(m1)):
linha_m3 = []
for j in range(len(m1[i])):
termo_m1 = m1[i][j]
termo_m2 = m2[i][j]
termo_m3 = termo_m1 + termo_m2
linha_m3.append(termo_m3)
matriz_soma.append(linha_m3)
else:
return False
return matriz_soma
'''
m1 = [[1], [2], [3]]
m2 = [[2, 3, 4], [5, 6, 7]]
#m1 = [[1, 2, 3], [4, 5, 6]]
#m2 = [[2, 3, 4], [5, 6, 7]]'''
|
3a1f4a57e023f8f2bb9b05795be2bd508c016913 | compas-dev/compas | /src/compas/geometry/_core/tangent.py | 1,385 | 3.75 | 4 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from math import sqrt
def tangent_points_to_circle_xy(circle, point):
"""Calculates the tangent points on a circle in the XY plane.
Parameters
----------
circle : [plane, float] | :class:`~compas.geometry.Circle`
Plane and radius of the circle.
point : [float, float] or [float, float, float] | :class:`~compas.geometry.Point`
XY(Z) coordinates of a point in the xy plane.
Returns
-------
tuple[[float, float, 0.0], [float, float, 0.0]]
the tangent points on the circle.
Examples
--------
>>> from compas.geometry import allclose
>>> circle = ((0, 0, 0), (0, 0, 1)), 1.0
>>> point = (2, 4, 0)
>>> t1, t2 = tangent_points_to_circle_xy(circle, point)
>>> allclose(t1, [-0.772, 0.636, 0.000], 1e-3)
True
>>> allclose(t2, [0.972, -0.236, 0.000], 1e-3)
True
"""
plane, R = circle
center, _ = plane
cx, cy = center[:2]
px, py = point[:2]
dx = px - cx
dy = py - cy
D = sqrt(dx**2 + dy**2)
L2 = D**2 - R**2
a = dx / D, dy / D
b = -a[1], a[0]
A = D - L2 / D
B = sqrt(R**2 - A**2)
t1 = cx + A * a[0] + B * b[0], cy + A * a[1] + B * b[1], 0
t2 = cx + A * a[0] - B * b[0], cy + A * a[1] - B * b[1], 0
return t1, t2
|
c5dbd9c533aad31eda5e5cea0c96360342ca3c3d | sky-dream/LeetCodeProblemsStudy | /[0169][Easy][Majority Element]/MajorityElement_2.py | 612 | 3.53125 | 4 | # solution 2, Hash table
# leetcode time cost : 176 ms
# leetcode memory cost : 13.2 MB
# Time Complexity: O(N)
# Space Complexity: O(N)
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
# get the max value's key from a dict
# d = {"a":1,"b":2, "c":5}
# solution 1, max(d, key=lambda k: d[k])
# solution 2, max(d, key=d.get)
# solution 3, max(d.items(), key=operator.itemgetter(1))[0], not easy understanding, not recomended, |
6f35094f9c120170ce8d64e86c29b8647a7b484c | Densatho/Python-2sem | /aula2/ex3.py | 654 | 3.828125 | 4 | while True:
try:
salario_velho = float(input("Coloque o salario: "))
break
except ValueError:
print("Não colocou um salario valido valida\n")
while True:
try:
percentual = float(input("Coloque o percentual: "))
break
except ValueError:
print("Não colocou um percentual valido\n")
percentual /= 100
aumento = salario_velho * percentual
salario_novo = salario_velho + aumento
aumento = round(aumento, 2)
salario_novo = round(salario_novo, 2)
print(f"Teve um aumento de R${aumento} com um salario total de R${salario_novo}")
|
632d4a79dd28559ece774037bc83935f74c532dd | hanwgyu/algorithm_problem_solving | /Leetcode/222.py | 908 | 3.921875 | 4 | # left child, right child의 height 를 비교해, 같으면 오른쪽 child로 이동, 다르면 왼쪽 child로 이동해야 가장 마지막 노드에 도달할 수 있다.
# Time : O((logN)^2), Space: O(logN)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def height(node: TreeNode) -> int:
if not node:
return 0
return 1 + height(node.left)
def dfs(node: TreeNode, n: int) -> int:
if not node:
return n//2
if height(node.left) == height(node.right):
return dfs(node.right, 2*n+1)
else:
return dfs(node.left, 2*n)
return dfs(root, 1)
|
df5d8f7a58fadc4096614b01a37f303132b43d77 | tanisha03/Sem5-ISE | /SLL-Python/Data-Science/Iris/iris.py | 882 | 3.5 | 4 | import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
iris_df = pd.read_csv("iris.csv")
print("---DataFrame---")
print(iris_df)
print("---info---")
iris_df.info()
print("---Functions---")
print(iris_df[["variety", "petal.width"]].groupby(["variety"], as_index=True).mean())
ax = sns.countplot(x="sepal.width", hue="variety", data=iris_df, palette="Set1")
ax.set(
title="Categorization of flowers based on sepal width",
xlabel="Categories",
ylabel="Total",
)
plt.show()
ax = sns.countplot(x="sepal.length", hue="variety", data=iris_df, palette="Set2")
ax.set(title="Sepal Length", xlabel="Categories", ylabel="Count")
plt.show()
ax = sns.countplot(x="petal.width", hue="variety", palette="Set3", data=iris_df)
ax.set(title="Flowers Categorical", xlabel="variety", ylabel="total")
plt.show()
|
50ce28bfa744108c107bb41e31856f2e0ac9b957 | marcfs31/joandaustria | /M3-Programacion/UF1/M3/Practica6_Condicionales.py | 9,365 | 3.921875 | 4 | # encoding: utf-8
"""*******************************************
* Demana nom i edat, i si ets major d'edat d'edat t'havisa que pots anar a la preso
*******************************************"""
"""
nom = raw_input("Escriu el teu nom: ")
edat = int(input("Escriu la teva edat: "))
if edat >= 18:
print "Vostè ja pot anar a la presó!"
print "Adeu " + nom
"""
"""*******************************************
* Ordena ascendentmen dos valors
*******************************************"""
"""
num1 = int(input("Escriu el primer numero: "))
num2 = int(input("Escriu el segón numero: "))
if num1 < num2:
print num1,"i",num2
else:
print num2,"i",num1
"""
"""*******************************************
*
*******************************************"""
"""
num1 = int(input("Escriu el primer numero: "))
num2 = int(input("Escriu el segón numero: "))
producte = num1 * num2
if producte == 0:
print "Es igual que 0"
elif producte < 0:
print "Es menor que 0"
else:
print "Es major que 0"
"""
"""*******************************************
*
*******************************************"""
"""
entrada = raw_input("Introduce un unico caracter cualquiera: ")
if entrada == "0" or entrada == "1" or entrada == "2" or entrada == "3" or entrada == "4" or entrada == "5" or entrada == "6" or entrada == "7" or entrada == "8" or entrada == "9":
print "Es un digit"
else:
print "Adios"
"""
"""*******************************************
*
*******************************************"""
"""
preu = float(input("Introdueix el preu original: "))
descompte = float(input("Introdueix el preu pagat: "))
if preu > descompte:
percentatge = preu - descompte
percentatge = percentatge / preu
percentatge = percentatge * 100
print "Tens un descompte del",int(percentatge),"%"
print "Has pagat",preu - descompte,"€ menys"
elif preu <descompte:
print "No hi ha descompte"
"""
"""*******************************************
*
*******************************************"""
"""
dia = int(input("Introdueix el Dia (DD): "))
mes = int(input("Introdueix el Mes (MM): "))
Any = int(input("Introdueix l'Any (AAAA): "))
hora = int(input("Introdueix l'Hora (HH): "))
minut = int(input("Introdueix els Minuts (MnMn): "))
segon = int(input("Introdueix els Segons (SS): "))
# Comprovacio d'errors, que els valors introduits siguin correctes
if mes > 12 or mes < 1:# <------ Mes
print "\n<<<No has introdiut be el Mes!>>>"
elif dia > 30 or dia < 1:# <------ Dia
print "\n<<<No has introdiut be el Dia!>>>"
elif hora > 23 or hora < 0:# <------ Hora
print "\n<<<No has introdiut be l’Hora!>>>"
elif minut > 59 or minut < 0:# <------ Minut
print "\n<<<No has introdiut be els Minuts!>>>"
elif segon > 59 or segon < 0:# <------ Segon
print "\n<<<No has introdiut be els Segons>>>"
else: # Si tot es correcte es procedeix a fer el calcul
if int(segon) + 1 == 60:# <------ Segon
segon = "0"
minut = minut + 1
if minut == 60:# <------ Minut
minut = "0"
hora = hora + 1
if hora == 24:# <------ Hora
hora = "0"
dia = dia + 1
if dia == 31:# <------ Dia
dia = "1"
mes = mes + 1
if mes == 13:# <------ Mes
mes = "1"
Any = Any + 1
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
else:# <------ Mes
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
else:# <------ Dia
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
else:# <------ Hora
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
else:# <------ Minut
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
else:# <------ Segon
segon = segon + 1
print "D"+str(dia)+"-M"+str(mes)+"-A"+str(Any)+"-H"+str(hora)+"-Mn"+str(minut)+"-S"+str(segon)
"""
"""*******************************************
*
*******************************************"""
"""
print "Calculadora senzilla"
num1 = int(input("Introdueix el primer numero amb el que vulguis operar: "))
op = raw_input("Intoduexi l'operació a realitzar(+ - * /): ")
num2 = int(input("Introdueix el segon numero amb el que vulguis operar: "))
if op == "+":
print "El resultat es:", num1+num2
elif op == "-":
print "El resultat es:", num1-num2
elif op == "*":
print "El resultat es:", num1*num2
elif op == "/":
if num2 == 0:
print "No pots dividir entre 0"
else:
print "El resultat es:", num1/num2
"""
"""*******************************************
*
*******************************************"""
"""
nom = raw_input("Nom del pacient: ")
edat = int(input("Edat del pacient: "))
print "Responde SI o NO a les següents preguntes"
print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
simptoma1 = raw_input("Tens estornuts?: ")
simptoma2 = raw_input("Tens mal de cap?: ")
simptoma3 = raw_input("Tens problemes d'estomac?: ")
simptoma4 = raw_input("Tens tos?: ")
if simptoma1 == "si" or simptoma1 == "Si" or simptoma1 == "sI" or simptoma1 == "SI" and simptoma2 == "si" or simptoma2 == "Si" or simptoma2 == "sI" or simptoma2 == "SI":
if simptoma3 == "si" or simptoma3 == "Si" or simptoma3 == "sI" or simptoma3 == "SI":
print "\nEt recomano que prenguis paracetamol"
else:
print "Et recomano àcid acetil salicílic (AAS)"
elif simptoma4 == "si" or simptoma4 == "Si" or simptoma4 == "sI" or simptoma4 == "SI" and simptoma4 == "si" or simptoma4 == "Si" or simptoma4 == "sI" or simptoma4 == "SI":
if edat >= 12:
print "\nPrente un caramel de d'eucaliptus"
else:
print "\nPrente un caramel de mel"
else:
print "\nVina a veurem a la consulta, al Carre Major"
"""
"""*******************************************
*
*******************************************"""
"""
semafor = raw_input("Escriu el color del semafor(vermell, groc, o verd): ")
if semafor == "vermell" or semafor == "Vermell" or semafor == "VERMELL":
print("\nQuiet!! Encara no pots pasar, espera que es posi verd.")
elif semafor == "groc" or semafor == "Groc" or semafor == "GROC":
print("\nNo corris. Millor espera que es torni a possar verd.")
elif semafor == "verd" or semafor == "Verd" or semafor == "VERD":
print ("\nAra es verd, pots creuar.")
else:
print ("\n"+semafor+" no es un color del semafor")
"""
"""*******************************************
*
*******************************************"""
"""
fills = int(input("Quants fills tens?: "))
if fills < 0:
print "Error, no pots tenir menys que 0 fills!"
elif fills == 0:
print "Tot el que t'has estalviat en bolquers!"
elif fills == 1:
print "Compte de no mimar-lo massa!"
elif fills >1 and fills <5:
print "No t'avorreixes a casa eh?"
elif fills > 4:
print "Tu sí fas país!"
"""
"""*******************************************
* Calculadora d'equacions de segon grau
*******************************************"""
"""
import math
print "Tenim l'equació de segon grau ax² + bx + c = 0\nIntrodueix els valors de a, b i c per resoldrela"
a = int(input("Valor de a: "))
b = int(input("Valor de b: "))
c = int(input("Valor de c: "))
inarrel = (b ** 2) - (4 * a * c)
if a == 0:
print "No es pot resoldre"
else:
if inarrel < 0:
print "L'interior de l'arrel dona", inarrel,"i no es pot resoldre l'equació"
else:
arrel = math.sqrt(inarrel)
print str(b)+"² - 4·"+str(a)+"·"+str(c)+" =",inarrel,"\n"
op1 = -b + arrel
print "-("+str(b)+") +"+str(inarrel)+" =",op1
op2 = -b - arrel
x1 = op1 / (2 * a)
x2 = op2 / (2 * a)
print str(op1)+"/2·"+str(a)+" =",x1
print "x1 =",x1
print "\n-("+str(b)+") -"+str(inarrel)+" =",op2
print str(op2)+"/2·"+str(a)+" =",x2
print "x2 =",x2
"""
"""*******************************************
* Ascensor, programa fet amb una funció
*******************************************"""
"""
import time
def ascensor(planta = 0):
print "Som al pis", planta
escollir = int(input("Per anar a cualsevol pis escrigui el numero del pis\nTenim planta baixa(0), primer pis(1), segon pis(2). A quin vols anar?: "))
if planta < escollir and escollir <= 2:
x = escollir - planta
planta = escollir
print "Pujant al pis",planta
time.sleep(x)
print "Ding! Ja hem arribat.\n"
elif planta > escollir and escollir >= 0:
x = planta - escollir
planta = escollir
print "Baixant al pis",planta
time.sleep(x)
print "Ding! Ja hem arribat.\n"
elif planta == escollir:
print "Ja ets al pis", escollir,"\n"
else:
print "\n<<< No tenim el pis", escollir,">>>\n"
ascensor(planta)
ascensor()
"""
"""*******************************************
* Ascensor, programa fet sense funció
*******************************************"""
"""
import time
planta = int(input("planta baixa(0), primer pis(1), segon pis(2), a quin pis som?(escrigui el numero del pis): "))
escollir = int(input("Per anar a cualsevol pis escrigui el numero del pis. A quin vols anar?: "))
if planta < escollir and escollir <= 2:
x = escollir - planta
planta = escollir
print "Pujant al pis",planta
time.sleep(x)
print "Ding! Ja hem arribat.\n"
elif planta > escollir and escollir >= 0:
x = planta - escollir
planta = escollir
print "Baixant al pis",planta
time.sleep(x)
print "Ding! Ja hem arribat.\n"
elif planta == escollir:
print "Ja ets al pis", escollir,"\n"
else:
print "\n<<< No tenim el pis", escollir,">>>\n"
"""
|
3ede2bef06333b01fb7f06ec18bbd987bc5e1e54 | RafelQC/practicaPython | /OOP/coche.py | 1,450 | 3.78125 | 4 | class coche():
def __init__(self): #CONSTRUCTOR definimos los estados iniciales de los objetos creados, más adelante pueden ser modificados
self.__largoChasis=250
self.__anchoChasis=120
self.__ruedas=4 #con las "__" no se pueden modificar estas variables desde fuera del objeto (ENCAPSULADO)
self.__enmarcha=False
def arrancaFrena(self,arrancamos):
self.__enmarcha=arrancamos
if(self.__enmarcha):
chequeo=self.__chequeoInterno()
if(self.__enmarcha and chequeo):
return "El coche está en marcha. "
elif(self.__enmarcha and chequeo==False):
return "Algo ha ido mal en el chequeo, no podemos arrancar."
else:
return "El coche está parado. "
def estado(self):
print("El coche tiene ", self.__ruedas, "ruedas, ", "un ancho de ", self.__anchoChasis, " y un largo de ", self.__largoChasis)
def __chequeoInterno(self): #aquest metode esta encapsulat, només es pot cridar dins l'objecte
print("Realizando chequeo interno... ")
self.gasolina="ok"
self.aceite="bajo"
self.puertas="cerradas"
if (self.gasolina=="ok" and self.aceite=="ok" and self.puertas=="cerradas"):
return True
else:
return False
miCoche=coche()
#print(miCoche.largoChasis)
#print(miCoche.ruedas)
print(miCoche.arrancaFrena(True))
miCoche.estado()
print(" - - - - - A continuación creamos el segundo objeto... - - - - -")
miCoche2=coche()
print(miCoche2.arrancaFrena(False))
miCoche2.ruedas=2
miCoche2.estado()
|
8239f18a31adb97a5acd81476e2e2b92ebd6c9a8 | Tapan-24/python | /thermometer.py | 288 | 4.1875 | 4 | x=input("Insert Temperature In 'C' or 'F' : ")
unit= x[-1]
print(unit)
x=int(x[0:-1]) #convert all input from str to int
if unit == 'C' or unit == 'c':
x=round(x*(9/5)+32)
print(str(x)+'F')
elif unit == 'F' or unit =="f":
x=round((x-32)*(5/9))
print(str(x)+'C')
|
d72d8148bf9f7d02d319be8de56ccf50be82197b | ankitkmsrit/Text_Analysis | /FacultyNameExtraction.py | 729 | 3.515625 | 4 | from GrabTexthtml import grabText
def fac():
facultyList =[]
i=1
while(i<33):
text = grabText("F:\\STUDY MATERIALS\\6TH SEM\\Compiler Design\\Compiler Design Project\\WebpageInput\\"+str(i)+".html") #returns text using the Grabtext file
a=0
if "Faculty Details" in text:
a = text.index("Faculty Details")
a = a + 2*len("Faculty Details")+2
text = text[a:]
s=""
for letter in text:
if(letter=="\n"):
break
s+=letter #grabbing faculty name
facultyList.append(s) #adding faculty name to list
i+=1
return facultyList
|
1c9bfa145d567414056ca7412e05e5666c3f9175 | jayvadaliya/GuessGame | /guessgame.py | 573 | 3.75 | 4 | import random
class guissingame():
global guess
guess = input("guess the number between 1-10:\n")
def __init__(self):
self.rand_choise = random.randint(0,10) #rand_choise save the random integer
# Method for resetting random number
def reset_random(self):
print("Resseting random number!!")
self.rand_choise = random.randint(0,10)
def userguess(self):
if guess == self.rand_choise:
print("you are right!!")
else:
print("sorry!! try again!!")
print("number is: {}".format(self.rand_choise))
g = guissingame()
g.userguess()
g.reset_random() |
454f66e62c47b6ee729f464940aa3a32106e84f6 | peterfuchs1/Py01 | /roman/roman.py | 3,186 | 4.0625 | 4 | """Convert to and from Roman numerals
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/05 21:57:20 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"
__path__ = '.'
from roman.Exceptions import * # InvalidRomanNumeralError, OutOfRangeError, NotIntegerError, RomanError
class Roman(object):
"""Roman numbers representation
"""
__instance = None
def __new__(cls, val=None):
"""We want only one instance!
:param cls:
:param val:
:return:
"""
if Roman.__instance is None:
Roman.__instance = object.__new__(cls)
Roman.fillLookupTables()
Roman.__instance.val = val
return Roman.__instance
#Create tables for fast conversion of roman numerals.
#See fillLookupTables() below.
toRomanTable = [ None ] # Skip an index since Roman numerals have no zero
fromRomanTable = {}
#Roman numerals must be less than 4000
MAX_ROMAN_NUMERAL = 3999
#Define digit mapping
romanNumeralMap = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1))
@staticmethod
def toRoman(n):
"""convert integer to Roman numeral"""
if not (0 < n <= Roman.MAX_ROMAN_NUMERAL):
raise OutOfRangeError("number out of range (must be 1..4999)")
if int(n) != n:
raise NotIntegerError("non-integers can not be converted")
return Roman.toRomanTable[n]
@staticmethod
def fromRoman(s):
"""convert Roman numeral to integer"""
if not s:
raise InvalidRomanNumeralError ('Input can not be blank')
if s not in Roman.fromRomanTable:
raise InvalidRomanNumeralError ('Invalid Roman numeral: %s' % s)
return Roman.fromRomanTable[s]
@staticmethod
def toRomanDynamic(n):
"""convert integer to Roman numeral using dynamic programming"""
assert(0 < n <= Roman.MAX_ROMAN_NUMERAL)
assert(int(n) == n)
result = ""
for numeral, integer in Roman.romanNumeralMap:
if n >= integer:
result = numeral
n -= integer
break
if n > 0:
result += Roman.toRomanTable[n]
return result
@staticmethod
def fillLookupTables():
"""compute all the possible roman numerals"""
#Save the values in two global tables to convert to and from integers.
for integer in range(1, Roman.MAX_ROMAN_NUMERAL + 1):
romanNumber = Roman.toRomanDynamic(integer)
Roman.toRomanTable.append(romanNumber)
Roman.fromRomanTable[romanNumber] = integer
def __init__(self):
pass |
8f1cfd791c5474ec9e6a3a8496bbcc63df678bce | Afifa-Aslam/Pyhthon-Practice | /task8.3.py | 1,216 | 3.8125 | 4 | import random
listOfWords = ['APPLE', 'BILBO', 'CHORUSED', 'DISIMAGINE', 'ENSURING', 'FORMALISING', 'GLITCHES', 'HARMINE',
'INDENTATION', 'JACKED', 'KALPACS',
'LAUNDRY', 'MASKED', 'NETTED', 'OXFORD', 'PARODY', 'QUOTIENTS', 'RACERS', 'SADNESS', 'THYREOID', 'UNDUE',
'VENT', 'WEDGED', 'XERIC', 'YOUTHHOOD', 'ZIFFS']
a = listOfWords[random.randint(0, len(listOfWords)-1)]
#print(a)
l = []
w = []
g = []
i = 0
while i < len(a):
l.append('-')
w.append(a[i])
i = i + 1
print(l)
#print(w)
incor = 0
print("You have 6 Choices.")
z = True
while z and incor < 6:
n = str(input("Guess your letter: ").upper())
x = 0
flag = False
if (n in g):
print("Already entered!")
else:
for i in w:
if n.upper() == i:
l[x] = n.upper()
flag = True
g.append(n.upper())
x = x + 1
if (flag == False):
incor = incor +1
print("inCorrect!")
print(str(6 - incor) + " choices left")
else:
print(l)
if (l == w):
z = False
if z == False:
print("You win!")
if incor == 6:
print("You Lose!")
|
6879e08c7b3bf548f3adf81751287b79370e69ed | a1403893559/rg201python | /杂物间/python基础/day10/函数的参数细节.py | 182 | 3.71875 | 4 | # 说明形式参数 什么是实际参数 形参 实参
def addOne(a):
a = a + 1
return a
a = 3
print('函数内部的a的值:',addOne(a))
print('函数外面的值:',a)
|
7976a43a9a2ca02841b4ba8ad223ea6d76d71d77 | ravi4all/PythonEveRegJan_2020 | /OperatorsInPython.py | 672 | 4 | 4 | '''
Airthmetic Operator - +, - ,/ ,*, //, **, %
Comparison Operator - ==, >, <, >=, <=, !=
Logical Operator - and, or, not
Membership Operators - in, not in
Identity Operators - is, not is
'''
# Guess the number
import random
random_num = random.randint(1,100)
while (num := int(input("Enter a number : "))):
if random_num == num:
print("Congrats, You guessed the number...")
break
elif num > random_num:
print("Too High...")
elif num < random_num:
print("Too Low...")
elif random_num > 100 or random_num < 1:
print("Invalid Number")
else:
print("Invalid Input...")
|
f7d12fe1ccaa5f6015f7543f1bbf7cac9937d00d | reedrosenbluth/riemann | /riemann.py | 872 | 3.734375 | 4 | from math import *
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def reimann(a, b, n, l, f):
numRange = np.arange(a, b, .02)
y = f(numRange)
w = float(b - a)/n
x = 0.0
d = {"l": 0, "r": 1, "m": 0.5}
offset = d[l[0]]
for i in range(n):
x += f(a + (i+offset)*w)
plt.gca().add_patch(matplotlib.patches.Rectangle((i*w + a,0),w,f(a + (i+offset)*w)))
plt.plot(numRange, y, color=(1.0, 0.00, 0.00), zorder=5)
s = w * x
print '\n', s, '\n'
def main():
functionString = raw_input("\nEnter a function: ")
a = input("Enter the start point: ")
b = input("Enter the end point: ")
n = input("Enter the number of rectangles: ")
l = raw_input("Type right, left, or middle: ")
reimann(a, b, n, l, lambda x: eval(functionString))
plt.show()
if __name__ == "__main__":
main()
|
d899e66dccacca664ee18ef39c7b6bc65fa7db7b | lakshmanraob/MyPythonExp | /src/learnings/dict.py | 419 | 3.796875 | 4 | # Created by labattula on 29/12/15.
def main():
print("this is dictionary file")
d = dict(
one=1,two=2,three=3,four=4,five='five'
)
d['six'] = 6
for k in sorted(d.keys()):
print(k,d[k])
print('--retrieving the value from dict--')
va = 'seven'
print(d.get(va,'other'))
for index, val in enumerate(d):
print(index,val)
if __name__ == '__main__':
main() |
254b45fc72efa4df21be6e46b8c4cacacf8d29c6 | Bruno-morozini/Aulas_DIO_Phyton | /Coursera_Phyton/LISTA_04/Exercicio_01 par ou impar.py | 152 | 3.90625 | 4 | x = int(input("Digite um numero para descobrir se é par ou impar"))
teste = x % 2
if teste == 0:
print("par")
else:
print("ímpar")
|
24f5c447ff8a9836669ae2afc52aa5997d34e5da | jophy-mj/python | /sample/p4.py | 102 | 3.8125 | 4 | a=input("enter 1st no:")
b=input("enter 2nd no:")
sum=float(a)*float(b)
print("sum of float no:",sum)
|
24c35770dfce731bf29e8cd5c7bd4350f9eca01e | AndreiBratkovski/Training | /CCI-4E/Arrays-and-Strings/rotateImage.py | 2,013 | 3.78125 | 4 | """
1.6 Given an image represented by an NxN matrix, where each pixel in the image
is 4 bytes, write a method to rotate the image bey 90 degrees. Can you do this
in place?
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
"""
import unittest
from collections import deque
#
# Extra space
#
def rotate_image(matrix):
results = []
m_length = len(matrix)
# we use N for both loops because we are looking at
# this from a column and row perspective rather than
# nested arrays
for col in range(0, m_length):
inner = deque([])
for row in range(0, m_length):
item = matrix[row][col]
inner.appendleft(item)
results.append(list(inner))
return results
#
# In place
#
def rotate_image_inplace(matrix, m_length):
for layer in range(0, (m_length // 2)):
first = layer
last = m_length - 1 - layer
for i in range(first, last):
offset = i - first
top = matrix[first][i] # save top
# left -> top
matrix[first][i] = matrix[last - offset][first]
# bottom -> left
matrix[last - offset][first] = matrix[last][last - offset]
# right -> bottom
matrix[last][last - offset] = matrix[i][last]
# top -> right
matrix[i][last] = top # right <- saved top
return matrix
class Test(unittest.TestCase):
input_matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
output_matrix = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
def test_rotate_image(self):
result = rotate_image(self.input_matrix)
self.assertEqual(result, self.output_matrix)
def test_rotate_image_inplace(self):
result = rotate_image_inplace(self.input_matrix,
len(self.input_matrix))
self.assertEqual(result, self.output_matrix)
if __name__ == "__main__":
unittest.main()
|
125495854d51f2780df0042a730cf0d78791c32d | aspiringguru/udacityIntroMachineLearning | /datasets_questions/explore_enron_data.py | 6,274 | 3.640625 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
from __future__ import division
import pickle
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
print "type(enron_data)=", type(enron_data)
print "len(enron_data)=", len(enron_data)
print "len(enron_data.keys())=", len(enron_data.keys())
print "enron_data.keys()=", enron_data.keys()
print len(enron_data['METTS MARK'])
#for key in enron_data.keys():
# print len(enron_data[key])
#NB: all have 21 records.
print type(enron_data['METTS MARK'])
print "enron_data['METTS MARK'].keys()=", enron_data['METTS MARK'].keys()
print enron_data['METTS MARK']['poi']
print type(enron_data['METTS MARK']['poi'])
#How Many POIs Exist?
countPOI = 0
for key in enron_data.keys():
if enron_data[key]['poi']:
countPOI += 1
print "countPOI =", countPOI
#What is the total value of the stock belonging to James Prentice?
print "---------"
name = 'Prentice James'
for key in enron_data.keys():
#print type(key), key
if name.lower() in key.lower():
print "match found \n\n\n\n"
print 'total_stock_value for ', key, ' =', enron_data[key]['total_stock_value']
break
"""
print "---------"
name = 'Colwell Wesley'
for key in enron_data.keys():
print type(key), key
if name.lower() in key.lower():
print "match found \n\n\n\n"
print 'from_poi_to_this_person=', enron_data[key]['from_poi_to_this_person']
print 'from_this_person_to_poi=', enron_data[key]['from_this_person_to_poi']
break
"""
#What is the value of stock options exercised by Jeffrey K Skilling?
"""
print "---------"
name = 'Skilling Jeffrey'
for key in enron_data.keys():
print type(key), key
if name.lower() in key.lower():
print "match found \n\n\n\n"
print 'exercised_stock_options=', enron_data[key]['exercised_stock_options']
break
"""
"""
#Follow the Money
#Of these three individuals (Lay, Skilling and Fastow),
#Jeffrey Skilling, Ken Lay, Andrew Fastow
# who took home the most money (largest value of "total_payments" feature)?
#How much money did that person get?
def getInfoByName(name, param):
for key in enron_data.keys():
#print type(key), key
if name.lower() in key.lower():
print "match found \n\n\n\n"
print param, ' = ', enron_data[key][param]
return enron_data[key][param]
results = []
results.append(getInfoByName("Skilling Jeffrey", "total_payments"))
results.append(getInfoByName("Lay Ken", "total_payments"))
results.append(getInfoByName("Fastow Andrew", "total_payments"))
print results
"""
"""
#Unfilled Features
count = 0
for key in enron_data.keys():
print type(key), key
print enron_data[key]
count += 1
if count>5: break
"""
"""
#Dealing with Unfilled Features
#How many folks in this dataset have a quantified salary? What about a known email address?
#'salary' 'email_address'
print "-------------------aaa"
import math
count = 0
countSalaryNotNAN = 0
countEmailNotNAN = 0
for key in enron_data.keys():
#print type(enron_data[key]), enron_data[key]
#print type(enron_data[key]['salary']), type(enron_data[key]['email_address'])
if not isinstance(enron_data[key]['salary'], basestring):
countSalaryNotNAN += 1
#if not math.isnan(enron_data[key]['email_address']):
#if isinstance(enron_data[key]['email_address'], basestring):
if not enron_data[key]['email_address'] == "NaN":
countEmailNotNAN += 1
#print enron_data[key]['email_address']
count += 1
#if count > 5: break
print "countSalaryNotNAN =", countSalaryNotNAN
print "countEmailNotNAN =", countEmailNotNAN
print "count = ", count
"""
"""
#Missing POIs 1 (optional)
#How many people in the E+F dataset (as it currently exists) have "NaN" for their total payments?
# What percentage of people in the dataset as a whole is this?
count = 0
for key in enron_data.keys():
#'total_payments'
if enron_data[key]['total_payments'] =="NaN":
print type(enron_data[key]['total_payments']), enron_data[key]['total_payments']
count += 1
print "No of 'total_payments' with value 'NaN' is ", count
numKeys = len(list(enron_data.keys()))
print "numKeys = ", numKeys
print count/numKeys * 100
"""
"""
#Missing POIs 2 (optional)
#How many POIs in the E+F dataset have "NaN" for their total payments?
# What percentage of POI's as a whole is this?
count = 0
for key in enron_data.keys():
#'total_payments'
if enron_data[key]['total_payments'] =="NaN" and enron_data[key]['poi']:
count += 1
print "total payments are 'NaN' and POI = ", count
"""
"""
#Missing POIs 3 (optional)
#If a machine learning algorithm were to use total_payments as a feature,
# would you expect it to associate a 'NaN' value with POIs or non-POIs?
countTotalPaymentNAN = 0
countPOI = 0
countTotalPaymentNAN_POI = 0
countPOI_TotalPaymentNAN = 0
for key in enron_data.keys():
if enron_data[key]['total_payments'] == "NaN":
print "'total_payments'='NaN', ", key, enron_data[key]['poi'], enron_data[key]['total_payments']
countTotalPaymentNAN += 1
if enron_data[key]['poi']:
countTotalPaymentNAN_POI += 1
print "TotalPayment is NAN=", countTotalPaymentNAN, ", TotalPayment is NAN & POI = ", countTotalPaymentNAN_POI
for key in enron_data.keys():
if enron_data[key]['poi']:
print "poi=True, ", key, enron_data[key]['poi'], enron_data[key]['total_payments']
countPOI += 1
if enron_data[key]['total_payments'] == "NaN":
countPOI_TotalPaymentNAN += 1
print "No if POI =", countPOI, ", is POI & TotalPayment is NAN = ",countPOI_TotalPaymentNAN
#results,
# TotalPayment is NAN= 21 , TotalPayment is NAN & POI = 0
# No if POI = 18 , is POI & TotalPayment is NAN = 0
# ie zero overlap between TotalPayment is NAN & POI is True.
print len(enron_data.keys())
""" |
069a767cf5c6a7bfe4af220517bec05027896e71 | akm12k16/Python3-SortingAlgorithm | /merge_algo1.py | 1,272 | 4.09375 | 4 | # sorting algorithms
# mergeSort
def merge_sort(a):
n = len(a)
if n < 2:
return a
q = int(n / 2)
left = a[:q]
right = a[q:]
# print("left : {%s} , right : {%s}, A : {%s}" % (left, right, a))
merge_sort(left)
merge_sort(right)
a = merge(a, left, right)
# print("Result A ", a)
return a
def merge(a, left, right):
l = len(left)
r = len(right)
i, j, k = 0, 0, 0
# print("In merge function left : {%s} , right : {%s}, A : {%s}" % (left, right, a))
while i < l and j < r:
if left[i] <= right[j]:
a[k] = left[i]
k = k + 1
i = i + 1
else:
a[k] = right[j]
k = k + 1
j = j + 1
while i < l:
a[k] = left[i]
k = k + 1
i = i + 1
while j < r:
a[k] = right[j]
k = k + 1
j = j + 1
return a
# A=[8.01203212, 7, 6.2, 4.123122, 3-3, 43, 432, -2, 43, 42, 224, 2432, -432.0102, -42.4, -242342, -242342, 24234232,
# -4, 0, 20, 0.0001, 00.2, 00.32, -0.41, 2, 432, 2, -224223423]
A = ['A', 'B', 'C', 'EF', 'ALPHA', 'ZOOM', 'AAPPLE', 'COMP', 'JAGA', 'KKDAL']
# A = [8, 7, 6, 3, 9, -2, 19, 21, -2]
print("UnSorted list : ", A)
merge_sort(A)
print("Sorted list : ", A)
|
71c25127421bfc082812c662c340e4210a2c4195 | natewachter/ASTR-119 | /hello_again.py | 223 | 3.84375 | 4 |
def main():
i = 0 # integer i=0
x = 119.0 # x = 119.0
for i in range(120):
if( (i%2)==0 ):
x += 3.0
else:
x -= 5.0
s = "The value of x is x = %3.2e" % x
print(s)
if __name__ == "__main__":
main() |
ed3ddf2e0c28da3c986ffcf2f7f2d65b56fd270f | ValorWind1/Automate_stuff | /more_regularexpressions_part2.py | 1,723 | 4.0625 | 4 | import re
laugh = re.compile(r"(Ha){3}")
msg = laugh.search("HaHaHa")
print(msg.group())
msg1 = laugh.search("Ha")
print(msg1 == None) #here, (Ha){3} matches 'HaHaHa' but not 'Ha'. Since it doesn’t match 'Ha', search()
#Since (Ha){3,5} can match three, four, or five instances of Ha in the string 'HaHaHaHaHa',
# you may wonder why the Match object’s call to group() in the previous curly bracket example returns
# 'HaHaHaHaHa' instead of the shorter possibilities.
# After all, 'HaHaHa' and 'HaHaHaHa' are also valid matches of the regular expression (Ha){3,5}.
print("---------------")
"""
Greedy and None Greedy Method
"""
# by default regular expressions are greedy by default
#
greedy = re.compile(r"(HA){3,5}")
gr =greedy.search("HAHAHAHAHA")
print(gr.group())
# find the less amount
nongreedy = re.compile(r"(HA){3,5}?")
nongr = nongreedy.search('HAHAHAHAHA')
print(nongr.group())
print("---------------")
"""
Findall() Method.
While search() will return a Match object of the first matched text in the searched string,
the findall() method will return the strings of every match in the searched string.
"""
phoneregex = re.compile(r"\d\d\d-\d\d\d-\d\d\d\d")
txt1 = phoneregex.search("Your Cellphone number is : 312-456-7893, and my work telephone is : 212-345-6789")
print(txt1.group()) # see it just returns the first that finds
txt2= phoneregex.findall('"Your Cellphone number is : 312-456-7893, and my work telephone is : 212-345-6789')
print(txt2) # it returns everything as tuples , since it doesnt have groups
txt3 = re.compile(r"(\d\d\d)-(\d\d\d)-(\d\d\d\d)") # has groups parenthesis, different than phoneregex
txt4 = txt3.findall('Cell: 415-555-9999 Work: 212-555-0000')
print(txt4)
|
d5ba87037248e1ff03c0ffa45e02a3137940da17 | kamhaj/Short_Texts_API | /tests/tests_short_texts/test__models.py | 1,277 | 3.578125 | 4 | '''
unit tests examples for testing models
testing models is basically checking if we can work with the model (CRUD operations)
if some default methods (e.g. save()) were overridden, then they should be tested too
'''
#from django.test import TestCase
from short_texts.models import Post
from .factories import PostFactory
import pytest
@pytest.mark.django_db
class TestPostModel():
def test_create_new_post(self):
post = PostFactory()
# Check all field and validators
post.clean_fields() # EXCLUDE: FK, O2O, M2M Fields
# Check if at least one Post is present (can be more, it depends on test order if we do not delete new instances in tests)
posts = Post.objects.all()
assert len(posts) >= 1
@pytest.mark.django_db
def test_check_attribute_in_post(self):
# Check attributes
post = PostFactory()
assert post.title == 'Test Post Title'
assert post.content == 'Test content.'
assert post.views_counter == 0
@pytest.mark.django_db
def test_check_str_representation_of_post(self):
# Check string representation
post = PostFactory(title="New Post Title", content='New content.')
assert post.__str__() == 'New Post Title' |
0a84c0429577b243c96237a55f6225329659dfb1 | clopez5313/PythonCode | /Lists/MaxMin.py | 320 | 4.09375 | 4 | numList = list()
while True:
number = input('Please enter a number: ')
if number=='done':
break
try:
number = int(number)
except:
print('Please enter a numeric value.')
continue
numList.append(number)
print('Maximum:',max(numList))
print('Minimum:',min(numList))
|
e60ab5cb9870e5a4dbabb9020168e5c4780363b5 | vignesh-nethaji/python-samples | /StringIterate.py | 113 | 3.828125 | 4 | count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found') |
c589fbb0f3c79d9448d984db81d97e46401dbc8d | shrinkhlaGatech/CodingChallenges | /Array/strStr.py | 524 | 3.671875 | 4 | #https://leetcode.com/problems/implement-strstr/
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
for k in range(len(haystack)-len(needle) + 1):
if haystack[k:len(needle)+k] == needle:
return k
return -1
#O(n*m) time as for every k a substring equal to length of m will be compared to the needle
#O(n*m) space as for every k a substring equal to the length of m will be produced |
cfc3df2fb4676566c08591a8cc863d05302619d8 | hoik92/Algorithm | /algorithm/work_7/5108_add_number.py | 1,098 | 3.796875 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.top = None
def isEmpty(self):
return self.top == None
def push(self, idx, item):
new = Node(item)
if self.isEmpty():
self.head = new
self.top = new
elif idx == -1:
self.top.next = new
self.top = new
elif idx == 0:
new.next = self.head
self.head = new
else:
p = self.head
for i in range(idx - 1):
p = p.next
new.next = p.next
p.next = new
for tc in range(1, int(input())+1):
N, M, L = map(int, input().split())
m = list(map(int, input().split()))
link = LinkedList()
for i in m:
link.push(-1, i)
for i in range(M):
idx, item = map(int, input().split())
link.push(idx, item)
p = link.head
for i in range(L):
p = p.next
print("#{} {}".format(tc, p.item)) |
47b6c4b88402834f70d9563ea76691d9389be082 | cizkey/OpenCVPractice | /tutorial18.py | 2,083 | 3.5 | 4 | # 基于dlib的face detection, eye detection
# dlib的检测比使用opencv的人脸检测更加精准和强大
### 重要说明
# 安装dlib
# 首先确保python版本为3.6,从https://pypi.org/simple/dlib/下载dlib-19.8.1-cp36-cp36m-win_amd64.whl,
# 然后使用pip install dlib-19.8.1-cp36-cp36m-win_amd64.whl命令安装
# 准备人脸关键点模型
# 从http://dlib.net/files/下载shape_predictor_68_face_landmarks.dat.bz2,解压后拷贝到工程中即可
###
# 参考文章:
# https://www.cnblogs.com/vipstone/p/8964656.html
###
import cv2 as cv
import dlib
# 读入图片, im --> image
image = cv.imread("./assets/girl.jpg")
# 转为灰度图片
gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# 获得检测器
detector = dlib.get_frontal_face_detector()
# 根据关键点训练模型,获得预测器
predictor = dlib.shape_predictor("./dat/shape_predictor_68_face_landmarks.dat")
# 检测人脸特征
faces = detector(gray_image)
# 绿色
green = (0, 255, 0)
thickness = 2
def mid_point(p1, p2):
return int((p1.x + p2.x) / 2), int((p1.y + p2.y) / 2)
for face in faces:
landmarks = predictor(gray_image, face)
# 绘制所有68个关键点
for pt in landmarks.parts():
pt_pos = (pt.x, pt.y)
cv.circle(image, pt_pos, 2, green, thickness)
# 绘制人脸区域
x, y = face.left(), face.top()
x1, y1 = face.right(), face.bottom()
cv.rectangle(image, (x, y), (x1, y1), green, thickness)
# 绘制左边眼关键区域
left_point = (landmarks.part(36).x, landmarks.part(36).y)
right_point = (landmarks.part(39).x, landmarks.part(39).y)
center_top = mid_point(landmarks.part(37), landmarks.part(38))
center_bottom = mid_point(landmarks.part(41), landmarks.part(40))
# 绘制眼睛的水平横线和纵线
hor_line = cv.line(image, left_point, right_point, green, thickness)
ver_line = cv.line(image, center_top, center_bottom, green, thickness)
cv.imshow("Image", image)
# 等待键盘输入
cv.waitKey(0) & 0xFF
# 销毁窗体
cv.destroyAllWindows()
|
0234c402bc5f3b5bcee6873295bd99e99220232a | melx1998/upmc | /1I001/1I001_TME8.py | 2,871 | 3.734375 | 4 | #Ex 3.4
def alphabet():
"""None->list[str]
Retourne la liste des lettres de l'alphabet"""
return [chr(i) for i in range (ord('a'), ord('z')+1)]
assert alphabet()==['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def est_voyelle(c):
"""str->Bool
Retourne True si 'c' est une voyelle"""
return (c=='a' or c=='e' or c=='i' or c=='o' or c=='u' or c=='y')
assert est_voyelle('e')== True
assert est_voyelle('a')== True
def voyelle():
"""None -> list[str]
Retourne la liste des voyelles dans l'alphabet"""
return [c for c in alphabet() if est_voyelle(c)]
assert voyelle()==['a','e','i','o','u','y']
def consonne():
"""None-> list[str]
Retourne la liste des consonnes dans l'alphabet"""
return [c for c in alphabet() if not est_voyelle(c)]
assert consonne()==['b', 'c', 'd', 'f', 'g', 'h','j', 'k', 'l', 'm', 'n','p', 'q', 'r', 's', 't','v', 'w', 'x','z']
#Ex 3.5
def liste_caracteres(c):
"""str-> list[str] """
return[c[i] for i in range (0,len(c))]
assert liste_caracteres('les carottes')==['l','e','s',' ','c','a','r','o','t','t','e','s']
assert liste_caracteres('')==[]
def chaine_de(L):
"""List[str]-> str
Retourne la chaine de caractère correspondant à la liste L passée en paramètre"""
#c : str
res='' #la chaine de caracteres retournée
for c in L:
res=res+c
return res
assert chaine_de(['l','e','s',' ','c','a','r','o','t','t','e','s'])=='les carottes'
assert chaine_de(liste_caracteres('les carottes'))=='les carottes'
assert chaine_de([])==''
def num_car(c):
"""str->int
hypothèse c est une lettre minusdcule
Retourne la lettre c codée (0 pour 'a', etc)"""
return ord(c)-ord('a')
assert num_car('a')==0
assert num_car('z')==25
def car_num(n):
"""int -> str
hypothèse : n>=0 et n<=25
Retourne le caractère correspondant à l'entier entrée en caractère selon le code instauré dans la fonction num_car"""
return chr(n+ord('a'))
assert car_num(25)=='z'
assert car_num(0)=='a'
def rot13(c):
if c==' ':
return ' '
return car_num((num_car(c)+13)%26)
assert rot13('a')=='n'
def codage_rot13(s):
return chaine_de([rot13(c) for c in s])
assert codage_rot13('les carottes sont cuites')=='yrf pnebggrf fbag phvgrf'
#Ex 8.4
def liste_non_multiple(n,L):
""" int*list[int]-> list[int]
hypothese: n>0
retourne la liste des elements de L qui ne sont pas multiples de n."""
return[k for k in L if not k%n==0]
assert liste_non_multiple(7,[2,3,4,5,6,7,8,9,10])==[2,3,4,5,6,8,9,10]
assert liste_non_multiple(2,[2,3,4,5,6,7,8,9,10])==[3,5,7,9]
def eratosthene(n):
L=[]
for k in range (2, n+1):
if n%k!=0:
L.append(k)
return L
assert eratosthene(10)==[2,3,5,7]
|
b37cbac9a53341c3075a711c8c68c30ead49c973 | dongkooi/ngothedong-fundamental-C4E18 | /session04/login.py | 455 | 3.671875 | 4 | import getpass
user = "qweqwe"
password = "123123"
u = input("User: ")
count = 0
while True:
if u == user:
p = getpass.getpass('Pass:')
if p == password:
print("Welcom, c4e")
break
else:
print("Wrong password, please try again")
elif u != user:
print("You are not super user")
u = input("User: ")
count +=1
if count == 3:
print("faild")
break |
b78522938a2d3f426085e5eb7201a75f8e9aa75c | codespeech/python3-starter | /print/001-print-simple-text.py | 137 | 3.59375 | 4 | # To print a simple text string using print function, you just need to pass
# the string as parameter.
print('I really love Codespeech') |
fec4663eb191a70e56029f5cad56f50c3332d27e | sakshimankar/python | /passwordGenerator.py | 359 | 3.875 | 4 | #PROJECT NO.1 (PASSWORD GENERATOR)
import random
print("Enter number of passwords")
n=int(input())
print("Enter number of words required in password")
w=int(input())
print("\nPasswords are:\n")
for step in range(n):
z=''
for step in range(w):
s=random.randint(97,122)
p=chr(s)
z=z+p
print(z)
print("\n")
|
57115c86df006999969154c6decb05106e7ed2a1 | sermoacidus/python_training_autumn_2020 | /homework6/tasks_hw6/task1_deco_for_class.py | 1,574 | 3.9375 | 4 | """
Написать декоратор instances_counter, который применяется к любому классу
и добавляет ему 2 метода:
get_created_instances - возвращает количество созданых экземпляров класса
reset_instances_counter - сбросить счетчик экземпляров,
возвращает значение до сброса
Имя декоратора и методов не менять
Ниже пример использования
"""
def instances_counter(cls):
if "amount_of_instances" not in cls.__dict__:
setattr(cls, "amount_of_instances", 0)
source_method_save = cls.__new__
def __new__(cls, *args, **kwargs):
cls.amount_of_instances += 1
return source_method_save(cls, *args, **kwargs)
@classmethod
def get_created_instances(cls):
amount = cls.amount_of_instances
return amount
@classmethod
def reset_instances_counter(cls):
current_amount_of_instances = cls.amount_of_instances
setattr(cls, "amount_of_instances", 0)
return current_amount_of_instances
cls.__new__ = __new__
setattr(cls, "get_created_instances", get_created_instances)
setattr(cls, "reset_instances_counter", reset_instances_counter)
return cls
@instances_counter
class User:
pass
if __name__ == "__main__":
User.get_created_instances() # 0
user, _, _ = User(), User(), User()
user.get_created_instances() # 3
user.reset_instances_counter() # 3
|
a40b240473f2230e40079123038c2f04303b0e19 | collinskibetkenduiwa/.PyTo.exePython | /app.py | 2,919 | 3.96875 | 4 | from tkinter import Tk, Entry, Button, StringVar
# The following code is for a calculator app created using tkinter
# To convert the app run pyinstller app.py
class Calculator:
def __init__(self, master):
master.title('Simple Calculator')
master.geometry('360x260+0+0')
master.config(bg='#438')
master.resizable(False, False)
self.equation = StringVar()
self.entry_value = ''
Entry(width = 28,bg='lightblue', font = ('Times', 16), textvariable = self.equation).place(x=0,y=0)
Button(width=8, text = '(', relief ='flat', command=lambda:self.show('(')).place(x=0,y=50)
Button(width=8, text = ')', relief ='flat', command=lambda:self.show(')')).place(x=90, y=50)
Button(width=8, text = '%', relief ='flat', command=lambda:self.show('%')).place(x=180, y=50)
Button(width=8, text = '1', relief ='flat', command=lambda:self.show(1)).place(x=0,y=90)
Button(width=8, text = '2', relief ='flat', command=lambda:self.show(2)).place(x=90,y=90)
Button(width=8, text = '3', relief ='flat', command=lambda:self.show(3)).place(x=180,y=90)
Button(width=8, text = '4', relief ='flat', command=lambda:self.show(4)).place(x=0,y=130)
Button(width=8, text = '5', relief ='flat', command=lambda:self.show(5)).place(x=90,y=130)
Button(width=8, text = '6', relief ='flat', command=lambda:self.show(6)).place(x=180,y=130)
Button(width=8, text = '7', relief ='flat', command=lambda:self.show(7)).place(x=0,y=170)
Button(width=8, text = '8', relief ='flat', command=lambda:self.show(8)).place(x=180,y=170)
Button(width=8, text = '9', relief ='flat', command=lambda:self.show(9)).place(x=90,y=170)
Button(width=8, text = '0', relief ='flat', command=lambda:self.show(0)).place(x=0,y=210)
Button(width=8, text = '.', relief ='flat', command=lambda:self.show('.')).place(x=90,y=210)
Button(width=8, text = '+', relief ='flat', command=lambda:self.show('+')).place(x=270,y=90)
Button(width=8, text = '-', relief ='flat', command=lambda:self.show('-')).place(x=270,y=130)
Button(width=8, text = '/', relief ='flat', command=lambda:self.show('/')).place(x=270,y=170)
Button(width=8, text = 'x', relief ='flat', command=lambda:self.show('*')).place(x=270,y=210)
Button(width=8, text = '=', bg='green', relief ='flat', command=self.solve).place(x=180, y=210)
Button(width=8, text = 'AC', relief ='flat', command=self.clear).place(x=270,y=50)
def show(self, value):
self.entry_value +=str(value)
self.equation.set(self.entry_value)
def clear(self):
self.entry_value = ''
self.equation.set(self.entry_value)
def solve(self):
result = eval(self.entry_value)
self.equation.set(result)
root = Tk()
calculator = Calculator(root)
root.mainloop() |
968cfca57c440ca19e143811b819926c67603148 | vcchang-zz/coding-practice | /Binary Search Trees/rangeSum/sum-every-node.py | 1,854 | 3.578125 | 4 | # Range sum BST
# Given the root node of a binary search tree,
# return the sum of values of all nodes with
# value between L and R (inclusive).
# Assumption: bst is guaranteed to have unique values
# Visit every node approach
# Input: Node bst (with n nodes), int left, int right
# Time: O(n) -> worst case = linear tree, height = n-1
# Space: O(n) -> call stack will only grow as tall as
# max depth (ie: height) of tree -> height
# = n-1 = tallest tree
from node import Node
def rangeSum(root: Node, left: int, right: int):
if not root:
return 0
sum = 0
if root.val >= left and root.val <= right:
sum += root.val
return sum + rangeSum(root.left, left, right) + rangeSum(root.right, left, right)
if __name__ == "__main__":
bstNone = None
leftNone = 1
rightNone = 17
expectedNone = 0
actualNone = rangeSum(bstNone, leftNone, rightNone)
assert actualNone == expectedNone
print(f"Range of sum in bst None = {actualNone}")
bstOne = Node(1)
leftOne = -1
rightOne = 2
expectedOne = 1
actualOne = rangeSum(bstOne, leftOne, rightOne)
assert actualOne == expectedOne
print(f"Range of sum in bst [1] = {actualOne}")
bstComplex = Node(10)
bstComplex.left = Node(4)
bstComplex.right = Node(17)
bstComplex.left.left = Node(2)
bstComplex.left.right = Node(6)
bstComplex.right.left = Node(13)
bstComplex.right.right = Node(21)
bstComplex.right.right.left = Node(19)
leftComplex = 6
rightComplex = 19
expectedComplex = 6 + 10 + 13 + 17 + 19
actualComplex = rangeSum(bstComplex, leftComplex, rightComplex)
assert actualComplex == expectedComplex
print(f"Range of sum in bst [10, 4, 17, 2, 6, 13, 21, None, None, None, None, None, None, 19, None] = {actualComplex}") |
3b0d0603920b6ad88f4e606e6a0e9e08efc14340 | patrickpeng0928/Leetcode | /Array/3.LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters_Array.py | 1,454 | 3.828125 | 4 | class Solution(object):
def longestUnique(self, s: 'str') -> int:
"""
Time - O(n)
Spacce - O(n)
1. Define a sliding window to contain the substring withouth repeating char
2. Using a dictionary to record the last occurance of the character in the string
3. Iterate through string from left to right, compare length of the sliding window with the max length before.
4. need to record the start point of the sliding window in each iteration
"""
dict = {}
res = 0
start = 0
for i, char in enumerate(s):
if char in dict and start < i:
# existing char in the sliding widonw
# reset the start of the sliding window to next char of the existing char
start = dict[char] + 1
else:
# no same char existing in the window
# extend window
# cal new length
res = max(res, i - start + 1)
# update the occureance of the char
dict[char] = i
return res
if __name__ == "__main__":
print("Start testing ... ")
s = Solution()
assert s.longestUnique("abcabcbb") == 3, \
"Failed, example: abcabcb"
assert s.longestUnique("bbbbb") == 1, \
"Failed, example: bbbbb"
assert s.longestUnique("pwwkew") == 3, \
"Failed, example: pwwkew"
print("All tests passed.")
|
d2898ac69327471e890be7c24e5045ca53e24262 | codeaffect/py_projects | /CodeChallenges/practice/pyramidString.py | 71 | 3.5 | 4 | n = int(input())+1
for i in range(1, n):
print(' '*(n-i-1), '#'*i)
|
5d56423138d807b8c2bc45cba1e4def5f37434d5 | liweiwei1419/Algorithms-Learning-Python | /sorting/merge_sort.py | 6,103 | 3.703125 | 4 | from sorting.examples import GenerateRandomArrayStrategy
from sorting.sorting_util import SortingUtil
class MergeSort:
def __str__(self):
return "归并排序"
def __merge_of_two_sorted_array(self, arr, left, mid, right):
# Python 中切片即复制,复制到一个临时数组中
nums_for_compare = arr[left:right + 1]
i = 0
j = mid - left + 1
# 通过 nums_for_compare 数组中设置两个指针 i、j 分别表示两个有序数组的开始
# 覆盖原始数组
for k in range(left, right + 1):
if i > mid - left:
arr[k] = nums_for_compare[j]
j += 1
elif j > right - left:
arr[k] = nums_for_compare[i]
i += 1
elif nums_for_compare[i] <= nums_for_compare[j]:
# 注意:这里使用 <= 是为了保证归并排序算法的稳定性
arr[k] = nums_for_compare[i]
i += 1
else:
assert nums_for_compare[i] >= nums_for_compare[j]
arr[k] = nums_for_compare[j]
j += 1
def __merge_sort(self, arr, left, right):
if left >= right:
return
# 这是一个陷阱,如果 left 和 right 都很大的话,left + right 容易越界
# Python 中整除使用 // 2
mid = (left + right) // 2
self.__merge_sort(arr, left, mid)
self.__merge_sort(arr, mid + 1, right)
self.__merge_of_two_sorted_array(arr, left, mid, right)
@SortingUtil.cal_time
def sort(self, arr):
"""
归并排序的入口函数
"""
size = len(arr)
self.__merge_sort(arr, 0, size - 1)
class MergeSortOptimizer:
def __str__(self):
return "归并排序的优化"
def __merge_of_two_sorted_array(self, arr, left, mid, right):
# 将原数组 [left, right] 区间内的元素复制到辅助数组
for index in range(left, right + 1):
nums_for_compare[index] = arr[index]
i = left
j = mid + 1
for k in range(left, right + 1):
if i == mid + 1:
# i 用完了,就拼命用 j
arr[k] = nums_for_compare[j]
j += 1
elif j > right:
# j 用完了,就拼命用 i
arr[k] = nums_for_compare[i]
i += 1
elif nums_for_compare[i] <= nums_for_compare[j]:
arr[k] = nums_for_compare[i]
i += 1
else:
assert nums_for_compare[i] > nums_for_compare[j]
arr[k] = nums_for_compare[j]
j += 1
def insert_sort_for_sub_interval(self, arr, left, right):
"""多次赋值的插入排序"""
for i in range(left + 1, right + 1):
temp = arr[i]
j = i
# 注意:这里 j 最多到 left
while j > left and arr[j - 1] > temp:
arr[j] = arr[j - 1]
j -= 1
arr[j] = temp
def __merge_sort(self, arr, left, right):
if right - left <= 15:
self.insert_sort_for_sub_interval(arr, left, right)
return
mid = left + (right - left) // 2
self.__merge_sort(arr, left, mid)
self.__merge_sort(arr, mid + 1, right)
if arr[mid] <= arr[mid + 1]:
return
self.__merge_of_two_sorted_array(arr, left, mid, right)
@SortingUtil.cal_time
def sort(self, arr):
global nums_for_compare
size = len(arr)
nums_for_compare = list(range(size))
self.__merge_sort(arr, 0, size - 1)
class MergeSortBU:
def __str__(self):
return "自底向上的归并排序"
def __merge_of_two_sorted_array(self, arr, left, mid, right):
for index in range(left, right + 1):
nums_for_compare[index] = arr[index]
i = left
j = mid + 1
for k in range(left, right + 1):
if i == mid + 1:
arr[k] = nums_for_compare[j]
j += 1
elif j > right:
arr[k] = nums_for_compare[i]
i += 1
elif nums_for_compare[i] <= nums_for_compare[j]:
arr[k] = nums_for_compare[i]
i += 1
else:
assert nums_for_compare[i] > nums_for_compare[j]
arr[k] = nums_for_compare[j]
j += 1
@SortingUtil.cal_time
def sort(self, arr):
size = len(arr)
global nums_for_compare
nums_for_compare = list(range(size))
sz = 1
# sz = 1, 2, 4, 8
while sz < size:
# left = 0, 2, 4, 6
left = 0
while left < size - sz:
self.__merge_of_two_sorted_array(arr, left, left + sz - 1, min(left + sz + sz - 1, size - 1))
left += 2 * sz
sz *= 2
if __name__ == '__main__':
# 测试基本的归并排序算法正确
# SortingUtil.test_sorting_algorithm(MergeSort())
# 比较插入排序与归并排序,可以看出归并排序快很多
# SortingUtil.compare_sorting_algorithms(GenerateRandomArrayStrategy(),
# InsertionSortOptimizer(),
# MergeSort())
# 比较归并排序与归并排序的优化
# SortingUtil.compare_sorting_algorithms(GenerateRandomArrayStrategy(),
# MergeSort(),
# MergeSortOptimizer())
# 测试自底向上的归并排序
# SortingUtil.test_sorting_algorithm(MergeSortBU())
# 比较自顶向下的归并排序(递归实现)与自底向上的归并排序(循环实现)
# 自底向上的归并排序更耗时,因为分割不均匀
SortingUtil.compare_sorting_algorithms(GenerateRandomArrayStrategy(),
MergeSortOptimizer(),
MergeSortBU())
|
52279c64adafe4d03a974967da882ba4888fed1b | zzz0906/LeetCode | /Scripts/7.py | 1,117 | 3.78125 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if (x > pow (2,31) - 1 or x < -pow(2,31)):
return 0
answer = 0
if (x >= 0):
data = []
while (x > 0):
data.append(x % 10)
x = int(x / 10)
mid = 1
while (len(data) != 0):
answer += data.pop() * mid
mid = mid * 10
if (answer > pow (2,31) - 1 or answer < -pow(2,31)):
return 0
return answer
if (x < 0):
x = x * -1
data = []
while (x > 0):
data.append(x % 10)
x = int(x / 10)
mid = 1
while (len(data) != 0):
#print(data)
answer += data.pop() * mid
mid = mid * 10
if (answer > pow (2,31) - 1 or answer < -pow(2,31)):
return 0
return answer * -1
if __name__ == '__main__':
solution = Solution()
print(solution.reverse(-16))
|
85469c8b45aeddb08152492ebdf357bb22da8917 | codingiscool121/Class-98-Functions-python- | /words.py | 301 | 4.125 | 4 | def wordcount():
filename = input("What is the file name?")
file = open(filename, 'r')
numberofwords = 0
for w in file:
words=w.split()
numberofwords=numberofwords+len(words)
print("There are " + str(numberofwords) + " words in this file.")
wordcount()
|
90cec95ee2eeca5fba5d11e8283676252df7600f | enoch-enchill/Python-Algorithms | /Numbers/WeirdNotWeird.py | 221 | 3.796875 | 4 |
def solution(n):
if (n%2 == 1) or (n >=6 and n <= 20):
print("Weird")
elif (n >=2 and n <=5) or n > 20:
print("Not Weird")
if __name__ == '__main__':
N = int(input())
solution(int(N))
|
eecd458a0b46377578e464129eb0960352f9b3cc | allenchng/Bit-O-Code | /leetcode/Python/Leetcode 349 Intersection of Two Arrays.py | 2,162 | 3.984375 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# There are multiple ways to solve this problem. I will show one approach using pointers and a dictionary. I encourage you to think about other ways to solve the problem!
# Looking at the inputs, I need to keep in mind two things.
# 1) The elements are out of order. If I'm searching for matches between arrays, it's inefficient to have to check each array. One way to solve this challenge is to sort both arrays in place before iterating through them.
# 2) The second thing to keep in mind is that integers can be repeated within an array and I don't want to double count that in my array.
nums1.sort()
nums2.sort()
# Here I set up two pointers to keep track of where I am in each array. I also set up a dictionary to solve my second problem. Remember, a dictionary has constant look up time.
a = 0
b = 0
res = {}
# Next I iterate through each array, if I ever reach the end of the array, I know there's no more elements to check for intersection. As I iterate, I check the values at each of my pointers. If one is greater than the other, I move the pointer until I find when the array values are equal. From there, I check if the value is in my dictionary. If not, add it. Ohterwise move both pointers forward.
while a < len(nums1) and b < len(nums2):
if nums1[a] < nums2[b]:
a += 1
elif nums1[a] > nums2[b]:
b += 1
else:
if nums1[a] not in res:
res[nums1[a]] = 1
a += 1
b += 1
return res
# Time complexity: Sorting in place is O(n log n) time and the loop is O(n), where n is the length of the shorter array.
# Space complexity: O(n) where there is perfect intersection across arrays and the values within each array are unique. |
34f167915d31c7ea565f62a5e6ada730bb791574 | ChrisClear/Coding_Dojo_Coursework | /Python/Python_Fundamentals/Fund_Completed/cointoss.py | 1,046 | 4.03125 | 4 | """
Coin Tosses Assignment, Coding Dojo Python fundamentals.
"""
#pylint: disable=C0103
def getRandom():
""" This function delivers a random number between 1 and 2 (heads or tails)
"""
import random
random_num = random.randint(1, 2)
return random_num
def coinToss():
""" This function gets a random number, expecting 1 or 2, and uses it for heads or tails.
Will count the results in order to output. This is a fun science experiment!
I expect the results to be close to 50/50.
"""
counter = 0 #initialize variable
headcount = 0
tailcount = 0
headortail = "head"
while counter < 5000:
nexttoss = getRandom() #get the next coin toss
if nexttoss is 1:
headortail = "head"
headcount += 1
else:
headortail = "tail"
tailcount += 1
print "Attempt #"+counter+": Throwing a coin... It's a "+headortail+"! Got "+headcount+"head(s) so far and "+tailcount+" tail(s) so far..."
print "Ending the program, thank you!"
|
8999dc19265e494989d1d2099fe2ba6936e75ed1 | dev-iwin/book8-hanbit-python-data-structure-algorithm | /02-99-exam-01-02-my-ver.py | 1,159 | 3.859375 | 4 | ## 자동 로또 번호 생성기 : my ver ##
## 동일한 줄을 제거하는 명령 1줄 추가 ##
import random
allLotto = []
oneLotto = []
count = 0
numLotto = 0
print("** 로또 번호 생성을 시작합니다. **")
count = int(input("로또를 몇 줄 구매할까요? --> "))
while len(allLotto) <= count-1: # 길이가 5일 때도 참이 되면, 한 줄 더 추가해서 6이 된다.
random.seed()
while len(oneLotto) <= 6: # 그럼 이건 왜 숫자가 7개 뽑히지 않는 거지?
numLotto = random.randint(1, 45)
if numLotto not in oneLotto:
oneLotto.append(numLotto)
oneLotto.sort()
if oneLotto not in allLotto :
allLotto.append(oneLotto)
oneLotto = []
for i in range(len(allLotto)):
lottoStr = "자동번호-->"
print(lottoStr, end=' ')
for k in range(6):
print("%3d" % allLotto[i][k], end=' ')
print('')
'''
https://www.geeksforgeeks.org/python-random-sample-function/
중복 없이 랜덤한 값을 범위 내에서 뽑는 법
from random import sample
list1 = [1, 2, 3, 4, 5]
print(sample(list1,3)) # 리스트1에서 중복 없이 3개 뽑아
''' |
8be8d1d863bd759464ed8f195f64dd1e805da4d2 | pengfei-code/python_learn | /10_gui_tkinter/10_gui_tkinter_messagebox.py | 255 | 3.71875 | 4 | from tkinter import *
from tkinter.messagebox import *
tk = Tk()
def show_info():
print("enter")
info = showinfo(message="hello")
print(info)
pass
btn = Button(tk,text="show info",command=lambda:show_info())
btn.pack()
tk.mainloop()
|
d0b70ef427e179dc8fd9b010bd8a2c07cb6609e4 | jianghaifeng/python | /idckeck.py | 682 | 3.96875 | 4 | #!/usr/bin/env python
import string
alphas = string.ascii_letters + '_'
nums = string.digits
print('Welcome to the Identifier Check V1.0')
inp = input('Identifier to test:')
if len(inp) == 1:
if inp[0] not in string.ascii_letters:
print('Invalid (symbol must be alphabetic)')
else:
print('OK as an identifier')
elif (len(inp)) > 1:
if (inp[0] not in alphas):
print('Invalid (first symbol must be alphabetic)')
else:
for otherchar in inp[1:]:
if otherchar not in alphas+nums:
print('Invalid (symbols must be alphanumeric)')
break
else:
print('OK as an identifier')
|
d1294d70ba8fc73412fdf0656d155eac7b8258e8 | stepalxser/Lafore_in_python | /Lafore/Chapter04/queue.py | 4,996 | 3.8125 | 4 | from typing import List, Optional
class Queue:
def __init__(self, size: int) -> None:
self._size = size
self._state: List[Optional[int]] = [None for _ in range(size)]
self._front_pointer = 0
self._rear_pointer = 0
self._elem_counter = 0
def __str__(self) -> str:
return str(self._state)
def insert(self, value: int) -> None:
if self._elem_counter == self._size:
raise ValueError('Queue is full')
if self._rear_pointer == self._size:
self._rear_pointer = 0
self._state[self._rear_pointer] = value
self._rear_pointer += 1
self._elem_counter += 1
def remove(self) -> int:
if not self._elem_counter:
raise ValueError('Queue is empty')
if self._front_pointer == self._size:
self._front_pointer = 0
result = self._state[self._front_pointer]
self._state[self._front_pointer] = None
self._front_pointer += 1
self._elem_counter -= 1
return result
def peek(self) -> int:
if self._elem_counter:
raise ValueError('Queue is empty')
return self._state[self._front_pointer]
@property
def is_empty(self) -> bool:
return not self._elem_counter
@property
def is_full(self) -> bool:
return self._elem_counter == self._size
# chapter04 programming project 4.1
def display(self) -> None:
if self._rear_pointer > self._front_pointer:
print(*self._state[self._front_pointer:self._rear_pointer], sep=' ')
else:
print(*self._state[self._front_pointer:], sep=' ', end=' ')
print(*self._state[0:self._rear_pointer], sep=' ')
# Chapter04 programming project 4.4
class PriorityQueue:
def __init__(self, size: int) -> None:
self._size = size
self._state: List[Optional[int]] = [None for _ in range(size)]
self._elem_counter = 0
def __str__(self) -> str:
return str(self._state)
@property
def is_empty(self) -> bool:
return not self._elem_counter
@property
def is_full(self) -> bool:
return self._elem_counter == self._size
def insert(self, value) -> None:
if self._elem_counter == 0:
self._state[self._elem_counter] = value
else:
insert_index = 0
for index in range(self._elem_counter-1, -1, -1):
if value > self._state[index]:
self._state[index+1] = self._state[index]
else:
insert_index = index + 1
break
self._state[insert_index] = value
self._elem_counter += 1
def remove(self) -> int:
result = self._state[self._elem_counter-1]
self._state[self._elem_counter-1] = None
self._elem_counter -= 1
return result
def peek(self) -> int:
return self._state[self._elem_counter]
class FastQueue:
def __init__(self, size: int) -> None:
self._size = size
self._state: List[Optional[int]] = [None for _ in range(size)]
self._elem_counter = 0
def __str__(self) -> str:
return str(self._state)
@property
def is_empty(self) -> bool:
return not self._elem_counter
@property
def is_full(self) -> bool:
return self._elem_counter == self._size
def insert(self, value) -> None:
self._state[self._elem_counter] = value
self._elem_counter += 1
def remove(self) -> int:
remove_index, min_elem = 0, float('+inf')
for index in range(self._elem_counter):
if self._state[index] > min_elem:
remove_index = index
result = self._state[remove_index]
self._state[remove_index] = None
for index in range(remove_index+1, self._elem_counter):
self._state[index], self._state[index-1] = self._state[index-1], self._state[index]
self._elem_counter -= 1
return result
def peek(self) -> int:
remove_index, min_elem = 0, float('+inf')
for index in range(self._elem_counter):
if self._state[index] > min_elem:
remove_index = index
return self._state[remove_index]
if __name__ == '__main__':
queue = Queue(10)
for item in range(10):
queue.insert(item)
queue.display()
for _ in range(5):
queue.remove()
queue.display()
for item in range(10, 15):
queue.insert(item)
queue.display()
fast_queue = FastQueue(10)
for item in range(1, 11):
fast_queue.insert(item)
print(fast_queue)
fast_queue.remove()
fast_queue.remove()
fast_queue.remove()
print(fast_queue)
priority_queue = PriorityQueue(10)
for item in range(100, 0, -10):
priority_queue.insert(item)
print(priority_queue)
for _ in range(5):
print(priority_queue.remove())
print(priority_queue) |
fb23aba11b977de9edf36425c8711bc82d5838ff | biwin/codecademy-python-projects | /pyglatin_1.py | 303 | 4.0625 | 4 | __author__ = 'payload'
print 'Welcome to the Pig Latin Translator!'
# len(x) computes the length of the given 'x'
# isalpha checks whether the given string is alphabet or not
original = raw_input("Enter a word")
if len(original) > 0 and original.isalpha():
print(original)
else:
print "empty" |
e501c676fb8435ec47c6d0b38106abf8438830f1 | dictator-x/practise_as | /algorithm/leetCode/0212_word_search_2.py | 1,911 | 3.734375 | 4 | """
212. Word Search II
"""
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
class TrieNode:
def __init__(self):
self.chars = [None] * 26
self.completeWord = None
wl = set(words)
r, c = len(board), len(board[0])
# Build trie.
root = TrieNode()
for word in wl:
temp = root
for char in word:
offset = ord(char) - ord("a")
# Only create new node if not exists
if temp.chars[offset] == None:
temp.chars[offset] = TrieNode()
temp = temp.chars[offset]
temp.completeWord = word
ret = set([])
def doFind(i, j, root):
if i < 0 or j < 0 or i == r or j == c or board[i][j] == "#":
return
char = board[i][j]
cur = root.chars[ord(char) - ord("a")]
if cur == None:
return
if cur.completeWord != None:
ret.add(cur.completeWord)
board[i][j] = "#"
doFind(i-1, j, cur)
doFind(i+1, j, cur)
doFind(i, j-1, cur)
doFind(i, j+1, cur)
board[i][j] = char
for i in range(r):
for j in range(c):
doFind(i, j, root)
return ret
if __name__ == "__main__":
# board = [['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']]
# words = ["oath","pea","eat","rain"]
# board = [['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']]
# words = ["oath","pea","eat","rain"]
board = [["a","b"],["c","d"]]
words = ["ab","cb","ad","bd","ac","ca","da","bc","db","adcb","dabc","abb","acb"]
solution = Solution()
print(solution.findWords(board, words))
|
40b43fdd7bd27856ea40e953fe378660231f6d5d | Szoul/Automate-The-Boring-Stuff | /Chapter 5/Testing_Finding_Variable_in_list_of_lists.py | 3,958 | 3.921875 | 4 | height = 5
listwithinlists = [[] for i in range (height)]
for i in range (height):
for letter in "abcd":
listwithinlists[i].append(str(i)+str(letter))
for y in range (height):
for x in range (4):
print (listwithinlists[y][x] + " ", end ="")
print ("")
variable_True = "1b"
variable_False = "123bhd"
list_True = ["1a", "2b", "4a"]
list_partially_False = ["123bd", "5423ac", "29ü", "1a"]
dict_True = {"1a":"1a", "2b":"2b", "4a":"3c"}
dict_partially_False = {"123bd":"123bd", "5423ac":"5423ac", "29ü":"29ü", "1a":"2b"}
def checkvariable (variable,list_to_check): #check if variable exists in a list of lists, return exists/doesn't exist
isinlist = False
for i in range(len(list_to_check)):
if variable in list_to_check[i]:
print (str(variable) + " \u001b[35m exists \u001b[37m in the list number " + str(i) + " of the list you checked")
return True
isinlist = True
else:
pass
if isinlist == False:
print (str(variable) + " is not part of the list")
return False
def checkvariable2 (variable, list_to_check):
if any(variable in list_to_check[i] for list_to_check[i] in list_to_check):
print (str(variable) + " \u001b[35m exists \u001b[37m in the list you checked")
return True
else:
print (str(variable) + " is not part of the list")
return False
def checklist (mylist,list_to_check): #check if all items of list exist in list of lists, return those who do/do not
isinlist = False
list_of_matches = []
list_of_non_matches = []
for i in range (len(mylist)):
isincurrentsearch = 0
for x in range (len(list_to_check)):
if mylist[i] in list_to_check[x]:
print (str(mylist[i]) + " \u001b[35m exists \u001b[37m in the list number " + str(x) + " of the list you checked")
isinlist = True
isincurrentsearch +=1
if isincurrentsearch == 0:
print (str(mylist[i]) + " does not exist in the you checked")
list_of_non_matches.append(mylist[i])
if isinlist == False:
print ("No item of your list is part of the checked list")
return mylist
else:
return [list_of_matches, list_of_non_matches]
def checklist2 (mylist, list_to_check): #doesnt work as intended yet
list_of_matches = []
for x in range(len(list_to_check)):
current_list_of_matches = [i for i in mylist if i in list_to_check[x]]
for k in range(len(current_list_of_matches)):
list_of_matches.append(current_list_of_matches[k])
list_of_non_matches = [i for i in mylist if i not in list_of_matches]
return [list_of_matches, list_of_non_matches]
def checkdictkeys (dictionary,list_to_check): #check if all keys of a dictionary exist as items of a list, return those who do/do not
list_of_keys = list(dictionary.keys())
return checklist(list_of_keys, list_to_check)
print ("Check first variable:")
checkvariable2(variable_True, listwithinlists)
print ("\n___________")
print("Check second variable:")
checkvariable2(variable_False, listwithinlists)
print ("\n___________")
print("Check first list:")
checklist(list_True, listwithinlists)
print ("\n___________")
print ("Check second list:")
checklist(list_partially_False, listwithinlists)
print ("\n___________")
print ("Check first dictionary")
checkdictkeys(dict_True, listwithinlists)
print ("\n___________")
print ("Check second dictionary")
checkdictkeys(dict_partially_False, listwithinlists)
print ("\n\n___________")
print ("Check first, then second list")
print (checklist2(list_True, listwithinlists))
print (checklist2(list_partially_False, listwithinlists))
# how to use [i for i in List1 if i in List2[iterate through all lists within this list]]
# (x in a for x in b)
|
ca75089bb3ccf6d6a83b4ce0e4593c441d4861f1 | juraj80/myPythonCookbook | /days/88-90-home-inventory-app/my_code.py | 3,288 | 3.640625 | 4 | import sqlite3
import sys
from contextlib import contextmanager
DB = "inventory.db"
def first_launch():
try:
conn = sqlite3.connect(DB)
except:
sys.exit('Error code X.')
@contextmanager
def access_db():
conn = sqlite3.connect(DB)
cursor = conn.cursor()
yield cursor
conn.commit()
conn.close()
def main_menu():
menu = {'1': "Add Room.", '2': "Add Inventory.", '3': "View Inventory List.", '4': "Total Value.", '5': "Exit."}
while True:
print('\n')
for num, item in sorted(menu.items()):
print(num, item)
choice = input('Selection: ')
if choice == '1':
add_room()
elif choice == '2':
add_inventory(check_input())
elif choice == '3':
view_inventory(check_input())
elif choice == '4':
calc_total()
elif choice == '5':
sys.exit()
else:
print("Invalid option, try again.")
def check_input():
while True:
print('\n')
for room in list_rooms():
print(room)
selection = input('Select a room: ').lower()
print(list_rooms())
if selection not in list_rooms():
print('\n%s does not exist.' % selection)
else:
return scrub(selection)
def add_room():
name = input('Enter the name of new room: ')
name = scrub(name)
with access_db() as cursor:
cursor.execute("CREATE TABLE'" + name.lower() + "'(Item TEXT, Value REAL)")
print("\nRoom with name %s was added to the db." % name)
# def list_rooms():
# return [room for room, items in ROOMS.items()]
def add_inventory(room):
while True:
print('\n')
name = input('Enter the name of item: ')
cost = float(input('Enter the value of item: '))
with access_db() as cursor:
cursor.execute("INSERT INTO '" + room + "' VALUES(?,?)", [name, cost])
print(f"Item '{name}' with value {cost} added to the inventory of room {room}")
cont = input('\nHit Q to quit or any other key to continue.')
if cont.lower() == 'q':
break
def view_inventory(room):
print(f'Items or room {room} :')
total = 0
with access_db() as cursor:
cursor.execute("SELECT * FROM '" + room + "'")
for data in cursor:
print(" %s: $%d" % (data[0], data[1]))
total += data[1]
print("Total value of room %s: $%d" % (room, total))
# Function to calculate the $ total of the entire database.
def calc_total():
total = 0
room_list = list_rooms()
with access_db() as cursor:
for room in room_list:
cursor.execute("SELECT Value FROM '" + room + "'")
for value in cursor:
# print(value)
total += value[0]
print("Total value of all rooms: $%d" % total)
def list_rooms():
room_list = []
with access_db() as cursor:
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
for room in cursor:
room_list.append(room[0])
return room_list
def scrub(name):
return ''.join(chr for chr in name if chr.isalnum())
if __name__ == '__main__':
first_launch()
main_menu()
|
eba04d7b413d89168500efe1fbdd04744f8d39ba | hareeshnagaraj/MoneyWeather | /app/populate_commodity.py | 9,150 | 3.59375 | 4 | #This script handles commodity data population into the database
#takes a command line argument specifying which commodity
#commodity .csv files are stored in /data/commodities/
import psycopg2
import urllib2
import csv
import sys
conn = psycopg2.connect(database="nagaraj_weather", user="nagaraj", password="nagaraj", host="localhost", port="63333")
cur = conn.cursor() #used to perform ops on db
conn.autocommit = True #used to automatically commit updates to db
def populateGold():
print("Loading gold data from /data/commodities/gold_prices.csv")
prequery = "SELECT * FROM commodity WHERE commodityname = 'gold'"
cur.execute(prequery)
if cur.rowcount == 0: #insert gold into the commodity database if not present
print("Adding gold to the commodity table")
cur.execute("""INSERT INTO commodity (commodityname,unit_measure) VALUES (%s,%s)""",('gold','troy ounce',))
prequery = "SELECT * FROM commodity_price WHERE commodityname = 'gold' AND day = %s AND month = %s AND year = %s"
with open('data/commodities/gold_prices.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
x = 0
for row in spamreader:
if x > 0:
date = row[0]
price = row[1]
dateparams = date.split("-")
year = dateparams[0]
month = dateparams[1]
day = dateparams[2]
cur.execute(prequery, (day,month,year))
# print(cur.rowcount)
# print(row)
if cur.rowcount == 0:
try:
cur.execute("""INSERT INTO commodity_price \
(commodityname,month,year,price,day) \
VALUES (%s, %s, %s, %s, %s)""", \
("gold",month,year,price,day,))
except Exception:
print("ERROR")
return ;
pass
x += 1
def populateCorn():
print("Loading corn data from /data/commodities/corn_prices.csv")
prequery = "SELECT * FROM commodity WHERE commodityname = 'corn'"
cur.execute(prequery)
if cur.rowcount == 0: #insert corn into the commodity database if not present
print("Adding corn to the commodity table")
cur.execute("""INSERT INTO commodity (commodityname,unit_measure) VALUES (%s,%s)""",('corn','cents per bushel',))
prequery = "SELECT * FROM commodity_price WHERE commodityname = 'corn' AND day = %s AND month = %s AND year = %s"
with open('data/commodities/corn_prices.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
x = 0
for row in spamreader:
if x > 0:
date = row[0]
price = row[1]
dateparams = date.split("-")
year = dateparams[0]
month = dateparams[1]
day = dateparams[2]
cur.execute(prequery, (day,month,year))
print(date + " " + price)
# print(cur.rowcount)
# print(row)
if cur.rowcount == 0:
try:
cur.execute("""INSERT INTO commodity_price \
(commodityname,month,year,price,day) \
VALUES (%s, %s, %s, %s, %s)""", \
("corn",month,year,price,day,))
except Exception:
print("ERROR")
return ;
pass
x += 1
def populateWheat():
print("Loading wheat data from /data/commodities/wheat_prices.csv")
prequery = "SELECT * FROM commodity WHERE commodityname = 'wheat'"
cur.execute(prequery)
if cur.rowcount == 0: #insert wheat into the commodity database if not present
print("Adding wheat to the commodity table")
cur.execute("""INSERT INTO commodity (commodityname,unit_measure) VALUES (%s,%s)""",('wheat','cents per bushel',))
prequery = "SELECT * FROM commodity_price WHERE commodityname = 'wheat' AND day = %s AND month = %s AND year = %s"
with open('data/commodities/wheat_prices.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
x = 0
for row in spamreader:
if x > 0:
date = row[0]
price = row[1]
dateparams = date.split("-")
year = dateparams[0]
month = dateparams[1]
day = dateparams[2]
cur.execute(prequery, (day,month,year))
print(date + " " + price)
# print(cur.rowcount)
# print(row)
if cur.rowcount == 0:
try:
cur.execute("""INSERT INTO commodity_price \
(commodityname,month,year,price,day) \
VALUES (%s, %s, %s, %s, %s)""", \
("wheat",month,year,price,day,))
except Exception:
print("ERROR")
return ;
pass
x += 1
def populateCoffee():
print("Loading coffee data from /data/commodities/coffee_prices.csv")
prequery = "SELECT * FROM commodity WHERE commodityname = 'coffee'"
cur.execute(prequery)
if cur.rowcount == 0: #insert coffee into the commodity database if not present
print("Adding coffee to the commodity table")
cur.execute("""INSERT INTO commodity (commodityname,unit_measure) VALUES (%s,%s)""",('coffee','cents per bushel',))
prequery = "SELECT * FROM commodity_price WHERE commodityname = 'coffee' AND day = %s AND month = %s AND year = %s"
with open('data/commodities/coffee_prices.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
x = 0
for row in spamreader:
if x > 0:
date = row[0]
price = row[1]
dateparams = date.split("-")
year = dateparams[0]
month = dateparams[1]
day = dateparams[2]
cur.execute(prequery, (day,month,year))
print(date + " " + price)
# print(cur.rowcount)
# print(row)
if cur.rowcount == 0:
try:
cur.execute("""INSERT INTO commodity_price \
(commodityname,month,year,price,day) \
VALUES (%s, %s, %s, %s, %s)""", \
("coffee",month,year,price,day,))
except Exception:
print("ERROR")
return ;
pass
x += 1
def populateNaturalGas():
print("Loading natural gas data from /data/commodities/natural_gas.csv")
prequery = "SELECT * FROM commodity WHERE commodityname = 'natural gas'"
cur.execute(prequery)
if cur.rowcount == 0: #insert natural gas into the commodity database if not present
print("Adding natural gas to the commodity table")
cur.execute("""INSERT INTO commodity (commodityname,unit_measure) VALUES (%s,%s)""",('natural gas','cents per bushel',))
prequery = "SELECT * FROM commodity_price WHERE commodityname = 'natural gas' AND day = %s AND month = %s AND year = %s"
with open('data/commodities/natural_gas.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
x = 0
for row in spamreader:
if x > 0:
date = row[0]
price = row[1]
dateparams = date.split("-")
year = dateparams[0]
month = dateparams[1]
day = dateparams[2]
cur.execute(prequery, (day,month,year))
print(date + " " + price)
# print(cur.rowcount)
# print(row)
if cur.rowcount == 0:
try:
cur.execute("""INSERT INTO commodity_price \
(commodityname,month,year,price,day) \
VALUES (%s, %s, %s, %s, %s)""", \
("natural gas",month,year,price,day,))
except Exception:
print("ERROR")
return ;
pass
x += 1
def main():
if(len(sys.argv) != 2):
print("Please execute this script as:")
print("python populate_commodity.py somecommodityname")
return
commodity = sys.argv[1].lower()
if commodity == "gold":
populateGold()
if commodity == "corn":
populateCorn()
if commodity == "wheat":
populateWheat()
if commodity == "coffee":
populateCoffee()
if commodity == "gas":
populateNaturalGas()
main() |
e259e4fa6b5a81078a94632e6f47d391c3f0fbb4 | chungleu/IntentTraining | /for_csv/process_dataframe.py | 7,022 | 3.890625 | 4 | """
Collection of useful methods to preprocess a dataframe.
- convert utterances to lowercase
- remove button clicks
- remove date/time utterances
- remove duplicate utterances
TODO:
- import list of buttons from central CSV
- get_df() function that checks whether the df is empty
"""
import pandas as pd
class process_dataframe(object):
def __init__(self, df, utterance_col='utterance', conf1_col='confidence1_0'):
self.df = df
self.utterance_col = utterance_col
self.utterance_lower_col = False
self.conf1_col = conf1_col
def utterance_col_to_lowercase(self):
"""
Creates new col with _lower appended to its name, which is a
lowercase version of the utterance col.
"""
self.utterance_lower_col = self.utterance_col + '_lower'
df = self.df.copy()
df[self.utterance_lower_col] = df[self.utterance_col].str.lower()
self.df = df
return df
def string_remove_chars(self, string_in, chars_to_remove):
"""
Remove characters in chars_to_remove from a string
"""
for char in chars_to_remove:
string_in = string_in.replace(char, '')
return string_in
def string_is_date(self, string_in):
"""
Returns whether a string can be parsed by the date parser
"""
from dateutil.parser import parse
try:
parse(string_in)
return True
except ValueError:
return False
except:
print('Warning: ' + str(string_in) + ' could not be parsed by the date parser')
return False
def remove_numeric_utterances(self, chars_toignore=[]):
"""
Drop utterances that are purely numeric.
First drops any chars from each utterance that are
in the list chars_toignore.
"""
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
# sort char list by longest first for easiest removal
chars_toignore.sort(key = len, reverse=True)
idx_todrop = []
for idx, utterance in self.df[self.utterance_lower_col].iteritems():
if str(utterance) != 'nan':
isdigit_stripped = self.string_remove_chars(utterance, chars_toignore)
isdigit = isdigit_stripped.isnumeric()
if isdigit:
idx_todrop.append(idx)
self.df = self.df.drop(index=idx_todrop)
def remove_date_utterances(self):
"""
Drop utterances that are purely dates.
"""
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
idx_todrop = []
for idx, utterance in self.df[self.utterance_lower_col].iteritems():
if str(utterance) != 'nan':
isdate = self.string_is_date(utterance)
if isdate:
idx_todrop.append(idx)
self.df = self.df.drop(index=idx_todrop)
def drop_utterances_containing(self, utterance_parts_to_remove, lower=True):
"""
Drop utterances that are in a list, e.g. button clicks.
By default this list should all be lowercase as it is
compared against lowercase utterances.
"""
# TODO: make generic for columns
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
if lower:
self.df = self.df[~self.df[self.utterance_lower_col].str.contains('|'.join(utterance_parts_to_remove))]
else:
self.df = self.df[~self.df[self.utterance_col].str.contains('|'.join(utterance_parts_to_remove))]
def get_utterances_containing_string(self, string_arg, lower=True):
"""
Return rows with utterances containing a string argument.
"""
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
if lower:
return self.df[self.df[self.utterance_lower_col].str.contains(string_arg)]
else:
return self.df[self.df[self.utterance_col].str.contains(string_arg)]
def drop_rows_with_column_value(self, column_name, toremove_list, lower=True, invert=False):
"""
Drop rows which contain a value from a list in a certain column.
By default this list is lowercase, and is compared against a
lowercase version of the column.
If the invert flag is used, this function will act as
keep_rows_with_column_value.
"""
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
if lower:
self.df = self.df[self.df[column_name].str.lower().isin(toremove_list) == invert]
else:
self.df = self.df[self.df[column_name].isin(toremove_list) == invert]
def drop_duplicate_utterances(self, duplicate_thresh=1):
"""
Drop utterances which are duplicated more than the number of times in specified by
duplicate_thresh.
"""
if not self.utterance_lower_col:
self.utterance_col_to_lowercase()
gb_utterance = self.df.groupby(self.utterance_lower_col).count()
idx_todrop_duplicates = gb_utterance[gb_utterance[self.utterance_col] > duplicate_thresh].index.tolist()
self.df = self.df[~self.df[self.utterance_lower_col].isin(idx_todrop_duplicates)]
def drop_confidence_greaterthan(self, confidence_thresh):
"""
Drop utterances with a confidence greater than the confidence threshold.
"""
self.df = self.df[self.df[self.conf1_col] <= confidence_thresh]
def check_df_not_empty(self):
"""
Raises a ValueError if len(df) == 0
"""
if self.df.shape[0] == 0:
raise ValueError('DataFrame empty (0 rows)')
def get_df(self):
"""
Checks whether the df is empty and returns it if it isn't.
"""
try:
self.check_df_not_empty()
return self.df.copy()
except:
print('Dataframe empty, so nothing returned.')
# TODO: Write unit tests for functions
if __name__ == '__main__':
import unittest
data_dict = {
"utterance": ["hello i am a string", "StRiNg WiTh UpPeRCaSe", "0892349482094", "14th feb 2018", "£24.59"]
}
df = pd.DataFrame.from_dict(data_dict)
def testLowercase(df):
process_df = process_dataframe(df, utterance_col='utterance')
process_df.utterance_col_to_lowercase()
data_dict_correct = {
"utterance": ["hello i am a string", "StRiNg WiTh UpPeRCaSe", "0892349482094", "14th feb 2018", "£24.59"],
"utterance_lower": ["hello i am a string", "string with uppercase", "0892349482094", "14th feb 2018", "£24.59"]
}
correct_df = pd.DataFrame.from_dict(data_dict_correct)
print( pd.DataFrame.equals(correct_df, process_df.df) )
testLowercase(df) |
06335233ba6be6e1011c55b6532f5f1bbf80a14f | topher2001/python_Misc | /regex.py | 95 | 3.8125 | 4 | import re
txt = "I have 21 Apples 1 banana"
x = re.findall("[0-9][0-9]", txt)
print(str(x))
|
8c072869f6aca912878d0cdd90fac66fa2e215a9 | lincappu/pycharmlearningproject | /函数模块库/string 模块.py | 307 | 3.890625 | 4 |
# 补充: str.format()
# 按位置:
print("{1} {0} {2}".format(1,2,3))
# 按名称参数
print('{first} {second} {three}'.format(first=1,second=2,three=3))
#按参数属性访问
c=3-5j
print('实数是{0.real}'.format(c))
# 按参数的项:
coor=(3,5)
print('x:{0[0]} Y:{0[1]}'.format(coor))
|
f63ca8fb02cb83cddd7128e4bba2463cc428e2b1 | wfeng1991/learnpy | /py/leetcode/48.py | 2,020 | 3.640625 | 4 | class Solution(object):
def rotate1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
# not in-place
length=len(matrix)
if length==0:
return []
res=[]
t=[]
cur=matrix[0]
for i in range(length):
for l in matrix:
t=[l[i]]+t
res.append(t)
t=[]
matrix = res
def rotate2(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
l=len(matrix)
clcles=l//2
pp=l-1
for i in range(clcles):
t=pp-i*2
for j in range(t):
p=matrix[i][i]
for k in range(i+1,l-i):
matrix[k-1][i]=matrix[k][i]
for k in range(i+1,l-i):
matrix[l-1-i][k-1]=matrix[l-1-i][k]
for k in range(l-i-1,i,-1):
matrix[k][l-1-i]=matrix[k-1][l-1-i]
for k in range(l-i-1,i,-1):
matrix[i][k]=matrix[i][k-1]
matrix[i][i+1]=p
# best
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
# \ flip
for i in xrange(n):
for j in xrange(i,n):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
# | flip
for i in xrange(n):
for j in xrange(n/2):
tmp = matrix[i][j]
matrix[i][j] = matrix[i][n-1-j]
matrix[i][n-1-j] = tmp
print(Solution().rotate([[2,29,20,26,16,28],[12,27,9,25,13,21],[32,33,32,2,28,14],[13,14,32,27,22,26],[33,1,20,7,21,7],[4,24,1,6,32,34]]))
|
d713a181dce59504c0dcda47ef95f18110f61d8b | shuvo14051/python-data-algo | /Problem-solving/URI/URI-1037.py | 326 | 3.78125 | 4 | N = float(input())
if ((N>=0.0) and (N<=25.0)):
print("Intervalo [0,25]")
elif((N>25.0) and (N<=50.0)):
print("Intervalo (25,50]")
elif((N>50.0) and (N<=75.0)):
print("Intervalo (50,75]")
elif((N>75.0) and (N<=100.0)):
print("Intervalo (75,100]")
elif((N<0.0) or (N>100.0)):
print("Fora de intervalo") |
1ef8575926412ce6a3ecabb70f03192ca95f53c2 | quocnguyen5/Co_So_Lap_Trinh_DUE_MIS3001_46K21.3 | /Chapter5/TEST/test.py | 901 | 3.53125 | 4 | # B = [1, 2, 3, 4.5]
# # print(len(L))
# # # for i in range(len(L)):
# # # print(L[i])
# # print(L.index(2))
# # L = []
# # n = int(input('n='))
# # for i in range(n):
# # L.append(input())
# # x = int(input('x='))
# # del(L[1:(len(L)-1)])
# # max = L[1]
# # for x in range(len(L)):
# # if L[x] > max:
# # max = L[x]
# # print(L)
# # print(max)
# print(B[1])
# # for i in range(len(B)):
# # while B[i] > B[i+1]:
# # B[i] = B[i+1]
# # B[i+1] = B[i]
# A = B.copy()
# print(A)
# names = ['an ', '”Nam”', ' “Binh”', '“Ngoc']
# x1 = names.pop(0)
# x2 = names.pop(-1)
# print(x1)
# print(x2)
# print(names)
# import copy
# numbers1 = [1,2,3,4,5]
# numbers2 = copy.copy(numbers1)
# print(numbers2)
# numbers3 = numbers1
# numbers3[2] = 6
# print(numbers3)
L = [1, 1, 2, 2, 3, 4, 4]
L = list(set(L))
print(L)
|
68cf0ba62359701983f229a15d65cf3ab20238b4 | oguzhanun/10_PythonProjects | /assignments/letterCounter.py | 178 | 3.59375 | 4 | sentence = input("please give me a string")
dict1 = dict()
for i in sentence :
if i in dict1.keys():
dict1[i]=dict1[i]+1
else :
dict1[i]=1
print(dict1) |
799c1b4a40eb2ba382c8543b4ed9d043d4da4e18 | suyashgautam44/Hacker-Rank-projects | /BalancingParenthesis.py | 984 | 4.15625 | 4 | #Balancing Parenthesis using stack
def compare_left_right(left, right):
if left == "(" and right == ")":
return True
elif left == "[" and right == "]":
return True
elif left == "{" and right == "}":
return True
else:
return False
# The second function is what actuallt takes a string as argument
# and uses principles of stack to evaluate if the string is balanced.
def pairing(s):
stack = []
for bracket in s:
if bracket in ["(", "[", "{"]:
stack.append(bracket)
else:
if len(stack) == 0:
return False
top = stack.pop()
if not compare_left_right(top, bracket):
return False
if len(stack) != 0:
return False
else:
return True
print pairing('({])')
print pairing('({[}])')
print pairing('({[]})')
print pairing('{[(])}')
print pairing('{{[[(())]]}}')
print pairing('()(){}{}')
|
c36494f13c61ca21cdb85eaba064a8e955d1e2ae | urishen/pythonHW | /Home_work1.py | 711 | 4 | 4 | string_var1 = input("Как Вас зовут?")
string_var2 = None
int_var1 = int(input("Сколько Вам лет?"))
int_var2 = int(input("Сколько лет вашему брату?"))
float_var = float(input("Какая у Вас температура?"))
bool_var = None
if int_var1 == int_var2:
string_var2 = "брат близнец"
elif int_var1 > int_var2:
bool_var = True
else:
bool_var = False
if bool_var == True:
string_var2 = "младший брат"
else:
string_var2 = "старший брат"
print(f"{string_var1}, Вам {int_var1} лет, у Вас есть {string_var2}.")
if float_var >= 37:
print(f"{float_var} Вероятно Вы заболели.") |
82b8362a6fbf16dd26ae95ddb448d6c9b9d2824d | HOZH/leetCode | /leetCodePython2023/1469.find-all-the-lonely-nodes.py | 972 | 3.65625 | 4 | #
# @lc app=leetcode id=1469 lang=python3
#
# [1469] Find All The Lonely Nodes
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:
self.ans = []
def helper(node,is_solo):
if is_solo:
self.ans.append(node.val)
has_left = True if node.left else False
has_right = True if node.right else False
if has_left and not has_right:
helper(node.left,True)
elif has_right and not has_left:
helper(node.right,True)
elif has_right and has_left:
helper(node.right,False)
helper(node.left,False)
helper(root,False)
return self.ans
# @lc code=end
|
85fe15c4068120a2776bf96defa8591e4df62be0 | yang4978/Hackerrank_for_Python | /Problem Solving/Algorithms/Sorting/20_lily's_homework.py | 1,975 | 3.671875 | 4 | #https://www.hackerrank.com/challenges/lilys-homework/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the lilysHomework function below.
def lilysHomework(arr):
# swap_incre = 0
# swap_decre = 0
# arr_incre_sort = sorted(arr)
# num_incre = [arr_incre_sort.index(i) for i in arr]
# num_decre = [len(arr)-1-i for i in num_incre]
# for i in range(len(num_incre)):
# if(num_incre[i]!=i):
# j = num_incre.index(i)
# temp = num_incre[i]
# num_incre[i] = i
# num_incre[j] = temp
# swap_incre += 1
# if(num_decre[i]!=i):
# j = num_decre.index(i)
# temp = num_decre[i]
# num_decre[i] = i
# num_decre[j] = temp
# swap_decre += 1
# print(num_decre)
#return min(swap_incre,swap_decre)
arr_reverse = arr[:]
len_arr = len(arr)
arr_dict = {}
arr_dict_reverse = {}
arr_sorted = sorted(arr)
arr_sorted_reverse = arr_sorted[::-1]
for i in range(len_arr):
arr_dict[arr[i]] = i
arr_dict_reverse[arr_reverse[i]] = i
result = 0
result_reverse = 0
for i in range(len_arr):
if(arr[i]!=arr_sorted[i]):
result +=1
arr_dict[arr[i]] = arr_dict[arr_sorted[i]]
arr[i],arr[arr_dict[arr[i]]] = arr_sorted[i],arr[i]
if(arr_reverse[i]!=arr_sorted_reverse[i]):
result_reverse +=1
arr_dict_reverse[arr_reverse[i]] = arr_dict_reverse[arr_sorted_reverse[i]]
arr_reverse[i],arr_reverse[arr_dict_reverse[arr_reverse[i]]] = arr_sorted_reverse[i],arr_reverse[i]
return min(result,result_reverse)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
ce4b77f41d6b536b0597872a99df70dca41476ed | avinash3699/NPTEL-The-Joy-of-Computing-using-Python | /Week 11/Programming Assignment 2 Word Sorting.py | 305 | 3.9375 | 4 | # Programming Assignment-2: word-sorting
'''
Question : Write a program that accepts a comma-separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them alphabetically.
'''
# Code
s=input().strip()
l=s.split(",")
print(*sorted(l),sep=",") |
afcb776c5750f4c37c97ed77e018b21b4ab99985 | godwinreigh/web-dev-things | /programming projects/python projects/tutorials2/8. Casting in python.py | 290 | 4.15625 | 4 | # casting means changing one data type, to another data type
# integer to float
x=1
a= float(x)
print (a)
# integer to string
print(str(x)) #you can set x to numbers #numbers can be string
#string to integer
print(int("34"))#words doesnt work
print(bool(0))#false
print(bool(1))#true
|
0d14ceb4fd8e0f27c4be41c54155d4639f149e18 | jutkko/learn | /python/mini-max-sum.py | 332 | 3.515625 | 4 | import unittest
def mini_sum(list):
return sum(sorted(list)[:-1])
def max_sum(list):
return sum(sorted(list)[1:])
class TestMiniMaxSum(unittest.TestCase):
def testExample(self):
self.assertEqual(mini_sum([1, 2, 3, 4, 5]), 10)
def testExample1(self):
self.assertEqual(max_sum([1, 2, 3, 4, 5]), 14)
|
f6f4521a58e3a7f796b83b24a45b0a95603bce7c | ganeshv1993/DataStructures-Algorithms | /Algorithms/Searching/LinearSearch.py | 491 | 3.765625 | 4 | #Conventional
def linear_search_1(arr, ele):
flag=False
for i in range (0, len(arr)):
if arr[i]==ele:
flag=True
print "Found in pos", i
if not flag:
print "Not found"
#The cool python way
def linear_search_2(arr, ele):
if ele in arr:
print "Found in pos", arr.index(ele)
else:
print "Not found"
arr=[1,2,3,4,5,6]
linear_search_1(arr, 4)
linear_search_2(arr, 4)
linear_search_1(arr, 8)
linear_search_2(arr, 8)
|
17e78e4c4ed1f14c200163364640d53ca4eb8996 | Jeremy277/exercise | /pytnon-month01/month01-class notes/day04-fb/exercise02-for&while.py | 597 | 3.640625 | 4 | #1.打印0123数字,累加0123,累加3579
sum_1 = 0
sum_2 = 0
for i in range(4):
print(i,end=' ')
sum_1 += i
print('累加:',sum_1)
for i in range(3,10,2):
print(i,end=' ')
sum_2 += i
print('累加:',sum_2)
for i in range(4,-1,-1):
print(i,end=' ')
#2.假设每张纸0.0001米,折纸10次 求厚度
thick_1 = 0.0001
thick_2 = 0.0001
for i in range(10):
thick_1 *= 2
print('\n对折10次后为%f米' % thick_1)
#3.折纸多少次为8848米
count = 0
while thick_2 < 8848:
count += 1
thick_2 *= 2
print('\n达到8848米需要对折%d次' % count)
|
c0c17e3717819a85d804bca205671a29f5a0e5e2 | hazelclement/python-programs | /graphs1.py | 875 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print ('x = %d, y = %d'%(ix, iy))
global coords
coords.append((ix, iy))
if len(coords) == 2:
fig.canvas.mpl_disconnect(cid)
return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)
#Here is a simple example that prints the location of the mouse click and which button was pressed:
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
cid = fig.canvas.mpl_connect('button_press_event', onclick) |
01898660a9a99487848edda625765ea602a6582f | vincentX3/Leetcode_practice | /easy/026RemoveDuplicatesfromSortedArray.py | 732 | 3.703125 | 4 | from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
detection={}
i,length=0,len(nums)
while i<length:
if nums[i] in detection:
nums.remove(nums[i])
length-=1
else:
detection[nums[i]] = 1
i+=1
return length
def removeDuplicates2(self, nums):
if not nums:
return 0
pointer = 0
for i in range(1, len(nums)):
if nums[i] != nums[pointer]:
pointer += 1
nums[pointer] = nums[i]
return pointer + 1
nums=[0,0,1,1,1,2,2,3,3,4]
print(Solution().removeDuplicates2(nums))
print(nums)
|
6f8dbf0fe066da73f3c2c02e901ab54ded85ef5b | jerrylance/LeetCode | /504.Base 7/504.Base 7.py | 866 | 3.65625 | 4 | # LeetCode Solution
# Zeyu Liu
# 2019.4.14
# 504.Base 7
from typing import List
# method 1 abs(),巧妙利用flag处理负数情况
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
s = ''
flag = ''
if num < 0:
flag = '-'
num = abs(num)
while num > 0:
s += str(num % 7)
num = num // 7
return flag + s[::-1]
# transfer method
solve = Solution()
print(solve.convertToBase7(100))
# method 2 recursive
class Solution:
def convertToBase7(self, num: int) -> str:
if num < 0:
return '-' + self.convertToBase7(-num)
if num < 7:
return str(num)
return self.convertToBase7(num // 7) + str(num % 7)
# transfer method
solve = Solution()
print(solve.convertToBase7(100)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.