blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
f11081f19d408f5a8dd5716f54476782484ba3b7
Immutare/euler-project
/eu3.py
351
3.53125
4
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ numero = 600851475143 factors = [] prime = 2 while True: if numero % prime == 0: factors.append(prime) numero = numero / prime else: prime+=1 if numero == 1: break print factors[-1:]
4c20561b630ea391b2ccebf306552bab5e3fad46
liuyanglxh/python-comprehensive
/arithmetic/mergeKLists/s2.py
773
3.5
4
from typing import List import functools from arithmetic.listnode import ListNode class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: lists = [ele for ele in lists if ele] # 倒叙排 def cmp(a: ListNode, b: ListNode): return b.val - a.val sorted(lists, key=functools.cmp_to_key(cmp)) head, tail = None, None while len(lists) > 0: index = len(lists) - 1 last_ele = lists[index] if not head: head, tail = last_ele, last_ele else: tail.next, tail = last_ele, last_ele if not last_ele.next: del lists[index] elif index != 0: lists[index] = last_ele.next pre, cur = lists[index - 1], lists[index] while index > 0 and pre.val < cur.val: lists[index - 1], lists[index] = cur, pre return head
db2be9683795956e279b869a6b4fd46b2c35f640
keeykeey/dogclassifier
/makedata.py
403
3.53125
4
#二つの犬の写真をモデルに投入できる型に整形する import os import numpy as np import pandas as pd class picturesdirectory(self): ''' <USAGE> ex) dir_name = picturesfile() #dir_name:directory which has some pictures to put into models in ''' def __init__(self,dirname); self.name = dirname self.pic_inside = os.listdir(dirname)
950550d66f2b5321fabf83eab06165c43e8b2869
joselluis7/bookstore
/app/helpers/utils.py
203
3.703125
4
#-*-encoding:utf-8-*- import locale def list_string(l): s = "" item = 0 if len(l) > 1: for item in range(len(l) - 1): s = s + l[item] + ", " s = s + l[item + 1] else: s = l.pop() return s
54c47a192ce2e43b3da61e8f1f57e6d59a42da4e
Ahmed-Sanad24/FEE
/question2-buylotsofFruit.py
700
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[8]: # we need that the price of 2 kilos of apple and 3 of pear and 4 of limes is 12.25 pounds # so we assume the price of these fruits according to this price fruitprice = {'apples': 1.00 ,'pears': 1.75 , 'limes': 1.25 , 'bananas':2.00 , 'oranges': 0.75 } # In[22]: def buylotsofFruit(orderlist): totalprice=0.00 totalprice = ( 1*orderlist[0][1] +1.75*orderlist[1][1] +1.25*orderlist[2][1] ) return totalprice # In[23]: testlist = [('apples',2.0),('pears',3.0),('limes',4.0)] try: print("the cost of ",testlist , "is ", buylotsofFruit(testlist)) except: print("error : the fruit you entered is not in the list of prices !")
9e779e2f52e92306fb44c1f50d0ed4286cff65b5
asyrul21/recode-beginner-python
/materials/week-5/src/endOfClass-1.py
593
4.34375
4
# The first part of this exercise is to define a function which returns a boolean. # it returns True if the number is odd, otherwise return False # If you remember, we assume that if a number is divided by 2 has a remainder of non 0, the # number is an odd number. # The loop will iterate through a list of numbers, and will call your function to check # if each of the number is odd print("Printing odd numbers") # define your function here def isOdd(number): ... numbers = range(0, 20) for number in numbers: if(isOdd(number)): print(str(number) + " is an odd number")
2c992e4a60f69a6bee14273f174dc8e76722078a
BlackRob/Euler
/prob24.py
1,603
3.765625
4
def genOrderedPerms(lcr,perms,p_in): """ generate ordered permutations by splitting lcr = list of characters remaining the idea is given a list of characters, the set of all possible permutations of those characters can be split into len(lcr) subsets, each starting with a particular character, for example, if our characters are a,b,c,d, our set of permutations can be split into sets starting with a, starting with b, etc. Each subset can be treated exactly as the original set, except one character has been removed from the lcr. If we operate recursively, we can create all permutations in order, or even just count them, as in this case where we only care about a particular permutation (the millionth) """ global j # our counter global p # length of perms list, doesn't change depth = p - p_in #if j == 15: # when we have counted this high we are done # print(perms) # return for i in range(p_in): llcr = list(lcr) # list of local characters remaining #print('depth = ',str(depth),' i = ',i,' ',p_in,' ',str(len(lcr))) perms[depth] = llcr[i] del llcr[i] if len(llcr) == 0: j += 1 if j == 1000000: print(perms,j) break return genOrderedPerms(llcr,perms,p_in-1) j = 0 # generated permutation counter perms = [0,0,0,0,0,0,0,0,0,0] p = len(perms) cars = ['0','1','2','3','4','5','6','7','8','9'] genOrderedPerms(cars,perms,p) print(perms,j)
00325bb2a5cdaaab88de688ec8312b7b1e0e04d5
qingyunpkdd/pylib
/design pattern/share.py
1,099
3.578125
4
#-*- encoding:utf-8 -*- __author__ = '' class Share_m(): def __init__(self,name=""): self.value={} self.name=name def __getitem__(self, item): print("method __getitem__{item} return".format(item=item)) return self.value[item] def __setitem__(self, key, value): print("method __setitem__") self.value[key]=value def __del__(self): print("delete item") del self.value class Obj: def __init__(self, value): self.content = value def __str__(self): return self.content class Share(object): def __init__(self): super().__init__() self.dct = {} def __getitem__(self, item): return self.dct.get(item, None) def __setitem__(self, key, value): self.dct[key] = value def main(): share = Share() share['one'] = Obj("a") share['two'] = Obj("b") share['one'] = Obj("c") one = share['one'] print(str(one)) if __name__ == '__main__': main() # s = Share_m("share obj") # s["c1"] = "object" # print(s["c1"]) # del s
08f62ea0742a2e489bfb3007c1ed14c2e4f92b4f
Aasthaengg/IBMdataset
/Python_codes/p02263/s708155947.py
365
3.59375
4
def push(x): global stack stack.append(x) def pop(): global stack ret = stack.pop() return ret ope = {"+": lambda a, b: b + a, "-": lambda a, b: b - a, "*": lambda a, b: b * a} if __name__ == '__main__': stack = [] for c in input().split(): if c in ope: push(ope[c](pop(), pop())) else: push(int(c)) print(" ".join(map(str, stack)))
623f329a718fcc13167a868f900e9ab079de7d3b
Zjianglin/Python_programming_demo
/chapter6/6-15.py
2,190
3.5625
4
''' 6-15.转换。 (a)给出两个可识别格式的日期,比如MM/DD/YY或者DD/MM/YY格式,计算出两 个日期间的天数。 (b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月。 (c)还是上面的例子,计算出到此人下次过生日还有多少天。 ''' import time def date2num(ds): ''' format: DD/MM/YYYY return the number of days since 1/1/1900 ''' months = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) date = [int(i) for i in ds.strip().split('/')] is_leap_year = lambda y: (y % 400 == 0) or (y % 4 == 0 and y % 100) days = date[0] + sum(months[:date[1]]) if is_leap_year(date[2]) and date[1] > 2: days += 1 years = (date[2] - 1900) days += (365 * years + years // 4) return days def days_gap(date1, date2): ''' date1 and date2 are string ''' return abs(date2num(date1) - date2num(date2)) def birthed_days(birthday): dnow = time.localtime() dn = [dnow.tm_mday, dnow.tm_mon, dnow.tm_year] dn = [str(i) for i in dn] return days_gap(birthday, '/'.join(dn)) def next_birthday(birthday): dnow = time.localtime() dn = [dnow.tm_mday, dnow.tm_mon, dnow.tm_year] db = [int(i) for i in birthday.strip().split('/')] if dn[1] == db[1] and dn[0] < db[0]: #same month, birthday doesn't pass return dn[0] - db[0] + 1 elif dn[1] > db[1] or (dn[1] == db[1] and dn[0] < db[0]): #this year passed date2 = '/'.join([str(db[0]), str(db[1]), str(dn[2] + 1)]) else: date2 = '/'.join([str(dn[0]), str(dn[1]), str(dn[2])]) date1 = '/'.join([str(db[0]), str(db[1]), str(dn[2])]) return days_gap(date1, date2) def main(): dates = ['2/1/1900', '16/1/2017', '16/1/2018'] birthdays = ['6/1/2017', '26/2/2017'] for d in dates: print("days between '{}' and '{}': {}".format(d, '16/1/2018', days_gap(d, '16/1/2018'))) for b in birthdays: print("birthday is {}, has been {} days since born, {} to next birthday".format( b, birthed_days(b), next_birthday(b) )) if __name__ == '__main__': main()
fc56a99431e68f2e958600e8c60063f57431d3bc
manugildev/IPDP-Course-DTU
/Assignment4/Assignment4F.py
765
3.75
4
import numpy as np import math # Function that returns if an specific experiment is complete or not def isComplete(temp): if temp.size == 3: return True return False def removeIncomplete(id): # This array will hold elements to remove numsToDelete = np.array([]) for i in id: temp = id[id > math.floor(i)] temp = temp[temp < math.floor(i) + 1] # We check if the experiment is not completed if not isComplete(temp): # Append not completed to the array numsToDelete = np.append(numsToDelete, temp) # We mask the elements in the that we need to remove from the original array mask = np.in1d(id, numsToDelete) return id[np.logical_not(mask)] print(removeIncomplete(np.array([1.3, 2.2, 2.3, 4.2, 5.1, 3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1])))
f2b7976c234fe6ef8ffeb7f9a2c47540609b2794
LuisFer24/programacion-python
/Laboratorio 4/Ejercicio 1,tarea 4.py
438
3.984375
4
#<> #Luis Fernando Velasco García #Ejercicio 1 #para ejecutar el programa se debe abrir python en la carpeta donde se encuentra el texto.txt, y ejecutar el programa a=raw_input("Introduce el nombre de un archivo.txt(debe estar en la carpeta actual): ") b=input("Introduzca el nùmero de lineas que desea leer: ") def lector(x,y): x=a y=b archivo=open(x,"r") for i in range(b): print archivo.readline() output=lector(a,b)
5a724273c94895abf7807b7c6a8191872f889ddb
shookies/text_finder
/WordFinder.py
1,126
3.5
4
############# Constants ############# #TODO add substring functionality ############# Word class ############# class word: def __init__(self, theWord, xs, ys, xe, ye, page): self.start = (xs, ys) self.end = (xe, ye) self._string = theWord self.pageNum = page def get_coors(self): return [self.start, self.end] #<----- list of tuples def get_string(self): return self._string def get_substring(self, substr): if (substr in self._string): pass #TODO handle substring coordinates ############# Global Variables ############# word_list = [] #keys: the words themselves as strings. values: the word class wrapper ############# Functions ############# def add_word(word_string, start, end, pageNum = 1): #TODO input checks? _word = word(word_string, start[0], start[1], end[0], end[1], pageNum) word_list.append(_word) def get_words(word_string): ret_list = [] for i in range (len(word_list)): if word_string in word_list[i].get_string(): ret_list.append(word_list[i]) return ret_list
42d8eb553fc62a2521d3a559c77f6be0066962bc
euijun0109/Multivariable-Linear-Regression
/LinearRegressionMultivariable.py
2,320
3.59375
4
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np class LinearRegressionMultivariable: def __init__(self, alpha, n): self.thetas = np.zeros((n, 1), dtype= float) self.m = 0 self.n = n self.cost = np.zeros((n, 1), dtype= float) self.alpha = alpha def hypothesis(self, x): return self.thetas.T.dot(x.T) def costs(self, x, y): self.cost = ((self.hypothesis(x).T - y).T.dot(x)).T def GD(self): self.thetas -= self.alpha * (1/self.m) * self.cost def calculate(self, x, y): self.costs(x, y) self.GD() print("costs:", end=" ") for cos in self.cost: print(cos[0], ",", end=" ") print(" ") self.cost = np.zeros((self.n, 1), dtype= float) print("thetas:", end=" ") for theta in self.thetas: print(theta[0], ",", end=" ") print('\n') def run(self, i, x, y): self.m = len(y) for _ in range(i): self.calculate(x, y) if self.n == 3: self.display3D(x, y) elif self.n == 2: self.display2D(x, y) else: pass def predict(self, x): return sum(self.hypothesis(x)) def resFunction(self, x1, x2): return self.thetas[0][0] + self.thetas[1][0] * x1 + self.thetas[2][0] * x2 def display3D(self, x1, y1): x = y = np.arange(-10.0, 10.0, 1) X, Y = np.meshgrid(x, y) zs = np.array([self.resFunction(x, y) for x, y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) X1 = [] Y1 = [] Z1 = y1.tolist() for row in x1: X1.append(row[1]) Y1.append(row[2]) fig = plt.figure() ax = Axes3D(fig) ax.scatter(X1, Y1, Z1, color='red') ax.plot_surface(X, Y, Z, alpha=0.5, color='grey') plt.show() def display2D(self, x, y): X1 = [] Y1 = y.T.tolist()[0] for row in x: X1.append(row[1]) X = [0, X1[self.m - 1] + 1] Y = [self.thetas[0], self.thetas[0] + self.thetas[1] * (X1[self.m - 1] + 1)] plt.plot(X1, Y1, "ro", label="data") plt.plot(X, Y, label="best fit line") plt.legend() plt.show()
9518984d313d2826ac675eaa6744edb421340912
dMedinaO/python_course
/examples_05_05/ejemplo_condiciones.py
967
4.03125
4
#determinar si enviamos una alerta de sismo #la alerta de sismo se enviara si y solo si, el valor de la actividad es mayor a 5 #num_habitantes > 1 -> si envio la alerta valor_escala = float(input("Favor ingrese el valor en escala ")) num_habitantes = float(input("Favor ingrese el numero de habitantes en MM ")) ''' #opcion A print("Valor escala {}".format(valor_escala)) if valor_escala > 5: print("Si hay un sismo") if num_habitantes > 1: print("Enviar alerta") else: print("No enviar alerta") else: print("No hay un sismo") #opcion B if valor_escala > 5 and num_habitantes >1: print("Si hay un sismo y debo enviar alerta") else: if valor_escala > 5 and num_habitantes <=1: print("Si hay un sismo") else: print("No hay un sismo") ''' #opcion C if valor_escala > 5 and num_habitantes >1: print("Si hay un sismo y debo enviar alerta") elif valor_escala > 5 and num_habitantes <=1: print("Si hay un sismo") else: print("No hay un sismo")
06a9c8729d1f8a751db0b7df4213838ebfc705e5
emmorga2007/morgan_e_pythonHW
/game.py
883
4.15625
4
#import then random package so we can generate a random ai from random import randint #"basket" of choices choices=["rock", "paper", "scissors"] #let the AI make choices computer=choices[randint(0,2)] #set up a game loop here so we don't have to keep restarting player= False while player is False: player=input(" choose rock, paper, or scissors: \n") #start doing some logic and condition checking print("computer: ", computer, "player: ", player) #always check a breaking condition first if player == computer: #wehave a tie, no point in going further print("tie, no one wins! try again") elif player == "quit": print("you choose to quit, quitter.") exit() else: print("NOT a tie. Now we can check other conditions") if player =="rock": print("check and see what the computer is, and win or lose") player = False computer = choices[randint(0,2)]
4f5576324116179724963f6b6b4a945c85368cd3
MinSuArin/Baekjoon
/1085 직사각형에서 탈출.py
290
3.5
4
if __name__ == "__main__" : x, y, w, h = map(int, input().split()) if w - x <= x : dis_x = w - x else : dis_x = x if h - y <= y : dis_y = h - y else : dis_y = y if dis_x <= dis_y : print(dis_x) else: print(dis_y)
6df259cad59beafb6dc8e1df557bd4369f9ad49d
Zerryth/algos
/algorithmic-toolbox/4.divide-n-conquer/quicksort.py
1,093
4.03125
4
# Uses python3 import sys import random def partition3(a, l, r): #write your code here pass def partition2(a, left, right): current_val = a[left] pivot = left for i in range(left + 1, right + 1): if a[i] <= current_val: pivot += 1 a[i], a[pivot] = a[pivot], a[i] a[left], a[pivot] = a[pivot], a[left] # what is this doing here? return pivot def randomized_quick_sort(a, left, right): if left >= right: return rand = random.randint(left, right) a[left], a[rand] = a[rand], a[left] # if rand is the same idx val as left, it'll swap with itself #use partition3 pivot = partition2(a, left, right) # a: [2, 2, 2, 3, 9], parition: 2 --> 1 randomized_quick_sort(a, left, pivot - 1) # [2, 2] -> [2] randomized_quick_sort(a, pivot + 1, right) # [3, 9] if __name__ == '__main__': # input = sys.stdin.read() # n, *a = list(map(int, input.split())) # n: 5, a: [2, 3, 9, 2, 2] n = 5 a = [2, 3, 9, 2, 2] randomized_quick_sort(a, 0, n - 1) for num in a: print(num, end=' ')
7593483db4836e2ef7b64493a5d7e60ed57055bd
bjainvarsha/coding-practice
/LinkedList.py
4,530
3.84375
4
class Node: def __init__(self, data = None): self.data = data self.next = None class Single_LL: def __init__(self): self.head = None self.tail = None def print_LL(self): if not self.head: print("Linked List Empty") return temp = self.head LL_string = "\n|" while temp: LL_string += str(temp.data) + "|-->|" temp = temp.next LL_string = LL_string[:-4] + "\n" if self.head: LL_string += "Head = " + str(self.head.data) + "\n" if self.tail: LL_string += "Tail = " + str(self.tail.data) + "\n" LL_string += "Length of LL = " + str(self.length()) print(LL_string) def insert_end(self, data): if self.tail: self.tail.next = Node(data) self.tail = self.tail.next else: self.head = self.tail = Node(data) def insert_begin(self, data): if self.head: temp = Node(data) temp.next = self.head self.head = temp else: self.head = self.tail = Node(data) def insert_list_end(self, list_values): for data in list_values: self.insert_end(data) def insert_list_begin(self, list_values): for data in list_values[::-1]: self.insert_begin(data) def delete_begin(self): if self.head: if self.head.next: data = self.head.data self.head = self.head.next else: data = self. head.data self.head = self.tail = None return data else: print("Linked List is empty") return None def delete_end(self): if self.head: if self.head.next: temp = self.head while temp.next != self.tail: temp = temp.next data = self.tail.data self.tail = temp self.tail.next = None else: data = self.head.data self.head = self.tail = None return data else: print("Linked List is empty") return None def length(self): if not self.head: return 0 else: count = 0 temp = self.head while temp: count += 1 temp = temp.next return count def search(self, data): if not self.head: return False else: temp = self.head while temp: if temp.data == data: return True temp = temp.next return False def get_nth_node(self, n): if not self.head: return None else: count = 0 temp = self.head while temp: count += 1 if count == n: return temp.data temp = temp.next return None def get_nth_node_end(self, n): if not self.head: return None else: count = n temp = self.head temp1 = self.head while count: count -= 1 if not temp: return None else: temp = temp.next if count == 0: while temp and temp1: temp = temp.next temp1 = temp1.next if temp1: return temp1.data else: return None def get_middle_node(self): if not self.head: return None elif self.head and self.head.next: slow = self.head fast = self.head while slow and fast and fast.next: slow = slow.next fast = fast.next.next if slow: return slow.data else: return None else: return self.head.data def reverse_LL(self): if not self.head: return None else: reversed_LL = Single_LL() temp = self.head while temp: reversed_LL.insert_begin(temp.data) temp = temp.next return reversed_LL def isEmpty(self): if not self.head: return True else: return False def get_head(self): if not self.head: return None else: return self.head def removeFirstOccurrenceByValue(self, value): if self.head and self.head.next: if self.head.data == value: self.head = self.head.next return temp = self.head while temp.next: if temp.next.data == value: if temp.next == self.tail: self.tail = temp temp.next = temp.next.next break temp = temp.next elif self.head: if self.head.data == value: self.head = self.tail = None else: print("Linked List Empty") return def detect_loop(linked_list): if not linked_list.isEmpty(): slow = linked_list.get_head() fast = linked_list.get_head().next print(slow.data) while slow and fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False if __name__ == '__main__': LL = Single_LL() LL.insert_list_begin([10,"sda",13,12]) LL.print_LL() LL.removeFirstOccurrenceByValue("sda") LL.print_LL() LL.removeFirstOccurrenceByValue(10) LL.print_LL() # # print(LL.get_middle_node()) # reverse_LL = Single_LL() # reverse_LL = LL.reverse_LL() # reverse_LL.print_LL() # LL.print_LL() # LL.tail.next = LL.head # print(detect_loop(LL))
aa8a563ff6ebd5195020835a8041fee4f0264f15
nijingxiong/LeetCode
/6ZigZagConversion.py
248
3.59375
4
# l=[0 for i in range(2)] # print(l) # l=['a','b'] # s=[] # s.append(l) # l=['c','d'] # s.append(l) # for i in s: # for j in i: # print(j) # print(s,l) s=[['a', 0], [0, 'b'], ['c', 0], [0, 'd'], ['e', 0], [0, 'f']] print(len(s)) print()
79432715628d3a2feb866ea13907782e79959a8c
hexycat/advent-of-code
/2022/python/07/main.py
2,497
3.703125
4
"""Day 7: https://adventofcode.com/2022/day/7""" def load_input(filepath: str) -> list: """Reads input and returns it as list[str]""" lines = [] with open(filepath, "r", encoding="utf-8") as file: for line in file.readlines(): lines.append(line.strip()) return lines def update_folder_size(filesystem: dict, cwd: tuple, size: int) -> dict: """Add size of cwd to itself and all parent folders""" for i in range(len(cwd)): filesystem[cwd[: i + 1]] += size return filesystem def create_filesystem(logs: list) -> dict: """Creates filesystem from logs""" filesystem = {("root",): 0} cwd = ("root",) dirsize = 0 for line in logs: if line.startswith("$ ls"): continue if line.startswith("dir"): dirname = line.split(" ")[-1] filesystem[cwd + (dirname,)] = 0 continue if line.startswith("$ cd"): filesystem = update_folder_size(filesystem, cwd=cwd, size=dirsize) dirsize = 0 change_to = line.split(" ")[-1] if change_to == "/": cwd = ("root",) elif change_to == "..": cwd = cwd[:-1] else: cwd = cwd + (change_to,) continue # Line that represents file size, _ = line.split(" ") dirsize += int(size) # Update filesystem with the last information filesystem = update_folder_size(filesystem=filesystem, cwd=cwd, size=dirsize) return filesystem def part_one(filesystem: dict) -> int: """Calculates total size of directories with size under 100000""" total_size = 0 for size in filesystem.values(): if size > 100_000: continue total_size += size return total_size def part_two(filesystem: dict) -> int: """Returns total size of directory to be deleted""" disk_space = 70000000 min_free_space = 30000000 unused_space = disk_space - filesystem[("root",)] if unused_space > min_free_space: return 0 space_to_free = min_free_space - unused_space candidates = [size for size in filesystem.values() if size >= space_to_free] return min(candidates) if __name__ == "__main__": terminal_logs = load_input("input") fs = create_filesystem(terminal_logs) print(f"Part one: Total size of folders under 100000: {part_one(fs)}") print(f"Part two: Size of the folder to be deleted: {part_two(fs)}")
f39cace481739444e92f8b17642525f9d5cbc407
VenkataNaveenTekkem/GoGraduates
/loops/Loops.py
1,841
4.15625
4
#for loop example x="python" for i in range(len(x)): # range starts from index 0 to the value given to it print(x[i]) y="loops class" for i in y: print(i) #take a string with alphanumeric characters and print only digits in the string z="abc123xyz" for i in z: if(i.isdecimal()): print(i) #this to explain integer values can't be iterated like strings a=1234 a=str(a) for i in a: print("Playing with integers ") print(i) smlist=[] smlist.append(1); smlist.append(2); smlist.extend([3,4,5,6,7]) print(smlist) for i in smlist: print(i) for i in range(len(smlist)): print("printing list by use of range") print(smlist[i]) #for loop for tuple Extuple=("sample","python",1,2,3,4) print('playing with tuple') for i in Extuple: print(i) print("tuple with range") for i in range(len(Extuple)): print(Extuple[i]) #for loops for dictionary sampleDict=dict() sampleDict['key1']="value1" sampleDict['key2']="values2" sampleDict["key3"]="value3" print(sampleDict) for i in sampleDict: print("print key and value=",i,sampleDict[i]) print("play with range in dictionary") for i in range(len(sampleDict)): print(i) print(sampleDict.get("key1")) for k,v in sampleDict.items(): print("print key value ",k,v) print("for loops for set") sampleset =set([1,2,"python",34.5,True]) print(sampleset) for i in sampleset: print(i) print("play for range with sets") for i in range(len(sampleset)): print(sampleset) print("range can't be used for sets ") intlist=[1,2,3,4,5] for i in range(2,len(intlist)): print(intlist[i]) print("nested for loop") nestlist=[1,2,3,4,5,[8,9,11,12]] print(nestlist) for i in nestlist: if(isinstance(i,list)): print("we are here ") for y in i: print("nested for loop values:",y) else: print(i)
8082034f3b44c9e9f716c6c0d76c2fd7224c0f9b
csusb-005411285/CodeBreakersCode
/maximum-number-of-visible-points.py
908
3.59375
4
class Solution: def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: left = 0 angles = [] count = 0 duplicates = 0 if angle == 360: return len(points) for point in points: x1, y1 = point x2, y2 = location if x1 == x2 and y1 == y2: duplicates += 1 continue angles.append(math.atan2((y2 - y1), (x2 - x1))) angles.sort() for i in range(len(angles)): angles.append(angles[i] + 2 * math.pi) d_angles = list(map(lambda x: degrees(x), angles)) angle = math.pi * angle/180 for right, val in enumerate(angles): while val - angles[left] > angle and left <= right: left += 1 count = max(count, right - left + 1) return count + duplicates
3d359be33202a34e3ef703be17130b19d8f8d3ae
joshdavham/Starting-Out-with-Python-Unofficial-Solutions
/Chapter 4/Q11.py
332
4.03125
4
#Question 11 def main(): seconds = float(input("Enter the number of seconds: ")) minutes = seconds / 60 hours = seconds / 3600 days = seconds / 86400 print("\nIn", seconds, "seconds there are...") print(minutes, "minutes.") print(hours, "hours.") print(days, "days.") main()
e99dbfbe5ab4b1c78297c4de7d70de75d0cc4570
RMhanovernorwichschools/Cryptography
/cryptography.py
2,462
3.890625
4
""" cryptography.py Author: Rachel Matthew Credit: none Assignment: Write and submit a program that encrypts and decrypts user data. See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md """ associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!" assoguide=list(zip(list(associations), range(0,len(associations)))) while True: answer='' task=input('Enter e to encrypt, d to decrypt, or q to quit: ') if task=='q': print('Goodbye!') break elif task=='e': string=input('Message: ') key=input('Key: ') kterm=0 if string=='': answer='' elif key=='': answer=string else: for x in list(string): for n in range(len(assoguide)): if assoguide[n][0]==x: str_n=assoguide[n][1] if assoguide[n][0]==list(key)[kterm]: key_n=assoguide[n][1] fin_n=str_n+key_n while fin_n>85: fin_n -= 85 kterm+=1 if kterm==len(key) or kterm>len(key): kterm=0 for n in range(len(assoguide)): if assoguide[n][1]==fin_n: piece=assoguide[n][0] answer=answer+piece print(answer) elif task=='d': string=input('Message: ') key=input('Key: ') kterm=0 if string=='': answer='' elif key=='': answer=string else: kterm=0 for x in list(string): for n in range(len(assoguide)): if assoguide[n][0]==x: str_n=assoguide[n][1] if assoguide[n][0]==list(key)[kterm]: key_n=assoguide[n][1] fin_n=str_n-key_n while fin_n>85: fin_n -= 85 while fin_n<0: fin_n +=85 kterm+=1 if kterm==len(key): kterm=0 for n in range(len(assoguide)): if assoguide[n][1]==fin_n: piece=assoguide[n][0] answer=answer+piece print(answer) else: print('Did not understand command, try again.')
a643c0dbfd386480209c177db10e428cdc9b68ab
stefan1123/newcoder
/构建乘积数组.py
1,724
3.65625
4
""" 题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。 代码情况:accepted """ class Solution: def multiply(self, A): # write code here # # 方法一,暴力相乘,O(n^2) # if len(A) <= 0: # return -1 # elif len(A) == 1: # # 数组A只有一个数字时,只需要返回一个与A[0]不等的数组 # return A[0]+1 # # def _mul(arr): # res = 1 # for i in range(len(arr)): # res *= arr[i] # return res # # B = [0 for i in range(len(A))] # for i in range(len(B)): # B[i] = _mul(A[:i]+A[i+1:]) # return B # 方法二: B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1] # 分两端,前半段是前i个数的乘积(A[0]*A[1]*...*A[i-1]),可以从i=0 # 开始累积一个数形成B[i]前半段;后半段反向累积;前后两端对应相乘 if len(A) <= 0: return [] length = len(A) B = [1 for i in range(length)] # 正序累积 ad = [1 for i in range(length)] # 反向累积 # 前半段 B[i]=A[0]*A[1]*...*A[i-1] 的累积 for i in range(1,length): B[i] = B[i-1]*A[i-1] # back = 1 # 暂时保存反向累乘的结果(累积) for j in range(length-2,-1,-1): ad[j] = ad[j+1]*A[j+1] B[j]*=ad[j] # 前后半段的累积相乘 # back *= A[j+1] # B[j] *= back return B if __name__ == '__main__': a = [5,7,2,8,3] res = Solution().multiply(a)
d89a593836f159e1d9f2edf7f1e0b55c434a13d0
yinxx2019/python
/hw06/print_cube.py
1,213
4.125
4
def main(): """ draws 2D cubes with sizes from user input """ n = int(input("Input cube size (multiple of 2): ")) while n % 2 != 0 or n < 2: n = int(input("Invalid value. Input cube size (multiple of 2): ")) else: cube(n) def cube(n): double_n = n * 2 # draw top side diag_edge = int(n / 2) space_top_line = diag_edge + 1 # first line of the top side print(" " * space_top_line + "+" + "-" * double_n + "+") # middle lines of the top side for row in range(diag_edge): space = space_top_line - (row + 1) print(" " * space + "/" + " " * double_n + "/" + " " * row + "|") # last line of the top side, also the first line of the front side print("+" + "-" * double_n + "+" + " " * diag_edge + "|") # draw front side for row in range(n - space_top_line): print("|" + " " * double_n + "|" + " " * diag_edge + "|") # draw diagnal corner print("|" + " " * double_n + "|" + " " * diag_edge + "+") for row in range(space_top_line - 1): print("|" + " " * double_n + "|" + " " * (diag_edge - row - 1) + "/") # last line of the front side print("+" + "-" * double_n + "+") main()
d07eb0c27412ecc3a1d11dba41581b1d6f0357d7
saivijay0604/algorithms
/general/arrayDiv3.py
568
4.15625
4
from numpy import * def isDiv3(x): for i in range(len(numberArray)): if numberArray[i] % 3 == 0: ele = numberArray[i] listElements.append(ele) else: pass print("From list numbers which are divisble by 3 are:",listElements) global numberArray numberArray = array([1,2,3,4,5,6,7,8,9,12]) listElements = [] #numberArray = [int(item) for item in input("Enter the list items : ").split()] print("Numbers in array", numberArray) isDiv3(numberArray) print("sum of numbers div by 3:", int(sum(listElements)))
3cec57cdc15456782476d6cd547fb9a5f5879661
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/mggdac001/question2.py
1,061
3.875
4
from math import sqrt def vector(): f='{0:1.2f}' vector_A=[] vector_a=input("Enter vector A:\n") vector_B=[] vector_b=input('Enter vector B:\n') for num in (vector_a.split()): vector_A.append(num) #print(vector_A[1]) for num in (vector_b.split()): vector_B.append(num) #print(vector_B) anbone=((eval( vector_A[0]))+(eval( vector_B[0]))) anbtwo=((eval( vector_A[1]))+(eval( vector_B[1]))) anbthree=((eval( vector_A[2]))+(eval( vector_B[2]))) ab=((eval( vector_A[0]))*(eval( vector_B[0])))+((eval( vector_A[1]))*(eval( vector_B[1])))+((eval( vector_A[2]))*(eval( vector_B[2]))) A=sqrt(((eval( vector_A[0]))**2)+((eval( vector_A[1]))**2)+((eval( vector_A[2]))**2)) B=sqrt(((eval( vector_B[0]))**2)+((eval( vector_B[1]))**2)+((eval( vector_B[2]))**2)) #print all the values print('A+B = [',anbone,', ',anbtwo,', ',anbthree,']',sep='') print('A.B',"=",ab) print("|A|",'=',(f.format(A))) print("|B|",'=',(f.format(B))) vector()
c28f2b5b07d8f4284d7d9643a834e9cefda2a320
mykeal-kenny/Intro-Python
/src/dicts.py
637
4.15625
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. waypoints = [ {"lat": "48.8584° N", "lon": "2.2945° E", "name": "Eiffel Tower"}, {"lat": "40.6892° N", "lon": "74.0445° W", "name": "Statue of Liberty"}, {"lat": "22.9519° S", "lon": "43.2105° W", "name": "Christ The Redeemer"}, ] # Write a loop that prints out all the field values for all the waypoints # places = [i["name"] for i in waypoints] # print(places) nl = "\n" for place in waypoints: for k, v in place.items(): print(f"{k}: {v}")
8b805de163a63153badac66f931466ddce7bb811
RahulBhoir/Python-Projects
/data_structure/panlindrone.py
463
3.96875
4
def ReverseNumber(number): reverse = 0 count = 0 while(number > 0): digit = int(number % 10) reverse = (reverse * 10) + digit number = int(number / 10) count += 1 return reverse def IsPanlindrone(number): reverse = ReverseNumber(number) if reverse == number: return True else: return False # return True if str(number) == str(number)[::-1] else False print(IsPanlindrone(1221))
d38111744ef9ec977aa3dc1f9e0834fa61cf1fa3
rhjohnstone/random
/series_betting.py
2,202
3.828125
4
""" Team A playing Team B in a series of 2k+1 games. The first team to win k+1 games wins the series. We want to place a 100 bet on Team A winning the series, with even odds. But we can only bet on a game-by-game basis. What betting strategy can we use to have the same result as the original plan? """ import operator def compute_current_net_and_bet(current_score,nets_bets,win,target_bet): score_A, score_B = current_score score_if_A_wins = (score_A+1,score_B) score_if_B_wins = (score_A,score_B+1) if (score_A == win-1): net_if_B_wins, bet_if_B_wins = nets_bets[score_if_B_wins] current_net = 0.5*(target_bet+net_if_B_wins) current_bet = 0.5*(target_bet-net_if_B_wins) elif (score_B == win-1): net_if_A_wins, bet_if_A_wins = nets_bets[score_if_A_wins] current_net = 0.5*(net_if_A_wins-target_bet) current_bet = 0.5*(net_if_A_wins+target_bet) else: net_if_A_wins, bet_if_A_wins = nets_bets[score_if_A_wins] net_if_B_wins, bet_if_B_wins = nets_bets[score_if_B_wins] current_net = 0.5*(net_if_A_wins + net_if_B_wins) current_bet = 0.5*(net_if_A_wins - net_if_B_wins) return current_net, current_bet target_bet = 100. k = 3 N = 2*k+1 # games in series win = k+1 # games necessary to win series print "Series of {} games, first to {} wins.".format(N,win) print "Betting game-by-game to recreate a single bet of {} on Team A winning the series.\n".format(target_bet) nets_bets = {} nets_bets[(win-1,win-1)] = (0,100) # if tied going into final game, the bet is the same as original bet scores = [(win-1,win-1)] for current_score in scores: for i in xrange(2): temp_score = (current_score[0]-(1-i),current_score[1]-i) if (temp_score[0]<0) or (temp_score[1]<0): continue if temp_score not in scores: scores.append(temp_score) nets_bets[temp_score] = compute_current_net_and_bet(temp_score,nets_bets,win,target_bet) else: continue nets_bets = sorted(nets_bets.items(), key=operator.itemgetter(0)) print "(Team A, Team B) score, bet:" for score, net_bet in nets_bets: print score, net_bet[1]
bf7a7280e44c710fe3a64f50ebe3deded0d67028
joaocarvalhoopen/Pencil_Draw_Help_Program
/pencil_draw_help_program.py
12,587
3.765625
4
############################################################################### # Name: Pencil Draw Help Program # # Author: Joao Nuno Carvalho # # Email: [email protected] # # Date: 2019.03.25 # # Description: This program takes a color or gray photo, transforms it into # # gray. Then expands the dynamic range to occupy all the 0 to # # 255 value range. Then asks the user for the number of # # independent values, or tones and subdivide the image into # # different tones. It then shows them in a cumulative order, sow # # that the user builds value or tone at each cumulative slice. # # License: MIT Open source # # Python version: Python 3.7 # # Libs used: Pillow a derivate from the lib PIL # ############################################################################### from PIL import Image, ImageDraw def show_and_save_image(image_in, grid_on, grid_number, path, filename): image_out = image_in if grid_on: # Draw grid. image = PencilImage(image_in) image.draw_grid(grid_number) image_out = image.get_img() image_out.show(title=filename) # The title doesn't work on Windows 10. image_out.save(path + filename) def apply_change_to_gray(pixel_in, param_1 = None, param_2 = None): # pixel_in is a tuple (R, G, B) each value is an int 0-255 . # It returns a pixel tuple. pixel_grey_val = ( pixel_in[0] + pixel_in[1] + pixel_in[2] ) / 3 pixel_grey_val = int( pixel_grey_val ) # R Red G Green B Blue pixel_out = (pixel_grey_val, pixel_grey_val, pixel_grey_val) return pixel_out def apply_change_expand_dynamic_range(pixel_in, param_1 = None, param_2 = None): # pixel_in is a tuple (R, G, B) each value is an int 0-255 . # It returns a pixel tuple. min = param_1 max = param_2 # Enforce that the image is gray. assert(pixel_in[0]==pixel_in[1] and pixel_in[1]==pixel_in[2]) pixel_grey_val = pixel_in[0] pixel_grey_val = ((pixel_grey_val - min) / max) * 255 pixel_grey_val = int( pixel_grey_val ) # R Red G Green B Blue pixel_out = (pixel_grey_val, pixel_grey_val, pixel_grey_val) return pixel_out class PencilImage: def __init__(self, img_in, num_gray_tones = 6): self.__img = img_in.copy() self.__max_col = self.__img.size[0] self.__max_row = self.__img.size[1] self.__pixels = self.__img.load() # create the pixel map self.__min = -1 self.__max = -1 self.__num_gray_tones = num_gray_tones self.__delta = int(255 / self.__num_gray_tones) self.__current_tone = 1 def get_img(self): return self.__img def get_max_col(self): return self.__max_col def get_max_row(self): return self.__max_row def get_num_gray_tones(self): return self.__num_gray_tones def get_info_str(self): return f" max_col = {self.__max_col}\n" \ + f" max_row = {self.__max_row}\n" \ + f" max_min = {self.__min}\n" \ + f" max_max = {self.__max}\n" def set_num_gray_tones(self, num_gray_tones): self.__num_gray_tones = num_gray_tones self.__delta = int(255 / self.__num_gray_tones) def apply_to_img_change(self, func_to_apply, param_1 = None, param_2 = None): for i in range(self.__max_col): # for every col: for j in range(self.__max_row): # For every row pixel_tmp_in = self.__pixels[i, j] pixel_tmp_out = func_to_apply(pixel_tmp_in, param_1, param_2) self.__pixels[i, j] = pixel_tmp_out def get_min_max(self): # Process only gray scale pictures. min = 255 max = 0 for i in range(self.__max_col): # for every col: for j in range(self.__max_row): # For every row pixel_tmp = self.__pixels[i, j] # Just to enforce that the image is a grey image. assert(pixel_tmp[0]==pixel_tmp[1] and pixel_tmp[1]==pixel_tmp[2]) if pixel_tmp[0] > max: max = pixel_tmp[0] if pixel_tmp[0] < min: min = pixel_tmp[0] return (min, max) def expand_dynamic_range(self): # Change the image to gray scale. self.apply_to_img_change(apply_change_to_gray) # Get min max value. self.__min, self.__max = self.get_min_max() # Expand dynamic range. self.apply_to_img_change(apply_change_expand_dynamic_range, self.__min, self.__max) def __generate_image_all_cases_tone(self, min_tone=None, unique_tone=None): tone_bins = self.__num_gray_tones img_out = self.__img.copy() pixels = img_out.load() for i in range(self.__max_col): # for every col: for j in range(self.__max_row): # For every row pixel_in = pixels[i, j] assert(pixel_in[0]==pixel_in[1] and pixel_in[1]==pixel_in[2]) gray_value = pixel_in[0] # Inverts the list. ex: 7, 6, 5, 4, 3, 2, 1, 0 for num_tones = 8 lst_tones = list(range(tone_bins - 1, -1, -1)) for tone_num in lst_tones: tone_val = tone_num * self.__delta # Cumulative case upper then max_tone if min_tone != None: if tone_num < min_tone: tone_out = (min_tone + 1) * self.__delta pixel_val = (tone_out, tone_out, tone_out) pixels[i, j] = pixel_val break # All tones case. if gray_value > tone_val: # tone_out = (tone_num - 1) * self.__delta tone_out = tone_num * self.__delta # R G B pixel = (tone_out, tone_out, tone_out) # Unique tone case. if unique_tone != None: if tone_num == unique_tone: pixels[i, j] = pixel else: pixels[i, j] = (255, 255, 255) # White break # All tones case. pixels[i, j] = pixel break return img_out def generate_image_only_one_tone(self, num_tone): return self.__generate_image_all_cases_tone(min_tone=None, unique_tone=num_tone) # The cumulative algorithm doesn't work, use the cumulative overlay. def generate_image_cumulative_tone(self, min_tone): return self.__generate_image_all_cases_tone(min_tone=min_tone, unique_tone=None) def generate_image_final_tone_bins(self): return self.__generate_image_all_cases_tone(min_tone=None, unique_tone=None) def generate_image_cumulative_overlay(self, img_all_tones, min_tone): # img_out_all_tones = pencil_img.generate_image_final_tone_bins() # img_out_all_tones.show() img_out = img_all_tones.copy() img_one_tone = self.generate_image_only_one_tone(num_tone=min_tone) # 6 -> 0 pixels_out = img_out.load() pixels_one_tone = img_one_tone.load() for i in range(self.__max_col): # for every col: for j in range(self.__max_row): # For every row pixel_one_tone = pixels_one_tone[i, j] if pixel_one_tone[0] < 255: # if it isn't white. pixel_output = (0, 255, 0) # Green pixel. pixels_out[i, j] = pixel_output return img_out def draw_grid(self, grid_number): # Calc grid lines position. delta_col = int(self.__max_col / grid_number) # ex: 4 lst_col = [delta_col * n for n in range(1, grid_number)] delta_row = int(self.__max_row / grid_number) # ex: 4 lst_row = [delta_row * n for n in range(1, grid_number)] # Draw the grid lines. draw = ImageDraw.Draw(self.__img, mode="RGB") for point_col in lst_col: draw.line([point_col, 0, point_col, self.__max_row], fill=(0, 0, 255), width=1) # fill RGB, blue for point_row in lst_row: draw.line([0, point_row, self.__max_col, point_row], fill=(0, 0, 255), width=1) # fill RGB, blue class Index: def __init__(self): self.__index = -1 def next(self): self.__index += 1 return self.__index if __name__ == "__main__": # Configurations. path_in = ".//images_in//" path_out = ".//images_out//" file_image_in = "lena-color.jpg" # This number is the number of different tones you can make # with graphite, inclusing the white. num_gray_tones = 8 grid_on = True # True / False grid_number = 4 # Grid num_col = num_row. # Execution. file_main = file_image_in[ : -4] # ex: "lena-color" ext = ".png" index_a = Index() img_in = Image.open(path_in + file_image_in) filename_out = file_main + f"_{index_a.next():02d}_original" + ext show_and_save_image(img_in, grid_on, grid_number, path_out, filename=filename_out) pencil_img = PencilImage(img_in, num_gray_tones=num_gray_tones) pencil_img.expand_dynamic_range() info_str = pencil_img.get_info_str() print(info_str) img_out = pencil_img.get_img() filename_out = file_main + f"_{index_a.next():02d}_expanded_range" + ext show_and_save_image(img_out, grid_on, grid_number, path_out, filename=filename_out) img_out_all_tones = pencil_img.generate_image_final_tone_bins() filename_out = file_main + f"_{index_a.next():02d}_all_tones" + ext show_and_save_image(img_out_all_tones, grid_on, grid_number, path_out, filename=filename_out) # For tone number = 8, and it draws the tones 6, 5, 4, 3, 2, 1, 0 (From lighter to darker) index_b = Index() for tone_i in range(pencil_img.get_num_gray_tones() - 2, -1, -1): img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = tone_i) filename_out = file_main + f"_{index_a.next():02d}_one_tone_{index_b.next():02d}_" + ext show_and_save_image(img_out_one_tone, grid_on, grid_number, path_out, filename=filename_out) # img_overlay = pencil_img.generate_image_cumulative_overlay(img_out_all_tones, min_tone = 6) # img_overlay.show() # Shows all overlays. # For tone number = 8, and it draws the tones 6, 5, 4, 3, 2, 1, 0 (From lighter to darker) index_b = Index() for tone_i in range(pencil_img.get_num_gray_tones() - 2, -1, -1): img_overlay = pencil_img.generate_image_cumulative_overlay(img_out_all_tones, min_tone = tone_i) filename_out = file_main + f"_{index_a.next():02d}_overlay_{index_b.next():02d}_" + ext show_and_save_image(img_overlay, grid_on, grid_number, path_out, filename=filename_out) # Tests... # img_out.save("lena_processada.png") # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 6) # img_out_one_tone.show("tone: " + str(6)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 5) # img_out_one_tone.show("tone: " + str(5)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 4) # img_out_one_tone.show("tone: " + str(4)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 3) # img_out_one_tone.show("tone: " + str(3)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 2) # img_out_one_tone.show("tone: " + str(2)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 1) # img_out_one_tone.show("tone: " + str(1)) # img_out_one_tone = pencil_img.generate_image_only_one_tone(num_tone = 0) # img_out_one_tone.show("tone: " + str(0))
05c39781642a44d51067178bdf5063582ff9a42e
huilongan/Python
/SinglyLinkedList.py
4,307
3.75
4
''' To review the singly linked list ''' #SinglyLinkedList class Empty(Exception): pass class SinglyLinkedBase: class _Node: __slots__='_element','_next' def __init__(self,element,next): self._element= element self._next=next def __init__(self): # sentinels self._head=self._Node(None,None) self._tail=self._Node(None,None) self._head._next=self._tail self._size=0 def __len__(self): return self._size def is_empty(self): return self._size==0 # for a singlyLinkedList, the only thing we know is the node after one particular node # so, all the insertion or deletion operations should base on the previous node def _insert_after(self,e,predecessor): new=self._Node(e,predecessor._next) predecessor._next=new self._size +=1 return new def _delete_after(self,predecessor,node): predecessor._next=node._next ans=node._element node=None self._size -=1 return ans def _replace(self,e,node): old=node._element node._element=e return old # C-7.27 # stack based on the singlyLinkedList class SinglyLinkedStack(SinglyLinkedBase): def push(self,e): self._insert_after(e,self._head) def pop(self): return self._delete_after(self._head,self._head._next) def top(self): if self._size==0: raise Empty("The queue is empty!") return self._head._next._element if __name__=='__main__': test=SinglyLinkedStack() test.push(10) test.push(20) test.push(30) test.push(40) test.pop() class LinkedQueue(SinglyLinkedBase): #here we have to remove the tail sentinel def enqueue(self,e): if self.is_empty(): newtail=self._insert_after(e,self._head) else: newtail=self._insert_after(e,self._tail) self._tail=newtail return newtail def dequeue(self): if self.is_empty(): raise Empty("The queue is empty!") return self._delete_after(self._head,self._head._next) def first(self): return self._head._next._element #_____________________________________________________________________# # Creativity c-7.26 def concatenate(self,Q): if not isinstance(Q,type(self)): raise ValueError("Wrong Type Input!") self._tail._next=Q._head._next self._tail=Q._tail self._size += len(Q) Q=None return self if __name__=='__main__': a=LinkedQueue() for i in range(10): a.enqueue(i) b=LinkedQueue() for i in 'abcd': b.enqueue(i) c=a.concatenate(b) len(c) c.dequeue() if __name__=='__main__': test=LinkedQueue() for i in range(10): test.enqueue(i) for i in range(10): test.dequeue() class CircularQueue: class _Node: __slots__='_element','_next' def __init__(self,element,next): self._element= element self._next=next def __init__(self): self._tail=None self._size=0 def __len__(self): return self._size def is_empty(self): return self._size==0 # use the sentinel here, to keep the tail as sentienl # but we cannot do this, because: # for a singlyLinked list, we cannot add a node to position previous to the tail def dequeue(self): if self.is_empty(): raise Empty("The queue is empty!") oldhead=self._tail._next if self._size==0: self._tail=None else: self._tail._next=oldhead._next self._size -=1 return oldhead._element def enqueue(self,e): new=self._Node(e,None) if self.is_empty(): self._tail=new new._next=new else: new._next=self._tail._next self._tail._next=new self._tail=new self._size +=1 def rotate(self): if self._size >0: self._tail=self._tail._next
04204910cf81ff567e669b20b6124c716a5f135f
SMAshhar/Python
/5_LoginGreeting.py
985
4.1875
4
current_usernames = ["admin", "v2fftb", "Ali", "Rubab", "Nawal"] # 5-8 greet every login. Some oneway, the others the otherway for a in current_usernames: username = input("Enter username: ") if username == "admin": print("Hello admin, would you like a report?") break elif username in current_usernames: print(f"Welcome back {username}. How can I make your world easy for you today?") break else: print("This username is not registered") #-5-9 send a message if there is nothing in a list # while current_usernames: # current_usernames.pop() # if current_usernames == []: # print(current_usernames) # print("We need more users") # 5-10 Checking usernames new_users = ["Imad", "Danish", "Ali", "Nawal", "Umer"] for a in new_users: if a in current_usernames: print(a, " is not available, please enter a different name") else: print(a, " username is available")
a5a95f41d6ea8593ead4e2d361ec72d086a9c4dc
cod3baze/initial-python-struture
/w3/JSON.py
1,035
3.703125
4
import json # dados JSON x = '{"name":"jhon", "age":30}' # Converter os Dados para dicionario python y = json.loads(x) print(y) # dicionario python w = { "name": "John", "age": 30, "city": "New York" } #converter o dicionário para dados JSON z = json.dumps(w) print(z) #Converte objetos Python em strings JSON, e imprima os valores: print(json.dumps({"name": "John", "age": 30})) print(json.dumps(["apple", "bananas"])) print(json.dumps(("apple", "bananas"))) print(json.dumps("hello")) print(json.dumps(42)) print(json.dumps(31.76)) print(json.dumps(True)) print(json.dumps(False)) print(json.dumps(None)) #Converte um objeto Python contendo todos os tipos de dados legais: a = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } #indent para os números de recuos #separators = padrao("," , ":") print(json.dumps(a, indent = 5, separators=(". ", " = ")))
09c9533f5c28e11aff42f91813f61e4fae6891f4
melissafear/CodingNomads_Labs_Onsite
/week_03/02_exception_handling/04_validate.py
537
4.625
5
''' Create a script that asks a user to input an integer, checks for the validity of the input type, and displays a message depending on whether the input was an integer or not. The script should keep prompting the user until they enter an integer. ''' isinteger = "nope" while isinteger == "nope": user_input = input("pls type a number: ") try: int(user_input) except ValueError as ve: print("That was not an integer, try again: ") else: print("its an integer!") isinteger = "yes"
d2a6ba9b155a54251489ef96fb94bd7557a0c5df
khalilabid95/checkpoints
/Q3.py
201
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 17:24:50 2020 @author: Khalil """ import math mydic={} n= int(input('donner la taille de list')) for i in range(1,n+1): mydic[i]= i*i print(mydic)
503c0f507b55b3ab7cd2c61a909cb48490c15c6e
linuxsed/python_script
/sort_list.py
115
3.625
4
a=[1,3,5,7,9] b=[2,4,6,8,10] new_list=[] for i in a+b: new_list.append(i) new_list.sort() print (new_list)
8449f12a28a2e514d912ced806727b50ffa9b287
beingimran/python
/even_odd.py
186
3.6875
4
a = [1,2,3,4,5,6,7,8,9,10] even=0 odd=0 for i in a: if i%2 == 0: even+=1 else: odd+=1 print("no. of even:",even) print("no.of odds:",odd)
2f2814cf781274742b3ab9e8ffec6f6d9c82ad57
tmoertel/practice
/EPI/06/soln_06_001_dutch_national_flag.py
2,712
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Tom Moertel <[email protected]> # 2013-10-23 r"""Solution to "Dutch National Flag" problem, 6.1 from EPI. Write a function that takes an array A and an index i and rearranges the elements such that all elements less than A[i] appear first, followed by all elements equal to A[i], followed by elements greater than A[i]. Discussion. This is the "Dutch National Flag" problem, which I have solved previously: https://github.com/tmoertel/practice/blob/master/programming_praxis/dutch_national_flag.py The idea is to maintain four partitions satisfying the following invariant conditions w.r.t. the pivot x = A[i]: - an LT partition on the left for elements < x, - a GT partition on the right for elements > x, - a MID/EQ partition in the lift middle for elements = x, and - a MID/UNX partition in the right middle for unexamined elements. Initially, the MID/UNX partition spans the entire array, and the other partitions are empty. But as we examine elements in MID/UNX, classify them w.r.t. x, and swap them into their respective partitions, those partitions will grow and the MID/UNX partition will shrink. When MID/UNX is finally empty, the invariant conditions on the other partitions will ensure that the rearranged elements of A represent a valid solution. """ def partition(A, i): """Rearrange A's elements into <, =, and > partitions on A[i].""" # Let the indices j, k, l give the start of MID/EQ, MID/UNX, and GT: # # 0123... j... k... l... # |||| | | | # ======= ======= ======= ======= # LT MID/EQ MID/UNX GT # A[ :j] A[j:k] A[k:l] A[l: ] j, k, l = 0, 0, len(A) # make swap helper over A def swap(j, k): A[j], A[k] = A[k], A[j] # partition on x = A[i], maintaining invariant conditions x = A[i] while k < l: if A[k] < x: swap(k, j) j += 1 k += 1 elif A[k] == x: k += 1 else: l -= 1 swap(k, l) return A # for convenient testing and chaining def test(): from nose.tools import assert_equal as eq from itertools import permutations def stable_partition(A, x): return ([a for a in A if a < x] + [a for a in A if a == x] + [a for a in A if a > x]) for n in xrange(5): for A in permutations(range(n)): A = list(A) for i in xrange(n): x = A[i] AP = partition(A, i) eq(sorted(AP), sorted(A)) # must preserve all elems eq(AP, stable_partition(AP, x)) # must be a valid partition
02c56e857cd58c6b65d0c6ff1680f3659d4df496
loponly/python_class
/Design_Patterns/1_Creational/Abstract_factory_.py
1,563
3.859375
4
import abc class Button(abc.ABC): """ Concret Button """ @abc.abstractmethod def render(self): pass class WinButton(Button): def render(self): return 'This is button for windows.' class MacButton(Button): def render(self): return 'This is button for mac.' class TextBox(abc.ABC): """ Concret TextBox """ @abc.abstractmethod def draw(abc): pass class WinTextBox(TextBox): def draw(self): return 'This is textbox for windows.' class MacTextBox(TextBox): def draw(self): return 'This is textbox for mac.' class GUI(abc.ABC): @abc.abstractmethod def createButton(self): pass @abc.abstractmethod def createTextBox(self): pass class WinGUI(GUI): def createButton(self) -> Button: return WinButton() def createTextBox(self) -> TextBox: return WinTextBox() class MacGUI(GUI): def createButton(self) -> Button: return MacButton() def createTextBox(self) -> TextBox: return MacTextBox() class Application(object): def __init__(self, factory): self.factory = factory() print(f'Drawing the {type(self.factory).__name__}') self.textBox = self.factory.createTextBox() self.button = self.factory.createButton() def paint(self): print(self.button.render()) print(self.textBox.draw()) if __name__ == "__main__": app = Application(WinGUI) app.paint() app = Application(MacGUI) app.paint()
006b07d42aeba64df4c4b2ebbc654c281bf1be98
bontu-fufa/competitive_programming-2019-20
/Take2/Week 2/sort-an-array.py
839
3.921875
4
#https://leetcode.com/problems/sort-an-array def sortArray(self, nums: List[int]) -> List[int]: # return sorted(nums) def merge_sort(values): if len(values)>1: m = len(values)//2 left = values[:m] right = values[m:] left = merge_sort(left) right = merge_sort(right) values =[] while len(left)>0 and len(right)>0: if left[0]<right[0]: values.append(left[0]) left.pop(0) else: values.append(right[0]) right.pop(0) for i in left: values.append(i) for i in right: values.append(i) return values result = merge_sort(nums) return result
3df73920a57c840cc1df8e9abc6f20e3c59e3eb0
fargofremling/learnypythonthehardway
/ex25.py
1,856
4.46875
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) # Study Drills # 1. Take the remaining lines of the What You Should See output and figure out what they are doing. Make sure you understand how you are running your functions in the ex25 module. # 2. Try doing this: help(ex25) and also help(ex25.break_words). Notice how you get help for your module, and how the help is those odd """ strings you put after each function in ex25? Those special strings are called documentation comments and we'll be seeing more of them. # 3. Typing ex25. is annoying. A shortcut is to do your import like this: from ex25 import * which is like saying, "Import everything from ex25." Programmers like saying things backward. Start a new session and see how all your functions are right there. # 4. Try breaking your file and see what it looks like in python when you use it. You will have to quit python with quit() to be able to reload it.
7333481e42efe3c0b46327f97c4ab71b6492311a
parzipug/Random-Passcode-Generator
/Random password generator.py
1,038
3.8125
4
import time import random def whitespace(x): for i in range(x): print("\n") def normalspace(x): for i in range(x): whitespace(1) time.sleep(.8) def passcode_generator(): print("<<< Random password generator. >>>") normalspace(1) length = int(input("How long would you like your password to be? >>> ")) normalspace(1) times = int(input("How many passwords would you like? >>> ")) normalspace(1) alphabet = "abcdefghijklmnopqrstuvwxyz" passcode = ' ' amount_of_passwords = (0) for x in range(times): password = ' ' amount_of_passwords += 1 for i in range(length): passcode += random.choice(alphabet) print("<<< Here is your " + "random password " + str(amount_of_passwords) + ". >>>") print(passcode) passcode = ' ' passcode_generator()
71b42cc185b048af5b065526decb65e6d519f4ac
alexReshetnyak/pure_python
/1_fundamentals/10_ tuples.py
992
4.3125
4
print('---------------------------TUPLES--------------------------------') # like list but we can't modify it (immutable) my_tuple = (1, 2, 3, 4, 5) # ! TypeError: 'tuple' object does not support item assignment # my_tuple[1] = 'z' print("my_tuple[0]:", my_tuple[0]) # 1 print("2 in my_tuple:", 2 in my_tuple) # True dictionary = { 123: [1, 2, 3], (1, 2, 3): [1, 2, 3], # * tuple as a key } print("dictionary[(1,2,3)]:", dictionary[(1, 2, 3)]) # [1, 2, 3] print('---------------------------TUPLES 2--------------------------------') my_tuple = (1, 2, 3, 4, 5) new_tuple = my_tuple[1:2] print("new_tuple:", new_tuple) # (2,) x, y, z, *other = my_tuple print("x:", x) # 1 print("y:", y) # 2 print("z:", z) # 3 print("other:", other) # [4, 5], returns list my_tuple = (1, 2, 3, 4, 5) print("my_tuple.count():", my_tuple.count(5)) # 1, count matches print("my_tuple.index(2):", my_tuple.index(2)) # 1, indexOf 2 print("len(my_tuple):", len(my_tuple)) # 5 print(":", ) #
00740f46e831f28c48242d22637e1c304f9c2f96
CNU-Computer-Physics/Example-and-Practice
/03_analysis/02A_function_differential.py
736
4.09375
4
""" 함수의 미분1 도함수를 출력하는 기초적인 방법 """ import matplotlib.pyplot as plt import numpy as np def f(x): return 3 * x ** 2 + 2 * x + 6 def g(func, x): y = [] h = 0.01 for _x in x: y.append((func(_x + h) - func(_x)) / h) return np.array(y) if __name__ == "__main__": x = np.linspace(0, 10) ax1 = plt.subplot(2, 1, 1) ax1.set_title("Original function") ax1.set_xlim(0, 10) ax1.set_ylim(0, 400) ax1.axes.xaxis.set_ticklabels([]) ax1.plot(x, f(x)) ax1.grid(True) ax2 = plt.subplot(2, 1, 2) ax2.set_title("Differential function") ax2.set_xlim(0, 10) ax2.set_ylim(0, 200) ax2.plot(x, g(f, x)) ax2.grid(True) plt.show()
27990b303362311d16fdcce1ee0266bdb692f6d2
jpark527/Fall2018
/Python/HarvaidX/knnClassification.py
4,436
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 2 23:38:02 2018 @author: j """ import numpy as np import random import scipy.stats as ss import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def getDistance(p1, p2): ''' Find the distance between p1 and p2. ''' p1 = np.array(p1) p2 = np.array(p2) return np.sqrt(np.sum(np.power(p2-p1, 2))) def majorityVote(votes): ''' Returns the most common element in votes. ''' voteCount = dict() for v in votes: if v in voteCount: voteCount[v] += 1 else: voteCount[v] = 1 maxVote = max(voteCount.values()) winners = list() for key, value in voteCount.items(): # this items() allows user to get both key and value at the same time if value == maxVote: winners.append(key) return random.choice(winners) def majorityVote2(votes): ''' Same as majorityVote ''' mode, count = ss.mstats.mode(votes) # print(mode, count) return random.choice(mode) def findNearestPoints(p, points, k=5): ''' Find the k nearest neighbors of point p and return their indices ''' distances = np.zeros(points.shape[0]) for i in range(len(distances)): distances[i] = getDistance(p, points[i]) d = np.argsort(distances) # gives the array of original indices in a sorted order. return d[:k%len(d)] def knnPredict(p, points, outcomes, k=5): ind = findNearestPoints(p, points, k) return majorityVote(outcomes[ind]) def generateSyntheticData(n=50): ''' Generate 2 sets of points from bivariate normal distributions. ''' points = np.concatenate((ss.norm(0,1).rvs((n,2)), ss.norm(1,1).rvs((n,2))), axis=0) outcomes = np.concatenate((np.repeat(0,n), np.repeat(1,n))) return points, outcomes def makePredictionGrid(predictors, outcomes, limits, h, k): ''' Classify each point on the prediction grid. ''' xMin, xMax, yMin, yMax = limits x = np.arange(xMin, xMax, h) y = np.arange(yMin, yMax, h) xx, yy = np.meshgrid(x,y) predictionGrid = np.zeros(xx.shape, dtype = int) for k1, v1 in enumerate(x): for k2, v2 in enumerate(y): p = np.array([v1, v2]) predictionGrid[k2, k1] = knnPredict(p, predictors, outcomes, k) return x, y, predictionGrid def plotPredictionGrid (xx, yy, predictionGrid): ''' Plot KNN predictions for every point on the grid. ''' backgroundColormap = ListedColormap (['hotpink', 'lightskyblue', 'yellowgreen']) observationColormap = ListedColormap (['red', 'blue', 'green']) plt.figure(figsize =(10,10)) plt.pcolormesh(xx, yy, predictionGrid, cmap = backgroundColormap, alpha = 0.5) plt.scatter(predictors[:,0], predictors [:,1], c = outcomes, cmap = observationColormap, s = 50) plt.xlabel('Variable 1'); plt.ylabel('Variable 2') plt.xticks(()); plt.yticks(()) plt.xlim (np.min(xx), np.max(xx)) plt.ylim (np.min(yy), np.max(yy)) #n = 5; k = 5; h = 0.1; limits=(-3,5,-3,5) #predictors, outcomes = generateSyntheticData(20) #xx, yy, predictionGrid = makePredictionGrid(predictors, outcomes, limits, h, k) #plotPredictionGrid(xx, yy, predictionGrid) #''' Plot points to visualize ''' #plt.figure() #plt.plot(predictors[:n,0], predictors[:n,1], 'rd') #plt.plot(predictors[n:,0], predictors[n:,1], 'go') #plt.axis(limits) ''' Different Data (Fisher 1988)''' from sklearn import datasets k = 5; h = 0.1; limits=(3,9,1.5, 5) iris = datasets.load_iris() predictors = iris.data[:, 0:2] outcomes = iris.target xx, yy, predictionGrid = makePredictionGrid(predictors,outcomes,limits,h,k) plotPredictionGrid(xx,yy,predictionGrid) #plt.plot(predictors[outcomes==0][:,0], predictors[outcomes==0][:,1], 'ro') #plt.plot(predictors[outcomes==1][:,0], predictors[outcomes==1][:,1], 'bo') #plt.plot(predictors[outcomes==2][:,0], predictors[outcomes==2][:,1], 'go') ''' More prediction using knn algorithm and sklearn library ''' from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5) knn.fit(predictors, outcomes) skPredictions = knn.predict(predictors) myPredictions = np.array([knnPredict(p, predictors, outcomes, 5) for p in predictors]) print(100 * np.mean(skPredictions==myPredictions)) print(100 * np.mean(skPredictions==outcomes)) print(100 * np.mean(myPredictions==outcomes))
56d983a2ebb06ff1bc4b65bf07fa189e830de598
marcos8896/Python-Crash-Course-For-Beginners
/classes/classes.py
1,335
4.03125
4
#CLASSES AND OBJECTS class Person: __name = '' __email = '' def __init__(self, name, email): self.__name = name self.__email = email def setName(self, name): self.__name = name def getName(self): return self.__name def setEmail(self, email): self.__email = email def getEmail(self): return self.__email def toString(self): return '{} can be contacted at {}'.format(self.__name, self.__email) # marcos = Person('Marcos Barrera', '[email protected]') # marcos.setName('Marcos Barrera') # marcos.setEmail('[email protected]') # print(marcos.getEmail(), marcos.getName()) # print(marcos.toString()) class Customer(Person): __balance = 0 def __init__(self, name, email, balance): self.__name = name self.__email = email self.__balance = balance super(Customer, self).__init__(name, email) def setBalance(self, balance): self.__balance = balance def getBalance(self): return self.__balance def toString(self): return '{} has a balance of {} and can be contacted at {}'.format(self.__name, self.__balance, self.__email) marcos = Customer('Marcos Barrera', '[email protected]', '1000') print(marcos.toString())
2d35e441b55121ba76ef7b05ef7a8b3a4bae2ef8
edanilovets/python-jumpstart
/05_weather_app/05_weather_app.py
1,334
3.59375
4
import requests import bs4 import collections WeatherReport = collections.namedtuple('WeatherReport', 'loc, temp') def main(): # print the header print_header() # get zip code from user zip_code = input('What is your zip code (96001)? ') # get html from web html = get_html_from_web(zip_code) # parse the html report = get_weather_from_html(html) # display for the forecast print('Location: {}'.format(report.loc)) print('Temperature: {}'.format(report.temp)) def print_header(): print('--------------------------') print(' WEATHER APP') print('--------------------------') print() def get_html_from_web(zip_code): url = 'https://www.wunderground.com/weather/us/or/portland/{}'.format(zip_code) response = requests.get(url) return response.text # print(response.text[0:250]) def cleanup_text(text: str): if not text: return text text = text.strip().replace("\n", "") return text def get_weather_from_html(html): soup = bs4.BeautifulSoup(html, "html.parser") loc = soup.find('h1').get_text() loc = cleanup_text(loc) temp = soup.find(class_='current-temp').get_text() temp = cleanup_text(temp) report = WeatherReport(loc=loc, temp=temp) return report if __name__ == '__main__': main()
088c2c0de2547adea8433d500df3f5c98bf75979
pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate
/samples/conceptual_samples/exceptional_handling/user_defined_exceptions.py
377
4.15625
4
# this is a sample python program which is used to create a user defined exception class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2*2) except MyError as e: print 'My exception occurred, value:', e.value # this is the end of the python program . happy coding ...!!!
63a39387a4d1c31de732f113390d2f9305528838
rlee1204/hackerrank
/strings/palindrome_index.py
675
3.65625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def get_palindrome_creation_index(s): len_s = len(s) for i in xrange(len_s//2): comparison_char_index = len_s - 1 - i if s[i] == s[comparison_char_index]: continue if s[i] == s[comparison_char_index - 1]: if i + 1 < len_s and s[i+1] == s[comparison_char_index -2]: return comparison_char_index return i return -1 cases = int(raw_input()) for _ in xrange(cases): s = raw_input() print get_palindrome_creation_index(s) print get_palindrome_creation_index('hgygsvlfwcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcflvsgygh')
9b5b033bc4889cde686257355ee3f07a14ce5653
jeremiahd/TTA_Student_Projects
/5_Python/Python Projects/TextGame/game.py
2,991
4.03125
4
# Python: 3.7.3 # Author: Jeremiah Davis # Purpose: Python text based game def start(nice=0, mean=0, name=""): #get user's name name = describe_game(name) nice, mean, name = nice_mean(nice, mean, name) def describe_game(name): """ check if this is a new game or not. If it is new, get the user's name. If it is not a new game, thank the player for playing again and continue with the game """ # meaning, if we do not already have this user's name, # then they are a new player and we need to get their name if name != "": print( "\nThank you for playing again, {}!".format(name) ) else: while True: if name == "": name = input( "\nWhat is your name? \n>>> ".capitalize() ) if name != "": print("\nWelcome, {}!".format(name) ) print("\nIn this game, you will be greeted \n by several different people.\n") print("but at the end of the game your fate \n will be sealed by your actions.") break return name def nice_mean(nice, mean, name): while True: # game loop show_score(nice,mean,name) pick = input("\nA stranger approaches you for a \nconversation. Will you be nice\nor mean? (N/M/quit) \n>>>: ".lower() ) if pick == "n": print("\nThe stranger walks away smiling...") nice = nice + 1 break if pick == "m": print("The stranger glares at you \nmenacingly and storms off...") mean = mean + 1 break if pick == "quit": quit() score(nice, mean, name) # pass the three variables to the score() def show_score(nice, mean, name): print( "\n{}, your current total: \n({}, Nice) and ({}, Mean)".format(name, nice, mean) ) def score(nice, mean, name): #score function is being passed the values stored within the 3 variables if nice > 2: win(nice, mean, name) if mean > 2: lose(nice, mean, name) else: nice_mean(nice,mean,name) def win(nice, mean, name): print( "\nNice job {}, you win!\n Everyone loves you and you've \n made lots of friends along the way!".format(name) ) again(nice, mean, name) def lose(nice, mean, name): print( "\nTerrible job {}, you lose!\n Everyone hates you and you've \n made no friends along the way!".format(name) ) again(nice, mean, name) def again(nice, mean, name): while True: choice = input("\nDo you want to play again? (y/n):\n>>> ").lower() if choice == "y": reset(nice,mean,name) break if choice == "n": print("\nOh, so sad, sorry to see you go!") quit() else: print("\nEnter ( Y ) for 'YES', ( N ) for 'NO':\n>>> ") def reset(nice, mean, name): nice = 0 mean = 0 start(nice, mean, name) # main entry point if __name__ == "__main__": start()
87ea315ed9bae5316a459750c1561de865b79d1a
duygucumbul/pyt4585
/kararorn1.py
1,539
3.796875
4
#Örnek: Dışarıdan kullanıcı not girişi sağlayacak # 0 - 30 => FF # 31 - 50 => DD # 51 - 70 => CC # 71 - 84 => BB # 85 -100 => AA harf notunu aldınız uyarısı veriniz. try: not_ = int(input("Lütfen notunuzu giriniz: ")) result = "Girilen {} notun karşılık harf notu: {}" if not_ <= 30 and not_ >= 0 : result = (result.format(not_,"FF")) elif not_ >= 31 and not_<= 50 : result = (result.format(not_,"DD")) elif not_ >= 51 and not_ <=70 : result = (result.format(not_,"CC")) elif not_ >= 71 and not_ <= 84 : result = (result.format(not_,"BB")) elif not_ >= 85 and not_ <= 100 : result = (result.format(not_,"AA")) else: result = ("0 ile 100 arasında bir değer giriniz") print (result) except ValueError as mahmud : print (mahmud) # try: # not_ = int(input("Lütfen notunuzu giriniz: ")) # result = "Girilen {} notun karşılık harf notu: {}" # if not_ <= 100 and not_ >= 0 : # result = "harf notunuz: " # if not_ <= 30 : # result = (result.format(not_,"FF")) # elif not_<= 50 : # result = (result.format(not_,"DD")) # elif not_ <=70 : # result = (result.format(not_,"CC")) # elif not_ <= 84 : # result = (result.format(not_,"BB")) # elif not_ <= 100 : # result = (result.format(not_,"AA")) # else: # result = ("0 ile 100 arasında bir değer giriniz") # print (result) # except ValueError as mahmud : # print (mahmud)
43ded8660e6586618b8950086e4c838eb71b856a
andriitugai/python-morsels
/ordered_set.py
2,361
3.921875
4
class OrderedSet(object): def __init__(self, some_iterable): self.container = [] self.underset = set() for item in some_iterable: if item not in self.underset: self.container.append(item) self.underset.add(item) def __repr__(self): return self.container.__repr__() def __str__(self): return self.container.__str__() def __iter__(self): return iter(self.container) def __eq__(self, other): if not (isinstance(other, OrderedSet) or isinstance(other, set)): # don't attempt to compare against unrelated types return NotImplemented if isinstance(other, set): return other == set(self.underset) else: if len(self) != len(other): return False return all(x == y for x, y in zip(self, other)) def __contains__(self, item): return item in self.underset def add(self, item): if item not in self.underset: self.container.append(item) self.underset.add(item) def discard(self, item): if item in self.underset: self.container.remove(item) self.underset.remove(item) def __len__(self): return len(self.container) def __getitem__(self, i): return self.container[i] if __name__ == "__main__": ordered_words = ["these", "are", "words", "in", "an", "order"] print(*OrderedSet(ordered_words)) print(*set(ordered_words)) print(*OrderedSet(["repeated", "words", "are", "not", "repeated"])) words = OrderedSet(["hello", "hello", "how", "are", "you"]) words.add("doing") print(*words) words.discard("Python!") words.discard("are") print(*words) # print({"0", "1", "2"} == OrderedSet(["2", "1", "0"])) print(OrderedSet([1, 2, 3]) == OrderedSet([1, 2, 3])) print(OrderedSet([1, 2, 3]) == OrderedSet([1, 2, 3, 4])) print(OrderedSet([1, 2, 3, 4]) == OrderedSet([1, 2, 3])) print(OrderedSet([1, 3, 2]) == OrderedSet([1, 2, 3])) print(OrderedSet(["how", "are", "you"]) == OrderedSet(["how", "you", "are"])) print(OrderedSet(["how", "are", "you"]) == {"how", "you", "are"}) print(OrderedSet(["how", "are", "you"]) == ["how", "are", "you"]) print(words[1], words[-1])
579ae81be6c17e61c7608b2e20d18a8c280062b0
Magnus-ITU/project1_code_1styear
/project_data.py
1,107
3.515625
4
import numpy as np def data_load_to_array(file): """Reads in the data from csv file and stores it in an array.""" with open(file, "r") as data_str: data_list = [] for i in data_str: list_str = i.split("\n") del list_str[-1] data_list.append(list_str) data_array = [] for line in data_list: data_array.append(np.array(line[0].split(","))) data_array = np.array(data_array) header = data_array[0] array_data_set = data_array[1:] array_data_set = array_data_set.reshape((len(array_data_set), len(header))) return array_data_set def main(): """Main function for executing each of the functions with corresponding parameters.""" file_acc = "road_safety_data_accidents_2019.csv" accidents_2019_data = data_load_to_array(file_acc) file_cas = "road_safety_data_casualties_2019.csv" # casualties_2019_data = data_load_to_array(file_cas) file_veh = "road_safety_data_vehicles_2019.csv" # vehicles_2019_data = data_load_to_array(file_veh) if __name__ == "__main__": main()
68a5b859eedeb3c618af6750be202ef51688eddf
JerinPaulS/Python-Programs
/MapSumPairs.py
1,641
4.09375
4
''' Implement the MapSum class: MapSum() Initializes the MapSum object. void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one. int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix. Example 1: Input ["MapSum", "insert", "sum", "insert", "sum"] [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] Output [null, null, 3, null, 5] Explanation MapSum mapSum = new MapSum(); mapSum.insert("apple", 3); mapSum.sum("ap"); // return 3 (apple = 3) mapSum.insert("app", 2); mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) Constraints: 1 <= key.length, prefix.length <= 50 key and prefix consist of only lowercase English letters. 1 <= val <= 1000 At most 50 calls will be made to insert and sum. ''' class MapSum(object): def __init__(self): """ Initialize your data structure here. """ self.word_dict = {} def insert(self, key, val): """ :type key: str :type val: int :rtype: None """ self.word_dict[key] = val def sum(self, prefix): """ :type prefix: str :rtype: int """ sum_val = 0 list_keys = self.word_dict.keys() for key in list_keys: if len(key) >= len(prefix) and prefix == key[:len(prefix)]: sum_val = sum_val + self.word_dict[key] return sum_val # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)
802875e2b188baa3741f7638bb1aaf493ddfabe4
i-tanuj/Drawing-Application
/multitreading/multitreadingapp3.py
430
3.59375
4
import time from threading import * def printsquare(l1): for i in l1: print("square of ",i,"is",i*i) time.sleep(1) def printcube(l2): for i in l2: print("cube of ",i,"is",i*i*i) time.sleep(1) being=time.time() l3=[n for n in range(1,11)] t1=Thread(target=printsquare,args=(l3,)) t2=Thread(target=printcube,args=(l3,)) t1.start() t2.start() t1.join() t2.join() end=time.time() print("Total time taken",end-being,"second")
15641eb4c521a1d17460445158c36cad1f23c0d1
ricardo1470/holbertonschool-interview
/0x1F-pascal_triangle/0-pascal_triangle.py
628
4.03125
4
#!/usr/bin/python3 """ that returns a list of lists of integers representing the Pascal’s triangle """ def pascal_triangle(n): """ Returns an empty list if n <= 0 """ if n <= 0: return [] """ Returns a list of lists of integers representing """ triangle = [[1]] """ Loop through the triangle """ for i in range(1, n): triangle.append([]) for j in range(i + 1): if j == 0 or j == i: triangle[i].append(1) else: triangle[i].append(triangle[i - 1][j - 1] + triangle[i - 1][j]) return triangle
fa078791349b673866e956a0a645022d0338da88
tarunpsquare/Python
/HangHimNotFreeHim.py
10,655
4.15625
4
# -*- coding: utf-8 -*- """ @author: Tarun Purohit [email protected] """ #Python Project:HANG HIM NOT FREE HIM #Implemented a game in python which is very similar to Hangman. #Turtle library used to draw the stick figure of the man. import random, time, turtle,sys def movies(): movies=["DJANGO UNCHAINED", "AVATAR", "INCEPTION", "DUNKIRK", "THE REVENANT"] chosenword=random.choice(movies) chosenwordlist=list(chosenword) attempts = (len(chosenword) + 3) print("Your movie has been selected at random. Let the guessing game begin!\n") print("A hint to make things easier:") if chosenword=='AVATAR': print("Graphical representation of a user or the user's character or persona.\n") elif chosenword=='DJANGO UNCHAINED': print("DJ Not chained.\n") elif chosenword=='INCEPTION': print("Entering dreams.\n") elif chosenword=='DUNKIRK': print("World War 2, Allied forces, German army.\n") elif chosenword=='THE REVENANT': print("Fur trading expedition, 1820s, bear, abandnded by hunting team.\n") elif chosenword=='THE EXORCIST': print("When a 12-year-old girl is possessed by a mysterious entity, her mother seeks the help of two priests to save her.\n") elif chosenword=='JURASSIC PARK': print("A pragmatic palaeontologist visiting an almost complete theme park is tasked with protecting a couple of kids after a power failure causes the park's cloned dinosaurs to run loose.\n") elif chosenword=='BACK TO THE FUTURE': print("A 17-year-old high school student, is accidentally sent thirty years into the past in a time-traveling DeLorean invented by his close friend, an eccentric scientist.\n") elif chosenword=='THE DARK KNIGHT': print("When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, a masked vigilante must accept one of the greatest psychological and physical tests of his ability to fight injustice.\n") elif chosenword=='GLADIATOR': print("A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery.\n") print("The number of allowed guesses for this word is:", attempts) guesses(chosenword, chosenwordlist, attempts) def places(): places=["QUEBEC", "ILLINOIS", "NEW YORK", "MELBOURNE", "SICILY"] chosenword=random.choice(places) chosenwordlist=list(chosenword) attempts = (len(chosenword) + 3) print("Your places has been selected at random. Let the guessing game begin!\n") print("A hint to make things easier:") if chosenword=='QUEBEC': print("Eastern province of Canada and the oldest city of Canada. Home to attractions such as Basilica of Sainte-Anne-de-Beaupré and Place Royale. Also constitutes of the French speaking population of Canada.\n") elif chosenword=='ILLINOIS': print("It is a midwestern state bordering Indiana in the east and the Mississippi River in the west. Nicknamed the Prairie State, it's marked by farmland, forests, rolling hills and wetlands. Chicago, one of the largest cities in the U.S, is in the northeast on the shores of Lake Michigan. \n") elif chosenword=='NEW YORK': print("Home to the Empire state building and also the most busiest place in U.S.A.\n") elif chosenword=='MELBOURNE': print("Coastal capital of the southeastern Australian state of Victoria. At the city's centre is the modern Federation Square development, with plazas, bars, and restaurants by the Yarra River.Also one of the most sought after places in Australia after Sydney.\n") elif chosenword=='SICILY': print("One of the most beautiful and historic places in Italy. The largest Mediterranean island, is just off the toe of Italy's boot. Its rich history is reflected in sites like the Valley of the Temples, the well-preserved ruins of 7 monumental, Doric-style Greek temples, and in the Byzantine mosaics at the Cappella Palatina, a former royal chapel in capital city Palermo.\n") print("The number of allowed guesses for this word is:", attempts) guesses(chosenword, chosenwordlist, attempts) def animals(): animals=["MONKEY", "CHEETAH", "BLACK MAMBA", "CROCODILE"] chosenword=random.choice(animals) chosenwordlist=list(chosenword) attempts = (len(chosenword) + 3) print("Your animal has been selected at random. Let the guessing game begin!\n") print("A hint to make things easier:") if chosenword=='MONKEY': print("Their fur is generally a shade of brown or black, and their muzzles, like those of baboons, are doglike but rounded in profile, with nostrils on the upper surface.\n") elif chosenword=='CHEETAH': print("Large cat native to Africa and central Iran. It is the fastest land animal, capable of running at 80 to 128 km/h, and as such has several adaptations for speed, including a light build, long thin legs and a long tail.\n") elif chosenword=='BLACK MAMBA': print("Species of highly venomous snake belonging to the family Elapidae. It is native to parts of sub-Saharan Africa.\n") elif chosenword=='CROCODILE': print("Large semiaquatic reptiles that live throughout the tropics in Africa, Asia, the Americas and Australia.have powerful jaws with many conical teeth and short legs with clawed webbed toes.\n") print("The number of allowed guesses for this word is:", attempts) guesses(chosenword, chosenwordlist, attempts) def guessedletter(guesslist): print("Your Secret word is: " + ''.join(guesslist)) def guesses(chosenword, chosenwordlist, attempts): guess='' hang=0 guesslist=list(guess) len(guess)==len(chosenword) rope=turtle.Turtle() rope.penup() rope.goto(-40.00,100.00) rope.back(100) rope.right(90.00) rope.pendown() rope.forward(300) rope.penup() rope.back(300) rope.pendown() rope.left(90) rope.forward(140) rope.right(90) rope.forward(40) for n in chosenwordlist: guesslist.append(' _ ') guessedletter(guesslist) while True: letter=input("Enter a letter\n") letter=letter.upper() if letter in guesslist: print("This letter has already been guessed.\n") print("Guess a different letter.\n") else: attempts=attempts-1 if letter in chosenwordlist: print("Bang on!") if attempts>0: print("You have: ", attempts," :attempts left.") for i in range(len(chosenwordlist)): if letter == chosenwordlist[i]: letterindex = i guesslist[letterindex] = letter guessedletter(guesslist) else: print("Oops! Try again.") hang=hang+1 hangman(hang, chosenword) if attempts > 0: print("You have ", attempts, 'guess left!') guessedletter(guesslist) joinedList = ''.join(guesslist) if joinedList.upper() == chosenword.upper(): print("Yay! you won.\nHang Him Not, Free Him") print("Do you wish to play again?\n") replay=input("Y for yes and anything else to quit") replay=replay.upper() if replay=='Y': user() else: print("Thank you for playing Hang Him Not Free Him! Hope you had fun.\n") sys.exit() elif attempts == 0: print("Too many Guesses!, Sorry better luck next time.") print("Hang Him, Not Free Him.\n") print("Do you wish to play again?\n") print("The secret word was: "+ chosenword()) replay=input("Y for yes and anything else to quit") replay=replay.upper() if replay=='Y': turtle.clearscreen() user() else: print("Thank you for playing Hang Him Not Free Him! Hope you had fun.\n") time.sleep(2) sys.exit() def hangman(hang, chosenword): if hang==1: turtle.penup() turtle.goto(0.00,0.00) turtle.setheading(0.00) turtle.pendown() turtle.circle(30) elif hang==2: turtle.right(90) turtle.forward(30) turtle.right(30.00) turtle.forward(40) turtle.penup() elif hang==3: turtle.back(40) turtle.left(60.00) turtle.pendown() turtle.forward(40) turtle.penup() elif hang==4: turtle.back(40) turtle.right(30.00) turtle.pendown() turtle.forward(60) turtle.right(30.00) turtle.forward(40) turtle.penup() elif hang==5: turtle.back(40) turtle.left(60.00) turtle.pendown() turtle.forward(40) print("Hang Him, Not Free Him\n") print("The secret word was: "+ chosenword) print("Do you wish to play again?\n") replay=input("Y for yes and anything else to quit") replay=replay.upper() if replay=='Y': turtle.clearscreen() user() else: print("Thank you for playing Hang Him Not Free Him! Hope you had fun.\n") sys.exit() def user(): turtle.clearscreen() name=input("Hey there! Enter your name:\n") if name.isalpha() == True: print("Hello", name.capitalize(), "let's start playing Hang Him Not Free Him!") time.sleep(1) print("The objective of the game is to guess the secret word chosen by the computer.") time.sleep(1) print("You can guess only one letter at a time. Don't forget to press 'enter key' after each guess.") time.sleep(2) print("Let the fun begin!") time.sleep(1) choice=int(input("What are you most confident about?\n 1.Movies\n 2.Places\n 3.Animals\n")) if choice==1: movies() elif choice==2: places() elif choice==3: animals() else: print("Wrong entry. Restart.") user() else: print("Invalid. Retype name.") user() user()
3280b7da5abda559f8699a795836e5cb595fae84
starryKey/LearnPython
/04-TKinter基础/TkinterExample09.py
958
3.59375
4
# 画一个五角星 import tkinter import math as m baseFrame = tkinter.Tk() w = tkinter.Canvas(baseFrame, width=300, height=300, background="gray" ) w.pack() center_x = 150 center_y = 150 r = 150 # 依次存放五个点的位置 points = [ #左上点 # pi是一个常量数字,3.1415926 center_x - int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #右上点 center_x + int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #左下点 center_x - int(r * m.sin( m.pi / 5)), center_y + int(r * m.cos( m.pi / 5)), #顶点 center_x, center_y - r, #右下点 center_x + int(r * m.sin(m.pi / 5)), center_y + int(r * m.cos(m.pi / 5)), ] # 创建一个多边形 w.create_polygon(points, outline="green", fill="yellow") w.create_text(150,150, text="五角星") baseFrame.mainloop()
21dda8a95578b433c2ae96aa6bbcede2799ae01a
luckyguy73/wb_homework
/2_week/valid_sudoku.py
812
3.75
4
import collections from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: def make_subs(): subs = [[] * 9 for _ in range(9)] for i in range(0, len(board), 3): for j in range(0, len(board), 3): for x in range(3): for y in range(3): subs[j // 3 + i].append(board[x + i][y + j]) return subs def check_area(area): for i in range(len(area)): for n in nums: if area[i].count(n) > 1: return False return True nums, cols, subs = '123456789', list(zip(*board)), make_subs() return all([check_area(x) for x in (board, cols, subs)])
427bea7bc24d055ca56872ad1f655137812c24a4
Connorsmith25/SSW567HW02Triangle
/Triangle.py
919
3.8125
4
# Connor Smith # Professor Saremi # SSW 567 # HW 02a # "I pledge my honor that I have abided by the Stevens Honor System" def classifyTriangle(a, b, c): # check if input is valid if not (isinstance(a, int) and isinstance(b, int) and isinstance(c, int)): return 'InvalidInput' if a <= 0 or b <= 0 or c <= 0: return 'InvalidInput' if a > 300 or b > 300 or c > 300: return 'InvalidInput' # sort sides by length for easier calculations sides = (a, b, c) a, b, c = sorted(sides) # check if input is a triangle if (a >= (b + c)) or (b >= (a + c)) or (c >= (a + b)): return 'NotATriangle' # now we know that we have a valid triangle elif ((a ** 2) + (b ** 2)) == (c ** 2): return 'Right' if a == b == c: return 'Equilateral' elif (a == b) or (a == c) or (b == c): return 'Isosceles' else: return 'Scalene'
af816a3d6e5b1cd5c6106a4bcc723e9b274bf6ca
cagriozcaglar/ProgrammingExamples
/DataStructures/TreesGraphs/SimilarStringGroups/SimilarStringGroups.py
1,902
4.09375
4
""" 839. Similar String Groups Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there? """ class Solution: def numSimilarGroups(self, strs: List[str]) -> int: # Generate adjacency graph among strings adj = defaultdict(list) for i, string in enumerate(strs): # Careful: End index is len(strs), because it is exclusive range boundary for j in range(i+1, len(strs)): if self.isSimilar(strs[i], strs[j]): adj[strs[i]].append(strs[j]) adj[strs[j]].append(strs[i]) visited = set() def dfs(word) -> None: nonlocal adj nonlocal visited if word in visited: return visited.add(word) for simWord in adj[word]: dfs(simWord) count = 0 for word in strs: if word not in visited: dfs(word) count += 1 return count def isSimilar(self, str1: str, str2: str) -> bool: diff = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diff += 1 return diff <= 2
ce5bec8be1b74ebc3f50b3f22e988ce20c5d5356
ijassiem/training_one
/pokemon/pokemon.py
3,645
4.09375
4
"""This module contains a two classes for creating pokemon.""" from random import randint def repeat(m): """Decorator-function allows decorated function to repeat random number of times, ranging from 0 to m. Parameters ---------- m : int The value of the maximum random number allowed to be generated. """ def inner(func_object): def wrapper(*args, **kwargs): rand_num = randint(0, m) print(f"Repeat {rand_num} times") for i in range(rand_num): func_object(*args, **kwargs) return wrapper return inner class Pokemon(object): """ This class Pokemon represents a pokemon character with several attributes. Attributes ---------- name : str Name of pokemon. nickname : str Nickname of pokemon. moves : list A list of 4 pokemon moves. """ repeat_max = 10 def __init__(self, name, nickname): """Initialise Pokemon class object with a name and nickname. Parameters ---------- name : str Name of pokemon. nickname : str Nickname of pokemon. """ self.name = name self.nickname = nickname self.moves = ["jump", "strike", "dash", "block"] @repeat(repeat_max) def speak(self): """Print the name of pokemon and repeat number of random times.""" print(self.name) def speak_once(self): """Print the name of pokemon once.""" print(self.name) def learn_move(self, new_move): """Add a new move to the list of the pokemon moves. The first item in list is removed. Parameters ---------- new_move : str The name of the new move to be added to the list of moves. """ self.moves.append(new_move) self.moves.pop(0) def print_details(self): """Print all details of pokemon.""" print(f"NAME: {self.name}") print(f"NICKNAME: {self.nickname}") print("MOVES:", end=" ") for i in self.moves: print(i, end=" ") print() class ElectricPokemon(Pokemon): """ This class ElectricPokemon inherits from the base class Pokemon, and represents a specific type pokemon character with several attributes. Attributes ---------- name : str Name of pokemon. nickname : str Nickname of pokemon. moves : list A list of 4 pokemon moves. pokemon_type : str Type of pokemon. """ def __init__(self, name, nickname, pokemon_type): """Initialise ELectricPokemon class object with a name, nickname and type. Parameters ---------- name : str Name of pokemon. nickname : str Nickname of pokemon. pokemon_type : str Type of pokemon. """ self.pokemon_type = pokemon_type super(ElectricPokemon, self).__init__(name, nickname) def print_details(self): """Print all details of pokemon.""" # print("\nNAME:", self.name) # print("NICKNAME:", self.nickname) # print("MOVES:", end=" ") # for i in self.moves: # print(i, end=" ") super(ElectricPokemon, self).print_details() print(f"SPECIES TYPE: {self.pokemon_type}") if __name__ == "__main__": p = Pokemon("pikachu", "pika") p.speak() p.speak() p.speak() p.learn_move("glide") p.print_details() e = ElectricPokemon("charmander", "char", "fire") e.speak() e.speak() e.speak() e.print_details()
83e4fbc0a18862239c2ce8f6792f5c7f8256ba78
L200180048/Praktikum-ASD
/modul2/5.py
1,147
4
4
class Mahasiswa(object): """Class Mahasiswa yang dibangun dari class Manusia""" kuliah =[] def __init__(self,nama,NIM,kota,us): """Metode inisialisasi ini menutupi metode inisiasi di class Manusia.""" self.nama = nama self.NIM = NIM self.kotaTinggal = kota self.uangsaku = us def __str__(self): s = self.nama+", NIM"+str(self.NIM)\ +". Tinggal di" +self.kotaTinggal \ +". Uang saku Rp."+str(self.uangsaku)\ +" tiap bulan." return s def ambilNama(self): return self.nama def ambilNIM(self): return self.NIM def ambilUangSaku(self): return self.uangsaku def ambilKotaTinggal(self): return self.kotaTinggal def perbaruiKotaTinggal(self,kotabaru): self.kotaTinggal = kotabaru def tambahUangSaku(self,uang): self.uangsaku = self.uangsaku+uang def ambilKuliah(self,mk): self.kuliah.append(mk) def listKuliah(self): return self.kuliah def hapusMatkul(self,mk): return self.kuliah.remove(mk)
bd89c6d757059c94af6517a23b88fb188814ad21
GScabbage/SpartaPasswordProject
/Password_Project/app/userinfo.py
6,167
4.125
4
import sqlite3 from contextlib import closing class userinfoclass: def checkvalid(cls,t): while True: check = input("Is the above correct?(y/n) ") if check.lower() == "y": print ("Great! next") return False break elif check.lower() == "n": print("ok, please re-enter data") return True break else: print("Error, ivalid option entered") def dayofb(self): while True: try: dayofb = int(input("Please enter day of birth: ")) if (len(str(dayofb))==2 or len(str(dayofb))==1) and dayofb in range(1,32): print (dayofb) return dayofb else: print ("date of birth outside of range") except: print("The data you entered was invalid, please enter an integer between 1-31") def monthofb(self): while True: try: monthofb = int(input("Please enter month of birth: ")) if (len(str(monthofb))==2 or len(str(monthofb))==1) and monthofb in range(1,13): print (monthofb) return monthofb else: print ("Month of birth can't exist on earth") except: print("The data you entered was invalid, please enter an integer between 1-12") def yearofb(self): while True: try: yearofb = int(input("Please enter year of birth: ")) if (len(str(yearofb))==4) and yearofb >=1903 and yearofb <=2021: print (yearofb) return yearofb else: print ("Year of birth can't exist, you are either dead or not born") except: print("The data you entered was invalid, please enter an integer between 1903-2021") def senduserdb(self, infodump): try: with closing(sqlite3.connect("users.db")) as connection: with closing(connection.cursor()) as cursor: cursor.execute("CREATE TABLE user_info (id INTEGER PRIMARY KEY, FirstName TEXT, LastName TEXT, DayMonthofBirth TEXT, MonthDayofBirth TEXT, YearofBirth TEXT, MoBtxt TEXT, YoBl2 TEXT);") connection.commit() except: pass with closing(sqlite3.connect("users.db")) as connection: with closing(connection.cursor()) as cursor: cursor.execute("INSERT INTO user_info (FirstName, LastName, DayMonthofBirth, MonthDayofBirth, YearofBirth, MoBtxt, YoBl2) VALUES (?,?,?,?,?,?,?)",(infodump[0],infodump[1],infodump[2],infodump[3],infodump[4],infodump[5], infodump[6],)) connection.commit() def gatherinfo(self): t=True while t==True: fn = input("Please enter first name: ") ln = input("Please enter last name: ") print (fn, ln) t = self.checkvalid(t) if t==False: break else: pass d=True while d==True: dfb = self.dayofb() mfb = self.monthofb() yfb = self.yearofb() print(dfb,'/',mfb,'/',yfb) d=self.checkvalid(d) if d==False: break else: pass while True: if mfb==2 and dfb>=29: leapyears = [1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020] if yfb in leapyears and dfb==29: print("I see you are a rare leap year baby") break else: print ("That day isn't in February!") dfb = self.dayofb() elif mfb in [4,6,9,11] and dfb==31: print("Your birth month has 30 days not 31!") dfb=self.dayofb() else: print("That all looks great, Thank You!") break dmfb=str(dfb)+str(mfb) mdfb=str(mfb)+str(dfb) userinfolist =[fn.lower(),ln.lower(),str(dmfb),str(mdfb),str(yfb)] if mfb == 1: userinfolist.append("jan") elif mfb == 2: userinfolist.append("feb") elif mfb == 3: userinfolist.append("mar") elif mfb == 4: userinfolist.append("apr") elif mfb == 5: userinfolist.append("may") elif mfb == 6: userinfolist.append("jun") elif mfb == 7: userinfolist.append("jul") elif mfb == 8: userinfolist.append("oct") elif mfb == 9: userinfolist.append("sep") elif mfb == 10: userinfolist.append("oct") elif mfb == 11: userinfolist.append("nov") else: userinfolist.append("dec") userinfolist.append(str(yfb)[-2:]) #print(userinfolist) self.senduserdb(userinfolist) return userinfolist def userdataretrieve(self): while True: fn=input("Please enter your first name: ") ln=input("Please enter your last name: ") with closing(sqlite3.connect("users.db")) as connection: with closing(connection.cursor()) as cursor: cursor.execute("SELECT * FROM user_info WHERE FirstName=? and LastName=?", (fn.lower(),ln.lower(),)) udat= cursor.fetchone() if udat==None: print("No data found") n=input("Search again?(y/n) ") if n.lower()=="y": print ("Resetting") else: break else: udat = list(udat) id = udat.pop(0) return udat
50a137a57c8b1d4b2d1974f0addbd573c6b4f2f8
Aasthaengg/IBMdataset
/Python_codes/p03693/s576535932.py
85
3.515625
4
a = int(input().replace(' ', '')) if a % 4 == 0: print('YES') else: print('NO')
4c6ffab64a4c31f1e36f51dc7cf70b0078a287d8
RamonFidencio/exercicios_python
/EX016.py
124
3.984375
4
import math n = float(input ("Digite o primeiro numero:")) n = int(n) print('A parte inteira do seu numero é {}'.format(n))
742c526824ddf5c50c8f970078ad7193044ba9a5
duyvk/GTVRec
/utils/similarity.py
1,941
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Mar 15, 2013 @author: rega ''' import math def similar_list_calculating(l1, l2): """ Tính similarity giữa 2 thành phần của 2 vector đặc trưng, công thức áp dụng trong hàm này là tính hệ số Jaccard, nếu 2 thành phần càng giống nhau thì hệ số Jaccard càng tiệm cận 1 và ngược lại nếu 2 thành phần càng khác nhau thì hệ số Jaccard càng tiệm cận 0. @param l1: list 1st @param l2: list 2nd @return: float, hệ số Jaccard """ if not isinstance(l1, list) and not isinstance(l1, tuple): l1 = l1.all() if not isinstance(l2, list) and not isinstance(l2, tuple): l2 = l2.all() shared_items = list(set(l1) & set(l2)) if shared_items: n_shared_items = len(shared_items) global_max = len(l1) + len(l2) - n_shared_items return 1.0*n_shared_items/global_max else: return 0.0 def similar_number_calculating(max_value, n1, n2): """ Tính similarity giữa 2 thành phần của 2 vector đặc trưng, công thức áp dụng trong hàm này là tính hệ số Jaccard, nếu 2 thành phần càng giống nhau thì hệ số Jaccard càng tiệm cận 1 và ngược lại nếu 2 thành phần càng khác nhau thì hệ số Jaccard càng tiệm cận 0. @param n1: number 1st @param n2: number 2nd @return: float, hệ số Jaccard """ # applied the formula: if max_value < 0: # regarless of maxscore max_value = max(n1,n2) score = (float)(max_value - abs(n1-n2))/max_value # min_value = min(n1, n2) # max_value = max(n1, n2) # return 1.0*min_value/max_value return score if __name__ =="__main__": a = [1,2,3] b = [2,3,4] print similar_list_calculating(a,b) print similar_number_calculating(-1, 4, 2)
612baf1e03b9cf22a01ab1007921239ed447f157
theGreenJedi/Path
/Python Books/Athena/training/demo/demo/threading/downloader.py
3,288
3.6875
4
""" downloader.py -- An example that uses threads to do work in the background while waiting for user input. """ # I've tried to keep this fairly simple. There are *many* possible enhancements! import os import threading import urllib2 # Importing readline adds some nice behavior to raw_input(). import readline def download(url_connection, destination, block_size=32768): """Open and download the contents of `url_connection` (a url object created with urllib2.urlopen) and save in the directory `destination`. The program reads `block_size` bytes at a time when downloading the file. The filename of the file written in `destination` will be taken from the final component of the string `url_connection.url`. """ basename = os.path.basename(url_connection.url) fullname = os.path.join(destination, basename) output_file = open(fullname, 'wb') done = False while not done: data = url_connection.read(block_size) output_file.write(data) done = len(data) < block_size output_file.close() url_connection.close() def main(destination): # `threads` is a list of tuples of the form (Thread, url). threads = [] while True: try: inp = raw_input("]] ") except EOFError: # This occurs if the user hits Ctrl-D print "exit" break inp = inp.strip() if len(inp) == 0: continue elif inp == 'exit': break elif inp == 'status': for thread, url in threads: if thread.is_alive(): print "Downloading '%s'" % url else: # Assume the input is a URL to be downloaded. try: url_connection = urllib2.urlopen(inp) except urllib2.HTTPError, e: print "HTTP error occurred when opening URL '%s'" % inp print "Error code %d: %s" % (e.code, e.msg) continue except (ValueError, urllib2.URLError): print "Invalid URL '%s'" % inp continue print "Downloading '%s'" % inp thread = threading.Thread(target=download, args=(url_connection, destination)) thread.daemon = True threads.append((thread, inp)) thread.start() if __name__ == "__main__": import argparse import textwrap description = textwrap.dedent("""\ A simple URL downloader that demonstrates python threads. At the prompt, enter a URL to download. Downloading will begin immediately, and the prompt will return. Two commands are also understood: status - Show the URLs currently downloading. exit - Exit the program. (Active downloads will stop.) """) parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=description) parser.add_argument('--dest', '-d', help='Destination directory; default is the current directory.') args = parser.parse_args() if args.dest is None: destination = os.path.curdir else: destination = args.dest main(destination)
7716f766825e178ed4f3b57299c25852f86a07b7
carter144/Leetcode-Problems
/problems/11.py
1,395
3.984375
4
""" 11. Container With Most Water Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Solution: The idea is to have two pointers one that starts from the beginning and one that starts at the end. At each iteration we calculate the area and store it into a variable keeping track of the max area. The area is calculated by the minimum height of the two pointers multiplied by the distance apart. We are done with the loop once the left pointer crosses over the right pointer. """ class Solution: def maxArea(self, height: List[int]) -> int: start = 0 end = len(height) - 1 area = 0 while start < end: temp = min(height[start], height[end]) * (end - start) area = max(area, temp) if height[start] > height[end]: end = end - 1 else: start = start + 1 return area
4a830aa37905446a7c99ed081cb32602e3e17482
ryanh153/Morsels
/53_78/55_natural_sort/test_sortutils.py
3,812
3.6875
4
import unittest from sortutils import natural_sort class NaturalSortTests(unittest.TestCase): """Tests for natural_sort.""" def test_empty_iterable(self): self.assertEqual(natural_sort([]), []) self.assertEqual(natural_sort(()), []) self.assertEqual(natural_sort(set()), []) def test_all_lowercase_strings(self): self.assertEqual( natural_sort(['cake', 'apple', 'ball', 'clover', 'zoo']), ['apple', 'ball', 'cake', 'clover', 'zoo'], ) def test_some_uppercase(self): self.assertEqual( natural_sort(['Cake', 'apple', 'ball', 'clover', 'Zoo']), ['apple', 'ball', 'Cake', 'clover', 'Zoo'], ) def test_with_spaces(self): self.assertEqual( natural_sort(['Sarah Clarke', 'Sara Hillard', 'Sarah Chiu']), ['Sara Hillard', 'Sarah Chiu', 'Sarah Clarke'], ) def test_descending_sort(self): self.assertEqual( natural_sort(['Cake', 'apple', 'ball', 'clover', 'Zoo']), ['apple', 'ball', 'Cake', 'clover', 'Zoo'], ) # To test the Bonus part of this exercise, comment out the following line # @unittest.expectedFailure def test_natural_key_function_and_key_argument(self): from sortutils import natural_key self.assertEqual( natural_sort(['cake', 'Zoo', 'Cake', 'zoo'], key=natural_key), ['cake', 'Cake', 'Zoo', 'zoo'], ) names = ['Sarah Clarke', 'Sara Hillard', 'Sarah Chiu'] self.assertEqual( natural_sort(names, key=lambda s: natural_sort(' '.join(s.split()[::-1]))), ['Sarah Chiu', 'Sarah Clarke', 'Sara Hillard'], ) # Make sure sort is stable self.assertEqual( natural_sort(['cake', 'Zoo', 'Cake', 'ball', 'cakE', 'zoo']), ['ball', 'cake', 'Cake', 'cakE', 'Zoo', 'zoo'], ) # To test the Bonus part of this exercise, comment out the following line # @unittest.expectedFailure def test_sorting_with_numbers(self): self.assertEqual( natural_sort(['take 8', 'take 11', 'take 9', 'take 10', 'take 1']), ['take 1', 'take 8', 'take 9', 'take 10', 'take 11'], ) self.assertEqual( natural_sort(['02', '1', '16', '17', '20', '26', '3', '30']), ['1', '02', '3', '16', '17', '20', '26', '30'], ) # To test the Bonus part of this exercise, comment out the following line # @unittest.expectedFailure def test_allow_registering_different_types(self): from sortutils import natural_key @natural_key.register(tuple) def sort_each(items): return [natural_key(x) for x in items] name_tuples = [('Chiu', 'Sarah'), ('Bailey', 'Lou'), ('Chiu', 'Alice')] self.assertEqual( natural_sort(name_tuples), [('Bailey', 'Lou'), ('Chiu', 'Alice'), ('Chiu', 'Sarah')], ) from pathlib import Path @natural_key.register(Path) def path_parts(path): return natural_key(path.parts) # Relies on tuple sorting above self.assertEqual( natural_sort([Path('docs (old)/file1'), Path('docs/file1')]), [Path('docs/file1'), Path('docs (old)/file1')], ) @natural_key.register(Path) # We're redefining how Path sorting works def path_to_string(path): return str(path) name_tuples = [('Chiu', 'Sarah'), ('Bailey', 'Lou'), ('Chiu', 'Alice')] self.assertEqual( natural_sort([Path('docs (old)/file1'), Path('docs/file1')]), [Path('docs (old)/file1'), Path('docs/file1')], ) with self.assertRaises(TypeError): natural_sort([object(), object()]) if __name__ == "__main__": unittest.main(verbosity=2)
65e1a15eefd4ea3d243e0872373eb9692b81f3f0
ayman-shah/Python-CA
/Python 1/20.3.py
213
4.03125
4
#Write your code here food = int(input("how many servings of ruit and veg have ye had")) if food >= 5: print("Well done, you've had your 5+ today") else: print("You should eat 5+ a day, every day.")
0de36965b96d9b69e38d47a2d292bfeebd1ef250
landenthemick/Codewars
/outlier.py
393
4.125
4
def find_outlier(integers): odd = 0 odd_list = [] even = 0 even_list = [] if len(integers) == 0: return None else: for item in integers: if item%2==0: even +=1 even_list.append(item) else: odd +=1 odd_list.append(item) if even > odd: return odd_list[0] else: return even_list[0] print(find_outlier([2,4,6,8,10,3]))
267cf38f3bbdaafe3505278ec8e8560516c72a34
mangeld/aoc2020
/src/day1.py
724
3.90625
4
from sys import argv from typing import List, Tuple from itertools import combinations from functools import reduce def find_2020_entries(entries: List[int], n_products=2) -> Tuple[int, ...]: for combination in combinations(entries, n_products): if sum(combination) == 2020: return combination return () if __name__ == '__main__': with open(argv[1]) as quizz_input: numbers = list(map(int, quizz_input.readlines())) multiply = lambda int_list: reduce(lambda a, b: a * b, int_list) answer = find_2020_entries(numbers) print("First answer:", multiply(answer)) answer = find_2020_entries(numbers, 3) print("Second answer:", multiply(answer))
28f81d8e11cd8c7253ba87b44db02aeeb1af388b
diordnar/DesignPattern
/Python/Builder/Builder.py
591
3.75
4
#! /usr/bin/python # -*- coding: utf-8 -*- ''' Builder Pattern Author: reimen Data: Oct.9.2014 ''' from abc import * class Builder(object): __metaclass__ = ABCMeta @abstractmethod def build(self): pass class Product(object): def execute(self): print "Hi" class ConcreteBuilder(Builder): def build(self): return Product() class Director(object): def __init__(self): self.builder = ConcreteBuilder() def create(self): return self.builder.build() if __name__ == '__main__': a = Director() p = a.create() p.execute()
cb2cc598984ab3f5bdec23659bd1c4405ef29287
prayas2409/Machine_Learning_Python
/Week2/ArrayQ4.py
1,293
3.921875
4
from Utility.UtilityDataStructures import UtilityDataStructures import array as array_object flag: bool = True while flag: try: print('Enter the number of elements to be added to the array') util = UtilityDataStructures() num = util.get_positive_integer() counter = 0 array = array_object.array('i', []) print("Enter the elements for the array") while counter in range(0, num): inputnum = util.get_integer() array.append(inputnum) counter += 1 # printing the array for counter in range(0, num): print(array[counter], " ") print("Enter the number to search and delete") search = util.get_integer() try: # removing the element in the array array.remove(search) num -= 1 print("After deleting the element in the array") # print the members of the array for counter2 in range(0, num): print(array[counter2], " ") except: print("Number not found in the array") except Exception as e: print("Process stopped because %s" % e) print("Enter 0 to exit another value to continue") if input() == 0: flag = False
5763d3c46d991023cb2977019e6477a5f03f2169
starschen/learning
/algorithm_practice/2_1递归的概念.py
2,082
3.828125
4
#encoding:utf8 #2_1递归的概念.py #例2-1 阶乘函数 def factorial(n): if n==1: return n else: return n*factorial(n-1) #例2-2 Fibonacci数列 def Fibonacci(n): if n==1 or n==2: return n else: return Fibonacci(n-1)+Fibonacci(n-2) #例2-3 Ackerman函数 def Ackerman(n,m): if n==1 and m==0: return 2 elif n==0: return 1 elif m==0: return n+2 else: return Ackerman(Ackerman(n-1,m),m-1) # print Ackerman(4,2) #例2-4 排列问题 def swap(a,b): a,b=b,a return a,b def Perm(l,k,m): '''设R={r1,r2,...,rn}是要进行排列的n个元素,Ri=R-{ri}.集合X中元素的全排列记为Perm(X). (ri)Perm(X)表示在全排列Perm(X)的每一个排列前加上前缀ri得到的排列。R的全排列归纳定义如下: 当n=1,Perm(R)=(r),其中r是集合R中唯一的元素 当n>1,Perm(R)由(r1)Perm(R1),(r2)Perm(R2),...,(rn)Perm(Rn)构成''' if k==m: return l else: for i in range(k,m+1): swap(l[k],l[i]) Perm(l,k+1,m) swap(l[k],l[i]) #例2-5 整数划分问题 def intDiv(n,m): '''将正整数n表示成一系列正整数的和,n=m1+m2+...+mi; (其中mi为正整数,并且1 <= mi <= n), 则{m1,m2,...,mi}为n的一个划分。如果{m1,m2,...,mi}中的最大值不超过m,即max(m1,m2,...,mi)<=m, 则称它属于n的一个m划分。这里我们记n的m划分的个数为intDiv(n,m)''' if n==1 or m==1: return 1 elif n<m: return intDiv(n,n) elif n==m: return (1+intDiv(n,m-1)) else: return intDiv(n-m,m)+intDiv(n,m-1) # print intDiv(6,6) #例2-6 Hanoi塔问题 #在网上看到的例子,来源不详,若有侵权请告知立刻删除 steps=0 def move(n,A,B): global steps steps+=1 print 'Move',n,'from',A,'to',B def Hanoi(n,A,B,C): if n==1: move(n,A,B) else: Hanoi(n-1,A,C,B) move(n,A,B) Hanoi(n-1,C,B,A) Hanoi(4,'A','B','C') print 'steps=',steps
0edfe460eb044805f188bdf8727eb4f74dd4e539
Sarbjyotsingh/learning-python
/Control Flow/forLoop.py
4,826
4.03125
4
cities = ['new york city', 'mountain view', 'chicago', 'los angeles'] for city in cities: print(city.title()) capitalized_cities = [] for city in cities: capitalized_cities.append(city.title()) # Range Function # With one variable argument become stop element print(list(range(4))) # With two variable argument become start and stop element print(list(range(2,6))) # With three variable argument become start, stop, and step element print(list(range(1,10,2))) # using range in for loop for index in range(len(cities)): cities[index] = cities[index].title() print(cities) sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] # Write a for loop to print out each word in the sentence list, one word per line for index in sentence: print(index) # Write a for loop using range() to print out multiples of 5 up to 30 inclusive for index in range(5,31,5): print(index) # Create a set of counters word book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin'] word_counter = {} for word in book_title: if word not in word_counter: word_counter[word] = 1 else: word_counter[word] += 1 print(word_counter) # Using the get method book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin'] word_counter = {} for word in book_title: word_counter[word] = word_counter.get(word, 0) + 1 print(word_counter) cast = { "Jerry Seinfeld": "Jerry Seinfeld", "Julia Louis-Dreyfus": "Elaine Benes", "Jason Alexander": "George Costanza", "Michael Richards": "Cosmo Kramer" } # Iterating through it in the usual way with a for loop would give you just the keys for key in cast: print(key) # If you wish to iterate through both keys and values, you can use the built-in method items for key, value in cast.items(): print("Actor: {} Role: {}".format(key, value)) result = 0 basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] #Iterate through the dictionary for key,value in basket_items.items(): if(key in fruits): result+=value #if the key is in the list of fruits, add the value (number of fruits) to result print(result) #Example 1 result = 0 basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key,value in basket_items.items(): if(key in fruits): result+=value print(result) #Example 2 result = 0 basket_items = {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key,value in basket_items.items(): if(key in fruits): result+=value print(result) #Example 3 result = 0 basket_items = {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key,value in basket_items.items(): if(key in fruits): result+=value print(result) # You would like to count the number of fruits in your basket. # In order to do this, you have the following dictionary and list of # fruits. Use the dictionary and list to count the total number # of fruits and not_fruits. fruit_count, not_fruit_count = 0, 0 basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] #Iterate through the dictionary for key,value in basket_items.items(): if(key in fruits): fruit_count+=value else: not_fruit_count += value #if the key is in the list of fruits, add to fruit_count. #if the key is not in the list, then add to the not_fruit_count print(fruit_count, not_fruit_count) names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] usernames = [] # write your for loop here for name in names: name = name.lower() name = name.replace(' ','_') usernames.append(name) print(usernames) usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # write your for loop here for i in range(len(usernames)): usernames[i] = usernames[i].lower().replace(" ", "_") print(usernames) items = ['first string', 'second string'] html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, it does # the characters that are after it in html_str are on the next line # write your code here for item in items: html_str += ("<li>"+item+"</li>\n") html_str += ("</ul>") print(html_str)
cf88f6fc1dcbe953ee26037aff766908c26fad7a
kalnin-a-i/Polyomino_Tiling
/creating_graph.py
697
3.578125
4
# Создание двудольного графа хранимого в виде двух словарей def create_graph(placements, size): M = size[0] N = size[1] graph = {} graph_invert = {} for i in range(M): for j in range(N): for position in placements.keys(): if placements[position][i][j] == 1: if (i, j) not in graph: graph[(i, j)] = set() if position not in graph_invert: graph_invert[position] = [] graph[(i, j)].add(position) graph_invert[position].append((i, j)) return graph, graph_invert
dc9801c5c0123046e1cf9e9b7258050401d85d93
youridv1/ProgrammingYouriDeVorHU
/venv/Les7/7_5.py
292
3.71875
4
def gemiddelde(zin): zin = zin.strip() zin = zin.strip('.') zin = zin.split(sep = ' ') total = 0 count = 0 for word in zin: total += len(word) count += 1 res = total / count return res print(gemiddelde(input("Geef een willekeurige zin: ")))
830233ff5aff4ac86942cb7746f188001b923f37
vivekanand-mathapati/python
/filter.py
383
4.125
4
'''As the name suggests, filter creates a list of elements for which a function returns true.''' def odds(value): return True if value % 2 != 0 else False lst = [1,2,3,4,5] odd_num = [x for x in filter(odds, lst)] print(odd_num) #OR odd_num = [x for x in filter(lambda x: x%2 != 0, lst)] print(odd_num) #OR odd_num = [x for x in filter(lambda x: odds(x), lst)] print(odd_num)
fba425f6a647b3201d0fb249cc288e693c7be558
maryaaldoukhi/Rock-Paper-Scissors
/_project2.py
5,675
4.125
4
#!/usr/bin/env python3 """This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" import random import time import sys moves = ['rock', 'paper', 'scissors'] """The Player class is the parent class for all of the Players in this game""" def print_stop(message): print(message) time.sleep(2) class Player: score = 0 my_move = None their_move = None def move(self): return 'rock' def learn(self, my_move, their_move): pass # This is the random player class unsystematic(Player): score = 0 def learn(self, my_move, their_move): pass def move(self): return random.choice(moves) class cycler(Player): score = 0 def learn(self, my_move, their_move): pass def move(self): if self.my_move is None: self.my_move = "scissors" elif self.my_move == "scissors": self.my_move = "paper" elif self.my_move == "paper": self.my_move = "rock" elif self.my_move == "rock": self.my_move = "scissors" return self.my_move # This is the Reflect Player class Immitator(Player): score = 0 def learn(self, my_move, their_move): self.my_move = their_move self.their_move = their_move def move(self): if self.their_move is None: return random.choice(["rock", "paper", "scissors"]) if self.their_move is not None: return self.their_move class Human(Player): score = 0 def learn(self, my_move, their_move): pass def move(self): while True: my_move = input("rock, paper or scissors?").lower() ending = "quit" if my_move in moves: break elif my_move == ending.lower(): sys.exit() else: continue return my_move def beats(one, two): return ((one == 'rock' and two == 'scissors') or (one == 'scissors' and two == 'paper') or (one == 'paper' and two == 'rock')) class Game: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def play_round(self): move1 = self.p1.move() move2 = self.p2.move() print(f"Player 1: {move1} Player 2: {move2}") self.p1.learn(move1, move2) self.p2.learn(move2, move1) if beats(move1, move2) is True: print("Player 1 won this round.") self.p1.score = self.p1.score + 1 print("Scores:") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-") elif beats(move2, move1) is True: print("Player 2 won this round.") self.p2.score = self.p2.score + 1 print("Scores:") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-") else: print("Its a tie. No one won.") print("Scores:") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-") def determine_rounds(self): while 2 == 2: try: answer = int(input("How many rounds would you like to play?")) return answer except ValueError: print("Ops! thats not an integer.") def play_game(self): print("<<<Game start!>>>") for round in range(self.determine_rounds()): print(f"Round {round}:") self.play_round() print("<<<Game over!>>>") if self.p1.score > self.p2.score: print("Total scores") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("Player 1 WON!") elif self.p1.score < self.p2.score: print("Total scores") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("Player 2 WON!") else: print("Final scores") print(f"Player1: {self.p1.score} Player2: {self.p2.score}") print("Its a tie. No one won:(") if __name__ == '__main__': print_stop("Hello! You are playing a game of Rock,Paper,Scissors.") print_stop("Rock beats scissors. Scissors beat paper. Paper beats rock. ") print_stop("You are Player 1.") print_stop("You are going to play against a computer," "so you must choose the computer's play method.") print_stop("Your choices will be shown below.") print_stop(""" 1.Repeated method. 2.Unsystematic method. 3.Cycler method. 4.Immitator method.""") while True: choice = input("Please choose the Computer's Play method" "(repeated,unsystematic,cycler,immitator):").lower() if choice == "repeated": game = Game(Human(), Player()) game.play_game() break elif choice == "unsystematic": game = Game(Human(), unsystematic()) game.play_game() break elif choice == "cycler": game = Game(Human(), cycler()) game.play_game() break elif choice == "immitator": game = Game(Human(), Immitator()) game.play_game() break else: continue
cb4e1bc0a2c7206b3b0172ed8dec05872f7abdc7
Muertogon/2pythonPam
/exercise3.py
188
3.609375
4
c = [] a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = int(input("input number: ")) for i in range(len(a)): if a[i] < b: c.append(a[i]) for i in range(len(c)): print(c[i])
2e0396cdae982499d26ab3618392fec1c9af7d58
zelzhan/Challenges-and-contests
/LeetCode/sqrt(x).py
660
4.09375
4
'''Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.''' class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x < 0: x = -x hi, lo = 2**31 -1, 0 while hi > lo: mid = int(lo + (hi - lo)/2) if mid**2 == x: return mid elif mid**2 > x: hi = mid else: lo = mid + 1 return hi - 1
e12cf5bf91590104b254a7e298dd629017449dc0
narnat/leetcode
/bt_is_cousins/cousins.py
3,237
3.859375
4
#!/usr/bin/env python3 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isCousins(self, root, x, y): from queue import Queue q = Queue(root) q.put(root) is_x = is_y = False while not q.empty(): size = q.qsize() while size: node = q.get() size -= 1 is_x = True if node.val == x else is_x is_y = True if node.val == y else is_y if node.left and node.right: if node.left.val == x and node.right.val == y: return False if node.right.val == x and node.left.val == y: return False if node.left: q.put(node.left) if node.right: q.put(node.right) if is_x and is_y: return True if is_x or is_y: return False return False def isCousins_2(self, root, x, y): """ My first solution""" from queue import Queue q = Queue() q.put(root) parent = None while not q.empty(): size = q.qsize() while size: node = q.get() size -= 1 if node.val == x or node.val == y: val = x if node.val == y else y while size: cousin = q.get() size -= 1 if cousin.val == val: if parent and parent.left != node: return True return False return False if node.left: if node.left.val == x or node.left.val == y: parent = node q.put(node.left) if node.right: if node.right.val == x or node.right.val == y: parent = node q.put(node.right) return False def isCousins_rec(self, root, x, y): """ Recursive solution, not that efficient""" def dfs(tree, depth, parent, val): if tree: if tree.val == val: return depth, parent return dfs(tree.left, depth + 1, tree, val) or dfs(tree.right, depth + 1, tree, val) d1, p1 = dfs(root, 0, None, x) d2, p2 = dfs(root, 0, None, y) return d1 == d2 and p1 != p2 def isCousins_rec_2(self, root, x, y): """ Optimized recursive solution""" def dfs(tree, depth, parent): if tree: if tree.val == x: store[0] = (depth, parent) if tree.val == y: store[1] = (depth, parent) dfs(tree.left, depth + 1, tree) dfs(tree.right, depth + 1, tree) store = [(0, 0), (-1, -1)] dfs(root, 0, None) d1, p1 = store[0] d2, p2 = store[1] return d1 == d2 and p1 != p2
b5dcede26818fe771ac888c3783d730103550bec
NickAlleeProgrammingProjectsPortfolio/pythonWorkBookProjects
/makingExcelFile.py
530
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 11 19:13:59 2020 create new folder and create an excel file in it. add my the argument to the excel file @author: nick """ import os, openpyxl p = os.getcwd() try: os.mkdir("excelFileFolder") except: print("folder already exists") os.chdir(p + "/excelFileFolder") newBook = openpyxl.Workbook() sheet = newBook["Sheet"] sheet['A1'] = "i added this from python" newBook.save(filename = "pythonExcelFile.xlsx") print("new folder and excel file made")
ae76e03f27f31e4e125d8616c094a629e8ccdbb1
Morena-D/Level-0-coding-challenge
/Task0_8.py
376
3.796875
4
def time_convert(t): hours = t // 60 minutes = t % 60 if hours == 1 and minutes ==1: return f"{hours} hour and {minutes} minute" if hours == 1: return f"{hours} hour and {minutes} minutes" if minutes == 1: return f"{hours} hours and {minutes} minute" return f"{hours} hours and {minutes} minutes" print(time_convert(71))
ef1f0ca3270844afb5be8f8892196f47b10252ea
toniferraprofe/septiembre
/escribir.py
326
3.890625
4
''' ESCRIBIR en Disco en Python ''' nombre = input('Nombre: ') # Escritura with open('file.txt', 'a') as f: for i in range(5): f.write(f'{nombre}\n') f.close() # f = open ('file.txt','w') # f.write(nombre) # f.close() # Lectura with open('file.txt','r') as f: for line in f: print(line)
6889a07d22b0b90ce37a6f2c4df7f9bfe8c28d02
devinyi/comp110-21f-workspace
/exercises/ex01/hype_machine.py
394
3.6875
4
# TODO: Write docstring here """Let's cheer someone up.""" # TODO: Initialize __author__ variable here name: str = input("What is your name? ") # TODO: Implement your program logic here print("You entered: ") print(name) print("Go out there and do your best " + name + "!") print(name + " is the GOAT!") print("Keep moving forward, " + name + ", keep moving forward.") __author__ = "730397389"
3ae2869e1e8e0dc0133b46231024224d369a2203
deivid-01/manejo_archivos
/json/jsontools.py
455
3.515625
4
import json def saveJSON(data,fileName): try: with open(fileName,'w') as json_file: # Guardar la informacion json.dump(data,json_file) print("Archivo "+fileName+" guardado") except : print("Archivo no fue creado exitosamente") def readJSON(fileName): with open(fileName,'r') as json_file: data = json.load(json_file) print("Archivo leido correctamente") return data
b194e9618df59bd9580504e7017cf1e8c16d8f20
jiangshen95/PasaPrepareRepo
/Leetcode100/leetcode100_python/MergeTwoSortedLists.py
1,001
3.828125
4
class ListNode: def __init__(self, val = 0, next = None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 if __name__ == "__main__": nums1 = [int(num) for num in input().split()] nums2 = [int(num) for num in input().split()] l1 = ListNode() l2 = ListNode() p = l1 for num in nums1: p.next = ListNode(num) p = p.next p = l2 for num in nums2: p.next = ListNode(num) p = p.next l1 = l1.next l2 = l2.next solution = Solution() result = solution.mergeTwoLists(l1, l2) while result: print(result.val, " ") result = result.next
db7439661ef0a91532197e7eb5f433c7175d1adf
SonBui24/Python
/Lesson07/Bai03.py
140
3.75
4
list_ = ['Tôi', 'Yêu', 'Thích'] s = input("Nhập chuỗi") s1 = [] for i in list_: s1.append(i + s) print(f"List mới là: {s1}")
b66e8843fbb48849145d927f27dd7ebd7b6cec54
glibesyck/URest
/urest/additional_functions.py
1,788
3.796875
4
""" Additional functions for work (transformation of data). ! converting ! sorting_tuples ! random_choice ! first_elements """ import random def converting (dictionary : dict) -> list : ''' Return the keys : values as list of tuples (keys, values). >>> converting ({'a' : 3, 'b' : 4, 'c' : 5}) [('a', 3), ('b', 4), ('c', 5)] ''' list_of_smth = [(keys, values) for keys, values in dictionary.items()] return list_of_smth def sorting_tuples (list_of_tuples : list) -> list : ''' Return the sorted list with values of tuples from maximum to minimum. >>> sorting_tuples ([('a', 3), ('b', 4), ('c', 2)]) [('b', 4), ('a', 3), ('c', 2)] ''' for bottom in range (len(list_of_tuples) - 1) : idx = bottom for itr in range (bottom+1, len(list_of_tuples)) : if list_of_tuples[itr][1] > list_of_tuples[idx][1] : idx = itr list_of_tuples[bottom], list_of_tuples[idx] = list_of_tuples[idx],\ list_of_tuples[bottom] return list_of_tuples def first_elements (list_of_tuples : list) -> list : ''' Return 5 first elements of list or less if len of list is less than 5. >>> first_elements ([('a', 3), ('b', 4), ('c', 2)]) ['a', 'b', 'c'] ''' new_list = [] if len(list_of_tuples) < 5 : for elem in list_of_tuples : new_list.append(elem[0]) else : for idx in range (5) : new_list.append(list_of_tuples[idx][0]) return new_list def random_choice (list_of_smth : list) -> list : ''' Return 5 random elements from list. ''' if len(list_of_smth) < 5 : return random.sample(list_of_smth, len(list_of_smth)) else : return random.sample(list_of_smth, 5)
331994596cb4c442bbcc0168a96d39ed5e45dc28
Aasthaengg/IBMdataset
/Python_codes/p03042/s191121905.py
190
3.59375
4
s = input() if 0 < int(s[:2]) <13 and 0< int(s[2:]) < 13: print("AMBIGUOUS") elif 0 < int(s[:2]) < 13: print("MMYY") elif 0 < int(s[2:]) < 13: print("YYMM") else: print("NA")
6dacdb8e6ccb4ad7bfec9e9180038c60be5703cd
CppChan/Leetcode
/medium/mediumCode/BinarySearchTree/LargestBSTSubtree.py
732
3.546875
4
class Solution(object): def largestBSTSubtree(self, root): if not root: return 0 return self.findBST(root)[0] def findBST(self, root): if not root:return None elif not root.left and not root.right: return (1, (root.val,root.val), True) # (root.val,root.val) is the min and max from this subtree one = self.findBST(root.left) two = self.findBST(root.right) if (one and two) and(one[2] and two[2]) and (one[1][1]<root.val and two[1][0]>root.val): return (one[0]+two[0]+1,(one[1][0], two[1][1]), True) else: if not one: return (two[0], two[1], False) elif not two:return (one[0], one[1], False) elif one[0]>=two[0]: return (one[0], one[1], False) else:return (two[0], two[1], False)
b8faf85858958db46d76cad4704067c8726982c7
KatyaKalache/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
158
3.71875
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): squares = [] for row in matrix: squares.append([i*i for i in row]) return squares
3d946fdafdbbfed302feaafd27ac132947b04f58
orgail/SkillFactory
/Python/C1.10/C1.10.3/Clients.py
715
3.671875
4
# Класс Clients содержит методы наполнения и получения данных списка клиентов class Clients: def __init__(self, clients, name = "", balance = 0): self.name = str(name) self.balance = str(balance) self.clients = clients def set_clients(self): if self.name: self.clients.append({"name": self.name, "balance": int(self.balance)}) class ClientsExec(Clients): def get_ClientBalance(self): for client in self.clients: if client['name'] == self.name:# например 'Иван Петров': return (f'Клиент \"{client["name"]}\". Баланс: {client["balance"]} руб.')
2339f7827eec58d7889a91bbe10b52b426fd79ea
BleShi/PythonLearning-CollegeCourse
/Week 6/6-九九乘法口诀表.py
172
4.03125
4
# 打印生成九九乘法口诀表 for i in range(1,10): # 行 for j in range(1,i+1): # 列 print(i,"*",j,"=",i*j,end=" ") # 横着生成 print() # 换行