blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
fcfe7333a63629913ea0c3cd56b447477182f188
ides15/learn-python
/defaultdict.py
744
3.796875
4
from collections import defaultdict dd = defaultdict(int) # int parameter is just the function int() which returns 0 words = str.split('red blue green red yellow blue red green green red') for word in words: dd[word] += 1 print(dd) print(dd) # above works because defaultdict will generate a key instead of throwing KeyError # d = dict() # words1 = str.split('red blue green red yellow blue red green green red') # for word in words: # d[word] += 1 # print(d) # above won't work because d doesn't already have those keys def isprimary(c): if (c == 'red') or (c == 'blue') or (c == 'green'): return True return False dd2 = defaultdict(bool) for word in words: dd2[word] = isprimary(word) print(dd2)
8e389b4f34ffe1de88cd94f147001e2a2bf27762
vsseixaso/atal
/lista-1/6.py
2,194
3.671875
4
# https://www.geeksforgeeks.org/traveling-salesman-problem-using-branch-and-bound-2/ import math MAX_N = float('inf') def copy_to_final(curr_path): final_path[:N + 1] = curr_path[:] final_path[N] = curr_path[0] def first_min(adj, i): min = MAX_N for k in range(N): if adj[i][k] < min and i != k: min = adj[i][k] return min def second_min(adj, i): first, second = MAX_N, MAX_N for j in range(N): if i == j: continue if adj[i][j] <= first: second = first first = adj[i][j] elif(adj[i][j] <= second and adj[i][j] != first): second = adj[i][j] return second def tsp_rec(adj, curr_bound, curr_weight, lvl, curr_path, vis): global final_res if lvl == N: if adj[curr_path[lvl - 1]][curr_path[0]] != 0: curr_res = curr_weight + adj[curr_path[lvl - 1]][curr_path[0]] if curr_res < final_res: copy_to_final(curr_path) final_res = curr_res return for i in range(N): if (adj[curr_path[lvl-1]][i] != 0 and vis[i] == False): temp = curr_bound curr_weight += adj[curr_path[lvl - 1]][i] if lvl == 1: curr_bound -= ((first_min(adj, curr_path[lvl - 1]) + first_min(adj, i)) / 2) else: curr_bound -= ((second_min(adj, curr_path[lvl - 1]) + first_min(adj, i)) / 2) if curr_bound + curr_weight < final_res: curr_path[lvl] = i vis[i] = True tsp_rec(adj, curr_bound, curr_weight, lvl + 1, curr_path, vis) curr_weight -= adj[curr_path[lvl - 1]][i] curr_bound = temp vis = [False] * len(vis) for j in range(lvl): if curr_path[j] != -1: vis[curr_path[j]] = True def tsp(adj): curr_bound = 0 curr_path = [-1] * (N + 1) vis = [False] * N for i in range(N): curr_bound += (first_min(adj, i) + second_min(adj, i)) curr_bound = math.ceil(curr_bound / 2) vis[0] = True curr_path[0] = 0 tsp_rec(adj, curr_bound, 0, 1, curr_path, vis) N=5 adj = [[0, 3, 1, 5, 8], [3, 0, 6, 7, 9], [1, 6, 0, 4, 2], [5, 7, 4, 0, 3], [8, 9, 2, 3, 0]] final_path = [None] * (N + 1) vis = [False] * N final_res = MAX_N tsp(adj) print("Minimum cost :", final_res) print("Path Taken : ", end = ' ') for i in range(N + 1): print(final_path[i], end = ' ')
f486c40cb86fd4dce28ca2ab462b71104dfb1b9a
esix/competitive-programming
/e-olymp/~contest-9863/E/main.py
77
3.546875
4
from math import sqrt a = int(input()) print (3 * a, a * a * sqrt(3) / 4)
60effd6c7470cf511ddf65addba07459c7f19799
artkra/stuff
/algos/incr_sub_seq.py
361
3.703125
4
def incsum(nums): sumlist = nums[:] for i in range(1,len(nums)): for j in range(0,i): if nums[j] < nums[i] and nums[i] + sumlist[j] > sumlist[i]: sumlist[i] = nums[i] + sumlist[j] print(sumlist) return max(sumlist) if __name__ == '__main__': arr = [1, 101, 2, 3, 100, 4, 5] print(incsum(arr))
d5be6be0426c6e5e9852da9f2abf48827077b92d
dev-himanshu/TA__Internship_Assignment_Solution
/Question-2.py
2,300
4.09375
4
import re def supermarket_shopping(budgets): product_name = input("\nEnter product : ") product_quantity = float(re.findall(r"[-+]?\d*\.\d+|\d+", input("Enter quantity : "))[0]) product_price = float(input("Enter price : ")) amount_left = 0 for values in shopping_list.values(): amount_left += values[1] amount_left = budgets - amount_left if amount_left < product_price: print("\nCan't buy the product because it's price is more than left amount.\n") else: amount_left = 0 if product_name in shopping_list: shopping_list[product_name][0], shopping_list[product_name][1] = product_quantity, product_price else: shopping_list[product_name] = [] shopping_list[product_name].append(product_quantity) shopping_list[product_name].append(product_price) for values in shopping_list.values(): amount_left += values[1] amount_left = budgets - amount_left print("\nAmount left : {0}.\n".format(amount_left)) if __name__ == "__main__": shopping_list = {} budget = int(input("Enter Your Budget : ")) while True: choice = input( "1. Add an item.\n2. Exit.\nEnter Your Choice : ") if choice == "1": supermarket_shopping(budgets=budget) elif choice == "2": amount_left = 0 for values in shopping_list.values(): amount_left += values[1] amount_left = budget - amount_left product = "" max_price_product = 0.0 for j, i in shopping_list.items(): if i[1] <= amount_left: if max_price_product < i[1]: product = j max_price_product = i[1] if len(product): print("\nAmount left can buy you {0}.\n".format(product)) print("Grocery List is :") print("Product Name\tQuantity\tPrice") for i, j in shopping_list.items(): print(i, "\t", str(j[0]) + " kg", "\t", j[1]) else: exit("Goodbye!!!") else: print("!!! Wrong Selection.\n")
8c4b99c9226b67d9eef862620087664a1ef78c73
Priyankasgowda/90dayschallenge
/p71.py
1,030
4
4
# A recursive Python3 program to print maximum # number of A's using following four keys # A recursive function that returns # the optimal length string for N keystrokes def findoptimal(N): # The optimal string length is # N when N is smaller than if N<=6: return N # Initialize result maxi=0 # TRY ALL POSSIBLE BREAK-POINTS # For any keystroke N, we need # to loop from N-3 keystrokes # back to 1 keystroke to find # a breakpoint 'b' after which we # will have Ctrl-A, Ctrl-C and then # only Ctrl-V all the way. for b in range(N-3,0,-1): curr=(N-b-1)*findoptimal(b) if curr>maxi: maxi=curr return maxi # Driver program if __name__=='__main__': # for the rest of the array we will # rely on the previous # entries to compute new ones for n in range(1,21): print('Maximum Number of As with ',n,'keystrokes is ' ,findoptimal(n))
882aaf1d82b6e26c2139b4ff0e8453cd4b1eba46
553672759/xxgit
/python/old/sort/bubble_sort.py
256
4.125
4
''' Created on 2017-1-4 @author: ''' def bubble_sort(lists): count=len(lists) for i in range(0,count): for j in range(i+1,count): if lists[i]>lists[j]: lists[i],lists[j]=lists[j],lists[i] return lists
309eb4aecb11478948d6ee6286213efb5f88c92f
RajDeliwala/PythonPractice
/WholefoodMarketAssesment.py
907
3.84375
4
#Assesment from WholeFoods Market that invloved dealing with queues which have values and prioritys class PriorityQueue: def __init__(self): self.size = 0 self.q = [] def enqueue(self, value, priority): if self.size >= 5: self.q.sort() if self.q[-1] < priority: self.q.pop() self.q.append((value,priority)) self.q.append((value,priority)) self.size += 1 def dequeue(self): if self.size == 0: return self.q.pop() self.size -= 1 def print(self): self.q.sort() for tuple in self.q: print(tuple) PQ = PriorityQueue() PQ.enqueue(5,2) PQ.enqueue(6,1) PQ.enqueue(7,-1) PQ.enqueue(3,0) PQ.dequeue() PQ.dequeue() PQ.enqueue(8,3) PQ.print()
446daa60cf9e5145dce7c145ec3be6053f0ade78
Visorgood/CodeBasics
/Python/BubbleSort.py
165
3.75
4
def BubbleSort(A): p = True while p: p = False for i in range(1, len(A)): if A[i - 1] > A[i]: t = A[i - 1] A[i - 1] = A[i] A[i] = t p = True
dab6bd15e17b6c29651d359e8b5d223c2e162dc6
kayodeomotoye/Code_Snippets
/timezones.py
1,154
3.5
4
import pytz from datetime import datetime, tzinfo MEETING_HOURS = range(6, 23) # meet from 6 - 22 max TIMEZONES = set(pytz.all_timezones) def within_schedule(utc, *timezones): """Receive a utc datetime and one or more timezones and check if they are all within schedule (MEETING_HOURS)""" try: tz = [pytz.timezone(_timezone) for _timezone in timezones] except: raise ValueError tz_hour = [tz.fromutc(utc).hour for tz in tz] return all(item in MEETING_HOURS for item in tz_hour) #pybites import pytz MEETING_HOURS = range(6, 23) # meet from 6 - 22 max TIMEZONES = set(pytz.all_timezones) def within_schedule(utc, *timezones): """Receive a utc datetime and one or more timezones and check if they are all within schedule (MEETING_HOURS)""" utc_aware = utc.replace(tzinfo=pytz.utc) localized_times = [] for tz in timezones: if tz not in TIMEZONES: raise ValueError('not a valid timezone') tz = pytz.timezone(tz) localized_times.append(utc_aware.astimezone(tz)) return all(dt.hour in MEETING_HOURS for dt in localized_times)
695b7faa4a5c1128c2dcf4f07f148a78ea8f46b1
heyker/LeetCodeCoding
/src/Contest/16B_1.py
514
3.625
4
#encoding=utf-8 ''' Created on 2016年12月22日 @author: heyker ''' class Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ if area<=0: return [0,0] import math inter=int(math.sqrt(area)) for i in range(inter,1,-1): if area%i==0: return [area/i,i] return [area,1] if __name__ == '__main__': s=Solution() print s.constructRectangle(1) pass
112dc0431aefe42a952cef20822febbc4220bd0f
dtung011/dtung011
/Fundamental/Session_3/mxn_ostars.py
271
3.9375
4
m = int(input("Enter number of colummns: ")) n = int(input("Enter number of rows: ")) # print ("*" * n) for i in range (n): for j in range (m): if (i+j) % 2 == 0: print ("*", end="") else: print ("o", end="") print ("\n")
2e412d24d1cff9ab36648c80f5ae6d8fd8aca43c
vatasescu-predi-andrei/lab7-Python
/lab 7 task 7.1 chal.py
375
4.21875
4
even=0 odd=0 print("Enter a series of integers, when you are done entering, enter '0'") userInput=int(input("Please enter a series of integers:")) while userInput!=0: if userInput%2==0: even=even+1 else: odd=odd+1 userInput=int(input("Please enter a series of integers:")) print("Even numbers:",even) print("Odd numbers:",odd)
9129c5ca239f03b2e96fa35b0718202cf2835c35
JiHyeonMon/-pre-Algorithm
/bak-class1/day5/bak10886.py
452
3.546875
4
#10886 #준희는 자기가 팀에서 귀여움을 담당하고 있다고 생각한다. 하지만 연수가 볼 때 그 의견은 뭔가 좀 잘못된 것 같았다. 그렇기에 설문조사를 하여 준희가 귀여운지 아닌지 알아보기로 했다. cnt = 0 for i in range(int(input())): if int(input()) == 1: cnt+=1 else: cnt-=1 if cnt>0: print("Junhee is cute!") else: print("Junhee is not cute!")
ee5e7d04569a6a72a3bb3d7f32c0d39d4943f02d
jainendrak/python-training
/Examples/9NetWorking,Multithreading,re/re/re3.py
417
3.71875
4
import re text = 'abbaaabbbbaaaaab' pattern='ab' occur= len(re.findall(pattern , text)) e=0 while(occur>0): match = re.search(pattern,text[e:] ) s = match.start() e = match.end() print("occurence at (%d--%d)"%(s+e,e+e)) occur-=1 """ for match in re.findall(pattern, text): print 'Found at "[%s,%s]"' %(match.start ,match.end) """
6867d43c20c5b709d219921b8ecb40bbcd351d51
soph714/6.00.1xFall2017
/Midterm/midterm_5.py
514
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 15 15:58:08 2017 @author: Ted """ def dict_invert(d): ''' code by theosopher 10/15/2017 6.00.1x MITx edX midterm d: dict Returns an inverted dictionary according to the instructions above ''' newD = {} for key in d.keys(): if d[key] in newD: newD[d[key]].append(key) newD[d[key]] = sorted(newD[d[key]]) else: newD[d[key]] = [key] return newD
9c726588d9174979efdb88e236a16af3e017198d
jamiebrynes7/advent-of-code-2017
/day_3/challenge2.py
1,952
3.828125
4
import sys import math def main(): # Get input arguments. try: target_value = int(sys.argv[1]) except IndexError: print("Usage: python challenge1.py <target_value>") exit(1) nodes = [Node(0, 0)] nodes[0].value = 1 square_size = 1 while True: coords = getListOfCoords(square_size) for coord in coords: x, y = coord node = Node(x, y) node.findAdjacentNodes(nodes) value = node.calculateNodeValue() if value > target_value: print("The answer is: " + str(value)) return print("Calculated value of node at {0},{1} to be {2}.".format(x,y,value)) nodes.append(node) square_size += 1 def getListOfCoords(square_size): coords = [] x = square_size y = -square_size + 1 # Go along right edge for i in range(y,square_size): coords.append((x,i)) y = square_size # Go along top edge for i in range(x, -square_size, -1): coords.append((i,y)) x = -square_size # Go along left edge for i in range(y, -square_size, -1): coords.append((x,i)) y = -square_size # Go along bottom edge for i in range(x, square_size + 1): coords.append((i,x)) return coords class Node : def __init__(self, x, y): self.x_coord = x self.y_coord = y self.adjacent_nodes = [] self.value = 0 def findAdjacentNodes(self, node_list): for node in node_list: if abs(node.x_coord - self.x_coord) <= 1 and abs(node.y_coord - self.y_coord) <= 1: self.adjacent_nodes.append(node) def calculateNodeValue(self): self.value = sum(node.value for node in self.adjacent_nodes) return self.value if __name__ == "__main__": main()
923e5714e5ad0c9fb3da55e4c8ff3e5a5a1ef338
paukey/python_pra
/learn_4.5.py
315
4
4
#2017年7月15日 #元组tuple()不能修改,但是可以给存储元组的变量赋值 list[]支持修改 dimensions=(200,40) for dimension in dimensions: print('原始元组'+str(dimension)) print('\n') dimensions=(100,100) for dimension in dimensions: print('重新赋值后'+str(dimension))
e30869245d2df582300dc65a40d735dc11cf80b7
nayyanmujadiya/ML-Python-Handson
/src/ml/pca_data_visualization.py
3,408
3.71875
4
''' Load Iris Dataset The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the iris dataset. ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" # loading dataset into Pandas DataFrame df = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target']) print(df.head()) ''' Standardize the Data Since PCA yields a feature subspace that maximizes the variance along the axes, it makes sense to standardize the data, especially, if it was measured on different scales. Although, all features in the Iris dataset were measured in centimeters, let us continue with the transformation of the data onto unit scale (mean=0 and variance=1), which is a requirement for the optimal performance of many machine learning algorithms. ''' features = ['sepal length', 'sepal width', 'petal length', 'petal width'] x = df.loc[:, features].values y = df.loc[:,['target']].values x = StandardScaler().fit_transform(x) print(pd.DataFrame(data = x, columns = features).head()) ''' PCA Projection to 2D The original data has 4 columns (sepal length, sepal width, petal length, and petal width). In this section, the code projects the original data which is 4 dimensional into 2 dimensions. I should note that after dimensionality reduction, there usually isn’t a particular meaning assigned to each principal component. The new components are just the two main dimensions of variation. ''' pca = PCA(n_components=2) principalComponents = pca.fit_transform(x) principalDf = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2']) principalDf.head(5) df[['target']].head() finalDf = pd.concat([principalDf, df[['target']]], axis = 1) finalDf.head(5) ''' Visualize 2D Projection This section is just plotting 2 dimensional data. Notice on the graph below that the classes seem well separated from each other. ''' fig = plt.figure(figsize = (8,8)) ax = fig.add_subplot(1,1,1) ax.set_xlabel('Principal Component 1', fontsize = 15) ax.set_ylabel('Principal Component 2', fontsize = 15) ax.set_title('2 Component PCA', fontsize = 20) targets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'] colors = ['r', 'g', 'b'] for target, color in zip(targets,colors): indicesToKeep = finalDf['target'] == target ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1'] , finalDf.loc[indicesToKeep, 'principal component 2'] , c = color , s = 50) ax.legend(targets) ax.grid() plt.show() ''' Explained Variance The explained variance tells you how much information (variance) can be attributed to each of the principal components. This is important as while you can convert 4 dimensional space to 2 dimensional space, you lose some of the variance (information) when you do this. By using the attribute explained_variance_ratio_, you can see that the first principal component contains 72.77% of the variance and the second principal component contains 23.03% of the variance. Together, the two components contain 95.80% of the information. ''' print(pca.explained_variance_ratio_)
2ef9752d84bbb0cb63ba346daef045407b502e6d
mrimj106/MriMJ
/check_path_exits.py
211
3.640625
4
#Program to check if path exists or not import os f1=os.path.exists("C:/Users/mritsing/Desktop/Python/test1/test3") if f1==True: print ("path exists") else: print ("path does not exists")
b3526d901669658727390ba18365b374a38d84b5
Mateusmsouza/Rascrapdinha
/BS1.py
1,473
4
4
html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ from bs4 import BeautifulSoup Sopinha = BeautifulSoup(html, 'html.parser') print(Sopinha.prettify()) # Mostra a variável identada print("-----------------------------------") print(Sopinha.title.name) # Mostra o conteudo de <title> print("-----------------------------------") print(Sopinha.body) # Busca e exibe a tag body e seu conteúdo print("-----------------------------------") print(Sopinha.p['class']) # Exibe a class atribuída a primeir incidência de "p" com class print("-----------------------------------") print(Sopinha.a) # Exibe a primeira incidência da tag 'a' print("-----------------------------------") print(Sopinha.find_all('a')) # Exibe todas as incidências da tag ('<a>'), separando por virgula print("-----------------------------------") print(Sopinha.find(id="link2")) # Exibe a incidência que contém exatamente 'link2' em Id, *caso seja apenas link, não retornará a incidência link2* print("-----------------------------------")
80252d9addcfa50b14ea7999bbb26b30b6afbdd5
mai20-meet/meetyl1201819
/lab6.py
1,149
3.984375
4
import turtle from turtle import Turtle from random import randint class Square(Turtle): def __init__(self, size, color): Turtle.__init__(self) self.shapesize= size turtle.shape("square") turtle.colormode(255) # turtle.color(color) ''' r = randint(0,255) g = randint(0,255) b = randint(0,255) turtle.color((r,g,b)) ''' def random_color(self): r = randint(0,255) g = randint(0,255) b = randint(0,255) self.color((r,g,b)) self.shape("square") # t1=Square(10, "blue") # t1.random_color() class Hexagon(Turtle): def __init__(self,size,color,speed): Turtle.__init__(self) self.size = size turtle.begin_poly() turtle.fillcolor(color) turtle.speed(speed) turtle.penup() turtle.backward(50) turtle.fd(50) turtle.right(50) turtle.fd(50) turtle.rt(50) turtle.fd(50) turtle.rt(50) turtle.fd(50) turtle.rt(50) turtle.fd(50) turtle.rt(50) turtle.fd(50) turtle.rt(50) turtle.fd(50) turtle.pendown() turtle.end_poly() H = turtle.get_poly() turtle.register_shape("myFavouriteHexagon", H) turtle.shape("myFavouriteHexagon") H=Hexagon(10, "pink",50) turtle.mainloop() #
b59e3d6be4d3c9a9fd56aa98468bf138e1617392
qw20140729/vip5
/day3/Day3_Assignment.py
3,210
4.25
4
# 1、打印小猫爱吃鱼,小猫要喝水 class Cat(object): def __init__(self,name): self.name = name def eat(self,food,water): print("{0}爱吃{1}, {0}要喝{2}".format(self.name,food,water)) def main_ex1(): cat = Cat("小猫") cat.eat('鱼','水') """ 2、小明爱跑步,爱吃东西。 1)小明体重75.0公斤 2)每次跑步会减肥0.5公斤 3)每次吃东西体重会增加1公斤 4)小美的体重是45.0公斤 """ class Person(object): def __init__(self,name,wg): self.name = name self.wg = wg def weight(self): print("{0}的体重是{1}公斤".format(self.name,self.wg)) class PerXM(Person): def __init__(self,name,wg): Person.__init__(self,name,wg) def interest(self): print("{0}爱跑步,爱吃东西。".format(self.name)) def eat(self): self.weight() self.wg += 1 print("每次吃东西体重会增加1公斤,体重变为:",self.wg) def run(self): self.weight() self.wg -= 0.5 print("每次跑步会减肥0.5公斤,体重变为:",self.wg) def main_ex2(): xiaoming = PerXM("小明",75.0) xiaoming.eat() xiaoming.run() # 小美的体重是45.0公斤 xiaom = Person("小美", '45.0') xiaom.weight() """ 3、摆放家具 需求: 1).房子有户型,总面积和家具名称列表 新房子没有任何的家具 2).家具有名字和占地面积,其中 床:占4平米 衣柜:占2平面 餐桌:占1.5平米 3).将以上三件家具添加到房子中 4).打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表 """ """" 分析:类--房子,方法--添加,属性--总面积、户型、床、衣柜、餐桌 """ class House(object): def __init__(self,area,houseType): self.area = area self.houseType = houseType self.bed = 4 self.closet = 2 self.diningTable = 1.5 def add(self): room = int(self.houseType[0]) hall = int(self.houseType[2]) reArea = self.area-(self.bed+self.closet)*room-self.diningTable*hall return room,hall,reArea def print_re(self): rooms,halls,re = self.add() print("房子户型{0},总面积{1},剩余面积{2},摆放{3}张床,{3}个衣柜,{4}个餐桌。".\ format(self.houseType,self.area,re,rooms,rooms,halls)) def main_ex3(): house = House(50,'3室1厅') house.print_re() """ 4.士兵开枪 需求: 1).士兵瑞恩有一把AK47 2).士兵可以开火(士兵开火扣动的是扳机) 3).枪 能够 发射子弹(把子弹发射出去) 4).枪 能够 装填子弹 --增加子弹的数量 """ """ 分析:类-士兵、枪,属性--姓名、子弹,方法开火,发射,装填 """ class Gun(object): def __init__(self,bullet): self.bullet = bullet def shoot(self): print(self.bullet.name) pass def chargeFull(self): pass class soldier(object): def __init__(self,name): self.name = name def main_ex4(): sd = soldier("瑞恩") gun = Gun(sd) gun.shoot() if __name__ == '__main__': main_ex4()
c140cae71898811776201177f3394afcce683f02
lhj0518/shingu
/11월3일 수업/yesterday.py
490
3.625
4
f=open("yesterday.txt",'r') yesterday_lyric = "" while 1: line = f.readline() if not line: break yesterday_lyric=yesterday_lyric+line.strip()+"\n" f.close() n1_of_yesterday=yesterday_lyric.upper().count("YESTERDAY") n2_of_yesterday=yesterday_lyric.count("Yesterday") n3_of_yesterday=yesterday_lyric.count("yesterday") print "Number of A Word 'YESTERDAY'",n1_of_yesterday print "Number of A Word 'Yesterday'",n2_of_yesterday print "Number of A Word 'yesterday'",n3_of_yesterday
8e84ba212d23c8a5a4f3000afbb04eef1d0b2912
jkirlans5282/Seymour
/algorithm.py
3,175
4.0625
4
#Algorithm Test #nested dictionary, {username:{resturant:rating}} users = { "tom":{"a":1,"b":1,"c":0,"d":-1,"h":1,"f":1}, "beth":{"a":1,"d":-1,"e":1}, "mike":{"b":1,"e":1,"h":1}, "emma":{"d":1,"g":0,"e":1} } def addUser(username): users[username]={} def addRestaurant(restaurant,username): while True: preference =input("[F]avorite, [L]iked, [D]isliked? ").lower() if preference == "f": preference = 1 break elif preference == "l": preference = 0 break elif preference == "d": preference = -1 break else: print("not a vaild option") temp = users[username] temp[restaurant] = preference users[username] = temp def userMatch(username): otherUsersMatchScore = {} user = users[username] # assigns users ratings to user for key in users: if key != username: # for all except username, We'll need to change this later to avoid lag once our data set gets larger. name = key # assigns the username to name temp = users[key] # assigns their ratings to temp otherUsersMatchScore[name] = 0 # sets otherUsersMatchScore for the other user initially equal to zero for key in temp: # For resturant rating pairs of the user that isnt the entered username try: otherUsersMatchScore[name] = otherUsersMatchScore[name] + (1 * temp[key] * user[key]) # scores the entered users similarity to other users by summing the overlaps in rating. Essentially. (both like it (1,1) adds one to score, one likes other dislikes subtracts one) except KeyError: print("keyerror") # hits this when the User has not also been to the resturant. Essentially does nothing. print(otherUsersMatchScore) reccommend(otherUsersMatchScore) def reccommend(otherUsersMatchScore): restaurants = {} for key in otherUsersMatchScore: name = key weight = otherUsersMatchScore[key] ratings = users[key] #looks at their ratings for key in ratings: try: restaurants[key] = restaurants[key] + weight * ratings[key] except KeyError: restaurants[key] = weight print(restaurants) def main(): while True: navigate =input("[N]ew user, [R]ate restaurant, [P]rint info, [M]atch users, [Q]uit? ").lower() if navigate == "n": username =input("Username? ").lower addUser(username) elif navigate == "r": username =input("Username? ").lower() restaurant =input("Restaurant? ").lower() addRestaurant(restaurant,username) elif navigate == "p": print(users) elif navigate == "m": username =input("Username? ").lower() userMatch(username) elif navigate == "q": break else: print("Not a valid input value") main()
b85955254f4fa2cb76da8df4638e01e2d29936c9
kevinelong/tyg
/pilot/lib/board.py
566
3.5625
4
class Board: def __init__(self, width=9, height=9): self.width = width self.height = height self.content = [] def add_item(self, item): self.content.append(item) def draw(self): for y in range(0, self.height): for x in range(0, self.width): symbol = "." for item in self.content: if item.position.x == x and item.position.y == y: symbol = item.symbol print(symbol, end=" ") print("", end="\r\n")
99dbfb4fd94a3edc96418bb54237374cdba94061
Sampreet/Competitive-Programming
/HackerRank/Domains/001 Algorithms/001 Warmup/E - Compare the Triplets [Score If Else]/compare-the-triplets.py
387
3.875
4
def compare_the_triplets(arr_a, arr_b): n = len(arr_a) a = sum([1 for i in range(n) if arr_a[i] > arr_b[i]]) b = sum([1 for i in range(n) if arr_a[i] < arr_b[i]]) print(str(a) + ' ' + str(b)) if __name__ == '__main__': arr_a = list(map(int, input().rstrip().split())) arr_b = list(map(int, input().rstrip().split())) compare_the_triplets(arr_a, arr_b)
7a68d5f286c1b7608380418528fa93e8f557d08f
aparnapr121/python_practice
/mro.py
390
3.546875
4
class A(): def __init__(self): print("inside A") super().__init__() class B(A): def __init__(self): print("inside B") super().__init__() class C(): def __init__(self): print("inside C") #super().__init__() class D(B,C): def __init__(self): print("inside D") super().__init__() obj = D() print(D.__mro__)
6daee9e1c22c4113fffb60dbe92b1f7b736a379d
marinaoliveira96/python-exercises
/curso_em_video/0069.py
615
3.78125
4
maiores = masc = fem20 = 0 while True: idade = int(input('Qual a sua idade? ')) if idade > 18: maiores += 1 sexo = input("Qual é o seu sexo? [F/M] ").strip().lower()[0] if sexo == 'm': masc += 1 elif sexo == 'f': if idade < 20: fem20 += 1 c = ' ' while c not in 'sn': c = input('Deseja continuar? [S/N]').strip().lower()[0] if c == 'n': break print(f'''Programa encerrado total de pessoas com mais de 18 anos igual a {maiores} total de homens cadastrados igual a {masc} Total de mulheres com menos de 20 anos igual a {fem20}''')
48733fd50e000ea4b216ff6debcdf231747e5a0d
AnaBVA/pythonCCG_2021
/scripts/ejemplos/read_fasta.py
314
3.515625
4
my_file = open("data/4_dna_sequences.txt", "r") my_file_contents = my_file.read() print(my_file_contents) print(len(my_file_contents)) # Abir archivo file = open("data/4_dna_sequences.txt", "r") # Leer las lineas for line in file: print("Length: " + str(len(line)) + " " + line) # Cerrar archivo file.close()
9c82bfb41fe94c2992c435746e516b2647d6ed07
chenzhiyuan0713/Leetcode
/Easy/Q48.py
483
4.03125
4
""" 709. 转换成小写字母 实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。 示例 1: 输入: "Hello" 输出: "hello" 示例 2: 输入: "here" 输出: "here" 示例 3: 输入: "LOVELY" 输出: "lovely" """ class Solution: def toLowerCase(self, str: str) -> str: return str.lower() answer = Solution() print(answer.toLowerCase("LOVELY"))
3ccf0b4d342313ba0714bc6378c5c24ff71b27fe
marceloamaro/Python-Mombaca
/Lista Aula07 - Dicionários e Sets/02.py
1,107
4.25
4
"""Escreva uma função que faça a verificação de existência de uma chave dentro de um dicionário. Caso a chave exista a função deve retornar o valor da chave, caso ela não exista, a função deve adicioná-la e retornar o dicionário.""" """ def verificacao(d, chave): if chave in d: print(" Chave existe o valor é =", d[chave]) else: print("nao presente") #d[chave] = d.get(chave) d[chave] = chave print(d) d = {'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6} chave = input("digite o a chave para verificação:") verificacao(d, chave) """ dados_pessoais={'nome':"Marcelo", "idade": 27, "cidade":'Mombaça', "estado_civil":'casado' } chave=(input("Qual chave voce quer procurar\n")) def verifica_chave(dados_pessoais, chave): if chave in dados_pessoais: print(dados_pessoais[chave]) else: print("Chave não econtrada") dados_pessoais[chave]=" " print(dados_pessoais) verifica_chave(dados_pessoais,chave)
82468988688a878e148712b1744ef607e1bfbff6
AbhiniveshP/Competitive-Coding-4
/PalindromeLL.py
1,913
3.90625
4
''' Solution 1. Find the mid of the LL using slow and fast pointers. 2. Reverse the second part of the LL. 3. Check each value in each half of the LL in parallel and return False if not equal, else return True Time Complexity: O(n) and Space Complexity: O(1) --- Passed all testcases on Leetcode successfully ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def __reverse(self, head): ''' :param head: head of the Linked list :return: reversed Linked List ''' prevNode = None currNode = head nextNode = head.next while (nextNode != None): currNode.next = prevNode prevNode = currNode currNode = nextNode nextNode = nextNode.next currNode.next = prevNode return currNode def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ # edge case check if (head == None or head.next == None): return True # initialize slow and fast pointers to find mid of the Linked List slowNode = head fastNode = head.next # find the mid node iteratively while (fastNode != None and fastNode.next != None): slowNode = slowNode.next fastNode = fastNode.next.next # reverse second half and initialize slow pointer to head again fastNode = self.__reverse(slowNode.next) slowNode.next = None slowNode = head # check each value in each half of the LL in parallel while (slowNode != None and fastNode != None): if (slowNode.val != fastNode.val): return False slowNode = slowNode.next fastNode = fastNode.next return True
6dd515adb8689fb2079893bad3a0347cecd9daf4
NearJiang/Python-route
/stopwatch/test seven.py
485
3.53125
4
import time as q class stopwatch: def start(self): self.begin=q.localtime() print('开始') def stop(self): self.end=q.localtime() self._calc() print('结束') def _calc(self): self.lasted=[] self.prompt='共运行了' for index in range(6): self.lasted.append(self.end[index]-self.begin[index]) self.prompt += str(self.lasted[index]) print(self.prompt)
3ae3f69f13deff622499a9d28025cd8f50798106
Tanakornguy/Tanakorn_Khuntamanee-CS01
/CS01-Grading.py
976
3.5625
4
a = int ( input ( ' กรอกคะแนนเก็บ! *คะแนนเก็บไม่เกิน 30 คะแนน : ' ) ) b = int ( input ( ' กรอกคะแนนสอบกลางภาค! *คะแนนสอบกลางภาคไม่เกิน 30 คะแนน : ' ) ) c = int ( input ( ' กรอกคะแนนสอบปลายภาค! *คะแนนสอบปลายภาคไม่เกิน 40 คะแนน : ' ) ) d = a + b + c if ( d >= 80 ) : print ( ' ได้เกรด A ' ) elif ( d >= 75 ) : print ( ' ได้เกรด B+ ' ) elif ( d >= 70 ) : print ( ' ได้เกรด B ' ) elif ( d >= 65 ) : print ( ' ได้เกรด C+ ' ) elif ( d >= 60 ) : print ( ' ได้เกรด C ' ) elif ( d >= 55 ) : print ( ' ได้เกรด D+ ') elif ( d >= 50 ) : print ( ' ได้เกรด D ') else : print ( ' ได้เกรด C ' )
a592acca804a50637567eb968d3b9118de7dc4f2
freylis/pyritms
/sort_utils/selection_sort.py
1,158
3.953125
4
""" Сортировка выбором Бежим по массиву из N элементов N раз, запоминая позицию I Бежим по массиву от позиции I до конца, запоминая минимальный встреченный элемент и его позицию K Меняем местами элементы в позиции I и K n^2 """ from sort_utils import base def sort(items): for index in range(len(items)): min_element = None subindex = 0 index_for_replace = None for subindex, tmp_val in enumerate(items[index:]): if min_element is None: min_element = tmp_val index_for_replace = subindex continue if tmp_val < min_element: min_element = tmp_val index_for_replace = subindex continue if index_for_replace and index != subindex: items[index], items[index_for_replace + index] = items[index_for_replace + index], items[index] return items if __name__ == '__main__': base.sorting_checker(sort)
2fa31b41928f3ff212ae8e1c24ca63580ebb0880
vsuriya93/Coding-Practice
/Hackerrank/Project Euler/1_multiplesOf3and5.py
306
3.578125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n=raw_input() n=int(n) for i in range(0,n): m=raw_input() m=int(m) output=0 k=3 a=(m-1)//3 b=(m-1)//5 common=(m-1)/15 output=(3*(a*(a+1))//2)+(5*(b*(b+1))//2)- (15*(common*(common+1))//2) print output
5711fb107c6b0136c85a27c6769767055d6e75c4
overbe/alien_invasion
/data.py
440
3.53125
4
import json class Storage: """A class to manage the data.""" def __init__(self): self.file = 'db/data.json' def get_score(self): try: with open(self.file) as f: score = json.load(f) except FileNotFoundError: return 0 else: return score def set_score(self, score): with open(self.file, 'w') as f: json.dump(score, f)
156638b071e4ae0e12e59da75da6c0733e85722d
nikita1610/100PythonProblems
/Problem89/Day89.py
202
3.703125
4
def check_binary_palindrome(n): l=[] while(n>0): l.append(n%2) n=n//2 b1="".join(map(str,l)) b2=b1[::-1] return b1==b2 n=9 ans=check_binary_palindrome(n) print(ans)
fc6b82ceef8a25ef923b62d18e46cb0b03e64166
Aasthaengg/IBMdataset
/Python_codes/p02401/s270151385.py
307
3.921875
4
#coding:utf-8 def cal(a, b, op): if op=="+": return a + b elif op == "-": return a - b elif op == "*": return a * b elif op == "/": return a//b else: return -1 while True: buff = input().split() a = int(buff[0]) b = int(buff[2]) op = buff[1] if op == "?": break print(cal(a, b, op))
d35f55c3d17304bd24f14052553d79f524e7bf0e
vinsonlee/projecteuler
/14.py
534
3.65625
4
N = 1000000 # Cache of Collatz results. C = {} C[1] = 1 def collatz(x): """ Calculate the number of terms for the sequence starting with x. """ if x in C: return C[x] elif x % 2 == 0: answer = 1 + collatz(x / 2) else: answer = 1 + collatz(3 * x + 1) C[x] = answer return answer longest_chain = 1 starting_number = 1 for i in range(2, N): chain = collatz(i) if chain > longest_chain: longest_chain = chain starting_number = i print starting_number
d9ffde7cd3e857be7afde55d4e654c51a3d31acf
maurya-subhashini1/List
/maigic_sqour.py
714
3.59375
4
maigic_square = [ [8, 3, 4], [1, 5, 9], [6, 7, 2] ] i=0 sum=0 while i<len(maigic_square): col=0 while col<len(maigic_square): sum=sum+maigic_square[i][col] col=col+1 j=0 s=0 while j<len(maigic_square): col=0 while col<len(maigic_square): s=s+maigic_square[i][col] col=col+1 j=j+1 k=0 a=0 while k<len(maigic_square): dig=0 while dig<len(maigic_square): a=a+maigic_square[i][dig] dig=dig+1 k=k+1 i=i+1 print(sum) print(s) print(a) if sum==s==a: print("its maigic_square") else: print("its not maigic_square")
69b7dec5566d40b2d62945c2c3477042d22de49f
ThomasHartmannDev/CursoPython
/Programas/01 - Fundamentos/01 - Tipos basicos/exemplo.py
656
4.09375
4
# Verdadeiro, Falso, nulo print(True) print(False) print(None) # Tipos numericos print(1 + 2) #Valor inteiro print(1.2 + 1) # Valor Float #Tipos de escrita. print('Texto dentro de aspas simples') print("Texto dentro de aspas duplas") print("você é " + 3 * 'muito ' + 'legal') #print(3 + '3') --> neste caso gera ambiguidade, ou você soma 3 + 3 ou você concatena para virar 33 #Lista print([1,2,3]) # Lista possui apenas valores dentro dela. #outro exemplo lista = [1,2,3] print(lista) #Dict ou Dicionario print({'nome': 'Thomas','Idade': 17}) # Outro exemplo: dicionario = { 'Nome':'Thomas', 'Idade': 17, } print(dicionario)
f9caf4f6b4655269d10315338cdc7fb86313c5b9
riturajkush/Geeks-for-geeks-DSA-in-python
/Recursion/Power Of Numbers.py
725
4
4
#User function Template for python3 #Complete this function def power(x,y): #mod = 10**9+7 if(y == 0): return 1 temp = power(x, int(y / 2)) if (y % 2 == 0): return ((temp%1000000007) * (temp%1000000007))%1000000007 else: if(y > 0): return ((x%1000000007) * (temp%1000000007) * (temp%1000000007))%1000000007 #{ # Driver Code Starts #Initial Template for Python 3 import math def main(): T=int(input()) while(T>0): N=input() R=N[::-1] ans=power(int(N),int(R)) print(ans) T-=1 if __name__=="__main__": main() # } Driver Code Ends
738110b1165d168eaba9da1fb10da23ad870e30f
Upasana360/All-My-Python-Programs
/adv_min_max.py
732
3.875
4
# def func(item): # return len(item) # name=['maggie','souravu','sujata','abc','xc'] # print(max(name,key=func)) # #this can also be done by lambda func # name1=['maggie','souravu','sujata','abc','xc','harshit vasihistha'] # print(max(name1,key=lambda item:len(item))) # student=[{'names':'upasana','score':90,'age':34}, # {'name':'upasana','score':60,'age':23}, # {'name':'harshit','score':45,'age':32}] # print(min(student,key=lambda d:d['score'])) # print(min(student,key=lambda item:item.get('age'))['name']) # print(max(student,key=lambda d:d['score'])) student1={ 'harshit':{'score':20,'age':54}, 'maggie':{'score':80,'age':48}, 'suji':{'score':50,'age':33} } print(max(student1,key=lambda item:student1[item]['score']))
bac8cdc603195c5b17e6bf46fcd9811ed373507f
HadilOwda/Project2
/cfp/final2 (copy).py
4,236
3.8125
4
#final project : space invaders by Hadil and Deema #0-import the libraries which we need import turtle import os import random #1-set up the screen wn = turtle.Screen() wn.title('Space Invaders') wn.setup(width=700 ,height=700) wn.bgpic('space_invaders_background.gif') wn.tracer(0) #Register the shapes turtle.register_shape('player.gif') turtle.register_shape('invader.gif') #a pen to write Game Over and YOU WON! pen = turtle.Turtle() pen.penup() pen.color('white') pen.hideturtle() pen.goto(0,0) #Draw the border border = turtle.Turtle() border.speed(0) border.color('white') border.penup() border.goto(-300,-300) border.pensize(3) border.pendown() for side in range(4): border.forward(600) border.left(90) border.hideturtle() #Set the score score = 0 #draw the score on the screen score_pen = turtle.Turtle() score_pen.hideturtle() score_pen.speed(0) score_pen.color('white') score_pen.penup() score_pen.goto(-290,270) score_string = 'score:'+ str(score) score_pen.write(score_string ,False , align = 'left',font=("Arial", 16, "normal")) #2-creat the player turtle player = turtle.Turtle() player.shape('player.gif') player.penup() player.speed(0) player.setheading(90) player.goto(0,-250) #choose number of enemies number_of_enemies = 30 #creat an empty list for the enemies enemies = [] #add enemies to the list for i in range(number_of_enemies): enemies.append(turtle.Turtle()) enemy_start_x = -225 enemy_start_y = 250 enemy_number = 0 for enemy in enemies: #4-creat the enemy enemy.shape('invader.gif') enemy.penup() enemy.speed(0) x = enemy_start_x + (50 * enemy_number) y = enemy_start_y enemy.goto(x,y) enemy_number+=1 if enemy_number == 10: enemy_start_y-= 40 enemy_number = 0 enemyspeed = 0.06 #5- creat the palyers bullet turtle bullet = turtle.Turtle() bullet.color('yellow') bullet.shape('triangle') bullet.penup() bullet.speed(0) bullet.setheading(90) bullet.shapesize(0.5,0.5) bullet.goto(0,-500) bullet.hideturtle() bulletspeed = 5 #define the bullet state (ready or fire) #ready-ready to fire #fire_bullet is firing bulletstate = 'ready' #3-mover the player turtle #make a virable to change the position of the player playersteps = 10 #functions to the key event listeners #the player movment def move_right(): x = player.xcor() x += playersteps if x > 280: x = 280 #we chose 280 cuz it's before the border by 20 pixels player.setx(x) def move_left(): x = player.xcor() x -= playersteps if x <-280: x = -280 #we chose 280 cuz it's before the border by 20 pixels player.setx(x) #fire the bullet def fire_bullet(): global bulletstate if bulletstate == 'ready': bulletstate = 'fire' #move the bullet above the player x = player.xcor() y = player.ycor() + 10 bullet.goto(x,y) bullet.showturtle() #check is the bullet is tuouching the enemy def isCollsion(t1,t2): distance = t1.distance(t2) if distance<20: return True else: return False def check(): for c in enemies: if c.ycor() <= -270: pen.color('red') pen.write('GAME OVER!!',False , align = 'left',font=("Arial", 19, "normal")) return True #call our player functions wn.listen() wn.onkey(move_right,'Right') wn.onkey(move_left,'Left') wn.onkey(fire_bullet,'space') #Main game loop while True: wn.update() for enemy in enemies: x = enemy.xcor()+enemyspeed enemy.setx(x) if enemy.xcor()>280: for e in enemies: y = e.ycor() y -= 20 e.sety(y) enemyspeed *= -1 if enemy.xcor()< -270: for e in enemies: y = e.ycor() y -= 20 e.sety(y) enemyspeed *= -1 if isCollsion(bullet,enemy): #reset the bullet bullet.hideturtle() bulletstate = 'ready' bullet.goto(0,-400) enemy.goto(0,10000) score += 10 score_pen.clear() score_string = 'score:' + str(score) score_pen.write(score_string ,False , align = 'left',font=("Arial", 19 , "normal")) #update score #fire the bullet if bulletstate == 'fire': y = bullet.ycor()+bulletspeed bullet.sety(y) #check if the bullet have gone to the top if bullet.ycor() > 275: bullet.hideturtle() bulletstate = 'ready' if score == 300: pen.color('green') pen.write('YOU WON!',False , align = 'left',font=("Arial", 19, "normal")) if check(): break turtle.mainloop()
fc4ce06356d48bfc7c463236583e9eb87a9bcfef
fingerroll/wip
/sort-transformed-array/s1.py
331
3.5625
4
# return sort results # x^2 should be x*x or x**2 class Solution(object): def sortTransformedArray(self, nums, a, b, c): """ :type nums: List[int] :type a: int :type b: int :type c: int :rtype: List[int] """ return sorted(map(lambda x: a* (x*x) + b*x + c, nums))
6d29c26567939e69b424fa33696eed98e34fcf39
ostrandr6399/CTI-110-1001
/M4HW2_Pennies_Ostrander.py
342
4.03125
4
#Calculate amount a person earns if salary is one penny a day #6/19/17 #CTI-110-M4HW4_7 #R.Ostrander NofDays = int(input('How many days do you want to calculate for?' )) for day in range (NofDays): print ('day', day + 1) pennies = 2**day print ("This would be your Salary if you earned a penny a day", pennies/100)
a9769296aa7bbd95c1b2a4b960d9f3be7b093eef
DarkAlexWang/leetcode
/laioffer/insert_node_sorted_list.py
463
3.921875
4
class Solution: def insert(self, head, value): node = ListNode() if head is None: node.val = value node.next = head head = node elif head.val >= value: node.next = head head = node else: cur = head while cur.next is not None and cur.next.val < value: cur = cur.next node.next = cur.next cur.next = node
2b7bafe48f08178a276526d412aad9b746b59dbc
MaksTresh/python-hw-course
/hw18/main.py
960
3.765625
4
import argparse from PIL import Image def resize_image(input_image: str, output_image: str, scale: float): image = Image.open(input_image) width, height = image.size size = int(width * scale), int(height * scale) resized_image = image.resize(size) resized_image.save(output_image) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Script for resizing an image with a given scale.') parser.add_argument('-i', '--input-image', dest='input_image', help='Input image', default='input.jpg') parser.add_argument('-o', '--output-image', dest='output_image', help='Output image', default='output.jpg') parser.add_argument('-s', '--scale', dest='scale', help='The scale of output image', default=0.5, type=float) args = parser.parse_args() if args.scale <= 0: print('The scale must be greater than zero') exit(2) resize_image(args.input_image, args.output_image, args.scale)
f5ba6e745291b470a4178ef6666a73b0e5577b1a
ZehuaWang/python_ladder
/python_ladder/python_ladder/BST/BinaryTree.py
5,551
3.9375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 6 17:25:05 2020 @author: ewang """ class Stack(object): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() def is_empty(self): return len(self.items) == 0 def peek(self): if not self.is_empty(): return self.items[-1] def size(self): return len(self.items) def __len__(self): return self.size() class Queue(object): def __init__(self): self.items = [] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): if not self.is_empty(): return self.items.pop() def is_empty(self): return len(self.items) == 0 def peek(self): if not self.is_empty(): return self.items[-1].value def __len__(self): return self.size() def size(self): return len(self.items) class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self,root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(tree.root, "") elif traversal_type == "inorder": return self.inorder_print(tree.root, "") elif traversal_type == "postorder": return self.postorder_print(tree.root, "") else: print("Traversal type " + str(traversal_type) + "is not supported.") # depth first search # pre-order in-order post-order def preorder_print(self, start, traversal): """" root -> left -> right""" if start: traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self, start, traversal): """left -> root -> right""" if start: traversal = self.inorder_print(start.left, traversal) traversal += (str(start.value) + "-") traversal = self.inorder_print(start.right, traversal) return traversal def postorder_print(self, start, traversal): """"left -> right -> root""" if start: traversal = self.postorder_print(start.left, traversal) traversal = self.postorder_print(start.right, traversal) traversal += (str(start.value) + "-") return traversal def reverse_levelorder_print(self, start): if start is None: return queue = Queue() stack = Stack() queue.enqueue(start) traversal = "" while len(queue) > 0: node = queue.dequeue() stack.push(node) if node.right: queue.enqueue(node.right) if node.left: queue.enqueue(node.left) while len(stack) > 0: node = stack.pop() traversal += str(node.value) + "-" return traversal # breadth-first search def levelorder_print(self,start): if start: visit_queue = [] visit_queue.append([start]) res = [] res.append([start.value]) # for child in visit_queue: # level_res = [] # if child.left: # visit_queue.append(child.left) # level_res.append(child.left.value) # if child.right: # visit_queue.append(child.right) # level_res.append(child.right.value) # if len(level_res) != 0: # res.append(level_res) # visit_queue.pop() while visit_queue: children = visit_queue.pop() level_res = [] level_visit_queue = [] for child in children: if child.left: level_visit_queue.append(child.left) level_res.append(child.left.value) if child.right: level_visit_queue.append(child.right) level_res.append(child.right.value) if len(level_visit_queue) != 0: visit_queue.append(level_visit_queue) if len(level_res) != 0: res.append(level_res) return res # 1 # / \ # 2 3 # / \ / \ # 4 6 7 5 tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) #tree.root.left.left = Node(4) #tree.root.left.right = Node(6) tree.root.right.left = Node(7) tree.root.right.right = Node(5) print(tree.levelorder_print(tree.root)) print(tree.reverse_levelorder_print(tree.root))
cae173457f536050c15faff7d02e4a61aeb67b14
VladimirBa/python_starter_homework
/006_Functions 2/006_homework_1.py
382
3.703125
4
z = 0 print(z) def greeting(z): while z < 2: print('Hello!') z += 1 print(z) greeting(z) def out_f(): x = 1 def inn_f(): global x print(x) x = 2 print(x) inn_f() print(x) def in_inn_f(): nonlocal x x = 3 print(x) in_inn_f() print(x) x = 10 print(x) out_f() print(x)
8085318e2af09eee96dfb9ff6cfe42a58c03ae0c
YusefQuinlan/PythonTutorial
/Intermediate/2.2 Tkinter/2.2.12_Tkinter_Lambda_Command.py
3,209
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 18:10:54 2020 @author: Yusef Quinlan """ """ The following demonstrates that using the button without passing an argument to the function xreturn() an error is produced. """ from tkinter import * Window =Tk() Window.title("Lambdas") Label1 = Label(Window,text="The following button returns x times 8") Label1.pack() x = 3 def xreturn(j): Label(Window, text=str(x * j)).pack() Button1 = Button(Window, text="this button returns x times 8", command=xreturn).pack() Window.mainloop() """ if we pass 8 to the xreturn command normally then the xreturn function packs a label of the value x * 8 before the button renders and the button does not function as intended, no idea why this happens in tkinter, but for whatever reason one cannot simply pass a function with an argument to the command parameter of a tkinter widget. """ from tkinter import * Window =Tk() Window.title("Lambdas") Label1 = Label(Window,text="The following button returns x times 8") Label1.pack() x = 3 def xreturn(j): Label(Window, text=str(x * j)).pack() Button1 = Button(Window, text="this button returns x times 8", command=xreturn(8)).pack() Window.mainloop() """ However by passing the command as a lambda and passing a value into a variable and using the function with that variable as an argument, we can use the function with a parameter without any weird errors or unintended functionality. """ from tkinter import * Window =Tk() Window.title("Lambdas") Label1 = Label(Window,text="The following button returns x times 8") Label1.pack() x = 3 def xreturn(j): Label(Window, text=str(x * j)).pack() Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack() Window.mainloop() """ The following demonstrates that we can pass several argument values to xreturn(j) to several buttons, and they all work as intended thanks to lambda. """ from tkinter import * Window =Tk() Window.title("Lambdas") Label1 = Label(Window,text="The following button returns x times 8") Label1.pack() x = 3 def xreturn(j): Label(Window, text=str(x * j)).pack() Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack() Button2 = Button(Window, text="this button returns x times 5", command= lambda j=5: xreturn(j)).pack() Button3 = Button(Window, text="this button returns x times 2", command= lambda j=2: xreturn(j)).pack() Window.mainloop() # Showing that lambda can be used for more than one function such as xset. from tkinter import * Window =Tk() Window.title("Lambdas") Label1 = Label(Window,text="The following button returns x times 8") Label1.pack() x = 3 def xreturn(j): Label(Window, text=str(x * j)).pack() def xset(i): global x x = i Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack() Button2 = Button(Window, text="this button returns x times 5", command= lambda j=5: xreturn(j)).pack() Button3 = Button(Window, text="this button returns x times 2", command= lambda j=2: xreturn(j)).pack() Button4 = Button(Window, text="this button sets x to 2", command= lambda setval=2: xset(setval)).pack() Window.mainloop()
87fb68d880f6c4c05161b8a531de14274a971661
rodhoda2020/PyCharm-Library
/REST APIs with Flask and Python/1. Full Python Refresher/32_custom_error_classes.py
1,315
3.921875
4
class TooManyPagesReadError(ValueError): # Inside the parameter is the parent class that we can inherit from pass class Book: def __init__(self, name: str, page_count: int): self.name = name self.page_count = page_count self.pages_read = 0 def __repr__(self): return ( f'<Book {self.name}, read {self.pages_read} pages out of {self.page_count}' ) def read(self, pages: int): if self.pages_read + pages > self.page_count: raise TooManyPagesReadError( f'You tried to read {self.pages_read + pages} pages, but this book only has ' f'{self.page_count} pages.' ) self.pages_read += pages print(f'You have now read {self.pages_read} pages out of {self.page_count}.') python101 = Book('Python 101', 50) try: python101.read(35) python101.read(50) except TooManyPagesReadError as e: print(e) #This will print the error message without showing the traceback # The error we face is that the book contains 50 pages, but if we send two parameters # that, together, would add up to 85, this would still be accepted by the program # The issue with this is that it does not leave a simple message for the user # Instead, you can use the try and except method
90ddb7c77c93c5d35d5f53c39128d4eb30630f17
Wesleysou/Exer-CRS-
/Programas/Aula-10/Aula 07 04/exer 2.py
481
3.828125
4
nomes=[] nota=[] resp='S' while(resp=='s'or resp=='S'): n=input('Digite o nome dos alunos') parcial=float(input('Digite a nota da parcial')) nome.append(n) nota.append(parcial) resp=(input('Digite s para continuar')) acum=0 for i in range(len(nota)): acum=acum+nota[i] media=acum/len(nota) print(media) for i in range(len(nota)): if(nota[i]>=media): print('O aluno',nomes[i],'está acima da média') print('nota',nota[i])
8a11ee715aa143a95b245dcc0bce050a24fdaa05
ace231/CS299_Labs
/lyP3.py
1,373
3.671875
4
# Alfredo Ceballos # CS 299 # Project 3 # Problem 1 # # Farenheit to Celsius formula : Tc = (Tf - 32) / 1.8 def faren_to_cels(f): return (f - 32) / 1.8 f_temp = -459.67 # Just start off at absolute zero while f_temp <= 200: if f_temp == -459.67: print("%7.2fF %7.2fC absolute zero" % (f_temp, faren_to_cels(f_temp))) f_temp = -60.0 elif f_temp == 30: # We're incrementing by 10 but set to 32 # or else it'll skip and keep going up print("%7.2fF %7.2fC" % (f_temp, faren_to_cels(f_temp))) f_temp = 32 print("%7.2fF %7.2fC freezing//melting point of water" \ % (f_temp, faren_to_cels(f_temp))) f_temp -= 2 # Set back to 30 elif f_temp == 70: print("%7.2fF %7.2fC room temperature" % (f_temp, faren_to_cels(f_temp))) elif f_temp == 90: print("%7.2fF %7.2fC" % (f_temp, faren_to_cels(f_temp))) f_temp = 98.6 print("%7.2fF %7.2fC body temperature" % (f_temp, faren_to_cels(f_temp))) f_temp -= 8.6 elif f_temp == 200: print("%7.2fF %7.2fC" % (f_temp, faren_to_cels(f_temp))) f_temp = 212 print("%7.2fF %7.2fC boiling temperature of water" \ % (f_temp, faren_to_cels(f_temp))) else: print("%7.2fF %7.2fC" % (f_temp, faren_to_cels(f_temp))) f_temp += 10
f573943c8878046121855d538f199cab790b0b35
Parfen1984/pythonproject-Public
/Zadanie2.py
202
3.875
4
for i in range(1, 101, 1): print (i) if i % 3 == 0: print(f" {i} Good") elif i % 5 == 0: print(f" {i} BETTER ") if i % 3 ==0 and i % 5 == 0: print(f" {i} Best ")
f188eccae4970a4a38aa79d9f316cb0979f153fa
HagenGaryP/lpthw
/ex12.py
802
4.5
4
# Exercise 12: Prompting People # When you typed input() you were typing the "(" and ")" characters, # which are parenthesis characters. This is similar to when you # used them to do a format with extra variables, as in f"{x} {y}". # For input you can also put in a prompt to show the user, so they # know what to type. # Put a string that you want for the prompt inside the () # i.e., y = input("Name? ") # This prompts the user with "Name?" and puts the reslut into the # variable 'y'. # We can rewrite ex11 by using input for all the prompting. age = input("How old are you, in years? ") height = input("How tall are you, in inches? ") weight = input("How much do you weigh, in pounds? ") print(f"So, you're {age} years old, {height} inches tall, and weigh {weight}lbs.")
f5e20133d54f0411ce970c0e99abfd68bd1dfcc7
uannabi/DesignPatterns
/CreationalPatterns/abstractFactory.py
1,136
4.3125
4
class Owl: """one of the objects to be returned""" def speak(self): return "whooom!" def __str__(self): return "Owl" class OwlFactory: """concrete factory""" def get_pet(self): """return a owl object""" return Owl() def get_food(self): """return a owl food object""" return "Owl Food!" class PetStore: """petstore houses our Abstract factory""" def __init__(self, pet_factory=None): """pet_factory is our abstract factory""" self._pet_factory = pet_factory def show_pet(self): """utility method to display the details of the objects return by the PetFactory""" pet = self._pet_factory.get_pet() pet_food = self._pet_factory.get_food() print("Our pet is '{}!".format(pet)) print("Our pet says hello by '{}!".format(pet.speak())) print("Its food is '{}!".format(pet_food)) # Create a Concrete Factory factory = OwlFactory() # Create a pet store housing our Abstract Factory shop = PetStore(factory) # Invoke the utility method to show the details of our pet shop.show_pet()
d756f9ef654ec60400b8538b19b97439a38d4eb7
niklashauschel/minesweeper
/src/logic.py
10,442
3.6875
4
# !/usr/bin/python """ @ author : Till Fetzer @ e-mail : till.fetzer@googlemail.com @ date : 23.05.2019 """ import random # stantard liberies import numpy as np from logging import * filename = 'logic' class Board(): """ creating and working an the board """ def __init__(self, colums, rows, bombs, board): # sometimes only board is use an rest the other """ in: rows and colums and bombs all numbers or an board for testing cases do: create a list with bombs and not bombs fileds and shuffle them randomly then formate this list to an 2d array or only the board for testing cases as board out: the 2d array with random bombs or the tsting case board TODO: add Properties set for rows, colums, bombs, board """ self.logNameClass = 'Board' logNameMethod = '__init__' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) self.rows = rows self.colums = colums self.bombs = bombs if board is None: notBombs = self.rows * self.colums - bombs if (notBombs > 0): self.board = [10]*self.bombs + notBombs*[0] # 10 is standing for bombs random.shuffle(self.board) self.board = np.array(self.board, dtype=int).reshape(rows, colums) log.debug("Board is created sucessful") else: log.error("There are to many bombs") else: self.board = board log.debug("Board is set from outside") def getBoard(self): """ getter for board TODO: addProperties get for board """ logNameMethod = 'getBoard' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) log.debug('getBoard call and Board looks like: \n {}'.format(self.board)) return self.board def getValueFromBoard(self, colum, row): """ getter for special value on index """ logNameMethod = 'getValueFromBoard' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) try: log.debug('value of return is {}'.format(self.board[row][colum])) return(self.board[row][colum]) except IndexError: log.error('IndexError') def getClickedFieldsAmount(self): """ in: - do: marked the clicked fileds out: amound of clicked fileds """ logNameMethod = 'getClieckedFieldsAmound' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) result = np.where(self.board == 11) listOfCoordinates = list(zip(result[1], result[0])) log.debug('value of return is {}'.format(len(listOfCoordinates))) return len(listOfCoordinates) def createWarnFields(self): """ in: - do: write on the filed with no bombs how much bombs are int the near out: the filed with everyfiled the number of bombs in the near """ logNameMethod = 'createWarnFields' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) result = np.where(self.board == 10) listOfCoordinates = list(zip(result[1], result[0])) for cord in listOfCoordinates: rowsOfBomb = cord[1] columsOfBomb = cord[0] for(rowsNeighbor, columsNeighbor) in self.getNeighbours(columsOfBomb, rowsOfBomb): if(rowsNeighbor >= 0 and rowsNeighbor < self.rows and columsNeighbor >= 0 and columsNeighbor < self.colums): self.board[rowsNeighbor][columsNeighbor] += 1 log.debug('Board after creating Warnfileds looks like: \n {}'.format(self.board)) def setValueFromBoard(self, colum, row): """ in: position of clicked field do: set the filed clicked (value=11) out: - """ logNameMethod = 'setValueFromBoard' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) self.board[row][colum] = 11 log.debug('value is setted as 11 that mean clicked') def getNeighbours(self, colum, row): ''' Free from minesweeper.py why a extra method? Because you need the Neighbours for a field in morec then one Mthod in: the colum and row from one field do: calculate the neighbars out: the neighbarsfrom one field ''' NEIGHBOURS = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) return ((row + neighborRow, colum + neighborColum) for (neighborRow, neighborColum) in NEIGHBOURS) def getAllOtherOpenFields(self, colum, row, _openfields): ''' in: an field with no bombs in the neighborhood and openfields list which is a list off allready calculatec that they have to be open in before rekursiv method call has to be null to beginning do: search all fields around which have no bombs around and also the first field which have bombs around out: all fields which should open in minesweeper, if you press a button on the filed ''' logNameMethod = 'getAllOtherOpenFields' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) log.debug('rekursiv call witth colum:{} row:{}'.format(colum, row)) openfields = _openfields if not openfields: openfields.append((colum, row)) for(rowsNeighbor, columsNeighbor) in self.getNeighbours(colum, row): if(rowsNeighbor >= 0 and rowsNeighbor < self.rows and columsNeighbor >= 0 and columsNeighbor < self.colums and not((columsNeighbor, rowsNeighbor) in openfields)): openfields.append((columsNeighbor, rowsNeighbor)) if(self.board[rowsNeighbor][columsNeighbor] == 0): self.getAllOtherOpenFields(columsNeighbor, rowsNeighbor, openfields) elif(rowsNeighbor == row + 1 and columsNeighbor == colum + 1 and self.board[rowsNeighbor][columsNeighbor]): return openfields elif (rowsNeighbor == row + 1 and columsNeighbor == colum + 1): return openfields def checkAllNeighboursWhereBombs(self): """ One off the methods there are only needed for checking if it is logical solvable in: the board after the method create warnfields do: Check if a bomb has only bombs as neighbour if not but all bombs at the value off 10 out: True or False """ logNameMethod = 'checkAllNeighboursWhereBombs' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) self.createWarnFields() test = np.where(self.board == 18) if(len(test[0]) != 0 and len(test[1]) != 0): log.debug('All Neighbours are bombs') return True else: morethan10 = np.where(self.board > 10) listOfCoordinates = list(zip(morethan10[0], morethan10[1])) for cord in listOfCoordinates: rowsof10 = cord[0] columsof10 = cord[1] self.board[rowsof10][columsof10] = 10 log.debug('not all Neighbours are bombs') return False def isBoardSolvable(self): """ One off the methods there are only needed for checking if it is logical solvable without it you can easily replace isBoardSolvable with createwarnfield in ooGUI.py and attach on this method and self.board[rowsneighbor][columsneighbor] != 10 in the ifclouse in: the board after init and the output of checkAllNeighboursWhereBombs and if it work mirrorAxis do: check if it is logical solvable out: create new init for not solvable or do nothing for solvable TODO: because logical solvable is not needed it is not check if it works, when it is not solvable in logical way """ logNameMethod = 'isBoardSolvable' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) result = np.where(self.board == 8) if((len(result[0]) != 0 and len(result[1]) != 0) or self.checkAllNeighboursWhereBombs()): # or self.mirrorAxis() log.debug('it is not solvable, create new board') self.__init__(self.colums, self.rows, self.bombs, None) else: log.debug('Allright it is solvable') pass def mirrorAxis(self): """ One off the methods there are only needed for checking if it is logical solvable in: the board off init do: check if there are any mirrorAxis that make the game in most off the cases unsolvable in logcial way examples off logical unsolvable fileds are in the folder notsolvable fields out: if it has mirrorAxis or not TODO: it is not tested and implement in the project, because this not part off the project needs you have it seen only as idee """ logNameMethod = 'mirrorAxis' log = getLogger(filename + '.' + self.logNameClass + '.' + logNameMethod) halfcolum = int(np.ceil(self.colums/2)) - 1 halfrow = int(np.ceil(self.rows/2)) - 1 for i in range(self.rows-1): for j in range(halfcolum): if(self.board[i][halfcolum - j - 1] == self.board[i][halfcolum + j] and i == halfcolum): return True else: i = self.rows for i in range(self.colums): for j in range(halfrow): if(self.board[halfrow - j - 1][i] == self.board[halfrow + j][i] and i == halfrow): return True else: i = self.colums log.debug('No MirrorAxis in Board') return False
4535916ed1aaca9cf5134108991d872ce3a938f4
Husayn17/Code-Lagos-Trials
/project-guessing.py
1,364
3.9375
4
import random def compare_number(numbers, user_guess): wrongright = [0,0] #wrong, then right for i in range(len(numbers)): if numbers[i] == user_guess[i]: wrongright[1]+=1 else: wrongright[0]+=1 return wrongright if __name__=='__main__': playings = True #Play the game numbers = str(random.randint(0,99)) #random 2 digit number guesses = 0 print('Lets play a Guessing Game!\nI will generate a number, and you would have to guess the numbers one digit at a time.\nFor every number in the wrong place, you get a wrong.\nFor every one in the right place, you get a right.\nThe game ends when you get 2 rights.\nType exit at any time to exit.') #Explanation while playings: user_guess = input('Give me your best guess!') if user_guess == 'exit': break wrongrightcount = compare_number(numbers, user_guess) guesses+=1 print(' You have '+ str(wrongrightcount[0]) + ' wrongs, and ' + str(wrongrightcount[1]) + ' rights.') if wrongrightcount[1]==2: playings = False print(' You win the game after ' + str(guesses) + '! The number was '+str(numbers)) break #redundant exit else: print('Your guess inst quite right, try again.')
3f3c65621a8c08e005a3efe10aeb16c43524a08a
amandathedev/Python-Fundamentals
/12_string_formatting/12_01_fstring.py
1,791
4.34375
4
''' Using f-strings, print out the name, last name, and quote of each person in the given dictionary, formatted like so: "The inspiring quote" - Lastname, Firstname ''' famous_quotes = [ {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."}, {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at " "kick boxing."}, {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy " "is about telescopes."}, {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."}, {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, " "and obeys the Second Law of Thermodynamics; i.e., it always increases."}, {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."}, {"full_name": "Alan Bennett", "quote": "Standards are always out of date. That’s what makes them standards."} ] # https://stackoverflow.com/questions/55433855/how-to-combine-list-of-dictionaries-based-on-key for x in famous_quotes: print(f"\"{x['quote']}\" - {', '.join(reversed(x['full_name'].split()))}") # quote_names = [k['full_name'] for k in famous_quotes] # quote = [i['quote'] for i in famous_quotes] # print(f"\"{quote[0]}\" - {quote_names[0]} ") # print(f"\"{quote[1]}\" - {quote_names[1]} ") # print(f"\"{quote[2]}\" - {quote_names[2]} ") # print(f"\"{quote[3]}\" - {quote_names[3]} ") # print(f"\"{quote[4]}\" - {quote_names[4]} ") # print(f"\"{quote[5]}\" - {quote_names[5]} ") # print(f"\"{quote[6]}\" - {quote_names[6]} ")
0e3629079a7462207d09e209cc7041df8e8be539
jliversi/advent_of_code
/2021/python_version/d14/solution.py
2,496
3.65625
4
# INPUT_FILE = 'input.txt' INPUT_FILE = 'test_input.txt' def parse_input(file_name): with open(file_name, 'r') as f: start, rules = f.read().split('\n\n') rules = {rule.split(' -> ')[0]: rule.split(' -> ')[1].strip() for rule in rules.split('\n')} return start.strip(), rules def part_one_step(string, rules): insertions = dict() # build insertions for i in range(len(string) - 1): substr = string[i:i+2] if substr in rules: insertions[i] = rules[substr] new_str = [] for i in range(len(string)): new_str.append(string[i]) if i in insertions: new_str.append(insertions[i]) return ''.join(new_str) def string_to_char_pairs(string): result = dict() for i in range(len(string) - 1): char_pair = string[i:i+2] result[char_pair] = result.get(char_pair, 0) + 1 return result def char_pairs_to_count_dict(char_pairs, first_char, last_char): count = dict() for char_pair, amt in char_pairs.items(): for char in char_pair: count[char] = count.get(char,0) + (amt / 2) count[first_char] += 1 count[last_char] += 1 return count def step(char_pairs, rules): result = dict() for pair in char_pairs: if pair in rules: amt = char_pairs[pair] x = pair[0] + rules[pair] y = rules[pair] + pair[1] result[x] = result.get(x, 0) + amt result[y] = result.get(y, 0) + amt else: result[pair] = char_pairs[pair] return result def part_one(start, rules): polymer_string = start for i in range(10): polymer_string = part_one_step(polymer_string, rules) char_count = {} for char in polymer_string: char_count[char] = char_count.get(char, 0) + 1 answer = max(char_count.values()) - min(char_count.values()) print(answer) def part_two(start, rules): first_char, last_char = start[0], start[-1] char_pairs = string_to_char_pairs(start) for i in range(40): print('Working on step ', i+1, '...') char_pairs = step(char_pairs, rules) # print(char_pairs) char_count = char_pairs_to_count_dict(char_pairs, first_char, last_char) # print(char_count) answer = max(char_count.values()) - min(char_count.values()) print(answer) def main(): start, rules = parse_input(INPUT_FILE) # part_one(start, rules) part_two(start, rules) if __name__ == '__main__': main()
bc576e57bcba7a8c18f437a5ffb8adfc7012d8bf
GutiEsteban/FundamentosDeProgramacionOrdenado
/ejercicio 4.py
436
3.84375
4
num1=int(input("ingrese el primer numero:")) num2=int(input("ingrese el suegundo numero:")) num3=int(input("ingrese el tercer numero:")) num4=int(input("ingrese el cuarto numero:")) sumadelos2primerosnumeros=num1+num2 productodel3y4=num3*num4 print("el resultado de los dos primeros numeros es :") print(sumadelos2primerosnumeros) print("el resultado de el producto del cuarto y el tercer numero es :") print(productodel3y4)
dfa387d4cc1e04da47f5b3a40d4024a19c9f7f74
dimtsap/UQpy
/src/UQpy/SampleMethods/MCMC/mcmc.py
21,671
3.546875
4
import numpy as np from UQpy.Distributions import Distribution class MCMC: """ Generate samples from arbitrary user-specified probability density function using Markov Chain Monte Carlo. This is the parent class for all MCMC algorithms. This parent class only provides the framework for MCMC and cannot be used directly for sampling. Sampling is done by calling the child class for the specific MCMC algorithm. **Inputs:** * **dimension** (`int`): A scalar value defining the dimension of target density function. Either `dimension` and `nchains` or `seed` must be provided. * **pdf_target** ((`list` of) callables): Target density function from which to draw random samples. Either `pdf_target` or `log_pdf_target` must be provided (the latter should be preferred for better numerical stability). If `pdf_target` is a callable, it refers to the joint pdf to sample from, it must take at least one input `x`, which are the point(s) at which to evaluate the pdf. Within MCMC the `pdf_target` is evaluated as: ``p(x) = pdf_target(x, *args_target)`` where `x` is a ndarray of shape (nsamples, dimension) and `args_target` are additional positional arguments that are provided to MCMC via its `args_target` input. If `pdf_target` is a list of callables, it refers to independent marginals to sample from. The marginal in dimension `j` is evaluated as: ``p_j(xj) = pdf_target[j](xj, *args_target[j])`` where `x` is a ndarray of shape (nsamples, dimension) * **log_pdf_target** ((`list` of) callables): Logarithm of the target density function from which to draw random samples. Either `pdf_target` or `log_pdf_target` must be provided (the latter should be preferred for better numerical stability). Same comments as for input `pdf_target`. * **args_target** ((`list` of) `tuple`): Positional arguments of the pdf / log-pdf target function. See `pdf_target` * **seed** (`ndarray`): Seed of the Markov chain(s), shape ``(nchains, dimension)``. Default: zeros(`nchains` x `dimension`). If `seed` is not provided, both `nchains` and `dimension` must be provided. * **nburn** (`int`): Length of burn-in - i.e., number of samples at the beginning of the chain to discard (note: no thinning during burn-in). Default is 0, no burn-in. * **jump** (`int`): Thinning parameter, used to reduce correlation between samples. Setting `jump=n` corresponds to skipping `n-1` states between accepted states of the chain. Default is 1 (no thinning). * **nchains** (`int`): The number of Markov chains to generate. Either `dimension` and `nchains` or `seed` must be provided. * **save_log_pdf** (`bool`): Boolean that indicates whether to save log-pdf values along with the samples. Default: False * **verbose** (`boolean`) Set ``verbose = True`` to print status messages to the terminal during execution. * **concat_chains** (`bool`): Boolean that indicates whether to concatenate the chains after a run, i.e., samples are stored as an `ndarray` of shape (nsamples * nchains, dimension) if True, (nsamples, nchains, dimension) if False. Default: True * **random_state** (None or `int` or ``numpy.random.RandomState`` object): Random seed used to initialize the pseudo-random number generator. Default is None. If an integer is provided, this sets the seed for an object of ``numpy.random.RandomState``. Otherwise, the object itself can be passed directly. **Attributes:** * **samples** (`ndarray`) Set of MCMC samples following the target distribution, `ndarray` of shape (`nsamples` * `nchains`, `dimension`) or (nsamples, nchains, dimension) (see input `concat_chains`). * **log_pdf_values** (`ndarray`) Values of the log pdf for the accepted samples, `ndarray` of shape (nchains * nsamples,) or (nsamples, nchains) * **nsamples** (`list`) Total number of samples; The `nsamples` attribute tallies the total number of generated samples. After each iteration, it is updated by 1. At the end of the simulation, the `nsamples` attribute equals the user-specified value for input `nsamples` given to the child class. * **nsamples_per_chain** (`list`) Total number of samples per chain; Similar to the attribute `nsamples`, it is updated during iterations as new samples are saved. * **niterations** (`list`) Total number of iterations, updated on-the-fly as the algorithm proceeds. It is related to number of samples as niterations=nburn+jump*nsamples_per_chain. * **acceptance_rate** (`list`) Acceptance ratio of the MCMC chains, computed separately for each chain. **Methods:** """ # Last Modified: 10/05/20 by Audrey Olivier def __init__(self, dimension=None, pdf_target=None, log_pdf_target=None, args_target=None, seed=None, nburn=0, jump=1, nchains=None, save_log_pdf=False, verbose=False, concat_chains=True, random_state=None): if not (isinstance(nburn, int) and nburn >= 0): raise TypeError('UQpy: nburn should be an integer >= 0') if not (isinstance(jump, int) and jump >= 1): raise TypeError('UQpy: jump should be an integer >= 1') self.nburn, self.jump = nburn, jump self.seed = self._preprocess_seed(seed=seed, dim=dimension, nchains=nchains) self.nchains, self.dimension = self.seed.shape # Check target pdf self.evaluate_log_target, self.evaluate_log_target_marginals = self._preprocess_target( pdf_=pdf_target, log_pdf_=log_pdf_target, args=args_target) self.save_log_pdf = save_log_pdf self.concat_chains = concat_chains self.random_state = random_state if isinstance(self.random_state, int): self.random_state = np.random.RandomState(self.random_state) elif not isinstance(self.random_state, (type(None), np.random.RandomState)): raise TypeError('UQpy: random_state must be None, an int or an np.random.RandomState object.') self.verbose = verbose self.log_pdf_target = log_pdf_target self.pdf_target = pdf_target self.args_target = args_target # Initialize a few more variables self.samples = None self.log_pdf_values = None self.acceptance_rate = [0.] * self.nchains self.nsamples, self.nsamples_per_chain = 0, 0 self.niterations = 0 # total nb of iterations, grows if you call run several times def run(self, nsamples=None, nsamples_per_chain=None): """ Run the MCMC algorithm. This function samples from the MCMC chains and appends samples to existing ones (if any). This method leverages the ``run_iterations`` method that is specific to each algorithm. **Inputs:** * **nsamples** (`int`): Number of samples to generate. * **nsamples_per_chain** (`int`) Number of samples to generate per chain. Either `nsamples` or `nsamples_per_chain` must be provided (not both). Not that if `nsamples` is not a multiple of `nchains`, `nsamples` is set to the next largest integer that is a multiple of `nchains`. """ # Initialize the runs: allocate space for the new samples and log pdf values final_nsamples, final_nsamples_per_chain, current_state, current_log_pdf = self._initialize_samples( nsamples=nsamples, nsamples_per_chain=nsamples_per_chain) if self.verbose: print('UQpy: Running MCMC...') # Run nsims iterations of the MCMC algorithm, starting at current_state while self.nsamples_per_chain < final_nsamples_per_chain: # update the total number of iterations self.niterations += 1 # run iteration current_state, current_log_pdf = self.run_one_iteration(current_state, current_log_pdf) # Update the chain, only if burn-in is over and the sample is not being jumped over # also increase the current number of samples and samples_per_chain if self.niterations > self.nburn and (self.niterations - self.nburn) % self.jump == 0: self.samples[self.nsamples_per_chain, :, :] = current_state.copy() if self.save_log_pdf: self.log_pdf_values[self.nsamples_per_chain, :] = current_log_pdf.copy() self.nsamples_per_chain += 1 self.nsamples += self.nchains if self.verbose: print('UQpy: MCMC run successfully !') # Concatenate chains maybe if self.concat_chains: self._concatenate_chains() def run_one_iteration(self, current_state, current_log_pdf): """ Run one iteration of the MCMC algorithm, starting at `current_state`. This method is over-written for each different MCMC algorithm. It must return the new state and associated log-pdf, which will be passed as inputs to the ``run_one_iteration`` method at the next iteration. **Inputs:** * **current_state** (`ndarray`): Current state of the chain(s), `ndarray` of shape ``(nchains, dimension)``. * **current_log_pdf** (`ndarray`): Log-pdf of the current state of the chain(s), `ndarray` of shape ``(nchains, )``. **Outputs/Returns:** * **new_state** (`ndarray`): New state of the chain(s), `ndarray` of shape ``(nchains, dimension)``. * **new_log_pdf** (`ndarray`): Log-pdf of the new state of the chain(s), `ndarray` of shape ``(nchains, )``. """ return [], [] #################################################################################################################### # Helper functions that can be used by all algorithms # Methods update_samples, update_accept_ratio and sample_candidate_from_proposal can be called in the run stage. # Methods preprocess_target, preprocess_proposal, check_seed and check_integers can be called in the init stage. def _concatenate_chains(self): """ Concatenate chains. Utility function that reshapes (in place) attribute samples from (nsamples, nchains, dimension) to (nsamples * nchains, dimension), and log_pdf_values from (nsamples, nchains) to (nsamples * nchains, ). No input / output. """ self.samples = self.samples.reshape((-1, self.dimension), order='C') if self.save_log_pdf: self.log_pdf_values = self.log_pdf_values.reshape((-1, ), order='C') return None def _unconcatenate_chains(self): """ Inverse of concatenate_chains. Utility function that reshapes (in place) attribute samples from (nsamples * nchains, dimension) to (nsamples, nchains, dimension), and log_pdf_values from (nsamples * nchains) to (nsamples, nchains). No input / output. """ self.samples = self.samples.reshape((-1, self.nchains, self.dimension), order='C') if self.save_log_pdf: self.log_pdf_values = self.log_pdf_values.reshape((-1, self.nchains), order='C') return None def _initialize_samples(self, nsamples, nsamples_per_chain): """ Initialize necessary attributes and variables before running the chain forward. Utility function that allocates space for samples and log likelihood values, initialize sample_index, acceptance ratio. If some samples already exist, allocate space to append new samples to the old ones. Computes the number of forward iterations nsims to be run (depending on burnin and jump parameters). **Inputs:** * nchains (int): number of chains run in parallel * nsamples (int): number of samples to be generated * nsamples_per_chain (int): number of samples to be generated per chain **Output/Returns:** * nsims (int): Number of iterations to perform * current_state (ndarray of shape (nchains, dim)): Current state of the chain to start from. """ if ((nsamples is not None) and (nsamples_per_chain is not None)) or ( nsamples is None and nsamples_per_chain is None): raise ValueError('UQpy: Either nsamples or nsamples_per_chain must be provided (not both)') if nsamples_per_chain is not None: if not (isinstance(nsamples_per_chain, int) and nsamples_per_chain >= 0): raise TypeError('UQpy: nsamples_per_chain must be an integer >= 0.') nsamples = int(nsamples_per_chain * self.nchains) else: if not (isinstance(nsamples, int) and nsamples >= 0): raise TypeError('UQpy: nsamples must be an integer >= 0.') nsamples_per_chain = int(np.ceil(nsamples / self.nchains)) nsamples = int(nsamples_per_chain * self.nchains) if self.samples is None: # very first call of run, set current_state as the seed and initialize self.samples self.samples = np.zeros((nsamples_per_chain, self.nchains, self.dimension)) if self.save_log_pdf: self.log_pdf_values = np.zeros((nsamples_per_chain, self.nchains)) current_state = np.zeros_like(self.seed) np.copyto(current_state, self.seed) current_log_pdf = self.evaluate_log_target(current_state) if self.nburn == 0: # if nburn is 0, save the seed, run one iteration less self.samples[0, :, :] = current_state if self.save_log_pdf: self.log_pdf_values[0, :] = current_log_pdf self.nsamples_per_chain += 1 self.nsamples += self.nchains final_nsamples, final_nsamples_per_chain = nsamples, nsamples_per_chain else: # fetch previous samples to start the new run, current state is last saved sample if len(self.samples.shape) == 2: # the chains were previously concatenated self._unconcatenate_chains() current_state = self.samples[-1] current_log_pdf = self.evaluate_log_target(current_state) self.samples = np.concatenate( [self.samples, np.zeros((nsamples_per_chain, self.nchains, self.dimension))], axis=0) if self.save_log_pdf: self.log_pdf_values = np.concatenate( [self.log_pdf_values, np.zeros((nsamples_per_chain, self.nchains))], axis=0) final_nsamples = nsamples + self.nsamples final_nsamples_per_chain = nsamples_per_chain + self.nsamples_per_chain return final_nsamples, final_nsamples_per_chain, current_state, current_log_pdf def _update_acceptance_rate(self, new_accept=None): """ Update acceptance rate of the chains. Utility function, uses an iterative function to update the acceptance rate of all the chains separately. **Inputs:** * new_accept (list (length nchains) of bool): indicates whether the current state was accepted (for each chain separately). """ self.acceptance_rate = [na / self.niterations + (self.niterations - 1) / self.niterations * a for (na, a) in zip(new_accept, self.acceptance_rate)] @staticmethod def _preprocess_target(log_pdf_, pdf_, args): """ Preprocess the target pdf inputs. Utility function (static method), that transforms the log_pdf, pdf, args inputs into a function that evaluates log_pdf_target(x) for a given x. If the target is given as a list of callables (marginal pdfs), the list of log margianals is also returned. **Inputs:** * log_pdf_ ((list of) callables): Log of the target density function from which to draw random samples. Either pdf_target or log_pdf_target must be provided. * pdf_ ((list of) callables): Target density function from which to draw random samples. Either pdf_target or log_pdf_target must be provided. * args (tuple): Positional arguments of the pdf target. **Output/Returns:** * evaluate_log_pdf (callable): Callable that computes the log of the target density function * evaluate_log_pdf_marginals (list of callables): List of callables to compute the log pdf of the marginals """ # log_pdf is provided if log_pdf_ is not None: if callable(log_pdf_): if args is None: args = () evaluate_log_pdf = (lambda x: log_pdf_(x, *args)) evaluate_log_pdf_marginals = None elif isinstance(log_pdf_, list) and (all(callable(p) for p in log_pdf_)): if args is None: args = [()] * len(log_pdf_) if not (isinstance(args, list) and len(args) == len(log_pdf_)): raise ValueError('UQpy: When log_pdf_target is a list, args should be a list (of tuples) of same ' 'length.') evaluate_log_pdf_marginals = list( map(lambda i: lambda x: log_pdf_[i](x, *args[i]), range(len(log_pdf_)))) evaluate_log_pdf = (lambda x: np.sum( [log_pdf_[i](x[:, i, np.newaxis], *args[i]) for i in range(len(log_pdf_))])) else: raise TypeError('UQpy: log_pdf_target must be a callable or list of callables') # pdf is provided elif pdf_ is not None: if callable(pdf_): if args is None: args = () evaluate_log_pdf = (lambda x: np.log(np.maximum(pdf_(x, *args), 10 ** (-320) * np.ones((x.shape[0],))))) evaluate_log_pdf_marginals = None elif isinstance(pdf_, (list, tuple)) and (all(callable(p) for p in pdf_)): if args is None: args = [()] * len(pdf_) if not (isinstance(args, (list, tuple)) and len(args) == len(pdf_)): raise ValueError('UQpy: When pdf_target is given as a list, args should also be a list of same ' 'length.') evaluate_log_pdf_marginals = list( map(lambda i: lambda x: np.log(np.maximum(pdf_[i](x, *args[i]), 10 ** (-320) * np.ones((x.shape[0],)))), range(len(pdf_)) )) evaluate_log_pdf = (lambda x: np.sum( [np.log(np.maximum(pdf_[i](x[:, i, np.newaxis], *args[i]), 10**(-320)*np.ones((x.shape[0],)))) for i in range(len(log_pdf_))])) else: raise TypeError('UQpy: pdf_target must be a callable or list of callables') else: raise ValueError('UQpy: log_pdf_target or pdf_target should be provided.') return evaluate_log_pdf, evaluate_log_pdf_marginals @staticmethod def _preprocess_seed(seed, dim, nchains): """ Preprocess input seed. Utility function (static method), that checks the dimension of seed, assign [0., 0., ..., 0.] if not provided. **Inputs:** * seed (ndarray): seed for MCMC * dim (int): dimension of target density **Output/Returns:** * seed (ndarray): seed for MCMC * dim (int): dimension of target density """ if seed is None: if dim is None or nchains is None: raise ValueError('UQpy: Either `seed` or `dimension` and `nchains` must be provided.') seed = np.zeros((nchains, dim)) else: seed = np.atleast_1d(seed) if len(seed.shape) == 1: seed = np.reshape(seed, (1, -1)) elif len(seed.shape) > 2: raise ValueError('UQpy: Input seed should be an array of shape (dimension, ) or (nchains, dimension).') if dim is not None and seed.shape[1] != dim: raise ValueError('UQpy: Wrong dimensions between seed and dimension.') if nchains is not None and seed.shape[0] != nchains: raise ValueError('UQpy: The number of chains and the seed shape are inconsistent.') return seed @staticmethod def _check_methods_proposal(proposal): """ Check if proposal has required methods. Utility function (static method), that checks that the given proposal distribution has 1) a rvs method and 2) a log pdf or pdf method. If a pdf method exists but no log_pdf, the log_pdf methods is added to the proposal object. Used in the MH and MMH initializations. **Inputs:** * proposal (Distribution object): proposal distribution """ if not isinstance(proposal, Distribution): raise TypeError('UQpy: Proposal should be a Distribution object') if not hasattr(proposal, 'rvs'): raise AttributeError('UQpy: The proposal should have an rvs method') if not hasattr(proposal, 'log_pdf'): if not hasattr(proposal, 'pdf'): raise AttributeError('UQpy: The proposal should have a log_pdf or pdf method') proposal.log_pdf = lambda x: np.log(np.maximum(proposal.pdf(x), 10 ** (-320) * np.ones((x.shape[0],))))
5ecee8c8ee06f6bb2e16ff1566a02c355783d44a
yiming1012/MyLeetCode
/LeetCode/动态规划法(dp)/322. Coin Change.py
2,388
3.8125
4
''' You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. Example 1: Input: coins = [1, 2, 5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Note: You may assume that you have an infinite number of each kind of coin. ''' import sys from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: ''' 执行用时 :1408 ms, 在所有 Python3 提交中击败了81.06%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了20.77%的用户 :param coins: :param amount: :return: ''' if len(coins) == 0 or amount < 0: return -1 dp = [amount + 1] * (amount + 1) dp[0] = 0 for coin in coins: for i in range(coin, amount + 1): # print(coin, i) dp[i] = min(dp[i], dp[i - coin] + 1) return dp[amount] if dp[amount] != amount + 1 else -1 def coinChange2(self, coins: List[int], amount: int) -> int: ''' 执行用时 :1408 ms, 在所有 Python3 提交中击败了81.06%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了20.77%的用户 :param coins: :param amount: :return: ''' if len(coins) == 0 or amount < 0: return -1 # 逆序排列 coins.sort(reverse=True) # ans = sys.maxsize ans = self.dfs(coins, 0, amount, 0, ans) # dfs:depth-first-search return ans if ans != sys.maxsize else -1 def dfs(self, coins, index, amount, count, ans): coin = coins[index] if index == len(coins) - 1: if amount % coin == 0: ans = min(ans, count + amount // coin) else: for i in range(amount // coin, -1, -1): if i + count >= ans: break self.dfs(coins, index + 1, amount - i * coin, i + count, ans) return ans if __name__ == '__main__': coins = [1, 2, 5] coins2 = [3] amount = 11 s = Solution() print(s.coinChange2(coins, amount))
255ff9b4c292216d37ae823cb095f335d68644b8
QLGQ/learning-python
/map.py
131
3.65625
4
#output the square of 0,1,2,3...100 into a list def square(n): return n*n L1 = range(101) L2 = list(map(square, L1)) print(L2)
c8013fadd47b2207036b30f261d113a16370e244
RafaelSanzio0/FACULDADE-PYTHON.1
/AULAS ATT/AULA08-ATT/AT01-AULA08.py
128
3.6875
4
#ATIVIDADE DE LABORATÓRIO 01 - AULA 08 #EXIBIR OS 10 PRIMEIROS MULTIPLOS DE 30 x = 0 while x <= 30: print(x) x = x+3
b6ce95ba6b0a9a43d64fae5f0fb2d8d6673bdfa1
FahimFBA/Python-Data-Structures-by-University-of-Michigan
/Dictionary/main.py
276
3.90625
4
# Many Counters with a Dictionary # One common use of dictionaries is counting how often we "see" something ccc = dict() ccc['ccev'] = 1 ccc['cwen'] = 1 print(ccc) # Output: {'ccev': 1, 'cwen': 1} ccc['cwen'] = ccc['cwen'] + 1 print(ccc) # Output : {'ccev': 1, 'cwen': 2}
27ad56538c8ccaebd8eabc54b6e98588888b799f
alokaviraj/python-program-3
/circle.py
115
4.03125
4
r=int(input("enter the radius of the circle")) pie=3.14 area=pie*r*r c=2*pie*r print("area=",area) print("cir=",c)
5d015a849beac9cf504cd4480f69f8f2755e616b
DevenMarrero/KTANE-Bot
/Password.py
1,416
3.671875
4
from Voice import speak def password(text): curr_password = [] crow1 = [] crow3 = [] txt = text.lower() text = txt.split(' next ') try: row1 = text[0].split() row3 = text[1].split() except IndexError: speak('Say Next in between rows') return for word in row1: lrow = word.replace(word, word[0]) crow1.append(lrow) letters = ' '.join([str(elem) for elem in crow1]) curr_password.append(letters) for word in row3: lrow = word.replace(word, word[0]) crow3.append(lrow) letters = ' '.join([str(elem) for elem in crow3]) curr_password.append(letters) passwords = ['about', 'after', 'again', 'below', 'could', 'every', 'first', 'found', 'great', 'house', 'large', 'learn', 'never', 'other', 'place', 'plant', 'point', 'right', 'small', 'sound', 'spell', 'still', 'study', 'their', 'there', 'these', 'thing', 'think', 'three', 'water', 'where', 'which', 'world', 'would', 'write'] posibles = [] for password in passwords: if password[0] in curr_password[0] and password[2] in curr_password[1]: posibles.append(password) janswer = ' '.join([str(elem) for elem in posibles]) if janswer.strip() == '': speak('No Possible answers') return speak(janswer)
cf020c231163feb33010b2de13fa8aad0c9cb32d
zhanglintc/leetcode
/Python/Trapping Rain Water.py
1,391
3.796875
4
# Trapping Rain Water # for leetcode problems # 2014.10.27 by zhanglin # Problem Link: # https://leetcode.com/problems/trapping-rain-water/ # Problem: # Given n non-negative integers representing an elevation map where the width of each bar is 1, # compute how much water it is able to trap after raining. # For example, # Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. # 3| _ # 2| _ | |_ _ # 1| _ | |_ _| |_| |_ # 0| | | | | | | # |------------------------- # 0 1 0 2 1 0 1 3 2 1 2 1 0 # The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. # In this case, 6 units of rain water are being trapped. # Thanks Lane for contributing this image! class Solution: # @param A, a list of integers # @return an integer def trap(self, A): if A == []: return 0 water = 0 # the water can be trapped max_idx = A.index(max(A)) # index of highest plank sub_max = 0 for i in range(max_idx): # from left to highest if A[i] < sub_max water += sub_max - A[i] else: sub_max = A[i] sub_max = 0 for i in range(len(A) - 1, max_idx, -1): # from right to highest if A[i] < sub_max water += sub_max - A[i] else: sub_max = A[i] return water
c99d5459c4ba2dee61238efdec6a2e1d06ac20cd
Kaustav-Biswas/Practice
/Regex Substitution.py
945
4.53125
5
''' The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda). The method is called for all matches and can be used to modify strings in different ways. The re.sub() method returns the modified string as an output. Task You are given a text of lines. The text contains && and || symbols. Your task is to modify those symbols to the following: && -> and || -> or Both && and || should have a space " " on both sides. Input Format The first line contains the integer, N. The next N lines each contain a line of the text. Constraints 0<N<100 Neither && nor || occur in the start or end of each line. Output Format Output the modified text. ''' import re #text = '\n'.join([input() for _ in range(int(input()))]) for _ in range(int(input())): text = input() text = re.sub(r' &&(?= )', ' and', text) text = re.sub(r' \|\|(?= )', ' or', text) print(text)
a26f269bbf1b1661d44635e49e32033f7c4928ba
Malkeet786/Python
/Chapter4/03_listmethod.py
205
3.53125
4
l1=[1,7,8,21,4,15,6] # print(l1) # l1.sort() sort list # l1.reverse() reverse list #l1.append(45) #adds att end of List l1.insert(2,100) # Insert 2 at index l1.pop(4)#remove l1.remove(15) #remove print(l1)
9a34a32b8720648ae0b66cc835b4c8aec13faeb2
luohaha66/MyCode
/leet_code/python/#23_merge_k_lists.py
2,262
3.6875
4
""" 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: 1->1->2->3->4->4->5->6 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: list) -> list: if not lists: return [] n = len(lists) return self.merge(lists, 0, n - 1) def merge(self, lists, left, right): if left == right: return lists[left] mid = left + (right - left) // 2 l1 = self.merge(lists, left, mid) l2 = self.merge(lists, mid + 1, right) return self.mergeTwoLists(l1, l2) def mergeTwoLists(self, l1, l2): 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 def version_one(self, lists: list): import heapq dummy = ListNode(0) p = dummy head = [] for i in range(len(lists)): if lists[i]: heapq.heappush(head, (lists[i].val, i)) lists[i] = lists[i].next while head: val, idx = heapq.heappop(head) p.next = ListNode(val) p = p.next if lists[idx]: heapq.heappush(head, (lists[idx].val, idx)) lists[idx] = lists[idx].next return dummy.next a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(6) e = ListNode(8) a.next = b b.next = c c.next = d d.next = e p = a while p: print(p.val, '->', end='') p = p.next print() f = ListNode(1) g = ListNode(4) h = ListNode(5) i = ListNode(6) j = ListNode(7) f.next = g g.next = h h.next = i i.next = j p = f while p: print(p.val, '->', end='') p = p.next print() j = ListNode(2) k = ListNode(6) l = ListNode(9) j.next = k k.next = l p = j while p: print(p.val, '->', end='') p = p.next print() lists = [a, f, j] s = Solution() p = s.mergeTwoLists(a, f) while p: print(p.val, '->', end='') p = p.next print()
12144c6aaed7acb04bd38928d7c6c6609b94e90d
wshis77/leetcode
/best-time-to-buy-and-sell-stock-ii.py
912
3.546875
4
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): i = 0 size = len(prices) buy = None sell = None result = 0 direction = [] while i < size: if i+1 == size: direction.append("DOWN") else: if prices[i] < prices[i+1]: direction.append("UP") else: direction.append("DOWN") i = i + 1 i= 0 while i < size: while i < size and direction[i] == "DOWN": i = i + 1 if i >= size: buy = None else: buy = prices[i] #print "buy " + str(buy) i = i + 1 while i < size and direction[i] == "UP": i = i + 1 if i >= size: sell = None else: #print "i " + str(i) sell = prices[i] #print "sell " + str(sell) i = i + 1 if buy != None and sell != None: result = result + sell - buy return result s = Solution() print s.maxProfit([1,3,2,4,6,1,-1])
0c56780e1a4341e7f9b5b7f44e2f30db4de277e7
Systemad/OOP-Python
/lists-dicts/list2.py
703
3.8125
4
## Only print odd numbers ''' tal = [3, 2, 8, 9, 7, 2] odd = [num for num in tal if num % 2 == 1] print(odd) ''' productList = [] class kop: product = "" price = 0 productNumber = "" amount = int(input("Hur många varor: ")) for i in range(amount): prod = input("vilken product? ") pric = int(input("Vad kostar det? ")) productNum = int(input("Product nummer? ")) #kop.product = prod #kop.price = pric #kop.productNumber = productNum productList.append(prod) productList.append(pric) productList.append(productNum) print(productList) #("Din product är: " , kop.product) # # #print("Din product kostar: " , kop.price) #print("Produkt nummer är: " , kop.productNumber)
dfcec46b826e32778b088e65e9b2ee61ac06a31c
JoseCardena365/practicas
/entrada.py
177
3.609375
4
#capturamos la entreda de teclado y la guardamos en una variable esto_es_una_entrada = input("ingrese algo: ") #imprimimos lo capturado por teclado print(estos_es_una_entrada)
1c7c74551d97a5a8bf44fc425a7f1e69d621710a
HelenaJanda/pyladies-7
/zaverecny-projekt/asteroids/v07_fly_out/spaceship.py
1,666
3.5
4
import pyglet import math # Degrees per second ROTATION_SPEED = 200 ACCELERATION = 200 class Spaceship: def __init__(self): self.x = 0 self.y = 0 self.x_speed = 0 self.y_speed = 0 self.rotation = 0 image = pyglet.image.load("../assets/PNG/playerShip1_blue.png") # Image is positioned by its middle, not lower left corner # Also important for rotation # // means integer division (floor) - 5//2 is 2 but 5/2 is 2.5 image.anchor_x = image.width // 2 image.anchor_y = image.height // 2 self.sprite = pyglet.sprite.Sprite(image) def draw(self): self.sprite.x = self.x self.sprite.y = self.y # we have rotation in rads, pyglet uses degrees # also, pyglet's zero is up, ours is on the right, right? self.sprite.rotation = 90 - math.degrees(self.rotation) self.sprite.draw() def tick(self, time_elapsed, keys_pressed, window): if pyglet.window.key.LEFT in keys_pressed: self.rotation = self.rotation + time_elapsed*ROTATION_SPEED if pyglet.window.key.RIGHT in keys_pressed: self.rotation = self.rotation - time_elapsed*ROTATION_SPEED if pyglet.window.key.UP in keys_pressed: self.x_speed += time_elapsed * ACCELERATION * math.cos(self.rotation) self.y_speed += time_elapsed * ACCELERATION * math.sin(self.rotation) self.x = self.x + time_elapsed*self.x_speed self.y = self.y + time_elapsed*self.y_speed # infinite space - wraparound coordinates self.x %= window.width self.y %= window.height
88037302efb31cbd034dfcedba9bb888ba9bac06
ps4417/algorithm
/Codeup/코드업 기초 100제/1088.py
293
3.765625
4
# 3의 배수는 통과? # 1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되, # 3의 배수인 경우는 출력하지 않도록 만들어보자. a = int(input()) for i in range(1,a+1): if(i%3==0): continue else: print(i,end=" ")
c2f97fab7e4abd3cb196b87280ea93a0023115ab
Javty/Python_Learning
/Web_APIS/Loop_dic.py
2,385
4.0625
4
favorites = {'color': 'purple', 'number': 42, 'animal': 'turtle', 'language': 'python'} dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} for key in dictionary: print(key) for key in dictionary.keys(): print(key) for value in dictionary.values(): print(value) for entry in dictionary.items(): print(entry) for key, value in favorites.items(): print(f"my favorite {key} is {value}") #split and count str = 'it appears that the the appears the most in the sentence' list = str.split(" ") dict = {} for word in list: if word in dict: dict[word] = dict[word] + 1 else: dict[word] = 1 for key, value in dict.items(): print(f"\'{key}\' appears {value} time(s) in the string") # Loop over list foods = [['apple', 'banana', 'orange'],['carrot', 'cucumber', 'tomato']] for e in foods: print(e) for e in foods[0]: print(e) # Loop Over dictionaries pets = { 'birds': { 'parrot': 'Arthur', 'canary': 'Ford' }, 'fish': { 'goldfish': 'Zaphod', 'koi': 'Trillium' } } for e in pets: print(e) print("new for:") for e in pets["birds"]: print(e) print("new for:") for e in pets["fish"]: print(e) print("new for:") for e in pets["birds"].values(): print(e) #list of dictionares weather = [ { 'date':'today', 'state': 'cloudy', 'temp': 68.5 }, { 'date':'tomorrow', 'state': 'sunny', 'temp': 74.8 } ] for e in weather[0].values(): print(e) for e in weather[0]: print(e) for e in weather: print(e['date']) print(e['state']) print(e['temp']) for e in weather: print(e['date']) print(e['state']) print(e['temp']) for forecast in weather: print(forecast['date']) print(forecast['state']) print(forecast['temp']) #for forecast in weather: # print('The weather for ' + forecast['date'] + ' will be ' + forecast['state'] + ' with a temperature of ' + str(forecast['temp']) + ' degrees.') for forecast in weather: print(f"The weather for {forecast['date']} will be {forecast['state']} with a temperature of {forecast['temp']} degrees.") for forecast in weather: date = forecast['date'] state = forecast['state'] temp = forecast['temp'] print(f"The weather for {date} will be {state} with a temperature of {temp} degrees.")
c78f5ae78fbba039794e0159fba8eed302487c9a
DaveRiv/Euler_Project
/project_euler.py
632
4.34375
4
''' 1. List all the natural numbers from 0 to 10 that are mulitples of 3 and 5 2. List all natural numbers from 1 to 1000 that are mulitple of 3 and 5 and the return the sum ''' def if_multiple(nat_number): ''' return True if it is a multiple of 3 or 5''' if nat_number % 3 == 0 or nat_number % 5 == 0: print nat_number return True else : return False '''end of one funcetion ''' def append_to_array(myarray, item_to_append): '''appends item_to_array to myarray ''' def sum_numbers( number ): ''' Sum all of the nmbers''' return
f16c4b3141683628250a7f6245fb2f360437822f
kpessa/CodeSignal
/py/floorDivision.py
491
3.578125
4
def division1(x, y): return x // y def division2(x, y): return int(x / y) testInput = [ { 'x': 15, 'y': -4 }, { 'x': 17, 'y': 13 }, { 'x': 5, 'y': 10 }, { 'x': -10, 'y': -3 }, { 'x': -8, 'y': 2 } ] for item in testInput: print( f"x: {item['x']}, y: {item['y']}\n" f"Div1: {division1(**item)}\n" f"Div2: {division2(**item)}\n" ) #%%
97219c62a5f57e378ca8217081f60499906471ac
hectorlopezmonroy/HackerRank
/Programming Languages/Python/Strings/What's Your Name?/Solution.py
884
4.28125
4
# -*- coding: utf-8 -*- # You are given the first name and last name of a person on two different lines. # Your task is to read them and print the following: # # Hello firstname lastname! You just delved into python. # # Input Format # # The first line contains the first name, and the second line contains the last # name. # # Constraints # # The length of the first and last name <= '10'. # # Output Format # # Print the output as mentioned above. # # Sample Input # # Ross # Taylor # # Sample Output # # Hello Ross Taylor! You just delved into python. # # Explanation # # The input read by the program is stored as a string data type. A string is a # collection of characters. def print_full_name(a, b): print(f'Hello {a} {b}! You just delved into python.') if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
6397379e6c67538607d5d6b9025980830877b539
fatimaparada/Linear-Regression
/Linear_regression_nosklearn.py
5,145
3.890625
4
#Writing code that implements gradient descent to perform linear regression #Yeswanth Bogireddy & Fatima Parada-Taboada import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns import random from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score #import dataset dataset = pd.read_csv('https://raw.githubusercontent.com/fatimaparada/Assignment1/master/Copy%20of%20Concrete_Data.csv') # Plot everything plt.figure(figsize=(15, 10)) plt.scatter(dataset['Cement (component 1)(kg in a m^3 mixture)'], dataset['Concrete compressive strength(MPa, megapascals) ']) #Splitting data X_train, X_test, y_train, y_test = train_test_split(dataset['Cement (component 1)(kg in a m^3 mixture)'], dataset['Concrete compressive strength(MPa, megapascals) ']) #Plotting training and testing data plt.figure(figsize=(15, 10)) plt.scatter(X_train, y_train, color = 'blue', label='Training Data') plt.scatter(X_test, y_test, color = 'red', label='Testing Data') class GradientDescent: def __init__(self, alp, bta, iterations, momentumsInterval): #------------------->Constructor to intialize the values for gradient descent. self.alp = alp self.bta = bta self.iteration_1 = iterations self.size = 0 self.momentum = momentumsInterval self.optimalweights = [] self.optimal_bias = 0 def calcPredition(self, X_train, coefficients, intercept): #------------------------->Prediction predictions = pd.Series() predictions = 0 for i in range(len(coefficients)): predictions = coefficients[i] * X_train.values predictions += intercept return predictions def calcLoss(self, X_train, y_train, coefficients, intercept): #-----------------> MSE predictions = self.calcPredition(X_train, coefficients, intercept) return ((predictions - y_train) ** 2).sum() * (1 / (2 * self.size)) def run_gradient_descent(self, X_train, y_train, coefficients, intercept):#-------------------> Preforms momentum gradient decesnt i = 0 while i < self.iteration_1: predictions = self.calcPredition(X_train, coefficients, intercept) intercept_derivative = (1 / self.size) * (predictions - y_train).sum() self.momentum[0] = (self.bta * self.momentum[0]) + ((i - self.bta) * intercept_derivative) intercept -= ((self.alp) * self.momentum[0]) for j in range(len(coefficients)): coeff_derivative = (1 / self.size) * ((predictions - y_train) * X_train).sum() self.momentum[j + 1] = (self.bta * self.momentum[j + 1]) + ((1 - self.bta) * coeff_derivative) coefficients[j] -= (self.alp * self.momentum[j + 1]) i += 1 error = self.calcLoss(X_train, y_train, coefficients, intercept) return error, coefficients, intercept def momentumGradientD(self, X_train, y_train): #----------------> Calling mgd with randomly generated values self.size = X_train.shape[0] i = 0 minError = float('inf') init_intercept = y_train.values.min() iterations = int(y_train.values.max()) - int(y_train.values.min()) while i < iterations: coefficients = [] coefficients.append(random.uniform(0.0, 8.0)) # change it currentError, coefficients, intercept = self.run_gradient_descent(X_train, y_train, coefficients, init_intercept) if (currentError < minError): minError = currentError self.optimalweights = coefficients self.optimal_bias = init_intercept init_intercept += 0.4 i += 0.4 #Print(i,bias/intercept,curr_error,coeff) return minError, self.optimalweights, self.optimal_bias def predict(self, X_test): return self.calcPredition(X_test, self.optimalweights, self.optimal_bias) alp = 0.00005 bta = 0.9 iterations = 1000 #import dataset dataset = pd.read_csv('https://raw.githubusercontent.com/fatimaparada/Assignment1/master/Copy%20of%20Concrete_Data.csv') size = dataset.shape[0] momentumIterval = [0, 0] model = GradientDescent(alp, bta, iterations, momentumIterval) #print(dataset['Concrete compressive strength(MPa, megapascals) '].min()) #print(dataset['Concrete compressive strength(MPa, megapascals) '].max()) print(model.momentumGradientD(dataset['Cement (component 1)(kg in a m^3 mixture)'], dataset['Concrete compressive strength(MPa, megapascals) '])) print((model).optimalweights,(model).optimal_bias) predictions = model.predict(X_test) print('Mean squared error: ') print(mean_squared_error(y_test.values, predictions)) print('R2 scored: ') print(r2_score(y_test.values, predictions)) plt.figure(figsize=(15,10)) plt.plot(X_test, predictions, color='g', label='Linear Regression') plt.scatter(X_test, y_test, label='Actual Testing Data')
fd7461e07c537977c05be0024432dfcbcc677c5d
JiaquanYe/LeetCodeSolution
/Tree/sword_SymmetryTree.py
938
4.0625
4
""" 问题描述:判断二叉树是否为对称的二叉树,如果一棵二叉树和其镜像二叉树一样,那么它就是对称的 references : symmetrical Tree: https://blog.csdn.net/ustcer_93lk/article/details/80373736 mirror Tree: https://blog.csdn.net/ustcer_93lk/article/details/80373690 """ class TreeNode(): def __init__(self, data=-1, left=None, right=None): self.data = data self.left = left self.right = right def isSymmetrical(treeRoot1, treeRoot2): if treeRoot1.data == -1 and treeRoot2.data == -1: #两个都是空,一样 return True elif treeRoot1.data == -1 or treeRoot2.data == -1 : #一个都是空,一样 return False elif treeRoot1.data != treeRoot2.data: #根节点不一样 return False else: return isSymmetrical(treeRoot1.left,treeRoot2.right) and isSymmetrical(treeRoot1.right, treeRoot2.left)
dabfaa57bb7de346012def3c984541909a571462
devLorran/Python
/ex0075.py
634
4.0625
4
'''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final mostra: A) Quantas vezes apareceu o valor 9. Usar length() B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.''' par = 0 num = tuple(int(input('Digite um número: ').format(n+1))for n in range(4)) try: print(f'O valor 3 foi digitado na posição: {num.index(3)+1}ª') except: print('O valor 3 não foi encontrado!') print(f'O valor 9 foi digitado {num.count(9)} vezes!') for n in num: if n % 2 == 0: par += 1 print(f'Foram digitados {par} pares na telas!')
35e62eda0b812e1e06f5d40d13b538e63df188dd
abhaybd/AoC2020
/day2/day2part2.py
324
3.71875
4
with open("input.txt") as f: lines = f.readlines() def is_valid(line: str): positions, letter, password = line.split(" ", 3) letter = letter[0] p1, p2 = [int(x)-1 for x in positions.split("-")] return (password[p1] == letter) ^ (password[p2] == letter) print(sum([is_valid(line) for line in lines]))
615461843c643d53b05359368e62feac992c6ecc
arrimonhere/Python-Calculator
/Python Calculator With Function.py
2,507
4.21875
4
# Calculator With Function # Code By Ar Rimon Ahmed # Function For Addition def Addition(x,y) : return x+y # Function For Substraction def Substraction(x,y) : return x-y # Function For Multliplication def Multliplication(x,y) : return x*y # Function For Division def Division(x,y) : return x/y # Function For Square def Square(x) : return x**2 # Function For Cube def Cube(x) : return x**3 print("For Addition Enter : +\nFor Substraction : -\nFor Multliplication : *\nFor Division : /\n For Square : ^\nAnd For Cube : @") Choose=input("\nEnter Your Choice (+,-,* or /) : ") # Condition For Addition if Choose=="+" : print("\nWelcome \nYou Decided To Do Addition Of Two Number.\n") num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) print("\nThe Addition Of Two Number Is : ",num1,"+",num2,"=", Addition(num1,num2)) # Condition For Substraction elif Choose=="-" : print("\nWelcome \nYou Decided To Do Substraction Of Two Number.\n") num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) print("\nThe Substraction Of Two Number Is : ",num1,"-",num2,"=", Substraction(num1,num2)) # Condition For Multliplication elif Choose=="*" : print("\nWelcome \nYou Decided To Do Multliplication Of Two Number.\n") num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) print("\nThe Multliplication Of Two Number Is : ",num1,"*",num2,"=", Multliplication(num1,num2)) # Condition For Division elif Choose=="/" : print("\nWelcome \nYou Decided To Do Division Of Two Number.\n") num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) print("\nThe Substraction Of Two Number Is : ",num1,"/",num2,"=", Division(num1,num2)) # Condition For Square elif Choose=="^" : print("\nWelcome \nYou Decided To Do Square Of A Number.\n") num1=int(input("Enter Any Number : ")) print("\nThe Square Of Your Number Is : ",num1,"*",num1,"=", Square(num1)) # Condition For Cube elif Choose=="@" : print("\nWelcome \nYou Decided To Do Cube Of A Number.\n") num1=int(input("Enter Any Number : ")) print("\nThe Cube Of Your Number Is : ",num1,"*",num1,"*",num1,"=", Cube(num1)) # Condition If Don't Understand One Desicion else : print("\nSorry \nWe Cannot Understand Your Desicion.\n") print("Please Try Again, With Correct Desicion.")
14b5eca6f4fd9fd68fcbb3842941a58c3c7b07bb
jsarraga/week1
/Quiz_1/Quiz1_Solution/solution.py
757
3.71875
4
import json # * Write a function ```readcurrency(filename)``` def readcurrency(filename): # read the lines of a file with open(filename, 'r') as file_object: lines = file_object.readlines() new_list = [] # Separate lines into two values for line in lines: new_dict = {} line = line.strip().split() new_dict['symbol'] = line[0] new_dict['rate'] = float(line[1]) new_list.append(new_dict) return new_list # print(readcurrency('currency.txt')) def save(filename, a_list): with open(filename, 'w') as file_object: new_data = {'data': a_list} json.dump(new_data, file_object, indent=2) save('currency.json',readcurrency('currency.txt'))
de46e0cae69ac24a678ca7b7404ab5eda3852bc4
zacharybraxton-lpsr/class-samples
/dawgz.py
196
3.734375
4
print("How many dogs do you have") puppie = raw_input() puppie2 = int(puppie) puppie2 = puppie2 + 4 puppie2 = puppie2 + 4 print("In two months, you will have " + str(puppie2) + " puppies")
5f6b409db562ff6ae2324ece1da712a66c7c5495
amalija-ramljak/advent-of-code-2018
/day25 - hot chocolate delivery/25.py
1,002
3.625
4
def get_manhattan(loc1, loc2): return sum([abs(a-b) for a, b in zip(loc1, loc2)]) stars = [] while True: line = input() if line == "": break line = line.split(",") for i, el in enumerate(line): line[i] = int(el) line = tuple(line) stars.append(line) constellations = dict() count = 0 for star in stars: cons = [] for con in constellations: for con_star in constellations[con]: if get_manhattan(star, con_star) <= 3: cons.append(con) break if len(cons) == 1: constellations[cons[0]] |= {star} elif len(cons) == 0: constellations[count] = {star} count += 1 elif len(cons) > 1: new_const = {star} for con in cons: for con_star in constellations[con]: new_const |= {con_star} constellations.pop(con) constellations[count] = new_const count += 1 print(len(constellations))
1aa877893d8caefda91a1749b95cf381de2248ca
kyakusahmed/talent_show
/reception.py
587
3.734375
4
file = open('VIP.txt','r') file1 = open('Ord.txt','r') ORD = [] VIP = [] for line in file: VIP.append(line) for line in file1: ORD.append(line) def registration_checker(name,data): result = "User Not Registered" for fullname in data: if fullname.casefold().find(name.casefold()) != -1: result = fullname return result return result while True: name1 = input("enter your name! ") print(registration_checker(name1,VIP)) print(registration_checker(name1,ORD))
70ca90a56a5c87dbc3e8f2e7d427591f46c24c92
untiwe/citrom_test
/usermanager/package.py
642
3.78125
4
import string import secrets import random #пример из документации https://docs.python.org/3/library/secrets.html def gen_new_password(): '''Функция возвращает пароль 6-10 символов''' alphabet = string.ascii_letters + string.digits while True: range_password = random.randint(6, 10) password = ''.join(secrets.choice(alphabet) for i in range(range_password)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): break return password
660545710fb4151683cc94aba57c55c31f043a41
chixujohnny/Leetcode
/Leetcode2020/剑指offer/树/剑指 Offer 32 - I. 从上到下打印二叉树【树的BFS队列打印】[2刷].py
1,254
3.875
4
# coding: utf-8 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] res = [root.val] queue = [root] # List[Treenode] while queue != []: if queue[0].left != None: queue.append(queue[0].left) res.append(queue[0].left.val) if queue[0].right != None: queue.append(queue[0].right) res.append(queue[0].right.val) queue = queue[1:] # pop return res treeList = [3,9,20,None,None,15,7] def CreateBineryTree(root, treeList, i): if i < len(treeList): if treeList[i] == None: return None else: root = TreeNode(treeList[i]) root.left = CreateBineryTree(root.left, treeList, 2*i+1) root.right = CreateBineryTree(root.right, treeList, 2*i+2) return root return root root = CreateBineryTree(None, treeList, 0) s = Solution() print s.levelOrder(root)
f0600c53972831fd5c600166e66ef536596cdede
rushirg/LeetCode-Problems
/solutions/how-many-numbers-are-smaller-than-the-current-number.py
873
3.75
4
""" 1365. How Many Numbers Are Smaller Than the Current Number https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/submissions/ """ class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: ans = [] for x in range(len(nums)): count = 0 for y in range(len(nums)): if(nums[y] < nums[x] and x != y): count += 1 ans.append(count) return ans """ Method 2 Faster 108ms using collections Counter from collections import Counter class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: ans = [] count = Counter(nums) for x in nums: cnt = 0 for i in range(x): cnt += count[i] ans.append(cnt) return ans """
031ed345b1ac49b3d312ecaecb49aeaa53db5910
luwinher/Python_Practice
/gPython/fifteen.py
279
3.5
4
# """Q15:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。""" score = int(input("请输入该同学分数:")) S = 'A' if (score>=90) else ('B' if (score>=60) else 'C') print(S)
e21748123819863d928a1ed5363e8f8a1ee0ebce
carlitomm/python_prog_course
/practica9.py
464
3.921875
4
def dec2bin(number): bin = "" if number == 0: return "0" while number > 0: bin = bin + (str(number%2)) number = int(number / 2) return bin[::-1] try: number = int(input("ingrese el numero a convertir ")) print (dec2bin(number)) except: print(".....ERROR...ingrese un numero entero") # https://alumnosuacj-my.sharepoint.com/:v:/g/personal/al206563_alumnos_uacj_mx/EUJUj7VVHQVHvXrDWYs2DJYB412bbZZkbi-RXDY7K2o_yw
423b768d5fb196bbcd77e5d7be41f90036639870
Pobe16/python-labs
/strings_and_functions/returnvalues3.py
1,543
4.1875
4
# Modify the program so it check that the temperature value is numeric # Temperature conversion program def centigradeToFahrenheit(cent): fahr = (9.0 / 5.0) * cent + 32 return fahr def fahrenheitToCentigrade(fahr): cent = (5.0 / 9.0) * (fahr - 32) return cent def isNumber(value): try: var = float(value) return True except (TypeError, ValueError): return False print("Welcome to the temperature conversion program") print("---------------------------------------------") print() while True: # Print out the menu: print("Please select a conversion:") print("1 Centigrade to Fahrenheit") print("2 Fahrenheit to Centigrade") print("3 Exit program") # Get the user's choice: convert = input("> ") if convert == '1': value = input("Please enter value in degrees Centigrade: ") if isNumber(value): value = float(value) result = centigradeToFahrenheit(value) print(result, "degrees Fahrenheit") else: print("Value is invalid - try again") elif convert == '2': value = input("Please enter value in degrees Fahrenheit: ") if isNumber(value): value = float(value) result = fahrenheitToCentigrade(value) print(result, "degrees Centigrade") else: print("Value is invalid - try again") elif convert == '3': print("Bye...") break else: print("Invalid choice - try again") print()
88dc8de7f934476fbf22635cdb0a7c15c3362f7d
yashu762001/Python-Tutorial
/DataType/Set.py
504
4.15625
4
animals = {"lion","lion","lion","tiger","giraffe","elephant"} print(animals) print(len(animals)) print(animals.__contains__("lion")) # print(animals[2]) # Since there is a random distribution so we can't say that at this particular location this string is gonna come. print(animals.add("peacock")) print(animals) animals.add("hello") print(animals) obj = {"lion","tiger","Dog","Cat","Mouse"} # print(obj) # animals = animals.intersection(obj) # print(animals) animals = animals.union(obj) print(animals)