blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
50e9615b9201501c9544c17337e2e0cfeb6a51bb
inverse18/algorithmsPractice1
/max_subarr_recursive.py
1,951
3.546875
4
A = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7] B = [-3, -9, -14, -4, -21, -5, -1, -1, -5, -6, -8] def find_maximum_crossing_subarray(A, i_begin, i_mid, i_end): # leftSum and iLeft each stores the maximum sum of the form (....iMid) and the beginning index of the sum. i_left = i_mid left_sum = A[i_left] # i is the iterating variable and sum stores the sum from index i to iMid. i = i_left sum = left_sum while i > i_begin: i -= 1 sum += A[i] if sum > left_sum: left_sum = sum i_left = i i_right = i_mid + 1 right_sum = A[i_right] i = i_right sum = right_sum while i < i_end: i += 1 sum += A[i] if sum > right_sum: right_sum = sum i_right = i return i_left, i_right, left_sum+right_sum def find_maximum_subarray(A, i_begin, i_end): # base step if i_begin == i_end: if A[i_begin] >= 0: return i_begin, i_end, A[i_begin] else: return -1, -1, 0 # recursive step else: i_mid = (i_begin + i_end)//2 (left_low, left_high, left_sum) = find_maximum_subarray(A, i_begin, i_mid) (right_low, right_high, right_sum) = find_maximum_subarray(A, i_mid+1, i_end) (cross_low, cross_high, cross_sum) = find_maximum_crossing_subarray(A, i_begin, i_mid, i_end) # compare the results. if left_sum >= cross_sum and left_sum >= right_sum: return left_low, left_high, left_sum elif right_sum >= cross_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_low, cross_high, cross_sum (i_from, i_to, arr_sum) = find_maximum_subarray(A, 0, len(A)-1) print("a maximum nonempty subarray is:") print(A[i_from:i_to + 1]) print("the sum is:") print(arr_sum)
ee116181f0400e0756192430c55ae2cb2e5848f1
DhanushaRamesh/CodeKata
/spsymbol.py
281
3.5625
4
class countofsp: def symbol(self,str): count=0 for i in range(0,len(str)): if str[i].isalpha(): continue elif str[i].isdigit(): continue elif str[i]==" ": continue else: count+=1 print(count) str=input() call=countofsp() call.symbol(str)
9bbd25ef694b8235c38c1b8af0e1bf9432f1c117
SnallQiu/algorithm
/insert/insert .py
434
3.828125
4
def insert(list): length = len(list) for i in range(1,length): if list[i]<list[i-1]: index = i #记录插入的位置 value = list[i] #记录插入的值 while index>0 and list[index-1]>value: list[index] = list[index-1] index -= 1 list[index] = value return list list = [5,71,222,44,] print(insert(list))
1e430c9a087289785bb110cba82a23f879de90a5
815382636/codebase
/leetcode/Solution45.py
847
3.59375
4
from typing import List class Solution: # 贪心 def jump(self, nums: List[int]) -> int: step, maxvalue, end = 0, 0, 0 for i in range(len(nums) - 1): maxvalue = max(maxvalue, i + nums[i]) if i == end: step += 1 end = maxvalue return step # 动态规划 # def jump(self, nums: List[int]) -> int: # row = len(nums) # if row == 1: # return 0 # for i in range(row - 2, -1, -1): # if row - 1 - i <= nums[i]: # nums[i] = 1 # elif nums[i] == 0: # nums[i] = float('inf') # else: # nums[i] = 1 + min(nums[i + 1:i + nums[i] + 1]) # return nums[0] if __name__ == '__main__': s = Solution() print(s.jump([2, 3, 1, 1, 4]))
044ff83782118b2242140e5b4ed089beb2377f56
Schmidty002/Ch.09_Functions
/9.0_Jedi_Training.py
2,797
4.09375
4
# Sign your name: Joe Schmidt # 1.) Correct the following code: (The user's number should be increased by 1 and printed.) # def increase(x): # return x + 1 # # num = input("Enter a number: ") # increase(x) # print("Your number has been increased to", x) # def increase(num): # global x # x = num + 1 # return x # # # num = int(input("Enter a number: ")) # increase(num) # print("Your number has been increased to", x) def increase(x): return x + 1 num = int(input("Enter a number: ")) increase(num) print("Your number has been increased to", num) # 2.) Correct the following code to print 1-10: # def count_to_ten: # for i in range[10]: # print(i) # # count_to_ten() def count_to_ten(): for i in range(1, 11): print(i) count_to_ten() # 3.) Correct the following code to sum the list: # def sum_list(list): # for i in list: # sum = i # return sum # # list = [45, 2, 10, -5, 100] # print(sum_list(list)) def sum_list(list): sum = 0 for i in list: sum += i return sum list = [45, 2, 10, -5, 100] print(sum_list(list)) # 4.) Correct the following code which should reverse the sentence that is entered. # def reverse(text): # result = "" # text_length = len(text) # for i in range(text_length): # result = result + text[i * -1] # return result # # text = input("Enter a sentence: ") # print(reverse(text)) def reverse(text): result = "" text_length = len(text) for i in range(text_length): result = result + text[(i + 1) * -1] return result text = input("Enter a sentence: ") print(reverse(text)) # 5.) Correct the following code: (if one of the options is not entered it should print the statements) # def get_user_choice(): # while True: # command = input("Command: ") # if command = f or command = m or command = s or command = d or command = q: # return command # # print("Hey, that's not a command. Here are your options:" ) # print("f - Full speed ahead") # print("m - Moderate speed") # print("s - Status") # print("d - Drink") # print("q - Quit") # # user_command = get_user_choice() # print("You entered:", user_command) def get_user_choice(): global command while True: command = input("Command: ") if command == "f" or command == "m" or command == "s" or command == "d" or command == "q": return command else: print("Hey, that's not a command. Here are your options:") print("f - Full speed ahead") print("m - Moderate speed") print("s - Status") print("d - Drink") print("q - Quit") get_user_choice() print("You entered:", command)
8ad91b8e0ff2cf24db4659a2a31678049f0267aa
lanzaiyige/PythonDemo
/iterTools.py
377
3.546875
4
#! /usr/bin/python import itertools natuals = itertools.count(1) natualResult = itertools.takewhile(lambda x : x <= 10, natuals) # for nn in natualResult: # print nn # for n in natuals: # print n # ns = itertools.repeat('A',10) # for s in ns: # print s # for c in itertools.chain('ABC','XYZ'): # print c for k,v in itertools.groupby('AAABBBCCAAA'): print k,list(v)
299f84d7c17e27b1335558f5e33be5c914770803
dsbaynetov/GeekBrains_Python
/lesson03/home_work/hw03_normal.py
2,816
4.34375
4
# Задание-1: # Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента. # Первыми элементами ряда считать цифры 1 1 print ("\n### Задание 1.Normal") def fibodigit(n): """ Функция вычисления числа n ряда Фибоначи :param n: номер числа в ряду :return: число n в ряду Фибоначи """ if n in (1, 2): return 1 return fibodigit (n - 1) + fibodigit (n - 2) def fibonacci(n, m): result = list (fibodigit (i) for i in range (1, m + 1) if i >= n) return result print( fibonacci(1,10) ) print( fibonacci(4,10) ) print( fibonacci(4,8) ) # Задача-2: # Напишите функцию, сортирующую принимаемый список по возрастанию. # Для сортировки используйте любой алгоритм (например пузырьковый). # Для решения данной задачи нельзя использовать встроенную функцию и метод sort() print ("\n### Задание 2.Normal") def sort_to_max(origin_list): flag = True while flag: flag = False for i in range (len (origin_list) - 1): if origin_list[i] > origin_list[i + 1]: origin_list[i], origin_list[i + 1] = origin_list[i + 1], origin_list[i] flag = True print(origin_list) sort_to_max([2, 10, -12, 2.5, 20, -11, 4, 4, 0]) print ("\n### Задание 3.Normal") # Задача-3: # Напишите собственную реализацию стандартной функции filter. # Разумеется, внутри нельзя использовать саму функцию filter. def my_filter(func, *args): tempo = list(*args) result = list( itm for itm in tempo if func(itm)) return result print(list(filter(lambda x: x%2, [10, 111, 102, 213, 314, 515]))) print(my_filter(lambda x: x%2, [10, 111, 102, 213, 314, 515])) print ("\n### Задание 4.Normal") # Задача-4: # Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4). # Определить, будут ли они вершинами параллелограмма. import math def side_len(point1, point2): result = math.sqrt (abs(point1[0] - point2[0]) ** 2 + abs(point1[1] - point2[1]) ** 2) return result def is_parall(a, b, c, d): #Проверка равенства сторон ab = side_len(a, b) bc = side_len(b, c) cd = side_len(c, d) ad = side_len(d, a) return (ab == cd) and (bc == ad) a1, a2, a3, a4 = (2,2), (4,5), (10,5), (8,2) print(is_parall(a1, a2, a3, a4))
18873c4bda42b21dda02fcf251792d3c0fc3cf94
zakonweb/algorithms-AS
/BUBBLE SORT/BubbleSort - Array Param 1/array param 1.py
526
3.625
4
def Bubble(TBS, UB): wasSwap = False for j in range(UB-1,0,-1): wasSwap = False a = 0 for i in range(j): a = a + 1 if TBS[i+1] < TBS[i]: wasSwap = True Temp = TBS[i] TBS[i] = TBS[i+1] TBS[i+1] = Temp if not wasSwap: break print("No. of loops:", a) thisArr = [] for i in range(5): x = input() thisArr.append(x) Bubble(thisArr, 5) for i in range(5): print(thisArr[i])
33d6559d11d837076e7099abb4bb619a4393b5db
nitendragautam/python_apps
/python_core/pythontutorials/multiThreadingEx.py
653
3.9375
4
import time import threading """ Multi Threading in Python """ def calc_square(numbers): print("Calculating Squares of Numbers") for n in numbers: time.sleep(1) print('Square:', n*n) def calc_cubes(numbers): print("Calculating Cubes of Numbers") for n in numbers: time.sleep(1) print('Cubes:',n*n*n) array = [2,3,8,9] current_time = time.time() t1 = threading.Thread(target=calc_square, args=(array,)) t2 = threading.Thread(target=calc_cubes, args=(array,)) t1.start() t2.start() t1.join() t2.join() print("Done in Time: ",time.time()-current_time)
381e27fcf3506007626383fc828ac1c914eec297
steadydoer/cs_python
/example/4.1 list.py
713
4.03125
4
family = ['엄마', '아빠', '형', '동생'] print (family) family.append('baby') print (family[0]) print (family[1]) print (family[2]) print (family[3]) print (family[4]) print (family[-1]) print (family[0:3]) print (family[3:6]) print (family[:3]) print (family[3:]) print(type(family[1])) print(type(family[1:4])) family.append("uncle") family.insert(0, "grand master") family.extend([1 , 2, 3]) print(family) family.remove('baby') family.remove(1) family.remove(2) del family[0] x = family.pop() print(family) print(x) print('uncle' in family) if 1 in family: print("There is '1'") else: print("There isn't '1'") family_copy = family[:] family_copy.sort() print(family) print(family_copy)
7b414a1d11730c4626058429be1f1d0aa910b912
Srinjoycode/Hangman_Python
/addWord.py
532
4.03125
4
print('-----Welcome to the Words Adding file of Hangman-----') f = open("words.txt", "a") num = int(input("Please enter the number of custom words you want to add:")) for i in range(num): word = input(f'Enter word number {i+1}:') f.write("\n"+word) print('All your reqested Custom Words Have been entered into the DB') flag = input("Would you like a Print-out of the words(Y/N):").upper() if flag == 'Y': fw = open("words.txt", "r") print(fw.read()) print("Exiting...") else: print("Exiting....") quit()
2447136e2fb51480cd96bff1e1b5e4b482661697
GraceRonnie/my-isc-work
/python/dancing/sets.py
240
4.125
4
a = set([0, 1, 2, 3, 4, 5]) b = set([2, 4, 6, 8]) print a.union(b) #union means show all the elements in both sets as one list but each element appears only once print a.intersection(b) #intersection shows which elements appear in both sets
5ab8a0018e9e1ddd39f9c549ab4dcd5df0eed32c
Jaricapa-holberton/holberton-system_engineering-devops
/0x16-api_advanced/2-recurse.py
1,125
3.65625
4
#!/usr/bin/python3 """Define recurse function""" import requests def get_title(children): """Return children's title""" return children.get("data").get("title") def recurse(subreddit, hot_list=[], after=None): """ Queries the Reddit API and returns a list containing the titles of all hot articles for a given subreddit. - If no results are found for the given subreddit, the function should return None """ url = "https://www.reddit.com/r/{}/hot.json".format(subreddit) headers = { "User-Agent": "linux:0x016.project:v1.0.0 (by /u/ecalvoc)" } params = {"limit": 100} if after: params["after"] = after hot_data = requests.get(url, headers=headers, params=params, allow_redirects=False).json().get("data") if not hot_data: return childrens = hot_data.get("children") hot_list.extend(list(map(get_title, childrens))) after = hot_data.get("after") if not after: return hot_list return recurse(subreddit, hot_list, after)
852fe1c91873fce55277461333bd0c38ae739156
Carlosmichico2/Tic-Antonio
/Primo.py
202
3.765625
4
def primos (): numero=input ("inserta un numero=") for i in range(2,numero): if(numero%i==0): print"Es primo" else: print"no es primo" primos()
21fb67a86b29cab4036cfe8e75cf1dc78ea0ff2c
lordjuacs/ICC-Mentoring
/2020-2/8th/e3.py
816
3.703125
4
import random def desordenar(lista): a = 0 b = len(lista) - 1 for i in range(len(lista)): temp = lista[i] otro_pos = random.randint(a,b) lista[i] = lista[otro_pos] lista[otro_pos] = temp return lista lista = [] for i in range(10): lista.append(float(input("Ingrese valor para la lista: "))) #print("Lista:", lista) #print("Lista deordenada:", desordenar(lista)) print("Lista:", end=" ") for i in range(len(lista)): if i == len(lista) - 1: print(lista[i], end="") else: print(lista[i], end=",") print() lista = desordenar(lista) print("Lista desordenada:", end=" ") for i in range(len(lista)): if i == len(lista) - 1: print(lista[i], end="") else: print(lista[i], end=",") print()
f25acc5a37789e33629d66d33e675ad685819776
honglingjinliu/atm
/atm.py
6,168
3.609375
4
import random,time from card import Card from user import User class Atm: def __init__(self,allUserInfo): self.allUserInfo = allUserInfo #检测密码 def isExistPwd(self,inputCard): if self.allUserInfo.get(inputCard).cardInfo.status: print("此卡已锁定,没有必要输入密码,请联系管理员!") return False for i in range(3): inputPwd = input("请输入密码:") if inputPwd == self.allUserInfo.get(inputCard).cardInfo.cardPwd: return True else: print("密码输入错误,还有%s次输入机会"%(2-i)) else: self.allUserInfo.get(inputCard).cardInfo.status = True #锁定卡 print("此卡已锁定!") print(self.allUserInfo.get(inputCard).cardInfo.status) return False #判断卡号是否存在 def isExistCard(self,cardNum): if not self.allUserInfo.get(cardNum): print("暂无此卡") return False return True def randomCardNum(self): #print cardnum = '' #卡号一共6位 for i in range(6): cardnum += str(random.randint(0,9)) #判断生成卡号有没有重复 #{1212:user1,2323:user2,1213:user3} # for i in self.allUserInfo: #字典遍历 下标(键){'name':'zs'} {cardnum:用户对象} # # # if i == cardnum: # self.randomCardNum() #通过get方法查找 生成的卡号是否有存在,若存在则重新生成(函数自调用) if self.allUserInfo.get(cardnum): self.randomCardNum() return cardnum #检测确认密码 def checkPwd(self,onePwd): # for i in range(3): two = input("请再次输入确认密码:") if two == onePwd: print("确认密码一致") return True else: print("密码输入错误,还有%s次输入机会"%(2-i)) else: print("确认密码三次用完") return False #开卡 def createUser(self): name = input('请输入姓名:') idCard = input('请输入身份证号:') phone = input('请输入电话号:') money = input('请输入预存金额:') #预存金额是否大于1 if int(money) < 1: print("预存金额不足,开卡失败!") return False onePwd = input("请输入卡密码:") twoPwd = self.checkPwd(onePwd) #调用检查确认密码 #确认密码三次机会用完 if not twoPwd: print("开卡失败!") return False #以上没有问题,进行开卡 #随机生成卡号 cardNum = self.randomCardNum() #创建卡对象 card = Card(cardNum,onePwd,money) #用户对象 self.allUserInfo[cardNum]=User(name,idCard,phone,card) # aa = {'name':'zs'} # aa['name']='12212' time.sleep(1) print("开卡成功!请牢记您的卡号%s"%cardNum) return #解卡 #。。。。。status = False def jiechusuooding(self): while True: idCard1=input("输入您所需要解锁的卡号") # print(self.allUserInfo.get(idCard1).cardInfo.status) #判断卡号是否存在 if not self.isExistCard(idCard1): print("没有查询到%s的卡号"%(idCard1)) continue if self.allUserInfo.get(idCard1).cardInfo.status==False: print("该卡没有锁定可以正常使用") return False self.allUserInfo.get(idCard1).cardInfo.status=False return True #查询 #当前登录用户卡号, self.allUserInfo.get(inputCard).cardInfo.mone def allpeople(self,inputCard): print("姓名:%s"%(self.allUserInfo.get(inputCard).name)) print("手机号:%s"%(self.allUserInfo.get(inputCard).phone)) print("身份证:%s"%(self.allUserInfo.get(inputCard).idCard)) print("账户还剩余的金额为%s"%(self.allUserInfo.get(inputCard).cardInfo.money)) #存款 #当前登录用户卡号 输入存款 0>(附加 0~2500) 余额+存入金额 def cunqian(self,inputCard): oldmaney=input("输入你存款的金额") oldmaney=int(oldmaney) if oldmaney>2500: print("您储存的金额过大,系统不能处理") elif oldmaney<=0: print("输入大于0的钱") else: self.allUserInfo.get(inputCard).cardInfo.money=str(int(self.allUserInfo.get(inputCard).cardInfo.money)+int(oldmaney)) print("账户还剩余的金额为%s"%(self.allUserInfo.get(inputCard).cardInfo.money)) #取款 #当前登录用户卡号 输入取款 def nomony(self,inputCard): newmoney=input("请输入要取款的金额") newmoney=int(newmoney) if newmoney>int(self.allUserInfo.get(inputCard).cardInfo.money): print("您账户上有多少钱,你心里没点逼数") # return elif newmoney<=0: print("必须取的钱是大于1的") else: self.allUserInfo.get(inputCard).cardInfo.money=str(int(self.allUserInfo.get(inputCard).cardInfo.money)-int(newmoney)) print("当前账户还剩余额%s"%(self.allUserInfo.get(inputCard).cardInfo.money)) print("取款成功") #转账 def transMoney(self,inputCard): transCard = input("请输入要转账的卡号:") #没有此卡 if not self.isExistCard(transCard): self.transMoney(inputCard) if transCard == inputCard: print("不能给自己转账!") return if self.allUserInfo.get(transCard).cardInfo.status: print("对方账号被锁定,无法转账!") return transmoney = input("请输入转账金额:") if int(self.allUserInfo.get(inputCard).cardInfo.money) > int(transmoney): self.allUserInfo.get(inputCard).cardInfo.money =str(int(self.allUserInfo.get(inputCard).cardInfo.money)-int(transmoney)) self.allUserInfo.get(transCard).cardInfo.money =str(int(self.allUserInfo.get(transCard).cardInfo.money)+int(transmoney)) print("转账成功!当前卡余额还剩%s"%(self.allUserInfo.get(inputCard).cardInfo.money)) return else: print("卡内余额不足,请重新操作!") #487560 #修改密码 def newpassword(self,inputCard): xinpassword=input("输入你的原密码") if xinpassword==self.allUserInfo.get(inputCard).cardInfo.cardPwd: newpass=input("输入成功,输入你的新密码吧") for i in range(3): oldpas=input("再次输入密码") if oldpas!=newpass: print("还能在失误%d"%(2-i)) else: self.allUserInfo.get(inputCard).cardInfo.cardPwd=newpass return else: print("输入的原密码有误")
aeabd0fcae467249ce8ac0733e4baaa06055f559
GeekvsCritic/Coffee-Machine
/Problems/Process integer input/task.py
284
3.78125
4
# put your python code here """for _ in range(10): ip = int(input()) if ip < 10: continue elif ip > 100: break else: print(ip) """ while True: ip = int(input()) if ip < 10: continue if ip > 100: break print(ip)
fe1da1950206fc4e7dd6fffa1d4703a41fdf2aa8
rihardssp/annotationtranslation
/src/caches/cache.py
633
3.515625
4
from abc import ABC, abstractmethod from diskcache import Cache class ICache(ABC): @abstractmethod def get(self, key: str) -> object: pass @abstractmethod def put(self, key: str, value: object): pass @abstractmethod def has(self, key: str) -> bool: pass class FileCache(ICache): def __init__(self, cache_path): self._cache = Cache(cache_path) def get(self, key: str) -> object: return self._cache[key] def put(self, key: str, value: object): self._cache[key] = value def has(self, key: str) -> bool: return key in self._cache
66cc75069de3e4930ae4216573a239801e1c3ddc
BSChuang/AdventOfCode2020
/day8.py
1,514
3.609375
4
file = open('input.txt', 'r') inp = file.read() file.close() inp = inp.split('\n') def parseInstr(instr): op, arg = instr.split() return op, int(arg) def partOne(inp): acc = 0 pc = 0 inp = [parseInstr(instr) for instr in inp] checked = [] while pc not in checked: checked.append(pc) op, arg = inp[pc] if op == 'nop': pc += 1 elif op == 'acc': acc += arg pc += 1 elif op == 'jmp': pc += arg return acc def partTwo(inp): inp = [parseInstr(instr) for instr in inp] return recursion(inp, [], 0, 0, False) def recursion(inp, checked, acc, pc, swapped): while pc not in checked: if pc == len(inp): return acc checked.append(pc) op, arg = inp[pc] if op == 'nop': if not swapped: result = recursion(inp, checked.copy(), acc, pc + arg, True) # As if we executed jmp instead if result != None: # If it has looped, ignore this reality return result pc += 1 elif op == 'acc': acc += arg pc += 1 elif op == 'jmp': if not swapped: result = recursion(inp, checked.copy(), acc, pc + 1, True) # As if we executed nop instead if result != None: # If it has looped, ignore this reality return result pc += arg return None print(partTwo(inp))
1f5b3ebc8c35ae304d90126a4509d7e1940c6681
rahil1303/LISTS_USING_PYTHON
/5_Searching_for_element_in_list.py
396
3.984375
4
### Using Linear Search myList6 = [10,20,30,40,50,60,70,80,90] def searchinList(list,value): for i in list: if i == value: return list.index(value) return 'The value does not exist' print(searchinList(myList6,20)) ### Search Method myList5 = [10,20,30,40,50,60,70,80,90] if 20 in myList5: print(myList5.index(20)) else: print("The value is not in the list")
8e49b789a9001d60f4525fae08cf0ab5ccba7583
SiddharthN16/ICS3U
/Lessons/1/basics.py
2,137
4.5625
5
#------------------------------------------------------------------- # Name: Lesson 1 - Basics (basics.py) # Purpose: Our first lesson, learning the basics # # Author: Mr. Kowalczewski # Created: 13-Feb-2019 # Updated: 05-May-2021 #---------------------------------------------------------------- # Comments should describe what the code is doing! # Printing using ', " , ''' print("Hello There!") print('General Kenobi,') print('''You are a bold one!''') # Why use each one? print('''"You miss 100% of the shots you don't take." - Wayne Gretzky''') # camelCase variables myIntegerThatICreated = -25 # integer myFloat = 5034759.8 # float myString = "Hello World" # string myBoolean = False # boolean # pot_hole_case my_string = "I don't think the system works" another_example_of_pot_hole_case = 8 # don't do this thisisafloat = 5.2 a = 85 # printing variables - always convert integers/floats to string before printing print(myString) print(str(myIntegerThatICreated)) print("The value of the float is: " + str(myFloat)) # Showing some Math and storing in variables # Dividing will always give a float result myAnswer = 23 / 4 print("The answer to 23 / 4 is: " + str(myAnswer)) # Whenever you divide you'll end up with a float (decimal) answer myAnswer = int(myAnswer) print("The answer with no decimals is: " + str(myAnswer)) myNewAnswer = 5 - 9 # Trying some integer divison (//) and modulo (%) integerDiv = 20 // 3 myModulo = 20 % 3 print("The integer division of 20 by 3 is: " + str(integerDiv) + ", and the remainder would be: " + str(myModulo)) # Doing "math" with a string numberString = "52" newString = numberString * 10 print(newString) # Taking input from the user for a calculation # The input() function gives you a STRING userInput = int(input("Please enter your age: ")) # Convert the input into an integer #userInput = int(userInput) # Adds 10 years to the age and prints a message newAge = userInput + 10 print("You will be " + str(newAge) + " in 10 years.") # Quicker way to increment your variables myInt = 10 myInt = myInt + 3 print(myInt) myNewInt = 10 myNewInt += 3 print(myNewInt)
6efb5a860b88569cbf5966c2c4dd7a2143877202
lukassn/CodeQuests
/URI/inPython/tipos_de_triangulo_1045.py
753
3.921875
4
#coding: utf-8 def insertionsort(A): for j in range(1,len(A)): key = A[j] i = j-1 while (i > -1) and key < A[i]: A[i+1]=A[i] i=i-1 A[i+1] = key return A enter = input().split() for i in range(len(enter)): enter[i] = float(enter[i]) insertionsort(enter) a, b, c = enter[2], enter[1], enter[0] saida = [] if a >= (b+c): print("NAO FORMA TRIANGULO") else: if ((a**2) == (b**2 + c**2)): print("TRIANGULO RETANGULO") if a**2 > (b**2 + c**2): print("TRIANGULO OBTSANGULO") if a**2 < (b**2 + c**2): print("TRIANGULO ACUTANGULO") if a == b or a == c or b == c: if a == b == c: print("TRIANGULO EQUILATERO") else: print("TRIANGULO ISOSCELES")
590224a4b8e80d3875ab357ada3a8fe91aac681d
BrettMcGregor/udemy-python-tim
/set_challenge.py
573
4.5
4
# Create a program that takes some text and returns a list of # all the characters in the text that are not vowels, sorted in # alphabetical order. # # You can either enter the text from the keyboard or # initialise a string variable with the string. mystring = "ANZAC day with the family, Brisbane, 2018" text = set(mystring) vowels = {"a", "e", "i", "o", "u"} no_vowels = text.difference(vowels) print(sorted(no_vowels)) no_vowels2 = [] for char in mystring: if char in vowels: continue else: no_vowels2.append(char) print(sorted(no_vowels2))
9ecd26ddf5306708d58bd18f46faff3f7bfdd7e9
rvmurdock/pythonprojects
/game.py
336
3.8125
4
# Author: Ryan V. Murdock # Contact: email #information about the code: A fun little python game name = input("What is your name?") age = int(input("What is your age?")) your_age_in_hundred_years = age+100 print("Hi, " + name + "!") print("Your age is " + str(age) + " but in 100 years, you are going to be " + str(your_age_in_hundred_years))
7126022b92f7079131facb194e98c27aab96e586
pranavsankhe/recursion_aoa
/problem3_2.py
1,436
4.03125
4
import math class matrix(): ''' The class has all the needed methods for calculating the fibonachi number''' # creating matrix class and defining dunder methods to perform # matrix multiplication and matrix mod and item def __init__(self, data): self.mat = data def __mul__(self, obj): m1 = self.mat m2 = obj.mat self.ans = [[0 for i in range(len(m2[0]))] for j in range(len(m1))] for i in range(len(m1)): for j in range(len(m2[0])): for k in range(len(m2)): self.ans[i][j] += m1[i][k] * m2[k][j] return matrix(self.ans) def __mod__(self, obj): for i in range(len(self.mat)): for j in range(len(self.mat[0])): self.mat[i][j] = self.mat[i][j] % obj return matrix(self.mat) def item(self, index): i = index // len(self.mat[0]) j = index % len(self.mat[0]) return self.mat[i][j] def __repr__(self): return 'Pranav-Matrix: {}'.format(self.mat) def main(): n = int(input()) if (n == 0): print(0) M = power(n-1) * matrix([[2],[1],[0]]) print(M.item(1)% 10007) def power(n): # stopping condition if (n == 0): return matrix([[1,0,0],[0,1,0],[0,0,1]]) R = power(math.floor(n/2)) R = R * R if (n % 2 == 1): # the matrix is specific to our series' defination R = R * matrix([[1,2,1],[1,0,0],[0,1,0]]) # get the mod of the matrix at every iteration so that the snumber # dont get too big for calulations return R % 10007 if __name__ == '__main__': main()
6f68da91ba2013cfe426e9ed2d89e1adc2990d35
hsinhuibiga/Array
/Two Sum.py
378
3.515625
4
#Two Sum class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ container = {} for i, num in enumerate(nums): if target - num in container: return [container[target - num], i] container[num] = i return
7fd19ec9a85699889a14091b5507cc9366b51fb2
huangyh09/pyseqlib
/kit/fasta_convert.py
3,715
3.703125
4
# This file is developed for convert fasta file(s) into new fasta file(s) # that have defined length of each line. This program has tow options: # (1) combine many fasta file into a single fasta file; # (2) split a big fasta file into many small fasta files with a single # ref_id in each file. For this case, --split is required. # Example: python fasta_split.py -i chr1.fa,chr2.fa -o genome.fa import os import sys from optparse import OptionParser def main(): # parse command line options parser = OptionParser() parser.add_option("--inFasta", "-i", dest="in_files", default=None, help="Input fasta file(s), e.g., C1.fa,C2.fa") parser.add_option("--outDir", "-o", dest="out_dir", default=None, help="Full path of output directory [default: $inFasta[0]/faConv].") parser.add_option("--lineLen", "-l", dest="line_len", default="50", help="Length of each line [default: %default].") parser.add_option("--split", action="store_true", dest="is_split", default=False, help="Split the output into many fasta files " "with each ref_id") (options, args) = parser.parse_args() if len(sys.argv[1:]) == 0: print("Welcome to Fasta-Convert!\n") print("use -h or --help for help on argument.") sys.exit(1) if options.in_files is None: print("Error: need input fasta file.") sys.exit(1) else: in_files = options.in_files.split(",") print("Converting %d fasta files... " %(len(in_files))) is_split = options.is_split line_len = int(options.line_len) if options.out_dir is None: if is_split is True: out_dir = os.path.dirname(in_files[0]) + "/faConv" else: out_dir = os.path.dirname(os.path.abspath(in_files[0])) else: out_dir = options.out_dir try: os.stat(out_dir) except: os.mkdir(out_dir) # process the data chrom_begin = False for aFasta in in_files: with open(aFasta, "r") as infile: for line in infile: if line.startswith(">"): prevLen = 0 if is_split is False: if chrom_begin is False: fid = open(out_dir + "/converted.fa", "w") chrom_begin = True else: fid.writelines("\n") fid.writelines(line) else: if chrom_begin is True: fid.close() else: chrom_begin = True fid = open(out_dir + line.split(" ")[0][1:] + ".fa", "w") fid.writelines(line.split(" ")[0] + "\n") elif chrom_begin is True: line = line.rstrip() chromLen = len(line) curr_len = line_len - prevLen if curr_len >= chromLen: curr_loc = chromLen fid.writelines(line) prevLen = prevLen + curr_len else: fid.writelines(line[:curr_len] + "\n") curr_loc = curr_len while curr_loc < chromLen-line_len: fid.writelines(line[curr_loc : curr_loc+line_len] + "\n") curr_loc = curr_loc + line_len prevLen = chromLen - curr_loc fid.writelines(line[curr_loc : curr_loc+prevLen]) fid.close() print("Converted!") if __name__ == "__main__": main()
ae277aa26e61edfd845687769df56caa9fb466ff
gotclout/Programming-Languages
/Ex1/interpret.py
6,680
3.671875
4
"""Interpreter for a mini-language with variables and loops. Operator trees that are interpreted are defined as PTREE ::= [ DLIST, CLIST ] DLIST ::= [ DTREE* ] where DTREE* means zero or more DTREEs DTREE ::= ["int", VAR] | ["proc", VAR, CLIST] CLIST ::= [ CTREE+ ] where CTREE+ means one or more CTREEs CTREE ::= ["=", VAR, ETREE] | ["print", ETREE] | ["while", ETREE, CLIST] | ["if", ETREE, CLIST, CLIST] | ["call", VAR] ETREE ::= NUMERAL | VAR | [OP, ETREE, ETREE] where OP is either "+" or "-" There is one crucial data structure: ns is a namespace --- it holds the program's variables and their values. It is a Python hash table (dictionary). For example, ns = {'x': 2, 'p': [['=' 'y', ['+', 'x', '1']], ['print', 'y']], 'y': 0}, holds vars x, p, and y, where int x has value 2, proc p has the command list for y=x+1; print y as its value, and int y has value 0. """ ns = {} intset = set() procset = set() def interpretPTREE(p): """pre: p is a program represented as a PTREE ::= [ DLIST, CLIST ] post: ns holds all the updates commanded by program p """ interpretDLIST(p[0]) # extract the declarations and process them interpretCLIST(p[1]) # extract the commands and execute them def interpretCLIST(clist): """pre: clist is a list of command trees: CLIST ::= [ CTREE+ ] post: ns holds all the updates commanded by clist """ for command in clist : interpretCTREE(command) def interpretDLIST(dlist): """pre: dlist is a list of declaration trees: DLIST ::= [ DTREE* ] post: ns holds all the declarations described by dlist """ for declaration in dlist : interpretDTREE(declaration) def interpretCTREE(c) : """pre: c is a command represented as a CTREE: CTREE ::= ["=", VAR, ETREE] | ["print", VAR] | ["while", ETREE, CLIST] | ["if", ETREE, CLIST, CLIST] | ["call", VAR] post: ns holds the updates commanded by c """ operator = c[0] if operator == "=" : # assignment command, ["=", VAR, ETREE] var = c[1] # get left-hand side if var in ns : # if already declared exprval = interpretETREE(c[2]) # evaluate the right-hand side ns[var] = exprval # do the assignment else : msg = "undeclared variable %s" % (var) crash(msg) elif operator == "print" : # print command, ["print", ETREE] exprval = interpretETREE(c[1]) # evaluate the expression print exprval # print the value elif operator == "while" : # while command, ["while", ETREE, CLIST] expr = c[1] body = c[2] while (interpretETREE(expr) != 0) : interpretCLIST(body) elif operator == "if" : # if condition ["if", ETREE, CLIST, CLIST] exp = c[1] body1 = c[2] body2 = c[3] if interpretETREE(exp) == 0 : # test the computed value if false interpretCLIST(body2) # execute then condition else : # otherwise interpretCLIST(body1) # execute the if condition elif operator == "call" : # call procedure ["call", VAR] proc = c[1] if proc in procset : if proc in ns : # see if variable name is defined exp = ns[proc] # look up its value interpretCLIST(exp) # evaluate the expression else : msg = "undeclared procedure %s" % (proc) crash(msg) else : msg = "%s is not a procedure" % (proc) crash(msg) else : # error crash("invalid command") def interpretETREE(e) : """pre: e is an expression represented as an ETREE: ETREE ::= NUMERAL | VAR | [OP, ETREE, ETREE] where OP is either "+" or "-" post: ans holds the numerical value of e returns: ans """ if isinstance(e, str) and e.isdigit() : # a numeral ans = int(e) elif isinstance(e, str) and len(e) > 0 and e[0].isalpha() : # var name if e not in intset : # is var name e decalared as an int msg = "variable name %s not declared int" % (e) crash(msg) elif e not in ns: # is var name e assigned a value in the namespace ? msg = "variable name %s not declared" % (e) crash(msg) else : ans = ns[e] # look up its value else : # [op, e1, e2] op = e[0] ans1 = interpretETREE(e[1]) ans2 = interpretETREE(e[2]) if op == "+" : ans = ans1 + ans2 elif op == "-" : ans = ans1 - ans2 else : msg = "illegal arithmetic operator %s" % (op) crash(msg) return ans def interpretDTREE(d) : """pre: d is a delaration represented as a DTREE: DTREE ::= ["int", VAR] | ["proc", VAR, CLIST] post: int var is added to ns with default value 0 or proc name VAR is added to ns with value CLIST returns: """ if d[0] == "int" : # ["int", VAR] var = d[1] if var in ns : # if already declared msg = "cannot redefine variable %s" % (var) crash(msg) else : ns[var] = 0 # add to ns intset.add(var) # add to set of ints elif d[0] == "proc" : # ["proc", VAR, CLIST] proc = d[1] if proc in ns : # if already declared msg = "cannot redefine procedure %s" % (proc) crash(msg) else : ns[proc] = d[2] # add proc to ns procset.add(proc) # add proc to procset else : msg = "expected declaration of int or proc, found %s" % (d[0]) crash(msg); def crash(message) : """pre: message is a string post: message is printed and interpreter stopped """ print message + "! crash! core dump:", ns raise Exception # stops the interpreter def main(program) : """pre: program is a PTREE ::= CLIST post: ns holds all updates within program """ global ns # ns is global to main ns = {} interpretPTREE(program) print "final namespace =", ns
debc080070a7c394c0422245238550fdcbdafc8d
mahesh-keswani/data_structures_algorithms_important_problems
/17_moveToEnd.py
425
3.890625
4
# Time: O(n) and space: O(1) def moveToEnd(array, target): i = 0 j = len(array) - 1 while i < j: # j should not get less than i while i < j and array[j] == target: j -= 1 while i < j and array[i] != target: i += 1 array[i], array[j] = array[j], array[i] return array x = [3, 5, 2, 4, 1, 2, 3, 8, 2, 2, 2] print(moveToEnd(x, 2))
d2a5626bf9654627fe8e56e5e929861996944ece
selbovi/python_exercises
/week2/muu.py
348
3.796875
4
c1 = int(input()) c_ = c1 < 5 or c1 % 10 == 2 or c1 % 10 == 3 or c1 % 10 == 4 if (c1 == 1 or c1 % 10 == 1) and not c1 == 11: print(str(c1), ' ', 'korova') elif c1 == 0 or c1 % 10 == 0: print(str(c1), ' ', 'korov') elif (c_) and (c1 != 12 and c1 != 13 and c1 != 14): print(str(c1), ' ', 'korovy') else: print(str(c1), ' ', 'korov')
8aba7e141c80dc04143a73ba140ae15750bfbd59
andersonpereiragithub/CursoEmVideoPython
/Aulas/aula22.py
484
4.4375
4
#Nessa aula, vamos continuar nossos estudos de funções em Python, # aprendendo como criar módulos em Python e reutilizar nossos # códigos em outros projetos. Vamos aprender também como agrupar # vários módulos em um pacote, ampliando ainda mais a modularização # em grandes projetos em Python. def fatorial(n): f = 1 for c in range(1, n + 1): f *= c return f num = int(input('Digite um valor: ')) fat = fatorial(num) print(f'O fatoria de {num} é {fat}.')
83ffe3d07253d76684f51dddc08aaa0318870835
scurry222/Ultimate_Interview_Preparation_Kit
/Coding_Questions/Graph_Algorithms/num_of_nodes.py
1,579
4.15625
4
# Problem statement # # Implement a function that returns the number of nodes at a given level of a directed graph # Try modifying the breadth-first traversal algorithm to achieve this goal. # To solve this problem, all the previously-implemented data structures will be available to us. # Input # # An undirected graph represented as an adjacency list, a starting vertex, and the level whose number of nodes we need to find # Output # # The number of nodes returned as a simple integer # Sample input # # Graph: # Vertex Edges # 0 2, 1 # 1 4, 3 # 2 None # 3 None # 4 None # Level: 1 # Sample output # # 1 from graph import Graph def number_of_nodes(graph, level): """ Calculates the number of nodes at given level :param graph: The graph :return: Total number of nodes at given level """ source = 0 visited = [0] * len(graph.graph) queue = [] queue.append(source) visited[source] = 1 result = 0 while queue: source = queue.pop(0) while graph.graph[source] is not None: data = graph.graph[source].vertex if visited[data] == 0: queue.append(data) visited[data] = visited[source] + 1 graph.graph[source] = graph.graph[source].next for i in range(len(graph.graph)): if visited[i] == level: result += 1 return result if __name__ == "__main__": V = 5 g = Graph(V) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 3) g.add_edge(1, 4) new_g2 = number_of_nodes(g, 1) print(new_g2)
001a726c41e120e304e44bf1530fba9b5deac59b
khanprog/Python-Stuff
/Search Algo/binarySearch.py
1,244
4.125
4
# -*- coding: utf-8 -*- """ @author: Arif Khan """ """ pseudocode 1. Found <- False 2. while not Found and first <= top 3. Midpoint <- (First + Last) DIV 2 4. If List[Midpoint] = ItemSought Then 5. ItemFound <- True 6. Else 7. If First >= Last Then 8. SearchFailed <- True 9. Else 10. If List[Midpoint] > ItemSought Then 11. Last <- Midpoint - 1 12. Else 13. First <- Midpoint + 1 14. EndIf 15. EndIf 16. EndIf """ def binarySearch(item, myList): found = False bottom = 0 top = len(myList) - 1 while not found and bottom <= top: midpoint = (bottom + top) // 2 if myList[midpoint] == item: found = True elif myList[midpoint] < item: bottom = midpoint + 1 else: top = midpoint - 1 return found if __name__ == "__main__": print("=**********= Binary Search =**********=") mylist = [1,2, 5, 7, 12, 14, 21, 28, 31, 36] search = int(input("Input the Item: ")) isFound = binarySearch(search, mylist) print() if isFound: print("The '{}' is in the list.".format(search)) else: print("The '{}' is not in the list.".format(search))
1e36975025e0a8f560dff3e613600792140b7393
gitdreams/data_structure
/sort/insertion_sort.py
1,185
4.03125
4
# -*- coding: utf-8 -*- # @Time : 2018/6/4 16:38 # @Author : li # @File : insertion_sort.py import random def insertion_sort(array): for index in range(1, len(array)): # 记录当前元素值 current_value = array[index] position = index # 只有在当前位置大于0,而且当前位置左边元素大于当前位置元素的时候 # 才需要将当前位置左边的一个元素往右移动一位,并且当前位置往左移动一位 while position > 0 and array[position-1] > current_value: array[position] = array[position-1] position -= 1 # 直到直到一位元素不比current_value小,或者已经将左边所有元素比较完。 # 记住左边永远是已经排好顺序的 # 当将当前位置左边所有的元素都排好顺序之后,将current_value的值赋给当前位置元素 array[position] = current_value # print(array) return array if __name__=="__main__": array = [random.randrange(10000+i) for i in range(10)] sort = insertion_sort(array) print "-------------插入排序之后----------------" print sort
a530c23d78527a986b023540e6416bf93a0ebd97
leandro-hl/python
/cadenas/4_3_claves.py
666
3.96875
4
#Los números de claves de dos cajas fuertes están intercalados dentro de un número #entero llamado "clave maestra", cuya longitud no se conoce. Realizar un programa #para obtener ambas claves, donde la primera se construye con los dígitos #impares de la clave maestra y la segunda con los dígitos pares. Los dígitos se #numeran desde la izquierda. Ejemplo: Si clave maestra = 18293, la clave 1 sería #123 y la clave 2 sería 89. def main(): claveMaestra = "18293" clavePrimaria = claveMaestra[::2] claveSecundaria = claveMaestra[1::2] print(f"clave primaria { clavePrimaria }") print(f"clave secundaria { claveSecundaria }") main()
58a822cd396144e277fb13caae5121c8746ca5bb
MohammadAmmar21/Python
/print_first2_and_last2elements.py
517
4.375
4
##Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Go to the editor ##Sample String : 'w3resource' n=list(input()) print(n) i=0 j=len(n)-1 for i in range(len(n)): if len(n)<2: print("empty string") break for i in range(len(n)): if(len(n)>2): print(n[i],n[i+1]) break for i in range(len(n)): if(len(n)>2): print(n[j-1],n[j]) break
459436851f35ca3377049d320162a1c38a1dd597
Jasper-27/A-bunch-of-FizzBuzz
/Code/FizzBuzz.py
279
3.765625
4
# FizzBuzz in Python3 https://github.com/Jasper-27 fizz = 3 buzz = 5 for i in range (1, 100): out = "" if i % fizz == 0: out += "Fizz" if i % buzz == 0: out += "Buzz" if out == "": print(i) else: print(out)
89b70ee0389eb016d726e1a0e3daa116529d207c
CalvinHardowar1/PinWheel
/PinWheel.py
660
3.890625
4
import turtle turtle2=turtle.Screen() turtle1=turtle.Turtle() turtle1.shape('arrow') turtle1.color("purple") turtle1.pensize(3) turtle1.forward(30) for b in range(3): turtle1.forward(50) turtle1.right(120) turtle1.back(30) turtle1.right(90) turtle1.forward(30) for b in range(3): turtle1.forward(50) turtle1.right(120) turtle1.back(30) turtle1.right(90) turtle1.forward(30) for b in range(3): turtle1.forward(50) turtle1.right(120) turtle1.back(30) turtle1.right(90) turtle1.forward(30) for b in range(3): turtle1.forward(50) turtle1.right(120) turtle1.back(30) turtle2.exitonclick()
dfd2543b9df91d20f953dc82bda302563c56e492
Muneeb-ullah/codes
/binary_search.py
1,349
4.28125
4
# Binary Search # # Coded By: Muneeb Mughal # Date : June 6, 2018 # # This is an implementation of binary search in python. # # Binary search work by taking a sorted list as input and finding the index of a specified number # in the list. Instead of comparing every element with the search_key the algorithm search only # the middle of list. Since the list is sorted, if the search_key occurs before the middle it means # that the elements ahead of the middle element are futile, vice verse if element occurs after the # middle element. In case the element does not exist in the list, the list will be exhausted! import random def binary_search( array, search_key): start = 0 end = len(array) while start <= end: index = (start + end) / 2 if array[index] == search_key: return index elif search_key < array[index]: # If the search key occurs before the middle element discard the list ahead end = index - 1 elif search_key > array[index]: # If the search key occurs after the middle element discard the previous list elements start = index + 1 return -1 # In case the element was not found data = [] for i in range(10): data.append(random.randint(1, 10)) data.sort() index = binary_search(data, 5) if index == -1: print "Element was not found in the list" else: print "Element found at index", index
b9a046c7d23a993b0d6c4576a783b19b60ef2296
VladaLukovskaya/Python
/lesson11_strings_slices/main.py
761
4.03125
4
text = 'Hello, world!' print(text[:5]) print(text[7:], '\n') full_name = 'Иванов И. И.' surname = full_name[:-6] print(surname, '\n') number = input('Enter: ') odd = even = 0 # срез будет от начала строки до конца с шагом два: 0, 2, 4,... for n in number[::2]: odd += int(n) # срез от второго элемента строки до конца с шагом два: 1, 3, 5,... for n in number[1::2]: even += int(n) if odd == even: print('Счастливый по-питерски!', '\n') else: print('Счастливый, но не по-питерски)', '\n') text = 'СЕЛ В ОЗЕРЕ БЕРЕЗОВ ЛЕС' text_reversed = text[::-1] print(text == text_reversed) print(text_reversed)
9c6e1079a9dc59ad258c649765324fcc1c425236
stewSquared/project-euler
/p050.py
1,219
3.71875
4
"""The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from math import sqrt LIMIT = 10**6 def primesUntil(n): composite = [False for _ in range(n)] for m in range(2, int(sqrt(n))+1): if not composite[m]: for i in range(m**2, n, m): composite[i] = True return [i for (i, m) in enumerate(composite) if (not m)][2:] primes = primesUntil(5000) def prime(n): if n < 2: return False for m in range(2, int(sqrt(n))+1): if n%m == 0: return False else: return True length = len(primes) - 1 ans = 0 while not ans: start = 0 s = sum(primes[start:(start+length)]) while (start+length) < len(primes) and s < LIMIT: if prime(s): ans = s break start += 1 s = sum(primes[start:(start+length)]) else: length -= 1 start = 0 print(ans)
8cb037f0688e7c87b3e80d1090622437d3b84382
YDD9/cs-study
/findPrime.py
905
3.84375
4
from math import sqrt def prime(N): # 0 and 1 are not prime res = [False, False] + [True] * (N-1) for i in range(2, int(sqrt(N))+1): pointer = i*i while pointer<= N: res[pointer] = False pointer += i out = [i for i in range(N+1) if res[i]] return res, out def prime2(N): sieve, out = [False, False] + [True] * (N-1), [] for p in range(2, N+1): if (sieve[p]): out.append(p) for i in range(p*p, N+1, p): sieve[i] = False return sieve, out # N must bigger than 2 N = 20 print prime(N) print prime2(N) def isPrime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for t in range(3, int(math.sqrt(n)+1),2): if n % t == 0: return False return True print [n for n in range(100) if isPrime(n)]
920fc969fe89b014e0621e24acf11df8bc2d8dc8
gnorgol/Python_Exercice
/Fonctions/Exercice 1.py
593
3.65625
4
def chiffrePorteBonheur(nb): verif = 0 resultat = 0 print(type(resultat)) while verif != 1 : for each in nb: resultat = resultat+int(each)*int(each) if resultat <= 10 : verif = 1 return str(resultat) else: nb = str(resultat) resultat = 0 print(nb) nb = input("Quelle est votre nombre : ") if chiffrePorteBonheur(nb) == 1: print("Le nombre "+nb+" est un nombre porte bonheur") else: print("Le nombre "+nb+" n'est pas un nombre porte bonheur")
07e14ce95ea299c047cc4d2698f43b68e476d46c
stromatolith/py_schule
/ex01_expon/expon_01.py
1,426
4.75
5
#!/usr/bin/env python """ Exponential growth is unintuitive. What is the annual interest rate that will double 100 Euros during 10 years? What rate will multiply it by 100? Without having ever looked at and remembering the results of such calculations one has no chance of making good estimates. With a computer program you can try out several interest rates and see how the result changes when you play with the parameters. Playing with a computer program can help you get a feeling quicker than doing the stuff with paper and calculator. Secondly, you can do plotting and visualisation as well. So here we have already several advantages of NUMERICAL COMPUTATION. """ """ Let's start with a simple example: a) How much of 100 Euros melt away during 10 years if the inflation is at 2%? b) How much does the capital grow if I get 3% interest from the bank? c) How does it look with both effects combined? """ c = 100.0 # the start capital: 100 Euros n = 10 # the time, the number of years K1 = 0.98 # 2% inflation means each year you multiply with that number print 'after 10 years with 2% inflation: {}'.format(c * K1**n) K2 = 1.03 # 3% interests means each year you multiply with that number print 'after 10 years with 3% interest: {}'.format(c * K2**n) print 'after 10 years with both effects: {}'.format(c * (K1*K2)**n) print 'Now change the numbers and try out different things.'
622f6694c1bf81bbfc82bf1bd7a4d2cf964960ce
zeeyang93/CS50-Projects
/pset6/cash.py
513
3.75
4
import cs50 # get input while True: change = cs50.get_float("Change owed: ") if change > 0: break # Cast to int, round it up and convert to cents cents = round(int(change*100)) # coins counter, starting from 0 coins = 0 while cents > 0: while cents >= 25: coins += 1 cents -= 25 while cents >= 10: coins += 1 cents -= 10 while cents >= 5: coins += 1 cents -= 5 while cents >= 1: coins += 1 cents -= 1 print(coins)
80d9b05a417128d78d5674db2d67377974bc28f5
LikhithReddy8/Astro_Science_project
/dc.py
4,757
3.578125
4
def my_dob(x,y,k): if y==3: if x >= 21 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS ARIES") print(" Symbol:RAM") elif y==4: if x >= 1 and x <= 19: print("\n",k,"YOUR ZODIC SIGN IS ARIES") print(" Symbol:RAM") elif y==4: if x >= 20 and x <=30: print("\n",k,"YOUR ZODIC SIGN IS TAURUS") print(" Symbol:BULL") elif y==5: if x >= 1 and x <=20: print("\n",k,"YOUR ZODIC SIGN IS TAURUS") print(" Symbol:BULL") elif y==5: if x >= 21 and x <=31: print("\n",k,"YOUR ZODIC SIGN IS GEMINI") print(" Symbol:TWINS") elif y==6: if x >= 1 and x <= 20: print("\n",k,"YOUR ZODIC SIGN IS GEMINI") print(" Symbol:TWINS") elif y==6: if x >= 21 and x <= 30: print("\n",k,"YOUR ZODIC SIGN IS CANCER") print(" Symbol:CRAB") elif y==7: if x >= 1 and x <= 22: print("\n",k,"YOUR ZODIC SIGN IS CANCER") print(" Symbol:CRAB") elif y==7: if x >= 23 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS LEO") print(" Symbol:LION") elif y== 8: if x >= 1 and x <= 22: print("\n", k,"YOUR ZODIC SIGN IS LEO") print(" Symbol:LION") elif y==8: if x >= 23 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS VIRGO") print(" Symbol:VIRGIN MAIDEN") elif y==9: if x >= 1 and x <= 22: print("\n",k,"YOUR ZODIC SIGN IS VIRGO") print(" Symbol:VIRGIN MAIDEN") elif y==9: if x >= 23 and x <= 30: print("\n",k,"YOUR ZODIC SIGN IS LIBRA") print(" Symbol:SCALES") elif y==10: if x >= 1 and x <= 22: print("\n",k,"YOUR ZODIC SIGN IS LIBRA") print(" Symbol:SCALES") elif y==10: if x >=23 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS SCORPIO") print(" Symbol: SCORPION") elif y==11: if x >=1 and x <= 21: print("\n",k,"YOUR ZODIC SIGN IS SCORPIO") print("Symbol:SCORPION") elif y==11: if x >= 22 and x <= 30: print("\n",k,"YOUR ZODIC SIGN IS SAGITTARIUS") print(" Symbol:ARCHER") elif y==12: if x >= 1 and x <= 21: print("\n",k,"YOUR ZODIC SIGN IS SAGITTARIUS") print(" Symbol:ARCHER") elif y==12: if x >= 22 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS CAPRICORN") print("Symbol:GOAT") elif y==1: if x >= 1 and x <= 19: print("\n",k,"YOUR ZODIC SIGN IS CAPRICORN") print(" Symbol:GOAT") elif y==1: if x >=20 and x <= 31: print("\n",k,"YOUR ZODIC SIGN IS AQUARIUS") print("Symbol:WATER CARRIER") elif y==2: if x >= 1 and x <= 18: print("\n",k,"YOUR ZODIC SIGN IS AQUARIUS") print(" Symbol:WATER CARRIER") elif y==2: if x >= 19 and x <= 28: print("\n",k,"YOUR ZODIC SIGN IS PISCES") print("Symbol:FISH") elif y==3: if x >= 1 and x <= 20: print("\n",k,"YOUR ZODIC SIGN IS PISCES") print(" Symbol:FISH") return; def my_ch(z): if z=='A' or z=='Z': print("\n GOOD PERSONALITY IN SOCIETY") elif z=='B' or z=='Y': print("\n WISHING TO HAVE GOOD ENVIRONMENT AROUND ") elif z=='C' or z=='X': print("\n VERY PEACE AND TAKES THE THINGS EASY") elif z=='D' or z=='W': print("\n GOOD IN CONCERN TO PEOPLE") elif z=='E' or z=='V': print("\n ALWAYS BEHAVING VERY SMART") elif z=='F' or z=='U': print("\n VERY CRUEL BUT SOME CONCERN TO THEM") elif z=='G' or z=='T': print("\n VERY TALENTED AND GOOD IN SERVING PEOPLE") elif z=='H' or z=='S': print("\n MAINLY FOCUS ON THE FUTURE DEVELOPMENT OF COUNTRY") elif z=='I' or z=='R': print("\n GOOD IN STUDIES AND HAVING MORE CONCERN ON OTHERS") elif z=='J' or z=='Q': print("\n VERY WEAK IN TAKING DECISIONS") elif z=='K' or z=='P': print("\n SMART IN THINKING OF NEW IDEAS") elif z=='L' or z=='O': print("\n DREAMER AND HAVING HIGH GOALS TO REACH") elif z=='M' or z=='N': print("\n GOOD LOOKING HAVING KIND HEARTOVER OTHERS.") else: print(" WRITE YOUR NAME CORRECTLY") return
159088a57b9dc8dc4f1902d4e1c9d2b139e995a2
hjiang36/Python-Learner
/SPOJ_PR5/main.py
1,265
3.515625
4
__author__ = 'Killua' import sys def next_palindrome(s): """ finding next palindrome for string s :param s: long integer represented as string :return: next palindrome represented as string """ # length of string l = len(s) s = list(s) p_left = 0 p_right = l - 1 status = False if l == 1: return '11' while p_left < p_right: if s[p_left] > s[p_right]: status = True elif s[p_left] < s[p_right]: status = False s[p_right] = s[p_left] p_left += 1 p_right -= 1 if status: return ''.join(s) while p_right >= 0: if s[p_right] < '9': s[p_right] = str(int(s[p_right]) + 1) s[p_left] = s[p_right] break else: s[p_left] = s[p_right] = '0' p_left += 1 p_right -= 1 if p_right < 0: s.insert(0, '1') s[-1] = '1' return ''.join(s) def main(): # number of test cases t = int(sys.stdin.readline()) # process for each test cases for _ in range(t): s = sys.stdin.readline() if s[-1] == '\n': s = s[:-1] print(next_palindrome(s)) if __name__ == '__main__': main()
adf8214fc3f21a5374010ad64dd38c9aa0e82848
blessey15/pehia-python-tutorials
/q10.py
134
3.671875
4
x = list(input().split(' ')) y = [] for i in x: if i not in y: y.append(i) for j in y: print(j, end=' ')
c718b55e685ecd282b48c4552aae86aa0c21bffa
yuispeuda/pro-lang
/python/calısma-soruları/matris_esik_degeri.py
298
3.515625
4
def matris_esik_degeri(liste,item): for i in range(len(liste)): for j in range(len(liste[i])): if liste[i][j] < item: liste[i][j] = 0 else : liste[i][j] = 1 print liste matris_esik_degeri([[12,3,4],[34,5,6,-9,0]],12)
9617bcfcf3a371d45e76c5d1f1e2691ae02d139c
Pumacens/Competitive-Programming-Solutions
/CodeWars-excercises/Python/7_kyu/files/1291. Very even numbers. .py
141
3.609375
4
def is_very_even_number(n): n = str(n) while len(n) > 1: n = str(sum(map(int, str(n)))) return int(n) % 2 == 0
a720ea806fead738d188d9b9c7173c0cbe636431
QW999/HW_V
/hw/Quarantine_2.py
1,217
4.03125
4
import datetime class Healthy: def __init__(self, Name): self.ill = self.Ill() self.curred = self.ill.Curred() self.Name = Name def __str__(self): return "Name: " + str(self.Name) def healthy(self): return self.Name + " is healthy" class Ill: def __init__(self): self.curred = self.Curred() self.today = datetime.date.today() self.startDate = datetime.date(2021, 2, 1) self.Days_after_infect = self.today - self.startDate def __str__(self): return "Infection date: " + str(self.startDate) + " / " + str(self.curred) + " / Days_after_infect: " + str(self.Days_after_infect) class Curred: def __init__(self): self.startDate = datetime.date(2021, 2, 1) self.endDate = datetime.date(2021, 2, 15) self.Quarantine = self.endDate - self.startDate def __str__(self): return "Quarantine period: " + str(self.Quarantine) pacient = Healthy("Igor Nicolaevici") print(pacient) print(pacient.healthy()) ill = Healthy.Ill() print(ill) curred = Healthy.Ill.Curred() print(curred)
612913b97ddb43103b6eedcd65be814e947b4690
busraerkoc/exercism
/python/kindergarten-garden/kindergarten_garden.py
642
3.578125
4
STUDENTS = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry'] class Garden: def __init__(self, diagram, students=STUDENTS): self.students = students self.diagram = diagram.split() self.students.sort() def plants(self, student): Plant = {"R" : "Radishes", "C" : "Clover", "G" : "Grass", "V" : "Violets"} result = [] indice = self.students.index(student) for i in range(2): result.append(Plant[self.diagram[i][indice*2]]) result.append(Plant[self.diagram[i][indice*2+1]]) return result
87411e33d72315a23cbc7ac4d43a5573663e26c6
ishantk/PythonTutorial
/venv/Inheritance/base.py
641
3.6875
4
class Parent: def sayHello(self): print "Hello from Parent" class Child(Parent): def sayHello(self): print "Hello from Child" def show(self): print "This is show of Child" class GrandChild(Child): def sayHello(self): print "Hello from Grand Child" def show(self): print "This is show of GrandChild" class A: def aShow(self,a): print "Show of A",a class B: def bShow(self): print "Show of B" class C(A,B): def cShow(self): #super print "Show of C" c = C() c.aShow(10) c.bShow() c.cShow() ch = Child() ch.sayHello() ch.show()
01e2a60d40fa1759fd314cfd8349515f1df2b5c9
FunWithPythonProgramming/beginner-exercises
/password-generator/george_solution.py
2,084
3.53125
4
import random import math import string def create_password(): lower_letters = ",".join(string.ascii_lowercase) upper_letters = ",".join(string.ascii_uppercase) numbers = [str(number+1) for number in range(9)] symbols = ",".join(string.punctuation) # check if it actually is >= 4 while True: password_length = int(input("How long should the password be? (must be greater than 4) ")) if password_length <= 4: print("More than 4 doofus") else: break condition_count = 0 need_letters = input("letters? (y/n) ").lower() if need_letters: need_upper_letters = input("upper? (y/n) ").lower() if need_upper_letters in ("y", "yes"): condition_count += 1 need_lower_letters = input("lower? (y/n) ").lower() if need_lower_letters in ("y", "yes"): condition_count += 1 need_numbers = input("numbers? (y/n) ").lower() if need_numbers in ("y", "yes"): condition_count += 1 need_symbols = input("symbols? (y/n) ").lower() if need_symbols in ("y", "yes"): condition_count += 1 min_of_each = math.ceil(password_length / condition_count) # if this isn't a multiple of 4, this will be wrong sub_num = (password_length - (min_of_each*condition_count)) password = "" data_folder = [] for number in range(min_of_each): if need_letters in ("y", "yes"): if need_upper_letters in ("y", "yes"): password += random.choice(upper_letters) if need_lower_letters in ("y", "yes"): password += random.choice(lower_letters) if need_numbers in ("y","yes"): password += random.choice(numbers) if need_symbols in ("y","yes"): password += random.choice(symbols) data_folder.append(password) return password[:sub_num] def main(): number_of_passwords = int(input("How many passwords should I create? ")) for _ in range(number_of_passwords): print(create_password()) main()
76b675ee7a6689818846cad068dd5d9d5ff84f00
PierreVieira/Python_Curso_Em_Video
/ex042.py
548
4.03125
4
""" Exercício Python 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: - EQUILÁTERO: todos os lados iguais """ a, b, c = map(float, input('Informe os três lados do triângulo: ').split()) if a > b + c or b > a + c or c > a + b: print('Os lados informados não formam um tirângulo!') else: if a == b == c: print('Triângulo equilátero') elif a != b and a != c and b != c: print('Triângulo escaleno') else: print('Triângulo isóceles')
64c5b1fceccf3f13d419a42ec3b911f5b6462bb8
Kiryukhasemenov/Russian_Loanwords_in_Mandarin
/2020/CWS_algorithms/wordlist_segmenter.py
354
3.515625
4
def wordlist_segmenter(sentence, vocab): candidates = list() rest = sentence for word in vocab: length = len(word) result = rest.find(word) if result != -1: cut = result+length rest = rest[cut:] candidates.append(word) else: pass return '_'.join(candidates)
a74c1b1ca15dff6383cf1680fd9eabaf0a566c25
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W5_HW2.py
3,845
3.984375
4
def leap_year(year): if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 != 0: return False else: return True def R(y,x): return y % x def day_of_week_jan1(year): inner_portion = 1 + 5 * R(year - 1, 4)\ + 4 * R(year - 1, 100)\ + 6 * R(year - 1, 400) day = R(inner_portion, 7) return day def num_days_in_month(month_num,leap_year_judge): big_months = [1,3,5,7,8,10,12] small_months = [4,6,9,11] if month_num in big_months: number_of_days = 31 elif month_num in small_months: number_of_days = 30 else: if leap_year_judge: number_of_days = 29 else: number_of_days = 28 return number_of_days def construct_cal_month(month_num, first_day_of_month, num_days_in_month): month_list = [] month_dict = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'} month_list.append(month_dict[month_num]) date_counter = 1 day_counter = first_day_of_month week_string = '' week_string = week_string + day_counter * ' ' while date_counter < num_days_in_month + 1: while day_counter < 7 and date_counter < num_days_in_month + 1: if date_counter < 10: week_string = week_string + ' ' + str(date_counter) else: week_string = week_string + ' ' + str(date_counter) day_counter += 1 date_counter += 1 month_list.append(week_string) week_string = '' day_counter = 0 return month_list def construct_cal_year(year): year_list = [] year_list.append(year) for i in range(1, 13): days_passed = 0 for j in range(1,i): days_passed += num_days_in_month(j, leap_year(year)) day_of_week = (day_of_week_jan1(year) + days_passed) % 7 this_month = construct_cal_month(i, day_of_week, num_days_in_month(i, leap_year(year))) year_list.append(this_month) return year_list def display_calendar(calendar_year, month): if month == None: year_list = construct_cal_year(calendar_year) year_list.pop(0) answer_string = '' for i in range(len(year_list)): for j in range(len(year_list[i])): answer_string = answer_string + year_list[i][j] + '\n' if j == 0: answer_string = answer_string + ' S M T W T F S\n' answer_string = answer_string + '\n' answer_string = answer_string[:-2] return answer_string else: days_passed = 0 for j in range(1, month): days_passed += num_days_in_month(j, leap_year(calendar_year)) day_of_week = (day_of_week_jan1(calendar_year) + days_passed) % 7 month_list = construct_cal_month(month, day_of_week, num_days_in_month(month, leap_year(calendar_year))) answer_string = '' for i in range(len(month_list)): answer_string += month_list[i] + '\n' if i == 0: answer_string += ' S M T W T F S\n' answer_string = answer_string[:-1] return answer_string ''' def display_calendar(calendar_year): year_list = construct_cal_year(calendar_year) year_list.pop(0) answer_string = '' for i in range(len(year_list)): for j in range(len(year_list[i])): answer_string = answer_string + year_list[i][j] + '\n' if j == 0: answer_string = answer_string + ' S M T W T F S\n' answer_string = answer_string + '\n' answer_string = answer_string[:-2] return answer_string ''' print display_calendar(2002,3)
051ff19cb52d19e280c61bdd61cefb6cf7620763
fkallin/Working-with-files-and-directories-in-Python
/persistence/pickler.py
645
3.53125
4
import pickle class Person: def __init__(self, first_name, last_name, id): self.first_name = first_name self.last_name = last_name self.id = id def greet(self): print(f'Hi, i am {self.first_name} {self.last_name}' f' and my ID is {self.id}') people = [ Person('John', 'Kennedy', 454), Person('Gearge', 'Bush', 1236) ] #Save data in binary format to a file with open('data.pickle', 'wb') as stream: pickle.dump(people, stream) #Load data from a file with open('data.pickle', 'rb') as stream: peeps = pickle.load(stream) for person in peeps: person.greet()
de0ecd219f76f5ecd9e2a10e0b6b9e6ae272cb78
zhanzecheng/leetcode
/62.不同路径.py
574
3.71875
4
# -*- coding: utf-8 -*- """ # @Time : 2018/5/28 上午9:39 # @Author : zhanzecheng # @File : 62.不同路径.py # @Software: PyCharm """ class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [[1] * n for x in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] if __name__ == '__main__': solution = Solution() m = 7 n = 3 print(solution.uniquePaths(m, n))
cbb88d6182d96b1a4f095ebc274320ffd086aba2
Mariamapa/Formulario-
/formulario.py
2,418
3.515625
4
from tkinter import * def send_data(): #Definición de las variables usuario_info = usuario.get() contraseña_info = contraseña.get() nombre_info = nombre.get() edad_info = str(edad.get()) #Abriremos la sección de llenado print(usuario_info,"\t", contraseña_info,"\t", nombre_info,"\t", edad_info) #Crearemos nuestra base de datos file = open("registro.txt", "a") file.write(usuario_info) file.write("\t") file.write(contraseña_info) file.write("\t") file.write(nombre_info) file.write("\t") file.write(edad_info) file.write("\t\n") file.close() print(" Nuevo usuario. Usuario: {} | Nombre completo: {} ".format(usuario_info, nombre_info)) usuario_entry.delete(0, END) contraseña_entry.delete(0, END) nombre_entry.delete(0, END) edad_entry.delete(0, END) mywindow = Tk() mywindow.geometry("650x550") mywindow.title("REGISTRO OMIND SEX ") mywindow.resizable(False,False) mywindow.config(background = "#fa8bf1") main_title = Label(text = "REGISTRO | OMIND SEX", font = ("calibri", 16), bg = "#fa8bf1", fg = "white", width = "500", height = "2") main_title.pack() usuario_label = Label(text = "Usuario", bg = "#fa8bf1", fg = "white", font = ("calibri", 14)) usuario_label.place(x = 200, y = 100) contraseña_label = Label(text = "Contraseña", bg = "#fa8bf1", fg = "white", font = ("calibri", 14)) contraseña_label.place(x = 200, y = 160) nombre_label = Label(text = "Nombre completo", bg = "#fa8bf1", fg = "white",font = ("calibri", 14)) nombre_label.place(x = 200, y = 220) edad_label = Label(text = "Edad", bg = "#fa8bf1", fg = "white", font = ("calibri", 14)) edad_label.place(x = 200, y = 280) usuario= StringVar() contraseña = StringVar() nombre= StringVar() edad= StringVar() usuario_entry = Entry(textvariable = usuario, width = "40") contraseña_entry = Entry(textvariable = contraseña, width = "40", show = "*") nombre_entry = Entry(textvariable = nombre, width = "40") edad_entry = Entry(textvariable = edad, width = "40") usuario_entry.place(x = 200, y = 130) contraseña_entry.place(x = 200, y = 190) nombre_entry.place(x = 200, y = 250) edad_entry.place(x = 200, y = 310) submit_btn = Button(mywindow,text = "Registrarse", width = "30", height = "2", command = send_data, bg = "#fc6998", font = ("calibri", 12)) submit_btn.place(x = 210, y = 350) mywindow.mainloop()
f40a7219679d7008811cdc90551a726bd60fc305
supportaps/python050920
/ua/univer/base/hw01arifmetic/task07.py
903
4.5
4
#7. Расход бензина в расчете на километры пройденного пути. Расход бензина в расчете #на километры пройденного автомобилем пути можно вычислить на основе формулы: #расход = пройденные километры / расход бензина в литрах. #Напишите программу, которая запрашивает у пользователя число пройденных километров #и расход бензина в литрах. Она должна рассчитать расход бензина автомобилем #и показать результат. distance = float(input(" Input distance in km: ")) fuel = float(input(" Input fuel in lit: ")) charge = distance / fuel print( "The charge of fuel is: ", charge)
d7d1b3c713c363b1a3cdd2697638a0a803f0f76b
avkour13/Avinash_C0804437_Assignment3
/main.py
861
3.515625
4
import timeit import UnitTest_Area import Student if __name__ == '__main__': start_time = timeit.default_timer() UnitTest_Area.UnitTest_Area().run_test() # Average marks for the class total_marks = int(input("Enter total marks for the students: ")) num_students = int(input("Enter total number of students: ")) average = Student.Student().avg_marks(total_marks, num_students) print("The average marks for the class is ", average) # Total marks for a student subject1 = int(input("Enter marks for Subject 1: ")) subject2 = int(input("Enter marks for Subject 2: ")) subject3 = int(input("Enter marks for Subject 3: ")) total = Student.Student().total_marks(subject1, subject2, subject3) print("Total marks for the student is ", total) end_time = timeit.default_timer() print(end_time - start_time)
d3769cc3a8dde39a5718712d7f30be388585f1b5
SuperGuy10/LeetCode_Practice
/Python/345. Reverse Vowels of a String.py
1,279
4.03125
4
''' Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede" Note: The vowels does not include the letter "y". ''' class Solution(object): def reverseVowels(self, s): vowels = set(list("aeiouAEIOU")) s = list(s) l, r = 0, len(s) - 1 while l < r: if s[l] in vowels and s[r] in vowels: s[l], s[r] = s[r], s[l] l += 1 r -= 1 if s[l] not in vowels: l += 1 if s[r] not in vowels: r -= 1 return ''.join(s) ''' using set(list) is much faster than using list or array. string can't do an in-place change. Use list to do that. ''' class Solution(object): def reverseVowels(self, s): vowels = ["a","e", "i", "o", "u", "A", "E", "I", "O", "U"] s = list(s) l, r = 0, len(s) - 1 while l < r: if s[l] in vowels and s[r] in vowels: s[l], s[r] = s[r], s[l] l += 1 r -= 1 if s[l] not in vowels: l += 1 if s[r] not in vowels: r -= 1 return ''.join(s)
44c38c7a71dbfe727425030c9e018a8b1ea5889c
bontu-fufa/competitive_programming-2019-20
/Take2/Week 1/count-servers-that-communicate.py
1,060
3.515625
4
#https://leetcode.com/problems/count-servers-that-communicate/submissions/ def countServers(self, grid: List[List[int]]) -> int: row,column = len(grid),len(grid[0]) visited = set() def neighborServers(r,c): neighbors = set() for i in range(column): if grid[r][i] == 1: neighbors.add((r,i)) for j in range(row): if grid[j][c] == 1: neighbors.add((j,c)) neighbors.remove((r,c)) return neighbors def serversInCommunication(r,c): neighbors = neighborServers(r,c) for n in neighbors: nRow,nCol = n if (nRow,nCol) not in visited and grid[nRow][nCol] == 1: visited.add((nRow,nCol)) for r in range(row): for c in range(column): if grid[r][c] == 1 : serversInCommunication(r,c) return len(visited)
1d008c5ed2db3ee4bf56ba9722990768818dada8
Miri-Hwang/Algorithm
/정렬/K번째수.py
322
3.546875
4
# 프로그래머스 # https://programmers.co.kr/learn/courses/30/lessons/42748 def solution(array, commands): answer = [] for command in commands: i = command[0] j = command[1] k = command[2] newarray = sorted(array[i-1:j]) answer.append(newarray[k-1]) return answer
90d9fd58012edf8687ef7b10912ff9fc8ecbf1b7
Jen-Lopez/GWC-SIP-19
/U1_Fundamentals/Python/secret_word.py
2,503
4.09375
4
#create a list of words #randomly generate a word to be guessed # print blank underscores to represent unsolved word # create a list of letters that have been said already # update the word as letters are said # track the amount of mistakes the player makes import random food_list = ["apple", "banana", "chocolate cake", "pizza","quiche", "taco", "cereal","donuts","cherries", "nuggets"] word = (random.choice(food_list)).lower() intro = """ Hello! Welcome to Guess The Secret Word. You will have 8 tries to guess the word. The topic is food. Goodluck! """ secret_word = "_" * len(word) said_letters = list() guesses = 0 print (intro) print ("This is your secret word:", secret_word, "WORD LENGTH:",len(secret_word)) while guesses < 8: guesses +=1 index = 0 indexes = list() solved = False print ("\nTry #",guesses) print ("Letters Used: ", said_letters) print ("Word:",secret_word) user_letter = input ("Enter a letter (or '1' to solve): ") if not( (user_letter.isalpha() and len(user_letter) == 1) or user_letter == "1" ): print ("\nInvalid input. Only single letter or '1' to solve!") continue if user_letter == "1": res = (input ("\nDo you want to solve? (y/n) ")).lower() if res == "y": guess = (input ("\nWhat's the word? ")).lower() if guess == word: print ("\nCongratulations. You Won!\n") solved = True break else: print ("Incorrect.\n") continue elif res == "n": guesses -= 1 # won't count towards you continue else: print ("Unacceptable input.\n") continue user_letter = user_letter.lower() if user_letter not in said_letters: said_letters.append(user_letter) else: print ("\nThis letter has already been said!\n") continue if user_letter in word: for c in word: if c == user_letter: indexes.append(index) index += 1 for i in indexes: secret_word = secret_word[:i] + user_letter + secret_word[i+1:] print ("\nNew Word:",secret_word, "\n") else: print ("\nIncorrect Try Again!") if secret_word == word: solved = True print ("Congratulations! You solved it!") break if not solved: print ("\nUnfortunately, the secret word was:", word) print ("Thanks for playing!\n")
8797259c739e13a992669438939abde8419c8d35
ICANDIGITAL/crash_course_python
/chapter_4/cubes.py
163
4.28125
4
#List Comprehension Method. cubes = [cube**3 for cube in range(1,11)] print(cubes) #Loop Method. cubes = list(range(1, 11)) for cube in cubes: print(cube**3)
9c82229092954feae6d720a135e099c5ce92ac46
danilche/learning-python
/us_states.py
2,200
4.15625
4
### Print all states that have "la" in name def find_la(states): for state in states: if "la" in state: print(state) ### Print all US states with name consisting of two or more words def two_or_more_words(states): for state in states: if " " in state: print(state) ### Print all US states with name shorter than 6 letters def shorter_than_six(states): for state in states: if len(state) < 6: print(state) ### Prints all US states name starting with 'P' or ending with 'y' (dakle, 'py' :) def starts_with_p_ends_with_y(states): for state in states: if state[0] == "P" or state[-1] == "y": print(state) def main(): us_states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'] print() print("US states with 'la' in name:") print() find_la(us_states) print("######################") print() print("US states with name consisting of two or more words:") print() two_or_more_words(us_states) print("######################") print() print("US states with name shorter than 6 letters:") print() shorter_than_six(us_states) print("######################") print() print("US states name starting with 'P' or ending with 'y':") print() starts_with_p_ends_with_y(us_states) print("######################") main()
fea8b7e3ab57e75136202caf2433799812d5dc71
virajmane/zipper
/Zipper.py
838
3.6875
4
import zipfile, os def zipfiles(folder): folder = os.path.abspath(folder) number = 1 while True: zipFileName = os.path.basename(folder) + "_" +str(number) +".zip" if not os.path.exists(zipFileName): break number += 1 print("Creating %s..." %(zipFileName)) zipping = zipfile.ZipFile(zipFileName, "w") for foldername,subfolders,filenames in os.walk(folder): print("Adding files %s" %(foldername)) zipping.write(foldername) for filename in filenames: """newBase / os.path.basename(folder) + "_" if filename.startswith(newBase) and filename.endswith(".zip"): continue""" zipping.write(os.path.join(foldername,filename)) zipping.close() print("Done") zipfiles("F:\\testing\\JP Morgan Internship")
d4e72265954621794546719b2f1603b8d3ec1897
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Recursividad.py
806
3.84375
4
def fib(n): '''Calcula el enesimo termino de la sucecsion de fibonacci con n natural ''' if n> 2: return fib(n-1) +fib(n-2) else: return 1 fib(1) fib(2) fib(5) fib(10) def suma(n): if n == 1: return 1 else: n = n+suma(n-1) return n def suma(n): if n>1: return n + suma(n-1) else: return (1) def printR(L): if L: print L[0], printR(L[1:]) else: None def printR1(L): #global T T =25 if len(L)> 1: print L[0], printR(L[1:]) else: print(L[0]) def f1(): return 2*x T=[-8,5,4,5,-3] L=[-8,5,4.5,3] printR([8,7,4,5,3,2,1,5]) printR1([8,7,4,5,3,2,1,5]) print "*------------*" x=15 print f1() print T
3ea3b2dae1d77aec638f027faa5f90591adc65d6
linshaoyong/leetcode
/python/linked_list/0061_rotate_list.py
1,843
3.78125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return None nodes = [] while head: nodes.append(head) head = head.next i = (len(nodes) - k) % len(nodes) if i == 0: return nodes[0] nodes[i - 1].next = None nodes[-1].next = nodes[0] return nodes[i] def test_rotate_right_1(): s = Solution() a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(4) e = ListNode(5) a.next = b b.next = c c.next = d d.next = e head = s.rotateRight(a, 2) assert 4 == head.val assert 5 == head.next.val assert 1 == head.next.next.val assert 2 == head.next.next.next.val assert 3 == head.next.next.next.next.val def test_rotate_right_2(): s = Solution() a = ListNode(0) b = ListNode(1) c = ListNode(2) a.next = b b.next = c head = s.rotateRight(a, 4) assert 2 == head.val assert 0 == head.next.val assert 1 == head.next.next.val def test_rotate_right_3(): s = Solution() head = s.rotateRight(None, 4) assert head is None def test_rotate_right_4(): s = Solution() a = ListNode(0) head = s.rotateRight(a, 4) assert 0 == head.val def test_rotate_right_5(): s = Solution() a = ListNode(1) b = ListNode(2) a.next = b head = s.rotateRight(a, 1) assert 2 == head.val def test_rotate_right_6(): s = Solution() a = ListNode(1) b = ListNode(2) a.next = b head = s.rotateRight(a, 0) assert 1 == head.val
642570d10f61c500ece526ea4ccafb52e36c04dc
kajili/interview-prep
/src/leetcode/backtracking/Permutations.py
1,193
3.765625
4
# LeetCode 46. Permutations [Medium] # Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. # Example 1: # Input: nums = [1,2,3] # Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] # Example 2: # Input: nums = [0,1] # Output: [[0,1],[1,0]] # Example 3: # Input: nums = [1] # Output: [[1]] class Solution: def permute(self, nums): result = [] if len(nums) == 0: return result visited = [False] * len(nums) # Can use set since numbers are distinct here # visited = set() self.backtrack(nums, visited, [], result) return result def backtrack(self, nums, visited, permutation, result): # If we find a permutation, add a copy of the permutation list to the result if len(permutation) == len(nums): result.append(permutation[:]) for i, num in enumerate(nums): if visited[i]: continue visited[i] = True permutation.append(num) self.backtrack(nums, visited, permutation, result) permutation.pop() visited[i] = False
f6faced63287800dc8527dff8d02a0adfebcb712
AssiaHristova/SoftUni-Software-Engineering
/Programming Basics/exams/shopping.py
554
3.8125
4
budget = float(input()) video_cards = int(input()) processors = int(input()) ram = int(input()) video_cards_price = video_cards * 250 processor_price = video_cards_price * 0.35 ram_price = video_cards_price * 0.10 total_price = video_cards_price + processors * processor_price + ram * ram_price if video_cards > processors: total_price = total_price * 0.85 money_out = budget - total_price if budget >= total_price: print(f"You have {money_out:.2f} leva left!") else: print(f"Not enough money! You need {abs(money_out):.2f} leva more!")
02f93c58ef2aff596b025b75982c80bd9736edad
hopkinsa17/Python-Projects
/GUI Version 23.py
6,426
3.609375
4
# --------------------------------------- # External Modules: # --------------------------------------- from tkinter import * # --------------------------------------- # Main frame: # --------------------------------------- def Window00(): '''Main frame for GUI''' root = Tk() root.title("Accounting F17 Project 1") frame00 = Frame(root, width=400) frame00.grid(row=0) Window01(root) # --------------------------------------- # Trial Balance Number: # --------------------------------------- def Window01(master): '''Frame for number of accounts on trial balance''' def Help(): '''What to do when <Help> button is clicked''' print("Window 01 <Help>") def Next(*args): '''What to do when <Next> button is clicked''' print("Window 01 <Next>") Window02(master, 2) frame01.grid_forget() def Exit(): '''What to do when <Exit> button is clicked''' print("Window 01 <Exit>") master.destroy() frame01 = Frame(master, width=400) frame01.grid(row=0) # Bind '<Return>' key to Next function: master.bind('<Return>', Next) # Define text variable: Status = StringVar(frame01) # Set text variable default: Status.set("Click <Next> to continue.") # Define number entry field: number_entry = Entry(frame01, width=15) # Define text grid handles: text01 = Label(frame01, text="How many accounts on the trial balance?") text02 = Label(frame01, text="Enter a number:") text03 = Label(frame01, textvariable=Status) # Define spacers: spacer01 = Frame(frame01, height=2, width=400, bd=1, relief=SUNKEN) spacer02 = Frame(frame01, height=20, width=195) spacer03 = Frame(frame01, height=20, width=395) spacer04 = Frame(frame01, height=20, width=395) spacer05 = Frame(frame01, height=20, width=395) spacer06 = Frame(frame01, height=2, width=400, bd=1, relief=SUNKEN) spacer07 = Frame(frame01, width=95) # Define buttons: help_button = Button(frame01, text="Help", command=Help) next_button = Button(frame01, text="Next", command=Next) exit_button = Button(frame01, text="Exit", command=Exit) # Place window elements: text01.grid(row=2, columnspan=4) spacer01.grid(row=3, columnspan=4) text02.grid(row=4, sticky=W) spacer02.grid(row=4, column=1) number_entry.grid(row=4, column=2, sticky=E, padx=5, pady=5, columnspan=2) spacer03.grid(row=5, columnspan=4) spacer04.grid(row=6, columnspan=4) spacer05.grid(row=7, columnspan=4) text03.grid(row=8, columnspan=4) spacer06.grid(row=9, columnspan=4) help_button.grid(row=10, sticky=W, padx=5) spacer07.grid(row=10, column=1) next_button.grid(row=10, column=2, sticky=E, pady=5) exit_button.grid(row=10, column=3, sticky=E, padx=5) # --------------------------------------- # Trial Balance accounts frame: # --------------------------------------- def Window02(master, number): '''Frame for accounts on trial balance''' def Help(): '''What to do when <Help> button is clicked''' print("Window 02 <Help>") def Next(*args): '''What to do when <Next> button is clicked''' print("Window 02 <Next>") def Exit(): '''What to do when <Exit> button is clicked''' print("Window 02 <Exit>") master.destroy() frame02 = Frame(master, width=400) frame02.grid(row=1) # Bind '<Return>' key to Next function master.bind('<Return>', Next) # Define text variables: Menu01 = StringVar(frame02) Menu02 = StringVar(frame02) Status = StringVar(frame02) # Set text variable defaults: Menu01.set('-----') Menu02.set('-----') Status.set("Click <Next> to continue.") # Define text grid handles: text01 = Label(frame02, text="Enter the following for each account.") text02 = Label(frame02, text="Name:") text03 = Label(frame02, text="Balance:") text04 = Label(frame02, text="Normal Balance:") text05 = Label(frame02, text="Type:") text06 = Label(frame02, textvariable=Status) # Define menu option lists: norm_bal_options = ("Debit", "Credit") acct_type_options = ("Asset", "Liabitity", "Owner Equity", "Revenue", "Expense") # Define entry fields and menus: name_entry = Entry(frame02, width=20) bal_entry = Entry(frame02, width=20) norm_bal_menu = OptionMenu(frame02, Menu01, *norm_bal_options) acct_type_menu = OptionMenu(frame02, Menu02, *acct_type_options) # Define spacers: spacer01 = Frame(frame02, height=2, width=400, bd=1, relief=SUNKEN) spacer02 = Frame(frame02, height=25, width=40) spacer03 = Frame(frame02, height=20, width=40) spacer04 = Frame(frame02, height=20, width=40) spacer05 = Frame(frame02, height=20, width=40) spacer06 = Frame(frame02, height=2, width=400, bd=1, relief=SUNKEN) spacer07 = Frame(frame02, height=20, width=20) # Define buttons: help_button = Button(frame02, text="Help", command=Help) next_button = Button(frame02, text="Next", command=Next) exit_button = Button(frame02, text="Exit", command=Exit) # Place frame elements: text01.grid(row=2, columnspan=4) spacer01.grid(row=3, columnspan=4) text02.grid(row=4, sticky=W) spacer02.grid(row=4, column=1) name_entry.grid(row=4, column=2, sticky=E, padx=5, columnspan=2) text03.grid(row=5, sticky=W) spacer03.grid(row=5, column=1) bal_entry.grid(row=5, column=2, sticky=E, padx=5, columnspan=2) text04.grid(row=6, sticky=W) spacer04.grid(row=6, column=1) norm_bal_menu.grid(row=6, column=2, sticky=E, padx=2.5, columnspan=2) text05.grid(row=7, sticky=W) spacer05.grid(row=7, column=1) acct_type_menu.grid(row=7, column=2, sticky=E, padx=2.5, columnspan=2, ) text06.grid(row=8, columnspan=4) spacer06.grid(row=9, columnspan=4) help_button.grid(row=10, sticky=W, padx=5) spacer07.grid(row=10, column=1) next_button.grid(row=10, column=2, sticky=E, pady=5) exit_button.grid(row=10, column=3, sticky=E, padx=5) # --------------------------------------- # Initiator: # --------------------------------------- Window00()
50f8bd145f84bbe1082c2c0f5c0dfdda8842be84
Chief16/Programs
/PastExe/PassGen2.py
207
3.625
4
import random a = int(input("Enter the digit :")) text = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM12345677890!@#$%^&*()?" passlen = a result = ' '.join(random.sample(text,passlen)) print(result)
45baf38ed5c8dd3d6e6a208eb0bb4ead8497dfa9
hemantcaf/RSA
/signature.py
717
3.71875
4
def sign(name, d, n): signedName = 1 d = '{0:b}'.format(d) for i in range(len(d)): signedName = (signedName * signedName) % n if d[i] == '1': signedName = (signedName * name) % n return signedName if __name__ == '__main__': D = int(input("Enter Private key")) N = int(input("Enter Modulo N")) name = 'hemant' name1 = name[0:3].encode('ascii') name2 = name[3:6].encode('ascii') name1 = name1.hex() name2 = name2.hex() name1 = int(name1, 16) name2 = int(name2, 16) print('The signature chunks', name1, name2) signature1 = sign(name1, D, N) signature2 = sign(name2, D, N) print('The signature is', signature1, signature2)
4cc1a3d968ed78696af7df91de45989399ada6de
silvareal/advance_python
/oop/oop_2-(property)/property/oop_properties.py
712
3.796875
4
''' property is the pythonic mechanism to implementing encapsulation and the interface to interact with private attributes of an object ''' class Email: #property def __init__(self, address): self._email = address #a private attribute def _set_email(self, value): if '@' not in value: print("not a valid mail address") else: self._email = value def _get_email(self): return self._email def _del_email(self): print("erasing mail...") del self._email #these interface provide the public attribut email email = property(_get_email, _set_email, _del_email, "this property contains the email")
508eec84e2973f8213db6f49c170b1e62a956b1d
rodrigo-r-martins/programming-problems
/leetcode/array/maxConsecutives.py
687
3.921875
4
""" Given a binary array, find the maximum number of consecutive 1s in this array. => Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain 0 and 1. The length of input array is a positive integer and will not exceed 10,000 """ def maxConsecutives(arr): max_consecs = 0 count = 0 for num in arr: if num == 1: count += 1 if count > max_consecs: max_consecs = count else: count = 0 return max_consecs if __name__ == "__main__": arr = [1,1,0,1,1,1] print(maxConsecutives(arr))
605f1c6b3220d2a31009024320bfdc5fc60b542a
comigo-github/data-collection-scripts
/data_collection_scripts/utf_decoder.py
1,218
3.765625
4
import sys, csv ''' @Date: 29.5.18 @Version: 1.0.0 @Author: Dorel Moran @Description: ''' def utf_decoder(input_file, output_file): with open(input_file + '.csv', newline='', encoding='utf-8') as input: reader = csv.reader(input) reader.__next__() with open(output_file + '.csv', 'w', newline='', encoding='utf-8') as output: writer = csv.writer(output) for row in reader: print(row[0]) new_row = row[0].encode('iso-8859-1').decode('utf-8') writer.writerow(new_row) def main(): try: if len(sys.argv) >= 2: input_file = sys.argv[1] else: input_file = input("Please enter input csv file name:") if len(sys.argv) >= 3: output_file = sys.argv[2] else: output_file = input("Please enter output csv file name:") utf_decoder(input_file, output_file) print("Successfuly created '" + output_file + "-.csv' from '" + input_file + ".csv'.", '\n') except IOError: print('\nI\O Error - make sure: \n A. Name of input file is correct. \n B.' ' No files with given input/output name are currently open.') if __name__ == '__main__': main()
7ed7b77f95f5961358918778d997a7d0f9b6dae6
Wangkaixinlove/python
/project1/test.py
646
4.09375
4
# 姓名:wkx # 日期:20190712 name="wkx" print("hello "+name+", would you like to learn some Python today?") name2="zzx" print(name2.upper(),name2.lower(),name2.title()) sentence='Albert Einstein once said, “A person who never made a mistake never tried anything new.”' print(sentence) famous_person="Albert Einstein" message ='“A person who never made a mistake never tried anything new.”' print(famous_person+" once said, "+message) name3="\twang\nkaixin "+"123" print(name3) print(name3.lstrip()) print(name3.rstrip()) print(3+5) print(12-4) print(2*4) print(800/100) age=22 message = "Happy " + age.__str__() + "rd Birthday!" print(message)
5a0e9dd4b42ee447140cf6923f872f1a3bd86cc7
harshsavasil/interview-preparation
/heaps/connect_ropes.py
755
4.1875
4
# Problem Statement - Connect Ropes # Given an array of length of ropes # Find the minimum cost of connecting these ropes. # cost of connecting two ropes of length X and Y = X + Y # video link - https://www.youtube.com/watch?v=_k_c9nqzKN0&list=PL_z_8CaSLPWdtY9W22VjnPxG30CXNZpI9&index=9 # solution - merge the ropes of minimum length at any time to get the minimum cost import heapq # test case elements = [1, 2, 3, 4, 5] # Processing test case if len(elements) == 0: print(0) min_heap = [] heapq.heapify(elements) min_cost = 0 while len(elements) != 1: rope_x = heapq.heappop(elements) rope_y = heapq.heappop(elements) min_cost += (rope_x + rope_y) heapq.heappush(elements, rope_x + rope_y) print("Min cost : {0}".format(min_cost))
61d71778798355a594a2d9826284934ef118171b
natasyaoktv/basic-python-b3
/classes.py
204
3.5625
4
class Myclass: x = 5 y = 10 luas = x*y # class wajib dipanggil def Myclasses(): x = 5 return x # return dulu p1 = Myclass() print(p1.luas) print(p1.x) print(p1.y) print(Myclasses())
6513bc6a25cbcdf7a2b7c03c05aa50f7c105dd60
PryanyyMed/QA_study
/schedule.py
1,386
4.09375
4
#1. Принимаю от пользователя дату #2. Составляю расписание раз в 2 дня (через день) #3. На 30 дней ДД ММ ГГ и день недели #4. Если это воскресенье, то перенести на понеделтник и опять через день import datetime #прошу у пользователся дату date_entry = input("Введите дату в формате ДД, ММ, ГГГГ ") #перевожу в формат даты ДД ММ ГГГГ - если ввести формат по-другому, то программа не запустится dt = datetime.datetime.strptime(date_entry, "%d, %m, %Y") #вывод списка по дням #скачать pip DateTimeRange (https://pypi.org/project/DateTimeRange/#get-iterator) from datetimerange import DateTimeRange # date_End - финальная дата через 30 дней date_End = datetime.timedelta(days=30) time_range = DateTimeRange(dt, dt + date_End) print ("Расписание на месяц: ") #список выводится через день (days=2) for value in time_range.range(datetime.timedelta(days=2)): #проверка на то, что будут выводиться дни с пн до сб if value.weekday() in range(0,6): print(value.strftime ("%A, %d %B, %Y"))
08693ddec2205ccaa3fbe2710a8accb1e43320bd
lxmambo/caleb-curry-python
/32-sort-numbers-as-strings.py
345
3.8125
4
numbers = [1,54,76,12,111,4343,6,8888,3,222,1,0,222,-1,-122,5,-30] numbers_str = ['1','54','76','12','111','4343','6','8888','3','222','1','0','222','-1','-122','5','-30'] numbers2 = numbers[:] numbers_str.sort() print(numbers_str) numbers2.sort(key=str) #converts numbers into a string #equivalent to do str(5) for all numbers print(numbers2)
e9e28908b3df227810ed3684aade69fcec471411
fluffigvarg/stonks
/stonks.py
2,834
3.5625
4
''' Simple program meant to automatically update stock prices and changes based on a defined interval. ''' from yahoo_fin import stock_info as si import time import schedule from datetime import datetime from termcolor import colored class StockTicker: def __init__(self, stock_name, moon_price=None): self.stock_name = stock_name self.initial_price = 0 self.current_price = 0 self.moon_price = moon_price # Target price for alerts self.delta = 0 self.percent_change = 0 self.text_color = "" def ShowLivePrices(self): current_time = datetime.now() current_time = current_time.strftime("%I:%M:%S %p") self.current_price = (si.get_live_price(self.stock_name)) self.delta = self.current_price - self.initial_price self.percent_change = self.delta / self.initial_price self.percent_change *= 100 if self.delta > 0: self.text_color = "green" elif self.delta < 0: self.text_color = "red" else: self.text_color = "white" print(colored(f"{self.stock_name}: Current ${self.current_price:.2f} (${self.delta:.2f} {self.percent_change:.2f}%) | Initial ${self.initial_price:.2f} | {current_time}", self.text_color)) def Alerts(self): # Alerts for target prices, a.k.a. Moon Price if self.moon_price: if self.current_price > self.moon_price: print(colored("--------------------------", "green")) print(colored(f"Pay attention to {self.stock_name}! It's going to the moon!", "green")) print(colored("--------------------------", "green")) if self.current_price > (self.moon_price * .5): print(colored("--------------------------", "yellow")) print(colored(f"{self.stock_name} is half way to the moon!", "yellow")) print(colored("--------------------------", "yellow")) def InitialPrice(self): self.initial_price = (si.get_live_price(self.stock_name)) # How often you want to update prices (currently in seconds) update_time = 600 # Create objects for each stock you want to track ("Ticker Symbol", Moon Price) gme = StockTicker("GME", 1000) amc = StockTicker("AMC", 40) # Add stock objects here stonks = [gme, amc] # Grab price at launch of app for a reference point for stonk in stonks: stonk.InitialPrice() # Just an intro message print(f"Fueling up the rocket, please be patient...will take about {update_time} seconds...") # Check live price and alert to swings for stonk in stonks: schedule.every(update_time).seconds.do(stonk.ShowLivePrices) schedule.every(update_time).seconds.do(stonk.Alerts) # Used for timer while True: schedule.run_pending() time.sleep(1)
a903edc0a166f99c587f49503f2d882cbc43b5e1
feifyKike/Star-Wars-Shootout
/asteroid.py
1,528
3.765625
4
import pygame from pygame.sprite import Sprite import random class Asteroid(Sprite): """Creating a single asteroido to be model after""" def __init__(self, ai_settings, screen): """Initialize attributes for asteroid""" super().__init__() self.ai_settings = ai_settings self.screen = screen # Load the asteroid image and get its rect self.asteroid_image = pygame.image.load('asteroid_pic.bmp') self.rect = self.asteroid_image.get_rect() # Start the position of the asteroid #self.screen_rect = self.screen.get_rect() #self.rect.right = self.screen_rect.right #self.rect.left = self.screen_rect.centery # Create a random spawn point on the right side of the screen self.screen_rect = self.screen.get_rect() self.rect.right = self.screen_rect.right spawn_range = ai_settings.screen_height - self.rect.height random_positiony = random.uniform(self.rect.height, spawn_range) self.rect.centery = random_positiony # Store the aliens exact position self.x = float(self.rect.right) self.speed_factor = ai_settings.asteroid_speed_factor def update(self): """Move bullet to the left of the screen""" self.x -= self.speed_factor # Update the rect position self.rect.x = self.x def blitme(self): """Draw the asteroid at its static location""" self.screen.blit(self.asteroid_image, self.rect)
4e8bb1a5824ff612dcda7aa04e3a8d099cb22cc7
juandab07/Algoritmos-y-programacion
/Ejercicio_17.py
514
4.0625
4
""" entradas montopresupuestado->float->presupuesto salidas ginecologia->float->ginecologia traumatologia->float->traumatologia pediatria->float->pediatria """ presupuesto=float(input(" digite el monto presupuestado " )) ginecologia=presupuesto*0.40 traumatologia=presupuesto*0.30 pediatria=presupuesto*0.30 print("el monto designado para ginecologia es: " +str(ginecologia)) print("el monto designado para traumatologia es: " +str(traumatologia)) print("el monto designado para pediatria es: " +str(pediatria))
7306ffbe67ab2be256974b859f3a6ac96edfe47a
redbillb/labs_data_science_academy
/Cap03/Lab02/calculadora.py
1,046
4.1875
4
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! print("\n******************* Python Calculator *******************") print("\nSelecione o numero da operacao desejada:") print("\n1 - Soma") print("2 - Subtracao") print("3 - Multiplicacao") print("4 - Divisao") opcao = int(input("\nDigite sua opcao (1/2/3/4): ")) if ( opcao < 1 or opcao > 4): print("opcao escolhida %s e invalida" %(opcao)) else: numero1 = int(input("\nDigite o primeiro numero: ")) numero2 = int(input("\nDigite o segundo numero: ")) resultado = 0 operacao = "" if ( opcao == 1 ): resultado = numero1 + numero2 operacao = "+" elif( opcao == 2 ): resultado = numero1 - numero2 operacao = "-" elif( opcao == 3 ): resultado = numero1 * numero2 operacao = "*" else: resultado = numero1 / numero2 operacao = "/" print ("\n\n%s %s %s = %s\n\n" %(numero1,operacao,numero2,resultado))
754078163a4663797b6c9d9012a2c218d7950a44
jclane/beginner-project-solutions
/python/google_case.py
1,861
4.1875
4
def google_casify(sentence): """ Returns the provided string in Google Case by first splitting the string into a list, filtering out any empty elements (extra spaces) and then looping through the result to make the first letter lowercase and the rest of the word uppercase. :param sentence: the string to be converted :return: a string representing the converted sentence """ sentence_list = filter(None, sentence.split(" ")) converted = [] for word in sentence_list: converted.append(word[0].lower() + word[1:].upper()) return " ".join(converted) def camel_casify(sentence): """ Returns the provided string in Camel Case by first spiltting the string into a list, filtering out any empty elements (extra spaces) and then looping through the resulting list of elements (words) The first element is dropped to lowercase, while the rest have the first character capitalized and the remaining changed to lowercase. :param sentence: the string to be converted :return: a string representing the converted sentence """ sentence_list = list(filter(None, sentence.split(" "))) converted = [] for ndex in range(0, len(sentence_list)): if ndex == 0: converted.append(sentence_list[ndex].lower()) else: converted.append(sentence_list[ndex][0].upper() + sentence_list[ndex][1:].lower()) return "".join(converted) def main(): while True: sentence = "" while not sentence: sentence = input("Enter sentence to convert >> ") if sentence.lower() in ["quit", "q"]: break else: print("Google Case: {}".format(google_casify(sentence))) print("Camel Case: {}".format(camel_casify(sentence))) main()
a311c44e1911c1bd846e6904ea50a20ce4d4dfd7
kenjimouriml/kyopro
/kenchon/ch03/test_get_min_pair.py
1,997
3.703125
4
import unittest from main import get_min_pair class SearchTest(unittest.TestCase): def test_get_min_pair_ok(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = [7, 2, 19, 4, 5, 3] K = 15 self.assertEqual(get_min_pair(num_list1, num_list2, K), 20) def test_get_min_pair_K(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = [7, 2, 19, 4, 5, 3] K = 90 self.assertEqual(get_min_pair(num_list1, num_list2, K), K) def test_get_min_value_typeerror1(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = 5 K = 90 with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) def test_get_min_value_typeerror2(self): num_list1 = 3 num_list2 = [1, 2, 3, 4, 5, 6] K = 90 with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) def test_get_min_value_typeerror3(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = [1, 2, 3, 4, 5, 6] K = [1, 3] with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) def test_get_min_value_typeerror4(self): num_list1 = [1, 2, 3, 4, "string", 6] num_list2 = [1, 2, 3, 4, 5, 6] K = 5 with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) def test_get_min_value_typeerror5(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = [1, 2, 3, 4, "string", 6] K = 5 with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) def test_get_min_value_typeerror6(self): num_list1 = [1, 2, 3, 4, 5, 6] num_list2 = [1, 2, 3, 4, 5, 6] K = "string" with self.assertRaises(TypeError): get_min_pair(num_list1, num_list2, K) if __name__ == "__main__": unittest.main()
8dbd635ab1396941aa47d8e3d4cbbb9e32d679d1
rafaelperazzo/programacao-web
/moodledata/vpl_data/67/usersdata/162/34004/submittedfiles/imc.py
293
3.9375
4
p=float(input('Digite o peso em quilos:')) h=float(input('Digite a altura em metros:')) IMC==p/(h**2) if IMC<20: print('ABAIXO') if 20<=IMC<=25: print('NORMAL') if 25<IMC<=30: print('SOBREPESO') if 30<IMC<=40: print('OBESIDADE') if IMC>40: print('OBESIDADE GRAVE')
1a64cc452b8dbfa3b03a1b4f488aaa16ed2a5bb7
octue/octue-app-wind-resource
/wind_resource/figures.py
1,799
3.625
4
from octue import analysis import json def create_figure_file(): """ Saves json file constructed from some analysis results. The json will be used later to create a figure. File can be saved to an arbitrary location, but by default is saved to the current directory """ # Any plotly compliant dict or list that can be converted to json. You can use the Plotly python sdk to construct figures, by adding it to requirements.txt fig = {"data": [{"x": ["giraffes", "orangutans", "monkeys"], "y": [20, 14, 23], "type": "bar" }]} # Dump the dict to a plain text json file. Note that for more advanced data (e.g. including numpy arrays etc) you # may wish to use the serialiser provided with the plotly library name = analysis.output_dir + '/zoo_barchart.json' with open(name, 'w') as outfile: json.dump(fig, outfile) # You can either do this here, or in your main run() function definition (or basically anywhere else you like)... # but you need to add the created file (which is part of the analysis results) to the output results manifest. In # this case we do it here, which has the advantage of keeping file creation and manifesting together; but has the # disadvantage of needing to modify your code to pass the analysis around. If you're unable to alter the API of your # code; no problem - just do all your manifest creation separately (e.g. at the end of the run function) fig_data = {'name': name, 'short_caption': 'A shortened caption', 'caption': 'A longer caption, perhaps including some description of why on earth we would want to see a bar chart of different zoo animals'} # TODO add_to_manifest('figure', name, fig_data)
70c1acdce1f57bc89e5ea3a87a0d373e567a6c84
alvaronaschez/amazon
/leetcode/amazon/dynamic_programming/longest_palindromic_substring.py
1,776
4.125
4
""" https://leetcode.com/explore/interview/card/amazon/80/dynamic-programming/489/ Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ def is_palindrome(s: str) -> bool: return s[::-1][:len(s)//2] == s[:len(s)//2] def is_palindrome_old(s: str, i: int, j: int) -> bool: return s[i:j] == s[i:j][::-1] def longestPalindrome(s: str) -> str: """ iterate over all possible lengths then over all possible substring of that length there are 1+2+...+n-1 possibilities, so its O(n**2) """ for n in reversed(range(len(s)+1)): for i in range(len(s)-n+1): if is_palindrome(s[i: i+n]): return s[i: i+n] def longestPalindrome_bruteforce(s: str) -> str: """ brute force: test all possible starts and ends """ n = 0 x = 0 y = 0 for i in range(len(s)+1): for j in range(i+1, len(s)+1): if j-i <= n: continue if is_palindrome_old(s, i, j): if j-i > n: # redundant but cheap x, y = i, j n = j-i return s[x: y] def longestPalindrome_dynamicprogramming(s: str) -> str: """dynamic programming""" a = [[False]*len(s) for _ in range(len(s))] m, x, y = 0, 0, -1 for i in reversed(range(len(s))): for j in range(i-1, len(s)): a[i][j] = j-i+1 <= 1 or (j-i-1 <= 1 or a[i+1] [j-1]) and s[i] == s[j] if a[i][j] and j-i+1 >= m: m, x, y = j-i+1, i, j return s[x:y+1]
15df31e9107ae345d22cb3933e77cb7233d8679e
eqfinney/algorithms
/merge_sort.py
1,765
4.25
4
# My implementation of the merge sort algorithm # Author: Emily Quinn Finney """ Challenge extensions: - can we get this to work with any iterable? - GENERATORS??? """ def merge_sort(unsorted_list): """ Given an unsorted list, returns the sorted version. unsorted_list: a list, unsorted. sorted_list: a list, sorted. >>> merge_sort([2,1,3]) [1, 2, 3] >>> merge_sort([3,2,1]) [1, 2, 3] """ n = len(unsorted_list) # base case if n <= 1: return unsorted_list else: # split the lists in half import ipdb; ipdb.set_trace() first_list = merge_sort(unsorted_list[:int(n/2)]) second_list = merge_sort(unsorted_list[int(n/2):]) sorted_list = merge_lists(first_list, second_list) return sorted_list def merge_lists(first_list, second_list): """ Merge two lists """ # run through a for loop and sort accordingly first_pointer = 0 second_pointer = 0 n = len(first_list+second_list) sorted_list = [] for i in range(n): # dealing with the end of the list if first_pointer == len(first_list): sorted_list += second_list[second_pointer:] break elif second_pointer == len(second_list): sorted_list += first_list[first_pointer:] break # dealing with cases that are not the end of the list elif first_list[first_pointer] <= second_list[second_pointer]: sorted_list += [first_list[first_pointer]] first_pointer += 1 else: sorted_list += [second_list[second_pointer]] second_pointer += 1 return sorted_list if __name__ == '__main__': import doctest doctest.testmod()
21c90f80e0c3f2411455296441e6704cc444ec01
ekdus1203/PythonLecc
/_03_if.py
1,173
3.921875
4
# 1) if문 # ; 조건문 # 조건이 참(True)면 실행, # 아니면 실행하지 않음 # 2) 간단한 if문 # str_money = input('현재 금액은?') # 문자열 '1000' # money = int(str_money) # 숫자 1000 # if money >= 1200: # print("빵 사먹을 수 있다 ^^") # 3) if else문 # str_money = input('현재 금액은?') # 문자열 '1000' # money = int(str_money) # 숫자 1000 # if money >= 1200: # print("빵 사먹을 수 있다 ^^") # else: # print("빵 못 사먹는다") # 4) if elif else문 # ; 10000 이상 케익 사먹을 수 있다 # 5000 이상 담배 사 필 수 있다 # 3000 이상 콜라 마실 수 있다 # 1200 이상 빵 사먹을 수 있다 # 1200 미만 못 사먹는다 # str_money = input('현재 금액은?') # 문자열 '1000' # money = int(str_money) # 숫자 1000 # if money >= 10000: # print("케익 사먹을 수 있다 ^^") # elif money >= 5000: # print("담배 사 필 수 있다 ^^") # elif money >= 3000: # print("콜라 마실 수 있다 ^^") # elif money >= 1200: # print("빵 사먹을 수 있다 ^^") # else: # print("못 사 먹는다 ^^")
991f550e361b07da181caa06d52f3827f6321c53
luan-gomes/python-basic-exercises
/decision/10.py
613
4.125
4
""" Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. """ print("Considere os seguintes códigos para responder a questão a seguir:") print("M - Matutino\nV - Vespertino\nN - Noturno") answer = input("Em que turno você estuda? Utilize os códigos supracitados!") if answer.lower() == 'm': print("Bom dia!") elif answer.lower() == 'v': print("Boa tarde!") elif answer.lower() == 'n': print("Boa noite!") else: print("Valor Inválido!")
346a8a53a5414e52c746f3a417fe2419e11a4f49
start555/Python_Learning
/Kurs/Lesson2/15.2.2.py
265
3.859375
4
# 2. Четные индексы # Выведите все элементы списка с четными индексами # (то есть A[0], A[2], A[4], ...). # Условия не использовать. lst = list(range(25)) lst2 = lst[::2] print(lst2)
158c7709e6856d36b40f81df4abe3d9b8e2fba77
sx0785/myPython
/fun_list_comprehensions.py
712
3.84375
4
list = [1,2,"a",3.14,True] #List comprehensions #[expr for val in collection] #[expr for val in collection if <test>] #[expr for val in collection if <test1> and <test2>] #[expr for val1 in collection1 and val2 in collection2] squares = [] for i in range(1,11): squares.append(i**2) print(squares) squares2 = [i**2 for i in range(10)] print(squares2) remainders5 = [x**2 % 5 for x in range(1,30)] print(remainders5) movies = ["Star Wars","Ghostbusters"] gmovies = [m for m in movies if m.startswith("G")] print(gmovies) movies = [("Star Wars",2010),("Ghostbusters",1999)] gmovies = [m[0] for m in movies if m[1]>2000] print(gmovies) A=[1,3,5,7] B=[2,4,6,8] C=[(a,b) for a in A for b in B] print(C)
adb96de27062ea0ebe176a60c3366178443e1a90
ebanner/project_euler
/grammar.py
1,284
3.703125
4
if __name__ == '__main__': digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] specials = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] all_numbers = [] for digit in digits: # will count up 1-9 all_numbers.append(digit) for teen in teens: # will count up 10-19 all_numbers.append(teen) offset = 0 for special in specials: all_numbers.append(special) for digit in digits: all_numbers.append(special+digit) one_through_ninety_nine = all_numbers[:] HUNDRED = 'hundred' AND = 'and' offset = 0 for digit in digits: all_numbers.append(digit+HUNDRED) for number in one_through_ninety_nine: all_numbers.append(digit+HUNDRED+AND+number) all_numbers.append('one'+'thousand') for i in range(0,len(all_numbers)-5,5): print("{:<30} {:<30} {:<40} {:<50} {:<60}".format(all_numbers[i], all_numbers[i+1], all_numbers[i+2], all_numbers[i+3], all_numbers[i+4])) print(all_numbers[-1]) total = 0 for number in all_numbers: total += len(number)
2562d899456b26515e045e0ed68ce83efb080197
gsudarshan1990/Python_Sets
/Special_Methods3/student1.py
322
3.765625
4
class Student: def __init__(self, name, favorite_subject,age): self.name = name self.age = age self.favorite_subject = favorite_subject def __str__(self): return f"name :{self.name} age:{self.age} favorite_subject:{self.favorite_subject}" s1=Student("sonu","physics",15) print(s1)