blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
25d9bba08eb6b53c6ec5125f0f1386ebd3c375f8 | tsuji-tomonori/prog | /numer0n/items/double.py | 900 | 3.75 | 4 | from module import standard_numer0n as nm
def use(info,turn,digit=3):
while True:
idx = input(f"{info[not turn]['name']}:表示させたい桁を指定してください")
fin_flag, idx = check_idx(idx)
if fin_flag: break
else: print(idx)
print("{0}さんの[{1}]桁目の数値は[{2}]です".format(
info[turn]["name"],
idx,info[turn]["ans"][idx-1]))
value, eb = nm.call(info,turn)
print("{} -> {} : {} ({})".format(info[turn]["name"],
info[not turn]["name"],eb,value))
if nm.isfin(eb,digit):
return (True,turn)
else: return (False,turn)
def check_idx(idx):
if not idx.isdigit():
return (False,"整数値ではありません")
idx = int(idx)
if not (1 <= idx <= 3):
return (False,"範囲外の数値を入力しています")
return (True ,idx)
|
9fa0e009c15e00016bfae128e68515f6aaa87e5d | rohanyadav030/cp_practice | /is-digit-present.py | 865 | 4.1875 | 4 | # Python program to print the number which
# contain the digit d from 0 to n
# Returns true if d is present as digit
# in number x.
def isDigitPresent(x, d):
# Breal loop if d is present as digit
if (x > 0):
if (x % 10 == d):
return(True)
else:
return(False)
else:
return(False)
# function to display the values
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n+1):
# checking for digit
if (i == d or isDigitPresent(i, d)):
print(i,end=" ")
# Driver code
n = 20
d = 5
print("n is",n)
print("d is",d)
print("The number of values are")
printNumbers(n, d)
'''
******************* output **********************
n is 47
d is 7
The number of values are
7 17 27 37 47
n is 20
d is 5
The number of values are
5 15
'''
|
702ae99a588af50dc3eb3077d6752c61f341b309 | DmitriBabin/babin_homework | /factorial_sequence.py | 376 | 3.703125 | 4 | import math
import itertools as it
class Factorial:
class Factorialiter:
def __init__(self):
self.i = 1
self.z = 1
def __next__(self):
self.z *= self.i
self.i += 1
return self.z
def __iter__(self):
return Factorial.Factorialiter()
for w in it.islice(Factorial(), 10):
print(w)
|
590dce90d6867aac4436f0c675c0f7266086ee87 | DmitriBabin/babin_homework | /euclidian_algorithm.py | 876 | 3.609375 | 4 | import random as rd
import math
a_number = rd.randint(1, 100)
b_number = rd.randint(1, 100)
print('gcd(',a_number,',',b_number,')')
print('Значение, полученное встроенным алгоритмом = ', math.gcd(a_number,b_number))
def gcd(a_number,b_number):
if b_number == 0:
return a_number
else:
return gcd(b_number, a_number % b_number)
print('Значение, полученное встроенным алгоритмом = ', gcd(a_number,b_number))
def extended_gcd(a_number,b_number):
if a_number == 0:
return (0, 1)
else:
x_num , y_num = extended_gcd(b_number % a_number, a_number)
return ( y_num - (b_number // a_number) * x_num, x_num)
print(a_number, '*', extended_gcd(a_number,b_number)[0], '+', b_number,
'*', extended_gcd(a_number,b_number)[1], '=' , gcd(a_number,b_number))
|
2b125895636c4f44e67d61b346faf6f9e0ffebd5 | Andy245Liu/Timato | /screentimer.py | 3,807 | 3.5 | 4 | from datetime import datetime
import sqlite3
import sys
import time
import pyautogui
if sys.version_info[0] == 2:
import Tkinter
tkinter = Tkinter
else:
import tkinter
from PIL import Image, ImageTk
first = 0
first2 = 0
#python C:\Users\Ahmad\Desktop\disptest.py
conn = sqlite3.connect('Data.db')
cursor = conn.execute("SELECT Name, Type, Weighting, MentalEffort, Deadline, Duration, ScreenBlock, StartTime from data") # SQL DB Imported
Name = []
Type = []
Weight = []
Mental = []
Deadline = []
Duration = []
Block = []
StartTime = []
for row in cursor:
Name.append(row[0]) # STR
Type.append(row[1]) # STR
Weight.append(row[2]) #INT
Mental.append(row[3]) # INT
Deadline.append(row[4]) # STR
Duration.append(row[5]) # INT
Block.append(row[6]) # INT
StartTime.append(row[7]) # STR
# print "ID = ", row[0]
# print "NAME = ", row[1]
# print "ADDRESS = ", row[2]
# print "SALARY = ", row[3], "\n"
def findact(h, m, hour, minute, dur):
for i in range(len(h)):
timestart = h[i] * 60 + m[i]
timeend = timestart + dur[i]
if((hour*60 + minute) >= timestart and (hour*60 + minute) < timeend):
return i
return 1000
def checkassign(hour,minute, Deadline):
for i in range(len(Deadline)):
temp = Deadline[i].find(":")
temptime = int(Deadline[i][temp-2])*600 + int(Deadline[i][temp-1]) * 60 + int(Deadline[i][temp+1]) * 10 + int(Deadline[i][temp+2])
if(temptime - (hour*60+minute) <= 30 and temptime - (hour*60+minute) >= 0):
return True
return False
minlist = []
hourlist = []
dur = []
for i in range(len(StartTime)):
a = StartTime[i]
temp = a.find(":")
minlist.append(int(a[temp+1]) * 10 + int(a[temp+2]))
hourlist.append(int(a[temp-2]) * 10 + int(a[temp-1]))
dur.append(int(Duration[i]))
#INSIDE LOOP
while True:
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
temp = dt_string.find(":")
hour = 0
minute = 0
hour = int(dt_string[temp-2]) * 10 + int(dt_string[temp-1])
minute = int(dt_string[temp+1]) * 10 + int(dt_string[temp+2])
overall = hour*60 + minute
breaktimes = []
a = findact(hourlist, minlist, hour, minute, dur)
if (a!= 1000):
if(Block[a] == 1 and checkassign(hour, minute, Deadline) == False):
freq = int(100/Mental[a])
breakt = int(10/Mental[a])
sum = 0
x = 0
while(sum < dur[i]):
breaktimes.append((hourlist[a] * 60 + minlist[a]) + freq*(x+1) + breakt * x)
sum+=freq*(x+1) + breakt * x
x+=1
for k in range(len(breaktimes)):
if(breaktimes[k] <= overall and overall < breaktimes[k] + breakt):
if(first == 0):
pyautogui.keyDown('alt')
pyautogui.press('tab', presses=2)
pyautogui.keyUp('alt')
first += 1
else:
pyautogui.hotkey('alt', 'tab')
time.sleep(0.1)
pyautogui.hotkey('ctrl', 'shift', 'e')
time.sleep(60*breakt)
pyautogui.hotkey('shift', 'a')
break
time.sleep(60)
# for i in range(2):
# if(first == 0):
# pyautogui.keyDown('alt')
# pyautogui.press('tab', presses=2)
# pyautogui.keyUp('alt')
# first += 1
# else:
# pyautogui.hotkey('alt', 'tab')
# time.sleep(0.1)
# pyautogui.hotkey('ctrl', 'shift', 'e')
# time.sleep(10)
# pyautogui.hotkey('shift', 'a')
# time.sleep(10)
|
82a3d01659c41567c0dde03c3e14585503b96295 | tianwen0110/find-job | /target_offer/print_list_reverse.py | 632 | 4.0625 | 4 | class listnode(object):
def __init__(self, x=None):
self.val = x
self.next = None
class solution(object):
def reverse_list(self, first):
if first.val == None:
return -1
elif first.next == None:
return first.val
nextnode = first
l = []
while nextnode != None:
l.insert(0, nextnode.val)
nextnode = nextnode.next
return l
node1 = listnode(10)
node2 = listnode(11)
node3 = listnode(13)
node1.next = node2
node2.next = node3
singleNode = listnode(12)
test = listnode()
S = solution()
print(S.reverse_list(node1)) |
ffd5c6d21ea6dd7630628a0c00af7f7959c710c1 | tianwen0110/find-job | /target_offer/从上到下打印二叉树.py | 1,024 | 4 | 4 |
'''
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
'''
'''
相当于按层遍历, 中间需要队列做转存
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class solution(object):
def printF(self, tree):
if tree == None:
return None
list1 = []
list1.append(tree)
list2 = []
while list1 != []:
list2.append(list1[0].val)
if list1[0].left != None:
list1.append(list1[0].left)
if list1[0].right != None:
list1.append(list1[0].right)
list1.pop(0)
print(list2)
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
s = solution()
s.printF(pNode1) |
ac78fe36eec01c1077bb1b3f83a454912d917bf0 | tianwen0110/find-job | /target_offer/正则表达式匹配.py | 1,364 | 3.703125 | 4 |
'''
请实现一个函数用来匹配包括'.'和'*'的正则表达式。
模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。
在本题中,匹配是指字符串的所有字符匹配整个模式。
例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
'''
class solution(object):
def match(self, string, pattern):
if type(string)!=str or type(pattern)!=str:
return None
i = 0
j = 0
length = len(string)
while i != length:
if j>=len(pattern):
return False
if string[i]==pattern[j]:
i = i+1
j = j+1
elif pattern[j]=='*':
if string[i]==pattern[j+1]:
i = i+1
j = j+2
elif string[i]==string[i-1]:
i = i+1
else:
return False
elif pattern[j] == '.':
i = i+1
j = j+1
elif pattern[j+1]=='*':
j = j+2
if j ==len(pattern):
return True
else:
return False
s = solution()
a = 'a.a'
b = 'ab*ac*a'
k = 'aaa'
c = 'aa.a'
d = 'ab*a'
print(s.match(k,d))
|
0855187a0284322baae4436ab56ffef37c7aed84 | tianwen0110/find-job | /target_offer/search_in_2dArray.py | 1,533 | 3.765625 | 4 | '''
在一个二维数组中,每一行都按照从左到右递增的顺序排序
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
class Solution(object):
def find(self, array, target):
if type(target) != int and type(target) != float:
return False
elif array == []:
return False
elif type(array[0][0]) != int and type(array[0][0]) != float:
return False
m = len(array)
n = len(array[0])
if target < array[0][0] or target > array[m-1][n-1]:
return False
i = 0
j = n - 1
while i < n and j >= 0:
if array[i][j] < target:
i = i + 1
elif array[i][j] == target:
return True
else:
j = j - 1
return False
array = [[1, 2, 8, 9],
[2, 4, 9, 12],
[4, 7, 10, 13],
[6, 8, 11, 15]]
array2 = []
array3 = [['a', 'b', 'c'],
['b', 'c', 'd']]
array4 = [[62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80],[63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81],[64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82],[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83],[66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],[67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85]]
findtarget = Solution()
print(findtarget.find(array4, 10))
|
7e349fc201f85a485b7a4da089951ddfaa61b2aa | lxndrblz/DHBW-Programmierung | /Semester_1/Probeklausur.py | 1,221 | 3.953125 | 4 | #encoding=utf-8
'''
99 Bottles of Beer
'''
bottles = 99
while bottles > 1:
print(str(bottles) + " bottles of beer on the wall," + str(bottles) + " bottles of beer. If one of those bottles should happen to fall")
bottles -= 1
print("One (last) bottle of beer on the wall,")
print("One (last) bottle of beer.")
print("Take it down, pass it around,")
print("No (more) bottles of beer on the wall.")
'''
Check Palindrom
'''
p = "regallager"
def check_palindrom(s):
return s == s[::-1]
print(check_palindrom(p))
# Sollte True ergeben
'''
Palindrom Wert
Erweitern Sie Ihr Programm um die Funktion palindrom_wert, die eine float-Zahl zurückliefert
'''
p = "regallager"
def palindrom_wert(s):
vokale = "aeiou"
anzahl_konsonant = 0.0
for c in s:
if c not in vokale:
anzahl_konsonant += 1
return float(anzahl_konsonant / len(s))
print(palindrom_wert(p))
# Sollte 0.6 ergeben
'''
Check palindrom Satz
'''
p = "sei fein, nie fies"
def check_palindrom_satz(s):
#Alle Satzzeichen entfernen
pattern = "!@#$%^&*()[]{};:,./<>?\|`~-=_+ "
for c in pattern:
s = s.replace(c, "")
return bool(s == s[::-1])
print(check_palindrom_satz(p))
# Sollte True sein
|
b6b91917c0e09643e6138b40f20e32eb8a088706 | lxndrblz/DHBW-Programmierung | /Semester_1/Aufgaben Moodle/Hash.py | 1,656 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import string
import random
import itertools
from random import randint
def hashthis(s):
h = 0
base = 1
for char in s:
h += ord(char) * base
base *= 26
return h
# Funktion generiert Passwort mittels eines kartesischen Produktes aus dem Buchstabenarray
def bruteforcelinear(h):
# Buchstaben in array umwandeln
buchstaben = string.ascii_lowercase
buchstabenarray = []
for char in buchstaben:
buchstabenarray.append(char)
password = ''
cartesianproduct = []
# Anzahl an Stellen
maxstellen = 5
# ArgumentListe für cartesisches Produkt erzeugen
for i in range(0, maxstellen):
cartesianproduct.append(buchstabenarray)
for pwcombinations in itertools.product(*cartesianproduct):
# Jede Kombination prüfen
for c in pwcombinations:
password += str(c)
if h == hashthis(password):
return password
password = ''
# Generiert Passwort aus zufälligen Kombinationen
def bruteforce(h):
buchstaben = string.ascii_lowercase
while True:
password = ''
# Zufaellige Länge
for i in range(randint(0, 10)):
# Zufaellige Buchstaben
c = random.choice(buchstaben)
password = password + c
if h == hashthis(password):
break
return password
hashwert = hashthis(str(raw_input("Ihr Passwort: ")))
print "Hash Wert: " + str(hashwert)
print "Passwort war (zufall) verfahren " + str(bruteforce(hashwert))
print "Passwort war (linear) verfahren " + str(bruteforcelinear(hashwert))
|
ffa05f9466c855d31dc19f6b1bf18f4d79a4802b | lxndrblz/DHBW-Programmierung | /Semester_2/ObjektOrientierung/Simulation/SimHuman/matches.py | 1,525 | 3.546875 | 4 | import names
import random
from SimHuman.men import men
from SimHuman.women import women
class matches(men, women):
def __init__(self, match_men, match_women):
self.__men = match_men
self.__women = match_women
self.__kids = []
#Ability to compare couples
def __eq__(self, second):
if self.__men == second.__men and self.__women == second.__women:
return True
else:
return False
def print(self):
print("Couple: " + self.__men.get_name() +"+"+ self.__women.get_name())
def print_kids(self):
for kid in self.__kids:
print ("\t" + kid.get_name())
def make_kids(self):
#Condition for getting kids in General
if (len(self.__kids) < 3) and 18 < self.__men.get_age() < 50 and 18 < self.__women.get_age() < 50 and self.__women.get_kids() < 4:
newkids = []
#Probablity to get kids:
if random.random()*len(self.__kids) < 0.2:
#Twins or just a single kid
for i in range(random.randint(1,3)):
if random.randint(0,2) == 0:
newkids.append(men(names.get_first_name(gender='male'), 0))
else:
newkids.append(women(names.get_first_name(gender='female'), 0,0))
self.__women.increase_baby_counter()
self.__kids.append(newkids)
return newkids
def get_kids(self):
return self.__kids |
ca9aed93c5422314ee6882a20224ea361401a82d | lxndrblz/DHBW-Programmierung | /Semester_1/Aufgaben Moodle/guess.py | 443 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
AnzahlVersuche = 1
ZufallsWert = randint(1,20)
print "Bitte eine Zahl zwischen 1 und 20 auswählen!"
guess = int(input("Ihr Tip: "))
while guess != ZufallsWert:
AnzahlVersuche += 1
if(guess>ZufallsWert):
print "Zahl ist kleiner"
else:
print "Zahl ist größer"
guess = int(input("Ihr neuer Tip: "))
print "Versuche: " + str(AnzahlVersuche) |
18bde0bbb7b8f371cbbab5d3a73310f823fa3570 | amrutha1352/4040 | /regularpolygon.py | 280 | 4.28125 | 4 | In [46]:
X= float(input("Enter the length of any side: "))
Y= int(input("Enter the number of sides in the regular polygon: "))
import math
numerator= math.pow(X,2)*Y
denominator= 4*(math.tan(math.pi/Y))
area= numerator/denominator
print("The area of the regular polygon is:",area) |
34e739ba20d456fad59dbc99ebab0d74be0830d0 | folivetti/Category4Programmers | /Monad/monadsLista.py | 393 | 3.5 | 4 | def bind(xs, k):
return (y for x in xs for y in k(x))
def geralista(x):
return [2*x]
def triples(n):
return ( (x,y,z) for z in range(1, n+1)
for x in range(1, z+1)
for y in range(x, z+1)
if (x**2 + y**2 == z**2))
for t in triples(10):
print(t)
print(list(bind([1,2,3], geralista)))
|
34c467f6bcb628d403321d30b29644d35af003f3 | jonesm1663/cti110 | /cti 110/P3HW2.py | 543 | 4.28125 | 4 | # CTI-110
# P3HW2 - Shipping Charges
# Michael Jones
# 12/2/18
#write a program tha asks the user to enter the weight of a package
#then display shipping charges
weightofpackage = int(input("Please enter the weight of the package:"))
if weightofpackage<= 2:
shippingcharges = 1.50
elif weightofpackage < 7:
shippingcharges = 3.00
elif weightofpackage < 11:
shippingcharges = 4.00
else:shippingcharges = 4.75
print("package weighs"+str(weightofpackage)+", you pay"+ \
format(shippingcharges,",.2f"))
|
619ebd59a6875ca0c6feb9a2074ba5412215c4ae | jonesm1663/cti110 | /cti 110/P3HW1.py | 820 | 4.4375 | 4 | # CTI-110
# P3HW1 - Roman Numerals
# Michael Jones
# 12/2/18
#Write a program that prompts the user to enter a number within the range of 1-10
#The program should display the Roman numeral version of that number.
#If the number is outside the range of 1-10, the program should display as error message.
userNumber = int(input("Please enter a number"))
if userNumber ==1:
print("1")
elif userNumber ==2:
print("II")
elif userNumber ==3:
print("III")
elif userNumber ==4:
print("IV")
elif userNumber ==5:
print("V")
elif userNumber ==6:
print("VI")
elif userNumber ==7:
print("VII")
elif userNumber ==8:
print("VIII")
elif userNumber ==9:
print("IX")
elif userNumber ==10:
print("X")
else:
print("Error: Please enter a number between 1 and 10.")
|
dba3fcfadbf30efd044878c01b985dfe8e2e9f91 | vishwesh5/HackerRank_Python | /Basic_Data_Types/lists.py | 602 | 3.890625 | 4 | # lists.py
# Link: https://www.hackerrank.com/challenges/python-lists
def carryOp(cmd, A):
cmd=cmd.strip().split(' ')
if cmd[0]=="insert":
A.insert(int(cmd[1]),int(cmd[2]))
elif cmd[0]=="print":
print(A)
elif cmd[0]=="remove":
A.remove(int(cmd[1]))
elif cmd[0]=="append":
A.append(int(cmd[1]))
elif cmd[0]=="sort":
A.sort()
elif cmd[0]=="pop":
A.pop()
elif cmd[0]=="reverse":
A.reverse()
return A
if __name__ == '__main__':
N = int(input())
A = []
for i in range(N):
A=carryOp(input(),A)
|
c60a5ffaf75adcbf8d8959e3b544c390a412b4bc | ryan-hill83/updated-calc | /input.py | 840 | 4.03125 | 4 | from calculator import addition, subtraction, multipication, division
while True:
try:
first = int(input("First Number: "))
operand = input("Would you like to +, -, * or / ? ")
second = int(input("Second Number: "))
if operand == "+":
addition(first, second)
break
elif operand == "-":
subtraction(first, second)
break
elif operand == "*":
multipication(first, second)
break
elif operand == "/":
division(first, second)
break
else:
print("Please enter a valid operand.")
except ValueError:
print("Please enter numbers only!")
quit = input("To quit the program, please press q then hit enter.").lower()
if quit == "q":
import sys
sys.exit(0)
|
ca7dfd42e32443a52c05e2d443398136b2311243 | fjesser/datascience | /syntax/m_see_data.py | 5,392 | 3.578125 | 4 | import datetime as dt
import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
def export_dataset_description_to_csv(dataset):
'''
Function takes description of dataset and saves it as csv
Input:
dataset: pd.dataFrame object
Returns:
nothing, saves csv-file
'''
described_data = dataset.describe(include="all")
described_data.to_csv("../output/description.csv")
def print_occurence_of_object_types(dataset):
'''
Function prints how often each manifestation of non-numeric columns appears
Input:
dataset: pd.dataFrame object
Returns:
nothing, prints to console
'''
for variable in dataset.columns:
if dataset[variable].dtype == 'object':
print(dataset[variable].value_counts())
def fix_meal_manifestations(dataset):
'''
Function adds undefined meals to SC meals (according to kaggle, Undefined/SC - no meal)
Input:
dataset: pd.dataFrame object
Returns:
dataset: pd.dataFrame object in which SC = Undefined + SC from input
'''
dataset['meal'] = dataset['meal'].replace(to_replace="Undefined", value="SC")
return(dataset)
def convert_date_per_row(row):
'''
Function creates a date object by reading the year, month and date of arrival per row
Input:
dataset: a row of the hotel dataset as pd.Series
Returns:
dataset: a date object including the arrival date
'''
year = row['arrival_date_year']
month = row['arrival_date_month']
day = row['arrival_date_day_of_month']
month = month.capitalize()
months_string = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
months_numeric = [i for i in range(1, 13)]
months = dict(zip(months_string, months_numeric))
numeric_date = date(year, months[month], day)
return(numeric_date)
''' My try to get the arrival_date as a date object. Uses apply and is thus really slow (seconds).
For optimization, read this link: https://stackoverflow.com/questions/52673285/performance-of-pandas-apply-vs-np-vectorize-to-create-new-column-from-existing-c
hotel_data['arrival_date'] = hotel_data.apply(convert_date, axis=1)
'''
def convert_date_in_dataset(dataset):
'''
This function is taken from Felix; my try is commented out
'''
dataset['arrival_date'] = ((dataset.arrival_date_year.astype(str) +
dataset.arrival_date_month +
dataset.arrival_date_day_of_month.astype(str)
)
.pipe(pd.to_datetime, format="%Y%B%d")
)
# dataset['arrival_date'] = dataset.apply(convert_date_per_row, axis=1)
return(dataset)
# hotel_data['arrival_date'] = hotel_data.apply(convert_date, axis=1, args=(
# hotel_data['arrival_date_year'], hotel_data['arrival_date_month'], hotel_data['arrival_date_day_of_month']))
def create_days_spent_column(dataset):
'''
Both reservation_status_date and arrival_date have to be dateobjects!
TODO: Write a unit test for it and convert if needed
'''
dataset['reservation_status_date'] = pd.to_datetime(dataset['reservation_status_date'])
dataset['days_spent'] = np.where(dataset['reservation_status'] == 'Check-Out',
(dataset['reservation_status_date'] - dataset['arrival_date']).dt.days, np.nan)
return(dataset)
# hotel_data['arrival_date'] = pd.to_datetime(hotel_data['arrival_date'])
def create_cost_column(dataset):
'''
Create a cost value that is the average daily rate times the total days days_spent
'''
dataset['cost'] = np.where(dataset['reservation_status'] == 'Check-Out',
dataset['adr'] * dataset['days_spent'], dataset['adr'])
return(dataset)
def set_noshows_to_na(dataset):
'''
Set occurences of "No-Show" in reservation_status column to NA
'''
dataset['reservation_status'] = np.where(dataset['reservation_status'] == 'No-Show', np.nan, dataset['reservation_status'])
return(dataset)
def get_final_dataset():
'''
Load the hotel dataset and prepare it for plotting
Input: nothing
Returns: pd.dataFrame object that contains the hotel data in tidy format and
with new columns for the arrival_date, total days spent and cost for the stay
Unnecessary columns are deleted
'''
# Load hotel data set from input folder
dataset = pd.read_csv("../input/hotel_bookings.csv")
# Add new columns
dataset = convert_date_in_dataset(dataset)
dataset = create_days_spent_column(dataset)
dataset = create_cost_column(dataset)
dataset = fix_meal_manifestations(dataset)
dataset = set_noshows_to_na(dataset)
# Delete now Unnecessary columns
dataset.drop(['arrival_date_year', 'arrival_date_month',
'arrival_date_day_of_month', 'adr', 'reservation_status_date'], axis=1)
return(dataset)
def write_final_dataset(dataset):
'''
Create a csv-file with the final dataset, that was curated
'''
dataset.to_csv("../input/hotel_bookings_mh.csv")
if __name__ == '__main__':
hotel_data = get_final_dataset()
write_final_dataset(hotel_data)
|
3e25c1171d4f8d10702ccee6660760d06ff1153a | manabled/01-Hello-Class | /02 guess.py | 1,085 | 4.0625 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin
import sys
import random
assert sys.version_info >= (3,4), "This script requires at least Python 3.4"
guessesTaken = 0
maxGuesses = 5
numRange = 30
print("Welcome to Guess the Number")
print("I'm thinking of a number between 1 and 30")
print("You have 5 attempts to guess the correct number")
number = random.randint(1,numRange)
for guessesTaken in range(maxGuesses):
guess = input('Guess the number: ')
try:
guess = int(guess)
if guess < number:
print("close, but too low")
if guess < number - 5:
print("too low")
if guess > number:
print("close, but too high")
if guess > number + 5:
print("too high")
if guess == number:
break
except ValueError:
print("please enter a valid integer")
if guess == number:
guessesTaken = str(guessesTaken + 1)
print('Well done, you guessed the number in '+ guessesTaken +' attempts')
if guess != number:
number = str(number)
print('You are out of attempts. The number I was thinking of was ' + number + '.')
|
812198bdc5e9bdb1f745f2a0196ee9b8d4f7029d | rlaqhdwns/django1 | /django1/src/files/files/2019/02/09/a1.py | 1,442 | 3.5 | 4 | '''
def defaultfun(a,b,c,d,e,f=20,g=10):
pass
def func(a=5,b=10,*args, **kwarges):
pass
def print_info(**kwarges):#딕셔너리 타입
print(kwarges)
def sum(*args):#튜플 타입
print (args)
isum = 0
for i in args:
isum += i
return isum
print(sum())
print(sum(10,20,30,40,55,123,1255,))
a=[1,2,3,4,5,6,7,8,]
print(sum(*a))
print_info(name='아무개', age=99)
diction={'name':'홍길동','age':28}
print_info(**diction)
def add(a,b):
return a+b
def dec(a,b):
return b-a
diction={'a':5, 'b':100}
print('add()', add(**diction))
print('dec()', dec(**diction))
'''
#클래스 : 변수 + 함수 묶음
#클래스를 통해서 객체를 생성할 수 있음
#객체는 독립적인 데이터를 가지고 있어서 객체들간에 충돌이 일어나지 않는다.
class Cookie():
pass #이 부분이 미완성일지언정 계속 진행 시킬 수 있다.
#객체생성 : 클래스이름()
a = Cookie()
b = Cookie()
print('a에 저장된 쿠키객체 : ', a)
print('b에 저장된 쿠키객체 : ', b)
#__name__ 변수의 값으로 해당파일이 실행된건지 임포트에 의해 실행된건지 확인할수 있다.
if __name__ == '__main__' : #테스트용 코드를 분리할 수 있음
a = Family()
b = Family()
print(a.lastname, b.lastname)
Family.lastname = "이" #클래스.클래스변수 = 값 >
|
677ce91ae856a4c1d6135c7a48327fc47bc41f05 | derejmi/Algorithm-questions-python | /valid_parenthesis.py | 1,062 | 3.796875 | 4 | class Solution:
def isValid(self, s: str) -> bool:
#have a hashtable which has the opening parenthesis as keys and the closing as values
#loop over the string
#if string in ht - add opening p to stack
#else compare string to the last parenthesis in the stack (pop off the stack) - i.e. if ht[lp] == str:
#if they are not equal return false
#after the loop check if the stack still has a length if it does - return False
#return True
hashtable = {"{":"}","[":"]","(":")"}
stack = []
for str in s:
if str in hashtable:
stack.append(str)
else:
if len(stack) > 0:
open = stack.pop()
if hashtable[open] != str:
return False
else:
return False
if len(stack) > 0:
return False
return True
|
6a569d1796355a0393f3e4f9af40644d8d50acb1 | Linshengyi-William/CS362-InClassActWeek7 | /unittest/test_palindrome.py | 696 | 3.984375 | 4 |
import unittest
import palindrome
print("Please enter a string.")
inp = input("String is: ")
class TestCase(unittest.TestCase):
def test_inputType(self):
self.assertEqual(type(inp),type("string"))
def test_returnType(self):
result = palindrome.isPalindrome(inp)
self.assertEqual(type(result),type(True))
def test_correctResult(self):
result = palindrome.isPalindrome(inp)
for i in range(0,len(inp)):
if inp[i] != inp[len(inp)-i-1]:
correct_result = False
break
correct_result = True
self.assertEqual(result,correct_result)
if __name__ == '__main__':unittest.main()
|
818ad247228ec2770d9d7c77e604cf6a2259a2d5 | Tanya-2000/CYSEC-GRP-2- | /PYTHON ASSIGNMENT 2/QUES-5.py | 262 | 3.859375 | 4 | def has_33(nums):
for x in range(0,len(nums)):
if nums[x] ==[3] and nums[x+1]==[3]:
return True
else:
return False
print(has_33([1, 3, 3]) )
print(has_33([1, 3, 1, 3]))
print(has_33([3, 1, 3])) |
521215542619ce7e49fe00e8617227d1a73401bc | AkshayLavhagale/Pylint_Coverage | /fixed_triangle.py | 1,321 | 4.0625 | 4 | """ Name - Akshay Lavhagale
HW 01: Testing triangle classification
The function returns a string that specifies whether the triangle is scalene,
isosceles, or equilateral, and whether it is a right triangle as well. """
def classify_triangle(side_1, side_2, side_3):
"""Triangle classification method"""
try:
side_1 = float(side_1)
side_2 = float(side_2)
side_3 = float(side_3)
except ValueError:
raise ValueError("The input value is not number")
else:
[side_1, side_2, side_3] = sorted([side_1, side_2, side_3])
if (side_1 + side_2 < side_3 and side_1 + side_3 < side_2 and side_2 + side_3 < side_1) or (
side_1 or side_2 or side_3) <= 0:
return "This is not a triangle"
else:
if round(((side_1 ** 2) + (side_2 ** 2)), 2) == round((side_3 ** 2), 2):
if side_1 == side_2 or side_2 == side_3 or side_3 == side_1:
return 'Right and Isosceles Triangle'
else:
return 'Right and Scalene Triangle'
elif side_1 == side_2 == side_3:
return "Equilateral"
if side_1 == side_2 or side_1 == side_3 or side_2 == side_3:
return "Isosceles"
else:
return "Scalene"
|
3818d7844a22ff4d6587b5d50b55ee99a9b2a724 | MaryHak/Machine-Learning-course | /random forest/logistic_regression.py | 1,945 | 3.765625 | 4 | """
Implementation of logistic regression
"""
import numpy as np
def sigmoid(s):
"""
sigmoid(s) = 1 / (1 + e^(-s))
"""
return 1 / (1 + np.exp(-s))
def normalize(X):
"""
This function normalizes X by dividing each column by its mean
"""
norm_X = np.ones(X.shape[0])
feature_means = [np.mean(norm_X)]
for elem in X.T[1:]:
feature_means.append(np.mean(elem))
elem = elem / np.mean(elem)
norm_X = np.column_stack((norm_X, elem))
return norm_X, feature_means
def gradient_descent(X, Y, epsilon=1e-8, l=1, step_size=1e-4, max_steps=1000):
"""
Implement gradient descent using full value of the gradient.
:param X: data matrix (2 dimensional np.array)
:param Y: response variables (1 dimensional np.array)
:param l: regularization parameter lambda
:param epsilon: approximation strength
:param max_steps: maximum number of iterations before algorithm will
terminate.
:return: value of beta (1 dimensional np.array)
"""
beta = np.zeros(X.shape[1])
X, feature_means = normalize(X)
for _ in range(max_steps):
res = []
for j in range(1, X.shape[1]):
S = 0
for i in range(X.shape[0]):
temp = sigmoid(X[i].dot(beta)) - Y[i]
S = S + temp*X[i, j]
res.append((S[0] + (l / feature_means[j]**2)*beta[j])/(X.shape[0]))
res = np.array(res)
res0 = 0
S = 0
for i in range(X.shape[0]):
temp = sigmoid(X[i].dot(beta)) - Y[i]
S = S + temp*X[i, 0]
res0 = S[0] /(X.shape[0])
new_beta_zero = beta[0] - step_size * res0
new_beta = np.array([new_beta_zero, *(beta[1:] - step_size * res)])
if sum((beta - new_beta)**2) < (sum(beta**2) * epsilon):
return new_beta, np.array(feature_means)
beta = new_beta
return beta, np.array(feature_means)
|
8b11a247b8f6e9ed329e29c7bee289db888e09b7 | JustinLaureano/nfl-stats | /Notes.py | 1,415 | 3.6875 | 4 | """
collect all players and stats
step 1: collect raw data and save it
get schedule
get game id
get game data
loop through range
save all data collected in a file i.e. player_stats_17.py
collect all stats in file
dict or class
class DataToDict():
def __init(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
class Player():
def __init(self, playerid, name, team):
self.playerid = playerid
self.name = name
self.team = team
ex dict:
player_dict = {}
def collect stats(load file)
player_dict[name] = item[name]
home or away
abbr
score
stats
defense
ast
ffum
int
name
sk
tkl
fumbles
kicking
kickret
passing
att
comp
ints
name
tds
twopta
twoptm
yds
punting
puntret
receiving
long
lngtd
name
rec
tds
twopta
twoptm
yds
rushing
att
lng
tngtd
name
tds
twopta
twoptm
yds
team
load stats
loop, add stats to dict
"""
|
06aec43fb274b37e7e5d8d92809c3d45c8912adf | Mandyp-ool/Lesson2 | /ex3.py | 1,434 | 4.09375 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить, к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и dict.
season_list = ['зима', 'весна', 'лето', 'осень']
season_dict = {0:'зима', 1:'весна', 2:'лето', 3:'осень'}
month = int(input("Введите месяц в виде целого числа от 1 до 12: "))
if month == 1 or month == 2 or month == 12:
print("Месяц относится к времеи года -", season_list[0])
print("Месяц относится к времеи года -", season_dict.get(0))
elif month == 3 or month == 4 or month == 5:
print("Месяц относится к времеи года -", season_list[1])
print("Месяц относится к времеи года -", season_dict.get(1))
elif month == 6 or month == 7 or month == 8:
print("Месяц относится к времеи года -", season_list[2])
print("Месяц относится к времеи года -", season_dict.get(2))
elif month == 9 or month == 10 or month == 11:
print("Месяц относится к времеи года -", season_list[3])
print("Месяц относится к времеи года -", season_dict.get(3))
|
2afd83f3ea59d217f622b7abdfbfce2055639b38 | ucabtyi/playground | /py/b_tree.py | 5,541 | 3.890625 | 4 | import sys
class Node:
def __init__(self, value, l=None, r=None):
self.value = value
self.l = l
self.r = r
def __str__(self):
s = "value: " + str(self.value)
if self.l:
s += " L: %s" % str(self.l.value)
else:
s += " L: None"
if self.r:
s += " R: %s" % str(self.r.value)
else:
s += " R: None"
# return str(self.value)
return s
class BTree:
def __init__(self):
self.root = None
def __repr__(self):
def _repr(node):
if node:
print str(node)
print "goto L"
_repr(node.l)
print "search result: %s" % str(node)
print "goto R"
_repr(node.r)
if self.root:
_repr(self.root)
else:
print None
def _left(self, node_value, new_value):
return new_value < node_value
def _right(self, node_value, new_value):
return new_value > node_value
def add_v(self, value):
def _add_v(node, value):
if value == node.value:
print "equals..."
return
elif self._left(node.value, value):
if node.l:
_add_v(node.l, value)
else:
node.l = Node(value)
else:
if node.r:
_add_v(node.r, value)
else:
node.r = Node(value)
if self.root is None:
self.root = Node(value)
else:
_add_v(self.root, value)
def find_v(self, value):
def _find_v(node, value):
if value == node.value:
print "found..."
return node
elif self._left(node.value, value):
if node.l:
_find_v(node.l, value)
else:
print "not found..."
return None
else:
if node.r:
_find_v(node.r, value)
else:
print "not found..."
return None
if self.root:
_find_v(self.root, value)
else:
print "not found..."
return None
def print_t(self):
thislevel = [self.root]
while thislevel:
nextlevel = list()
for n in thislevel:
print n.value,
if n.l: nextlevel.append(n.l)
if n.r: nextlevel.append(n.r)
print
thislevel = nextlevel
def revert(self):
def _revert(node):
if node:
node.l, node.r = _revert(node.r), _revert(node.l)
return node
if self.root:
_revert(self.root)
def max_sum_l2l(self):
def max_sum_path(node, opt):
if node is None:
return 0
l_sum = max_sum_path(node.l, opt)
r_sum = max_sum_path(node.r, opt)
if node.l and node.r:
# important -- result only valid for a node contains both children
# otherwise no leaf to leaf
opt[0] = max(opt[0], l_sum+r_sum+node.value)
print "current max: " + str(opt)
return max(l_sum, r_sum) + node.value
return node.value + l_sum + r_sum
opt = [-sys.maxint-1]
max_sum_path(self.root, opt)
print "result: " + str(opt)
def max_sum_n2n(self):
def max_sum_path(node, opt):
if node is None:
return 0
l_sum = max_sum_path(node.l, opt)
r_sum = max_sum_path(node.r, opt)
# 4 situations -- node only, node + left max, node + right max, node + both max(go through)
opt[0] = max(opt[0], node.value, node.value+l_sum, node.value+r_sum, node.value+l_sum+r_sum)
if node.l and node.r:
# max path sum -- can only count one side
return max(max(l_sum, r_sum) + node.value, node.value)
else:
return max(node.value + l_sum + r_sum, node.value)
opt = [-sys.maxint-1]
max_sum_path(self.root, opt)
print "result: " + str(opt)
def main(args):
tree = BTree()
# tree.add_v(5)
# tree.add_v(9)
# tree.add_v(6)
# tree.add_v(7)
# tree.add_v(4)
# tree.add_v(3)
# tree.add_v(1)
# tree.add_v(8)
# tree.add_v(11)
# tree.add_v(10)
tree.root = Node(10)
tree.root.l = Node(-1)
tree.root.r = Node(-2)
# tree.root.l = Node(5)
# tree.root.r = Node(6)
# tree.root.l.l = Node(-8)
# tree.root.l.r = Node(1)
# tree.root.l.l.l = Node(2)
# tree.root.l.l.r = Node(6)
# tree.root.r.l = Node(3)
# tree.root.r.r = Node(9)
# tree.root.r.r.r= Node(0)
# tree.root.r.r.r.l = Node(4)
# tree.root.r.r.r.r = Node(-1)
# tree.root.r.r.r.r.l = Node(10)
# tree.root.l = Node(2)
# tree.root.r = Node(10);
# tree.root.l.l = Node(20);
# tree.root.l.r = Node(1);
# tree.root.r.r = Node(-25);
# tree.root.r.r.l = Node(3);
# tree.root.r.r.r = Node(4);
# print tree.root
# print str(tree.__repr__())
tree.print_t()
# tree.revert()
print "#####"
# tree.print_t()
# tree.find_v(111)
# tree.max_sum_l2l()
tree.max_sum_n2n()
if __name__ == "__main__":
main(sys.argv[1:])
|
bfb650ee9eb5e44a26f2a114ee7810e388c0dccc | FlyingPumba/algo3 | /hanoi.py | 1,828 | 3.8125 | 4 | #!/usr/bin/env python
import sys
import os
import time
if len(sys.argv) > 2:
print "Too many arguments"
sys.exit()
elif len(sys.argv) == 2:
n = int(sys.argv[1])
else:
print "Too few arguments"
sys.exit()
# helper functions
def display():
os.system('clear')
print "T1: ", list(reversed(towers[0]))
print "T2: ", list(reversed(towers[1]))
print "T3: ", list(reversed(towers[2]))
def attemptMove(i):
destination = []
if len(towers[i]) == 0:
return destination
for j in xrange(3):
if abs(j-i) == 1 and (len(towers[j]) == 0 or towers[i][0] < towers[j][0]):
destination.append(j)
return destination
# initialize
towers = [[],[],[]]
for i in xrange(1,n+1):
towers[0].append(i)
display()
a = raw_input('')
last_destination_tower = -1
last_origin_tower = -1
while len(towers[2]) != n:
# check which tower should move next
origin_tower = -1
destination_tower = -1
for origin_tower in xrange(3):
possible_destinations = attemptMove(origin_tower)
if len(possible_destinations) == 0:
continue
found = False
for destination_tower in possible_destinations:
if not (destination_tower == last_origin_tower and origin_tower == last_destination_tower):
last_origin_tower = origin_tower
last_destination_tower = destination_tower
found = True
break
if found:
break
#print next_tower
disc = towers[origin_tower][0]
towers[origin_tower] = towers[origin_tower][1:]
if origin_tower < destination_tower:
towers[origin_tower + 1][:0] = [disc]
else:
towers[origin_tower - 1][:0] = [disc]
display()
#time.sleep(0.25) # sleep 250 milliseconds
a = raw_input('')
|
1ce3182ee7cc93e36e6104f6352ccfcc2d592a57 | BrayanRuiz/AprendiendoPython | /Compara.py | 658 | 3.921875 | 4 | # Compara.py
# Autor: Brayan Javier Ruiz Navarro
# Fecha de Creación: 15/09/2019
numero1=int(input("Dame el numero uno: "))
numero2=int(input("Dame el numero dos: "))
salida="Numeros proporcionados: {} y {}. {}."
if (numero1==numero2):
# Entra aqui si los numeros son iguales
print(salida.format(numero1, numero2,"Los numeros son iguales"))
else:
# Si los numeros NO son iguales
if numero1>numero2:
# Chequea si el primer numero es mayor al segundo.
print(salida.format(numero1, numero2,"El mayor es el primero"))
else:
# Ahora si el numero mayor es el segundo
print(salida.format(numero1, numero2,"El mayor es el segundo")) |
18f0fe41b07500f4cc067520d7fc1a40c95382df | hafizmuhammadhamza/LearningPython | /Assignment3/Untitled-1.py | 1,951 | 4.09375 | 4 | Assignment#3
## calculator
val1 = input("Enter first value")
val2 = input("Enter 2nd value")
operator = input("Enter operator")
val1 = int(val1)
val2 = int(val2)
if operator == '+' :
val = val1+val2
print(val,"answer")
elif operator == '-':
val = val1-val2
print(val,"answer")
elif operator =='/' :
val = val1 / val2
print(val,"answer")
elif operator =='*' :
val = val1 * val2
print(val,"answer")
elif operator =='**' :
val = val1 ** val2
print(val,"answer")
else:
print("entetr correct value")
output:
Enter first value2
Enter 2nd value5
Enter operator**
32 answe
## For adding key value in dictionary
customer_detail={
"First name":"Hamza",
"Last name":"Abid",
"Email" : "[email protected]"
}
for customer_inf in customer_detail.keys():
print(customer_inf,"keys")
output:
First name keys
Last name keys
Email keys
##For sum all numeric values
val = {"A":24,"B":20,"c":20,"D":19}
total= sum(vl.values())
print(total)
output:
83
## To chek if given key already exist in dictonary
list = {1: 2, 2:20, 3 :4, 5 :30, 6 :50, 7 :70}
def a_keypresent(n):
if n in list:
print("key is present in the dictionary")
else:
print("key is not present in dictionary")
a_keypresent(3)
a_keypresent(4)
output:
key is present in the dictionary
key is not present in dictionary
## python program to chk if there is any numeric values in this list using for loop
num_list = [2,4,8,10,12,14,15,16,17,19]
user_input = int(input("Enter the number"))
if user_input in num_list :
print(f'{user_input}exist in this list!')
else:
print(f'{user_input}does not exist in this list!')
## duplicate values from list
list = [1,2,3,2,4,6,9,6,10]
length_of_list = len(list)
duplicate_values =[]
for i in range(length_of_list):
k = i+1
for j in range(k,length_of_list):
if list[i] == list[j]and list[i]not in duplicate_values:
duplicate_values.append(list[i])
print(duplicate_values) |
14f729286c7dd1baad31e91de84f32623aaf4ea3 | curiousboey/Split_expense | /main.py | 5,449 | 3.75 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
Total = int(input("Please enter the total expense: "))
people_money = {'A':0,'Su':0,'Sa':0,'B':0,'Sh':0,'D':0,'K':0, 'U':0, 'J':0}
exclude_person= input("Are there people to exclude from the list? (y/n): ")
exclude_name2 = 'y'
while exclude_name2 == 'y' or exclude_name2 == 'Y':
if exclude_person == 'y' or exclude_person == 'Y':
exclude_name = input('Enter the name of person: ')
del people_money[exclude_name]
exclude_name2 = input('Are there more people to exclude from the list? (y/n): ')
else:
pass
people = list(people_money.keys())
money = list(people_money.values())
no_donor = int(input('Enter the number of donor: '))
donor_name = []
donor_money = []
for i in range(no_donor):
donor_name_ask= input('Enter the name of donor: ')
donor_name.append(donor_name_ask)
donor_money_ask= int(input('Enter the amount given: '))
donor_money.append(donor_money_ask)
people_money[donor_name_ask]= donor_money_ask
ask_changes= input('Did anyone keep the changes? (y/n): ')
if ask_changes == 'y' or ask_changes == 'Y':
ask_changes_name = input('Who keeps the changes?: ')
changes_amount = sum(donor_money) - Total
people_money[ask_changes_name] = abs(donor_money[donor_name.index(ask_changes_name)]-changes_amount)
else:
pass
expense_per_head = Total/len(people_money)
print('Total expenses per person: ',expense_per_head)
confirm_expense_per_head = input('Do you want to proceed with this expenses per head? (y/n): ')
if confirm_expense_per_head == 'y' or confirm_expense_per_head == 'Y':
pass
else:
expense_per_head = int(input('Enter the approx. expenses per head: '))
print('Approx. expenses per person: ', expense_per_head)
people = list(people_money.keys())
money = list(people_money.values())
final_giver_name= []
final_giver_amount= []
final_receiver_name= []
final_receiver_amount= []
final_neutral_name= []
for j in range(len(people_money)):
if money[j] < expense_per_head:
final_giver_name.append(people[j])
final_giver_amount.append(abs(money[j]-expense_per_head))
elif money[j] == expense_per_head:
final_neutral_name.append(people[j])
else:
final_receiver_name.append(people[j])
final_receiver_amount.append(abs(money[j] - expense_per_head))
Final_text= []
while not(final_receiver_name == [] or final_giver_name == []):
n = final_receiver_amount[0] // expense_per_head
for l in range(n + 1):
if final_giver_amount == []:
pass
else:
if final_receiver_amount[0] < final_giver_amount[0]:
Final_text.append(final_receiver_name[0] + ' receives ' + str(final_receiver_amount[0]) + ' from ' + final_giver_name[0])
print(final_receiver_name[0] + ' receives ' + str(final_receiver_amount[0]) + ' from ' + final_giver_name[0])
final_receiver_name.pop(0)
final_giver_amount[0] = final_giver_amount[0] - final_receiver_amount[0]
final_receiver_amount.pop(0)
else:
Final_text.append(final_receiver_name[0] + ' receives ' + str(final_giver_amount[0]) + ' from ' + final_giver_name[0])
print(final_receiver_name[0] + ' receives ' + str(final_giver_amount[0]) + ' from ' + final_giver_name[0])
final_receiver_amount[0] = final_receiver_amount[0] - final_giver_amount[0]
final_giver_name.pop(0)
final_giver_amount.pop(0)
print(np.array(Final_text))
# create figure
fig = plt.figure(figsize=(10, 20))
plt.ylim([0,5])
# setting values to rows and column variables
rows = 4
columns = 3
# reading images
Image1 = cv2.imread('Image1_B.jpg')
Image2 = cv2.imread('Image2_Sa.jpg')
Image3 = cv2.imread('Image3_Sh.jpg')
Image4 = cv2.imread('Image4_Su.jpg')
Image5 = cv2.imread('Image5_D.jpg')
Image6 = cv2.imread('Image6_K.jpg')
Image7 = cv2.imread('Image7_A.jpg')
Image8 = cv2.imread('Image8_U.jpg')
Image9 = cv2.imread('Image9_J.jpg')
for r in range(len(Final_text)):
plt.text(0.1, 4.9-(r/6), Final_text[r], fontsize=12)
plt.title("Expenses Calculation",
fontsize='20',
backgroundcolor='green',
color='white',loc='right')
# Adds a subplot at the 1st position
fig.add_subplot(rows, columns, 4)
# showing image
plt.imshow(Image1)
plt.axis('off')
plt.title("Bhupendra(B)")
# Adds a subplot at the 2nd position
fig.add_subplot(rows, columns, 5)
# showing image
plt.imshow(Image2)
plt.axis('off')
plt.title("Sarita(Sa)")
# Adds a subplot at the 3rd position
fig.add_subplot(rows, columns, 6)
# showing image
plt.imshow(Image3)
plt.axis('off')
plt.title("Shikheb(Sh)")
# Adds a subplot at the 4th position
fig.add_subplot(rows, columns, 7)
# showing image
plt.imshow(Image4)
plt.axis('off')
plt.title("Sulav(Su)")
fig.add_subplot(rows, columns, 8)
# showing image
plt.imshow(Image5)
plt.axis('off')
plt.title("Dibesh(D)")
fig.add_subplot(rows, columns, 9)
# showing image
plt.imshow(Image6)
plt.axis('off')
plt.title("Kritika(K)")
fig.add_subplot(rows, columns, 10)
# showing image
plt.imshow(Image7)
plt.axis('off')
plt.title("Aabhash(A)")
fig.add_subplot(rows, columns, 11)
# showing image
plt.imshow(Image8)
plt.axis('off')
plt.title("Urmila(U)")
fig.add_subplot(rows, columns, 12)
# showing image
plt.imshow(Image9)
plt.axis('off')
plt.title("Jitendra(J)")
|
10fed4644051512c170e4b7486046b989ea914e7 | bencheng0904/Python200818_2 | /turtle05.py | 220 | 3.640625 | 4 | import turtle
screen=turtle.Screen
screen
a = turtle.Turtle()
n=int(input("你要幾邊形:"))
for i in range(n):
a.forward(100)
a.left(360/n)
turtle.done()
|
2a02c14e29e2394226df08d57d452ff6c1feab68 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program3.py | 396 | 3.796875 | 4 | s=0
sp=6
for i in range(1,5):
for j in range(1,s+1):
print(" ", end="")
s=s+1
print("*",end="")
for k in range(1,sp+1):
print(" ",end="")
sp=sp-2
print("*")
s=3
sp=0
for i in range(1,5):
for j in range(1,s+1):
print(" ", end="")
s=s-1
print("*",end="")
for k in range(1,sp+1):
print(" ",end="")
sp=sp+2
print("*")
|
e8c123bc4f74385b8c83d21d1d16e806c67c3e29 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program2.py | 249 | 4 | 4 | n=int(input("Enter the number: "))
if(n<0):
print("Incorrect Input")
else:
print("Fibonacci series is: ")
a=0
b=1
print(a, b, end=" ")
for i in range(1,n-1):
c=a+b
print ( c, end=" ")
a=b
b=c
|
2a7106f28502efe3d57e692d8428236b14921945 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program5.py | 263 | 4.0625 | 4 | for i in range(3,0,-1):
print(i, end="")
for j in range(1,i):
print("*", end="")
print(i,end="")
print()
for i in range(1,4):
print(i, end="")
for j in range(1,i):
print("*", end="")
print(i,end="")
print()
|
439f0067ee46a8dc51afb93675750c267ec6a54a | kimhyunkwang/algorithm-study-02 | /2주차/김윤주/숫자 나라 특허 전쟁.py | 107 | 4.09375 | 4 | num = int(input())
sum=0
for i in range(num):
if i % 3 ==0 or i % 5 ==0:
sum = sum+i
print(sum) |
3bf16699407123dc74114f452f88bfd6f33914be | kimhyunkwang/algorithm-study-02 | /3주차/김현광/해치웠나.py | 181 | 3.640625 | 4 | fight = input()
villain = fight.count("(")
hero = fight.count(")")
if fight[0] == ")":
print("NO")
elif villain > hero or villain < hero:
print("NO")
else:
print("YES") |
b3e26a6e084e4c1b3b14358483e02e8901d52116 | kimhyunkwang/algorithm-study-02 | /4주차/정소원/4주차_암호 만들기.py | 281 | 3.71875 | 4 | n = int(input())
words = [input() for _ in range(n)]
def encryption(s):
alpha = [chr(ord('A')+i) for i in range(26)]
res = ''
for c in s:
idx = (ord(c)-ord('A')+1) % 26
res += alpha[idx]
return res
for word in words:
print(encryption(word))
|
c86c5802eedd1316f0ccd88e91213661ba00ceaf | kimhyunkwang/algorithm-study-02 | /3주차/강현우/근거 없는 자신감.py | 230 | 3.75 | 4 | score = list(map(int, input().split()))
score.pop(0)
average = sum(score) / len(score)
good_student = 0
for i in score:
if i > average:
good_student += 1
print("{:.3f}%".format(round(good_student/len(score)*100,3))) |
47ccf26e0a4109f42effb74ebfabbdf5814242e7 | kimhyunkwang/algorithm-study-02 | /2주차/김현광/무어의 법칙[Moore's Law].py | 108 | 3.71875 | 4 | n = int(input())
SUM = 0
n_str = str(2**n)
for i in range(len(n_str)):
SUM += int(n_str[i])
print(SUM) |
d08aa6822d4f277870069b700c232c8b5550c3a0 | kimhyunkwang/algorithm-study-02 | /2주차/심재민/숫자 나라 특허 전쟁.py | 233 | 3.84375 | 4 | # 숫자 나라 특허 전쟁
N = int(input())
three = []
five = []
for i in range(1, N):
if i % 3 == 0:
three.append(i)
elif i % 5 == 0:
five.append(i)
num = three + five
print(sum(set(num))) |
698b8212c16b1a11a5fb9d63af5db687d404039f | beyzakilickol/week1Friday | /algorithms.py | 953 | 4.1875 | 4 | #Write a program which will remove duplicates from the array.
arr = ['Beyza', 'Emre', 'John', 'Emre', 'Mark', 'Beyza']
arr = set(arr)
arr = list(arr)
print(arr)
#-------Second way------------------------
remove_dups = []
for i in range(0, len(arr)):
if arr[i] not in remove_dups:
remove_dups.append(arr[i])
print(remove_dups)
#-------------Assignment 2-------------------------
#Write a program which finds the largest element in the array
arr = [3,5,7,8,9,14,24,105]
print(max(arr))
#-------------Assignment 3--------------------------------
#Write a program which finds the smallest element in the array
print(min(arr))
# stringArr = ['beyza', 'cem', 'ramazan', 'ak', 'ghrmhffjhfd', 'yep']
# print(min(stringArr)) # returns ak in alphabetical order
#------------Assigment 4----------------------------------
#Write a program to display a pyramid
string = "*"
for i in range(1, 18 , 2):
print('{:^50}'.format(i * string))
|
34da44a06b3aa45cf48daa2bb0f967289adaa72b | ArunDhwaj/python | /myoops/oops_depth.py | 297 | 3.59375 | 4 | class Book:
def __init__(self, name, pageNumber):
self.name = name
self.pageNumber = pageNumber
hindi = Book('Hindi', 200)
java = Book('Java', 590)
#english.name = 'English'
#english.pageNumber = 2000
print(hindi.name, hindi.pageNumber)
print(java.name, java.pageNumber)
|
7676878c6cf7c1395fde4e3f4f96a650b08556c9 | ajh1143/HackerRank_Practice | /TripletComparison.py | 1,048 | 3.59375 | 4 | #Compare values in equal positions of two arrays, awarding a point to the array with the greater value in the comparison point.
#If values are equal, no points will be awarded for that comparison.
#Return a list of values indicating the score for each array owner, named Alice and Bob
#!/bin/python3
import os
import sys
def solve(a0, a1, a2, b0, b1, b2):
aliceScore = 0
bobScore = 0
alice = [a0, a1, a2]
bob = [b0, b1, b2]
for t in range(3):
if alice[t] == bob[t]:
pass
elif alice[t] > bob[t]:
aliceScore +=1
else:
bobScore += 1
return aliceScore, bobScore
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
a0A1A2 = input().split()
a0 = int(a0A1A2[0])
a1 = int(a0A1A2[1])
a2 = int(a0A1A2[2])
b0B1B2 = input().split()
b0 = int(b0B1B2[0])
b1 = int(b0B1B2[1])
b2 = int(b0B1B2[2])
result = solve(a0, a1, a2, b0, b1, b2)
f.write(' '.join(map(str, result)))
f.write('\n')
f.close()
|
73c8c88528e7c980308ade1d8f59545bd9fee2e1 | McSwellian/3414-Hackbots-FRC-scouting | /Manual Data Entry.py | 1,074 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 00:12:39 2018
@author: Maxwell Ledermann
"""
import pickle
import os
def is_number(inpt):
try:
float(inpt)
return True
except ValueError:
return False
while(True):
print("Type 'exit' or 'x' at any time to safely exit the program.")
team_number = input("Enter team number: ")
if team_number in ("exit","x"):
break
if is_number(team_number) == True:
match_number = input("Enter match number, leave blank to cancel: ")
if match_number in ("exit","x"):
break
elif match_number != "" and is_number(match_number) == True:
scan = input("Press enter to begin scan, type any other value to cancel: ")
if scan in ("exit","x"):
break
elif scan == "":
keyword = True
pickle.dump((team_number,match_number,keyword), open( "entry data.p", "wb" ))
keyword = False
clear = lambda: os.system('cls')
clear() |
32f05d2f45e3bad3e2014e1ba768a6b92d4e67b6 | soumyadc/myLearning | /python/statement/loop-generator.py | 575 | 4.3125 | 4 | #!/usr/bin/python
# A Generator:
# helps to generate a iterator object by adding 1-by-1 elements in iterator.
#A generator is a function that produces or yields a sequence of values using yield method.
def fibonacci(n): #define the generator function
a, b, counter = 0, 1, 0 # a=0, b=1, counter=0
while True:
if(counter > n):
return
yield a
a=b
b=a+b
counter += 1
it=fibonacci(5) # it is out iterator object here
while True:
try:
print (next(it))
except:
break
print("GoodBye")
|
7400c080f5ce15b3a5537f436e3458772b42d801 | soumyadc/myLearning | /python/tkinter-gui/hello.py | 737 | 4.21875 | 4 | #!/usr/bin/python
from Tkinter import *
import tkMessageBox
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
# Code to add widgets will go here...
# Tk root widget, which is a window with a title bar and other decoration provided by the window manager.
# The root widget has to be created before any other widgets and there can only be one root widget.
top = Tk()
L1= Label(top, text="Hello World")
L1.pack(side=LEFT)
# Button, when clicked it calls helloCallBack() function
B1=Button(top, text="Hello", command=helloCallBack)
B1.pack(side=RIGHT)
# The window won't appear until we enter the Tkinter event loop
# Our script will remain in the event loop until we close the window
top.mainloop()
|
f79177c85731cb3d855362ae429046af9f26755b | soumyadc/myLearning | /python/tkinter-gui/label-dynamic-content.py | 433 | 3.59375 | 4 | #!/usr/bin/python
from Tkinter import *
import tkMessageBox
def counter_label(L2):
counter = 0
L2.config(text="Hello World")
top = Tk()
top.title("Counting Seconds")
logo= PhotoImage(file="/home/soumyadc/Pictures/Python.png")
L1= Label(top, image=logo).pack(side="right")
L2 = Label(top, fg="green").pack(side="left")
counter_label(L2)
B1=Button(top, text='stop', width=25, command=top.destroy).pack()
top.mainloop()
|
c553dbc7c7a4d74904c17b53cd050f1448648d2f | tavu/nao_footsteps | /footstep_handler/src/footstep_handler/stepQueue.py | 1,077 | 3.59375 | 4 | import copy
class StepQueue(object):
_steps = None
_nextStep = 0
def __init__(self):
self._steps = []
self._nextStep = 0
return
def clear(self):
self._steps = []
self._nextStep = 0
return
def addStep(self, step):
new_step = copy.deepcopy(step)
self._steps.append(new_step)
return
def addSteps(self, steps):
#self._steps = copy.deepcopy(steps)
self._steps.extend(copy.deepcopy(steps) )
self._nextStep = 0
return
def isEmpty(self):
return len(self._steps) == 0
def isFInished(self):
if self.isEmpty() :
return True
if len(self._steps) <= self._nextStep :
return True
return False
def size(self):
return len(self._steps)
def nextStep(self):
if self.isFInished():
return None
nextStep = self._steps[self._nextStep]
self._nextStep = self._nextStep +1
return nextStep
|
09605e5fb1a9abd9463bb22d7aa5476a461cdf0a | maarjaryytel/python | /Tund_2/loop.py | 898 | 3.75 | 4 | #while
#for
#index=100
#teineIndex=10
#print(index)
#while index<=10:
#print(teineIndex)
#index+=1
#index+=100
#if index==5:
# print(index)
#break
#continue
#else:
#print("Condition is false")
#fruits=["apple", "banana", "cherry"]
#for x in fruits:
#print(x)
#for x in range(2,60,3): #see viimane nr tõstab 3 võrra
#print(x)
#pass kui ma ei taha siin midagi kuvada, siis panen pass,
#siis ta läheb edasi
#else:
#print("finished!")
#for x in range(11): #10 korda
#for x in range(11): #10 korda
#print(x) #ehk kuvab 2 korda järjest
cars=["Audi", "BMW", "Ford", "Mazda", "Peugeot"]
print(cars)
vastus = input("Vali nimekirjast oma lemmik: ")
#for car in cars: see on vale
#print(cars.index(vastus))
for car in cars:
print(cars.index(car)) #(cars.index(vastus)) |
10ba8e8b576debb45c7fe3d6fb9caa72fcad6c60 | maarjaryytel/python | /Tund_4/kolmnurk.py | 701 | 3.625 | 4 | def kolmnurga_funktsioon():
kolmnurgaAlus=int(input("Sisesta kolmnurga alus (cm): "))
kolmnurgaKõrgus= int(input("Sisesta kolmnurga kõrgus (cm): "))
kolmnurgaPindala=kolmnurgaAlus*kolmnurgaKõrgus/2
##print("Vastus on: ", kolmnurgaPindala) #parem on returni kasutada
return kolmnurgaPindala
def ruudu_funktsioon():
ruuduKylg=int(input("Sisesta ruudu külg (cm): "))
ruuduPindala= ruuduKylg*ruuduKylg
return ruuduPindala
def ristkyliku_funktsioon():
kyljePikkus=int(input("Sisesta ristküliku külje pikkus (cm): "))
kyljeLaius=int(input("Sisesta ristküliku külje laius (cm): "))
ristkylikuPindala= kyljePikkus*kyljeLaius
return ristkylikuPindala
|
c3d8d2b2ed1064d21443522737f47d4320f60e16 | donariumdebbie/BaekjoonOnlineJudge | /1000/1008.py | 393 | 3.546875 | 4 | # Completed 2017-08-20
# correct code
from __future__ import division
input_numbers = raw_input()
int_nums = [int(item) for item in input_numbers.split()]
print int_nums[0]/int_nums[1]
# first submitted : correct but runtime error
# import numpy as np
# input_numbers = raw_input()
# int_nums = [int(item) for item in input_numbers.split()]
# print np.true_divide(int_nums[0],int_nums[1]) |
11be5b7d615e15e376720def2715bed5b84a43e6 | ybgirgin3/tkinter-CRM-gui | /2main.py | 6,807 | 3.5625 | 4 | from tkinter import *
from tkinter import ttk
import sqlite3
root = Tk()
root.geometry("800x500")
db_name = "tkinter_db.sqlite3"
# create db or connect one
conn = sqlite3.connect(db_name)
c = conn.cursor()
# create table
c.execute("""CREATE TABLE if not exists table1 (
ID integer,
numara INTEGER,
adi TEXT,
soyadi TEXT,
telefonu INTEGER)
""")
# commit changes
conn.commit()
conn.close()
def query_database():
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("SELECT * FROM table1")
records = c.fetchall()
from pprint import pprint
pprint(records)
print()
global count
count = 0
"""for record in records:
print(recor d)"""
for record in records:
if count % 2 == 0:
my_tree.insert(parent="", index="end", iid=count, text="", values = (record[0], record[1], record[2], record[3], record[4]), tags=('evenrow',) )
else:
my_tree.insert(parent="", index="end", iid=count, text="", values = (record[0], record[1], record[2], record[3], record[4]), tags=('oddrow',) )
count += 1
conn.commit()
conn.close()
# add style
style = ttk.Style()
style.theme_use('default')
style.configure("Treeview", background="#D3D3D3D", foreground="black", rowheight=25, fieldbackground="#D3D3D3")
style.map("Treeview", background=[('selected', '#347083')])
tree_frame = Frame(root)
tree_frame.pack(pady=10)
tree_scroll = Scrollbar(tree_frame)
tree_scroll.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll.set, selectmode="extended")
my_tree.pack()
tree_scroll.config(command=my_tree.yview)
# columns
my_tree['columns'] = ('ID', 'Numara', 'Adi', 'Soyadi', 'Telefonu')
# formt colum
my_tree.column("#0", width=0)
my_tree.column("ID", anchor = W)
my_tree.column("Numara", anchor = W)
my_tree.column("Adi", anchor=CENTER)
my_tree.column("Soyadi",anchor=CENTER)
my_tree.column("Telefonu",anchor=CENTER)
# headings
my_tree.heading("#0", text="LABEL", anchor=W)
my_tree.heading("ID", text="ID", anchor=CENTER)
my_tree.heading("Numara", text="Numara", anchor=CENTER)
my_tree.heading("Adi", text="Adi", anchor=CENTER)
my_tree.heading("Soyadi", text="Soyadi", anchor=CENTER)
my_tree.heading("Telefonu", text="Telefonu", anchor=CENTER)
# add data
my_tree.tag_configure('oddrow', background='white')
my_tree.tag_configure('evenrow', background='lightblue')
# add record entry boxes
data_frame = LabelFrame(root, text="Kayıtlar")
data_frame.pack(fill="x", expand="yes", padx=20, side="left")
# labelları ekle
id_label = Label(data_frame, text="id")
id_label.grid(row=0, column=1, padx=10, pady=10)
id_entry = Entry(data_frame)
id_entry.grid(row=1, column=1, padx=10, pady=10)
# ogrenci no
ogrenci_no_label = Label(data_frame, text="Öğrenci No")
ogrenci_no_label.grid(row=2, column=1, padx=10, pady=10)
ogrenci_no_entry = Entry(data_frame)
ogrenci_no_entry.grid(row=3, column=1, padx=10, pady=10)
ogrenci_adi_label = Label(data_frame, text="Adi")
ogrenci_adi_label.grid(row=4, column=1, padx=10, pady=10)
ogrenci_adi_entry = Entry(data_frame)
ogrenci_adi_entry.grid(row=5, column=1, padx=10, pady=10)
ogrenci_soyadi_label = Label(data_frame, text="Soyadi")
ogrenci_soyadi_label.grid(row=6, column=1, padx=10, pady=10)
ogrenci_soyadi_entry = Entry(data_frame)
ogrenci_soyadi_entry.grid(row=7, column=1, padx=10, pady=10)
ogrenci_telefonu_label = Label(data_frame, text="Telefonu")
ogrenci_telefonu_label.grid(row=8, column=1, padx=10, pady=10)
ogrenci_telefonu_entry = Entry(data_frame)
ogrenci_telefonu_entry.grid(row=9, column=1, padx=10, pady=10)
# clear entry boxes
def clear_entries():
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# select records
def select_records(e):
# clear entry boxes
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# grap record nauber
selected = my_tree.focus()
# grap value
values = my_tree.item(selected, "values")
# output entry boxes
id_entry.insert(0, values[0]),
ogrenci_no_entry.insert(0, values[1])
ogrenci_adi_entry.insert(0, values[2])
ogrenci_soyadi_entry.insert(0, values[3])
ogrenci_telefonu_entry.insert(0, values[4])
def update_record():
#selected = select_records()
selected = my_tree.focus()
print(selected)
my_tree.item(selected, text="", values=(id_entry.get(), ogrenci_no_entry.get(), ogrenci_adi_entry.get(), ogrenci_soyadi_entry.get(), ogrenci_telefonu_entry.get()))
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("""UPDATE table1 SET
numara = :no,
adi = :name,
soyadi = :surname,
telefonu = :phone
WHERE oid = :oid""",
{
'no': ogrenci_no_entry.get(),
'name': ogrenci_adi_entry.get(),
'surname': ogrenci_soyadi_entry.get(),
'phone': ogrenci_telefonu_entry.get(),
'oid': id_entry.get(),
})
conn.commit()
conn.close()
clear_entries()
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# add new record
def add_record():
conn = sqlite3.connect(db_name)
c = conn.cursor()
# control entry field
if len(id_entry.get()) == 0:
print("boş eleman")
elif len(id_entry.get()) > 0:
c.execute("INSERT INTO table1 VALUES (:id, :no, :name, :surname, :phone )",
{
'id': id_entry.get(),
'no': ogrenci_no_entry.get(),
'name': ogrenci_adi_entry.get(),
'surname': ogrenci_soyadi_entry.get(),
'phone': ogrenci_telefonu_entry.get(),
})
conn.commit()
conn.close()
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# clear tree view
my_tree.delete(*my_tree.get_children())
query_database()
def remove_record():
# remove from tree
x = my_tree.selection()[0]
my_tree.delete(x)
# remove from database
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("DELETE from table1 WHERE oid=" + id_entry.get())
conn.commit()
conn.close()
clear_entries()
# add buttons
button_frame = LabelFrame(root, text="Buttons")
button_frame.pack(fill='x', expand='yes', padx=20, side="right")
add_button = Button(button_frame, text="Ekle", command=add_record)
add_button.grid(row=0, column=0, padx=10, pady=10)
update_button = Button(button_frame, text="Güncelle", command=update_record)
update_button.grid(row=1, column=0, padx=10, pady=10)
delete_button = Button(button_frame, text="Sil", command=remove_record)
delete_button.grid(row=2, column=0, padx=10, pady=10)
# bind tree
my_tree.bind("<ButtonRelease-1>", select_records)
query_database()
update_record()
root.mainloop()
|
00810e6d82eadcefd857be63319e07356c69cf77 | stewartad/goodcop-dadcop | /player.py | 3,247 | 3.515625 | 4 | import pygame, constants
class Player(pygame.sprite.Sprite):
# constrctor class that takes x, y coordinates as parameters
def __init__(self, x, y):
# call parent constructor
pygame.sprite.Sprite.__init__(self)
# set sprite image and rectangle
self.image = pygame.image.load("goodcop.png")
self.rect = self.image.get_rect()
# set position
self.rect.x = x
self.rect.y = y
# set width and height
self.width = self.rect.width
self.height = self.rect.height
# set velocity and acceleration
self.dx = 0
self.dy = 0
self.ay = constants.GRAV
# set variable to retrieve platforms from main
self.walls = None
def moveLeft(self):
# Move in negative x direction
self.dx = -constants.X_VEL
def moveRight(self):
# Move in positive x direction
self.dx = constants.X_VEL
def jump(self):
# Move down 2 pixels and check for collision, then move back up 2 pixels
self.rect.y += 2
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
self.rect.y -=2
# jump if sprite is on the ground, or collided with a platform
if self.checkGround() or len(block_hit_list)>0:
self.dy = -constants.Y_VEL
self.rect.y -= 4
def stop(self):
# set x velocity to zero to stop movement
self.dx = 0
def checkGround(self):
onGround = False
# if bottom of rectangle is greater than or equal to the screen height,
# then the sprite is on the ground
if self.rect.bottom >= constants.SCR_HEIGHT:
onGround = True
return onGround
def addGrav(self):
# If platform moves, this ensures player moves with it
if self.dy == 0:
self.dy = 1
else:
self.dy -= constants.GRAV
if self.checkGround():
# If on the ground, negate gravity
self.dy = 0
self.rect.y = constants.SCR_HEIGHT - self.height
def update(self):
# Account for gravity
self.addGrav()
# move in x direction
self.rect.x += self.dx
# check if x movement resulted in collision
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.dx > 0:
self.rect.right = block.rect.left
if self.dx < 0:
self.rect.left = block.rect.right
# check if x movement goes off screen
if self.rect.right >= constants.SCR_WIDTH:
self.rect.right = constants.SCR_WIDTH
elif self.rect.x <= 0:
self.rect.x = 0
# move in y direction
self.rect.y += self.dy
# check if y movement resulted in collision
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.dy > 0:
self.rect.bottom = block.rect.top
if self.dy < 0:
self.rect.top = block.rect.bottom
self.dy=0
|
29c1733f39888ca54099d2e15a762d8d748c06f9 | opiroi/sololearn_python | /assistant/python_iterators_and_generators.py | 1,556 | 4.5 | 4 |
def iteration_over_list():
"""Iteration over list elements.
:return: None
"""
print("##### ##### iteration_over_list ##### #####")
for i in [1, 2, 3, 4]:
print(i)
# prints:
# 1
# 2
# 3
# 4
def iteration_over_string():
"""Iteration over string characters.
:return: None
"""
print("##### ##### iteration_over_string ##### #####")
for i in "python":
print(i)
# prints:
# p
# y
# t
# h
# o
# n
def iteration_over_dictionary():
"""Iteration over dictionary elements.
:return: None
"""
print("##### ##### iteration_over_dictionary ##### #####")
for i in {"x": 1, "y": 2, "z": 3}:
print(i)
# prints:
# z
# y
# x
def iteration_over_file_line():
"""Iteration over file lines.
:return: None
"""
print("##### ##### iteration_over_file_line ##### #####")
for line in open("a.txt"):
print(line)
# prints:
# first line
# second line
def iteration_practical_usage():
"""Efficient usage examples of iterations.
1. list join
2. dictionary join
3. string list
4. dictionary list
:return: None
"""
print("##### ##### iteration_practical_usage ##### #####")
print(",".join(["a", "b", "c"]))
# prints as string: 'a,b,c'
print(",".join({"x": 1, "y": 2}))
# prints as string: 'y,x'
print(list("python"))
# prints as list: ['p', 'y', 't', 'h', 'o', 'n']
list({"x": 1, "y": 2})
# prints as list: ['y', 'x']
|
a80e193e474dbf030fe16d22c4bcc50dba20d6f9 | lionfish0/QueueBuffer | /QueueBuffer/__init__.py | 3,484 | 4.1875 | 4 | from multiprocessing import Queue, Value, Manager
import threading
class QueueBuffer():
def __init__(self,size=10):
"""Create a queue buffer. One adds items by calling the put(item) method.
One can wait for new items to be added by using the blocking pop() method
which returns the index and the item that have been added. One can read
items that have been added previously using the read(index) method.
The constructor takes one optional argument, size, which means older items
are deleted."""
self.inbound = Queue() #an internal queue to manage the class properly in a thread safe manner.
self.index = Value('i',0) #index of next item to be added.
self.manager = Manager()
self.buffer = self.manager.list() #the buffer we will store things in.
self.size = size #the maximum size of the buffer
self.newitem = Queue() #a blocking event to control the pop method
t = threading.Thread(target=self.worker) #the worker that will run when items are added.
t.start() #start the worker
self.newitemindex = 0 #index of items to pop
def len(self):
"""Get the number of items that have been added. This doesn't mean they all remain!"""
return self.index.value
def unpopped(self):
"""Return the number of items still to pop"""
return self.newitem.qsize()
def worker(self):
"""
Helper function, internally blocks until an item is added to the internal
queue, this is then added into our buffer, and various indices are sorted.
"""
while True:
item,index = self.inbound.get()
if index is None:
self.buffer.append(item)
self.index.value = self.index.value + 1 #index of next item for buffer
if len(self.buffer)>self.size:
del self.buffer[0]
self.newitem.put(None)
else:
self.buffer[len(self.buffer)+(index - self.index.value)] = item
def put(self,item,index=None):
"""
Add an item to the queue.
"""
self.inbound.put((item,index))
def read(self,getindex):
"""Read item at index getindex. Returns the item. Fails if item no longer exists."""
if getindex<0:
#print("Indicies are non-negative")
return None
try:
bufinx = len(self.buffer)+(getindex - self.index.value)
if bufinx<0:
#print("This item has been deleted, try increasing the queue size")
return None
return self.buffer[bufinx]
except IndexError:
#print("This item doesn't exist yet")
return None
def pop(self):
"""Blocks until a new item is added. Returns the index and the item.
!Item remains in the QueueBuffer, so 'pop' is slightly misleading.
It will return (index,None) if the item has already been lost from the buffer."""
self.newitem.get() #blocks until an item is added, using a queue for this to ensure that only one worker is triggered.
#if self.newitemindex+1==self.index: self.newitem.clear()
index = self.newitemindex
item = self.read(index)
self.newitemindex += 1
return index, item
|
e85970fdb453b4554290f61d7b0ef3ecc7ae0028 | knoixs/Heard_First | /ceshi.py | 1,241 | 3.578125 | 4 | # class A(object):
# def go(self):
# print "go A go!"
#
# def stop(self):
# print "stop A stop!"
#
# def pause(self):
# raise Exception("Not Implemented")
#
#
# class B(A):
# def go(self):
# super(B, self).go()
# print "go B go"
#
#
# class C(A):
# def go(self):
# super(C, self).go()
# print "go C go!"
#
#
# class D(B, C):
# def go(self):
# super(D, self).go()
# print "go D go!"
#
# def stop(self):
# super(D, self).stop()
# print "stop D stop!"
#
# def pause(self):
# print "wait D wait!"
#
#
# class E(B, C):
# pass
#
#
# a = A()
# b = B()
# c = C()
# d = D()
# e = E()
#
# print a.go()
# print b.go()
# print c.go()
# print d.go()
# print e.go()
#
class Node(object):
def __init__(self, sName):
self._lChildren = []
self.sName = sName
def __repr__(self):
return "<Node '{}'>".format(self.sName)
def append(self, *args, **kwargs):
self._lChildren.append(*args, **kwargs)
def print_all_1(self):
print self
for oChild in self._lChildren:
oChild.print_all_1()
def print_all_2(self):
def gen(o):
pass
|
e667b9b82d8e19fbbbe80b48ea77c3ed37d45528 | sathishtammalla/PythonLearning | /Week2/collectionsdemo.py | 8,842 | 4.03125 | 4 | from collections import Counter
colls = ['Write a Python program that takes mylist = ["WA", "CA", "NY"] and add “IL” to the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print position/Index of CA in the list using list index function.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print position/index of each item in the list using list index function.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and sort the list using list sort function.',
'Write a Python program that takes mylist = ["Seattle", "Bellevue", "Redmond", “Issaquah”] and print it using for loop.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print it respective state names (Ex: WA is Washington] for each item in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times WA appeared in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times WA and CA appeared in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print sum of all the items in the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print large number from the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print middle number from the list.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”] and print the string that appeared more than once.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”] and remove duplicates from the list.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”, “POR”, “KEN”, “NJC”] and remove all even items in the list.',
'Write a Python program that takes mylist = [“CALIFORNIA”, “SEATTLE”, “PIT”] and print number of characters in each item in the list.',
'Write a Python program that takes list1 = [“WA”, “CA”] and list2 = [“Washinton”, “California] and create a list3 = [“WA”, “Washington”, “CA”, “California”].',
'Write a Python program that takes mylist = [6, 2, 7, 3, 4, 5] and sort the list ascending without using sort function.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print second largest number from the list.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print the tuple using for loop',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print first item using index.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and change first item = “NJ” and print.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and check if “CA” exists and print.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print length of the tuple.'
]
# print(colls)
print(colls[0])
mylist = ['WA', 'CA', 'NY']
print(f'Items in list : {mylist}')
print("Adding 'IL' to the list")
mylist.append('IL')
print(f'Items in list after adding : {mylist}')
print(colls[1])
print(f'Current Items in mylist : {mylist}')
print(colls[2])
print(f'Index position of "CA" is : {mylist.index("CA")}')
print(colls[3])
for index, value in enumerate(mylist):
print(f'Index : {index} Value : {value}')
print(colls[4])
mylist = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'My list is before sorting {mylist}')
mylist.sort()
print(f'The Sorted list is : {mylist}')
print(colls[5])
cities = ["Seattle", "Bellevue", "Redmond", "Issaquah"]
print(f'Cities in the list {cities}')
print('Looping and printing each city')
for c in cities:
print(c)
print(colls[6])
states = ['WA', 'CA', 'NY', 'IL']
st_name = ['Washington', 'California', 'New York', 'Illinois']
print(f'Printing full names of the STATES {states}')
for index, value in zip(states, st_name):
print(f'{index} - {value}')
print(colls[7])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of "WA" in the list {states.count("WA")}')
print(colls[8])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of "WA" and "CA" in the list {states.count("WA")} and {states.count("CA")}')
print(colls[9])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of each element in the list {Counter(states)}')
for key, value in dict(Counter(states)).items():
print(f'State :{key} Count : {value}')
print(colls[10])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing sum of all the items : {sum(l)}')
print(colls[11])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing largest number in the list : {max(l)}')
print(colls[12])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing middle number from the list : {(l[int(len(l) / 2)])}')
print(colls[13])
li = ['CAL', 'SEA', 'PIT', 'CAL', 'SEA']
print(f'Items in list {li}')
print(f'Printing items that appeared more than 1 ')
for key, value in dict(Counter(li)).items():
if value > 1:
print(f'{key} - {value}')
print(colls[14])
li = ['CAL', 'SEA', 'PIT', 'CAL', 'SEA']
print(f'Items in list {li}')
print(f'Printing items after removing duplicates')
for key, value in dict(Counter(li)).items():
print(key)
print('Removing duplicates using set..')
st = set(li)
print(st)
print(colls[15])
states = ['CAL', 'SEA', 'PIT', 'CAL', 'POR', 'KEN', 'NJC']
print(f'Items in the list {states}')
print(f'remove only even items from the list and print')
states = states[1::2]
print(states)
print(colls[16])
li = ['CALIFORNIA', 'SEATTLE', 'PIT']
print(f'Items in the list {li}')
print('Printing Characters in each item of the list')
for i in li:
print(f'Item : {i} No of Chars {len(i)}')
print(colls[17])
list1 = ['WA', 'CA']
list2 = ['Washinton', 'California']
print(f'2 lists {list1} and {list2}')
print('Adding 2 lists')
list3 = list1 + list2
print(f'Items in list 3 after adding {list3}')
print(colls[18])
mylist = [6, 2, 7, 3, 4, 5]
print(f'Items in the list {mylist}')
print('printing items in ascending order without using Sort function')
sort_list = []
for i in range(len(mylist)):
num = min(mylist)
sort_list.append(num)
idx = mylist.index(num)
mylist.pop(idx)
print(sort_list)
print(colls[19])
li = [4, 5, 2, 8, 3, 1]
print(f'Items in the list {li}')
print('printing the second largest item in the list')
print(f'Second largest number in the list {sorted(li)[-2:-1:]}')
print(colls[20])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print('Printing them one by one')
for i in mytuple:
print(i)
print(colls[20])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Printing first item using Index -> {mytuple[0]}')
print(colls[21])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
mytuple = ("NJ",) + mytuple[1::]
print(f'Replacing first item with "NJ" -> {mytuple}')
print(colls[22])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Checking if "CA" exists -> {"CA" in mytuple}')
print(colls[23])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Printing length of Tuple {len(mytuple)}')
print('Set Exercises.....')
myset = {"NFL", "Cricket", "Baseball"}
print(f'printing set items -- printing without order.... {myset}')
print('Adding "Soccer" to Set ')
myset.add('Soccer')
print(f'printing set items after adding -- printing without order.... {myset}')
print('Using pop to remove item and print which item popped out')
popped = myset.pop()
print(f'Popped out items from set is : {popped}')
print('Set operations...intersect between two sets')
myset1 = {"NFL", "Cricket", "Baseball"}
myset2 = {"NFL", "Cricket", "Soccer"}
myset3 = {"NFL","Cricket"}
print(f' Set 1 {myset1} and set 2 {myset2}')
print(f'Set interset {myset1.intersection(myset2)}')
print(f'Set different 1 minus 2 {myset1.difference(myset2)}')
print(f'Set different 2 minus 1 {myset2.difference(myset1)}')
print(f'Set union {myset2.union(myset1)}')
print(f' Set 1 {myset1} and set 2 {myset3}')
print(f'Set 1 is superset of 3 -> {myset1.issuperset(myset3)}')
|
d9416fcdf18c6288f5c0777de675ae3fcf9f599c | sathishtammalla/PythonLearning | /factorial.py | 1,273 | 4.09375 | 4 | 5# Regular Factorial Function
def factorial(n):
num = n
fact = 1
if n > 900:
print('Number is too big..Enter a number less than 900')
n = 1
while num > 1:
fact = fact * num
num = num - 1
#print(fact)
print('Factorial of ' + str(n) + ' is ' + str(fact))
# Recursive Factorial Function
def rec_fact(n):
return 1 if(n <=1) else (n * rec_fact(n-1))
def check_if_number(n):
try:
n = int(n)
rn = 'Y'
return rn
except:
rn = 'N'
return rn
# Global Infinite Loop....
print('This is a Factorial Program....'+'\n')
while True:
print('Enter a number between 1 and 900 to find a factorial or press x to exit')
entry = input()
if entry == 'x' or entry =='X':
print('Thanks for using Factorial Program.! Hope you found it useful!')
break
#else if
else:
if check_if_number(entry) == 'Y':
#factorial(int(entry))
if int(entry) > 900:
print('Number is too big..Enter a number less than 900')
else:
print('Factorial of '+ entry +' is ' + str(rec_fact(int(entry))))
else:
print("This is not a Valid number..please enter a Positive number")
|
7b3a4e66395735192270abc17f1c77bc8d5ee5bd | newjoseph/Python | /Kakao/String/parentheses.py | 2,587 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# parentheses example
def solution(p):
#print("solution called, p is: " + p + "\n" )
answer = ""
#strings and substrings
#w = ""
u = ""
v = ""
temp_str = ""
rev_str = ""
#number of parentheses
left = 0
right = 0
count = 0
# flag
correct = True;
#step 1
#if p is an empty string, return p;
if len(p) == 0:
#print("empty string!")
return p
# step 2
#count the number of parentheses
for i in range(0, len(p)):
if p[i] == "(" :
left += 1
else:
right += 1
# this is the first case the number of left and right are the same
if left == right:
u = p[0: 2*left]
v = p[2*left:]
#print("u: " + u)
#print("v: " + v)
break
# check this is the correct parenthese ()
for i in range(0, len(u)):
#count the number of "("
if u[i] == "(":
count += 1
# find ")"
else:
# if the first element is not "("
if count == 0 and i == 0 :
#print("u: "+ u +" change to false")
correct = False
break
# reduce the number of counter
count -= 1
if count < 0:
correct = False
break;
else:
continue
"""
for j in range(1, count + 1):
print("i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count) + " lenth of u is " + "{}".format(len(u)))
#
#if u[i+j] == "(" :
if count < 0:
print( " change to false " + "i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count))
correct = False
break
else:
continue
"""
# reset the counter
count = 0
#print( "u: " + u + " v: " + v)
#if the string u is correct
if correct == True:
temp = u + solution(v)
#print(" u is " + u +" CORRECT! and return: " + temp)
return temp
# if the string u is not correct
else:
#print(" u is " + u +" INCORRECT!")
#print("check: " + check)
temp_str = "(" + solution(v) + ")"
# remove the first and the last character
temp_u = u[1:len(u)-1]
# change parentheses from ( to ) and ) to (
for i in range(len(temp_u)):
if temp_u[i] == "(":
rev_str += ")"
else:
rev_str += "("
#print("temp_str: " + temp_str + " rev_str: " + rev_str)
answer = temp_str + rev_str
#print("end! \n")
return answer
|
d17f0a5bc03b4ac03c3c9ed841d221d67866e268 | Rahul-Chaudhary-2301/Tic-Tac-Toe-Python | /Tic_Tac_Toe.py | 982 | 3.640625 | 4 | #Tic Tac Toe
from Player import Player
from UI import UI
from Game import Game
if __name__ == '__main__':
print('Wellcome to X O')
print(' 1] Play with CPU\n 2] Play with Human \n 3]Exit')
opt = int(input('>'))
if opt == 1:
pass
sel = input('Select X / O : ')
if sel == 'X':
Player1 = Player('X')
Computer = Player('O','COMPUTER')
Board = UI()
G = Game(Player1,Computer,Board,mode='C')
G.play()
else:
Player2 = Player('O')
Computer = Player('X','COMPUTER')
Board = UI()
G = Game(Computer,Player2,Board,mode='C')
G.play()
elif opt == 2:
Player1 = Player('X')
Player2 = Player('O')
Board = UI()
G = Game(Player1,Player2,Board,mode='H')
G.play()
elif opt == 3:
exit()
|
40834ff71cc6200a7028bd1d8a7cacf42c9f886e | nicolaetiut/PLPNick | /checkpoint1/sort.py | 2,480 | 4.25 | 4 | """Sort list of dictionaries from file based on the dictionary keys.
The rule for comparing dictionaries between them is:
- if the value of the dictionary with the lowest alphabetic key
is lower than the value of the other dictionary with the lowest
alphabetic key, then the first dictionary is smaller than the
second.
- if the two values specified in the previous rule are equal
reapply the algorithm ignoring the current key.
"""
import sys
def quicksort(l):
"""Quicksort implementation using list comprehensions
>>> quicksort([1, 2, 3])
[1, 2, 3]
>>> quicksort('bac')
['a', 'b', 'c']
>>> quicksort([{'bb': 1, 'aa': 2}, {'ba': 1, 'ab': 2}, {'aa': 1, 'ac': 2}])
[{'aa': 1, 'ac': 2}, {'aa': 2, 'bb': 1}, {'ab': 2, 'ba': 1}]
>>> quicksort([])
[]
"""
if l == []:
return []
else:
pivot = l[0]
sub_list = [list_element for list_element in l[1:]
if list_element < pivot]
lesser = quicksort(sub_list)
sub_list = [list_element for list_element in l[1:]
if list_element >= pivot]
greater = quicksort(sub_list)
return lesser + [pivot] + greater
def sortListFromFile(fileName, outputFileName):
"""Sort list of dictionaries from file. The input is a file containing
the list of dictionaries. Each dictionary key value is specified on
the same line in the form <key> <whitespace> <value>. Each list item
is split by an empty row. The output is a file containing a list of
integers specifying the dictionary list in sorted order. Each integer
identifies a dictionary in the order they were received in the input
file.
>>> sortListFromFile('nonexistentfile','output.txt')
Traceback (most recent call last):
...
IOError: [Errno 2] No such file or directory: 'nonexistentfile'
"""
l = []
with open(fileName, 'r') as f:
elem = {}
for line in f:
if line.strip():
line = line.split()
elem[line[0]] = line[1]
else:
l.append(elem)
elem = {}
l.append(elem)
f.closed
with open(outputFileName, 'w+') as f:
for list_elem in quicksort(l):
f.write(str(l.index(list_elem)) + '\n')
f.closed
if __name__ == "__main__":
if (len(sys.argv) > 1):
sortListFromFile(sys.argv[1], 'output.txt')
else:
print "Please provide an input file as argument."
|
3e6a7cde7bc3639de439ae27c55bf17cc34a5dcd | Michellinian/unit-3 | /snakify_practice/square.py | 92 | 3.921875 | 4 | # A program that takes a number and prints its square
a = int(input())
b = (a ** 2)
print(b) |
532a675840c95eefc4fe9a27f6b5cebe5658bcd7 | Michellinian/unit-3 | /snakify_practice/prevNext.py | 116 | 3.9375 | 4 | # Read the integer numbers and prints its previous and next numbers
num = int(input())
print(num - 1)
print(num + 1) |
235fd1475b420583988d3f61962a2a043b719b5b | Michellinian/unit-3 | /snakify_practice/signFunc.py | 190 | 4.03125 | 4 | # For the given integer X print 1 if it's positive
# -1 if it's negative
# 0 if it's equal to zero
num = int(input())
if num < 0:
print(-1)
elif num == 0:
print(0)
else:
print(1) |
4fe12c2ab9d4892088c5270beb6e2ce5d96debb1 | chapman-cs510-2016f/cw-03-datapanthers | /test_sequences.py | 915 | 4.3125 | 4 | #!/usr/bin/env python
import sequences
# this function imports the sequences.py and tests the fibonacci function to check if it returns the expected list.
def test_fibonacci():
fib_list=sequences.fibonacci(5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
#
### INSTRUCTOR COMMENT:
# It is better to have each assert run in a separate test function. They are really separate tests that way.
# Also, it may be more clear in this case to skip defining so many intermediate variables:
# assert sequences.fibonacci(1) == [1]
#
fib_list=sequences.fibonacci(1)
test_list=[1]
assert fib_list == test_list
fib_list=sequences.fibonacci(10)
test_list=[1,1,2,3,5,8,13,21,34,55]
assert fib_list == test_list
# test to make sure negative input works
fib_list=sequences.fibonacci(-5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
|
1480d01f8e418339339087623e55c93c3a01ee86 | pdtrang/COMP8295-Binf-Algorithm | /suffixarr.py | 712 | 3.546875 | 4 | seq = 'THECATISINTHEHAT'
query = 'IN'
def Search_str(seq,query):
idx = []
for i in range(len(seq)-len(query)+1):
if (query == seq[i:i+len(query)]):
idx.append(i)
return idx
def Search(seq, query):
l, r = 0, len(SA)-1
while l<=r:
mid = (l+r)//2
print(l, mid, r, seq[SA[mid]:])
if seq[SA[mid]:].startswith(query):
return SA[mid]
if query < seq[SA[mid]:]:
r = mid - 1
else:
l = mid + 1
return -1
def BuildSA(seq):
SA = []
for i in range(len(seq)):
SA.append(i)
SA.sort(key=lambda k: seq[k:])
return SA
def PrintSA(SA):
for i in range(len(SA)):
print('%3d %3d %s' %(i, SA[i], seq[SA[i]:]))
SA=BuildSA(seq)
PrintSA(SA)
print("query", query)
print(Search(seq, query))
|
82568658ecaa75070b2bb60c20f49c59c43f0672 | kenguoasd/ichw | /currency.py | 2,559 | 4.09375 | 4 | #!/usr/bin/env python3
"""currency.py:用来进行货币的换算的一个函数
__author__ = "Wenxiang.Guo"
__pkuid__ = "1800011767"
__email__ = "[email protected]"
"""
from urllib.request import urlopen #如作业说明,在Python中访问URL
a = input() #a为输入的第一个变量
b = input() #b为输入的第二个变量
c = input() #c为输入的第三个变量
def exchange(currency_from, currency_to, amount_from): #定义所需要的exchange函数,括号里为三个变量
"""Returns: amount of currency received in the given exchange.
In this exchange, the user is changing amount_from money in
currency currency_from to the currency currency_to. The value
returned represents the amount in currency currency_to.
The value returned has type float.
Parameter currency_from: the currency on hand
Precondition: currency_from is a string for a valid currency code
Parameter currency_to: the currency to convert to
Precondition: currency_to is a string for a valid currency code
Parameter amount_from: amount of currency to convert
Precondition: amount_from is a float"""
cf = currency_from #把第一个自变量currency_from换成简单的cf
ct = currency_to #把第二个自变量currency_to换成简单的ct
af = amount_from #把第三个自变量amount_from换成简单的af
web = 'http://cs1110.cs.cornell.edu/2016fa/a1server.php?from='+cf+'&to='+ct+'&amt='+af #这是把三个自变量输入到网址中得到一个字符
doc = urlopen(web) #如作业说明所讲访问这个网页
docstr = doc.read() #如作业说明
doc.close() #如作业说明
jstr = docstr.decode('ascii') #通过ascii码进行转化
s = jstr.split(':')[2] #将所得字符串以:分割并取第三部分
q = eval(s)[0] #将所取部分换成列表格式并取第一部分
p = q.split()[0] #将所得到的浮点数+空格+字母按空格分开并提取数字
return(p) #得到所需数字
print(exchange(a,b,c)) #执行函数
def testa():
"""定义一个用来检查exchange函数的函数"""
assert(str(17.13025) == exchange('USD','CNY','2.5')) #判断前后是否相同
def testall():
"""定义一个检查所有的函数(这里就一个)"""
testa() #执行函数testa()
print('It tests passed') #输出字符
testall() #执行testall()
|
c653a9e13975ea2ed34ad45f98c04c07e712e0a8 | Chooo4u/Decision-Tree | /problem3.py | 15,165 | 3.59375 | 4 | import math
import numpy as np
from collections import Counter
#-------------------------------------------------------------------------
'''
Problem 3: Decision Tree (with Descrete Attributes)
In this problem, you will implement the decision tree method for classification problems.
You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.
'''
#-----------------------------------------------
class Node:
'''
Decision Tree Node (with discrete attributes)
Inputs:
X: the data instances in the node, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
i: the index of the attribute being tested in the node, an integer scalar
C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
isleaf: whether or not this node is a leaf node, a boolean scalar
p: the label to be predicted on the node (i.e., most common label in the node).
'''
def __init__(self,X,Y, i=None,C=None, isleaf= False,p=None):
self.X = X
self.Y = Y
self.i = i
self.C= C
self.isleaf = isleaf
self.p = p
#-----------------------------------------------
class Tree(object):
'''
Decision Tree (with discrete attributes).
We are using ID3(Iterative Dichotomiser 3) algorithm. So this decision tree is also called ID3.
'''
#--------------------------
@staticmethod
def entropy(Y):
'''
Compute the entropy of a list of values.
Input:
Y: a list of values, a numpy array of int/float/string values.
Output:
e: the entropy of the list of values, a float scalar
Hint: you could use collections.Counter.
'''
#########################################
## INSERT YOUR CODE HERE
c = Counter()
for y in Y:
c[y] = c[y]+1
list_Y = c.keys()
p_y = []
for y in list_Y:
p_y.append(c[y])
n = sum(p_y)
e = 0
for i in range(len(p_y)):
e += - p_y[i]/n * math.log((p_y[i]/n), 2)
#########################################
return e
#--------------------------
@staticmethod
def conditional_entropy(Y,X):
'''
Compute the conditional entropy of y given x.
Input:
Y: a list of values, a numpy array of int/float/string values.
X: a list of values, a numpy array of int/float/string values.
Output:
ce: the conditional entropy of y given x, a float scalar
'''
#########################################
## INSERT YOUR CODE HERE
cx = Counter(X)
list_X = cx.keys()
p_x = []
for x in list_X:
p_x.append(cx[x])
nx = sum(p_x)
XY = []
for (x, y) in zip(X, Y):
XY.append([x, y])
ce = 0
for x in list_X:
newy = []
for i in range(len(XY)):
if XY[i][0] == x:
newy.append(XY[i][1])
ce += cx[x] / nx * ( Tree.entropy(newy))
#########################################
return ce
#--------------------------
@staticmethod
def information_gain(Y,X):
'''
Compute the information gain of y after spliting over attribute x
Input:
X: a list of values, a numpy array of int/float/string values.
Y: a list of values, a numpy array of int/float/string values.
Output:
g: the information gain of y after spliting over x, a float scalar
'''
#########################################
## INSERT YOUR CODE HERE
g = Tree.entropy(Y) - Tree.conditional_entropy(Y, X)
#########################################
return g
#--------------------------
@staticmethod
def best_attribute(X,Y):
'''
Find the best attribute to split the node.
Here we use information gain to evaluate the attributes.
If there is a tie in the best attributes, select the one with the smallest index.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n. Each element can be int/float/string.
Output:
i: the index of the attribute to split, an integer scalar
'''
#########################################
## INSERT YOUR CODE HERE
glist = []
for i in range(len(X)):
g = Tree.information_gain(X[i,:],Y)
glist.append(g)
i = np.argmax(glist)
#########################################
return i
#--------------------------
@staticmethod
def split(X,Y,i):
'''
Split the node based upon the i-th attribute.
(1) split the matrix X based upon the values in i-th attribute
(2) split the labels Y based upon the values in i-th attribute
(3) build children nodes by assigning a submatrix of X and Y to each node
(4) build the dictionary to combine each value in the i-th attribute with a child node.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
i: the index of the attribute to split, an integer scalar
Output:
C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
'''
#########################################
## INSERT YOUR CODE HERE
Xi = X[i]
cXi = Counter(Xi)
list_Xi = cXi.keys()
C = {}
for x in list_Xi:
id = []
for j in range(len(X[0])):
if Xi[j] == x:
id.append(j)
# xt = X[:,j].T
# y = Y[j]
# xilist.append(xt)
# ylist.append(y)
# submatX = (np.matrix(xilist)).T
# submatY = np.array(ylist)
submatX = X[:,id]
submatY = Y[id]
C[x] = Node(submatX, submatY)
#########################################
return C
#--------------------------
@staticmethod
def stop1(Y):
'''
Test condition 1 (stop splitting): whether or not all the instances have the same label.
Input:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Output:
s: whether or not Conidtion 1 holds, a boolean scalar.
True if all labels are the same. Otherwise, false.
'''
#########################################
## INSERT YOUR CODE HERE
if np.all(Y == Y[0]):
s = True
else:
s = False
#########################################
return s
#--------------------------
@staticmethod
def stop2(X):
'''
Test condition 2 (stop splitting): whether or not all the instances have the same attributes.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Output:
s: whether or not Conidtion 2 holds, a boolean scalar.
'''
#########################################
## INSERT YOUR CODE HERE
if len(X[0]) == 1:
s = True
else:
x = X[:,0]
X2 = np.copy(X)
for j in range(len(X[0])):
X2[:,j] = x
if np.all(X == X2):
s = True
else:
s = False
#########################################
return s
#--------------------------
@staticmethod
def most_common(Y):
'''
Get the most-common label from the list Y.
Input:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Here n is the number data instances in the node.
Output:
y: the most common label, a scalar, can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
cY = Counter(Y)
top1 = cY.most_common(1)
y = top1[0][0]
#########################################
return y
#--------------------------
@staticmethod
def build_tree(t):
'''
Recursively build tree nodes.
Input:
t: a node of the decision tree, without the subtree built.
t.X: the feature matrix, a numpy float matrix of shape n by p.
Each element can be int/float/string.
Here n is the number data instances, p is the number of attributes.
t.Y: the class labels of the instances in the node, a numpy array of length n.
t.C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
'''
#########################################
## INSERT YOUR CODE HERE
t.p = Tree.most_common(t.Y)
# if Condition 1 or 2 holds, stop recursion
if Tree.stop1(t.Y) or Tree.stop2(t.X):
t.isleaf = True
t.i = None
t.C = None
return
else:
# t.isleaf = False
# find the best attribute to split
t.i = Tree.best_attribute(t.X, t.Y)
t.C = Tree.split(t.X, t.Y, t.i)
# recursively build subtree on each child node
for leaf in t.C:
Tree.build_tree(t.C[leaf])
#########################################
#--------------------------
@staticmethod
def train(X, Y):
'''
Given a training set, train a decision tree.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the training set, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Output:
t: the root of the tree.
'''
#########################################
## INSERT YOUR CODE HERE
t = Node(X,Y, i=None,C=None, isleaf= False,p=None)
Tree.build_tree(t)
#########################################
return t
#--------------------------
@staticmethod
def inference(t,x):
'''
Given a decision tree and one data instance, infer the label of the instance recursively.
Input:
t: the root of the tree.
x: the attribute vector, a numpy vectr of shape p.
Each attribute value can be int/float/string.
Output:
y: the class label, a scalar, which can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
# predict label, if the current node is a leaf node
if t.isleaf == True:
y = t.p
pass
else:
children = t.C
if children.get(x[t.i]) == None:
y = t.p
pass
else:
y = Tree.inference(children[x[t.i]],x)
#########################################
return y
#--------------------------
@staticmethod
def predict(t,X):
'''
Given a decision tree and a dataset, predict the labels on the dataset.
Input:
t: the root of the tree.
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the dataset, p is the number of attributes.
Output:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
# Y = np.empty(shape=(len(X[0])), dtype = 'str')
Y = []
for j in range(len(X[0])):
y = Tree.inference(t,X[:,j])
Y.append(y)
Y = np.array(Y)
#########################################
return Y
#--------------------------
@staticmethod
def load_dataset(filename='data1.csv'):
'''
Load dataset 1 from the CSV file: 'data1.csv'.
The first row of the file is the header (including the names of the attributes)
In the remaining rows, each row represents one data instance.
The first column of the file is the label to be predicted.
In remaining columns, each column represents an attribute.
Input:
filename: the filename of the dataset, a string.
Output:
X: the feature matrix, a numpy matrix of shape p by n.
Each element is a string.
Here n is the number data instances in the dataset, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element is a string.
Note: Here you can assume the data type is always str.
'''
#########################################
## INSERT YOUR CODE HERE
file = np.loadtxt(filename, dtype = str, delimiter = ',')
Y = file[1:,0]
X = file[1:,1:].T
#########################################
return X,Y
|
0bfc113811d704a2aad0b1698df54706fd8e8cb0 | ruifgomes/exercises | /numeros_10-20.py | 405 | 4 | 4 | #numeros de 10 a 20
#for sequencia in range(10,20):
# print(sequencia)
resultado = float(input("Insira o seu resultado: "))
if 0 >= resultado or resultado >= 20:
print("Resultado invalido")
elif resultado <= 10:
print("Insulficiente :( ")
elif resultado <= 14:
print("Bom :| ")
elif resultado >14:
print("Muito Bom :D ")
# print("Resultado de teste não correto")
|
f6f19b9d52b40d3f2f560d70864f669ca4da5df0 | vdaytona/UNSWResearch | /Fitting/FittingPowerSearchingMethod.py | 3,209 | 3.640625 | 4 | '''
Created on 15 Nov 2016
to fit the curve using power search method
@author: vdaytona
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from sklearn.metrics import r2_score
# 1. read in data
rawData = pd.read_csv(".\Data\data.csv", header = None)
x_data = rawData[0].values
x_data = [float(x) for x in x_data]
y_data = rawData[1].values
#weight_data = rawData[2].values
def func1(x,a,b,c,d):
return a + b * np.exp(-np.power((x/c),d))
def square_score_func1(x,y,a,b,c,d):
y_predict = []
for x_value in x:
y_predict.append(func1(x_value, a, b, c, d))
square_score_fitted = r2_score(y,y_predict)
#print square_score_fitted
return square_score_fitted
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
if __name__ == '__main__':
# 2. Preprocess if necessary
# 3. set the function and search range and interval of parameter
# function: a + b * exp(-(x/c)^d)
a_start = 0.00025
a_end = 0.00035
a_interval = 0.000005
a = [x for x in drange(a_start, a_end, a_interval)]
b_start = 0.0004
b_end = 0.0005
b_interval = 0.000005
b = [x for x in drange(b_start, b_end, b_interval)]
c_start = 1500
c_end = 3000
c_interval = 20
c = [x for x in drange(c_start, c_end, c_interval)]
d_start = 0.34
d_end = 0.44
d_interval = 0.01
d = [x for x in drange(d_start, d_end, d_interval)]
# 4. calculate the best combination due to correlation coefficient
loop = len(a) * len(b) * len(c) * len(d)
print loop
result = []
loop_now = 0
for a_value in a:
for b_value in b:
for c_value in c:
for d_value in d:
r2_square_fiited = square_score_func1(x_data,y_data,a_value,b_value,c_value,d_value )
result.append((a_value,b_value,c_value,d_value,r2_square_fiited))
loop_now +=1
print (str(loop) + " in all, now is " + str(loop_now) + " the r2_square is " + str(r2_square_fiited) + " , finished " + str(float(loop_now) / float(loop) * 100) + " percent ")
result_sorted = sorted(result, key = lambda result : result[4],reverse=True)
# 5. output the best 10000 result and all result
result_pd = pd.DataFrame(data=result_sorted)
timeNow = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
fileName_best = './Result/' + timeNow + '_FittingPowerSearch_best' + '.csv'
fileName_all = './Result/' + timeNow + '_FittingPowerSearch' + '.csv'
result_pd[0:20000].to_csv(fileName_best,header = None)
#result_pd.to_csv(fileName_all,header = None)
#result_pd = pd.to_csv
# 6. Draw the best result of fitting
#y_fit = []
#for x_value in x_data:
# y_fit.append(func1(x_value, result_sorted[0][0], result_sorted[0][1], result_sorted[0][2], result_sorted[0][3]))
#print result_sorted[0]
#print y_fit
#print y_data
#plt.plot(x_data, y_data)
#plt.plot(x_data,y_fit)
#plt.show() |
32531f0772951f2fd6642fe775445c7c29cc266e | vsevolodzakk/alien_invasion | /alien_game/ship.py | 1,996 | 3.734375 | 4 | import pygame
from pygame.sprite import Sprite
class Ship():
def __init__(self, game_settings, screen):
"""Инициирует корабль и задает его начальную позицию"""
self.screen = screen
self.game_settings = game_settings
# Загрузка изображения корабля
self.image = pygame.image.load('images/rocket.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#Saving ship center coordiantes
self.center = float(self.rect.centerx)
#Movement flag
self.moving_right = False
self.moving_left = False
def update(self):
"""Updates position according to flag state"""
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.game_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.game_settings.ship_speed_factor
self.rect.centerx = self.center
def blitme(self):
"""Рисует кораблю в текущей позиции"""
self.screen.blit(self.image, self.rect)
class Bullet(Sprite):
def __init__(self, game_settings, screen, ship):
"""Bullet object appears"""
super().__init__()
self.screen = screen
#Bullet creation in (0,0) position
self.rect = pygame.Rect(0, 0, game_settings.bullet_width, game_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#Bullet center coordiantes
self.y = float(self.rect.y)
self.color = game_settings.bullet_color
self.speed = game_settings.bullet_speed
def update(self):
"""Translate bullet on the screen"""
#Bullet position update in float
self.y -= self.speed
#Rect position update
self.rect.y = self.y
def draw_bullet(self):
"""Bullet on the screen"""
pygame.draw.rect(self.screen, self.color, self.rect) |
d109b9b4d0728b734b104b99d3d9ae19e6a4bf26 | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter2/chapter2_list_comprehensions_02.py | 189 | 3.515625 | 4 | from random import randint, seed
seed(10) # Set random seed to make examples reproducible
random_elements = [randint(1, 10) for i in range(5)]
print(random_elements) # [10, 1, 7, 8, 10]
|
c5ba4eb1584f0a92159ac2930bb899e45d45651d | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter11/chapter11_compare_operations.py | 366 | 3.65625 | 4 | import numpy as np
np.random.seed(0) # Set the random seed to make examples reproducible
m = np.random.randint(10, size=1000000) # An array with a million of elements
def standard_double(array):
output = np.empty(array.size)
for i in range(array.size):
output[i] = array[i] * 2
return output
def numpy_double(array):
return array * 2
|
eb0c93ebd736a18a087959cfd68d713e07a965a2 | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter4/chapter4_standard_field_types_01.py | 230 | 3.515625 | 4 | from pydantic import BaseModel
class Person(BaseModel):
first_name: str
last_name: str
age: int
person = Person(first_name="John", last_name="Doe", age=30)
print(person) # first_name='John' last_name='Doe' age=30
|
4f053e59411e550fde83e90311951c77f0143a0d | jackgoode123/variables | /what is your name.py | 160 | 3.875 | 4 | #jackgoode
#09-09-2014
#what is your name
first_name = input ("please enter your first name: ")
print (first_name)
print ("hi {0}!".format(first_name))
|
ddd45e09f38821920c652af1a89b10c607674806 | cem05/108 | /unique_conversionround.py | 1,186 | 4.03125 | 4 | #unique conversion problem, something different
#Currency Conversion to Euros from US Dollars
#1 EURO (EUR) = 1.2043 U.S. dollar (USD)
#from https://www.wellsfargo.com/foreign-exchange/currency-rates/ on 10/23/2018
print('This program can be used to convert to Euros from US Dollars.')
print('The exchage rate was taken from https://www.wellsfargo.com/foreign-exchange/currency-rates/ on 10/03/2018, and was 1 EURO (EUR) = 1.2187 U.S. dollar (USD)')
Euro = 1
USD = 1.2043
print('\n')
usd_exchanged = input('Enter amount of whole dollars to be converted: ')
usd_exchanged = int(usd_exchanged)
euro_received = usd_exchanged//USD
print('You receive',int(round(euro_received)),'Euros, rounded down to the nearest Euro, as we only convert to whole Euros.')
#conversion fee from WellsFargo is 7$ flat fee if converting under 1000 USD
#and free at or above 1000 USD and over free
print('The conversion fee from WellsFargo is 7$ flat fee if converting under 1000 USD and free at or above 1000 USD')
if usd_exchanged >= 1000: print('You owe Wells Fargo',(usd_exchanged),'dollars.')
if usd_exchanged < 1000: print('You owe Wells Fargo',(usd_exchanged + 7),'dollars.')
|
96df74099fa7a2432fb2796df8f440948bf76277 | f-bandet/Where-s-The-Money | /wheres_the_money.py | 4,730 | 4.21875 | 4 | ###
### Author: Faye Bandet
### Description: Welcome to Where's The Money! This is a program that helps a user
### visualize and understand how much money they spend of various categories of expenditures.
###
from os import _exit as exit
### Greeting statement
print ('-----------------------------')
print ("----- WHERE'S THE MONEY -----")
print ('-----------------------------')
### Checking for numbers
a_s = input ('What is your annual salary? \n')
if a_s.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
a_s = float (a_s)
m_r = input ('How much is your monthly mortgage/rent? \n')
if m_r.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
m_r = float (m_r)
b = input ('What do you spend on bills monthly? \n')
if b.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
b = float (b)
f = input ('What are your weekly grocery/food expenses? \n')
if f.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
f = float (f)
tr = input ('How much do you spend on travel annually? \n')
if tr.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
tr = float (tr)
ta = input ('Tax percentage? \n')
if ta.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
ta = float(ta)
### TAX STATEMENTS
### I added a lowercase x when I transitioned variables.
### Basic input functions
if(ta<100):
print()
tax = (ta / 100.0) * a_s
taxx = (tax / a_s) * 100
if ta <0 or ta >100:
print ('Tax must be between 0% and 100%.')
exit (0)
m_rx = ((m_r * 12) / a_s) * 100
bx = ((b * 12) / a_s) * 100
fx = ((f * 52) / a_s) * 100
trx = ((tr) / a_s) * 100
e = (a_s) - (m_r * 12) - (b * 12) - (f * 52) - (tr) - (tax)
ex = (e / a_s) * 100
### Print the financial break down statement
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
print ('See the financial breakdown below, based on a salary of', '$' + format(a_s, '.0f'))
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
###formatting
print('| mortgage/rent | $' + format (m_r * 12, '10,.0f'), '|' +
format (m_rx, '6,.1f') + '% |', '#' * int (m_rx))
print('| bills | $' + format (b * 12, '10,.0f'), '|' +
format (bx, '6,.1f') + '% |', '#' * int (bx))
print('| food | $' + format (f * 52, '10,.0f'), '|' +
format (fx, '6,.1f') + '% |', '#' * int (fx))
print('| travel | $' + format (tr, '10,.0f'), '|' +
format (trx, '6,.1f') + '% |', '#' * int (trx))
print('| tax | $' + format (tax, '10,.1f'), '|' +
format (taxx, '6,.1f') + '% |', '#' * int (taxx))
print('| extra | $' + format (e, '10,.1f'), '|' +
format (ex, '6,.1f') + '% |', '#' * int (ex))
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
exit (0) |
a35e944774f76b40797b0d0b03cd97159e2a9a9b | SYiH/little_games_things | /knb.py | 2,356 | 3.90625 | 4 | import random, sys
while True:
while True:
b=('камень','ножницы','бумага')
usr=input('Камень, ножницы или бумага? Для выхода: "Выход" ')
usr=usr.lower()
if usr=='выход':
sys.exit()
elif usr.isalpha()==False:
print('Неверное значение, попробуйте снова.')
elif usr not in b:
print('Неверное значение, попробуйте снова.')
else:
break
pc=random.choice(b)
usr=usr.capitalize()
pc=pc.capitalize()
if pc==usr:
print('Ничья')
elif usr=='Ножницы' and pc=='Бумага': #Ножницы и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
elif usr=='Бумага' and pc=='Ножницы': #Ножницы и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Камень' and pc=='Ножницы': #Ножницы и камень
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
elif usr=='Ножницы' and pc=='Камень': #Ножницы и камень
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Камень' and pc=='Бумага': #Камень и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Бумага' and pc=='Камень': #Камень и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
#else:
# while True:
# print('FATAL ERROR, DESTRUCTING PC')
|
671ee10d18931cda87cf94638f47747616eaed1c | RyanFatsena/Python_C11_BekerjaDenganDateTime | /Prak1C11.py | 601 | 3.84375 | 4 | #1
from datetime import *
def diffDate(i) :
listTgl = i.split("-")
dateList = []
for x in listTgl :
dateList.append(int(x))
kemarin = date(dateList[0], dateList[1], dateList[2])
hariIni = datetime.date(datetime.now())
delta = kemarin - hariIni
hasil = delta.days
return hasil
try :
tanggal = input("Masukkan tanggal yang anda inginkan berformat (yyyy-mm-dd) : ")
hasil = diffDate(tanggal)
print("Selisih tanggal {0} dengan hari ini adalah {1} hari".format(tanggal, hasil))
except ValueError :
print("Masukkan tanggal yang benar")
|
aad0123b1cbabad5f0fb0f9196628f0a853d28bb | jsteinhauser/Transparent-conductor-solver | /TClayer_GUI.py | 4,917 | 3.515625 | 4 | ## Import
import tkinter as tk
import TClayer as TC
from decimal import Decimal
## GUI
class GUI(tk.Frame):
""" Main GUI heritate from tkinter Frame """
def __init__(self): # Constructor
self.mainFrame = tk.Frame().pack() # Main frame
self.buildGUI() # launch widget builder
def stdInput (self, text):
""" helper function to build a std label-entry"""
self.entryFrame = tk.Frame(self.mainFrame)
tk.Label(self.entryFrame,text=text,width=25,anchor=tk.E).pack(side=tk.LEFT)
self.myEntry = tk.Entry(self.entryFrame,width=10)
self.myEntry.pack(side=tk.LEFT,padx=5,pady=2)
self.entryFrame.pack(side=tk.TOP)
return self.myEntry
def buildGUI (self):
""" Build the GUI """
self.picture = tk.PhotoImage(file = "Formula.gif")
formula = tk.Label(self.mainFrame,image=self.picture,
background="white")
formula.pack(anchor=tk.E, fill=tk.X)
tk.Label(self.mainFrame,background="white",
text="\nEnter known parameters and press 'solve'\n").pack(anchor=tk.E, fill=tk.X)
self.inputList = ['Thickness (nm) :',
'Sheet resistance (Ohms-square) :',
'Resistivity (Ohms.cm) :',
'Conductivity (S) :',
'Mobility (cm2.V-1.s-1) :',
'Carrier density (cm-3) :'
]
self.entries=[]
for str in self.inputList :
self.thisEntry = self.stdInput(str)
self.entries.append(self.thisEntry)
self.buttonFrame=tk.Frame()
self.clearAllButton = tk.Button(self.buttonFrame,text="Clear", width=12,
command=self.clearAll)
self.clearAllButton.bind("<Return>", self.clearAllWrapper)
self.clearAllButton.pack(side=tk.LEFT,padx=5)
self.solveButton=tk.Button(self.buttonFrame,text="Solve", width=12,
command=self.solve)
self.solveButton.bind("<Return>", self.solveWrapper)
self.solveButton.pack(side=tk.LEFT,padx=5)
self.solveButton.focus_force()
self.buttonFrame.pack(anchor=tk.E,pady=7)
self.msg = tk.StringVar()
self.statusBar = tk.Label(self.mainFrame,background="gray",
textvariable=self.msg, justify=tk.LEFT)
self.statusBar.pack(anchor=tk.E, fill=tk.X)
# Callbacks
def solveWrapper(self,event):
self.solve()
def solve(self):
""" Solve and display"""
values=[] # Get values
for object in self.entries:
val = object.get()
try:
val=float(val)
values.append(val)
except ValueError:
values.append(None)
thisTC = TC.TClayer(values[0],values[1],values[2],
values[3],values[4],values[5]) # Instantiate a TClayer
thisTC.solve() # Solve it
values=[thisTC.getThickness(), # Get the output values
(thisTC.getSheetResistance()),
(thisTC.getResistivity()),
(thisTC.getConductivity()),
(thisTC.getMobility()),
(thisTC.getCarrierDensity())]
i=0
for object in self.entries: # Display output values
object.delete(0,tk.END) # Delete entry content
if i in [0,3]:
try:
object.insert(0,"%.0f"%values[i]) # Display and format the output value if exist
except:
pass
if i in [1,4]:
try:
object.insert(0,"%.1f"%values[i])
except:
pass
if i in [2]:
try:
object.insert(0,"%.2e"%values[i])
except:
pass
if i in [5]:
try:
object.insert(0,"%.1e"%values[i])
except:
pass
i=i+1
self.msg.set(thisTC.getMsg()[:-1])
def clearAllWrapper(self,event):
self.clearAll()
def clearAll(self):
""" clear all entries """
for object in self.entries:
object.delete(0,tk.END)
self.msg.set("")
## init GUI
root = tk.Tk() # Build main window
root.title("TC-solver")
app = GUI() # Instantiate the GUI
root.mainloop() # Run event loop on main window
|
a18a4d56a8863c6112864ba0958ece31ea5d24d7 | longshuicui/leetcode-learning | /04.排序/692. 前K个高频单词(Medium).py | 1,435 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/5/20
@function:
692. 前K个高频单词 (Medium)
https://leetcode-cn.com/problems/top-k-frequent-words/
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。 注意,按字母顺序 "i" 在 "love" 之前。
示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,出现次数依次为 4, 3, 2 和 1 次。
"""
def topKFrequent(words, k):
freq={} # 时间复杂度O(n), 空间复杂度O(l)
for word in words:
freq[word]=freq.get(word,0)+1
freq=sorted(freq.items(), key=lambda x:x[0], reverse=False) # 时间复杂度O(nlogn),空间复杂度O(logn)
freq=sorted(freq, key=lambda x:x[1], reverse=True) # # 时间复杂度O(nlogn),空间复杂度O(logn)
res=[]
for i in range(k):
res.append(freq[i][0])
return res
words=["i", "love", "leetcode", "i", "love", "coding"]
k=3
res=topKFrequent(words, k)
print(res) |
0826e56877d23ee9a6012dd2d8f0f89d0367fed5 | longshuicui/leetcode-learning | /01.贪心算法/区间问题/763.Partition Labels (Medium).py | 1,048 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/02/15
@function:
763. Partition Labels (Medium)
https://leetcode.com/problems/partition-labels/
A string S of lowercase English letters is given.
We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
"""
def partitionLabels(s):
# 统计每个字母出现的始末位置,变成区间问题
last={c:i for i,c in enumerate(s)}
j=anchor=0
ans=[]
for i,c in enumerate(s):
j=max(j,last[c])
if i==j:
ans.append(i-anchor+1)
anchor=i+1
return ans
s="ababcbacadefegdehijhklij"
res=partitionLabels(s)
print(res)
|
19c9392ec1edf3b17fec038531959b09e3184bdd | longshuicui/leetcode-learning | /08.数据结构/数组/48.Rotate Image (Medium).py | 944 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/3
@function:
48. Rotate Image (Medium)
https://leetcode.com/problems/rotate-image/
题目描述
给定一个 n × n 的矩阵,求它顺时针旋转 90 度的结果,且必须在原矩阵上修改(in-place)。O(1)空间复杂度
输入输出样例
输入和输出都是一个二维整数矩阵。
Input:
[[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[[7,4,1],
[8,5,2],
[9,6,3]]
题解
每次只考虑四个间隔90度的位置,可以进行O(1)的额外空间旋转
"""
def rotate(matrix):
n=len(matrix)-1
for i in range(n//2+1):
for j in range(i,n-i):
matrix[j][n-i],matrix[i][j],matrix[n-j][i],matrix[n-i][n-j]=\
matrix[i][j],matrix[n-j][i],matrix[n-i][n-j],matrix[j][n-i]
return matrix
matrix=[[1,2,3],[4,5,6],[7,8,9]]
matrix=rotate(matrix)
print(matrix) |
d32283fbe67015b2ac7c4aefeedda87da1acd33b | longshuicui/leetcode-learning | /08.数据结构/优先队列(堆排序)/priority_queue.py | 2,033 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/4
@function:
优先队列
可以在O(1)时间内获得最大值,并且在O(logn)时间内取出最大值和插入任意值
优先队列常常用堆来实现。堆是一个完全二叉树。其父节点的值总是大于等于子节点的值。堆得实现用数组 ,
堆的实现方法:
核心操作是上浮和下沉 :如果一个节点比父节点大,那么交换这两个节点;交换过后可能还会比新的父节点大,
因此需要不断的进行比较和交换操作,这个过程叫上浮;类似的,如果一个节点比父节点小,也需要不断的向下
比较和交换操作,这个过程叫下沉。如果一个节点有两个子节点,交换最大的子节点。
维护的是数据结构的大于关系
"""
class PriorityQueue:
def __init__(self,maxSize):
"""初始化一个数组,构建完全二叉树"""
self.heap=[]
self.maxSize=maxSize
def top(self):
"""返回堆的根节点-最大值"""
return self.heap[0]
def swim(self,pos):
"""上浮"""
while pos>1 and self.heap[pos//2]<self.heap[pos]:
self.heap[pos//2], self.heap[pos]=self.heap[pos],self.heap[pos//2]
pos//=2
def sink(self,pos):
while 2*pos<=self.maxSize:
i=2*pos
if i<self.maxSize and self.heap[i]<self.heap[i+1]:
i+=1
if self.heap[pos]>=self.heap[i]:
break
self.heap[pos], self.heap[i]=self.heap[i], self.heap[pos]
pos=i
def push(self, k):
"""插入任意值,把新的数字放在最后一位ie,然后上浮"""
self.heap.append(k)
self.swim(len(self.heap)-1)
def pop(self):
self.heap[0], self.heap[-1]=self.heap[-1], self.heap[0]
self.heap.pop()
self.sink(0)
queue=PriorityQueue(10)
values=[5,4,8,6,2,7,1,3]
for val in values:
queue.push(val)
print(queue.heap) |
d37fd9b2691a2cb11cd6c6d92fd428e32b773153 | longshuicui/leetcode-learning | /09.字符串/字符串比较/242.Valid Anagram (Easy).py | 907 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/7
@function:
242. Valid Anagram (Easy)
https://leetcode.com/problems/valid-anagram/
题目描述
判断两个字符串包含的字符是否 完全相同 (不考虑顺序)。
输入输出样例
输入两个字符串,输出一个布尔值,表示两个字符串是否满足条件。
Input: s = "anagram", t = "nagaram"
Output: true
题解
使用哈希表或者数组统计两个字符串中每个字符出现的 频次 ,若频次相同 则说明他们包含的字符完全相同
"""
def isAnagram(s,t):
if len(s)!=len(t):
return False
counts={chr(i):0 for i in range(97,97+26)}
for i in range(len(s)):
counts[s[i]]+=1
counts[t[i]]-=1
for c in counts:
if counts[c]:
return False
return True
s = "anagram"
t = "nagaram"
ans=isAnagram(s,t)
print(ans) |
4c368fcf33423a8da4337c71271649d8cdcb93f4 | longshuicui/leetcode-learning | /12.数学/263. 丑数(Easy).py | 786 | 4 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/04/10
@function:
263. 丑数 (Easy)
https://leetcode-cn.com/problems/ugly-number/
给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
示例 1:
输入:n = 6
输出:true
解释:6 = 2 × 3
示例 2:
输入:n = 8
输出:true
解释:8 = 2 × 2 × 2
示例 3:
输入:n = 14
输出:false
解释:14 不是丑数,因为它包含了另外一个质因数 7 。
"""
def isUgly(n):
if n<=0:
return False
for factor in [2,3,5]:
while n%factor==0:
n//=factor
return n==1
n=14
res=isUgly(n)
print(res) |
8e60d212527da25dfcd1d7b46706012f552c61c5 | longshuicui/leetcode-learning | /10.链表/160.Intersection of Two Linked Lists (Easy).py | 1,379 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/8
@function:
160. Intersection of Two Linked Lists (Easy)
https://leetcode.com/problems/intersection-of-two-linked-lists/
题目描述
给定两个链表,判断它们是否相交于一点,并求这个相交节点。
输入输出样例
输入是两条链表,输出是一个节点。如无相交节点,则返回一个空节点。
题解
假设链表A的头节点到相交点的距离为a,距离B的头节点到相交点的距离为b,相交点到
链表终点的距离为c。我们使用两个指针,分别指向两个链表的头节点,并以相同的速度
前进,若到达链表结尾,则移动到另一条链表的头节点继续前进。按照这种方法,两个
指针会在a+b+c次前进后到达相交节点。
利用环路去做
"""
class ListNode:
def __init__(self, value, next=None):
self.value = value
self.next = next
def getIntersectionNode(headA, headB):
if headA is None or headB is None:
return None
l1, l2=headA, headB
while l1!=l2:
l1=l1.next if l1 else headB
l2=l2.next if l2 else headA
return l1
a=[1,9,1,2,4]
b=[3,2,4]
head=ListNode(2,ListNode(4))
headA=ListNode(1,ListNode(9,ListNode(1,head)))
headB=ListNode(3,head)
node=getIntersectionNode(headA,headB)
print(node.value)
|
d76d149e9719c27d2bb11132aaf4453ce9394974 | longshuicui/leetcode-learning | /06.动态规划/子序列问题/300.Longest Increasing Subsequence (Medium).py | 1,557 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/2
@function:
300. Longest Increasing Subsequence (Medium)
https://leetcode.com/problems/longest-increasing-subsequence/
题目描述
给定一个未排序的整数数组,求 最长 的 递增 子序列的长度。
注意 按照 LeetCode 的习惯,子序列(subsequence)不必连续,子数组(subarray)或子字符串
(substring)必须连续。
输入输出样例
输入是一个一维数组,输出是一个正整数,表示最长递增子序列的长度。
Input: [10,9,2,5,3,7,101,18]
Output: 4
在这个样例中,最长递增子序列之一是 [2,3,7,18]。
题解
求最长上升子序列的长度, 动态规划
第一种方法,定义一个dp数组,其中dp[i]表示以i结尾的子序列的性质。在处理好每个位置之后,统计一遍各个位置的结果
可以得到题目要求的结果。对于每一个位置i,如果其之前的某个位置j所对的数字小于所对应的数字,则我们可以获得一个以
i结尾的长度为dp[j]+1的子序列。需要遍历两遍, 时间复杂度为O(n**n)
"""
def lengthOfLIS(nums):
max_length=0
if len(nums)<=1:
return len(nums)
dp=[1 for _ in range(len(nums))]
for i in range(len(nums)):
for j in range(0,i):
if nums[i]>nums[j]:
dp[i]=max(dp[i],dp[j]+1)
max_length=max(max_length,dp[i])
return max_length
nums=[10,9,2,5,3,7,101,18]
res=lengthOfLIS(nums)
print(res)
|
20ad59679e55cafeda0c21e4bc11a2abeb5255e5 | longshuicui/leetcode-learning | /03.二分查找/1011. 在 D 天内送达包裹的能力(Medium).py | 1,734 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/4/26
@function:
1011. 在 D 天内送达包裹的能力 (Medium)
https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i个包裹的重量为weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8
第 4 天:9
第 5 天:10
请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], D = 3
输出:6
示例 3:
输入:weights = [1,2,3,1,1], D = 4
输出:3
题解:
二分查找判定
"""
def shipWithinDays(weights, D):
left, right = max(weights), sum(weights)
while left <= right:
mid = left + (right - left) // 2
curr, day = 0, 0
for weight in weights:
if curr + weight > mid:
day += 1
curr = 0
curr += weight
day += 1
if day <= D:
right = mid - 1
else:
left = mid + 1
return left
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D = 5
res = shipWithinDays(weights, D)
print(res)
|
dfa2c9a903d36e9c0d41e5112cc689e2fa44f969 | longshuicui/leetcode-learning | /06.动态规划/分割类型题/139.Word Break (Medium).py | 1,203 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/2
@function:
139. Word Break (Medium)
https://leetcode.com/problems/word-break/
题目描述
给定一个字符串和一个字符串集合,求是否存在一种分割方式,使得原字符串分割后的子字
符串都可以在集合内找到。
输入输出样例
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
在这个样例中,字符串可以被分割为 [“apple” ,“pen” ,“apple” ]
题解
类似于完全平方分割问题,分割条件由集合内的字符串决定,因此在考虑每个分割位置时,需要遍历字符串集合。
以确定当前位置是否可以成功分割。对于位置0,需要初始化为真
"""
def wordBreak(s, wordDict):
dp=[False]*(len(s)+1)
dp[0]=True # 初始位置初始化为真
for i in range(1,len(s)+1):
for word in wordDict:
if i>=len(word) and s[i-len(word):i]==word:
dp[i]=dp[i] or dp[i-len(word)]
return dp[len(s)]
s = "leetcode"
wordDict = ["leet", "code"]
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
res=wordBreak(s, wordDict)
print(res) |
c6a9c8a6da02b290fb10bfcb5e7145aeab575fc8 | longshuicui/leetcode-learning | /03.二分查找/旋转数组找数字/540.Single Element in a Sorted Array (Medium).py | 1,137 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/18
@function:
540. Single Element in a Sorted Array (Medium)
https://leetcode.com/problems/single-element-in-a-sorted-array/
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
Follow up: Your solution should run in O(log n) time and O(1) space.
在时间复杂度为O(logn)和空间复杂度为O(1)的条件下找出只出现一次的数字
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Input: nums = [3,3,7,7,10,11,11]
Output: 10
因为是O(logn)的时间复杂度,不可以使用位操作,使用二分搜索来做
数组里面的数字要么出现一次,要么出现两次
"""
def singleNonDuplicate(nums):
if len(nums) == 1:
return nums[0]
l,r=0, len(nums)-1
while l<=r:
if nums[l]!=nums[l+1]:
return nums[l]
if nums[r]!=nums[r-1]:
return nums[r]
l+=2
r-=2
return -1
nums=[3,3,7,7,10,11,11]
num=singleNonDuplicate(nums)
print(num) |
23fec7cac2c6dae1931577d195e554638a949702 | longshuicui/leetcode-learning | /07.位运算/477. 汉明距离总和(Medium).py | 1,374 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/5/28
@function:
477. 汉明距离总和 (Medium)
https://leetcode-cn.com/problems/total-hamming-distance/
两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。
计算一个数组中,任意两个数之间汉明距离的总和。
示例:
输入: 4, 14, 2
输出: 6
解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系)
所以答案为:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
"""
def totalHammingDistanceBrute(nums):
"""暴力求解 时间复杂度为O(n^2logC)"""
def hammingDistance(x, y):
diff = x ^ y
ans = 0
while diff:
ans += diff & 1
diff >>= 1
return ans
ans=0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
ans+=hammingDistance(nums[i],nums[j])
return ans
def totalHammingDistance(nums):
"""第i位的汉明距离c*(n-c),c为第i位为1的个数"""
ans=0
for i in range(30):
c=0
for val in nums:
c+=(val>>i)&1 # 统计第i位为1的个数
ans+=c*(len(nums)-c)
return ans
nums=[4,14,2]
res=totalHammingDistanceBrute(nums)
print(res) |
f8133e1eceeec54774ed972bd87e50f3b6da3f6f | billillib/100daysofcode-with-python-course | /days/13-15-text-games/code/game.py | 2,595 | 3.96875 | 4 | import random
def main():
print_header()
ask_player_name()
game_loop(create_rolls())
class Roll:
def __init__(self, name):
self.name = name
self.beats = None
self.loses = None
def can_defeat(self, beats):
if self.beats == beats:
return True
else:
return False
def loses_to(self, loses):
if self.loses == loses:
return True
else:
return False
def print_header():
print("Welcome to the awesome game of ROCK PAPER SCISSORS!!!")
def ask_player_name():
name = input("What is your name: ")
continue_game = input(f'are you ready to rock {name}? Type YES or NO: ')
if continue_game.upper() == 'YES':
print('Heck YEA!')
else:
print(f'Bye {name}...')
exit()
def create_rolls():
paper = Roll('Paper')
rock = Roll('Rock')
scissors = Roll('Scissors')
paper.beats = rock
paper.loses = scissors
rock.beats = scissors
rock.loses = paper
scissors.beats = paper
scissors.loses = rock
return paper, rock, scissors
def player_input(rolls):
choice = input("[R]ock, [P]aper, [S]cissors: ")
if choice.upper() == 'R':
return rolls[1]
elif choice.upper() == 'P':
return rolls[0]
elif choice.upper() == 'S':
return rolls[2]
else:
print("Invalid input")
def computer_input(rolls):
computer = random.choice(rolls)
return computer
def game_action(player, computer):
print(f'You chose {player.name}, computer chose {computer.name}')
if player.can_defeat(computer):
print('You won!')
return 1
elif player.loses_to(computer):
print('You lost!')
return 0
else:
print('Tie!')
return -1
def game_loop(rolls):
tracker = {'player': 0, 'computer': 0, 'tie': 0}
count = 0
while count < 3:
computer_roll = computer_input(rolls)
player_roll = player_input(rolls)
outcome = game_action(player_roll, computer_roll)
if outcome == 1:
tracker["player"] += 1
elif outcome == 0:
tracker["computer"] += 1
else:
tracker["tie"] += 1
count += 1
# print(tracker)
if tracker.get("player") > tracker.get("computer"):
print("YOU WON THE WHOLE THING!")
elif tracker.get("player") < tracker.get("computer"):
print("YOU LOST TO A COMPUTER OMG")
else:
print("HOW DID YOU TIE THREE TIMES IN A ROW??!?")
if __name__ == '__main__':
main()
|
8551d1220dd96bc945ca0272ffe8c797184d7504 | Manisha269/Test | /BackendTask.py | 561 | 3.828125 | 4 | input_string = input("Enter leads of various company: ")
userList = input_string.split(",")
def leads(User_list):
Lead_list={}
count={}
for i in User_list:
domain_name=i[i.index('@')+1:]
name=i[0:i.index('@')]
if(domain_name not in Lead_list):
Lead_list[domain_name]=[]
Lead_list[domain_name].append(name)
count[domain_name]=1
else:
Lead_list[domain_name].append(name)
count[domain_name]+=1
return Lead_list, count
print(leads(userList))
|
e3ab01a2ae4cb41fed9a8f34ca37b7c83c009304 | atominize/textbites | /textbites/api.py | 4,818 | 3.671875 | 4 | #!/usr/bin/env python
"""
API for textual resources. These are abstract base classes.
"""
from collections import namedtuple
class Resource:
""" Represents a textual resource which can provide references into it.
"""
def name(self):
""" Name is the pretty of the top reference.
"""
return self.top_reference().pretty()
def reference(self, string_ref):
""" Parse this string reference and return an object.
Supports the following formats:
Chapter N
chapter N
N
Chapter N:M
Chapter N:M-P
Doesn't support chapter range
Doesn't support open ended line ranges
Currently doesn't do any validation.
"""
raise NotImplementedError()
def top_reference(self):
""" Top-most reference for this resource, which can be traversed.
"""
raise NotImplementedError()
class Reference(object):
""" Represents some section of text.
NOTE: in future may want to add:
- parent()
- get_number() (e.g. line number), though
the goal is that the impl doesn't need to have that level of
detail.
- next()/prev() - for walking the chain
"""
def __init__(self):
# set parent for children
if self.children():
for child in self.children():
#print "Setting parent of %s to %s" % (child, self)
child._parent = self
def resource(self):
""" Return the resource that this is part of.
"""
return self.root()._resource
def pretty(self):
""" Return a canonical string of this reference.
"""
raise NotImplementedError()
def path(self):
""" Default relative path is pretty() except for root. This is
because resources are already namespaced under their resource
name which is this top level description.
"""
if self == self.root():
return ""
return self.pretty()
def short(self):
""" Shorter version of pretty with relative information.
e.g. a line would only include its number.
"""
return self.pretty()
def text(self):
""" Return string of the text corresponding to this reference.
Should probably be unsupported for entire book.
NOTE: how do we promise to handle whitespace? Currently,
line ranges are joined by lines.
"""
raise NotImplementedError()
def search(self, pattern):
""" Return list of Reference which match within this scope, which
indicate line matches.
"""
raise NotImplementedError()
def children(self):
""" Return an iterable of References under this item.
"""
raise NotImplementedError()
def parent(self):
""" Return parent reference or None.
For this, subclasses must have called Reference's ctor.
"""
try:
return self._parent
except:
return None
def root(self):
""" Top-most reference.
"""
top = self
while top.parent() != None:
top = top.parent()
return top
def previous(self):
""" Return reference for previous or None.
For this, subclasses must have called Reference's ctor.
"""
if self.parent():
try:
idx = self.parent().children().index(self)
if idx != -1 and idx >= 1:
return self.parent()[idx-1]
except:
pass
return None
def next(self):
""" Return reference for next or None.
For this, subclasses must have called Reference's ctor.
"""
if self.parent():
try:
idx = self.parent().children().index(self)
if idx != -1 and idx+1 < len(self.parent()):
return self.parent()[idx+1]
except:
pass
return None
def indices(self):
""" Return a pair of integers representing the order of this reference
within the resource. Used for determining overlap between references
in the database. Base on start and end.
Defined recursively, so only lowest level needs an overridden impl.
"""
return Index(self.children()[0].indices().start,
self.children()[-1].indices().end)
def __len__(self):
if self.children():
return len(self.children())
return 0
def __getitem__(self, key):
return self.children()[key]
def __str__(self):
return "%s:%s" % (type(self), self.pretty())
def __nonzero__(self):
""" Don't want evaluation based on len(). """
return 1
Index = namedtuple('Index', ['start', 'end'])
class UnparsableReferenceError(Exception):
""" Reference format is not supported.
"""
def __init__(self, val=""):
self.val = val
def __str__(self):
return repr(self.val)
class InvalidReferenceError(Exception):
""" Reference is out of bounds.
"""
def __init__(self, val=""):
self.val = val
def __str__(self):
return repr(self.val)
|
922071d30c161c1519d7f19910aabf7ba985ae03 | FRCTeam1571/Robot2017_Offseason | /Trevor/Interface/runrobotWIP.py | 2,840 | 3.796875 | 4 | #!/usr/bin/env python3
# coding=utf-8
import os
import platform # this is to detect the operating system for cross-platform compatibility
os.system('color f9')
@staticmethod
def error():
""" this is used when the program breaks or for stopping the command prompt from closing. """
print("")
input("Press Enter")
class Statics:
""" this is just a class full of static methods """
@staticmethod
def brk():
"""
this is used to add the line break. its just to save writing code
"""
print('')
print('')
print('')
print('')
def target_file():
"""
this attempts to find the file specified by the user.
:returns: file path of robot file
:rtype: str
"""
global fn, fpath
print("please input file name [should be 'robot.py'. you may click enter for the default}")
fn = input(": ")
if fn is "":
fn = "robot.py"
ext = ".py" #Checks for .py file extension
if ext not in fn:
fn = fn+ext
print("Is the program in this folder? [y/n]")
fpq = input(": ")
if fpq.lower() == 'n':
os.chdir
fpath = input("enter file path: ")
else:
fpath = os.path.join(os.path.dirname(__file__))
print(fpath)
Statics.brk()
return (fn, fpath)
def run_mode():
pass
def platCheck():
""" allows for cross-platform support though the assignment of variables """
global clear
platname = platform.system()
if platname == 'Linux':
clear = 'clear'
# Linux
elif platname == 'Darwin':
clear = 'clear'
#This is experimental. None of us know how to use OSX or have it.
# MAC OS X
elif platname == 'Windows':
clear = 'cls'
# Windows
else:
print("What is your OS?")
print("A. Linux")
print("B. Mac OS/ OSX")
print("C. Windows")
osq = input(": ")
if osq == "A" or osq == "a":
clear = 'clear'
if osq == "B" or osq == "b":
clear = 'clear'
if osq == "C" or osq == "c":
clear = 'cls'
return clear
platCheck() #Called for testing
os.system(clear)
print("\n \n \n \n Welcome to the CALibrate Robotics Robot UI\n")
Statics.brk()
target_file()
os.chdir(fpath)
run_mode()
""" THE LAND OF STUFF TO DO """
# TODO search for file name in super, child, and current dir [use current as primary]
# TODO set to save a config file. More options setting for program reset, self test, and others.
# TODO make separate menus for specific things in the UI
# TODO make it actually run the robot based off of the OS. have to figure out os.system() variable issue first.
# TODO make a way to find if the user has RobotPy and PyGame installed
"""
Made by:
Trevor W. - Team 1571
Ethan A. - Team 5183
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.