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
7dc315634ef2beda7b03551c4727d249d437ffbe
CarlosPimentel10/py-Projects
/exercise2.py
655
4.34375
4
# FIND THE NUMBER OF OCCURRENCES OF LETTERS IN THE FOLLOWING STRING # use a dictionary # from pprint import pprint -> this module is used to print data in a more readable way sentence = 'This is a common interview question' char_frequency = {} for char in sentence: if char in char_frequency: char_frequency[char] += 1 else: char_frequency[char] = 1 # pprint(char_frequency, width=1) -> this function is used to print data in a more readable way char_frequency_sorted = sorted(char_frequency.items(), key=lambda kv:kv[1], reverse=True) print(char_frequency_sorted[0])
8b83fb55fe6a169eedaff02f253c391d3c2e0f88
Miracle-bo/Work
/19.06/work-等腰三角.py
225
3.90625
4
# 单循环 for a in range(1,9): c = 2*a-1 d = '* '*c f = ' '*(8-a) print(f'{f}{d}') # 嵌套循环 for x in range(1,9): y = 2*x-1 for z in range(1,9-x): print(' ',end='') print('* '*y)
b38f053fc0eb34382f55171633479273bd53dea5
RahatIbnRafiq/leetcodeProblems
/Linked List Problems/725. Split Linked List in Parts.py
862
3.578125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getSize(self,root): p1 = root length = 0 while p1: length +=1 p1 = p1.next return length def splitListToParts(self, root, k): N = self.getSize(root) listsWithExtra = N%k normalListSize = N/k results = [] cur = root for i in xrange(k): temp = [] for j in xrange(normalListSize): temp.append(cur.val) cur = cur.next if listsWithExtra > 0: temp.append(cur.val) cur = cur.next listsWithExtra -= 1 results.append(temp) return results
7c52d759c6ed4d19c3952d013f70bfca5ecff6e8
alexandraback/datacollection
/solutions_5753053697277952_0/Python/easyrider/run.py
1,288
3.515625
4
#!/usr/bin/python3 import numpy nr_of_tasks = int(input()) def p_name(ind): return chr(ind + ord('A')) def find_index_of_max_value(_list): max_value = 0 counter = -1 for item in _list: counter = counter + 1 if item > max_value: max_value = item + 0 pos = counter + 0 return p_name(pos), pos def check_if_one_more(_list): name, pos = find_index_of_max_value(_list) total = sum(_list) - 1 for ind, item in enumerate(_list): if item > int(total / 2) and ind is not pos: return None, None return name, pos for task_index in range(1,nr_of_tasks+1): nr_of_parties = int(input()) parties = [int(item) for item in input().split()] nr_of_parties_left = len(parties) nr_of_people = sum(parties) result = [] while sum(parties) > 0: res = "" name1, pos1 = find_index_of_max_value(parties) parties[pos1] = parties[pos1] - 1 res = name1 name, pos = check_if_one_more(parties) if name is not None: parties[pos] = parties[pos] - 1 res = "".join([name1, name]) result.append(res) print("Case #{task}: {result}".format(task=task_index, result=" ".join(result)))
88bd6e35a06da2c04376be4178b1b96967723b93
4RG0S/2020-Fall-Jookgorithm
/김송이/[2020.10]/[2020.10.02]10825.py
624
3.625
4
import re def main(): n = int(input()) p=re.compile('(\D+)(\s)(\d+)(\s)(\d+)(\s)(\d+)') student_list = [] regular_list=[] for i in range(n): student_list.append(input()) #for student in student_list: # s_list=p.findall(student) # regular_list.extend(s_list) #print(regular_list) student_list.sort(key=lambda x: (-int(p.match(x).group(3)),int(p.match(x).group(5)),-int(p.match(x).group(7)),p.match(x).group(1))) print(student_list) for s in student_list: print_name=list(s.split()) print(print_name[0]) if __name__ == '__main__': main()
d241d4cd2d50e000980c26b5811918a871781e03
wseungjin/codingTest
/kakaoEnterprise/chihoon/1.py
508
3.734375
4
def solution(x,spaces): sortedArray = [] for index,value in enumerate(spaces): sortedArray.append((value,index)) sortedArray.sort() minValues = [] for start in range(len(spaces) - x + 1): for value in sortedArray: if start <= value[1] and value[1] < start + x: minValues.append(value[0]) break return max(minValues) def main(): print(solution(2,[8,2,4,6])) print(solution(1,[1,2,3,1,2])) main()
fdaee5881dbe4a1afd7a017f23ecba697fe02405
clhernandez/projecteuler
/ex5_2.py
773
4.03125
4
import sys, time #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def smallMultiple(num, size): for x in xrange(1,size): if(num%x!=0): return False pass return True def searchSmallMultiple(size): found = False; num=1 init = time.time() while(found==False): if(smallMultiple(num,size)): found=True print "El menor numero divisible por los primeros {0} numeros es: {1} en {2}sec".format(size, num, time.time(); return num else: # print "NUM {0}".format(num) num+=1 searchSmallMultiple(20)
f235c39b3819518b10d216212e40fb16507b1474
joshseymour/python-challenge
/PyPoll.py
2,311
3.84375
4
#import libraries import os import csv #set file path csvpath = os.path.join("Resources", "election_data.csv") #create counters votes = 0 winning = 0 #create list without headers data = [] #create list of candidates candidates = [] #create dictionaries of candidate votes & percentage of votes candidate_vote = {} candidate_percent = {} #open the CSV with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader) data = list(csvreader) #loop thorugh to count the votes and get candidate names for row in data: #count the number of votes votes = votes + 1 #condition to append unique candidate and get count of votes if row[2] not in candidates: candidates.append(row[2]) candidate_vote[row[2]] = 0 candidate_vote[row[2]] = candidate_vote[row[2]] + 1 #Find count of votes for each candiate for (key, value) in candidate_vote.items(): candidate_percent[key] = round(value/votes * 100, 1) if winning < value: winning = value elected_candidate = key #print out the results of the election print("Election Results") print("-------------------------") print("Total Votes: " + str(votes)) print("-------------------------") for (key,value) in candidate_vote.items(): print(f'{key}: {candidate_percent[key]}% ({value})') print("-------------------------") print("Winner: " + elected_candidate) print("-------------------------") # Specify the file to write to output_path = os.path.join("pypoll_output.txt") with open(output_path, 'w', newline='') as csvfile: # Initialize csv.writer csvwriter = csv.writer(csvfile, delimiter=',') #print the election results csvwriter.writerow(['Election Results']) csvwriter.writerow(['-------------------------']) csvwriter.writerow(['Total Votes: ' + str(votes)]) csvwriter.writerow(['-------------------------']) for (key,value) in candidate_vote.items(): csvwriter.writerow([f'{key}: {candidate_percent[key]}% ({value})']) csvwriter.writerow(['-------------------------']) csvwriter.writerow(['Winner: ' + elected_candidate]) csvwriter.writerow(['-------------------------'])
8339adf8196b966a16bcd04e614589c2edc898e9
Styfjion/code
/ex_quicksort.py
1,102
3.90625
4
def quicksort(array): if len(array) >= 2: mid = array[len(array)//2] array.remove(mid) right,left = [],[] for unit in array: if unit>=mid: right.append(unit) else: left.append(unit) return quicksort(left)+[mid]+quicksort(right) else: return array def megresort(array): if len(array) <= 1: return array mid = len(array)//2 left = megresort(array[:mid]) right = megresort(array[:mid]) return mergre(left,right) def mergre(left,right): r,l = 0,0 result = [] while l < len(left) and r < len(right): if left[l] < right[r]: result.append(left[l]) else: result.append(right[r]) result += left[l:] result += right[r:] return result def big_endheapy(arr,start,end): root = start while True: child = 2*root + 1 if child > end: break if child+1 < end and arr[child] < arr[child+1]: child += 1 if arr[root] < arr[]
b604f6dca715c61940b77714f03053fd0c275bf4
ahmedfadhil/Binary-tree-insertion
/bst_remove_node.py
1,357
3.875
4
def remove_node(self, value, parent): if value < self.value and self.left_child: return self.left_child.remove_node(self, value) elif value < self.value: return False elif value > self.value and self.right_child: return self.right_child.remove_node(self, value) elif value > self.value: return False else: if self.left_child is None and self.right_child is None and self == parent.left_child: parent.left_child = None self.clear_node() elif self.left_child is None and self.right_child is None and self == parent.right_child: parent.right_child = None self.clear_node() elif self.left_child and self.right_child is None and self == parent.right_child: parent.right_child = self.left_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.left_child: parent.left_child = self.right_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.right_child: parent.right_child = self.right_child self.clear_node() else: self.value = self.right_child.find_minimum_value() self.right_child.remove_node(self.value, self) return True
5c5410f692aa23555eff353a04a4eaa1f38b13b4
MagicTrucy/Python
/liste_adjacence_vers_tableau_adjacence.py
632
3.578125
4
# Donnée : l la liste d'adjacence l = [[1,3],[0,2],[1],[0]] # Initialisation # N : nombre de pages N = 4 # A : tableau d'adjacence A = [[False for x in range(N)] for y in range(N)] # Début du traitement # index_page : l'index en cours dans la liste for index_page in range(len(l)): # index_lien : l'index en cours dans la liste à la position l[index_page] for index_lien in range(len(l[index_page])): # page_pointee (int) : page pointee par le lien numéro index_lien # de la page numéro index_page page_pointee = l[index_page][index_lien] A[page_pointee][index_page] = True print(A)
c557a0847300970310bd8c3963b3dfc9acece269
wzlwit/jac_spark
/lecture2/task3.py
2,175
3.703125
4
# Task 3: Skeleton of an ML program: Transformer, Estimator, Parameters # Objective: Understand the building block of any ML application with the example of predicting the role of an IT professional is developer by looking at his experience and annual salary #Read data # df = spark.read.csv("/home/s_kante/spark/data/developers_survey_training.csv", header='true') df = spark.read.csv("/home/student/jac_spark/lecture2/data/Task1_2_3/developers_survey_training.csv", header='true') #Replace IsDeveloper value with integer 1 or 0 df.createOrReplaceTempView("inputData") df1 = spark.sql("SELECT CASE IsDeveloper WHEN 'Yes' THEN 1 ELSE 0 END AS label, CAST(YearsOfExp AS FLOAT) AS YearsOfExp, CAST(Salary AS FLOAT) AS Salary FROM inputData "); #Create feature vector from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler(inputCols=["Salary","YearsOfExp"], outputCol="features") combined = assembler.transform(df1) vector_df = combined.select(combined.label, combined.features) #Estimator: Create an instance LogisticRegression which is an estimator from pyspark.ml.classification import LogisticRegression lr_estimator = LogisticRegression(maxIter=10) print str(LogisticRegression().explainParams()) #Train the model model = lr_estimator.fit(vector_df) #Parameters: Check the parameters used to train the model params = model.extractParamMap() #Pass parameters explicitly while training the model params = {lr_estimator.maxIter:15} model = lr_estimator.fit(vector_df, params) #Transformer: test the model. Transform method will return a dataframe with predictions prediction = model.transform(vector_df) #Save the model on disc # model.save("/home/student/jac_spark/lecture2/data/trained_models/predict_emp_role") model.write().overwrite().save("/home/student/jac_spark/lecture2/data/trained_models/predict_emp_role") #Load a trained model from disc to memory from pyspark.ml.classification import LogisticRegressionModel mymodel = LogisticRegressionModel.load("/home/student/jac_spark/lecture2/data/trained_models/predict_emp_role") prediction = mymodel.transform(vector_df) #QUESTION: How do we predict in actual production environment?
19045f74871fb0fd8f5edb4153e1c76db75c1a28
111110100/my-leetcode-codewars-hackerrank-submissions
/leetcode/countMatches.py
757
3.65625
4
class Solution: def countMatches(self, items: list, ruleKey: str, ruleValue: str) -> int: map = { 'type': 0, 'color': 1, 'name': 2, } return sum([1 for item in items if item[map[ruleKey]] == ruleValue]) class Solution2: def countMatches(self, items: list, ruleKey: str, ruleValue: str) -> int: rules = ['type', 'color', 'name'] return sum((1 for item in items if item[rules.index(ruleKey)] == ruleValue)) answer = Solution2() input = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]] key = 'color' value = 'silver' print(answer.countMatches(input, key, value)) key = 'type' value = 'phone' print(answer.countMatches(input, key, value))
9af700efd4dc47f354bc1ca2805a6ac9caf416db
NhungTu/learninglab
/pandas/pandas_info_gain.py
1,233
4.03125
4
""" Classification is a way to 'bin' observations in order to better understand particular attributes. Optimally, observations in the same 'bin' or subset of the original have a lot in common; and different subsets have little in common. One measure of this is the 'information gain', or reduction of entropy (randomness) among the observations. """ import numpy as np #python's array proccesing / linear algebra library import pandas as pd #data processing / stats library import matplotlib.pyplot as plt #data visualization import csv #write a file with some simple data #the DataFrame is a 2-d object. Think a dict of Series objects # or a spreadsheet. #There are lots of ways to build one. Here, we use a 2-d ndarray # with row and column labels. #(height, weight) data =\ ( (20, 10), (30, 20), (50, 15), (10, 10), (45, 35), (60, 25), (10, 10), (35, 25), (60, 25), (70, 50) ) #define some indices for the rows and columns columns=('height(cm)', 'weight(kg)') #column index index=range(1, len(data) + 1) #row index, starting at 1 #data nda=np.asarray(data) #converts an array-like object to an ndarray #DataFrame constructor df=pd.DataFrame(nda, index=index, columns=columns)
a1fe405ceeb9858642b94d19349d4f9b6e2a3a8c
dawchenlee/dawchengit
/Leetcode/day13对称二叉树.py
2,277
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 23 17:43:40 2019 题目:对称二叉树 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 @author: dawchen """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: # 递归法时间复杂度O(n),空间复杂度O(n) return self.isMirror(root, root) def isMirror(self, leftRoot: TreeNode, rightRoot:TreeNode): if leftRoot == None and rightRoot == None: return True if leftRoot == None or rightRoot == None: return False if leftRoot.val != rightRoot.val: return False return self.isMirror(leftRoot.left, rightRoot.right) and self.isMirror(leftRoot.right, rightRoot.left) # 方法二 队列实现 class Solution: def isSymmetric(self, root): """ 队列 :param root: :return: """ if not root: return True node_queue = [root.left, root.right] # 在空队列中加入左子树和右子树 while node_queue: left = node_queue.pop(0) # 依次弹出两个元素 right = node_queue.pop(0) if not right and not left: # 如果均为空,继续下一个循环 continue if not right or not left: # 如果只有一个为空,返回False return False if left.val != right.val: # 都非空,再判断值是否相等 return False node_queue.append(left.left) # 将两个左右子树的左右子树逆序加入队列 node_queue.append(right.right) node_queue.append(left.right) node_queue.append(right.left) #node_queue.extend([left.left, right.right, left.right, right.left]) #或者用这一句话写 return True
26960f12f803d7d5e57687917b6c9d1da6f1b50d
Eymric/pythonCours
/rh.py
502
3.546875
4
class DateNaissance: def __init__(self, jour, mois, annee): self.jour = jour self.mois = mois self.annee = annee def ToString(self): return print(self.jour,'/',self.mois,'/',self.annee) class Personne: def __init__(self, nom, prenom): self.nom = nom self.prenom = prenom def afficher(self): return pprint('Nom:', self.nom, \n 'Prenom:', self.prenom, \n 'Date de naissance:', DateNaissance() ) a = Personne('A', 'B') a.afficher
18ae5ca84072ae2474f15985d193c7ba6f7334a9
habibanalytics/Python_Exercises
/Programs/SumOfDigits.py
141
3.671875
4
num = input("Enter a number: ") lenth=len(num) index=0 sm=0 while index < lenth: n=int(num[index]) sm=sm+n index+=1 print(sm)
10fbbb4cb6f14a4007e2686f09d0e99a67f51b50
alexandraback/datacollection
/solutions_1484496_0/Python/Staer/sums.py
980
3.71875
4
def find_combos(initial_set): from itertools import combinations for size in xrange(1,num_elements): for combo1 in combinations(initial_set, size): for size2 in xrange(1, num_elements): for combo2 in combinations(initial_set, size2): if combo1 != combo2 and sum(combo1)==sum(combo2): return [combo1, combo2] return None if __name__ == "__main__": import sys f = sys.stdin T = int(f.readline()) for i in xrange(T): data = f.readline().strip().split(' ') num_elements = int(data[0]) initial_set = [] for d in xrange(num_elements): initial_set.append(int(data[d+1])) print "Case #%s:" % (i+1) result = find_combos(initial_set) if result == None: print "Impossible" continue else: for combo in result: # Print the combo on a line as_strings = [] for item in combo: as_strings.append(str(item)) print ' '.join(as_strings)
f6eab9f3837741bf991e6d38eba212316851294f
ravigaur06/PythonProject
/duck_typing_EAFP/eafp.py
462
3.828125
4
person={"name":"karthi","Age":7,"Grade":"second grade"} try: print ("I am {name}.I am {Age} years old.I am studying in {Grade}".format(**person)) except KeyError as e: print ("Missing Key{}".format(e)) l1=[1,2,3,4,5] try: print (l1[6]) except IndexError as e: print (e) import os my_file="/tmp/test.txt" try: f=open(my_file) except IOError as e: print ("File can not be accessed") else: with f: print (f.read())
608718374408fa9124e69f6c8b0c9d34d71bc28c
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4160/codes/1593_1804.py
360
4.125
4
# Coordenadas de A (xa, ya): xa = float(input(" Digite a coordenada xa: ")) ya = float(input(" Digite a coordenada ya: ")) # Coordenadas de B (xb, yb): xb = float(input(" Digite a coordenada xb: ")) yb = float(input(" Digite a coordenada yb: ")) # Distancia entre A e B (d): from math import sqrt d = sqrt ((xb - xa)** 2 + (yb - ya)** 2) print(round(d,3))
b306deb502be381e12e648b4dc4d05e68d528859
anitazhaochen/nowcoder
/线性表/反转链表.py
710
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): if pHead is None or pHead.next is None: return pHead p1 = pHead p2 = pHead.next pHead.next = None while p2: pre = p1 p1 = p2 p2 = p2.next p1.next = pre return p1 node = ListNode(1) node.next = ListNode(2) node.next.next = ListNode(3) node.next.next.next = ListNode(4) node1 = Solution().ReverseList(node) while node1: print(node1.val) node1 = node1.next
b228341b94fe1aec3846dbd8f639907aa84c4777
akshansh2000/project-euler
/py/4.py
308
3.734375
4
def is_palindrome(num): if str(num) == str(num)[::-1]: return 1 return 0 maximum = 0 for outer in range(999, 99, -1): for inner in range(999, 99, -1): if is_palindrome(outer * inner): maximum = outer * inner if outer * inner > maximum else maximum print(maximum)
99d7f7e7d2c95b1f34c52f483d53ef1dbee17f0b
rishinkaku/Software-University---Software-Engineering
/Python Fundamentals/Final_Exam_Prep/05. Easter Bake.py
525
3.890625
4
import math easter_bread = int(input()) sugar_count = 0 flower_count = 0 flower_max = 0 sugar_max = 0 for i in range(1, easter_bread+1): sugar = int(input()) sugar_count += sugar flower = int(input()) flower_count += flower if sugar > sugar_max: sugar_max = sugar if flower > flower_max: flower_max = flower print(f"Sugar: {math.ceil(sugar_count/950)}") print(f"Flour: {math.ceil(flower_count/750)}") print(f"Max used flour is {flower_max} grams, max used sugar is {sugar_max} grams.")
3e5af17bad1c236cf8cbb568a03713ab2ea38e6b
makwana-jaydip/Mini-Projects
/Card Remember/Remember_Card_Game.py
4,790
3.96875
4
#Card Remember Game #0 To 9 Number Card available in hide format when you press the card is turn on and show the card number. #first step is press any card #next step is press different card if card number is matches then it doesn't turns off if doesn't match then after pressing the third card first two card is turns off. #Label turns show that How many steps you take for complete the game. when two card is open then turns count is increase import simplegui import random s1=s2=range(0,10) s3=s1+s2 t=0 state=0 f=1 #For Reset def reset(): global card,s3,t,state t=0 state=0 card=[False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False] random.shuffle(s3) def new_game(): global s3,t,card,state card=[False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False] random.shuffle(s3) t=0 state=0 label.set_text("Turns = "+ str(t)) def mouse_click(pos): global card,state,t,i,i1,i2,f if pos[0]>0 and pos[0]<=49: if card[0]==False: card[0]=True i=0 f=1 elif pos[0]>50 and pos[0]<=99: if card[1]==False: card[1]=True i=1 f=1 elif pos[0]>100 and pos[0]<=149: if card[2]==False: card[2]=True i=2 f=1 elif pos[0]>150 and pos[0]<=199: if card[3]==False: card[3]=True i=3 f=1 elif pos[0]>200 and pos[0]<=249: if card[4]==False: card[4]=True i=4 f=1 elif pos[0]>250 and pos[0]<=299: if card[5]==False: card[5]=True i=5 f=1 elif pos[0]>300 and pos[0]<349: if card[6]==False: card[6]=True i=6 f=1 elif pos[0]>350 and pos[0]<=399: if card[7]==False: card[7]=True i=7 f=1 elif pos[0]>400 and pos[0]<=449: if card[8]==False: card[8]=True i=8 f=1 elif pos[0]>450 and pos[0]<=499: if card[9]==False: card[9]=True i=9 f=1 elif pos[0]>500 and pos[0]<=549: if card[10]==False: card[10]=True i=10 f=1 elif pos[0]>550 and pos[0]<=599: if card[11]==False: card[11]=True i=11 f=1 elif pos[0]>600 and pos[0]<=649: if card[12]==False: card[12]=True i=12 f=1 elif pos[0]>650 and pos[0]<=699: if card[13]==False: card[13]=True i=13 f=1 elif pos[0]>700 and pos[0]<=749: if card[14]==False: card[14]=True i=14 f=1 elif pos[0]>750 and pos[0]<=799: if card[15]==False: card[15]=True i=15 f=1 elif pos[0]>800 and pos[0]<=849: if card[16]==False: card[16]=True i=16 f=1 elif pos[0]>850 and pos[0]<=899: if card[17]==False: card[17]=True i=17 f=1 elif pos[0]>900 and pos[0]<=949: if card[18]==False: card[18]=True i=18 f=1 elif pos[0]>950 and pos[0]<=999: if card[19]==False: card[19]=True i=19 f=1 if f==1: if state==0: state=1 i1=i elif state==1: if i1!=i: state=2 i2=i t+=1 label.set_text("Turns = "+ str(t)) else: if i2!=i and i1!=i: state=1 if s3[i1]!=s3[i2]: card[i1]=False card[i2]=False i1=i f=0 def draw(canvas): global a,b,c,d,s,card,i,t s=8 a=0 b=0 c=50 d=100 for i in s3: canvas.draw_text(str(i),[s,65],66,"White") s+=50 for j in card: if j==False: canvas.draw_polygon([[a,b],[a,d],[c,d],[c,b]],1,"Black","yellow") a+=50 c+=50 frame=simplegui.create_frame("Remember card",1000,100) #Reset Button frame.add_button("RESET",reset) #Count the turns label=frame.add_label("Turns = "+ str(t)) frame.set_draw_handler(draw) frame.set_mouseclick_handler(mouse_click) #start_here new_game() frame.start()
656a9789028288aa1989770a7d60b23a75a65d02
bresslem/ppi
/Serie_5/linear_solvers.py
3,415
3.5
4
""" Author: Bressler_Marisa, Jeschke_Anne Date: 2020_01_03 Solves the given linear equation system Ax = b via forward and backward substitution given the LU-decomposition with full pivoting pr * A * pc = l * u and with CG method. """ #pylint: disable=invalid-name, dangerous-default-value, import-error, unused-import import scipy.linalg as lina import scipy.sparse import numpy as np def solve_lu(pr, l, u, pc, b): """ Solves the linear system Ax = b via forward and backward substitution given the decomposition pr * A * pc = l * u. Parameters ---------- pr : scipy.sparse.csr_matrix row permutation matrix of LU-decomposition l : scipy.sparse.csr_matrix lower triangular unit diagonal matrix of LU-decomposition u : scipy.sparse.csr_matrix upper triangular matrix of LU-decomposition pc : scipy.sparse.csr_matrix column permutation matrix of LU-decomposition b : numpy.ndarray vector of the right-hand-side of the linear system Returns ------- x : numpy.ndarray solution of the linear system """ z = lina.solve_triangular(l.toarray(), np.dot(pr.toarray(), b), lower=True, unit_diagonal=True) y = lina.solve_triangular(u.toarray(), z) x = np.dot(pc.toarray(), y) return x def solve_cg(A, b, x0, params=dict(eps=1e-8, max_iter=1000, min_red=1e-4)): """ Solves the linear system Ax = b via the conjugated gradient method. Parameters ---------- A : scipy.sparse.csr_matrix system matrix of the linear system b : numpy.ndarray right-hand-side of the linear system x0 : numpy.ndarray initial guess of the solution params : dict, optional dictionary containing termination conditions eps : float tolerance for the norm of the residual in the infinity norm max_iter : int maximal number of iterations that the solver will perform. If set less or equal to 0 no constraint on the number of iterations is imposed. min_red : float minimal reduction of the residual in each step Returns ------- str reason of termination. Key of the respective termination parameter. list iterates of the algorithm. First entry is `x0`. list residuals of the iterates Raises ------ ValueError If no termination condition is active, i.e., `eps=0` and `max_iter=0`, etc. """ if params["max_iter"] <= 0 and params["min_red"] <= 0 and params["eps"] <= 0: raise ValueError('No termination condition provided.') iterates = [x0] residuals = [A.dot(x0) - b] d = -residuals[0] for k in range(params["max_iter"]+1): z = A.dot(d) c = np.dot(residuals[k], residuals[k])/np.dot(d, z) iterates.append(iterates[k] + c*d) residuals.append(residuals[k] + c*z) if abs(lina.norm(residuals[k+1], np.inf) - lina.norm(residuals[k], np.inf)) < params["min_red"]: return "min_red", iterates, residuals if lina.norm(residuals[k+1], np.inf) < params["eps"]: return "eps", iterates, residuals beta = (np.dot(residuals[k+1], residuals[k+1])/np.dot(residuals[k], residuals[k])) d = -residuals[k+1] + beta*d return "max_iter", iterates, residuals
55ff891db63d3c457107ccaf8cbd864dd880959b
bthakr1/Faster_Pandas
/Candies.py
436
3.96875
4
candies = [2,3,5,1,3] extraCandies = 3 def kidsWithCandies(candies,extraCandies): maxCandies = max(candies) result = [] for i in range(len(candies)): if candies[i] + extraCandies >= maxCandies: result.append(True) else: result.append(False) return result def inplaceKidsWithCandies(candies,extraCandies): return [candy + extraCandies >= max(candies) for candy in candies]
aa386b27b7777e49086cd40a1b33a85d342ec31d
AttilaAV/szkriptnyelvek
/harmadik_o/palindrom_it.py
240
4.125
4
#!/usr/bin/env python3 def palindrome(s): return s == s[::-1] def main(): s = input("Enter a string: ") ans = palindrome(s.lower()) if ans: print("Palindrome") else: print("Not Palindrome") if __name__ == "__main__": main()
51eea69b91543915042008fb9e9123fc336f916b
BretFarley129/Hospital
/hospital.py
1,257
3.8125
4
class Patient(object): def __init__(self, idNum, name, allergies): self.id = idNum self.name = name self.allergies = allergies self.bed = 0 def display(self): print "" print self.id print self.name print self.allergies print self.bed class Hospital(object): def __init__(self,name): self.patients = [] self.name = name self.capacity = 3 def admit(self, p): if len(self.patients) < self.capacity: self.patients.append(p) p.bed = len(self.patients) print "welcome to the hospital" else: print "sorry u gon die" return self def discharge(self, p): p.bed = 0 self.patients.remove(p) print "get out of the hospital" return self def displayPeople(self): print "PATENTS:" for i in self.patients: i.display() return self p1 = Patient(1001, "Jon", "peanut") p2 = Patient(2002, "Alice", "gatorade") p3 = Patient(3003, "Zeke", "hot sauce") p4 = Patient(4004, "Linden", "doritos") Kaiser = Hospital("Kaiser") Kaiser.admit(p1).admit(p2).admit(p3).admit(p4).discharge(p3).displayPeople()
e3af53856bf058051588397292d4271088cba855
francosorbello/Python-Can
/palabras.py
3,346
3.65625
4
from algo1 import * from libreriafinal import * def imprimir(L): node=L.head while node!=None: imprimirLIST(node.value) node=node.nextNode def comparoyordeno(pal1,pal2,bigL): if pal1.value>pal2.value: aux=bigL.value bigL.value=bigL.nextNode.value bigL.nextNode.value=aux return if pal1.value==pal2.value and pal1.nextNode != None and pal2.nextNode != None:#pal1/2.nextNode != None se asegura que no haya problemas si las palabras son iguales. comparoyordeno(pal1.nextNode,pal2.nextNode,bigL)#si son la misma letra, vuelvo a llamar a la funcion con los siguientes nodos return def ordeno(Lwords): wordnodeaux=Lwords.head while wordnodeaux !=None: wordnode=Lwords.head while wordnode.nextNode != None: l1=wordnode.value#accedo a la lista del nodo l2=wordnode.nextNode.value#accedo a la lista del nodo siguiente pal1=l1.head pal2=l2.head comparoyordeno(pal1,pal2,wordnode) wordnode=wordnode.nextNode wordnodeaux=wordnodeaux.nextNode class node: value=None nextNode=None class LinkedList: head=None Lwords=LinkedList()#esta lista guarda las otras listas word1=LinkedList() appendLIST(word1,"h") appendLIST(word1,"o") appendLIST(word1,"l") appendLIST(word1,"a") appendLIST(word1,"a") imprimirLIST(word1) #--# word2=LinkedList() appendLIST(word2,"p") appendLIST(word2,"e") appendLIST(word2,"d") appendLIST(word2,"r") appendLIST(word2,"o") imprimirLIST(word2) #--# word3=LinkedList() appendLIST(word3,"h") appendLIST(word3,"e") appendLIST(word3,"l") appendLIST(word3,"l") appendLIST(word3,"o") imprimirLIST(word3) #--# word4=LinkedList() appendLIST(word4,"c") appendLIST(word4,"o") appendLIST(word4,"m") appendLIST(word4,"o") imprimirLIST(word4) #--# word5=LinkedList() appendLIST(word5,"e") appendLIST(word5,"s") appendLIST(word5,"t") appendLIST(word5,"a") appendLIST(word5,"s") imprimirLIST(word5) #--# word6=LinkedList() appendLIST(word6,"h") appendLIST(word6,"a") appendLIST(word6,"r") appendLIST(word6,"p") appendLIST(word6,"o") imprimirLIST(word6) #--# word7=LinkedList() appendLIST(word7,"a") appendLIST(word7,"l") appendLIST(word7,"g") appendLIST(word7,"o") imprimirLIST(word7) #--# word8=LinkedList() appendLIST(word8,"l") appendLIST(word8,"c") appendLIST(word8,"c") imprimirLIST(word8) #--# word9=LinkedList() appendLIST(word9,"h") appendLIST(word9,"o") appendLIST(word9,"l") appendLIST(word9,"i") appendLIST(word9,"t") appendLIST(word9,"a") imprimirLIST(word9) #--# word10=LinkedList() appendLIST(word10,"h") appendLIST(word10,"o") appendLIST(word10,"l") appendLIST(word10,"o") appendLIST(word10,"t") appendLIST(word10,"i") appendLIST(word10,"t") appendLIST(word10,"a") imprimirLIST(word10) #--# word11=LinkedList() appendLIST(word11,"h") appendLIST(word11,"o") appendLIST(word11,"l") appendLIST(word11,"a") imprimirLIST(word11) #Agrego las listas a otra lista appendLIST(Lwords,word1) appendLIST(Lwords,word2) appendLIST(Lwords,word3) appendLIST(Lwords,word4) appendLIST(Lwords,word5) appendLIST(Lwords,word6) appendLIST(Lwords,word7) appendLIST(Lwords,word8) appendLIST(Lwords,word9) appendLIST(Lwords,word10) appendLIST(Lwords,word11) print("----") ordeno(Lwords) print("Lista ordenada:") imprimir(Lwords)
1648e7e52f67235fb8c029418a31be2f723d7319
JungAh12/BOJ
/4344.py
570
3.5625
4
import sys if __name__ == '__main__': T = sys.stdin.readline().rstrip() for _ in range(int(T)): score = sys.stdin.readline().rstrip() score = score.split(' ') student = int(score[0]) score_sum = 0 for i in range(1, len(score)): score_sum+=int(score[i]) score_sum = score_sum/student st=student for i in range(1, len(score)): if score_sum >= int(score[i]): st-=1 avg = round(float((st/student)*100),3) print('%.3f%s' %(avg,'%'))
15c9b126f5dcfcd6f772c531704fd4c6b9a583fa
artembigdata/lesson_2_home_work
/task_4.py
122
3.671875
4
string = input("введите слова - ").split() for i, word in enumerate(string, 1): print(f'{i} {word[:10]}')
a911d1fc62ed31100370d9ef0699dddd45f4d67b
RutyRibeiro/CursoEmVideo-Python
/Exercícios/utilidadesCeV/dado.py
495
3.890625
4
def substituir(num): if num.find(',') != -1: num=num.replace(',','.') return num def teste (num): try: float(num) except ValueError: return False return True def leiafloat(num): while True: num=substituir(num) testando=teste(num) if testando==True: num=float(num) return num else: print('Digite um valor válido!') num=input('Digite o preço: ')
8bcca92158608be10dd77ba81f6e81457e878cd1
Devalekhaa/deva
/play27.py
119
3.890625
4
d=input() e='' for i in d: if i.isupper(): e+=i.lower() if i.islower(): e+=i.upper() print(e)
f44ea1477741a6e3eaca0cdd436a590127cc8e9a
manbalboy/python-another-level
/python-basic-syntax/Chapter08/04.오버라이딩 클래스 변수.py
912
3.75
4
# 생성자 # : 인스턴스를 만들 때 호출되는 메서드 import random class Monster: max_num = 1000 def __init__(self, name, health, attack): self.name = name self.health = health self.attack = attack Monster.max_num -= 1 def move(self): print("이동하기") class Wolf(Monster): pass class Shark(Monster): def move(self): print("헤엄치기") class Dragon(Monster): # 생성자 오버라이딩 def __init__(self, name, health, attack): super().__init__(name, health, attack) self.skills = ("불뿜기", "꼬리치기", "날개치기") def move(self): print("날기") def skill(self): print(f"{self.name} 스킬사용 {self.skills[random.randint(0, 2)]}") dragon = Dragon("드래곤", 299, 200) dragon.skill() dragon.skill() dragon.skill() dragon.skill() dragon.skill()
12e22b18b2369d092d4bc4b9cd4cc9873820d61a
gunupati/Programs
/Event_Driven_Using_Tkinter/ex1.py
269
3.578125
4
from tkinter import * from tkinter import messagebox top=Tk() top.geometry("100x100") def helloCallBack(event): msg=messagebox.showinfo('Hello Python','Hello World') B=Button(top,text='Hello') B.bind('<Button-1>',helloCallBack) B.place(x=40,y=40) top.mainloop()
7347c543c572f1a3abbfc31a12e478e86c7197e0
abhilshit/bloxorz
/app/position.py
764
3.578125
4
# Copyright (c) 2020. Abhilshit Soni import json class Position: """ A position object depicting position on terrain map. """ def __init__(self, x, y): """ Initialize position based on column (x) row(y) :param x: :param y: """ self.x = x self.y = y def dx(self, d): """ Utility function to shift x by a certain distance d :param d: :return: """ return Position(self.x + d, self.y) def dy(self, d): """ Utility function to shift x by a certain distance d :param d: :return: """ return Position(self.x, self.y + d) def __str__(self): return json.dumps([self.x, self.y])
1b97790207e2a53718591095ca03160fab8ea45f
HussainAther/computerscience
/puzzles/wordtransform.py
2,033
4.0625
4
import numpy as np import enchant d = enchant.Dict("en_US") """ In 1879, Lewis Carroll proposed the following puzzle to the readers of Vanity Fair: transform one English word into another by going through a series of intermediate English words, where each word in the sequence differs from the next by only one substitution. To transform head into tail one can use four intermediates: head → heal → teal → tell → tall → tail. We say that two words v and w are equivalent if v can be transformed into w by substituting individual letters in such a way that all intermediate words are English words present in an English dictionary. Use enchant to check if words are in the dictionary like this d.check("Hello"). """ alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] def eqwords(a, b, s=0): """ Given two words a and b, find out whether they're equivalent. We may find the Lewis Carroll distance between a and b as the smallest number of substitutions needed to transform a into v with all intermediate words still being words in the dictionary. If a and b are not equivalent, return False. s is the number of substitutions. """ for i, j in enumerate(a): # for each index and letter in a p = [] # possible substitutions for k in alphabet: # for each alphabet letter we may substitute if j != k: # if we can substitute this letter for the letter in a tempa = a[:i] + k + s[i + 1:] if d.check(tempa) and tempa != b: p.append(tempa) s += 1 elif d.check(tempa) and tempa == b: return s if p != []: for t in p: eqwords(t, b) return False
c290ec53ccc04672d490d9ed6ded1e5ba3135be4
hmonika/A
/remove_item.py
917
3.6875
4
def remove_one(list_input): print list_input count = 0 while len(list_input) != count: if len(list_input) > (count + 2) and list_input[count]+1 == list_input[count+1] and len(list_input) > (count + 2) and list_input[count+2] == list_input[count] + 2 : list_input.pop(count) elif len(list_input) > (count+1) and list_input[count]+1 == list_input[count+1]: list_input.pop(count) list_input.pop(count) else: count += 1 print list_input def remove_cons_dup(list_input): print list_input count = 0 while len(list_input) != count: if list_input[count] == list_input[count+1]: list_input.pop(count) count += 1 else: count += 1 print list_input
00c22e87a8315daf2cd3cea64e8c98c03f5cdafb
darshancool25/IIIT_Codes
/SY Lab Codes/SEM 3/SEM 3 Python/Assignment 4/A4_2.py
123
3.9375
4
num = int(input("Enter a number : ")) mylist = [i for i in input().split(' ')] print([i for i in mylist if (len(i)>num)])
85c6e9b791e8915c02eb79205bdc6b964ac41305
AbiFranklin/Cellular-Automata
/src/conways.py
5,377
3.703125
4
import pygame, random import pygameMenu import sys from patterns import blinker # Define some colors and other constants BLUE = (66, 87, 245) WHITE = (255, 255, 255) PINK = (242, 172, 241) GRAY = (228, 230, 235) DGRAY = (192, 192, 192) WIN_SIZE = 500 CELL_SIZE = 20 # This sets the margin between each cell MARGIN = 15 assert WIN_SIZE % CELL_SIZE == 0 def new_grid(): grid = {} for y in range(CELL_SIZE): for x in range(CELL_SIZE): grid[x, y] = 0 return grid def color(cell, grid): x = cell[0] x = x * CELL_SIZE y = cell[1] y = y * CELL_SIZE if grid[cell] == 0: pygame.draw.circle(screen,PINK, (x+50, y+20), 10) if grid[cell] == 1: pygame.draw.circle(screen,BLUE, (x+50, y+20), 10) def find_neighbors(cell, grid): neighbors = 0 for x in range(-1,2): for y in range(-1, 2): neighbor_cell = (cell[0] + x, cell[1] + y) if neighbor_cell[0] < CELL_SIZE and neighbor_cell[0] >=1: if neighbor_cell[1] < CELL_SIZE and neighbor_cell[1] >= 0: if grid[neighbor_cell] == 1: if x == 0 and y == 0: neighbors += 0 else: neighbors += 1 return neighbors def life(grid): nex_gen = {} for cell in grid: neighbor_sum = find_neighbors(cell, grid) if grid[cell] == 1: if neighbor_sum < 2: nex_gen[cell] = 0 elif neighbor_sum > 3: nex_gen[cell] = 0 else: nex_gen[cell] = 1 else: if neighbor_sum == 3: nex_gen[cell] = 1 else: nex_gen[cell] = 0 return nex_gen # -------- Main Program Loop ----------- def main(): pygame.init() size = (WIN_SIZE, WIN_SIZE) global screen screen = pygame.display.set_mode(size) screen.fill(WHITE) game = new_grid() if len(sys.argv) == 1 or sys.argv[1] == 'random': for cell in game: game[cell] = random.randint(0,1) elif sys.argv[1] == 'blinker': for cell in blinker: game[cell] = 1 elif sys.argv[1] == 'block': game[(1,1)] = 1 game[(1,2)] = 1 game[(1,7)] = 1 game[(1,8)] = 1 game[(1,13)] = 1 game[(1,14)] = 1 game[(2,1)] = 1 game[(2,2)] = 1 game[(2,7)] = 1 game[(2,8)] = 1 game[(2,13)] = 1 game[(2,14)] = 1 game[(4,1)] = 1 game[(4,2)] = 1 game[(4,7)] = 1 game[(4,8)] = 1 game[(4,13)] = 1 game[(4,14)] = 1 game[(5,1)] = 1 game[(5,2)] = 1 game[(5,7)] = 1 game[(5,8)] = 1 game[(5,13)] = 1 game[(5,14)] = 1 game[(7,1)] = 1 game[(7,2)] = 1 game[(7,7)] = 1 game[(7,8)] = 1 game[(7,13)] = 1 game[(7,14)] = 1 game[(8,1)] = 1 game[(8,2)] = 1 game[(8,7)] = 1 game[(8,8)] = 1 game[(8,13)] = 1 game[(8,14)] = 1 game[(10,1)] = 1 game[(10,2)] = 1 game[(10,7)] = 1 game[(10,8)] = 1 game[(10,13)] = 1 game[(10,14)] = 1 game[(11,1)] = 1 game[(11,2)] = 1 game[(11,7)] = 1 game[(11,8)] = 1 game[(11,13)] = 1 game[(11,14)] = 1 game[(13,1)] = 1 game[(13,2)] = 1 game[(13,7)] = 1 game[(13,8)] = 1 game[(13,13)] = 1 game[(13,14)] = 1 game[(14,1)] = 1 game[(14,2)] = 1 game[(14,7)] = 1 game[(14,8)] = 1 game[(14,13)] = 1 game[(14,14)] = 1 game[(16,1)] = 1 game[(16,2)] = 1 game[(16,7)] = 1 game[(16,8)] = 1 game[(16,13)] = 1 game[(16,14)] = 1 game[(17,1)] = 1 game[(17,2)] = 1 game[(17,7)] = 1 game[(17,8)] = 1 game[(17,13)] = 1 game[(17,14)] = 1 done = False clock = pygame.time.Clock() generations = 0 is_paused = False while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.set_caption("Conway's Game of Life ~ Generation: " + str(generations)) pause_button = pygame.draw.rect(screen, GRAY, (350, 420, 100, 50)) pygame.draw.line(screen, DGRAY, [350, 471], [450, 471], 3) pygame.draw.line(screen, DGRAY, [451, 420], [451, 471], 3) font = pygame.font.SysFont('Arial', 25) label = 'Pause/Play' text = font.render(label, True, (0, 0, 0)) textRect = text.get_rect() textRect.center = (pause_button.center[0], pause_button.center[1]) screen.blit(text, textRect) if event.type == pygame.MOUSEBUTTONDOWN: click_pos = pygame.mouse.get_pos() if pause_button.collidepoint(click_pos): is_paused = not is_paused if not is_paused: game = life(game) for cell in game: color(cell, game) generations += 1 pygame.display.flip() clock.tick(5) pygame.quit() if __name__ == "__main__": main()
4bdc9f2fc05777672453d6f16eea9141803c610d
Moandh81/python-self-training
/tuple/7.py
265
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #Write a Python program to get the 4th element and 4th element from last of a tuple. mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "duck" ,"bull", "sheep") print(mytuple[3]) print(mytuple[len(mytuple) -4])
4c974dd9b5d91ae44e790161750adf8ac54ed8c9
TMJUSTNOW/python-for-everybody-1
/coursera_py4e/programming_foundations_with_python/rename_files.py
579
3.96875
4
import os def rename_files (): #1 get file names from a folder file_list = os.listdir('/Users/JF/Documents/1PROFESSION/PYTHON/Python_WD/prank') print (file_list) saved_path = os.getcwd() print ("Current Working Directory is " +saved_path) os.chdir('/Users/JF/Documents/1PROFESSION/PYTHON/Python_WD/prank') #2 for each file, rename filename for file_name in file_list: print ("Old name - " +file_name) print ("New name - " +file_name.translate(None, "0123456789")) os.rename(file_name, file_name.translate(None, "0123456789")) os.chdir(saved_path) rename_files()
8ec5effda08a122b015a7303c6e9fd84005779ee
rdimaggio/kata
/multi_split/multi_split.py
707
3.875
4
def multi_split(string_to_split, list_of_delimiters): string_to_split = [string_to_split] for each in list_of_delimiters: output = [] for item in string_to_split: result = 0 while result >= 0: old_result = result result = item[result:].find(each) if result >= 0: output.append(item[old_result:result + old_result]) result += len(each) + old_result output.append(item[old_result:]) string_to_split = output return string_to_split print multi_split('ddxy', ['d']) == ['', '', 'xy'] print multi_split('dogxycat', ['og', 'y']) == ['d', 'x', 'cat']
3126c9169436f37d8b9ccf6def73f3e14867c597
Kiet2910/ipsip-project
/Python Practice(11-2018)/Sets.py
2,165
4.25
4
##Symmetric Difference #Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either M or N but do not exist in both. a,b = [set(input().split()) for _ in range(4)][1::2] print(*sorted(a^b, key=int), sep='\n') ##Set .add() #pick the stamps one by one from a stack of country stamps. Find the total number of distinct country stamps. print(len(set([str(input()) for x in range(int(input()))]))) ##Set .symmetric_difference() Operation #You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both. n,s1=int(input()),set(map(int,input().split())) b,s2=int(input()),set(map(int,input().split())) print(len((s1.difference(s2)).union(s2.difference(s1)))) ##Set Mutations #given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set. Your task is to execute those operations and print the sum of elements from set A. if __name__ == '__main__': (_, A) = (int(input()),set(map(int, input().split()))) B = int(input()) for _ in range(B): (command, newSet) = (input().split()[0],set(map(int, input().split()))) getattr(A, command)(newSet) print (sum(A)) ##Check Subset #Task: given two sets, A and B. Your job is to find whether set A is a subset of set B. for i in range(int(input())): _, a = input(), set(map(int, input().split())) _, b = input(), set(map(int, input().split())) print(a.issubset(b)) ##Check Strict Superset #Task: given a set and other sets. Your job is to find whether set A is a strict superset of each of the N sets. #Print True, if A is a strict superset of each of the N sets. Otherwise, print False. #A strict superset has at least one element that does not exist in its subset. a = set(input().split()) print(all(a > set(input().split()) for _ in range(int(input())))) ##
84aef766d85ef4f9f6e9f1d6e7417d5de46ea214
tiagorodriguessimoes/LinguaNatural-Authorship-mp2
/normalizermstopwords.py
1,092
3.59375
4
#!/usr/bin/python # -*- coding: utf-8-*- # Grupo 29 # Joao Pinheiro 73302 # Tiago Simoes 73100 import re import sys import string from nltk.corpus import stopwords def main(): file_path = sys.argv[1] list_strings = [] with open(file_path, 'r') as file: content = file.readlines() for line in content: line_no_punct = separatePunctuation(line) line_no_punct_no_stopwords = removeStopwords(line_no_punct) # Remover paragrafos sem conteudo. if(line_no_punct_no_stopwords != '\n'): list_strings.append(line_no_punct_no_stopwords) for string in list_strings: print string def separatePunctuation(s): # return a string without punctuation list_punctuation = '([:.+^*%\/_,!?(\[\])])' s = re.sub(list_punctuation, r' \1 ', s) s = re.sub('\s{2,}', ' ', s) #print s return s def removeStopwords(string): #returns a string without stopwords stop = set(stopwords.words('portuguese')) list_message = [i for i in string.split() if i not in stop] str_message = '' for word in list_message: str_message += word + ' ' return str_message[:-1] if __name__ == '__main__': main()
3609f25932c6022f36d9a1948c8f12b151c23e83
Jamshid93/TaskBook
/While/w6.py
104
3.671875
4
N=int(input("N=")) if N%2==0: L=2 else: L=1 F=1 while N>=L: F=F*N N=N-2 print(float(F))
641fdd99cef6c038a3ad52ae152baec611038863
HexxGamerDraenor/Ex6-Task
/Desktop/Projects/ex6.py
1,136
4.1875
4
name = input("Name: ") age = int(input("Age: ")) height = int(input("Height(cm): ")) weight = int(input("Weight(kg): ")) eyeCol = input("Eye Colour: ") hairCol = input("Hair Colour: ") if(age < 10): print ("Go get your parent please and ask them to not let you on the computer, silly x") elif(age > 10 or age < 18): print ("Go back to school silly, you shouldn't be playing with this app!") elif(age > 18 or age < 60): print ("You're probably assessing this code, and I thank you for correctly inputting stuff!") if(height < 130): print ("AWWWWWWWWWWWWWWW SMOL CUTE BEAN!") elif(height > 130 or height < 160): print ("Average height boundaries, I pat you nicely") elif(height > 160 or height < 180): print ("waw so tall") else: print ("HEIGHT ERROR WAW") if(weight < 20): print("uhm...you should try and get some help sweetie, you're really light") elif (weight > 20 or weight < 40): print ("Do me a favour and go eat a banana! bananas are great! yay for potassium! x") elif (weight > 40 or weight < 90): print ("yay for average weight!!!!") else: print ("You're doing okay!")
4b299235a7e6fdd7d24d1e3c6c3b666e4e5545f5
philippbechhaus/uda-ipnd-s2
/fill-in-the-blanks.py
9,146
3.5
4
# fill-in-the-blanks # by Philipp quiz_blanks = ["___1___", "___2___","___3___","___4___"] #blank codes in sample texts quiz1_answers = ["theory","GPS","navigation","Earth"] #answers for paragraph_1 quiz2_answers = ["satellite","speed","atomic","nanosecond"] #answers for paragraph_2 quiz3_answers = ["Differential","Kinematik","relative","dilation"] #answers for paragraph_3 paragraph_1 = '''People often ask me "What good is Relativity?" It is a commonplace to think of Relativity as an abstract and highly arcane mathematical ___1___ that has no consequences for everyday life. This is in fact far from the truth. Consider for a moment that when you are riding in a commercial airliner, the pilot and crew are navigating to your destination with the aid of the Global Positioning System ( ___2___ ). Further, many luxury cars now come with built-in ___3___ systems that include ___2___ receivers with digital maps, and you can purchase hand-held ___2___ navigation units that will give you your position on the ___4___ (latitude, longitude, and altitude) to an accuracy of 5 to 10 meters that weigh only a few ounces and cost around $100.''' paragraph_2 = '''The nominal GPS configuration consists of a network of 24 ___1___ s in high orbits around the Earth, but up to 30 or so ___1___ s may be on station at any given time. Each ___1___ in the GPS constellation orbits at an altitude of about 20,000 km from the ground, and has an orbital ___2___ of about 14,000 km/hour (the orbital period is roughly 12 hours - contrary to popular belief, GPS ___1___ s are not in geosynchronous or geostationary orbits). The ___1___ orbits are distributed so that at least 4 ___1___ s are always visible from any point on the Earth at any given instant (with up to 12 visible at one time). Each ___1___ carries with it an ___3___ clock that "ticks" with an accuracy of 1 ___4___ (1 billionth of a second). A GPS receiver in an airplane determines its current position and course by comparing the time signals it receives from a number of the GPS ___1___ s (usually 6 to 12) and trilaterating on the known positions of each ___1___ . The precision achieved is remarkable: even a simple hand-held GPS receiver can determine your absolute position on the surface of the Earth to within 5 to 10 meters in only a few seconds. A GPS receiver in a car can give accurate readings of position, ___2___ , and course in real-time!''' paragraph_3 = '''More sophisticated techniques, like ___1___ GPS (DGPS) and Real-Time ___2___ (RTK) methods, can deliver centimeter-level positions with a few minutes of measurement. Such methods allow GPS and related satellite navigation system data to be used in precision surveying, autodrive systems, and other applications requiring greater position accuracy than achieved with standard GPS receivers.To achieve this level of precision, the clock ticks from the GPS satellites must be known to an accuracy of 20-30 nanoseconds. However, because the satellites are constantly moving ___3___ to observers on the Earth, effects predicted by the Special and General theories of Relativity must be taken into account to achieve the desired 20-30 nanosecond accuracy. Because an observer on the ground sees the satellites in motion ___3___ to them, Special Relativity predicts that we should see their clocks ticking more slowly (see the Special Relativity lecture). Special Relativity predicts that the on-board atomic clocks on the satellites should fall behind clocks on the ground by about 7 microseconds per day because of the slower ticking rate due to the time ___4___ effect of their ___3___ motion.''' # ---prompt--- # Behavior: prompt examines if word is in the list quiz_blanks. If not, function returns None # Input: word can be any String; quiz_blanks are pre-defined and are references inside paragraph_1,2,3 # Output: either word if String is found in quiz_blanks or None if word is not inside quiz_blanks def prompt(word,quiz_blanks): for blank in quiz_blanks: if blank in word: return blank return None # ---change_blank--- # Behavior: change_blank switches all "blanks" in question with the respective "word" inside a "paragraph" # Input: word can be any String, blank can be any String, paragraph can be any String containing >1 words # Output: returns a new list of strings where "word" replaced "blank" def change_blank(word, blank, paragraph): count = 0 newparagraph = paragraph while count < len(newparagraph): if newparagraph[count] in blank: newparagraph[count] = word count = count+1 else: count = count+1 return newparagraph # ---initiation--- # Behavior: initiation sets difficulty of quiz # Input: None # Output: String refering to level of experience def initiation(): beginnerlevel = 1 advancedlevel = 2 expertlevel = 3 print "How do GPS satellites work?" "\n" "Quiz by Philipp Bechhaus" "\n" "\n" while True: try: experience = int(raw_input("How experienced are you?: " "\n" "\n" "Select" "\n" "1 for BEGINNER" "\n" "2 for ADVANCED" "\n" "3 for PRO" "\n" "\n")) except ValueError: print "That's not a number!" else: if beginnerlevel <= experience <= expertlevel: break else: print "We're not there yet.." return experience # ---setting functions--- # Behavior: set_paragraph, set_answerset and goodluck returns a pre-defined set of pararaphs, answers and goodluck sentences based on the level of experience # Input: Integer 1 <= x <= 3 # Output: paragraph, list of quiz answers, good luck sentences def set_paragraph(experience): if experience == 1: return paragraph_1 if experience == 2: return paragraph_2 if experience == 3: return paragraph_3 def set_answerset(experience): if experience == 1: return quiz1_answers if experience == 2: return quiz2_answers if experience == 3: return quiz3_answers def goodluck(experience): if experience == 1: return "You've selected BEGINNER. Let's get started!" "\n" "You have 4 lifelines. Be careful!" "\n" if experience == 2: return "You've selected ADVANCED. Be prepared!" "\n" "You have 4 lifelines. Be careful!" "\n" if experience == 3: return "You've selected PRO. Good luck!" "\n" "You have 4 lifelines. Be careful!" "\n" # ---nextLevel--- # Behavior: prints the (updated) joined solution paragraph # Input: old solution list # Output: new solution paragraph def joinSolution(solution): print "\n" return " ".join(solution) + "\n" + "\n" # ---answerCheck--- # Behavior: checks if the given answer is equal to pos in list of answer_set. If it is, function returns "true", else "false" # Input: replacement-String (must be a quiz_blank), selected list of answers, pos in list, old solution list # Output: String true or String false def answerCheck(replacement,answer_set,pos,solution): try: user_input = str(raw_input("Please insert your answer for " + replacement + ": ")) except ValueError: print "We are looking for words!" else: if user_input == answer_set[pos]: solution = change_blank(user_input,replacement,solution) print "\n" "Good! Correct answer!" "\n" "-" return "true" else: print "\n" "Incorrect, try again!" return "false" # ---game_process--- # Behavior: loops through the solution list, finds quiz_blanks, prompts the quiz and modifies the solution list accordingly once answer is correct and counter is >0 # Input: pre-defined quiz_blanks, selected paragraph and selected list of answers # Output: solution paragraph to quiz or String "Game over" once lifelines are exceeded def game_process(quiz_blanks,paragraph,answer_set): counter = 4 pos = 0 solution = paragraph.split() for word in solution: replacement = prompt(word,quiz_blanks) if counter != 0: if replacement != None: print joinSolution(solution) while counter != 0: answer = answerCheck(replacement,answer_set,pos,solution) if answer == "false": counter = counter - 1 print "You have " + str(counter) + " more lifelines!" "\n" else: pos = pos + 1 break else: return "\n" ":( Game over!" solution = " ".join(solution) print "\n" "\n" "Awesomesauce! You've done it!" "\n" return solution # --- # play is the umbrella function for running a normal game combining functions above def play(quiz_blanks): experience = initiation() paragraph = set_paragraph(experience) answer_set = set_answerset(experience) print goodluck(experience) return game_process(quiz_blanks,paragraph,answer_set) # --- # run game print play(quiz_blanks)
e69d72586bcf1be38abd9ed129bb1831d0eb7093
tcrowell4/adventofcode
/2020/day22_part1.py
1,377
3.640625
4
#!/usr/bin/python # day19_part1.py """ """ import sys import pprint import re import numpy as np def play_cards(p1, p2): num_cards = len(p1) + len(p2) print("Number of cards : {}".format(num_cards)) # if both players have cards then continue playing while len(p1) and len(p2): # draw card p1card = p1.pop(0) p2card = p2.pop(0) if p1card > p2card: p1.append(p1card) p1.append(p2card) else: p2.append(p2card) p2.append(p1card) print("player1 {}".format(p1)) print("player2 {}".format(p2)) if len(p1): winner = p1 else: winner = p2 score_values = [x for x in range(num_cards, 0, -1)] score = 0 for i, _ in enumerate(winner): print(i, winner[i], score_values[i]) score += winner[i] * score_values[i] print("Final Score {}".format(score)) def main(): with open("day22_input.txt", "r") as f: player1, player2 = [row.split("\n") for row in f.read().strip().split("\n\n")] print("player1", player1) print("player2", player2) # sum = process_input(tiles) p1cards = [int(card) for card in player1[1:]] p2cards = [int(card) for card in player2[1:]] print(p1cards) print(p2cards) play_cards(p1cards, p2cards) sys.exit(1) if __name__ == "__main__": main()
a227a685196521b97549d56b57a7a0546e68f90a
Hyun-JaeUng/TIL
/PythonExam/Day8/collectionmgrTest2.py
661
3.578125
4
yoil = ["월", "화", "수", "목","금", "토", "일"] food = ["갈비탕", "순대국", "칼국수", "삼겹살"] menu = zip(yoil, food) print(menu, type(menu)) #type이 , zip 객체임 for y, f in menu: print("%s요일 메뉴 : %s" % (y, f)) print("*"*20) menu = zip(yoil, food) d2 = dict(menu) # 딕셔너리로 for y, f in d2.items(): print("%s요일 메뉴 : %s" % (y, f)) print(d2) print(menu) print("*"*20) zip1 = zip([1, 2, 3], [4, 5, 6]) zip2 = zip([1, 2, 3], [4, 5, 6], [7, 8, 9]) zip3 = zip("abc", "def") #print(list(zip1)) print(list(zip2)) print(list(zip3)) print("이거는 왜 비어있을까?") print(dict(zip1)) print(dict(zip3))
63c533373e7dea736862a053c97378161b398fac
JasonCh17/Tomato
/week2/分割等和子集.py
1,169
3.625
4
class Solution: def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ if sum(nums) %2 ==1:#若和的一半不是偶数,则返回False return False elif len(nums)==2 and nums[0]==nums[1]: #排除[1,1]的情况 return True else: ''' [1,2,3,4],half_num=5 将序列从大到小排序,[4,3,2,1],先把最大的值4放进去sums,从4后面的数里面选择, 4+3>5,则不选3,下一个,4+2>5,跳过下一个,4+1=5,返回True;若遍历到4后面所有的数都不能使4+num[j]=5,则从3开始遍历。 ''' nums.sort(reverse=True) half_nums = sum(nums)/2 for i in range(len(nums)): sums = nums[i] for j in range(i+1,len(nums)): if sums + nums[j] > half_nums: continue elif sums +nums[j] < half_nums: sums = sums +nums[j] else: return True return False
f48e09d0ae8dd35d466777e29ca84bca454f9a31
nirgalili/us-states-quiz
/scoreboard.py
761
3.6875
4
from turtle import Turtle STATES_NUMBER = 50 FONT = ("Courier", 54, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.hideturtle() self.penup() self.color("black") self.goto(0, 280) self.score = 0 def write_new_score(self): argument = f"{self.score}/{STATES_NUMBER}" self.write(argument, False, "center", FONT) def change_score(self): self.clear() self.score += 1 self.write_new_score() def complete_quiz_check(self): if self.score == STATES_NUMBER: self.clear() self.write("Well done! You got all the states right.", False, "center", ("Courier", 24, "normal")) return True
deff55698a008e59cd467bd1a13e358e22ec81d0
qmnguyenw/python_py4e
/geeksforgeeks/python/expert/2_19.py
2,957
4.4375
4
Pandas Groupby and Computing Median The Pandas in Python is known as the most popular and powerful tool for performing data analysis. It because of the beauty of Pandas functionality and the ability to work on sets and subsets of the large dataset. So in this article, we are going to study how pandas Group By functionality works and saves tons of effort while working on a large dataset. Also, we will solve real-world problems using Pandas Group By and Median functionalities. ### **Pandas groupby()** The groupby() method in pandas splits the dataset into subsets to make computations easier. Generally, groupby() splits the data, applies the functionalities, and then combine the result for us. Let’s take an example if we have data on alcohol consumption of different countries and we want to perform data analysis continent-wise, this problem can be minimized using groupby() method in pandas. It splits the data continent-wise and calculates median using the median() method. **Syntax :** > DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, > group_keys=True, squeeze=<object object>, observed=False, dropna=True) **Example 1** : Find the median of alcohol consumption continent-wise on a given dataset. **Dataset:** Drinksbycountry.csv ## Python3 __ __ __ __ __ __ __ # import the packages import pandas as pd # read Dataset data = pd.read_csv("drinksbycountry.csv") data.head() # peform groupby on continent and find median # of total_litres_of_pure_alcohol data.groupby(["continent"])["total_litres_of_pure_alcohol"].median() # peform groupby on continent and find median # of wine_serving data.groupby(["continent"])["wine_servings"].median() --- __ __ **Output :** ![](https://media.geeksforgeeks.org/wp-content/uploads/20201114123613/2.PNG) median of total_litres_of_pure_alcohol ![](https://media.geeksforgeeks.org/wp-content/uploads/20201114123631/3.PNG) median of wine_serving **Example 2:** Find the median of the total population group by age on a given dataset. **Dataset:** WorldPopulationByAge2020.csv ## Python3 __ __ __ __ __ __ __ # import packages import pandas as pd # read Dataset data = pd.read_csv("WorldPopulationByAge2020.csv") data.head() # perform group by AgeGrp and find median data.groupby(["AgeGrp"])["PopTotal"].median() --- __ __ **Output :** ![](https://media.geeksforgeeks.org/wp-content/uploads/20201114125336/5.PNG) Group by Age Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
94fd6ca69f412302be7505f9a1d032e8e5a66027
suprviserpy632157/zdy
/ZDY/Jan_all/pythonbase/January0112/text0112/day0112_test1.py
567
3.859375
4
# 1.编写函数fun,其功能是计算并返回下列多项式的和 # sn=1+1/1!+1/2!+1/3!+…+1/n! # 建议用数学模块中的math.factorical(x)函数 # 求当n=20时,sn的值 # def fun(n): # from math import factorial as fac # s=0 # if n==0: # return 1 # else: # return 1/n*1/fac(n-1) # print("he=",sum(map(fun,range(0,21)))) # return sum([1/fac(x) for x in range(1+n)]) def fun2(n): from math import factorial as fac sn=0 for x in range(0,n+1): sn+=1/fac(x) return sn print(fun2(20))
6129e3089871169ad3dfbe17d78342b17551959d
llewyn-jh/data_structure-algorithm
/py_is_palindrome.py
2,155
4.0625
4
"""Check the Palindrome""" import re import time import collections def is_palindrome_match(string: str) -> bool: """Use the match method of regular expression and slicing""" string = string.lower() string = [char.lower() for char in string if re.match('[a-zA-Z]|[0-9]', char)] return string[::-1] == string def is_palindrome_sub(string: str) -> bool: """User the sub method of regular expression and slicing""" string = string.lower() string = re.sub('[^a-z0-9]', '', string) return string[::-1] == string def is_palindrome_isalnum(string: int) -> bool: """Use the isalnum function and slicing""" string = string.lower() string = [char for char in string if char.isalnum()] return string[::-1] == string def is_palindrome_no_slicing(string: str) -> bool: """Use python while loop""" string = [char.lower() for char in string if char.isalnum()] while len(string) > 1: if string.pop(0) != string.pop(): return False return True def is_palindrome_deque_no_slicing(string: str) -> bool: """Use python while loop and deque""" string: Deque = collections.deque() string = [char.lower() for char in string if char.isalnum()] while len(string) > 1: if string.pop(0) != string.pop(): return False return True if __name__ == "__main__": EXAMPLE = "A man, a plan, a canal: Panama" start = time.time() is_palindrome_match(EXAMPLE) runtime = time.time() - start print(f"Runtime with re match method: {runtime:0.8f}") start = time.time() is_palindrome_sub(EXAMPLE) runtime = time.time() - start print(f"Runtime with re sub method: {runtime:0.8f}") start = time.time() is_palindrome_isalnum(EXAMPLE) runtime = time.time() - start print(f"Runtime with isalnum: {runtime:0.8f}") start = time.time() is_palindrome_no_slicing(EXAMPLE) runtime = time.time() - start print(f"Runtime without slicing: {runtime:0.8f}") start = time.time() is_palindrome_deque_no_slicing(EXAMPLE) runtime = time.time() - start print(f"Runtime with deque: {runtime:0.8f}")
2e7e44cd2b3e8b1ee4321d0e4ee547f6fd489874
sonukrishna/Anandh_python
/chapter_2/q28_enumearate.py
201
4.15625
4
''' the function prints the index and value of the given list ''' def enum(lst): return [(x,lst[y])for x in range(len(lst))for y in range(len(lst))if x==y] aa=list('abrakadabra!') print enum(aa)
d92012c1caca20071c53db233806f68aa624a680
kkkyan/leetcode
/problem-string-easy/58.最后一个单词的长度.py
1,122
3.609375
4
# # @lc app=leetcode.cn id=58 lang=python3 # # [58] 最后一个单词的长度 # # https://leetcode-cn.com/problems/length-of-last-word/description/ # # algorithms # Easy (30.84%) # Likes: 130 # Dislikes: 0 # Total Accepted: 39.1K # Total Submissions: 126.7K # Testcase Example: '"Hello World"' # # 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 # # 如果不存在最后一个单词,请返回 0 。 # # 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 # # 示例: # # 输入: "Hello World" # 输出: 5 # # # class Solution: def lengthOfLastWord(self, s: str) -> int: # arr = s.split() # if len(arr) == 0: # return 0 # return len(arr[-1]) if len(s) == 0: return 0 ret = 0 flag = False # flag指示是否遇见了单词 for i in range(len(s)-1, -1, -1): if s[i] == " ": if flag == False: continue else: break ret += 1 flag = True return ret
26ec638ed1cd5c3cc65dd69956407d9653219468
gabriellaec/desoft-analise-exercicios
/backup/user_139/ch22_2020_03_04_11_28_13_775698.py
102
3.671875
4
a = int(input('Quantos cigaros por dia?') b = int(input('Há quantos anos?') p = (a * 10) * b print(p)
5c20adbd5d94763cc4d374562375d7c11cf71d43
edu-athensoft/cdes1201dataanalysis
/session01/statistics/std.py
686
4.15625
4
import math numstr = input("to find standard deviation, input a set of numbers separated by space: ") try: numlist = numstr.split() num = list(map(float, numlist)) # conv to int mean = math.fsum(num[:]) / len(num) diff = [] i = 0 while i < len(num): square = (mean - num[i]) ** 2 i += 1 diff.append(square) var = math.fsum(diff[:]) std = var ** (1 / 2) print(std) except ValueError: # not num or separated by comma print("please enter valid numbers and separate them by space") except IndexError: # no input print("please enter at least one number") except: print("other error occured, please try again")
70d5f90cb777e2f8e6f3ea024f90d622e2df404e
althafuddin/python
/Python_Teaching/introduction/test_cities.py
705
3.96875
4
import unittest from city_functions import get_city_name class TestCityNames(unittest.TestCase): """Test the format given city name and country name""" def test_city_country(self): """Test the fucntion to work with 'hyderabad india'?""" formatted_name = get_city_name('hyderabad', 'india') self.assertEqual(formatted_name, 'Hyderabad, India') def test_city_country_population(self): """Test the function to work with 'seattle usa 100000' ?""" formatted_name = get_city_name('seattle', 'usa', population='100000') self.assertEqual(formatted_name, 'Seattle, Usa - Population 100000') if __name__ == '__main__': unittest.main()
862dd49905db491d5086140514ef7251f7a03031
pp2095/BE-Project
/create_dict.py
1,882
3.515625
4
import csv, json from collections import OrderedDict def make_json(f1,f2): #csvfile=open("maria_results1.csv","r") csvfile=open(f1,"r") #print "OPENED CLUSTER RESULTS" csvreader = csv.reader(csvfile, delimiter=',') emos=['joy','optimism','admiration','acceptance','fear','apprehension','amazement','surprise','loathing','disgust','rage','anger','anticipation','interest','sadness','disapproval','appreciation','grief','love'] main_json=OrderedDict() main_json["name"]="flare" main_json["description"]="flare" main_json["children"]=[] #{"name":"flare","description":"flare","children":[]} main_children=[] for item in emos: dict=OrderedDict() dict["name"]=item dict["description"]="Tweets classified as "+item dict["children"]=[] main_json["children"].append(dict) #print main_json for row in csvreader: #print len(row) #print "Making JSON for "+row[0] tweet_description=OrderedDict() tweet_wise_emo=[] i=0 while i<19: dict=OrderedDict() dict["name"]=emos[i] dict["description"]="How much "+emos[i]+" is present in the tweet" dict["size"]=row[i+2] i=i+1 tweet_wise_emo.append(dict) #print tweet_wise_emo tweet_description["name"]=unicode(row[0],errors='ignore') tweet_description["description"]="A classified tweet" tweet_description["children"]=tweet_wise_emo #print tweet_description for item in main_json["children"]: #print item if item["name"]==row[1]: item["children"].append(tweet_description) #print "appended to "+row[1] #print item #print "FINAL!!!!!!!!!!!!!!!!!!" #print 'MAIN JSON IS:' #print main_json output_json = json.dumps(main_json) #print output_json #with open('D:/xampp/htdocs/BE Project Vis/flare1.json','w') as outfile: with open('D:/xampp/htdocs/BE Project Vis/'+f2,'w') as outfile: json.dump(main_json,outfile)
e1dff830aafb8f6d14e7e94bc45fbb17011a1b97
lucascoelho33/ifpi-ads-algoritmos2020
/VETORES - ALONGAMENTO/alongamento.py
2,353
3.9375
4
def main(): numero = int(input('Quantos números? ')) vetor = gerar_vetor(numero, -1) print(vetor) for pos in range(len(vetor)): vetor[pos] = int(input('Num: ')) print(vetor) qtd_pares = contar_pares(vetor) qtd_impares = contar_impares(vetor) qtd_positivo = contar_positivo(vetor) qtd_negativo = contar_negativo(vetor) print(f'Pares: {qtd_pares}') print(f'Ímpares: {qtd_impares}') print(f'Positivos: {qtd_positivo}') print(f'Negativos: {qtd_negativo}') print('') vetor_transformado = transformar(vetor) print('>> Vetor Transformado <<') print(vetor) qtd_pares = contar_pares(vetor_transformado) qtd_impares = contar_impares(vetor_transformado) qtd_positivo = contar_positivo(vetor_transformado) qtd_negativo = contar_negativo(vetor_transformado) print(f'Pares: {qtd_pares}') print(f'Ímpares: {qtd_impares}') print(f'Positivos: {qtd_positivo}') print(f'Negativos: {qtd_negativo}') print('') media = calcular_media(vetor_transformado) print(f'Média: {media}') def gerar_vetor(num, valor): return [valor] * num def contar_pares(vetor): qtd = 0 for numero in vetor: if eh_par(numero): qtd += 1 return qtd def eh_par(numero): if numero % 2 == 0: return numero def contar_impares(vetor): qtd = 0 for numero in vetor: if eh_impar(numero): qtd += 1 return qtd def eh_impar(numero): if numero % 2 != 0: return numero def contar_positivo(vetor): qtd = 0 for numero in vetor: if eh_positivo(numero): qtd += 1 return qtd def eh_positivo(numero): if numero > 0: return numero def contar_negativo(vetor): qtd = 0 for numero in vetor: if eh_negativo(numero): qtd += 1 return qtd def eh_negativo(numero): if numero < 0: return numero def transformar(vetor): for i in range(len(vetor)): if vetor[i] > 0: vetor[i] = vetor[i] * 2 else: vetor[i] = vetor[i] / 2 return vetor def calcular_media(vetor): somatorio = 0 for valor in vetor: somatorio += valor media = somatorio / len(vetor) return media main()
58a7b172b7f719eca24e0f98780dc5056daa0a3e
foureyes/csci-ua.0479-spring2021-001
/assignments/hw03/grade.py
1,073
4.5
4
""" grade.py ===== Translate a numeric grade to a letter grade. 1. Ask the user for a numeric grade. 2. Use the table below to calculate the corresponding letter: 90-100 - A 80-89 - B 70-79 - C 60-69 - D 0-59 - F 3. Print out both the number and letter grade. 4. If the value is not numeric, allow the error to happen. 5. However, if the number is not within the ranges specified in the table, output: "Could not translate %s into a letter grade" where %s is the numeric grade" __COMMENT YOUR SOURCE CODE__ by * briefly describing parts of your program * including your name, the date, and your class section at the top of your file (above these instructions) Example Output (consider text after the ">" user input): Run 1: ----- What grade did you get? > 59 Number Grade: 59 Letter Grade: F Run 2: ----- What grade did you get? > 89 Number Grade: 89 Letter Grade: B Run 3: ----- What grade did you get? > 90 Number Grade: 90 Letter Grade: A Run 4: ----- What grade did you get? > -12 Couldn't translate -12 into a letter grade """
371c1cae2d4f48126b87feb8f4396bc80790eab2
ctucker02/CircuitPython
/Servo_cap_touch.py
951
3.609375
4
import time import board import touchio import pulseio #necessary libraries from adafruit_motor import Servo pwm = pulseio.PWMOut(board.A2, duty_cycle= 2 ** 15, frequency=50) #how long the pulses are and how many there are my_servo = Servo.Servo(pwm) #defining servo touch_A0 = touchio.TouchIn(board.A0) #making touch pin at A0 touch_A5 = touchio.TouchIn(board.A5) #making touch pin at A5 my_servo.angle = 0 #start at 0 x = 5 q = 5 while True: if touch_A0.value and x>0: #touch value from 0-90 print('forward') my_servo.angle = x #servo angle = 5 x = x + q #when touch_A0 is touched the servo will move 5 degrees forward time.sleep(.10) if touch_A5.value and x<180: #touch value from 90-180 print('backward') my_servo.angle = x #servo angle = 5 x = x - q #when touch_A5 is touched the servo will move 5 degrees backward time.sleep(.10)
59fe125c05f6a8ee110d4a94f0dfd77fc202ef37
yongwang07/leetcode_python
/vertical_order.py
1,903
3.515625
4
from collections import defaultdict, Counter from binary_tree import Node from operator import itemgetter def vertical_order(root): m = defaultdict(list) def helper(node, level): if node is None: return m[level].append(node.value) helper(node.left, level - 1) helper(node.right, level + 1) helper(root, 0) return list(map(itemgetter(1), sorted(m.items(), key=itemgetter(0)))) def remove_duplicate(s): visited, count, st = set(), Counter(s), [] for c in s: if c in visited: continue while len(st) > 0 and ord(c) < ord(st[-1]) and count[st[-1]] > 0: visited.remove(st.pop()) count[c] -= 1 visited.add(c) st.append(c) return ''.join(st) def generate_abbre(word): tmp, res = [], [] def helper(start): if start == len(word): res.append(''.join(tmp)) return tmp.append(word[start]) helper(start + 1) tmp.pop() merge = False if len(tmp) > 0 and tmp[-1].isdigit(): tmp[-1] = str(int(tmp[-1]) + 1) merge = True else: tmp.append(str(1)) helper(start + 1) if merge: tmp[-1] = str(int(tmp[-1]) - 1) else: tmp.pop() helper(0) return res if __name__ == '__main__': print('leetcode 313, 320') root = Node(3) root.left = Node(9) root.right = Node(20) root.right.left = Node(15) root.right.right = Node(7) print(vertical_order(root)) root = Node(3) root.left = Node(9) root.left.left = Node(4) root.left.right = Node(5) root.right = Node(20) root.right.left = Node(2) root.right.right = Node(7) print(vertical_order(root)) print(remove_duplicate('bcabc')) print(remove_duplicate('cbacdcbc')) print(generate_abbre('word'))
7ad7a58844d9e95fc4225b2f6bf5c6867a3dd0fd
schakkirala/workspace
/Guttag3.1.py
154
3.71875
4
i = int(raw_input('Enter an int: ')) root = 2 for pwr in range(0,abs(6)+1): print root, ' ', pwr if (root**pwr == abs(i)): print root, '::: ', pwr
9fcfba3bb243cd4d2cc4aeef3aef33f1684793e2
Florisbruinsma/GoGame
/GoGame.py
14,352
3.78125
4
import numpy as np import random class ObservationSpace: def __init__(self, boardSize=5): self.shape = (boardSize*boardSize,) class ActionSpace: def __init__(self, boardSize=5): self.n = boardSize*boardSize class GoGame: def __init__(self, boardSize=5, maxTurns=30): """ initiates all variables needed for Parameters ---- boardSize : int size of the dimensions of the board Maxturns : when using the step functtion for rl this is the amount of turn afterw hich a game will be ended Returns ---- nothing """ self.boardSize = boardSize#dimensions of the board self.maxTurns = maxTurns#maximum amount of turns that can be taken with the step function self.currentBoard = np.zeros((boardSize,boardSize), dtype = int)#current state of the board as 2d list self.boardHistory = np.expand_dims(np.zeros((boardSize,boardSize), dtype = int),axis=0)#history of all the turns as 3d list, first axis is turn amount self.boardCheck = np.zeros((self.boardSize,self.boardSize), dtype = int)#used to make sure places on the board dont get checked twice self.players = [0,1,2]# neutral, p1, p2 self.captures = [0,0,0]#amount of stones that where captures from the corresponding player self.scores = [0,0,0]#scores of the players self.groups = [],[],[] self.passMove = [0,0] self.currentTurn = 0 self.action_space = ActionSpace(boardSize) self.observation_space = ObservationSpace(boardSize) def restartGame(self): """ resets all changed values, thereby restarting the game Returns ---- nothing """ # for comments on the variables look at the __init__ self.currentBoard = np.zeros((self.boardSize,self.boardSize), dtype = int) self.boardHistory = np.expand_dims(np.zeros((self.boardSize,self.boardSize), dtype = int),axis=0) self.boardCheck = np.zeros((self.boardSize,self.boardSize), dtype = int) self.captures = [0,0,0] self.scores = [0,0,0] self.groups = [],[],[] self.passMove = [0,0] self.currentTurn = 0 def printBoard(self, specific_board=False): """ print the given game board with player 1 as x and player 2 as o Parameters ---- specific_board : 2d list with shape boardSize,boardSize Returns ---- nothing """ if(not specific_board): board = self.currentBoard for row in range(self.boardSize): for col in range(self.boardSize): if(board[row][col] == 0): print('-',end='') elif(board[row][col] == 1): print('x',end='') elif(board[row][col] == 2): print('o',end='') print('') print('') def revertBoard(self, turn): """ revert the current board back to the given turn Parameters ---- turn : int, value of the turn you want to revert to Returns ---- nothing """ if(self.currentTurn <= turn): return else: self.currentBoard = self.boardHistory[turn] self.currentTurn = turn self.boardHistory = self.boardHistory[:turn+1] def takeTurn(self, coord, player, passMove = False): """ handles everything that happens during a turn Parameters ---- coord : tuple, coord is used as (row,col) player: int, number of the player, can be 1 or 2 passMove: bool set this as true if you want to pass Returns ---- done: bool true if game is over """ if(passMove == True): self.passMove[player] = True if(self.passMove[0] == True and self.passMove[1] == True): return True else: return False if(not self.checkValidMove(coord,player)): return False self.currentBoard[coord] = player self.resolveTurn(player) self.boardHistory = np.vstack((self.boardHistory,np.expand_dims(self.currentBoard,axis=0))) self.currentTurn += 1 self.updateScore() return True def resolveTurn(self,player): """ resolves everything that happens after a stone is placed. Like stone captures, and tries to find the current groups, for the score Parameters ---- player : int can be 1 or 2 is used to determine which pieces to capture first Returns ---- nothing """ # assign every space on the board to a chain capture = False chains = [],[],[] self.groups = [],[],[] first_player = 1 if (player==1) else 2#which player played this turn, so captures can be checked first for the oponent second_player = 2 if (player==1) else 1 self.boardCheck = np.zeros((self.boardSize,self.boardSize), dtype = int) #create and extend chains for row in range(self.boardSize): for col in range(self.boardSize): if(self.boardCheck[row][col] == 0): chains[self.currentBoard[row][col]].append(self.extendChains((row,col),self.currentBoard[row][col])) #check for captures for chain in chains[second_player]: if(len(self.getLiberties(chain)) == 0): self.captures[second_player] += len(chain) self.removeStones(chain) capture = True for chain in chains[first_player]: if(len(self.getLiberties(chain)) == 0): self.captures[first_player] += len(chain) self.removeStones(chain) capture = True if capture: self.resolveTurn(player)#something has changed on the board so we will check for captures again return #add some of the neutral chains to player groups self.groups[1].extend(chains[1]) self.groups[2].extend(chains[2]) for chain in chains[0]: connection = [] for coord in chain: connection.extend(self.checkNeighbours(coord)) if (not(2 in connection) and 1 in connection): self.groups[1].append(chain) elif (not(1 in connection) and 2 in connection): self.groups[2].append(chain) else: self.groups[0].append(chain) def checkNeighbours(self,coord): """ check the neighbours of a coordinate Parameters ---- coord : tuple, coord is used as (row,col) Returns ---- return a list with [top,right,down,left] neighbour with value 0,1,2 or 3 with 3 being oob """ connections = [(coord[0]+1,coord[1]),(coord[0],coord[1]+1),(coord[0]-1,coord[1]),(coord[0],coord[1]-1)] neighbours = [] for coord in connections: if(max(coord)>=self.boardSize or min(coord) < 0): neighbours.append(3) else: neighbours.append(self.currentBoard[coord]) return neighbours def checkValidMove(self, coord, player): """ check if a move is valid Parameters ---- coord : tuple, coord is used as (row,col) player: int, number of the player, can be 1 or 2 Returns ---- bool """ # check if coord is within bounds if(max(coord) >= self.boardSize or min(coord) < 0): return False # check if position is already filled if(self.currentBoard[coord] != 0): return False neighbours = self.checkNeighbours(coord) # check for suicide move if(not((player == 1 and (1 in neighbours or 0 in neighbours)) or (player == 2 and (2 in neighbours or 0 in neighbours)))): return False return True def extendChains(self,coord,val,chain_list=None): """ use recursion to find every stone in the chain that is connected from the coordinate Parameters ---- coord : tuple, coord is used as (row,col) val: int, state of a stone, can be 0, 1 or 2 Returns ---- list of the full chain """ if(chain_list==None): chain_list=[] chain_list.append(coord) self.boardCheck[coord] = 1#do this board check to make sure the first coord isn't added dubbel new_list = [] connections = [(coord[0]+1,coord[1]),(coord[0],coord[1]+1),(coord[0]-1,coord[1]),(coord[0],coord[1]-1)] for coord in connections: if(max(coord)<self.boardSize and min(coord) >= 0 and self.boardCheck[coord] == 0 and self.currentBoard[coord] == val): new_list.append(coord) self.boardCheck[coord] = 1 for coord in new_list: chain_list.extend(self.extendChains(coord,val)) return chain_list def getLiberties(self, chain): """ return a list of all liberties of the given chain Parameters ---- chain : list of tuple coordinates (row,col) Returns ---- list of all the coordinates of liberties """ liberties = [] for stone in chain: connections = [(stone[0]+1,stone[1]),(stone[0],stone[1]+1),(stone[0]-1,stone[1]),(stone[0],stone[1]-1)] for coord in connections: if(max(coord)<self.boardSize and min(coord) >= 0 and self.currentBoard[coord] == 0): if(not liberties.count(coord)): liberties.append(coord) return liberties def removeStones(self, chain): """ removes all stones in given chain from the board Parameters ---- chain : list of tuple coordinates (row,col) Returns ---- nothing """ for coord in chain: self.currentBoard[coord] = 0 def updateScore(self): """ counts the total score per player, you get a point per stone in your group and get 1 point substracted per captured stone Parameters ---- None Returns ---- the scores of all players """ for player in self.players: total_amount = 0 for group in self.groups[player]: total_amount += len(group) total_amount -= self.captures[player] self.scores[player] = total_amount return self.scores ##-----helper functions-----## def getAllValidMoves(self, player): """ creates a list of all valid possible moves for the player Parameters ---- player: int, number of the player, can be 1 or 2 Returns ---- list of all the coord's of valid moves for that player """ moves = [] for row in range(self.boardSize): for col in range(self.boardSize): coord = (row,col) if(self.currentBoard[coord] == 0): neighbours = self.checkNeighbours(coord) if(((player == 1 and (1 in neighbours or 0 in neighbours)) or (player == 2 and (2 in neighbours or 0 in neighbours)))): moves.append(coord) return moves def getRandomMove(self,player): """ gives you a random alid move for the selected player Parameters ---- player: int, number of the player, can be 1 or 2 Returns ---- coord : tuple, coord is used as (row,col) """ moves = self.getAllValidMoves(player) return random.choice(moves) def coordToFlatMove(self, coord): """ converts a coord tupple to an int Parameters ---- coord : tuple, coord is used as (row,col) Returns ---- flat_move : int value of the given coord """ flat_move = coord[0]*self.boardSize+coord[1] return flat_move def flatMoveToCoord(self, flat_move): """ converts an int to a coord tupple Parameters ---- flat_move : int value of the given coord Returns ---- coord : tuple, coord is used as (row,col) """ coord=[0,0] coord[0] = int(flat_move / self.boardSize) coord[1] = flat_move % self.boardSize if(coord[0]>=self.boardSize or coord[1]>=self.boardSize): coord = [0,0] return tuple(coord) def makeRandomMove(self, player): """ makes a random move for the given player Parameters ---- player: int, number of the player, can be 1 or 2 Returns ---- done: bool true if game is over """ return self.takeTurn(self.getRandomMove(player), player) ##-----functionalities to make this class feel just like an open ai gym envirement-----## def step(self, action): reward = 0 coord = self.flatMoveToCoord(action) if(not self.takeTurn(coord, 1)): reward = -100 self.makeRandomMove(2)#let ai take random move state = self.currentBoard.flatten() if(reward == 0): reward = self.scores[1] - self.scores[2] if(self.currentTurn >= self.maxTurns): done = True else: done = False info = "Go game" return state, reward, done, info def reset(self): self.restartGame() state = self.currentBoard.flatten() return state def render(self): self.printBoard() # TODO """ Create a handicap system, based on board size Enable or disable if turns should be forced to be alternately between the players Setting an amount of handicap points for going second visual interface class coin toss funcion to decide who goes first """
887aae9683e0db9948b9ef8f22ae99108945d1fa
KongChan1988/51CTO-Treasure
/Python_Study/第一模块学习/Day1/New_dir/Login.py
339
3.890625
4
# -*- coding:utf-8 -*- # Author:D.Greay username = 'alex' password = '123' _username = input('请输入用户名: ') _password = input('请输入密码: ') if _username == username and _password == password: print('Welcome user.txt {name} Login '.format(name = username.title())) else: print('Please enter the correct username')
bc4d041ac984cceda4e15068d454fd647a3e57cd
kunal27071999/KunalAgrawal_week_1
/Week_1_basic/Week_1_basic_Q16.py
172
4.1875
4
"""WAP to print swap two numbers without using the third variable""" a = 1 b = 2 print("Before swap :", a, b) a = a + b b = a - b a = a - b print("After swap :", a, b)
991059d068e28baa2f8988e46d0fe8e54806a95e
ValeriaLco/Python-Class
/Ejercicios/Strings/crossing_words.py
367
3.578125
4
import math def cruzando_palabras(palabra1, palabra2): mitad1 = math.ceil(len(palabra1) / 2) mitad2 = math.ceil(len(palabra2) / 2) string1 = palabra1[:mitad1] + palabra2[mitad2:] string2 = palabra1[mitad1:] + palabra2[:mitad2] print(string1) print(string2) string1 = input() string2 = input() cruzando_palabras(string1, string2)
36abf24931c9784fe910ad50af7ef4fe373be471
b3ngmann/python-pastime
/ps10/ps10.py
14,689
3.71875
4
# 6.00x Problem Set 10 # Graph optimization # Finding shortest paths through MIT buildings # import string, time # This imports everything from `graph.py` as if it was defined in this file! from graph import * # # Problem 2: Building up the Campus Map # # Before you write any code, write a couple of sentences here # describing how you will model this problem as a graph. # This is a helpful exercise to help you organize your # thoughts before you tackle a big design problem! # def load_map(mapFilename): """ Parses the map file and constructs a directed graph Parameters: mapFilename : name of the map file Assumes: Each entry in the map file consists of the following four positive integers, separated by a blank space: From To TotalDistance DistanceOutdoors e.g. 32 76 54 23 This entry would become an edge from 32 to 76. Returns: a directed graph representing the map """ # TODO print "Loading map from file..." # result = WeightedDigraph() # with open(mapFilename) as f: # for line in f: # src, dest, total, outdoors = line.split() # weights = {'total': int(total), 'outdoors': int(outdoors)} # src = Node(src) # dest = Node(dest) # edge = WeightedEdge(src, dest, weights['total'], weights['outdoors']) # try: # result.addNode(src) # except ValueError: # pass # try: # result.addNode(dest) # except ValueError: # pass # result.addEdge(edge) # return result campus_graph = WeightedDigraph() with open(mapFilename, 'r') as map_file: for line in map_file.readlines(): src,dest,total_distance,outdoors_distance = line.split() start_node = Node(src) end_node = Node(dest) if not campus_graph.hasNode(start_node): campus_graph.addNode(start_node) if not campus_graph.hasNode(end_node): campus_graph.addNode(end_node) edge = WeightedEdge(start_node,end_node,int(total_distance),int(outdoors_distance)) campus_graph.addEdge(edge) return campus_graph def calc_total_distance(path): return sum(edge.total_distance for edge in path) def calc_distance_outdoors(path): return sum(edge[2] for edge in path) def is_node_visited(node, path): for edge in path: if node in (edge.getSource(), edge.getDestination()): return True return False def get_node_list(path): visited = [str(edge.getSource()) for edge in path] visited.append(str(path[-1].getDestination())) return visited def timeit(func): def _timeit(*args, **kwargs): start = time.time() try: result = func(*args, **kwargs) except ValueError: raise else: return result finally: duration = time.time() - start print '{0} ran for: {1:0.5f} secs.'.format(func.__name__, duration) return _timeit # mitMap = load_map("mit_map.txt") # print isinstance(mitMap, Digraph) # # Problem 3: Finding the Shortest Path using Brute Force Search # # State the optimization problem as a function to minimize # and what the constraints are # @timeit def bruteForceSearch(digraph, start, end, maxTotalDist, maxDistOutdoors): """ Finds the shortest path from start to end using brute-force approach. The total distance travelled on the path must not exceed maxTotalDist, and the distance spent outdoor on this path must not exceed maxDistOutdoors. Parameters: digraph: instance of class Digraph or its subclass start, end: start & end building numbers (strings) maxTotalDist : maximum total distance on a path (integer) maxDistOutdoors: maximum distance spent outdoors on a path (integer) Assumes: start and end are numbers for existing buildings in graph Returns: The shortest-path from start to end, represented by a list of building numbers (in strings), [n_1, n_2, ..., n_k], where there exists an edge from n_i to n_(i+1) in digraph, for all 1 <= i < k. If there exists no path that satisfies maxTotalDist and maxDistOutdoors constraints, then raises a ValueError. """ def _gen_paths(original_path, edges): yield original_path for edge in edges: if not is_node_visited(edge.getDestination(), original_path): yield original_path + [edge] stack = [[edge] for edge in digraph.childrenOf(Node(start))] valid_paths = [] while stack: path = stack.pop(-1) #next_edges = digraph.childrenOf(path[-1]) next_edges = digraph.edgesFrom(path[-1]) for new_path in _gen_paths(path, next_edges): if calc_distance_outdoors(new_path) <= maxDistOutdoors: if new_path[-1].getDestination().getName() == end: valid_paths.append(new_path) elif new_path is not path: stack.append(new_path) shortest, min_distance = None, maxTotalDist for path in valid_paths: distance = calc_total_distance(path) if distance < min_distance: shortest, min_distance = path, distance if shortest is None: raise ValueError() return get_node_list(shortest) # start = Node(start) # end = Node(end) # path = [start] # queue = digraph.childrenOf(path[-1])[:] # total = [] # outdoors = [] # result = [] # while queue: # edge = queue.pop() # parent = edge.getSource() # next_node = edge.getDestination() # weights = edge.getWeights() # while path[-1] != parent: # path.pop() # total.pop() # outdoors.pop() # test1 = next_node not in path # test2 = sum(total) + weights['total'] <= maxTotalDist # test3 = sum(outdoors) + weights['outdoors'] <= maxDistOutdoors # if test1 and test2 and test3: # total.append(weights['total']) # outdoors.append(weights['outdoors']) # path.append(next_node) # if next_node == end: # maxTotalDist = sum(total) + 1 # result = path[:] # else: # queue.extend(digraph.childrenOf(path[-1])) # if result: # return [n.getName() for n in result] # else: # raise ValueError # # Problem 4: Finding the Shorest Path using Optimized Search Method # @timeit def directedDFS(digraph, start, end, maxTotalDist, maxDistOutdoors): """ Finds the shortest path from start to end using directed depth-first. search approach. The total distance travelled on the path must not exceed maxTotalDist, and the distance spent outdoor on this path must not exceed maxDistOutdoors. Parameters: digraph: instance of class Digraph or its subclass start, end: start & end building numbers (strings) maxTotalDist : maximum total distance on a path (integer) maxDistOutdoors: maximum distance spent outdoors on a path (integer) Assumes: start and end are numbers for existing buildings in graph Returns: The shortest-path from start to end, represented by a list of building numbers (in strings), [n_1, n_2, ..., n_k], where there exists an edge from n_i to n_(i+1) in digraph, for all 1 <= i < k. If there exists no path that satisfies maxTotalDist and maxDistOutdoors constraints, then raises a ValueError. """ def _gen_paths(original_path, edges): yield original_path for edge in edges: if not is_node_visited(edge.getDestination(), original_path): yield original_path + [edge] stack = [[edge] for edge in digraph.childrenOf(Node(start))] while stack: path = stack.pop(-1) #next_edges = digraph.childrenOf(path[-1].getDestination()) next_edges = digraph.edgesFrom(path[-1]) for new_path in _gen_paths(path, next_edges): if (calc_distance_outdoors(new_path) <= maxDistOutdoors and calc_total_distance(new_path) <= maxTotalDist): if new_path[-1].getDestination().getName() == end: return get_node_list(new_path) elif new_path is not path: stack.append(new_path) raise ValueError() # start = Node(start) # end = Node(end) # path = [start] # queue = digraph.childrenOf(path[-1])[:] # total = [] # outdoors = [] # while queue: # edge = queue.pop() # parent = edge.getSource() # next_node = edge.getDestination() # weights = edge.getWeights() # while path[-1] != parent: # path.pop() # total.pop() # outdoors.pop() # test1 = next_node not in path # test2 = sum(total) + weights['total'] <= maxTotalDist # test3 = sum(outdoors) + weights['outdoors'] <= maxDistOutdoors # if test1 and test2 and test3: # total.append(weights['total']) # outdoors.append(weights['outdoors']) # path.append(next_node) # if next_node == end: # return [n.getName() for n in path] # else: # queue.extend(digraph.childrenOf(path[-1])) # raise ValueError # Uncomment below when ready to test #### NOTE! These tests may take a few minutes to run!! #### if __name__ == '__main__': # Test cases mitMap = load_map("mit_map.txt") print isinstance(mitMap, Digraph) print isinstance(mitMap, WeightedDigraph) print 'nodes', mitMap.nodes print 'edges', mitMap.edges LARGE_DIST = 1000000 # Test case 1 print "---------------" print "Test case 1:" print "Find the shortest-path from Building 32 to 56" expectedPath1 = ['32', '56'] brutePath1 = bruteForceSearch(mitMap, '32', '56', LARGE_DIST, LARGE_DIST) dfsPath1 = directedDFS(mitMap, '32', '56', LARGE_DIST, LARGE_DIST) print "Expected: ", expectedPath1 print "Brute-force: ", brutePath1 print "DFS: ", dfsPath1 print "Correct? BFS: {0}; DFS: {1}".format(expectedPath1 == brutePath1, expectedPath1 == dfsPath1) # Test case 2 # print "---------------" # print "Test case 2:" # print "Find the shortest-path from Building 32 to 56 without going outdoors" # expectedPath2 = ['32', '36', '26', '16', '56'] # brutePath2 = bruteForceSearch(mitMap, '32', '56', LARGE_DIST, 0) # dfsPath2 = directedDFS(mitMap, '32', '56', LARGE_DIST, 0) # print "Expected: ", expectedPath2 # print "Brute-force: ", brutePath2 # print "DFS: ", dfsPath2 # print "Correct? BFS: {0}; DFS: {1}".format(expectedPath2 == brutePath2, expectedPath2 == dfsPath2) # Test case 3 # print "---------------" # print "Test case 3:" # print "Find the shortest-path from Building 2 to 9" # expectedPath3 = ['2', '3', '7', '9'] # brutePath3 = bruteForceSearch(mitMap, '2', '9', LARGE_DIST, LARGE_DIST) # dfsPath3 = directedDFS(mitMap, '2', '9', LARGE_DIST, LARGE_DIST) # print "Expected: ", expectedPath3 # print "Brute-force: ", brutePath3 # print "DFS: ", dfsPath3 # print "Correct? BFS: {0}; DFS: {1}".format(expectedPath3 == brutePath3, expectedPath3 == dfsPath3) # Test case 4 # print "---------------" # print "Test case 4:" # print "Find the shortest-path from Building 2 to 9 without going outdoors" # expectedPath4 = ['2', '4', '10', '13', '9'] # brutePath4 = bruteForceSearch(mitMap, '2', '9', LARGE_DIST, 0) # dfsPath4 = directedDFS(mitMap, '2', '9', LARGE_DIST, 0) # print "Expected: ", expectedPath4 # print "Brute-force: ", brutePath4 # print "DFS: ", dfsPath4 # print "Correct? BFS: {0}; DFS: {1}".format(expectedPath4 == brutePath4, expectedPath4 == dfsPath4) # Test case 5 # print "---------------" # print "Test case 5:" # print "Find the shortest-path from Building 1 to 32" # expectedPath5 = ['1', '4', '12', '32'] # brutePath5 = bruteForceSearch(mitMap, '1', '32', LARGE_DIST, LARGE_DIST) # dfsPath5 = directedDFS(mitMap, '1', '32', LARGE_DIST, LARGE_DIST) # print "Expected: ", expectedPath5 # print "Brute-force: ", brutePath5 # print "DFS: ", dfsPath5 # print "Correct? BFS: {0}; DFS: {1}".format(expectedPath5 == brutePath5, expectedPath5 == dfsPath5) # Test case 6 # print "---------------" # print "Test case 6:" # print "Find the shortest-path from Building 1 to 32 without going outdoors" # expectedPath6 = ['1', '3', '10', '4', '12', '24', '34', '36', '32'] # brutePath6 = bruteForceSearch(mitMap, '1', '32', LARGE_DIST, 0) # dfsPath6 = directedDFS(mitMap, '1', '32', LARGE_DIST, 0) # print "Expected: ", expectedPath6 # print "Brute-force: ", brutePath6 # print "DFS: ", dfsPath6 # print "Correct? BFS: {0}; DFS: {1}".format(expectedPath6 == brutePath6, expectedPath6 == dfsPath6) # Test case 7 # print "---------------" # print "Test case 7:" # print "Find the shortest-path from Building 8 to 50 without going outdoors" # bruteRaisedErr = 'No' # dfsRaisedErr = 'No' # try: # bruteForceSearch(mitMap, '8', '50', LARGE_DIST, 0) # except ValueError: # bruteRaisedErr = 'Yes' # try: # directedDFS(mitMap, '8', '50', LARGE_DIST, 0) # except ValueError: # dfsRaisedErr = 'Yes' # print "Expected: No such path! Should throw a value error." # print "Did brute force search raise an error?", bruteRaisedErr # print "Did DFS search raise an error?", dfsRaisedErr # Test case 8 # print "---------------" # print "Test case 8:" # print "Find the shortest-path from Building 10 to 32 without walking" # print "more than 100 meters in total" # bruteRaisedErr = 'No' # dfsRaisedErr = 'No' # try: # bruteForceSearch(mitMap, '10', '32', 100, LARGE_DIST) # except ValueError: # bruteRaisedErr = 'Yes' # try: # directedDFS(mitMap, '10', '32', 100, LARGE_DIST) # except ValueError: # dfsRaisedErr = 'Yes' # print "Expected: No such path! Should throw a value error." # print "Did brute force search raise an error?", bruteRaisedErr # print "Did DFS search raise an error?", dfsRaisedErr
4f121996bac99b8754401b74274d490f64628b6c
ksks2012/BD_simulater
/main_window.py
4,508
3.578125
4
import tkinter as tk class Window(object): def __init__(self): self.window_handle = tk.Tk() self.window_handle.title('BD Simulater') self.window_handle.geometry('200x100') # return super(Window, self).__init__() def create_label(self): self.var = tk.StringVar() # text_var self.label = tk.Label(self.window_handle, textvariable=self.var, # 标签的文字 bg='yellow', # 背景颜色 font=('Arial', 12), # 字体和字体大小 width=15, height=2 # 标签长宽 ) self.label.pack() # 固定窗口位置 pass def create_button(self): self.on_hit = False button = tk.Button(self.window_handle, text='hit me', # 显示在按钮上的文字 width=15, height=2, command=self.print_selection) # 点击按钮式执行的命令 button.pack() # 按钮位置 pass def button_listener(self): if self.on_hit == False: # 从 False 状态变成 True 状态 print("on hit") self.on_hit = True self.var.set('you hit me') # 设置标签的文字为 'you hit me' else: # 从 True 状态变成 False 状态 self.on_hit = False self.var.set('') # 设置 文字为空 pass def create_entry(self): self.entry = tk.Entry(self.window_handle, show='*') self.entry.pack() self.text = tk.Text(self.window_handle, height=2) self.text.pack() pass def create_insert_point_buttom(self): self.button1 = tk.Button(self.window_handle, text="insert point", width=15, height=2, command=self.insert_point) self.button1.pack() pass def create_insert_end_buttom(self): self.button2 = tk.Button(self.window_handle, text="insert_end", width=15, height=2, command=self.insert_end) self.button2.pack() pass def insert_point(self): var = self.entry.get() self.text.insert('insert', var) def insert_end(self): var = self.entry.get() self.text.insert('end', var) def create_listbox(self): var2 = tk.StringVar() var2.set((11, 22, 33, 44)) # 为变量设置值 # 创建Listbox self.listbox = tk.Listbox(self.window_handle, listvariable=var2) # 将var2的值赋给Listbox # 创建一个list并将值循环添加到Listbox控件中 list_items = [1, 2, 3, 4] for item in list_items: self.listbox.insert('end', item) # 从最后一个位置开始加入值 self.listbox.insert(1, 'first') # 在第一个位置加入'first'字符 self.listbox.insert(2, 'second') # 在第二个位置加入'second'字符 self.listbox.delete(2) # 删除第二个位置的字符 self.listbox.pack() pass def print_selection(self, v): #v = self.scale.get() self.label.config(text='you have selected ' + self.var.get()) #self.label.config(text='you have selected ' + self.var.get()) # value = self.listbox.get(self.listbox.curselection()) # 获取当前选中的文本 # self.var.set(value) # 为label设置值 pass def create_radio(self): radio1 = tk.Radiobutton(self.window_handle, text='Option A', variable=self.var, value='A', command=self.print_selection) radio1.pack() pass def create_scale(self): self.scale = tk.Scale(self.window_handle, label='try me', from_=5, to=11, orient=tk.HORIZONTAL, variable=self.var, length=200, showvalue=0, tickinterval=2, resolution=0.01, command=self.print_selection) self.scale.pack() pass if __name__ == "__main__": window = Window() window.create_label() # window.create_button() # window.create_entry() # window.create_insert_point_buttom() # window.create_insert_end_buttom() # while(1): # window.create_listbox() # window.create_radio() window.create_scale() window.window_handle.mainloop() # window.create_labe() pass
7cc38a04961f68721a9a3dd9f8ec5e68e491c22c
x0rk/python-projects
/String_length.py
183
4.21875
4
def str_len(): str1 = input("Enter a string: ") #str1 = "kavinash" result = str1.index(str1[-1]) + 1 return result print("Length of the string is ",str_len())
61c48ca181da06b26a51d93b9197065a431a27be
Shadjistefanov/python-fundamentals
/Courses_practice.py
107
3.609375
4
n = int(input()) courses = [] for i in range(n): text = input() courses.append(text) print(courses)
dd553c33a30664bd55b71ea21d38d44e22955bfd
junyoung-o/PS-Python
/by date/2021.05.14/124나라의 숫자.py
643
3.671875
4
question = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] answer = [1, 2, 4, 11, 12, 14, 21, 22, 24, 41] num = ["1", "2", "4"] def get_result(n): if(n <= 3): return num[n - 1] q, r = divmod(n - 1, 3) return get_result(q) + num[r] def solution(n): answer = get_result(n) print(answer) return int(answer) for i, (q, a) in enumerate(zip(question, answer)): if(solution(int(q)) == a): print("{} is right".format(i + 1)) else: print("{} is worng".format(i + 1))
e0547bcc6c094e3f72ac3a4efe31e9c43c650b33
Aasthaengg/IBMdataset
/Python_codes/p03634/s286729663.py
1,037
3.5
4
import sys def input(): return sys.stdin.readline().rstrip() def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) from collections import deque from heapq import heappop, heappush def main(): def dijkstra(k): def push(v, x): if dist[v] <= x: return dist[v] = x heappush(q, (x, v)) inf = 10**18 dist = [inf]*n q = [] push(k, 0) while q: x, v = heappop(q) if x > dist[v]: continue for nv, c in g[v]: push(nv, x+c) return dist n = ii() g = [[] for _ in range(n)] for _ in range(n-1): a, b, c = mi() a -= 1 b -= 1 g[a].append((b, c)) g[b].append((a, c)) q, k = mi() k -= 1 dist = dijkstra(k) for i in range(q): a, b = mi() a -= 1 b -= 1 print(dist[a]+dist[b]) if __name__ == '__main__': main()
1ddff1ecd5dae626a82d5887b4d33df6e2a162c5
YuliangZHENG6/hackerrank
/CrackingTheCodingInterview/dataStructure/Trees_IsThisBinarySearchTree.py
508
3.890625
4
# python 3 """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ ##### METHOD 1 def checkBST(root): return checkInorder(root, [-1]) def checkInorder(root, prev): result = True if root.left: result &= checkInorder(root.left, prev) if prev[0] >= root.data: return False prev[0] = root.data if root.right: result &= checkInorder(root.right, prev) return result
95f49937a7334ab61b02d22c7218cfedff3f76d8
jpch89/picpython
/pp_009_多线程执行的不确定性.py
671
3.71875
4
from threading import Thread, current_thread import time def do_sth(): for i in range(5): print('%s: %d' % (current_thread().getName(), i)) time.sleep(2) if __name__ == '__main__': for i in range(3): Thread(target=do_sth).start() do_sth() """ Thread-1: 0 Thread-2: 0 Thread-3: 0 MainThread: 0 MainThread: 1 Thread-2: 1 Thread-1: 1 Thread-3: 1 MainThread: 2 Thread-3: 2 Thread-1: 2 Thread-2: 2 MainThread: 3 Thread-3: 3 Thread-1: 3 Thread-2: 3 MainThread: 4 Thread-2: 4 Thread-1: 4 Thread-3: 4 """ """ 小结 默认情况下,多个进程的执行顺序和时间都是不确定的。 完全取决于操作系统的调度。 """
9aed21372b8d00dfafa048142c134581f6f20ea3
malaybiswal/python
/leetcode/containsDuplicate1.py
292
3.734375
4
#https://leetcode.com/problems/contains-duplicate/ def containsDuplicate(nums): """ :type nums: List[int] :rtype: bool """ l1=len(nums) l2=len(set(nums)) if(l1!=l2): return True else: return False arr=[1,2,3,4,6,2] print(containsDuplicate(arr))
f06375983a352943b6ad34eafeb9ffa85f9bb32d
marisalvarani/FaculdadeADS
/Listas/6).py
701
4
4
n = int(input("Digite a quantidade de nomes:" )) lst_nomes = [] while n<3 or n>10: n = int(input("Digite a quantidade de nomes entre 4 e 9:" )) for x in range(1,n): nome = str(input("Digite o nome:" )) lst_nomes.append(nome) print("Nomes digitados:", lst_nomes) lst_nomes.insert(3, "Teste") print("Lista após incluir 'Teste' no índice 3:",lst_nomes) del lst_nomes[2] print("Lista após excluir o elemeno de índice 2",lst_nomes) qtde = lst_nomes.count("Ana") if qtde > 0: print("Índice da primeira ocorrência do nome Ana na lista:", lst_nomes.index("Ana")) else: print("Não existe o nome Ana na lista") lst_nomes.sort() print("Lista ordenada:",lst_nomes)
9c1dfbb72b3608a79f7e74859e48f8e8c1623370
Srynetix/libnx-gol
/tools/font.py
2,150
3.96875
4
""" Hex font data generator. From an input string, generate an 32-bit hex code to use for font rendering. Example, for a font size of 5 x 6 pixels (0 for a white pixel and 1 for a black pixel) ..o.. => 00100 .ooo. => 01110 ..o.. => 00100 ..o.. => 00100 .ooo. => 01110 ..o.. => 00100 => Input string: "00100 01110 00100 00100 01110 00100" => Hex code: 0x08e211c4 """ import argparse import math def main(): parser = argparse.ArgumentParser(description="hex font data generator") parser.add_argument("binary") args = parser.parse_args() hex_str = generate_hex(args.binary) print(hex_str) def generate_hex(binary): """ Generate hex string from binary string. String format (5 * 6): "00000 00000 00000 00000 00000 00000" :param binary: Binary string (str) :rtype: Hex string (str) """ flat = "".join(binary.split(" ")) packets = partition_str(flat, 4) rev_packets = reverse_all(packets) hex_str = "" for p in rev_packets: hex_str += hex(int(p, base=2))[2:] hex_str = "0x{0}".format(hex_str) return hex_str def partition_str(s, limit): """ Partition string each `limit` character. Example: s: "foobarfoobarfoobar" limit: 4 result: ["foob", "arfo", "obar", "foob", "ar"] :param s: String (str) :param limit: Limit (int) :rtype: List (list) """ str_length = len(s) output = [] current = [] packs_len = int(math.ceil(str_length / limit)) for l in range(packs_len): for i in range(limit): idx = i + l * limit if idx < str_length: current.append(s[idx]) output.append("".join(current)) current = [] return output def reverse_all(l): """ Reverse a list, while reversing its content. Example: l: ["abcde", "fghij"] result: ["jihgf", "edcba"] :param l: List (list) :rtype: Reversed list (list) """ output = [] for x in l[::-1]: output.append("".join(list(reversed(x)))) return output if __name__ == "__main__": main()
d2e38630ab4ff120f1f7d39cb1776fddc5789c24
akalikhan/flask_course
/Lecture8/table.py
331
3.6875
4
import sqlite3 conn = sqlite3.connect('data.db') cur = conn.cursor() create_items = 'CREATE TABLE IF NOT EXISTS items (name TEXT, price REAL)' cur.execute(create_items) create_users = 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)' cur.execute(create_users) conn.commit() conn.close()
25b032fe2e2307604b243b068d33d6d0ac10176e
Skywonder/Connect4-Python
/I32CFSP.py
2,220
3.59375
4
# ANPING HE (17685951) KUAN-PING CHANG(71018021) import socket def get_host()->str: '''prompts the user for host address, and check for validity''' while True: result = input('Please enter the host name or address: ').strip() if result == '': print('Error! Invalid host name or address. Please try again.') else: return result def get_port()->int: '''prompts the user for port number (0-65535), and returns it''' while True: try: result = int(input('Please enter the port number: ').strip()) if result >= 0 and result <= 65535: return result else: print('Please enter an integer between 0 and 65535.') except: print('Please enter an integer between 0 and 65535.') def connect(host:str, port:int)-> 'A socket connection': '''connects to the server, and set up an psudo file''' c = socket.socket() c.connect((host,port)) infile = c.makefile('r',newline = '\r\n') outfile = c.makefile('w', newline = '\r\n') return (c, infile, outfile) def close(connection:'socket connection')->None: '''close the files and connection''' c, infile, outfile = connection print('Closing connection...') infile.close() outfile.close() c.close() print('Connection closed') return def _send(con:'socket connection',s:str)->None: '''sends the command to the server''' c,infile,outfile = con s += '\r\n' outfile.write(s) outfile.flush() return def _receive(con:'socket connection'): '''receives responses from the server''' c,infile,outfile = con result = infile.readline()[:-1] return result def talk(con:'socket connection',s:str)->list: '''sends commands to the server and interpreting the response from the server''' _send(con,s) response = _receive(con) response = response.strip().split() if response[0] == 'OKAY': a = _receive(con).strip().split() response.extend(a) b = _receive(con).strip().split() response.extend(b) elif response[0] == 'INVALID': _receive(con) return response
2c41ddf8d0f5e6d1da6e57d60dd7b9f1793051f9
Vivekyadv/450-DSA
/3. String/4. Count and Say problem.py
714
3.8125
4
# Given a number n, return the nth pattern # pattern is defined as # N = 4 # countAndSay(1) = "1" # countAndSay(2) = say "1" = one 1 = "11" # countAndSay(3) = say "11" = two 1's = "21" # countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" def countAndSay(n): if n == 1: return '1' if n == 2: return '11' result = '11' for i in range(3, n+1): temp = '' count = 1 result += '@' for j in range(len(result)-1): if result[j] == result[j+1]: count += 1 else: temp += str(count) + result[j] count = 1 result = temp return result print(countAndSay(6))
434f99afbd5ab32cc089dd3abad8d4e6f9b8d57a
baghirov/python-slides
/Lecture7/lecture-examples/lecture7-2.py
377
3.765625
4
a = float(input("Performance of CPUA:")) b = float(input("Performance of CPUA:")) performance_rate = a/b print(f'I have been living here for {years} years') faculties = ["Case", "Ce", "Cs", "Ssch", "Med"] index = int( input(f'These are the faculties {faculties} which index do you want to use?')) faculties[index] print(f'You chose {faculties[index]}') print(2 + '2')
164afc1b17243ef5e8ec91e8c2687d6d097d1bb7
Ellana42/OnePyce2
/terrain.py
10,764
3.640625
4
from random import randrange, random, seed, choices, shuffle from math import sin, cos, pi, fabs, sqrt import copy from pygame import Rect, Color class Terrain: @classmethod def get_terrains(cls): terrains = { "S": ("Sea", "Water"), "E": ("Pond", "Water"), "M": ("Mountain", "Mountain"), "F": ("Forest", "Forest"), "B": ("Wood", "Forest"), "P": ("Meadows", "Ground"), "C": ("Field", "Ground"), "X": ("Cliff", "Mountain"), "G": ("Beach", "Ground"), "R": ("Road", "Path"), "V": ("City", "Path"), } return {k: {"name": name, "type": terrain_type} for k, (name, terrain_type) in terrains.items()} def __init__(self): island_size = randrange(40, 80) width, height = island_size, island_size self.board = [[0 for _ in range(width)] for _ in range(height)] self.width, self.height = width, height def get_board(self): return self.board def get_dimensions(self): return self.width, self.height def copy_board(self): return copy.deepcopy(self.board) def get_random_positions(self, number): width, height = self.width, self.height board = self.board positions = set() for _ in range(number): while True: c, r = randrange(width), randrange(height) if board[r][c] == 0 and (c, r) not in positions: positions.add((c, r)) break return positions def put_random_obstacles(self, what, number): width, height = self.width, self.height board = self.board for _ in range(number): while True: c, r = randrange(width), randrange(height) cell_content = board[r][c] if cell_content == 0: board[r][c] = what break def is_inside_board(self, r, c): width, height = self.width, self.height return c in range(width) and r in range(height) def one_pass(self, what, threshold, to_what='', direction=None): dir_x, dir_y = 0, 0 if direction is not None: dir_x, dir_y = cos(direction), sin(direction) previous_board = self.copy_board() for r, line in enumerate(previous_board): for c, cell in enumerate(line): if cell == what: for h, v in ((i, j) for i in range(-1, 2) for j in range(-1, 2) if (i, j) != (0, 0)): around_r, around_c = r + v, c + h if direction is None: threshold_kept = threshold else: threshold_kept = fabs(h * dir_x + v * dir_y) * threshold if self.is_inside_board(around_r, around_c) and random() < threshold_kept and \ self.board[around_r][around_c] == 0: self.board[around_r][around_c] = what if to_what == '' else to_what def multiple_pass(self, what, threshold, passes, to_what='', direction=None): for _ in range(passes): self.one_pass(what, threshold, to_what, direction) def invert_board(self, fill): previous_board = self.copy_board() for r, line in enumerate(previous_board): for c, cell in enumerate(line): self.board[r][c] = fill if cell == 0 else 0 def fill_with(self, what): for r, line in enumerate(self.board): for c, cell in enumerate(line): if cell == 0: self.board[r][c] = what def draw_road(self, start, end): def possible_moves(c, r): return ((h, v) for h, v in {(-1, 0), (1, 0), (0, -1), (0, 1)} if self.board[r + v][c + h] == 0) def junction(c, r): return [(h, v) for h, v in {(-1, 0), (1, 0), (0, -1), (0, 1)} if self.board[r + v][c + h] in ('V', 'R') and (r + v != start[1] or c + h != start[0])] path = [] c, r = start # Current position c_e, r_e = end # Target position last_h, last_v = 0, 0 # Last move while c != c_e or r != r_e: if len(junction(c, r)) > 0: break d = sqrt((c_e - c) ** 2 + (r_e - r) ** 2) - 0.5 dir_h, dir_v = 0, 0 if d > 0: dir_h, dir_v = (c_e - c) / d, (r_e - r) / d weighted_moves_p = {} weighted_moves_n = {} weighted_moves = {} for move_h, move_v in possible_moves(c, r): if last_h + move_h == 0 and last_v + move_v == 0: continue dir = move_h * dir_h + move_v * dir_v if dir > 0: weighted_moves_p[(move_h, move_v)] = dir else: weighted_moves_n[(move_h, move_v)] = dir if len(weighted_moves_p) > 0: weighted_moves = weighted_moves_p if (last_h, last_v) in weighted_moves: weighted_moves[(last_h, last_v)] += 1 elif len(weighted_moves_n) > 0: m = min(weighted_moves_n.values()) weighted_moves = {k: v - m for k, v in weighted_moves_n.items()} if len(weighted_moves) == 0: break keys, values = list(zip(*(list(weighted_moves.items())))) if len(keys) > 1: try: move = choices(keys, weights=values) except: break move_h, move_v = move[0] else: move_h, move_v = keys[0] c += move_h r += move_v last_h, last_v = move_h, move_v if self.board[r][c] in ("R", "V"): break if c != c_e or r != r_e: path.append((c, r)) for c, r in path: self.board[r][c] = "R" def update_board_at(self, positions, what): for c, r in positions: self.board[r][c] = what def generate_island(self): mountains_factor = 1.0 mountains_thickness = 1.0 woods = 1.0 woods_thickness = 1.0 ponds = 1.0 ponds_thickness = 1.0 meadow = 1.0 meadow_thickness = 1.0 # Island shaped creation self.board[self.height // 2][self.width // 2] = "X" self.multiple_pass("X", 0.08, int(min(self.height, self.width) * 1.2), direction=random() * pi) self.invert_board("S") cities = self.get_random_positions(randrange(7, 14)) self.update_board_at(cities, "V") if len(cities) > 0: base_city = cities.pop() while len(cities) > 0: c, r = base_city distances = [((c_city, r_city), (c_city - c) ** 2 + (r_city - r) ** 2) for c_city, r_city in cities] # distances = sorted(distances, key=lambda x:x[1]) shuffle(distances) for target_city, _ in distances[:2]: self.draw_road(base_city, target_city) base_city = cities.pop() # Island shaped creation self.multiple_pass("S", 0.2, 1, to_what="G") # Plage le long de la mer self.multiple_pass("G", 0.05, 4) # Extension des plages self.multiple_pass("S", 0.05, 1, to_what="X") # Falaise le long de la mer self.multiple_pass("G", 0.05, 1, to_what="X") # Falaise le long du sable self.multiple_pass("X", 0.1, 4, direction=random() * pi) # Extension des falaises # Montains island_size = min(self.width, self.height) mountain_seeds = int(mountains_factor * island_size // 7) mountain_thickness = int(island_size * mountains_thickness) // 4 self.put_random_obstacles("M", randrange(int(mountain_seeds * 0.8), mountain_seeds)) self.multiple_pass("M", 0.10, randrange(int(mountain_thickness * 0.8), mountain_thickness), direction=random() * pi) # Forêt jouxtant la montagne self.multiple_pass("M", 0.1, 1, "F") # Départ à partir de la montagne self.multiple_pass("F", 0.1, 3, "F") # Etendre un peu # Bois self.put_random_obstacles("B", int(woods * 8)) self.multiple_pass("B", 0.2, int(woods * 3)) # Etangs self.put_random_obstacles("E", int(ponds * 6)) self.multiple_pass("E", 0.3, int(ponds * 3)) # Prairie self.put_random_obstacles("P", int(6 * meadow)) self.multiple_pass("P", 0.3, int(5 * meadow_thickness)) # Champs self.fill_with("C") if __name__ == "__main__": import pygame def display_colored_board(screen, board, width, height, size_x, size_y): terrains = { "S": Color(20, 196, 250), # "Mer" "E": Color(162, 224, 242), # Etang "M": Color(74, 43, 5), # "Montagne" "F": Color(5, 74, 48), # Forêt "B": Color(8, 196, 55), # Bois "P": Color(194, 240, 43), # "Prairie", "C": Color(222, 209, 109), # "Champs", "X": Color(100, 75, 10), # Falaises "G": Color(252, 236, 88), # Plage "R": Color(255, 255, 255), # Road "V": Color(255, 0, 0), # City } f_x, f_y = int(size_x / width), int(size_y / height) for r, line in enumerate(board): for c, cell in enumerate(line): rect = Rect(c * f_x, r * f_y, f_x, f_y) pygame.draw.rect(screen, terrains[cell], rect) terrain = Terrain() terrain.generate_island() a_board = terrain.get_board() width, height = terrain.get_dimensions() pygame.init() screen_size = 800 f = int(screen_size / max(width, height)) size_x, size_y = width * f, height * f screen = pygame.display.set_mode((size_x, size_y)) pygame.display.set_caption('OnePyce terrain generator') pygame.mouse.set_visible(0) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False screen.blit(background, (0, 0)) display_colored_board(screen, a_board, width, height, size_x, size_y) pygame.display.flip() clock.tick(10)
3b998067e8888d297fea25efcd0676d2fa0feaaa
krishna-rawat-hp/PythonProgramming
/codes/list14.py
200
4.15625
4
# Python list common element in two list lst1 = [1,2,3,4,5] lst2 = [4,5,6,7,8] # Example-1 cele = [] for i in lst1: for j in lst2: if i == j: cele.append(i) print("Common Element is: ",cele)
4f2f175bf9c2315b0fd9fb7ea4acf4b895d35ecb
ch0r1es-1n-ch0rge/starting_out_with_Python
/Chapter 5 - Programming Exercises/CH: 5 - Kinetic Energy.py
1,326
4.4375
4
# In physics, an object that is in motion is said to have kinetic energy. The following formula can be used to determine # a moving object's kinetic energy: # KE = 1/2mv^2 # The variables in the formula ae as follows: KE is the kinetic energy, m is the object's mass in kilograms, and v is # the object's velocity in meters per second. # Write a functions named kinetic_energy that accepts an object's mass (in kilograms) and velocity (in meters per # second) as arguments. The function should return the amount of kinetic energy that the object has. Write a program # that asks the user to enter values for mass and velocity, then calls the kinetic_energy function to get the object's # kinetic energy. # Create Main Function def main(): user_mass = float(input('Enter the mass (in kilograms) of the moving object: ')) user_velocity = float(input('Enter the velocity (in meters per second) of the moving object: ')) ke = kinetic_energy(user_mass, user_velocity) print('With a mass of:', format(user_mass, ',.2f'), 'kilograms', 'and a velocity of:', user_velocity, 'meters per second.') print('The kinetic energy of the object is:', ke) def kinetic_energy(mass, velocity): ke = (1 / 2) * mass * (velocity ** 2) return format(ke, ',.2f') main()
98ed3b42a67f5fa0060a5f7db93fa47b07f4da8c
3wh1te/Leecode
/code/searchMatrix.py
2,358
3.53125
4
class Solution: def searchMatrix(self, matrix, target): def search(matrix,row,col,target): if row < 0 or col >= len(matrix[0]): return False if matrix[row][col] == target: return True elif matrix[row][col] < target: return search(matrix, row, col + 1, target) else: return search(matrix, row - 1, col, target) return search(matrix,len(matrix) - 1, 0, target) def searchMatrix1(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix == []: return False if target > matrix[-1][-1] or target < matrix[0][0]: return False right_x,right_y = len(matrix),len(matrix[0]) left_x,left_y = 0, 0 return self.binary_search_m(matrix, left_x, left_y, right_x, right_y, target) def binary_search_m(self,matrix,left_x,left_y,right_x,right_y,target): lx,ly,rx,ry = left_x,left_y,right_x,right_y if right_x == left_x and right_y == left_y: if matrix[left_x][left_y] != target: return False else: return True mid,mid_x,mid_y = 0,0,0 while right_x >= left_x and right_y >= left_y: mid_x = int((right_x + left_x - 1) / 2) mid_y = int((right_y + left_y - 1) / 2) mid = matrix[mid_x][mid_y] if mid == target: return True elif mid < target: left_x, left_y = mid_x + 1, mid_y + 1 else: right_x, right_y = mid_x - 1, mid_y - 1 # 分两部分大于mid_x,小于mid_y : larger than mid_y litte than mid_x # 上 print(mid) top = self.binary_search_m(matrix, lx, mid_y, mid_x, ry, target) if top: return top # 下 bottom = self.binary_search_m(matrix, mid_x, ly, rx, mid_y, target) return bottom if __name__ == '__main__': # 先二分搜索对角线,再二分搜索列和行 matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] print(Solution().searchMatrix(matrix,12)) print(Solution().searchMatrix(matrix, 20))
7d6d949479b831b2c60b7c87cc0a34458fceb4b5
DREAMS-lab/SES230-Coding-for-Exploration
/Labs/linear-regression.py
608
3.515625
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression x = 30*np.random.random((20,1)) slope = 0.5 intercept = 1.0 noise_vec = np.random.normal(size=x.shape) y_without_noise = slope * x + intercept y = y_without_noise + noise_vec model = LinearRegression() model.fit(x,y) num_elem = 30 x_new = np.linspace(0,30,num_elem) x_new = x_new.reshape((num_elem,1)) y_new = model.predict(x_new) plt.scatter(x,y) plt.xlabel('x') plt.ylabel('y = 0.5x+1') plt.plot(x_new,y_new,'.') plt.plot(x, y_without_noise, 'r.') print(model.coef_) print(model.intercept_) plt.show()
ce88aef91451479eec95a2430951b741789958a4
nivi2021python/luminarpython
/functions/subfunction3.py
121
3.828125
4
#subtraction with arguments and return type def sub(no1,no2): diff=no1-no2 print(diff) data=sub(8,5) print(data)
c0d5c34707901f4db3b99f00229a595d2276cc91
mehulchopradev/kate-elizabeth-alon-python
/play_tuples.py
638
4.21875
4
# create a tuple of details of a book in library b1 = ('Prog in C', 900, 4500) print(type(b1)) # create an empty tuple b2 = () print(type(b2)) # create a tuple that has only one element b3 = ('Prog in Java',) # leave a trailing comma print(type(b3)) # a tuple is also like a sequence of elements # position of the elements is 0 based print(b1[0]) print(b1[-1]) # extract a sub tuple (consiting of the price and pages) from the larger tuple print(b1[1:]) # length of the tuple print(len(b1)) print(len(b3)) # print on a new line, individual elements from the b1 tuple for v in b1: print(v) ''' A tuple is an immutable object '''
a9a9271bfad563ad4f474867c6c06f04d43a72a6
vcancy/python-algorithm
/leetcode/Algorithms/Array/88.py
817
4.03125
4
__author__ = "vcancy" # /usr/bin/python # -*-coding:utf-8-*- """ 分析: 题目中要求将nums2插入nums1中,最后存在nums1中 最后新的nums1的大小为m+n-1 倒序nums1和nums2,判断最后一位,越大的数放在新nums1的最后 """ class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ index = m + n - 1 m = m - 1 n = n - 1 while n >= 0: if m >= 0 and nums1[m] > nums2[n]: nums1[index] = nums1[m] m -= 1 else: nums1[index] = nums2[n] n -= 1 index -= 1
f7de23137952b2a1f77816f470f794e7d00ddd3c
Bosh-Kuo/Udemy-Bootcamp-of-Data-Science-with-Python
/Section5_Pandas_Essential/Ex5_9.py
274
3.859375
4
import pandas as pd s = pd.Series([1, 2, 3, 4, 5, 6], index = ['a', 'b', 'c', 'd', 'e', 'f']) print(f'First element: {s[0]}') print(f'Third element: {s[2]}') print(f'First three elements: \n{s[:3]}') print(f'Last three elements: \n{s[-3:]}') print(f'Last element: {s[-1]}')
d00fe7f4128eac3bc95b1f81a3fb3032c5c06b8f
johannbzh/Cracking-The-Coding-Interview-Python-Solutions
/stacks_and_queues/MyQueue.py
321
3.5625
4
class MyQueue(object): def __init__(self): self.enq = [] self.deq = [] def push(self, x): self.enq.append(x) def popleft(self): if not self.deq : while self.enq : self.deq.append(self.enq.pop()) return self.deq.pop() if self.deq else None
6dbab9f1c75e22a6f8bc1c602008d3364219d273
fomitim37/PEP8_class
/main.py
986
3.953125
4
"""class file""" def summ(a_num, b_num): """summ function""" return a_num + b_num class Human(): """Human class""" def __init__(self, name, height, weight): """__init__ function""" self.name = name self.height = height self.weight = weight def is_weight_normal(self, height, weight): """is_weight_normal function""" if height - 100 >= weight: return self.name + ", Your weight is normal." return self.name + ", Your weight isn't normal!" def letters_count(self): """letters_count function""" name_list = [] for letter in self.name: name_list.append(letter) return len(name_list) print("Enter your name, height and weight: ") NEW_HUMAN = Human(input().capitalize(), int(input()), int(input())) print("Hello, " + NEW_HUMAN.name + ". ") print(NEW_HUMAN.is_weight_normal(NEW_HUMAN.height, NEW_HUMAN.weight)) print(NEW_HUMAN.letters_count())
21b2e08dab5d6a4637dcf02c506a410698a81c1f
vinayakgaur/Algorithm-Problems
/Jewels_and_Stones.py
689
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 10 11:55:34 2021 @author: VGaur """ # You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. # Letters are case sensitive, so "a" is considered a different type of stone from "A" class Solution: def numJewelsInStones(self, jewels: str, stone: str) -> int: l = [] sum =0 for i in jewels: l.append(i) for j in stone: if j in l: sum += 1 return sum
aef0d92d1f0355e5f1ca6fcbfb16c32136b1b7f3
sherms77/Python-challenges
/HackerRank/Python if-Else/tests/rule2-test.py
362
3.859375
4
# Rule 2: if n is even and in the inlcusive range of 2 to 5 print Not Weird # n = int(input('Enter num:')) def rule2(n): if n%2 and n in range(2,6): print('Not Weird') else: print('Weird') rule2(2) # out[2]: Not Weird rule2(3) # out[3]: Weird rule2(4) # out[4]: Not Weird rule2(5) # out[5]: Weird # 070421: Correct outputs
aa7b2481c3591abf0aa1ddedd30a23d01359ab39
Mils18/Lab
/class_TollSyste_3.py
6,963
3.734375
4
class Vehicle: def __init__(self,cPriceM,bPriceM,tPriceM,cPriceP,bPriceP,tPriceP): self.cPriceM = cPriceM self.bPriceM = bPriceM self.tPriceM = tPriceM self.cPriceP = cPriceP self.bPriceP = bPriceP self.tPriceP = tPriceP def getcPriceM(self): return self.cPriceM def getbPriceM(self): return self.bPriceM def gettPriceM(self): return self.tPriceM def getcPriceP(self): return self.cPriceP def getbPriceP(self): return self.bPriceP def gettPriceP(self): return self.tPriceP class TollBooth(Vehicle): def __init__(self, cPriceM,bPriceM,tPriceM, cPriceP,bPriceP,tPriceP, countCarM,countBusM,countTruckM ,countCarP,countBusP,countTruckP): Vehicle.__init__(self, cPriceM,bPriceM,tPriceM, cPriceP,bPriceP,tPriceP) self.countCarM = countCarM self.countBusM = countBusM self.countTruckM = countTruckM self.countCarP = countCarP self.countBusP = countBusP self.countTruckP = countTruckP def calculationTBM(self): x = int(self.countCarM) * self.cPriceM y = int(self.countBusM) * self.bPriceM z = int(self.countTruckM) * self.tPriceM totalTBM = x + y + z return totalTBM def printAllTBM(self): timesP = 20 print("Location: Meruya") print(timesP * "-") print("car\t\tBus\t\tTruck") print(timesP * "-") print(str(self.countCarM) + "\t\t" + str(self.countBusM) + "\t\t" + str(self.countTruckM)) print(timesP * "-") def calculationTBP(self): x = int(self.countCarP) * self.cPriceP y = int(self.countBusP) * self.bPriceP z = int(self.countTruckP) * self.tPriceP totalTBP = x + y + z return totalTBP def printAllTBP(self): timesP = 20 print("Location: Pondok Aren") print(timesP * "-") print("car\t\tBus\t\tTruck") print(timesP * "-") print(str(self.countCarP) + "\t\t" + str(self.countBusP) + "\t\t" + str(self.countTruckP)) print(timesP * "-") # class TollGate(TollBooth): # def __init__(self,cPriceM,bPriceM,tPriceM, # cPriceP,bPriceP,tPriceP, # countCarM,countBusM,countTruckM, # countCarP,countBusP,countTruckP): # # TollBooth.__init__(self, # cPriceM,bPriceM,tPriceM, # cPriceP,bPriceP,tPriceP, # countCarM,countBusM,countTruckM, # countCarP,countBusP,countTruckP) # # def printMeruya(self): # TollBooth.printAllTBM() # def calculationTBM(self): # x = int(self.countCarM) * self.cPriceM # y = int(self.countBusM) * self.bPriceM # z = int(self.countTruckM) * self.tPriceM # totalTBM = x + y + z # return totalTBM # def printAllTBM(self): # timesP = 20 # print(timesP * "-") # print("car\t\tBus\t\tTruck") # print(timesP * "-") # print(str(self.countCarM) + "\t\t" + str(self.countBusM) + "\t\t" + str(self.countTruckM)) # print(timesP * "-") cPriceM = 6000 bPriceM = 8000 tPriceM = 10000 cPriceP = 18000 bPriceP = 20000 tPriceP = 25000 countCarM = 0 countBusM = 0 countTruckM = 0 countCarP = 0 countBusP = 0 countTruckP = 0 a = Vehicle(cPriceM,bPriceM,tPriceM,cPriceP,bPriceP,tPriceP)# totalTB = 0 # meruya = TollGate(cPriceM,bPriceM,tPriceM,cPriceP,bPriceP # ,tPriceP,countCarM,countBusM,countTruckM # ,countCarP,countBusP,countTruckP) # # pondokAren = TollGate(cPriceM,bPriceM,tPriceM,cPriceP,bPriceP # ,tPriceP,countCarM,countBusM,countTruckM # ,countCarP,countBusP,countTruckP) otherTollGate = "Y" timesE = 55 timesS = 15 print(timesE*"=", "\n",timesS*" ","Toll Payment Systems" "\n",timesS*" "," PT Jasa Marga, Tbk." "\n"+timesE*"=") while otherTollGate != "N": tollGate = input("1. Meruya\n" "2. Pondok Aren\n" "Location of Toll Gate : ") tollGate = tollGate.upper() otherVehicle = "Y" if tollGate == "MERUYA": while otherVehicle != "N": vehicle = int(input("Category of Vehicles" "\n1. Car" "\n2. Bus" "\n3. Truck")) #carMeruya if vehicle == 1: print("Fee",a.getcPriceM()) countCarM += 1 #busMeruya if vehicle == 2: print("Fee",a.getbPriceM()) countBusM += 1 #truckMeruya if vehicle == 3: print("Fee",a.gettPriceM()) countTruckM += 1 if vehicle == 4: print(countCarM,countBusM,countTruckM) otherVehicle = input("\nIs there any other vehicle (Y/N)? \n") otherVehicle = otherVehicle.upper() elif tollGate == "PONDOK AREN": while otherVehicle != "N": vehicle = int(input("Category of Vehicles" "\n1. Car" "\n2. Bus" "\n3. Truck")) #carPondokAren if vehicle == 1: print("Fee",a.getcPriceP()) countCarP += 1 #busPondokAren if vehicle == 2: print("Fee",a.getbPriceP()) countBusP += 1 #truckPondokAren if vehicle == 3: print("Fee",a.gettPriceP()) countTruckP += 1 if vehicle == 4: print(countCarP,countBusP,countTruckP) otherVehicle = input("\nIs there any other vehicle (Y/N)? \n") otherVehicle = otherVehicle.upper() otherTollGate = input("\nIs there any other toll gate (Y/N)? \n") otherTollGate = otherTollGate.upper() b = TollBooth(cPriceM,bPriceM,tPriceM, cPriceP,bPriceP,tPriceP, countCarM,countBusM,countTruckM ,countCarP,countBusP,countTruckP) b.printAllTBM() print("Total revenue: Rp.",b.calculationTBM()) print() b.printAllTBP() print("Total revenue: Rp.",b.calculationTBP()) grandTotalRevenue = int(b.calculationTBM())+ int(b.calculationTBP()) print("Grand total revenue: Rp.",grandTotalRevenue) # print() # # pondokAren.printAllTB() # print("Total revenue: Rp.",pondokAren.calculationTB()) #
b7c77fbd738a031da2a9eba9f8138848d101c831
jiangyihong/PythonTutorials
/chapter10/exercise10_6.py
409
3.96875
4
first_number_str = input("Please input first number:") try: first_number = int(first_number_str) except ValueError as e: print("You input wrong number!") first_number = 0 second_number_str = input("Please input second number:") try: second_number = int(second_number_str) except ValueError as e: second_number = 0 print("You input wrong number!") print(first_number + second_number)