blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
fbee40adb066a74cfbe3db56013a1f6dc02ba6e8
ppg003/Tiku
/Meituan/3.py
1,430
3.53125
4
""" http://cv.qiaobutang.com/post/55c483380cf2b4db80726f3d 给定N个磁盘,每个磁盘大小为D[i],i=0...N-1,现在要在这N个磁盘上"顺序分配"M个分区,每个分区大小为P[j],j=0....M-1。 顺序分配的意思是:分配一个分区P[j]时,如果当前磁盘剩余空间足够,则在当前磁盘分配; 如果不够,则尝试下一个磁盘,直到找到一个磁盘D[i+k]可以容纳该分区; 分配下一个分区P[j+1]时,则从当前磁盘D[i+k]的剩余空间开始分配,不在使用D[i+k]之前磁盘末分配的空间; 如果这M个分区不能在这N个磁盘完全分配,则认为分配失败,请实现函数,is_allocable判断给定N个磁盘(数组D)和M个分区(数组P),是否会出现分配失败的情况。 举例:磁盘为[120,120,120],分区为[60,60,80,20,80]可分配 ,如果为[60,80,80,20,80]则分配失败。 """ def is_allocable(d, m): l_d = len(d) l_m = len(m) t_d = sum(d) t_m = sum(m) if t_m > t_d: return False i_d = 0 i_m = 0 while i_d < l_d and 0 < t_m < t_d: res = d[i_d] while i_m < l_m and res >= m[i_m]: res -= m[i_m] t_m -= m[i_m] i_m += 1 t_d -= d[i_d] i_d += 1 if t_m > 0: return False return True d = [120, 120, 120] m_s = [60, 60, 80, 20, 80] m_f = [60, 80, 80, 20, 80] print(is_allocable(d, m_s))
e8278e64263352c641d5b0d76588c055cee6b294
mhejl/howto
/python_lessons/examples/example_02.py
1,016
3.59375
4
# magic methods # Typy class Point2: def __init__(self, x=0.0, y=0.0): self._x = x self._y = y @property def x(self): return self._x @x.setter def x(self, value): self._x = value @property def y(self): return self._y #override def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) # return self.x == other.x and self.y == other.y def __hash__(self): return hash([self.x, self.y]) def Point3(Point2): def __init__(self, x, y, z): super().__init__(x, y) self._z = z @property def z(self): return self._z def __eq__(self, other): pass def __hash_(self): pass pa = Point2(1, 2) pb = Point2(1, 1) print(pa == pb) pa.x = 'blbost' pa.y = 'blbost' print(pa.x) #print(pa) #print(dir(pa)) # operace def vector2_plus(lhs, rhs): """ lhs/rhs jsou n-tice """ (lhs[0] + rhs[0], lhs[1] + rhs[1])
790fcdd7026304cddc50dc13d69de109ddfa7554
JulyKikuAkita/PythonPrac
/cs15211/SentenceScreenFitting.py
4,121
4
4
__source__ = 'https://leetcode.com/problems/sentence-screen-fitting/' # Time: O(r + n * c) # Space: O(n) # # Description: 418. Sentence Screen Fitting # # Given a rows x cols screen and a sentence represented by a list of non-empty words, # find how many times the given sentence can be fitted on the screen. # # Note: # # A word cannot be split into two lines. # The order of words in the sentence must remain unchanged. # Two consecutive words in a line must be separated by a single space. # Total words in the sentence won't exceed 100. # Length of each word is greater than 0 and won't exceed 10. # 1 <= rows, cols <= 20,000. # Example 1: # # Input: # rows = 2, cols = 8, sentence = ["hello", "world"] # # Output: # 1 # # Explanation: # hello--- # world--- # # The character '-' signifies an empty space on the screen. # Example 2: # # Input: # rows = 3, cols = 6, sentence = ["a", "bcd", "e"] # # Output: # 2 # # Explanation: # a-bcd- # e-a--- # bcd-e- # # The character '-' signifies an empty space on the screen. # Example 3: # # Input: # rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] # # Output: # 1 # # Explanation: # I-had # apple # pie-I # had-- # # The character '-' signifies an empty space on the screen. # Hide Company Tags Google # Hide Tags Dynamic Programming import unittest # 460ms 7.30% class Solution(object): def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ def words_fit(sentence, start, cols): if len(sentence[start]) > cols: return 0 s, count = len(sentence[start]), 1 i = (start + 1) % len(sentence) while s + 1 + len(sentence[i]) <= cols: s += 1 + len(sentence[i]) count += 1 i = (i + 1) % len(sentence) return count wc = [0] * len(sentence) for i in xrange(len(sentence)): wc[i] = words_fit(sentence, i, cols) words, start = 0, 0 for i in xrange(rows): words += wc[start] start = (start + wc[start]) % len(sentence) return words / len(sentence) class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: Say sentence=["abc", "de", "f], rows=4, and cols=6. The screen should look like "abc de" "f abc " "de f " "abc de" Consider the following repeating sentence string, with positions of the start character of each row on the screen. "abc de f abc de f abc de f ..." ^ ^ ^ ^ ^ 0 7 13 18 25 Our goal is to find the start position of the row next to the last row on the screen, which is 25 here. Since actually it's the length of everything earlier, we can get the answer by dividing this number by the length of (non-repeated) sentence string. Note that the non-repeated sentence string has a space at the end; it is "abc de f " in this example. Here is how we find that position. In each iteration, we need to adjust start based on spaces either added or removed. "abc de f abc de f abc de f ..." // start=0 012345 // start=start+cols+adjustment=0+6+1=7 (1 space removed in screen string) 012345 // start=7+6+0=13 012345 // start=13+6-1=18 (1 space added) 012345 // start=18+6+1=25 (1 space added) 012345 # # 16ms 48.14% class Solution { public int wordsTyping(String[] sentence, int rows, int cols) { String s = String.join(" ", sentence) + " "; int start = 0, l = s.length(); for (int i = 0; i < rows; i++) { start += cols; if (s.charAt(start % l) == ' ') { start++; } else { while (start > 0 && s.charAt((start-1) % l) != ' ') { start--; } } } return start / s.length(); } } '''
15c638e41aa61e84a8eba2d1b00bb6451095ff6c
marcelogabrielcn/ExerciciosPython
/exe062 - Super progressão aritmética v3-0.py
477
3.921875
4
print('Gerador de PA') print('-=-' * 10) primeiro = int(input('Qual o primeiro termo da PA? ')) razao = int(input('Digite a razão da PA: ')) termo = primeiro cont = 1 total = 0 mais = 10 while mais != 0: total += mais while cont <= total: print('{} > '.format(termo), end='') termo += razao cont += 1 print('PAUSA') mais = int(input('Você quer ver mais quantos termos? >')) print('Progressão finalizada com {} termos'.format(total))
ec3d5e79c1eb7c7a02935e2465e5c0854e130b44
SoniaPuri1/FST-M1
/Python/Activities/Activity 7.py
186
3.890625
4
# List Sum Calculator numbers = list(input("Enter the numbers seperated by commas:").split (",")) #numbers = [3,4,5] sum = 0 for i in numbers: sum += int(i) print (sum)
1f3bcda2373388f6cb9072a6acc4e764e2ffc057
ataylor1184/cse231
/Proj04/proj04.py
2,352
4.09375
4
#============================================================================== # This program is used to determine if you are laughing or not # It does so by checking for patterns in the charectors entered # Any combination of H followed by A or O followed by H again # and ending in !, is considered laughing #============================================================================== def get_ch(): ch= "test" while ch!= "": ch = input("Enter a character or press the Return key to finish: ") if len(ch)<=1 and ch.isalpha: #checks length of charector entered return ch #returns charector else: print("Invalid input, please try again.") def find_state(state, ch): st = state if ch != "": #if charector is blank, return the state if st ==1: if ch=='h': #checks if first letter is an H st=2 return st #sets state to 2, to check next letter else : st = 5 return st if st ==2: if ch== 'o' or ch=='a': #check if next letter is an A or O st =3 #moves on to third state return st else : st=5 return st if st ==3: if ch== 'h': #If letter is an H, next letter that is checked is st =2 #O or A, so back to state 2 return st elif ch =='!': st = 4 else : st=5 return st if st ==4: if ch== '!': st =4 return 4 else : st =5 return 5 else : return st pass def main(): user_input ="" state_count = 1 print("I can recognize if you are laughing or not.") print("Please enter one character at a time.") string = "empty" while string != "": string = get_ch() user_input += string state_count = find_state(state_count,string) #recursively calls itself print("\nYou entered", user_input) if state_count ==4: print("You are laughing.") else : print("You are not laughing.") main()
762e774b05b606950e767b836602a5caa2cee608
tibetsam/learning
/hashlogin.py
609
3.640625
4
import hashlib db={} def register(): username=input('Username:') password=input('Password:') #global db h_password=password+username+'the-Salt' db[username]=hashlib.md5(h_password.encode('utf-8')).hexdigest() print ('Done!') return def login(): username=input('Username:') password=input('Password:') #global db h_password=password+username+'the-Salt' if db[username]==hashlib.md5(h_password.encode('utf-8')).hexdigest(): print('Login correct!') else: print('Username or password is not correct!') return register() login()
6d3ff0db4352d992bbdebdfd957bc069e9f62b8c
BerezinAlexander/edge_op
/edge_op/primitives.py
2,775
3.984375
4
# Примитивы from math import sqrt class Point(object): x = 0 y = 0 def __init__(self, crd=[0, 0]): self.x = crd[0] self.y = crd[1] def crd(self, crd): self.x = crd[0] self.y = crd[1] def getList(self): return [self.x, self.y] class Line(object): xy0 = Point() xy1 = Point() coef = [] def __init__(self, crd=[Point(), Point([1,1])]): self.xy0 = crd[0] self.xy1 = crd[1] # расчет коэффициентов прямой по координатам двух точек def equationLine(self): EPS = 1e-6 #если точки совпадают, то по ним нельзя построить прямую if (self.xy0.x == self.xy1.x & self.xy0.y == self.xy1.y): return # получение коэффициентов прямой по координатам двух точек a = self.xy0.y - self.xy1.y b = self.xy1.x - self.xy0.x c = -1 * (self.xy0.y - self.xy1.y) * self.xy0.x - (self.xy1.x - self.xy0.x) * self.xy0.y # нормировка прямой z = sqrt(a * a + b * b) a /= z b /= z c /= z if ((a < -EPS) | ((abs(a) < EPS) & (b < -EPS))): a *= -1 b *= -1 c *= -1 self.coef = [a, b, c] # расчет определителя def det(x11, x12, x21, x22): return x11 * x22 - x12 * x21 # нахождение общей точки текощей линии с линией line def commonPoint(self, line): # [0] - прямые параллельны и не пересекаются # [1, res] - прямые пересекаются в одной точке, res - координаты пересечения # [2] - прямые совпадают и имеет бесконечно точек пересечения EPS = 1e-6 denom = Line.det(self.coef[0], self.coef[1], line.coef[0], line.coef[1]) if (abs(denom) < EPS): # прямые совпадают и имеет бесконечно точек пересечения if (self.coef[2] == line.coef[2]): return [2] # прямые параллельны и не пересекаются return [0] # прямые пересекаются в одной точке, вычисляем координаты res = Point() res.x = int(Line.det(-self.coef[2], self.coef[1], -line.coef[2], line.coef[1]) / denom) res.y = int(Line.det( self.coef[0], -self.coef[2], line.coef[0], -line.coef[2]) / denom) return [1, res]
d8bfcd767d37e8f97c5ea68272467c6ad2e4214a
sheikh210/LearnPython
/program_control_flow/forLoops.py
861
4.09375
4
parrot = "Norwegian Blue" # Similar for for-each loop in Java - Define the variable (character) contained within the iterable object (parrot) # for character in parrot: # print(character) # value = "9,342;534,029 134-390]619" # separators = "" # # for char in value: # if not char.isnumeric(): # separators = separators + char # # print(separators) # Similar to regular for-loops in java - Define a range and iterate n number of times for i in range(1, 20): print("i is {}".format(i)) # If you just want the loop to run n number of times, don't give a start value for i in range(10): print("Aamna & Sami") # If you'd like to step a distinct amount through the loop, you can provide a step value that is smaller than the # stop value, but you also have to include the start value for i in range(0, 10, 2): print("Sami & Aamna")
32f961efcf6ca43b127757ff24e613a8d9bb6406
SaidNM/Teoria-Computacional
/AutomataNoDet/AND.py
1,030
3.8125
4
def automata(cadena): estados=[] trayectoria=[] estado=0 for elemento in cadena: if (estado==0): estado=estadoCero(elemento,trayectoria) estados.append(trayectoria) print elif(estado==1): estado=estadoUno(elemento,trayectoria) estados.append(trayectoria) elif(estado==2): estado=estadoDOs(elemento,trayectoria) estados.append(trayectoria) else: return -1 return estados def estadoCero(elemento,trayectoria): if(elemento=='0'): trayectoria.append("q0") trayectoria.append("q1") return 1 elif(elemento=='1'): trayectoria=[] trayectoria.append("q0") return 0 else: return -1 def estadoUno(elemento,trayectoria): if(elemento=='0'): trayectoria=[] trayectoria.append("q0") return 0 elif(elemento=='1'): trayectoria.append("q2") return 2 else: return -1 def estadoDos(elemento,trayectoria): if(elemento=="0"): trayectoria=[] trayectoria.append("q0") return 0 elif(elemento=="1"): trayectoria=[] trayectoria.append("q0") return 0 else: return -1
3b63da543d2c5644c343e685a1c487a3adcfb0dc
cwhsu023/pbc_project
/mousedrawline.py
570
3.703125
4
from tkinter import * def main(): root = Tk() w = Canvas(root, width=200, height=200, background="white") w.pack() def _paint(event): # event.x 鼠標左鍵的橫坐標 # event.y 鼠標左鍵的縱坐標 x1, y1 = (event.x - 1), (event.y - 1) x2, y2 = (event.x + 1), (event.y + 1) w.create_oval(x1, y1, x2, y2, fill="red") # 鼠標左鍵一點,就畫出了一個小的橢圓 # 畫布與鼠標左鍵進行綁定 w.bind("<B1-Motion>", _paint) mainloop() if __name__ == '__main__': main()
3d7781bd3539eb1aef91e797867eafd8a6ac21d5
candyer/leetcode
/2020 September LeetCoding Challenge/21_carPooling.py
2,304
4.1875
4
# https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3467/ # Car Pooling # You are driving a vehicle that has capacity empty seats initially available for passengers. # The vehicle only drives east (ie. it cannot turn around and drive west.) # Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about # the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and # drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location. # Return true if and only if it is possible to pick up and drop off all passengers for all the given trips. # Example 1: # Input: trips = [[2,1,5],[3,3,7]], capacity = 4 # Output: false # Example 2: # Input: trips = [[2,1,5],[3,3,7]], capacity = 5 # Output: true # Example 3: # Input: trips = [[2,1,5],[3,5,7]], capacity = 3 # Output: true # Example 4: # Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11 # Output: true # Constraints: # trips.length <= 1000 # trips[i].length == 3 # 1 <= trips[i][0] <= 100 # 0 <= trips[i][1] < trips[i][2] <= 1000 # 1 <= capacity <= 100000 ##################################################################### from typing import List def carPooling(trips: List[List[int]], capacity: int) -> bool: if not trips: return True trips.sort(key=lambda x:x[1]) passengers = [0] * 1001 for num, start, end in trips: for i in range(start, end): if passengers[i] > capacity - num: return False passengers[i] += num return True ##################################################################### from typing import List def carPooling(trips: List[List[int]], capacity: int) -> bool: change = [] for num, start, end in trips: change.append([start, num]) change.append([end, -num]) change.sort() passengers = 0 for stop, num in change: passengers += num if passengers > capacity: return False return True assert(carPooling([[2,1,5],[3,3,7]], 4) == False) assert(carPooling([[2,1,5],[3,3,7]], 5) == True) assert(carPooling([[2,1,5],[3,5,7]], 3) == True) assert(carPooling([[3,2,7],[3,7,9],[8,3,9]], 11) == True) assert(carPooling([[9,3,4],[9,1,7],[4,2,4],[7,4,5]], 23) == True)
1e7c0ddb3d83bb26eebd6b60b4b06a18c1789fa9
andiainunnajib/basic-python-b7-b
/if_else.py
192
3.875
4
a = int(input("Masukkan a: ")) b = int(input("Masukkan b: ")) if a > b: print("a lebih besar dari b") elif a == b: print("a sama besar dari b") else: print("a lebih kecil dari b")
4242b7b75a6d54426ba38b7fc3c4dfe4fc599df0
kamaalpalmer/StockPredictionML
/p2data/quartiles.py
891
3.6875
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np file_name = "dow_jones_index.data.csv" #f = open(file_name) #data = pd.loadtxt(fname=f, delimiter = ',') # these come from reading the names file; could be first line in some datasets cols = ['quarter', 'open', 'high', 'low', 'close', 'volume', 'percent_change_price', 'percent_change_volume_over_last_wk', 'previous_weeks_volume', 'next_weeks_open', 'next_weeks_close', 'days_to_next_dividend','percent_return_next_dividend','percent_change_next_weeks_price'] # this adds the column headers to the data frame while reading in the data data = pd.read_csv(file_name, names=cols) # use the column for pregnancies, make three bins, use numbers, not labels newcol = pd.qcut(data['percent_change_next_weeks_price'], 3, labels=False) print(newcol) data['q_percent_change_next_weeks_price'] = newcol print(data)
13d608787bebef1f66a9dd9c9b313fbf072be824
gabriellaec/desoft-analise-exercicios
/backup/user_084/ch59_2020_03_17_22_52_16_143390.py
105
3.703125
4
def asteriscos(n): n=int(input('escolha um numero positivo: ') y='*' print (y*n) return n
feeb8440c5d9d636922f153694a2aeab6a4ce988
Nimor111/101-v5
/week6/stack.py
986
3.90625
4
class Node: def __init__(self, value=None, link=None): self.value = value self.link = link class Stack: def __init__(self): self.start = None def empty(self): return self.start is None def push(self, el): if self.empty(): self.start = Node(el) else: new = Node(el, self.start) self.start = new def pop(self): if self.empty(): raise "Empty stack!" else: value = self.start.value self.start = self.start.link return value def pprint(self): res = [] while self.start is not None: res.append(str(self.start.value)) self.start = self.start.link return "->".join(res) def main(): stack = Stack() stack.push(5) stack.push(4) stack.push(3) stack.push(2) print(stack.pop()) print(stack.pprint()) if __name__ == '__main__': main()
100a059e463491f97c8508893bdbc5a54a210346
nbonham/507project1
/gradecalc.py
6,323
4.03125
4
#import csv ## Part 1: [8 pts] Create a dictionary of the student that is organized as shown [note that the dictionary is “pretty printed” here for readability--you don’t need to do this. Just calling print(my_dict) is OK] : - DONE ## {'Julie': {‘Assn 1’:'9', ‘Assn 2’: '19', ‘Assn 3’: '9', ‘Final Exam’: '22'}, ## Student Assn 1 Assn 2 Assn 3 Final Exam # initialize dictionaries studentGrades = {} assignments = {} finalGrades = {} count = 0 # open the file, script out new lines and then create lists for stuff needed later, like headers, weights and max points. Also create a dictionary with keys as student names and values as a dictionary of their grades fhand = open("gradebook.csv") for line in fhand : line = line.strip('\n') items = line.split(",") #print(type(items)) if line.startswith("Student") : headers = line.split(",") #print(headers) elif line.startswith("weight"): weights = line.split(",") elif line.startswith("max_points"): maxpoints = line.split(",") else: studentGrades[items[0]] = {headers[1] : items[1], headers[2] : items[2], headers[3] : items[3], headers[4]:items[4]} fhand.close() print('PART 1') print(studentGrades) print('') #print(headers) #print(weights) #print(maxpoints) ## Part 2: [8 pts] Create a dictionary of the assignment weights and point values that is organized as shown [note that the dictionary is “pretty printed” here for readability--you don’t need to do this.Just calling print(my_dict) is OK]: ## {'Assn 1': {'weight': '0.15', 'max_points': '12'}, # needed to deal with the "student" in the header and then used similar process as in part 1 for header in headers : if header == "Student" : continue else : try: count += 1 assignments[header] = {'weight' : weights[count], 'max_points' : maxpoints[count]} except: continue print('PART 2') print(assignments) print('') ## Part 3: [8 pts] Create a function ‘student_average(student_name)’ that returns the weighted final grade for the student whose name is passed into the function. [The “weighted average” is the sum of (weight * percentage grade) for all of a student’s assignments]. Print() each student’s weighted average to the console like so (your output should match the following): ## Julie : 84.33333333333333 print('PART 3') def student_average(student_name) : avg = 0 #print(studentGrades[student_name]) a1 = (float(studentGrades.get(student_name).get("Assn 1")) / float(assignments.get('Assn 1').get('max_points'))) * float(assignments.get('Assn 1').get('weight')) a2 = (float(studentGrades.get(student_name).get("Assn 2")) / float(assignments.get('Assn 2').get('max_points'))) * float(assignments.get('Assn 2').get('weight')) a3 = (float(studentGrades.get(student_name).get("Assn 3")) / float(assignments.get('Assn 3').get('max_points'))) * float(assignments.get('Assn 3').get('weight')) final = (float(studentGrades.get(student_name).get("Final Exam")) / float(assignments.get('Final Exam').get('max_points'))) * float(assignments.get('Final Exam').get('weight')) avg = (a1 + a2 + a3 + final)*100 return str(avg) # (grade / max) * weight = total for student in studentGrades : print(student + " : " + student_average(student)) print('') ## Part 4: [6 pts] Create a function ‘assn_average(assn_name)” that returns the average score *as a percentage* for that assignment, across all students. Print() the average score for each assignment, like so (your output should match the following): print('PART 4') # loop through the students and return their grades for the assignment name that is passed through, sum the grades, sum the max points and then calculate the average, returning the result classAvgList = [] def assn_average(assn_name): classSum = 0 classMax = 0 for student in studentGrades : #print(student) classSum += float(studentGrades.get(student).get(assn_name)) classMax += float(assignments.get(assn_name).get('max_points')) classAvg = (classSum / classMax)*100 classAvgList.append(classAvg) return classAvg # loop through the assignment names and pass them into the assn_average function. If statement to skip pass the "students" item in the list for header in headers : if header == "Student" : continue else : print(header + " : " + str(assn_average(header))) print('') ## Part 5: [5 pts extra credit] Create a function ‘format_gradebook()’ that uses string.format() to generate a single string that, when printed out, looks like this. print('PART 5') def format_gradebook(): totalClassAvg = 0 totalClassGrade = 0 c = 0 rowHeaders = "{0:<12}{1:>12}{2:>12}{3:>12}{4:>12}{5:>12}".format(headers[0], headers[1], headers[2], headers[3], headers[4],'Grade') print(rowHeaders) print('-'*75) for student in studentGrades : a1 = float(studentGrades.get(student).get("Assn 1"))/float(assignments.get("Assn 1").get('max_points'))*100 a2 = float(studentGrades.get(student).get("Assn 2"))/float(assignments.get("Assn 2").get('max_points'))*100 a3 = float(studentGrades.get(student).get("Assn 3"))/float(assignments.get("Assn 3").get('max_points'))*100 fe = float(studentGrades.get(student).get("Final Exam"))/float(assignments.get("Final Exam").get('max_points'))*100 grade = a1*float(weights[1])+a2*float(weights[2])+a3*float(weights[3])+fe*float(weights[4]) totalClassGrade += grade c += 1 rowStudent = "{0:<12}{1:>11.1f}%{2:>11.1f}%{3:>11.1f}%{4:>11.1f}%{5:>11.1f}%".format(student,a1, a2, a3, fe, grade) print(rowStudent) print('-'*75) totalClassAvg = totalClassGrade / c rowAverages = "{0:<12}{1:>11.1f}%{2:>11.1f}%{3:>11.1f}%{4:>11.1f}%{5:>11.1f}%".format('Average',float(classAvgList[0]),float(classAvgList[1]),float(classAvgList[2]),float(classAvgList[3]),totalClassAvg) print(rowAverages) #print("nevermind, realized how much I would have to refactor my code to make this not be a pain in the butt...") format_gradebook()
36f1357972f91991d331161536171d44ecbc0972
diego-garcia-martin/PythonIntroCourse
/Ejemplo.py
609
3.578125
4
import turtle import random import player turtle.bgcolor("black") turtle.screensize(800, 400) # de -400 a 400 en x y de -200 a 200 en y bob = player.Player("Bob", "blue", -400, -200) joe = player.Player("Joe", "red", -400, 0) susan = player.Player("Susan", "pink", -400, 200) for i in range(1000): bob.move() joe.move() susan.move() if bob.x > 100: print(f"{bob.name} es el ganador!!!") break if joe.x > 100: print(f"{joe.name} es el ganador!!!") break if susan.x > 100: print(f"{susan.name} es el ganador!!!") break turtle.done()
c760117b6f3ea8b0cb7479606fac216d744d739a
xuanziwenzi/pythonzixue
/haohaoxuexi/ceshi.py
470
4.1875
4
##print('hello,',end = ' ') ##print('world.') #5.4.2 ##name = input('what is your name? ') ##if name.endswith(name): ## print("hello,Mr.{}".format(name)) ## #5.4.5 name = input('what is your name?') if name.endswith('gumby'): if name.startswith("mr."): print('hello,mr.gumby') elif name.startswith('mrs.'): print('hello,mrs.gumby') else : print('hello,gumby') else : print('hello,stringer')
cbc0add73868064ff808641b3315463cbfa1185b
EricPoehlsen/Echo
/irc_socket.py
4,369
3.703125
4
import socket import datetime import platform import os class IRC: irc = socket.socket() def __init__(self): self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def send(self, msg): """ sends a raw message to the server Note: Commands are implemented as separate methods and will call the send method. Args: msg (str): the raw message to send """ self.irc.send(bytes(msg + "\n", "utf-8")) print("OUT: ", msg) def recv(self): """ This is the socket listener Returns str """ msg = str(self.irc.recv(2040), "utf-8") # receive the text return msg def privmsg(self, reciever, msg): self.send("PRIVMSG " + reciever + " " + msg) def mode(self, receiver, mode): self.send("MODE " + receiver + " " + mode) def connect(self, nick=None, real=None, server=None, port=6667): # defines the socket print("connecting to:" + server) self.irc.connect((server, 6667)) # connects to the server user_msg = " ".join(["USER", nick, nick, nick, real]) self.send(user_msg) nick_msg = "NICK " + nick self.send(nick_msg) def join(self, channel): self.send("JOIN " + channel) def pong(self, msg): self.send("PONG " + msg) def quit(self): self.send("QUIT :shutting down ...") def identify(self, password): self.send("IDENTIFY " + password) # ctcp handlers def ctcp_send(self, receiver, msg): privmsg = "PRIVMSG " + receiver + " :" msg = chr(1)+msg+chr(1) self.send(privmsg + msg) def ctcp_version(self, sender): notice = "NOTICE " + sender + " :" name = "Echo Bot" version = "0.0a" os_info = " ".join([ platform.system(), platform.version(), platform.machine() ]) info = [name, version, os_info] msg = chr(1) + "VERSION " + " : ".join(info) + chr(1) self.send(notice + msg) def ctcp_finger(self, sender): notice = "NOTICE " + sender + " :" info = "This Echo Bot is run by Eric Poehlsen - "\ "https://www.eric-poehlsen.de" msg = chr(1) + "FINGER :" + info + chr(1) self.send(notice + msg) def ctcp_source(self, sender): notice = "NOTICE " + sender + " :" info = "The source code of Echo Bot is available at "\ "https://github.com/EricPoehlsen/Echo" msg = chr(1) + "SOURCE :" + info + chr(1) self.send(notice + msg) def ctcp_time(self, sender): notice = "NOTICE " + sender + " :" time = str(datetime.datetime.now()) msg = chr(1) + "TIME :" + time + chr(1) self.send(notice + msg) def ctcp_ping(self, sender, msg): notice = "NOTICE " + sender + " :" self.send(notice + msg) def ctcp_clientinfo(self, sender, msg): notice = "NOTICE " + sender + " :" info = "EchoBot 0.0a Supported tags: " implemented = [ "PING", "VERSION", "CLIENTINFO", "USERINFO", "FINGER", "SOURCE", "TIME", "ACTION", ] not_implemented = [ "AVATAR", "DCC", "PAGE" ] msg = chr(1) + "TIME :" + info + chr(1) self.send(notice + msg) def ctcp_error(self, sender, msg, nickname): print("trying to send error") notice = "NOTICE " + sender + " :" command = msg.replace(chr(1), "") if command.startswith("ERRMSG"): info = "You have successfully queried my error message ..." else: info = "{cmd} : unknown request. Try /CTCP {nick} CLIENTINFO".format( cmd=command, nick=nickname ) out_msg = chr(1) + "ERRMSG :" + info + chr(1) print(notice + out_msg) # self.send(notice + out_msg) """ USERINFO - A string set by the user (never the client coder) CLIENTINFO - Dynamic master index of what a client knows. PING - Used to measure the delay of the IRC network between clients. TIME - Gets the local date and time from other clients. """
97632073e77fa86f4de1b82e6a193c51ee0e9fd5
ASHISH-KUMAR-PANDEY/python
/Sum_of_GP.py
439
3.765625
4
# Python Program to find Sum of Geometric Progression Series import math def sumofGP(a, n, r): total = (a * (1 - math.pow(r, n ))) / (1- r) return total a = int(input("Please Enter First Number of an G.P Series: : ")) n = int(input("Please Enter the Total Numbers in this G.P Series: : ")) r = int(input("Please Enter the Common Ratio : ")) total = sumofGP(a, n, r) print("\nThe Sum of Geometric Progression Series = " , total)
23b412ba192528b76a5d1b8b6623a77ec238b19a
sukanta-27/DSA_prep
/Stack/ExpressionConversion.py
2,207
3.71875
4
class Conversion: def __init__(self): self.stack = [] self.precedence = { '(': 0, '+': 1, '-': 1, '*': 2, '/': 2 } def greaterThanOrEqualToTop(self, operator): # Checks if the operator in greater in terms of precedence or not compared to the top element if self.precedence[self.stack[-1]] < self.precedence[operator]: return True return False def infixToPostfix(self, expression): result = [] for i in expression: # print(self.stack) if i.isalnum(): result.append(i) elif i == '(': self.stack.append(i) elif i == ')': while len(self.stack) > 0 and self.stack[-1] != '(': result.append(self.stack.pop()) if self.stack[-1] == '(': self.stack.pop() else: if len(self.stack) > 0 and not self.greaterThanOrEqualToTop(i): while len(self.stack) > 0 and not self.greaterThanOrEqualToTop(i): result.append(self.stack.pop()) self.stack.append(i) else: self.stack.append(i) while len(self.stack) > 0: x = self.stack.pop() result.append(x) postfix = ''.join(result) print(f"Infix: {expression} \t Postfix: {postfix}") return postfix def infixToPrefix(self, expression): reverse_expression = [] for i in reversed(expression): if i == ')': reverse_expression.append('(') elif i == '(': reverse_expression.append(')') else: reverse_expression.append(i) postfix = self.infixToPostfix("".join(reverse_expression)) prefix = postfix[::-1] print(f"Infix: {expression} \t Prefix: {prefix}") return prefix c = Conversion() c.infixToPostfix("2+3*4+5+6") c.infixToPostfix("(2+3*4+(5+6))") c.infixToPrefix("2+3*4+5+6") c.infixToPrefix("(2+3*4+(5+6))") c.infixToPrefix("A+B*C/(E-F)")
2ad2919a717ce6810501d0695f22768bd01f5f86
Naveen479/python
/test_input2.py
267
4
4
#!/usr/bin/python name = raw_input('what is your name::') age = int(raw_input('what is your age::')) income = float(raw_input('what is your income::')) print ('Here is the data you entered::') print ('Name:', name) print ('age:',age) print ('income:',income)
6849fbe05f25e8a5bb05e493feee3598b098099a
bnow0806/sparta_algorithm
/week3/08_queue.py
1,282
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.tail = None def enqueue(self, value): # 어떻게 하면 될까요? #head tail #[3] -> [4] -> [5] new_node = Node(value) if self.is_empty() is True: self.head = new_node self.tail = new_node return self.tail.next = new_node self.tail = new_node return def dequeue(self): # 어떻게 하면 될까요? # head tail # [3] -> [4] -> [5] if self.is_empty(): return "Queue is empty" deleted_data = self.head.data self.head = self.head.next return deleted_data def peek(self): # 어떻게 하면 될까요? if self.is_empty(): return "Queue is empty" return self.head.data def is_empty(self): # 어떻게 하면 될까요? return self.head is None queue = Queue() queue.enqueue(3) queue.enqueue(4) queue.enqueue(5) print(queue.peek()) print(queue.dequeue()) print(queue.dequeue()) print(queue.dequeue()) print(queue.dequeue()) print(queue.is_empty())
163aca2f8d5d5bc47c6947e0a38897af7a21ef09
MrCellenge/kodeklubben
/steg 8.py
430
3.875
4
from turtle import* from random import randrange,choice colors=['red','blue','green','purple','yellow','lime'] def poly(sides,length): angle=360/sides for n in range(sides): forward(length) right(angle) for count in range(10): pencolor(choice(colors)) right(randrange(0,360)) penup() forward(randrange(20,100)) pendown() poly(randrange(3,9),randrange(10,30))
4f0c05ef624fc4639114b676b38d5979990ee934
tubaDude99/Old-Python-Exercises
/Unit 1/3Practice3a.py
4,042
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # Lab 3a # ## Conditionals Practice # # ----- # # ### Student will be able to # - **Control code flow with `if`... `else` conditional logic** # - Using Boolean string methods (`.isupper(), .isalpha(), startswith()...`) # - Using comparision (`>, <, >=, <=, ==, !=`) # - Using Strings in comparisons # ## `if else` # # In[3]: # [ ] input a variable: age as digit and cast to int # if age greater than or equal to 12 then print message on age in 10 years # or else print message "It is good to be" age age = int(input("How old are you? ")) if age >= 12: print("In 10 years you will be " + str(age + 10)) else: print("It is good to be " + str(age)) # In[7]: # [ ] input a number # - if number is NOT a digit cast to int # - print number "greater than 100 is" True/False x = input() if type(x) != int: x = int(x) print(str(x) + " greater than 100 is " + str(x>100)) # ### Guessing a letter A-Z # **check_guess()** takes two string arguments: **letter and guess** (both expect single alphabetical character) # - If guess is not an alpha character print invalid and return False # - Test and print if guess is "high" or "low" and return False # - Test and print if guess is "correct" and return True # In[12]: # [ ] create check_guess() # call with test def check_guess(letter,guess): if guess.isalpha() == False: print("invalid") return(False) elif guess == letter: print("correct") return(True) elif guess > letter: print("high") return(False) elif guess < letter: print("low") return(False) # In[13]: # [ ] call check_guess with user input def check_guess(letter,guess): if guess.isalpha() == False: print("invalid") return(False) elif guess == letter: print("correct") return(True) elif guess > letter: print("high") return(False) elif guess < letter: print("low") return(False) print(check_guess("b",input("What's your guess? "))) # ### Letter Guess # **Create letter_guess() function that gives the user three guesses** # - Take a letter character argument for the answer letter # - Get user input for letter guess # - Call check_guess() with answer and guess # - End letter_guess if # - check_guess() equals True, return True # - or after 3 failed attempts, return False # In[5]: # [ ] create letter_guess() function, call the function to test def check_guess(letter,guess): if guess.isalpha() == False: print("invalid") return(False) elif guess == letter: print("correct") return(True) elif guess > letter: print("high") return(False) elif guess < letter: print("low") return(False) def letter_guess(answer): i = 0 check = "b" while check != True and i < 3: check = check_guess(answer,input("What is your guess? ")) i = i + 1 letter_guess("b") # ### Pet Conversation # **Ask the user for a sentence about a pet and then reply** # - Get user input in variable: about_pet # - Using a series of **if** statements, respond with appropriate conversation # - Check if "dog" is in the string about_pet (sample reply "Ah, a dog") # - Check if "cat" is in the string about_pet # - Check if 1 or more animal is in string about_pet # - No need for **else**'s # - Finish by thanking for the story # In[9]: # [ ] complete pet conversation about_pet = input("What kind of pet do you have? ").lower() if "dog" in about_pet: print("Ah, a dog") if "cat" in about_pet: print("Ah, a cat") if "cat" in about_pet or "dog" in about_pet or "fish" in about_pet or "bird" in about_pet or "lizard" in about_pet: print("Ah, one or more animals") print("Thank you for the story") # [Terms of use](http://go.microsoft.com/fwlink/?LinkID=206977) &nbsp; [Privacy & cookies](https://go.microsoft.com/fwlink/?LinkId=521839) &nbsp; © 2017 Microsoft
96b732d47eaecd42a72402443f121b7cfe089fc9
pratheep123/guvi222
/sumofdigits.py
140
4
4
a=int(input("Enter the digits:")) sum=0 while (a>0): remainder=a%10 a=a//10 sum=sum+remainder print("The sum of a:",sum)
89e238c6b24747beb8955a61673a4e1ee706ebc5
yichong-sabrina/learn-python
/Chap1 Basis/1_2 List Tuple.py
1,245
4.5625
5
# List MyClass = ['Alice', 'Bob', 'Cindy', 'David', 'Edgar', 'Frida'] print(MyClass[0]) # Subscript begins from 0 print(MyClass[-1]) # Subscript -1 represents the last element length = len(MyClass); print(length) # len( ) MyClass.append('George') # Add elements: append / insert MyClass.insert(0, 'Zero') print(MyClass) MyClass.pop() # Delete elements: pop MyClass.pop(-3) print(MyClass) MyClass[1] = 'Anna' # Replace elements print(MyClass) NextClass = ['ABC', 1, 2.345, True, MyClass] # Different types of elements can be included in one list print(NextClass) print(NextClass[-1][1]) Empty = [ ] # Empty List print(Empty, len(Empty)) # Tuple Tuple_1 = (1, 2, 3) # Elements in tuples cannot be changed Tuple_2 = (1, ) # A tuple with one element must include a comma!! Typle_3 = ( ) # Empty tuple print(Tuple_1, Tuple_2, Typle_3)
160215f284f94194c83a13433cbffd0f118c1572
GabrielJar/Python
/1a semana/fatura.py
342
3.8125
4
name = input("Digite o nome do cliente: ") expirationDay = input("Digite o dia do vencimento: ") expirationMonth = input("Digite o mês do vencimento: ") value = input("Digite o valor da fatura: ") print("Olá, ", name) print("A sua fatura com vencimento em", expirationDay, "de", expirationMonth, "no valor de R$", value, " está fechada.")
7eca02ae0bd62b82085d35368a661b327d0063df
to-yuki/pythonLab-v3
/sample/4/Other_Function.py
379
3.625
4
# デフォルト引数 def funcDefArg(x=0,y=0): print(x) print(y) funcDefArg() # 任意引数 def funcMultiArg(*n): print(n) print(n[2]) funcMultiArg(10,20,30,40) def funcKeyArg(id='null',name='null'): print(id) print(name) # キーワード引数を使用した呼び出し funcKeyArg(name='Yamada',id='001') # ラムダ式 f = lambda x: x + 1 ans = f(5) print(ans)
162bf9c2b95fb5a7b13cf9c577fc71bf1eabaa17
victorh800/sfcurves
/tests/hilbert_outline.py
1,097
3.625
4
#!/usr/bin/env python3 import sys import random from sfcurves.hilbert import forward, reverse, Algorithm from sfcurves.outline import wall_follower def assert_equals(actual, expected): if actual != expected: print(' actual:', actual) print('expected:', expected) assert False if __name__ == '__main__': # order 1 trace = wall_follower(4, 0, 0, forward, reverse) assert_equals(trace, [(0,0)]) trace = wall_follower(4, 0, 1, forward, reverse) assert_equals(trace, [(0,0), (0,1)]) trace = wall_follower(4, 0, 2, forward, reverse) assert_equals(trace, [(0,0), (0,1), (1,1), (0,1)]) # note the (0,1) attempt to return home trace = wall_follower(4, 0, 3, forward, reverse) assert_equals(trace, [(0,0), (1,0), (1,1), (0,1)]) # note CCW travel around the square # order 2 trace = wall_follower(16, 0, 7, forward, reverse) assert_equals(trace, [(0,0), (1,0), (1,1), (1,2), (1,3), (0,3), (0,2), (0,1)]) trace = wall_follower(16, 2, 7, forward, reverse) assert_equals(trace, [(0,1), (1,1), (1,2), (1,3), (0,3), (0,2)]) # note the initial move left to find wall print('PASS')
4242c50449055d0f86fbafc64be56e995d722709
KPHippe/AccelerometerApplication
/pythonEchoServer/echoServer.py
1,080
3.71875
4
import socket #Creates a TCP Socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #We bind the socket to port 9999 s.bind(('', 9999)) #We allow 5 connections to be in the queue, we are waiting for 1 or more (up to 5) connections s.listen(5) while True: #We accept the incoming connection, wait for a connection if it doesn't come immediately clientsocket, address = s.accept() print(f"Connection from {address} has been established.") while True: message = '' #We wait for a message to come from the client and decode it message = clientsocket.recv(256).decode("utf-8") #if the length of the message is < 0, an error occured, we break and close the connection, see the client for why if len(message) <= 0: break print(f"Message from client: {message}") #we just send the info back to the client clientsocket.send(bytes(message,"utf-8")) #Close the socket, this is if there is an error clientsocket.close() print(f"Connection from {address} has been closed.")
96add58225e669eadd157d80f432fa6b94715d58
rblack42/math-magik-lpp
/mmdesigner/ArcAirfoil.py
1,009
3.734375
4
# -*- coding: utf8 -*- """ ArcAirfoil ~~~~~~~~~~ height function for circular arc airfoil """ import math class ArcAirfoil(object): """manage circular arc airfoil""" def __init__(self,chord, camber, spar_size): self.chord = chord c = chord - 2 * spar_size self.camber = camber self.spar_size = spar_size self.thickness = self.chord * self.camber/100 self.radius = c**2 / (8 * self.thickness) + self.thickness/2 def height(self,x): t = self.thickness r = self.radius ct = self.chord c = ct - 2 * self.spar_size x = x * ct if x < self.spar_size: return 0 if x > ct - self.spar_size: return 0 h = -r + t + math.sqrt((-c/2 + r + x)*(c/2 + r - x)) return h if __name__ == "__main__": print("Check circular arc airfoil height") a = ArcAirfoil(5,5,1/16) print("x=0 ->",a.height(0)) print("x=0.5 ->",a.height(0.5)) print("x=1 ->",a.height(1.0))
f9cf1703c0ef53c675f66995ed0a5ad16e4c747a
keionbis/SmartMouse_2018
/docs/ipynb_gen_py/DC Motor Simulation.py
5,417
3.796875
4
# coding: utf-8 # # DC Motor Simulation # Look at the dynamics_model.pdf for the explanation behind this code. # In[1]: import numpy as np import matplotlib.pyplot as plt # In[2]: def simulate(V, J, C, K, R, L, theta_dot=0, i=0): # simulate T seconds T = 5 dt = 0.01 ts = np.arange(0, T, dt) theta_dots = np.zeros(ts.shape[0]) currents = np.zeros(ts.shape[0]) for idx, t in enumerate(ts): A = np.array([[-C/J,K/J],[-K/L,-R/L]]) B = np.array([0, 1/L]) x = np.array([theta_dot, i]) w = V(t, i, theta_dot) x_dot = A@x+B*w # print(x_dot, theta_dot, i) theta_dot += (x_dot[0] * dt) i += (x_dot[1] * dt) theta_dots[idx] = theta_dot currents[idx] = i return ts, theta_dots, currents def const_V(v): def _v(t, i, theta_dot): return v return _v ts, theta_dots, _ = simulate(const_V(1), J=0.01, C=0.1, K=0.01, R=1, L=0.5) plt.figure() plt.plot(ts, theta_dots) plt.title("Motor response to 1v input") plt.ylabel("Speed (rad/s)") plt.xlabel("Time (seconds)") ts, theta_dots, _ = simulate(const_V(5), J=0.01, C=0.1, K=0.01, R=1, L=0.5) plt.figure() plt.plot(ts, theta_dots) plt.title("Motor response to 5v input") plt.ylabel("Speed (rad/s)") plt.xlabel("Time (seconds)") ts, theta_dots, _ = simulate(const_V(5), J=0.05, C=0.1, K=0.01, R=1, L=0.5) plt.figure() plt.plot(ts, theta_dots) plt.title("Heavier motor response to 5v input") plt.ylabel("Speed (rad/s)") plt.xlabel("Time (seconds)") ts, theta_dots, _ = simulate(const_V(5), J=0.05, C=0.1, K=0.01, R=1, L=0.5, theta_dot=1) plt.figure() plt.plot(ts, theta_dots) plt.title("Already spinning motor response to 5v input") plt.ylabel("Speed (rad/s)") plt.xlabel("Time (seconds)") plt.show() # In[3]: ts, theta_dots, currents = simulate(const_V(5), J=0.00005, C=0.0004, K=0.01, R=2.5, L=0.1) plt.figure(figsize=(11,5)) plt.subplot(121) plt.plot(ts, theta_dots * 0.0145) plt.title("Speed of realistic motor") plt.ylabel("Speed (meter/s)") plt.xlabel("Time (seconds)") plt.subplot(122) plt.plot(ts, currents) plt.title("Current of realistic motor") plt.ylabel("Current (amps)") plt.xlabel("Time (seconds)") plt.show() # we can use the slope of this line as our feed forward slope # We just need to convert from $\frac{v}{m*s^{-1}}$ to $\frac{f}{rad*s^{-1}}$ # # $$ \frac{\text{volts}}{m*s^{-1}}*\frac{255\text{ abstract force}}{5\text{ volts}}*\frac{0.0145\text{ meters}}{\text{radians}} $$ # # The invert this value. # ## Wheel inertia calculation # # $$ I_z = \frac{mr^2}{2} = \frac{0.0122*0.014^2}{2} = 0.0000011956 $$ # # \*source for mass & radius: https://www.pololu.com/product/1127 # # Solving IVP for DC Motor Model # # The following differential equation describes our dc motor model # # $$ \frac{K}{LJ}u = \ddot{y} + \bigg(\frac{C}{J} + \frac{RJ}{L}\bigg)\dot{y} + \bigg(\frac{RC}{LJ} + \frac{K^2}{LJ}\bigg)y $$ # # First find the generic solution to the homogeneous form: # # $$ 0 = \ddot{y} + \bigg(\frac{C}{J} + \frac{RJ}{L}\bigg)\dot{y} + \bigg(\frac{RC}{LJ} + \frac{K^2}{LJ}\bigg)y $$ # # If we plug in the following coefficients # # | Var | Value | # |-----|--------------| # | J | 0.000658 | # | C | 0.0000024571 | # | K | 0.0787 | # | R | 5 | # | L | 0.58 | # # The following code calculates the roots # In[5]: J = 0.000658 C = 0.0000012615 + 0.0000011956 K = 0.0787 R = 5 L = 0.58 a = 1 b = C/J+R/L c = R*C/(L*J) + K**2/(L*J) print(a, b, c) root_1 = (-b + np.sqrt(b**2-4*a*c))/2 root_2 = (-b - np.sqrt(b**2-4*a*c))/2 print("characteristic roots:") print(root_1) print(root_2) # These roots then give us the general form of our solution: # # $$ y(x) = c_1e^{-2.7845x} + c_2e^{-5.8399x} $$ # # If we have an initial speed an velocity $y(0) = y_0$ and $\dot{y}(0) = \dot{y}_0$ we can solve for $c_1$ and $c_2$. Remember, $y$ here is wheel angle, so this means we just need our initial angle and velocity. Let's do an example where $y_0 = 0m$ and $\dot{y}_0 = 0.2m/s$ # # \begin{align*} # 0 &= c_1e^{-2.7845(0)} + c_2e^{-5.8399(0)} \\ # 0 &= c_1 + c_2 \\ # c_1 &= -c_2 \\ # \dot{y}(x) &= -2.7845c_1e^{-2.7845x} + -5.8399c_2e^{-5.8399x} \\ # 0.2 &= -2.7845c_1e^{-2.7845(0)} + -5.8399c_2e^{-5.8399(0)} \\ # 0.2 &= -2.7845c_1 + -5.8399c_2 \\ # 0.2 &= -2.7845(-c_2) + -5.8399c_2 \\ # 0.2 &= (2.7845 + -5.8399)c_2 \\ # 0.2 &= -3.0554c_2 \\ # -0.06546 &= c_2 \\ # 0.06546 &= c_1 # \end{align*} # # We how need a particular solution. # In[6]: print("for u=5 volts") u=5 f = K/(L*J)*u print("forcing term = ", f) # A particular solution will satisfy this equation: # # $$ 1031.0764 = \ddot{y} + 8.6244\dot{y} + 16.2613y $$ # # We should suspect this has a constant solution A, so we can solve for that like so # $$\begin{align*} # 1031.0764 &= (0) + 8.6244(1) + 16.2613A \\ # 1031.0764 &= 8.6244 + 16.2613A \\ # A &= \frac{1031.0764 - 8.6244}{16.2613} \\ # A &= 1022.4519 # \end{align*}$$ # In[7]: print("A = ", (f - b)/a) y_particular = (f - b)/a # This means our end result specific solution is # # $$ y(x) = c_1e^{-2.7845x} + c_2e^{-5.8399x} + 1022.4520 $$ # In[8]: x = np.linspace(0, 10, 1000) u = 5 y = 0.06546*np.exp(-2.7845*x) + -0.06546*np.exp(-5.8399*x) + y_particular plt.figure(figsize=(10,10)) plt.plot(x, y) plt.title("y(x) = 0.06546e^{-2.7845x} + -0.06546e^{-5.8399x}") plt.show()
7976e479fb3da78d5d730b99fdbde61152b4a0be
chenxy3791/leetcode
/array-and-string/removeElement.py
3,723
3.53125
4
""" 让我们从另一个经典问题开始: 给定一个数组和一个值,原地删除该值的所有实例并返回新的长度。 如果我们没有空间复杂度上的限制,那就更容易了。我们可以初始化一个新的数组来存储答案。如果元素不等于给定的目标值,则迭代原始数组并将元素添加到新的数组中。 实际上,它相当于使用了两个指针,一个用于原始数组的迭代,另一个总是指向新数组的最后一个位置。 重新考虑空间限制 现在让我们重新考虑空间受到限制的情况。 我们可以采用类似的策略,我们继续使用两个指针:一个仍然用于迭代,而第二个指针总是指向下一次添加的位置。 总结二 这是你需要使用双指针技巧的一种非常常见的情况:同时有一个慢指针和一个快指针。 解决这类问题的关键是:确定两个指针的移动策略。 与前一个场景类似,你有时可能需要在使用双指针技巧之前对数组进行排序,也可能需要运用贪心想法来决定你的运动策略。 总结一 总之,使用双指针技巧的典型场景之一是你想要从两端向中间迭代数组。 这时你可以使用双指针技巧:一个指针从始端开始,而另一个指针从末端开始。 值得注意的是,这种技巧经常在排序数组中使用。 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } """ import time class Solution: #def twoSum(self, numbers: List[int], target: int) -> List[int]: def removeElement(self, numbers, target): nNums = len(numbers) # Ignore the validity check, assuming the valid input data. rPtr = 0 wPtr = 0 while rPtr < nNums: print(rPtr, wPtr) if numbers[rPtr] != target: #print('Successful: ', fPtr, bPtr) numbers[wPtr] = numbers[rPtr] wPtr = wPtr + 1 rPtr = rPtr + 1 #print(numbers[0:wPtr]) return wPtr if __name__ == '__main__': sln = Solution() # Testcase1 print('Testcase1...') nums = [1, 2, 3, 4, 5, 6, 7, 8, 9] target = 2 print(sln.removeElement(nums, target)) # Testcase1 print('Testcase1...') nums = [0,1,2,2,3,0,4,2] target = 2 print(sln.removeElement(nums, target))
d3c3c96930096eeb9dbcecbcd58c3c1a7434a916
Dong-Ni/PythonDemo
/eg97.py
298
3.75
4
#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == "__main__": filename = input("输入一个文件名字:\n") fp = open(filename, "w") ch = input("输入一个字符:") while ch!="#": fp.write(ch) print(ch, end=" ") ch = input("") fp.close()
d30e421050f8d9b28da2626d1eb51929d0baca53
jayala-29/python-challenges
/advCalc2.py
2,832
4.15625
4
# function descriptor: advCalc2() # advanced calculator that supports addition, subtraction, multiplication, and division # note: input from user does NOT use spaces # part 2 of building PEMDAS-based calculator # this represents parsing an expression as an algorithm # for operations in general, we go "left to right" # multiplication and division will come first # then the addition and subtraction # the example should be parsed as follows: # 1+2*3*4-25/5 <- input # 1+6*4-25/5 # 1+24-25/5 # 1+24-5 # 25-5 # 20 <- output # return type: nothing; program should end when the user types 'n' # example: Please enter an expression to calculate: '1+2*3*4-25/5' # Okay, the output is 20 # Do you want to calculate anything else? [y|n] 'n' # Okay, bye bye :) # you should start by pasting what you have from part 1 def advCalc2(): while True: expression = input("Please enter and expression to calculate: ") ls = [] numLs = [] oprLs = [] current = 0 lastNum = [] for item in expression: ls.append(item) for i in range(len(ls)): if(ls[i] == "+" or ls[i] == "-" or ls[i] == "*" or ls[i] == "/"): oprLs.append(ls[i]) num = [] lastOpr = i for j in range(current,i): num.append(ls[j]) numLs.append("".join(num)) current = i+1 for i in range(lastOpr+1, len(ls)): lastNum.append(ls[i]) numLs.append("".join(lastNum)) while True: for i in range(len(oprLs)): if(oprLs[i] == "+" or oprLs[i] == "-"): continue if(oprLs[i] == "*"): newNum = mult(int(numLs[i]), int(numLs[i+1])) if(oprLs[i] == "/"): newNum = div(int(numLs[i]), int(numLs[i+1])) oprLs.pop(i) numLs.pop(i+1) numLs.pop(i) numLs.insert(i, newNum) break check = 0 for i in range(len(oprLs)): if(oprLs[i] == "+" or oprLs[i] == "-"): check += 1 if(check == len(oprLs)): break while True: for i in range(len(oprLs)): if(oprLs[i] == "+"): newNum = add(int(numLs[i]), int(numLs[i+1])) if(oprLs[i] == "-"): newNum = sub(int(numLs[i]), int(numLs[i+1])) oprLs.pop(i) numLs.pop(i+1) numLs.pop(i) numLs.insert(i, newNum) break if(len(oprLs) == 0): break print("Okay, the output is " + str(numLs[0])) more = input("Do you want to calculate anything else? [y|n] ") if(more == "n"): print("Okay, bye bye :)") break return def add(a,b): return a + b def sub(a,b): return a - b def mult(a,b): return a * b def div(a,b): return a / b advCalc2()
5735977951318e2fead7a5ee65f3ab6689ea86bc
brianchiang-tw/UD1110_Intro_to_Python_Programming
/L7_Advanced Topics/Quiz_Iterators and Generators.py
1,930
4.28125
4
# Q1: # Quiz: Implement my_enumerate # Write your own generator function that works like the built-in function enumerate. # Calling the function like this: ''' lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] for i, lesson in my_enumerate(lessons, 1): print("Lesson {}: {}".format(i, lesson)) should output: Lesson 1: Why Python Programming Lesson 2: Data Types and Operators Lesson 3: Control Flow Lesson 4: Functions Lesson 5: Scripting ''' # Solution: lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] def my_enumerate(iterable, start=0): # Implement your generator function here for i in range(0, len(iterable)): yield i+start, iterable[i] for i, lesson in my_enumerate(lessons, 1): print("Lesson {}: {}".format(i, lesson)) # expected output ''' Lesson 1: Why Python Programming Lesson 2: Data Types and Operators Lesson 3: Control Flow Lesson 4: Functions Lesson 5: Scripting ''' # Q2: # Quiz: Chunker # If you have an iterable that is too large to fit in memory in full (e.g., when dealing with large files), being able to take and use chunks of it at a time can be very valuable. # Implement a generator function, chunker, that takes in an iterable and yields a chunk of a specified size at a time. # Calling the function like this: ''' for chunk in chunker(range(25), 4): print(list(chunk)) should output: [0, 1, 2, 3] [4, 5, 6, 7] [8, 9, 10, 11] [12, 13, 14, 15] [16, 17, 18, 19] [20, 21, 22, 23] [24] ''' # Solution: def chunker(iterable, size): # Implement function here for i in range( 0, len(iterable), size): yield iterable[i: i+size] for chunk in chunker(range(25), 4): print(list(chunk)) # expected output: ''' [0, 1, 2, 3] [4, 5, 6, 7] [8, 9, 10, 11] [12, 13, 14, 15] [16, 17, 18, 19] [20, 21, 22, 23] [24] '''
329a13e26a26fcfc62c707ae1e40971aa85d7f7a
mherna42/initials
/initials.py
153
3.890625
4
def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ # TODO your code here print("Hello World")
b4ff6e7fdf170afc504b5cddbda73a5599cb9742
lujamaharjan/IWAssignmentPython1
/DataType/Question35.py
399
4.53125
5
# 35.​ Write a Python program to iterate over dictionaries using for loops. our_dic = {'apple':1, 'banana':4, 'coconut':7} #gives key only for key in our_dic: print(key, '=', our_dic[key]) #iteraties as tuple for item in our_dic.items(): print(item) for key, value in our_dic.items(): print(key, '=>', value) for key in our_dic.keys(): print(key) for val in our_dic.values(): print(val)
46fa89ce156eefdbc722a35b122663b089d6c655
YuYong0408/Python-Crash-Course
/cars.py
912
4.375
4
# coding=UTF-8 # sort ĸ˳иģ ͨreverse = True ĸ cars = ['bmw', 'adui', 'benz','toyota','subaru'] cars.sort() print(cars) cars.sort(reverse = True) print(cars) # sorted бʱ cars = ['bmw', 'adui', 'benz','toyota','subaru'] print(sorted(cars)) print(sorted(cars,reverse = True)) # ԭб˳򲻱 print(cars) # бת print("\n") print(cars) cars.reverse() print(cars) print(len(cars)) cars = ['bmw', 'adui', 'benz','toyota','subaru'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) car ='bmw' if(car == 'bmw'): print('Ture') else: print('false') if(car =='BMW'): print('Ture') else: print('false') if(car =='audi'): print('Ture') else: print('false')
7f5459e37150d9703cc1afcc5968317895c9e68f
ay701/Coding_Challenges
/tree/leftNodesBST.py
1,231
4.375
4
# Print Left Nodes of a Binary Tree # Given a binary tree, return the left-most node of each level in the tree. # https://www.geeksforgeeks.org/print-left-view-binary-tree/ # Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n). # # Input : # 1 # / \ # 2 3 # / \ \ # 4 5 6 # Output : 1 2 4 # # Input : # 1 # / \ # 2 3 # \ # 4 # \ # 5 # \ # 6 # Output :1 2 4 5 6 class Node: def __init__(self, data): self.data = data self.left = None self.right = None def printNode(root, curr_level, last_level): if root is None: return if last_level<curr_level: print "%d\t" %(root.data) last_level = curr_level curr_level += 1 printNode(root.left, curr_level, last_level) printNode(root.right, curr_level, last_level) def printLeftNodes(root): printNode(root, 1, 0) # Driver program to test above function root = Node(12) root.left = Node(10) root.right = Node(20) root.right.left = Node(25) root.right.right = Node(40) printLeftNodes(root)
67b9929db7253fd3aba531db8d17bc96dea1cd37
lincky1103/GitCode
/ex15.py
281
3.734375
4
from sys import argv script, filename = argv txt = open(filename) print('Here is your file: %r.' %(filename)) print(txt.read()) print('Also ask u to type it again:') file_again = input('> ') txt_again = open(file_again) print(txt_again.read()) txt.close() txt_again.close()
e116caa19e722677a436a8f1a623d9a2bb7eb6f2
kitagawa-hr/Project_Euler
/python/042.py
1,205
3.84375
4
""" Project Euler Problem 42 ======================== The n-th term of the sequence of triangle numbers is given by, t[n] = 1/2n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t[10]. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import math readfile = '../resources/42.txt' f = open(readfile, 'r', encoding='utf-8') words = f.read().split(',') f.close() alpha = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") def calc_score(x): score = 0 for n in x: if n in alpha: score += alpha.index(n) + 1 return score def main(): scores = [calc_score(n) for n in words] end = math.floor(2 * math.sqrt(max(scores))) tn = [n * (n + 1) / 2 for n in range(1, end + 1)] ans = sum([scores.count(n) for n in tn]) print(ans) if __name__ == '__main__': main()
257dc3a7f3249c16feca736677b6720f1b91b681
gabriellaec/desoft-analise-exercicios
/backup/user_014/ch16_2020_04_03_23_57_22_226057.py
157
3.59375
4
conta_inicial = float(input('Qual foi o valor da conta? ')) conta_final = conta_inicial * 1.1 print('Valor da conta com 10%: R$ {0:.2f}'.format(conta_final))
61e6a13ae6d35e08c6eba924bd8480061fa171d1
TrainingByPackt/Python-Fundamentals-eLearning
/Lesson03/3_stringIndexSlice.py
174
3.53125
4
colour = input('Please enter hex colour value:') r = colour[0:2] g = colour[2:4] b = colour[4:6] print(r, g, b) r = int(r, 16) g = int(g, 16) b = int(b, 16) print(r, g, b)
48c81f2851622ab5e42d14b11e68728bc98dcd15
koonerts/algo
/py-algo/grokk-tci/dual-heaps.py
7,796
3.734375
4
import heapq from heapq import * class MedianOfAStream: def __init__(self): self.min_heap = [] self.max_heap = [] def insert_num(self, num): if not self.max_heap: heappush(self.max_heap, -num) else: if num < -self.max_heap[0]: heappush(self.max_heap, -num) else: heappush(self.min_heap, num) len_diff = abs(len(self.min_heap) - len(self.max_heap)) is_min_larger = len(self.min_heap) > len(self.max_heap) if len_diff > 1 or is_min_larger: if is_min_larger: heappush(self.max_heap, -heappop(self.min_heap)) else: heappush(self.min_heap, -heappop(self.max_heap)) def find_median(self): heap_len = len(self.min_heap) + len(self.max_heap) if heap_len % 2 == 1: return -self.max_heap[0] else: return (-self.max_heap[0] + self.min_heap[0])/2 class SlidingWindowMedian: def __init__(self): self.min_heap = [] self.max_heap = [] def find_sliding_window_median(self, nums: list[int], k: int): """ Given an array of numbers and a number ‘k’, find the median of all the ‘k’ sized sub-arrays (or windows) of the array. Example 1: Input: nums=[1, 2, -1, 3, 5], k = 2 Output: [1.5, 0.5, 1.0, 4.0] Explanation: Lets consider all windows of size ‘2’: [1, 2, -1, 3, 5] -> median is 1.5 [1, 2, -1, 3, 5] -> median is 0.5 [1, 2, -1, 3, 5] -> median is 1.0 [1, 2, -1, 3, 5] -> median is 4.0 Example 2: Input: nums=[1, 2, -1, 3, 5], k = 3 Output: [1.0, 2.0, 3.0] Explanation: Lets consider all windows of size ‘3’: [1, 2, -1, 3, 5] -> median is 1.0 [1, 2, -1, 3, 5] -> median is 2.0 [1, 2, -1, 3, 5] -> median is 3.0 """ """ Steps: 1) Increase window size until size k while maintaining min/max heaps - Heap rules: if nums[i] < -max_heap[0] -> insert into max_heap else insert into min_heap Resize heaps if difference in heap lengths > 1 or length of min_heap > length of max_heap 2) If i == k: - insert median (either -max_heap[0] or avg(-max_heap[0] + min_heap[0])) - reduce sliding window and pop from appropriate heap 3) Repeat for all remaining i """ start, min_h, max_h, result = 0, [], [], [] def insert_num(num: int): if not max_h or num <= -max_h[0]: heappush(max_h, -num) else: heappush(min_h, num) heap_length_diff = abs(len(min_h) - len(max_h)) is_min_heap_larger = len(min_h) > len(max_h) while heap_length_diff > 1 or is_min_heap_larger: if is_min_heap_larger: heappush(max_h, -heappop(min_h)) else: heappush(min_h, -heappop(max_h)) heap_length_diff = abs(len(min_h) - len(max_h)) is_min_heap_larger = len(min_h) > len(max_h) def get_median() -> float: heap_len = len(min_h) + len(max_h) if heap_len % 2 == 0: return (-max_h[0] + min_h[0])/2 else: return -max_h[0] def pop_num(num: int): def remove(heap, num): ind = heap.index(num) # find the element # move the element to the end and delete it heap[ind] = heap[-1] del heap[-1] # we can use heapify to readjust the elements but that would be O(N), # instead, we will adjust only one element which will O(logN) if ind < len(heap): heapq._siftup(heap, ind) heapq._siftdown(heap, 0, ind) if num <= -max_h[0]: remove(max_h, -num) else: remove(min_h, num) for i, num in enumerate(nums): insert_num(num) window_len = i - start + 1 if window_len == k: result.append(get_median()) if i < len(nums) - 1: pop_num(nums[start]) start += 1 return result def find_maximum_capital(capital: list[int], profits: list[int], numberOfProjects: int, initialCapital: int) -> int: """ Given a set of investment projects with their respective profits, we need to find the most profitable projects. We are given an initial capital and are allowed to invest only in a fixed number of projects. Our goal is to choose projects that give us the maximum profit. Write a function that returns the maximum total capital after selecting the most profitable projects. We can start an investment project only when we have the required capital. Once a project is selected, we can assume that its profit has become our capital. Example 1: Input: Project Capitals=[0,1,2], Project Profits=[1,2,3], Initial Capital=1, Number of Projects=2 Output: 6 Explanation: With initial capital of ‘1’, we will start the second project which will give us profit of ‘2’. Once we selected our first project, our total capital will become 3 (profit + initial capital). With ‘3’ capital, we will select the third project, which will give us ‘3’ profit. After the completion of the two projects, our total capital will be 6 (1+2+3). Example 2: Input: Project Capitals=[0,1,2,3], Project Profits=[1,2,3,5], Initial Capital=0, Number of Projects=3 Output: 8 Explanation: With ‘0’ capital, we can only select the first project, bringing out capital to 1. Next, we will select the second project, which will bring our capital to 3. Next, we will select the fourth project, giving us a profit of 5. After selecting the three projects, our total capital will be 8 (1+2+5). """ # TODO: Come back to return -1 class Interval: def __init__(self, start, end): self.start = start self.end = end def find_next_interval(intervals: list[Interval]): """ Given an array of intervals, find the next interval of each interval. In a list of intervals, for an interval ‘i’ its next interval ‘j’ will have the smallest ‘start’ greater than or equal to the ‘end’ of ‘i’. Write a function to return an array containing indices of the next interval of each input interval. If there is no next interval of a given interval, return -1. It is given that none of the intervals have the same start point. Example 1: Input: Intervals [[2,3], [3,4], [5,6]] Output: [1, 2, -1] Explanation: The next interval of [2,3] is [3,4] having index ‘1’. Similarly, the next interval of [3,4] is [5,6] having index ‘2’. There is no next interval for [5,6] hence we have ‘-1’. Example 2: Input: Intervals [[3,4], [1,5], [4,6]] Output: [2, -1, -1] Explanation: The next interval of [3,4] is [4,6] which has index ‘2’. There is no next interval for [1,5] and [4,6]. """ # TODO: Come back to result = [] return result def main(): result = find_next_interval( [Interval(2, 3), Interval(3, 4), Interval(5, 6)]) print("Next interval indices are: " + str(result)) result = find_next_interval( [Interval(3, 4), Interval(1, 5), Interval(4, 6)]) print("Next interval indices are: " + str(result)) main()
adbd9ac199ca78604a8c2a260309b1c0a8fac0ea
Sohone-Guo/The-Unversity-of-Sydney
/NoSQL 2016/Neo4j/neo4j_query.py
5,029
3.625
4
from py2neo import Graph graph = Graph(password = 'neo4jneo4j') print('Simple query:') print('1: Given a user id, find all artists the user\'s friends listen.') print('2: Given an artist name, find the most recent 10 recent 10 tags that have been assigned to it.') print('3: Given an artist name, find the top 10 users based on their respective listening counts of this artist. Display both the user id and the listening count.') print('4: Given a user id, find the most recent 10 artists the user has assigned tag to.') print('Complex queries') print('5: Find the top 5 artists ranked by the number of users listening to it') print('6: Given an artist name. find the top 20 tags assigned to it. The tags are ranked by the number of times it has been assigned to this artist') print('7: Given a user id, find the top 5 artists listened by his friends but not him. We rank artists by the sum of friends listening counts of the artist.') print('8: Given an artist name, find the top 5 similar artists. Here similarity between a pair of artists is defined by the number of unique users that have listened both. The higher the number, the more similar the two artists are.') question = int(input('Which Question: ')) # Simple query 1 if question == 1: friend_artist_matrix = [] user_ID = str(input('Input your user ID: ')) # find user's friends friend_raw = graph.data('match (:user{userID:{id}}) - [:friend]->(n) return (n.userID)',id=user_ID) for user_ID_length in range(len(friend_raw)): # find artists listened by user's friends friend_artist = graph.data('match (:user{userID:{f_id}}) - [:weight] ->(n) return n.name, n.url, n.pictureURL',f_id = friend_raw[user_ID_length]['(n.userID)'] ) print(friend_artist) # Simple query 2 elif question == 2: artist_name = input('Input artist name: ') print(graph.data('match (:user) - [n:tags] ->(:artist{name:{name}}) return n.tagValue,n.time order by n.time desc limit 10',name = artist_name )) # Simple query 3 elif question == 3: weightnumber_dic = {} artist_name = input('Input artist name: ') # find listening counts of users weightnumber = graph.data('match (u:user) - [n:weight] ->(:artist{name:{name}}) return u.userID,n.weightnumber order by n.weightnumber desc ',name=artist_name) for i in range(len(weightnumber)): weightnumber_dic['useID:%s'%weightnumber[i]['u.userID']]=int(weightnumber[i]['n.weightnumber']) # print top 10 users for i in range(10): print(sorted(weightnumber_dic, key=weightnumber_dic.__getitem__ ,reverse = True)[i],weightnumber_dic[sorted(weightnumber_dic, key=weightnumber_dic.__getitem__ ,reverse = True)[i]]) # Simple query 4 elif question == 4: user_ID = str(input('Input your user ID: ')) print(graph.data('match (u:user{userID:{id}}) - [n:tags] ->(a:artist) with n,a order by n.time desc return distinct a.name limit 10',id=user_ID)) # Complex query 1 elif question == 5 : print(graph.data('match (u:user) - [n:weight] ->(a:artist) return a.name,count(n) order by count(n) desc limit 5')) # Complex query 2 elif question == 6: artist_name = input('Input artist name: ') print(graph.data('match (p:user) - [n:tags] ->(:artist{name:{name}}) return n.tagValue, count(n) order by count(n) desc limit 20',name=artist_name)) # Complex query 3 elif question == 7: friend_matrix = [] self_artist_matrix =[] user_ID = str(input('Input your user ID: ')) # find user's friends friend_raw = graph.data('match (:user{userID:{id}}) - [:friend]->(n) return (n.userID)', id=user_ID) for i in range(len(friend_raw)): friend_matrix.append(friend_raw[i]['(n.userID)']) # find artists listened by user self_artist = graph.data('match (:user{userID:{id}}) - [:weight]->(n) return (n.name)', id=user_ID) for j in range(len(self_artist)): self_artist_matrix.append(self_artist[j]['(n.name)']) # find artists listened by user's friends and listening counts artist = graph.data('match (u:user) - [n:weight] ->(a:artist) where u.userID IN {matrix} return a.name,sum(toInt(n.weightnumber)) order by sum(toInt(n.weightnumber)) desc limit 10',matrix = friend_matrix) count = 0 # exclude artists listened by user for k in range(len(artist)): if artist[k]['a.name'] not in self_artist_matrix and count < 5: print(artist[k]) count +=1 # Complex query 4 elif question == 8: user_ID_matrix =[] artist_name = input('Input artist name: ') # find users who listen to this artist user_ID = graph.data('match (p:user) - [n:weight] ->(:artist{name:{name}}) return p.userID',name=artist_name) for i in range(len(user_ID)): user_ID_matrix.append(user_ID[i]['p.userID']) # find top 6 similar artists artist = graph.data('match (p:user) - [n:weight] ->(a:artist) where p.userID IN {matrix} return a.name, count(n) order by count(n) desc limit 6',matrix = user_ID_matrix) # exclude this artist print(artist[1:])
9fd298321bf13377201d1b755eee5ecb15fd0151
elad-rubinstein/threads-python
/threads task two.py
1,755
4
4
""" Threads_competition """ import constant from queue import Queue import threading import time lst_names = [] def get_score(threads_name: str, event: threading.Event, queue: Queue): """ According to the event, the func take a score from a global list and put a name in another global list :param threads_name: The name of the thread accessing this method. :param event: The Event used to synchronize between threads. :param queue: A queue to store scores. """ event.wait() queue.get() lst_names.append(threads_name) event.clear() def calculate_score(): """ Calculate which thread in a global list has the highest score and print it """ max_wins = 0 max_name = "" for thread_name in lst_names: name_count = lst_names.count(thread_name) if name_count > max_wins and name_count > 1: max_wins = name_count max_name = thread_name if max_name: print(f"Winner is {max_name}") else: print("There isn't one winner!") def main(): """ The method runs a a five-round-competition between threads using the get_score method """ event = threading.Event() queue = Queue() round_thread = 1 while round_thread <= constant.last_round: queue.put(int(input("input a score: "))) for i in range(constant.range_threads): name = "thread " + str(i + 1) x = threading.Thread(target=get_score, args=[name, event, queue]) x.start() event.set() time.sleep(constant.sleep_time) print("list of winners every round: ") print(lst_names) round_thread += 1 calculate_score() if __name__ == '__main__': main()
0135db039501fcc411c8f1e63b2d61afe9f55090
masontmorrow/Intro-Python
/src/dicts.py
643
4.40625
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. a = { "lat": 35.4675602, "lon": -97.5164276, "name": "OKC" } b = { "lat": 37.7749295, "lon": -122.4194155, "name": "SFO" } c = { "lat": 51.9244201, "lon": 4.4777326, "name": "ROT" } waypoints = [a, b, c] print(waypoints) # Write a loop that prints out all the field values for all the waypoints for i in waypoints: print(f'The name of the waypoint is {i["name"]}. It sits at latitude {i["lat"]}, longitude {i["lon"]}.')
98aa1bff99659189195066b6855c965c5e9c8457
jeancre11/PYTHON-2020
/CLASE 2/codigo10 lista par e impar.py
488
3.625
4
lista=[100, 20, 21, 23, 24] #lista_impar 21 23 #lista_para 10 20 24 cond=23 in lista lista_par=[] lista_impar=[] #devuelve true o false para el elemento print(cond) print(lista) for val in lista: #print(val, end=" ") if val%2!=0: break print(val, end=" ") print("") #print("AHORA TENEMOS") #lista=[100, 20, 21, 23, 24] for val in lista: if val%2==0: lista_par.append(val) else: lista_impar.append(val) print(lista_par) print(lista_impar)
62c3e9cd9d412f4f32fef6ee86fb944d69f5e6e3
hyunjun/practice
/python/problem-string/uncommon_words_from_two_sentences.py
949
3.578125
4
# https://leetcode.com/problems/uncommon-words-from-two-sentences # https://leetcode.com/problems/uncommon-words-from-two-sentences/solution class Solution: # 63.44% def uncommonFromSentences(self, A, B): if (A is None or 0 == len(A)) and (B is None or 0 == len(B)): return [] words = A.split(' ') words.extend(B.split(' ')) wordCntDict = {} for word in words: if word in wordCntDict: wordCntDict[word] += 1 else: wordCntDict[word] = 1 return [word for word, cnt in wordCntDict.items() if 1 == cnt] s = Solution() data = [('this apple is sweet', 'this apple is sour', ['sweet', 'sour']), ('apple apple', 'banana', ['banana']), ] for A, B, expected in data: real = s.uncommonFromSentences(A, B) print('{}, {}, expected {}, real {}, result {}'.format(A, B, expected, real, expected == real))
a9e664c7ded3abd88f4ae034989edcd8cc9f1378
hellohano/my_leetcode
/Path Sum/Path Sum.py
628
3.828125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def hasPathSum(self, root, sum): return self.dfs(root, sum, 0) def dfs(self, node, sum, current_sum): if node == None: return False; if node.left == None and node.right == None: return current_sum + node.val == sum return self.dfs(node.left, sum, current_sum + node.val) or self.dfs(node.right, sum, current_sum + node.val)
5b9c5069fee35e8678ba1c1ef8c1ae99c78e9cf9
akyare/Python-Students-IoT
/2-data-structures/4-comprehensions/DictionaryComprehension.py
678
4.46875
4
# Look at ListComprehension if you have forgotten the comprehension theory. # Lets do an example of dictionary comprehension: random_chars = {x: chr(x * 50) for x in range(11)} # Using the built-in function chr() to convert integers to chars. # Lets see what we got here using the unpacking technique: for key, value in random_chars.items(): print(F"{'The key'} {key} {'holds the value'} {value}") # We can use comprehensions with: List, Sets and dictionaries but what about tuples: rand_tuples = (x for x in range(11)) # Let's see what we get here: print(rand_tuples) # Spoiler alert: the above code returns a generator obj more about that in GeneratorObjects.py
027884b3bbea959a692e31e4454b4b63f56b32f0
harrislapiroff/aoc-2018
/d1_2.py
793
3.796875
4
from typing import List def first_frequency_reached_twice( changes: List[str], initial_value: int = 0 ) -> int: value = initial_value frequencies_reached = () num_changes = len(changes) change_ints = [int(n) for n in changes] i = 0 while value not in frequencies_reached: # Add the new frequency to the list of frequencies seen frequencies_reached += (value,) # Update the frequency with the next change in our list value += change_ints[i % num_changes] # Increment the counter i += 1 return value if __name__ == '__main__': with open('data/1.txt', 'r') as file: print( first_frequency_reached_twice( [x.strip() for x in file.readlines()] ) )
59bb75d9bea8dd055544ea08414f6d430a7f4e42
rohitkottamasu/Tictactoe
/tic2.py
1,579
3.71875
4
#tic-tac-toe import sys board=[] board1 = [['00','01','02'],['10','11','12'],['20','21','22']] p=0 def print1(): for i in range(3): for j in range(3): sys.stdout.write("%s | " % board[i][j]) print "\n-------------" def positions(): board1 = [['00','01','02'],['10','11','12'],['20','21','22']] for i in range(3): for j in range(3): sys.stdout.write("%s | " % board1[i][j]) print "\n-------------" def game(st,c): for i in range(3): for j in range(3): if(board[i][j]==st): board[i][j] = c def emptycheck(): for i in range(3): for j in range(3): if (board[i][j] == str(i)+str(j)): p=1 return p def win(): if board[0]=='x' or board[1]=='x' or board[2]=='x': print("Player1 wins") elif board[0]=='o' or board[1]=='o' or board[2]=='o': print("Player2 wins") elif board[0][0]=='x' and board[1][1]=='x' and board[2][2]=='x': print("Player1 wins") elif board[0][0]=='o'and board[1][1]=='o' and board[2][2]=='o': print("Player2 wins") elif board[0][2]=='x' and board[1][1]=='x' and board[2][0]=='x': print("Player1 wins") elif board[0][2]=='o'and board[1][1]=='o' and board[2][0]=='o': print("Player2 wins") def input(): print('player1-x') print('player2-o') print("CURRENT BOARD:-") positions() i=1 while i!=0 and emptycheck(): if(i%2!=0): print("player1 turn:") a=raw_input("Enter the position") game(a,'x') else: print("player2 turn:") a=raw_input("Enter the position") game(a,'o') i=i+1 win()
b293389a91c98dd5d4421a2d3728ed55b06ae68b
emcraciu/PEP21G02
/modul6/app1.py
1,385
4.34375
4
# Create an object for a shop that when iterated will return all of the products in the shop class Shop: # constructor receive list of products in shop def __init__(self, products: list): self.products = products # iter method must return an object that is an iterator or generator def __iter__(self): # a copy of the products list is sent to the iterator so that the original is not consumed return ShopIterator(self.products.copy()) # class for iterator object must implement at least: __iter__ and __next__ class ShopIterator: def __init__(self, products: list): self.products = products # iter method for iterators will always return it's self def __iter__(self): return self def __next__(self): if not self.products: raise StopIteration # we consume the list of products return self.products.pop() if __name__ == '__main__': shop = Shop(['books', 'bananas', 'water']) print('From constructor:', shop.products) # iterate using for loop for item in shop: print('For loop', item) # iterate using methods shop_iter = shop.__iter__() print('First product:', shop_iter.__next__()) print('Second product:', shop_iter.__next__()) print('Third product:', shop_iter.__next__()) print('Forth product:', shop_iter.__next__())
461123885e4d456fa9b47b7387f51e504a7fe7fb
MacHu-GWU/pyrabbit-python-advance-guide-project
/pyguide/p3_stdlib/c10_functional_programming/functools/lru_cache.py
2,321
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LRU (least recently used) cache这种缓存能将函数最近N次被调用的输入参数和返回值 缓存起来, 每次有新的访问时, 会首先到缓存保存过的输入参数中查找, 如果找不到再真正 执行函数。 LRU缓存的典型作用就是新闻客户端, 例如缓存保存最新的20篇文章。用户每次登陆, 服务 器就不需要去读取数据库, 而可以直接把缓存中的内容推送给用户。 注: 此模块在Python3.2之后才出现 Reference: https://docs.python.org/3.3/library/functools.html#functools.lru_cache """ from __future__ import print_function from functools import lru_cache import time def fib1(n): """recursive solution for fibonacci(n). """ if n < 2: return n return fib1(n-1) + fib1(n-2) def fib2(n): """dynamic programming solution for fibonacci(n). """ if n <= 2: return 1 i, res = 1, 1 for _ in range(n - 2): i, res = res, res + i return res @lru_cache(maxsize=5) def fib3(n): """use LRU cache and recursive solution for fibonacci(n). """ if n < 2: return n return fib1(n-1) + fib1(n-2) if __name__ == "__main__": complexity = 20 print("call fib once...") st = time.clock() fib1(complexity) print("%.6f" % (time.clock() - st)) st = time.clock() fib2(complexity) print("%.6f" % (time.clock() - st)) st = time.clock() fib3(complexity) print("%.6f" % (time.clock() - st)) print("call fib 1 to n...") st = time.clock() [fib1(i) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st)) st = time.clock() [fib2(i) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st)) st = time.clock() [fib3(i) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st)) print("call fib n many times...") st = time.clock() [fib1(complexity) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st)) st = time.clock() [fib2(complexity) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st)) st = time.clock() [fib3(complexity) for i in range(1, complexity+1)] print("%.6f" % (time.clock() - st))
fa0ed3fdb0858ad68ab90fd291d2b397b8436051
SergioO21/intermediate_python
/power_in_dictionaries.py
469
3.90625
4
def run(): power_3_dict = {} # 1000 sqrt challenge sqrt_1000_dict = {i: i ** 0.5 for i in range(1, 1001)} # Dictionary comprehension form power_dict = {i: i ** 3 for i in range(1, 101) if i % 3 != 0} # Common form for i in range(1, 101): if i % 3 != 0: power_3_dict[i] = i ** 3 print(power_3_dict) print("") print(power_dict) print("") print(sqrt_1000_dict) if __name__ == "__main__": run()
90a55ef8f89321593ebaa1fd95068f18677945dc
thivatm/Hello-world
/Python/CurrentDirDetails.py
627
3.828125
4
import os import csv import io # os.walk returns three tuples- dirpath, dirname, filenames. # We can use them and get the list of the files and folders of the current directory. filenames = [] for root, dirs, files in os.walk(".",topdown = False): for name in files: print(os.path.join(root,name)) filenames.append(name) for name in dirs: print(os.path.join(root,name)) # For writing in a csv the name of the files in the directory with io.open("details.csv", "w", encoding="utf-8") as csvfile: csvwriter = csv.writer(csvfile, delimiter = "\n") csvwriter.writerow(filenames) print("") print("Csv Created.")
6c54ab805d54c4824511e565058e25a09c9d6682
Niatruc/tf_test
/rnn_test.py
2,874
3.828125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 数据 mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # 超参 lr = 0.001 # 学习率 training_iters = 100000 batch_size = 128 # display_step = 10 n_inputs = 28 # 图片28×28 n_steps = 28 # 时间步,28步 n_hidden_units = 128 # 隐藏层神经元数目 n_classes = 10 # 分类0~9 # x = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None, n_classes]) # 定义权重 weights = { # (28, 128) 'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])), # (128, 10) 'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes])) } biases = { # (128, ) 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])), # (10, ) 'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ])) } def RNN(X, weights, biases): # # X: (128 batches, 28 steps, 28 inputs) => (128*28, 28 inputs),三维转二维 # 将图片展开成一维序列(长为128×28, 共28个输入序列) X = tf.reshape(X, [-1, n_inputs]) # X_in => (128 batches * 28 steps, 128 hidden_units) X_in = tf.matmul(X, weights['in']) + biases['in'] # X_in => (128 batches, 28 steps, 128 hidden_units) X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units]) # cell # forget_bias为1,表示不希望forget前面的东西;state_is_tuple为True,即生成一个元组:(主线剧情,分线剧情) # lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True) lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True) # lstm细胞分为主线state和分线state; 初始化为全零 _init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) outputs, states = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=_init_state, time_major=False) # 输出层 results = tf.matmul(states[1], weights['out']) + biases['out'] return results pred = RNN(x, weights, biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) train_op = tf.train.AdamOptimizer(lr).minimize(cost) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) step = 0 while step * batch_size < training_iters: batch_xs, batch_ys = mnist.train.next_batch(batch_size) batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs]) sess.run([train_op], feed_dict={ x: batch_xs, y: batch_ys, }) if step % 20 == 0: print(sess.run(accuracy, feed_dict={ x: batch_xs, y: batch_ys, })) step += 1
02926f4a00ca4cff46f864ce927616e0d8c1e42d
lidianxiang/leetcode_in_python
/堆/347-前K个高频元素.py
2,476
3.796875
4
""" 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] """ import heapq import collections class Solutions: """ 1、首先建立一个元素值对应的出现频率的哈希表,在python中有个collections库中的Counter方法可以构建我们需要的哈希表 2、建立堆。在python中可以使用heapq库中的nlargest方法。堆中添加一个元素的复杂度是O(log(K)),要进行N次复杂度是O(N), """ def topKFrequent(self, nums, k): # 建立元素值与出现频率的哈希表 count = collections.Counter(nums) # 构建堆,利用堆的性质来返回topK问题 return heapq.nlargest(k, count.keys(), key=count.get) class Solution: """堆排序处理海量数据的topK问题""" def topKFrequent(self, nums, k): # 对于堆的子树(parent,left_child, right_child)的交换过程,将最小值总是放在最上面 def heapify(arr, n, i): smallest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[l][1] < arr[i][1]: smallest = l if r < n and arr[r][1] < arr[smallest][1]: smallest = r if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] heapify(arr, n, smallest) # 构建字典遍历一次统计出现频率 map_dict = {} for item in nums: if item not in map_dict.keys(): map_dict[item] = 1 else: map_dict[item] += 1 map_arr = list(map_dict.items()) length = len(map_dict.keys()) # 取前k个数,构建规模为k的最小堆 if k <= length: k_minheap = map_arr[:k] for i in range(k // 2 - 1, -1, -1): heapify(k_minheap, k, i) for i in range(k, length): if map_arr[i][1] > k_minheap[0][1]: k_minheap[0] = map_arr[i] heapify(k_minheap, k, 0) # 遍历规模k之外的数据,大于堆顶则入堆,维护规模为k的最小堆 for i in range(k - 1, 0, -1): k_minheap[i], k_minheap[0] = k_minheap[0], k_minheap[i] k -= 1 heapify(k_minheap, k, 0) return [item[0] for item in k_minheap]
600d5a9aa33cb125820305e2fbe12cfa08dca41f
x-jeff/Tensorflow_Code_Demo
/Demo5/5.1.tensorboard_network_structure.py
2,139
3.546875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 #该语句会自动创建名为MNIST_data的文件夹,并下载MNIST数据集 #如果已存在,则直接读取数据集 mnist=input_data.read_data_sets("../Demo3/MNIST_data",one_hot=True) #mini-batch size batch_size=100 #训练集的数目 #print(mnist.train.num_examples)#55000 #一个epoch内包含的mini-batch个数 n_batch=mnist.train.num_examples // batch_size #命名空间 with tf.name_scope("input"): #定义网络的输入和输出 x=tf.placeholder(tf.float32,[None,784],name='x-input')#28*28*1=784 y=tf.placeholder(tf.float32,[None,10],name='y-input')#0,1,2,3,4,5,6,7,8,9 with tf.name_scope("layer"): #创建一个简单的神经网络(无隐藏层) with tf.name_scope("weights"): W=tf.Variable(tf.zeros([784,10]),name="W") with tf.name_scope("biases"): b=tf.Variable(tf.zeros([10]),name="b") with tf.name_scope("wx_plus_b"): wx_plus_b=tf.matmul(x,W)+b with tf.name_scope("softmax"): prediction=tf.nn.softmax(wx_plus_b) with tf.name_scope("loss"): #均方误差 loss=tf.reduce_mean(tf.square(y-prediction)) with tf.name_scope("train"): #梯度下降法 train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化变量 init=tf.global_variables_initializer() with tf.name_scope("accuracy"): #统计预测结果 with tf.name_scope("correct_prediction"): correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#返回一个布尔型的列表 with tf.name_scope("accuracy"): accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) writer=tf.summary.FileWriter("logs/",sess.graph) for epoch in range(1): for batch in range(n_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("Iter "+str(epoch)+", Testing Accuracy "+str(acc))
61b96a38bf1e6a364e026c80a6217d9698e3995e
JahazielGuzman/python_practice
/mergesort.py
791
3.8125
4
def mergesort(a,p,r): if p < r: q = int((p+r)/2) mergesort(a,p,q) mergesort(a,q+1,r) merge(a,p,q,r) def merge(a,p,q,r): n1 = q - p + 1 n2 = r - q L = [] R = [] for i in range(0,n1): L.append(a[p+i]) for j in range(0,n2): R.append(a[q+j+1]) i = 0 j = 0 k = p while k <= r and i < n1 and j < n2: if L[i] <= R[j]: a[k] = L[i] i += 1 else: a[k] = R[j] j += 1 k += 1 if (i < n1): for x in range(i,n1): a[k] = L[x] k += 1 else: for x in range (j,n2): a[k] = R[x] k += 1 list = [2,1,4,6,5,12,7,2,0] mergesort(list,0,len(list)-1) print list
d847c93c7487ab48a22fab717d5a670a5b279119
is2soccer/class_projects
/python/1.py
1,414
4.03125
4
# Project: Discussion # Name: Khanh Tran # Date: 02/26/14 # Description: This program will create a graphic window that # draws 5 dice on the screen from graphics import * # define 'dots' function def blackDot(center,win): blackdot=Circle(center,10) blackdot.draw(win) blackdot.setFill("Black") return blackdot # define main function def main(): # create windows win = GraphWin("5 Dice",560,120) win.setBackground("white") # Use loop to create 5 dices without dot for rec in range(5): pointx = 100*rec + (10 * rec) rect = Rectangle(Point(pointx + 10,110),Point(pointx + 110,10)) rect.draw(win) rect.setFill("white") # Use loop to create dot inside the dices for upright1 in range (4): pointx = 110 * upright1 Dots = blackDot(Point(pointx + 200,30),win) for upright2 in range(2): pointx = 110 * upright2 Dots = blackDot(Point(pointx + 360,30),win) for midpoint in range(3): pointx = 220 * midpoint Dots = blackDot(Point(pointx + 60,60),win) for bottom1 in range (4): pointx = 110 * bottom1 Dots = blackDot(Point(pointx + 140,90),win) for bottom2 in range(2): pointx = 110 * bottom2 Dots = blackDot(Point(pointx + 420 ,90),win) # Call function main()
24e288d2df8dd236870909c918b00507f7febe9b
CodingInterview2018Gazua/coding_interview
/coding_interview/lansun/chapter3/3.4_hanoi_towers.py
692
3.59375
4
# /usr/bin/python # -*- coding: utf-8 -*- # 3.4 하노이탑 문제에는 3개의 탑과 N개의 원판이 등장하는데 각 원판은 어느 탑으로도 옮길 수 있다 # 하노이 탑 퍼즐은 세 개의 탑 가운데 하나에 이 N개의 원판을 쌓아두고 시작한다 # 이때 원판들은 지름이 작은 원판이 위쪽에 오도록 배열된다. 하노이 탑 퍼즐에는 다음과 같은 제약조건들이 있다 def hanoi(n, start, by, dest): if n == 1: print '{} -> {}'.format(start, dest) else: hanoi(n-1, start, dest, by) hanoi(1, start, by, dest) hanoi(n-1, by, start, dest) tray_num = 3 hanoi(tray_num, 'A', 'B', 'C')
c7d68dca2b098ef151f272c157db4ae0888ac262
nojhan/atelierscientifique-graph
/graphdisplayer.py
2,481
3.515625
4
import turtle import time # TODO: Optimiser def DrawGraph(G, path=0, scale=100, animationspeed=0, linethickness=5, nodesize=10, bgcolor="black", graphcolor="white", pathcolor="red", startcolor="cyan", finishcolor="lime"): # paramétrage de l'écran wn = turtle.Screen() wn.bgcolor(bgcolor) # paramétrage du turtle t = turtle.Turtle() t.hideturtle() t.pencolor(graphcolor) t.pensize(linethickness) t.fillcolor(graphcolor) t.speed(0) # traçage du graphe et dessin des noeuds i = 0 nodecount = len(G) start = time.time() tracedlines = [] for node in G: percentage = round(i / nodecount * 100, 2) nodesleft = nodecount - i print(f"Status: {percentage} % completed. There is {nodesleft} nodes left to draw.") scalednode = (node[0] * scale, node[1] * scale) t.penup() TraceCircle(t, scalednode, nodesize, graphcolor) t.goto(scalednode) t.pendown() for neighbor in G[node]: if (node, neighbor) not in tracedlines and (neighbor, node) not in tracedlines: scaledneighbor = (neighbor[0] * scale, neighbor[1] * scale) t.goto(scaledneighbor) t.goto(scalednode) tracedlines.append((node, neighbor)) i+=1 t.penup() end = time.time() s = end - start print(f"Status: 100%. Task completed successfully. It took {round(s // 60)}mn{round(s % 60)}s to complete the graph.") # traçage du chemin, du départ et de l'arrivée si un chemin est donné en paramètres if path != 0: start = (path[0][0] * scale, path[0][1] * scale) finish = (path[-1][0] * scale, path[-1][1] * scale) # path[-1] est le dernier élement de path (-1 le 1er en partant de la fin, -2 le deuxième, etc.) TraceCircle(t, start, nodesize, startcolor) t.color(pathcolor) t.goto(path[0][0] * scale, path[0][1] * scale) t.pendown() t.speed(animationspeed) for node in path: t.goto(node[0] * scale, node[1] * scale) t.penup() TraceCircle(t, finish, nodesize, finishcolor) wn.mainloop() def TraceCircle(t, pos, radius, color): t.speed(0) t.color(color) t.goto(pos[0], pos[1] - radius) t.begin_fill() t.circle(radius) t.end_fill()
6e21c1eb0baa2a88e3855c90ca21ef64b9057938
miguelgfierro/pybase
/plot_base/plot_confusion_matrix.py
1,695
3.78125
4
import itertools import numpy as np import matplotlib.pyplot as plt def plot_confusion_matrix( cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues ): """Plots a confusion matrix. Args: cm (np.array): The confusion matrix array. classes (list): List wit the classes names. normalize (bool): Flag to normalize data. title (str): Title of the plot. cmap (matplotlib.cm): `Matplotlib colormap <https://matplotlib.org/api/cm_api.html>`_ Examples: >>> matplotlib.use("Template") # Avoids opening a window in plt.show() >>> a = np.array([[10, 3, 0],[1, 2, 3],[1, 5, 9]]) >>> classes = ['cl1', 'cl2', 'cl3'] >>> plot_confusion_matrix(a, classes, normalize=False) >>> plot_confusion_matrix(a, classes, normalize=True) """ cm_max = cm.max() cm_min = cm.min() if cm_min > 0: cm_min = 0 if normalize: cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis] cm_max = 1 plt.imshow(cm, interpolation="nearest", cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) thresh = cm_max / 2.0 plt.clim(cm_min, cm_max) for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text( j, i, round(cm[i, j], 3), # round to 3 decimals if they are float horizontalalignment="center", color="white" if cm[i, j] > thresh else "black", ) plt.ylabel("True label") plt.xlabel("Predicted label") plt.show()
8053045835240b92902ae0ad6ca65defcadf73a3
NikitaKirin/Linear-equation-solver-calculator
/main.py
1,212
3.78125
4
import core.method_of_Cramer as calc matrix_of_variables = [] matrix_of_free = [] count_line = 0 count_free_line = 0 while True: line = input( 'Вводите коэффициенты при неизвестных построчно через пробел! - для остановки ввода введите Stop' + '\n') if line == "Stop": break else: line = line.split(' ') current_line = [int(i) for i in line] count_line += 1 matrix_of_variables.append(current_line) while True: line = input( 'Вводите свободные переменные построчно! - для остановки ввода введите Stop' + '\n') if line == "Stop": break else: line = line.split(' ') current_line = [int(i) for i in line] count_free_line += 1 matrix_of_free.append(current_line) if count_line != count_free_line: print("Данные введены не в правильном формате") else: answer = calc.method_of_cramer(matrix_of_variables, matrix_of_free) print('Ответ:' + '\n') for j in range(len(answer)): print(f'X{j + 1} = {answer[j]}')
7c49e8644fb479e2c017c80673c37c6de9c7ce61
AdamZhouSE/pythonHomework
/Code/CodeRecords/2506/61406/303936.py
281
3.515625
4
source = input().split(',') result = [] for i in range(0,len(source)): source[i] = int(source[i]) result.append(1) for b in range(1,len(source)): for a in range(0,b): if source[b]>source[a]: result[b] = max(result[b],result[a]+1) print(max(result))
bb27ca33aa1acc7c4227ae43246cbae976580f38
shadibdair/MyProjects
/Python Projects/Build Calculator/04_Step.py
860
4.0625
4
# Building a calculator import re print("Our Magical Calculator") print(" S H A D I\n") print("Type 'quit' to exit\n") previous = 0 run = True def performMath(): global run global previous equation = "" if previous == 0: equation = input("Enter equation: ") else: equation = input(str(previous)) if equation == 'quit': print("Goodbye, human.") run=False else: equation = re.sub('[a-zA-Z,.:()" "]','',equation) if previous == 0: previous = eval(equation) else: previous = eval(str(previous) + equation) while run: performMath() # Our Magical Calculator # S H A D I # Type 'quit' to exit # Enter equation: 5+1 # 6*3 # 18+11 # 29-23 # 6*12 # 72%12 # Enter equation: quit # Goodbye, human.
90c56ce5fab92ee8846ed5fdd6a67090e84d9606
ekorkut/python
/data_structures/tree/traversals.py
1,144
3.734375
4
from node import Node from collections import deque one = Node(1, None, None) four = Node(4, None, None) six = Node(6, None, None) five = Node(5, one, four) two = Node(2, six, None) three = Node(3, five, two) def pre_order(n): print n.data if n.left is not None: pre_order(n.left) if n.right is not None: pre_order(n.right) def post_order(n): if n.left is not None: post_order(n.left) if n.right is not None: post_order(n.right) print n.data def in_order(n): if n.left is not None: in_order(n.left) print n.data if n.right is not None: in_order(n.right) def level_order(n): q = deque() q.append(n) print n.data while len(q) > 0: n = q.popleft() if n.left is not None: print n.left.data q.append(n.left) if n.right is not None: print n.right.data q.append(n.right) print 'Pre-order traversal:' pre_order(three) print 'Post-order traversal:' post_order(three) print "In-order traversal:" in_order(three) print "Level-order traversal:" level_order(three)
3b64094d650c426b7a4c74c0d9d4eaf78b3c2310
indurkhya/Python_PES_Training
/Ques32.py
3,063
4.53125
5
# Write a program to perform following operations on List. Create three lists as List1, List2 and List3 having 5 # city names each list. # a. Find the length city of each list element and print city and length # b. Find the maximum and minimum string length element of each list # c. Compare each list and determine which city is biggest & smallest with length. # d. Delete first and last element of each list and print list contents. # a. Find the length city of each list element and print city and length lis1 = ["Bhopal","Jabalpur","India","Katni","Bangalore"] lis2 = ["Bhopal","Jabalpur","India","Katni","Bangalore"] lis3 = ["Bhopal","Jabalpur","India","Katni","Bangalore"] for item in lis1: print("City is: ",item,"length is: ",len(item)) for item in lis2: print("City is: ",item,"length is: ",len(item)) for item in lis3: print("City is: ",item,"length is: ",len(item)) # b. Find the maximum and minimum string length element of each list # c. Compare each list and determine which city is biggest & smallest with length. a = ["Bhopal","Jabalpur","India","Katni","Bangalore"] b = ["Bhopal","Jabalpur","India","Katni","Bangalore"] c = ["Bhopal","Jabalpur","India","Katni","Bangalore"] print("**********************************************************************************************************") lis = [] for item in a: length = len(item) lis.append(length) print("The maximum string length element ",max(lis)) print("The minimum string length element ",min(lis)) minpos = lis.index(min(lis)) maxpos = lis.index(max(lis)) print("The maximum is at position", maxpos) print("The minimum is at position", minpos) print("**********************************************************************************************************") for item in b: length = len(item) lis.append(length) print("The maximum string length element ",max(lis)) print("The minimum string length element ",min(lis)) minpos = lis.index(min(lis)) maxpos = lis.index(max(lis)) print("The maximum is at position", maxpos) print("The minimum is at position", minpos) print("**********************************************************************************************************") # for item in c: length = len(item) lis.append(length) print("The maximum string length element ",max(lis)) print("The minimum string length element ",min(lis)) minpos = lis.index(min(lis)) maxpos = lis.index(max(lis)) print("The maximum is at position", maxpos) print("The minimum is at position", minpos) print("**********************************************************************************************************") # d. Delete first and last element of each list and print list contents. ab = ["Bhopal","Jabalpur","India","Katni","Bangalore"] # print(ab) for i in range(0,len(ab)): if ab[i]==ab[0]: ab.remove(ab[0]) print(ab) else: break for i in range(0,len(ab)): if ab[i]==ab[len(ab)-1]: ab.pop() print(ab)
80fcfc3f7b2db04a7712693f74b05cef146524fb
srikanthpragada/PYTHON_03_JULY_2018_DEMO
/sqlite/change_loc.py
439
3.6875
4
import sqlite3 con = sqlite3.connect(r"e:\classroom\python\july3\hr.db") # Connection cur = con.cursor() # Cursor id = input("Enter department id :") loc = input("Enter new location :") cur.execute("update departments set location = ? where deptid = ?", (loc,id)) if cur.rowcount == 1: print("Successfully updated!") con.commit() else: print("Department Id Not Found!")
5bce59a4f343f43c3ef9592731e4d2a837231698
lyonva/ScheduleBot
/src/event_type.py
2,609
3.953125
4
class event_type: def __init__(self, event_name, start_time, end_time): """ Function: __init__ Description: Creates a new event_type object instance Input: self - The current type object instance name - String representing the type of event start_time - datetime object representing the start time of preferred time range end_time - datetime object representing the end time of preferred time range Output: - A new event_type object instance """ self.event_name = event_name self.start_time = start_time self.end_time = end_time # Converts event object to a string def __str__(self): """ Function: __str__ Description: Converts an event_type object into a string Input: self - The current event_type object instance Output: A formatted string that represents all the information about an type instance """ output = ( self.event_name + " " + str(self.start_time) + " " + str(self.end_time) ) return output def get_start_time(self): """ Function: get_start_time Description: Converts an start time in event_type object into a string Input: self - The current event_type object instance Output: A formatted string of the start time """ return str(self.start_time.strftime('%I:%M %p')) def get_end_time(self): """ Function: get_end_time Description: Converts an end time in event_type object into a string Input: self - The current event_type object instance Output: A formatted string of end time """ return str(self.end_time.strftime('%I:%M %p')) # Converts event object to a list def to_list_event(self): """ Function: to_list_event Description: Converts an event_type object into a list Input: self - The current event_type object instance Output: array - A list with each index being an attribute of the self event_type object """ array = [self.event_name, self.get_start_time(), self.get_end_time()] return array
ce233ac0f4383921685b36c753c8c8a08fe15e3e
AnatolyDomrachev/karantin
/is28/beresnev28/beresnev_lr/zadanie_2-9.py
377
3.5625
4
a=[[0],[0],[0],[0]] for w in range(4): for e in range(4): a[w][e]=int(input("Введите элемент массива = ")) print(a[0]) print(a[1]) print(a[2]) print(a[3]) s=a[1][1] for k in range(4): for u in range(4): if a[k][u] >= s: s=a[k][u] str=k sto=u print("наибольшее число = ", s,"строка = ",str+1,"столбец = ",sto+1)
883625c65b5915ad0eb3a312bea4a46e5d67463f
jeffn12/advent2020
/Day_1/Day_1.py
687
3.609375
4
entries = [] f = open("Day_1/Day_1.txt", "r") for line in f: entries.append(int(line)) f.close() def getProductOfTwo(entrylist): for first in entrylist: for second in entrylist[entrylist.index(first):]: if (second + first == 2020): return first * second return None def getProductOfThree(entrylist): for first in entrylist: for second in entrylist[entrylist.index(first):]: for third in entrylist[entrylist.index(second):]: if (first + second + third == 2020): return first * second * third return None print(getProductOfTwo(entries)) print(getProductOfThree(entries))
d8b035a10a86e3f8e963f52db7fb34077e935684
qq854051086/46-Simple-Python-Exercises-Solutions
/problem_27.py
1,141
4.46875
4
''' Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map() 3) using list comprehensions ''' def map_word_with_length_using_for(word_list): map_word_length = dict() for item in word_list: map_word_length[item] = len(item) return map_word_length ##################################################### def map_word_with_length_using_map(word_list): word_len_list = list(map(lambda x:len(x),word_list)) return dict(zip(word_list,word_len_list)) ##################################################### def map_word_with_length_using_list_comprehensions(word_list): word_len_list = [len(item) for item in word_list] return dict(zip(word_list, word_len_list)) # list of Shanto's imaginary girlfriends :D word_list = ['mithila','prokriti','amrita'] print(map_word_with_length_using_for(word_list)) print(map_word_with_length_using_map(word_list)) print(map_word_with_length_using_list_comprehensions(word_list))
9c241cca1ac186fe88a648216b67f42c4cd4ec5e
renol767/python_Dasar
/Dicoding/Dasar/Penanganan Kesalahan/test.py
551
3.75
4
d = {'ratarata': '10.0'} try: print('rata-rata: {}'.format(d['rata_rata'])) except KeyError:\ print('kunci tidak ditemukan di dictionary') except ValueError:\ print('nilai tidak sesuai') try: print('rata-rata: {}'.format(d['ratarata'] / 3)) except KeyError: print('kunci tidak ditemukan di dictionary') except (ValueError, TypeError): print('nilai atau tipe tidak sesuai') try: print('pembulatan rata-rata: {}'.format(int(d['ratarata']))) except (ValueError, TypeError) as e: print('penangan kesalahan: {}'.format(e))
e8c881291c4021e2bb4bb6bb9bd556e1f4512cac
dtingg/Fall2018-PY210A
/students/Vincent_Aquila/session03/list_lab.py
5,725
4.375
4
""" Python210A Vincent Aquila Fall2018 using Python 3.7.0 assignment objective: List Lab Note - I am using many/extra print statements in the code for the purpose of testing. Comment and Doc Strings might be explaining the obvious to experienced developers; if they seem redundant, it is for my learning purposes. There are four sections, each beginning with #Series 1, #Series 2, etc. """ #Series 1 """ -Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. -Display the list (plain old print() is fine…). -Ask the user for another fruit and add it to the end of the list. -Display the list. -Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct. -Add another fruit to the beginning of the list using “+” and display the list. -Add another fruit to the beginning of the list using insert() and display the list. -Display all the fruits that begin with “P”, using a for loop. """ list = ["Apples", "Pears", "Oranges", "Peaches"] for i in list: print(i) """ list = ["Apples", "Pears", "Oranges", "Peaches"] - *note to self* the list positioned below a for loop throws a TypeError - list needs to be above for loop """ response = input("Please select one other fruit you want added to this list. > ") new_fruit = response.title() """ The purpose of .title() is to ensure the first letter of the word is capitalized. Later in the program, in a for loop, the loop searches for words, and those words begin with a capital letter. If a user entered a word, where the first letters is not capitalized, then the program would not work properly. .title() ensures the program works correctly. """ #print(new_fruit) #test point to see the new fruit that was requested list.append(new_fruit) print(list) #this prints the amended list with the new fruit added to the end response = input("Please pick a number between 0 and 4. > ") number = response print(number) #note, further work could be done - when entering numbers outside 0-4 for j, item in enumerate(list): #generates two columns: numbers and fruits print(j, item) print(list) #add second fruit to the beginning of the list using + list.insert(0, "Strawberry") print(list) """ I learned a lot here - tried to use: l = (str(k)[1:-1]) which removes brackets from the list in the terminal display - but - after stripping brackets from a list and then employing an insert method - it won't work - throws an attribute error. Insert only works with a bracketed list. Unable to use the + sign to add the second fruit to the beginning of the list. """ #add a thrid fruit to the beginning of the list using insert() list.insert(0, "Kiwi") print(list) #display all the friuts that begin with "P" using a for loop for item in list: if "P" in item: print(item) print("---End of Series 1 Exercises---") #end of Series 1 #Series 2 """ Using the list created in series 1 above: -Display the list. -Remove the last fruit from the list. -Display the list. -Ask the user for a fruit to delete, find it and delete it. (Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) """ print(list) list2 = list #remove the last fruit from the list and display the new list list2.pop() print(list2) #ask the user for a fruit to delete and delete it response = input("Select a fruit to delete from the list. > ") response = response.title() list2.remove(response) print(list2) double_list = list2 * 2 print(double_list) print("---End of Series 2 Exercises---") #end of Series 2 #Series 3 """ Again, using the list from series 1: -Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). -For each “no”, delete that fruit from the list. -For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values (a while loop is good here) -Display the list. """ list3 = ["Apples", "Pears", "Oranges", "Peaches"] #original list response_apples = input("Do you like apples? Please respond with yes or no > ") if response_apples == "no": list3.remove("Apples") print(list3) response_pears = input("Do you like pears? Please respond with yes or no > ") if response_pears == "no": list3.remove("Pears") print(list3) response_oranges = input("Do you like oranges? Please respond with yes or no > ") if response_oranges == "no": list3.remove("Oranges") print(list3) response_peaches = input("Do you like peaches? Please respond with a yes or no > ") if response_peaches == "no": list3.remove("Peaches") print(list3) print("---End of Series 3 Exercies---") #end of Series 3 """ Series 4 Once more, using the list from series 1: -Make a copy of the list and reverse the letters in each fruit in the copy. -Delete the last item of the original list. Display the original list and the copy. """ list = ["Apples", "Pears", "Oranges", "Peaches"] list4 = list[:] #making a copy of list, now called list4 print(list4) Apples = (list[0]) print(Apples) reverse_Apples = Apples[::-1] print(reverse_Apples) Pears = (list[1]) print(Pears) reverse_Pears = Pears[::-1] print(reverse_Pears) Oranges = (list[2]) print(Oranges) reverse_Oranges = Oranges[::-1] print(reverse_Oranges) Peaches = (list[3]) print(Peaches) reverse_Peaches = Peaches[::-1] print(reverse_Peaches) #delete the last item of the original list - using pop() to remove Peaches list.pop() print(list) #prints the new list minus Peaches print(list4) #prints the copy of the list print("---End of Series 4 Exercies---") #end of Series4
5d61213715a8982cf881ad82c7a957182d5dacc0
PJTURP/Python-Practice
/main.py
195
3.84375
4
def function(): count = 1 potato = 1 while potato <= 10: while count <= 10: print(count) count = count + 1 potato = potato + 1 count = 1 function()
cae7c438f8a60585284997848cfff427112223d3
sanjay100192/Autosearch
/main.py
1,006
3.515625
4
import os import re from threading import Thread def run_threads(filename,module_name, c): obj = re.split(r'[\\]', filename)[-1:] with open(filename, "r") as f: for line in f.readlines(): if module_name in line: c += 1 if c == 1: print "Found in {} \n".format(filename) else: print "{} modules has same name in {} \n".format(c, "".join(obj)) Dir = "C:\Users\sanjay\PycharmProjects\Find_module" order = "{}\order.txt".format(Dir) register = "C:\Users\sanjay\PycharmProjects\Find_module\Register.txt" mnm = "{}\mnm.txt".format(Dir) c = 0 ans = raw_input("Enter module name : ") thread = Thread(target = run_threads, args = (order, ans, c)) thread2 = Thread(target = run_threads, args = (register, ans, c)) thread3 = Thread(target = run_threads, args = (mnm, ans, c)) thread.start() thread2.start() thread3.start() thread.join() #print "order completed" thread.join() #print "Register completed" thread.join() #print "mnm completed"
8f639d3874556d61d9ced7c4d751a3e917e0fce8
cyf1981/algoPrac
/Arrays/decompressRLElist.py
709
3.515625
4
''' https://leetcode.com/problems/decompress-run-length-encoded-list/ Orginally implemented the below solution but then converted it into a list comprehension solution Time complexity O(n*m) where m is the freq of a number n Space complexity O(n*m) ''' class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: return [x for i in range(0, len(nums), 2) for x in [nums[i+1]] * nums[i] ] # decompressed = [] # for i in range(0, len(nums), 2): # freq = nums[i] # val = nums[i+1] # #print(freq, val) # for j in range(freq): # decompressed.append(val) # return decompressed
f0ca1ee428b27beb25363bcd3118bcb236ff95a4
jaehyunan11/leetcode_Practice
/TOP_QUESTIONS/240.Search_a_2D_Matrix_II.py
1,190
3.8125
4
class Solution: def searchMatrix(self, matrix, target): print(len(matrix)) print(len(matrix[0])) for row in matrix: if target in row: return True return False # Bruce Force # TIME : O(n*m) since n * m search in the matrix # Space : O(1) def searchMatrix2(self, matrix, target): # empty matrix is doesn't contain target if len(matrix) == 0 or len(matrix[0]) == 0: return False # starting point row, col = 0, len(matrix[0])-1 while row < len(matrix) and col >= 0: # num in matrix is greater than target then pointer move to bottom if matrix[row][col] < target: row += 1 # num in matrix is less than target then pointer move to left elif matrix[row][col] > target: col -= 1 else: return True return False # TIME O(n+m) # Space O(1) : S = Solution() 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]] target = 5 print(S.searchMatrix(matrix, target)) print(S.searchMatrix2(matrix, target))
73038e322a51be5411d5badf3fbbf472ad14d4ca
ddenizakpinar/Practices
/Simple Array Sum.py
223
3.6875
4
# https://www.hackerrank.com/challenges/simple-array-sum/problem # 26.07.2020 def simpleArraySum(ar): return sum(ar) ar_count = int(input()) ar = list(map(int, input().rstrip().split())) print(simpleArraySum(ar))
376d7bafa7b7c633757d051604394ae822b0dc50
evanraalte/AdventOfCode2019
/day6.py
1,482
3.59375
4
def findDeps(orbit,relations,lst): for r in relations: if orbit in relations: lst.append((orbit,relations[orbit])) return 1 + findDeps(relations[orbit],relations,lst) return 0 f = open("day6.input","r") orbits = f.readlines() orbit_relations = [ orbit.strip().split(")") for orbit in orbits] # flatten list , filter unique flat_orbits = [] for orbit_relation in orbit_relations: flat_orbits = flat_orbits + orbit_relation unique_orbits = list(dict.fromkeys(flat_orbits)) orbit_relations = {sub[1] : sub[0] for sub in orbit_relations} part1 = 0 you = [] san = [] for orbit in unique_orbits: lst = [] deps = findDeps(orbit,orbit_relations,lst) # print(lst) def contains(lst,string): for e in lst: if e[0] == string: return True return False if contains(lst,'YOU'): you = lst[:] if contains(lst,'SAN'): san = lst[:] part1 += deps print(f"you : {you}") print(f"san : {san}") print(f"difference : {set(san).difference(set(you))}") print(f"difference : {set(you).difference(set(san))}") print(f"symmetric difference: {len(set(you).symmetric_difference(san))-2}") # alternative youCrossingLen = len(set(san).difference(set(you))) - 1 sanCrossingLen = len(set(you).difference(set(san))) - 1 part2 = youCrossingLen + sanCrossingLen # part2 = len(you.union(san) - you.difference(san)) - 1 print(f"part: {part1}") print(f"part: {part2}")
ffdc65e79bf63c670f6f7df3b411198c8e45d9b9
gqjuly/hipython
/helloword/2020_7_days/ten/c2.py
287
3.875
4
import re #判断字符串中是否有Python a = 'C|C++|Java|C#|Python|JavaScript' r = re.findall('Python', a) if len(r) != 0: print('字符串中包含Python') else: print('NO') # print(r) #方法一 var = a.index('Python') > -1 print(var) #方法二 print('Python' in a)
feed37b36f0a67bf60370dfb48226a80d0c082b4
CRomanIA/Python_Undemy
/Seccion_20_Librerias_Panda/Secc20_cap77_Eliminar_Elementos.py
709
3.84375
4
#Eliminar elementos en series y dataframes import pandas as pd import numpy as np np.arange(4) serie = pd.Series(np.arange(4), index=['a','b','c','d']) print(serie) #Si queremos eliminar un elemento (c) print(serie.drop('c')) #reshape = que la lista de valores se divide en 3 filas y 3 columnas print(np.arange(9).reshape(3,3)) lista_valores = np.arange(9).reshape(3,3) lista_indices = ['a','b','c'] lista_columnas = ['c1','c2','c3'] dataframe = pd.DataFrame(lista_valores, index=lista_indices, columns=lista_columnas) print(dataframe) print(dataframe.drop('b')) print(dataframe.drop('c2',axis=1)) dataframe = dataframe.drop('b') print(dataframe) dataframe = dataframe.drop('c2',axis=1) print(dataframe)
7978c3db80ec89104a3ed545a5f01a51a3fd9a6c
onlykumarabhishek/Algos-P1-Python
/Week2/Assignment2.py
1,976
4
4
tally = 0 def get_list(): """ Create list of integers using QuickSort.txt :return: list of integers """ with open('QuickSort.txt') as f: lon = [] for line in f: lon.append([int(x) for x in line.split()][0]) return lon def quick_sort(unsorted_list, question_num): return quick_sort_this(unsorted_list, 0, len(unsorted_list)-1, question_num) def quick_sort_this(unsorted_list, begin, end, question_num): global tally if end - begin == -1: return else: if question_num == 1: pivot_index = begin if question_num == 2: pivot_index = end if question_num == 3: pivot_index = median_pivot(unsorted_list, begin, end) unsorted_list[pivot_index], unsorted_list[begin] = unsorted_list[begin], unsorted_list[pivot_index] new_pivot_index = partition(unsorted_list, begin, end+1) quick_sort_this(unsorted_list, begin, new_pivot_index - 1, question_num) quick_sort_this(unsorted_list, new_pivot_index + 1, end, question_num) return def partition(arr, left, right): global tally tally += right - left - 1 pivot = arr[left] i = left + 1 for j in range(left+1, right): if arr[j] < pivot: arr[i], arr[j] = arr[j], arr[i] i += 1 arr[left], arr[i-1] = arr[i-1], arr[left] return i-1 def median_pivot(arr, begin, end): median_index = (begin + end) / 2 first = arr[begin] second = arr[median_index] third = arr[end] if first > second > third or first < second < third: return median_index if first > third > second or first < third < second: return end return begin def main(): global tally questions = [1, 2, 3] for i in questions: lon = get_list() tally = 0 quick_sort(lon, i) print 'Question', i, ':', tally return if __name__ == '__main__': main()
6fd658b940a1f216053dd972c44c9533a31bae8b
Rebeljah/Alien_Invasion
/bullet.py
1,772
4.03125
4
import pygame as pg from pygame.sprite import Sprite class Bullet(Sprite): """A class that represents a travelling bullet. This class uses code from Python Crash Course""" def __init__(self, game): """Create a bullet object at the ship's current position""" super().__init__() self.game = game self.ship = game.ship self.width = self.game.vars.bullet_w self.height = self.game.vars.bullet_h self.color = pg.Color(self.game.vars.bullet_color) # create the rectangle for the bullet and set its position self.rect = pg.Rect(0, 0, self.width, self.height) self.rect.midtop = self.ship.rect.midtop # store the bullet's y-value so it can move upward accurately self.y = float(self.rect.y) self.x = float(self.rect.x) def update(self, dt): """ Update the bullet's position, move the bullet rectangle, and delete the bullet if it has moved off screen """ # pixels per second * delta time in seconds move_distance = self.game.vars.bullet_speed * dt self.y -= move_distance # move up self.rect.y = self.y # align the bullet with the ship's centerx until it clears the ship if self.rect.bottom >= self.ship.rect.top: self.rect.centerx = self.ship.rect.centerx # remove the bullet if it has left the screen if self.rect.bottom < self.game.rect.top: self.remove_self() def draw_bullet(self): """draw the bullet to the game screen""" pg.draw.ellipse(self.game.screen, self.color, self.rect) def remove_self(self): """Remove this bullet from the bullets group""" self.remove(self.ship.bullets)
f1b2aa351cda874b70ef2ee914d6bcd3a56ea1e7
j0nah/rosalind
/dna/count_dna_nucleotides.py
601
3.828125
4
import collections # A string is simply an ordered collection of symbols selected from some alphabet # and formed into a word; the length of a string is the number of symbols that it contains. class CountDnaNucleotides: def __init__ (self, dnaString): self.dnaString = dnaString self.count_a = 0 self.count_c = 0 self.count_t = 0 self.count_g = 0 def count(self): return collections.Counter(list(self.dnaString)) def prettyCount(self): res = self.count() return "{} {} {} {}".format(res["A"], res["C"], res["G"], res["T"])
a04e781282d8bdc3b7d886cd39d98662aa4de488
MinKyeong031/Python_Study
/WS/set_study.py
411
3.640625
4
# 순서 X # 중복으로 저장 X # 합집합, 교집합, 차집합같은 집합 연산 가능 s1 = {1, 2, 3} s2 = {2, 3, 4, 4} # s3 = {} # 타입? => 딕셔너리 s3 = set() # print(s1[0]) print(s1) print(s2) # 중복 저장 불가 s2.add(4) s2.add(5) s2.add(5) s1 = {1, 2, 3} s2 = {2, 3, 4, 4} # 합집합 print(s1.union(s2)) # 교집합 print(s1.intersection(s2)) # 차집합 print(s1.difference(s2))
cd7fd204ec00b6d65ab37f011d1801609a2da0b7
sakakazu2468/AtCoder_py
/abc/026/a.py
79
3.625
4
a = int(input()) if a%2: print((a//2)*(a//2+1)) else: print((a//2)**2)
7cf9eed5656f9375a5876821a443586da6027565
Glightman/BlueEdTech_exercicios
/dict02.py
316
4
4
""" 2. Exercício Treino - Crie um dicionário em que suas chaves correspondem a números inteiros entre [1, 10] e cada valor associado é o número ao quadrado. {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} """ numeros = {} for num in range(0,10): numeros [num] = num**2 print(numeros)
805bf2beea9fe2aa7e7dfc29278e6d877f108a3b
tariqueameer7/course-python
/Labs/Lab01/Lab01-02_sum.py
123
4.03125
4
str_N = input("Please enter a number to find summation of 1..N: ") N = int(str_N) + 1 total = sum(range(1,N)) print(total)
2d766d56f1cd4b95a9800c01efb5dce214d393c9
darcangelomauro/rng_new
/script/commtxt.py
641
3.515625
4
nH = int(input('nH\n')) nL = int(input('nL\n')) print('COMM1') for i in range(nH): for j in range(i+1, nH): for k in range(nH, nH+nL): print('[H' + str(i+1) + ',H' + str(j+1) + ']L' + str(k-nH+1), end=' ') print('') print('COMM2') for i in range(nH, nH+nL): for j in range(i+1, nH+nL): for k in range(nH, nH+nL): print('[L' + str(i-nH+1) + ',L' + str(j-nH+1) + ']L' + str(k-nH+1), end=' ') print('') print('COMM3') for i in range(nH, nH+nL): for j in range(nH): for k in range(nH): print('[L' + str(i-nH+1) + ',H' + str(j+1) + ']H' + str(k+1), end=' ') print('')
d7e5bdbc9fe6baef34506a72a3115d2cce7bf159
dhlee49/MapReducePr
/tmapper.py
901
3.90625
4
#!/usr/bin/env python3 #sys for output import sys def gen_input(input_file): """ in: input file out: generator object for that input file """ for line in input_file: yield line.split() def trigrammap(lyric): """ in: tuple of all words in lyrics prints all triigrams to sys.stdout out: none """ pprev = None prev = None for word in lyric: if prev is not None and pprev is not None: print("%s %s %s\t%d" % (pprev,prev,word,1)) pprev = prev prev = word return def main(): """ Read input from stdin and toss it to gen_input to obtain generator for stdin then apply biigram to each line """ input_generator = gen_input(sys.stdin) for line in input_generator: #ignore first song id line = line[1:] trigrammap(line) if __name__ == "__main__": main()
203083351f1f2a0388e5f6c642dc02c141a6bf20
jonathanssaldanha/CursoPython
/104 Exercicios Python/ex048.py
487
3.796875
4
# FAÇA UM PROGRAMA QUE CALCULE A SOMA ENTRE TODOS OS NUMEROS IMPARES QUE SAO MULTIPLUS DE # TRES E QUE SE ENCONTRAM NO INTERVALO DE 1 ATE 500 soma = 0 cont = 0 for c in range(1, 501, 2): if c% 3 == 0: cont += 1 #cont = cont + 1 soma += c #soma = soma + c #print(c, end=' ') print('A soma de todos os {} valores solicitados é {}'.format(cont, soma))
61954413ccb3f6be30e906dfbaa9f5dd2ef12f7c
cholidek/python
/Day4/Homework3.py
294
3.796875
4
# Narysuj piramidę Mario - jako input - wysokość piramidy # np. piramida wysokości 3 ma wyglądać: # # # # ### # ##### wysokosc = input('Podaj wysokość piramidy: ') wysokosc = int(wysokosc) for i in range(wysokosc): print(" " * (wysokosc - 1 * i) + ("#") + ("#" * (1 * i)))
65c69c2f1b04aec517e64db1abe56eef84922458
Harry-2014/pythoncookbook
/chapter1/112.py
1,260
4.15625
4
''' 1.12 序列中出现次数最多的元素 问题 怎样找出一个序列中出现次数最多的元素呢? 解决方案 collections.Counter 类就是专门为这类问题而设计的,它甚至有一个有用的 most_common() 方法直接给了你答案。 ''' words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) print(word_counts) # 出现频率最高的3 个单词 top_three = word_counts.most_common(3) print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)] ''' 讨论 作为输入,Counter 对象可以接受任意的由可哈希(hashable)元素构成的序列 对象。在底层实现上,一个Counter 对象就是一个字典,将元素映射到它出现的次数 上。 ''' morewords = ['why','are','you','not','looking','in','my','eyes'] word_counts.update(morewords) print(word_counts) ''' Counter 实例一个鲜为人知的特性是它们可以很容易的跟数学运算操作相结合。 ''' a = Counter(words) b = Counter(morewords) c = a + b print(c) d = a - b print(d)