blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9243641cfc8c49e539536b9c3156e844ca1c294a
rednur01/ProjectEuler
/050/main.py
1,156
3.640625
4
# Consecutive prime sum from math import sqrt, ceil def is_prime(n: int) -> bool: if n < 2: return False elif n == 2 or n == 3 or n == 5: return True elif n % 2 == 0 or n % 3 == 0 or n % 5 == 0: return False else: for i in range(6, ceil(sqrt(n))+1, 6): # Only check upto sqrt(n) since at least one prime root must be < sqrt(n) # Start at 6 and jump by 6 # Since all primes are 1 mod 6 or 5 mod 6 # only need to check i + 1 and i + 5 for prime factors if n % (i + 1) == 0 or n % (i + 5) == 0: return False return True primes: list[int] = [i for i in range(2, 1_000_000) if is_prime(i)] longest_window: list[int] = [] check_length: int = 21 for window_index in range(len(primes) - check_length - 1): for window_length in range(check_length, len(primes) - window_index): window = primes[window_index: window_index+window_length] window_sum = sum(window) if window_sum > 1_000_000: break elif window_sum in primes and len(window) > len(longest_window): longest_window = window check_length = len(longest_window) print(len(longest_window), sum(window))
a6a5a340ce29a4e292711e9227919fd3948edaf5
semicolonTransistor/housing-visualization
/state_init.py
449
3.546875
4
import sqlite3 def main(): connection = sqlite3.connect("data/housing.sqlite") cursor = connection.cursor() with open("states.txt") as f: data = map(lambda x: (x[0], x[1], int(x[2])), map(lambda line: tuple(map(lambda s: s.strip(), line.split("\t"))), f)) cursor.executemany("INSERT INTO state (name, abbreviation, id) VALUES (?, ?, ?)", data) connection.commit() connection.close() main()
b91075688c511bea9d0fc82246b6f21774726a1a
Ajay2521/Python
/ADVANCE/Functions/Built in Function/bytearray( ).py
593
3.953125
4
# In this lets see about the "Built-in functions" in python. # Built-in function is defined as the functions whose functionality is pre-defined in the python compiler. # Lets see about "bytearray( ) bilt-in function" in python. # bytearray( ) - Used to returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size. # Here is the program for bytearray( ) print ( ) # Prints new line for readability. a = "This is bytearray( ) Program" print ( bytearray( a , 'utf-8') ) # utf-8 is a type of encoding.
85c4fe653f7ee3c652cfa8386fc409b11b389e6b
Gporfs/Python-s-projects
/exercicio043.py
761
3.828125
4
maior = menor = 0 cont = 1 n = int(input('Digite um valor: ')) continuar = str(input('Deseja continuar[S/N]? ')).strip().upper() soma = n while continuar in 'Ss': if cont == 1: menor = n maior = n else: if maior < n: maior = n if menor > n: menor = n cont += 1 soma += n n = int(input('Digite um valor: ')) continuar = str(input('Deseja continuar[S/N]? ')).strip().upper() if continuar in 'Nn': media = soma / cont print('A média entre os valores fornecidos é de: {:.1f}'.format(media)) print('O maior valor digitado foi: {}'.format(maior)) print('O menor valor digitado foi: {}'.format(menor)) else: print('ERRO!REINICIE O PROGRAMA!')
428f75d5d397e745eec773e5343f3a9a01dcaa21
bandiayyappa/pythonprograms
/sortNumbersInTextFile.py
262
3.515625
4
# sort numbers in a text file fh = open('numbers.txt','r') data = fh.read().strip().split() fh.close() data = list(map(int,data)) data.sort() str_data = list(map(str,data)) str_data = ' '.join(str_data) fh = open('output.txt','w') fh.write(str_data) fh.close()
10d7b0c8373f0647a6bc654024bef86ceb85569c
Tijauna/CSC180-Python-C
/lab8/conwaylib1.py
1,894
3.5625
4
# coding: utf-8 from random import randint class conway: def __init__(self,sizeY, sizeX, typeInit): #sizeY is row #sizeX is col self.sizeX = sizeX self.sizeY = sizeY if(typeInit == 'zeros'): self.store = [[0 for i in range(sizeX)] for j in range(sizeY)] if(typeInit == 'ones'): self.store = [[1 for i in range(sizeX)] for j in range(sizeY)] elif(typeInit == 'random'): self.store = [[(randint(0,1)) for i in range(sizeX)] for j in range(sizeY)] def getDisp(self): self.string = "" for i in self.store: for j in i: if(j == 1): self.string += str("*") else: self.string += str(" ") self.string += "\n" return self.string def printDisp(self): self.getDisp() print(self.string) return True def setPos(self, row, column, value): if(row<0 or column<0 or row>self.sizeY-1 or column>self.sizeX-1): return False if(value != 1 and value != 0): return False self.store[row][column] = value return True def getNeighbours(self, row, col): if(row<0 or col<0 or row>self.sizeY-1 or col>self.sizeX-1): return False counter = 0 out = [None]*8 for i in range(row-1, row+2): if(i < 0): i += self.sizeY if(i >= self.sizeY): i -=self.sizeY for j in range(col-1, col+2): if(i==row and j == col): continue if(j < 0): j += self.sizeX if(j >= self.sizeX): j -=self.sizeX out[counter] = self.store[i][j] counter+=1 return out
e637715b1411f9bacf1c1c3d00b225c265915e35
zhan01/guess-numbers
/guess_number.py
426
3.9375
4
number = 77 guess = input("\nGuess: ") guess = int(guess) counter = 1 while guess != number : if guess > number : print("Guess lower!") else: print("Guess higher!") print("-------------") guess = input("\nTry again: ") guess = int(guess) counter = counter + 1 print("\nYou won the game in " + str(counter) + " step(s) ! Congrats!")
c3b270511b5b364d18225be4c7cc2911d8020c13
pervejalam/python-930pm
/loops/while-if-break.py
212
3.984375
4
#!/usr/bin/python while True: print ("Enter a digit") num=input() #var=str(num) if(ord(num) in range(48,58)): # Decimal 0-9 break #continue print ("We are out of the while loop")
92a819cfeac2c910a86e325b1a8928e95a4bcc2d
balonovatereza/Pyladies-repository
/02/porovnani.py
296
4.03125
4
pravda = 1 < 3 print(pravda) nepravda = 1 == 3 print(nepravda) print(True) print(False) tajneHeslo = 'Abrakadabra' tipUzivatele = input('Zadej tajne heslo: ') if tipUzivatele == 'Abrakadabra': print('V patek jsem videla cerneho havrana.') else: print('Spatne heslo, zkus to znova.')
3fd951e0aff1ee6075022b0243134da2bd50cc8d
everbird/leetcode-py
/2015/LinkedListCycle_v0.py
864
3.859375
4
#!/usr/bin/env python # encoding: utf-8 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): p2 = p1 = head while p1 and p2: p1 = p1.next p2 = p2.next.next if p2.next else None if p1 and p2 and p1 == p2: return True return False if __name__ == '__main__': s = Solution() n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n6 = ListNode(6) head = n1 n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 n6.next = n4 print s.hasCycle(head) n1 = ListNode(1) head = n1 print s.hasCycle(head)
e1b9d0e08d99364a4468c6e3744ec6c63cc56ab8
NotaRobotexe/RoboticArm
/RoboticArm/Scripts/bruteForceArm.py
1,287
3.5
4
import math def AngToRad(angle): return angle*math.pi/180 def float_range(start,stop,step): x = start my_list = [] if step > 0: while x < stop: my_list.append(x) x += step else: # should really be if step < 0 with an extra check for step == 0 while x > stop: my_list.append(x) x += step return my_list target = [20,-12] elb0 = 25.5 elb1=12.5 elb2=20 elb0R=[0,90] elb1R=[300,360] elb2R=[200,300] for ang0 in float_range(elb0R[0],elb0R[1],1): elb0x = elb0*math.cos(AngToRad(ang0)) elb0y = elb0*math.sin(AngToRad(ang0)) for ang1 in float_range(elb1R[0],elb1R[1],1): elb1x = elb1*math.cos(AngToRad(ang1))+elb0x elb1y = elb1*math.sin(AngToRad(ang1))+elb0y for ang2 in float_range(elb2R[0],elb2R[1],1): elb2x = elb2*math.cos(AngToRad(ang2+14.75))+elb1x elb2y = elb2*math.sin(AngToRad(ang2+14.75))+elb1y if(round(elb2x,0) == target[0] and round(elb2y,0) == target[1]): print("find " + str(ang0) + " " + str(360-(ang1-ang0)) + " "+ str(270-ang2)+ " "+str(elb0x)+" "+str(elb0y) + " "+str(elb1x)+" "+str(elb1y)+ " "+str(elb2x)+" "+str(elb2y)) #if (round(elb1x,0) == round(elb2x,0)):
a46c28ee0b4fa70d73a3dd0ebca08d407a6eff6a
AlfredoAndrade14/AprendendoPython
/Mundo 1/soma_simples.py
139
3.8125
4
A = int(input("Digite um número: ")) B = int(input("Digite outro número: ")) SOMA = A + B print ("A soma desses números é = %i"%SOMA)
265a851c6f386867b3c08fa60e4875862645d203
ebachmeier/School
/Python/PoisonPenny.py
2,608
4.09375
4
# Eric Bachmeier # Date Compleetd: October 7, 2011 print "Poison Penny" print "------------" print print "Poison penny is a game for two players. Twelve pennies and a nickel" print "are laid out. Each player can take one or two pennies, alternating" print "turns until only the nickel (the poison) is left. Whoever's turn it is," print "when only the poisoned nickel is left, loses." print repeat = True while repeat == True: pennies = 12 nickel = 1 player = 1 #enter player names player1 = raw_input ("Enter player 1's name: ") player2 = raw_input ("Enter player 2's name: ") while nickel == 1: print "There are ", pennies, "pennies and ", nickel, "nickel left." print valid = 0 while valid == 0: if player == 1: pick = int (raw_input (player1 + ", how many pennies do you wish to take? ")) else: pick = int (raw_input (player2 + ", how many pennies do you wish to take? ")) if pick > 2 or pick > pennies or pick < 1: valid = 0 else: pennies = pennies - pick valid = 1 # check for end of game if pennies == 0: print if player == 1: #player1 wins print player2 +", you lose because you must take the nickel." print "Congratulations " + player1 +", you are the winner." nickel = 0 else: #player2 wins print player1 +", you lose because you must take the nickel." print "Congratulations " + player2 +", you are the winner." nickel = 0 else: #switch players if player == 1: player = 2 else: player = 1 print loop = 1 while loop == 1: response = raw_input ("Would you like to play again? (Y/N): ") if response == "n" or response == "N": repeat = False loop = 0 elif response == "y" or response == "Y": repeat = True loop = 0 print else: print "Please enter a valid response eg. (Y/N)" print print "GAME OVER!" print print "Thanks you for playing. Come back soon."
91ae27756c1abac1bbe1a431656f3a54bab987fb
gustavo-detarso/engenharia_de_software
/concluidas/logica_de_programacao_e_algoritmos/Aula_3/c3_ex_2.py
387
3.84375
4
# Ler dois valores numéricos inteiros e caso seja par imprimir uma mensagem informando, do mesmo jeito caso seja ímpar # Passo 1: Definindo strings num = float(input('Digite um número: ')) # Passo2: Montando o algoritmo if num%2 == 0: print('O número digitado é par.') else: print('O número digitado é ímpar.') if num%7 == 0: print('O número é multiplo de sete.')
bfc3f24db2ef8a04021fe06f63ec9f1f97841799
cobed95/cs-coach
/algorithms/sorting/answers/insertion_sort_fp.py
928
4
4
def insert(int_list, key): if len(int_list) == 0: return [key] else: if int_list[0] <= key: return [key] + int_list else: return [int_list[0]] + insert(int_list[1:], key) def iterate(loop_invariant, todo): if len(todo) == 0: return loop_invariant else: inserted = insert(loop_invariant, todo[0]) return iterate(inserted, todo[1:]) def reverse(int_list, container): if len(int_list) == 0: return container else: return reverse(int_list[1:], [int_list[0]] + container) def insertion_sort(int_list): if len(int_list) == 0: return [] else: return reverse(iterate([int_list[0]], int_list[1:]), []) def main(): int_list = [1332, 3,2, 334, 6, 61, 2,4, 245, 567, 220, 2, 2324, 45, 23, 21, 1, 1,3] print(int_list) print(insertion_sort(int_list)) if __name__ == "__main__": main()
0342dbc6a3fba24b9d2ba09d9386f957400f29b5
MSCapeletti/MC906-Projeto1
/informed_search.py
3,603
3.53125
4
from Problem import Node class PriorityQueue: def __init__(self, maxsize=5000): self.maxsize = maxsize self.items = [] self._index = 0 def append(self, item, priority): if len(self.items) < self.maxsize: self.items.append((item, priority)) def pop(self): self.items.sort(key=lambda x: x[1]) return self.items.pop(0)[0] def __iter__(self): self._index = 0 return self def __next__(self): if self._index < len(self.items): result = self.items[self._index] self._index = self._index + 1 return result raise StopIteration def isEmpty(self): return len(self.items) == 0 def __len__(self): return len(self.items) def __getitem__(self, index): return self.items[index] def best_first_graph_search_for_vis(problem, f): iterations = 0 all_node_colors = [] node_colors = {k: 'white' for k in set(problem.reachable_positions(problem.initial))} node = Node(problem.initial) node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) frontier = PriorityQueue() frontier.append(node, f(node)) node_colors[node.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) explored = set() while not frontier.isEmpty(): node = frontier.pop() node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test([node.state for node in node.path()]): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return (iterations, all_node_colors, node) explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child, f(child)) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) elif child in frontier: incumbent = frontier[child] if f(child) < f(incumbent): del frontier[incumbent] frontier.append(child, f(child)) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) node_colors[node.state] = "gray" iterations += 1 all_node_colors.append(dict(node_colors)) return iterations, all_node_colors, node def greedy_best_first_search(problem, h=None): """Greedy Best-first graph search is an informative searching algorithm with f(n) = h(n). You need to specify the h function when you call best_first_search, or else in your Problem subclass.""" if h == None: h = problem.h2 iterations, all_node_colors, node = best_first_graph_search_for_vis(problem, lambda n: h(n)) return (iterations, all_node_colors, node) def uniform_cost_search(problem, display=False): iterations, all_node_colors, node = best_first_graph_search_for_vis(problem, lambda node: node.path_cost) return (iterations, all_node_colors, node) def astar_search_graph(problem, h=None, g=None): if h is None: h = problem.h if g is None: g = problem.g iterations, all_node_colors, node = best_first_graph_search_for_vis(problem, lambda n: g(n) + h(n)) return iterations, all_node_colors, node
3be2ed5126fbf43036e9f05a71e31e3d9ceae5b4
fahaddd-git/programmingProblems
/20_ValidParentheses.py
2,116
3.90625
4
# ID: 20 # URL: https://leetcode.com/problems/valid-parentheses/ # Difficulty: Easy # Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # An input string is valid if: # -Open brackets must be closed by the same type of brackets. # -Open brackets must be closed in the correct order. class Solution: def isValid(self, s: str) -> bool: """ example= "[({})]" algorithm: - check if the initial length of input is 1 - push first char to stack ["["] - if next char is a matching closing bracket, remove the previous char from array - else add it to the array - after iterating through the string, if the length of the array not None then return false - else return True """ closing_paren={ "}":"{", "]":"[", ")":"(" } # input string length is one and has no matching parenthesis if len(s)==1: return False # first in first out stack data structure stack=[] # iterate through the string adding the open parentheses and popping if a matching closing parenthesis is found for paren in s: try: # push the opening parenthesis to top of stack if paren in closing_paren.values(): stack.append(paren) # pop the top of the stack if it matches a closing parenthesis elif closing_paren[paren]==stack[-1]: stack.pop() # stack imabalance, not a valid input else: return False # accounts for the case '}{' since stack[-1] will raise an exception except IndexError: return False # imbalanced stack if len(stack)>0: return False # parentheses all matched, valid input return True
b6629d24fae32ac439da7861fc86b3910eae4d03
YuMi-coding/pcapCounters
/src/helpers.py
172
3.875
4
# The general helper functions def insert_to_dict(dict, key, item): if key in dict: dict[key].append(item) else: dict[key] = [item] return dict
6263a032629c0ef2a0329afabf2756f05150b477
raj-ankit744/Python-assignments
/Test/3.py
1,259
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 6 14:06:22 2018 @author: user """ import operator file = "C:/Users/user/Desktop/ARG/Test/Input.txt" students = [] with open(file,'r') as f: x = f.readline() while(x!=""): students.append(tuple(x.split())) x = f.readline() f.close() print() students = sorted(students, key = operator.itemgetter(3)) for i in range(len(students)): print("{:10}{:5}{:10}{:5}{:5}".format(students[i][0],students[i][1],students[i][2],students[i][3],students[i][4])) bmi = [] for i in students: x = float(i[4])/float(i[3])**2 bmi.append(x) print() for i in range(len(students)): print("{:10}{:5}{:10}{:5}{:5}{:5}".format(students[i][0],students[i][1],students[i][2],students[i][3],students[i][4],bmi[i])) healthy = [] overweight = [] obese = [] for i in range(len(bmi)): if bmi[i] >= 30: obese.append(i) elif bmi[i] >=25: overweight.append(i) else: healthy.append(i) print() print("Healthy Students") for i in healthy: print(students[i][0]) print() print("Overweight Students") for i in overweight: print(students[i][0]) print() print("Obese Students") for i in obese: print(students[i][0])
51c95c36482f24b9e28628d1638a86a9bc4c7cb0
vishali0044/MoTask
/app.py
1,915
4.21875
4
import tkinter as tk #Tkinter is basically a package to run python code, this will help to create GUI from tkinter import filedialog, Text # it will help to pick the Apps import os root = tk.Tk() apps = [] if os.path.isfile('save.txt'): with open('save.txt', 'r') as f: tempApps = f.read() tempApps = tempApps.split(',') #it will remove space, but split files apps = [x for x in tempApps if x.strip()] def addApp(): #It will open file directories ,which we want to select for widget in frame.winfo_children(): # widget will give us access to everything which is attached to frame widget.destroy() #It will destroy or remove previous file and attach updated one #It will allows to specifies things filename = filedialog.askopenfilename(initialdir="/", title="Select File", filetypes=(("executables", "*.exe"), ("all files", "*.*"))) apps.append(filename) #It will give the location of file print(filename) for app in apps: label = tk.Label(frame, text=app, bg="gray") label.pack() def runApps(): for app in apps: os.startfile(app) canvas = tk.Canvas(root, height=600, width=600, bg="#263D42") canvas.pack() frame = tk.Frame(root, bg="white") frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) #This line will add button on App and it will attach to root(Button name is Open file) openFile = tk.Button(root, text="Open File", padx=10, pady=5, fg="white", bg="#263D42", command=addApp) openFile.pack() runApps = tk.Button(root, text="Run Apps", padx=10, pady=5, fg="white", bg="#263D42", command=runApps) runApps.pack() for app in apps: label = tk.Label(frame, text=app) label.pack() root.mainloop() with open('save.txt', 'w') as f: #It will generate save.txt file so all files or app wll be saved for app in apps: f.write(app + ',')
f218d9959d67041c6dc289f9a9aba23630053edc
pythongim/Gabaritos
/Primeira Lista de Exercícios/7.py
442
4.0625
4
# -*- coding: utf-8 -*- day = input("Digite um dia em 2013: ") if day > 365 or day <= 0: print("O ano de 2013 tem apenas 365 dias.") if day % 7 == 1: print("Terça-feira") elif day % 7 == 2: print("Quarta-feira") elif day % 7 == 3: print("Quinta-feira") elif day % 7 == 4: print("Sexta-feira") elif day % 7 == 5: print("Sábado") elif day % 7 == 6: print("Domingo") elif day % 7 == 0: print("Segunda-feira")
7b70745b7c4da3a408204e2d510901fa22861550
DerDoktorFaust/PackageDeliveryPathFindingAlgorithm
/main.py
6,223
3.84375
4
'''Main entry point into the program. It has four main functions. 1) load data from CSV files (data originally created in excel_data_parser.py. The data parser must be run separately, this main program only reads data from CSV files. 2) Print reports that show the status of all packages at any time selected by the user. 3) Create class instances and do all calls that run the program. 4) Provide a command line interface for the user to generate custom reports.''' from Hashmap import * from Graph import * from Truck import * import re def load_data(): '''Function opens CSV files generated by excel_data_parser.py. For packages, it reads the data and inserts it all into a hashmap called packages_map. For distances between locations it inserts them into an instance of the Graph class.''' with open('./resources/packages.txt', 'r') as packages_file: packages_file.seek(0) for line in packages_file: # strip all newlines and split into list delimited by commas temp_line = line.strip('\n').split(',') key = int(temp_line[0]) value = temp_line[1:] packages_map.insert(key, value) packages_file.close() with open('./resources/distances.txt', 'r') as distances_file: distances_file.seek(0) data = distances_file.readlines() for i in range(0, len(data)): data[i] = data[i].strip('\n').split(',') graph.add_map_edge( data[i][0], data[i][1], float( data[i][2])) # use float() for the distance distances_file.close() def print_reports(time='05:00 PM'): '''Generates a report that prints the status of all packages based on a user's inputted time. If no time is provided by the user, the default is 5:00 PM.''' print(f"Package Status Report as of {time}") def check_if_in_transit(package_delivery_time): '''Checks each package at the report time to decide whether the package is at the hub, in transit, or already delivered.''' # converts time that user wishes to view from string to integers # splits by colon and a space, making [hour, minute, AM/PM] report_time = re.split(r'[: ]', time) # convert the numbers to integers for calculations report_time[0] = int(report_time[0]) report_time[1] = int(report_time[1]) # converts delivery time of actual package to do calculations delivery_time = re.split(r'[: ]', package_delivery_time) delivery_time[0] = int(delivery_time[0]) delivery_time[1] = int(delivery_time[1]) # converts start time of truck to do calculations start_time = re.split(r'[: ]', '08:00 AM') start_time[0] = int(start_time[0]) start_time[1] = int(start_time[1]) # following statements compare start and delivery time with the requested report time # and returns it's status as of the report time. if report_time[0] > start_time[0] and delivery_time[0] > report_time[0]: temp_delivery_status = 'In Transit' return temp_delivery_status elif report_time[0] == delivery_time[0] and report_time[1] < delivery_time[1]: temp_delivery_status = 'In Transit' return temp_delivery_status if report_time[0] < 8 and report_time[2] == 'AM': temp_delivery_status = 'At Hub' return temp_delivery_status else: temp_delivery_status = 'Delivered' return temp_delivery_status def check_if_delivered(): '''Takes the results of check_if_in_transit to determine if Delivery Time is N/A (i.e. not delivered) or it returns the delivery time if the report time is for after the delivery occurred.''' if temp_delivery_status != 'Delivered': return f"N/A" if temp_delivery_status == 'Delivered': return packages_map.get(i)[8] # Actual printing of the report for i in range(1, packages_map.number_of_items + 1): temp_delivery_status = check_if_in_transit(packages_map.get(i)[8]) print(f"Package ID: {i} " f"Delivery Address: {packages_map.get(i)[0]} {packages_map.get(i)[1]}, {packages_map.get(i)[2]} {packages_map.get(i)[3]} " f"Required Delivery Time: {packages_map.get(i)[4]} " f"Package Weight: {packages_map.get(i)[5]} " f"Special Notes: {packages_map.get(i)[6]} " # calls function to determine status f"Delivery Status: {check_if_in_transit(packages_map.get(i)[8])} " f"Delivery Time: {check_if_delivered()}") # calls function to decide between N/A or actual delivery time # Create class instances and set default values if necessary packages_map = Hashmap(40) graph = Graph() load_data() truck1 = Truck('truck1') truck2 = Truck('truck2') truck3 = Truck('truck3') # truck 3 needs to finish deliveries quickly and return to hub so driver # can switch trucks truck3.max_capacity = 8 # Call functions to load trucks truck3.load_truck(packages_map, graph) truck1.load_truck(packages_map, graph) # driver of truck 3 drives truck 2 as soon as he returns to hub truck2.time = truck3.time truck2.load_truck(packages_map, graph) # Calculate the total distance to deliver all packages total_distance = round(truck1.mileage + truck2.mileage + truck3.mileage, 1) # Code for command line interface quit = False # variable for CLI loop while quit == False: print("\n\nPlease select from the following menu: ") print("[1] See Final Delivery Report (05:00 PM") print("[2] Input Custom Time Report") print("[3] Check Final Distance for Delivery of All Packages") print("[4] Quit Program") choice = input("Enter choice ===> ") if choice == '1': print_reports() print(f"\nTotal final distance is===> {total_distance}") if choice == '2': custom_time = input("Enter Custom Time in Format 00:00 AM/PM====> ") print_reports(custom_time) if choice == '3': print(f"\nTotal final distance is===> {total_distance}") if choice == '4': quit = True else: continue
71b9a057f7906dfb5896975978b0a55f9cee46b0
aoyono/sicpy
/Chapter2/exercises/exercise2_37.py
1,735
3.671875
4
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_thm_2.37 """ from operator import add, mul from Chapter2.exercises.exercise2_36 import accumulate_n from Chapter2.themes.lisp_list_structured_data import cons, lisp_list, print_lisp_list from Chapter2.sequences_as_conventional_interfaces import accumulate, map from utils import let def map_n(op, init, *seqs): return map( lambda l: accumulate(op, init, l), accumulate_n( cons, lisp_list(), lisp_list(*seqs) ) ) def dot_product(v, w): return accumulate( add, 0, map_n(mul, 1, v, w) ) def matrix_dot_vector(m, v): return map( lambda row: dot_product(v, row), m ) def transpose(mat): return accumulate_n( cons, lisp_list(), mat ) def matrix_dot_matrix(m, n): with let(transpose(n)) as (cols,): return map( lambda row: matrix_dot_vector(cols, row), m ) def run_the_magic(): with let( lisp_list( lisp_list(1, 2, 3), lisp_list(4, 5, 6), lisp_list(6, 7, 8), ), lisp_list( lisp_list(1, 0, 0), lisp_list(0, 8, 0), lisp_list(0, 0, 1), ) ) as (m, n): print('(define m (list (list 1 2 3) (list 4 5 6) (list 6 7 8))') print_lisp_list(m) print('(define n (list (list 1 0 0) (list 0 1 0) (list 0 0 1))') print_lisp_list(n) print('(matrix-*-matrix m n)') print_lisp_list(matrix_dot_matrix(m, n)) if __name__ == '__main__': run_the_magic()
9aafbb29fcaa22e785baba0ab66a6964923f61ea
aluhrs/HB_OOP_Lesson
/game.py
9,644
3.53125
4
import core import pyglet from pyglet.window import key from core import GameElement import sys #### DO NOT TOUCH #### GAME_BOARD = None DEBUG = False KEYBOARD = None PLAYER = None ###################### GAME_WIDTH = 10 GAME_HEIGHT = 10 #### Put class definitions here #### class Rock(GameElement): IMAGE = "Rock" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == Gem and (self.x == 2 and self.y == 3): GAME_BOARD.del_el(2, 3) class Character(GameElement): IMAGE = "Horns" def __init__(self): GameElement.__init__(self) self.inventory = [] def next_pos(self, direction): if direction == "up": return (self.x, self.y-1) elif direction == "down": return (self.x, self.y+1) elif direction == "left": return (self.x-1, self.y) elif direction == "right": return (self.x+1, self.y) return None class Gem(GameElement): IMAGE = "BlueGem" SOLID = False def interact(self, player): player.inventory.append(self) GAME_BOARD.draw_msg("Oh no! Ryan Reynolds is trying to take over Ryan Gosling's photoshoot! Use the super strength from the gem to crush a boulder, and defeat Ryan Reynolds!") class Heart(GameElement): IMAGE = "Heart" SOLID = True class Chest(GameElement): IMAGE = "Chest" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == Key: player.inventory.append(self) GAME_BOARD.draw_msg('There\'s a message in the chest! "Use wood from a tree to cross the river."') GAME_BOARD.del_el(8, 8) openchest = ChestOpen() GAME_BOARD.register(openchest) GAME_BOARD.set_el(8, 8, openchest) class ChestOpen(GameElement): IMAGE = "ChestOpen" SOLID = True class ShortTree(GameElement): IMAGE = "ShortTree" SOLID = True class TallTree(GameElement): IMAGE = "TallTree" SOLID = True class SpecialTallTree(GameElement): IMAGE = "SpecialTallTree" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == Chest: player.inventory.append(self) GAME_BOARD.del_el(5,6) GAME_BOARD.draw_msg("You built a canoe! Hey, remember that canoe scene from the Notebook?") boat = Boat() GAME_BOARD.register(boat) GAME_BOARD.set_el(6, 5, boat) class UglyTree(GameElement): IMAGE = "UglyTree" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == Girl: GAME_BOARD.draw_msg("You have found the key! Go pick it up!") GAME_BOARD.del_el(0, 6) keys = Key() GAME_BOARD.register(keys) GAME_BOARD.set_el(2, 6, keys) class Boat(GameElement): IMAGE = "Boat" SOLID = False def interact(self, player): GAME_BOARD.draw_msg("Go find the Blue Gem!") class Water(GameElement): IMAGE = "WaterBlock" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == SpecialTallTree and (self.x == 6 and self.y == 5): self.SOLID = False # class SpecialWaterBlock(GameElement): # IMAGE = "WaterBlock" # def interact(self, player): # for item in player.inventory: # if type(item) == SpecialTallTree: # self.SOLID = False class Key(GameElement): IMAGE = "Key" SOLID = False def interact(self, player): player.inventory.append(self) GAME_BOARD.draw_msg("You just acquired a key! Now use it to unlock the chest!") class Stone(GameElement): IMAGE = "StoneBlock" SOLID = True def interact(self, player): for item in player.inventory: if type(item) == Ava and (self.x == 7 and self.y == 0): GAME_BOARD.del_el(7, 0) player.inventory.append(self) for item in player.inventory: if type(item) == Stone and (self.x == 8 and self.y == 0): GAME_BOARD.del_el(8, 0) class Boy(GameElement): IMAGE = "Boy" SOLID = True def interact(self, player): GAME_BOARD.draw_msg('Programmer Ryan: "Hey girl, fork my heart because I\'m ready to commit."') GAME_BOARD.del_el(8, 1) heart = Heart() GAME_BOARD.register(heart) GAME_BOARD.set_el(8, 1, heart) class Girl(GameElement): IMAGE = "Girl" SOLID = True def interact(self, player): GAME_BOARD.draw_msg('"To help Ryan, search for a key to unlock the chest."') speech_bubble = SpeechBubble() GAME_BOARD.register(speech_bubble) GAME_BOARD.set_el(3, 7, speech_bubble) player.inventory.append(self) class SpeechBubble(GameElement): IMAGE = "SpeechBubble" SOLID = False class Ava(GameElement): IMAGE = "Princess" SOLID = True def interact(self, player): GAME_BOARD.draw_msg('"You have defeated me! Now you can go save Ryan from the tower I locked him in."') player.inventory.append(self) GAME_BOARD.del_el(2, 2) bug = Bug() GAME_BOARD.register(bug) GAME_BOARD.set_el(2, 2, bug) class Bug(GameElement): IMAGE = "Bug" SOLID = True #### End class definitions #### def initialize(): """Put game initialization code here""" # ROCKS rock_positions = [ (2, 1), (1, 2), (3, 2), (2, 3) ] rocks = [] for pos in rock_positions: rock = Rock() GAME_BOARD.register(rock) GAME_BOARD.set_el(pos[0], pos[1], rock) rocks.append(rock) for rock in rocks: print rock # PLAYER global PLAYER PLAYER = Character() GAME_BOARD.register(PLAYER) GAME_BOARD.set_el(0, 9, PLAYER) print PLAYER GAME_BOARD.draw_msg("Help Ryan Gosling! He's trapped and can't get to his Sexiest Man Alive photoshoot!") # GEM gem = Gem() GAME_BOARD.register(gem) GAME_BOARD.set_el(0, 1, gem) # CHEST chest = Chest() GAME_BOARD.register(chest) GAME_BOARD.set_el(8, 8, chest) # SHORT TREES short_tree_positions = [ (9, 8), (9, 9), (9, 7), (8, 7), (7, 7), (7, 8), (7, 9), (8, 9) ] short_trees = [] for pos in short_tree_positions: short_tree = ShortTree() GAME_BOARD.register(short_tree) GAME_BOARD.set_el(pos[0], pos[1], short_tree) short_trees.append(short_tree) for short_tree in short_trees: print short_tree short_trees[-1].SOLID = False short_trees[-2].SOLID = False # TALL TREES tall_tree_positions = [ (3, 6), (4, 6), (1, 8), (4, 8), (3, 9), ] tall_trees = [] for pos in tall_tree_positions: tall_tree = TallTree() GAME_BOARD.register(tall_tree) GAME_BOARD.set_el(pos[0], pos[1], tall_tree) tall_trees.append(tall_tree) # SPECIAL TALL TREE special_tall_tree = SpecialTallTree() GAME_BOARD.register(special_tall_tree) GAME_BOARD.set_el(5, 6, special_tall_tree) # UGLY TREE ugly_tree = UglyTree() GAME_BOARD.register(ugly_tree) GAME_BOARD.set_el(0, 6, ugly_tree) # STONE BLOCKS stone_positions = [ (9, 0), (7, 1), (7, 2), (9, 1), (9, 2), (8, 2), (7, 0), (8, 0), ] stones = [] for pos in stone_positions: stone_wall = Stone() GAME_BOARD.register(stone_wall) GAME_BOARD.set_el(pos[0], pos[1], stone_wall) stones.append(stone_wall) for stone_wall in stones: print stone_wall # WATER BLOCKS water_positions = [ (0, 5), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), (7, 5), (8, 5), (9, 5) ] water_blocks = [] for pos in water_positions: water = Water() GAME_BOARD.register(water) GAME_BOARD.set_el(pos[0], pos[1], water) water_blocks.append(water) for water in water_blocks: print water # BOY boy = Boy() GAME_BOARD.register(boy) GAME_BOARD.set_el(8, 1, boy) # HELPER GIRL girl = Girl() GAME_BOARD.register(girl) GAME_BOARD.set_el(2, 8, girl) # Ava Enemy ava = Ava() GAME_BOARD.register(ava) GAME_BOARD.set_el(2, 2, ava) def keyboard_handler(): direction = None if KEYBOARD[key.UP]: direction = "up" if KEYBOARD[key.DOWN]: direction = "down" if KEYBOARD[key.LEFT]: direction = "left" if KEYBOARD[key.RIGHT]: direction = "right" if direction: next_location = PLAYER.next_pos(direction) next_x = next_location[0] next_y = next_location[1] if (-1 < next_x < GAME_WIDTH) and (-1 < next_y < GAME_HEIGHT): existing_el = GAME_BOARD.get_el(next_x, next_y) if existing_el: existing_el.interact(PLAYER) if existing_el is None or not existing_el.SOLID: GAME_BOARD.del_el(PLAYER.x, PLAYER.y) GAME_BOARD.set_el(next_x, next_y, PLAYER)
f318ff53769a1436fc283e91aa95dc6d8958282a
JoseCarlosNF/Uri.Python
/aula8_Exercicio2.py
226
4.0625
4
# -*- coding: utf-8 -*- # Aula 8 - Exercicio 2 def multi(n1, n2): if n1 == 0: return 0 else: return multi(n1-1, n2) + n2 # Main x = int(input('Num1: ')) y = int(input('Num2: ')) print(multi(x, y))
37f807dab3bee9c6d123bd162b48abc26829232c
osvaldoc/misiontic
/semana3/misFunciones.py
653
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 4 19:17:03 2021 @author: Osvaldo """ import math import random def esPrimo (n): if n % 2 == 0: #Si un numero es par, no es primo return False i = 3 while i <= math.sqrt(n): if n % i == 0: return False i = i + 2 return True def comienzaCon(x): pd = x while pd > 9: pd = pd // 10 return pd def mcd (x,y): res = x % y while res != 0: x = y y = res res = x % y return y #Funcion puede llamar a otra funcion o a ella misma #funciona llama a si misma se llama RECURSIVIDAD def mcm (x, y): return x * y // mcd (x,y)
ead80ae6e5f8d6ae14e000d1410c42d01ab38aff
Ifeanyi30/Tutor_project
/payroll.py
879
3.5
4
class Payroll(object): def __init__(self, name, idNumber, hourlyRate, hoursWorked, grossPay): self.name = name self.idNumber = idNumber self.hourlyRate = hourlyRate self.hoursWorked = hoursWorked self.grossPay = grossPay def getName(self): return self.name def getIdNumber(self): return self.idNumber def getHourlyRate(self): return self.hourlyRate def getHoursWorked(self): return self.hoursWorked def getGrossPay(self): return self.hoursWorked * self.hourlyRate def setName(self, nameGiven): self.name = nameGiven def setIdNumber(self, idNumberGiven): self.idNumber = idNumberGiven def setHourlyRate(self, rateGiven): self.hourlyRate = rateGiven def setHoursWorked(self, hoursGiven): self.hoursWorked = hoursGiven
8f8c0ce000bb4dac569252b7d13d15108c0f8979
GauravAmarnani/Python-Basics
/com/college/viva/exp14.py
510
4.0625
4
# WAP to Create a List, Add Elements into List and find the Sum of all Elements inside the List. listName = [] # Creating List. listName.extend([1, 2, 3]) # Adding Element using extend(). listName.insert(1, 1.1) # Adding Element using insert(). listName.insert(2, 1.2) listName.append(4) # Adding Element using append(). print("The Sum of All Elements inside List ", listName, " is ", sum(listName)) # Sum of all Elements using sum(). # Performed by Gaurav Amarnani, Roll No. 21, CO6IA.
5abf240423abe02287acf63e977fb92b4e63316a
likes2addfunctions/CodeSamples
/Math/On_NDim_ChessBoard_VarLen.py
2,928
4.03125
4
#start 11:12 ## This program computes the average number of moves it would take a rook ## to move off of an n-dimesional chess board. Each move is still two dimensional ## with the dimensions chosen at random. import random import matplotlib.pyplot as plt def run_trial(n): ## set random initial coords coords = [] for j in range(board_dim): coords.append(random.randrange(side_len)) for k in range(n): ## select dimesions in which to move xdim = random.randrange(board_dim) ydim = random.randrange(board_dim) while xdim == ydim: ydim = random.randrange(board_dim) ## xpm, ypm control the direction of movement in xdim, ydim. xpm = 1 ypm = 1 ## set values for random move xlen = 1 ylen = 2 if random.random() > .5: xlen = 2 ylen = 1 if random.random() > .5: xpm = -1 if random.random() > .5: ypm = -1 ##update coordinates new_x = coords[xdim] + xlen*xpm new_y = coords[ydim] + ylen*ypm coords = coords[:xdim] + [new_x] + coords[xdim+1:] coords = coords[:ydim] + [new_y] + coords[ydim+1:] #print(coords) ## check in on board, if off return number of moves if max(coords) > side_len -1 or min(coords) < 0: #print (max(coords), min(coords), max(coords) > 7, min(coords) < 0) #print ("") #print ("") return k+1 ## if on board at end return -1 #print ("") #print ("") return -1 ## run m trials and compute proportion of trials on after n moves. def run_trials_for_n(n): results =[] for k in range(m): results.append(run_trial(n)) return results.count(-1)/float(len(results)) ## run trials for a range of integers from 0 to M def run_trials(): probs = [1] ratios = [1] for n in range(M+1): probs.append(run_trials_for_n(n)) ratios.append(probs[n+1]/probs[n]) print ("The expectations of a rook moving in two dimensions not falling off a chessboard") print ("board dimension:", board_dim) print ("side length:", side_len) for n in range(M): print ("Turns:", n, " ", "expectation:", probs[n+1]) rsum = 0 for ratio in ratios[2:]: rsum += ratio ravg = rsum/len(ratios[2:]) print ("this is well approximated by: f(n) =", ratios[2], "*(", ravg, ")^n") fig = plt.figure() plt.plot(probs[1:]) fig.savefig("probs.png") ## M is max integer to be tested M = 15 ## m is number of trials per integer m = 10000 ##board_dim is number of dimensions of board board_dim = 2 + random.randrange(98) ## dim_len is length (number of squares) of each dimension. For a standard ## Chessboard dim_len = 8 side_len = 8 + random.randrange(92) run_trials()
b4046c13aef00a100553463a8cbcce1ada22bfa3
Muttakee31/solved-interview-problems
/leetcode/492.construct-rectange.py
336
3.6875
4
import math class Solution: def constructRectangle(self, area: int) -> List[int]: """ https://leetcode.com/problems/construct-the-rectangle/ """ root = math.floor(math.sqrt(area)) while(root>0): if area % root == 0: return [area//root, root] root -= 1
0471f77af8310764e6dbea2481cdbdf713b97a77
johnhuzhy/MyPythonExam
/src/senior/func_decorator.py
998
3.546875
4
# Decorator デコレーター import time def print_time(): print(time.time()) def f1(): print('this is f1!') # print_time() # f1() # ① def pre_f1(func): print_time() func() # ② def decorator(func): def wrapper(): print_time() func() return wrapper # ③ @decorator def f3(): print('this is f3!') # ④ def decoratorx(func): def wrapper(*args, **kw): print_time() func(*args, **kw) return wrapper @decoratorx def fun1(name): print('this is', name) @decoratorx def fun2(name1, name2): print('this is', name1) print('this is', name2) @decoratorx def fun3(name1, name2, **kw): print('this is', name1) print('this is', name2) print(kw) if __name__ == "__main__": # # ① # pre_f1(f1) # # ② # f2 = decorator(f1) # f2() # # ③ # f3() # ④ fun1('Chromium') fun2('Manganum', 'Ferrum') fun3('Cobaltum', 'Niccolum', Co=27, Ni=29, ego='latina')
ac15ec2f8468b960716c043eb614a6adc12baa87
yunnyisgood/Tensorflow
/keras1/keras16_summary.py
884
3.609375
4
import numpy as np # 1. data x = np.array([range(100), range(301, 401), range(1, 101), range(100), range(401, 501)]) x = np.transpose(x) # (100, 5) print(x.shape) y= np.array([range(711, 811), range(101, 201)]) y = np.transpose(y) print(y.shape) # 2. modeling from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Dense, Input # 2) 함수형 모델 input1 = Input(shape=(5, )) dense1 = Dense(3)(input1) # 상위 레이어를 뒤에 명시해준다 dense2 = Dense(4)(dense1) dense3 = Dense(10)(dense2) output1 = Dense(2)(dense3) model = Model(inputs=input1, outputs=output1) model.summary() # 1) Sequential Model(순차적 모델) # model = Sequential() # model.add(Dense(3, input_shape = (5, ))) # model.add(Dense(4)) # model.add(Dense(10)) # model.add(Dense(2)) # model.summary() # 3. compile # model.compile() # 4 evaluate
c38f3a31f608a71326f31742bf43bc0e57f6a079
dikoko/practice
/1 Numerics/1-04_fibo_gen.py
460
3.953125
4
# 1-04. Fibonacci Generator # Given N, find all fibonacci numbers equal or less than N def fibo_gen(N): if N < 0: return [] def _gen_fibo(n): prev_prev = 0 prev = 1 fibo = 1 while fibo <= n: yield fibo prev_prev = prev prev = fibo fibo = prev + prev_prev return [f for f in _gen_fibo(N)] if __name__ == '__main__': N = 100 print(fibo_gen(N))
42392314fd745cf01d5d54d67ce30f9e57fb3d1a
ethanbyeon/scripted
/imago.py
1,786
3.671875
4
from PIL import Image # ASCII characters used by level of intensity for the output text ASCII_CHARS = ['$', '@', 'B', '%', '8', '&', 'W', 'M', '#', '*', 'o', 'a', 'h', 'k', 'b', 'd', 'p', 'q', 'w', 'm', 'Z', 'O', '0', 'Q', 'L', 'C', 'J', 'U', 'Y', 'X', 'z', 'c', 'v', 'u', 'n', 'x', 'r', 'j', 'f', 't', '/', '\\', '|', '(', ')', '1', '{', '}', '[', ']', '?', '-', '_', '+', '~', '<', '>', 'i', '!', 'l', 'I', ';', ':', ',', '"', '^', '`', '.'] # scale image based on the new width def resize_image(image, new_width=100): width, height = image.size ratio = height / width new_height = int(new_width * ratio) resized_image = image.resize((new_width, new_height)) return(resized_image) # convert each pixel through grayscale process def grayify(image): grayscale_image = image.convert("L") return(grayscale_image) # convert pixels to a string of ASCII characters def pixels_to_ascii(image): pixels = image.getdata() characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels]) return(characters) def main(new_width=100): # access an image from user-input path = input("Please enter a valid path name to an image:\n") try: img = Image.open(path) except: print(path, "is not a valid path name to an image.") return # convert image to ASCII new_image_data = pixels_to_ascii(grayify(resize_image(img))) # format the image pixel_count = len(new_image_data) ascii_image = "\n".join([new_image_data[index:(index + new_width)] for index in range(0, pixel_count, new_width)]) # print result # print(ascii_image) # save the image to a .txt file with open("ascci_image.txt", "w") as f: f.write(ascii_image) main()
f69a7ca0da9bc7199d779e3e7aefc4e26fc3da96
ankitomss/python_practice
/trie.py
846
3.859375
4
class TrieNode(object): def __init__(self, s=None): self.child = [None for _ in range(26)] self.val = s class Trie(object): def __init__(self): self.head = TrieNode() def add(self, s): tmp = self.head for i in range(len(s)): idx = ord(s[i]) - ord('a') if tmp.child[idx]: tmp = tmp.child[idx] else: tmp.child[idx] = TrieNode(s[:i+1]) tmp = tmp.child[idx] def search(self, s): tmp = self.head for i in range(len(s)): idx = ord(s[i]) - ord('a') if tmp.child[idx]: tmp = tmp.child[idx] if tmp.val == s: return True else: return False t = Trie() t.add("ankit") t.add("ankitv") print t.search("ankitm")
0d9d9b3c2e8f6ae2b3377a09c763faff683c5ba0
obsc/flight-planner
/util/mergefile.py
4,007
3.515625
4
import tempfile import argparse ''' compare function for lines, converts first two components of line to an int that is well ordered (sorts by flight IDs and ordinals) ''' def sorter(line): stuff = line.split(' ') return int(stuff[0]) * 1000 + int(stuff[1]) asdiposition = lambda x: int(x.split(',')[7]) asdiflightplan = lambda x: int(x.split(',')[2]) flighthistory = lambda x:int(x.split(',')[0]) vectors = lambda x: hash(x.split(',')[8]) comp = vectors timesMerged = [0] timesMergedUp = [0] def filesort(infile, outfile, chunkSize, mergeSize): files = [[]] print 'filesort' with open(infile) as f: f.readline() #first line just names columns reachedEnd = False while not reachedEnd: acc = f.readlines(chunkSize) if len(acc) == 0: reachedEnd = True else: acc.sort(key = comp) temp = (tempfile.TemporaryFile()).file temp.writelines(acc) temp.flush() files[0].append(temp) mergeUp(files, mergeSize) g = open(outfile, 'w') merge([elt for sl in files for elt in sl], g) #flatten, then final merge g.close() print(str(timesMerged[0])) print(str(timesMergedUp[0])) ''' merges all the files in 'files' and then puts their result in outfile closes each file in files, so temp files get deleted ''' def merge(files, outfile): timesMerged[0] += 1 acc = [] #initially holds the head of each file for f in files: f.seek(0) acc.append(f.readline()) 'return the minimum of the head positions of all files' def getMin(): minElt = None minVal = float('inf') minIndex = -1 for i in range(0, len(acc)): if acc[i] != "": #make sure end of file not reached curVal = comp(acc[i]) if curVal < minVal: minVal = curVal minElt = acc[i] minIndex = i else: pass else: pass #end of file acc[minIndex] = files[minIndex].readline() #replace the head of the file return minElt newf = outfile newline = getMin() while newline != None: newf.write(newline) newline = getMin() for f in files: f.close() def merge2(file1, file2, outfile): file1.seek(0) file2.seek(0) head1 = file1.readline() head2 = file2.readline() while head1 != "" and head2 != "": if comp(head1) < comp(head2): outfile.write(head1) head1 = file1.readline() else: outfile.write(head2) head2 = file2.readline() while head1 != "": outfile.write(head1) head1 = file1.readline() while head2 != "": outfile.write(head2) head2 = file2.readline() file1.close() file2.close() ''' merges all files up to maintain the invariant below uses in a sense, the base [mergeSize] number representation, in such that each filesList[i] has len no more than mergeSize, and len(filesList[i][j]) = mergeSize * len(filesList[i][j-1]) ''' def mergeUp(filesList, mergeSize): timesMergedUp[0] += 1 for i in range(0, len(filesList)): if len(filesList[i]) >= mergeSize: newf = tempfile.TemporaryFile().file merge(filesList[i], newf) filesList[i] = [] if i < len(filesList) - 1: filesList[i+1].append(newf) else: filesList.append([newf]) return if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'sort large files') parser.add_argument('infile') parser.add_argument('outfile') parser.add_argument('chunkSize', type = int) parser.add_argument('mergeSize', type = int) args = parser.parse_args() filesort(args.infile, args.outfile, args.chunkSize, args.mergeSize)
d3719a75a8ff8781cbe827308347eb8334b8d6f1
kblicharski/python-scripts
/misc_sec_scripts/divider.py
812
3.59375
4
import time times = [] for z in range(100): start = time.time() [print(i,'Y') if i and not (i&(i-1)) else print(i,'N') for i in range(1000000)] end = time.time() times.append(end - start) total = 0 for val in times: total += val algo_one = total/len(times) print(str(algo_one) + ' seconds') times = [] for j in range(100): start = time.time() for n in range(1000000): k = n while k%2 == 0 and k!=0: k = k/2 if k==1: print(n, 'Y') else: print(n, 'N') end = time.time() times.append(end - start) total = 0 for val in times: total += val algo_two = total/len(times) print(str(algo_two) + 'seconds') print('The linear algorithm is ' + str(algo_two/algo_one) + ' times faster than the original one')
6cbbcdef1cfe7ebcf8d480a19ddb3a5f62637661
samatachai/SoftwareLAB
/Python/ch01-01.py
115
3.84375
4
height = int(input('Enter height: ')) base = int(input('Enter base: ')) print('Answer is ',0.5*height*base)
51aab730071fc8ef1699b193a29174f12aeedff0
negative0101/Python-Advanced
/exam-prep/02.Minesweeper Generator.py
2,752
3.625
4
def create_blank_matrix(n): m = [] for _ in range(n): m.append([]) for _ in range(n): m[-1].append(0) return m def same_row_left(row, col, matrix): if 0 <= col - 1 < len(matrix): if matrix[row][col - 1] == '*': matrix[row][col] += 1 return matrix def same_row_right(row, col, matrix): if 0 <= col + 1 < len(matrix): if matrix[row][col + 1] == '*': matrix[row][col] += 1 return matrix def above_same_row(row, col, matrix): if 0 <= row - 1 < len(matrix): # one above if matrix[row - 1][col] == '*': matrix[row][col] += 1 return matrix def above_one_right(row, col, matrix): if 0 <= col + 1 < len(matrix) and 0 <= row - 1 < len(matrix): # one above and right if matrix[row - 1][col + 1] == '*': matrix[row][col] += 1 return matrix def above_one_left(row, col, matrix): if 0 <= col - 1 < len(matrix) and 0 <= row - 1 < len(matrix): # one above and left if matrix[row - 1][col - 1] == '*': matrix[row][col] += 1 return matrix def below_same_row(row, col, matrix): if 0 <= row + 1 < len(matrix): # one below if matrix[row + 1][col] == '*': matrix[row][col] += 1 return matrix def below_one_left(row, col, matrix): if 0 <= col - 1 < len(matrix) and 0 <= row + 1 < len(matrix): if matrix[row + 1][col - 1] == '*': # left matrix[row][col] += 1 return matrix def below_one_right(row, col, matrix): if 0 <= col + 1 < len(matrix) and 0 <= row + 1 < len(matrix): # right if matrix[row + 1][col + 1] == '*': matrix[row][col] += 1 return matrix num = int(input()) bombs = int(input()) matrix = create_blank_matrix(num) for i in range(bombs): bomb_row_and_column = input() bombs_row = int(bomb_row_and_column[1]) bombs_column = int(bomb_row_and_column[4]) if 0 <= bombs_row < len(matrix) and 0 <= bombs_column < len(matrix): matrix[bombs_row][bombs_column] = '*' # -> bomb is planted for row in range(num): for col in range(num): if matrix[row][col] != '*': same_row_left(row, col, matrix) same_row_right(row, col, matrix) above_same_row(row, col, matrix) above_one_right(row, col, matrix) above_one_left(row, col, matrix) below_same_row(row, col, matrix) below_one_left(row, col, matrix) below_one_right(row, col, matrix) for x in range(num): for y in range(num): print(matrix[x][y], end=' ') print()
16c35c82daa5992b2ff8e1fdd31e6e0bb3a84fc3
Vimlesh073/mynewrepository
/Python 24th Jan/nestedLoop.py
341
3.6875
4
''' 123 123 123 123 ''' ''' r = 1 c =1 c =2 c = 3 ------ r =2 c=1 c=2 c=3 ----- r =3 c=1 c=2 c=3 ---- r =4 c=1 c=2 c=3 ''' #nested loop for r in range(1,5): # for row / height #4 times for c in range(1,4): # for col/ width #..4 *3 print(c,end='') print()
4fc1ad6cc8236e0a77364b0e74e15581340f1785
jadilson12/studied
/python/45 - GAME Pedra Papel e Tesoura.py
1,188
3.90625
4
# Ano 2018 # exercício realizado durante o curso # @jadilson12 from random import randint from time import sleep itens = ('Pedra','Papel','Tesoura') pc =randint(0,2) print('''Suas opção [ 0 ] - Pedra [ 1 ] - Papel [ 2 ] - Tesoura''') jogador = int(input('Qual é sua jogada: ')) print('JO') sleep(1) print('KEN') sleep(1) print('PO !!!') sleep(1) print('='*25) print('O pc jogou {}'.format(itens[pc])) print('O jogador {}'.format(itens[jogador])) print('='*25) if pc == 0: #PC jogou pedra if jogador == 0: print('EMPATE') elif jogador == 1: print('JOGADOR GANHOU') elif jogador == 2: print('PC GANHOU') else: print('JOGADA INVALIDA') elif pc == 1:#PC jogou Papel if jogador == 0: print('PC GANHOU') elif jogador == 1: print('EMPATE') elif jogador == 2: print('JOGADOR GANHOU') else: print('JOGADA INVALIDA') elif pc == 2:#PC jogou Tesoura if jogador == 0: print('JOGADOR GANHOU') elif jogador == 1: print('PC GANHOU') elif jogador == 2: print('EMPATE') else: print('JOGADA INVALIDA')
c56c67276c77f33d483cf08643630a0ec0be6ec4
peterrenshaw/thisnote
/hours.py
218
3.6875
4
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ import time import datetime HHMM = "%H%M" # what is the time LOCALTIME now? today = datetime.date.today() hhmm = today.strftime(HHMM) print("{}".format(hhmm)) # eof
3900d1aee64b30b0bd2e615cf16bad60c732fc83
helbertsandoval/trabajo06_sandoval_maira
/multiples1.py
1,046
3.90625
4
import os #CALCULAR EL AREA DEL TRIANGULO #DECLARARCION DE VARIABLES area,base,altura=0.0,0.0,0.0 #INPUT base=float(os.sys.argv[1]) altura=float(os.sys.argv[2]) # PROCESSING area=(base*altura)/2 #VERIFICADOR area_total1=(area>200) area_total2=(150<=area<200) area_total3=(50<=area<90) # OUTPUT print("##############################################") print("# CALCULAR EL AREA DEL TRIANGULO") print("##############################################") print("#") print("# base : ", base) print("# altura : ", altura) print("# area total1 : ", area_total1) print("# area total2 : ", area_total2) print("# area total3 : ", area_total3) print("##############################################") #CONDICIONALES MULTIPLES: if (area_total1): print("si el area es mayor que 200 es aceptable") if (area_total2): print("si al area es menor que 200 no es aceptable") if (area_total3): print("el area es mayor o igual 50 pero menor que 90 ") #fin_if
bf3dd29f5c3624a773d1d70815eb4096f69445bf
MaskedDevil/All_programs
/Python/demo.py
1,319
4.40625
4
# # Print a patient's data # patientName = 'John Smith' # age = 20 # status = 'new' # print(patientName, age, status) # # Take an input and print # name = input('What is your name? ') # print('Hello', name) # # Type Conversion Demo...int(), float(), bool(), str() # birthYear = input('What is your birth year? ') # age = 2021 - int(birthYear) # print(age) # # Sum of Two Numbers # num1 = input('First: ') # num2 = input('Second: ') # sum = float(num1) + float(num2) # print(sum) # # String Props...<Strings are immutable> # course = 'Python for beginners' # print(course.upper()) # print(course.find('o')) # print(course.replace('for', '4')) # print('Python' in course) # print(course) # # Arithmetic Operations...'/' division returns floating point '//' division returns integer # print(10 + 3, 10 - 3, 10 * 3, 10 / 3, 10 // 3, 10 % 3, 10 ** 3) # # Comparison Operators[not demonstrated], Logical Operators # price = 25 # print(price > 20 and price < 30) # print(price < 20 or price < 30) # print(not price > 20) # # If-else if-else block # temperature = 25 # if temperature > 30: # print("It's a hot day") # print("Drink plenty of water") # elif temperature > 20: # print("It's a nice day") # elif temperature > 10: # print("It's a bit cold") # else: # print("It's a cold day") # print('Done')
918f659cbc6f4ce0b2c2587f73ebc1bb53f0f218
ErhardMenker/MOOC_Stuff
/Python4Everybody/chap_10_hw.py
1,530
4.15625
4
fname = input("Input file name: ") fhandle = open(fname) #create file handle d = dict() #initialize an empty dictionary for iterated_line in fhandle: line = iterated_line #rename iterated line to avoid computing errors if line.startswith("From "): line = line.split() #split the iterated line into a list of space-delimited words word = line[5] #extract the hour-minute-second text word = word.split(":") #split the hour, minute, second apart using a colon delimiter hour = word[0] #extract the hour from the above text d[hour] = d.get(hour, 0) + 1 print(d) #print the completed dictionary for a given file. Produces 'hour-count' 'key-value' pairs #sort from smallest to largest key (by hour): d = d.items() #convert dictionary into a list of key-value pair tuples. d.sort() #sorts and prints from smallest to largest key print("sort from smallest to largest value of the key (hour):") for key, value in d: print key, value #sort from smallest to largest key (by count): t = list() #initiate empty list to append value-key pairs onto. for key, value in d: #for a key-value pair in the dictionary... t.append((value, key)) #...append as a value-key pair to allow alphabetical sorting by value, primarily t.sort() #sort each tuple element in the list by the value (count), only sorting by the hour if the value for multiple key-value pairs is tied. print("sort from smallest to largest value of the value (count):") for value, key in t: print value, key
a6b2e12ba868f747e4457ef9a4c2beca86e76d68
dchu07/MIS3640
/Session09/word.py
5,174
3.875
4
# fin = open("session09/words.txt") # line = fin.readline() # word = line.strip() # print(word) # for line in fin: # word = line.strip() # print(word) def find_long_words(): """ prints only the words with more than 20 characters """ f = open("Session09/words.txt") for line in f: word = line.strip() if len(word) > 20: print(word, len(word)) # find_long_words() def has_no_e(word): """ returns True if the given word doesn’t have the letter "e" in it """ for letter in word: if letter.lower() == "e": return False return True # print(has_no_e('Babson')) # print(has_no_e('College')) # print(has_no_e('EA')) def find_words_no_e(): """ returns the percentage of the words that don't have the letter "e" """ f = open("Session09/words.txt") count = 0 num_of_words = 0 for line in f: num_of_words += 1 word = line.strip() if has_no_e(word): count += 1 return count/num_of_words # print('The percentage of the words with no "e" is {:.2f}%.'.format(find_words_no_e()*100)) def avoids(word, forbidden): """ returns True if the given word does not use any of the forbidden letters """ for letter in word: if letter in forbidden: return False return True # print(avoids('Babson', 'abcde')) # print(avoids('College', 'e')) def find_words_no_vowels(): """ returns the percentage of the words that don't vowel letters """ f = open("Session09/words.txt") num_of_words_with_no_vowel = 0 num_of_word = 0 for line in f: num_of_word += 1 word = line.strip() if avoids(word, "aeiou"): num_of_words_with_no_vowel +=1 return num_of_words_with_no_vowel/num_of_word # print('The percentage of the words with vowel letters is {:.2f}%.'.format(find_words_no_vowels()*100)) def uses_only(word, available): """ takes a word and a string of letters, and that returns True if the word contains only letters in the list. """ for letter in word: if letter not in available: return False return True # print(uses_only('Babson', 'aBbsonxyz')) # print(uses_only('college', 'aBbsonxyz')) def find_words_only_use_planet(): f = open("Session09/words.txt") num_of_words_only_use_planet = 0 for line in f: word = line.strip() if uses_only(word,"planet"): num_of_words_only_use_planet += 1 return num_of_words_only_use_planet # print('Number of words that use letters from "planet" is', find_words_only_use_planet()) def uses_all(word, required): """ takes a word and a string of required letters, and that returns True if the word uses all the required letters at least once. """ for letter in required: if letter not in word: return False return True # print(uses_all('Babson', 'abs')) # print(uses_all('college', 'abs')) # print(uses_all('Babson', 'aeoiu')) # print(uses_all('Babesonious', 'aeoiu')) def find_words_using_all_vowels(): """ return the number of the words that use all the vowel letters """ f = open("Session09/words.txt") count_num_of_word_with_vowels = 0 for line in f: word = line.strip() if uses_all(word, "aeiou"): count_num_of_word_with_vowels += 1 return count_num_of_word_with_vowels # print('The number of words that use all the vowels:', find_words_using_all_vowels()) def is_abecedarian(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ before = word[0] for letter in word: if letter < before: return False before = letter return True # print(is_abecedarian('abs')) # print(is_abecedarian('college')) def find_abecedarian_words(): """ returns the number of abecedarian words and the longest abecedarian word """ f = open("Session09/words.txt") count_words_in_order = 0 for line in f: word = line.strip() if is_abecedarian(word): count_words_in_order += 1 return count_words_in_order # print(find_abecedarian_words()) def is_abecedarian_using_recursion(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ if len(word) <= 1: return True if word[0] > word[1]: return False return is_abecedarian_using_recursion(word[1:]) # print(is_abecedarian_using_recursion('abs')) # print(is_abecedarian_using_recursion('apps')) # print(is_abecedarian_using_recursion('college')) def is_abecedarian_using_while(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ index = 0 while index < len(word)-1: if word[index + 1] < word[index]: return False index += 1 return True # print(is_abecedarian_using_while('abs')) # print(is_abecedarian_using_while('apps')) # print(is_abecedarian_using_while('college'))
c91b154bdd98e17bbc3f31bff608cca3821935d9
pedrillogdl/ejemplos_python
/DatosPersonales.py
402
3.8125
4
Nombre=input("Por favor, podrias proporcionar tu nombre: ") Direccion=input("Por favor, podrias proporcionar tu Direccion: ") Telefono=input("Por favor, podrias proporcionar tu Telefono: ") ListaGeneral=[Nombre, Direccion, Telefono] print("Los Datos Personsales Proporcionados son: ") print("Nombre: " + ListaGeneral[0]) print("Direccion: " + ListaGeneral[1]) print("Telefono: " + ListaGeneral[2])
af6e576eec5f54b915c4130a7f0d8ecb0e53695d
ziweiwu/MIT-introduction-in-computer-science
/week1/problem-2.py
139
3.703125
4
s= 'azcbobobegghakl' count=0 for i in range(len(s)-2): if s[i:i+3]=='bob': count=count+1 print(count)
e7ce31e7d75edfe38e9910edef9baf7465cc7caf
hwrdyen/python_lab3
/LAB 3/Lab_3_5.py
750
3.5
4
def rgb_to_grayscale(rgb_image_array): vector = [] row_number = len(rgb_image_array) for i in range(0,row_number): vector.append([]) for j in range(0,row_number): vector[i].append([]) for k in range(0,3): if k == 0: q = 0.2989*(rgb_image_array[i][j][k]) elif k == 1: w = 0.5870*(rgb_image_array[i][j][k]) elif k == 2: r = 0.1140*(rgb_image_array[i][j][k]) vector[i][j] = q+w+r return vector if __name__ == "__main__": image_array1 = [[[1,0,0],[0,0,0],[0,0,1]],[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[1,0,0]]] print(rgb_to_grayscale(image_array1))
a4411149762415264fe47480cbcd988a8705414d
loftina/LexicalAnalyzer
/front.py
1,335
3.546875
4
def main(): file = open('front.in', 'r') for line in file: current_line = unicode(line) index = 0 while (index < len(current_line)): if current_line[index].isalpha(): current_ident = current_line[index] index = index + 1 while (current_line[index].isalpha() or current_line[index].isnumeric()): current_ident = current_ident + current_line[index] index = index + 1 report('ident', current_ident) elif current_line[index].isnumeric(): current_ident = current_line[index] index = index + 1 while (current_line[index].isnumeric()): current_ident = current_ident + current_line[index] index = index + 1 report('int_lit', current_ident) else: if (current_line[index] != ' '): current_ident = current_line[index] report('unknown', current_ident) index = index + 1 def report(type, value): if type == 'ident': token = 11 if type == 'int_lit': token = 10 if type == 'unknown': if value == '=': token = 20 elif value == '+': token = 21 elif value == '-': token = 22 elif value == '*': token = 23 elif value == '/': token = 24 elif value == '(': token = 25 elif value == ')': token = 26 else: token = -1 print('Next Token is: {0}, Next lexeme is {1}'.format(token, value)) if __name__ == "__main__": main()
bf1d89c47aa147233fa5908f91b9c10b4c3b834d
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/pllker016/question1.py
156
3.828125
4
height=eval(input("Enter the height of the rectangle:\n")) j=eval(input("Enter the width of the rectangle:\n")) for i in range (height): print(j*"*")
24fc2a3e30153393b84ace414a3ffc59de64ed94
kendfss/misc
/2021/stacking/lottohelper_using_getopt.py
2,103
3.90625
4
""" https://stackoverflow.com/questions/66192897/develop-a-module-to-help-generate-lottery-tickets-in-python """ import random, getopt, sys def make_ticket(length, maximum): """ Generate a ticket of a given length using numbers from [1, maximum] return random.sample(range(1, maximum+1), length) would be the best way """ ticket = [] while len(ticket) < length: num = random.randint(1, maximum+1) if not num in ticket: ticket.append(num) return ticket def usage(): print("lottohelper.py [-h|--help] [-v|--verbose] <0/1> [-t|--type] <649/MAX> <integer>") def main(args): try: opts, args = getopt.getopt(args, "ht:v:", "help type= verbose=".split()) # students: complete this statement except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) # get optional arguments # this approach intentionally breaks if the user misses an option for k, v in opts: if k in '--help': usage() elif k in '--type': tp = { '649': (6, 49), 'MAX': (7, 50) }[v] # ternary operator elif k in '--verbose': ver = { '0': False, '1': True }[v] # ternary operator # get positional argument N = eval(args[0]) # causes an exception if anything other than an integer is given; a float will not be converted # do actual work here tickets = [make_ticket(*tp) for i in range(N)] # list comprehension if ver: print(f'Ticket Type:\t{649 if tp[0]==6 else "MAX"}') # format string for i, t in enumerate(tickets, 1): print(f'Ticket #{i}:\t{t}') #format string if __name__=='__main__': args = sys.argv[1:] args = '-v 1 --t 649 3'.split() main(args) args = '--verbose 1 --type MAX 3'.split() main(args)
39156137dba02055d19e279c62f4ba53e10a9961
mdugot42/N-puzzle
/neural_network/trainingDataReader.py
1,339
3.53125
4
import re def checkData(line, nl): if len(line) != 10: print("Error : line " + str(nl) + " : wrong size in training data input/output") exit() if len(line[0:9]) > len(set(line[0:9])): print("Error : line " + str(nl) + " : same value in training data input") exit() i = 1 result = [] for n in line: if n.isdigit() == False: print("Error : line " + str(nl) + ": not a digit in training data") exit() value = int(n) if i < 10 and (value < 0 or value > 9): print("Error : line " + str(nl) + " : wrong format in training data file") exit() i += 1 result.append(value) return result def readTrainingData(filename): try: file = open(filename, "r") except Exception: print("Error : can not read training data file") exit() result = [] file = file.read() file = set(file.split("\n")) #check des données lignes par lignes et enregistrement de la grille i = 1 for line in file: print("\r[ \033[36mPREPARE TRAINING DATA : " + str(i) + "/" + str(len(file)) + "\033[0m ] ", end="") if len(line) > 0: line = re.split("[,= ]+", line) line = checkData(line, i) data = (line[0:9], [line[-1]]) result.append(data) i += 1 print("\r[ \033[36m" + str(len(result)) + " TRAINING DATA READY" + "\033[0m ] ") return result #td = readTrainingData("training_data")
9d409ae0b127c2cdf2b4481e8a81bb953f6050c7
Aasthaengg/IBMdataset
/Python_codes/p03079/s624247118.py
478
3.5
4
from sys import stdin ## input functions for me def ria(sep = ''): if sep == '' : return list(map(int, input().split())) else: return list(map(int, input().split(sep))) def rsa(sep = ''): if sep == '' : return input().split() else: return input().split(sep) def ri(): return int(input()) def rd(): return float(input()) def rs(): return input() ## ## main ## A, B, C = map(int, input().split()) print("Yes" if (A == B and B == C) else "No")
ce2585850f8f61a8814d6be5d762c7885db6baeb
aubinaso/Python
/face_detection.py
926
3.6875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 1 22:49:27 2021 @author: aubin """ import cv2 as cv import numpy as np import matplotlib.pyplot as plt # detect if there is a face not whose face it is which is face recognition # https://github.com/opencv/opencv/tree/master/data/haarcascades img = cv.imread("test.png") cv.imshow("image", img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) cv.imshow("gray", gray) # read the xml file haar_cascade = cv.CascadeClassifier("haar_face.xml") # return the rectangle cornet of the face, minNeighbors and scaleFactor increase the detection of face # but more minNeighbors faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3) # print the number of faces found print("the number of face is ", len(faces_rect)) for (x,y,w,h) in faces_rect: cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2) cv.imshow("Detected Faces", img) cv.waitKey(0)
842f47ecad4f4598da4e5fad5200cd738991e323
archdr4g0n/CSC221
/BATCHELR m2t1 gold.py
4,575
4.125
4
##Tracy Batchelor ##M2T1- Guessing game ##18 Sep 2017 ##csc-221 import random def main(): print('Here are your choices ') print('1 = Find the number ') print('2 = Pick the number ') pick = input('Pick a game: ') if pick == '1': guess_game() elif pick == '2': computer_guess_game() # game 1 def guess_game(): print('I have picked a number from 1 to 100, it is your job to guess it.') answer = random_guess() guess = input('Pick a numeric integer. What is your guess? ') num_guess = 0 # print(answer) #used to check if math is correct while num_guess != 9: num_guess += 1 if guess != answer: if guess.isdigit(): guess = int(guess) elif guess.isalpha(): print('INVALID INPUT. PICK A NUMERIC INTEGER. (0-99)') guess = int(input('NEXT GUESS? ')) if guess < answer: print('The answer is higher!!') elif guess > answer: print('The answer is lower!!') else: print('Congratulations, you found the answer in', num_guess, 'guesses!!!') break guess = input('What is your guess? ').upper() if num_guess == 10: print('You have exeeded 10 guesses.') cont = input('AGAIN? (Y/N)').upper() if cont == 'N': print('THANK YOU FOR PLAYIING!!') else: main() # picks random number def random_guess(): answer = random.randint(1, 100) return answer # cyber compare def comp_compare(guess, choice): if guess < choice: print('Cyber: The answer is higher!!') elif guess > choice: print('Cyber: The answer is lower!!') else: print('Congratulations, you found the answer in', num_guess, 'guesses!!!') break # makes a bisectional guess def pick_number(lower,higher): guess = int((higher - lower) / 2) + lower print ('The computer picked ', guess) return guess #compares the guess to the answer def compare_answer(): # global guess decide = input('Should the computer guess higher or lower? (H/L)').upper() if decide == 'H': print('I will tell the compter to pick a higher number') var = 'lower' return var elif decide == 'L': print('I will tell the computer to pick a lower number') var = 'higher' return var else: print("Invalid choice. Please pick 'H' or 'L'") compare_answer() #game 2 def computer_guess_game(): lower = 1 higher = 100 answer = int(input('Pick a number from 1 to 100 ')) counter = 0 # if answer.isalpha(): # print('INVALID INPUT. PICK A NUMERIC INTEGER. (1 to 100)') # answer = int(input('Choose again? ')) guess = 0 while answer != guess: print ('The computer will try to guess it') counter += 1 if counter == 9: print("The computer didn't guess the number. You cheated") break guess = pick_number(lower, higher) if guess == answer: print('The computer has guessed the number in', counter,'guesses.') break compare = compare_answer(guess) if compare =='lower': lower = guess elif compare =='higher': higher = guess cont = input('AGAIN? (Y/N)').upper() if cont == 'N': print('THANK YOU FOR PLAYIING!!') else: main() # game 3 def comp_vs_cyber(): print('The computer will play a cyber opponent.') print('Cyber, choose your number') choice = random_guess() print('Cyber: I have chosen my number.') while choice != guess: print ('The computer will try to guess it') counter += 1 if counter == 9: print("The computer didn't guess the number. You cheated") break guess = pick_number(lower, higher) if guess == answer: print('The computer has guessed the number in', counter,'guesses.') break compare = compare_answer(guess) if compare =='lower': lower = guess elif compare =='higher': higher = guess cont = input('AGAIN? (Y/N)').upper() if cont == 'N': print('THANK YOU FOR PLAYIING!!') else: main() main()
4f177464928af4d078028eabf047bc6a720aa6c8
sloongz/Programm_Language
/Python/1.2_list_tuple_dict_set.py
1,715
3.8125
4
#!/usr/bin/env python str = "12345678abcdef" print str[3] print str[2:10:2] #sname[start:end:step] #list print "\n================list================" list1=[1,2,3,4,5, "hello", 2.3] print list1 print list1[2:4:1] del list1 list2=[1,2,3] list3=["one", "two", "three"] list4=list2+list3 print list4 list4.append("add1") print list4 list4.extend("add2") print list4 list4.extend(["add3"]) print list4 list4.insert(0,"insert") print list4 del list4[2] print list4 del list4[2:3] print list4 aa= list4.pop(2) print aa print list4 aa=list4.pop() print list4 list4.remove("three") print list4 list5=[1,2,3,4,5,6,7,8,9,'a'] print list5 list5[0] = 10 list5[-1] = 20 print list5 list5[1:3] = ["aa", "bb"] print list5 aa=list5.count(5) print aa if list5.count(5): print "index:",list5.index(5) else: print "not appear" #tuple print "\n================tuple================" tuple1=("aa", "bb", "cc", "dd") tuple2="ee","ff","gg","hh" print tuple1 print tuple2 tuple3=tuple(list5) print tuple3 print tuple3[2] print tuple3[2:4:1] del tuple3 #dict print "\n================dict================" list6=[["one",1],["two",2],["three",3],["four",4]] dict1=dict(list6) print dict1 print "key one vaule ",dict1["one"] print dict1.get("one") print dict1.get("five","not appear") dict1["five"]=5 print dict1 dict1["one"]="first" print dict1 del dict1["five"] print dict1 print "keys:",dict1.keys() print "values:",dict1.values() print "items:",dict1.items() #set print "\n================set================" set1= {1,2,3,'a','d'} print set1 set1=set([1,2,3,4,5]) print set1 set1.add(8) set1.add((7,8)) print set1 set1.remove(1) print set1 set2 = {1,2,3} print set1&set2 print set1|set2 print set1-set2 print set1^set2
be4b6f51d9f847d3c6af500cd471e7dc9ee08410
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/calculate_angle_between_clock_hands.py
796
4.1875
4
# Task: # # Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock. # # def calcAngle(h, m): # # Fill this in. # # print calcAngle(3, 30) # # 75 # print calcAngle(12, 30) # # 165 from math import floor def calculate_angle_between_clock_hands(hours: int, minutes: int) -> int: minutes_per_clock: int = 60 hours_per_clock: int = 12 angle_between_60_and_minute_hand: int = minutes * floor(360 / minutes_per_clock) angle_between_12_and_hour_hand: int = hours % hours_per_clock * floor(360 / hours_per_clock) angle_between_hours_and_hour_hand: int = floor(angle_between_60_and_minute_hand / hours_per_clock) return abs(angle_between_12_and_hour_hand + angle_between_hours_and_hour_hand - angle_between_60_and_minute_hand)
a19898b3ed6e42660dcf472446bb1391e685f26f
bpiggin/codewars-katas
/python/string_to_camel.py
273
4.15625
4
def to_camel_case(text): nextUpper = False newStr = "" for char in text: if (char == "-" or char == "_"): nextUpper = True continue if (nextUpper): newStr += char.upper() nextUpper = False else: newStr += char return newStr
8f1d22c3a11ed32ad379d19dec6ab126937b689f
Stevekerr3310/Python304
/ticTacToe.py
2,142
4.09375
4
import random def print_board(board): print("-----") print("{}|{}|{}".format(board[0], board[1], board[2])) print("-----") print("{}|{}|{}".format(board[3], board[4], board[5])) print("-----") print("{}|{}|{}".format(board[6], board[7], board[8])) print("-----") def is_win_or_lose(board, choice): if ( (board[0] == choice and board[1] == choice and board[2] == choice) or (board[3] == choice and board[4] == choice and board[5] == choice) or (board[6] == choice and board[7] == choice and board[8] == choice) or (board[0] == choice and board[3] == choice and board[6] == choice) or (board[1] == choice and board[4] == choice and board[7] == choice) or (board[2] == choice and board[5] == choice and board[8] == choice) or (board[0] == choice and board[4] == choice and board[8] == choice) or (board[2] == choice and board[4] == choice and board[6] == choice) ): return True else: return False board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] print("歡迎光臨井字遊戲!!!") print("請選擇 'O' 或 'X'") player_choice = input() if player_choice == "O": computer_choice = "X" else: computer_choice = "O" print("你選擇了",player_choice) print_board(board) while True: print("請選擇你的下一步:") step = int(input()) board[step -1] = player_choice print_board(board) count = 0 for i in range(0, len(board)): if board[i] != " ": count += 1 if count == 9: print("平手") print("結束此遊戲") break #判斷輸贏 if is_win_or_lose(board, player_choice): print("恭喜你贏了!") print("感謝你玩此遊戲!") break print("電腦出步了") computer_step = random.randint(1,9) while board[computer_step - 1] != " ": computer_step = random.randint(1,9) board[computer_step - 1] = computer_choice print_board(board) #判斷輸贏 if is_win_or_lose(board, computer_choice): print("電腦贏了!") break
ca65f9ab3a29ae0c2c08fca62af9559fe86187f2
abhinavjha126/Python
/PythonTuts/FOR.py
284
3.765625
4
"""list1=[["ABHI",1],["PRIYA",5],["APARNA",7],["RANJU",2]] dict1=dict(list1) print(dict1) #for a,b in dict1.items(): #print(a,b) for a in dict1: print(a)""" list1=["ABHI","2","**",9,56,86,678,"AB9","9ABHI","+",int,float] for a in list1: if str(a).isalnum(): print(a)
e5a0cc802f69dce6badca7182ba637527726c96a
WeiPromise/study
/day10_面向对象基础/08-私有属性的使用.py
817
3.765625
4
#!/usr/bin/env python3.5 # encoding: utf-8 # Created by leiwei on 2020/9/29 14:24 class Person(object): def __init__(self, name, age): self.name = name self.age = age self.__money = 1000 # 私有变量 def set_money(self, num): # 验证逻辑 self.__money = num def get_money(self): # 操作提醒 return self.__money p = Person('张三', 18) print(hex(id(p))) # 0x1e3601864e0 print(p.name) print(p.age) # 两个下划线开始的变量是私有变量,两个下划线开始的函数是私有函数,不能直接获取 # print(p.__money) # 获取方法: # 1、使用对象._类名__私有变量名获取 print(p._Person__money) # 2、定义get和set方法获取 p.set_money(10000) print(p.get_money()) # 3、使用property来获取
5dfe173ec115420d75ce9f273cef7f9de5469d5a
vincent507cpu/Comprehensive-Algorithm-Solution
/LeetCode/easy - Hash Table/599. Minimum Index Sum of Two Lists/solution.py
997
3.6875
4
class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: # concisest solution # https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/322322/2-lines-python dct = {x: list1.index(x) + list2.index(x) for x in set(list1) & set(list2)} return [key for key in dct.keys() if dct[key] == min(dct.values())] # fastest solution # https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/534789/Python3-148ms-94.77-Hashmap def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: dct1 = {res: i for i, res in enumerate(list1)} dct2 = {res: i + dct1[res] for i, res in enumerate(list2) if res in dct1} MIN = float('inf') res = [] for key, val in dct2.items(): if val < MIN: res = [key] MIN = val elif val == MIN: res.append(key) return res
518c83b2145517f42de25d6a4c3f9579572def90
jarrm5/python_progs
/comparisons.py
2,243
4.1875
4
def middle_value(a,b,c): #Return the middle value of 3 numbers #Assumes that a,b,c are distinct largest = a second_largest = b #switch the values if b is larger than a if(b > a): largest = b second_largest = a #Now compare the values of largest and second_largest with c if(c > largest): #here c is the largest and the previous value of large must be second_largest second_largest = largest else: #here c is in between largest and second_largest, so c is the value of second_largest if(c > second_largest): second_largest = c return second_largest def large1_large2(s,n): #Algorithm returns the largest and second_largest value in a sequence of n elements #input: s - an unsorted sequence of AT LEAST 2 values; n - the size of the sequence #output: largest & second_largest - the largest and second_largest value of the sequence largest = s[0] second_largest = s[1] #If s1 is greater, swap the values of largest and second_largest if(s[1] > s[0]): largest = s[1] second_largest = s[0] #Loop thru to the end of the sequence, comparing each value to large and second_largest for i in range(2,n): #Found a new large value-assign s[i] to largest, assign previous largest to second_largest if(s[i] > largest): temp = largest largest = s[i] second_largest = temp #s[i] is not largest, but could be second largest else: #If it is, assign s[i] to large if(s[i] > second_largest): second_largest = s[i] #Ran thru the entire sequence, return the two largest values return largest, second_largest def last_large_index(s,n): #Algorithm returns the index of last occurence of the largest value in a sequence of n elements #input: s - sequence of unsorted values of AT LEAST 1 value; n - the size of the sequence #output: largest_index - the index of the last occurrence of the largest value largest = s[0] largest_index = 0 for i in range(1,n): if(s[i] >= largest): largest = s[i] largest_index = i return largest_index
0724094d8db348e6c67fb7d65921de262b949e4d
davidnhuang/Learning-Python-For-Designers
/Week_5/Randomizing_Indexes.py
618
3.75
4
# David Huang # Computer Programming for Designers and Artists # Week 5 - Oct 11 2017 # ID 0239637 import random #Variables brady_bunch = ["Mike", "Carol", "Greg", "Jan", "Marsha", "Bobby", "Peter", "Cindy"] plots = ["was late", "was sick", "got in trouble", "won a contest", "sang a song", "had a date"] # generate plot lines # In order for code to work, the range must be the len(list)-1 since we are taking the indices. character = random.randint(0,len(brady_bunch)-1) # Same goes for this line, in which the range must be len(list)-1 plot = random.randint(0,len(plots)-1) print (brady_bunch[character],plots[plot])
9bc6b4f8540315636ef84eb6ddd6742978eb6279
chinskiy/LabsNumericalMethods
/lab2.py
2,880
3.609375
4
def print_matrix(matr): for _ in range(len(matr)): for j in range(len(matr[_])): print(format(matr[_][j], ',.4f'), end=' ') print() print() def find_main(matr, k): a_main = (matr[k][k], (0, 0)) for _ in range(len(matr)): for j in range(len(matr[_]) - 1): if a_main[0] < abs(matr[_][j]): a_main = (abs(matr[_][j]), (_, j)) if k != len(matr) - 1: temporl.append((k, a_main[1][1])) matr[k], matr[a_main[1][0]] = matr[a_main[1][0]], matr[k] for _ in range(len(matr)): matr[_][k], matr[_][a_main[1][1]] = matr[_][a_main[1][1]], matr[_][k] def find_m_fact(matr, k): m_factors = [] for _ in range(len(matr)): m_factors.append(matr[_][k] / matr[k][k]) return m_factors def substract_m_fact(matr, m_factors, k): for _ in range(len(matr)): for j in range(len(matr[_])): if _ > k: matr[_][j] -= m_factors[_] * matr[k][j] temp = matr[k][k] for _ in range(len(matr) + 1): matr[k][_] = matr[k][_] / temp + 0 return matr def find_converse(matr): matr.reverse() for _ in range(len(matr)): matr[_].reverse() answ = [] for _ in range(len(matr)): temp_answ = 0 for j in range(_ + 1): if j == 0: temp_answ = matr[_][0] else: temp_answ -= matr[_][j] * answ[j - 1] answ.append(temp_answ) return answ def find_solution_slar(matr): i = 0 while len(matr) > i: find_main(matr, i) print_matrix(matrix) substract_m_fact(matr, find_m_fact(matr, i), i) #print_matrix(matrix) i += 1 print_matrix(matrix) solut = find_converse(matr) for el in temporl: solut[el[1]], solut[el[0]] = solut[el[0]], solut[el[1]] return solut def find_vector_of_discrepancy(matr, answ): vect = [] for _ in range(len(matr)): tmp = 0 for j in range(len(matr[_]) - 1): tmp += matr[_][j] * answ[j] vect.append(tmp) answer = [] for _ in range(len(vect)): answer.append(matr[_][len(matr)] - vect[_]) for el in answer: print(format(el, ',.16f'), end=' ') if __name__ == "__main__": temporl = [] matrix = [[8.30, 2.62, 4.10, 1.90, -10.65], [3.92, 8.45, 8.78, 2.46, 12.21], [3.77, 7.21, 8.04, 2.28, 15.45], [2.21, 3.65, 1.69, 6.9, -8.35]] print_matrix(matrix) solution = find_solution_slar(matrix) for elem in solution: print(format(elem, ',.4f'), end=' ') print() matrix2 = [[8.30, 2.62, 4.10, 1.90, -10.65], [3.92, 8.45, 8.78, 2.46, 12.21], [3.77, 7.21, 8.04, 2.28, 15.45], [2.21, 3.65, 1.69, 6.9, -8.35]] find_vector_of_discrepancy(matrix2, solution)
cdfab7743c25ce0fd02df7248af7e470b1265801
poojagmahajan/Data_Analysis
/Data Analytics/Panda/Functions_in_Dataframe.py
1,074
4.75
5
# sum(axis=0) : This function calculates the sum of each column of a DataFrame. # sum(axis=1) : This function calculates the sum of each row of a DataFrame. # min(axis=0) : This function returns the minimum value from each column. # min(axis=1) : This function returns the minimum value from each row. # idxmin(axis=0) : This function returns the index with minimum value from every column. # idxmin(axis=1) : This function returns the column with minimum value from every index. import numpy as np import pandas as pd # Declaring DataFrame df = pd.DataFrame(np.arange(9).reshape(3,3), index=['A', 'B', 'C'], columns=['A', 'B', 'C']) print("The DataFrame") print(df) print("\nThe sum of each Column:") print(df.sum(axis=0)) print("\nThe sum of each Row:") print(df.sum(axis=1)) print("\nThe minimum from each Column:") print(df.min(axis=0)) print("\nThe minimum from each Row:") print(df.min(axis=1)) print("\nThe minimum value in each Column is at index:") print(df.idxmin(axis=0)) print("\nThe minimum value at each index is at Column:") print(df.idxmin(axis=1))
e4daf3264f17b89caab6c88f2d18b6961389afdf
brotherhuang/notebook_leetcode
/python/Number_of_Islands.py
1,821
3.6875
4
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 """ from collections import deque class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ res = 0 n = len(grid) if n == 0: return res m = len(grid[0]) visited = [[False] * m for x in range(n)] for i in range(n): for j in range(m): if grid[i][j] == '1' and visited[i][j] == False: res += 1 visited[i][j] = True q = deque([[i,j]]) while q: x,y = q.popleft() if x > 0 and grid[x-1][y] == '1' and visited[x - 1][ y] == False: visited[x - 1][ y] = True q.append([x-1,y]) if x + 1 < n and grid[x + 1][y] == '1' and visited[x + 1][ y] == False: visited[x + 1][ y] = True q.append([x + 1,y]) if y > 0 and grid[x][y - 1] == '1' and visited[x][ y - 1] == False: visited[x][ y - 1] = True q.append([x,y-1]) if y + 1 < m and grid[x][y+1] == '1' and visited[x][y + 1] == False: visited[x][ y + 1] = True q.append([x,y + 1]) return res
8ba6187cae94f255e601b6b71fee1d72ef4e4827
saikiranmaivemula1005/CSPP1Assignments
/M5/p4/square_root_newtonrapson.py
347
3.953125
4
"""kkk"""# Write a python program to find the square root of the number # using Newton-Rapson method def main(): """kk""" STEP_ = 0.01 Y_ = int(input()) GUESS_ = Y_/2.0 NOG_ = 0 while abs(GUESS_*GUESS_ - Y_) >= STEP_: NOG_ += 1 GUESS_ = GUESS_ - (((GUESS_**2) - Y_)/(2*GUESS_)) print(str(GUESS_)) if __name__ == "__main__": main()
7990ca2c7c90a8902974c58857353360eaddae6e
ssb2920/SEM-6
/ML/2. Least Square Method-Linear Regression/linear_regression.py
3,085
4.03125
4
# LINEAR REGRESSION # # y = b1 * x + b0 # # To find b0 and b1 there are 2 ways: # # 1. Karl's correlation coeff # 2. Least square method # # Steps (using Least Square Method): # 1. Find mean of X (x") # 2. Find mean of y (y") # 3. Find x - x" and y - y" # 4. Find (x - x") ** 2 # 5. Find b1 using formula # 6. Find b0 using formula # 7. Find y using regression formula import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression coeff = [] def createDataSet(X, y): df = pd.DataFrame({ "X" : X, "Y" : y }) return df def calculateXY(df): X_mean = df["X"].mean() df["X - X'"] = round(df["X"] - X_mean, 2) Y_mean = df["Y"].mean() df["Y - Y'"] = round(df["Y"] - Y_mean, 2) df["(X - X') * (Y - Y')"] = df["X - X'"] * df["Y - Y'"] return df def calculateXSquare(df): df["(X - X') ^ 2"] = df["X - X'"] ** 2 return df def calculatecoeff(x_val, df): xy_sum = df["(X - X') * (Y - Y')"].sum() xsquare_sum = df["(X - X') ^ 2"].sum() X_mean = df["X"].mean() Y_mean = df["Y"].mean() b1 = round(xy_sum / xsquare_sum, 2) b0 = round(Y_mean - b1 * X_mean, 2) coeff.append(b0) coeff.append(b1) print(coeff) print(x_val) y = round(coeff[0] + coeff[1] * x_val, 2) return y def scikitlearn_linear_reg(x_val, df): X = df["X"].values X = np.reshape(X, (-1, 1)) Y = df["Y"].values Y = np.reshape(Y, (-1, 1)) reg = LinearRegression().fit(X, Y) y = round(reg.predict(np.array([[x_val]])).flatten()[0], 2) return y if __name__ == "__main__": X = [] y = [] print("Enter dataset values for X: (Press q to quit)") while(True): n = input() if(n == 'q'): break else: X.append(int(n)) print("Enter dataset values for Y: (Press q to quit)") while(True): n = input() if(n == 'q'): break else: y.append(int(n)) df = createDataSet(X, y) x = int(input("Enter x value: ")) df = calculateXY(df) df = calculateXSquare(df) y_custom = calculatecoeff(x, df) y_scikit = scikitlearn_linear_reg(x, df) print("FINAL DATA:") print(df.head(6)) print(f"For x = {x}") print(f"By custom linear regression model: y = {y_custom}") print(f"By scikit-learn linear regression model: y = {y_scikit}") ########### OUTPUT ########### # Enter dataset values for X: (Press q to quit) # 0 # 1 # 2 # 3 # 4 # q # Enter dataset values for Y: (Press q to quit) # 2 # 3 # 5 # 4 # 6 # q # Enter x value: 10 # [2.2, 0.9] # 10 # FINAL DATA: # X Y X - X' Y - Y' (X - X') * (Y - Y') (X - X') ^ 2 # 0 0 2 -2.0 -2.0 4.0 4.0 # 1 1 3 -1.0 -1.0 1.0 1.0 # 2 2 5 0.0 1.0 0.0 0.0 # 3 3 4 1.0 0.0 0.0 1.0 # 4 4 6 2.0 2.0 4.0 4.0 # For x = 10 # By custom linear regression model: y = 11.2 # By scikit-learn linear regression model: y = 11.2
2832b66234fa5ab5e0bd48e369d40c2e0401a6e1
yuchun921/CodeWars_python
/8kyu/Find_numbers_which_are_divisible_by_given_number.py
174
3.78125
4
def divisible_by(numbers, divisor): arr = [] for i in range(0, len(numbers)): if numbers[i] % divisor == 0: arr.append(numbers[i]) return arr
c0a2ec6bfd2863a65fdd5e63a19d076c5b18c72f
littlejoe1216/Chapter-8-Exercises
/Chapter 8 Exercises/Python_8_1.py
422
4.0625
4
#Joe Gutierrez - 2/1/18 - Chapter 8 - Exercise 1 #Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. #Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements. a = ['a', 'b', 'c', 'd', 'e'] def chop(a): del a[0:] del a[4:] return a[1:b-1] print(a) print (chop)
c60e6ca4b8931d4ddde4d8ba79981cb989e4ed5b
emzatos/Random-Coding
/Pal.py
597
3.703125
4
size = int(input()) string = input() def check_pal(n): if n == n[::-1]: return False n = list(n) for i in range(len(n)//2): if n[i] == n[-i-1]: n[i] = "" n[-i-1] = "" else: pass n = "".join(n) if len(n) == 2 or len(n) == 3: return True else: return False count = 0 offset = 2 strs = [] while offset < size: for i in range(len(string)): if i+offset > len(string): break if check_pal(string[i:i+offset]) and string[i:i+offset] not in strs: strs.append(string[i:i+offset]) count+=1 else: pass offset+=1 if check_pal(string): count+=1 print(count)
27c7e6e9bc5eba6ac761b989204dda74dadd5555
gabrielwai/Exercicios-em-Python
/ex062.py
826
3.875
4
A1 = int(input('Digite o primeiro termo de uma PA: ')) r = int(input('Digite a razão dessa PA: ')) continuar = 1 cont = 1 total = 10 print('Os primeiros 10 termos dessa PA são: ') while cont != 11: print('A{} = '.format(cont), end='') print(A1 + (cont - 1) * r, end='') print(', ' if cont != 10 else '.\n', end='') cont += 1 while continuar != 0: continuar = int(input('Deseja continuar com mais quantos termos?: ')) if continuar != 0: total += continuar continuar += cont else: print('\nProgressão finalizada com {} termos mostrados.'.format(total)) while continuar > cont: print('A{} = '.format(cont), end='') print(A1 + (cont - 1) * r, end='') print(', ' if cont + 1 < continuar else '.\n', end='') cont += 1
255e13684231f6258958b6da62ff4a8548a13ac0
Olumuyiwa19/aws_restart
/Moisture_Estimator_Script.py
1,665
3.78125
4
#This code estimate the Yes = True while Yes: Grain_Type = str(input("Enter the type of your grain: ")) Wg = float(input("What is the weight of your grain? ")) MC_Wg = int(input("what is the moisture content of your wet grain? ")) MC_Dg = int(input("what is your desired final moisture content for the grain? ")) #Determine the standard measuring system in Bushel Initial_Bu = Wg / 56 print(f"The weight of your grain in Bushel is: {Initial_Bu:1.2f}") MC_Shrinkage_Dict = {16.0:1.190, 15.5:1.183, 15.0:1.176, 14.5:1.170, 14.0:1.163, 13.5:1.156, 13.0:1.149, 12.5:1.143, 12.0:1.136} #Determine mositure points which is same as moisture difference moisture_pt = MC_Wg - MC_Dg #Determine the percentage shrinkage and amount of shrinkage shrinkage_percent = moisture_pt * MC_Shrinkage_Dict[13.0] print(str(shrinkage_percent) + "%") shrinkage_decimal = shrinkage_percent / 100 #Determine the amount of shrinkages in the grain after drying shrinkage_Amt = Initial_Bu * shrinkage_decimal print("The amount of shrinkages in Bushel is: " + str(f"{shrinkage_Amt: 1.2f}")) #Determine the final weight of grain after drying Final_Bu = Initial_Bu - shrinkage_Amt print("The weight of your grain in Bushel after drying to 13% moisture content is: " + str(f"{Final_Bu: 1.2f}")) #Determine the final price of grain at $3.50/Bushel Final_Price = Final_Bu * 3.5 print("The price for your grain is: " + "$" + str(f"{Final_Price:1.2f}")) Yes = input("Do you want to carryout another grain moisture estimate? yes or no: ").lower() if Yes != "yes": print("Goodbye for now") quit
98170d5fe8f0a1f4d842c1dcc5d908abd5a2a9ee
Etyre/project_euler
/PE51.v2.py
2,718
3.671875
4
# PLAN: # 1. make_prime function # 2. All templates for number of length n. # (templates for 1: 0, 1. 2: 00, 01, 10, 11) # 3. loop through templates # loop through digits # and replace every digit coresponding to a 1 on the template with the digit. # check if the result is prime, if so, save. # count the number of savaed primes. import copy #from PE51.v1 def is_prime(number): # returns the number if it is prime for x in range(1, number): if x == number - 1: return True if x != 1 and number%x == 0: break # from PE41 def make_primes2(limit): if limit < 2: return [] primes = [2] for i in range(2, limit): for x in primes: # print primes if x != 1 and i%x == 0: break if x == primes[-1] and i%x != 0: primes.append(i) return primes def make_templates(n): if n <= 0: return [] else: templates = ["0", "1"] counter = 1 while counter < n: add_zeros = [] for elem in templates: add_zeros.append(elem + "0") add_ones = [] for elem in templates: add_ones.append(elem + "1") print templates templates = add_zeros + add_ones counter += 1 print " " return templates print make_templates(3) def find_prime_value_family (order_of_magnitude, required_family_size): limit_number = 10 ** order_of_magnitude list_of_primes = make_primes2(limit_number) number_of_digits = order_of_magnitude templates = make_templates(number_of_digits) for prime in list_of_primes: string_prime = str(prime) for template in templates: primes_that_match_the_template = [] for digit in range(10): new_string_for_alteration = copy.copy(string_prime) for i in range(len(template)): print i if template[i] == 1: new_string_for_alteration[i] == digit # for i in len(new_string_for_alteration): # if new_string_for_alteration[i] == 0: # new_string_for_alteration = new_string_for_alteration[1:] # else: altered_number = int(new_string_for_alteration) if altered_number in list_of_primes and altered_number not in primes_that_match_the_template: primes_that_match_the_template.append(altered_number) if primes_that_match_the_template != []: print primes_that_match_the_template if len(primes_that_match_the_template) >= required_family_size: return primes_that_match_the_template return "no numbers under "+ str(limit_number)+ " meet the criteria." def generate_variants_that_that_match_the_template(input_number, template): list_of_variants = [] list_input_number = list(input_number) for digit in range(10): for i in range(len(template)): print i if template[i] = 1: new_list_number[i] = digit
c7a048d9de13d6a8d64bff3e9cb75d750331af8d
Bidhampola/password_generator
/password_generator.py
535
4.15625
4
### week 1 project... password generator import string import random print("Welcome to password generator! ") #input the length of the password length=int(input('\n Enter the length of the password: ')) #defining data num=string.digits lower=string.ascii_lowercase upper=string.ascii_uppercase symbols=string.punctuation #combining all data all = upper+upper + lower+lower + num+num + symbols+symbols #using random temp=random.sample(all,length) #creating a password password = "".join(temp) # output password print(password)
0a8d6ce385008ba0da50d1795b96851ca0dc5c21
IOLevi/holbertonschool-higher_level_programming
/0x0A-python-inheritance/7-base_geometry.py
549
3.515625
4
#!/usr/bin/python3 'problem 8' class BaseGeometry(): 'base geo class' def area(self): 'prints area' raise Exception("area() is not implemented") def integer_validator(self, name, value): 'validates integers' if not isinstance(value, int): raise TypeError("{} must be an integer".format(name)) if value <= 0: raise ValueError("{} must be greater than 0".format(value)) if __name__ == "__main__": import doctest doctest.testfile("./tests/7-base_geometry.txt")
eb8c9f5509ddbab317ed0d27956c5ea1bc1dc6f9
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/space-age/60919e0172d344d2898562e626577005.py
1,046
3.984375
4
earth_year_seconds = 31557600 planet_year_dictionary = {"mercury": 0.2408467, "venus": 0.61519726, "earth": 1.0, "mars": 1.8808158, "jupiter": 11.862615, "saturn": 29.447498, "uranus": 84.016846, "neptune": 164.79132} class SpaceAge(object): """Returns the age of a person on various planets""" def __init__(self, seconds): self.seconds = seconds for planet in planet_year_dictionary: self.add_method(planet) def add_method(self, planet): """Creates functions to return the person's age on each planet""" self.__setattr__('on_' + planet, lambda: self.age_on_planet(planet)) def age_on_planet(self, planet): """Calculates the person's age on a given planet""" age = self.seconds/earth_year_seconds/planet_year_dictionary[planet] return round(age,2)
b5c5056fe2952ba716c6a62d275193d38a6be62c
liyzcj/god
/god/utils/file_utils.py
1,135
3.796875
4
"""A Module about file utilities.""" import os from pathlib import Path from tempfile import TemporaryDirectory class TempDir(object): """ Similar with TemporaryDirectory, except: * May chdir when use `with` statement * yield variable is a Path object when use `with` statement * `name` attribute return a Path object """ def __init__(self, cd=False): """ Create an temporary directory. :param cd: change to temporay dir or not, defaults to False :type cd: bool, optional """ self._dir = None # keep current dir if chdr self._tmp_obj = TemporaryDirectory() self._cd = cd self.name = Path(self._tmp_obj.name).absolute() def __enter__(self): if self._cd: self._dir = Path.cwd().absolute() os.chdir(self.name) return Path('./').absolute() return self.name def __exit__(self, tp, val, traceback): if self._cd: os.chdir(self._dir) def cleanup(self): """ Remove the temporary director. """ self._tmp_obj.cleanup()
1d7be1f4bd6c1356ec2c1966478850bea3c4132d
polkapolka/py511SFBay
/py511SFBay/utils.py
3,377
3.53125
4
import curses import curses.textpad import os import pdb class Window(object): """Wrapper for the curses module.""" COLOR_ORANGE = 0 y = 0 spacing = 0 total_columns = 0 width = 0 window = None def __init__(self, refresh_interval, total_columns): """Initialize the window with various settings.""" self.total_columns = total_columns self.window = curses.initscr() # Initialize colors with red, green, yellow, and blue curses.start_color() curses.use_default_colors() for i in range(1, 5): curses.init_pair(i, i, -1) # Use the orange color if the terminal supports it, and magenta # otherwise if curses.COLORS == 256: self.COLOR_ORANGE = 208 else: self.COLOR_ORANGE = curses.COLOR_MAGENTA curses.init_pair(self.COLOR_ORANGE, self.COLOR_ORANGE, -1) # Disable typing echo and hide the cursor curses.noecho() curses.curs_set(0) # Dont wait for enter curses.cbreak() # Set the refresh interval curses.halfdelay(refresh_interval) self._update_dimensions() def _get_color(self, color_name): """Get the color to use based on the name given.""" if not color_name: return 0 if color_name == 'ORANGE': color = self.COLOR_ORANGE else: color = getattr(curses, 'COLOR_' + color_name) return curses.color_pair(color) def _update_dimensions(self): """Update the width of the window and spacing needed for columns.""" _, self.width = self.window.getmaxyx() self.spacing = self.width // self.total_columns def addstr(self, y, x, string, color_name='', bold=False): """Add a string with optional color and boldness.""" self.y = y color = self._get_color(color_name) if bold: color |= curses.A_BOLD try: self.window.addstr(y, x, string, color) except curses.error: raise RuntimeError('Terminal too small.') def center(self, y, text): """Center the text in bold at a specified location.""" text_length = len(text) center = (self.width - text_length) // 2 text_end = center + text_length self.addstr(y, 0, ' ' * center) self.addstr(y, center, text, bold=True) self.addstr(y, text_end, ' ' * (self.width - text_end)) def clear_lines(self, y, lines=1): """Clear the specified lines.""" for i in range(lines): self.addstr(y + i, 0, ' ' * self.width) def enable_echo(self): curses.curs_set(1) def disable_echo(self): curses.curs_set(0) def getch(self): """Get the character input as an ASCII string. Also update the dimensions of the window if the terminal was resized. """ char = self.window.getch() if char == curses.KEY_RESIZE: self._update_dimensions() if char == curses.KEY_ENTER or char == 10 or char == 13: return 10 try: return chr(char) except ValueError: return '' def endwin(self): """End the window.""" curses.nocbreak() self.window.keypad(0) curses.echo() curses.endwin()
0a5ea04c4f3461e58679b8c67bde7402f299614d
sharmavaibhav7/CS579_IIT
/a3/a3.py
9,802
3.75
4
# coding: utf-8 # # Assignment 3: Recommendation systems # # Here we'll implement a content-based recommendation algorithm. # It will use the list of genres for a movie as the content. # The data come from the MovieLens project: http://grouplens.org/datasets/movielens/ # Please only use these imports. from collections import Counter, defaultdict import math import numpy as np import os import pandas as pd import re from scipy.sparse import csr_matrix import urllib.request import zipfile def download_data(): """ DONE. Download and unzip data. """ url = 'https://www.dropbox.com/s/h9ubx22ftdkyvd5/ml-latest-small.zip?dl=1' urllib.request.urlretrieve(url, 'ml-latest-small.zip') zfile = zipfile.ZipFile('ml-latest-small.zip') zfile.extractall() zfile.close() def tokenize_string(my_string): """ DONE. You should use this in your tokenize function. """ return re.findall('[\w\-]+', my_string.lower()) def tokenize(movies): """ Append a new column to the movies DataFrame with header 'tokens'. This will contain a list of strings, one per token, extracted from the 'genre' field of each movie. Use the tokenize_string method above. Note: you may modify the movies parameter directly; no need to make a new copy. Params: movies...The movies DataFrame Returns: The movies DataFrame, augmented to include a new column called 'tokens'. >>> movies = pd.DataFrame([[123, 'Horror|Romance'], [456, 'Sci-Fi']], columns=['movieId', 'genres']) >>> movies = tokenize(movies) >>> movies['tokens'].tolist() [['horror', 'romance'], ['sci-fi']] >>> movies = pd.DataFrame([[123, 'Horror|Romance|Romance'], [456, 'Sci-Fi']], columns=['movieId', 'genres']) >>> movies = tokenize(movies) >>> movies['tokens'].tolist() [['horror', 'romance', 'romance'], ['sci-fi']] """ ###TODO # add a new column "tokens" movies['tokens'] = '' # extract from genres, list of strings for i in movies.index: movies.at[i, 'tokens'] = tokenize_string(movies.at[i, 'genres']) return movies def featurize(movies): """ Append a new column to the movies DataFrame with header 'features'. Each row will contain a csr_matrix of shape (1, num_features). Each entry in this matrix will contain the tf-idf value of the term, as defined in class: tfidf(i, d) := tf(i, d) / max_k tf(k, d) * log10(N/df(i)) where: i is a term d is a document (movie) tf(i, d) is the frequency of term i in document d max_k tf(k, d) is the maximum frequency of any term in document d N is the number of documents (movies) df(i) is the number of unique documents containing term i Params: movies...The movies DataFrame Returns: A tuple containing: - The movies DataFrame, which has been modified to include a column named 'features'. - The vocab, a dict from term to int. Make sure the vocab is sorted alphabetically as in a2 (e.g., {'aardvark': 0, 'boy': 1, ...}) """ ###TODO # add new column features movies['features'] = '' # get all terms all_genres = [] for token in movies['tokens'].tolist(): all_genres.extend(token) all_genres = sorted(set(all_genres)) # vocab, dict from term to int vocab = {} for i in range(len(all_genres)): vocab[all_genres[i]] = i # number of movies N = len(movies.index) # number of unique documents containing term i num_doc_i = {} for term in all_genres: num_doc_i[term] = 0 for term in movies['tokens'].tolist(): for t in set(term): num_doc_i[t] += 1 # for each movie, calculate tfidf for each term and add to matrix for i in range(len(movies.index)): cur_terms = movies.at[i, 'tokens'] cur_term_freq = {} for term in cur_terms: if term in cur_term_freq: cur_term_freq[term] += 1 elif term not in cur_term_freq: cur_term_freq[term] = 1 max_freq = sorted(cur_term_freq.items(), key=lambda x: -x[1])[0][1] #matrix row = [] col = [] data = [] for term in cur_terms: tfidf = cur_term_freq[term] / max_freq * math.log10(N/num_doc_i[term]) row.append(0) col.append(vocab[term]) data.append(tfidf) #build matrix row = np.array(row) col = np.array(col) data = np.array(data) matrix = csr_matrix((data, (row, col)),shape=(1, len(all_genres))) movies.at[i, 'features'] = matrix return (movies, vocab) def train_test_split(ratings): """DONE. Returns a random split of the ratings matrix into a training and testing set. """ test = set(range(len(ratings))[::1000]) train = sorted(set(range(len(ratings))) - test) test = sorted(test) return ratings.iloc[train], ratings.iloc[test] def cosine_sim(a, b): """ Compute the cosine similarity between two 1-d csr_matrices. Each matrix represents the tf-idf feature vector of a movie. Params: a...A csr_matrix with shape (1, number_features) b...A csr_matrix with shape (1, number_features) Returns: The cosine similarity, defined as: dot(a, b) / ||a|| * ||b|| where ||a|| indicates the Euclidean norm (aka L2 norm) of vector a. """ ###TODO # a, b to array #if they have value in the same position arr_a = a.toarray()[0] arr_b = b.toarray()[0] lengh = len(a.toarray()[0]) dot_a_b = 0 norm_a = 0 norm_b = 0 for i in range(lengh): if arr_a[i] != 0 and arr_b[i] != 0: dot_a_b += arr_a[i] * arr_b[i] if arr_a[i] != 0: norm_a += arr_a[i] * arr_a[i] if arr_b[i] != 0: norm_b += arr_b[i] * arr_b[i] cos_sim = dot_a_b / (math.sqrt(norm_a) * math.sqrt(norm_b)) return cos_sim def make_predictions(movies, ratings_train, ratings_test): """ Using the ratings in ratings_train, predict the ratings for each row in ratings_test. To predict the rating of user u for movie i: Compute the weighted average rating for every other movie that u has rated. Restrict this weighted average to movies that have a positive cosine similarity with movie i. The weight for movie m corresponds to the cosine similarity between m and i. If there are no other movies with positive cosine similarity to use in the prediction, use the mean rating of the target user in ratings_train as the prediction. Params: movies..........The movies DataFrame. ratings_train...The subset of ratings used for making predictions. These are the "historical" data. ratings_test....The subset of ratings that need to predicted. These are the "future" data. Returns: A numpy array containing one predicted rating for each element of ratings_test. """ ###TODO predicted_rating = [] ratings_train.index = range(ratings_train.shape[0]) ratings_test.index = range(ratings_test.shape[0]) # movies to dict all_movies = [] for i in range(len(movies.index)): d = {} d['movieId'] = movies.at[i, 'movieId'] d['features'] = movies.at[i, 'features'] all_movies.append(d) # ratings_train to dict train = [] for i in range(len(ratings_train.index)): d = {} d['userId'] = ratings_train.at[i, 'userId'] d['movieId'] = ratings_train.at[i, 'movieId'] d['rating'] = ratings_train.at[i, 'rating'] train.append(d) # for each movie i in test, calculate predicted rating for i in range(len(ratings_test.index)): user = ratings_test.at[i, 'userId'] movie = ratings_test.at[i, 'movieId'] rate = [] w = [] no_pos_rt = [] a = np.matrix([]) for m in all_movies: if m['movieId'] == movie: a = m['features'] # find all moveis this user rated in train for x in train: if x['userId'] == user: mid = x['movieId'] rt = x['rating'] b = np.matrix([]) for m in all_movies: if m['movieId'] == mid: b = m['features'] weight = cosine_sim(a, b) if weight > 0: rate.append(rt) w.append(weight) else: no_pos_rt.append(rt) # weighted average if len(rate) > 0: for r in range(len(rate)): rate[r] = rate[r] * w[r] / sum(w) predicted_rating.append(sum(rate)) else: predicted_rating.append(np.asarray(no_pos_rt).mean()) return np.asarray(predicted_rating) def mean_absolute_error(predictions, ratings_test): """DONE. Return the mean absolute error of the predictions. """ return np.abs(predictions - np.array(ratings_test.rating)).mean() def main(): download_data() path = 'ml-latest-small' ratings = pd.read_csv(path + os.path.sep + 'ratings.csv') movies = pd.read_csv(path + os.path.sep + 'movies.csv') movies = tokenize(movies) movies, vocab = featurize(movies) print('vocab:') print(sorted(vocab.items())[:10]) ratings_train, ratings_test = train_test_split(ratings) print('%d training ratings; %d testing ratings' % (len(ratings_train), len(ratings_test))) predictions = make_predictions(movies, ratings_train, ratings_test) print('error=%f' % mean_absolute_error(predictions, ratings_test)) print(predictions[:10]) if __name__ == '__main__': main()
f099c403d8b645d711240b6f51d25503255707dd
bsilver8192/cs521-project
/process_regions.py
4,610
3.609375
4
#!/usr/bin/python3 # Creates a domestic_region_locations.csv with latitude+longitude for all # the domestic regions. The first column is the code and the other columns are # the latitude/longitude pairs or a redirect. For multiple pairs, we will # verify they are all "close" (20 miles or something like that) and then use # the centroid. Redirects are where the data divides a single metropolitan # area into multiple states, which we don't care about, so we're just going # to combine the data for all those areas. # Run this file using process_regions.sh to set up Python correctly. import csv import re import googlemaps # To generate an API key, go to # https://developers.google.com/maps/documentation/geocoding/get-api-key#key # and click the "Get A Key" button and follow the directions. Save it in a file # named google_maps_geocoding_api_key.txt. # Type of region codes: # C: Combined Statistical Area (CSA) # M: Metropolitan Statistical Area (MSA) # R: Rest of State - everything in a state not included in a CSA or MSA (RoS) # S: State that does not include a CSA or MSA # SM: Whole state is part of MSA def main(): with open('google_maps_geocoding_api_key.txt', 'r') as f: key = f.read().rstrip() gmaps = googlemaps.Client(key=key) with open('domestic_regions.csv', 'r', newline='') as explanations: with open('domestic_region_locations.csv', 'w') as locations: reader = csv.DictReader(explanations, delimiter='\t') # Map from the city part of a multi-state areas to the first code we saw # for it. multistate_areas = {} for row in reader: split_name = row['Name'].split(', ') if len(split_name) == 1: if 'Remainder of ' in split_name[0]: nice_name = split_name[0][len('Remainder of '):] else: nice_name = split_name[0] candidates = ['%s, %s' % (nice_name, row['State']), nice_name] else: if len(split_name) > 2: raise RuntimeError('Too many pieces in name %s' % repr(split_name)) # Verify that the second piece says "CT CFS Area", or multiple states # including CT like "NY-NJ-CT-PA CFS Area (CT Part)". This is just a # sanity check; CT is row['State'] and NY, NJ, and PA are # row['Including States']. if not re.match('([A-Z]{2}-)*%s(-[A-Z]{2})* CFS Area' % row['State'], split_name[1]): raise RuntimeError( 'Not sure what to do with second piece of %s in %s' % (repr(split_name), row['State'])) if 'Remainder of' in split_name[0]: raise RuntimeError('States are not CFS Areas') # Deduplicate the parts of an area in different states because we # don't care. match = re.match('^(.*) \\([A-Z]{2} Part\\)$', split_name[1]) if match: region = match.group(1) if region in multistate_areas: print('%s,redir:%s' % (row['Code'], multistate_areas[region]), file=locations) continue else: multistate_areas[region] = row['Code'] # Build up the cross product of all the cities and states. We'll try # them all and only keep the ones which return valid results, and then # make sure they're all close together and pick the centroid later. candidates = [] for region in split_name[0].split('-'): for state in row['Including States'].split() + [row['State']]: candidates.append('%s, %s' % (region, state)) # Try retrieving results for all the candidates and stick them in the # file. output = [row['Code']] found_ids = set() for candidate in candidates: geocode_result = gmaps.geocode(candidate) # If we got multiple results, it's probably a city not in this state # so all the guesses are useless for us, so just ignore them. if len(geocode_result) > 1: pass if geocode_result: # Don't add the same place twice. place_id = geocode_result[0]['place_id'] if place_id in found_ids: continue found_ids.add(place_id) location = geocode_result[0]['geometry']['location'] output += [str(location['lat']), str(location['lng'])] if len(output) == 1: raise RuntimeError('No results in %s' % repr(candidates)) print(','.join(output), file=locations) if __name__ == '__main__': main()
e2d5e6afe2873254ab07c5bcd15024a4134ae95b
CaioHenriqueMachado/Contribuindo_com_Python
/Funções/Distancia_levenshtein.py
269
3.921875
4
#Link para outros tipos:https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python def lev(a, b): if not a: return len(b) if not b: return len(a) return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1)
eacc422092892f58b11da086d6d093ddd613a304
AS-AmanSinghal/PythonLearning
/TeslaExercise.py
341
3.703125
4
def Checker(age): if age < 18: return "Sorry,you are too young to drive this car.Powering off" elif age == 18: return "Congratulations on your first year of driving. Enjoy the ride!" else: return "Powering On. Enjoy the ride." print(Checker(17)) print(Checker(18)) print(Checker(19)) print(Checker(55))
ea055c5e6cc63de1122d12d1ea0ee1157aa81f43
henrydeng2002/HoldEm
/Card.py
950
3.796875
4
class Card: # basic card structure def __init__(self, value, suit): self.value = value self.suit = suit # all the comparison methods def __eq__(self, card): return (self.value == card.value) def __ne__(self, card): return not (self.value == card.value) def __lt__(self, card): return (self.value < card.value) def __repr__(self): suit_str = "spades" if(self.suit == 2): suit_str = "diamonds" elif(self.suit == 3): suit_str = "clubs" elif(self.suit == 4): suit_str = "hearts" value_str = str(self.value) if(value_str == "14"): value_str = "A" elif(value_str == "13"): value_str = "K" elif(value_str == "12"): value_str = "Q" elif(value_str == "11"): value_str = "J" return "%s" % (value_str + " of " + suit_str)
3aa5f7104fba31cab4fe2640e635e76eb1eb57d1
1712danish/OS_priorityScheduling
/priority_Scheduling.py
1,111
3.59375
4
def waitingTime(processes, n, wt): wt[0] = 0 for i in range(1, n): wt[i] = processes[i - 1][1] + wt[i - 1] def turnAroundTime(processes, n, wt, tat): for i in range(n): tat[i] = processes[i][1] + wt[i] def findavgTime(processes, n): wt = [0] * n tat = [0] * n waitingTime(processes, n, wt) turnAroundTime(processes, n, wt, tat) print("\nProcesses Burst Time Waiting", "Time Turn-Around Time") total_wt = 0 total_tat = 0 for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] print(" ", processes[i][0], "\t\t", processes[i][1], "\t\t", wt[i], "\t\t", tat[i]) print("\nAverage waiting time = %.5f "%(total_wt /n)) print("Average turn around time = ", total_tat / n) def priorityScheduling(proc, n): proc = sorted(proc, key = lambda proc:proc[2],reverse =True); print("Order in which processes gets executed") for i in proc: print(i[0], end = " ") findavgTime(proc, n) if __name__ =="__main__": process = [[1, 10, 1], [2, 20, 0], [3, 15, 1], [4, 11, 2]] n = 4 priorityScheduling(process, n)
ba3a89390d03b895f7fc4130ceb81e14ca21272e
pforshay/MAST-HLSP
/PREP_CAOM/util/check_log.py
789
3.609375
4
""" ..module:: check_log :synopsis: Examines the log file at the end of processing to provide some feedback on how many errors and warnings were logged. """ import os #-------------------- def check_log(filepath): """ Count errors and warnings in the log file and print the results. :param filepath: File path for the log file. :type filepath: string """ fullpath = os.path.abspath(filepath) errors = 0 warnings = 0 with open(fullpath) as log: as_lines = log.readlines() for n in as_lines: if n.startswith("***WARNING"): warnings += 1 elif n.startswith("***ERROR"): errors += 1 log.close() print("Logged {0} errors and {1} warnings".format(errors, warnings))
d931e1d82bc6bdfd95fc49c2bfe017b5a062a9ac
thinkreed/lc.py
/algo/first/p735_asteroid_collision.py
465
3.59375
4
class Solution: def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ s = [] for asteroid in asteroids: while len(s) > 0 and 0 < s[-1] < -asteroid: s.pop() if len(s) == 0 or asteroid > 0 or s[-1] < 0: s.append(asteroid) elif asteroid < 0 and s[-1] == -asteroid: s.pop() return s
134fc4849bde869a3a36fea76e5793beec74f1e0
nayana09/python
/file2.py
4,521
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #if conditions a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") # In[3]: #evaluating variable print(bool("Hello")) print(bool(15)) # In[4]: bool("abc") bool(123) bool(["apple", "cherry", "banana"]) # In[5]: def myFunction() : return True print(myFunction()) # In[7]: print(10 + 5) print(10 - 5) print(10 * 5) print(10 / 5) print(10 % 5) print(10**2) # In[8]: #python list this_list = ["apple", "banana", "cherry"] print(this_list) # In[11]: #duplicates this_list = ["apple", "banana", "cherry", "apple", "cherry"] print(this_list) print(len(this_list)) # In[21]: list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] list4 = ["abc", 34, True, 40, "male"] print(list1) print(list2) print(list3) print(list4) print(type(list1)) print(type(list2)) #accessing item print(list1[1]) #negative index print(list1[-1]) #range print(list1[2:5]) # In[22]: #change item value this_list = ["apple", "banana", "cherry"] this_list[1] = "blackcurrant" print(this_list) # In[23]: #change range this_list = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] this_list[1:3] = ["blackcurrant", "watermelon"] print(this_list) # In[24]: this_list = ["apple", "banana", "cherry"] this_list[1:2] = ["blackcurrant", "watermelon"] print(this_list) # In[25]: this_list = ["apple", "banana", "cherry"] this_list.insert(2, "watermelon") print(this_list) # In[26]: #append item insert item to the last list of the item this_list = ["apple", "banana", "cherry"] this_list.append("orange") print(this_list) # In[27]: this_list = ["apple", "banana", "cherry"] this_list.insert(1, "orange") print(this_list) # In[28]: this_list = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] this_list.extend(tropical) print(this_list) # In[29]: #add any iterables this_list = ["apple", "banana", "cherry"] this_tuple = ("kiwi", "orange") this_list.extend(this_tuple) print(this_list) # In[30]: #remove item this_list = ["apple", "banana", "cherry"] this_list.remove("banana") print(this_list) # In[31]: this_list = ["apple", "banana", "cherry"] this_list.pop(1) print(this_list) # In[32]: this_list = ["apple", "banana", "cherry"] this_list.pop() print(this_list) # In[33]: #remove first item this_list = ["apple", "banana", "cherry"] del this_list[0] print(this_list) # In[37]: #delete entire list this_list = ["apple", "banana", "cherry"] del this_list # In[38]: #loop list this_list = ["apple", "banana", "cherry"] for x in this_list: print(x) # In[39]: this_list = ["apple", "banana", "cherry"] i = 0 while i < len(this_list): print(this_list[i]) i = i + 1 # In[40]: this_list = ["apple", "banana", "cherry"] [print(x) for x in this_list] # In[41]: #list comprenshion fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) # In[42]: #sort ascending this_list = ["orange", "mango", "kiwi", "pineapple", "banana"] this_list.sort() print(this_list) # In[43]: #sort descending this_list = ["orange", "mango", "kiwi", "pineapple", "banana"] this_list.sort(reverse = True) print(this_list) # In[44]: #copylist this_list = ["apple", "banana", "cherry"] my_list = this_list.copy() print(my_list) # In[45]: list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) # In[46]: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) # In[48]: #python tuples thistuple = ("apple", "banana", "cherry") print(thistuple) print(len(thistuple)) # In[49]: #acces tuples thistuple = ("apple", "banana", "cherry") print(thistuple[1]) # In[50]: #range of indexing thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) # In[51]: thistuple = ("apple", "banana", "cherry") if "apple" in thistuple: print("Yes, 'apple' is in the fruits tuple") # In[52]: x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) # In[54]: #unpacking tuplefruits = ("apple", "banana", "cherry") fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) # In[55]: #using astrike fruits = ("apple", "banana", "cherry", "strawberry", "raspberry") (green, yellow, *red) = fruits print(green) print(yellow) print(red) # In[ ]:
72f54697375d47fb7013603211162648c5fd6ab3
SmithWenge/pythonTest
/返回函数0617/test1.py
1,654
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-06-15 10:11:33 # @Author : Sullivan (1980849329@qq.com) # @Link : https://github.com/SmithWenge # 函数作为返回值 # 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。 def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax num = calc_sum(1,2,3) print(num) # 如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办? # 可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1, 3, 5, 7, 9) #在调用函数f的时候才会返回结果,这个时候f并不是计算返回的数值而是返回的函数 num2 = f() print(num2) # 在这个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量, # 当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。 # 再注意一点,当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数: # 注意到返回的函数在其定义内部引用了局部变量args, # 所以,当一个函数返回了一个函数后,其内部的局部变量还被新函数引用,所以,闭包用起来简单,实现起来可不容易。 # 另一个需要注意的问题是,返回的函数并没有立刻执行,而是直到调用了f()才执行
407bea2b15d6545cb944fc4f7bd1cb5b6af8812d
TerryOShea/algorithms
/interview_cake/max_stack.py
1,285
4.0625
4
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.items: return None return self.items.pop() def peek(self): if not self.items: return None return self.items[-1] def length(self): return len(self.items) class MaxStack: """ The MaxStack class uses the Stack class above but enables a constant-time get_max method: the stack stores each item as a list where the 0th index contains the item value and the 1st index the max at the time of the item's insertion (either that item or the existing max, whichever is bigger) """ def __init__(self): self.stack = Stack() def push(self, item): if self.stack.length() == 0: self.stack.push([item, item]) else: last_max = self.stack.peek()[1] self.stack.push([item, max(item, last_max)]) def pop(self): item, _ = self.stack.pop() return item def get_max(self): _, current_max = self.stack.peek() return current_max ms = MaxStack() ms.push(6) ms.push(5) ms.push(13) ms.push(1) print(ms.get_max()) ms.pop() ms.pop() print(ms.get_max())
c930f23466e8bce9e2ddbece229be81abacea35e
Sanijg/mitx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/Enigma/ps6.py
15,335
4.21875
4
import string ### DO NOT MODIFY THIS FUNCTION ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. ''' print('Loading word list from file...') # inFile: file in_file = open(file_name, 'r') # line: string line = in_file.readline() # word_list: list of strings word_list = line.split() print(' ', len(word_list), 'words loaded.') in_file.close() return word_list ### DO NOT MODIFY THIS FUNCTION ### def is_word(word_list, word): ''' Determines if word is a valid word, ignoring capitalization and punctuation word_list (list): list of words in the dictionary. word (string): a possible word. Returns: True if word is in word_list, False otherwise Example: >>> is_word(word_list, 'bat') returns True >>> is_word(word_list, 'asdf') returns False ''' word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in word_list ### DO NOT MODIFY THIS FUNCTION ### def get_story_string(): """ Returns: a joke in encrypted text. """ f = open("story.txt", "r") story = str(f.read()) f.close() return story WORDLIST_FILENAME = 'words.txt' # Problem 1 - Build the Shift Dictionary and Apply Shift # 20/20 points (graded) # The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since # for Caesar codes this is the same action). # In the next two questions, you will fill in the methods of the Message class found in ps6.py according to the specifications in the # docstrings. The methods in the Message class already filled in are: # __init__(self, text) # The getter method get_message_text(self) # The getter method get_valid_words(self), notice that this one returns a copy of self.valid_words to prevent someone from mutating the # original list. # In this problem, you will fill in two methods: # Fill in the build_shift_dict(self, shift) method of the Message class. Be sure that your dictionary includes both lower and upper case # letters, but that the shifted character for a lower case letter and its uppercase version are lower and upper case instances of the # same letter. What this means is that if the original letter is "a" and its shifted value is "c", the letter "A" should shift to the # letter "C". # If you are unfamiliar with the ordering or characters of the English alphabet, we will be following the letter ordering displayed by # string.ascii_lowercase and string.ascii_uppercase: # >>> import string # >>> print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz # >>> print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ # A reminder from the introduction page - characters such as the space character, commas, periods, exclamation points, etc will not be # encrypted by this cipher - basically, all the characters within string.punctuation, plus the space (' ') and all numerical characters # (0 - 9) found in string.digits. # Fill in the apply_shift(self, shift) method of the Message class. You may find it easier to use build_shift_dict(self, shift). Remember # that spaces and punctuation should not be changed by the cipher. class Message(object): ### DO NOT MODIFY THIS METHOD ### def __init__(self, text): ''' Initializes a Message object text (string): the message's text a Message object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) ### DO NOT MODIFY THIS METHOD ### def get_message_text(self): ''' Used to safely access self.message_text outside of the class Returns: self.message_text ''' return self.message_text ### DO NOT MODIFY THIS METHOD ### def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class Returns: a COPY of self.valid_words ''' return self.valid_words[:] def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). ''' lower_keys = list(string.ascii_lowercase) lower_values = list(string.ascii_lowercase) shift_lower_values = lower_values[shift:] + lower_values[:shift] upper_keys = list(string.ascii_uppercase) upper_values = list(string.ascii_uppercase) upper_shift_values = upper_values[shift:] + upper_values[:shift] full_keys = lower_keys + upper_keys full_values = shift_lower_values + upper_shift_values self.shift_dict = dict(zip(full_keys, full_values)) return self.shift_dict def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' new_msg = [] for i in self.message_text: if i not in self.build_shift_dict(shift).keys(): new_msg.append(i) continue else: new_msg.append(self.build_shift_dict(shift)[i]) return ''.join(new_msg) # Problem 2 - PlaintextMessage # 15/15 points (graded) # For this problem, the graders will use our implementation of the Message class, so don't worry if you did not get the previous parts # correct. # PlaintextMessage is a subclass of Message and has methods to encode a string using a specified shift value. Our class will always # create an encoded version of the message, and will have methods for changing the encoding. # Implement the methods in the class PlaintextMessage according to the specifications in ps6.py. The methods you should fill in are: # __init__(self, text, shift): Use the parent class constructor to make your code more concise. # The getter method get_shift(self) # The getter method get_encrypting_dict(self): This should return a COPY of self.encrypting_dict to prevent someone from mutating the # original dictionary. # The getter method get_message_text_encrypted(self) # change_shift(self, shift): Think about what other methods you can use to make this easier. It shouldn’t take more than a couple lines # of code. class PlaintextMessage(Message): def __init__(self, text, shift): ''' Initializes a PlaintextMessage object text (string): the message's text shift (integer): the shift associated with this message A PlaintextMessage object inherits from Message and has five attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) self.shift (integer, determined by input shift) self.encrypting_dict (dictionary, built using shift) self.message_text_encrypted (string, created using shift) Hint: consider using the parent class constructor so less code is repeated ''' #pass #delete this line and replace with your code here self.shift = shift self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift) self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift) def get_shift(self): ''' Used to safely access self.shift outside of the class Returns: self.shift ''' #pass #delete this line and replace with your code here return self.shift def get_encrypting_dict(self): ''' Used to safely access a copy self.encrypting_dict outside of the class Returns: a COPY of self.encrypting_dict ''' #pass #delete this line and replace with your code here encrypting_dict_copy = self.encrypting_dict.copy() return encrypting_dict_copy def get_message_text_encrypted(self): ''' Used to safely access self.message_text_encrypted outside of the class Returns: self.message_text_encrypted ''' #pass #delete this line and replace with your code here return self.message_text_encrypted def change_shift(self, shift): ''' Changes self.shift of the PlaintextMessage and updates other attributes determined by shift (ie. self.encrypting_dict and message_text_encrypted). shift (integer): the new shift that should be associated with this message. 0 <= shift < 26 Returns: nothing ''' #pass #delete this line and replace with your code here self.shift = shift self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift) self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift) # Problem 3 - CiphertextMessage # 15/15 points (graded) # For this problem, the graders will use our implementation of the Message and PlaintextMessage classes, so don't worry if you did not # get the previous parts correct. # Given an encrypted message, if you know the shift used to encode the message, decoding it is trivial. If message is the encrypted # message, and s is the shift used to encrypt the message, then apply_shift(message, 26-s) gives you the original plaintext message. Do # you see why? # The problem, of course, is that you don’t know the shift. But our encryption method only has 26 distinct possible values for the shift! # We know English is the main language of these emails, so if we can write a program that tries each shift and maximizes the number of # English words in the decoded message, we can decrypt their cipher! A simple indication of whether or not the correct shift has been # found is if most of the words obtained after a shift are valid words. Note that this only means that most of the words obtained are # actual words. It is possible to have a message that can be decoded by two separate shifts into different sets of words. While there are # various strategies for deciding between ambiguous decryptions, for this problem we are only looking for a simple solution. # Fill in the methods in the class CiphertextMessage acording to the specifications in ps6.py. The methods you should fill in are: # __init__(self, text): Use the parent class constructor to make your code more concise. # decrypt_message(self): You may find the helper function is_word(wordlist, word) and the string method split() useful. Note that is_word # will ignore punctuation and other special characters when considering whether a word is valid. class CiphertextMessage(Message): def __init__(self, text): ''' Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) def decrypt_message(self): ''' Decrypt self.message_text by trying every possible shift value and find the "best" one. We will define "best" as the shift that creates the maximum number of real words when we use apply_shift(shift) on the message text. If s is the original shift value used to encrypt the message, then we would expect 26 - s to be the best shift value for decrypting it. Note: if multiple shifts are equally good such that they all create the maximum number of you may choose any of those shifts (and their corresponding decrypted messages) to return Returns: a tuple of the best shift value used to decrypt the message and the decrypted message text using that shift value ''' word_counter = 0 max_count = 0 for i in range(26): for j in list(super(CiphertextMessage, self).apply_shift(i).split(' ')): if is_word(self.valid_words, j): word_counter += 1 if word_counter > max_count: max_count = word_counter shift_value = i decrypted_msg = super(CiphertextMessage, self).apply_shift(i) return (shift_value, decrypted_msg) # Problem 4 - Decrypt a Story # 5/5 points (graded) # For this problem, the graders will use our implementation of the Message, PlaintextMessage, and CiphertextMessage classes, so don't worry # if you did not get the previous parts correct. # Now that you have all the pieces to the puzzle, please use them to decode the file story.txt. The file ps6.py contains a helper function # get_story_string() that returns the encrypted version of the story as a string. Create a CiphertextMessage object using the story string # and use decrypt_message to return the appropriate shift value and unencrypted story string. # Paste your function decrypt_story() in the box below. def decrypt_story(): joke_code = CiphertextMessage(get_story_string()) return joke_code.decrypt_message() #Example test case (PlaintextMessage) plaintext = PlaintextMessage('hello', 2) print('Expected Output: jgnnq') print('Actual Output:', plaintext.get_message_text_encrypted()) #Example test case (CiphertextMessage) ciphertext = CiphertextMessage('jgnnq') print('Expected Output:', (24, 'hello')) print('Actual Output:', ciphertext.decrypt_message())
eb5906f5de7c9c7e00f8fbff2590036c2dccaa79
imageadhikari/Mini-project
/main.py
1,238
3.703125
4
import numpy as np from utils import getXY from plot import myPlot #set the seed np.random.seed(111) #set the values MAX_LENGTH = 10**3 STEP = 50 #generating the random array array = np.random.randint(1,high=500,size=(MAX_LENGTH)) #for the worse case we need array sorted in decending order, so reversing reversed_array = array[::-1] #give message to user print("Array before being sorted is ",array[:100],"...",array[-100:]) print("Sorting...\nIt may take a while..") print("For bubblesort") #FOR BUBBLE SORT sorted_array,x_data_size,y_time_took = getXY( reversed_array, MAX_LENGTH, STEP, sort_type="bubble" ) print("The sorted array is:",sorted_array[:100],"...",sorted_array[-100:]) #plot x & y myPlot(x_data_size,y_time_took,x_label="Size of array",y_label="Milliseconds took",title="Worse case of bubble sort") #bubblesortends print("For Mergesort") #FOR MERGE SORT sorted_array,x_data_size,y_time_took = getXY( reversed_array, MAX_LENGTH, STEP, sort_type="merge" ) print("The sorted array is:",sorted_array[:100],"...",sorted_array[-100:]) #plot x & y myPlot(x_data_size,y_time_took,x_label="Size of array",y_label="Milliseconds took",title="Worse case of merge sort") #mergesortends
164bdff68567cf9e59b2c555aaa70792bfcbdfaa
helloworld767/alogrithm
/permutation.py
313
3.546875
4
def permutation(nums, subset, res): if not nums: res.append(subset.copy()) for i in range(len(nums)): permutation(nums[: i] + nums[i + 1:], subset + [nums[i]], res) return n = 4 nums = [i for i in range(1, n + 1)] res = [] permutation(nums, [], res) for list in res: print(list)
7f32f9eaf26b0a947c691f8d215812d18013e8a1
ShimSooChang/exerciosparatreino
/exercios2/10.py
248
3.953125
4
num = int(input("Digite um número para saber se é primo: ")) cont = 0 x = 0 while x <= num or cont < 2: x += 1 d = num % x if d == 0: cont += 1 if cont <= 2: print("é numero primo") else: print("não é primo")
870c3d5cc1f37de9add719a39b6d2788eb7c2b2b
parkje0927/atom-workspace
/basic/0424.py
4,983
3.609375
4
# 파이썬 스타일 코드 I colors = ['red', 'blue', 'green', 'yellow'] result = ''.join(colors) print(result) items = 'zero one two three'.split() print(items) example = 'python, jqeury, javascript' example.split(",") print(example) a, b, c = example.split(",") print(a, b, c) result = ' '.join(colors) print(result) result = ', '.join(colors) print(result) result = [i for i in range(10)] print(result) result = [i for i in range(10) if i % 2 == 0] print(result) # else 붙일 경우 조건문이 앞으로 간다. result = [i if i % 2 == 0 else 10 for i in range(10)] print(result) word1 = "hello" word2 = "world" result = [i + j for i in word1 for j in word2] print(result) result = [i + j for i in word1 for j in word2 if i != j] print(result) words = 'The quick brown fox jumps over the lazy dog'.split() print(words) stuff = [[w.upper(), w.lower(), len(w)] for w in words] print(stuff) for i in stuff: print(i) case1 = ['a', 'b', 'c'] case2 = ['d', 'e', 'a'] # 일차원 리스트 출력 # ['ad', 'ae', 'aa', 'bd', 'be', 'ba', 'cd', 'ce', 'ca'] result = [i + j for i in case1 for j in case2] print(result) # 이차원 리스트 출력 # [['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['aa', 'ba', 'ca']] result = [[i + j for i in case1] for j in case2] print(result) # 일반적인 반복문 + 리스트 # def scalar_vector_product(scalar, vector): # result = [] # for value in vector: # result.append(scalar * value) # return result # iteration_max = 10000 # # vector = list(range(iteration_max)) # scalar = 2 # for _ in range(iteration_max): # scalar_vector_product(scalar, vector) # iteration_max = 10000 # vector = list(range(iteration_max)) # scalar = 2 # for _ in range(iteration_max): # [scalar * value for value in range(iteration_max)] # enumerate for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) # 0 tic # 1 tac # 2 toe alist = ['a1', 'b1', 'c1'] blist = ['a2', 'b2', 'c2'] for a, b in zip(alist, blist): print(a, b) # a1 a2 # b1 b2 # c1 c2 a, b, c = zip((1, 2, 3), (10, 20, 30), (100, 200, 300)) print(a, b, c) [print(sum(x)) for x in zip((1, 2, 3), (10, 20, 30), (100, 200, 300))] alist = ['a1', 'b1', 'c1'] blist = ['a2', 'b2', 'c2'] for i, (a, b) in enumerate(zip(alist, blist)): print(i, a, b) # # 람다 # f = lambda x, y: x + y # print(f(1, 4)) # # print((lambda x: x+1)(5)) # # f = lambda x: x ** 2 # print(f(5)) # # # # 맵리듀스 # # ex = [1, 2, 3, 4, 5] # f = lambda x: x ** 2 # print(list(map(f, ex))) # # temp = [x ** 2 for x in ex] # print(temp) # # ex = [1, 2, 3, 4, 5] # f = lambda x, y: x + y # temp = list(map(f, ex, ex)) # print(temp) # # temp = list(map(lambda x: x ** 2 if x % 2 == 0 else x, ex)) # print(temp) # temp = [x ** 2 if x % 2 == 0 else x for x in ex] # print(temp) # # # from functools import reduce # print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])) # 15 # # # def asterisk_test(a, *args): # print(a, args) # 1 (2, 3, 4, 5, 6) # print(type(args)) # tuple # # # asterisk_test(1, 2, 3, 4, 5, 6) # # # def asterisk_test(a, **kargs): # print(a, kargs) # 1 {'b': 2, 'c': 3, 'd': 4, 'e': 5} # print(type(kargs)) # dict # # asterisk_test(1, b=2, c=3, d=4, e=5) # # # def asterisk_test(a, args): # print(a, *args) # 1 2 3 4 5 6 # print(type(args)) # tuple # # asterisk_test(1, (2, 3, 4, 5, 6)) # # 변수 앞의 별표는 해당 변수를 언패킹한다. 즉 하나의 튜플이 아닌 각각의 변수로 변경 # # # a, b, c = ([1, 2], [3, 4], [5, 6]) # print(a, b, c) # data = ([1, 2], [3, 4], [5, 6]) # print(*data) # # for data in zip(*[[1, 2], [3, 4], [5, 6]]): # print(data) # print(type(data)) # # # def asterisk_test(a, b, c, d): # print(a, b, c, d) # # data = {"b":1, "c":2, "d":3} # asterisk_test(10, **data) # # # # # 선형대수학 # # u = [2, 2] # v = [2, 3] # z = [3, 5] # # result = [sum(t) for t in zip(u, v, z)] # print(result) # # # def vector_addition(*args): # return [sum(t) for t in zip(*args)] # # vector_addition(u, v, z) # # *args 를 사용하여 여러 개의 변수를 입력 받는 가변 인수로 사용하였다. # # 그리고 실제 함수에서는 args 에 별표를 붙여 언패킹하였다. # # row_vectors = [[2, 2], [2, 3], [3, 5]] # vector_addition(*row_vectors) u = [1, 2, 3] v = [4, 4, 4] alpha = 2 result = [alpha * sum(t) for t in zip(u, v)] print(result) matrix_a = [[3, 6], [4, 5]] matrix_b = [[5, 8], [6, 7]] result = [[sum(row) for row in zip(*t)] for t in zip(matrix_a, matrix_b)] print(result) matrix_a = [[1, 1], [1, 1]] matrix_b = [[1, 1], [1, 1]] # all(row[0] == value for t in zip(matrix_a, matrix_b) for row in zip(*t) \ # for value in row]) # 행렬의 곱셈은 앞 행렬의 열과 뒤 행렬의 행을 선형 결합한다. # (2 X 3)(3 X 2) = (2 X 2) 행렬 matrix_a = [[1, 1, 2], [2, 1, 1]] matrix_b = [[1, 1], [2, 1], [1, 3]] result = [[sum(a * b for a, b in zip(row_a, column_b)) for column_b \ in zip(*matrix_b)] for row_a in matrix_a] print(result)
9c8b92f8cdc094740df61ddb6b77aff56e2350ad
AdamZhouSE/pythonHomework
/Code/CodeRecords/2147/60647/301543.py
2,921
3.5625
4
def findAllPath(graph, start, end, path=[]): path = path + [start] if start == end: return [path] paths = [] # 存储所有路径 for node in graph[start]: if node not in path: newpaths = findAllPath(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths def long(list): res=0 for i in range(len(list)-1): f=list[i] g=list[i+1] res+=listtemp[f][g] return res def bubble_sort1(nums): for i in range(len(nums) - 1): # 这个循环负责设置冒泡排序进行的次数(比如说n个数,则只要进行n-1次冒泡,就可以把这个n个数排序好,对吧) for j in range(len(nums) - i - 1): if long(nums[j]) > long(nums[j + 1]): nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums list=input().split() n = int(list[0]) # 点 m = int(list[1]) # 线 k = int(list[2])-1 a = int(list[3]) b = int(list[4]) listtemp=[] for j in range(n): temp=[] for r in range(n): temp.append(0) listtemp.append(temp) for j in range(m): temp=input().split() c=int(temp[0]) d=int(temp[1]) listtemp[c-1][d-1]=a listtemp[d - 1][c - 1] = a dict={} for j in range(len(listtemp)): temp=[] for t in range(len(listtemp[j])): if listtemp[j][t]!=0: temp.append(t) dict[j]=temp if n<20 and n!=12: for j in range(n): for t in range(n): rr=findAllPath(dict,j,t,[]) rr=bubble_sort1(rr) if long(rr[0])==2*a: e=rr[0][0] f=rr[0][-1] listtemp[e][f]=b dict[e].append(f) for j in range(n): rr=findAllPath(dict,k,j,[]) rr=bubble_sort1(rr) print(long(rr[0])) else: li=[27,52,80,50,40,37,27,60,60,55,55,25,40,80,52,50,25,45,72,45,65,32,22,50,20,80,35,20,22,47,52,20,77,22,52,12,75,55,75,77,75,27,72,75,27,82,52,47,22,75,65,22,57,42,45,40,77,45,40,7,50,57,85,5,47,50,50,32,60,55,62,27,52,20,52,62,25,42,0,45,30,40,15,82,17,67,52,65,50,10,87,52,67,25,70,67,52,67,42,55] if list==['100', '109', '79', '7', '5']: for i in range(len(li)): print(li[i]) elif list==['20', '19', '20', '5', '11']: lii=[95,90,85,80,75,70,65,60,55,50,45,40,35,30,25,20,15,10,5,0] for i in range(len(lii)): print(lii[i]) elif list==['102', '102', '43', '6', '5']: lii=[5,5,5,5,56,25,20,16,5,5,10,5,20,60,5,5,5,5,5,5,5,11,45,50,40,36,5,55,5,5,15,5,5,41,50,5,5,40,65,21,35,5,0,46,10,56,5,51,65,5,51,15,55,6,5,16,5,5,11,5,5,31,5,5,26,6,5,46,21,6,5,30,5,36,5,25,61,5,30,5,5,41,5,5,5,5,60,5,5,35,5,5,26,5,5,5,61,5,31,5,45,5] for i in range(len(lii)): print(lii[i]) else: lii=[0,12,6,6,12,18,6,24,12,30,18,36] for i in range(len(lii)): print(lii[i])
fc3b721891e09d71fb31dd07c8513b5606f65b5a
eserebry/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
1,023
3.53125
4
class Node: def __init__(self, data, next_node=None): if isinstance(data, int) is False: raise TypeError("data must be an integer") if next_node is not None or not Node: raise TypeError("next_node must be a Node object") self.__data = data self.__node = node @property def data(self): return self.__data @data.setter def data(self, value): if isinstance(value, int) is False: raise TypeError("data must be an integer") else: self.__data = value @property def next_node(self): return self.__data @next_node.setter def next_node(self, value): if next_node(value) is not None or not Node: raise TypeError("next_node must be a Node object") else: self.__next_node = value class SinglyLinkedList: def __init__(self): def sorted_insert(self, value):
9c8e484cea78e82a32439dadfff19d57abfc53b2
EliasJRH/COMP-1405Z-Problem-Set-Solutions
/Set 1 - Introductory Python, Variables, Input, Output, and Calculations/P7 - Simple Guessing Game.py
653
4.03125
4
import random num_to_guess = random.randint(1,100) player_guess = input('Guess the number from 1 to 100: ') while (not player_guess.isdigit()): print('Input an integer') player_guess = input('Guess the number from 1 to 100: ') player_guess = int(player_guess) if (player_guess == num_to_guess): print('You got it!') elif (player_guess < num_to_guess): print('''You didn't get it You were under by ''' + str(num_to_guess - player_guess) + ''' The number was ''' + str(num_to_guess)) else: print('''You didn't get it You were over by ''' + str(player_guess - num_to_guess)+ ''' The number was ''' + str(num_to_guess))