blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
904a159e7e29fd2ae4fb6ed79e6e015a84827bf3
GyuReeKim/solving_code
/d1/d1_1545.py
68
3.609375
4
num = int(input()) for n in range(num,-1, -1): print(n, end=' ')
fc06b3b7251af9699e92f92501cb1028257db7f7
JoaoRicardoRaiser/python-basic
/Atividade 3.py
513
4.3125
4
# Faça um Programa que peça dois números e imprima a soma. # numero1 =float(input("Digite um número:\n")) # numero2 = float(input("Digite outro número:\n")) # print(f"A soma dos seus números foi:\n{numero1+numero2}") print("Digite um número: ") numero1 = float(input()) print("Digite outro número: ") numero2 = float(input()) soma = numero1 + numero2 print("A soma dos seus números foi: ", soma) print("A soma dos seus números foi: {} ".format(soma)) print(f"A soma dos seus números foi: {soma}")
576ef97ebcaf4b8785a8a55d6355b69186e1ee8f
Iamsmart123/AE402
/class402_6.py
1,536
3.5
4
import pygame,random WHITE = (255,255,255) BLACK = (0,0,0) YELLOW = (255,255,0) x=[300,250,200,250] y=[250,250,250,200] pygame.init() done = False size = (700,500) screen= pygame.display.set_mode(size) pygame.display.set_caption("game") clock=pygame.time.Clock() def new_color(choice): tmp=random.randint(0,3) while choice == tmp: tmp=random.randint(0,3) choice = tmp return choice choice = random.randint(0,3) score = 0 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill(WHITE) if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: if(choice == 2): choice =new_color(choice) score = score+1 elif event.key == pygame.K_RIGHT: if(choice == 0): choice =new_color(choice) score = score+1 elif event.key == pygame.K_UP: if(choice == 3): choice =new_color(choice) score = score+1 elif event.key == pygame.K_DOWN: if(choice == 1): choice =new_color(choice) score = score+1 for i in range(4): if i == choice: color = YELLOW else: color = BLACK pygame.draw.rect(screen,color,[x[i],y[i],40,40]) pygame.display.set_caption(str(score)) pygame.display.flip() clock.tick(60) pygame.quit()
12ec825abee1d8bcc67e395e819a4c31f901798f
prabhanshu-aggarwal/Data_Structure_and_Algo
/LinkedList/Nth_node _from_last.py
1,011
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed May 20 20:30:15 2020 @author: Prabhanshu Aggarwal """ class Node: def __init__(self, value): self.value = value self.next_node = None class LinkedList(): def __init__(self): self.head = None def Nth(self, nval): left=self.head right=self.head inc=0 while(right is not None): if(inc>=nval): left = left.next_node right=right.next_node else: right=right.next_node inc+=1 print(left.value) def printList(self): temp = self.head while(temp): print (temp.value) temp = temp.next_node list1 = LinkedList() list1.head=Node(1) b=Node(2) c=Node(3) d=Node(4) e=Node(5) f=Node(6) g=Node(7) list1.head.next_node = b b.next_node = c c.next_node = d d.next_node = e e.next_node = f f.next_node = g list1.Nth(5)
0636f272d626febdd698ff2debcc25f9e500c342
guiconti/workout
/crackingthecodeinterview/stacksandqueues/3-3.py
1,493
3.71875
4
# Design a stack that also contains a min function with O(1) class SetOfStacks(): amountOfStacks = 1 stacks = [[]] * 5 stackThreshold = 4 currentStackSize = 0 def push(self, value): if self.currentStackSize == self.stackThreshold: self.amountOfStacks += 1 self.currentStackSize = 0 if not self.stacks[self.amountOfStacks - 1]: self.stacks[self.amountOfStacks - 1] = [] self.stacks[self.amountOfStacks - 1].append(value) self.currentStackSize += 1 def pop(self): if self.currentStackSize == 0: if self.amountOfStacks == 1: return False self.currentStackSize = self.stackThreshold self.amountOfStacks -= 1 self.currentStackSize -= 1 return self.stacks[self.amountOfStacks - 1].pop() def peek(self): if self.currentStackSize == 0: if self.amountOfStacks == 1: return False return self.stacks[self.amountOfStacks - 2] return self.stacks[self.amountOfStacks - 1] def isEmpty(self): return self.currentStackSize == 0 and self.amountOfStacks == 1 # Solution 2 if no buffer is allowed we could for each element create a runner pointer # That will go through the remaining elements looking for duplicates O(n^2) if __name__ == '__main__': stack = SetOfStacks() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) stack.push(6) stack.push(7) stack.push(8) stack.pop() stack.push(8) stack.push(9) stack.pop() print(stack.stacks)
9385f9e37bcc4abb06505978ca4a5fe7faa877b2
secretdsy/programmers
/level2/heap/42626__76.py
379
3.578125
4
def solution(scoville, K): answer = 0 while(1): scoville.sort(reverse=True) if(scoville[-1] > K): return answer elif(len(scoville) == 1): return -1 else: a=scoville.pop() b=scoville.pop() scoville.append(a + 2 * b) answer+=1 return -1 # 효율성 0
c6f2701eaa10b3a9fe4bfd43f7e71e04f25d6ce3
suneethreddy/Python-for-Everybody
/ch9ex3.py
421
3.984375
4
mail_count = dict() try: fname = input('Enter file name:') except: print('Enter a proper file!') exit() fhand = open(fname) for line in fhand: words = line.split() if len(words) < 3 or words[0] != 'From': continue else: if words[1] not in mail_count: mail_count[words[1]] = 1 else: mail_count[words[1]] += 1 print(mail_count)
afd27afaf1a78ea7136c93790d7d9737f94710b3
nitin-gera/PythonFileOperations
/WriteFile.py
565
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 27 09:58:12 2018 @author: nitingera """ #myfile = open("employees.txt", "r") #print(myfile.read()) #print(myfile.read(13)) #print(myfile.readline()) #print(myfile.readline()) #for line in myfile: # print("1:", line) writefile = open("names.txt", "a") name = "" listofnames = "" while(name != "XXX"): name = input("Enter your name:") if(name != "XXX"): listofnames += name listofnames += "\n" print("Saving:", listofnames) writefile.write(listofnames) writefile.close()
326d42cd0c426a198f5488de58ed7c4b903d448a
wesenu/MITx-6.00.2x-3
/UNIT 3/Lecture 9 - Sampling and Standard Error/Exercise_2.py
1,352
4.1875
4
#========== #Exercise 2 #========== #2/2 points (graded) #You are given the following partially completed function and a file julytemps.txt containing the daily maximum and minimum temperatures for each day in Boston for the 31 days of July 2012. In the loop, we need to make sure we ignore all lines that don't contain the relevant data. def loadFile(): inFile = open('julytemps.txt') high = [] low = [] for line in inFile: fields = line.split() # FILL THIS IN continue else: high.append(int(fields[1])) low.append(int(fields[2])) return (low, high) #Be sure that you have looked through the raw data file and that you understand which lines do and do not contain relevant data. Which set of conditions would capture all non-data lines (ie, provide a filter that would catch anything that wasn't relevant data)? fields is the variable that contains a list of elements in a line. if len(fields) < 3 or not fields[0].isdigit(): #Suppose you defined diffTemps = list(numpy.array(highTemps) - numpy.array(lowTemps)) to be a list which is the element-by-element difference between highTemps and lowTemps. Which is a valid plotting statement for a graph with days on the horizontal axis and the temperature difference on the vertical axis? pylab.plot(range(1,32), diffTemps)
0dd33f715d37a87c87201267d6b28a350aabeb56
cnagadya/bc_16_codelab
/Day_two/carclass_oop.py
1,268
3.640625
4
""" Car class to instatiate various vehicles""" class Car(object): #car properties def __init__(self, name = 'General' , model = 'GM' , car_type = 'saloon'): self.name = name self.model = model self.car_type = car_type #self.speed = 0 #speed initially 0, ie when parked self.speed = 0 #setting the doors no. if self.name == 'Porshe' or self.name == 'Koenigsegg': self.num_of_doors = 2 else: self.num_of_doors = 4 #setting the wheel no. if self.car_type == 'trailer': self.num_of_wheels = 8 else: self.num_of_wheels = 4 #for the saloon cars def is_saloon(self): if self.car_type != 'trailer': return True #speed when pedal is hit using def drive(self, drive_gear): if self.car_type == 'trailer': self.speed = 11*drive_gear else: self.speed = 10**drive_gear return self honda = Car(name ='Honda') toyota = Car(name ='Toyota', model = 'Corolla') opel = Car(name ='Opel', model = 'Omega 3') porshe = Car(name ='Porshe', model = '911 Turbo') koenigsegg = Car(name ='Koenigsegg', model = 'Agera R') print toyota.model print honda.model print honda.num_of_doors print porshe.num_of_doors
59f161798a650563af2839cffe45ffac321a176d
CppChan/Leetcode
/medium/mediumCode/LinkedList/RotateListbyKplaces.py
638
3.5625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def rotateKplace(self, head, n): dummy = ListNode(0) dummy.next = head cur = dummy size = 0 while cur.next: size+=1 cur = cur.next if size == 0 or size == 1 or n == 0: return dummy.next while n>size: n-=size if n == size: return dummy.next pre = size - n cur = dummy i = 0 while i < pre: cur = cur.next i+=1 post = cur.next cur.next = None newpre = dummy.next cur = post while cur.next: cur = cur.next cur.next = newpost return post
ac0cc8025151eabecaa5049a862b8c3bafeb7052
m-hawke/codeeval
/moderate/179_broken_lcd.py
868
3.59375
4
import sys # LCD segments for each digit with decimal point off segments = { '0': 0b11111100, '1': 0b01100000, '2': 0b11011010, '3': 0b11110010, '4': 0b01100110, '5': 0b10110110, '6': 0b10111110, '7': 0b11100000, '8': 0b11111110, '9': 0b11110110, } for line in sys.stdin: lcd_segments, number = line.strip().split(';') lcd_segments = [int(x, 2) for x in lcd_segments.split()] digits = [] for digit in number: if digit == '.': digits[-1] += 1 # turn on decimal point for preceding digit else: digits.append(segments[digit]) for i in range(len(lcd_segments)-len(digits)+1): if all(digit & lcd_segment == digit for digit, lcd_segment in zip(digits, lcd_segments[i:])): print(1) break else: print(0)
e341cd22b3248bb41f630d6be8925011be6009a2
vanshika1104/learning-python-codes
/conversion to alt upper.py
204
3.96875
4
word = input("Enter a word: ") print("ORIGINAL:",word) output='' for x in range(0, len(word)): if(x%2==0): output+=word[x].upper() else: output+=word[x] print("New value:",output)
57af116d0ec729b98500dfaeb199e9d038a71005
Sasha1152/Training
/power_of_power.py
496
3.75
4
import time def power_of(power): cache = {} def hidden(x): start = time.time() if x in cache: print('Using cached data {} sec'.format(round(time.time() - start, 3))) return cache[x] else: cache[x] = x**power**power print('Calculating power of...{} sec'.format(round(time.time() - start, 3))) return cache[x] return hidden p7 = power_of(7) p7(2) p7(2) p7(4) p7(4) p7(6) p7(6) p7(36) p7(36)
eebc8f8adb69daba5bd5c9432a6e68f68489da1a
NarcissusLJY/store-for-lulu
/Python_78/lesson_03作业.py
3,593
3.625
4
# # 1.a=[1,2,'6','summer'] 请用成员运算符判断 i是否在这个列表里面 -- if # a = [1,2,'6','summer'] # if "i" in a: # print(True) # else: # print(False) # # 2.dict_1={"class_id":45,'num':20} 请判断班级上课人数是否大于5,注:num表示课堂人数。如果大于5,输出人数。 # dict_1 = {"class_id": 45,'num': 20} # a = dict_1['num'] # if a>5: # print("上课人数为:{}".format(a)) # else: # print("上课人数不足5人") ''' 3. list1 = ['肥兔', '鹿鹿', 'Freestyle', '等', '地球', '阑珊', '柠檬'],列表当中的每一个值包含:姓名、性别、年龄、城市。以字典的形式表达。并且把字典都存在新的 list中,最后打印最终的列表。 方法1: 手动扩充--字典--存放在列表里面;{} --简单 方法2: 自动--dict()--不强制-- for循环 ,list.append() ''' # 方法1 # list1 = ['肥兔', '鹿鹿', 'Freestyle', '等', '地球', '阑珊', '柠檬'] # dict1 = {"name":"肥兔","gender":"male","age":18,"city":"天津"} # dict2 = {"name":"鹿鹿","gender":"female","age":18,"city":"江苏"} # dict3 = {"name":"Freestyle","gender":"male","age":18,"city":"杭州"} # dict4 = {"name":"等","gender":"male","age":18,"city":"广东"} # dict5 = {"name":"地球","gender":"male","age":18,"city":"深圳"} # dict6 = {"name":"阑珊","gender":"female","age":18,"city":"湖南"} # dict7 = {"name":"柠檬","gender":"female","age":18,"city":"广西"} # list2 = [dict1,dict2,dict3,dict4,dict5,dict6,dict7] # print(list2) # 方法2-1 # list1 = ['肥兔', '鹿鹿', 'Freestyle', '等', '地球', '阑珊', '柠檬'] # dict1 = dict(name="肥兔",gender="male",age=18,city="天津") # dict2 = dict(name="鹿鹿",gender="female",age=18,city="江苏") # dict3 = dict(name="Freestyle",gender="male",age=18,city="杭州") # dict4 = dict(name="等",gender="male",age=18,city="广东") # dict5 = dict(name="地球",gender="male",age=18,city="深圳") # dict6 = dict(name="阑珊",gender="female",age=18,city="湖南") # dict7 = dict(name="柠檬",gender="female",age=18,city="广西") # list2 = [] # for name in list1: # if name == dict1['name']: # list2.append(dict1) # elif name == dict2['name']: # list2.append(dict2) # elif name == dict3['name']: # list2.append(dict3) # elif name == dict4['name']: # list2.append(dict4) # elif name == dict5['name']: # list2.append(dict5) # elif name == dict6['name']: # list2.append(dict6) # else: # list2.append(dict7) # print(list2) # 方法2-2 # list1 = ['肥兔', '鹿鹿', 'Freestyle', '等', '地球', '阑珊', '柠檬'] # list2 = [] # for i in list1: # dict1 = dict(name=i, gender="male", age=18, city="天津") # list2.append(dict1) # print(list2) # 方法2-3 # list1 = ['肥兔', '鹿鹿', 'Freestyle', '等', '地球', '阑珊', '柠檬'] # list2 = ['male','female','male','male','male','female','female'] # list3 = ['18','18','18','18','18','18','18'] # list4 = ['天津','江苏','杭州','广东','深圳','湖南','广西'] # list5 = [] # for i in range(7): # dict1 = dict(name=list1[i],gender=list2[i],age=list3[i],city=list4[i]) # list5.append(dict1) # print(list5) # # 4.for循环遍历其他的数据类型 --字典 # b = {"name":"鹿鹿","age":18,"gender":"female","city":"江苏","score":[100,99,98]} # for key,value in b.items(): # print("{}:{}".format(key,value)) # # 4.for循环遍历其他的数据类型 --元组 # tuple1 = ("hello","world",123,["happy","new","year"]) # for elem in tuple1: # print(elem)
bb46d092bf4c4ccfbacbb723a183fef84906e02b
DukMastaaa/KTANE
/Modules/MorseCode.py
9,004
3.703125
4
"""Morse Code Module.""" import tkinter as tk import random import BaseModule import const MORSE_WORDS = {'shell': 3.505, 'halls': 3.515, 'slick': 3.522, 'trick': 3.532, 'boxes': 3.535, 'leaks': 3.542, 'strobe': 3.545, 'bistro': 3.552, 'flick': 3.555, 'bombs': 3.565, 'break': 3.572, 'brick': 3.575, 'steak': 3.582, 'sting': 3.592, 'vector': 3.595, 'beats': 3.6} class MorseCodeTranslator(object): ALPHA_TO_MORSE = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--.." } @staticmethod def encode(plaintext: str) -> str: """Encodes plaintext into morse. In the ciphertext, there is one space between each character and two spaces between each word of the plaintext. Use str.strip(" ") to obtain each plaintext character. Spaces between each plaintext word will show as an empty string literal. """ plaintext = plaintext.strip() ciphertext_list = [] for char in plaintext: if char.isalpha(): ciphertext_list.append(MorseCodeTranslator.ALPHA_TO_MORSE[char.upper()]) elif char == " ": ciphertext_list.append("") return " ".join(ciphertext_list) class MorseCodeModel(BaseModule.ModuleModel): def __init__(self, controller: "MorseCodeController"): super().__init__(controller) self._word = "" self._solution = 0 self._morse = "" self.init_morse_code() self.calc_solution() def init_morse_code(self) -> None: self._word = random.choice(list(MORSE_WORDS)) self._morse = MorseCodeTranslator.encode(self._word) def get_morse_code_data(self) -> str: return self._morse def calc_solution(self) -> None: self._solution = MORSE_WORDS[self._word] def check_solution(self, index: int) -> None: """Checks whether the index of the word in `MORSE_WORDS` is correct.""" if MORSE_WORDS[list(MORSE_WORDS)[index]] == self._solution: self.controller.make_solved() else: self.controller.add_strike() class MorseCodeView(BaseModule.ModuleView): DIT_DURATION = 200 DAH_MULTIPLIER = 3 SIGNAL_END_MULTIPLIER = 1 CHAR_END_MULTIPLIER = 3 WORD_END_MULTIPLIER = 7 LIGHT_TOP_X = 20 LIGHT_TOP_Y = 30 LIGHT_WIDTH = 40 LIGHT_HEIGHT = 30 L_ARROW_TOP_X = 20 L_ARROW_TOP_Y = 90 L_ARROW_WIDTH = 30 L_ARROW_HEIGHT = 40 # geometry yucky L_ARROW_BEND_COORD = (L_ARROW_TOP_X, L_ARROW_TOP_Y + L_ARROW_HEIGHT / 2) L_ARROW_TOP_COORD = (L_ARROW_TOP_X + L_ARROW_WIDTH, L_ARROW_TOP_Y) L_ARROW_BOTTOM_COORD = (L_ARROW_TOP_X + L_ARROW_WIDTH, L_ARROW_TOP_Y + L_ARROW_HEIGHT) L_ARROW_COORDS = (*L_ARROW_BEND_COORD, *L_ARROW_TOP_COORD, *L_ARROW_BOTTOM_COORD) R_ARROW_BEND_COORD = (const.MODULE_WIDTH - L_ARROW_TOP_X, L_ARROW_TOP_Y + L_ARROW_HEIGHT / 2) R_ARROW_TOP_COORD = (const.MODULE_WIDTH - L_ARROW_TOP_X - L_ARROW_WIDTH, L_ARROW_TOP_Y) R_ARROW_BOTTOM_COORD = (const.MODULE_WIDTH - L_ARROW_TOP_X - L_ARROW_WIDTH, L_ARROW_TOP_Y + L_ARROW_HEIGHT) R_ARROW_COORDS = (*R_ARROW_BEND_COORD, *R_ARROW_TOP_COORD, *R_ARROW_BOTTOM_COORD) FREQ_RECT_GAP = 5 FREQ_RECT_TOP_X = L_ARROW_TOP_X + L_ARROW_WIDTH + FREQ_RECT_GAP FREQ_RECT_TOP_Y = L_ARROW_TOP_Y FREQ_RECT_BOTTOM_X = R_ARROW_TOP_COORD[0] - FREQ_RECT_GAP FREQ_RECT_BOTTOM_Y = L_ARROW_TOP_Y + L_ARROW_HEIGHT FREQ_TEXT_X = (FREQ_RECT_TOP_X + FREQ_RECT_BOTTOM_X) / 2 FREQ_TEXT_Y = (FREQ_RECT_TOP_Y + FREQ_RECT_BOTTOM_Y) / 2 FREQ_TEXT_FONT = ("Courier", 20) TX_WIDTH = 50 TX_HEIGHT = 30 TX_TOP_X = const.MODULE_WIDTH / 2 - TX_WIDTH / 2 TX_TOP_Y = const.MODULE_HEIGHT - TX_HEIGHT - 20 TX_TEXT_X = TX_TOP_X + TX_WIDTH / 2 TX_TEXT_Y = TX_TOP_Y + TX_HEIGHT / 2 TX_TEXT_FONT = ("Courier", 20) def __init__(self, bomb_view, controller: "MorseCodeController"): super().__init__(bomb_view, controller) self._morse = "" self._flash_schedule = [] self._freq_index = 0 self._light_id = 0 self._freq_text_id = 0 def attach_morse_code(self, morse: str): self._morse = morse self.calculate_flash_schedule() self.draw_morse_code() def calculate_flash_schedule(self) -> None: """Calculates a "schedule" of flashes and the time duration after the initial flash. The flash schedule will be a list of tuples where the first element is bool, indicating whether the light is on or off. The second element indicates the time in ms after the first initial flash. """ chars = self._morse.split() time_counter = 0 for char in chars: for signal in char: self._flash_schedule.append((True, time_counter)) if signal == ".": time_counter += self.DIT_DURATION elif signal == "-": time_counter += self.DIT_DURATION * self.DAH_MULTIPLIER self._flash_schedule.append((False, time_counter)) time_counter += self.DIT_DURATION * self.SIGNAL_END_MULTIPLIER time_counter += self.DIT_DURATION * self.CHAR_END_MULTIPLIER time_counter += self.DIT_DURATION * self.WORD_END_MULTIPLIER self._flash_schedule.append((False, time_counter)) def draw_morse_code(self) -> None: self._light_id = self.create_rectangle( self.LIGHT_TOP_X, self.LIGHT_TOP_Y, self.LIGHT_TOP_X + self.LIGHT_WIDTH, self.LIGHT_TOP_Y + self.LIGHT_HEIGHT, fill=const.COL_BLACK, outline=const.COL_BLACK ) left_id = self.create_polygon( *self.L_ARROW_COORDS, fill="light gray", outline=const.COL_BLACK ) right_id = self.create_polygon( *self.R_ARROW_COORDS, fill="light gray", outline=const.COL_BLACK ) self.create_rectangle( # freq rect self.FREQ_RECT_TOP_X, self.FREQ_RECT_TOP_Y, self.FREQ_RECT_BOTTOM_X, self.FREQ_RECT_BOTTOM_Y, fill=const.COL_BLACK ) self._freq_text_id = self.create_text( self.FREQ_TEXT_X, self.FREQ_TEXT_Y, text=list(MORSE_WORDS.values())[self._freq_index], font=self.FREQ_TEXT_FONT, fill=const.COL_WHITE ) tx_rect_id = self.create_rectangle( self.TX_TOP_X, self.TX_TOP_Y, self.TX_TOP_X + self.TX_WIDTH, self.TX_TOP_Y + self.TX_HEIGHT, fill="light gray", outline=const.COL_BLACK ) tx_text_id = self.create_text( self.TX_TEXT_X, self.TX_TEXT_Y, text="TX", font=self.TX_TEXT_FONT ) self.tag_bind(left_id, const.BIND_LEFT_PRESS, lambda event: self.arrow_press(False)) self.tag_bind(right_id, const.BIND_LEFT_PRESS, lambda event: self.arrow_press(True)) self.tag_bind(tx_rect_id, const.BIND_LEFT_PRESS, lambda event: self.tx_press()) self.tag_bind(tx_text_id, const.BIND_LEFT_PRESS, lambda event: self.tx_press()) self._restart_schedule() def arrow_press(self, right_side: bool) -> None: if right_side: if self._freq_index < len(MORSE_WORDS) - 1: self._freq_index += 1 else: if self._freq_index > 0: self._freq_index -= 1 self.itemconfigure(self._freq_text_id, text=list(MORSE_WORDS.values())[self._freq_index]) def tx_press(self) -> None: self.controller.check_solution(self._freq_index) def _restart_schedule(self) -> None: for light_state, time in self._flash_schedule: self.after(time, self._control_light, light_state) self.after(self._flash_schedule[-1][1], self._restart_schedule) def _control_light(self, state: bool) -> None: self.itemconfigure(self._light_id, fill=(const.COL_YELLOW if state else "light gray")) class MorseCodeController(BaseModule.ModuleController): model_class = MorseCodeModel view_class = MorseCodeView def __init__(self, bomb_reference, parent_reference: tk.Frame): super().__init__(bomb_reference, parent_reference) self.view.attach_morse_code(self.model.get_morse_code_data()) def check_solution(self, index: int) -> None: self.model.check_solution(index)
92fe902c7403152dd7247fb26d6e9a1b24e07a67
epacuit/ppe-simulations
/_build/jupyter_execute/game-theory/02a-intro-game-theory.py
14,835
3.859375
4
# Introduction to Game Theory A *game* refers to any interactive situation involving a group of "self-interested" agents, or players. The defining feature of a game is that the players are engaged in an "interdependent decision problem". **Reading** 1. M. Osborne, [Nash Equilibrium: Theory](https://umd.instructure.com/courses/1301051/files/61184686?module_item_id=10560654), Chapter from [*Introduction to Game Theory*](https://www.economics.utoronto.ca/osborne/igt/index.html), Oxford University Press, 2002. 2. D. Ross, [Game Theory](https://plato.stanford.edu/entries/game-theory/), Stanford Encyclopedia of Philosophy, 2019. 3. E. Pacuit and O. Roy, [Epistemic Foundations of Game Theory](https://plato.stanford.edu/entries/epistemic-game/), Stanford Encyclopedia of Philosophy, 2012. # make graphs look nice import seaborn as sns sns.set() The mathematical description of a game includes at least the following components: 1. The *players*. In this entry, we only consider games with finitely many players. We use $N$ to denote the set of players in a game. 2. For each player $i\in N$, a finite set of *feasible* options (typically called *actions* or *strategies*). 3. For each player $i\in N$, a *preference* over the possible outcomes of the game. The standard approach in game theory is to represent each player's preference as a (von Neumann-Morgenstern) utility function that assigns a real number to each outcome of the game. A game may represent other features of the strategic situation. For instance, some games represent multi-stage decision problems which may include simultaneous or stochastic moves. For simplicity, we start with games that involve players making a single decision simultaneously without stochastic moves. A **game in strategic form** is a tuple $\langle N, (S_i)_{i\in N}, (u_i)_{i\in N}\rangle$ where: 1. $N$ is a finite non-empty set 2. For each $i\in N$, $S_i$ is a finite non-empty set 3. For each $i\in N$, $u_i:\times_iS_i \rightarrow\mathbb{R}$ is player $i$'s utility. The elements of $\times_{i\in N} S_i$ are the outcomes of the game and are called **strategy profiles**. In most games, no single player has total control over which outcome will be realized at the end of the interaction. The outcome of a game depends on the decisions of <em>all players</em>. The central analytic tool of classical game theory are **solution concepts**. A solution concept associates a set of outcomes (i.e., a set of strategy profiles) with each game (from some fixed class of games). From a prescriptive point of view, a solution concept is a recommendation about what the players should do in a game, or about what outcomes can be expected assuming that the players choose *rationally*. From a predictive point of view, solution concepts describe what the players will actually do in a game. ## Nash Equilibrium Let $G=\langle N, (S_i)_{i\in N}, (u_i)_{i\in N}\rangle$ be a finite strategic game (each $S_i$ is finite and the set of players $N$ is finite). A **strategy profile** is an element $\times_{i\in N} S_i$ Given a strategy profile $\sigma\in \times_{i\in N}S_i$, $\sigma_{-i}$ is an element of $$ S_1\times S_2\times\cdots S_{i-1}\times S_{i+1}\times \cdots S_n$$ A strategy profiel $\sigma$ is a **pure strategy Nash equilibrium** provided that for all $i\in N$, for all $a\in S_i$, $$u_i(\sigma) \ge u_i(a, \sigma_{-i})$$ ## Pure Coordination Game | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(1, 1)$ | $(0, 0)$| |$S2$ |$(0, 0)$ | $(1, 1)$| There are two pure strategy Nash equilibria: $(S1, S1)$ and $(S2, S2)$ > The basic intellectual premise, or working hypothesis, for rational players in this game seems to be the premise that some rule must be used if success is to exceed coincidence, and that the best rule to be found, whatever its rationalization, is consequently a rational rule. (T. Schelling, *The Strategy of Conflict*, pg. 283) ## Hi-Lo Game | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(3, 3)$ | $(0, 0)$| |$S2$ |$(0, 0)$ | $(1, 1)$| There are two pure strategy Nash equilibria: $(S1, S1)$ and $(S2, S2)$ > There are these two broad empirical facts about Hi-Lo games, people almost always choose [$S1$] and people with common knowledge of each other's rationality think it is obviously rational to choose [$S1$]." (M. Bacharach, *Beyond Individual Choice*, p. 42) ## Matching Pennies | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(1, -1)$ | $(-1, 1)$| |$S2$ |$(-1, 1)$ | $(1, -1)$| There are no pure strategy Nash equilibria. A **mixed strategy** for player $i$ in a finite game $\langle N, (S_i)_{i\in N}, (u_i)_{i\in N}\rangle$ is a lottery on $S_i$, i.e., a probability over player $i$'s strategies. ![mixed-strat.jpg](mixed-strat.jpg) The utilities for a mixed strategy profile $(p, q)$ is: $$\mbox{Row}: p(1-q) -pq - (1-p)(1-q) + (1-p)q$$ $$\mbox{Col}: -p(1-q) +pq + (1-p)(1-q) - (1-p)q)$$ > We are reluctant to believe that our decisions are made at random. We prefer to be able to point to a reason for each action we take. Outside of Las Vegas we do not spin roulettes. (A. Rubinstein, Comments on the Interpretation of Game Theory, Econometrica 59, 909 - 924, 1991) What does it mean to play a mixed strategy? * Randomize to confuse your opponent (e.g., matching pennies games) * Players randomize when they are uncertain about the other’s action (e.g., battle of the sexes game) * Mixed strategies are a concise description of what might happen in repeated play * Mixed strategies describe population dynamics: After selecting 2 agents from a population, a mixed strategy is the probability of getting an agent who will play one pure strategy or another. | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(1, -1)$ | $(-1, 1)$| |$S2$ |$(-1, 1)$ | $(1, -1)$| There is one mixed strategy Nash equilibria: $((1/2: S1, 1/2: S2), (1/2:S1, 1/2:S2))$. ## Battle of the Sexes | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(2, 1)$ | $(0, 0)$| |$S2$ |$(0, 0)$ | $(1, 2)$| There are two pure strategy Nash equilibrium $(S1, S1)$ and $(S2, S2)$ (and one mixed strategy Nash equilibrium). ## Stag Hunt | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(3, 3)$ | $(0, 2)$| |$S2$ |$(2, 0)$ | $(1, 1)$| There are two pure strategy Nash equilibrium $(S1, S1)$ and $(S2, S2)$. While $(S1, S1)$ Pareto dominates $(S1, S1)$, but $(S2, S2)$ is 'less risky'. > The problem of instituting, or improving, the social contract can be thought of as the problem of moving from riskless hunt hare equilibrium to the risky but rewarding stag hunt equilibrium. (B. Skyrms, *Stag Hunt and the Evolution of Social Structure*, p. 9) ## Prisoner's Dilemma | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(3, 3)$ | $(0, 4)$| |$S2$ |$(4, 0)$ | $(1, 1)$| There is one Nash equilibrium $(S2, S2)$. The non-equilibrium $(S1, S1)$ Pareto-dominates $(S2, S2)$. > Game theorists think it just plain wrong to claim that the Prisoners' Dilemma embodies the essence of the problem of human cooperation. On the contrary, it represents a situation in which the dice are as loaded against the emergence of cooperation as they could possibly be. If the great game of life played by the human species were the Prisoner's Dilemma, we wouldn't have evolved as social animals!....No paradox of rationality exists. Rational players don't cooperate in the Prisoners' Dilemma, because the conditions necessary for rational cooperation are absent in this game. (K. Binmore, *Natural Justice*, p. 63) ## Game Theory in Python * Gambit - [https://gambitproject.readthedocs.io/en/latest/index.html](https://gambitproject.readthedocs.io/en/latest/index.html): a library of game theory software and tools for the construction and analysis of finite extensive and strategic games. * Nashpy - [https://nashpy.readthedocs.io/en/latest/](https://nashpy.readthedocs.io/en/latest/): a simple library used for the computation of equilibria in 2 player strategic form games. * Axelrod - [https://axelrod.readthedocs.io/en/stable/index.html](https://axelrod.readthedocs.io/en/stable/index.html): a library to study iterated prisoner's dilemma. ### Nashpy import nashpy as nash import numpy as np # Coordination Game A = np.array([[1, 0], [0, 1]]) B = np.array([[1, 0], [0, 1]]) coord = nash.Game(A, B) print(coord) print([1,2]) print(np.array([1,2])) sigma1_r = [1, 0] sigma1_c = [0, 1] print("The utilities are ", coord[sigma1_r, sigma1_c]) sigma2_r = [1 / 2, 1 / 2] sigma2_c = [1 / 2, 1 / 2] print("The utilities are ", coord[sigma2_r, sigma2_c]) eqs = coord.support_enumeration() print("The Nash equilibria are:") for ne in eqs: print("\t", ne) # Hi-Lo A = np.array([[3, 0], [0, 1]]) B = np.array([[3, 0], [0, 1]]) hilo = nash.Game(A, B) eqs = hilo.support_enumeration() print("The Nash equilibria for Hi-Lo are:") for ne in eqs: print("\t", ne) # Battle of the Sexes A = np.array([[2, 0], [0, 1]]) B = np.array([[1, 0], [0, 2]]) bos = nash.Game(A, B) eqs = bos.support_enumeration() print("The Nash equilibria for Battle of the Sexes are:") for ne in eqs: print("\t", ne) # Stag Hunt A = np.array([[3, 0], [2, 1]]) B = np.array([[3, 2], [0, 1]]) sh = nash.Game(A, B) eqs = sh.support_enumeration() print("The Nash equilibria for the Stag Hunt are:") for ne in eqs: print("\t", ne) # Prisoner's Dilemma A = np.array([[3, 0], [4, 1]]) B = np.array([[3, 4], [0, 1]]) pd = nash.Game(A, B) eqs = pd.support_enumeration() print("The Nash equilibria for the Prisoner's Dilemma are:") for ne in eqs: print("\t", ne) ### Axelrod [Axelrod](https://axelrod.readthedocs.io/en/stable/index.html) is a Python package to study repeated play of the Prisoner's Dilemma: | &nbsp; |$S1$ | $S2$ | |----|----|----| |$S1$ |$(3, 3)$ | $(0, 4)$| |$S2$ |$(4, 0)$ | $(1, 1)$| There are different ways to repeat play of PD: 1. Two players repeatedly playing a PD 2. Multiple players repeatedly playing PD against each other 3. Multiple players repeatedly playing PD against their neighbors #### Running a Match In a Match, two player repeatedly play a PD. import axelrod as axl players = (axl.Cooperator(), axl.Alternator()) match = axl.Match(players, 5) print("Match Play: ", match.play()) print("Match Scores: ", match.scores()) print("Final Scores: ", match.final_score()) print("Final Scores Per Turn: ", match.final_score_per_turn()) print("Winner: ", match.winner()) print("Cooperation: ", match.cooperation()) print("Normalized Coperation: ", match.normalised_cooperation()) players = (axl.Cooperator(), axl.Random()) match = axl.Match(players=players, turns=10, noise=0.0) match.play() print("Match Scores: ", match.scores()) print("Final Scores: ", match.final_score()) print("Final Scores Per Turn: ", match.final_score_per_turn()) print("Winner: ", match.winner()) print("Cooperation: ", match.cooperation()) print("Normalized Coperation: ", match.normalised_cooperation()) #### Running a Tournament In a tournament, each player plays every other player. import pprint players = [axl.Cooperator(), axl.Defector(), axl.TitForTat(), axl.Grudger()] tournament = axl.Tournament(players) results = tournament.play(progress_bar=False) print("Ranked players: ", results.ranked_names) print("Normalized Scores: ", results.normalised_scores ) print("Wins: ", results.wins) print("payoff matrix") pprint.pprint(results.payoff_matrix); plot = axl.Plot(results) plot.boxplot(); plot.winplot(); players = [axl.Cooperator(), axl.Defector(), axl.TitForTat(), axl.Grudger(), axl.Random()] tournament = axl.Tournament(players) results = tournament.play(progress_bar=False) print(results.ranked_names) plot = axl.Plot(results) plot.boxplot(); p = plot.winplot() plot.payoff(); #### Axelrod's Tournament In 1980, Robert Axelrod (a political scientist) invited submissions to a computer tournament version of an iterated prisoners dilemma (["Effective Choice in the Prisoner's Dilemma"](http://journals.sagepub.com/doi/abs/10.1177/002200278002400101)). - 15 strategies submitted. - Round robin tournament with 200 stages including a 16th player who played randomly. - The winner (average score) was in fact a very simple strategy: Tit For Tat. This strategy starts by cooperating and then repeats the opponents previous move. The fact that Tit For Tat won garnered a lot of (still ongoing) research. For an overview o of how to use axelrod to reproduce this first tournament, see [http://axelrod.readthedocs.io/en/stable/reference/overview_of_strategies.html#axelrod-s-first-tournament](http://axelrod.readthedocs.io/en/stable/reference/overview_of_strategies.html#axelrod-s-first-tournament). axelrod_first_tournament = [s() for s in axl.axelrod_first_strategies] number_of_strategies = len(axelrod_first_tournament) for player in axelrod_first_tournament: print(player) tournament = axl.Tournament( players=axelrod_first_tournament, turns=200, repetitions=5, ) results = tournament.play(progress_bar=False) for name in results.ranked_names: print(name) plot = axl.Plot(results) plot.boxplot(); There are over 200 strategies implemented in axelrod (see [https://axelrod.readthedocs.io/en/stable/reference/all_strategies.html](https://axelrod.readthedocs.io/en/stable/reference/all_strategies.html)). Including some recent strategies that have done quite well in tournaments: Press, William H. and Freeman J. Dyson (2012), [Iterated prisoner’s dilemma contains strategies that dominate any evolutionary opponent](https://www.pnas.org/content/109/26/10409). Proceedings of the National Academy of Sciences, 109, 10409–10413. players = [ axl.ZDExtort2(), axl.ZDSet2(), axl.TitForTat()] tournament = axl.Tournament( players=players, turns=200, repetitions=5, ) results = tournament.play(progress_bar=False) for name in results.ranked_names: print(name) #### Moran Process Given an initial population of players, the population is iterated in rounds consisting of: 1. matches played between each pair of players, with the cumulative total scores recorded. 2. a player is chosen to reproduce proportional to the player’s score in the round. 3. a player is chosen at random to be replaced. players = [axl.Cooperator(), axl.Cooperator(),axl.Cooperator(),axl.Cooperator(), axl.Cooperator(), axl.Cooperator(), axl.Defector(), axl.Random()] mp = axl.MoranProcess(players, turns=100) mp.play() print("Winning strategy: ", mp.winning_strategy_name) mp.populations_plot(); #### Moran Process with Mutation players = [axl.Cooperator(), axl.Defector(), axl.TitForTat(), axl.Grudger()] mp = axl.MoranProcess(players, turns=100, mutation_rate=0.1) for _ in mp: if len(mp.population_distribution()) == 1: break mp.populations_plot();
9d407283653686298784f56409754415fb5d752d
chetana0410/Mini-Projects
/weather-App/weather.py
968
3.5
4
import requests, json city = input('Enter your city: ') url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=3265874a2c77ae4a04bb96236a642d2f" temp_f = requests.get(url).json() print(f''' Temperature: {round(temp_f['main']['temp']-273)}, longitude: {temp_f['coord']['lon']}, latitude: {temp_f['coord']['lat']}, description: {temp_f['weather'][0]['description']}, feels_like: {round(temp_f['main']['feels_like']-273)}, temp_min: {round(temp_f['main']['temp_min']-273)}, temp_max: {round(temp_f['main']['temp_max']-273)}, pressure: {temp_f['main']['pressure']}, humidity: {temp_f['main']['humidity']}, wind: {temp_f['wind']}, country: {temp_f['sys']['country']}, sunrise: {temp_f['sys']['sunrise']}, sunset: {temp_f['sys']['sunset']}, timezone: {temp_f['timezone']} ''')
bfe3e9e47bcb46c1a64acf01a889621046014d13
cuber-it/aktueller-kurs
/Tag8/sql_alchemy_basics.py
636
3.6875
4
from sqlalchemy import create_engine, Table, MetaData, select # Create an engine that connects to the sqlite database engine = create_engine('sqlite:///example.db') metadata = MetaData() # define the table stocks = Table('stocks', metadata, autoload_with=engine) # Start a new connection with engine.connect() as connection: # Insert a new row connection.execute(stocks.insert().values(date='2006-01-05', trans='BUY', symbol='RHAT', qty=100, price=35.14)) # Execute a select statement s = select(stocks).where(stocks.c.symbol == 'RHAT') result = connection.execute(s) for row in result: print(row)
756d5e3bbbbe8ff8738b284505a0f24494b34c8e
yavuzselimhanaksahin/tensorlayer_example
/ch_1/basics/static_mlp_perceptron.py
793
3.984375
4
import tensorflow as tf from tensorlayer.layers import Input, Dense from tensorlayer.models import Model # a multilayer perceptron (MLP) model with three dense layers def get_mlp_model(inputs_shape): ni = Input(inputs_shape) # since the connection between layers is explicitly defined # in_channels of each layer is automatically inferred nn = Dense(n_units=800, act=tf.nn.relu)(ni) nn = Dense(n_units=800, act=tf.nn.relu)(nn) nn = Dense(n_units=10, act=tf.nn.relu)(nn) # automatic build a model based on the connection between M = Model(inputs=ni, outputs=nn) return M MLP = get_mlp_model([None, 784]) # switch to evaluation mode MLP.eval() # ingest data into the model # the computation can be accelerated by using @tf.function in outputs = MLP(data)
412467f5c10925760d068144ce1e7c83cd7b0ede
nestorghh/coding_interview
/cracking/string_compression.py
335
3.5625
4
#string compression @cracking the coding interview. # this is not what is beaing asked. from collections import Counter def string_compression2(st): cs='' cnt = Counter() for c in st: cnt[c]+=1 for k in cnt.keys(): cs = cs+str(k)+str(cnt[k]) return cs print(string_compression('aabccccaaa'))
050f8efb95ed2c8100fdcd94b524b0cd741e3a8d
DanielBrito/ufc
/Monitoria - Fundamentos de Programação/Lista 5 - Ítalo/exe26.py
688
4.03125
4
# Lista 4 (Ítalo) - Questao 26 import random cartao = [] for _ in range(6): n = int(input("Digite um número: ")) cartao.append(n) sorteados = [] terminado = False while not terminado: valor = random.randint(0, 10) if valor not in sorteados: sorteados.append(valor) if len(sorteados)==6: terminado = True acertos = set(cartao).intersection(sorteados) print("") print("Acertos:", acertos) print("") print("Números sorteados:", sorteados) print("") if len(acertos)<=3: print("Sem premiacão") elif len(acertos)==4: print("Quadra") elif len(acertos)==5: print("Quina") else: print("Sena")
87fccd77226f67ba5cd45becf25fa98ccdc14894
wyattlaprise/random_number
/random_number.py
272
4
4
import random try: min = int(input('Low number = ')) max = int(input('High number = ')) rand_num = random.randint(min, max) print('A random number between {0} and {1} is: {2}'.format(min, max, rand_num)) except: print('Sorry, something went wrong')
c8040b6e88ce28afe4656625dfed2a3a26450090
shreyaxh/Recursion-for-newbs
/Program to Display calender.py
135
4.21875
4
#to display calendar for entire year from calendar import calendar year = int(input('Enter year :')) print(calendar(year, 2, 1, 8, 3))
d74d89f91396c46b53305e2b6544240f6e259a1d
alok8899/colab_python
/python054ds.py
501
3.96875
4
#! python3 from os import system import random from itertools import combinations system("cls") naturalnolist=[1,2,3,4,5,6,7,8,9] print("the original string given for analysis is ",list(naturalnolist)) random.shuffle(naturalnolist) print("the random shuffle list for amalysis ",list(naturalnolist)) pickupelement=int(input("please enter the number of element to pickup ")) generatedcombi=combinations(naturalnolist,pickupelement) print(list(generatedcombi))
b3a02d4c8a679cdbbffc9dce4542ad10ee5e3bcc
mbick315/advent-of-code-2020
/day6/part1.py
1,394
3.796875
4
def calc_number_questions_answered(num_people, group_set, all_answered_yes): if all_answered_yes: return len(dict(filter(lambda elem: elem[1] == num_people, group_set.items()))) else: return len(group_set) def process_questions_and_return_total_count(all_answered_yes): with open('input.txt', 'r') as reader: total_count = 0 group_set = {} num_people = 0 for line in reader: split_spaces = line.split() if len(split_spaces) == 0: number_questions_answered = calc_number_questions_answered(num_people, group_set, all_answered_yes) total_count += number_questions_answered num_people = 0 group_set = {} continue num_people += 1 for char in line: if char.isspace(): continue if char in group_set: group_set[char] = group_set[char] + 1 else: group_set[char] = 1 total_count += calc_number_questions_answered(num_people, group_set, all_answered_yes) return total_count print("Total count: {}".format(process_questions_and_return_total_count(all_answered_yes=False))) print("Total count where all answered yes: {}".format(process_questions_and_return_total_count(all_answered_yes=True)))
f79b047d9fb40c66196ca15a7a04e9573ec296e1
weiguangjiayou/LeetCode
/LeetCode/LeetCode541reverse-string-ii.py
687
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/12/26 4:47 PM # @Author : Slade # @File : LeetCode541reverse-string-ii.py class Solution: def reverseStr(self, s: str, k: int) -> str: def reverseSingle(s, k): if len(s) >= k: return s[:k][::-1] + s[k:] else: return s[:k][::-1] return reverseSingle(s[:2 * k], k) + self.reverseStr(s[2 * k:], k) if s[2 * k:] else reverseSingle(s[:2 * k], k) + "" if __name__ == '__main__': s = Solution() print(s.reverseStr("abcdefg", 8))
d9b1cdbe8a2fd88d4be93b17dc56c2af1fba12bd
RPMeyer/intro-to-python
/Intro to Python/Project/testProject2.py
4,059
4.03125
4
#YOUTUBE VIDEO of powerpoint: https://youtu.be/DhLMyyw6-X8 import turtle testTurt = turtle.Turtle() testTurt.speed(1) wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("wnInfo") testTurt.penup() turtle.tracer(0,0) def createPolys(poly1,poly2,poly3,poly4,color1,color2): '''Registers a new shape that replaces the turtle out of poly1 through poly4. Applies colors c1 and c2 to the specified polys''' s = turtle.Shape("compound") s.addcomponent(poly1, color1) s.addcomponent(poly2, color2) s.addcomponent(poly3, color1) s.addcomponent(poly4, color2) wn.register_shape("myshape", s) #registers the user created shape to later be used as the turtle #thus allowing the stamp methods to create the pattern def stampShape(color1='blue',color2='red'): '''creates shape for stamp, and stamps''' createPolys(poly1,poly2,poly3,poly4,color1,color2) turn=90 #rotates the turtle 4 times in a circle to create the simple shape of the pattern - specified via createPolys for i in range(0,4,1): testTurt.shape("myshape") testTurt.seth(turn) testTurt.stamp() turn+= 90 def createSquare(magVal, color1='blue', color2='red'): '''creates the square that composes the desired pattern. The pattern is the turtle shape repeated 4 times, then repeating that 4 more times''' shapeSize=61*magVal for n in range(0,4,1): for i in range(0,4,1): stampShape(color1,color2) testTurt.forward(shapeSize) testTurt.forward(-4*shapeSize) testTurt.left(90) testTurt.forward(shapeSize) testTurt.right(90) return testTurt.pos() #used for debugging - not entirely necessary in current code factor def swapColors(color1,color2,colorHolder=''): '''uses colorHolder variable to effectively swap color1 and color2, then returns color1 and color2''' colorHolder=color1 color1=color2 color2=colorHolder return color1,color2 def createPattern(magVal,color1,color2, times): '''creates a pattern of createSquare() as a (times)x(times) square with alternating colors. Squares changed in size via magVal''' shapeSize=61*magVal bounds=shapeSize*times*4 #useful in determining if turtle is out of bounds, but primarily used to get screensize, 4 because squares are 4x4 individually wn.setup(width=bounds-shapeSize, height=bounds-shapeSize, startx=None, starty=None) #sets up the windows dimensions for ease of viewing wn.setworldcoordinates(0, 0, wn.window_width(), wn.window_height()) #starts turtle creating pattern in bottom left corner testTurt.penup() squareCount=0 x=0 testTurt.shapesize(magVal) #resizes the pattern with a multiplier of magVal while(True): testTurt.goto(shapeSize*x*4,0) #prevents turtle from creating squares on top of squares on top of squares, and moves appropriate x-distance x+=1 for i in range(0,times,1): #used to facilitate the swapping of colors and create the appropriate number of squares if not i%2==0: createSquare(magVal,color1,color2) squareCount+=1 elif i%2==0: createSquare(magVal,color2,color1) squareCount+=1 color1,color2=swapColors(color1,color2) #assigns the new color values after being swapped after the if statement is executed if squareCount==(times*times): #16 due to being 4 x 4 square break #------------------------------------ # IMPORTANT - backbone of the pattern # # values assigned to create individual polygons that compose the appropriate shape/pattern to be replicated. # each poly is a tupel composed of the points in a (x,y) plane that create said polygon. #------------------------------------ poly1 = ((0,0),(20,0),(0,-20)) poly2 = ((20,0),(30,0),(20,-10),(10,-10),(10,-20),(0,-30),(0,-20),(10,-10)) poly3 = ((30,-10),(30,0),(20,-10),(10,-10),(10,-20),(0,-30),(10,-30)) poly4 = ((10,-30),(30,-30),(30,-10)) createPattern(1,'black', 'blue',4) wn.exitonclick()
c35ffcb663d83db7d291d46908ec618085360835
faklijta/pallida-basic-exam-trial
/namefromemail/name_from_email.py
642
4.1875
4
# Create a function that takes email address as input in the following format: # firstName.lastName@exam.com # and returns a string that represents the user name in the following format: # last_name first_name # example: "elek.viz@exam.com" for this input the output should be: "Viz Elek" # accents does not matter # email = str(input("elek.viz@exam.com") def new_function(email): name_split = email.split(".") first_name = name_split[0] name_split2 = name_split[1] look_up_last_name = name_split2.split("@") last_name = look_up_last_name[0] name_from_email = (last_name).title() + " " + (first_name).title() print(name_from_email) new_function("elek.viz@exam.com")
3e5c14344560b0d2097eb55e7ccae16b0cfb67de
HenryHS/untitled
/test/demo01.py
660
3.671875
4
import random print(random.randint(1, 5)) n = 10 def add(a, b): return a+b class Father(): #双下划线开头和结尾,特殊属性方法 #初始化方法 def __init__(self, name): print(id(self)) self.name = name def __del__(self): print('del') def show(self): print('name:', self.name) # 双下划线 private 单下划线 protected 无 public class Son(Father): def __init__(self, name, age): super().__init__(name) self.age = age def show(self): print('name:', self.name, ',age:', self.age) if __name__ == '__main__': s = Son('11', 30) s.show()
5311a8246d0474a0e75b1132929c20a8e8836811
garg10may/Data-Structures-and-Algorithms
/sorting/Problems/mergeSortedArrays.py
1,125
4.21875
4
''' You have to merge the two sorted arrays into one sorted array (in non-increasing order) Input: First line contains an integer T, denoting the number of test cases. First line of each test case contains two space separated integers X and Y, denoting the size of the two sorted arrays. Second line of each test case contains X space separated integers, denoting the first sorted array P. Third line of each test case contains Y space separated integers, denoting the second array Q. Output: For each test case, print (X + Y) space separated integer representing the merged array. Constraints: 1 <= T <= 100 1 <= X, Y <= 5*104 0 <= Pi, Qi <= 109 Example: INPUT: 1 4 5 7 5 3 1 9 8 6 2 0 OUTPUT: 9 8 7 6 5 3 2 1 0 ''' def merge( arr1, arr2): x = len(arr1) y = len(arr2) i,j = 0, 0 result = [] while i < x and j < y: if arr1[i] > arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 #any of the array might be left, check for that if j==y: result.extend(arr1[i:]) else: result.extend(arr2[j:]) return result result = merge( [10,9,8,6,2,0], [1] ) print result
fafdceb5f6d566d5902a186f58ac081cc325185a
gseverina/python-trainings
/hackerrank/fizz_buzz.py
349
3.890625
4
def fizz_buzz(n): # Write your code here p = "" for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: p = "FizzBuzz" elif i % 3 == 0: p = "Fizz" elif i % 5 == 0: p = "Buzz" else: p = i print(f'{p}.') if __name__ == "__main__": fizz_buzz(15)
5c853f8fe02ab5663c31a1babbccd9d2f6c2b76f
wherculano/wikiPython
/05_Exercicios_Funcoes/05-TaxaDeImposto.py
478
3.9375
4
""" Faça um programa com uma função chamada somaImposto. A função possui dois parâmetros formais: taxaImposto, que é a quantia de imposto sobre vendas expressa em porcentagem e custo, que é o custo de um item antes do imposto. A função “altera” o valor de custo para incluir o imposto sobre vendas. """ def somaImposto(taxaImposto, custo): custo += custo * taxaImposto / 100 return custo # 15% de imposto sobre o valor 100 print(somaImposto(15, 100))
ff39cb2e05a6a48090fd13573295cf389bd79c39
kanikshas4/python-github
/classwork
1,880
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 29 13:48:24 2020 @author: kanikshasharma """ #%% def cube(): n=int(input("enter the number: ")) print("the number is: ",n) c=n*n*n print("cube of the number is: ",c) cube() #%% def cube(n): print("the number is ",n) c=n*n*n print("the cube of the number is: ",c) cube(5) #%% def circlearea(): r=int(input("enter the radius of circle")) PI=3.14 area=1 area=PI*r*r print("the area of the circle",area) circlearea() #%% def circlearea(rad): print("the radius of the circle",rad) PI=3.14 area=1 area=rad*rad*PI print("the area of the circle: ",area) circlearea(5) #%% def sum(): n1=int(input("enter the first number")) n2=int(input("enter the second number")) if n1>n2: n2=n2,n1 sum=0 for i in range(n1,n2+1,1): sum=sum+1 print(i) print("sum of all numbers in between",n1,"to",n2,"is",sum) sum() #%% def sum(n1,n2): if n1>n2: n2=n2,n1 sum=0 for i in range(n1,n2+1,1): sum=sum+1 print(i) print("sum of all the numbers in between",n1,"to",n2,"is",sum) sum(2,7) #%% def sum(n1,n2): if n1>n2: n2=n2,n1 sum=0 for i in range(n1,n2+1,1): sum=sum+1 print(i) print("sum of all the numbers in between",n1,"to",n2,"is",sum) sum(n2=9,n1=2) #%% def func(let1,let2): let=let1+let2 print("the concatenated let",let) let1=str(input("enter the 1st let: ")) let2=str(input("enter the 2nd let: ")) func(let1,let2) #%% def func(let1,let2): let=let1+let2 print("the charecter: ",let) let1=str(input("enter 1st charecter: ")) let2=str(input("enter 2nd charecter: ")) func(let2,let1) #%% def func(let1,let2="world"): let=let1+let2 print("the charecter: ",let) func(let1="hello",let2="everyone") func(let1="hey")
e33727f9e708edf46480fb2971266c2e95f20916
bletzacker/alyra
/2/1/5/2.1.5.py
280
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Exercice 2.1.5 """ import math def bloc_reward(height) : """ function bloc_reward(height) """ return math.floor((50 / (2 ** (height // 210000)) * 10**8)) print(str(bloc_reward(2100001)*10**(-8))+' BTC')
0ef88cbd48a369aa1a14daa9812442392a1b1704
ferdirn/hello-python
/pythontuples.py
229
4.0625
4
#!/usr/bin/env python print 'Python tuple example' tuple = ('abcde', 123, 2.23, 'Ferdi', 70.2) tinytuple = (123, 'Ferdi') print tuple print tuple[0] print tuple[1:3] print tuple[2:] print tinytuple * 2 print tinytuple + tuple
d7f8018c3a7f9fa238a6282f111f4943657962e1
aakashkawale/Python
/Assignment 1/Cheacking Gross Salary of employ by taking basic salary as input.py
384
3.78125
4
bs=int(input("Enter Your Basic Salary : ")) if bs<=10000: hra=(bs*20)/100 da=(bs*80)/100 gs=bs+hra+da print("Your Gross Salary Is", gs) elif bs>=10000 and bs<=20000: hra=(bs*25)/100 da=(bs*90)/100 gs=bs+hra+da print("Your Gross Salary Is", gs) elif bs>20000: hra=(bs*30)/100 da=(bs*95)/100 gs=bs+hra+da print("Your Gross Salary Is", gs)
5a87a9acf026f421ac2a5ab09ef67f422afad67c
eugeniocarvalho/URI
/Uri - 1035.py
514
3.6875
4
''' Leia 4 valores inteiros A, B, C e D. A seguir, se B for maior do que C e se D for maior do que A, e a soma de C com D for maior que a soma de A e B e se C e D, ambos, forem positivos e se a variável A for par escrever a mensagem "Valores aceitos", senão escrever "Valores nao aceitos". ''' A, B, C, D = input().split(" ") A = int(A) B = int(B) C = int(C) D = int(D) if B > C and D > A and C + D > A + B and C > 0 and D > 0 and A % 2 == 0: print('Valores aceitos') else: print('Valores nao aceitos')
5bade332ebad7bf298cb0207abbe2407812e0c0f
Santos1000/Curso-Python
/PYTHON/pythonDesafios/desafio085.py
668
3.859375
4
''' COM DUAS LISTAS pares = [] impar = [] for c in range(1,8): num = (float(input(f'Digite o {c} valor: '))) if num % 2 == 0: pares.append(num) else: impar.append(num) print('--'*30) print(f'Os valores pares digitados foram: {pares}') print(f'Os valores impares digitados foram: {impar}')''' lista = [[],[]] num = 0 for c in range(1,8): num = (int(input(f'Digite o {c} valor: '))) if num % 2 ==0: lista[0].append(num) else: lista[1].append(num) lista[0].sort() lista[1].sort() print('--'*30) print(f'Os valores pares digitados foram: {lista[0]}') print(f'Os valores impares digitados foram: {lista[1]}')
dfb0a60b4d1bd7570fcf8a3a612b9388258d688c
Cameron-Carter/ICS3U-Unit5-03-Python-middle_percentage
/middle_grade.py
1,381
4.34375
4
#!/usr/bin/env python3 # Created by: Cameron Carter # Created on May 2021 # This program displays the middle grade of each mark level import string def find_middle(level_mark): # Finds middle grade # Process and output if level_mark == "4+": grade = 97 elif level_mark == "4": grade = 90 elif level_mark == "4-": grade = 83 elif level_mark == "3+": grade = 78 elif level_mark == "3": grade = 75 elif level_mark == "3-": grade = 71 elif level_mark == "2+": grade = 68 elif level_mark == "2": grade = 65 elif level_mark == "2-": grade = 61 elif level_mark == "1+": grade = 58 elif level_mark == "1": grade = 55 elif level_mark == "1-": grade = 51 elif level_mark == "R": grade = 25 else: grade = -1 return grade def main(): # This function calls find_middle # Input level_mark = str( input("Enter the grade level you wanted converted to a percentage: ") ) # Function call percentage = find_middle(level_mark) # Process and output if percentage == -1: print("Invalid mark") else: print("The middle percentage of {0} is {1}%.".format( level_mark, percentage )) print("\nDone.") if __name__ == "__main__": main()
164821eb93e1a34993c62cf61c9d1e2c411f666d
DeanHe/Practice
/LeetCodePython/FindTwoNonOverlappingSubarraysEachWithTargetSum.py
1,766
4.0625
4
""" You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Constraints: 1 <= arr.length <= 105 1 <= arr[i] <= 1000 1 <= target <= 108 """ from typing import List class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: sz = len(arr) UPER_BOUND = 10 ** 7 res = UPER_BOUND pre_sum_idx = {0: -1} min_len = [0] * sz total = 0 for i, n in enumerate(arr): if i == 0: min_len[i] = UPER_BOUND else: min_len[i] = min_len[i - 1] total += n if total - target in pre_sum_idx: s = pre_sum_idx[total - target] min_len[i] = min(min_len[i], i - s) if s != -1 and min_len[s] != UPER_BOUND: res = min(res, min_len[s] + i - s) pre_sum_idx[total] = i return res if res != UPER_BOUND else -1
7e7e36fb9de5710e45747a68d83cd2604521c693
EXCurryBar/108-2_Python-class
/[0410]Homework.py
1,844
4.09375
4
from os import system # ===================Code for Question 26======================= def Q26(): str1 = input("Enter a three digits integer :") if(str1 == str1[::-1]): print(str1, "is palindrome") else: print(str1, "is not palindrome") # ===================Code for Question 27======================= def Q27(): def function(x, y): return 100*x - 200*y x, y = eval(input("Enter a point's x and y coordinates :")) if(function(x, y) > 0 and (x < 0 or y < 0)): print("The point is in the triangle") elif(function(x, y) < 0): print("The point is not in the triangle") else: print("The point is not in the triangle") # ===================Code for Question 33======================= def Q33(): dec = int(input("Enter a decimal value(0~15) :")) print("The hexadecimal value is", hex(dec)[2].capitalize()) # ===================Code for Question 34======================= def Q34(): Hex = input("Enter a hexadecimal value(0~F) :") if('0'<= Hex <= '9' and len(Hex) == 1): print("The decimal value is", Hex) elif(Hex >= 'A' and Hex <= 'F'): print("The decimal value is", 10 + ord(Hex)-ord('A')) else: print("Wrong input") while True: try: system("cls") Input = input('Question number(Q or q to quit):') if Input == '26': Q26() system("pause") elif Input == '27': Q27() system("pause") elif Input == '33': Q33() system("pause") elif Input == '34': Q34() system("pause") elif Input == 'q'or Input == 'Q': break else: print('Wrong input') system("pause") except KeyboardInterrupt: print('\nbye') break
e6f9d423a6705a89449e3f8198b4ba0af2af931e
P79N6A/WeCloud
/platform/bin/http.py
3,158
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #告诉Linux系统这是一个可以执行的文件,window忽略 #楼上这一句用来使py支持中文的 import math import os #print("http") #name=input('please input your name:') #print("i age:",name) #age=input('please input your age:') #if age >= 18: # print('you are big people') #else: # print('small people') #print('I\'m %s,my years old is %d,PI is %f' %('caoke',23,1.2)) #格式化输出,字符串%s,数字%d,浮点型%f,用%()来表示参数,中文需要用''包围 #print('Hi,{0},your score is {1}'.format('中文',59)) #classmates=['caoke','liyong','liuyanlei'] #print(classmates) #print(classmates[1]) #print(classmates[-1]) #classmates.insert(1,'wupengfei') #print(classmates) #classmates.pop() #print(classmates) #classmates.pop(1) #print(classmates) #classmates.insert(1,['wupengfei','liuyanlei']) #print(classmates) #print(classmates[1]) #courses=('yuwen','shuxue','yinyu') #print(courses) #t=(1,) #print(t) #age=20 #if age>18: # print("age is",age) #score=input('please input score:') #s=int(score) #if score>60: # print('pass') #elif score>80: # print('high score') #else: # print('sb') #lr=list(range(5)) #print(lr) #for l in lr: # print(l) #sum=0 #n=0 #while n<10: # sum=sum+n # n=n+1 #print(sum) #i=1 #while i<100: # if i==10: # break # print(i) # i=i+1 #dis={"caoke":34,"liyong":45} #print(dis['caoke']) #if 'l' in dis: # print(dis['l']) #else: # print("0") #print(dis.get("l",-1)) #dis['wupengfei']=29 #print(dis) #dis.pop('liyong') #print(dis) #a=(2,3,4) #dis[a]='23' #print(dis) #b=(2,3,[3,4]) #print(dis) #s=set([2,3,3,4]) #print(s) #print(s.remove(3)) #print(s) #h=hex(23) #print(h) #def myabs(x): # if not isinstance(x,(int,float)): # raise TypeError("bad type") # if x>0: # return x # else: # return -x #ab = myabs(-1) #print(ab) #ac = myabs(a) #print(ac) #print(math.sqrt(2)) #def power(x): # return x*x; #print(power(2)) #def power(x,n=2): # s=1 # while n>0: # n=n-1 # s=s*x # return s #print(power(2,3)) #print(power(2)) #def call(*nums): # for i in nums: # print(i) #t=(1,2,3) #call(*t) #L=range(100) #print(L) #print(L[0:10]) #print(L[20:30]) #print(L[-10:]) #print(L[:5]) #R=L[:] #print(R) #print(R[::2]) #S="String" #print(S[:2]) #dirlist=os.listdir(".") #print(dirlist) #for x in dirlist: # print(x) #dirs=[x for x in os.listdir(".")] #print(dirs) #map={"a":1,"b":2,"c":3} #for x,y in map.items(): # print(x,y) #L1 = ['Hello', 'World', 18, 'Apple', None] ##L2=[if isinstance(x,(str)): x.lower() for x in L1] #L2 = [s.lower() for s in L1 if isinstance(s,str)] #print(L2) #def f(x): # return x*x #r=map(f,[1,2,3,4]) #print(r) #def f1(x,y): # return x*10+y #s=reduce(f1,[1,3,5,7,9]) #print(s) origin=['adam', 'LISA', 'barT'] def f(x): newV="" for i,v in enumerate(x): if i==0: newV=newV+v.upper(); else: newV=newV+v.lower(); return newV simple=map(f,origin) print(simple) def f(x,y): return x*y def prod(L): j=reduce(f,L) return j print(prod([1,2,3]))
41f8006c3c2f030f519ff93b391101269a60d956
DokySp/acmicpc-practice
/GC01/code.py
723
4.0625
4
# Structure class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Build tree # Depth 0 root = Node(data=1) # Depth 1 root.left = Node(data=2) root.right = Node(data=3) # Depth 2 root.left.left = Node(data=4) root.right.left = Node(data=5) root.right.right = Node(data=6) # Depth 3 root.left.left.left = Node(data=7) root.left.left.right = Node(data=8) root.right.right.left = Node(data=9) # Depth 4 root.left.left.right.left = Node(data=10) def inorder(node: Node): if node.left is not None: inorder(node.left) print(node.data) if node.right is not None: inorder(node.right) else: print(node.data) # L - 자신 - R inorder(root)
c77747fb52203702f86c1f932e23946cc545ffe8
Nathi72TcF/level-0-coding-challenges
/task_8.py
401
4.21875
4
def convert_time(time): hour = int(time / 60) minutes = time % 60 if hour == 1 and minutes == 1: print("%d hour %d minute" % (hour, minutes)) elif hour == 1: print("%d hour %d minutes" % (hour, minutes)) elif minutes == 1: print("%d hours %d minute" % (hour, minutes)) else: print("%d hours %d minutes" % (hour, minutes)) convert_time(133)
4a41549ee044db877e2464c0bc4dcea84309e669
anhpham311/PhamNgocAnh-Fundamentals-C4E22
/Session3/Homework/btvn1.py
334
4.125
4
shop = ["t-shirt","sweater"] print(shop) new_item = input("Enter new item: ") shop.append(new_item) print(shop) update_position = int(input("Update position? ")) new_item = input("New item: ") shop[update_position-1] = new_item print(shop) delete_position = int(input("Delete position? ")) shop.pop(delete_position-1) print(shop)
e3c4dca6129a7a4a5a7c631382aad48e4c99d4a1
ChangxingJiang/LeetCode
/LOCF_剑指Offer/Offer56I/Offer56I_Python_1.py
827
3.625
4
from typing import List class Solution: def singleNumbers(self, nums: List[int]) -> List[int]: # 找到只出现了一次的两个数的异或结果 lst = 0 for n in nums: lst ^= n # 找到两个数第一个不相同的位 diff = 1 while diff & lst == 0: diff <<= 1 # 依据第一个不相同的位对该位的两种情况分别进行异或操作(此时每组只有一个出现一次的数) a, b = 0, 0 for n in nums: if n & diff: a ^= n else: b ^= n return [a, b] if __name__ == "__main__": # [1,6] 或 [6,1] print(Solution().singleNumbers([4, 1, 4, 6])) # [2,10] 或 [10,2] print(Solution().singleNumbers([1, 2, 10, 4, 1, 4, 3, 3]))
3d2ea6565e705a94dfb2988eb176a27322b7d255
antonioroddev/Uri
/2691.py
347
3.578125
4
n = int(input()) for i in range(n): string = input() lista = string.split('x') a = int(lista[0]) b = int(lista[1]) if a == b: for d in range(5,11): print('{} x {} = {}' .format(a,d,a*d)) else: for d in range(5,11): print('{} x {} = {} && {} x {} = {}' .format(a,d,a*d,b,d,b*d))
253bc8cdbad9aab5783b81637213b2eba823e601
wang264/JiuZhangLintcode
/AlgorithmAdvance/L4/require/919_meeting-rooms-ii.py
1,879
3.828125
4
# 919. Meeting Rooms II # 中文English # Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), # find the minimum number of conference rooms required. # # Example # Example1 # # Input: intervals = [(0,30),(5,10),(15,20)] # Output: 2 # Explanation: # We need two meeting rooms # room1: (0,30) # room2: (5,10),(15,20) # Example2 # # Input: intervals = [(2,7)] # Output: 1 # Explanation: # Only need one meeting room # Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end class Solution: """ @param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required """ # use sweep line algorithm # if meeting A end at 30 and meeting B start at 30. meeting end first. # so [(0,30), (30,50)] only need 1 meeting room def minMeetingRooms(self, intervals): # delta = +1 --> meeting room +1, meeting start # delta = -1 --> meeting room -1, meeting over # because be default if the 'time' are the same, -1 appear before 1 after sort ascendingly. events = [] # (time, delta) for interval in intervals: start_time, end_time = interval events.append((start_time, +1)) events.append((end_time, -1)) events.sort() curr_meeting_rooms = 0 max_meeting_rooms = 0 for event in events: event_time, delta = event curr_meeting_rooms += delta max_meeting_rooms = max(max_meeting_rooms, curr_meeting_rooms) return max_meeting_rooms sol = Solution() assert sol.minMeetingRooms(intervals=[(0, 30), (30, 50)]) == 1 assert sol.minMeetingRooms(intervals=[(0, 30), (5, 10), (15, 20)]) == 2 assert sol.minMeetingRooms(intervals=[(2, 7)]) == 1
a7341aea39474ab454dd4ace47ca7ad81b596afb
Nicht-menschlich/Sort-Algorithms
/Utils/Utils.py
2,322
3.875
4
import time as t class Utils: def askForIntInput(self): self.printProg(0.05, "You will be asked to insert numbers") t.sleep(0.75) self.printProg(0.05, "Please seperate each number with an ','") t.sleep(0.75) self.printProg(0.05, "Have fun with my program!") t.sleep(0.5) sortList = [] while not sortList: self.printProg(0.05, "Please insert a the list/items: ") inStr = input() if ',' in inStr: currentInt = "" # sets value for currentInt for i in range(len(inStr)): char = list(inStr)[i] if char != ' ': if char == ',' and currentInt != "": try: sortList += [int(currentInt)] # adds the new number to the list currentInt = "" # resets the value of currentInt except: self.printProg(0.05, "The input contains unexpected characters!") t.sleep(0.5) sortList = [] # resets tha value of the list break else: currentInt += char # adds the current character of the string input to the currentInt string if i == len(inStr) - 1: try: sortList += [int(currentInt)] # adds the new number to the list except: self.printProg(0.05, "The input contains unexpected characters!") t.sleep(0.5) sortList = [] # resets tha value of the list self.printProg(0.05, "Your input is ready to sort now. Below you can see it") self.printProg(0.05, str(sortList)) t.sleep(0.5) print("Work in Progress", end='') t.sleep(0.5) self.printProg(0.3, "..........") t.sleep(0.5) return sortList @staticmethod def printProg(time, text): for i in list(text): print(i, end='') t.sleep(time) print("")
b43ad2373670c9f1950f13f0647346f9538c0a28
KarlLichterVonRandoll/learning_python
/month05/datascience/day04/07-aaa.py
266
3.828125
4
""" 数据轴向汇总 """ import numpy as np data = np.arange(1, 13).reshape(3, 4) print(data) def func(ary): return np.max(ary), np.mean(ary), np.min(ary) r = np.apply_along_axis(func, 1, data) print(r) r = np.apply_along_axis(func, 0, data) print(r)
3ceac325abf4bbe301e44a7d9b95ba916e350918
mfriedman79/python-course
/Labs/Lab 3/solution.py
510
3.53125
4
# Dictionaries # [1] names = ['melon', 'mango', 'banana', 'apple'] costs = [1.29, 2.55, 0.79, 1.49] d = dict(zip(names,costs)) # [2] d['kiwi'] = 3.19 # [3] d.pop('mango') # [4] 'strawberry' in d # [5] for key in d: if d[key] == 2.55: print('Exists') # Sets # [1] s = set([2,3,5,7,11,13]) # [2] s = set('python') # [3] set('silent') == set('listen') # [4] len(set('mississippi')) # Files and Lists # [1] f = open('names.txt', 'w') for name in names: f.write(name + '\n') f.close()
7abc6f70b88ad69e0b0e4245799a67b864a13938
sharon-meishi/Booking-Chatbot
/dentalservice/demo/dentalservice_initialize.py
1,390
3.796875
4
import sqlite3 # initialize database def create_db(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS DENTALINFO (dentist_id integer PRIMARY KEY AUTOINCREMENT, dentist_name text NOT NULL, location text NOT NULL, specialization text NOT NULL, phone text NOT NULL); ''') print("Table created") c.close() conn.commit() conn.close() def inserst_db(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.sharon', 'Burwood', 'Oral Surgery', '0451028117')") c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.henry', 'Randwick', 'Paediatric Dentistry', '0451123456')") c.execute("INSERT INTO DENTALINFO (dentist_name, location, specialization, phone) \ VALUES ('dr.suzy', 'Eastwood', 'Orthodontics','0451456789')") print("Inserted") c.close() conn.commit() conn.close() if __name__ == '__main__': create_db("DentalService.db") inserst_db("DentalService.db")
7c579afa8cd66e6b0bcab15a784cb4b259099968
0xUvaish/The-Complete-FAANG-Preparation
/1]. DSA/1]. Data Structures/01]. Array/Python/_005)_Left_Rotate_Array_by_1.py
318
4.375
4
""" Function to rotate an the first element """ def left_rotate(arr, num): tmp = arr[0] for index in range(1, num): arr[index - 1] = arr[index] arr[num - 1] = tmp arr = [1, 2, 3, 4, 5] num = 2 print("Before Left Rotation:", arr) left_rotate(arr, num) print("After '1' Left Rotation:", arr)
62ddd83d7b4339d837183e7ce281d8264acf05b1
deepesh-promied/python-batch2
/PrivateandPublic.py
1,302
3.78125
4
class Vehicle(): VehicleCount = 0 def __init__(self,tyre=0): self.tyre = tyre self._bootspace = 100 self.__tyre_size = 50 Vehicle.VehicleCount +=1 def getTyre(self): return self.tyre def getTyreSize(self): return self.__tyre_size def setTyre(self,tyre): self.tyre=tyre def __str__(self): return f'Vehicle Object With Tyre Size {self.getTyre()}' def __repr__(self): return f'Vehicle Representation' def __demoMethod(self): return 'Vehicle Class' @classmethod #decorator def getVehicleCount(cls): return cls.VehicleCount @staticmethod def getVehicleCount1(): return 'Static Method' class Car: def __init__(self): pass def __demoMethod(self): return 'Car Class' class Sedan(Car,Vehicle): def __init__(self): Vehicle.__init__(self) Car.__init__(self) #v = Vehicle() #print(dir(v)) #x = str(v) # v.__str__ #x = v #print(v._bootspace) #v1 = str(v) #print(v.__dict__) #print(v.__tyre_size) # Error #print(v.getTyreSize()) #print(dir(v)) s = Sedan() print(s._Car__demoMethod()) print(s._Vehicle__demoMethod()) print(Vehicle.getVehicleCount()) Vehicle.getVehicleCount1()
b7a20443631a51d0452f4cc712e9cc5522cc6b6f
channamakover/Google-Project
/Google project/string_utils.py
1,109
3.53125
4
import re from constants import * def ind(ch): """ :return index of char in trie node """ ch = ch.lower() if ch.isalpha(): return ord(ch) - ord("a") + NUM_SPECIAL_CH elif ch.isnumeric(): return ord(ch) - ord("0") + NUM_ALPHAS + NUM_SPECIAL_CH if ch == " ": return SPACE_INDEX return END_INDEX def char(index): """ :return char represented by index in trie node """ if index == SPACE_INDEX: return " " if index == END_INDEX: return END if index < NUM_ALPHAS + NUM_SPECIAL_CH: return chr(index + ord("a")) return chr(index + ord("0")) def get_all_suffixes(s): """generator function to generate all suffixes of a string""" for i in range(len(s) - 1): yield s[i:], i def generic_string(s): """ remove extra spaces, ignore cases, ignore comets :param s: string :return: generic string """ s = "".join([ch for ch in s if ch.isnumeric() or ord("a") <= ord(ch.lower()) <= ord("z") or ch == " "]) return re.sub(' +', ' ', s) + END
907ecd618684539d6eaa15d76ad301967a2ae809
joaoroberto50/sendim
/lista.py
64
3.625
4
lista = [1, 2, 3, 4, 5, 6] x = 0 for i in lista: x+=1 print(x)
3fe596c5b5bcdd3a4871b4ef38698633c6ff2db6
aliabbas1031/Pythonexercises
/sumofmultiplesof3and5.py
191
3.546875
4
def sumofmultiplesof3and5(a): i=0 for a in range(1,a+1): if a%3 == 0 or a%5==0: i = a+i return i print(sumofmultiplesof3and5(10))
61535a2456b09141abd11fe8cc574060c563323a
Wakme/Leetocde-Notion
/codeparser.py
677
3.5625
4
# 解析代码, 在代码中提取出注释中的标签以及删除掉多余的注释 def parse_code(rawCode): lines = rawCode.split('\n') res = {} code = "" for line in lines: if line.find("@Notion") != -1: continue elif line.find("@Tags") != -1: res['tags'] = parse_tags(line) elif line.find("@Note") != -1: res['note'] = parse_note(line) else: code += line + "\n" res['code'] = code return res def parse_note(line): return line[line.find(":") + 1:].strip() def parse_tags(line): res = [t.strip() for t in line[line.find(':') + 1:].split(",")] return res
e56b0ab2b323c016a55f7331bcf4d08704536331
shankar7791/MI-10-DevOps
/Personel/Anjali/Assessment/16march/1.py
380
4.1875
4
# Python program to interchange first and last elements in a list def swap(): n=int(input("Enter the number of element in list ")) list=[] for x in range(0,n): ele=input("Enter element ") list.append(ele) print(f"Befor swap list {list} ") temp=list[0] list[0]=list[n-1] list[n-1]=temp print(f"After swap list {list} ") swap()
d91b491add007c5f73d075d4692a14eda170d78d
zstoebs/Daily-Coding-Problem
/December 2019/12-13-2019.py
1,500
4.03125
4
""" @author Zach Stoebner @date 12-13-2019 @descrip Given a number in Roman numeral format, convert it to decimal. The values of Roman numerals are as follows: { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } In addition, note that the Roman numeral system uses subtractive notation for numbers such as IV and XL. For the input XIV, for instance, you should return 14. """ # roman_to_decimal # Converts a number in Roman numerals to decimal # Complexity: O(n) def roman_to_decimal(roman=""): numerals = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } prev = 0 count = 0 for num in reversed(roman): if prev > numerals[num]: count -= numerals[num] prev = 0 else: prev = numerals[num] count += prev return count ###TESTS print(roman_to_decimal("X")) print(roman_to_decimal("IX")) print(roman_to_decimal("IV")) print(roman_to_decimal("III")) print(roman_to_decimal("XIV")) print(roman_to_decimal("XL")) """ 10 9 4 3 14 40 """ ### ADMIN SOLUTION def decimate(s): decimal_map = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} total = 0 for i in range(len(s) - 1): if decimal_map[s[i]] >= decimal_map[s[i + 1]]: total += decimal_map[s[i]] else: total -= decimal_map[s[i]] total += decimal_map[s[-1]] return total
9a28a7ec7d8c106934dad688024f189d665ca43d
BiancaPal/PYTHON
/INTRODUCTION TO PYTHON/printing.py
784
3.5
4
#"Gabriel Garcia Marquez, part of poem" print("If for a moment God would forget that I am a rag doll and give me a scrap of life, possibly I would not say everything that I think, but I would definitely think everything that I say.") print("I would value things not for how much they are worth but rather for what they mean.") print("I would sleep little, dream more. I know that for each minute that we close our eyes we lose sixty seconds of light.") print("I would walk when the others loiter; I would awaken when the others sleep.") print("I would listen when the others speak, and how I would enjoy a good chocolate ice cream.") print("If God would bestow on me a scrap of life, I would dress simply, I would throw myself flat under the sun, exposing not only my body but also my soul.")
fbc3c64849c2633e9d5a1de58b34d041c096ac1a
ashenoy95/text-mining
/wikipedia_mining.py
3,883
3.703125
4
import requests ''' Wikipedia Mediawiki API docs: https://www.mediawiki.org/wiki/API:Info Wikipedia API Sandbox: https://www.mediawiki.org/wiki/Special:ApiSandbox To retrieve different information, only the params have to be changed. ''' WIKIPEDIA_API_ENDPOINT = 'https://en.wikipedia.org/w/api.php' def page_ids(titles): """Look up the Wikipedia page ids by title. For example, the Wikipedia page id of "Albert Einstein" is 736. Args: titles (list of str): List of Wikipedia page titles. Returns: list of int: List of Wikipedia page ids. """ params = { 'action': 'query', 'prop': 'info', 'titles': '|'.join(titles), 'format': 'json', 'formatversion': 2 # version 2 is easier to work with } payload = requests.get(WIKIPEDIA_API_ENDPOINT, params=params) response = payload.json() pageids = [] for i in range(len(titles)): pageids.append(response['query']['pages'][i]['pageid']) return pageids def page_lengths(ids): """Find the length of a page according to the Mediawiki API. A page's length is measured in bytes which, for English-language pages, is approximately equal to the number of characters in the page's source. Args: ids (list of str): List of Wikipedia page ids. Returns: list of int: List of page lengths. """ page_lengths = [] ids = list(map(str,ids)) params = { 'action': 'query', 'prop': 'info', 'pageids': '|'.join(ids), 'format': 'json', 'formatversion': 2 } payload = requests.get(WIKIPEDIA_API_ENDPOINT, params=params) response = payload.json() for i in range(len(ids)): page_lengths.append(response['query']['pages'][i]['length']) return page_lengths def recent_revision_ids(id, n): """Find the revision ids of recent revisions to a single Wikipedia page. The Wikipedia page is identified by its page id and only the `n` most recent revision ids are returned. Args: id (int): Wikipedia page id n (int): Number of revision ids to return. Returns: list of int: List of length `n` of revision ids. """ revision_ids = [] params = { 'action': 'query', 'prop': 'revisions', 'pageids': id, 'format': 'json', 'formatversion': 2, 'rvlimit': n } payload = requests.get(WIKIPEDIA_API_ENDPOINT, params=params) response = payload.json() for i in range(n): revision_ids.append(response['query']['pages'][0]['revisions'][i]['revid']) return revision_ids def revisions(revision_ids): """Fetch the content of revisions. Revisions are identified by their revision ids. Args: revision_ids (list of int): Wikipedia revision ids Returns: list of str: List of length `n` of revision contents. """ revision_contents = [] revision_ids = list(map(str,revision_ids)) params = { 'action': 'query', 'prop': 'revisions', 'revids': '|'.join(revision_ids), 'rvprop': 'content', 'format': 'json', 'formatversion': 2 } payload = requests.get(WIKIPEDIA_API_ENDPOINT, params=params) response = payload.json() for page in response['query']['pages']: for rev in page['revisions']: revision_contents.append(rev['content']) return revision_contents if __name__ == '__main__': titles = ['Albert Einstein','Germany'] print('Titles: ', titles) ids = page_ids(titles) print('Page IDs: ', ids) print('Page lengths: ', page_lengths(ids)) recent_revision_ids = recent_revision_ids(ids, 3) print("3 most recent revision ids: ", recent_revision_ids) #print('Revision {}:\n'.format(recent_revision_ids[0]), revisions(recent_revision_ids)[0])
267891d311b53169084e38d225f4f96101dbf885
Jian-Lei/LeetCodeExercise
/example/exercise_7.py
838
3.8125
4
#!/usr/bin/env python # coding=utf-8 """ Auther: jian.lei Email: leijian0907@163.com 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2*31, 2*31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 https://leetcode-cn.com/problems/reverse-integer/ """ def reverse(x): """ :param x: int :return: """ if "-" in str(x): y = str(x)[1:] else: y = str(x) ll1 = [i for i in y] ll1.reverse() num = int("".join(ll1)) if "-" in str(x): num = 0 - num return num if -2147483648 < num < 2147483647 else 0 if __name__ == "__main__": s1 = -4567890 s2 = 1534236469 print(reverse(s1)) print(reverse(s2))
07d6f7bcfb53b775bc77db3e249c7a10592d0702
Jdrowan87A/myPython
/OldNotes.py
2,842
4.40625
4
import random # nested for loop with formating. Note that integers won't print into a string - # unless you changed the type to str(). If you are just printing a number, then no - # to change for x in range(5): for y in range(x): r = random.randrange(0,100000) / 1000 s = " Random: {:>6.3f}".format(r) print("x:" + str(x) +" y:" + str(y) + s) #format on the end of a string allows us to add variables into the string at locations name = "Joshua" fString = "Hello {}, and welcome".format(name) print (fString) print (fString[:4]) print (fString[1:3]) #lists are the basic arrays of Python. You can add multi dimensional directly in. #iterating over the list uses a simple or loop without indexing. myList = ['first','second',['third', 'fourth'], 6, 9] for x in myList: print(x) # this is a basic function that takes an integer and returns 4 items in a tuple def myPowers(x): squared = x**2 cubed = x**3 quad = x**4 pent = x**5 return squared,cubed,quad,pent results = myPowers(3) print(results) print(results[2]) a,b,c,d = myPowers(4) print(a,b,c,d) #enumerate adds numbers to the start, mySpanish = ['uno','dos','tres','quatro'] for index, num in enumerate(mySpanish): print("{} - {}".format(index + 1, num)) ## quiz question def octal_to_string(octal): result = "" value_letters = [(4,"r"),(2,"w"),(1,"x")] # Iterate over each of the digits in octal for x in [int(n) for n in str(octal)]: # Check for each of the permissions values for value, letter in value_letters: if x >= value: result += letter x -= value else: result += '-' return result print(octal_to_string(755)) # Should be rwxr-xr-x print(octal_to_string(644)) # Should be rw-r--r-- print(octal_to_string(750)) # Should be rwxr-x--- print(octal_to_string(600)) # Should be rw------- ## dictionaries use keys and values def groups_per_user(group_dictionary): user_groups = {} # Go through group_dictionary for group,users in group_dictionary.items(): # Now go through the users in the group for user in users: user_groups[user] = user_groups.get(user,[]) +[group] # Now add the group to the the list of # groups for this user, creating the entry # in the dictionary if necessary return(user_groups) print(groups_per_user({"local": ["admin", "userA"], "public": ["admin", "userB"], "administrator": ["admin"] })) ############################# ## writing a class class MyClass: def __init__(self, name, size): self.name = name self.size = size def sparkle(self): """Reduces size by 5 and prints new size. This is DOCSTRING """ self.size -= 5 print(self.size) def __str__(self): return "Stop printing my Shit!!!" Josh = MyClass("Joshua", 160) print(Josh.size) Josh.sparkle() print(Josh)
7f95d9b93182a8f0bf38f95a4fd325b4e1bcb839
benquick123/code-profiling
/code/batch-2/vse-naloge-brez-testov/DN13-M-153.py
1,881
3.734375
4
# Napiši razred Minobot. Ta sicer ne bo imel več nobene zveze z minami, imel pa bo zvezo z nalogo Minobot, ki smo jo reševali pred časom. # Minobot se v začetku nahaja na koordinatah (0, 0) in je obrnjen na desno. # Koordinatni sistem je takšen kot pri matematiki: koordinata y narašča navzgor. # Razred Minobot ima naslednje metode. # naprej(d) gre za d naprej v podani smeri; # desno() se obrne za 90 stopinj v desno; # levo() se obrne za 90 stopinj levo; # koordinate() vrne trenutne koordinate (x in y) # razdalja() vrne pravokotno razdaljo (Manhattansko razdaljo) do koordinat (0, 0): če se robot nahaja na (5, -3), je razdalja do (0, 0) enaka 8. # Če, recimo izvedemo # a = Minobot() # a.levo() # a.naprej(4) # a.desno() # a.naprej(3) # print(a.koordinate()) # se izpiše (3, 4). class Minobot: def __init__(self): self.koord = (0, 0) self.stran = 0 self.spr1 = 360 self.spr2 = 0 def naprej(self, d): x, y = self.koord if self.stran == 0: x += d self.koord = (x, y) elif self.stran == 90: y += d self.koord = (x, y) elif self.stran == 180: x -= d self.koord = (x, y) elif self.stran == 270: y -= d self.koord = (x, y) def desno(self): self.stran = self.spr1 - 90 self.spr1 -= 90 if self.spr1 == 0: self.spr1 = 360 def levo(self): self.stran = self.spr2 + 90 self.spr2 += 90 if self.spr2 == 360: self.spr2 = 0 def koordinate(self): return self.koord def razdalja(self): zx, zy = self.koord kx, ky = (0, 0) return abs(kx - zx) + abs(ky - zy)
9f7254b1bfca544762ff533cc4f2bc179b2aa65a
MaiadeOlive/Curso-Python3
/desafios-1mundo-01-35/D028 ADIVINHANDO NUMEROS.py
191
3.671875
4
import random a = (0,1,2,3,4,5) l = random.choice(a) m = int(input("De 0 a 5 qual seria sua aposta? ")) if l == m: print("Caramba acertou!!!") else: print('Não foi dessa vez!')
7c59faf34a655977e856ab333cad03b131e42c75
ctrlProgrammer/python
/ProjectEuler/library/Primes.py
3,034
3.96875
4
""" Creado por CtrlProgrammer https://github.com/ctrlProgrammer/ """ import os.path as path class Primes(): """ Validacion y contencion de numeros primos. Validacion: Se considera numero primo aquel que solo es divisible de manera entera entre 1 y el mismo Metodo para contener numeros primos: Se utiliza un bucle en el que validamos cada numero hasta un maximo en el bucle se guardan constantemente los numeros considerados primos y se crea una lista con ellos. Despues se crea un archivo .txt en el que se almacenan para su proximo uso. De esta manera solo generamos y validamos cierta cantidad de numeros primos. """ def __init__(self): """ Se obtiene el nombre del archivo en donde se quieren generar u obtener los numeros primos """ self.max_prime = 30000 def is_prime(self, num): """ Validacion de numeros primos Se considera numero primo aquel que solo es divisible de manera entera entre 1 y el mismo """ divisors = [] for i in range(1, num + 1): div = num / i if(isinstance(div, float)): if div.is_integer(): div = int(div) if isinstance(div, int): divisors.append(i) "Si este numero solo tiene dos divisores es considerado primo (el mismo y 1)" if(len(divisors) == 2): return True else: return False def create_primes_array(self, max_prime): """ Generacion de numeros primos Genera una lista llena de numeros primos, desde el 1 hasta el maximo incluido en los paramentros """ primes = [] for i in range(1, max_prime): if self.is_prime(i): primes.append(i) return primes def write_primes_txt(self, max_prime): """ Generacion de archivo con numeros primos Obtiene la lista de primos, los transforma en un string y los separa con , """ f = open(self.primes_txt, 'w') primes_array = self.create_primes_array(max_prime) primes_array = ",".join(str(int_) for int_ in primes_array) if f.write(primes_array): return True def get_primes_txt(self, txt): """ Obtencion de archivo con primos Formato: 1,3,5,7... Abre el archivo y lo convierte en una lista de enteros """ self.primes_txt = txt if(path.exists(self.primes_txt)): f = open(self.primes_txt) primes_array = f.read() # Seaparate all element with , primes_array = primes_array.split(',') # Convert all elements to integer for i in range(0, len(primes_array)): primes_array[i] = int(primes_array[i]) return primes_array else: self.write_primes_txt(self.max_prime)
50f6e833325334a5514e1f18c83f4fe57a29c3e5
MatthewViens/MITx-6.00.1x
/Week1-Python-Basics/Lesson2-Core-Elements-of-Programs/4-while-2.py
192
3.96875
4
# Convert the following into code that uses a whle loop. # prints Hello! # prints 10 # prints 8 # prints 6 # prints 4 # prints 2 print('Hello!') i = 10 while i >= 2: print(i) i -= 2
3dba3f96cda2b18fb32471f908e8cdaa0be70dca
Acheros/Dotfiles
/practice/practice27.py
291
3.890625
4
#!/usr/bin/python3 r_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) def make_more_word(): new_list=[] for i in r_list_1: if any(i in word for word in color_list_2): new_list.append(i) return new_list print(make_more_word())
8fdafc68043e8727cb9bbed41508e04e398e9256
0dd17y/Learning-Python-The-Hard-Way
/16.__Names_Variables_Code_Functions.py
507
4.3125
4
def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) #we dont need *args, Instead we can actually do this def print_two_again(arg1,arg2): print "This is still the arg1: %r, and this is still the arg2 %r" % (arg1, arg2) def print_one(arg1): print "Your one arg is %r " % arg1 #This one prints nothing. def printNothing(): print "Hey, Looks like i got nothing." print_two("Martin", "Mwanzia") print_two_again("Martin", "Mwanzia") print_one ("HelloWorld")
95af7584e7a1dbf579906e09324058cafc595d20
marceloigor/ifpi-ads-algoritmos2020.2
/uri_1001_Extremamente Básico.py
201
3.75
4
def main(): # Entrada a = int(input('Digite o valor de A: ')) b = int(input('Digite o valor de B: ')) # Processamento x = a + b # Saída print(f'x = {x}') main()
6df335cf7e3524bbd375b1236ca921be01006daa
tomaswender/praktic2
/lesson2/task_2.py
524
4.15625
4
#2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). a = list(input('Введите число: ')) my_list = [] my_list2 = [] for i in a: if int(i) % 2 == 0: my_list.append(i) else: my_list2.append(i) print(f'Четных: {len(my_list)}') print(f'Не четных: {len(my_list2)}')
bca8fa7ea12f188a9e016065bd79b49c9c0482b6
610yilingliu/leetcode
/Python3/458.poor-pigs.py
1,613
3.59375
4
# # @lc app=leetcode id=458 lang=python3 # # [458] Poor Pigs # # https://leetcode.com/problems/poor-pigs/description/ # # algorithms # Hard (47.02%) # Likes: 372 # Dislikes: 801 # Total Accepted: 18.6K # Total Submissions: 39.3K # Testcase Example: '1000\n15\n60' # # There are 1000 buckets, one and only one of them is poisonous, while the rest # are filled with water. They all look identical. If a pig drinks the poison it # will die within 15 minutes. What is the minimum amount of pigs you need to # figure out which bucket is poisonous within one hour? # # Answer this question, and write an algorithm for the general case. # # # # General case: # # If there are n buckets and a pig drinking poison will die within m minutes, # how many pigs (x) you need to figure out the poisonous bucket within p # minutes? There is exactly one bucket with poison. # # # # Note: # # # A pig can be allowed to drink simultaneously on as many buckets as one would # like, and the feeding takes no time. # After a pig has instantly finished drinking buckets, there has to be a cool # down time of m minutes. During this time, only observation is allowed and no # feedings at all. # Any given bucket can be sampled an infinite number of times (by an unlimited # number of pigs). # # # @lc code=start class Solution: def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: single_dimension_len = minutesToTest/minutesToDie + 1 pig_num = 0 while single_dimension_len ** pig_num < buckets: pig_num += 1 return pig_num # @lc code=end
37f85bb9208ca62be92855d80b347cd82e18ad45
mmngreco/checkio
/house-password.py
1,053
3.546875
4
def checkio(data): n = len(data) return all([any(map(str.isalpha, data)), any(map(str.isdigit, data)), any(map(str.isupper, data)), any(map(str.islower, data)), n >= 10]) # def checkio(data): # n = len(data) # d = [w for w in data] # return all([any(map(lambda e: e.isalpha(), d)), # any(map(lambda e: e.isdigit(), d)), # any(map(lambda e: e.isupper(), d)), # any(map(lambda e: e.islower(), d)), # n >= 10]) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio('A1213pokl') == False, "1st example" assert checkio('bAse730onE4') == True, "2nd example" assert checkio('asasasasasasasaas') == False, "3rd example" assert checkio('QWERTYqwerty') == False, "4th example" assert checkio('123456123456') == False, "5th example" assert checkio('QwErTy911poqqqq') == True, "6th example" print "All correct"
62cde85f3baa2e49de16f3ae9f733bdf685cf5b4
al1922/Paillier-cryptosystem
/prime.py
1,833
3.921875
4
from secrets import randbits from gmpy2 import next_prime, is_prime """ Brief explanation of imported functions: randbits: genarete n-bit number. next_prime: returns the next probable prime number. is_prime: return True if number is probably prime. secrets documentation: https://docs.python.org/3/library/secrets.html gmpy2 documentation: https://readthedocs.org/projects/gmpy2/downloads/pdf/latest/ """ def generatePrimeNumbers(nbits): """ This function generate two n-bits Safe prime numbers. Where: nbits: The number of bits in generete number. """ def generatePrime(nbits): """ This function generate n-bits Prime number. """ number = randbits(nbits) # Genarete n-bits number. odd_number = (number&(number - 1)) + 1 # Change number to odd number. prime_number = next_prime(odd_number) # Finding a prime number starting with an odd_number. return prime_number def generateSafePrime(nbits): """ This function generate n-bits Safe prime number. """ while True: prime_number = generatePrime(nbits - 1) # Generate (n-bits - 1) Prime number. safe_prime_number = 2 * prime_number - 1 # Calculation of n-bits Safe prime number. if (is_prime(safe_prime_number)): # Checking if the calculated Number is prime. return safe_prime_number fisrt_number = generateSafePrime(nbits) # Generation of the first prime number. second_number = generateSafePrime(nbits) # Generation of the second prime number. while fisrt_number == second_number : # Fisrt and second prime number can't be the same. second_number = generateSafePrime(nbits) return fisrt_number, second_number
7efda6a066acf22dc642b0bb3c68e50bd79c26a2
ptyshevs/ft_linalg
/ft_linalg.py
3,190
3.53125
4
from Matrix import Matrix import collections def eye(n): """ Create nxn Identity matrix :param n: side :return: """ return Matrix([[1 if i == j else 0 for i in range(n)] for j in range(n)]) def flipud(A): """ Flip lower-upper triangular matrix :param A: Matrix :return: """ return A[::-1] def is_close(a, b, tol=1e-13): """ Python stores 15 digits after comma, thus this weird tolerance """ return abs(a - b) < tol def zeros(shape): """ Create Matrix of size <shape>, filled with zeros. If shape is integer, create nxn zero matrix :param shape: :return: """ if type(shape) is int: return Matrix([[0 for _ in range(shape)] for _ in range(shape)]) elif isinstance(shape, collections.Sequence) and len(shape) == 2: return Matrix([[0 for _ in range(shape[1])] for _ in range(shape[0])]) else: raise ValueError("Don't understand input shape:", shape) def zeros_like(A): return zeros(A.shape) def vec_to_diag(v): """ Create a diagonal matrix from a vector :param v: :return: """ n = len(v) A = zeros((n, n)) for i in range(n): A[i, i] = v[i] return A def argmax(A, axis=0): """ Find index of maximum value in A :param A: Matrix :param axis: 0 for row index, 1 for column index, 2 for (row, col) tuple :return: index (-1 in case of error) """ max_row, max_col, max_val = -1, -1, None if type(A) in (list, tuple): # instead of failing miserably, find proper index for i, v in enumerate(A): if max_val is None: max_val = v max_row = i elif v > max_val: max_val = v max_row = i return max_row if A.shape == (0, 0): return max_row if A.shape[0] == 1 or A.shape[1] == 1: for i, val in enumerate(A): if max_val is None: max_val = val max_row = i elif val > max_val: max_val = val max_row = i return max_row for i, row in enumerate(A): for j, col in enumerate(row): if max_val is None: max_val = col max_row, max_col = i, j elif col > max_val: max_val = col max_row, max_col = i, j if axis == 0: return max_row elif axis == 1: return max_col else: return max_row, max_col def cut_diagonal(A): nrow, ncol = A.shape D = eye(nrow) for i in range(nrow): D[i, i] = A[i, i] return D def cut_lower_triangular(A, strict=True): nrow, ncol = A.shape X = A.copy() for i in range(nrow): for j in range(ncol): if j > i or (strict and j >= i): X[i, j] = 0 return X def to_file(A, filename): """ Save matrix coefficients to file """ with open(filename, "w+") as f: print(A, file=f) if __name__ == '__main__': v = Matrix([[1], [2], [3]]) A = vec_to_diag([0, 2, 3, 1, 2, 33 , 21, 1 ,1 , 1, 3, 4]) print(A)
809dcc0c19597d23ad305bc713c22090196f5cde
gkrudah/2018_AI
/assignment1/2013012278_assignment_1.py
11,629
3.5
4
import queue import sys import heapq mazeinfo = [] startrow = 0 exitrow = 0 keycol = 0 keyrow = 0 #read maze size def readmazeinfo(f): global mazeinfo mazeinfo = [] line = f.readline() line = line.split(" ") for data in line: data = int(data) mazeinfo.append(data) ''' find start, key, exit location for heuristic return 0 when success return -1 when fail ''' def find(maze): global startrow global exitrow global keycol global keyrow for i in range(mazeinfo[2]): if maze[0][i] == 3: startrow = i #print("startrow=", startrow) if maze[mazeinfo[1] - 1][i] == 4: exitrow = i #print("exitrow=", exitrow) for i in range(mazeinfo[1]): if i == 0: continue for j in range(mazeinfo[2]): if maze[i][j] == 6: keycol = i keyrow = j #print("key=", keycol, keyrow) break if startrow == 0 or exitrow == 0 or keycol == 0 or keyrow == 0: return -1 else: return 0 ''' solve maze by bfs path priority is EWSN return 0 when success return -1 when fail p.s kinda wrong because number 5 replace tiles that be searched not shortest path tiles ''' def bfs(maze): global mazeinfo global startrow global keycol global keyrow totalnode = 0 movex = [1, -1, 0, 0] movey = [0, 0, 1, -1] visit_key = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] visit_exit = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] q = queue.Queue() q.put((0, startrow)) #find key while q: x, y = q.get() totalnode += 1 if maze[x][y] == 6: maze[x][y] = 5 print("key_length=", visit_key[x][y]) print("key_time=", totalnode) break for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_key[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_key[nx][ny] = visit_key[x][y] + 1 if maze[nx][ny] != 6 and maze[nx][ny] != 4: maze[nx][ny] = 5 q.put((nx, ny)) q.queue.clear() q.put((keycol, keyrow)) visit_exit[keycol][keyrow] = visit_key[x][y] #find exit while q: x, y = q.get() totalnode += 1 if maze[x][y] == 4: for k in maze: print(k) print("---") print("length=", visit_exit[x][y]) print("time=", totalnode) return 0 for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_exit[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_exit[nx][ny] = visit_exit[x][y] + 1 if maze[nx][ny] != 4: maze[nx][ny] = 5 q.put((nx, ny)) return -1 ''' 4 functions below are heuristic functions ''' def distance_key(locationcol, locationrow, spentnode): global keycol global keyrow return abs(locationcol - keycol) + abs(locationrow - keyrow) + spentnode def distance_key_greed(locationcol, locationrow): global keycol global keyrow return abs(locationcol - keycol) + abs(locationrow - keyrow) def distance_exit(locationcol, locationrow, spentnode): global mazeinfo global exitrow return abs(mazeinfo[1] - 1 - locationcol) + abs(locationrow - exitrow) + spentnode def distance_exit_greed(locationcol, locationrow): global mazeinfo global exitrow return abs(mazeinfo[1] - 1 - locationcol) + abs(locationrow - exitrow) ''' solve maze by heuristic A* function give priortiy (how far + how much spent) return 0 when success return -1 when fail p.s kinda wrong because number 5 replace tiles that be searched not shortest path tiles ''' def heuristic(maze): global mazeinfo global startrow global exitrow global keycol global keyrow totalnode = 0 movex = [1, -1, 0, 0] movey = [0, 0, 1, -1] visit_key = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] visit_exit = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] q = [] heapq.heappush(q, (distance_key(0, startrow, 0), 0, startrow)) #find key while q: h, x, y = heapq.heappop(q) totalnode += 1 if maze[x][y] == 6: maze[x][y] = 5 print("key_length=", visit_key[x][y]) print("key_time=", totalnode) break for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_key[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_key[nx][ny] = visit_key[x][y] + 1 if maze[nx][ny] != 6 and maze[nx][ny] != 4: maze[nx][ny] = 5 heapq.heappush(q, (distance_key(nx, ny, visit_key[nx][ny]), nx, ny)) q = [] heapq.heappush(q, (distance_exit(keycol, keyrow, visit_key[x][y]), keycol, keyrow)) visit_exit[keycol][keyrow] = visit_key[x][y] #find exit while q: h, x, y = heapq.heappop(q) totalnode += 1 if maze[x][y] == 4: for k in maze: print(k) print("---") print("length=", visit_exit[x][y]) print("time=", totalnode) return 0 for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_exit[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_exit[nx][ny] = visit_exit[x][y] + 1 if maze[nx][ny] != 4: maze[nx][ny] = 5 heapq.heappush(q, (distance_exit(nx, ny, visit_exit[nx][ny]), nx, ny)) return -1 ''' solve maze by heuristic greed function give priortiy (how far) replace shortest path tiles by using tree make nodes can search by their location (location in 2d array == node.data) this code uses this algorithm actually return 0 when success return -1 when fail ''' def heuristic_greed(maze, filename): global mazeinfo global startrow global exitrow global keycol global keyrow totalnode = 0 movex = [1, -1, 0, 0] movey = [0, 0, 1, -1] visit_key = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] visit_exit = [[0] * int(mazeinfo[2]) for _ in range(int(mazeinfo[1]))] q = [] heapq.heappush(q, (distance_key_greed(0, startrow), 0, startrow)) nodes_key = [] for i in range(mazeinfo[1] * mazeinfo[2]): nodes_key.append(Node((0, 0))) mazetree = Tree() mazetree.insert(None, nodes_key[startrow]) #find key while q: h, x, y = heapq.heappop(q) parent = nodes_key[(x * mazeinfo[2] + y)] totalnode += 1 if maze[x][y] == 6: #print("key_length=", visit_key[x][y]) #print("key_time=", totalnode) break for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_key[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_key[nx][ny] = visit_key[x][y] + 1 if maze[nx][ny] != 4: node = nodes_key[(nx * mazeinfo[2]) + ny] node.data = (nx, ny) mazetree.insert(parent, node) heapq.heappush(q, (distance_key_greed(nx, ny), nx, ny)) q = [] heapq.heappush(q, (distance_exit_greed(keycol, keyrow), keycol, keyrow)) visit_exit[keycol][keyrow] = visit_key[x][y] nodes_exit = [] for i in range(mazeinfo[1] * mazeinfo[2]): nodes_exit.append(Node((0, 0))) #find exit while q: h, x, y = heapq.heappop(q) if x == keycol and y == keyrow: parent = nodes_key[(x * mazeinfo[2] + y)] else: parent = nodes_exit[(x * mazeinfo[2] + y)] totalnode += 1 if maze[x][y] == 4: ''' for k in maze: print(k) print("---") print("length=", visit_exit[x][y]) print("time=", totalnode) ''' printmaze(nodes_exit, maze, visit_exit[x][y], totalnode, filename) return 0 for i in range(4): nx = x + movex[i] ny = y + movey[i] if 1 <= nx < mazeinfo[1] and 1 <= ny < mazeinfo[2]: if visit_exit[nx][ny] == 0 and maze[nx][ny] != 1 and maze[nx][ny] != 3: visit_exit[nx][ny] = visit_exit[x][y] + 1 node = nodes_exit[(nx * mazeinfo[2]) + ny] node.data = (nx, ny) mazetree.insert(parent, node) heapq.heappush(q, (distance_exit_greed(nx, ny), nx, ny)) return -1 #change maze and print total output to file def printmaze(nodes, maze, length, time, filename): global mazeinfo global startrow global exitrow global keycol global keyrow node = nodes[(mazeinfo[2] * (mazeinfo[1] - 1)) + exitrow] while True: parent = node.parent if parent is None: break x, y = parent.data maze[x][y] = 5 node = parent #cause initial data is (0, 0) maze[0][0] = 1 f = open(filename, 'w') for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = str(maze[i][j]) for i in maze: f.write(" ".join(i)) f.write("\n") f.write("---\n") f.write("length=%d\n" % length) f.write("time=%d" % time) f.close() #solve first_floor maze def first_floor(): global mazeinfo f = open("first_floor.txt", 'r')#put file name which you want readmazeinfo(f) maze = [] for line in f: maze.append(line.split()) for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = int(maze[i][j]) if find(maze): print("WRONG MAZE") sys.exit() #if bfs(maze): #if heuristic(maze): if heuristic_greed(maze, "first_floor_output.txt"): print("NO KEY or NO EXIT") sys.exit() f.close() #solve second_floor maze def second_floor(): global mazeinfo f = open("second_floor.txt", 'r')#put file name which you want readmazeinfo(f) maze = [] for line in f: maze.append(line.split()) for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = int(maze[i][j]) if find(maze): print("WRONG MAZE") sys.exit() #if bfs(maze): #if heuristic(maze): if heuristic_greed(maze, "second_floor_output.txt"): print("NO KEY or NO EXIT") sys.exit() f.close() #solve third_floor maze def third_floor(): global mazeinfo f = open("third_floor.txt", 'r')#put file name which you want readmazeinfo(f) maze = [] for line in f: maze.append(line.split()) for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = int(maze[i][j]) if find(maze): print("WRONG MAZE") sys.exit() #if bfs(maze): #if heuristic(maze): if heuristic_greed(maze, "third_floor_output.txt"): print("NO KEY or NO EXIT") sys.exit() f.close() #solve fourth_floor maze def fourth_floor(): global mazeinfo f = open("fourth_floor.txt", 'r')#put file name which you want readmazeinfo(f) maze = [] for line in f: maze.append(line.split()) for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = int(maze[i][j]) if find(maze): print("WRONG MAZE") sys.exit() #if bfs(maze): #if heuristic(maze): if heuristic_greed(maze, "fourth_floor_output.txt"): print("NO KEY or NO EXIT") sys.exit() f.close() #solve fifth_floor maze def fifth_floor(): global mazeinfo f = open("fifth_floor.txt", 'r')#put file name which you want readmazeinfo(f) maze = [] for line in f: maze.append(line.split()) for i in range(mazeinfo[1]): for j in range(mazeinfo[2]): maze[i][j] = int(maze[i][j]) if find(maze): print("WRONG MAZE") sys.exit() #if bfs(maze): #if heuristic(maze): if heuristic_greed(maze, "fifth_floor_output.txt"): print("NO KEY or NO EXIT") sys.exit() f.close() ''' Tree node make parent to find each node's parent ''' class Node(object): def __init__(self, data): self.data = data self.parent = self.child1 = self.child2 = self.child3 = None ''' 3 branch factor tree exit program when behave wrong ''' class Tree(object): def __init__(self): self.root = None def insert(self, parent, node): if parent is None: self.root = node else: if parent.child1 is None: parent.child1 = node elif parent.child2 is None: parent.child2 = node elif parent.child3 is None: parent.child3 = node else: print("Wrong Tree") sys.exit() node.parent = parent def main(): first_floor() second_floor() third_floor() fourth_floor() fifth_floor() if __name__ == "__main__": main()
8ff3716faa1409dcde9716c1b322a38c5adfc76a
abc20899/PythonLearn
/src/basic/basic/JsonTest.py
543
3.796875
4
# json 库 """ json与python数据类型的对应关系 {} dict [] list 123.05 int或float null None true/flase True/False """ import json #对数据进行编码 from enum import Enum python_data = {'persions':[{'name':'june','age':29},{'name':'zhen','age':31}]} #一个字典 json_str = json.dumps(python_data) #转换成一个json print(json_str) json_data = '{"name":"june","age":29}' python_dic = json.loads(json_data) print(python_dic) class VIP(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 print(VIP.YELLOW.value)
41a0acb1a831fd60d9b641c1ac97f9dce6bd4efe
secjoe88/ProjectEuler
/Python/gridProcess.py
2,547
3.796875
4
# gridProcess.py # Author: Joey Willhite # Date: 11/13/2013 def gridProcess(file_name): # A function to find the product of any horizontal, vertical, or diagonal group of 4 numbers in a 20x20 grid. Used # to solve problem #11 file=open(file_name, 'r') matrix=[[0 for i in range(20)] for j in range(20)] max=0 """Read in values from file and parse as values are read""" for i in range(len(matrix)): for j in range(len(matrix[i])): """Read value, place in matrix""" matrix[i][j]=int(file.read(2)) file.read(1) """Check horizontal and left diagonal products (if there are sufficient matrix entries)""" if j+1>=4: temp=calcHorizProduct(matrix,i,j) if temp>max: print('Old max:' + str(max) + ' new max:' + str(temp)) max=temp if i+1>=4: temp=calcLeftDiagProd(matrix, i, j) if temp>max: print('Old max:' + str(max) + ' new max:' + str(temp)) max=temp """Check right diagonal products and vertical products (if there are sufficient matrix entries)""" if i+1>=4: temp=calcVertProduct(matrix,i,j) if temp>max: print('Old max:' + str(max) + ' new max:' + str(temp)) max=temp if (j+1)<=17: temp=calcRightDiagProd(matrix, i, j) if temp>max: print('Old max:' + str(max) + ' new max:' + str(temp)) max=temp print('Global max is:' + str(max)) """Helper methods to calculate various products""" def calcVertProduct(matrix,i,j): currentMax=matrix[i][j]*matrix[i-1][j]*matrix[i-2][j]*matrix[i-3][j] return currentMax def calcHorizProduct(matrix,i,j): currentMax=matrix[i][j]*matrix[i][j-1]*matrix[i][j-2]*matrix[i][j-3] #print('Current left horizontal product:' + str(currentMax)) return currentMax def calcLeftDiagProd(matrix, i, j): currentMax=matrix[i][j]*matrix[i-1][j-1]*matrix[i-2][j-2]*matrix[i-3][j-3] #print ('I:'+str(i+1)+', J:'+str(j+1)+' Left diagonal product:' +str(currentMax)) return currentMax def calcRightDiagProd(matrix, i, j): currentMax=matrix[i][j]*matrix[i-1][j+1]*matrix[i-2][j+2]*matrix[i-3][j+3] #print ('I:' +str(i+1)+', J:'+str(j+1)+', Right diagonal product:' +str(currentMax)) return currentMax
f1e8fb4c56ea019127a1a58a428c261ee642ec8f
kren1504/Training_codewars_hackerrank
/average.py
766
4.125
4
""" #Get the averages of these numbers Write a method, that gets an array of integer-numbers and return an array of the averages of each integer-number and his follower, if there is one. Example: Input: [ 1, 3, 5, 1, -10] Output: [ 2, 4, 3, -4.5] If the array has 0 or 1 values or is null, your method should return an empty array. Have fun coding it and please don't forget to vote and rank this kata! :-) def averages(arr): return [(arr[x]+arr[x+1])/2 for x in range(len(arr or [])-1)] """ def averages(arr): if type(arr) != list :return [] if arr == [] : return [] res = [] for i in range(len(arr)-1): res.append( (arr[i] + arr[i+1])/2) return res if __name__ == "__main__": print(averages([ 1, 3, 5, 1, -10]))
bb63317a3148e46253ceba3b7b8f572c746fb53c
XinhangXu/CP1404
/assign2.1/Assign02/placecollection.py
6,535
3.765625
4
# Create PlaceCollection class in this file from Assign02.place import Place from operator import attrgetter class PlaceCollection: def __init__(self): """initializing the program""" # built an array [][] data_list = [] for i in range(200): data_list.append([0] * 5) # [0] place, [1] country, [2] priority, [3] 'v' or 'n' self.data_list = data_list def __getitem__(self, item): return self.data_list[item] def __str__(self): """used for testing test_placecollection""" return self.data_list # fuction for sort list by priority def takeThird(val): return int(val[2]) def list_place(self,city,country,priority,status): data_list.sort(key=takeThird()) # sort by priority, no: descending -> reverse = True n = 1 # the order number of unvisited place # print unvisited places first, add * and order number for line in data_list: if line[3] == 'n': print("*{}. ".format(n), end="") print("{:12} in {:16} priority {:>4}".format(line[0], line[1], line[2])) n = n + 1 # print visited places, add order number for line_x in data_list: if line_x[3] == 'v': print(" {}. ".format(n), end="") print("{:12} in {:16} priority {:>4}".format(line_x[0], line_x[1], line_x[2])) n = n + 1 # show the number of total places and unvisited places place_total = 0 unvisited_place = 0 for line_n in data_list: if line_n[3] == 'n' or line_n[3] == 'v': place_total = place_total + 1 if line_n[3] == 'n': unvisited_place = unvisited_place + 1 print("{} places. You still want to visit {} places.".format(int(place_total), int(unvisited_place))) def add_place(self,city,country,priority,status): city = str(input(" Name: ")) while city == "": print("Input can not be blank") name = str(input(" Name: ")) else: country = str(input(" Country: ")) while country == "": print("Input can not be blank") country = str(input(" Country: ")) else: index = 0 priority = input(" Priority: ") while index == 0: if priority == "": # none print("Input can not be blank") index == 0 priority = input(" Priority: ") else: # not none if priority.isdigit(): # is number index = 1 data_list.append([name, country, priority, 'n', '']) print("{} in {} (priority {}) added to Travel Tracker".format(name, country, priority)) show_menu() command = input(">>> ").lower() elif priority.startswith('-') and priority[1:].isdigit(): # it < 0 print("Number must be > 0") index == 0 priority = input(" Priority: ") else: print("Invalid input; enter a valid number") index == 0 priority = input(" Priority: ") def mark_place(self): # show place list as command'l' data_list.sort(key=takeThird) # sort by priority, no: descending -> reverse = True n = 1 # the order number of unvisited place # print unvisited places first, add * and order number for line in data_list: if line[3] == 'n': print("*{}. ".format(n), end="") print("{:12} in {:12} priority {:12}".format(line[0], line[1], line[2])) line[4] = n n = n + 1 # print visited places, add order number for line_x in data_list: if line_x[3] == 'v': print(" {}. ".format(n), end="") print("{:12} in {:12} priority {:12}".format(line_x[0], line_x[1], line_x[2])) line_x[4] = n n = n + 1 # show the number of total places and unvisited places place_total = 0 unvisited_place = 0 for line_n in data_list: if line_n[3] == 'n' or line_n[3] == 'v': place_total = place_total + 1 if line_n[3] == 'n': unvisited_place = unvisited_place + 1 print("{} places. You still want to visit {} places.".format(int(place_total), int(unvisited_place))) # ask for entering place would like to mark print("Enter the number of a place to mark as visited") mark_in = input(">>> ") index = 0 while index == 0: if mark_in == "": # none print("Input can not be blank") index == 0 mark_in = input(">>> ") else: # not none if mark_in.isdigit(): # is a vaild number mark_num = int(mark_in) for line in data_list: if line[4] == mark_num: # when number_in(the num shows on displaying list) == order number # check the place is 'v' or 'n' if line[3] == 'n': index = 1 line[3] = 'v' print("{} in {} visited!".format(line[0], line[1])) show_menu() command = input(">>> ").lower() else: index = 0 print("That place is already visited") mark_in = input(">>> ") elif mark_in.startswith('-') and mark_in[1:].isdigit(): # it < 0 print("Number must be > 0") index == 0 mark_in = input(">>> ") else: print("Invalid input; enter a valid number") index == 0 mark_in = input(">>> ")
07a52e17d73b6091d29d0dabfc6796a1eba2a88b
pauldmccarthy/fsleyes-widgets
/fsleyes_widgets/utils/typedict.py
10,605
3.8125
4
#!/usr/bin/env python # # typedict.py - Provides the TypeDict class. # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # """This module provides the :class:`TypeDict` class, a type-aware dictionary. """ from collections import abc class TypeDict(object): """A type-aware dictionary. The purpose of the ``TypeDict`` is to allow value lookup using either classes or instances as keys. The ``TypeDict`` can be used in the same way that you would use a regular ``dict``, but the ``get`` and ``__getitem__`` methods have some extra functionality. **Easy to understand example** Let's say we have a class with some properties:: import fsleyes_widgets.utils.typedict as td class Animal(object): isMammal = True numLegs = 4 And we want to associate some tooltips with those properties:: tooltips = td.TypeDict({ 'Animal.isMammal' : 'Set this to True for mammals, ' 'False for reptiles.', 'Animal.numLegs' : 'The nuber of legs on this animal.' }) Because we used a ``TypeDict``, we can now look up those tooltips in a number of ways:: a = Animal() # Lookup by string (equivalent to a normal dict lookup) tt = tooltips['Animal.isMammal'] # Lookup by class tt = tooltips[Animal, 'isMammal'] # Lookup by instance tt = tooltips[a, 'isMammal'] This functionality also works across class hierarchies:: class Cat(Animal): numYoutubeHits = 10 tooltips = td.TypeDict({ 'Animal.isMammal' : 'Set this to True for mammals, ' 'False for reptiles.', 'Animal.numLegs' : 'The nuber of legs on this animal.', 'Cat.numYoutubeHits' : 'Number of youtube videos this cat ' 'has starred in.' }) c = Cat() isMammalTooltip = tooltips[Cat, 'isMammal'] numLegsTooltip = tooltips[c, 'numLegs'] youtubeHitsTooltip = tooltips[c, 'numYoutubeHits'] # Class-hierachy-aware TypeDict lookups only # work when you pass in an instance/class as # the key - the following will result in a # KeyError: t = tooltips['Cat.numLegs'] The :meth:`get` method has some extra functionality for working with class hierarchies:: tooltips = td.TypeDict({ 'Animal.isMammal' : 'Set this to True for mammals, ' 'False for reptiles.', 'Animal.numLegs' : 'The nuber of legs on this animal.', 'Cat.numLegs' : 'This will be equal to four for all cats, ' 'but could be less for disabled cats, ' 'or more for lucky cats.', 'Cat.numYoutubeHits' : 'Number of youtube videos this cat ' 'has starred in.' }) print tooltips.get((c, 'numLegs')) # 'This will be equal to four for all cats, but could ' # 'be less for disabled cats, or more for lucky cats.' print tooltips.get((c, 'numLegs'), allhits=True) # ['This will be equal to four for all cats, but could ' # 'be less for disabled cats, or more for lucky cats.', # 'The nuber of legs on this animal.'] print tooltips.get((c, 'numLegs'), allhits=True, bykey=True) # {('Animal', 'numLegs'): 'The nuber of legs on this animal.', # ('Cat', 'numLegs'): 'This will be equal to four for all cats, ' # 'but could be less for disabled cats, or ' # 'more for lucky cats.'} **Boring technical description** The ``TypeDict`` is a custom dictionary which allows classes or class instances to be used as keys for value lookups, but internally transforms any class/instance keys into strings. Tuple keys are supported. Value assignment with class/instance keys is not supported. All keys are transformed via the :meth:`tokenifyKey` method before being internally used and/or stored. If a class/instance is passed in as a key, and there is no value associated with that class, a search is performed on all of the base classes of that class to see if any values are present for them. """ def __init__(self, initial=None): """Create a ``TypeDict``. :arg initial: Dictionary containing initial values. """ if initial is None: initial = {} self.__dict = {} for k, v in initial.items(): self[k] = v def __str__(self): return self.__dict.__str__() def __repr__(self): return self.__dict.__repr__() def __len__(self): return len(self.__dict) def keys(self): return self.__dict.keys() def values(self): return self.__dict.values() def items(self): return self.__dict.items() def __setitem__(self, key, value): self.__dict[self.tokenifyKey(key)] = value def tokenifyKey(self, key): """Turns a dictionary key, which may have been specified as a string, or a combination of strings and types, into a tuple. """ if isinstance(key, str): if '.' in key: return tuple(key.split('.')) else: return key if isinstance(key, abc.Sequence): tKeys = map(self.tokenifyKey, key) key = [] for tk in tKeys: if isinstance(tk, str): key.append(tk) elif isinstance(tk, abc.Sequence): key += list(tk) else: key.append(tk) return tuple(key) return key def get(self, key, default=None, allhits=False, bykey=False, exact=False): """Retrieve the value associated with the given key. If no value is present, return the specified ``default`` value, which itself defaults to ``None``. If the specified key contains a class or instance, and the ``exact`` argument is ``False`` (the default), the entire class hierarchy is searched, and the first value present for the class, or any base class, are returned. If ``exact is True`` and no value exists for the specific class, the ``default`` is returned. If ``exact is False`` and the ``allhits`` argument evaluates to ``True``, the entire class hierarchy is searched, and all values present for the class, and any base class, are returned as a sequence. If ``allhits`` is ``True`` and the ``bykey`` parameter is also set to ``True``, a dictionary is returned rather than a sequence, where the dictionary contents are the subset of this dictionary, containing the keys which equated to the given key, and their corresponding values. """ try: return self.__getitem__(key, allhits, bykey, exact) except KeyError: return default def __getitem__(self, key, allhits=False, bykey=False, exact=False): origKey = key key = self.tokenifyKey(key) bases = [] # Make the code a bit easier by # treating non-tuple keys as tuples if not isinstance(key, tuple): key = tuple([key]) newKey = [] # Transform any class/instance elements into # their string representation (the class name) for elem in key: if isinstance(elem, type): newKey.append(elem.__name__) bases .append(elem.__bases__) elif not isinstance(elem, (str, int)): newKey.append(elem.__class__.__name__) bases .append(elem.__class__.__bases__) else: newKey.append(elem) bases .append(None) if exact: bases = [] key = newKey keys = [] hits = [] while True: # If the key was not a tuple turn # it back into a single element key # for the lookup if len(key) == 1: lKey = key[0] else: lKey = tuple(key) val = self.__dict.get(lKey, None) # We've found a value for the key if val is not None: # If allhits is false, just return the value if not allhits: return val # Otherwise, accumulate the value, and keep # searching else: hits.append(val) if bykey: keys.append(lKey) # No more base classes to search for - there # really is no value associated with this key elif all([b is None for b in bases]): raise KeyError(key) # Search through the base classes to see # if a value is present for one of them for i, (elem, elemBases) in enumerate(zip(key, bases)): if elemBases is None: continue # test each of the base classes # of the current tuple element for elemBase in elemBases: newKey = list(key) newKey[i] = elemBase if len(newKey) == 1: newKey = newKey[0] else: newKey = tuple(newKey) try: newVal = self.__getitem__(newKey, allhits, bykey) except KeyError: continue if not allhits: return newVal else: if bykey: newKeys, newVals = zip(*newVal.items()) keys.extend(newKeys) hits.extend(newVals) else: hits.extend(newVal) # No value for any base classes either if len(hits) == 0: raise KeyError(origKey) # if bykey is true, return a dict # containing the values and their # corresponding keys if bykey: return dict(zip(keys, hits)) # otherwise just return the # list of matched values else: return hits
6d5a6a201929d4870df2e653608ebebb06cd1e9f
Ruchika1706/Tkinter
/GridLayout.py
333
4.0625
4
from Tkinter import * root = Tk() label1 = Label(root, text = "Label1") label2 = Label(root, text = "Label2") #Text Fields are called Entries entry1 = Entry(root) entry2 = Entry(root) label1.grid(row = 0, column = 0) label2.grid(row = 1, column = 0) entry1.grid(row = 0, column = 1) entry2.grid(row = 1, column = 1) root.mainloop()
b057e7133d4cf70da15522a70decfda3cba60a75
nivbhaskhar/Leetcode-solutions
/21_MergeTwoSortedLists.py
1,090
4.03125
4
#https://leetcode.com/problems/merge-two-sorted-lists/ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: root = ListNode(0) pointer_1 = l1 pointer_2 = l2 current_node = root while(pointer_1 is not None or pointer_2 is not None): current_node.next = ListNode(0) current_node = current_node.next val_1 = math.inf val_2 = math.inf if pointer_1 is not None: val_1 = pointer_1.val if pointer_2 is not None: val_2 = pointer_2.val if val_1 <= val_2: current_node.val = val_1 pointer_1 = pointer_1.next else: current_node.val = val_2 pointer_2 = pointer_2.next return root.next # Complexity analysis #O(sum of sizes of linked lists)
028a5b53fb2fb4c0e102e7410bfa5aad5bd03ec8
pppk520/miscellaneous
/ib/level_6/tree/pre_order.py
762
3.8125
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @return a list of integers def preorderTraversal(self, A): self.ll = [] self.preorder(A) return self.ll def preorder(self, root): if root == None: return self.ll.append(root.val) self.preorder(root.left) self.preorder(root.right) if __name__ == '__main__': root = TreeNode(0) root.left = TreeNode(1) root.right = TreeNode(2) root.left.right = TreeNode(3) root.right.left = TreeNode(4) print(Solution().preorderTraversal(root)) # 01324
f0d98ffe7ec95c15c5b6ec87e655f26d1ecefb2d
HausCloud/Holberton
/holbertonschool-higher_level_programming/0x07-python-test_driven_development/5-text_indentation.py
577
4.3125
4
#!/usr/bin/python3 """ Module to indent text depending on certain characters """ def text_indentation(text): """ function to indent stuff """ if type(text) is not (str): raise TypeError("text must be a string") x = 0 for char in text: if char is " " and x == 0: continue if char is not " " and x == 0: x = -1 if char is not "." and char is not "?" and char is not ":": print(char, end="") else: print(char, end="") print() print() x = 0
4739ee1c01f56099e985fdba341eb56c79db41e8
vini52/Exercicios_PI_Python
/ece/lista1/lista1_5.py
157
3.875
4
palavra = input() palavra = palavra.lower() palavra = list(palavra) if palavra == palavra[::-1]: print('PALINDROMO') else: print('NAO EH PALINDROMO')
18bbebd4b4d327efa19681f2f0fa8e0a2ae85fcc
Dev-Learn/LearnPython
/syntax/oop/animal.py
327
3.59375
4
class Animal: # Constructor def __init__(self, name): # Lớp Animal có 1 thuộc tính (attribute): 'name'. self.name = name # Phương thức (method): def showInfo(self): print("I'm " + self.name) # Phương thức (method): def move(self): print("moving ...")
63e466246b50aba85aada209fde6ce54fd304190
statisdisc/modellingAndSimulation
/laserAtomTrap/src/objects/particle.py
1,414
3.578125
4
import numpy as np class particle: # Initialising function. Declare variables. def __init__(self, position, velocity, dragCoefficient=0.): self.position = position self.velocity = velocity self.dragCoefficient = dragCoefficient self.positions = [] self.velocities = [] if type(self.position) == list: self.position = np.array(self.position) if type(self.velocity) == list: self.velocity = np.array(self.velocity) def addHistory(self): self.positions.append(self.position) self.velocities.append(self.velocity) def update(self, position, velocity): ''' Update particle properties ''' self.position = position self.velocity = velocity self.addHistory() def drag(self): ''' Calculate the drag of the particle with respect to its frame of reference ''' return -self.dragCoefficient * np.sqrt(np.dot(self.velocity,self.velocity)) * self.velocity def move(self, a, dt): ''' Move the particle given an acceleration (a) and a timestep (dt) ''' self.velocity = self.velocity + dt*a + dt*self.drag() self.position = self.position + dt*self.velocity self.addHistory()
b4a5c298370dd47f40d44333b143e3dd0a602de0
aryamanmaithani/aryamanmaithani.github.io
/alg/groups/sylow.py
1,245
3.5625
4
__author__ = 'aryaman' start = 3 # inclusive end = 9999 # inclusive step = 2 filepath = "sylow-odd.txt" def primeFac(n): PF = [] p = 2 c = 0 div = False while not n == 1: while n % p == 0: div = True n //= p c += 1 if div: PF.append([p, c]) c = 0 div = False p += 1 return PF def npval(PF, p): cp = 1 # complimentary part for pf in PF: # calculating cp if not pf[0] == p: cp *= (pf[0]**pf[1]) np = [] # list of values nptest = 1 while nptest <= cp: if cp % nptest == 0: np.append(nptest) nptest += p return np count = 0 output = "" n = start while n <= end: PF = primeFac(n) if len(PF) > 1: np1 = True for pf in PF: if len(npval(PF, pf[0])) > 1: np1 = False break if not np1: count += 1 output = output + str(n) primefac = "" data = "" for pf in PF: primefac += " * "+str(pf[0])+"^"+str(pf[1]) data += str(pf[0]) + ": " + str(npval(PF, pf[0])) + "\n" primefac = primefac[3:] output += " = " + primefac + "\n" output += data output += "===============\n" n += step file = open(filepath, "w") file.write("There were "+str(count)+" such numbers out of the "+ str((end-start)/2) +" tested.\n===============\n") file.write(output)
d97745cfd3ee633f734cfec79efa55a2c4b269b6
Parkduksung/study-python
/과제/2주차.py
11,489
3.53125
4
#k번째 수 array = [1,5,2,6,3,7,4] commands = [[2,5,3], [4,4,1], [1,7,3]] #풀긴했는데 더 줄여볼수 있음 lambda 쓰면. def solution(array, commands): answer = [] for num in commands: answer.append(sorted(array[num[0]-1:num[1]])[num[2]-1]) return answer print(solution(array,commands)) #두 정수 사이의 합 def solution(a, b): return sum([i for i in range(min(a,b),max(a,b)+1,1)]) # 축약해봄. # def solution1(a, b): # return sum(range(min(a,b),max(a,b)+1)) #만약 min , max 못쓰면 3항연산자 써서 하면됨. # max = a >= b and a or b 등. #문자열 내 p와 y의 개수 def solution(s): return s.lower().count("p")==s.lower().count("y")==0 and True or s.lower().count("p")==s.lower().count("y") # 근데 사실상 0 일때의 예외 처리 생각해서 3항 연산자 넣어봤는데 # 처음 생각했던 s.lower().count("p")==s.lower().count("y") 이것만 해도 될듯. # 왜냐면 둘다 0개면 저 식이 성립해서 true 뱉어내니.. # def solution(s): # return s.lower().count("p")==s.lower().count("y") #문자열 내림차순으로 배치하기. def solution(s): return ''.join(list(reversed(sorted(s)))) #sorted 는 list() 로 안감싸도 잘 나오는데 #reversed 는 list 로 감싸야 나옴. #kotlin 에서 joinToString 같이 join 으로 list -> String 으로 바꿈. #sorted 내부 보니까 파라메터로 bool 형식의 reverse 가 있네. # 좀더 줄여보면 ''.join(sorted(s, reverse=True)) 이런식으로 가능. 가독성에서는 좋지만 하는건 똑같음. #문자열 다루기 기본. def solution(s): return (len(s) == 4 or len(s) == 6) and s.isdigit() #여기서 한번더 줄여보면 4,6 이니까 이걸 그냥 리스트에 담아 놓고 in 으로 안에 있는지 확인해볼수 있는듯. #len(s) in [4,6] and s.isdigit() #문자열 내 마음대로 정렬하기 import operator def solution(strings, n): return [i[0] for i in sorted(({i:i[n] for i in sorted(strings)}).items(), key=operator.itemgetter(1))] #가운데 글자 가져오기 def solution(s): return s[int(len(s)/2)-1 : int(len(s)/2)+1] if len(s)%2 == 0 else s[int(len(s)/2)] #두 개 뽑아서 더하기. def solution(numbers): answer = [] for i in range(len(numbers)) : for j in range(len(numbers)) : if i!=j : answer.append(numbers[i]+numbers[j]) return sorted(list(set(answer))) #수박수박수박~ #너무 쉽게 품.. def solution(n): answer = '' for i in range(n) : if i%2==0 : answer +="수" else: answer +="박" return answer #3진법 뒤집기 def solution(n): return sum( int(3**(len(reverse3Notation(n))-1-i)) * reverse3Notation(n)[i] for i in range(len(reverse3Notation(n)))) def reverse3Notation(n) : a = [] while n : if n%3 == 0 : a.append(0) else: a.append(int(n%3)) n = int(n/3) return a #같은 숫자는 싫어 def solution(arr): answer = [] answer.append(arr[0]) for i in range(len(arr)-1) : if arr[i] == arr[i+1] : continue else: answer.append(arr[i+1]) return answer #자연수 뒤집어 배열로 만들기. def solution(n): return list(reversed([int(i) for i in str(n)])) #약수의 합 def solution(n): answer = 0 for i in range(1,n+1) : if n%i ==0 : answer += i return answer #문자열 정수로 바꾸기 def solution(s): answer = int(s) return answer # #나누어 떨어지는 숫자 배열 def solution(arr, divisor): answer = [i for i in arr if i%divisor == 0] return sorted(answer) if len(answer)!=0 else [-1] #짝수와 홀수 def solution(num): return "Even" if num%2==0 else "Odd" #x만큼 간격이 있는 n개의 숫자 def solution(x, n): return [x*i for i in range(1,n+1)] #서울에서 김서방 찾기 def solution(seoul): return "김서방은 "+ str(seoul.index("Kim"))+"에 있다" #format 으로 하는것도 생각 # => "김서방은 {}에 있다".format(seoul.index("Kim")) #행렬의 덧셈 def solution(arr1, arr2): result = [[]] for i in range(0,len(arr1)) : if i!=0 : result.extend([[]]) for j in range(0,len(arr1[0])) : result[i].append(arr1[i][j] + arr2[i][j]) return result #너무 어렵게 푼거같은데.. for i,j 이런식으로 해서 zip 이용해서도 풀어보아야 할 문제. #핸드폰 번호 가리기 def solution(phone_number): return ''.join(["*" for i in range(0,len(phone_number)-4)])+phone_number[-4:] #생각해보니 "*" * len(phone_number)-4 해도 되네. #2016년 import datetime def solution(a, b): day_list = ["MON","TUE","WED","THU","FRI","SAT","SUN"] return day_list[datetime.date(2016,a,b).weekday()] #자릿수 더하기 def solution(n): return sum([int(i) for i in str(n)]) #정수 제곱근 판별 import math def solution(n): return (int(math.sqrt(n))+1)**2 if math.sqrt(n) == int(math.sqrt(n)) else -1 #제일 작은 수 제거하기 def solution(arr): t = min(arr) return [-1] if len(arr)<=1 else [i for i in arr if i != t] #정수 내림차순으로 배치하기 def solution(n): return int("".join(sorted([i for i in str(n)],reverse=True))) #list(str(n)) 이런식으로 해서 list 가 된다. #이상한 문자 만들기 def solution(s): return " ".join([changeText(i) for i in s.split(" ")]) def changeText(text) : convertText = "" for i in range(0,len(text)) : if i%2==0 : convertText += text[i].upper() else: convertText += text[i].lower() return convertText # 아래 학습할 것... # " ".join(map(lambda x: "".join([a.lower() if i % 2 else a.upper() for i, a in enumerate(x)]), s.split(" "))) #직사각형 별찍기 # a,b = map(int, input().strip().split(' ')) # for i in range(0,b) : # print("*"*a) #최대공약수와 최소공배수 import math def solution(n, m): return [gcm(n,m) , n*m / gcm(n,m)] def gcm(a,b) : result = 1 for i in range(2,min(a,b)+1) : while (a%i==0)&(b%i==0) : result *= i a = a/i b = b/i continue return result #예산 def solution(d, budget): answer = 0 sum = 0 for i in sorted(d) : if sum+i <= budget : sum += i answer += 1 else : break return answer #하샤드 수 def solution(x): return True if x%sum([int(i) for i in str(x)]) == 0 else False #콜라츠 추측 def solution(num): t = 0 while t <= 500 : if num == 1 : break if num % 2 == 0 : num /= 2 t += 1 continue else : num = (num*3)+1 t += 1 continue return t if num == 1 else -1 #실패율 def solution(N, stages): result = getTupleList(N, stages) result.sort(key = lambda x:-x[1]) return [i[0] for i in result] def getTupleList(N, stages): answer = [] t = len(stages) for i in range(1,N+1) : p = (float(stages.count(i))) / t if (float(stages.count(i))) !=0 else 0 if p != 0 : answer.append((i , p)) else : answer.append((i, 0 )) t-= stages.count(i) return answer #시저 암호 def solution(s, n): return "".join([plusText(i,n) for i in s]) def plusText(text,k) : answer = "" if text == " " : answer = text elif 97 <= ord(text) <= 122 : answer = chr(ord(text)-26 + k) if ord(text) + k > 122 else chr(ord(text) + k) elif 65 <= ord(text) <= 90 : answer = chr(ord(text)-26 + k) if ord(text) + k > 90 else chr(ord(text) + k) return answer #먼가 문제가 그리 좋지는 않음.. #내적 def solution(a, b): return sum([a[i] * b[i] for i in range(0,len(a))]) #[1차] 다트 게임 def solution(dartResult): num = "" _result = [] result = [] for i in dartResult : if i.isdigit() == True: num += i elif i.isalpha() == True: if i == "S" : _result.append(int(num)) elif i == "D": _result.append(int(num)**2) else : _result.append(int(num)**3) num = "" else : _result.append(i) for i in range(len(_result)) : if _result[i] == "*" : if len(result) >= 2 : result[len(result)-1] *= 2 result[len(result)-2] *= 2 else : result[len(result)-1] *= 2 elif _result[i] == "#": result[len(result)-1] *= -1 else : result.append(_result[i]) return sum(result) #크레인 인형뽑기 게임 def solution(board, moves): result = [] count = 0 for i in moves : for j in range(len(board[i-1])) : if board[j][i-1] >0 : if len(result) == 0 : result.append(board[j][i-1]) else : if result[-1] == board[j][i-1] : result.pop() count+=1 else : result.append(board[j][i-1]) board[j][i-1] = 0 break return count*2 #[1차] 비밀지도 def solution(n, arr1, arr2): answer = [] list_arr1 = [] list_arr2 = [] for i in arr1 : convertBin = "{:b}".format(i) list_arr1.append((("0")*(n-len(convertBin)))+convertBin) for j in arr2 : convertBin = "{:b}".format(j) list_arr2.append((("0")*(n-len(convertBin)))+convertBin) for i in range(n) : line = "" for j in range(n) : if int(list_arr1[i][j]) + int(list_arr2[i][j]) >= 1: line += "#" else : line += " " answer.append(line) return #모의고사 def solution(answers): p1 = [1,2,3,4,5] p2 = [2,1,2,3,2,4,2,5] p3 = [3,3,1,1,2,2,4,4,5,5] s1 = 0 s2 = 0 s3 = 0 for i in range(len(answers)) : if p1[i%5] == answers[i]: s1 += 1 if p2[i%8] == answers[i]: s2 += 1 if p3[i%10] == answers[i]: s3 += 1 a =[] if s1 == s2 and s1 == s3 : a = [1,2,3] elif s1>s2 and s1 == s3 : a = [1,3] elif s2>s1 and s2 == s3 : a = [2,3] elif s2>s3 and s1 == s2 : a = [1,2] elif s1 >s2 and s1 > s3: a = [1] elif s2 >s3 and s2 > s1: a = [2] elif s3>s2 and s3> s1: a = [3] return a ################### Lv2 ####################### #최댓값과 최솟값 def solution(s): splitList = s.split(" ") convertIntList = [int(i) for i in splitList] return "{} {}".format(min(convertIntList),max(convertIntList)) #최솟값 만들기 def solution(A,B): A = sorted(A) B = sorted(B, reverse=True) return sum([a*b for a,b in zip(A,B)]) #행렬의 곱셈 def solution(arr1, arr2): answer = [] for idx1 in range(len(arr1)): row = [] for idx2 in range(len(arr2[0])): tmp = 0 for idx3 in range(len(arr1[0])): tmp += arr1[idx1][idx3] * arr2[idx3][idx2] row.append(tmp) answer.append(row) return answer
459ff43098b6cdea39fe1f50a99b4a6cc52e7072
ofu/brisbert
/apibert/engines/dummy.py
1,206
3.859375
4
""" Default dictionary returned by the dummy class, only the database and id fields are required, all the rest are optional """ default_ = { 'id': 100, 'keyword': ['pineapple', 'onion', 'belt'], 'date': '10-12-2009', 'text': 'Crazy optional text', 'url' : '/static/dummy/01.jpg' } class Dummy(object): """ Dummy engine class, returns a dict object for certain methods called """ def keyword(self, value, num, request): """ Returns at most num dict objects, as an iterable, with keyword as a keyword in the dict. """ retval = dict(default_) retval['keyword'].append(value) return [ retval ] def date(self, value, num, request): """ Returns at most num dict objects, as an iterable, with all dict objects matching the date passed """ retval = dict(default_) retval['date'] = value return [ retval ] def id(self, value, num, request): """ Returns at most 1 dict objects, as an iterable, specified by its id of value """ retval = dict(default_) retval['id'] = value return [ retval ]
2bcee23d1eb74a6e1149f0b1271c883c3d6d5aad
rewonderful/MLC
/src/problem_173.py
2,290
3.71875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ class BSTIterator: """ My Method Using Stack 核心还是中序遍历,只不过这时候用栈来存储中间的状态 其实首先看提议,要一直返回第ksmallest的,那就是要中序遍历 并且某一时刻会有回溯的情况,肯定要用栈来保存的 用栈来保存的话可以使得存储空间降低到Oh hasNext可以是O1,但是next并不能是O1 一直appendleft,相当于,最左侧的节点一定是左右都是None的,所以访问了最左侧节点,即使 append了right,因为right是None,所以跳过了, 那么自然就根据stack,找到了node的上一级节点,也就是左根右的【根】了,而访问了根之后, 根据 """ def __init__(self, root): """ :type root: TreeNode """ self.stack = [] self.appendLeft(root) def next(self): """ @return the next smallest number :rtype: int """ curr = self.stack.pop() self.appendLeft(curr.right) return curr.val def hasNext(self): """ @return whether we have a next smallest number :rtype: bool """ return len(self.stack) != 0 def appendLeft(self, node): while node != None: self.stack.append(node) node = node.left class BSTIterator1: """ My Brute Froce Method 中序遍历存起来在queue中,然后next就相当于是queue.pop hasNext就看队列是否为空 这样能保障next和hasNext是O1,但是整体存储是ON,直接存下来所有的节点值了 """ def __init__(self, root): """ :type root: TreeNode """ self.queue = [] def inorder(root): if root == None: return inorder(root.left) self.queue.append(root.val) inorder(root.right) inorder(root) def next(self): """ @return the next smallest number :rtype: int """ return self.queue.pop(0) def hasNext(self): """ @return whether we have a next smallest number :rtype: bool """ return len(self.queue) != 0
1d6d1afbe4ac77e3b378b6d7dd7748d3f7307614
loukaab/Piggy
/student.py
14,708
3.59375
4
from teacher import PiggyParent import random, sys, time class Piggy(PiggyParent): ''' ************* SYSTEM SETUP ************* ''' def __init__(self, addr=8, detect=True): PiggyParent.__init__(self) # run the parent constructor ''' MAGIC NUMBERS <-- where we hard-code our settings ''' self.LEFT_DEFAULT = 100 self.RIGHT_DEFAULT = 100 self.SAFE_DIST = 250 self.MIDPOINT = 1500 # what servo command (1000-2000) is straight forward for your bot? self.load_defaults() # self.fullcand[] def load_defaults(self): """Implements the magic numbers defined in constructor""" self.set_motor_limits(self.MOTOR_LEFT, self.LEFT_DEFAULT) self.set_motor_limits(self.MOTOR_RIGHT, self.RIGHT_DEFAULT) self.set_servo(self.SERVO_1, self.MIDPOINT) def menu(self): """Displays menu dictionary, takes key-input and calls method""" ## This is a DICTIONARY, it's a list with custom index values. Python is cool. # Please feel free to change the menu and add options. print("\n *** MENU ***") menu = {"n": ("Autonomous Navigation", self.nav), "u": ("User Navigation", self.unav), "d": ("Dance", self.dance), "o": ("Obstacle count", self.obstacle_count), "c": ("Calibrate", self.calibrate), "h": ("Hold position", self.hold_position), "v": ("Veer navigation", self.slither), "q": ("Quit", self.quit) } # loop and print the menu... for key in sorted(menu.keys()): print(key + ":" + menu[key][0]) # store the user's answer ans = str.lower(input("Your selection: ")) # activate the item selected menu.get(ans, [None, self.quit])[1]() ''' **************** STUDENT PROJECTS **************** ''' def hold_position(self): startheading = self.get_heading() rsave = self.RIGHT_DEFAULT lsave = self.LEFT_DEFAULT self.LEFT_DEFAULT = 50 self.RIGHT_DEFAULT = 50 while True: if abs(startheading - self.get_heading()) > 15: self.turn_to_deg(startheading) self.LEFT_DEFAULT = lsave self.RIGHT_DEFAULT = rsave def waggle(self): """This makes the robot do the 'waggle' dance """ # Robot 'waggles' 4 times for i in range(2): self.turn_to_deg(45) time.sleep(.5) self.stop() self.servo(1750) time.sleep(.5) self.stop() self.turn_by_deg(-90) time.sleep(.5) self.stop() self.servo(1250) time.sleep(.5) self.stop() def headshake(self): """Function that makes robot do the 'head shake' """ # Robot shakes head 4 times for i in range(4): self.servo(1750) self.stop() self.servo(1250) self.stop() def loopy(self): """This function makes the robot do loop-dee-loops""" for s in range(2): self.turn_by_deg(350) self.turn_by_deg(-350) def moonwalk(self): self.turn_by_deg(-45) self.back() time.sleep(.75) self.stop() self.turn_by_deg(45) self.back() time.sleep(.75) self.stop() def macarena(self): for i in range(4): self.servo(1050) self.stop() time.sleep(.5) self.servo(1950) self.stop() time.sleep(.5) self.turn_by_deg(-45) self.stop() time.sleep(.5) self.turn_by_deg(90) self.stop() time.sleep(.5) self.turn_by_deg(450) def safe_to_dance(self): """360 distance check to see if surroundings are safe for movement""" for x in range(4): for ang in range(1000, 2001, 100): self.servo(ang) time.sleep(.1) if self.read_distance() < 250: return False self.turn_by_deg(90) return True def dance(self): """A higher numbered algorithm to make robot dance""" # Check to see if surroundings are safe if not self.safe_to_dance(): print("Are you trying to kill me?") else: print("Ya know what kid, I like you.") # Calling other dance moves # Declare dance randomizer variable and function list rd = random.randint(0, 4) fun = [self.waggle, self.headshake, self.loopy, self.moonwalk, self.macarena] # Loop to make robot do random dance for m in range(3): fun[4]() rd = random.randint(0, 4) # print("I don't know how to dance. \nPlease give my programmer a zero.") def scan(self): """Sweep the servo and populate the scan_data dictionary""" for angle in range(self.MIDPOINT-350, self.MIDPOINT+350, 100): self.servo(angle) self.scan_data[angle] = self.read_distance() def largescan(self): """Does a wide-ranged scan, and turns robot to hopefully open area""" for angle in range(self.MIDPOINT-500, self.MIDPOINT+500, 100): self.servo(angle) self.wide_scan_data[angle] = self.read_distance() def obstacle_count(self): """Does a 360 scan and determines obstacle count""" # Setting up magic variables found_something = False # Trigger count = 0 trigger_distance = 250 # Writing down starting position for storage starting_position = self.get_heading() # Starting rotation for scanning self.right(primary=60, counter=60) # While loop for object scanning while self.get_heading() != starting_position: if self.read_distance() < trigger_distance and not found_something: found_something = True count += 1 print("\n Found something!") elif self.read_distance() > trigger_distance and found_something: found_something = False print("\n Seems I have a clear view, resetting trigger") self.stop print("I found %d objects" % count) return count def quick_check(self): # three quick checks for ang in range(self.MIDPOINT-150, self.MIDPOINT+151, 150): self.servo(ang) if self.read_distance() < self.SAFE_DIST: return False return True def turn(self, head): """Part of program that controls robot's turning function, takes in corner count var""" rt = 0 rc = 0 lt = 0 lc = 0 # obtaining distance data to calculate average distance for ang, dist in self.wide_scan_data.items(): if ang < self.MIDPOINT: rt += dist rc += 1 else: lt += dist lc += 1 # average distance data to find open side la = lt / lc ra = rt / rc # Turns to side that is open if la > ra: self.turn_by_deg(-22) head -= 22 else: self.turn_by_deg(22) head += 22 def forw(self): self.fwd() time.sleep(.5) self.stop() def back(self): self.back() time.sleep(.5) self.stop() def lt(self): self.turn_by_deg(-22.5) def rt(self): self.turn_by_deg(22.5) def lasteffort(self, leave): self.turn_to_deg(leave) self.fwd() def fullcan(self): pass """ for i in range(0, 361, 60): self.turn_to_deg(i) self.fullcand[i] = self.read_distance() self.turn_to_deg(i) """ def unav(self): print("---------! USER NAVIGATION ACTIVATED !----------\n") while True: umenu = {"f": ("Forward", self.forw), "b": ("Back", self.back), "r": ("Right", self.rt), "l": ("Left", self.lt) } # loop and print the menu... for key in sorted(umenu.keys()): print(key + ":" + umenu[key][0]) # store the user's answer ans = str.lower(input("Your selection: ")) # activate the item selected umenu.get(ans, [None, self.quit])[1]() def slither(self): """ Practive a smooth veer """ # write down where we started starting_direction = self.get_heading() # start driving forward self.set_motor_power(self.MOTOR_LEFT, self.LEFT_DEFAULT) self.set_motor_power(self.MOTOR_RIGHT, self.RIGHT_DEFAULT) self.fwd() # throttle down the left motor for power in range(self.LEFT_DEFAULT, 70, -5): self.set_motor_power(self.MOTOR_LEFT, power) time.sleep(.5) print("throttling down left") # throttle up left for power in range(70, self.LEFT_DEFAULT + 1, 5): self.set_motor_power(self.MOTOR_LEFT, power) time.sleep(.5) print("throttling up left") # throttle down the right motor for power in range(self.RIGHT_DEFAULT, 70, -5): self.set_motor_power(self.MOTOR_RIGHT, power) time.sleep(.5) print("throttling down right") # throttle up right for power in range(70, self.LEFT_DEFAULT + 1, 5): self.set_motor_power(self.MOTOR_RIGHT, power) time.sleep(.5) print("throttling up right") left_speed = self.LEFT_DEFAULT right_speed = self.RIGHT_DEFAULT # straighten out while self.get_heading() != starting_direction: # if I need to veer right if self.get_heading() < starting_direction: right_speed -= 10 print("veer right") # if I need to veer left elif self.get_heading() > starting_direction: left_speed -= 10 print("veer left") self.set_motor_power(self.MOTOR_LEFT, self.LEFT_DEFAULT) self.set_motor_power(self.MOTOR_RIGHT, self.RIGHT_DEFAULT) time.sleep(.1) def nav(self): print("-----------! NAVIGATION ACTIVATED !------------\n") print("-------- [ Press CTRL + C to stop me ] --------\n") print("-----------! NAVIGATION ACTIVATED !------------\n") # print("Wait a second. \nI can't navigate the maze at all. Please give my programmer a zero.") # these to values allow easier tracking direction to allow a turn bias starthead = 180 currenthead = 180 exitheading = self.get_heading() check = True # inital large scan to determine optimal first turn self.largescan() self.turn(starthead) # robot moves fowards until it detects a wall while True: cc = 0 self.servo(self.MIDPOINT) if self.read_distance() < 1500: while self.quick_check(): self.fwd() time.sleep(.01) self.stop() check = False else: self.fwd() time.sleep(1) self.stop() # if robot is facing wildly away from exit, turn towards exit if abs(starthead - currenthead) > 90 or self.read_distance() >= 1500: self.turn_to_deg(exitheading) currenthead = 180 # traversal # magic numbers for counters while not check: self.scan() cc += 1 left_total = 0 left_count = 0 right_total = 0 right_count = 0 # transversal itself, collects distance and angle data for ang, dist in self.scan_data.items(): if ang < self.MIDPOINT: right_total += dist right_count += 1 else: left_total += dist left_count += 1 # average distance data to find open side left_avg = left_total / left_count right_avg = right_total / right_count # if already turned 4 times then do 180 to get out of corner if cc >= 4: self.turn_by_deg(90) currenthead += 90 if self.quick_check() >= 250: cc = 0 check = True self.turn_by_deg(-180) currenthead -= 180 if self.quick_check() >= 250: cc = 0 check = True self.lasteffort(exitheading) """ cc = 0 check = True currenthead = 0 """ # Turns to side that is open with bias towards exit of maze elif left_avg > right_avg: self.turn_by_deg(-45) currenthead -= 45 else: self.turn_by_deg(45) currenthead += 45 # checks if turned away from wall, if not, add 1 to turn checker and redoes turning protocal if self.read_distance() > self.SAFE_DIST: check = True else: cc += 1 if currenthead < 0: currenthead = abs(currenthead) ########### ## MAIN APP if __name__ == "__main__": # only run this loop if this is the main file p = Piggy() if sys.version_info < (3, 0): sys.stdout.write("Sorry, requires Python 3.x\n") p.quit() try: while True: # app loop p.menu() except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard. p.quit()
394ac4de865afea47b588101d0f8e3a03efb2465
paulosrlj/PythonCourse
/Módulo 2 - Programação procedural/Aula15 - CombinacoesPermutacoes/aula15.py
529
3.953125
4
''' Combinations, permutations e products = Itertools Combinação - ordem não importa Permutação - Ordem importa Ambos não repetem valores unicos Produto - Ordem importa e repete valores unicos ''' from itertools import combinations, count, permutations, product pessoa = ['Luiz', 'André', 'Ana', 'Eduardo', 'Fabio', 'Rose'] for grupo in combinations(pessoa, 2): print(grupo) print() for grupo in permutations(pessoa, 2): print(grupo) print() for grupo in product(pessoa, repeat=2): print(grupo) print()
c21d309b5083755f06fc9d37664cd5532806716e
renweiXu/PyDemo
/com/xu/base/IfElse.py
289
3.640625
4
def get_score(n): if n >= 90: return "优秀" elif ( n >= 80 and n<85 ) : return "良好" else : return "合格" result = get_score(86) print(result) n=60 if n >= 90: print( "优秀") elif n >= 80: print( "良好") else: print( "合格")
c6e07e106fedba61caffd6982f8030d942973f33
ishankkm/pythonProgs
/algo/binarySearchTree.py
4,443
3.53125
4
''' Created on Jun 3, 2018 @author: ishank ''' from __future__ import print_function class Node: def __init__(self, val): self.value = val self.left = None self.right = None class TreeTraversal: def __init__(self): pass # covert array format to tree format @staticmethod def arrayToBST(arr, i=0): if (i > len(arr) - 1) or (arr[i] == None): return None root = Node(arr[i]) root.left = TreeTraversal.arrayToBST(arr, 2 * i + 1) root.right = TreeTraversal.arrayToBST(arr, 2 * i + 2) return root @staticmethod def levelOrderTraversal(root): queue = [root] cur, arr = 0, [] while cur < len(queue): arr.append(queue[cur].value) if queue[cur].left != None: queue.append(queue[cur].left) if queue[cur].right != None: queue.append(queue[cur].right) cur += 1 return arr @staticmethod def depthOrderTraversal(root): stack = [root] arr = [] while len(stack) > 0: node = stack.pop() arr.append(node.value) if node.right != None: stack.append(node.right) if node.left != None: stack.append(node.left) return arr @staticmethod def depthOrderTraversal_rec(root): if root == None: return [] arr = [root.value] arr += TreeTraversal.depthOrderTraversal_rec(root.left) arr += TreeTraversal.depthOrderTraversal_rec(root.right) return arr class BST: def __init__(self): pass @staticmethod def insert(root, key): if root is None: root = Node(key) return root elif root.value < key: if root.right != None: BST.insert(root.right, key) else: root.right = Node(key) elif root.value > key: if root.left != None: BST.insert(root.left, key) else: root.left = Node(key) return root @staticmethod def balancedBST(arr): if len(arr) == 1: return Node(arr[0]) elif len(arr) == 0: return None arr = sorted(arr) mid = len(arr) // 2 root = Node(arr[mid]) root.left = BST.balancedBST(arr[:mid]) root.right = BST.balancedBST(arr[mid+1:]) return root @staticmethod def dfs(root, key): if root == None: return False if root.value == key: return True elif root.value < key: return BST.dfs(root.right, key) else: return BST.dfs(root.left, key) @staticmethod def inorderSuccessor(root): node = root while node.left != None: node = node.left return node @staticmethod def delete(root, key): if root == None: return if root.value < key: root.right = BST.delete(root.right, key) elif root.value > key: root.left = BST.delete(root.left, key) else: if root.left == None: node = root.right root = None return node elif root.right == None: node = root.left root = None return node else: root.value = BST.inorderSuccessor(root.right).value root.right = BST.delete(root.right, root.value) return root return root # tree = [2,1,3,4] # print(TreeTraversal.levelOrderTraversal(BST.balancedBST(tree))) # tree = [8, 3, 10, 1, 6, None, 14, None, None, 4, 7, None, None, 13, None] # bst = TreeTraversal.arrayToBST(tree) # print(TreeTraversal.levelOrderTraversal(bst)) # print(BST.delete(bst, 13).value) # print(TreeTraversal.levelOrderTraversal(bst))
7c86e9b153827bcfb7db90868e0017b6411d1894
gurmeetkhehra/python-practice
/Variables.py
570
3.796875
4
# I am learning Python # message = 'i love khivi' #String variable uglyString = ' I Love Khivi' print("uglyString" + uglyString) #variable number # my_integer1 = 10 # _1interger_my = 100 # print(my_integer1) # print(my_integer1 + _1interger_my + 99) # # #float variable # # current_balance = 500.50 # print(current_balance) # # my_integer1 # my_integer1 = 20 # print(my_integer1) # # #Boolean variables # is_jasmine_millionaire = True # print("'is_jasmine_millionaire:'") # print(is_jasmine_millionaire) # # is_jasmine_married = False # print(is_jasmine_married)
e0b92d6d98b67ecf5e09a43a769a238337d0f1db
dkrieger-personal/tkp
/python/sandbox/hangman-base code.py
1,450
4.09375
4
import random print("hangman!") #choose a word (display length) #guess a letter #determine whether it's right or wrong #insert the correctly guessed letters #count tbe incorrect guesses until it has exceeded its maximum #continue guessing and repeat def getword (): words= ["green", "yellow", "chicken","gentlemen"] i=random.randint (0,len(words)-1) return words[i] def getguess (): guess= input('guess-->') return guess #choose a word (display length, initialize game) ThisGameWord = getword() #print(ThisGameWord, len(ThisGameWord)) print('Your word has this many letters: ',len(ThisGameWord)) #guess a letter and put it in a variable MyGuess = [] #array of guesses youwin = 0 #indicates if you have won g=0 #counter of guesses while youwin == 0: MyGuess.append(getguess()) correctcount=0 for i in range (0,(len(ThisGameWord))): gotit = 0 for j in range(0,g+1): if (ThisGameWord[i]==MyGuess[j]): gotit=1 correctcount+=1 if (gotit==1): print(ThisGameWord[i],end='') else: print('-',end='') print('') if correctcount == len(ThisGameWord): print('You win!') youwin=1 else: g+=1 #insert the correctly guessed letters #count the incorrect guesses until it has exceeded its maximum #continue guessing and repeat #for i in range(1,5): # print ('Guess #',i,':',getguess())