blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a6d40cc0cfd1a5e6d7cdc79a9891e0e8bbd7370d
dipeshwor/draw2codeOpenCV
/overlayOpenCV.py
1,760
3.5625
4
# import the necessary packages import imutils import numpy as np import cv2 # load the watermark image, making sure we retain the 4th channel # which contains the alpha transparency watermark = cv2.imread('images/colorOutline.png', cv2.IMREAD_UNCHANGED) watermark = imutils.resize(watermark,width=200) (wH, wW) = watermark.shape[:2] # split the watermark into its respective Blue, Green, Red, and # Alpha channels; then take the bitwise AND between all channels # and the Alpha channels to construct the actaul watermark # NOTE: I'm not sure why we have to do this, but if we don't, # pixels are marked as opaque when they shouldn't be (B, G, R, A) = cv2.split(watermark) B = cv2.bitwise_and(B, B, mask=A) G = cv2.bitwise_and(G, G, mask=A) R = cv2.bitwise_and(R, R, mask=A) watermark = cv2.merge([B, G, R, A]) # load the input image, then add an extra dimension to the # image (i.e., the alpha transparency) image = cv2.imread('images/tufts.jpg') image = imutils.resize(image,width=600) (h, w) = image.shape[:2] image = np.dstack([image, np.ones((h, w), dtype="uint8") * 255]) # construct an overlay that is the same size as the input # image, (using an extra dimension for the alpha transparency), # then add the watermark to the overlay in the bottom-right # corner overlay = np.zeros((h, w, 4), dtype="uint8") #overlay[h - wH - 10:h - 10, w - wW - 10:w - 10] = watermark overlay[h - wH - 150:h - 150, w - wW - 150:w - 150] = watermark # blend the two images together using transparent overlays output = image.copy() #cv2.addWeighted(overlay, 1, output, 1.0, 0, output) cv2.addWeighted(overlay, 1, output, 1, 0, output) # Show required images cv2.imshow("Output", output) cv2.waitKey() cv2.destroyAllWindows() #cv2.imwrite('images/merged.png', output)
2557da2c97f3f128391c06bca07d628ceab5fcb6
Hatlelol/ITGK
/Øving 2/Årstider.py
776
3.609375
4
dato = int(input("Skriv en dato")) month = input("Skriv inn måned") month = month.lower() aar = ["januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember"] for x in range(0, len(aar)): #lager en for løkke for å bestemme måneden med et tall if month == aar[x]: month = int(x) val = month*100 + dato #gir datoen en verdi med tre eller fire siffer for å representere dato og måned i samme variabel vaar = 220 sommer = 521 host = 822 vinter = 1121 if vaar <= val < sommer: print("Vår") elif sommer <= val < host: print("Sommer") elif host <= val < vinter: print("host") elif 0 < val > 1131: print("skriv inn noe gyldig") else: print("vinter")
9979be936956b9d246dddb2d5a6c7edb0e11a073
danielmmetz/euler
/euler041.py
727
4.03125
4
""" 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 prime import isprime from itertools import permutations from functools import reduce def tuple_to_int(t): return reduce(lambda x, y: x*10+y, t) def answer(): # observation: cannot be 8 or 9 due to divisibility by 3 for n in range(7, 0, -1): possibilities = map(tuple_to_int, permutations(range(n, 0, -1))) for candidate in possibilities: if isprime(candidate): return candidate if __name__ == '__main__': print(answer())
28b48d37c3ec17bf2fdedee4bebbd8d82ff5d710
zhongmb/suanfa
/leetcode/2.py
2,107
3.859375
4
''' 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: n = l1.val + l2.val l3 = ListNode(n % 10) l3.next = ListNode(n // 10) p1 = l1.next p2 = l2.next p3 = l3 while True: if p1 and p2: sum = p1.val + p2.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p1 = p1.next p2 = p2.next p3 = p3.next elif p1 and not p2: sum = p1.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p1 = p1.next p3 = p3.next elif not p1 and p2: sum = p2.val + p3.next.val p3.next.val = sum % 10 p3.next.next = ListNode(sum // 10) p2 = p2.next p3 = p3.next else: if p3.next.val == 0: p3.next = None break return l3 if __name__ == '__main__': # l1 = [2,4,3] # l2 = [5,6,4] l11 = ListNode(2) l12 = ListNode(4) l13 = ListNode(3) l1 = l11 l1.next = l12 l12.next = l13 l21 = ListNode(5) l22 = ListNode(6) l23 = ListNode(4) l2 = l21 l2.next = l22 l22.next = l23 l3 = Solution().addTwoNumbers(l1,l2) print(l3.val) print(l3.next.val) print(l3.next.next.val)
50023b3a0576fb33bfb518fcc57d0155f2dd9c99
gabriellaec/desoft-analise-exercicios
/backup/user_029/ch99_2019_11_27_18_22_58_478287.py
208
3.515625
4
def login_disponivel(x,usuarios): for i in range(len(usuarios)): if x in usuarios: usuarios.append(x+'1') return usuarios if x not in usuarios: return x
067be42e51eb207eb9ac916be4468fc73bb0170e
Rutrle/algorithms
/recursions/string_reverse.py
251
3.921875
4
def recursice_reversal(rec_string: str) -> str: if len(rec_string) == 0: return '' last_letter = rec_string[-1] rec_string = rec_string[:-1] return last_letter+recursice_reversal(rec_string) print(recursice_reversal('tree'))
99cb3648b7b53d40e9eadf73cb90663ce99a57bb
ingenierodevops/Tic-Tac-Toe
/Problems/The farm/main.py
730
3.96875
4
precios = {'sheep': 6769, 'cow': 3848, 'pig': 1296, 'goat': 678, 'chicken': 23} def print_animals(dinero, animal_name): number = int(dinero / precios[animal_name]) if number > 1: if animal_name != "sheep": print(number, animal_name + "s") else: print(number, "sheep") else: print("1", animal_name) coins = int(input()) if coins >= precios['sheep']: print_animals(coins, "sheep") elif coins >= precios['cow']: print_animals(coins, "cow") elif coins >= precios['pig']: print_animals(coins, "pig") elif coins >= precios['goat']: print_animals(coins, "goat") elif coins >= precios['chicken']: print_animals(coins, "chicken") else: print("None")
8480bdd55e1b116e30d18c390de607ca0ac291c1
rohan-khurana/Algorithms
/LeetCode_Monthly_Challenge/July/Python3/Week_4/Binary Tree Zigzag Level Order Traversal.py
1,086
3.90625
4
""" PROBLEM: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] """ # 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 class Solution: def DFS(self, root: TreeNode, level: int, ans: List[List[int]]): if root is None: return if len(ans) <= level: ans.append([]); if level % 2 == 0: ans[level].append(root.val); else: ans[level].insert(0, root.val); self.DFS(root.left, level + 1, ans); self.DFS(root.right, level + 1, ans); def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: ans = [] self.DFS(root, 0, ans) return ans
dae5b29394b1e73dc4feba996bf64e2b90f7ee29
pikriramdani/p7_labspy03
/latihan2.py
483
3.859375
4
#file tugas Latihan 2 - praktikum 3 print("Tugas Pertemuan 7 - Praktikum 3 - Latihan 2 ") angka=0 while True: bilangan = int(input("Masukan Bilangan : ")) if (angka < bilangan): angka=bilangan if (bilangan == 0): break print("Bilangan terbesar adalah: ",angka) print() print("============================") print("= Nama : Pikri Ramdani ") print("= NIM :312010162 ") print("= Kelas : TI.20 A.1 ") print("============================")
429f60d1a631df3b6169703f338cc582a821df50
stefifm/guia05
/ordenar nros.py
787
4.09375
4
print ("Ordenar 3 números") n1 = int(input("Ingrese N1: ")) n2 = int(input("Ingrese N2: ")) n3 = int(input("Ingrese N3: ")) if n1 >= n2 and n1 >= n3: mayor = n1 if n2 > n3: medio = n2 menor = n3 else: medio = n3 menor = n2 elif n2 >= n1 and n2 >= n3: mayor = n2 if n1 > n3: medio = n1 menor = n3 else: medio = n3 menor = n1 elif n3 >= n2 and n3 >= n1: mayor = n3 if n2 > n1: medio = n2 menor = n1 else: medio = n1 menor = n2 print("Mayor:", mayor, "Medio:", medio, "Menor:", menor) resto = mayor % medio if menor == resto: print("Tercero igual al resto de los dos") else: print("Tercero no es igual al resto de los dos y valor es:", resto)
d6832a198421c41d1206719719f20877078bc29d
MadaooQuake/Pinko
/core/core.py
1,302
3.5625
4
# -*- coding: utf-8 -*- import pygame from collision import Collision from objects.cir import Circle from controls import Control class Screen: screen_width = 1024 screen_height = 576 move_available = True; def __init__(self): pygame.init control = Control() screen = pygame.display.set_mode((self.screen_width, self.screen_height)) done = False circle = Circle() circle.set_circle_positions(100,100) circle.draw_circle(screen) check_colision = Collision() check_colision.set_width_and_height(self.screen_width, self.screen_height) Control clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True control.get_event(pygame.key.get_pressed()) control.check_key() check_colision.get_move(control.get_x(), control.get_y()) if check_colision.check_board(circle.get_position_x(),circle.get_position_y()): circle.move_circle(screen, control.get_x(), control.get_y()) pygame.display.flip() clock.tick(60) if __name__ == "__main__": scr = Screen()
6a22e610d0bd1567be709a2af20d9dda84a15fe0
Marytem/UCU_Courses
/programming_basics/incertion sorting.py
410
3.640625
4
def insertion_sort(lst): for i in range(1, len(lst)): tmp = lst[i] j = i - 1 while tmp < lst[j] and j > -1: lst[j + 1] = lst[j] j -= 1 lst[j + 1] = tmp return lst import random import math print(100000*100000) print(int(100000*math.log(100000))) numbers = [] for i in range(100000): numbers.append(random.randint(1,1000))
180d9bf45fd0a73bf358af1ac8a0de031670430c
xiaotian1991/actual-10-homework
/04/tantianran/function_home_work.py
1,470
3.859375
4
#!/usr/bin/env python def menu(): print 'Registration: 1. Landing: 2' number = raw_input('Please select the operating:') return number def work(n): f = open('userpassword.txt') passwd = {} for i in f.readlines(): tmp = i.split(':') passwd[tmp[0]] = tmp[1] while True: if n == str(1): username = raw_input('Registered user name:') if passwd.has_key(username) == True: print 'The user name is registered, please try again' continue password = raw_input('Set the password:') passw = raw_input('Again to confirm password:') if passw != password: print 'sorry! Password error, please try again' continue else: print 'Registration completed!' f = open('userpassword.txt','a+') f.write('%s:%s\n' % (username,password)) break elif n == str(2): username = raw_input('user:') password = raw_input('password:') if passwd.has_key(username) == True: paw = passwd[username] if password in paw: print 'Oh my god!Login to complete' break else: print 'Sorry, authentication failed' continue else: print 'User name does not exist, please return to register, thank you!' continue else: print ' sorry. Input is wrong, please input again.' continue num = menu() work(num)
8233621e317efeb5c134e0c50a3b2bfb7985f6dd
BlazeBreaker-code/A.I.Exploration_Robots
/FinishedA.I.Project_Rooker/algo.py
9,945
3.859375
4
import sys, os, random os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" import pygame pygame.init() BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREY = (211, 211, 211) GREEN = (0, 255, 0) RED = (255, 0, 0) WINDOW_HEIGHT = 1000 WINDOW_WIDTH = 1000 robots = [] spots = [] movement = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'R'] def main(): global CLOCK, SCREEN, robots, spots quit = "N" while quit == 'N' or quit == "n": robots = [] spots = [] robotNum = input("Pick the number of robots you would like to use(integer): ") if robotNum.isdigit(): robotNum = int(robotNum) else: robotNum = "k" while not isinstance(robotNum, int): print("WRONG INPUT!!! Please choose an integer!") robotNum = input("Now what number of robots you would like to use(integer): ") if robotNum.isdigit(): robotNum = int(robotNum) else: robotNum = "k" askRange = input("Pick the range you would like to use(integer): ") if askRange.isdigit(): askRange = int(askRange) else: askRange = "k" while not isinstance(askRange, int): print("WRONG INPUT!!! Please choose an integer!") askRange = input("Now what range you would like to use(integer): ") if askRange.isdigit(): askRange = int(askRange) else: askRange = "k" print(f'You have picked {robotNum} number of robots with the range of {askRange}.') print("The solution is now being visualized.") print("If there are any faulty spawns with the robots please restart the program.") pygame.init() SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) CLOCK = pygame.time.Clock() SCREEN.fill(WHITE) drawGrid(robotNum) algorithm1(askRange) # CLOCK.tick(30) quit1 = input("Do you wish to exit (Y if yes, N if no)? ") while (quit1 != 'N' and quit1 != 'n') and (quit1 != 'Y' and quit1 != 'y'): print("WRONG INPUT!!! Please choose either N or Y!") quit1 = input("Do you wish to exit (Y if yes, N if no)? ") quit1 = str(quit1) quit = quit1 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() # Makes an environment with random obstacles and random starting positions for the robots def drawGrid(robotNum): blockSize = 20 i = 0 pop = 0 start = random.randint(1, 1000) for x in range(0, WINDOW_WIDTH, blockSize): for y in range(0, WINDOW_HEIGHT, blockSize): value = random.randint(1, 7) if value == 3: rect = pygame.Rect(x, y, blockSize, blockSize) pygame.draw.rect(SCREEN, BLACK, rect) spots.append(Spot(x, y, 1, 0, 0, 0)) else: if start == pop and i < robotNum: rect = pygame.Rect(x, y, blockSize, blockSize) pygame.draw.rect(SCREEN, RED, rect) robots.append(Robot(x, y)) spots.append(Spot(x, y, 0, 1, 1, 0)) i = i + 1 else: pop = pop + 1 rect = pygame.Rect(x, y, blockSize, blockSize) pygame.draw.rect(SCREEN, GREY, rect, 1) spots.append(Spot(x, y, 0, 0, 0, 0)) def update(x1, y1, x2, y2, q): s = len(spots) rect1 = pygame.Rect(x1, y1, 20, 20) pygame.draw.rect(SCREEN, GREEN, rect1) rect2 = pygame.Rect(x2, y2, 20, 20) pygame.draw.rect(SCREEN, RED, rect2) robots[q].x = x2 robots[q].y = y2 for w in range(s): if spots[w].x == x1 and spots[w].y == y1: spots[w].occupied = 0 for e in range(s): if spots[e].x == x2 and spots[e].y == y2: spots[e].occupied = 1 spots[e].visited = 1 spots[e].fron = 0 class Robot: def __init__(self, x, y): self.x = x self.y = y class Spot: def __init__(self, x, y, obstacle, occupied, visited, fron): self.x = x self.y = y self.obstacle = obstacle self.occupied = occupied self.visited = visited self.fron = fron # Communication Exploration def algorithm1(r): t = 0 T = 80000 # k < 9^n n being number of robots k = int((9 ** (len(robots))) / (3 ** (len(robots)))) if k > 15: k = 10 n = len(robots) # Range # r = 15 while t < T: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return pygame.event.get() pop = [] for i in range(k): cfg = [] for j in range(n): value = random.randint(0, 8) cfg.append(movement[value]) pop.append(cfg) cfg_max = pop[0] for l in range(k): if utility(pop[l], r) >= utility(cfg_max, r): cfg_max = pop[l] listCo = [] l1 = [] for y in range(n): ran = True second = move(cfg_max[y], y) listCo.append(second) tempx, tempy = second for u in range(n): if ((abs(robots[u].x - second[0]) + abs(robots[u].y - second[1])) / 20) > r: ran = False for i in listCo: if i not in l1: if (findCoorCell(second) and ran): update(robots[y].x, robots[y].y, tempx, tempy, y) l1.append(i) pygame.time.delay(-50) pygame.display.flip() t = t + 1 def move(m, i): if m == "N": coord = tuple([robots[i].x, robots[i].y - 20]) return coord if m == "NE": coord = tuple([robots[i].x + 20, robots[i].y - 20]) return coord if m == "E": coord = tuple([robots[i].x + 20, robots[i].y]) return coord if m == "SE": coord = tuple([robots[i].x + 20, robots[i].y + 20]) return coord if m == "S": coord = tuple([robots[i].x, robots[i].y + 20]) return coord if m == "SW": coord = tuple([robots[i].x - 20, robots[i].y + 20]) return coord if m == "W": coord = tuple([robots[i].x - 20, robots[i].y]) return coord if m == "NW": coord = tuple([robots[i].x - 20, robots[i].y - 20]) return coord if m == "R": coord = tuple([robots[i].x, robots[i].y]) return coord def findCoorCell(coord): s = len(spots) for x in range(s): if spots[x].x == coord[0] and spots[x].y == coord[1] and spots[x].obstacle != 1 and spots[x].occupied != 1: return True return False def findVisited(coord): s = len(spots) for x in range(s): if spots[x].x == coord[0] and spots[x].y == coord[1] and spots[x].visited == 0: return True return False def makeSureNotSame(cfg): n = len(robots) Checker = [] for x in range(n): coord2 = move(cfg[x], x) Checker.append(coord2) m = len(Checker) for j in range(m): for k in range(m): if Checker[j] == Checker[k]: return False return True def utility(cfg, r): total = 0 n = len(robots) limit = 0 for x in range(n): coord2 = move(cfg[x], x) if not findCoorCell(coord2): total = total - 3000000 else: for u in range(n): if limit == 0: if ((abs(robots[u].x - coord2[0]) + abs(robots[u].y - coord2[1])) / 20) > r: total = total - 300000 limit = 1 else: # Check the frontier and see what is the lowest value to a frontier node currentRobot = tuple([robots[x].x, robots[x].y]) checkFrontier(currentRobot) great = makeFrontArray() if great: dist = [] for q in great: dist.append((abs(q[0] - coord2[0]) + abs(q[1] - coord2[1])) / 20) total = total - min(dist) if not great: print("Program has been completed!") sys.exit(0) return total # Checks nodes around current to see if they are visited or not, if not, they go into a frontier node array def checkFrontier(check): sp = len(spots) nearby = [tuple([check[0], check[1] - 20]), tuple([check[0] + 20, check[1] - 20]), tuple([check[0] + 20, check[1]]), tuple([check[0] + 20, check[1] + 20]), tuple([check[0], check[1] + 20]), tuple([check[0] - 20, check[1] + 20]), tuple([check[0] - 20, check[1]]), tuple([check[0] - 20, check[1] - 20]), tuple([check[0], check[1]])] for u in nearby: for i in range(sp): if spots[i].x == u[0] and spots[i].y == u[1] and spots[i].obstacle == 0 and spots[i].visited == 0: spots[i].fron = 1 def makeFrontArray(): frontier = [] sp = len(spots) for i in range(sp): if spots[i].fron == 1: fill = tuple([spots[i].x, spots[i].y]) frontier.append(fill) return frontier main()
e7bbd1f5bd55f8c5bd77fc5121432e30d10be53b
chethan-kt/Python-Exercises
/q44.py
467
3.984375
4
""" Question: Define a class named American which has a static method called printNationality. Hints: Use @staticmethod decorator to define class static method. """ class American: def __init__(self, name): self.name = name def printName(self): print self.name @staticmethod def printNationality(): print "American" a1 = American("Tom") a1.printName() a1.printNationality() American.printNationality()
47a5fd83a313fdf2c098e948bab0db783ef5bc8f
yibeihuang/LeetCode
/wordladder.py
1,155
3.671875
4
__author__ = 'yibeihuang' def construct_dict(word_list): d = {} for word in word_list: for i in range(len(word)): s = word[:i] + "_" + word[i+1:] # tmp = d.get(s, []) dict.get(key, default=None), # default is the Value to be returned in case key does not exist. d[s] = d.get(s, []) + [word] return d def ladderLength(beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: Set[str] :rtype: int """ queue, visited = [(beginWord,1)], set(beginWord) while queue: word, length = queue.pop(0) if word==endWord: return length for j in range(len(word)): for i in 'abcdefghijklmnopqrstuvwxyz': tmp = word[:j]+i+word[j+1:] if tmp not in visited and tmp in wordList: queue.append((tmp,length+1)) visited.add(tmp) return 0 word_list=["a","b","c"] print(ladderLength("a","c",word_list))
0f3273d0c46be8f11fc723b40e290d025ce41f11
Sakariyeyare/ZY-ZAKI
/cal.py
4,287
3.796875
4
from tkinter import * root=Tk() root.title("Calculator") #functions text_input = StringVar() operator='' def button_click(numbers): global operator operator = operator + str(numbers) text_input.set(operator) def button_clearDisplay(): global operator operator ='' text_input.set('') def button_equalInput(): global operator sumup = str(eval(operator)) text_input.set(sumup) operator ='' #buttons text_display = Entry(font=("arial", 20, "bold"), textvariable=text_input, bg='powder blue', bd=30, insertwidth=4, justify='right') text_display.grid(columnspan=4) button7 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='7', \ command=lambda :button_click(7)).grid(row=2, column=0) button8 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='8', \ command=lambda :button_click(8)).grid(row=2, column=1) button9 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='9', \ command=lambda :button_click(9)).grid(row=2, column=2) button_add = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='+', \ command=lambda :button_click('+')).grid(row=2, column=3) button4 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='4', \ command=lambda :button_click(4)).grid(row=3, column=0) button5 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='5', \ command=lambda :button_click(5)).grid(row=3, column=1) button6 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='6', \ command=lambda :button_click(6)).grid(row=3, column=2) button_subtraction= Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='-', \ command=lambda :button_click('-')).grid(row=3, column=3) button1 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='1', \ command=lambda :button_click(1)).grid(row=4, column=0) button2 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='2', \ command=lambda :button_click(2)).grid(row=4, column=1) button3 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='3', \ command=lambda :button_click(3)).grid(row=4, column=2) button_multiply = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='*', \ command=lambda :button_click('*')).grid(row=4, column=3) button0 = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='0', \ command=lambda :button_click(0)).grid(row=5, column=0) button_clear = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='C', \ command =button_clearDisplay).grid(row=5, column=1) button_equal = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='=', \ command=button_equalInput).grid(row=5, column=2) button_divide = Button( padx=16, pady=16, bd=8, bg='powder blue', fg='black', font=('arial',20,'bold'), text='/', \ command=lambda :button_click('/')).grid(row=5, column=3) root.mainloop()
a2e8a459047b57a854e6e7513b204cdb96dd96f3
IgorProninP/Codewars
/range_extraction.py
1,395
4.65625
5
""" A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17" Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" """ def solution(args): result = [] temp = [args[0]] for digit in args[1:]: if digit - temp[-1] > 1: if len(temp) > 2: result.append(f'{temp[0]}-{temp[-1]}') temp = [digit] else: for num in temp: result.append(str(num)) temp = [digit] else: temp.append(digit) if len(temp) > 2: result.append(f'{temp[0]}-{temp[-1]}') else: for i in temp: result.append(str(i)) return ','.join(result) if __name__ == '__main__': data = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20, 22, 23] print(solution(data))
a5db9fd26eb9545e406d36be36477fa52082e13b
chaksamu/python
/venv/dict.py
1,300
3.640625
4
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print (Dict['Tiffany']) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print((Dict['Tiffany'])) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print(studentX) print(studentY) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print(Dict) Dict.update({"Sarah":9}) print(Dict) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print(Dict) del Dict ['Charlie'] print(Dict) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print( "Students Name: %s " % Dict.items() ) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("Students Name: %s" % list(Dict.items())) Dict={'Chakri': 20, 'Chandu': 21, 'Jaya': 22, 'Asu': 23} #Boys={'Chakri': 20, 'Chandu': 21, 'Jaya': 22} #Girls={'Asu': 23} Students=list(Dict.keys()) Students.sort() for S in Students: print(":".join((S,str(Dict[S])))) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("Length : %d" % len (Dict)) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("variable Type: %s" %type (Dict)) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("printable string:%s" % str (Dict))
f17bfb2851d61d7fdd1acfabb07cb9e0a9730424
bema97/home_work
/ch2task_3.py
117
3.953125
4
number = int(input("Please, enter a number: ")) previous = number - 1 next = number + 1 print(previous, number, next)
5a696eb6bafe109af3ad7e2ba972fd2bdbc7ed1f
lordjuacs/ICC-Trabajos
/Ciclo 1/Examen 3/27busqueda_binaria_numero_comparaciones.py
910
3.75
4
def busquedaBinaria(Lista, item): low = 0 high = len(Lista) - 1 comparacion = 0 encontrado = False while (low <= high) and not encontrado: mid = low + (high - low) // 2 if Lista[mid] == item: comparacion += 1 encontrado = True else: if item < Lista[mid]: high = mid - 1 comparacion += 1 else: low = mid + 1 comparacion += 1 return (encontrado, comparacion) lista = [10,20,30,40,50,60,70,80,90] buscar = int(input("Ingrese numero a buscar: ")) (si_o_no, compa) = busquedaBinaria(lista, buscar) if si_o_no == True: print("El numero " + str(buscar) + " se encuentra en la lista despues de " + str(compa) + " comparaciones") else: print("El numero " + str(buscar) + " no se encuentra en la lista despues de " + str(compa) + " comparaciones")
1b264907d11eaa4f392456bb05f2f0bc7a4ec57d
brrgrr/LC101_Unit1
/chapters/chapter8_excercises.py
8,430
4.0625
4
#1 def print_triangular_numbers(n): sum=0 for i in range(n): sum += (i+1) print(sum) def main(): print_triangular_numbers(5) if __name__ == "__main__": main() #2 import random import turtle def is_in_screen(screen, t): left_bound = - screen.window_width() / 2 right_bound = screen.window_width() / 2 top_bound = screen.window_height() / 2 bottom_bound = -screen.window_height() / 2 turtle_x = t.xcor() turtle_y = t.ycor() still_in = True if turtle_x > right_bound or turtle_x < left_bound: still_in = False if turtle_y > top_bound or turtle_y < bottom_bound: still_in = False return still_in def main(): julia = turtle.Turtle() screen = turtle.Screen() julia.shape('turtle') while is_in_screen(screen, julia): julia.seth(random.randrange(0,360, 30)) julia.forward(50) screen.exitonclick() if __name__ == "__main__": main() #3 import random import turtle wn = turtle.Screen() left_bound = -wn.window_width() / 2 right_bound = wn.window_width() / 2 top_bound = wn.window_height() / 2 bottom_bound = -wn.window_height() / 2 def random_start(t): t.ht() t.up() t.goto(random.randrange(left_bound, right_bound), random.randrange(bottom_bound, top_bound)) t.seth(random.randrange(0,360,90)) t.down() t.st() def walk(t): coin = random.randrange(0, 2) if coin == 0: t.left(90) else: t.right(90) t.forward(50) def is_in_screen(t): turtle_x = t.xcor() turtle_y = t.ycor() still_in = True if turtle_x > right_bound or turtle_x < left_bound: still_in = False if turtle_y > top_bound or turtle_y < bottom_bound: still_in = False return still_in def main(): ben = turtle.Turtle() liz = turtle.Turtle() random_start(ben) random_start(liz) ben.color('green') liz.color('yellow') while is_in_screen(ben) and is_in_screen(liz): walk(ben) walk(liz) wn.exitonclick() if __name__ == "__main__": main() #4 import random import turtle import math wn = turtle.Screen() left_bound = -wn.window_width() / 2 right_bound = wn.window_width() / 2 top_bound = wn.window_height() / 2 bottom_bound = -wn.window_height() / 2 def random_start(t): t.speed(0) t.ht() t.up() t.goto(random.randrange(left_bound, right_bound), random.randrange(bottom_bound, top_bound)) t.seth(random.randrange(0,360,90)) t.down() t.st() def walk(t1, t2): for t in [t1,t2]: t.left(random.choice([-90,90])) for i in range(50): t.forward(2) if is_bounce(t1,t2): t.seth(t.heading()+180) def is_in_screen(t): turtle_x = t.xcor() turtle_y = t.ycor() still_in = True if turtle_x > right_bound or turtle_x < left_bound: still_in = False if turtle_y > top_bound or turtle_y < bottom_bound: still_in = False return still_in def is_bounce(t1, t2): bounce = False for t in [t1,t2]: turtle_x = t.xcor() turtle_y = t.ycor() if min( abs(turtle_x - right_bound), abs(turtle_x - left_bound), abs(turtle_y - top_bound), abs(turtle_y - bottom_bound)) < 5: bounce = True if t1.distance(t2) < 5: bounce = True return bounce def main(): ben = turtle.Turtle() liz = turtle.Turtle() random_start(ben) random_start(liz) ben.color('green') liz.color('yellow') while is_in_screen(ben) and is_in_screen(liz): walk(ben,liz) else: ben.home() liz.home() wn.exitonclick() if __name__ == "__main__": main() #5 import sys def workout_coach(lift_name, wt): print("Time to", lift_name, wt, "pounds! You got this!") def main(): sys.setExecutionLimit(120000) # keep program from timing out lifts = ["squat", "bench", "deadlift"] # Your code here for lift_name in lifts: wt = 10 input_prompt = "Keep doing the " + lift_name + "? Enter yes for the next set." keep_going = 'yes' while keep_going == 'yes': workout_coach(lift_name, wt) keep_going =input(input_prompt) wt +=10 if lift_name == 'bench' and wt > 200: break elif keep_going != 'yes': break else: continue if __name__ == "__main__": main() #6 import image def remove_red(p): new_red = 0 green = p.getGreen() blue = p.getBlue() new_pixel = image.Pixel(new_red, green, blue) return new_pixel img = image.Image("luther.jpg") new_img = image.EmptyImage(img.getWidth(), img.getHeight()) win = image.ImageWin(img.getWidth(), img.getHeight()) for col in range(img.getWidth()): for row in range(img.getHeight()): p = img.getPixel(col, row) new_img.setPixel(col, row, remove_red(p)) new_img.draw(win) win.exitonclick() #7 import image def grayscale(p): red = p.getRed() green = p.getGreen() blue = p.getBlue() gray = (red + green + blue) / 3 new_pixel = image.Pixel(gray, gray, gray) return new_pixel img = image.Image("luther.jpg") new_img = image.EmptyImage(img.getWidth(), img.getHeight()) win = image.ImageWin(img.getWidth(), img.getHeight()) for col in range(img.getWidth()): for row in range(img.getHeight()): p = img.getPixel(col, row) new_img.setPixel(col, row, grayscale(p)) new_img.draw(win) win.exitonclick() #8 import image def grayscale(p): red = p.getRed() green = p.getGreen() blue = p.getBlue() gray = (red + green + blue) /3 new_pixel = image.Pixel(gray, gray, gray) return new_pixel def black_white(p): grayscale(p) if p.getRed() < 128: bw = 0 else: bw = 255 new_pixel = image.Pixel(bw, bw, bw) return new_pixel img = image.Image("luther.jpg") new_img = image.EmptyImage(img.getWidth(), img.getHeight()) win = image.ImageWin(img.getWidth(), img.getHeight()) img.draw(win) for col in range(img.getWidth()): for row in range(img.getHeight()): p = img.getPixel(col, row) new_img.setPixel(col, row, black_white(p)) new_img.draw(win) win.exitonclick() #9 import image def sepia(p): R = p.getRed() G = p.getGreen() B = p.getBlue() new_r = min(int(R * 0.393 + G * 0.769 + B * 0.189),255) new_g = min(int(R * 0.349 + G * 0.686 + B * 0.168),255) new_b = min(int(R * 0.272 + G * 0.534 + B * 0.131),255) new_pixel = image.Pixel(new_r, new_g, new_b) return new_pixel img = image.Image("luther.jpg") new_img = image.EmptyImage(img.getWidth(), img.getHeight()) win = image.ImageWin(img.getWidth(), img.getHeight()) img.draw(win) for col in range(img.getWidth()): for row in range(img.getHeight()): p = img.getPixel(col, row) new_img.setPixel(col, row, sepia(p)) new_img.draw(win) win.exitonclick() #10 import image def double(old_image): old_w = old_image.getWidth() old_h = old_image.getHeight() new_img = image.EmptyImage(old_w * 2, old_h * 2) for row in range(old_h): for col in range(old_w): old_pixel = old_image.getPixel(col, row) new_img.setPixel(2*col, 2*row, old_pixel) new_img.setPixel(2*col+1, 2*row, old_pixel) new_img.setPixel(2*col, 2*row+1, old_pixel) new_img.setPixel(2*col+1, 2*row+1, old_pixel) return new_img def main(): img = image.Image("luther.jpg") win = image.ImageWin(img.getWidth() * 2, img.getHeight() * 2) big_img = double(img) big_img.draw(win) win.exitonclick() if __name__ == "__main__": main() #Weekly Graded Assignment def course_grader(test_scores): ''' sum_scores=0 for i in test_scores: sum_scores += i ''' avg_score = sum(test_scores) / len(test_scores) if avg_score < 70 or min(test_scores) < 50: message = 'fail' elif avg_score >= 70 and min(test_scores) > 50: message = 'pass' return message def main(): print(course_grader([100,75,45])) # "fail" print(course_grader([100,70,85])) # "pass" print(course_grader([80,60,60])) # "fail" print(course_grader([80,80,90,30,80])) # "fail" print(course_grader([70,70,70,70,70])) # "pass" if __name__ == "__main__": main()
a6a963b7e4503c9cdac63efdcd034483c383f325
TverskayN/The_invasion_of_the_cats
/spray.py
2,061
3.59375
4
import pygame from pygame.sprite import Sprite class Spray(Sprite): """Класс реализующий действия пульверизатора (пульвика).""" def __init__(self, ai_setting, screen): """Инициализирует пульвелизатор и задает его начальное положение.""" super(Spray, self).__init__() self.screen = screen self.ai_setting = ai_setting # Загрузка изображения пульвика и получение прямоугольника. self.image = pygame.image.load('images/spray.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # Каждый новый пульвик появляется у левого края экрана. self.rect.centery = self.screen_rect.centery self.rect.left = self.screen_rect.left # Сохранение вещественной координаты центра пульвика self.center = float(self.rect.centery) # Флаг перемещения self.moving_down = False self.moving_up = False def update(self): """Обновляет позицию пульвика с учетом флагов.""" # Обновляем атрибут center, не rect. if self.moving_down and self.rect.centery < 2 * self.screen_rect.centery: self.rect.centery += self.ai_setting.spray_speed_factor elif self.moving_up and self.rect.centery > 0: self.rect.centery -= self.ai_setting.spray_speed_factor # Обновление атрибута rect на основании self.center. def blitme(self): """Рисует пульвик в текущей позиции.""" self.screen.blit(self.image, self.rect) def center_spray(self): """Размещает корабль в центре левой стороны.""" self.rect.centery = self.screen_rect.centery
878a14db796af689ae9e2fd8a71392427536d833
jianghan0001/python
/FishC/regist and login.py
1,430
4.0625
4
#用dict建立账号及登录系统 user_data={} def new_user(): promp = 'Please enter username' while True: username=input(promp) if username in user_data: print ('username has already been used.') continue else: break psw= input('Please set you password') user_data[username]=psw print ('Registration complete, give it a try!') def sign_in(): promp = 'Please enter username' while True: username = input(promp) if username not in user_data: print('username not available, please reenter') continue else: break psw = input('Please enter you password') if psw != user_data[username]: print('Your password is wrong!') else: print('Wellcome to xxoo system!') def showMenu(): prompt = ''' |--- 新建用户:N/n ---| |--- 登录账号:E/e ---| |--- 推出程序:Q/q ---| |--- 请输入指令代码:''' while True: pa= False while not pa: code = input(prompt) if code not in 'NnEeQq': print('代码错误 重新输入') else: pa = True if code == 'Q' or code == 'q': break if code == 'N' or code == 'n': new_user() if code == 'E' or code == 'e' sign_in() showMenu()
0121b869d89763148c8a92b7fb2806ff5d58cbd2
youngcadam/leetcode
/problem5.py
3,866
3.5
4
'''approach 1 class Solution: def longestPalindrome(self, s: str) -> str: max_len = 0 curr_len = 0 max_substr = "" length = len(s) if length == 0: return "" if length == 1: return s[0] elif length == 2: if s[0] == s[1]: return s else: return s[0] for c in range(1, length): i, j = c - 1, c # if the middle two elements are the same if s[i] == s[j]: curr_len = 2 j = j + 1 # move j right until different while j < length: if s[i] == s[j]: curr_len = curr_len + 1 j = j + 1 else: j = j - 1 break if j == length: j = j - 1 # move i left until different i = i - 1 while i >= 0: if s[i] == s[j]: curr_len = curr_len + 1 i = i - 1 else: i = i + 1 break if i < 0: i = i + 1 # if we reached the end of the string if i == 0 or j == length - 1: if curr_len > max_len: max_substr = s[i:i + curr_len] max_len = curr_len curr_len = 0 continue # otherwise, see if palindrome extends beyond the identical elements else: i, j = i - 1, j + 1 while i >= 0 and j < length: if s[i] == s[j]: i, j = i - 1, j + 1 curr_len = curr_len + 2 else: i = i + 1 j = j - 1 break if i < 0: i += 1 if curr_len > max_len: max_substr = s[i:i + curr_len] max_len = curr_len curr_len = 0 else: curr_len = 0 # otherwise, middle element is unique (e.g. cowoc) else: j = j + 1 curr_len = 1 while i >= 0 and j < length: if s[i] == s[j]: curr_len += 2 i, j = i - 1, j + 1 else: break # reset indices to where s[i] == s[j] last i = i + 1 if curr_len > max_len: max_substr = s[i:i + curr_len] max_len = curr_len curr_len = 0 else: curr_len = 0 return max_substr ''' # Dynamic programming aproach # # import numpy as np s = "aabacdddc" max_str = "" length = len(s) x = np.identity(length) if length == 0: print("") if length == 1: print(s[0]) if length == 2: if s[0] == s[1]: print(s) else: prin(s[0]) # check P(i,i + 1) for palindromes of length 2 for i in range(length - 1): if s[i] == s[i + 1]: x[i, i + 1] = 1 # check for palindromes of length >= 3 for j in range(2, length): for i in range(length - j): if x[i + 1, i + j - 1] and s[i] == s[i + j]: x[i, i + j] = 1 max_str = s[i:i + j + 1]
362ee858aa13aa4ee9df941b5185a921badb555b
ramanenka/cormen
/foundations/test_merge_sort_with_insertion_sort.py
534
3.578125
4
from merge_sort import merge_sort from insertion_sort import insertion_sort from merge_sort_with_insertions_sort import merge_sort_with_insertions_sort import random import time a = [random.random() for i in range(100000)] a1 = a[:] start = time.time() merge_sort(a1, 0, len(a1) - 1, 0) print(time.time() - start) # a2 = a[:] # start = time.time() # insertion_sort(a2, 0, len(a2) - 1) # print(time.time() - start) a3 = a[:] start = time.time() merge_sort_with_insertions_sort(a3, 0, len(a3) - 1, 6, 0) print(time.time() - start)
1e2ea827fe6273131dc841c3fcbe9a90de98404a
alvesdealmeida/Projeto_Python_TSC_UFF
/AD2Q2.py
1,887
3.71875
4
import struct def processarArquivo(nomeArquivo,resultadoSorteio): print("Conteúdo do Arquivo de Apostas",nomeArquivo+":") totalApostas = 0 acertos = dict() for qtdAcertos in range(3, 9): acertos[qtdAcertos] = set() with open(nomeArquivo, "r") as arquivo: for linha in arquivo: print(linha, end="") if(len(linha.split("#"))>1): totalApostas = totalApostas + 1 nomeApostador = linha.split("#")[0] numerosJogados = set(map(int, linha.split("#")[1:])) qtdAcertos = len(resultadoSorteio & numerosJogados) if(qtdAcertos >= 3): acertos[qtdAcertos].add(nomeApostador) print("---- Fim do Arquivo de Apostas ----\n") return totalApostas,acertos def imprimeResultados(totalAposta, acertos): if (totalAposta == 0): print("“Nenhuma Aposta!!!") else: print("Total de Apostas:", totalAposta) existeVencedor = False for qtdAcertos in range(8, 2, -1): if (len(acertos[qtdAcertos]) == 0): print("Ninguém Acertou", qtdAcertos, "Números!!!") else: existeVencedor = True print("Foi(ram)", len(acertos[qtdAcertos]), "Ganhador(es) com", qtdAcertos, "Acertos:") for nomesGanhador in sorted(acertos[qtdAcertos]): print('\t', nomesGanhador) if (existeVencedor == False): print("ACUMULOU TUDO") def main(): nomeArquivo = input()+".txt" resultadoSorteio = set(map(int, input().split())) try: totalAposta,acertos = processarArquivo(nomeArquivo,resultadoSorteio) imprimeResultados(totalAposta,acertos) except IOError: print('O arquivo não foi encontrado') main()
2f5a967bd6e64ee5776fcc63f6db22bca2aadd53
jameschenmech/Deep_Learning_Keras
/keras_intro.py
6,506
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 14 09:36:08 2018 @author: junch """ # ============================================================================= # #Forward propagation with one hidden layer # ============================================================================= import numpy as np input_data = np.array([2,3]) weights = {'node_0':np.array([1,1]), 'node_1':np.array([-1,1]), 'output':np.array([2,-1])} node_0_value = (input_data*weights['node_0']).sum() node_1_value = (input_data*weights['node_1']).sum() hidden_layer_values = np.array([node_0_value, node_1_value]) print("\nFirst model deep learning") print("hidden layer: ", hidden_layer_values) output = (hidden_layer_values*weights['output']).sum() print("output: ",output) # ============================================================================= # #Another example of one hidden layer # ============================================================================= input_data = np.array([3, 5]) weights = {'node_0':np.array([2,4]), 'node_1':np.array([4,-5]), 'output':np.array([2,7])} node_0_value = (input_data*weights['node_0']).sum() node_1_value = (input_data*weights['node_1']).sum() hidden_layer_values = np.array([node_0_value, node_1_value]) print("\nSecond model deep learning") print("hidden layer: ", hidden_layer_values) output = (hidden_layer_values*weights['output']).sum() print("output: ",output) # ============================================================================= # #Activation functions #captures non-linearities inthe hidden layers #applied coming into the node #relu function #tanh function was popular previously # ============================================================================= input_data = np.array([-1,2]) weights = {'node_0':np.array([3,3]), 'node_1':np.array([1,5]), 'output':np.array([2,-1])} #activation function applied to the node input node_0_input = (input_data*weights['node_0']).sum() node_0_output = np.tanh(node_0_input) #activation function applied to the node input node_1_input = (input_data*weights['node_1']).sum() node_1_output = np.tanh(node_1_input) #new hidden layer values hidden_layer_outputs = np.array([node_0_output, node_1_output]) print("\nLearning model with activation tanh function") print("hidden layer outputs: ", hidden_layer_outputs) output = (hidden_layer_outputs*weights['output']).sum() print("output: ",output) # ============================================================================= # #Using the RELU activation function # ============================================================================= def relu(input): '''Define relu activation function''' output = max(input,0) return output input_data = np.array([3,5]) weights = {'node_0':np.array([2,4]), 'node_1':np.array([4,-5]), 'output':np.array([2,7])} #activation function applied to the node input node_0_input = (input_data*weights['node_0']).sum() node_0_output = relu(node_0_input) #activation function applied to the node input node_1_input = (input_data*weights['node_1']).sum() node_1_output = relu(node_1_input) #new hidden layer values hidden_layer_outputs = np.array([node_0_output, node_1_output]) print("\nLearning model with activation RELU function") print("hidden layer outputs: ", hidden_layer_outputs) final_input_layer = (hidden_layer_outputs*weights['output']).sum() output = relu(final_input_layer) print("output: ",output) # ============================================================================= # #Apply to many observations/rows of data # ============================================================================= input_data = [np.array([3,5]), np.array([1,-1]),np.array([0,0]),\ np.array([8,4])] weights = {'node_0':np.array([2,4]), 'node_1':np.array([4,-5]), 'output':np.array([2,7])} #define predict with network def predict_with_network(input_data_row, weights): #activation function applied to the node input node_0_input = (input_data_row*weights['node_0']).sum() node_0_output = relu(node_0_input) #activation function applied to the node input node_1_input = (input_data_row*weights['node_1']).sum() node_1_output = relu(node_1_input) #new hidden layer values hidden_layer_outputs = np.array([node_0_output, node_1_output]) # print("\nLearning model with activation RELU function") # print("hidden layer outputs: ", hidden_layer_outputs) input_to_final_layer = (hidden_layer_outputs*weights['output']).sum() model_output = relu(input_to_final_layer) # print("output: ",model_output) return model_output #Create empty list to store prediction results results=[] for input_data_row in input_data: results.append(predict_with_network(input_data_row, weights)) print("\nresults for list of different inputs:") print(results) # ============================================================================= # #Deeper Networks # ============================================================================= def predict_with_network_2d(input_data): #activation function applied to the node input node_0_0_input = (input_data*weights['node_0_0']).sum() node_0_0_output = relu(node_0_0_input) #activation function applied to the node input node_0_1_input = (input_data*weights['node_0_1']).sum() node_0_1_output = relu(node_0_1_input) #new hidden layer values hidden_0_outputs = np.array([node_0_0_output, node_0_1_output]) #activation function applied to the node input node_1_0_input = (hidden_0_outputs*weights['node_1_0']).sum() node_1_0_output = relu(node_1_0_input) #activation function applied to the node input node_1_1_input = (hidden_0_outputs*weights['node_1_1']).sum() node_1_1_output = relu(node_1_1_input) #new hidden layer values hidden_1_outputs = np.array([node_1_0_output, node_1_1_output]) input_to_final_layer = np.array(hidden_1_outputs*weights['output']).sum() model_output = relu(input_to_final_layer) return model_output weights = {'node_0_0':np.array([2,4]), 'node_0_1':np.array([4,-5]), 'node_1_0':np.array([-1,2]), 'node_1_1':np.array([1,2]), 'output':np.array([2,7])} input_data = np.array([3,5]) output = predict_with_network_2d(input_data) print("\n2 layer networkd output:") print(output)
ff335cc32fa9d4af33b39e95c41fd9ddbc35555d
imgomez0127/daily-programming
/interview-questions/dip3.py
529
3.65625
4
class Solution: def longestPalindrome(self, s): cur_max = "" string_length = len(s) for i in range(string_length): for j in range(string_length): reversed_string = "".join(reversed(s[i:j])) if s[i:j] == reversed_string and len(reversed_string) > len(cur_max): cur_max = s[i:j] return cur_max # Test program s = "tracecars" print(s) print(str(Solution().longestPalindrome(s))) # racecar
381471abaa18c629ae53bbcfa3bbe52e66dd933c
Bryant6/deep-learning
/numpy_pandas/numpy_study.py
3,014
3.59375
4
import numpy as np # ==================================================== # numpy 的基本属性 # ==================================================== array = np.array([[1, 2, 3], [2, 3, 4]]) print(array) print("number of dim: ", array.ndim) print("shape: ", array.shape) print("size: ", array.size) # ==================================================== # numpy array的创建 # ==================================================== a = np.array([2, 23, 4], dtype=np.float32) print(a.dtype) b = np.zeros((3, 4), dtype=int) print(b) b = np.ones((3, 4), dtype=int) print(b) b = np.empty((3, 4)) print(b) b = np.arange(10, 20, 2) # [10 12 14 16 18] print(b) b = np.arange(12).reshape((3, 4)) print(b) b = np.linspace(1, 10, 5) # [ 1. 3.25 5.5 7.75 10. ] print(b) # ==================================================== # numpy 基本运算 # ==================================================== a = np.array([10, 20, 30, 40]) b = np.arange(4) print(a, b) print(a-b, a+b) print(a**2) # 平方 print(np.sin(a)) print(b < 3) A = np.array([[1, 1], [0, 1]]) B = np.arange(4).reshape((2, 2)) print(A, '\n', B) print(A * B) # 逐个相乘 print(np.dot(A, B)) # 矩阵乘法 print(A.dot(B)) a = np.random.random((2, 4)) # 0-1 print(a) print(np.sum(a), np.min(a), np.max(a)) print(np.sum(a, axis=1), np.min(a, axis=0), np.max(a, axis=1)) # axis=1(行) A = np.arange(2, 14).reshape((3, 4)) print(A) print(np.argmin(A)) # 最小值索引 print(np.mean(A), A.mean(), np.average(A)) # 平均值 print(np.median(A)) # 中位数 print(np.cumsum(A)) # 累加 print(np.diff(A)) # 累差 print(np.nonzero(A)) print(np.sort(A)) # 逐行排序 print(np.transpose(A), A.T) print(np.clip(A, 5, 9)) print(np.mean(A, axis=0)) # ==================================================== # numpy 索引 # ==================================================== A = np.arange(3, 15) B = A.reshape((3, 4)) print(A) print(B) print(A[3]) print(B[1][1], B[1, 1]) for row in A: print(row) print(A.flat) # ==================================================== # numpy array 合并 # ==================================================== A = np.array([1, 1, 1]) B = np.array([2, 2, 2]) print(np.vstack((A, B))) # 向下合并 print(np.hstack((A, B))) # 向右合并 print(A[np.newaxis, :]) print(A[:, np.newaxis]) print(np.concatenate((A, B, B, A, A), axis=0)) # ==================================================== # numpy array 分割 # ==================================================== A = np.arange(12).reshape((3, 4)) print(A) print(np.split(A, 3, axis=0)) print(np.array_split(A, 3, axis=1)) # 允许不等分割 print(np.vsplit(A, 3)) print(np.hsplit(A, 2)) # ==================================================== # numpy array copy # ==================================================== a = np.arange(4) print(a) b = a c = a d = b a[0] = 11 print(a, b is a) b = a.copy() # 仅赋值 print(b is a)
066099065c374b37028d76a785e7918f69139dae
jade0304/python-exercise
/34_same_frequency/same_frequency.py
1,122
3.65625
4
def same_frequency(num1, num2): """Do these nums have same frequencies of digits? >>> same_frequency(551122, 221515) True >>> same_frequency(321142, 3212215) False >>> same_frequency(1212, 2211) True """ # my own result: count = {} count2 = {} for num in list(num1): count[num] = count.get(ltr, 0) + 1 max_key = max(count.values()): for (key, val) in count.items(): if val == max_key: num1_key = key for num2 in list(num2): count2[num2] = count2.get(ltr, 0) + 1 max_key = max(count2.values()): for (key, val) in count2.items(): if val == max_key: num2_key = key return if num1_key == num2_key #create a func freq_counter() # def freq_counter(coll): # """Returns frequency counter mapping of coll.""" # counts = {} # for x in coll: # counts[x] = counts.get(x, 0) + 1 # return counts # def same_frequency(num1, num2): # return freq_counter(str(num1)) == freq_counter(str(num2))
07f80a37a99f83fdc2db51b6d2ca44c1666dec13
lillelarsen/python-crash-course
/dictionaries.py
810
4.03125
4
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # Create dict person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 30 } print(person, type(person)) # # Use constructor # person2 = dict(first_name='Sara', last_name='Williams') # Get value print(person['first_name']) print(person.get('last_name')) # Add key/value person['phone'] = '666-666-6666' # Get dict keys print(person.keys()) # Get dict items print(person.items()) # Copy dict person2 = person.copy() person2['City'] = 'Boston' print(person2) # Remove item del(person['age']) person.pop('phone') # Clear person.clear() # Get length print(len(person2)) # List of dict people = [ {'name': 'Martha', 'age': 30}, {'name': 'Kevin', 'age': 25} ] print(people[1]['name'])
e03316571a6cea5ec355878c8e5183cbde76bfda
lumecre/tema_8
/8.1_unit_converter.py
468
3.84375
4
#programa realizado para una trasformacion de km a millas trans= int(raw_input("introduce los km: ")) miles= trans * 1.6 print str(trans) + " km son " + str(miles) + " millas " ask= int(raw_input("desea hacer otra conversion, si o no? : ")) if trans= int(raw_input("introduce los km: ")) miles= trans * 1.6 print str(trans) + " km son " + str(miles) + " millas " ask= int(raw_input("desea hacer otra conversion? : ")) elif deniega print "adios y gracias"
ac4efbba9de2f9687a4668a5dad1c63459c490b6
parkourben99/SpeedOfPi
/lib/timer.py
502
3.609375
4
import time class Timer(object): def __init__(self): self.__start_time = 0 self.__end_time = 0 def start(self): self.__start_time = time.time() def stop(self): self.__end_time = time.time() total_time = self.__calc_total_time() self.__reset() return total_time def __calc_total_time(self): return self.__end_time - self.__start_time def __reset(self): self.__start_time = 0 self.__end_time = 0
8f29e973d0d2b7c57464f7dc9afe08607372d747
Xaaris/Hauptprojekt
/src/lp_validation/LPValidationNetWithDataAugmentation.py
3,000
3.84375
4
""" Trains a simple convnet on images to determine if they show a full license plate or not. To enhance the training effect on the relatively small data set, data augmentation is used Based on https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html """ import os import keras import numpy as np from keras.layers import Activation, Dropout, Flatten, Dense from keras.layers import Conv2D, MaxPooling2D from keras.models import Sequential from keras.preprocessing.image import ImageDataGenerator from src.utils.image_utils import resize_image img_rows, img_cols = 50, 150 batch_size = 32 def create_model(): model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(img_rows, img_cols, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts the 3D feature maps to 1D feature vectors model.add(Dense(64)) model.add(Activation("relu")) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation("sigmoid")) model.compile(loss="binary_crossentropy", optimizer=keras.optimizers.Adam(), metrics=["accuracy"]) print(model.summary()) return model def train_model(model): train_datagen = ImageDataGenerator( rotation_range=3, shear_range=3, brightness_range=(1, 1.2)) test_datagen = ImageDataGenerator(brightness_range=(1, 1.2)) train_generator = train_datagen.flow_from_directory( "data/train", target_size=(img_rows, img_cols), # all images will be resized to 50x150 batch_size=batch_size, class_mode="binary") # since we use binary_crossentropy loss, we need binary labels validation_generator = test_datagen.flow_from_directory( "data/test", target_size=(img_rows, img_cols), batch_size=batch_size, class_mode="binary") model.fit_generator( train_generator, steps_per_epoch=307 // batch_size, epochs=20, validation_data=validation_generator, validation_steps=88 // batch_size) model.save_weights("model_data/lp_validation.h5") def load_weights(model): model.load_weights(os.path.abspath("src/lp_validation/model_data/lp_validation.h5")) def predict(model, license_plate_candidate): """returns a boolean whether the model predicts the 'license_plate_candidate' to be a valid license plate""" resized_patch = resize_image(license_plate_candidate, (img_cols, img_rows)) expanded_dims_for_batch = np.expand_dims(resized_patch, axis=0) prediction = model.predict(expanded_dims_for_batch) if prediction[0][0] < 0.5 and prediction[0][1] > 0.5: return True else: return False
9ddf7f4a9c468ea2b9c958f1fcf222cb213437dd
merimus/coding-bootcamp
/euler/merimus/21/21.py
425
3.515625
4
def divisors(n): # return list (numbers less than n which divide evenly into n) return [i for i in range(1, (n+1)/2+1) if n % i == 0] d_mem = dict() def d(n): if n in d_mem: return d_mem[n] d_mem[n] = sum(divisors(n)) return d_mem[n] def isAmicable(n): a = d(n) if a == n: return False; b = d(a) return b == n print sum([n for n in range(1, 10000-1) if isAmicable(n)])
8cb0330f88caaf8c95f6889d02176ee68caf4dc4
SeanyDcode/codechallenges
/dailychallenge1014.py
735
3.6875
4
# from dailycodingproblem.com # # Daily Challenge #1014 # Given a start word, an end word, and a dictionary of valid words, find the shortest transformation sequence from start to end such # that only one letter is changed at each step of the sequence, and each transformed word exists in the dictionary. If there is no # possible transformation, return null. Each word in the dictionary have the same length as start and end and is lowercase. # # For example, given start = "dog", end = "cat", and dictionary = {"dot", "dop", "dat", "cat"}, return ["dog", "dot", "dat", "cat"]. # # Given start = "dog", end = "cat", and dictionary = {"dot", "tod", "dat", "dar"}, return null as there is no possible transformation # from dog to cat.
b3562fd813f7a871b60aa1d8ddf876ff1a527cd2
gokou00/python_programming_challenges
/codesignal/extractMatrixColumn.py
296
3.65625
4
def extractMatrixColumn(matrix, column): arr = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if j == column: arr.append(matrix[i][j]) return arr print(extractMatrixColumn([[1,1],[5,0],[2,3]] ,0))
55c8283ff65ffeabec04fba48efc62f111af535f
newfull5/Programmers
/다음에 올 숫자.py
147
3.53125
4
def solution(common): a,b,c = common[:3] if a-b == b-c: return common[-1] + (b-a) else: return common[-1] * (b/a)
4663c637185ad0717e840cde573f8b7ac251ef26
sikami/Python-3
/ass_85.py
433
3.984375
4
#open file and read #if name starts from 'From ', extract 2nd word #print words a = input() if len(a) < 1: a = "mbox-short.txt" fname = open(a) count = 0 emails = list() for line in fname: if line.startswith("From "): words = line.split() emails.append(words[1]) count += 1 for email in emails: print(email) print("There were", count, "lines in the file with From as the first word")
ba0846beebba9c04f8c767efc186ba695512500c
huantar/projet_algo_texte
/model/distancePage.py
1,231
3.578125
4
# Nous avons decide d'utiliser la distance de hamming, # car aprés plusieurs test c'etait l'algo le plus rapide ######## hamming ######## # Calcule la distance de hamming entre deux string et retourne sa valeur def dist_hamming(m1,m2): d = 0 for a,b in zip(m1,m2): if a != b : d += 1 return d ######## levenshtein ######## # Calcule la distance de levenshtein entre deux string et retourne sa valeur def lev(a, b): if not a: return len(b) if not b: return len(a) return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1) # Calcule la distance de levenshtein entre deux string et retourne sa valeur def levenshtein(s, t): if s == t: return 0 elif len(s) == 0: return len(t) elif len(t) == 0: return len(s) v0 = [None] * (len(t) + 1) v1 = [None] * (len(t) + 1) for i in range(len(v0)): v0[i] = i for i in range(len(s)): v1[0] = i + 1 for j in range(len(t)): cost = 0 if s[i] == t[j] else 1 v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) for j in range(len(v0)): v0[j] = v1[j] return v1[len(t)]
1d66aff9f95c8381ab58ff8f583e85cf612a74f4
Aman-dev271/Pythonprograming
/33th_decoratorss.py
997
4.21875
4
""" def function(): print("subscribe now Tech Aman") fun1 = function del function fun1() def fun_returner(num): if num== 0: return print if num == 1: return sum a = fun_returner(0) print(a) # function as an argument we also can use def fun_as_argument(aman): aman("amandeep is a good boy and this function is take a function as an argument") fun_as_argument(print) """ # decorator function def dec_function(func1): def now_execute(): print("The Execution start") func1(a1,b2) print("The Execution Is Done") return now_execute # this is another way to define the decorator # @dec_function def aman_ka_function(a1, b2): c= a1+b2 print(f"addition answer of {a1} and {b2} is ={c}") a1 = int(input("Enter the value of 'a'")) b2 = int(input("Enter the value of 'b' ")) # actual work decorator aman_ka_function = dec_function(aman_ka_function) aman_ka_function()
4783bf7e2627fad4b3b0852f9877ab8ab96ec5ad
alihusain120/InterviewProbs
/ParkingLot.py
2,467
3.890625
4
# Parking Lot program # # class ParkingLot: def __init__(self, maxCapacity): self.maxCapacity = maxCapacity self.currentCapacity = 0 self.spaces = [None] * maxCapacity def isFull(self): return self.maxCapacity == self.currentCapacity def park(self, Vehicle): if self.isFull(): #no spots available print("The parking lot is full. Please try again later.") return else: #park the car i = 0 while i < len(self.spaces): if self.spaces[i].isAvailable(): #found spot, park vehicle if not self.spaces[i].size >= Vehicle.size: i += 1 continue self.spaces[i].vehicleAtSpot = Vehicle self.currentCapacity += 1 Vehicle.parkingSpot = i print("Your car was successfully parked in spot " + str(i)) return print("There are no available parking spots. Please try again later.") return def remove(self, Vehicle): if Vehicle.parkingSpot >= 0 and Vehicle.parkingSpot < len(self.spaces): toReturnVehicle = self.spaces[parkingSpot] self.spaces[Vehicle.parkingSpot].vehicleAtSpot = None self.currentCapacity -= 1 Vehicle.parkingSpot = -1 return toReturnVehicle else: print("Your vehicle is not in the parking lot.") return def checkSpot(self, i): if self.spaces[i].isAvailable(): print("This spot is free.") else: print("There is a car in this spot") return self.spaces[i] class ParkingSpace: def __init__(self, size): self.size = size self.vehicleAtSpot = None def isAvailable(self): if self.vehicleAtSpot is None: return True else: return False class Vehicle: def __init__(self, size, licensePlate): self.size = size self.licensePlate = licensePlate self.parkingSpot = -1 def getPlate(self): return self.licensePlate def getParkingSpot(self): return self.parkingSpot
6512d38a8be8094b9efce349848918bd92af1bb9
h2r/slu_core
/tools/esdcs/python/esdcs/gui/esdc_utils.py
796
3.578125
4
def highlightTextLabel(label, esdc): """Change the label text to highlight a single esdc""" start, end = esdc.range labelText = (esdc.entireText[0:start]+ "<b>" + esdc.entireText[start:end] + "</b>" + esdc.entireText[end:]) label.setText(labelText) def highlightTextLabelESDCs(label, esdcs): """Change the label text to highlight a list of esdcs""" offset = 0 labelText = '' text = esdcs[0].entireText esdcs.sort(key=lambda esdc: esdc.range[0]) for esdc in esdcs: start, end = esdc.range labelText += (text[offset:start] + "<b>" + text[start:end] + "</b>") offset = end labelText += text[offset:] label.setText(labelText)
eeb0448fd4232fb7ae5c7e8f11c513cc63fec50b
khushboo1510/leetcode-solutions
/30-Day LeetCoding Challenge/April/Medium/201. Bitwise AND of Numbers Range.py
783
3.515625
4
""" https://leetcode.com/problems/bitwise-and-of-numbers-range/ Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. """ class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: if m == 0 or m == n: return m if len(bin(m)) != len(bin(n)): return 0 mb = f"{m:#033b}" nb = f"{n:#033b}" result = 0 while mb.find('1') == nb.find('1'): pos = mb.find('1') msb = 32 - pos msbint = pow(2, msb) result += msbint m = m - msbint n = n - msbint mb = f"{m:#033b}" nb = f"{n:#033b}" return result
afdeb97ad4e3df7ca77b3d757a25d368a72254d6
tehs0ap/Project-Euler-Python
/Solutions/Problems_20-29/Problem_25.py
825
3.78125
4
''' Created on 2012-12-06 @author: Marty ''' ''' The Fibonacci sequence is defined by the recurrence relation: Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? ''' import time startTime = time.time() previousTerms = [1,1] currentTerm = 0 found = False n=2 while not found: n+=1 currentTerm = previousTerms[0]+previousTerms[1] previousTerms[0] = previousTerms[1] previousTerms[1] = currentTerm if currentTerm / 10**999 > 0 : found = True print n print "Time Elapsed: " + str(time.time() - startTime)
3d784eaf6f8682d78898a19a465577a831984109
mohit3wadhwa/2021
/speech_v3.py
2,121
3.953125
4
# #import library # import speech_recognition as sr # # Initialize recognizer class (for recognizing the speech) # r = sr.Recognizer() # # Reading Audio file as source # # listening the audio file and store in audio_text variable # with sr.AudioFile('audio.wav') as source: # audio_text = r.listen(source) # # recoginize_() method will throw a request error if the API is unreachable, hence using exception handling # try: # # using google speech recognition # text = r.recognize_google(audio_text) # print('Converting audio transcripts into text ...') # print(text) # except: # print('Sorry.. run again...') #First off install below libraries - # 1. pip3 install SpeechRecognition # 2. pip3 install PyAudio #import speech library import os import speech_recognition as sr print(os.path.abspath('Audio_transcript.txt')) # Initialize recognizer class (for recognizing the speech) recogn = sr.Recognizer() # listening from Microphone # listening the speech and store in 'audio' variable with sr.Microphone() as source: print("Please spreak now\n") audio = recogn.listen(source) print("Listening stops working!\n") # recoginize_() method will throw error if the Google's API does not work try: # Calling google speech API for speech recognition #print("You said: " + recogn.recognize_google(audio)) # Writing Transcript to a text file f = open("Audio_transcript.txt", "w") f.write(recogn.recognize_google(audio)) f.close() #open and read the file after the writing: f = open("Audio_transcript.txt", "r") print("Reading from file - " + f.read() + "\n") print("_____________________________________________________________") print("Transcript has been successfully written to file 'Audio_transcript.txt' at path -> " + os.path.abspath('Audio_transcript.txt')) print("_____________________________________________________________") except: print("Something's wrong...")
bbdf13926fa9271af0b089e21656964723700948
ninja0109/Project-Euler-Solutions
/Problem 5-Smallest multiple.py
387
3.65625
4
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def lcm(m,n): if m>n: i=n while i%m!=0: i+=n print(i) else: i=m while i%n!=0: i+=m print(i) return i for i in range(1,20): p=lcm(i,p) print(p)
16740fcfeda2464613cddd6f521bcf079c3b22e6
qingdongPeng/py_test
/test/object/create-class.py
431
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ##创建类 ## python 是动态语言, 对于每一个实例, 可以直接给他们的属性赋值 class Student(object): pass xiaoming = Student() xiaoming.name = "xiaoming" xiaohong = Student() xiaohong.name = "xiaohong" xiaoqiang = Student() xiaoqiang.name = "xiaoqiang" list = [xiaoming, xiaohong, xiaoqiang] for a in list: print(a.name) print(xiaoming == xiaohong)
149d3db8da0d885c86d43f10f375a5a85e81a65b
MuhammadHafizhRafi/Muhammad-Hafizh-Rafi-Susanto_I0320065_Abyan_Tugas7
/I0320065_Soal1_Tugas7.py
688
3.984375
4
#count print("==============count=================") str = "Selamat Idul Fitri" sub = "a" print ("str.count(sub, 4, 16) : ", str.count(sub, 4, 16)) sub = "an" print ("str.count(sub) : ", str.count(sub)) #center print("==============center=================") str = "Makan opor saat Idul Fitri" print ("str.center(40, 'a') : ", str.center(40, 'a')) print ("str.center(40) : ", str.center(40)) #capitalize print("==============capitalize=================") str ='Semangat mengerjakan tugas prokom!' s=str.capitalize() print(s) #replace print("==============replace=================") str = " Durian buah yang enak, pepaya tidak" s = str.replace ("durian", "pepaya") print(s)
6c759be45095d8cb38dd44aeab624e4f388946d0
WalmsleyIsRad/prg1_homework
/practice_code/greet.py
621
3.875
4
''' def message(recipient,sender): print("Hello, "+recipient+ " How are you? What is up?") print("-"+sender) student = "Patrick Walmsley" teacher = "Mr. Gold" message(student,teacher) ''' #write a function that will tell you if a number is in the range of two other numbers def number_in_range(low,high,number): if(low < number and high > number): return True else: return False number1 = 1 number10 = 10 number_in_the_range = 4 number_out_range = -5 number_too_high = 100 print(number_in_range(number1,number10,number_in_the_range)) print(number_in_range(number1,number10,number_out_range))
62da756cb87760c5f87ff54e1c902e0091a576dc
zabdulmanea/100DaysOfCode
/day11_saudidevorg.py
724
4.46875
4
# Python Operators - part 2 # Logical Operators x = 5 print("Logical Operators (x = 5):") print("(x < 6 or x > 7)?", x < 6 or x > 7) print("(x < 6 and x > 7)?", x < 6 and x > 7) print("not(x < 6)?", not(x < 6)) print("---------------------------------------------") # Identity & Membership Operators x = [1, 3] y = [1, 3] z = x print(x is y) # False print(x is not y) # True print(x is not z) # False print(x != y) # False print(1 in x) # True print(3 not in x) # False print("---------------------------------------------") # Bitwise Operators # AND print(15 & 3) # 00001111 & 00000011 = 00000011 = 3 # XOR print(3 ^ 3) # 00000011 ^ 00000011 = 00000000 = 0 print("---------------------------------------------")
14f9b252cc1f9e088ac47864017906c399d0945a
WoodyLuo/PYTHON
/Lecture08/ex03_printList.py
257
4.15625
4
''' Exercise03 - printList Functions. Chung Yuan Christian University written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.) ''' def printList(lst): for element in lst: print(element) lst = [3, 1, 2, 6, 4, 2] printList(lst)
78c94454f1284ee2fe8c8ac0d8a0ebd3dd6e6f72
Dipen-Dedania/tensorflow-playground
/03_tensor_mul_2.py
1,017
3.703125
4
import tensorflow as tf # A feature that is convenient to use when we want to explore the data content of an object is # tf.InteractiveSession(). Using it and .eval() method, we can get a full look at the values # without the need to constantly refer to the session object # Initialize two constants x1 = tf.constant([1,2,3]) print(x1.get_shape()) x2 = tf.constant([4,5,6]) print(x2.get_shape()) result = tf.multiply(x1, x2) sess = tf.InteractiveSession() print('multiply result: \n {}'.format(result.eval())) ########################################################### print('### Now we will try with the matrix') x3 = tf.constant([[1,2,3],[3,2,1]]) print(x3.get_shape()) x4 = tf.constant([1,0,2]) print(x4.get_shape()) x4 = tf.expand_dims(x4,1) print(x4.get_shape()) result2 = tf.matmul(x3, x4) sess = tf.InteractiveSession() print('After expanding x4 dimension: \n {}'.format(x4.eval())) print('matmul result2: \n {}'.format(result2.eval())) ### Output # [ (1*1) + (0*2) + (2*3), (1*3) + (0*2) + (2*1)]
934433148038ddb73f1b3b5049570cb279af84c1
marquesarthur/programming_problems
/interviewbit/interviewbit/math/grid_unique_paths.py
421
3.546875
4
class Solution: fact = {} def factorial(self, n): x = 1 for i in range(1, n + 1): x *= i return x # @param A : integer # @param B : integer # @return an integer def uniquePaths(self, A, B): x = A + B - 2 right = A - 1 down = B - 1 paths = self.factorial(x) / (self.factorial(right) * self.factorial(down)) return paths
f8e809c6922d4c4d835125d2a84ad150fbdb44a2
gaurihatode23/Assignment-1
/Task7.py
4,135
3.8125
4
#Question1 of Task 7 class calculate(): def __init__(self,C,H): self.C=C self.H=H def formula(self,D): return ((2*self.C*D)/self.H)**2 D=int(input("Enter the value of D")) obj1=calculate(50,30) Q = obj1.formula(D) print(Q) #Question2 of Task 7 class Shape(): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self,length): Shape.__init__(self) self.length=length self.Shape=0 def area(self): return self.length*self.length obj1=Square(50) new_area=obj1.area() print("Area is:",new_area) #Question3 of Task 7 class calculate: def threeSum(self, input_num): input_num, result, i = sorted(input_num), [], 0 while i < len(input_num) - 2: j, k = i + 1, len(input_num) - 1 while j < k: if input_num[i] + input_num[j] + input_num[k] < 0: j += 1 elif input_num[i] + input_num[j] + input_num[k] > 0: k -= 1 else: result.append([input_num[i], input_num[j], input_num[k]]) j, k = j + 1, k - 1 while j < k and input_num[j] == input_num[j - 1]: j += 1 while j < k and input_num[k] == input_num[k + 1]: k -= 1 i += 1 while i < len(input_num) - 2 and input_num[i] == input_num[i - 1]: i += 1 return result print(calculate().threeSum([-25, -10, -7, -3, 2, 4, 8, 10])) #Question4 of Task 7 1.class Test: def __init__(self): self.x = 0 class Derived_Test(Test): def __init__(self): self.y = 1 def main(): b = Derived_Test() print(b.x,b.y) main() Output-File "/Users/gaurihatode/reverse_word.py", line 10, in <module> main() File "/Users/gaurihatode/reverse_word.py", line 9, in main print(b.x,b.y) AttributeError: 'Derived_Test' object has no attribute 'x' Reason- class Derived_Test doesn not have variable x defined in it. To use the oject of Class test the Derived_Test class should have Test.__init__(self). 2.class A: def __init__(self, x= 1): self.x = x class der(A): def __init__(self,y = 2): super().__init__() self.y = y def main(): obj = der() print(obj.x, obj.y) main()) Output-File "/Users/gaurihatode/reverse_word.py", line 11 main()) ^ SyntaxError: unmatched ')' Reason- extra paranthese at the calling of main function 3.class A: def __init__(self,x): self.x = x def count(self,x): self.x = self.x+1 class B(A): def __init__(self, y=0): A.__init__(self, 3) self.y = y def count(self): self.y += 1 def main(): obj = B() obj.count() print(obj.x, obj.y) Main() Output-File "/Users/gaurihatode/reverse_word.py", line 6, in <module> class B(A): File "/Users/gaurihatode/reverse_word.py", line 16, in B main() File "/Users/gaurihatode/reverse_word.py", line 13, in main obj = B() NameError: name 'B' is not defined Reason- The class objects are defined at the class level no inside a method. 4.class A: def __init__(self): self.multiply(15) print(self.i) def multiply(self, i): self.i = 4 * i; class B(A): def __init__(self): super().__init__() def multiply(self, i): self.i = 2 * i; obj = B() Output-30 #Question5 of Task 7 class time(): def __init__(self,hours, minutes): self.hours=hours self.minutes=minutes def addTime(x1,x2): x3=time(0,0) if x1.minutes+x2.minutes > 60: x3.hours=(x1.minutes+x2.minutes)/60 x3.hours=x3.hours+x1.hours+x2.hours x3.minutes=(x1.minutes+x2.minutes)-(((x1.minutes+x2.minutes)/60)*60) return x3 def display_time(self): print("Calcuted Time is:",self.hours,"Calculated hours:",self.minutes,"min") def display_min(self): print((self.hours*60)+self.minutes) k=time(2,50) l=time(1,20) j=time.addTime(k,l) j.display_time() j.display_min() #Question6 of Task 7
cef5e401880844bdfe6fa6fa80778f31554d8963
midephysco/midepython
/forloop004.py
251
4.1875
4
password = "" while password != "secret": password = input("Please enter your password: ") if password== "secret": print("Thank you. You have entered the correct password") else: print("Sorry the value entered is incorrect")
6413e198992dca44160d4a4e2cadf0d9f3e45326
Wiserlightning/Blackjack-game
/BlackJack in python.py
4,710
3.671875
4
import os import random the_deck = [2,3,4,5,6,7,8,9,10,11,12,13,14]*4 def deal(the_deck): hand = [] for i in range(2): random.shuffle(the_deck) card= the_deck.pop() if card==11: card1 = 'Jack' if card==12: card1 = 'Queen' if card==13: card1 = 'King' if card==14: card1 = 'Ace' hand.append(card) return hand def play_again(): again = input("Do you want to play? (Y/N): ").lower() if again == "y": dealer_hand = [] player_hand = [] the_deck = [2,3,4,5,6,7,8,9,10,11,12,13,14]*4 game() else: print("Thanks for playing!") exit() def total(hand): total= 0 for card in hand: if card == 11 or card ==12 or card == 13: total = total+10 elif card == 14: if total >= 11: total = total + 1 else: total = total + 11 else: total = total + card return total def hit(hand): card = the_deck.pop() if card == 11: card1 = "J" if card == 12: card1 = "Q" if card == 13: card1 = "K" if card == 14: card1 = "Ace" hand.append(card) return hand def print_results(dealer_hand, player_hand): print("The dealer has a ",str(dealer_hand),"for a total of ",str(total(dealer_hand))) print("You have a ",str(player_hand)," for a total of ",str(total(player_hand))) def blackjack(dealer_hand, player_hand): if total(player_hand) == 21: print_results(dealer_hand, player_hand) print("Congratulations! You got a Blackjack!\n") play_again() elif total(dealer_hand) == 21: print_results(dealer_hand, player_hand) print("Sorry, you lose. The dealer got a blackjack.\n") play_again() def score(dealer_hand, player_hand): if total(player_hand) == 21: print_results(dealer_hand, player_hand) print("Congratulations! You got a Blackjack!\n") elif total(dealer_hand) == 21: print_results(dealer_hand, player_hand) print("Sorry, you lose. The dealer got a blackjack.\n") elif total(player_hand) > 21: print_results(dealer_hand, player_hand) print("Sorry. You busted. You lose.\n") elif total(dealer_hand) > 21: print_results(dealer_hand, player_hand) print("Dealer busts. You win!\n") elif total(player_hand) < total(dealer_hand): print_results(dealer_hand, player_hand) print("Sorry. Your score isn't higher than the dealer. You lose.\n") elif total(player_hand) > total(dealer_hand): print_results(dealer_hand, player_hand) print("Congratulations. Your score is higher than the dealer. You win\n") def game(): choice = 0 print("WELCOME TO BLACKJACK!\n") dealer_hand = deal(the_deck) player_hand = deal(the_deck) p1=[] while choice != "q": print("The dealer is showing a " + str(dealer_hand[0])) for i in player_hand: p1.append(i) if i == 11: p1.append("Jack") if i == 12: p1.append("Queen") if i == 13: p1.append("King") if i == 14: p1.append("Ace") print("You have a",p1," for a total of " + str(total(player_hand))) blackjack(dealer_hand, player_hand) choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower() if choice == "h": hit(player_hand) while total(dealer_hand) < 17: hit(dealer_hand) score(dealer_hand, player_hand) play_again() elif choice == "s": while total(dealer_hand) < 17: hit(dealer_hand) score(dealer_hand, player_hand) play_again() elif choice == "q": print("Bye!") exit() play_again()
c9c139f363fa80c39b7291a15f031c7afa4048eb
qiaobilong/Python
/Learn_Python3_The_Hard_Way/ex34.py
161
3.734375
4
lists = [1,2,3,4,5] def my_list(lists): for i in range(len(lists)): print(f"index:{i} - ",end = "") print(lists[i]) pass my_list(lists)
85c28395bdce4329171677609ab6a0733a805d1d
fabiorfc/Exercicios-Python
/Python-Brasil/1-EstruturaSequencial/ex_15.py
1,413
4.125
4
# -*- coding: utf-8 -*- """ 15 - Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: a) salário bruto. b) quanto pagou ao INSS. c) quanto pagou ao sindicato. d) o salário líquido. e) calcule os descontos e o salário líquido, conforme a tabela abaixo: + Salário Bruto : R$ - IR (11%) : R$ - INSS (8%) : R$ - Sindicato ( 5%) : R$ = Salário Liquido : R$ Obs.: Salário Bruto - Descontos = Salário Líquido. """ valor_hora = float(input('Informe o valor da hora trabalhada: ')) total_horas = float(input('Informe quantas horas você trabalha no mês: ')) #Efetuando os cálculos salario_bruto = valor_hora * total_horas inss = salario_bruto * 0.08 ir = salario_bruto * 0.11 sindicato = salario_bruto * 0.05 salario_liquido = salario_bruto * 0.76 #Imprimindo os resultados print('Dados da remuneração: ') print('Salário bruto: R$ {}'.format(salario_bruto)) print('Desconto do IR: R$ {}'.format(ir)) print('Desconto do INSS: R$ {}'.format(inss)) print('Desconto do sindicato: R$ {}'.format(sindicato)) print('Salário líquido: R$ {}'.format(salario_liquido))
ef851f6f1a17eacfe0489d9bc5954d39066588a1
GHIaayush/Phylogenetic-Tree
/phylo.py
8,180
3.671875
4
#importd the genome file from genome import* #imports the tree file from tree import* """ File:phylo.py Author: Aayush Ghimire, Date:05/2/2018, Purpose: To construct phylogenetic trees starting from the genome sequences of a set of organisms. """ """ This function ask the user for the input file, size of ngram they wish to make """ def ask_user(): """ This function ask the user about the size of ngram they wish to make and returns the ngram as the int value and file after opening it PARAMETER: NONE RETURN: the file and int value is returned PRE-CONDITION: it ask the input from user POST-CONDITION: the legit user input will be converted to int for n gram size and file will be returned """ user_input = input('FASTA file: ') N_size = input('n-gram size: ')#ask input try: open_file = open(user_input)#opens except IOError: print("ERROR: could not open file " + user_input) exit(1) try: N_size = int(N_size) except ValueError: print("ERROR: Bad value for N") exit(1) return open_file, N_size """ This function process the file """ def read_fasta(open_file): """ This file takes opened file passed by the user and process it PARAMETER: the opened file is passed as a parameter RETURN: the virus list i.e the list of the id and genome is returned PRE-CONDITION: the file passed is just opened POST-CONDITION: virus list is the list that contains organism id and genome in a sequence """ virus_list = []#new list to store genome_str = ""#new str to concat for line in open_file: #loops through file line = line.strip()#Remove all empty lines and pace if line != "": #print(line) if line[0][0] == ">":#is id line if genome_str != "":#checks for concatenation virus_list.append(genome_str)#append in a list genome_str = ""#appends and reset it virus_list.append(line)#append a details elif (line[0][0] == "A" or line[0][0] == "C" or line[0][0] == "G" or line[0][0] == "T"):#checks for genome line genome_str += line#concat the str virus_list.append(genome_str)#append the last line return(virus_list)#gets all the file """ This function creates a genome object and a tree object. """ def create_genome_tree_obj(virus_list,N_size): """ This fucntion takes a list, the int value input by the user and makes a genome object which has id , and set a sequence and tree object which has a string as id and left and right as none. It also creates a list and dictionary that has key as a id(type string) and value as a genome object.Two list that stores genome and tree object PARAMETERS:the cleaned list which has id and genome string in a sequencce and N-gram size input of the user is passed as a parameter RETURNS: the genome list, dictionary and tree_list are returned PRE-CONDITION: parameter passed are type list and int value POST-CONDITION: list and dictionary are returned """ genome_list = []#to store genome object tree_list = []#to store tree object genome_dic = {}#to store id associated with object for i in range(0,len(virus_list),2): #loops and step by two because it has id and genome seq virus_id = virus_list[i].split()#split the id virus_id[0] = virus_id[0].replace(">","")#replace ">" seq = virus_list[i+1]#gets a sequence tree = Tree()#creates tree tree.set_id(virus_id[0])#sets if tree.add_list(virus_id[0])#add in a list tree_list.append(tree)#append tree object in list gd = GenomeData()#create genome data object gd.set_id(virus_id[0])#sets id gd.set_sequence(seq)#sets sequence gd.set_ngrams(N_size)#sets n grams if virus_id[0] not in genome_dic:#checks if key exist genome_dic[virus_id[0]] = gd#creates a key and value genome_list.append(gd)#append in dicionary return genome_list, genome_dic, tree_list """ This function checks the maxim similarity between the two trees among all the trees in the trees list """ def tree_similarity(genome_list,genome_dic,tree_list): """ This checks the similarity between the all possible tree objects and returns the maximum similarity and that two tree object as a tuple PARAMETER: genome list, genome dic and tree list are passed as a parameter RETURN: max value of similarity and two tree which got the maximum similarity is returned PRE-CONDITION: list and dictionary are passed POST-CONDITION: int and tuple is returned """ i = 0#sets as for while loop max_value = -1#sets max as -1 max_tree = tuple()#create an empty tuple while len(tree_list) != i:# key1 = tree_list[i] j = i + 1 while len(tree_list) != j: key2 = tree_list[j] #calls a helper function val_max , tree_max = seq_set_sim(key1,key2,genome_dic) if val_max > max_value : max_value = val_max max_tree = tree_max j += 1 i += 1 return max_value,max_tree """ This function takes a tree list. Calls a hepler function And combines two tree which has maximum similarity until the list has one single tree object. """ def make_list(genome_list,genome_dic,tree_list):#,max_value,max_tree): """ This function combines two tress which has the maximum similarity. It creates a new tree object. It removes those two tree object from the tree list. """ while len(tree_list) > 1:#till there is one element in list max_value , max_tree =tree_similarity(genome_list,genome_dic,tree_list) tree = Tree()#new tree object if str(max_tree[0]) < str(max_tree[1]): tree._left = max_tree[0] tree._right = max_tree[1] else: tree._right = max_tree[0] tree._left = max_tree[1] tree.join_list(max_tree[0].get_list(),max_tree[1].get_list()) tree_list.append(tree) tree_list.remove(max_tree[0])#reoves from list tree_list.remove(max_tree[1])#removes from list return tree_list#return tree list """ This function computes the jacard index of the sets and returns the maximum value of similarity and tuple of tree object which has highest similarity """ def seq_set_sim(key1,key2,genome_dic): """ This function computes the jacard index of two sets and returns the highest similarity value and tuple of tree object which has highest similarity """ new = -1 max_tree = tuple() var1 =(key1.get_list()) var2 =(key2.get_list()) #loops through list for i in range(len(var1)): for j in range(len(var2)): s1 = genome_dic[var1[i]].get_ngrams() s2 = genome_dic[var2[j]].get_ngrams() #computes the similarity similarity= (float (len(s1.intersection(s2))) / float (len(s1.union(s2)))) if similarity > new: new = similarity max_tree = (key1,key2) #highest value and tree tuple return new, max_tree """ This is the main of the program.It calls all the function in the program. """ def main(): #ask the user in the function and stores the return value open_file, N_size = ask_user() #store clean list virus_list = read_fasta(open_file) #store genome_list dictionary and list genome_list, genome_dic, tree_list = (create_genome_tree_obj (virus_list,N_size)) #makes the final tree, and return it final_tree = make_list(genome_list, genome_dic, tree_list) #prints the tree print(final_tree[0]) main()
9db91562129ba71e331a1e05bd4ccd25c04f6b4a
YasminLN12/Mision_02
/cuenta.py
382
3.8125
4
# Autor: Yasmín Landaverde Nava, A01745725 # Descripcion: Este programa calcula el costo total de la comida incluyendo la propina e iva. stotal = int(input("¿Cuánto fue el total de su cuenta?: ")) prop = stotal*.13 iva = stotal*.16 print("Costo de su comida: $", "%.2f" % stotal) print("Propina: $", "%.2f" % prop) print("IVA:", "%.2f" % iva) ct = stotal + prop + iva print("Costo total: $", ct)
efce3a47e104c82d46a23889b72e14f3ca0003aa
islami00/csc102
/class4/problem17/sumAgainClass.py
351
3.828125
4
# You ar presented with the scores of 4 students in your department. Among the task that is expected of you on the # student scores are as follows: #1. get score from students number = 4 scores = [int(input("Enter a number: ")) for x in range(number)] # 2. compute sum sum_Scores = sum(scores) # 3. compute average avg_scores = sum_Scores/len(scores)
4fde366610d69b95e54c0e7559212c87780270a2
jinwoov/hacktoberfest
/Scripts/random_print_of_helloworld.py
834
3.78125
4
# Aim: print each letter of 'hello world' in order and in random points in time # How: printing letter based on whether the ascii code of each letter appears in the milliseconds of the current time # get the characters of the phrase in ascii code and put them in a list helloworld = 'hello world' in_ascii = [] for i in helloworld: in_ascii.append(ord(i)) #print(in_ascii) #[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] import datetime import time # from now + 1 minute endTime = datetime.datetime.now() + datetime.timedelta(minutes=1) for i in in_ascii: while True: milliseconds = time.time()*1000.0 milliseconds_str = str(milliseconds) if str(i) in milliseconds_str: print(chr(i) ) # print the character of the ascii code break # if letter printed, succceded, break
f690a0c653395cfdf5aeecc8737fa231985e930e
adarshadrocks/pyhonActivities
/swapping.py
192
3.703125
4
#!/usr/bin/python '''swapping of two no.s''' x=raw_input("enter the first no.") y=raw_input("enter the second no.") x,y=y,x print "after swapping" print "first no. :"+x print "second no. :"+y
605318247bbd4eec3afff53be397ffd6a26227eb
MrNullPointer/Python-Basics
/fib.py
215
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 2 16:25:20 2020 @author: parikshitdubey """ def fib(x): if x == 1 or x == 0: return 1 else: return fib(x-1) + fib(x-2)
6b2f7cc3221c0865b509c77efed9d59526efae3e
maroro0220/Rassberry_python_device
/calculator_per.py
666
3.75
4
class Calculator: def __init__(self,lis): self.tot=0 self.lis=lis def sum(self): self.tot=sum(self.lis) print(self.tot) def avg(self): if self.tot!=0: self.av=self.tot/len(self.lis) else: self.av=sum(self.lis)/len(self.lis) print(self.av) if __name__=='__main__': li=[] #li=[1,2,3,4,5] while True: num=int(input('enter num (0->end):')) if num==0: break li.append(num) cal1=Calculator(li) cal1.sum() cal1.avg()
72e7a94b85a4e57d00b106ddcaa8b61a579df1e9
pb0528/codelib
/Python/lesson/list.py
487
3.6875
4
def main(): fruits = ['grape', 'apple', 'strawbery', 'waxberry'] fruits += ['pitaya', 'pear'] # 循环遍历列表元素 for iterm in fruits: print(iterm.title(), end='') print() #列表切片 fruits1 = fruits[1:4] print(fruits1) def reduces(): #用range 生成列表 list1 = list(range(1,11)) print(list1) # 生成表达式 list2 = [x * x for x in range(1,11)] print(list2) if __name__ == '__main__': main()
87ebd7a7fc2ebac23c005ac730a0fb82875f14e2
alanaalfeche/python-sandbox
/rosalind/python_village/INI3.py
598
3.84375
4
""" Given: A string s of length at most 200 letters and four integers a, b, c and d. Return: The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice. """ string = input("Provide a string to splice: ") splice_sites = input("Provide splice sites: ") ss_list = list(map(int, splice_sites.split())) print(ss_list) for splice_site in range(0, len(ss_list)-1, 2): ss_pair = ss_list[splice_site:splice_site+2] word = string[ss_pair[0]:ss_pair[1]+1] # inclusive print(word)
31d79608f17a4283452ecfee7a8673e3cd3519f4
CristianPabon/TrabajosPython
/py6_retos2/reto013.py
159
3.78125
4
a = int(input('Primer número en rango: ')) b = int(input('Segundo número en rango: ')) c = (a + b)/2 print('La media de los números', a,' y ', b,' es: ', c)
c0a7b47621f71f0522512b3e17e64de4eb2e06c5
Spookso/draughts
/min_max_sep.py
16,745
4
4
import pygame, math, movement, time, random # Initiates the pygame library pygame.init() # Sets up a window of size 800 x 800 pixels with the tag 'resizable' win = pygame.display.set_mode((800, 800), pygame.RESIZABLE) # Sets the caption for the window as "Draughts" pygame.display.set_caption("Draughts") # allows pygame.time.Clock() to be accessed easily clock = pygame.time.Clock() # Initisalises variables turn = 1 correct_turn = True # Default window size width = 800 height = 800 # sets whether there will be an ai opponent # if input("Play against the computer? ") == "Yes": # ai = True # else: # ai = False ai = True random_ai = False calculated = False print("ai true") # Declares the 'current_board' array, a 2D array that consists of rows of numbers representing pieces or empty squares current_board = [ [0, 3, 0, 3, 0, 3, 0, 3], [3, 0, 3, 0, 3, 0, 3, 0], [0, 3, 0, 3, 0, 3, 0, 3], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0] ] movelist = [] # current_board = [ # [0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 2, 0, 0, 0, 3, 0], # [0, 0, 0, 3, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 3, 0], # [0, 0, 0, 3, 0, 0, 0, 1], # [0, 0, 1, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 1, 0], # [0, 0, 0, 0, 0, 4, 0, 0] # ] saved_board = [] for row in current_board: saved_board.append(row) # Changes player turn def turn_change(turn): turn += 1 if turn > 2: turn = 1 return turn # Checks if a player is out of pieces def win_check(board): red = True blue = True for row in board: for piece in row: if piece == 1 or piece == 2: red = False elif piece == 3 or piece == 4: blue = False if red: return 1 if blue: return 2 return 0 # checks whether a piece will be kinged def king_check(board): num = 0 for piece in board[0]: if piece == 1: board[0][num] = 2 num += 1 num = 0 for piece in board[7]: if piece == 3: board[7][num] = 4 num += 1 def update(moves): board = [ [0, 3, 0, 3, 0, 3, 0, 3], [3, 0, 3, 0, 3, 0, 3, 0], [0, 3, 0, 3, 0, 3, 0, 3], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0] ] # print("updating") for i in range(0, len(moves)): board = movement.move(board, moves[i][0], moves[i][1], moves[i][2], moves[i][3], moves[i][4], moves[i][5]) king_check(board) return board def max(ai_board, depth, cap): ai_saved = [] for row in ai_board: ai_saved.append(row) # the score of the best possiblity is initialised at -200, below the score given if the game is lost maxv = -200 sx = None sy = None ex = None ey = None # if the ai has won with this board, it makes no move from here if win_check(ai_board) == 1: return (-100, 0, 0, 0, 0, depth) if win_check(ai_board) == 2: return (100, 0, 0, 0, 0, depth) # checks whether the ai should search down another layer of the tree if depth <= cap: # print("RUNNING") # si, sj = starting row and starting col for si in range(0, 8): for sj in range(0, 8): # if the piece is on the ai's team if ai_board[si][sj] == 3 or ai_board[si][sj] == 4: # ei, ej = ending row and ending col for ei in range(0, 8): for ej in range(0, 8): # if the move is legal if movement.move_check(ai_board, si, sj, ei, ej)[0]: depth += 1 direction, side = movement.move_check(ai_board, si, sj, ei, ej)[2], movement.move_check(ai_board, si, sj, ei, ej)[3] # if the move is not a double-take move if not movement.move_check(ai_board, si, sj, ei, ej)[4]: movement.move(ai_board, si, sj, ei, ej, direction, side) # otherwise: else: depth += 1 forcedx, forcedy = movement.double_move_check(ai_board, si, sj, direction, side)[3], movement.double_move_check(ai_board, si, sj, direction, side)[4] movement.move(ai_board, si, sj, ei, ej, direction, side) movement.move(ai_board, si, sj, forcedx, forcedy, direction, side) (m, min_si, min_sj, min_ei, min_ej, depth) = min(ai_board, depth, cap) if m > maxv: maxv = m sx = si sy = sj ex = ei ey = ej ai_board = [] for row in ai_saved: ai_board.append(row) else: # do the scoring of this board here, make up some m value for the score score = 0 for x in range(0, 8): for y in range(0, 8): if ai_board[x][y] == 1: score -= 1 if ai_board[x][y] == 2: score -= 2 if ai_board[x][y] == 3: score += 1 if ai_board[x][y] == 4: score += 2 m = score depth = 0 return (m, sx, sy, ex, ey, depth) def min(ai_board, depth, cap): ai_saved = [] for row in ai_board: ai_saved.append(row) # the score of the best possiblity is initialised at 200, above the score given if the game is won minv = 200 sx = None sy = None ex = None ey = None # if the ai has won with this board, it makes no move from here if win_check(ai_board) == 1: return (-100, 0, 0, 0, 0, depth) if win_check(ai_board) == 2: return (100, 0, 0, 0, 0, depth) # checks whether the ai should search down another layer of the tree if depth <= cap: # si, sj = starting row and starting col for si in range(0, 8): for sj in range(0, 8): # if the piece is on the ai's team if ai_board[si][sj] == 1 or ai_board[si][sj] == 2: # ei, ej = ending row and ending col for ei in range(0, 8): for ej in range(0, 8): # if the move is legal if movement.move_check(ai_board, si, sj, ei, ej)[0]: depth += 1 direction, side = movement.move_check(ai_board, si, sj, ei, ej)[2], movement.move_check(ai_board, si, sj, ei, ej)[3] # if the move is not a double-take move if not movement.move_check(ai_board, si, sj, ei, ej)[4]: movement.move(ai_board, si, sj, ei, ej, direction, side) # otherwise: else: depth += 1 forcedx, forcedy = movement.double_move_check(ai_board, si, sj, direction, side)[3], movement.double_move_check(ai_board, si, sj, direction, side)[4] movement.move(ai_board, si, sj, ei, ej, direction, side) movement.move(ai_board, si, sj, forcedx, forcedy, direction, side) (m, max_si, max_sj, max_ei, max_ej, depth) = max(ai_board, depth, cap) if m < minv: minv = m sx = si sy = sj ex = ei ey = ej ai_board = [] for row in ai_saved: ai_board.append(row) else: # do the scoring of this board here, make up some m value for the score score = 0 for x in range(0, 8): for y in range(0, 8): if ai_board[x][y] == 1: score -= 1 if ai_board[x][y] == 2: score -= 2 if ai_board[x][y] == 3: score += 1 if ai_board[x][y] == 4: score += 2 m = score depth = 0 return (m, sx, sy, ex, ey, depth) def draw_window(win, board): colour = (255, 255, 255) x = 0 y = 0 # Drawing out board for row in board: for square in row: pygame.draw.rect(win, colour, (x, y, round(width / 8), round(height / 8))) # Swapping colour if colour == (255, 255, 255): colour = (100, 160, 100) else: colour = (255, 255, 255) x += round(width / 8) # Swapping colour again for next row if colour == (255, 255, 255): colour = (100, 160, 100) else: colour = (255, 255, 255) y += round(height / 8) x = 0 # Drawing pieces onto screen x = round((width / 8) / 2) y = round((height / 8) / 2) for row in board: for piece in row: if piece == 1: pygame.draw.circle(win, (255, 0, 0), (x, y), round(width / 20)) elif piece == 2: pygame.draw.circle(win, (255, 255, 0), (x, y), round(width / 20)) elif piece == 3: pygame.draw.circle(win, (0, 0, 255), (x, y), round(width / 20)) elif piece == 4: pygame.draw.circle(win, (0, 255, 255), (x, y), round(width / 20)) x += round(width / 8) x = round((width / 8) / 2) y += round(height / 8) pygame.display.update() selected = False progress = False saved_row, saved_col = 0, 0 repeat = False run = True while run: human = False clock.tick(60) mouse_x, mouse_y = pygame.mouse.get_pos() for event in pygame.event.get(): # quits game if event.type == pygame.QUIT: run = False # Checks if mouse is clicked if event.type == pygame.MOUSEBUTTONDOWN: # If a piece is already selected if selected: mouse_x = math.floor((mouse_x / (width / 8))) mouse_y = math.floor((mouse_y / (height / 8))) if repeat: # if it is consecutive move, ensure that the piece is taking another piece if end_row == mouse_y + 2 or end_row == mouse_y - 2: end_col, end_row = mouse_x, mouse_y else: end_col, end_row = mouse_x, mouse_y progress = True human = True # If a piece has not been selected else: mouse_x = math.floor((mouse_x / (width / 8))) mouse_y = math.floor((mouse_y / (height / 8))) print(mouse_x, mouse_y) if current_board[mouse_y][mouse_x] != 0: if repeat: print("SAVED", saved_row, saved_col) # if it is consecutive move, ensure that the same piece is moving if mouse_x == saved_row and mouse_y == saved_col: start_col, start_row = mouse_x, mouse_y else: start_col, start_row = mouse_x, mouse_y selected = True elif event.type == pygame.VIDEORESIZE: width, height = event.w, event.h surface = pygame.display.set_mode((width, height), pygame.RESIZABLE) if turn == 2 and ai: progress = True # Checks whether an attempt at a move should be made if progress: if turn == 1: print("turn:", turn, "start row:", start_row, "start col:", start_col, "piece:", current_board[start_row][start_col]) print() # Checks whether it is moving the right piece for their turn if turn == 1: if current_board[start_row][start_col] != 1 and current_board[start_row][start_col] != 2: correct_turn = False print("Not piece in turn 1") elif turn == 2 and not ai: if current_board[start_row][start_col] != 3 and current_board[start_row][start_col] != 4: correct_turn = False print("Not piece in turn 2") elif random_ai: legal_moves = [] start_row = 0 for row in current_board: start_col = 0 if ai_repeat: start_row, start_col = saved for piece in row: if piece in [3, 4]: for end_row in range(0, 8): for end_col in range(0, 8): if movement.move_check(current_board, start_row, start_col, end_row, end_col)[0]: legal_moves.append([start_row, start_col, end_row, end_col, movement.move_check(current_board, start_row, start_col, end_row, end_col)[2], movement.move_check(current_board, start_row, start_col, end_row, end_col)[3]]) if not ai_repeat: start_col += 1 start_row += 1 try: time.sleep(0.4) choice = random.randint(0, len(legal_moves) - 1) correct_turn = True progress = False start_row, start_col, end_row, end_col, direction, side = legal_moves[choice] ai_repeat = False if movement.move_check(current_board, start_row, start_col, end_row, end_col)[4]: ai_repeat = True saved = [start_row, start_col] except: print("NO MOVES") correct_turn = False elif ai: ai_board = [] for row in current_board: ai_board.append(row) cap = 10 (m, start_row, start_col, end_row, end_col, depth) = max(ai_board, 0, cap) print("BEST MOVE:") print(start_row, start_col) print(end_row, end_col) # print(current_board) # correct_turn = True ai = False # moves the piece repeat = False if correct_turn: moving, double, direction, side, repeat = movement.move_check(current_board, start_row, start_col, end_row, end_col) # if the move was valid, change the turn if moving: print("start row", start_row) movelist.append([start_row, start_col, end_row, end_col, direction, side]) current_board = movement.move(current_board, start_row, start_col, end_row, end_col, direction, side) # if the move was a piece taking move, check if it can move again if double: repeat, saved_col, saved_row, work_row, work_col = movement.double_move_check(current_board, end_row, end_col, direction, side) # somehow ai gets stuck when it repeats # keeps recalculating moves - not sure exactly what's wrong if not repeat: turn = turn_change(turn) ai = True double = False # else don't change the turn else: pass # print("Invalid move") # resets the progress with clicking on a piece progress = False selected = False correct_turn = True calculated = False current_board = update(movelist) # Checks if one player is out of pieces if win_check(current_board) == 1: print("White wins!") run = False elif win_check(current_board) == 2: print("Black wins!") run = False # Checks if a piece can be kinged king_check(current_board) draw_window(win, current_board) pygame.quit()
bcecc78fb05e7d5177668ee21e866718de93812c
chenxu0602/LeetCode
/1338.reduce-array-size-to-the-half.py
2,613
3.765625
4
# # @lc app=leetcode id=1338 lang=python3 # # [1338] Reduce Array Size to The Half # # https://leetcode.com/problems/reduce-array-size-to-the-half/description/ # # algorithms # Medium (66.73%) # Likes: 311 # Dislikes: 32 # Total Accepted: 27.1K # Total Submissions: 40.6K # Testcase Example: '[3,3,3,3,5,5,5,2,2,7]' # # Given an array arr.  You can choose a set of integers and remove all the # occurrences of these integers in the array. # # Return the minimum size of the set so that at least half of the integers of # the array are removed. # # # Example 1: # # # Input: arr = [3,3,3,3,5,5,5,2,2,7] # Output: 2 # Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has # size 5 (i.e equal to half of the size of the old array). # Possible sets of size 2 are {3,5},{3,2},{5,2}. # Choosing set {2,7} is not possible as it will make the new array # [3,3,3,3,5,5,5] which has size greater than half of the size of the old # array. # # # Example 2: # # # Input: arr = [7,7,7,7,7,7] # Output: 1 # Explanation: The only possible set you can choose is {7}. This will make the # new array empty. # # # Example 3: # # # Input: arr = [1,9] # Output: 1 # # # Example 4: # # # Input: arr = [1000,1000,3,7] # Output: 1 # # # Example 5: # # # Input: arr = [1,2,3,4,5,6,7,8,9,10] # Output: 5 # # # # Constraints: # # # 1 <= arr.length <= 10^5 # arr.length is even. # 1 <= arr[i] <= 10^5 # # # @lc code=start from collections import Counter import math class Solution: def minSetSize(self, arr: List[int]) -> int: # counts = Counter(arr) # counts = [count for number, count in counts.most_common()] # total_removed = 0 # set_size = 0 # for count in counts: # total_removed += count # set_size += 1 # if total_removed >= len(arr) // 2: # break # return set_size # Hashing and Bucket Sort # O(n) counts = Counter(arr) max_value = max(counts.values()) buckets = [0] * (max_value + 1) for count in counts.values(): buckets[count] += 1 set_size = 0 arr_numbers_to_remove = len(arr) // 2 bucket = max_value while arr_numbers_to_remove > 0: max_needed_from_bucket = math.ceil(arr_numbers_to_remove / bucket) set_size_increase = min(buckets[bucket], max_needed_from_bucket) set_size += set_size_increase arr_numbers_to_remove -= set_size_increase * bucket bucket -= 1 return set_size # @lc code=end
a0ceff07ec709c9c52bea130d2f7777421d78e42
lucasloo/leetcodepy
/solutions/137SingleNumberII.py
641
3.59375
4
# Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ a = set() b = set() for i in nums: if i in a: b.discard(i) else: a.add(i) b.add(i) return b.pop() class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ return (int)((3*sum(set(nums)) - sum(nums)) / 2)
4e0c2bed4caed5f14c87ff9928d3a591df1fcb82
bcostaaa01/history_of_lego_pandas_py
/lego_history_pandas.py
1,032
3.65625
4
# Import pandas import pandas as pd # Read colors data colors = pd.read_csv('datasets/colors.csv') # Print the first few rows print(colors.head()) # How many distinct colors are available? num_colors = colors.rgb.size # Print num_colors print(num_colors) # colors_summary: Distribution of colors based on transparency colors_summary = colors.groupby('is_trans').count() # Print colors_summary print(colors_summary) %matplotlib inline # Read sets data as `sets` sets = pd.read_csv('datasets/sets.csv') # Create a summary of average number of parts by year: `parts_by_year` parts_by_year = sets[['year', 'num_parts']].groupby('year').mean() # Plot trends in average number of parts by year parts_by_year.plot() # themes_by_year: Number of themes shipped by year themes_by_year = sets.groupby('year')[['theme_id']].nunique() themes_by_year.head() # Get the number of unique themes released in 1999 num_themes = themes_by_year.loc[1999, 'theme_id'] # Print the number of unique themes released in 1999 print(num_themes)
9870793f9fba335eecda48666048f1ed9f86938d
cxv8/CSE
/notes/semester 2 Notes - Kentzu Xiong.py
356
4
4
print("Hello World") # Single-line comment car = 5 driving = True print("I have %d cars" % car) print("I have " + str(car) + " car") age = input("How old are you? ") print("You are %s years old" % age) color = ['red', 'green', 'black', 'white', 'gold'] color.append('pink') color.pop(0) print(color) print (len(color)) print (color[1]) print ("hiii")
6e50bbcb8c57fa9c3da30af68593571b5c0e54e7
Margarita89/AlgorithmsAndDataStructures
/Cracking the Coding Interview/8_Recursion and Dynamic Programming/8_3.py
627
4.125
4
# Magic Index: A magic index in an array A[ 1..n-1] is defined to be an index such that A[i] = i # Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. # Comment: talk about logic of returns def magic_index(arr, start, end): if start > end: return -1 mid = (start + end) // 2 if arr[mid] == mid: return mid elif arr[mid] < mid: return magic_index(arr, mid+1, end) else: return magic_index(arr, start, mid-1) if __name__ == "__main__": arr = [-20, -10, 0, 1, 4, 7, 18] print(magic_index(arr, 0, len(arr)-1))
4b39550366db7fed2b378805ecad9ad03491c3ba
KVasilius/ALevel_Python_Project
/Tkinter.py
10,706
3.859375
4
from tkinter import * import sqlite3 # login window, checks user name & password with the db one. def loginwindow(): def loginget(): username, userpassword = userName.get(), userPassword.get() cursor.execute("""SELECT user_password FROM user_data WHERE user_name = :user_name""", {'user_name': userName.get()}) connection_login.commit() if username != "" or userpassword !="": info = cursor.fetchall() try: db_password = ''.join(info[0]) error_check = True except IndexError: error_message = Label(logInWindow, text = "Username or password incorrect", fg = "red").grid(row = 3, columnspan = 2) error_check = False if error_check == True: if db_password == userpassword: logInWindow.destroy() menuWindow(username) else: error_message = Label(logInWindow, text = "Username or password incorrect", fg = "red").grid(row = 3, columnspan = 2) def destroy(): logInWindow.destroy() registerWindow() def return_login(event): loginget() logInWindow = Tk() logInWindow.title("Snake") logInWindow.resizable(False, False) title = Label(logInWindow, text = "Log In").grid(row = 0, columnspan = 2) userNameLabel = Label(logInWindow, text = "Username").grid(row = 1, column = 0) userPasswordLabel = Label(logInWindow, text = "Password").grid(row = 2, column = 0) userName = Entry(logInWindow) userName.grid(row = 1, column = 1) userPassword = Entry(logInWindow, show="*") userPassword.grid(row = 2, column = 1) loginButton = Button(logInWindow, text = " Log in ", command = loginget).grid(row = 4, column = 0) registerButton = Button(logInWindow, text = " Registration ", command = destroy).grid(row = 4, column = 1) logInWindow.bind("<Return>", return_login) logInWindow.mainloop() def registerWindow(): def destroy(): RegisterWindow.destroy() loginwindow() def registration(): username, userpassword, checkuserpassword = userName.get(), userPassword.get(), userPasswordCheck.get() if username != "" and userpassword != "": if userpassword == checkuserpassword: try: cursor.execute("""INSERT INTO user_data VALUES (:user_name, :user_password, :high_score )""",{'user_name': username,'user_password': userpassword, 'high_score': 0}) connection_login.commit() error_check = True except sqlite3.IntegrityError: error_message = Label(RegisterWindow, text = "Username already exists", fg = "red").grid(row = 4, columnspan = 2) error_check = False if error_check == True: destroy() else: no_match_message = Label(RegisterWindow, text = "Passwords do not match", fg = "red").grid(row = 4, columnspan = 2) #cursor.execute("INSERT INTO user_data VALUES (:user_name, :user_password, :high_score )",{'user_name': username,'user_password': userpassword, 'high_score': 0}) #connection_login.commit() RegisterWindow = Tk() RegisterWindow.title("Snake") RegisterWindow.resizable(False, False) title = Label(RegisterWindow, text = "Registration").grid(row = 0, columnspan = 2) userNamelabel = Label(RegisterWindow, text = "Username").grid(row = 1, column = 0) userPasswordlabel = Label(RegisterWindow, text = "Password").grid(row = 2, column = 0) userPasswordChecklabel = Label(RegisterWindow, text = "Password check").grid(row = 3, column = 0) userName = Entry(RegisterWindow) userName.grid(row = 1, column = 1) userPassword = Entry(RegisterWindow, show="*") userPassword.grid(row = 2, column = 1) userPasswordCheck = Entry(RegisterWindow, show="*") userPasswordCheck.grid(row = 3, column = 1) LogInButton = Button(RegisterWindow, text = " Login ", command = destroy).grid(row = 5, column = 0) RegisterButton = Button(RegisterWindow, text = " Register ", command = registration).grid(row = 5, column = 1) RegisterWindow.mainloop() def menuWindow(UserName): def rules(): MenuWindow.destroy() ruleWindow(UserName) def game(): MenuWindow.destroy() try1 = Gamemode() try1.Tkinter_window() #test1() def highscore(): MenuWindow.destroy() highscoreWindow(UserName) MenuWindow = Tk() MenuWindow.title("Snake") MenuWindow.resizable(False, False) nameLabel = Label(MenuWindow, text = "Welcome "+UserName).pack() startGameButton = Button(MenuWindow, text = "Start Game", command = game).pack(fill=BOTH, side = TOP) rulesButton = Button(MenuWindow, text = "Rules", command = rules).pack(fill=BOTH) highScore = Button(MenuWindow, text = "High Score", command = highscore).pack(fill=BOTH, side = BOTTOM) MenuWindow.mainloop() def ruleWindow(UserName): def destroy(): RuleWindow.destroy() menuWindow(UserName) RuleWindow = Tk() RuleWindow.title("Snake") RuleWindow.resizable(False, False) ruleLabel = Label(RuleWindow, text = "The rules:\n The snake starts at the center of the board, moving north (upward). \n The snake moves at a constant speed. \n The snake moves only north, south, east, or west. \n Apples appear at random locations. \n There is always exactly one apple visible at any given time. \n When the snake eats (runs into) an apple, it gets longer. \n The game continues until the snake dies. \n A snake dies by by running into its own tail. \n The final score is based on the number of apples eaten by the snake.").pack() MenuWindowButton = Button(RuleWindow, text = "Menu", command = destroy).pack() RuleWindow.mainloop() def highscoreWindow(UserName): def destroy(): HighScoreWindow.destroy() menuWindow(UserName) HighScoreWindow = Tk() HighScoreWindow.title("Snake") HighScoreWindow.resizable(False, False) HighScoreLabelTitle = Label(HighScoreWindow, text = "High Score Table").grid(row = 0, columnspan = 3) HighScoreLabelNameTitle = Label(HighScoreWindow, text = "Name").grid(row = 1, column = 1) HighScoreLabelScoreTitle = Label(HighScoreWindow, text = "Score").grid(row = 1, column = 2) MenuWindowButton = Button(HighScoreWindow, text = "Menu", command = destroy).grid(row = 11, columnspan = 3) cursor.execute("""SELECT high_score, user_name FROM user_data ORDER By high_score DESC LIMIT 10""") raw_highscore = cursor.fetchall() print(raw_highscore) for count in range(10): highscore_conversion = raw_highscore[count] print(highscore_conversion) HighScoreLabelText = Label(HighScoreWindow, text = count+1).grid(row = count+2, column = 0) HighScoreLabelName = Label(HighScoreWindow, text = highscore_conversion[1]).grid(row = count+2, column = 1) HighScoreLabelScore = Label(HighScoreWindow, text = highscore_conversion[0]).grid(row = count+2, column = 2) HighScoreWindow.mainloop() class Gamemode(): def __init__(self): self.map_size = 0 self.gameModeSelection = Tk() self.bGC_var = False def state_change(self): if self.map_size == 1: self.smallGameCheck.select(); self.mediumGameCheck.deselect(); self.bigGameCheck.deselect() elif self.map_size == 2: self.smallGameCheck.deselect(); self.mediumGameCheck.select(); self.bigGameCheck.deselect() elif self.map_size == 3: self.smallGameCheck.deselect(); self.mediumGameCheck.deselect(); self.bigGameCheck.select() elif self.map_size == 4: self.smallGameCheck.deselect(); self.mediumGameCheck.deselect(); self.bigGameCheck.deselect(); self.customGameCheck.deselect() elif self.map_size == 5: self.smallGameCheck.deselect(); self.mediumGameCheck.deselect(); self.bigGameCheck.deselect(); self.classicGameCheck.deselect() elif self.map_size == 0: self.smallGameCheck.deselect(); self.mediumGameCheck.deselect(); self.bigGameCheck.deselect(); self.customGameCheck.deselect(); self.classicGameCheck.deselect() def small_game(self): if self.map_size != 1: self.map_size = 1 elif self.map_size == 1: self.map_size = 0 #print(self.smallGameCheck.state()) self.state_change() def medium_game(self): if self.map_size != 2: self.map_size = 2 elif self.map_size == 2: self.map_size = 0 self.state_change() def big_game(self): if self.map_size != 3: self.map_size = 3 elif self.map_size == 3: self.map_size = 0 self.state_change() def classic_game(self): if self.map_size != 4: self.map_size, self.size = 4, (1080, 720) elif self.map_size == 4: self.map_size = 0 self.state_change() def custom_game(self): if self.map_size != 5: self.map_size = 5 elif self.map_size == 5: self.map_size = 0 self.state_change() def start_game1(self): pass def Tkinter_window(self): self.classicGameCheck = Checkbutton(self.gameModeSelection, text = "Classic game?", command = self.classic_game) self.customGameCheck = Checkbutton(self.gameModeSelection, text = "Custom game?", command = self.custom_game) self.beginGameButton = Button(self.gameModeSelection, text = "Start Game", command = self.start_game1).pack() self.bigGameCheck = Checkbutton(self.gameModeSelection, text = "Big Map", command = self.big_game) self.mediumGameCheck = Checkbutton(self.gameModeSelection, text = "Medium Map", command = self.medium_game) self.smallGameCheck = Checkbutton(self.gameModeSelection, text = "Small Map", command = self.small_game) self.classicGameCheck.pack() self.customGameCheck.pack() self.bigGameCheck.pack() self.mediumGameCheck.pack() self.smallGameCheck.pack() #self.gameModeSelection.mainloop() connection_login = sqlite3.connect("user_data.db") cursor = connection_login.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS user_data (user_name text, user_password text, high_score intiger)""") cursor.execute("""CREATE UNIQUE INDEX IF NOT EXISTS IDX_Login ON user_data(user_name, user_password)""") loginwindow() connection_login.close()
8aa130fe10776387d57d1fef930f38b1cff3ffbd
JRosadoDiaz/SimplePersistenceProject
/Employee.py
1,048
3.65625
4
class Employee: #Constructor def __init__(self, employee_id, first_name, last_name, hire_year): self.employee_id = employee_id self.first_name = first_name self.last_name = last_name self.hire_year = hire_year.replace("\n", "") def get_employee_id(self): return self.employee_id def get_employee_first_name(self): return self.first_name def get_employee_last_name(self): return self.last_name def get_employee_hire_year(self): return self.hire_year def set_employee_id(self, id): self.employee_id = id def set_employee_first_name(self, name): self.first_name = name def set_employee_last_name(self, name): self.last_name = name def set_employee_hire_year(self, year): self.hire_year = year def toString(self): return "ID: " + self.get_employee_id() + ", Name: " + self.get_employee_first_name() + " " + self.get_employee_last_name() + ", Hire Year: " + self.get_employee_hire_year()
48bf36a3d25f3603d62b7fb96362abde60fd0c92
kush96/ApiRateLimiter
/API5.py
783
3.546875
4
import json #json package import requests #requests package def api5(): print '#' * 40 print 'Welcome to API 5' curr_base = raw_input('enter base currency or q to quit: ') # Input Base currency name if curr_base =="q": print "END OF API 5" print '#' * 40 return data = requests.get('https://api.exchangeratesapi.io/latest?base='+curr_base+'') # Requesting data from the Url after concatinating base curr data_format = json.loads(data.text) # Extracting text from the data if 'error' in data_format.keys(): # Checking if error occured or not print ('Wrong Currency') else: print(json.dumps(data_format,sort_keys=True,indent=4)) print "END OF API 5" print '#' * 40
132ee7e4043f69ef7bb76158731ffc4e15d45124
ssavann/PY-POO
/constructeur_classe.py
662
3.96875
4
''' POO: Le constructeur de classe c'est une méthode qui porte un nom spécial __init__ self: représente l'instance "voiture1" et "voiture2" ''' class Vehicule: def __init__(self , marque_vehicule, couleur_vehicule): #Attributs (variable de classe) self.marque = marque_vehicule self.couleur = couleur_vehicule #Programme voiture1 = Vehicule("Renault", "rouge") #instance objet voiture2 = Vehicule("Toyota", "noire") #instance objet print(f"La voiture 1 est de couleur {voiture1.couleur} et c'est une {voiture1.marque}") print(f"La voiture 2 est de couleur {voiture2.couleur} et c'est une {voiture2.marque}")
58c7ff693418bfb7734765fc69f13052defeb188
an4p/python_learning
/less07/less07_03.py
198
3.703125
4
try: file1 = open("file1.txt") for line in file1: int(line) except ValueError as e: print(e) else: print("I did it!") finally: file1.close() print("Closing file...")
ce6a8a6e242479b0bb4a472dba25327f7623e060
RenanBertolotti/Python
/Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 02 - Funçoes (def) (Parte 2)/Aula02.py
1,071
4.09375
4
""" Funçoes (def) - return """ def funcao(msg): #print(msg) #Em vez de print, usar: return msg variavel = funcao("ola mundo") print(variavel) #Retorna NULO , pois foi utilizado o print como retorno na funçao!,sendo o correto RETURN #quando acontecer isso,usar: if variavel is not None: #checando se nao e Nulo print(variavel) else: print("nenhum valor") ######################################### def divisao(n1, n2): if n2 == 0: return f'nao existe divisao por 0' else: return n1 / n2 #Assim conta = divisao(10, 0) print(conta) #OU print(divisao(10, 5)) ############################################# def lista(): # funcao que retorna lista return [1, 2, 3, 4, 5] var = lista() print(var, type(var)) ############################################# def none(): return #funcao que retona nulo ############################################ def boolean(): return True #Funcao que retonar booleano verdadeiro #############################################
e1ea87a7047cc68b587d582f934a1a05516bdf52
kunalprompt/numpy
/numpyArraySlicing.py
879
4.40625
4
''' Hello World! http://kunalprompt.github.io ''' print __doc__ import numpy as np ''' Indexing, and Slicing in Python Numpy There are three kinds of indexing available: 1. record access, 2. basic slicing, 3. advanced indexing Which one occurs depends on obj. ''' # Record Access already done. # Slicing (start:stop:step) # 1D Slicing numObjA = np.arange(20, dtype='float') print "1-D numObjA Slicing " # like an array, indexing goes here as # array = 112 12 133 # Indexes = 0 1 2 # Indexing= -3 -2 -1 start=13;stop=17;step=1 # [::-1] to reverse the ndarray print numObjA[start:stop: step] # 2D Slicing numObjB = np.reshape(np.arange(20, dtype='float'), (5,4)) print "numObjB \n", numObjB print "Slicing the 2-D numpy object numObjB " print numObjB[1:3, 0:2] # like numObj[0:5, 1:2] will return all rows (start=1, stop=5, step=1) and colums (start=1, stop=2, step=1)
14ff0a3cf377b11911822a8c07f7e405511e102a
leNEKO/exercism-solution
/python/word-count/word_count.py
681
3.828125
4
import re from collections import defaultdict def word_count(phrase): cleaning = phrase.lower() cleaning = re.sub(r"(\w+)'(\w+)", "\\1ˇˇˇ\\2", cleaning) # better hack, but ugly cleaning = re.sub(r"[\W_]+", " ", cleaning) clean = re.sub(r"ˇˇˇ", "'", cleaning) + " " words = defaultdict(int) word = "" for char in clean: char = char.lower() if char == " ": if word.strip(): words[word] += 1 word = "" else: word += char return dict(words) def main(): print(word_count("go Go GO Stop stop")) if __name__ == '__main__': main()
76c96afe8cb18eeb351367f109d00f24ac2c5503
gschen/sctu-ds-2020
/1906101033-唐超/Day0310/课堂作业1.py
703
3.9375
4
# 一、定义一个学生Student类。有下面的类属性: # 1姓名name; # 2年龄age # 3成绩score (语文,数学,英语) [每课成绩的类型为整数] # 类方法: # 1获取学生的姓名: get name() # 2获取学生的年龄: get age() # 3返回3门科目中最高的分数。get course() class Student(): def __init__(self,name,age,score): self.name=name self.age=age self.score=score def get_name(self): print('姓名:',self.name) def get_age(self): print('年龄:',self.age) def get_score(self): print('最高分:',max(self.score)) x=Student('张三',20,[80,90,95]) x.get_name() x.get_age() x.get_score()
fca26a5bc74983b3907eeebe765b9271b8cc2aa2
kmcginn/advent-of-code
/2019/day12/moons.py
10,421
4.03125
4
#! python3 """ from: https://adventofcode.com/2019/day/12 --- Day 12: The N-Body Problem --- The space near Jupiter is not a very safe place; you need to be careful of a big distracting red spot, extreme radiation, and a whole lot of moons swirling around. You decide to start by tracking the four largest moons: Io, Europa, Ganymede, and Callisto. After a brief scan, you calculate the position of each moon (your puzzle input). You just need to simulate their motion so you can avoid them. Each moon has a 3-dimensional position (x, y, and z) and a 3-dimensional velocity. The position of each moon is given in your scan; the x, y, and z velocity of each moon starts at 0. Simulate the motion of the moons in time steps. Within each time step, first update the velocity of every moon by applying gravity. Then, once all moons' velocities have been updated, update the position of every moon by applying velocity. Time progresses by one step once all of the positions are updated. To apply gravity, consider every pair of moons. On each axis (x, y, and z), the velocity of each moon changes by exactly +1 or -1 to pull the moons together. For example, if Ganymede has an x position of 3, and Callisto has a x position of 5, then Ganymede's x velocity changes by +1 (because 5 > 3) and Callisto's x velocity changes by -1 (because 3 < 5). However, if the positions on a given axis are the same, the velocity on that axis does not change for that pair of moons. Once all gravity has been applied, apply velocity: simply add the velocity of each moon to its own position. For example, if Europa has a position of x=1, y=2, z=3 and a velocity of x=-2, y=0,z=3, then its new position would be x=-1, y=2, z=6. This process does not modify the velocity of any moon. For example, suppose your scan reveals the following positions: <x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1> Simulating the motion of these moons would produce the following: After 0 steps: pos=<x=-1, y= 0, z= 2>, vel=<x= 0, y= 0, z= 0> pos=<x= 2, y=-10, z=-7>, vel=<x= 0, y= 0, z= 0> pos=<x= 4, y= -8, z= 8>, vel=<x= 0, y= 0, z= 0> pos=<x= 3, y= 5, z=-1>, vel=<x= 0, y= 0, z= 0> After 1 step: pos=<x= 2, y=-1, z= 1>, vel=<x= 3, y=-1, z=-1> pos=<x= 3, y=-7, z=-4>, vel=<x= 1, y= 3, z= 3> pos=<x= 1, y=-7, z= 5>, vel=<x=-3, y= 1, z=-3> pos=<x= 2, y= 2, z= 0>, vel=<x=-1, y=-3, z= 1> After 2 steps: pos=<x= 5, y=-3, z=-1>, vel=<x= 3, y=-2, z=-2> pos=<x= 1, y=-2, z= 2>, vel=<x=-2, y= 5, z= 6> pos=<x= 1, y=-4, z=-1>, vel=<x= 0, y= 3, z=-6> pos=<x= 1, y=-4, z= 2>, vel=<x=-1, y=-6, z= 2> After 3 steps: pos=<x= 5, y=-6, z=-1>, vel=<x= 0, y=-3, z= 0> pos=<x= 0, y= 0, z= 6>, vel=<x=-1, y= 2, z= 4> pos=<x= 2, y= 1, z=-5>, vel=<x= 1, y= 5, z=-4> pos=<x= 1, y=-8, z= 2>, vel=<x= 0, y=-4, z= 0> After 4 steps: pos=<x= 2, y=-8, z= 0>, vel=<x=-3, y=-2, z= 1> pos=<x= 2, y= 1, z= 7>, vel=<x= 2, y= 1, z= 1> pos=<x= 2, y= 3, z=-6>, vel=<x= 0, y= 2, z=-1> pos=<x= 2, y=-9, z= 1>, vel=<x= 1, y=-1, z=-1> After 5 steps: pos=<x=-1, y=-9, z= 2>, vel=<x=-3, y=-1, z= 2> pos=<x= 4, y= 1, z= 5>, vel=<x= 2, y= 0, z=-2> pos=<x= 2, y= 2, z=-4>, vel=<x= 0, y=-1, z= 2> pos=<x= 3, y=-7, z=-1>, vel=<x= 1, y= 2, z=-2> After 6 steps: pos=<x=-1, y=-7, z= 3>, vel=<x= 0, y= 2, z= 1> pos=<x= 3, y= 0, z= 0>, vel=<x=-1, y=-1, z=-5> pos=<x= 3, y=-2, z= 1>, vel=<x= 1, y=-4, z= 5> pos=<x= 3, y=-4, z=-2>, vel=<x= 0, y= 3, z=-1> After 7 steps: pos=<x= 2, y=-2, z= 1>, vel=<x= 3, y= 5, z=-2> pos=<x= 1, y=-4, z=-4>, vel=<x=-2, y=-4, z=-4> pos=<x= 3, y=-7, z= 5>, vel=<x= 0, y=-5, z= 4> pos=<x= 2, y= 0, z= 0>, vel=<x=-1, y= 4, z= 2> After 8 steps: pos=<x= 5, y= 2, z=-2>, vel=<x= 3, y= 4, z=-3> pos=<x= 2, y=-7, z=-5>, vel=<x= 1, y=-3, z=-1> pos=<x= 0, y=-9, z= 6>, vel=<x=-3, y=-2, z= 1> pos=<x= 1, y= 1, z= 3>, vel=<x=-1, y= 1, z= 3> After 9 steps: pos=<x= 5, y= 3, z=-4>, vel=<x= 0, y= 1, z=-2> pos=<x= 2, y=-9, z=-3>, vel=<x= 0, y=-2, z= 2> pos=<x= 0, y=-8, z= 4>, vel=<x= 0, y= 1, z=-2> pos=<x= 1, y= 1, z= 5>, vel=<x= 0, y= 0, z= 2> After 10 steps: pos=<x= 2, y= 1, z=-3>, vel=<x=-3, y=-2, z= 1> pos=<x= 1, y=-8, z= 0>, vel=<x=-1, y= 1, z= 3> pos=<x= 3, y=-6, z= 1>, vel=<x= 3, y= 2, z=-3> pos=<x= 2, y= 0, z= 4>, vel=<x= 1, y=-1, z=-1> Then, it might help to calculate the total energy in the system. The total energy for a single moon is its potential energy multiplied by its kinetic energy. A moon's potential energy is the sum of the absolute values of its x, y, and z position coordinates. A moon's kinetic energy is the sum of the absolute values of its velocity coordinates. Below, each line shows the calculations for a moon's potential energy (pot), kinetic energy (kin), and total energy: Energy after 10 steps: pot: 2 + 1 + 3 = 6; kin: 3 + 2 + 1 = 6; total: 6 * 6 = 36 pot: 1 + 8 + 0 = 9; kin: 1 + 1 + 3 = 5; total: 9 * 5 = 45 pot: 3 + 6 + 1 = 10; kin: 3 + 2 + 3 = 8; total: 10 * 8 = 80 pot: 2 + 0 + 4 = 6; kin: 1 + 1 + 1 = 3; total: 6 * 3 = 18 Sum of total energy: 36 + 45 + 80 + 18 = 179 In the above example, adding together the total energy for all moons after 10 steps produces the total energy in the system, 179. Here's a second example: <x=-8, y=-10, z=0> <x=5, y=5, z=10> <x=2, y=-7, z=3> <x=9, y=-8, z=-3> Every ten steps of simulation for 100 steps produces: After 0 steps: pos=<x= -8, y=-10, z= 0>, vel=<x= 0, y= 0, z= 0> pos=<x= 5, y= 5, z= 10>, vel=<x= 0, y= 0, z= 0> pos=<x= 2, y= -7, z= 3>, vel=<x= 0, y= 0, z= 0> pos=<x= 9, y= -8, z= -3>, vel=<x= 0, y= 0, z= 0> After 10 steps: pos=<x= -9, y=-10, z= 1>, vel=<x= -2, y= -2, z= -1> pos=<x= 4, y= 10, z= 9>, vel=<x= -3, y= 7, z= -2> pos=<x= 8, y=-10, z= -3>, vel=<x= 5, y= -1, z= -2> pos=<x= 5, y=-10, z= 3>, vel=<x= 0, y= -4, z= 5> After 20 steps: pos=<x=-10, y= 3, z= -4>, vel=<x= -5, y= 2, z= 0> pos=<x= 5, y=-25, z= 6>, vel=<x= 1, y= 1, z= -4> pos=<x= 13, y= 1, z= 1>, vel=<x= 5, y= -2, z= 2> pos=<x= 0, y= 1, z= 7>, vel=<x= -1, y= -1, z= 2> After 30 steps: pos=<x= 15, y= -6, z= -9>, vel=<x= -5, y= 4, z= 0> pos=<x= -4, y=-11, z= 3>, vel=<x= -3, y=-10, z= 0> pos=<x= 0, y= -1, z= 11>, vel=<x= 7, y= 4, z= 3> pos=<x= -3, y= -2, z= 5>, vel=<x= 1, y= 2, z= -3> After 40 steps: pos=<x= 14, y=-12, z= -4>, vel=<x= 11, y= 3, z= 0> pos=<x= -1, y= 18, z= 8>, vel=<x= -5, y= 2, z= 3> pos=<x= -5, y=-14, z= 8>, vel=<x= 1, y= -2, z= 0> pos=<x= 0, y=-12, z= -2>, vel=<x= -7, y= -3, z= -3> After 50 steps: pos=<x=-23, y= 4, z= 1>, vel=<x= -7, y= -1, z= 2> pos=<x= 20, y=-31, z= 13>, vel=<x= 5, y= 3, z= 4> pos=<x= -4, y= 6, z= 1>, vel=<x= -1, y= 1, z= -3> pos=<x= 15, y= 1, z= -5>, vel=<x= 3, y= -3, z= -3> After 60 steps: pos=<x= 36, y=-10, z= 6>, vel=<x= 5, y= 0, z= 3> pos=<x=-18, y= 10, z= 9>, vel=<x= -3, y= -7, z= 5> pos=<x= 8, y=-12, z= -3>, vel=<x= -2, y= 1, z= -7> pos=<x=-18, y= -8, z= -2>, vel=<x= 0, y= 6, z= -1> After 70 steps: pos=<x=-33, y= -6, z= 5>, vel=<x= -5, y= -4, z= 7> pos=<x= 13, y= -9, z= 2>, vel=<x= -2, y= 11, z= 3> pos=<x= 11, y= -8, z= 2>, vel=<x= 8, y= -6, z= -7> pos=<x= 17, y= 3, z= 1>, vel=<x= -1, y= -1, z= -3> After 80 steps: pos=<x= 30, y= -8, z= 3>, vel=<x= 3, y= 3, z= 0> pos=<x= -2, y= -4, z= 0>, vel=<x= 4, y=-13, z= 2> pos=<x=-18, y= -7, z= 15>, vel=<x= -8, y= 2, z= -2> pos=<x= -2, y= -1, z= -8>, vel=<x= 1, y= 8, z= 0> After 90 steps: pos=<x=-25, y= -1, z= 4>, vel=<x= 1, y= -3, z= 4> pos=<x= 2, y= -9, z= 0>, vel=<x= -3, y= 13, z= -1> pos=<x= 32, y= -8, z= 14>, vel=<x= 5, y= -4, z= 6> pos=<x= -1, y= -2, z= -8>, vel=<x= -3, y= -6, z= -9> After 100 steps: pos=<x= 8, y=-12, z= -9>, vel=<x= -7, y= 3, z= 0> pos=<x= 13, y= 16, z= -3>, vel=<x= 3, y=-11, z= -5> pos=<x=-29, y=-11, z= -1>, vel=<x= -3, y= 7, z= 4> pos=<x= 16, y=-13, z= 23>, vel=<x= 7, y= 1, z= 1> Energy after 100 steps: pot: 8 + 12 + 9 = 29; kin: 7 + 3 + 0 = 10; total: 29 * 10 = 290 pot: 13 + 16 + 3 = 32; kin: 3 + 11 + 5 = 19; total: 32 * 19 = 608 pot: 29 + 11 + 1 = 41; kin: 3 + 7 + 4 = 14; total: 41 * 14 = 574 pot: 16 + 13 + 23 = 52; kin: 7 + 1 + 1 = 9; total: 52 * 9 = 468 Sum of total energy: 290 + 608 + 574 + 468 = 1940 What is the total energy in the system after simulating the moons given in your scan for 1000 steps? """ import os from functools import reduce def main(): """Solve the problem!""" script_dir = os.path.dirname(__file__) file_path = os.path.join(script_dir, './input.txt') moons_pos = list() with open(file_path) as input_file: for line in input_file: moons_pos.append(parse_coords(line)) moons_vel = [[0, 0, 0] for x in range(0, len(moons_pos))] num_steps = 1000 show_steps = False for i in range(0, num_steps): step_simulation(moons_pos, moons_vel) if show_steps: print("After", i+1, " steps") for j in range(0, len(moons_pos)): print("Position:", moons_pos[j], "Velocity:", moons_vel[j]) total_energy = calcluate_total_energy(moons_pos, moons_vel) print(total_energy) def parse_coords(coord_str): """Parse a line like <x=1, y=2, z=-3> into [1, 2, -3]""" coords = coord_str.strip('<>\n').split(',') return [int(coords[x].split('=')[1]) for x in range(0, 3)] def step_simulation(moons_pos, moons_vel): """Apply one step to the simulation bodies""" # apply gravity to velocity for i in range(0, len(moons_pos)): for j in range(i+1, len(moons_pos)): for coord in range(0, 3): if moons_pos[i][coord] == moons_pos[j][coord]: continue if moons_pos[i][coord] > moons_pos[j][coord]: moons_vel[i][coord] -= 1 moons_vel[j][coord] += 1 else: moons_vel[i][coord] += 1 moons_vel[j][coord] -= 1 # apply velocity to position for i in range(0, len(moons_pos)): for coord in range(0, 3): moons_pos[i][coord] += moons_vel[i][coord] def calcluate_total_energy(moons_pos, moons_vel): """Calculate the total energy of the system""" total_energy = 0 for i in range(0, len(moons_pos)): pot_e = reduce(lambda x, y: abs(x) + abs(y), moons_pos[i]) kin_e = reduce(lambda x, y: abs(x) + abs(y), moons_vel[i]) total_energy += pot_e * kin_e return total_energy if __name__ == "__main__": main()
b04d4dc370e4c6e31585360424c00bea193ca5f0
IST256-Spring2018/demos
/Lesson-11/darksky.py
967
3.671875
4
""" https://darksky.net/dev 78b65883930875275cd338e25131cdee """ import requests def get_coords(address): api_key = "AIzaSyDFuKg19Z_gzuOnKYa0JusiWFJZ6avhwn8" url = "https://maps.googleapis.com/maps/api/geocode/json" response = requests.get(url, params={"address": address, "key": api_key}) if response.status_code == 200: result = response.json() latlng = result["results"][0]["geometry"]["location"] return latlng return None def get_weather_summary(lat, lng): url = "https://api.darksky.net/forecast/{}/{},{}" key = "78b65883930875275cd338e25131cdee" req_url = url.format(key, lat, lng) response = requests.get(req_url) if response.ok: current_weather_data = response.json() summary = current_weather_data["currently"]["summary"] return summary return "Error" address = input("What is you city and state? ") latlng = get_coords(address) summary = get_weather_summary(latlng["lat"], latlng["lng"]) print("Your weather is currently: {}".format(summary))
668ce4ec755cb8faf3c312b1e97c146194334858
kitconcept/robotframework-pageobjects
/robotpageobjects/sig.py
980
3.671875
4
""" Responsible for figuring out a method signature as a string. """ import inspect from collections import namedtuple DefaultArg = namedtuple('DefaultArg', 'is_valid value') def get_default_arg(args, defaults, i): if not defaults: return DefaultArg(False, None) args_with_no_defaults = len(args) - len(defaults) if i < args_with_no_defaults: return DefaultArg(False, None) else: value = defaults[i - args_with_no_defaults] if (type(value) is str): value = '"%s"' % value return DefaultArg(True, value) def get_method_sig(method): argspec = inspect.getargspec(method) i=0 args = [] for arg in argspec.args: default_arg = get_default_arg(argspec.args, argspec.defaults, i) if default_arg.is_valid: args.append("%s=%s" % (arg, default_arg.value)) else: args.append(arg) i += 1 return "%s(%s)" % (method.__name__, ", ".join(args))
eb2c961b584e956782fb3f738569a2c16463e348
XiaoqingWang/python_code
/python语法基础/02.if、while、for/15-剪刀石头布.py
526
3.78125
4
import random #1.提示并获取用户的输入 player = int(input("请输入 0剪刀 1石头 2布:")) #2.让电脑出一个 computer = random.randint(0,2) #3.判断用户的输入,然后显示对应的结果 #if 玩家获胜的条件 if(player == 0 and computer == 2) or (player == 1 and computer == 0) or (player == 2 and computer == 1): print("赢了。。。可以去买洗衣粉...") elif player == computer: print("平局了...洗洗手决战到天亮。。。") else: print("输了...回家拿钱 再来...")
393e284fa55e060fb66c652212633fd6fd05685b
hdf2104/python_tests
/tuple_functions.py
1,088
4.375
4
''' Several useful functions(or methods) for doing things with tuples ''' def TVCKWA (a_tup=(2,3,4,5), an_int=6) : '''this returns the input with an_int as the first term''' print a_tup, an_int print a_tup[1:] print a_tup *2 print (an_int,) + a_tup[1:] #need oto create a new tuple that looks like above that is sliced new_tup = (an_int,) + a_tup[1:] #new_tup = new_tup + a_tup[1:] is the same as new_tup += a_tup[1:] return new_tup def print_tuple( tup = (1,2,3) ) : '''prints a tuple, no return value ''' return tup ''' define a new function that takes in any number of touples, find the length of each of those tuples, and returns a list of lengths ''' '''returns the length of tuples that have been input. Find out how to do arbitrary number of inputs in a function(ie (1,2,3),(5,6),(1,10,100,1000))>> [3,2,4]''' def ftL (*tuples) : list_of_len = [] print tuples #iterating over each item in tuples for tup in tuples : print tup print len(tup) list_of_len.append(len(tup)) return list_of_len
fbcf48c6a92f26fdcc9b573421a32e40cb1250ac
jlzxian/Python
/tutorial/NumPy/Arithmetic Operations.py
727
4.125
4
"""Arithmetic Operations""" import numpy as np def test_run(): a = np.array([(1,2,3,4,5),(10,20,30,40,50)]) print("OG array a:\n",a) #Multiply a by 2 print("\nMultiply a by 2:\n", 2*a) #Divide a by 2 print("\nDivide a by 2:\n", a/2) b = np.array([(100,200,300,400,500),(1,2,3,4,5)]) print("OG array b:\n",b) #Add two arrays print("\nAdd a+b:\n", a+b) #Multiply two arrays 'note: it is not linear multiplication, it is element time respective element in second array' print("\nMultiplcation a*b:\n",a*b) #Instead use np.dot(a,b) print("\nDot Product a.b:\n",np.dot(np.array([(1,0),(0,1)]),np.array([(4,1),(2,2)]))) if __name__ == "__main__": test_run()
162871a2c13f83c96c4a08b890374a29d5ab90d7
nowacki69/Python
/Udemy/Python3Bootcamp/Modules/73_Built_In_Modules_Exercise.py
364
3.59375
4
# It's time to get some practice with built-in modules. Here's your mission: # - Import the math module # - use math.sqrt to find the square root of 15129 and save it in 'answer' # Import the math module: import math # Use math.sqrt to find the square root of 15129 and save it to variable # called answer: num = 15129 answer = math.sqrt(num) print(answer)
c858740aca4412c22f714ae3e19d063c10383f54
AsgardRodent/MyPy
/arguments.py
1,143
4.1875
4
def print_name_age(name = "someone", age = "ancient"): print("hi my name is ", name ,"i am ", age, " years old") print_name_age("gaurav", 20) print_name_age("regigas") print_name_age("supahotfire", 28) print_name_age(age=32) # to solve the above error u can directly replace the line(4) with the following code which just [rints all the data as itself # print("hi my name is ", name ,"i am ", age , " years old") ----> this is to be replaced # as a back up the default line is provided below :D # print("hi my name is " + name + " i am " + str(age) + " years old")--------> default line # in line(9) only 32 is passed which will be replaced by the name since it as per the definition/the parameters provided to the function # so the keyword "None" is used to skip a parameter hence the new line will be :D # print_name_age(None,32) ------> new line # print_name_age(32)---------> default line # none --> bool # this error can be sorted using key arguments like #print_name_age(age = 32) # REMEMBER KEY ARGUMENTS CAN BE PASSED IN ANY MANNER AS YOU LIKE ,SINCE THEY ARE DEFINED TO A SPECIFIC VALUE
1e30a99c62bcb5aa44be58891d8210b608794cfd
guam68/class_iguana
/Code/Richard/python/lab18-peaks-valleys.py
1,508
3.90625
4
""" author: Richard Sherman 2018-12-06 lab10-peaks-valleys.py, takes a list of ints and identifies elements greater than their immediate neighbors ('peaks') and elements less than their immediate neighbors ('valleys'). Tries to extend this logic beyond immediate neighbors to find the 'volume' of 'valleys' and the 'height' of 'peaks' """ import random print('We\'ll generate a list of integers, then identify the \'peaks\' (those greater than their immediate neighbors\ and the \'valleys\' (those less than their immediate neighbors. Here is the randomly generated list:') terrain = [] size = range(7) for i in size: terrain.append(random.randint(0, 10)) print(terrain) print('First we identify the peaks:') # there must be a way to do this using slicing only, but the while loop seems easier to read and easier to type peaks = [] #if terrain[0] > terrain[1]: # don't need this # peaks.append(0) i = 0 while i < len(terrain) - 1: if terrain[i] > terrain[i - 1] and terrain[i] > terrain[i + 1]: peaks.append(i) i += 1 print(peaks) print('\nThen we identify the valleys:') valleys = [] #if terrain[0] > terrain[1]: # don't need this # valleys.append(0) i = 0 while i < len(terrain) - 1: if terrain[i] < terrain[i - 1] and terrain[i] < terrain[i + 1]: valleys.append(i) i += 1 print(valleys) print('\nNow we want to know the volume of the valleys:') index_value = [] for i in range(len(terrain) - 1) : index_value.append((i, terrain[i])) print(index_value)
c0dbd7c99771debca7726a3d4a4536c7ec9b4d02
RSofiaC/LearningMachines
/assigment1_rle.py
1,126
3.890625
4
# rle assignment # by rsofiac # for patrick hebron's learning machines class # at nyu itp # fall 2017 # input can be any string with characters, no numbers # output will be an encoded string def coding(input): # initialize output output = '' # initialize counter of same character counter = 0 # count the characters countChar = 0 # initialize current character currentChar = input[0] # iterate through the input for ch in input: # add up the countChar countChar = countChar + 1 # check if the character is repeated if ch == currentChar: counter = counter + 1 # else, append to the output else: # append the info output = output + currentChar + str(counter) # reset counter counter = 1 # reset currentChar currentChar = ch # catch the last char if countChar == len(input): output = output + currentChar + str(counter) # print output print output #still need to find how to decode this one coding ("jsdgkkkasdiii")
7828dddc6d776f5c29049e35fb796bb33aead500
AlexHolmes4/Python-Repository
/PY4E adaptations/13.4-adaptation_Simplified_xPath_and_List_Comprehension.py
1,108
3.859375
4
#This program will prompt for a URL, read the XML data from that URL using urllib #and then parse and extract the comment counts from the XML data, computing the sum of numbers in the file import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE #obtain the input source url = input('Enter URL: ') if len(url) < 1: url = "http://py4e-data.dr-chuck.net/comments_42.xml" print("Retrieving", url) #obtain the response webhandle = urllib.request.urlopen(url, context=ctx) byteresp = webhandle.read() print("Retrieved", len(byteresp), "characters") #print(byteresp.decode()) hidden, as used for reviewing XML format prior to parsing. #parse into ET to otain the paths tree = ET.fromstring(byteresp) #fromstring works with class bytes #find all the count nodes with xPath, loop through them and extract the text value, pass into int function and sum the lot with list comprehension. print(sum([int(i.text) for i in tree.findall('.//count')]))
8e5eb4f80f779f67547de1fb1c3dd5fd250b7a3e
arun5061/Python
/Python_My/String count using dict.py
369
3.53125
4
word=input('Enter string:') d={} for k in word: d[k]=10 print(';;;',d) d[k]=d.get(k,0)+1 print('d:',d) for n,v in sorted(d.items()): print('{} occured {} times'.format(n,v)) d={} s={'a','e','i','o','u'} for k in word: if k in s: d[k]=d.get(k,0)+1 print('d:',d) for n,v in sorted(d.items()): print('{} occured {} times'.format(n,v))
1f1efdffc23d9cc21e9075b6451cd8d78e59b9d1
SvetoslavGeorgiev/SoftUni
/Programming_Basics_Python/First_Steps_in_Coding_Lab/Pet_Shop/Pet_Shop.py
185
3.609375
4
food_for_dogs = int(input()) food_for_other_animals = int(input()) money_needed = (food_for_dogs * 2.50) + (food_for_other_animals * 4.00) print(f"{format(money_needed, '.2f')} lv.")
f802eb365b0e68b33c2fca91aeb89de067e65725
AmberBianco/Coding-and-Informatics-Projects
/matrices.py
3,278
4.15625
4
11 def add_row(matrix): """ >>> m = [[0, 0], [0, 0]] >>> add_row(m) [[0, 0], [0, 0], [0, 0]] >>> n = [[3, 2, 5], [1, 4, 7]] >>> add_row(n) [[3, 2, 5], [1, 4, 7], [0, 0, 0]] >>> n [[3, 2, 5], [1, 4, 7]] """ newmatrix = [] for row in matrix: newrow = [len(matrix[0]) * [0]] new = newmatrix + newrow return matrix + new def add_column(matrix): """ >>> m = [[0, 0], [0, 0]] >>> add_column(m) [[0, 0, 0], [0, 0, 0]] >>> n = [[3, 2], [5, 1], [4, 7]] >>> add_column(n) [[3, 2, 0], [5, 1, 0], [4, 7, 0]] >>> n [[3, 2], [5, 1], [4, 7]] """ newmatrix = [[]] * len(matrix) for i in range(len(matrix)): newmatrix[i] = matrix[i] + [0] return newmatrix #12 def add_matrices(m1, m2): """ >>> a = [[1, 2], [3, 4]] >>> b = [[2, 2], [2, 2]] >>> add_matrices(a, b) [[3, 4], [5, 6]] >>> c = [[8, 2], [3, 4], [5, 7]] >>> d = [[3, 2], [9, 2], [10, 12]] >>> add_matrices(c, d) [[11, 4], [12, 6], [15, 19]] >>> c [[8, 2], [3, 4], [5, 7]] >>> d [[3, 2], [9, 2], [10, 12]] """ mat1= m1[:] mat2=m2[:] mat_sum= [] for i in range(len(m1)): added_row=[] for j in range(len(mat1[i])): added_row.append (mat1[i][j] + mat2[i][j]) mat_sum.append(added_row) return mat_sum #13 def scalar_mult(s, m): """ >>> a = [[1, 2], [3, 4]] >>> scalar_mult(3, a) [[3, 6], [9, 12]] >>> b = [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]] >>> scalar_mult(10, b) [[30, 50, 70], [10, 10, 10], [0, 20, 0], [20, 20, 30]] >>> b [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]] """ mult_lst = [] for row in m: new_row = [] for elem in row: new_row.append(elem * s) mult_lst.append(new_row) return mult_lst #14 def row_times_column(m1, row, m2, column): """ >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0) 19 >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1) 22 >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 0) 43 >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 1) 50 """ result = 0 for i in range(len(m1[row])): result = result + m1[row][i] * m2[i][column] return result def matrix_mult(m1, m2): """ >>> matrix_mult([[1, 2], [3, 4]], [[5, 6], [7, 8]]) [[19, 22], [43, 50]] >>> matrix_mult([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 1], [2, 3]]) [[31, 19], [85, 55]] >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]]) [[39, 54, 69], [13, 23, 33], [14, 19, 24]] """ rows_m1 = len(m1) cols_m2 = len(m2[0]) mult_matrix = [] for row in range(rows_m1): new_row = [] for column in range(cols_m2): new_row.append(row_times_column(m1, row, m2, column)) mult_matrix.append(new_row) return mult_matrix if __name__ == '__main__': import doctest doctest.testmod()
3f52cdc6e6a2cf532657871074563a052466b145
omiplekevin/bywave-python-training
/exer_002.py
354
3.953125
4
# -*- coding: utf-8 -*- """ Exercise #2 Write a program that prints all multiples of 7 that are below 100. Hints: check python’s range Function """ # your name and email address here __author__ = 'xXLXx <kevin@bywave.com.au>' if __name__ == '__main__': mods = [x for x in range(0,100) if x % 7 == 0] print(mods) # for x in range(0,100,7): # print x