blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
42a0355b4227b2c2d9a724e2dda33caf3865a8c0
ZavalichiR/Backup
/PP/Python/P42vs3.py
1,671
3.921875
4
if __name__ == "__main__": # definim cele 5 stari ale automatului stari = ["0 cents deposited", # starea 0 "5 cents deposited", # starea 1 "10 cents deposited", # starea 2 "15 cents deposited", # starea 3 "20 cents or more deposited" # starea 4 ] # succesiunea starilor in functie de nickel sau dime tranzitii = [ # din starea 0 { "nickel": 1, # cu intrarea "nickel" tranzitez in starea 1 "dime": 2 # cu intrarea "dime" tranzitez in starea 2 }, # din starea 1, etc... { "nickel": 2, "dime": 3 }, { "nickel": 3, "dime": 4 }, { "nickel": 4, "dime": 4 }, { # 4=stare finala "nickel": 1, "dime": 2 # ne intoarcem in starile 1 si 2 } ] # citim starea initiala stare_initiala = input("Stare initiala: ") while stare_initiala not in range(0, 4): stare_initiala = input("Stare initiala: ") stare_curenta = stare_initiala print("Starea curenta este: %s" % stari[stare_curenta]) print("Introduceti valori pentru monedele de introdus in automat: ") while True: val_moneda = input("0 - nickel, 1 - dime, 2 - parasire program ") if val_moneda == 2: break elif val_moneda == 1: stare_curenta = tranzitii[stare_curenta]["dime"] elif val_moneda == 0: stare_curenta = tranzitii[stare_curenta]["nickel"] print("Starea curenta este: %s" % stari[stare_curenta])
ee29ab32f6db958dbaad04828b1fe229ea6b6218
aucan/LeetCode-problems
/199.BinaryTreeRightSideView.py
1,372
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 27 11:44:32 2021 @author: nenad """ """ URL: https://leetcode.com/problems/binary-tree-right-side-view/ Description: Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Example 2: Input: root = [1,null,3] Output: [1,3] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100 """ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import defaultdict class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if root is None: return [] levels = defaultdict(list) queue = [(root, 0)] while len(queue): node, level = queue.pop(0) levels[level].append(node.val) if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) # take the rightmost node at every level return [levels[i][-1] for i in range(level+1)]
35d527ac4401f00ef6e1af37e841a6c36666fd16
Rengga-Setya/Muhammad-Rengga-Setya-Marliansyah-I0320069-Wildan-Tugas3
/I0320069_exercise3.1.py
194
3.65625
4
#Contoh sederhana pembuatan list pada bahasa pemrograman python list1 = ['kimia','fisika',1993,2017] list2 = [1,2,3,4,5,6,7] print("list1[0]: ",list1[0]) print("list2[1:5]: ",list2[1:5])
2e2c96f31e901076750cd65177d848266bb89160
afrancais/euler
/src/problems_30_40/euler_36.py
190
3.515625
4
def palindrome(i): return str(i) == str(i)[::-1] s = 0 for i in range(0, 1000001): b = bin(i)[2:] if palindrome(i) and palindrome(b): print i s += i print s
a828e3b193c68ceeb4503a69e9364f0771a92469
sarcino/music_player
/test.py
894
3.859375
4
from tkinter import * from tkinter import ttk # event types - buttonpress, buttonrelease, enter, leave, motion, keypress, keyrelease, focusin, focusout root = Tk() def key_press(event): print("type: {}".format(event.type)) print("widget: {}".format(event.widget)) print("char: {}".format(event.char)) print("keysym: {}".format(event.keysym)) print("keycode: {}".format(event.keycode)) # bind has two paramenters - event, function callback # root.bind("<KeyPress>", key_press) def shortcut(action): print(action) root.bind("<Control-c>", lambda e: shortcut("Copy")) root.bind("<Control-v>", lambda e: shortcut("Paste")) # combination - keyboard events - <KeyPress-Delete> - user pressed Delete key # <a>, <space>, <less>, <1> - a printable key # <Shift_L>, <Control_R>, <F5>, <Up> # <Return> - for pressing the Enter key!!! # <Control-Alt-Next> root.mainloop()
556ed2a348e99652afa5984f3c58bd4f08f41226
DaniloCoelho/estudos-python
/newfile.py
246
3.8125
4
nome = input('qual seu nome? ' ) if nome == 'lucas': print('bom dia batinta') elif nome == 'davi': print('bom dia bolota') elif nome == 'aline': print('bom dia minha linda') elif nome == 'danilo': print('bom dia papai')
ad75ed0d013e6a56aab0f47d1746303685203d64
hieutran106/leetcode-ht
/leetcode-python/medium/_621_task_scheduler/solution.py
1,023
3.5625
4
from typing import List from collections import Counter, deque import heapq class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: freqs = Counter(tasks) max_heap = [-f for f in freqs.values()] heapq.heapify(max_heap) queue = deque([]) # store [-cnt, time] time = 0 while len(max_heap) or len(queue) > 0: # Look at the queue and see if we can put data to heap if len(queue) > 0: if queue[0][1] <= time: top = queue.popleft() heapq.heappush(max_heap, top[0]) if len(max_heap) ==0: # idle # print("Must idle") time += 1 continue # otherwise, can process a task # get the most frequent item from the heap cnt = 1 + heapq.heappop(max_heap) if cnt < 0 : queue.append((cnt, time + n + 1)) time += 1 return time
9a02b05fc77148188d3d5ad537e202116da066d6
ayshrv/algolab-assignments
/Jarvis Algorithm Graph.py
1,603
3.59375
4
'''input 7 0,3 2,2 1,1 2,1 3,0 0,0 4,4 ''' import numpy as np import matplotlib.pyplot as plt # Jarvis Algorithm hull=[] def orientation(a,b,c): val=(b[1]-a[1])*(c[0]-b[0])-(b[0]-a[0])*(c[1]-b[1]) if val==0: return 0 if val>0: return 1 return 2 def convexHull(p,n): if n<3: return l=0 for i in range(1,n): if(p[i][0]<p[l][0]): l=i a=l while True: hull.append((p[a][0],p[a][1])) b=(a+1)%n for i in range(n): if(orientation(p[a],p[i],p[b])==2): b=i a=b if(a==l): break for i in range(len(hull)): print('('+str(hull[i][0])+','+str(hull[i][1])+')') #Driver Program n=input("Enter the number of points: ") print(n) points=[] print("Enter the points: ") for i in range(n): a,b=map(int,raw_input().split(',')) print(str(i+1)+'.('+str(a)+','+str(b)+')') points.append((a,b)) convexHull(points,n) print(points) print(hull) points=np.array(points) hull=np.array(hull) print(hull[:,0]) print(hull[:,1]) # Plotting Points x_min=min(points[:,0]) x_max=max(points[:,0]) y_min=min(points[:,1]) y_max=max(points[:,1]) x_length=abs(x_max-x_min) y_length=abs(y_max-y_min) # plt.axis([x_min,x_max,y_min,y_max]) plt.axis([x_min-0.1*x_length,x_max+.1*x_length,y_min-.1*y_length,y_max+.1*y_length]) # plt.axis([-5,5,-5,5]) plt.plot(points[:,0],points[:,1],'bo',marker='o',markerfacecolor='green',markersize=6) plt.plot(hull[:,0],hull[:,1],'r-',marker='o',markerfacecolor='black',markersize=8) # plt.plot(hull[:,0],hull[:,1],'r-',markersize=8) plt.plot([hull[0][0],hull[-1][0]],[hull[0][1],hull[-1][1]],'r-',marker='o',markerfacecolor='black',markersize=8) plt.show()
97f1bb1ab1b596fdb6aa14a1c19ce7c6f8214274
yomicchi/smartninja_homework
/homework04/calculator/calculator.py
1,259
4.0625
4
# coding=utf-8 print "╔════════════════════════════════════════════════╗" print "║ Willkommen beim Taschenrechner 2000! ║" print "║ ∧_∧ ║" print "║ /(๑•ω•๑) /\ ║" print "║ /| ̄∪ ∪  ̄|\/ ║" print "║ |__ __ |/ ║" print "╚════════════════════════════════════════════════╝" num1 = float(raw_input("Gib den ersten Wert ein: ")) print num1 num2 = float(raw_input("Gib einen zweiten Wert ein ")) print num2 operation = raw_input("Wähle eine Rechenart aus (+, -, *, /:) ") print operation if operation == "+": print "Das Ergebnis beträgt " + str(num1 + num2) + "." elif operation == "-": print "Das Ergebnis beträgt " + str(num1 - num2) + "." elif operation == "*": print "Das Ergebnis beträgt " + str(num1 * num2) + "." elif operation == "/": print "Das Ergebnis beträgt " + str(num1 / num2) + "." else: print "Du hast keine gültige Rechenart ausgewählt!"
1a20cd39964a1e63e52cef6c15b702129bfe6e91
Dmckinney821/udemy
/DigitalCrafts-04-2018/my_turtle_demo3.py
652
3.59375
4
from turtle import * import random import math # c1 = '#0971B2' # c2 = '#1485CC' bgcolor('black') shape('arrow') speed(10) down() colors = [ '#52067F', '#C058FF', '#A30CFF', '#673F7F', '#830ACC' ] def draw_square(side, p_color): pencolor(p_color) for i in range(4): forward(side) left(90) def draw_circle(p_width, c_width, p_color, f_color): # begin_fill() # fillcolor(f_color) pencolor(p_color) width(p_width) circle(c_width) # end_fill() def main(): input() while True: draw_square(random.randint(1, 300), random.choice(colors)) left(random.randint(1, 360)) # speed(random.randint(0, 10)) main()
61122771947b2e2b8eeeda634104a4afba771194
digital-shokunin/ayn-random
/aynrandom/aynrandom.py
938
3.828125
4
__author__ = 'David Mitchell' import random import genprime def randint(start, stop, numbers=[]): """Returns a random integer between the range of the first two numbers provided as parameters. Optional third parameter can be an array/dictionary of numbers that are "intrinsically better", otherwise, prime numbers are considered intrinsically better. """ if not numbers: for number in genprime.genPrimes(): if number > stop: break elif number > start: numbers.append(number) random.seed() bitwheel = random.random() # roll the big wheel if bitwheel <= 0.01: # Favor the 1%, only they get truly random numbers return random.randint(start, stop) elif bitwheel > 0.01: # the 99% only get the prime (intrinsically better) numbers return numbers[random.randint(0, len(numbers)-1)] if __name__ == '__main__': pass
9108d672d1f043730a7e1c2a48d2847e4ea0bcac
bukovyakp/study_python
/intersect_union.py
259
3.578125
4
def intersect (*args): res = [] for x in args[0]: for other in args[1:]: if x not in other : break else: res.append(x) return res def union (*args): res = [] for part in args: for x in part: if x not in res: res.append(x) return res
2aa7b57bcdebe8017f0b32a636d29df723c450a5
Justmiku/jupiter_assignment
/mrit/order.py
582
3.859375
4
## order class to which requires the user who ordered and the restaurant ## from where the item was ordered and the actual items ordered ## here user,restaurant and items are are object of user , restaurant and items class class Order: def __init__(self, user, restaurant, items): self.user = user self.restaurant = restaurant self.items = items self.status = "Success" ## function to check the status of the order def check_status(self): return self.status ## function to update the status of the order def update_status(self, key): self.status = key
5903f02c7ad31f81feaaaeeae772e228cda06b79
simongarisch/DSH
/test.py
97
3.5
4
def square(a): return a ** a for i in range(6): print("square ", i, "-> ", square(i))
d1e6505c49c3d5f981bef90257449773be230dfa
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_10/try_10.10/try_10.10.py
563
4.1875
4
#Done by Carlos Amaral in 13/07/2020 #Common words def count_common_words(filename): """Count the approximate number of times 'the' is repeated.""" try: with open (filename, encoding='utf-8') as file: contents = file.read() except FileNotFoundError: print(f"Sorry the {filename} you're looking for, does not exist.") else: count_word = contents.lower().count('the') print(f"'The' appears in {filename}, {count_word} times") filename = 'Adventures_Sherlock_Holmes.txt' count_common_words(filename)
c79024a4847f92b8c39d913ec5372f199d181647
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/260/42182/submittedfiles/testes.py
206
3.8125
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO #!/usr/bin/python import math a=3 b=4.5 for i in range (1,13,1): print(x) fx=(-x**3)-math.cos(x) dx=-(3*x**2)+math.sin(x) x=x-(fx)/(dx)
266d59c0ca2b4a56c024867a9734f33699822e19
mahyuan/Front_end_basics
/python_demo/drawSnake.py
410
3.71875
4
import turtle def drawSnake(rad, angle, len, neckrad): for i in range(len): turtle.circle(rad, angle) turtle.circle(-rad, angle) turtle.circle(rad, angle/2) turtle.fd(rad) turtle.circle(neckrad+1, 180) turtle.fd(rad*2/3) def main(): turtle.setup(1300, 800, 0, 0) pythonsize = 30 turtle.pensize(pythonsize) turtle.pencolor("#34fd90") turtle.seth(-40) drawSnake(40, 80, 5, pythonsize/2) main()
fad325d7d8dbb01bf24265d73ca0d6f1a27fa7f6
hxh-robb/robb-learning
/00-Python/google-python-exercises/basic/list1.py
4,387
3.984375
4
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic list exercises # Fill in the code for the functions below. main() is already set up # to call the functions with a few different inputs, # printing 'OK' when each function is correct. # The starter code for each function includes a 'return' # which is just a placeholder for your code. # It's ok if you do not complete all the functions, and there # are some additional functions to try in list2.py. # A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(words): # +++your code here+++ count = 0 for word in words: if len(word) >= 2 and word[0] == word[-1]: count += 1 return count # B. front_x # Given a list of strings, return a list with the strings # in sorted order, except group all the strings that begin with 'x' first. # e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] # Hint: this can be done by making 2 lists and sorting each of them # before combining them. def front_x(words): # +++your code here+++ # return front_x_solution_1(words) # return front_x_solution_2(words) # return front_x_solution_3(words) return front_x_solution_4(words) def front_x_solution_1(words): ''' avoid pylint warning ''' i = 0 while i < len(words) - 1: j = i + 1 while j < len(words): ch_x = words[i][0] ch_y = words[j][0] if (ch_x != 'x' and ch_y == 'x') or \ (((ch_x == 'x' and ch_y == 'x') or (ch_x != 'x' and ch_y != 'x')) and words[i] > words[j]): tmp = words[i] words[i] = words[j] words[j] = tmp j += 1 i += 1 return words def front_x_solution_2(words): ''' avoid pylint warning ''' my_cmp = lambda x, y: ( 0 if x == y else 1 if (x[0] != 'x' and y[0] == 'x') or \ (((x[0] == 'x' and y[0] == 'x') or (x[0] != 'x' and y[0] != 'x')) and x > y) else -1 ) words.sort(cmp=my_cmp) return words def front_x_solution_3(words): ''' avoid pylint warning ''' part_1 = [] part_2 = [] for word in words: if word[0] == 'x': part_1.append(word) else: part_2.append(word) return sorted(part_1) + sorted(part_2) def front_x_solution_4(words): ''' avoid pylint warning ''' # words.sort(key=lambda x: x if len(x) > 0 and x[0] == 'x' else 'y' + x) # return words return sorted(words, key=lambda x: x if x and x[0] == 'x' else 'y' + x) # C. sort_last # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Hint: use a custom key= function to extract the last element form each tuple. def sort_last(tuples): # +++your code here+++ return sorted(tuples, key=lambda x: x[-1]) # Simple provided test() function used in main() to print # what each function returns vs. what it's supposed to return. def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) # Calls the above functions with interesting inputs. def main(): print 'match_ends' test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2) test(match_ends(['aaa', 'be', 'abc', 'hello']), 1) print print 'front_x' test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) print print 'sort_last' test(sort_last([(1, 3), (3, 2), (2, 1)]), [(2, 1), (3, 2), (1, 3)]) test(sort_last([(2, 3), (1, 2), (3, 1)]), [(3, 1), (1, 2), (2, 3)]) test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) if __name__ == '__main__': main()
8e547c293b84b038a4d37b72e40a0e6a9af27063
18d-shady/Python-Projects
/dice roller.py
321
3.78125
4
dec = input("Roll dice????, Y or n : ") dice = list(range(1, 7)) while(True): if dec == 'y': import random d = random.choice(dice) print(d) elif dec == 'n': quit() try: if 'n' in input("Roll more? y or no: "): break except(): pass
51f5b0ddb887cccbff109884a1bc87d69452dc6c
nathanramnath21/Standard-Deviation
/standard-debation/class1.py
552
3.671875
4
import csv with open("class1.csv", newline='') as f: reader=csv.reader(f) file_data=list(reader) #comment file_data.pop(0) total_marks=0 total_entries=len(file_data) for marks in file_data: total_marks+=float(marks[1]) mean=total_marks/total_entries print("The mean is: "+str(mean)) import pandas as pd import plotly.express as px df=pd.read_csv('class1.csv') fig=px.scatter(df, x="Student Number", y="Marks", title="Class 1 Marks") fig.update_layout(shapes=[dict( type='line', y0=mean, y1= mean, x0=0, x1=total_entries )]) fig.show()
ca96a933fe42a93b11ee195f0fd47666ab58a071
Slidda/LearningPython1
/TestPrintScript_Variable.py
412
3.6875
4
# I am a huge dork thingtoprint = "Hello, Dork!" print(thingtoprint) #this'll print "Hello, Dork!" Hopefully. print('This is a "string."') print('''I'm here!''') print('''Here we go go go!''') boringString = "Boooring!" print(boringString) print(len(boringString)) conCatBoom = boringString + "&" + thingtoprint print(conCatBoom) print(thingtoprint, "&", boringString) baZinga = "bazinga" print(baZinga[2:6])
5fd375ffae8ec5c6bfeab8f269f193f48345cdcb
pchung39/py-parser
/algorithms/binary_tree.py
1,136
4.15625
4
# -*- coding: utf-8 -*- class TreeNode(object): def __init__(self, value): self.value = value self.left_node = None self.right_node = None class BinaryTree(object): def __init__(self): self.root = None def get_left_node(self): return(self.left_node) def get_right_node(self): return(self.right_node) def add(self,value): if self.root == None: self.root = TreeNode(value) else: def insert_left(self, node): if self.left_node == None: self.left_node = TreeNode(node) else: new_node = TreeNode(node) new_node.left_node = self.left_node self.left_node = new_node.left_node def insert_right(self, node): if self.right_node == None: self.right_node = TreeNode(node) else: new_node = TreeNode(node) new_node.right_node = self.right_node self.right_node = new_node.right_node tree = BinaryTree() t = TreeNode('a') tree.insert_left('b') print(t.left_node) tree.insert_right('c') print(t.right_node)
3fd2037d3ab49460c0f312c1e466b1148d7e6013
mdflood-developer/d20_dice_dissector
/dice_utility.py
1,658
3.609375
4
# String parser for dice values in pen and paper RPGs like Pathfinder and Dungeons & Dragons. # Takes a value like '4d8+2' (which means, in game terms "Roll four eight-sided dice and add two to the final result") # and returns the values as individual integers in a dictionary # Also includes functions to roll the dice returned from diceDissector import random def diceDissector(dice_roll_value): dstring = dice_roll_value dstring_num = int(dstring.split('d')[0]) dstring_dice = dstring.split('d')[1] if '+' in dstring_dice: dstring_mult = int(dstring_dice.split('+')[0]) dstring_bonus = int(dstring_dice.split('+')[1]) elif '-' in dstring_dice: dstring_mult = int(dstring_dice.split('-')[0]) dstring_bonus = int(dstring_dice.split('-')[1]) dstring_bonus = -dstring_bonus else: dstring_mult = int(dstring_dice) dstring_bonus = 0 roll_low = (dstring_num * 1) + dstring_bonus roll_high = (dstring_num * dstring_mult) + dstring_bonus dicevalue = { 'dice':dstring, 'num_dice':(dstring_num), 'num_value':(dstring_mult), 'num_bonus':(dstring_bonus), 'high':roll_low, 'low':roll_high } return dicevalue def rollDice(dicedata): dice_to_roll = dicedata['num_dice'] value_of_dice = dicedata['num_value'] bonus_to_add = dicedata['num_bonus'] total = 0 for i in range(0,dice_to_roll): diceroll = random.randint(0,value_of_dice) total += diceroll total += bonus_to_add if total < 0: total = 0 return total
d9f015176240e6b444e0706b8f92c88eacce1061
ingmarcomaop/algorithms
/between-two-sets.py
864
3.5
4
#Between Two Sets def getTotalX(a, b): last_a = a[len(a) - 1] first_b = b[0] array = [x for x in range(last_a, first_b + 1)] #print(str(array)) numbers = 0 aux = 0 for i in range(0, len(array)): aux = 1 for j in range(0, len(a)): #print(str(array[i]) + " % " + str(a[j])) if array[i] % a[j] != 0: aux = 0 else: continue for j in range(0, len(b)): if b[j] % array[i] != 0: aux = 0 else: continue if aux == 1: numbers += 1 else: continue return numbers print(str(numbers)) #print(str(array_b)) a = [2, 6] b = [24, 36] test = getTotalX(a, b) print(test)
eaac222feec500caab9a10a76a0a7dc6f6108a62
seetusharma/Python-Basic-Programmes
/HCF_OF_TWO_NUMBER.py
264
4.0625
4
num1=int(input("Enter first number: ")) num2=int(input("Enter second number: ")) num3=int(input("Enter second number: ")) i=2 gcd=0 while i<=num1 and i<=num2 and i<=num3: if num1%i==0 and num2%i==0 and num3%i==0: gcd=i i=i+1 print(gcd)
328b17bc68ccbe85cc8e5125c1a6edc5e7c1b2a3
jackHorwell/automatedChessBoard
/main.py
13,828
3.5
4
# Imports modules to control raspberry pi GPIO import RPi.GPIO as GPIO import time import charlieplexing # Sets up Stockfish engine from stockfish import Stockfish stockfish = Stockfish("/home/pi/Downloads/a-stockf") stockfish = Stockfish(parameters={"Threads": 2, "Minimum Thinking Time": 30}) stockfish.set_skill_level(1) # 97 is the ASCII code for a, using this we can reduce this down to a numeric form asciiA = 97 # Class to store piece attributes like colour and type class Piece: def __init__(self, colour, pieceType, icon): self.colour = colour self.pieceType = pieceType self.icon = icon # Class to group together piece initialisation class Pieces: def initialisePieces(self): # Initalises the piece objects and passes their attributes self.wp = Piece("white", "pawn", "♙") self.wr = Piece("white", "rook", "♖") self.wkn = Piece("white", "knight", "♞") self.wb = Piece("white", "bishop", "♗") self.wq = Piece("white", "queen", "♕") self.wk = Piece("white", "king", "♔") self.bp = Piece("black", "pawn", "♟") self.br = Piece("black", "rook", "♜") self.bkn = Piece("black", "knight", "♞") self.bb = Piece("black", "bishop", "♝") self.bq = Piece("black", "queen", "♛") self.bk = Piece("black", "king", "♚") # Class to store the current state and last known legal state of the board class BoardRecord: def __init__(self, p): # Stack to store previous move self.previousMoves = [] # Dictionaries linking the name of a piece with its object self.whitePieceObjects = {"q": p.wq, "k": p.wk, "r": p.wr, "n": p.wkn, "b": p.wb, "p": p.wp} self.blackPieceObjects = {"q": p.bq, "k": p.bk, "r": p.br, "n": p.bkn, "b": p.bb, "p": p.bp} # Creates a 2D array to store piece locations self.board = [[p.wr,p.wkn,p.wb,p.wq,p.wk,p.wb,p.wkn,p.wr], [p.wp,p.wp,p.wp,p.wp,p.wp,p.wp,p.wp,p.wp], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [p.bp,p.bp,p.bp,p.bp,p.bp,p.bp,p.bp,p.bp], [p.br,p.bkn,p.bb,p.bq,p.bk,p.bb,p.bkn,p.br]] # Getter for board variable def getBoard(self): # Prints each row and converts objects into their assigned icons for row in range(7, -1, -1): rowToPrint = [] for square in self.board[row]: if square != 0: rowToPrint.append(square.icon) else: rowToPrint.append("0 ") print("".join(rowToPrint)) return self.board # Setter for board variable # Takes two coordinates and moves a piece to it's new position def setBoard(self, pieceFrom, pieceTo, move): self.board[pieceTo[1]][pieceTo[0]] = self.board[pieceFrom[1]][pieceFrom[0]] self.board[pieceFrom[1]][pieceFrom[0]] = 0 # Adds move made to the previousMoves array if move != "castle": self.previousMoves.append(move) # Updates the moves made for the engine stockfish.set_position(self.previousMoves) # Function to change a piece type on the board def promotePiece(self, position, colour, promoteTo): if colour == "w": self.board[position[1]][position[0]] = self.whitePieceObjects[promoteTo] elif colour == "b": self.board[position[1]][position[0]] = self.blackPieceObjects[promoteTo] # Stores the pin numbers used for the rows and columns # Index + 1 is the row number rowPins = [23, 18, 11, 9, 10, 22, 27, 17] columnPins = [21, 20, 16, 12, 7, 8, 25, 24] # Sets the pins to be inputs or outputs def pinSetup(): GPIO.setmode(GPIO.BCM) for pin in rowPins: GPIO.setup(pin, GPIO.OUT) for pin in columnPins: GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # Function to turn off all the row pins to make sure none are accidently left on def resetRowPins(): for pin in rowPins: GPIO.output(pin, 0) # Function to return the position of pieces in a 2D array def scanCurrentBoard(): board = [] # Provides power to rows one by one and checks columns for input # Stores the output to board array for row in range(8): board.append([]) GPIO.output(rowPins[row], 1) for column in range(8): board[row].append(GPIO.input(columnPins[column])) GPIO.output(rowPins[row], 0) return board ''' Used for development purposes, delete in final ''' for i in range(7, -1, -1): print(" ".join(map(str,board[i]))) print("\n\n") # Takes the current state of the board and repeatedly checks # for a change. Once found will return the position of the change # Takes an optional paramater if we are checking for movement to a square # to prevent the piece being detected twice """ Could optimise with wait for edge? """ def reportChange(moveFrom = None): resetRowPins() oldBoard = scanCurrentBoard() while True: newBoard = scanCurrentBoard() if newBoard != oldBoard: for row in range(8): if newBoard[row] != oldBoard[row]: for column in range(8): if newBoard[row][column] != oldBoard[row][column]: if moveFrom != [column, row]: resetRowPins() return [column, row] # Function that waits for a square to turn from on to off def detectFallingAtPosition(coordinates): GPIO.output(rowPins[coordinates[1]], 1) GPIO.add_event_detect(columnPins[coordinates[0]], GPIO.FALLING) numberRows = [8, 7, 6, 5, 4, 3, 2, 1] numberCols = [9, 10, 11, 12, 13, 14, 15, 16] while True: # Lights up position charlieplexing.turnOn(numberRows[coordinates[1]]) charlieplexing.turnOn(numberCols[coordinates[0]]) # Breaks loop once piece is picked up if GPIO.event_detected(columnPins[coordinates[0]]): GPIO.remove_event_detect(columnPins[coordinates[0]]) charlieplexing.turnOn(0) break #GPIO.wait_for_edge(columnPins[coordinates[0]], GPIO.FALLING) GPIO.output(rowPins[coordinates[1]], 0) # Function that waits for a square to turn from off to on def detectRisingAtPosition(coordinates): GPIO.output(rowPins[coordinates[1]], 1) GPIO.add_event_detect(columnPins[coordinates[0]], GPIO.RISING) numberRows = [8, 7, 6, 5, 4, 3, 2, 1] numberCols = [9, 10, 11, 12, 13, 14, 15, 16] while True: # Lights up position charlieplexing.turnOn(numberRows[coordinates[1]]) charlieplexing.turnOn(numberCols[coordinates[0]]) # Breaks loop once piece is placed down if GPIO.event_detected(columnPins[coordinates[0]]): GPIO.remove_event_detect(columnPins[coordinates[0]]) charlieplexing.turnOn(0) break #GPIO.wait_for_edge(columnPins[coordinates[0]], GPIO.FALLING) GPIO.output(rowPins[coordinates[1]], 0) # Will return True if there is currently a piece at the given coordinates def isOccupied(coordinates): board = currentBoard.getBoard() if board[coordinates[1]][coordinates[0]] != 0: return True else: return False # Function to take a move generated by the computer # and update the board if there has been a promotion def checkForPromotion(move, toMove): if len(move) == 5: currentBoard.promotePiece(toMove, computerColour, move[-1]) print(f"Piece is now {move[-1]}") # Function to determine if a player can promote a piece, if true then # the player is asked to which piece he would like to promote # Input is then returned def checkForPromotionOpportunity(moveTo, moveFrom): board = currentBoard.getBoard() promoteTo = "" # Checks for white pawns in black back line if moveTo[1] == 7 and board[moveFrom[1]][moveFrom[0]].pieceType == "pawn": promoteTo = input("What would you like to promote to: ") # Checks for black pawns in white back line if moveTo[1] == 0 and board[moveFrom[1]][moveFrom[0]].pieceType == "pawn": promoteTo = input("What would you like to promote to: ") # If promotion is not available then "" is returned return promoteTo # Function to detect if AI or player has castled and tells the user to move the castle def checkForCastle(move, fromMove): board = currentBoard.getBoard() if board[fromMove[1]][fromMove[0]].pieceType == "king": # Detects which castling move has been made and moves castle if move == "e1c1": currentBoard.setBoard([0, 0], [3, 0], "castle") moveComputerPieces([0, 0], [3, 0], "a1c1") elif move == "e1g1": currentBoard.setBoard([7, 0], [5, 0], "castle") moveComputerPieces([7, 0], [5, 0], "h1f1") elif move == "e8c8": currentBoard.setBoard([0, 7], [3, 7], "castle") moveComputerPieces([0, 7], [3, 7], "a8c8") elif move == "e8g8": currentBoard.setBoard([7, 7], [5, 7], "castle") moveComputerPieces([7, 7], [5, 7], "h8f8") # Function to make sure that the pieces are where they're meant to be # Recursively calls itself until all pieces are in the correct position def checkBoardIsLegal(): board = currentBoard.getBoard() for row in range(8): resetRowPins() GPIO.output(rowPins[row], 1) for column in range(8): # First checks for pieces where no pieces should be if board[row][column] == 0 and GPIO.input(columnPins[column]) == 1: print(f"Remove piece from: {convertToChessNotation([column, row])}") detectFallingAtPosition([column, row]) resetRowPins() checkBoardIsLegal() return # Then checks for empty spaces where pieces should be elif board[row][column] != 0 and GPIO.input(columnPins[column]) == 0: print(f"Place {board[row][column].colour.capitalize()} {board[row][column].pieceType.capitalize()} on {convertToChessNotation([column, row])}") detectRisingAtPosition([column, row]) resetRowPins() checkBoardIsLegal() return resetRowPins() # Function to tell player where to move pieces def moveComputerPieces(moveFrom, moveTo, move): # Tells user which piece to pick up, checks for piece removal print(f"Move piece from {move[0:2]}") detectFallingAtPosition(moveFrom) # Checks if moveTo position is already occupied, if so tells user to remove it if isOccupied(moveTo): print(f"Remove piece from {move[2:]}") detectFallingAtPosition(moveTo) # Tells user where to move piece print(f"Move piece to {move[2:]}") detectRisingAtPosition(moveTo) print("Thank you!") resetRowPins() # Function to convert move to chess notation (for Stockfish) # Example: "a2" def convertToChessNotation(move): return chr(ord('a') + move[0]) + str(move[1] + 1) # Function to convert chess notation to move # Example: [1, 1] def convertToMove(chessNotation): return [ord(chessNotation[0]) - asciiA, int(chessNotation[1]) - 1] # Function to obtain the move a player makes def getPlayerMove(): moveFrom = reportChange() print(f"From: {moveFrom}") moveTo = reportChange(moveFrom) print(f"To {moveTo}") # Checks if a pawn can be promoted promotion = checkForPromotionOpportunity(moveTo, moveFrom) if isOccupied(moveTo): print("Place down piece") detectRisingAtPosition(moveTo) # Adds the from move, to move and promotion if available so the AI can understand it move = convertToChessNotation(moveFrom) + convertToChessNotation(moveTo) + promotion # Checks if player has castled checkForCastle(move, moveFrom) if stockfish.is_move_correct(move): print("legal shmegle") currentBoard.setBoard(moveFrom, moveTo, move) # If player has promoted a piece then board is updated if promotion != "": promotePiece(moveTo, playerColour, promotion) currentBoard.getBoard() else: print("Not a legal move") charlieplexing.allFlash() checkBoardIsLegal() getPlayerMove() return # Function to get the AI to generate a move def generateMove(): move = stockfish.get_best_move() # Splits move into where it's moving from and where it's moving to # Converts letters into their corresponding alphabet # Both arrays have: column then row fromMove = convertToMove(move[0:2]) toMove = convertToMove(move[2:4]) moveComputerPieces(fromMove, toMove, move) # Checks if player has castled checkForCastle(move, fromMove) # Updates board currentBoard.setBoard(fromMove, toMove, move) checkForPromotion(move, toMove) p = Pieces() p.initialisePieces() currentBoard = BoardRecord(p) computerColour = "b" playerColour = "w" pinSetup() m = input("") resetRowPins() checkBoardIsLegal() while True: getPlayerMove() checkBoardIsLegal() evaluation = stockfish.get_evaluation() print(evaluation) if evaluation["type"] == 'mate' and evaluation["value"] == 0: while True: charlieplexing.slide("fast") generateMove() checkBoardIsLegal() evaluation = stockfish.get_evaluation() print(evaluation) if evaluation["type"] == 'mate' and evaluation["value"] == 0: while True: charlieplexing.slide("fast")
329d06bab63755a4bab1299db5411a81f4c08763
LawrenceJu1/Digitera
/houzz_scraper.py
670
3.546875
4
from bs4 import BeautifulSoup from selenium import webdriver from houzz_job_scraper import job_scraper #opening the webdriver and the houzz.com page with each profession webdriver = webdriver.Chrome(executable_path = "chromedriver.exe") webdriver.get("https://www.houzz.com/professionals") #finds the url to each profession using beautifulsoup page_soup = BeautifulSoup(webdriver.page_source, "html.parser") urls = page_soup.findAll("a", {"class":"spf-link hz-color-link hz-color-link--black hz-color-link--enabled"}) #loops through each profession, creating a .csv file for each one for url in urls: url = url["href"] job = url[36:] job_scraper(job, url)
2b25989049f1e6eef57fdde70f734506fccbf406
Pratham82/Python-Programming
/HackerRank/Practice/Basic Data types/Finding the percentage.py
632
3.765625
4
""" Finding the percentage Input: 3 Krishna 67 68 69 Arjun 70 98 63 Malika 52 56 60 Malika Output: 56.00 Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.1 """ from functools import reduce if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() required_arr = student_marks[query_name] op = format( reduce(lambda a, b: a + b, required_arr) / len(required_arr), '.2f') print(op)
a24fd83b0c997e21e239b5916d54e5b40f4f978d
archenRen/learnpy
/aoc2018/day15/part1.py
1,674
3.5
4
class Unit: def __init__(self, gender, loc, hp): self.gender = gender self.loc = loc self.hp = hp def in_range_nodes(self, graph): x, y = self.loc nodes = [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)] return [node for node in nodes if graph[node] == "."] def find_enemy(self, graph, units): for target in units: if self.gender == target.gender: continue target.in_range_nodes(graph) class Solution: def __init__(self): self.graph, self.height, self.width = self.make_graph() self.units = self.init_units() def make_graph(self): with open("inputtest") as f: graph = {} j = 0 width = 0 for line in f.readlines(): width = len(line.strip("\n")) for i, s in enumerate(line.strip("\n")): graph[(i, j)] = s j += 1 return graph, j, width def init_units(self): units = [] for loc, v in self.graph.items(): if v == "G": units.append(Unit("G", loc, 200)) elif v == "E": units.append(Unit("E", loc, 200)) return sorted(self.units, key=lambda x: (x[1], x[0])) def solve(self): ticks = 0 while True: # if all(G) or all(E): # break for unit in self.units: if unit.hp < 0: continue unit.find_enemy(self.graph, self.units) if __name__ == '__main__': s = Solution() s.solve() print("ok") import string
621695b6ae61f0c3861d6f6a404fbb9293f6c234
patrickr012/CP1404
/Projects/Week One/Pracs/loops.py
418
3.859375
4
""" CP1404 - Week One Loops A program designed to test the functionality of various loops. Patrick Robinson - 12251568 """ for i in range(1, 21, 2): print(i, end=" ") print() for i in range(0 , 100, 10): print(i, end=" ") print() for i in range(20, 1, -1): print(i, end=" ") print() stars = int(input("Please enter the amount of stars")) for i in range(1, stars+1, 1): print("*" * i, end="\n") print()
4cafb5674d7402c262b258129da1f00270af33c6
CarlosArro2001/Little-Book-of-Programming-Problems-Python-Edition
/HelloName.py
358
4.34375
4
#... #Aim : Write a program that will ask you your name .It will then display "Hello name" where name is the name you have entered. #Author : Carlos Raniel Ariate Arro #Date : 06-09-2019 #... #Asking the user the name . print("What is your name :") #Waiting for the input of the user. x = input() #Displaying "Hello " then the name. print("Hello " + x)
32de27bf482dd756e5c057b5135de4755e7257d2
idixon2/csc221
/project/test_final_project.doctest.py
397
3.890625
4
''' >>> def is_leap_year(1996): if (year % 4 == 0): print("is a Leap Year.", 1996); return True else: if (year % 100 == 0): print("is not a Leap Year.", 1990); return False else: if (year % 400 == 0): print("is a Leap Year.", 1996); return True ''' if __name__ == "__main__": import doctest doctest.testmod()
1aaf32b16f6f340d520bf2c58e9343d7ad8a18ec
famalhaut/ProjectEuler
/problems_40s/problem_41.py
884
3.859375
4
""" Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? """ from common.primes import miller_rabin_test from itertools import permutations def problem(): max_prime = 0 flag = False # 1 + 2 + ... + 9 = 45, 45 % 3 => 9-digit pandigital is not prime. for pw in range(8, 0, -1): for permut in permutations(range(1, pw + 1)): num = 0 for i in permut: num *= 10 num += i if miller_rabin_test(num): max_prime = max(max_prime, num) flag = True if flag: break return max_prime if __name__ == '__main__': print('Answer:', problem())
420054a82221eebea9dded02de1288851255c13e
ewelkaw/advent_of_code
/ad_5.py
2,271
4.375
4
# --- Day 5: A Maze of Twisty Trampolines, All Alike --- # An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions, and it would like assistance from any programs with spare cycles to help find the exit. # The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. # In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. # For example, consider the following list of jump offsets: # 0 # 3 # 0 # 1 # -3 # Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found: # (0) 3 0 1 -3 - before we have taken any steps. # (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1. # 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2. # 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind. # 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2. # 2 5 0 1 -2 - jump 4 steps forward, escaping the maze. # In this example, the exit is reached in 5 steps. # How many steps does it take to reach the exit? def open_file(): with open(os.path.join("/Users/ewelina/Documents/AC","ad_5_data.txt")) as f: input = f.readlines() input = list(map((lambda x: int(x.replace("\n", ""))), input)) return input def find_counter(input): n = len(input) counter = 0 offset = 0 old_index = 0 index = 0 while index < n: counter += 1 offset = input[index] old_index = index index += offset input[old_index] += 1 return counter a = find_counter(input) ### ANSWER ### # 354121 #
1c7273f93ee997f572d0e8b32bb1bd97ff083d8e
khristovv/Solututions-Programming-101-HackBulgaria-2019
/Week02/Day2Terminal/reduce_file_path.py
486
3.53125
4
# reduce_file_path.py import sys def get_args(): return sys.argv[1] def reduce_file_path(path): reduced_path = [] for ch in path.split('/'): if ch == '..' and reduced_path: reduced_path.pop() elif ch != '' and ch != '.' and ch != '..': reduced_path.append('/' + ch) return ''.join(reduced_path) if reduced_path else '/' def main(): path = get_args() print(reduce_file_path(path)) if __name__ == '__main__': main()
686190977f9a775b8baf96eaf7123fb4e424ad2b
RobertCurry0216/AoC
/2018/day11.py
1,467
3.640625
4
def get_power(x, y, serial): """" Get the power level for a given fuel cell """ if x == 0 or y == 0: return 0 _id = x + 10 power = _id * y + serial power *= _id power = (power // 100) % 10 return power - 5 def max_nxn(grid, n): """ return the max value for a nxn section of a given grid """ _max = 0 _max_point = None for y in range(1, 301 - n): for x in range(1, 301 - n): A = grid[y][x] B = grid[y][x+n] C = grid[y+n][x] D = grid[y+n][x+n] total = A + D - B - C if total > _max: _max = total _max_point = (x+1, y+1) return _max_point, _max def partial_sum_table(): """ generate a partial sum table """ grid_serial = 6303 sum_grid = [[0 for _ in range(301)] for __ in range(301)] for y in range(1, 301): for x in range(1, 301): sum_grid[y][x] = get_power(x, y, grid_serial) \ + sum_grid[y-1][x] \ + sum_grid[y][x - 1] \ - sum_grid[y - 1][x - 1] return sum_grid if __name__ == '__main__': grid = partial_sum_table() max_v = 0 max_p = 0 max_n = 0 for n in range(3, 301): p, v = max_nxn(grid, n) if v > max_v: max_v = v max_p = p max_n = n print(f'loop {n} of 300') print(max_p, max_n)
d42fcc3d7dc736ea8761d30bd2ba6d5940f6dde7
bluepine/topcoder
/algortihms_challenges-master/general/subsegment.py
1,788
4.0625
4
""" solution to subsegmenting problem Questions to ask interviewer: 1. what if the input string is already a word? 2. should I only consider segmentation into two words? - look at first solution 3. what if input string cannot be segmented? 4. what about spelling correction? 5. what if there are multiple valid segmentations? 6. what operations does dictionary support? 7. how big is the dictionary? """ dictionary = {} def initialize_dictionary(): with open('/usr/share/dict/words', 'r') as f: for word in f: word = word.strip() if len(word) > 0 and not dictionary.has_key(word): dictionary[word] = None # simplest solution - segmentation only into two words def subsegment_simple(string): if string is None or len(string) < 1: return False # situation when the input string is already a word if dictionary.has_key(string): return string for i in xrange(len(string)): prefix = string[: i+1] if dictionary.has_key(prefix): sufix = string[i+1 :] if dictionary.has_key(sufix): return prefix + " " + sufix return False # general solution - recursive O(2^n) def subsegment_general(string): if string is None or len(string) < 1: return None # stop when sting is a word if dictionary.has_key(string): return string # iterate for i in xrange(len(string)): prefix = string[ : i+1] if dictionary.has_key(prefix): sufix = string[i+1 :] sub_sufix = subsegment_general(sufix) if sub_sufix != None: return prefix + " " + sub_sufix initialize_dictionary() print subsegment_simple('peanutbutter') print subsegment_general('peanutbutter')
b4f0642695728e65f72f25eb1bde460a8974dbe5
Abhinittiwari7/SigPython_Task
/Module_6/dictionary.py
63
3.515625
4
A=dict() for x in range(1,11): A[x]=x**2 print(A)
8a567d174a58f017842e4c3c36c9a10e427f2dd8
pythonmentor/gokan-p3
/ressourcepy/affichage.py
961
3.640625
4
class Affichage: def __init__(self, labyrinthe, hero): self.labyrinthe = labyrinthe self.hero = hero def afficher(self): for y in range(15): for x in range(15): if (x, y) == self.hero.position: print("H", end="") elif (x, y) in self.labyrinthe.chemins: print(" ", end="") if (x, y) in self.labyrinthe.murs: print("*", end="") print() print() def test(): labyrinthe = Labyrinthe() labyrinthe.charger_structure() hero = Hero(labyrinthe) affichage = Affichage(labyrinthe, hero) while True: affichage.afficher() choix = input("Ou voulez-vous aller? ") if choix in ("haut", "bas", "gauche", "droite"): hero.move(getattr(directions, choix)) elif choix == "quitter": break if __name__ == "__main__": test()
d5bdb4fb163f169fd0832bb6c6edfba7192407e6
DiOsTvE/Python
/12 - ejer12.py
3,743
4.125
4
""" Ingresar 5 números y decir si son múltiplos de 3 o no. """ """ for i in range(5): numero = int(input(f"Ingresa el número {i}: ")) if(numero % 3)==0: print("Es múltiplo de 3") else: print("No es múltiplo de 3") """ """ Ingresar 10 números enteros y contar cuántos de esos números son distintos de 0. """ """ acum = 0 for i in range(10): numero = int(input(f"Ingresa el número {i}: ")) if(numero != 0): acum = acum + 1 print("La cantidad de números enteros distintos de 0 son: ") print(acum) """ """ Realice un programa que muestre una cuenta regresiva desde el 20 al 0. """ """ for i in range(20,-1,-1): print(i) """ """ Realice un programa donde se ingresen una cantidad de compras diarias y se muestre el total facturado ese día. """ """ total = 0 importe = 0 compras = int(input("Cuantas compras has realizado en el día: ")) for i in range(compras): importe = float(input(f"Inserta el importe de la compra {i+1}: ")) total = total + importe print("El total facturado en el día es: ") print(total) """ """ Realice un programa que solicite los lados de 5 triángulos y especifique qué tipo de triangulo es cada uno de ellos """ """ aux = 0 aux2 = 0 cuenta = 1 lado = 0 for i in range(3): while lado == 0: lado = float(input(f"Introduce el lado {i+1}: ")) if lado == 0: print("Valor no válido.") if aux == 0: aux = lado elif aux == lado: cuenta = cuenta + 1 aux2 = lado elif aux == lado or aux2 == lado: cuenta = cuenta + 1 lado=0 if cuenta == 1: print("El triangulo es escaleno") elif cuenta == 2: print("El triangulo es isosceles") elif cuenta == 3: print("El triangulo es equilatero") else: print("No es un triangulo") """ """ Realice un programa que escriba la tabla de multiplicar de un número ingresado por el usuario. También debe indicar el inicio y el fin de la tabla. """ """ numero = int(input("Introduce un número para mostrar su tabla de multiplicar: ")) print("La tabla de multiplicar del", numero) for i in range(11): print(numero,"*",i,"=",i*numero) print("Fin de la tabla de multiplicar del", numero) """ """ Desarrollar un programa que muestre la tabla del 5 (del 5 al 50) """ """ print("La tabla de multiplicar del 5") for i in range(11): print("5 *",i,"=",i*5) print("Fin de la tabla de multiplicar del 5") """ """ Se desea obtener una serie de promedios partiendo de: a - Las notas de 5 estudiantes de física. b - Las notas de 7 estudiantes de programación. c - Las notas de 8 estudiantes de medicina. Se debe: Obtener el promedio de notas por cada carrera y mostrar cual es la carrera que presenta mejor promedio. """ prom_fis = 0 nota = 0 for i in range(5): nota = float(input(f"Introduce la nota {i+1} de física: ")) prom_fis = prom_fis + nota prom_fis = prom_fis / 5 print("La nota media de física es: ",prom_fis) prom_pro = 0 nota = 0 for i in range(7): nota = float(input(f"Introduce la nota {i+1} de programación: ")) prom_pro = prom_pro + nota prom_pro = prom_pro / 7 print("La nota media de programación es: ",prom_pro) prom_med = 0 nota = 0 for i in range(8): nota = float(input(f"Introduce la nota {i+1} de medicina: ")) prom_med = prom_med + nota prom_med = prom_med / 8 print("La nota media de medicina es: ",prom_med) if prom_fis > prom_pro and prom_fis > prom_med: print("La carrera con mejor promedio es Física, con una nota media de ",prom_fis) elif prom_pro > prom_fis and prom_pro > prom_med: print("La carrera con mejor promedio es Programación, con una nota media de ",prom_pro) else: print("La carrera con mejor promedio es Medicina, con una nota media de ",prom_med)
9d720ee93f375323828ce294c028bc388680f7e3
reivajlow/ayudantia
/ayudantia progamacion/clase1/ejercicios/ex6.py
407
4.125
4
""" Definir una función inversa() que calcule la inversión de una cadena. Por ejemplo la cadena "estoy probando" debería devolver la cadena "odnaborp yotse" """ def inversa(cadena): largo = len(cadena) ultimo = cadena[largo - 1] ultimo2 = cadena[-1] for i in range(largo - 1, -1, -1): print(cadena[i], end="") return if __name__ == "__main__": inversa([1,2,3,4,5])
2a45b8f146c70af9967b203c4cc587a0bdc801a2
nakayamaqs/PythonModule
/Learning/func_return.py
1,354
4.3125
4
# from :http://docs.python.org/3.3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters # By returning a tuple of the results: def func2(a, b): a = 'new-value' # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = 'old-value', 99 x, y = func2(x, y) print(x, y) # output: new-value 100 # By passing a mutable (changeable in-place) object: def func1(a): a[0] = 'new-value' # 'a' references a mutable list a[1] = a[1] + 1 # changes a shared object args = ['old-value', 99] func1(args) print(args[0], args[1]) # output: new-value 100 # By passing in a dictionary that gets mutated: def func3(args): args['a'] = 'new-value' # args is a mutable dictionary args['b'] = args['b'] + 1 # change it in-place args = {'a':' old-value', 'b': 99} func3(args) print(args['a'], args['b']) # Or bundle up values in a class instance: class callByRef: def __init__(self, **args): for (key, value) in args.items(): setattr(self, key, value) def func4(args): args.a = 'new-value by func4.' # args is a mutable callByRef args.b = args.b + 100 # change object in-place args = callByRef(a='old-value', b=99,c=23) func4(args) print(args.a, args.b, args.c)
15283c3d51a9232781ff7454c5bc6972164e07cc
cmobrien123/Python-for-Everybody-Courses-1-through-4
/Ch6Notes.py
1,976
4.125
4
# fruit = 'banana' # # # index = 5 # # # # while index>=0: # # letter = fruit[index] # # print(letter) # # index = index -1 # # print('done') # # # print(fruit[:]) # # # # # # # # # # def count(Letter, word): # # count = 0 # # for x in word: # # if x == Letter: # # count = count + 1 # # print(count) # # # # count('a', fruit) # # # print(test) # # k=fruit.upper() # # print(k,'!') # line = 'Have a nice day' # print(line.startswith('h')) # print(line) data ='From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' a = data.find('@') print(a) s= data.find(' ',a) ## find the first ' ' after the @ (weridly they have the ' 'first) print(s) host = data[a+1:s] print(host) # camels = 42 # x= '%d' % camels # # print(x) # print(type(x)) # print(type(camels)) # # y= 'I have seen over %d camels' %camels # print(y) ## you need the %camels at the end of this in order for it to work # # t = 'In %d years I have seen %g %s.' % (3,0.1,'camels') # print(t) ### %d is integer ### %g is float ### %s is string # st1 = 'hi' # st2 = 'there' # st3 = st1+" "+st2 # print(st3) # pi = st1[1] # # print(pi) # # # # # fruit = 'banana' # # # # # # index = 0 # while index < len(fruit): # x = fruit[index] # print(x) # index = index+1 # print('done!') # # # # for letter in fruit: # # print(letter) # ## this is more elegant, aka shorter and easier to follow/less mistakes # # count= 0 # for x in fruit: # if x == 'a': # count= count+1 # print(count) # # s = 'Monty Python' # ' # print(s[0:5]) # print(s[6:]) # print(s[6:10000]) # print(s[1:2])' ##note that the afer the : is up to but no including # print(e) # ## Z>a # greet = 'Hello Bob' # zap = greet.lower() # # print(zap) # # print('HI There'.lower()) # # t= dir(zap) # print(t) ## better to have a copy of the string library on you # o =fruit.find('na') # print(o) # s = 'Monty Python ' # # print(s) # # x = s.lstrip() # # print(x) # # x= s.startswith('M') # print(x)
8689b7fdd9bac0c6ee718dc61267cad81f540862
ktisha/study
/Stanford-algo/algo/2/quick_sort.py
1,168
3.703125
4
__author__ = 'catherine' comparisons = 0 def get_data(name): my_file = file(name) data = [] for x in my_file.readlines(): data.append(int(x)) return data def swap(data, i, j): data[i], data[j] = data[j], data[i] def partition(data, left, right, pivot): swap(data, left, pivot) p = data[left] i = left + 1 for j in xrange(left + 1, right): if data[j] < p: data[i], data[j] = data[j], data[i] i += 1 data[i-1], data[left] = data[left], data[i-1] return i-1 def pick_pivot(data, left, right): middle = left + (right - left - 1) / 2 m = [(left, data[left]), (right - 1, data[right - 1]), (middle, data[middle])] m = sorted(m, key=lambda x: x[1]) return m[1][0] #return left #return right - 1 def quick_sort(data, left, right): if right - left <= 1: return 0 pivot = pick_pivot(data, left, right) index = partition(data, left, right, pivot) count = right - left - 1 # print index count += quick_sort(data, left, index) count += quick_sort(data, index+1, right) return count if __name__ == "__main__": data = get_data("array.txt") count = quick_sort(data, 0, len(data)) print count
c0a3100eb8423aae5ca6af4aa00791596fa29aab
RomuloKennedy/pythonFIAP
/Capitulo4_Dicionarios/Tupla.py
556
4.0625
4
ips={} resp = "S" while resp == "S": ips[(input("Digite os dois primeiros octetos: "), input("Digite os dois últimos octetos: "))]=input("Nome da máquina: ") resp=input("Digite <S> para continuar: ").upper() print("Exibindo os ip's: ") for ip in ips.keys(): print(ip[0]+"."+ip[1]) print("Exibindo Máquinas no mesmo endereço: ") pesquisa=input("Digite os dois últimos octetos: ") for ip,nome in ips.items(): print("Máquinas no mesmo endereço (redes diferentes)") if (ip[1]==pesquisa): print(nome)
d235e2863cda43e9cb2a041122d12b3968e0c00b
vishal-chillal/assignments
/tasks/3rd_count_unique_words.py
1,276
4.1875
4
from sys import argv def open_file(file_name): ''' check if any errors in the file like validity/permissions and return file handler''' try: fp = open(file_name,'r') except Exception as e: print e return file_text = ''.join(e for e in fp.read() if e.isalnum() or e == " ") return file_text def count_unique_words_using_set(fp): word_list = fp.split() print "count of unique words in file is:", len(set(word_list)) def count_unique_words(fp): ''' in this function actual words are counted and count maintained in dictionary with word as KEY and its count as VALUE ''' word_list = fp.split() word_dict = {} for word in word_list: if word not in word_dict: word_dict[word] = 1 else: word_dict[word] += 1 print "unique_word_count: ", len(word_dict) if __name__ == "__main__": if(len(argv) != 2): print "please give input file." exit(0) file_name = argv[1] fp = open_file(file_name) if fp == None: exit(0) count_unique_words(fp) count_unique_words_using_set(fp)
bb4a77dae3bacae0f555dbe2a84028aaa72afef1
nolo2k9/Delta-Coin-Cryptocurrency-Applied-Project
/backend/utils/hashing.py
1,194
4.25
4
import hashlib import json """ This will return a sha-256 hash of all the given arguements. Implements imported sha-256 function from hashlib. Turns our data into a byte string using utf-8. By using the sorted() method, we prevent errors involving identical data giving different results if the data becomes unsorted or jumbled. """ def crypto_hash(*args): # parse data args to a string using a lambda function stringified_args = sorted(map(lambda data: json.dumps(data), args)) # join our args into a string joined_data = ''.join(stringified_args) # debug output #print(f'stringified_args: {stringified_args}') #print(f'joined_data: {joined_data}') # hash function return hashlib.sha256(joined_data.encode('utf-8')).hexdigest() """ Main method for testing expected results """ def main(): print(f"crypto_hash('one', 2, [3]): {crypto_hash('one', 2, [3])}") # the order is different but the data is the same, expected output should be the same print(f"crypto_hash(2, 'one', [3]): {crypto_hash(2, 'one', [3])}") # this checks if we're directly running the file, and if so just run the main method. if __name__ == '__main__': main()
701af53b745d7f9d33eff0c1e70ddb3d109b2635
Armyz/learnPython
/learnPythonExample/pythonGrammar/07-property.py
467
4.15625
4
""" property : 1.讲类方法变为转换为只读属性 2.对类对象中的私有变量进行修改和值获取的一种方法,setter和getter方法 """ class Test(object): def __init__(self): self.__num = 21 @property def num(self): print("-----getter------") return self.__num @num.setter def num(self, newNum): print("-----setter------") self.__num = newNum t = Test() t.num = 100 print(t.num)
d06ea57bfde414b1bf78275def37575583c1d1cb
brianoc707/Coding-Dojo
/python_stack/algos/bacesvalid.py
921
3.75
4
def bracesValid(somestring): pcount = 0 bcount = 0 Bcount = 0 list1 = [] for x in range (len(somestring)): if somestring[x] == "(": pcount += 1 list1.append(x) if somestring[x] == ")": pcount -= 1 if list1[len(list1)-1] == '(': list1.pop() if somestring[x] == "[": bcount += 1 list1.append(x) if somestring[x] == "]": bcount -= 1 if list1[len(list1)-1] == '[': list1.pop() if somestring[x] == "{": Bcount += 1 list1.append(x) if somestring[x] == "}": Bcount -= 1 if list1[len(list1)-1] == '{': list1.pop() if list1 == []: return True else: return False print(bracesValid("A(1)s[0(n]0{t)0}k)"))
ebc72ade04179c5cf1d0f555b3f62d7d8dbee34a
Mayank2134/100daysofDSA
/Queues/queue _implimentation_using_list.py
484
4.375
4
#implementing queue using list # Initializing a queue queue = [] # Adding elements to the queue queue.append('l') queue.append('o') queue.append('k') queue.append('e') queue.append('s') queue.append('h') print("Initial queue") print(queue) # Removing elements from the queue print("\nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) #printing the queue after removing the element print("\nQueue after removing elements") print(queue)
6709e831ed9afb08db2bf3609fc3168c6e9a36b1
anantprsd5/Exercism
/diff.py
257
3.828125
4
def diff(): arr=[] s=0 s1=0 n=input("Enter the value of n") for i in range(n): val=input("enter " + str(i+1) + " Value") arr.append(val) for i in arr: s=s+i**2 s1=s1+i diff=s1**2-s return diff
bdfbab280350e4ec4319ae98f50001440a8a8e28
r-bhikhie/AdventOfCode
/2019/Day1/puzzle01.py
1,230
4.1875
4
#!/usr/bin/python3 # Advent of code 2019 # Day 1 # Puzzle 1 # # Ravi Bhikhie ''' The Elves quickly load you into a spacecraft and prepare to launch. At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet. Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2. For a mass of 1969, the fuel required is 654. For a mass of 100756, the fuel required is 33583. The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. What is the sum of the fuel requirements for all of the modules on your spacecraft? ''' # See puz1_in.txt for inputs answer = 0 modules = [] with open('puz1_in.txt','r') as f: for line in f: answer = answer + (int(line) // 3) answer = answer -2 print(answer)
88b4ea66f6bf071f1343cbeea60fcc64f81d2211
SAKaNa567/algorithm_class
/quicksort.py
391
3.875
4
def quicksort(seq): if len(seq) <1: return seq pivot = seq[len(seq)-1] left = [] right = [] for x in range(0,len(seq)-1): if seq[x] <= pivot: left.append(seq[x]) else: right.append(seq[x]) left = quicksort(left) right = quicksort(right) foo = [pivot] return left + foo + right print quicksort([2,9,1,8,3])
4248a16af7eeda19aa8bbdb232b4efe151fb0d2c
BUCKFAE/Semester06
/TheoInf/Exercises/Training/Kellerautomat/main.py
3,701
3.546875
4
from typing import SupportsRound def run(word): """Runs the pda e -> epsilon t -> top symbol """ states = ["0"] stacks = [["t"]] # X needs to be replaced by e, A, B rules = { "0aX": "0AX", "0bX": "0BX", "0aX": "1X", "0bX": "1X", "0eX": "1X", "1aA": "1", "1bB": "1", "1et": "1" } # Iterating over the word for c in word: print(f"{stacks=}\n{states=}") states, stacks, _ = execute_rules(states, stacks, c, rules) print("Finished the word!") changed = True while changed and not any([len(s) == 0 or (s.count("t") == len(s)) for s in stacks]): states, stacks, changed = execute_rules(states, stacks, None, rules) print(f"{stacks=}\n{states=}") print(f"{stacks=}\n{states=}") return any([len(s) == 0 or (len(set(s)) == 1 and s[0] == "t") for s in stacks]) def execute_rules(states, stacks, c, rules): newStates = [] newStacks = [] changed = False # Stepping for each state we are in right now for currentState in range(len(states)): newStacks.append(stacks[currentState]) newStates.append(states[currentState]) # Applying all rules for rule in rules.keys(): # Exchaning X for t, A, B for currentRule in set([(rule.replace("X", r), rules[rule].replace("X", r)) for r in ["t", "A", "B"]]): # Checking if we are in the correct start state if states[currentState] == currentRule[0][0]: # Checking if the input symbol matches if c == currentRule[0][1] or currentRule[0][1] == "e": if len(stacks[currentState]) == 0: continue # Checking if the symbol in sthe stack matches if stacks[currentState][-1] == currentRule[0][2]: # Removing old newStacks.pop() newStates.pop() # Appending new state newStates.append(currentRule[1][0]) currentStack = stacks[currentState].copy() currentStack, _ = pop(currentStack) for f in currentRule[1][1:]: currentStack = push(currentStack, f) newStacks.append(currentStack) changed = True return newStates.copy(), newStacks.copy(), changed def push(stack, w): return stack + [w] def pop(stack): if len(stack) > 0: return stack[:-1], stack[-1] return None def is_symmetric(word): if len(word) % 2 == 0: return word == word[::-1] return is_symmetric(word[:int(len(word) / 2)] + word[int(len(word) / 2) + 1:]) # Testing if the stack works stack = [] for i in range(10): stack = push(stack, i) print(stack) for i in range(9, -1, -1): stack, res = pop(stack) print(f"{stack=}\n{res=}\n{i=}") assert res == i # Ensuring is_symmetric is correct assert is_symmetric("a") == True assert is_symmetric("b") == True assert is_symmetric("ab") == False assert is_symmetric("ba") == False assert is_symmetric("aaa") == True assert is_symmetric("bbb") == True assert is_symmetric("aba") == True assert is_symmetric("bab") == True assert is_symmetric("bba") == False assert is_symmetric("baa") == False print(f"{run('aabaa')=}") print(f"{run('abaa')=}") #print(f"{run('abaa')=}")
3464e818986d38e4b76982dd2cba71a6157621c5
eflipe/python-exercises
/codewars/kata_4_delete_occurrences.py
1,070
3.84375
4
''' Task Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3]. Example delete_nth ([1,1,1,1],2) # return [1,1] delete_nth ([20,37,20,21],1) # return [20,37,21] ''' lista = [1, 2, 3, 1, 2, 1, 2, 3] lista_2 = [1, 1, 1, 1] lista_3 = [20, 37, 20, 21] lista_4 = [1, 1, 3, 3, 7, 2, 2, 2, 2] def delete_nth(order, max_e): list = [] for item in order: list.append(item) if list.count(item) > max_e: list.pop() return list print(delete_nth(lista, 2)) """ Otra soluciones: def delete_nth(order,max_e): ans = [] for o in order: if ans.count(o) < max_e: ans.append(o) return ans def delete_nth(order,max_e): answer = [] for x in order: if answer.count(x) < max_e: answer.append(x) return answer """
8d8a5cafcd2a306ad49f4917d75534dcefe51fc5
mengguoru/Algorithm
/generate_red_packets.py
644
3.984375
4
''' description : algorithm of generating red packets. summary : use Normalization author ;mengguoru date : 2016/02/12 ''' import random money = input('How much?:') num_packets = input('How many packet?:') index_your_choice = input('You choose which packet?:') red_packet = [] total = 0 for x in range(int(num_packets)): generate_num = random.randint(1,100) total = total + generate_num red_packet.append(generate_num) # normalization try: num_normalization = red_packet[int(index_your_choice)]/total money_you_get = num_normalization*int(money) print('You get:',money_you_get) except Exception as e: raise e
3039879d84d9d85f58955c18f714bcc3e8582dec
Andres707/Curso-de-web-scraping-con-introduccion-a-python
/semana 1/comentarios.py
266
3.90625
4
__author__ = "Andres707" # Este es un comentario ''' Este es un comentario por bloque if a == b: print(a+b) ''' a = 3 b = 1 if a == b: # Este es un comentario por bloque de codigo print('a es igual a b') # TODO: Este es un comentario identificador
fd92fce06dbef0383303099de5eebbd158f6bf35
r14r/Streamlit_Working-with_Streamlit
/Repositories/release-demos/0.84/demos/pagination.py
1,242
3.71875
4
import streamlit as st import pandas as pd @st.cache def load_data(): # From https://www.kaggle.com/claudiodavi/superhero-set/home return pd.read_csv("demos/heroes_information.csv") def show(): st.write( """ ## 📑 Pagination Too much data to display? Now you can paginate through items (e.g. a table), storing the current page number in `st.session_state`. """ ) st.write("") if "page" not in st.session_state: st.session_state.page = 0 def next_page(): st.session_state.page += 1 def prev_page(): st.session_state.page -= 1 col1, col2, col3, _ = st.columns([0.1, 0.17, 0.1, 0.63]) if st.session_state.page < 4: col3.button(">", on_click=next_page) else: col3.write("") # this makes the empty column show up on mobile if st.session_state.page > 0: col1.button("<", on_click=prev_page) else: col1.write("") # this makes the empty column show up on mobile col2.write(f"Page {1+st.session_state.page} of {5}") start = 10 * st.session_state.page end = start + 10 st.write("") st.write(load_data().iloc[start:end]) if __name__ == "__main__": show()
2f78f7aa7dc8d34dade288c6b8e0d10c7c7306a5
paulofreitasnobrega/coursera-introducao-a-ciencia-da-computacao-com-python-parte-1
/week3/bhaskara.py
1,442
4.3125
4
# Week 3 - Exercícios Adicionais (Opcionais) # Exercício 2 - Desafio da videoaula # Cálculo das Raízes com a Fórmula Bhaskara # Faça um programa em Python que recebe 3 entradas (a, b e c). E usando # a fórmula de bhaskara deverá imprimir as raízes. Onde (Delta < 0) não # haverá raízes reais; (Delta == 0) possui uma raiz real; (Delta > 0) # possui duas raizes reais. # Aluno: Paulo Freitas Nobrega import math # Retorna o valor númerico fornecido pelo usuário def PegarEntrada(label): return int(input("Entrada {}: ".format(label))) # Calcula o Delta através dos valores númericos a, b, c e por meio deste # retorna uma resposta com a quantidade de raízes reais def Bhaskara(a, b, c): delta = (b**2) - (4*a*c) if delta >= 0: raizes = (-b + math.sqrt(delta)) / (2*a), (-b - math.sqrt(delta)) / (2*a) raizesEmOrdem = tuple(sorted(raizes)) if delta > 0: return "as raízes da equação são {} e {}".format(raizesEmOrdem[0], raizesEmOrdem[1]) else: return "a raiz desta equação é {}".format(raizes[0]) else: return "esta equação não possui raízes reais" entradas = PegarEntrada("A"), PegarEntrada("B"), PegarEntrada("C") print(Bhaskara(entradas[0], entradas[1], entradas[2])) # Guia de Testes # [Delta < 0]: A=1, B=-4, C=5 - Sem Raiz Real # [Delta == 0]: A=4, B=-4, C=1 - Raiz Real: 0.5 # [Delta > 0]: A=1, B=-5, C=6 - Raízes Reais: 3.0 e 2.0
dd3e4d4e4a678548f18bf3b6964eab3a58d945ec
xiashuo/tedu_execises
/month01/day4/exercise1.py
607
3.828125
4
""" 根据应纳税所得额计算税率与速算扣除数 """ money = float(input('请输入应纳税所得额')) if money <= 36000: tax_rate = 0.03 deduction = 0 elif money <= 144000: tax_rate = 0.1 deduction = 2520 elif money <= 300000: tax_rate = 0.2 deduction = 16920 elif money <= 420000: tax_rate = 0.25 deduction = 31920 elif money <= 660000: tax_rate = 0.3 deduction = 52920 elif money <= 960000: tax_rate = 0.35 deduction = 85920 else: tax_rate = 0.45 deduction = 181920 print(f'税率是{tax_rate * 100}%速算扣除数是{deduction}')
39f45ca0918db23c9784f4a86106a66bc2eb7ffe
sidchilling/Programming-Practice
/perm-check.py
530
3.6875
4
# Check whther array A is a permutation def solution(A): track_l = [False] * len(A) for num in A: if (num - 1) < len(A): if track_l[num - 1]: # this element already occurred - not a permutation return 0 else: track_l[num - 1] = True # all the elements in track_l must be true for present in track_l: if not present: # not a permutation return 0 # it is a permutation return 1 if __name__ == '__main__': print solution(A = [4, 1, 3, 2]) print solution(A = [4, 1, 3])
115b764a1f781750fd95b1a820b4309ca2058c6f
MananKavi/lab-practical
/src/practicals/set5/fourthProg.py
454
4.03125
4
import turtle myPen = turtle.Turtle() myPen.color("blue") def drawPolygon(numberOfsides, startingPoint): exteriorAngle = 360 / numberOfsides length = 600 / numberOfsides myPen.penup() myPen.goto(-50, startingPoint) myPen.pendown() for i in range(0, numberOfsides): myPen.forward(length) myPen.left(exteriorAngle) drawPolygon(3, 300) drawPolygon(4, 100) drawPolygon(6, -100) drawPolygon(8, -350) turtle.done
e3f5c0f80714c713535c50276e2b59a76724fbec
Altarena/IIS
/4/kollresh.py
4,983
3.578125
4
import itertools, random from random import randint class win: def __init__(self): self.cand = ["a1", "a2", "a3"] self.gol = {"a1":0, "a2":0, "a3":0} def match(self): people = 100 while people != 0: ran = random.randint(0,2) self.gol[self.cand[ran]] += 1 people -= 1 inverse = [(value, key) for key, value in self.gol.items()] print ("Относительного большества: ", max(inverse)[1]) print(self.gol) class Condorcet: def __init__(self): self.candidates = set() self.scores = dict() # score for each permutation of two candidates self.results = dict() # winner of each pair of candidates self.winner = None # Condorcet winner of the election self.voters = vot # ranking of each voter def process(self): self._build_dict() self._matches_candidates() self._elect_winner() self.coplend() self.simpson() return self.winner def _build_dict(self): for voting in self.voters: for candidate in voting: self.candidates.add(candidate) for pair in list(itertools.permutations(voting, 2)): if pair not in self.scores: self.scores[pair] = 0 if voting.index(pair[0]) < voting.index(pair[1]): self.scores[pair] += 1 def _matches_candidates(self): for match in list(itertools.combinations(self.candidates, 2)): reverse = tuple(reversed(match)) if self.scores[match] > self.scores[reverse]: self.results[match] = match[0] else: self.results[match] = match[1] def _elect_winner(self): for candidate in self.candidates: candidate_score = 0 for result in self.results: if candidate in result and self.results[result] == candidate: candidate_score += 1 if candidate_score == len(self.candidates) - 1: self.winner = candidate print("Явный победитель: ", self.winner) def coplend(self): cond = {} for i in self.candidates: cond.update({i: 0}) for voting in self.voters: for candidate in voting: self.candidates.add(candidate) for pair in list(itertools.permutations(voting, 2)): if pair not in self.scores: cond[pair[0]] = 0 if voting.index(pair[0]) < voting.index(pair[1]): cond[pair[0]] += 1 inverse = [(value, key) for key, value in cond.items()] print ("Правило Копленда: ", max(inverse)[1]) def simpson(self): cond = {} for i in self.candidates: cond.update({i: 0}) for i in range(len(list(cond))): a= [] for j in range(len(list(self.scores))): if list(cond.keys())[i] in list(self.scores.keys())[j][0]: a.append(list(self.scores.values())[j]) cond[list(cond.keys())[i]] = a for i in list(cond.keys()): cond[i] = min(cond[i]) inverse = [(value, key) for key, value in cond.items()] print ("Правило Симпсона: ", max(inverse)[1]) class Bord(): def __init__(self): self.voters = vot self.candidates = set() self.results = {} self.scores = {} def process(self): self.variant() self.matchs() def variant(self): for voting in self.voters: for candidate in voting: self.candidates.add(candidate) for pare in list(itertools.permutations(self.candidates, 3)): self.scores[pare] = 0 for voting in self.voters: if voting in list(self.scores.keys()): self.scores[voting] += 1 def matchs(self): cond = {} for i in self.candidates: cond.update({i: 0}) ball = [i for i in range(len(cond.keys()), 0, -1)] print(ball) keyscor = list(self.scores.keys()) keycond =list(cond.keys()) for keyc in keycond: for keys in keyscor: for i in range(len(ball)): if keyc == keys[i]: cond[keyc] += (ball[i]+1)*self.scores[keys] inverse = [(value, key) for key, value in cond.items()] print ("Метод Борда: ", max(inverse)[1]) vot = [("a1", "a2", "a3"), ("a1", "a3", "a2"), ("a2", "a1", "a3"), ("a1", "a2", "a3")] Condorcet().process() Bord().process() win().match()
13e9c20764f557bb2a66db2ce95007df2ee98c89
mosesobeng/Lab_Python_04
/Lab04_1.py
234
3.828125
4
groceries = ['bananas ','strawberies','apples ','bread '] groceries.append('champagne ') groceries.remove('bread ') groceries.sort() for i in groceries: s=list(i) print i + ' --->'+ (str(s[0:1]))[2:3]
bcd283d1d089f46d737a5aa410248b1c121dc7f1
RinSer/ProbabilityTheoryQuestion
/answer.py
642
3.828125
4
#!/usr/bin/env python # Finds the number of positive integer triples which sum equals 10 # and the number of such combinations containing 4 three_sum_to_ten = 0; containing_four = 0; for x in range(1, 10): for y in range(1, 10): for z in range(1, 10): if (x + y + z) == 10: three_sum_to_ten += 1 if x == 4 or y == 4 or z == 4: containing_four += 1 print('contains 4! \#' + str(containing_four)) print(str(x) + ' + ' + str(y) + ' + ' + str(z) + ' \#' + str(three_sum_to_ten)) print(str(containing_four) + '/' + str(three_sum_to_ten))
fc432d5ae3028fa515d6c31b7ef32d90bf941491
stdg3/python3M
/course7/functionsAreObjects.py
734
4.09375
4
def myFunction(): print("i am a function") print("functions are objects", isinstance(myFunction, object)) # you can use var to store funtions test = myFunction test() # you can pass functions as parameters def callPassedFunction(incomming): print("calling") incomming() print("called") callPassedFunction(myFunction) # you can not call uncallable things try: d = 2 d() except TypeError as e: print("it is not a function", e) # you can check if something could be called print(callable(len), callable(45), callable(callable)) # you can return function from a function def returnMinFunction(): return min test = returnMinFunction() minvalue = test(4, 5, 8 ,0) print("min val is: ", minvalue)
f739a8d6f57af6e976cb34f2c56132ebf9339d28
TalhaBhutto/Ciphers
/Network Security/ColumnarCipherTask2.py
1,053
3.65625
4
def encrypt(Data,key): l=len(Data) l2=0 temp2=[] temp2.append("{") temp="" k2="" num=0 num2=0 num4=0 row=0 LK=int(len(key)) while((l/LK)%1): l=l+1 Data=Data+"X" row=int(l/LK) while(l2<l): temp=temp+Data[(l2%row)*LK+num] l2=l2+1 if(l2%row==0): temp2.append(key[num]+temp) temp="" num=num+1 for x in temp2: num=0 num2=0 num3=0 for y in temp2: if(x[0]>y[0]): x=y x2="" for z in x: if(num2!=0): temp=temp+z num2=num2+1 for y in temp2: if(x==y and num3==0): temp2[num]="{" num3=num3+1 num=num+1 return temp data="LETSTRYCOLUMNARCIPHERTOSECUREOURTHEMESSAGE" A="MANGO" print("The encrypted message is:\n"+encrypt(data,A)) print(encrypt(data,A)) print("Made by group # 4\nNoman Ahmed 42\nTalha Hussain 51")
fc4269b1b8080d2f517fd19c3436e83b3c6c64e9
HoweChen/PythonNote-CYH
/Matplotlib/mpl_square.py
342
3.5
4
import matplotlib.pyplot as plt x_value = [1, 2, 3, 4, 5] square = [1, 4, 9, 16, 25] plt.plot(x_value, square, linewidth=5) # plt title plt.title("Square Numbers", fontsize=24) # x label plt.xlabel("Value", fontsize=14) # y label plt.ylabel("Square of Value", fontsize=14) # label mark plt.tick_params(axis='both', labelsize=14) plt.show()
33d04a1e60fd903386745467204b0bd4e493584f
xinwang26/leetcodeprac
/reverse_integer.py
363
3.65625
4
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ sign = -1 if x <0 else 1 x = sign *x y = 0 while x >0: y = y*10 + x%10 x = x //10 if (y*sign >= 2**31-1) or (y*sign <= -2**31): return 0 y *= sign return y
f5a44c78677db5ead6159caf50bd167cda70c7cb
sayimpuvinay/Problem-3
/Program-3.py
628
3.8125
4
""" Problem-3: With a single integer as the input, generate the following until a = x [series of numbers as shown in below examples] Output: (examples) 1) input a = 1, then output : 1 2) input a = 2, then output : 1 3) input a = 3, then output : 1, 3, 5 4) input a = 4, then output : 1, 3, 5 5) input a = 5, then output : 1, 3, 5, 7, 9 6) input a = 6, then output : 1, 3, 5, 7, 9 . . 7) input a = x, then output : 1, 3, 5, 7, ....... """ a = int(input()) count = 1 str1 = "1,"; if (a%2 == 0): a = a-1 else: pass for i in range(a-1): count = count + 2 str1 = str1 + str(count) + ","; print(str1.strip(","))
eb99f88c9bb970a41d2778686388d7f040005909
mochrisal/csci5448-hw
/hw1/hw1_q4_shapes.py
2,306
4.25
4
""" Implementation of an object oriented program that implements creating various Shapes author: Morgan Allen course: csci 5448 Object Oriented Analysis and Design due date: 2/1/2019 """ # ====================================================================================================================== # === Class Definitions ================================================================================================ # ====================================================================================================================== # Parent Shape Class class Shape(object): def __init__(self, name, sides): self.name = name self.sides = sides def __repr__(self): return "I am a Shape called {} with {} sides".format(self.name, self.sides) # Circle Class class Circle(Shape): def __init__(self): Shape.__init__(self, "Circle", "infinite") def display(self): print("This is a method to display a Circle.") # Triangle Class class Triangle(Shape): def __init__(self): Shape.__init__(self, "Triangle", 3) def display(self): print("This is a method to display a Triangle") # Square Class class Square(Shape): def __init__(self): Shape.__init__(self, "Square", 4) def display(self): print("This is a method to display a Square.") # ====================================================================================================================== # === Main Program ===================================================================================================== # ====================================================================================================================== # Create a collection of shapes through instantiation c = Circle() t = Triangle() s = Square() # Create a 'database' of these shapes database = [c,t,s,t,s,c,c,t,s,c,t,s,s] # Print number of shapes in the 'database' print("There are {} shapes in database.".format(len(database))) print('\n') # Print each shape in the 'database' print("Printing each shape in database") for shape in database: print(shape) print('\n') # Call the display() function for each shape in the 'database' print("Calling display() function of each shape in database") for shape in database: shape.display()
34ba84a353937822b8f9329effc073185459a380
C-Joseph/formation_python_06_2020
/mes_scripts/volubile.py
324
4.3125
4
#!/usr/bin/env python3 #Tells user if length of string entered is <10, <10 and >20 or >20 phrase = input("Write something here: ") if len(phrase) < 10: print("Phrase of less than 10 characters") elif len(phrase) <= 20: print("Phrase of 10 to 20 characters") else: print("Phrase of more than 20 characters")
92b54227896ff303e6c0414102defbe4e224ff1e
PrchalJan/BlackJack
/packages/classes/class_package.py
1,442
3.65625
4
# I'm programming the classes here. import random suits = ('Spades', 'Diamodns', 'Clubs', 'Hearts') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10,\ 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} class Card(): def __init__(self, suit, rank): self.suit = suit self.rank = rank self.value = values[self.rank] def __str__(self): return self.rank + ' of ' + self.suit class Deck(): def __init__(self): self.cards = [] for suit in suits: for rank in ranks: self.cards.append(Card(suit,rank)) def __str__(self): comp = '' for card in self.cards: comp = comp + '\n' + card.__str__() return 'The deck has: \n' + comp def shuffle(self): random.shuffle(self.cards) def deal(self): return self.cards.pop() class Hand(): def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self, card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': self.aces += 1 def adjust_for_ace(self): while self.value > 21 and self.aces: self.value -= 10 self.aces -= 1 class Chips(): def __init__(self): self.total = 100 self.bet = 0 def lose_bet(self): self.total -= self.bet self.bet = 0 def win_bet(self): self.total += self.bet self.bet = 0
7246429a63d6c7ad7f782d2dfb03bde5bdd6c26b
khanmaster/eng_57_opp
/python_getters_setters.py
2,914
4.53125
5
# # # we will look at methods in python # # # python Magic # # # understanding private and getters and setters # # # # # Let's dive into Pythonic magic # # # # class Method_examples: # # this_can_be_accessed_easily = "Hey, here I am easily found" # # # # method = Method_examples() # # print(method.this_can_be_accessed_easily) # # # # # Let's make a change to our variable # # method.this_can_be_accessed_easily = "I have changed" # # print(method.this_can_be_accessed_easily) # # # The pythonic magic saves us a lot of time but this relates to a class variable and is accessible everywhere as we know # # # Let's move onto the __init__ method as we should use for created data with our objects # # # # class Method_init_example: # # def __init__(self): # # self.this_can_be_accessed_easily = "Hey, here I am easily found" # # # # method_init = Method_init_example() # # print(method_init.this_can_be_accessed_easily) # # # # method_init.this_can_be_accessed_easily = "I have changed " # # print(method_init.this_can_be_accessed_easily) # # # # # again nothing should change here but if python didn't deliver all the above magic # # # 3rd iteration # class Method_example: # def __init__(self): # self.this_can_be_accessed_easily = "Hey here I am " # # # getter method # def get_this_can_be_accssed_easily(self): # return self.this_can_be_accessed_easily # # # setter method # def set_this_can_be_accessed_easily(self, value_to_be_set): # self.this_can_be_accessed_easily = value_to_be_set # # # method_getter_setter = Method_example() # # print(method_getter_setter.get_this_can_be_accssed_easily()) # # method_getter_setter.set_this_can_be_accessed_easily("I have changed") # print(method_getter_setter.get_this_can_be_accssed_easily()) # # 4th iteration # Let's take our previous code and add _ to our variable in self: class Method_example: def __init__(self): # here we will add self._this_can_be_accessed_easily and run self._this_can_be_accessed_easily = "Hey here I am " # getter method def get_this_can_be_accssed_easily(self): # Let'd add _ here as well return self._this_can_be_accessed_easily # setter method def set_this_can_be_accessed_easily(self, value_to_be_set): # Let'd add _ here as well self._this_can_be_accessed_easily = value_to_be_set # by adding an _ with our variables we are telling python to essentially, not generate the getter & setters automatically method_getter_setter = Method_example() print(method_getter_setter.get_this_can_be_accssed_easily()) method_getter_setter.set_this_can_be_accessed_easily("I have changed") print(method_getter_setter.get_this_can_be_accssed_easily()) #The same can be done for our methods and we'll do that in our 5th iterations # 5th iteration # we will do the same with our methods now but will add double __ :
a4f50f755298f3cc75d3aa1522a9b2683c7f7275
evanchan92/learnpython
/LPTHW/ex21.py
506
4.0625
4
def add(a,b): print(f"Adding {a} + {b}") return a + b def subtract(a,b): print(f"Subtracting {a} - {b}") return a - b def multiply(a, b): return a * b def divide(a, b): return a / b age = add(30,5) height = subtract(78,4) weight = multiply(90,2) iq = divide(200,2) print(f"Age: {age}, Height: {height}, weight: {weight},IQ:{iq}") print("There's a puzzle.") what = add(age, subtract(height,multiply(weight,divide(iq,2)))) print("that becomes",what, "Can you do it by hand?")
292385892531b943424d0f08d308c84f4d5f0b22
BrunoZarjitsky/URI
/2787.py
145
3.734375
4
linha = int(input()) coluna = int(input()) if linha%2 == 1 and coluna%2 == 1 or linha%2 == 0 and coluna%2 == 0: print (1) else: print (0)
8599544db2677e5adba1459bf3a3645fdcbbd2c1
sajalkuikel/100-Python-Exercises
/Solutions/3.Exercise50-75/66.py
463
4.0625
4
# Question: Create an English to Portuguese translation program. # # The program takes a word from the user as input and translates it using the following dictionary as a vocabulary source. # # d = dict(weather = "clima", earth = "terra", rain = "chuva") # # Expected output: # # Enter word: earth # terra d = dict(weather="clima", earth="terra", rain="chuva") def vocabulary(word): return d[word] word = input("Enter the word: ") print(vocabulary(word))
df87dcb8f5f482f8245ebeb7b5ecaa1f41f849db
kevalrathod/Python-Learning-Practice
/other_Exmple/Fibo.py
427
4.0625
4
#Without Recursion # def fibonacci(n): # a = 0 # b = 1 # for i in range(0, n): # temp = a # a = b # b = temp + b # return a # n=int(input()) # for c in range(0, n): # print(fibonacci(c)) #using Recursion def Fibo(n): if n==0: return 0 elif n==1: return 1 else: return(Fibo(n-1)+Fibo(n-2)) if __name__ == '__main__': n=int(input()) for i in range(0,n): print(Fibo(i))
98a26409b55834830929ccde659e462a3bf87c14
ovenbakedgoods/CodeWars
/ReturnMiddle.py
165
3.53125
4
def get_middle(s): how_big = len(s) if how_big % 2 == 0: return s[int(how_big/2) - 1] + s[int(how_big/2)] else: return s[int(how_big/2)]
190beafb7f689da0ca655178d8a51cdd77c8d41f
AdamZhouSE/pythonHomework
/Code/CodeRecords/2453/60671/246537.py
152
3.765625
4
str1=input() strr=str1.split(",") strrr="".join(strr) num=int(input()) if(strrr.find(str(num))==-1): print(False) else: print(True)
edafa87123838b38cbf82d63e53931c80134ee05
gabriel-barreto/uri
/begginer/2807.py
652
3.875
4
#!/usr/bin/python3 #-*- coding: utf-8 -*- def join(itens): s = "" for item in itens: s += ("{} ".format(item)) return s.strip() # Setting static value s = [1, 1] # Getting user input n = int(input()) # Handle with index if (n < 2): # Building an index to get a substring of default sequnece index = (n - 1) if (index <= 0): index = 1 # Printing result print(join(s[0:index])) else: # Removing initialized values n -= len(s) # Generating sequence for i in range(n): s.append(s[-1] + s[-2]) # Printing genereted sequence print(join(s[::-1]))
6f6f19d33cf84463ad1608b6bd1060c14d7a6edd
kozakh/ProjectEuler
/Problems/355/max-weight-coprime-set.py
7,273
3.6875
4
#!/bin/python """ Možnosti: - zahrabat se do peřin s knížkou diskrétní matematiky od Habaly - genetickej algoritmus - simulated annealing """ from math import log def sieve(upper_bound): numbers = [True]*(upper_bound + 1) numbers[0] = numbers[1] = False primes = [] for i in range(upper_bound + 1): if numbers[i] == True: primes.append(i) for j in range(i*i, upper_bound+1, i): numbers[j] = False return primes """ The same as function after, the only difference is that only big_prime*(low_prime**log(upper_bound/big_prime, low_prime)) are added """ def squareable_max_prime_combinations(upper_bound): primes = sieve(upper_bound) composable = [x for x in primes if x*x > upper_bound and x <= (upper_bound//2)] squareable = [x for x in primes if x*x <= upper_bound] combinations = [] for i, prime in enumerate(squareable): combinations.append([]) max_power = int(log(upper_bound, prime)) combinations[i].append((prime**max_power, 0)) for big_prime in composable: if prime * big_prime > upper_bound: break combinations[i].append((big_prime*(prime**(int(log(upper_bound/big_prime, prime)))), big_prime)) return combinations """ Numbers of combinations in one bracket: l = [len(x) for x in squareable_max_prime_combinations(200000)] Number of all possible combinations: from functools import reduce reduce(lambda x, y: x * y, l) """ def resolve_conflicts(assignment, combinations, upper_bound): conflicts = {x:y for x, y in assignment if len(y) > 1} blacklist = {} # Dictionary of low_prime : set(big_primes), where each low_prime is assigned the set of big_primes it can't be used with. primes = sieve(upper_bound) while bool(conflicts): for big_prime, low_prime_list in conflicts: winner = max(low_prime_list) # Make a list of primes to reassign conflict_list = low_prime_list.copy() conflict_list.remove(winner) # We can remove all other assigned low primes, because we're reassigning them in the next loop assignment[big_prime] = [winner] for low_prime in conflict_list: blacklist.setdefault(low_prime, []).append(big_prime) for x,y in combinations[primes.index(low_prime)]: if y not in blacklist[low_prime] and x > (primes[i]**int(log(upper_bound, primes[i])) + y): assignment.setdefault(y, []).append(low_prime) break conflicts = {x:y for x, y in assignment if len(y) > 1} return assignment """ For every low prime finds big prime in such way that low_prime * big_prime > low_prime**int(log(upper_bound, low_prime)) + big_prime """ def get_max_whose_product_is_bigger_than_sum(combinations, upper_bound): result_combinations = [] primes = sieve(upper_bound) big_to_low_primes = {} used_big_primes = set() for i, c in enumerate(combinations): c.sort(key=(lambda x: x[1]), reverse=True) max_combinable_big_prime = -1 max_product = -1 for x,y in c: if x > (primes[i]**int(log(upper_bound, primes[i])) + y): # and y not in used_big_primes: #Beware (prime**max_power, 0) big_to_low_primes.setdefault(y, []).append(primes[i]) max_combinable_big_prime = y max_product = x break if max_combinable_big_prime != -1: result_combinations.append(max_product) used_big_primes.add(max_combinable_big_prime) else: result_combinations.append(primes[i]**int(log(upper_bound, primes[i]))) return resolve_conflicts(big_to_low_primes, combinations, upper_bound), used_big_primes """ For the integer argument, the function returns a list of lists of tuples in the following structure: [ [(squareable_prime**1, 0), (squareable_prime**1 * composable_prime, composable_prime),...], ..., [(max_squareable_prime**max_power * composable_prime)]] """ def squareable_prime_combinations(upper_bound): primes = sieve(upper_bound) composable = [x for x in primes if x*x > upper_bound and x <= (upper_bound//2)] squareable = [x for x in primes if x*x <= upper_bound] combinations = [] for i, prime in enumerate(squareable): combinations.append([]) max_power = int(log(upper_bound, prime)) for power in range(1, max_power + 1): combinations[i].append((prime**power, 0)) for big_prime in composable: if prime**power * big_prime > upper_bound: break combinations[i].append((prime**power * big_prime, big_prime)) return combinations def reduce_combinations(combinations): for l in combinations: l.sort(key=lambda tup: tup[0], reverse=True) return [l[:3] for l in combinations] """ No backtracking. Even when considering 2 possibilities for each of the 86 squareable primes, the time, ((2**86)//3 000 000 000)/(60*60*24*365.3) = 817 137 154.0486793 years, is unbearable. """ #def maximize_combinations_bt(upper_bound): #combinations = reduce_combinations(squareable_prime_combinations(upper_bound)) #max = 0 #for def maximize(prime, prime_list, upper_bound, conflicts,blacklist): max_power = int(log(upper_bound, prime)) max = prime**max_power used_prime = -1 power = -1 for i in range(max_power+1): # TODO range(max_power + 1)!!! But that doesn't change anything, since max is originally set to max power. for p in prime_list: candidate = prime**i * p if candidate > upper_bound or p in blacklist: continue if candidate > max: max = candidate used_prime = p power = i if used_prime != -1: prime_list.remove(used_prime) # print("Used {}".format(used_prime)) #if used_prime != -1: # conflicts.setdefault(used_prime, []).append((prime, power)) return max """ No, bad approach. Should I add 10 or 5 and 8? """ def Co(n): primes = sieve(n) copiable = [x for x in primes if x > (n//2)] composable = [x for x in primes if x*x > n and x <= (n//2)] squareable = [x for x in primes if x*x <= n] result_list = copiable.copy() conflicts = dict() for p in reversed(squareable): #Loop through the primes in reversed order. TODO revise, not necessarily a better way. #for p in squareable: result_list.append(maximize(p,composable,n,conflicts, [])) for p in composable: result_list.append(p) # Add all unused primes from list result_list.append(1) print(conflicts) for key,val in conflicts.items(): if len(val) > 1: print("{}: {}".format(key,val)) #print(result_list) #print(copiable) #print(len(copiable)) #print(composable) #print(len(composable)) #print(squareable) #print(len(squareable)) return sum(result_list) if __name__ == "__main__": print("Sum: {}".format(Co(30)))
6c3b04654097a00e7e9e2401a96cc038d706611a
Schuture/DL-course
/第1次作业/提取子阵.py
850
3.609375
4
import numpy as np np.random.seed(2020) def subPart(A, position, shape, fill = 0): n, m = A.shape x, y = position[0] - 1, position[1] - 1 height, width = shape left = y - (width - 1) // 2 right = left + width up = x - (height - 1) // 2 down = up + height if 0 <= left and right <= n and 0 <= up and down <= m: # 完全包含 return A[up:down, left:right] pad_width = max([0, -left, -up, right-m, down-n]) # 计算填充宽度 A = np.pad(A, pad_width = pad_width, mode = 'constant', constant_values = 0) return A[up+pad_width:down+pad_width, left+pad_width:right+pad_width] A = np.random.randint(0, 10, (5, 5)) shape = (4, 3) position = (1, 1) print('原矩阵:') print(A) print('\n形状{},中心{}的子矩阵如下:'.format(shape, position)) print(subPart(A, position, shape))
4a54726e37fc06633302156296ded34f7b203e94
khmahmud101/CodingBat_problem_solve
/Logic-1/near_ten.py
135
3.65625
4
def near_ten(num): if num % 10 <=2: return True elif num % 10 >= 8 and num % 10 <=10: return True else: return False
9bfed17d2fdb99a73c173fcaf0155c33080630fb
R1sh1Par1kh/text-to-morse
/code.py
635
3.78125
4
# main.py morseDict = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--.."} def morseText(msg): morseMsg = "" for letter in msg: if letter == " ": morseMsg += " " else: morseMsg += morseDict[letter] + " " return morseMsg msg = input("Type in a message to translate into morse code (in all lowercase): ") print("\n" + morseText(msg))
0fb0c324b7732ab490a71f2d069eca7673a43eb2
astilleman/MI
/6_palindroom.py
1,100
4.1875
4
""" Een palindroom is een string die hetzelfde leest van links naar rechts, als omgekeerd. Enkele voorbeelden van palindromen zijn: - kayak - racecar - was it a cat I saw Schrijf een recursieve functie die een string vraagt aan de gebruiker en nakijkt of deze string al dan niet een palindroom is. Indien de ingevoerde string een palindroom is, moet de functie True teruggeven, anders geeft de functie False terug. Je mag ervan uitgaan dat de gegeven string geen spaties bevat. Let op: Zorg ervoor dat je functie niet hoofdlettergevoelig is. """ def is_palindroom(string): result = True if string == "": exit() if string[0] != string[-1]: result = False else: result = is_palindroom(string[1:len(string)]) return result # TESTS assert is_palindroom("") assert is_palindroom("a") assert is_palindroom("aa") assert not is_palindroom("ab") assert is_palindroom("aba") assert not is_palindroom("aab") assert is_palindroom("kayak") assert not is_palindroom("racehorse") assert is_palindroom("racecar") assert is_palindroom("wasitacatIsaw")
a8bc766a447df8a9242b4066d4696849796dc0d5
ImportMengjie/Leetcode
/290.单词规律.py
1,675
3.65625
4
# # @lc app=leetcode.cn id=290 lang=python3 # # [290] 单词规律 # # https://leetcode-cn.com/problems/word-pattern/description/ # # algorithms # Easy (42.35%) # Likes: 152 # Dislikes: 0 # Total Accepted: 24.2K # Total Submissions: 56.6K # Testcase Example: '"abba"\n"dog cat cat dog"' # # 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 # # 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 # # 示例1: # # 输入: pattern = "abba", str = "dog cat cat dog" # 输出: true # # 示例 2: # # 输入:pattern = "abba", str = "dog cat cat fish" # 输出: false # # 示例 3: # # 输入: pattern = "aaaa", str = "dog cat cat dog" # 输出: false # # 示例 4: # # 输入: pattern = "abba", str = "dog dog dog dog" # 输出: false # # 说明: # 你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。     # # # @lc code=start class Solution: def wordPattern(self, pattern: str, str: str) -> bool: split_str = str.split() if len(pattern) == len(split_str): pattern_dict = {} str_dict = {} for i in range(len(pattern)): if pattern[i] not in pattern_dict: pattern_dict[pattern[i]] = i if split_str[i] not in str_dict: str_dict[split_str[i]] = i if pattern_dict[pattern[i]]!=str_dict[split_str[i]]: return False return True return False # @lc code=end
7e4704e0045a3842406e4eee9be5c8033c93eedb
wufei74/lpthw
/ex20.py
2,024
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 30 18:14:25 2020 @author: wufei """ #ex20.py #import modules for arguments from sys import argv #Set arguments to variables script, input_file=argv #Create function for printing an entire open file def print_all(f): print(f.read()) #Go back to the start of file f def rewind(f): f.seek(0) #Create function that requires 2 variables. Line_count, #which shows which line we're on currently. #and F, which is the file we want to read the line from. #Readline reads one line at a time. def print_a_line(line_count, f): print(line_count, f.readline()) #Set variable for open file for our argument given filename. #so we can access it. current_file = open(input_file) print("First, let's print the whole file:\n") # callour function p_a that reads an open file and prints it print_all(current_file) print("Now let's rewind, kind of like a tape.") #Since the file is open and it reads one at a time, we need to go #back to the beginning of the file so we can do it one line #at a time. rewind(current_file) print("Let's print three lines:") #This sets the current counter of line to 1. We are at the #0 byte of our open file. Now it will read one line at #a time, and we then add one to the current_line count current_line = 1 print_a_line(current_line, current_file) print(current_line) current_line += 1 print_a_line(current_line, current_file) print(current_line) current_line += 1 print_a_line(current_line, current_file) print(current_line) print("Closing file ", current_file.name) current_file.close() #Testing this to verify that readline will keep going and #remember where it was. It does. We just use the current_line #as a viewable count for the user. #rewind(current_file) #print(current_file.readline()) #print(current_file.readline()) #print(current_file.readline()) #print(current_file.readline()) #print(current_file.readline()) #print(current_file.readline()) #print(current_file.readline())
e8cb78b18da33c89208f83b67e29f30f5105c2ae
sudhakar-github/hello-world
/python/raw_input.py
170
3.578125
4
user = pwd = '' while True: user = raw_input('enter username: ') if user: break while True: pwd = raw_input('enter password: ') if pwd: break print user print pwd
d57ff8acfbb9865c7626a6b5e8a4ceb50107d346
abhisheksahnii/python_you_and_me
/expressions.py
246
3.90625
4
#!/usr/bin/env python3 a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) x = a - b / 3 + c * 2 - 1 y = a - b / (3 + c) * (2 - 1) z = a - (b / (3 + c) * 2) - 1 print ("X = ",x) print ("Y = ",y) print ("Z = ",z)
98f3a96af4baa36af132ea4d9a3cb48932044c98
thenicopixie/holbertonschool-higher_level_programming
/0x0A-python-inheritance/2-is_same_class.py
287
3.84375
4
#!/usr/bin/python3 """Module for is same class""" def is_same_class(obj, a_class): """Check for instance of object Return: True is object is an instance of given class, or False if not """ if type(obj) is a_class: return True else: return False
856c63198206a9dfad4a2040c21734bd1e7eb2f4
shin99921/software_basic
/bc/20.py
269
3.765625
4
def str2int(n): jud = str.isdigit(n) if jud == True: print("문자열이 숫자로만 입력되었습니다.") n = int(n) print(type(n)) return n else: return None a = input("문자열 입력:") print(str2int(a))
0b504b5f63a12b756f7eee29d6d6a7b71824d0e5
QilinGu/Sorting-and-Data-Structures
/Algorithmic-Toolbox/Week-3/covering_segments.py
1,082
3.953125
4
# Uses python3 import sys from collections import namedtuple from operator import attrgetter Segment = namedtuple('Segment', 'start end') def optimal_points(segments): """ Returns minimum list of points that fall at least once in each provided segment :param segments: list of namedtuple objects containing the start and stop points of each segment :return: list of points that fall in every segment """ # Sort segments by endpoint segments = sorted(segments, key=attrgetter("end")) points = [segments[0].end] # First safe point is last point in first segment point_idx = 0 for line in segments[1:]: if line.start > points[point_idx]: points.append(line.end) point_idx += 1 return points def main(): vals = sys.stdin.read() n, *data = map(int, vals.split()) segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2]))) points = optimal_points(segments) print(len(points)) for p in points: print(p, end=' ') if __name__ == '__main__': main()
fc183fbb9ec3bb476b0c40167153a6c2203be05b
martin-krutsky/symmetries-in-deep-learning
/1_binlogic_baseline/neural_net.py
12,154
3.671875
4
import numpy as np import matplotlib.pyplot as plt def sigmoid(Z): return 1/(1+np.exp(-Z)), Z def relu(Z): return np.maximum(0,Z), Z def leaky_relu(Z, alpha=0.01): return np.maximum(alpha*Z, Z), Z def sigmoid_backward(dA, Z): sig = sigmoid(Z)[0] return dA * sig * (1 - sig) def relu_backward(dA, Z): dZ = np.array(dA, copy = True) dZ[Z <= 0] = 0; return dZ; def leaky_relu_backward(dA, Z, alpha=0.01): dZ = np.array(dA, copy = True) dZ[Z <= 0] = alpha; return dZ; def initialize_parameters_deep(layer_dims, seed, weights=None, weight_multiplier=0.1, weight_addition=0): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1]) bl -- bias vector of shape (layer_dims[l], 1) """ np.random.seed(seed) parameters = {} L = len(layer_dims) # number of layers in the network if weights is None: for l in range(1, L): parameters[f'W{l}'] = np.random.randn(layer_dims[l], layer_dims[l-1])*weight_multiplier + weight_addition parameters[f'b{l}'] = np.zeros((layer_dims[l], 1)) else: for l in range(1, L): parameters[f'W{l}'] = np.array(weights[l-1][:, 1:]) parameters[f'b{l}'] = np.array(weights[l-1][:, 0]).reshape(-1, 1) return parameters def linear_forward(A, W, b): """ Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) Returns: Z -- the input of the activation function, also called pre-activation parameter cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass efficiently """ # print(f'W shape: {W.shape}, A shape: {A.shape}, b shape: {b.shape}') Z = np.dot(W, A) + b.reshape(-1, 1) cache = (A, W, b) return Z, cache def linear_activation_forward(A_prev, W, b, activation): """ Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: A -- the output of the activation function, also called the post-activation value cache -- a python tuple containing "linear_cache" and "activation_cache"; stored for computing the backward pass efficiently """ if activation == "sigmoid": Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = sigmoid(Z) elif activation == "relu": Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = relu(Z) elif activation == "leaky_relu": Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = leaky_relu(Z) cache = (linear_cache, activation_cache) return A, cache def L_model_forward(X, parameters, hidden_act='relu'): """ Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- last post-activation value caches -- list of caches containing: every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1) """ caches = [] A = X L = len(parameters) // 2 # number of layers in the neural network for l in range(1, L): A_prev = A W, b = parameters['W' + str(l)], parameters['b' + str(l)] A, cache = linear_activation_forward(A_prev, W, b, hidden_act) caches.append(cache) W, b = parameters['W' + str(L)], parameters['b' + str(L)] AL, cache = linear_activation_forward(A, W, b, 'sigmoid') caches.append(cache) return AL, caches def compute_cost_entropy(AL, Y): """ Arguments: AL -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples) Returns: cost -- cross-entropy cost """ cost = -np.mean(Y * np.log(AL) + (1 - Y) * np.log(1 - AL)) cost = np.squeeze(cost) return cost def compute_cost_mse(AL, Y): return np.mean((AL - Y) ** 2) def compute_class_error(AL, Y): return np.sum(abs(classify(AL) - Y)) def linear_backward(dZ, cache): """ Arguments: dZ -- Gradient of the cost with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ A_prev, W, b = cache m = A_prev.shape[1] dW = np.dot(dZ, np.transpose(A_prev)) / m db = np.mean(dZ, axis=1, keepdims=True) dA_prev = np.dot(np.transpose(W), dZ) return dA_prev, dW, db def linear_activation_backward(dA, cache, activation): """ Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ linear_cache, activation_cache = cache if activation == "relu": dZ = relu_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) elif activation == "leaky_relu": dZ = leaky_relu_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) elif activation == "sigmoid": dZ = sigmoid_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) return dA_prev, dW, db def L_model_backward(AL, Y, caches, hidden_act='relu', criterion='entropy'): """ Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) caches -- list of caches containing: every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2) the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1]) Returns: grads -- A dictionary with the gradients grads["dA" + str(l)] = ... grads["dW" + str(l)] = ... grads["db" + str(l)] = ... """ grads = {} L = len(caches) # the number of layers m = AL.shape[1] Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL # Initializing the backpropagation if criterion == 'entropy': dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) elif criterion == 'mse': dAL = 2*(AL - Y) current_cache = caches[L-1] grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, 'sigmoid') # Loop from l=L-2 to l=0 for l in reversed(range(L-1)): current_cache = caches[l] grads["dA" + str(l)], grads["dW" + str(l + 1)], grads["db" + str(l + 1)] = linear_activation_backward(grads["dA" + str(l+1)], current_cache, hidden_act) return grads def update_parameters(parameters, grads, learning_rate): """ Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Returns: parameters -- python dictionary containing your updated parameters parameters["W" + str(l)] = ... parameters["b" + str(l)] = ... """ L = len(parameters) // 2 # number of layers in the neural network for l in range(L): parameters["W" + str(l+1)] -= learning_rate * grads["dW" + str(l+1)] parameters["b" + str(l+1)] -= learning_rate * grads["db" + str(l+1)] return parameters def classify(activations): predictions = np.where(activations > 0.5, 1, 0) return predictions class MyNetwork: def __init__(self, dim_list, seed=0, weights=None, weight_multiplier=0.1, hidden_act='relu', weight_addition=0): self.seed = seed self.hidden_act = hidden_act self.parameters = initialize_parameters_deep(dim_list, seed, weights=weights, weight_multiplier=weight_multiplier, weight_addition=weight_addition) def fit(self, X, Y, learning_rate=0.0075, num_iterations=3000, criterion='entropy', print_cost=False, plot_costs=True): entropy_costs = [] misclass = [] mses = [] for i in range(0, num_iterations): AL, caches = L_model_forward(X, self.parameters, hidden_act=self.hidden_act) if criterion == 'entropy': cost = compute_cost_entropy(AL, Y) elif criterion == 'mse': cost = compute_cost_mse(AL, Y) grads = L_model_backward(AL, Y, caches, hidden_act=self.hidden_act, criterion=criterion) self.parameters = update_parameters(self.parameters, grads, learning_rate) # Print the cost every 1000 training example if print_cost and i % 1000 == 0: print ("Cost after iteration %i: %f" %(i, cost)) if criterion == 'entropy': entropy_costs.append(cost) mses.append(compute_cost_mse(AL, Y)) elif criterion == 'mse': entropy_costs.append(compute_cost_entropy(AL, Y)) mses.append(cost) misclass.append(compute_class_error(AL, Y)/X.shape[1]) if plot_costs: # plot the cost plt.plot(np.squeeze(entropy_costs), label='Entropy') plt.plot(np.squeeze(misclass), label='% of Misclassifications') plt.plot(np.squeeze(mses), label='MSE') plt.ylabel('Cost') plt.xlabel('Iterations') plt.title(f"activation={self.hidden_act}, lr={learning_rate}, num_iter={num_iterations}, seed={self.seed}") plt.legend() plt.savefig(f'imgs/error_act{self.hidden_act}_seed{self.seed}') plt.show() print('Training results:') print(f'Cross-Entropy: {entropy_costs[-1]}') print(f'MSE: {mses[-1]}') print(f'Misclassification count: {int(misclass[-1] * X.shape[1])}/{X.shape[1]}') print() return entropy_costs[-1], mses[-1], misclass[-1] def predict(self, X): activations, caches = L_model_forward(X, self.parameters) predictions = np.where(activations > 0.5, 1, 0) return predictions def score(self, AL, Y): cross_entropy = compute_cost_entropy(AL, Y) print('Training results:') print(f'Cross-Entropy: {cross_entropy}') print(f'MSE: {compute_cost_mse(AL, Y)}') print(f'Misclassification count: {compute_class_error(AL, Y)}/{X.shape[1]}')
77cf3c2b284a46ad6ebeb30ac33fb0225e412161
drdreff/SpiteAndCurry
/cis117/lab3/convertDates.py
2,115
4.53125
5
#!/usr/bin/python3 ########################################################### # CIS 117 Python Programming: Lab #3 # # List Indexing and date format conversion # ########################################################### RUNS = 5 # to control the number of tests MONTHS = ['January','February','March', 'April','May','June', 'July','August','September', 'October','November','December', ] def formalDate(date_string): ''' accepts date string in the form of mm/dd/yyyy and returns a formal date in the form "Month, dd, yyyy" ''' # month names global MONTHS # array to hold string bits of the date date_chunks = [] # slice the input string on the slashes date_chunks = date_string.split('/') # 'mm' bit of input, converted to int and shifted for zero index into MONTHS converted_date = MONTHS[int(date_chunks[0]) - 1] # append rest of the string using string formats not converted_date.append() converted_date = "%s %s, %s" % (converted_date,date_chunks[1],date_chunks[2]) return converted_date def getUserInput(): ''' this will accept user input, in a less simple form this is also where we would loop until we got acceptable input that our converter could parse. ''' date_string = input('Enter a date (mm/dd/yyyy): ') # validate user input here return date_string # main loop for run in range(0,RUNS): # feed input to the conversion method converted_date = formalDate(getUserInput()) print("The converted date is: %s" % converted_date) '''Sample Run (included command prompt to show number of runs): mdavis@kali:~/school/cis117/lab3$ ./convertDates.py Enter a date (mm/dd/yyyy): 07/06/2017 The converted date is: July 06, 2017 Enter a date (mm/dd/yyyy): 02/11/2006 The converted date is: February 11, 2006 Enter a date (mm/dd/yyyy): 04/04/2001 The converted date is: April 04, 2001 Enter a date (mm/dd/yyyy): 07/30/1998 The converted date is: July 30, 1998 Enter a date (mm/dd/yyyy): 10/02/1994 The converted date is: October 02, 1994 mdavis@kali:~/school/cis117/lab3$ '''
a3f375f6dbaad5797512007cd87691d3073202a4
underlinejunior/python
/dicionarios/ex04 - q01.py
432
3.609375
4
prods=[] quants=[] dic={} while True: prod=str(input('informe o nome do produto: ')) prod=prod.upper() if prod=='FIM': break else: quant = int(input('informe a quantidade de {} a comprar: '.format(prod))) prods.append(prod) quants.append(quant) dic=dict(zip(prods,quants)) print(dic) soma=0 for x in dic.values(): soma=soma+x print('o total dos itens é ',soma)
42108cd688a986a687057abcba6968d77fdd77bb
betalantz/CodingDojo_LearningProjects
/Python/Fundamentals/names.py
1,125
3.578125
4
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def print_names(list, bool): output = [] for val in list: new_name = val['first_name'] + " " + val['last_name'] output.append(new_name) if bool == True: print new_name return output print_names(students, True) users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } def print_nested(dict): for key in dict: print key full_names = print_names(dict[key], False) for i, value in enumerate(full_names): print "{} - {} - {}".format(i +1, value, len(value)-1) print_nested(users)
f10048eb317835abb1ac9ced2a4e3f67915c1f37
Folkas/autoplius-scraper
/function/old_scraper.py
4,545
3.734375
4
from bs4 import BeautifulSoup import requests import pandas as pd from time import sleep from random import randint def autoplius_scraper(sample_size: int) -> pd.DataFrame: """ The function scrapes car sale adverts from en.autoplius.lt and using BeautifulSoup package extracts information about car marque, manufacturing date, price (in €) as well as technical details: engine (in l), types of vehicle, fuel and gearbox, engine power (in kW) and mileage (in km). Data is returned in pandas DataFrame format and then is exported to autoplius.csv file in the repository. Parameters: * sample_size(int): number of car adverts to be extracted after the scraping Returns: * pd.DataFrame with details about cars on sale (marque, manufacturing date, price, engine, vehicle, fuel, gearbox, power and mileage) * data is exported to autoplius.csv file in the repository """ # calculating the number of website scraping iterations page_no = len(range(0, sample_size, 20)) for i in range(1, page_no + 1): URL = f"https://en.autoplius.lt/ads/used-cars?page_nr={i}" page = requests.get( URL, headers=( { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } ), ) soup = BeautifulSoup(page.content, "html.parser") ( marques, engines, carTypes, years, fuels, gearboxes, powers, mileages, prices, ) = ([] for i in range(9)) cars = soup.find_all("a", class_="announcement-item") for car in cars: # extracting info about car marque marque = ( car.find("div", class_="announcement-title").text.strip().split(",")[0] ) marques.append(marque) # car engine engine = ( car.find("div", class_="announcement-title") .text.strip() .split(",")[1] .split()[0] ) engines.append(engine) # vehicle type carType = ( car.find("div", class_="announcement-title") .text.strip() .split(",")[2] .replace(" ", "") ) carTypes.append(carType) # date of manufacturing year = ( car.find("span", attrs={"title": "Date of manufacture"}) .text.strip() .split("-")[0] ) years.append(year) # fuel type fuel = car.find("span", attrs={"title": "Fuel type"}).text.strip() fuels.append(fuel) # gearbox gearbox = car.find("span", attrs={"title": "Gearbox"}).text.strip() gearboxes.append(gearbox) # engine power power = car.find("span", attrs={"title": "Power"}).text.strip().split()[0] powers.append(int(power)) # mileage mileage = ( car.find("span", attrs={"title": "Mileage"}) .text.replace(" km", "") .replace(" ", "") .strip() ) mileages.append(int(mileage)) # price price = ( car.find("div", attrs={"class": "announcement-pricing-info"}) .text.strip() .replace(" €", "") .replace(" ", "") .split()[0] ) prices.append(int(price)) # controlling the execution of scraping by pausing the looping rate sleep(randint(2, 10)) # inserting lists into pandas DataFrame result = pd.DataFrame( { "Marque": marques, "CarType": carTypes, "FuelType": fuels, "Gearbox": gearboxes, "ManufacturingDate": years, "Engine_l": engines, "Power_kW": powers, "Mileage_km": mileages, "Price_€": prices, } ) # exporting the dataframe to .csv file result.to_csv("autoplius.csv", index=False) return result
9189e9c98267f32bebdb2cc98214fbae2271d6db
joseluissuclupefarronan/TRABAJO05
/boleta02.py
727
4.0625
4
#input Distancia=int(input("Distancia:")) Tiempo=int(input("Tiempo:")) #processing Velocidad=(Distancia/Tiempo) print("Velocidad:", Velocidad) #verificador comprobar=(Velocidad<=40) #output print("#############################################") print("# DISTANCIA RECORRIDA POR UN MOVIL #") print("#############################################") print("# DATOS: VALOR: #") print("# Distancia: ",Distancia," #") print("# Tiempo: ",Tiempo," # ") print("# Velocidad: ",Velocidad," #") print("#############################################") print(" comprobar la velocidad:", comprobar)
0868e5081817411d70503ff693a9e721f77974ae
Tolsi/otus-reverse-engineering-2020
/lec10/segmentDescriptor.py
2,222
3.84375
4
#!/usr/bin/env python3 def input_num_between_zero_and_n(max): r = -1 while True: try: r = int(input()) if r < 0 or r > max: print(f'Input number between 0 and {max}') else: return r except: print(f'Input number between 0 and {r}') if __name__ == '__main__': # test constants # base_address = int(format(1, '032b'), 2) # segment_limit = int(format(1, '020b'), 2) # g = 1 # l = 1 # db = 1 # avl = 1 # p = 1 # dpl = int(format(1, '2b'), 2) # s = 1 # type = int(format(1, '4b'), 2) print("Input Base Address (32 bits):") base_address = input_num_between_zero_and_n(2**32-1) print("Input Segment Limit (20 bits):") segment_limit = input_num_between_zero_and_n(2**20-1) print("Input Granularity bit (1 bit):") g = input_num_between_zero_and_n(1) print("Input Long bit (1 bit):") l = input_num_between_zero_and_n(1) print("Input Default operand size/Big bit (1 bit):") db = input_num_between_zero_and_n(1) print("Input Available bit (1 bit):") avl = input_num_between_zero_and_n(1) print("Input Present bit (1 bit):") p = input_num_between_zero_and_n(1) print("Input Descriptor privilege level (4 bits):") dpl = input_num_between_zero_and_n(3) print("Input s (1 bit):") s = input_num_between_zero_and_n(1) print("Input Segment Type (4 bits):") type = input_num_between_zero_and_n(3) header = [] header.append(format(base_address & 0xFF, '08b')) header.append(format(g, '01b')) header.append(hex(db)[2:]) header.append(hex(l)[2:]) header.append(bin(avl)[2:]) header.append(format(segment_limit & 0xF, '04b')) header.append(bin(p)[2:]) header.append(format(dpl, '02b')) header.append(bin(s)[2:]) header.append(format(type, '04b')) header.append(format(base_address >> 8 & 0xFF, '08b')) header.append(format(base_address & 0xFFFF, '016b')) header.append(format(segment_limit >> 5, '016b')) b = ''.join(header) print('Memory descriptor:') print('bin:\t' + b) print('hex:\t' + hex(int(b, 2))) print('dec:\t' + str(int(b, 2)))