blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4fcfcd1ce5acdf209357bf23e361d3134a8355f8
ishandutta2007/ProjectEuler-2
/euler/calculus.py
702
3.65625
4
def gradient_descent(f, a, b): '''Return local minimum of 'f' a <= x <= b''' def f_derivative(x): return (f(x + e) - f(x)) / e e = 1e-10 gamma = 1e-6 x_old = 0 x_new = (a + b) / 2 while abs(x_new - x_old) > e: x_old = x_new x_new = x_old - f_derivative(x_old) * gamma return x_new def Newton_Raphson(f, x_0, e): '''Return root of 'f' near x_0''' def f_derivative(x): epsilon = 1e-5 return (f(x + epsilon) - f(x)) / epsilon x_n = x_0 delta = f(x_n) / f_derivative(x_n) while abs(delta) >= e: x_n = x_n - delta delta = f(x_n) / f_derivative(x_n) return x_n
c2f17e3d76485fab3ee15e40356ddc5932349e59
zhangchizju2012/LeetCode
/202.py
763
3.578125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jul 7 17:24:42 2017 @author: zhangchi """ class Solution(object): # 按照实际运行过程写一下代码就可以了 def isHappy(self, n): """ :type n: int :rtype: bool """ self.dic = {n:1} temp = n while True: temp = self.helper(temp) if temp == 1: return True elif temp in self.dic: return False self.dic[temp] = 1 def helper(self, n): result = 0 while n != 0: temp = n % 10 result += temp ** 2 n = n // 10 return result s = Solution() print s.isHappy(19)
6e91420faefa50d39e70c8999bf5dc67491b5d32
KhizarSultan/Python
/Python Repo/chapter_6/prac.py
2,078
4.78125
5
#Tuples # is a -data structure to store any kind of data but tuples are immutables # they can not updated, can not change in original value # no pop, no insert, no append , no remove #tuples use when we know our data will not change and it is more faster than list days = ('monday','tuesday','wednesday') #methods: # count(), len(), slicing, index() print(days) # days[0] = 'Monday' #Error print(days[-1]) print(days.count('tuesday')) print(days.index('wednesday')) mixed = (1,2,3,4.0,"khizar") for i in mixed: print(i) #tuple with one element one = (1) #it is integer not a tuple two = (2,) # now it it tuple word = ("words") #it is a string not a tuple word2= ("words",) #now it is a tuple print(type(one)) #int print(type(two)) #tuple print(type(word)) print(type(word2)) #tuple without parenthesis fruits = 'Guava' ,'Melone','Apple' print(type(fruits)) #tuple print(fruits) #Tuple Unpaking guava,melon,apple = (fruits) asad,haider,habib,khizar = 30,25,23,20 print(f"{guava} and {melon} and {apple}") print(f"{asad} and {haider} and {habib} and {khizar}") #List inside Tuples names = ('khizar','Habib','Haider','Asad',[20,23,25,28],'Maryam') # we can perfome all the fucntion and method of list to the list within in tuple names[4].pop() print(names) names[4].append(28) print(names) print(min(names[4])) print(sum(names[4])) def func1(num1,num2): sum = num1 + num2 diff = num1 - num2 mul = num1 * num2 if num2!=0: div = num1 / num2 return sum,diff,mul,div # it will return a tuple that contains the answers like this (sum,diff,mul,div) sum,diff,mul,div = (func1(10,10)) print(f"The sum is {sum} and Difference is {diff} and Multiplication is {mul} and the Division is {div}") # we can change the tuple into list numbers = tuple(range(1,11)) # tuple print(numbers) numbers_list = list(numbers) #now this is converted into list print(numbers_list) string_numbers = str(numbers_list) #now this is converted into string print(string_numbers)
6c5cf8927717ba8bbd14fbfb3624913a547e988f
Dyndyn/python
/lab5.2.py
374
3.875
4
#!/usr/bin/python #-*- coding: utf-8 -*- door = list(input("What's height and width of door (write using comma)? ")) door.sort() arr = list(input("What's a, b, c (write using comma)? ")) arr.sort() if arr[1] <= door[1] and arr[0] <= door[0]: print("There is way to fit the box through the door.") else: print("There is NO way to fit the box through the door.")
fb89971ea0ea84e95f796dfe377dd81b71f4d7fa
Pradeep-Deepu/Deepu
/2.7.py
165
3.90625
4
import string alphabet = set(string.ascii_lowercase) c=str(input("Enter your string")) print(alphabet) print(set(c.lower())) print(set(c.lower()) >= alphabet)
1d8b6f82435406a153db529d0a177a681559c0ca
muhammadhuzaifa023/All-data-files
/compresshions (2).py
5,590
3.546875
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """#=========================list comprission============================== #=========================== Lambda function =============================== list=[] for i in range(1,11): if i%2==0: list.append(i) print(list) #via list comression #list=[] #input=[1,2,3,4,5,6,7,8,9,10] final=[i for i in range(1,11)] print(final) #================================ final=[i**2 for i in range(1,11)if i%2==0] print(final) #====================================== 2d array [[]]denoted by row and ineer value is [[2,3]] # is column [[1,2],[3,4]] i=0 i=1 j=0 j=1 matric=[[1,2],[3,4]] for i in range(0,2): for j in range(0,2): print(matric[i][j],end="\t") print("\n") final=[[matric[i][j]for j in range(0,2)]for j in range(0,2)] print(final) #======================================================================== # transpose matric row change into column and column change into row matric=[[1,2],[3,4]] for j in range(0,2): for i in range(0,2): print(matric[i][j],end="\t") print("\n") final=[[matric[i][j]for i in range(0,2)]for j in range(0,2)] print(final) #================================================================ list=[] for i in range(1,145): list.append(i) print(list) for i in list: n=input("enter the value:") z=i*n if z%2==0: print("it ok") else: print("not ok") #=============================================================== list=[] for i in range(1,145): list.append(i) print(i) n=int(input("enter the value;")) for j in range(list): z=j*n if z<144: print(z) #==========================================================- list=[-1,2,-3,-4] pos,neg=[i for i in list if i>0],[j for j in list if j<0] print(pos,neg) #====================== dictionary compression============================== dic={1:"a",2:"b",3:"c",4:"d"} dict={i:j for i,j in dic.items()} print(dict) #============================================================================= dic={1:"a",2:"b",3:"c",4:"d"} dict={j for j in dic.values()} print(dict) #================================================================================= dic={1:"a",2:"b",3:"c",4:"d"} dict={i for i in dic.keys()} print(dict) #============================================================================= dic={1:"a",2:"b",3:"c",4:"d"} dict={j for j in dic.values()} print(dict) #======================================================================== dic={1:"a",2:"b",3:"c",4:"d"} dict={j*2 for j in dic.values()} print(dict) #========================================================================== dic={1:"a",2:"b",3:"c",4:"d"} dict={i*2:j+"a" for j in dic.values()} print(dict) #===================================================================== # nested dictionary n nested dictionary nested dictionary compression====== nested={1:{1:"A"},2:{2:"B"},3:{3:"C"},4:{4:"D"}} final={k1:{k2 for (k2,v2) in v1.items()}for(k1,v1) in nested.items()} print(final) #============================================================================== nested={1:{1:"A"},2:{2:"B"},3:{3:"C"},4:{4:"D"}} final={k1:{v2 for (k2,v2) in v1.items()}for(k1,v1) in nested.items()} print(final) #========================================================================= nested={1:{1:"A"},2:{2:"B"},3:{3:"C"},4:{4:"D"}} final={k1:{v2:k2 for (k2,v2) in v1.items()}for(k1,v1) in nested.items()} print(final) #============================================================================= nested={1:{1:"A"},2:{2:"B"},3:{3:"C"},4:{4:"D"}} final={k1:{v2 for (k2,v2) in v1.items()}for (k1,v1) in nested.items()} print(final) #============================================================================= def square(n): res=n*n return res square(2) #===================== lambda function ======================================= final=lambda x,a,e:x*a*e print(final(2,3,4)) #===================================================================== #Code: # Constructing output list WITHOUT Using List comprehensions input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_list = [] # Using loop for constructing output list for var in input_list: if var % 2 == 0: output_list.append(var) print("Output List using for loop:", output_list) #===================================================================== #Code: # Using List comprehensions for constructing output list input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] list_using_comp = [var for var in input_list if var % 2 == 0] print("Output List using list comprehensions:",list_using_comp) #========================================================================= #Constructing output list using for loop output_list = [] for var in range(1, 10): output_list.append(var ** 2) print("Output List using for loop:", output_list) #======================================================================= #Code: # Constructing output list using list comprehension list_using_comp = [var**2 for var in range(1, 10)] print("Output List using list comprehension:",list_using_comp) #======================================================================== #Code: num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0] print(num_list) #=======================================================================
8ced74677751f25581dfa29f57abec41f29d3b91
Bharanij27/bharanirep
/PyplayS28.py
77
3.640625
4
n=list(input()) for i in range(len(n)): if n[i]!=" ": print(n[i],end="")
f96b093a0d8b3d39141eb77429b1cb9a117b8dea
DiGMi/RowingBot
/boat.py
337
3.609375
4
class Boat(object): def __init__(self,size): self.rowers = [None]*size def add_rower(self, pos, name): self.rowers[pos-1] = name def get_missing(self): ret = [] i = 1 for x in self.rowers: if x == None: ret.append(i) i += 1 return ret
a3bdf3485a64f93beb09faab0ddd6907caeb3516
tlin1130/Top-Scores-Problem
/TopScores.py
1,140
3.96875
4
# Given a list of unsorted scores in range[0,highest_possible_scores], # fastsort() sorts the list in O(n) time and space using a dictionary def fastsort(highest_possible_score, unsorted_scores): dictionary = {} sorted_scores = [None] * len(unsorted_scores) index = 0 for each_score in unsorted_scores: if each_score in dictionary: dictionary[each_score] += 1 else: dictionary[each_score] = 1 for i in range(0,highest_possible_score + 1): if not(i in dictionary): continue else: value = dictionary[i] for j in range(index, index + value): sorted_scores[j] = i index = index + value return sorted_scores # test code highest_possible_score = 100 unsorted_scores = [37,89,41,65,91,53] result = fastsort(highest_possible_score, unsorted_scores) print result # result = [37,41,53,65,89,91] unsorted_scores = [3,10,20,10,7,3] result = fastsort(highest_possible_score, unsorted_scores) print result # result = [3,3,7,10,10,20] unsorted_scores = [100,50,70,20,20,30,60,80,60,100] result = fastsort(highest_possible_score, unsorted_scores) print result # result = [20,20,30,50,60,60,70,80,100,100]
f9ecbf8e59d6270c83338fb3d6c3b2e0c49a85b9
DenilsonSilvaCode/Python3-CursoemVideo
/PythonExercicios/ex028.py
743
4.1875
4
'''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.''' from random import randint from time import sleep computador = randint(0, 5) # Faz o computador "PENSAR" print('-=-' * 20) print('Vou pensar em um número entre 0 e 5. Tente adivinhar...') print('-=-' * 20) jogador = int(input('Em que número eu pensei? ')) # jogador tenta adivinhar print('PROCESSANDO...') sleep(5) if jogador == computador: print('Parabens! Você venceu') else: print('Voce perdeu! Eu pensei no número {} e não no {}'.format(computador, jogador))
bcd90fcb3f49c07f33acfe36e50a93c2a36ab6ad
Noor-Ansari/Algorithms
/count sort.py
510
3.546875
4
def count(a): size = len(a) maxi = max(a)+1 count = [0]*maxi output = [0]*size for i in range(0,size): count[a[i]] +=1 for i in range(1,maxi): count[i] += count[i-1] i = size-1 while i >=0: output[count[a[i]]-1] = a[i] count[a[i]] -=1 i -=1 for i in range(0,size): a[i] = output[i] return a arr = [5,17,3,2,9,0,12,41,17] print("Unsorted array :-",arr) sorted_arr = count(arr) print("Sorted array :-",sorted_arr)
8c2c3dcaade4c4ef079ea4080b3568c37c0706a9
informatorio2020com07/actividades
/meza_cristian/008/Ahorcado_Game/src/juego.py
3,698
3.640625
4
from os import system from random import choice from time import sleep def titulo(): tit="AHORCADO GAME!" print(tit.center(50, "=")) def carga_palabras(): palabras=("AMOR","ROMA","PERRO","GATO","JUEGO","TELE","SILLON","HABITACION","CAMPERA","MOCHILA","CELULAR","PUERTA","COPA","BAÑERA","JARDIN") return choice(palabras) def limpiar_pantalla(): system("cls") def dibuja_palabra(adivina): muestra=list(adivina.values()) print("".join(muestra)) def adivina_dicc(palabra): adivina_pal={} for x in range(0,len(palabra)): adivina_pal.setdefault(x, " ____ ") return adivina_pal def controla_letra(letra, pal, adivina): bandera=False for x in range(0, len(pal)): if pal[x]==letra: adivina[x]=letra bandera=True return bandera def controla_palabra_completa(adivina): bandera=False if " ____ " in adivina.values(): print("FALTA MENOS!!!!") sleep(1) else: bandera=True return bandera def imprime_pantalla(vidas,adivina,list_letra): limpiar_pantalla() titulo() print() print("Vidas Disponibles: ",vidas) print("Letras Utilizadas hasta el momento: ", list_letra) imprime_ahorcado(vidas) dibuja_palabra(adivina) def juego_play(): list_letra=[] pal=carga_palabras() adivina=adivina_dicc(pal) vidas=6 while vidas>=0: imprime_pantalla(vidas, adivina, list_letra) letra=input("\nIngrese Letra: ") if letra.isdigit(): print("Solo se Permiten Letras!!! Vuelva a Intentar") sleep(1) elif len(letra)>1: print("Solo se Permite 1 Letra por Vuelta!!! Vuelva a Intentar") sleep(1) elif letra=="": print("Favor Ingresar Letra!!!") sleep(1) elif letra.upper() in list_letra: print("Letra ya Utilizada!!! Vuelva a Intentar") sleep(1) else: control_vidas=controla_letra(letra.upper(), pal,adivina) list_letra.append(letra.upper()) if control_vidas==False: print("Letra no Encontrada!") sleep(1) vidas=vidas-1 else: completo=controla_palabra_completa(adivina) if completo==True: imprime_pantalla(vidas, adivina, list_letra) print("GENIO!!!!! PALABRA CORRECTA!!!!") sleep(4) vidas=-1 def imprime_ahorcado(vidas): if vidas==6: print(''' +---+ | | | | | | =========''') elif vidas==5: print(''' +---+ | | | O | | | =========''') elif vidas==4: print(''' +---+ | | | O | | | | =========''') elif vidas==3: print(''' +---+ | | | O | /| | | =========''') elif vidas==2: print(''' +---+ | | | O | /|\\ | | =========''') elif vidas==1: print(''' +---+ | | | O | /|\\ | / | =========''') else: print(''' +---+ | | | O | /|\\ | / \\ | =========''')
0aec371f861123a4c19b71aa14df15e9a7f0e99e
Pixeluh/Animal-Shelter-Game
/AngryOldLady.py
1,734
3.734375
4
from FileReader import FileReader class AngryOldLady(FileReader): #reads the quiz information from a file and adds it to the object def __init__(self, fileName): super().__init__(fileName) try: self.quizFile = open(file_name, "r") except IOError as e: print("Unable to open the file AngryQuiz.txt. Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() self.beginDialog = next_line(quizFile) self.endDialog = next_line(quizFile) self.gEnding = next_line(quizFile) self.bEnding = next_line(quizFile) self.goodPoints = int(0) self.badPoints = int(0) self.totalPoints = int(0) intro, question, answers, correct, incorrect = next_block(file_name) def getGoodPoints(self): return self.goodPoints def getBadPoints(self): return self.badPoints def getTotalPoints(self): return self.totalPoints #toString method def __str__(self): output = "" output += ("Good points: " + goodPoints + "\nBad Points: " + badPoints + "\nTotal Points: " + totalPoints) return output #returns the good ending def gEnding(self): return self.gEnding #returns the bad ending def bEnding(self): return self.bEnding #adds good points for correct answers def addGood(self): self.goodPoints += 1 self.totalPoints += 1 #adds bad points for incorrect answers def addBad(self): self.badPoints += 1 self.totalPoints += 1 #adds total points for neutral answers def addTotal(self): self.totalPoints += 1
acbe25d47342388668d9ac3cff699410c4b6c431
nancy20162113/python-
/matplotlib/7.动手试一试_立方.py
332
3.9375
4
#author='zhy' import matplotlib.pyplot as plt x_values=[1,2,3,4,5] y_values=[x**3 for x in x_values] #plt.scatter(x_values,y_values,c='red',s=100) plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Reds,s=100) plt.title("Cubic",fontsize=14) plt.xlabel("Value",fontsize=14) plt.ylabel("Cubic of Value",fontsize=14) plt.show()
16b994a7ac9f4635c25d6bddac148e2c930d593b
mzhuang1/lintcode-by-python
/简单/112. 删除排序链表中的重复元素.py
849
3.953125
4
# -*- coding: utf-8 -*- """ 给定一个排序链表,删除所有重复的元素每个元素只留下一个 样例 给出 1->1->2->null,返回 1->2->null 给出 1->1->2->3->3->null,返回 1->2->3->null """ """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: head is the head of the linked list @return: head of linked list """ def deleteDuplicates(self, head): # write your code here if not head: return None pre = head cur = head.next while cur: if pre.val == cur.val: pre.next = cur.next cur = cur.next else: pre = cur cur = cur.next return head
2824d16bb0d6d0715e0c355f275958fbc43d83ea
RyanD1996/FYP
/FYP/pong.py
12,363
3.515625
4
import pygame import random import numpy as np import sys FPS = 60 # Game window dimensions WINDOW_WIDTH = 500 WINDOW_HEIGHT = 420 GAME_HEIGHT=400 # Size of the paddle PADDLE_WIDTH = 15 PADDLE_HEIGHT = 60 PADDLE_BUFFER= 15 # Size of the ball BALL_WIDTH = 20 BALL_HEIGHT = 20 MAX_SCORE = 11 # Speed of ball and paddle objects PADDLE_SPEED = 3 BALL_X_SPEED = 2 BALL_Y_SPEED = 2 # Colours for the paddles and ball WHITE = (255,255,255) BLACK = (0,0,0) BROWN = (210,105,30) def draw_ball(screen, x_pos, y_pos): ball = pygame.Rect(x_pos,y_pos, BALL_WIDTH, BALL_HEIGHT) pygame.draw.rect(screen, WHITE, ball) def draw_paddle_AI(screen, AI_paddle_y_position): # Paddle is located on the left side of the screen. paddle = pygame.Rect(PADDLE_BUFFER, AI_paddle_y_position, PADDLE_WIDTH, PADDLE_HEIGHT) pygame.draw.rect(screen,WHITE, paddle) def draw_paddle_user(screen, user_paddle_y_pos): # Paddle is located on the right side of the screen. paddle = pygame.Rect(WINDOW_WIDTH - PADDLE_BUFFER - PADDLE_WIDTH, user_paddle_y_pos, PADDLE_WIDTH, PADDLE_HEIGHT) pygame.draw.rect(screen,BROWN, paddle) def update_ball(AI_paddle_y_pos, user_paddle_y_pos, ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction, episode_counter, done, misses, returns, AI_score, opponent_score): ball_x_pos = ball_x_pos + ball_x_direction * BALL_X_SPEED*3 ball_y_pos = ball_y_pos + ball_y_direction * BALL_Y_SPEED*3 score = 0.0 # Check for a collision, if the ball hits the left side then switch direction. if((ball_x_pos <= (PADDLE_BUFFER + PADDLE_WIDTH)) and ((ball_y_pos + BALL_HEIGHT) >= AI_paddle_y_pos) and # Check the ball is not below the paddle (ball_y_pos <= (AI_paddle_y_pos + PADDLE_HEIGHT)) and (ball_x_direction==-1)): # Check ball is above the bottom of the paddle ball_x_direction = 1 #print("Bot hits the ball") #score = 1.0 returns += 1 elif (ball_x_pos <=0): ball_x_direction = 1 opponent_score = opponent_scores(opponent_score) score = -1.0 done=True misses += 1 ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction = reset_ball(ball_x_pos, ball_y_pos) AI_paddle_y_pos, user_paddle_y_pos = reset_paddles(AI_paddle_y_pos, user_paddle_y_pos) episode_counter += 1 #if(AI_score == MAX_SCORE or opponent_score == MAX_SCORE): #done = True return [score, AI_paddle_y_pos, user_paddle_y_pos, ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction, episode_counter, done, misses, returns, AI_score, opponent_score] if(ball_x_pos >= WINDOW_WIDTH - PADDLE_WIDTH - PADDLE_BUFFER and ball_y_pos + BALL_HEIGHT >= user_paddle_y_pos and ball_y_pos - BALL_HEIGHT <= user_paddle_y_pos + PADDLE_HEIGHT): ball_x_direction = -1 elif(ball_x_pos >= WINDOW_WIDTH - BALL_WIDTH): #score = 10.0 ball_x_direction = -1 AI_score = AI_scores(AI_score) score = 1.0 done=True print("Bot WINS!") # score = 1.0 ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction = reset_ball(ball_x_pos, ball_y_pos) AI_paddle_y_pos, user_paddle_y_pos = reset_paddles(AI_paddle_y_pos, user_paddle_y_pos) episode_counter += 1 #if(AI_score == MAX_SCORE or opponent_score == MAX_SCORE): # done = True return [score, AI_paddle_y_pos, user_paddle_y_pos, ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction, episode_counter, done, misses, returns, AI_score, opponent_score] if(ball_y_pos <=0): ball_y_pos = 0 ball_y_direction = 1 elif(ball_y_pos >= WINDOW_HEIGHT - BALL_HEIGHT): ball_y_pos = WINDOW_HEIGHT - BALL_HEIGHT ball_y_direction = -1 return [score, AI_paddle_y_pos, user_paddle_y_pos, ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction, episode_counter, done, misses, returns, AI_score, opponent_score] def reset_ball(ball_x_pos, ball_y_pos): num = np.random.randint(0, 9) ball_x_pos = WINDOW_HEIGHT/2 - BALL_WIDTH/2 # randomly decide where the ball will move if (0 <= num < 3): ball_x_direction = 1 ball_y_direction = 1 if (3 <= num < 5): ball_x_direction = -1 ball_y_direction = 1 if (5 <= num < 8): ball_x_direction = 1 ball_y_direction = -1 if (8 <= num < 10): ball_x_direction = -1 ball_y_direction = -1 # new random number num = np.random.randint(0, 9) # where it will start, y part ball_y_pos = num * (WINDOW_HEIGHT - BALL_HEIGHT) return ball_x_pos, ball_y_pos, ball_x_direction, ball_y_direction def AI_scores(AI_score): AI_score += 1 return AI_score def opponent_scores(opponent_score): opponent_score += 1 #print("Hello") return opponent_score def reset_paddles(AI_paddle_y_pos, user_paddle_y_pos): # Initialise pos of paddles AI_paddle_y_pos = WINDOW_HEIGHT / 2 - PADDLE_HEIGHT / 2 user_paddle_y_pos = WINDOW_HEIGHT / 2 - PADDLE_HEIGHT / 2 return AI_paddle_y_pos, user_paddle_y_pos def update_AI_paddle(action, AI_paddle_y_pos): # If action == move up if(action == 1): AI_paddle_y_pos -= PADDLE_SPEED*5 # If action == move down elif(action == 2): AI_paddle_y_pos += PADDLE_SPEED*5 elif(action == 3): AI_paddle_y_pos = AI_paddle_y_pos if(AI_paddle_y_pos < 0): AI_paddle_y_pos = 0 if(AI_paddle_y_pos > WINDOW_HEIGHT - PADDLE_HEIGHT): AI_paddle_y_pos = WINDOW_HEIGHT - PADDLE_HEIGHT return AI_paddle_y_pos def update_user_paddle(user_paddle_y_pos, ball_y_pos, user_action, ball_x_pos): if(user_action is None): #move down if ball is in upper half if(ball_x_pos > WINDOW_WIDTH/2): if ((user_paddle_y_pos + PADDLE_HEIGHT/2) < (ball_y_pos + BALL_HEIGHT/2)): user_paddle_y_pos = user_paddle_y_pos + PADDLE_SPEED*7.5 #move up if ball is in lower half if(user_paddle_y_pos + PADDLE_HEIGHT/2 > ball_y_pos + BALL_HEIGHT/2): user_paddle_y_pos = user_paddle_y_pos - PADDLE_SPEED*7.5 #don't let it hit top if (user_paddle_y_pos < 0): user_paddle_y_pos = 0 #dont let it hit bottom if (user_paddle_y_pos > WINDOW_HEIGHT - PADDLE_HEIGHT): user_paddle_y_pos = WINDOW_HEIGHT - PADDLE_HEIGHT return user_paddle_y_pos else: return user_paddle_y_pos else: #move down if ball is in upper half if (user_action == 2): user_paddle_y_pos = user_paddle_y_pos + PADDLE_SPEED*7.5 #move up if ball is in lower half if(user_action == 1): user_paddle_y_pos = user_paddle_y_pos - PADDLE_SPEED*7.5 if(user_action == 0): user_paddle_y_pos = user_paddle_y_pos #don't let it hit top if (user_paddle_y_pos < 0): user_paddle_y_pos = 0 #dont let it hit bottom if (user_paddle_y_pos > WINDOW_HEIGHT - PADDLE_HEIGHT): paddle2YPos = WINDOW_HEIGHT - PADDLE_HEIGHT return user_paddle_y_pos class Pong: def __init__(self, human_mode): self.human_mode = human_mode pygame.init() # Initialise Screen self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) self.font = pygame.font.SysFont("calibri", 20) # Random number between 0-9 for direction of ball self.AI_score = 0 self.opponent_score = 0 self.ball_x_direction = 0 self.ball_y_direction = 0 num = np.random.randint(0,9) self.done = False # Keep Score self.tally = 0 self.return_rate = 0 self.returns = 0 self.misses = 0 self.episode_counter =0 # Initialise pos of paddles self.AI_paddle_y_pos = WINDOW_HEIGHT /2 - PADDLE_HEIGHT /2 self.user_paddle_y_pos = WINDOW_HEIGHT / 2 - PADDLE_HEIGHT / 2 # Ball direction #self.ball_x_direction =1 #self.ball_y_direction =1 # Starting point self.ball_x_pos = WINDOW_HEIGHT/2 - BALL_WIDTH/2 #randomly decide where the ball will move if(0 < num < 3): self.ball_x_direction = 1 self.ball_y_direction = 1 if (3 <= num < 5): self.ball_x_direction = -1 self.ball_y_direction = 1 if (5 <= num < 8): self.ball_x_direction = 1 self.ball_y_direction = -1 if (8 <= num < 10): self.ball_x_direction = -1 self.ball_y_direction = -1 #new random number num = np.random.randint(0,9) #where it will start, y part self.ball_y_pos = num*(WINDOW_HEIGHT - BALL_HEIGHT)/9 def get_curr_frame(self): # For each frame, call event queue pygame.event.pump() #Paint background self.screen.fill(BLACK) #Draw paddles draw_paddle_AI(self.screen,self.AI_paddle_y_pos) draw_paddle_user(self.screen, self.user_paddle_y_pos) #Draw ball draw_ball(self.screen, self.ball_x_pos, self.ball_y_pos) # Get pixels image_data = pygame.surfarray.array3d(pygame.display.get_surface()) # Update the window pygame.display.flip() # Return screen data return [image_data] def get_next_frame(self, action, user_action): pygame.event.pump() score = 0 done = False self.screen.fill(BLACK) self.AI_paddle_y_pos = update_AI_paddle(action, self.AI_paddle_y_pos) draw_paddle_AI(self.screen, self.AI_paddle_y_pos) self.user_paddle_y_pos = update_user_paddle(self.user_paddle_y_pos, self.ball_y_pos, user_action, self.ball_x_pos) draw_paddle_user(self.screen, self.user_paddle_y_pos) [score, self.AI_paddle_y_pos, self.user_paddle_y_pos, self.ball_x_pos, self.ball_y_pos, self.ball_x_direction, self.ball_y_direction, self.episode_counter, done, misses, returns, self.AI_score, self.opponent_score] = update_ball(self.AI_paddle_y_pos, self.user_paddle_y_pos, self.ball_x_pos, self.ball_y_pos, self.ball_x_direction, self.ball_y_direction, self.episode_counter, self.done, self.misses, self.returns, self.AI_score, self.opponent_score) draw_ball(self.screen, self.ball_x_pos, self.ball_y_pos) self.misses = misses self.returns = returns exit_message = "Press Q to exit" # Display Parameters if(not self.human_mode): returns_display = self.font.render("Returns: " + str(self.returns), True, (255, 255, 255)) self.screen.blit(returns_display, (300., 400.)) misses_display = self.font.render("Misses: " + str(self.misses), True, (255, 255, 255)) self.screen.blit(misses_display, (400., 400.)) TimeDisplay = self.font.render(" " + str(exit_message), True, (255, 255, 255)) self.screen.blit(TimeDisplay, (10., 400.)) if(self.human_mode): bot_score = self.font.render("Bot Score: " + str(self.AI_score), True, (255, 255, 255)) self.screen.blit(bot_score, (200., 400.)) human_score = self.font.render("Human Score: " + str(self.opponent_score), True, (255, 255, 255)) self.screen.blit(human_score, (350., 400.)) TimeDisplay = self.font.render(" " + str(exit_message), True, (255, 255, 255)) self.screen.blit(TimeDisplay, (10., 400.)) # Get pixels if(score>0.5 or score <-0.5): if(self.returns == 0): self.return_rate = 0 else: self.return_rate = (self.returns/(self.misses + self.returns))*100 self.tally = 0.1*score + self.tally*0.9 image_data = pygame.surfarray.array3d(pygame.display.get_surface()) # Update the window pygame.display.flip() return [score,image_data, done]
f90536e32ec1b4ac3ea1c84374022bb517ae57a2
nipsn/EjerciciosPythonLP
/e6h1.py
111
3.5625
4
def escalera(n): for x in range(1,n+1): print("".join([str(y) for y in range(1,x+1)])) escalera(5)
fe3021ccb9a65a1d4e90f488c58f5d908640c8ee
jinger02/testcodes
/4-exercise1.py
316
3.6875
4
#import random #for i in range(10): # x = random.random() # print(x) #n = 5 #while n > 0: # print(n) # n=n-1 #print('Blastoff!') #n = 10 #while True: # print(n, end=' ') # n = n-1 #print('Done!') while True: line = input('> ') if line == 'done': break print(line)
0d0d81f28d1c39a0e13470f352406f46735459a4
sumitkrm/lang-1
/python/ds-algo/ds/graph/digraph-cycle-dfs.py
1,127
3.59375
4
from collections import defaultdict class Graph: def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def isCycleUtilDfs(self, v, visited, recstack): visited.add(v) recstack.add(v) if v not in self.graph: return False for neighbour in self.graph[v]: if neighbour not in visited: if self.isCycleUtilDfs(neighbour, visited, recstack): return True elif neighbour in recstack: return True if v in recstack: recstack.remove(v) return False def isCycleDfs(self): visited = set() recstack = set() for v in self.graph: if self.isCycleUtilDfs(v, visited, recstack): return True return False # Driver Program graph = Graph(5) graph.addEdge('A', 'B') graph.addEdge('A', 'C') graph.addEdge('A', 'D') graph.addEdge('E', 'A') # Check cycle print (graph.isCycleDfs()) # Create cycle graph.addEdge('B', 'E') print (graph.isCycleDfs())
fc5a41b2f7a256da788e1a0dbb1e7dade3907b47
zhouwei713/Flasky
/app/api/date_time.py
583
3.84375
4
''' Created on 20171208 @author: zhou ''' ''' generate date list ''' import datetime def datelist(start, end): start_date = datetime.date(*start) end_date = datetime.date(*end) result = [] curr_date = start_date while curr_date != end_date: result.append("%04d-%02d-%02d" % (curr_date.year, curr_date.month, curr_date.day)) curr_date += datetime.timedelta(1) result.append("%04d-%02d-%02d" % (curr_date.year, curr_date.month, curr_date.day)) return result if __name__ == "__main__": print datelist((2017, 1, 1), (2017, 11, 30))
8c8d4b66b0b1044d2a090cdfda363589b7d20d28
naoyasugiyama/chainer-tutorial
/Exercises/Step01.py
3,141
3.96875
4
# python chainer Tutorial # url : https://tutorials.chainer.org/ja/Exercise_Step_01.html# import math # 問2.1 (組み込み関数) def sample01(): a=[4, 8, 3, 4, 1] print(len(a)) print(max(a)) print(min(a)) print(sum(a)) a.sort() print(a) # 問2.2 (演算) def sample02(): #5 float print( 1.2 + 3.8 ) # 0 inter print( 10 // 100 ) # false bool print( 1 >= 0 ) # true bool print( 'Hello World' == 'Hello World' ) # true bool print( not 'Chainer' != 'Tutorial' ) # false print( all([True, True, False]) ) # true print( any([True, True, False]) ) # 3 print(abs(-3)) # 0 error print( type(2 // 0) ) # 問2.3 (リストの基本操作) def sample03(): a = [4, 8, 3, 4, 1] # a.pop(0) first # a.pop(-1) last # a.append(100) print(a) # 問2.4 (リスト内包表記) def sample04(): a = [4, 8, 3, 4, 1] #squares = [ x % 2 for x in a ] #print(squares) #countOdd(a) removeEven(a) def countOdd( data_list :list): squears = [ x % 2 for x in data_list ] print(squears.count(1)) def removeEven( data_list :list ): b = [ x for x in data_list if x % 2 != 0 ] print(b) # 問2.5 (文字列) def sample05(): # number_s = [ str(x) for x in range(100) ] # result = ' '.join(number_s) print( ' '.join( [str(x) for x in range(100)] ) ) print(" 1.0 / 7.0 is {0:.9f}".format( 1.0 / 7.0 )) # 問2.6 (クラス) class DataManager(): def __init__(self, x, y, z): self.x, self.y ,self.z = x , y , z def add_x(self, delta ): self.x += delta def add_y(self, delta ): self.y += delta def add_z(self, delta ): self.z += delta def sum(self): return self.x + self.y + self.z def sample06(): data_manager = DataManager( 2, 3, 5 ) print( data_manager.sum() ) data_manager.add_x(4) print( data_manager.sum() ) data_manager.add_y(0) print( data_manager.sum() ) data_manager.add_z(-9) print(data_manager.sum()) # 問2.7 (関数呼び出し) def f(a): # print( "f(a):{%s}" % id(a) ) a = [ 6, 7, 8 ] # print( "f(a):{%s}" % id(a) ) ) def g(a): a.append(1) def somfunction(): a0 = [1, 2, 3] print( "a0:[%s]" % id(a0) ) f(a0) print(a0) # print 1,2,3 # f(a) 関数 a= [ 6, 7, 8] のときにオブジェクトを生成している 変数 a0とは別になる # id()を使えばオブジェクトが同じかわかる a1 = [1, 2, 3] g(a1) print(a1) # 1,2,3,1 g()にリストを追加される # リスト型を関数の引数にするときは参照がわたされる def sample07(): somfunction() # 問2.8 (制御構文) # 2 ~ 100までの素数をリスト化 def sample08(): max_num = 100 primes = [ p for p in range( 2, max_num ) if check_prime03(p) ] print( primes ) def check_prime03( num ): if num == 1: return False for check in range( 2, int(math.sqrt(num)) + 1 ): if num % check == 0: return False return True if __name__ == '__main__': sample08()
697c71bfa3a707d89c489f0ef0917f62be9c6112
connormoffatt/Baseball
/Analyzing Baseball Data With R/Book - First Edition/Chapter 5 - Value of Plays Using Run Expectancy/ch5_exercise1.py
5,730
3.546875
4
import pandas as pd # Run Values of Hits # In Section 5.8, we found the average run vaalue of a home run and a single # (a) # Use similar R code as described in Section 5.8 for the 2011 season data to # find the mean run values for a double and for a triple # read in 2011 play by play data data2011 = pd.read_csv('all2011.csv', header=None) fields = pd.read_csv('fields.csv') data2011.columns = fields.loc[:, 'Header'] # We want to calculate the runs scored for the remaining of the inning # First calculate the runs at a given time data2011['RUNS'] = data2011.AWAY_SCORE_CT + data2011.HOME_SCORE_CT # Create a unique ID for each half inning data2011['HALF_INNING'] = data2011.GAME_ID + data2011.INN_CT.map(str) + \ data2011.BAT_HOME_ID.map(str) # Now we will calculate how many runs were scored at the end of the inning # Calculate the number of runs scored during each play data2011['RUNS_SCORED'] = (data2011.BAT_DEST_ID > 3).astype(int) + \ (data2011.RUN1_DEST_ID > 3).astype(int) + \ (data2011.RUN2_DEST_ID > 3).astype(int) + \ (data2011.RUN3_DEST_ID > 3).astype(int) # Get the Number of runs scored in a specific inning RUNS_SCORED_INNING = data2011.groupby(['HALF_INNING']).sum().loc[:, 'RUNS_SCORED'] # Find the total game runs at the beginning of the inning with '[' function RUNS_SCORED_START = data2011.loc[:, ['HALF_INNING', 'RUNS']].groupby( ['HALF_INNING']).min().loc[:, 'RUNS'] # Get the maximum number of runs in the half inning MAX = pd.DataFrame(RUNS_SCORED_INNING + RUNS_SCORED_START) MAX.columns = ['MAX_RUNS'] MAX['half'] = MAX.index # Merge together the max_runs into the data2011 dataframe data2011 = data2011.merge(MAX, left_on='HALF_INNING', right_on='half') # Calculate the runs for the remainder of the inning. Typo in Book data2011['RUNS_ROI'] = data2011.MAX_RUNS - data2011.RUNS # Create Binary Variable to determine if runner is on a base before play RUNNER1 = data2011['BASE1_RUN_ID'].notna().astype(int) RUNNER2 = data2011['BASE2_RUN_ID'].notna().astype(int) RUNNER3 = data2011['BASE3_RUN_ID'].notna().astype(int) # Create the current state data2011['STATE'] = RUNNER1.map(str) + RUNNER2.map(str) + RUNNER3.map(str) + \ ' ' + data2011.OUTS_CT.map(str) # Create Binary Variable to determine if a runner is on a base after play NRUNNER1 = ((data2011.RUN1_DEST_ID == 1) | \ (data2011.BAT_DEST_ID == 1)).astype(int) NRUNNER2 = ((data2011.BAT_DEST_ID == 2) | \ (data2011.RUN1_DEST_ID == 2) | \ (data2011.RUN2_DEST_ID == 2)).astype(int) NRUNNER3 = ((data2011.BAT_DEST_ID == 3) | \ (data2011.RUN1_DEST_ID == 3) | \ (data2011.RUN2_DEST_ID == 3) | \ (data2011.RUN3_DEST_ID == 3)).astype(int) # Get number of outs at the end of play NOUTS = data2011.OUTS_CT + data2011.EVENT_OUTS_CT # Get the new state at the end of the play data2011['NEW_STATE'] = NRUNNER1.map(str) + NRUNNER2.map(str) + \ NRUNNER3.map(str) + ' ' + NOUTS.map(str) # Reduce dataframe to when states change or runs score data2011 = data2011[(data2011.STATE != data2011.NEW_STATE) | (data2011.RUNS_SCORED > 0)] # Get the number of outs per inning and merge into the dataframe OUTS = pd.DataFrame(data2011.loc[:, ['HALF_INNING', 'EVENT_OUTS_CT']].groupby( ['HALF_INNING']).sum().loc[:, 'EVENT_OUTS_CT']) OUTS.columns = ['INNING_OUTS'] OUTS['half'] = OUTS.index data2011 = data2011.merge(OUTS, left_on='HALF_INNING', right_on='half') # filter out half innings that are walk-offs because they are not complete # innings data2011c = data2011[data2011.INNING_OUTS == 3] # Calculate the expected number of runs for each element of the matrix RUNS = pd.DataFrame(data2011c.loc[:, ['STATE', 'RUNS_ROI']].groupby( ['STATE']).mean().loc[:, 'RUNS_ROI']) # Add Three Out States to Create Potential States data frame s3 = ['000 3', '001 3', '010 3', '011 3', '100 3', '101 3', '110 3', '111 3'] zeros_data = {'RUNS_ROI':[0,0,0,0,0,0,0,0]} RUNS_POTENTIAL = RUNS.append(pd.DataFrame(data=zeros_data, index=s3)) # Calculate Runs Value of State Before Play data2011['RUNS_STATE'] = RUNS_POTENTIAL.loc[data2011. STATE,].reset_index().loc[:,'RUNS_ROI'] # Calculate Runs Value of State After Play data2011['RUNS_NEW_STATE'] = RUNS_POTENTIAL.loc[data2011. NEW_STATE,].reset_index().loc[:,'RUNS_ROI'] # Calculate Runs Value of each play data2011['RUNS_VALUE'] = data2011.RUNS_NEW_STATE - data2011.RUNS_STATE + \ data2011.RUNS_SCORED # (a) # Use similar R code as described in Section 5.8 for the 2011 season data to # find the mean run values for a double and for a triples # Mean value of single d_single = data2011[data2011.EVENT_CD == 20] mean_single = d_single.RUNS_VALUE.mean() # Mean value of double d_double = data2011[data2011.EVENT_CD == 21] mean_double = d_double.RUNS_VALUE.mean() # Mean value of triple d_triple = data2011[data2011.EVENT_CD == 22] mean_triple = d_triple.RUNS_VALUE.mean() # Mean value of homer d_homerun= data2011[data2011.EVENT_CD == 23] mean_homerun = d_homerun.RUNS_VALUE.mean() # Values # single: 0.442 # double: 0.736 # triple: 1.064 # homerun: 1.392 # (b) # Albert and Bennett (2001) use a regression approach to obtain the weights # 0.46, 0.80, 1.02, and 1.40 for a single, double, triple, and home run, # respectively. Compare the results from section 5.8 and part (a) with the # weights of Albert and Bennett # The results from above are similar to the values derived by Albert and # Bennett
7042356cedf8cd2ceb4b9c6f2755bfe905e94cc1
ihthisham/Jetbrains
/Zookeeper/Problems/Sum/main.py
112
3.546875
4
# put your python code here n1 = int(input()) n2 = int(input()) n3 = int(input()) Sum = n1 + n2 + n3 print(Sum)
25b51499c2d956b484168fc201981eb13f69f120
an-lam/python-class
/functions/lab3.py
205
3.71875
4
def checkIP(ipaddress) # Code to check IP address ipaddress = input("Please enter IP address") while ipaddress != 'q' valid = checkIP(ipaddress) if valid == True # ask for more info
5720948f10007c7a603c810c03746aab8c973f13
Taher-Ali/exercises_from_py4e
/add_two.py
148
3.890625
4
a = input('Enter first number:') b = input('Enter second number:') def addtwo(a,b): added = int(a)+int(b) return added x = addtwo(a,b) print(x)
984d2e575b1a5747769f68309f3544954d64d76a
zllion/ProjectEuler
/p049.py
2,177
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 4 18:56:03 2020 @author: zhixia liu """ """ Project Euler 49: Prime permutations The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? """ #%% naive bf from helper import prime_list from itertools import permutations import sys prime = prime_list(10000) def arithmseq(lst): temp = sorted(lst) for i in range(len(temp)-1): for j in range(i+1,len(temp)): dif = temp[j]-temp[i] if (temp[j]+dif) in temp: return [temp[i],temp[j],temp[j]+dif] return None result=[] skiplst = [] for i in prime: if i<1000: continue if i in skiplst: continue plst=[] for j in permutations(str(i),4): if j[0] == '0': continue j = int(''.join(j)) if j in plst: continue if prime.isPrime(j): plst.append(j) skiplst += plst if len(plst)>=3: temp = arithmseq(plst) if temp is not None: result.append(temp) print(result) #%% others def main(): from helper import prime_list def sorted(seq): seq = list(seq) seq.sort() return "".join(seq) p = prime_list(10000) pd = {} for pi in p: if pi < 1000: continue spi = sorted(str(pi)) pd.setdefault(spi, []).append(pi) for i, pi in enumerate(p): if pi < 1000 or pi == 1487: continue spi = sorted(str(pi)) pals = pd[spi] if len(pals) < 3: continue for pj in pals: if pj <= pi: continue if sorted(str(pj)) != spi: continue diff = pj - pi pk = pj+diff if pk in pals: print("%s%s%s" % (pi, pj, pk)) return main()
a9a1e1dacde8dd8fe01f964da7c8b76dfdfbce4c
InnoFang/algo-set
/LeetCode/0703. Kth Largest Element in a Stream/solution.py
617
3.625
4
""" 10 / 10 test cases passed. Status: Accepted Runtime: 88 ms """ class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.min_heap = nums heapq.heapify(self.min_heap) while len(self.min_heap) > k: heapq.heappop(self.min_heap) def add(self, val: int) -> int: heapq.heappush(self.min_heap, val) if len(self.min_heap) > self.k: heapq.heappop(self.min_heap) return self.min_heap[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
6eba03e891b9577633f9cc2952a76adfaeeb414b
LarsenClose/python-data-structures
/structures/binary_tree.py
3,291
3.828125
4
''' Description: Binary Search Tree implementation Author: Larsen Close Version: Completed through A work, revisited to work on remove() Outline and initial tests provided in class by Professor Dr. Beaty at MSU Denver ''' class BinaryTree(): """Binary tree class""" _empty = {} def __init__(self, value=None, parent=None): self.left = self.right = None self.value = self._empty self.parent = parent if value: try: for i in value: self.insert(i) except TypeError: self.insert(value) def __iter__(self): if self.left: for node in self.left: yield node yield self.value if self.right: for node in self.right: yield node def __str__(self): return ','.join(str(node) for node in self) def empty(self): """Returns true if empty""" return self.value == self._empty def insert(self, value): """Binary tree insert function""" if self.empty(): self.value = value return if value < self.value: if not self.left: self.left = BinaryTree(value, self) else: self.left.insert(value) else: if not self.right: self.right = BinaryTree(value, self) else: self.right.insert(value) def next_highest(self): next_highest = self.left while next_highest.right: next_highest = next_highest.right return next_highest def remove_both_references(self): next_highest = self.next_highest() self.remove(next_highest.value) if not self.parent: self.value = next_highest.value return next_highest.left = self.left next_highest.right = self.right self.reference_replacement(next_highest) def remove(self, value): # Base case we've found the value if self.value == value: # If no children we just have to delete the reference to self if not self.left and not self.right: self.reference_replacement(None) # If only right child then # replace the reference to self with right child elif not self.left: self.reference_replacement(self.right) # Same but left elif not self.right: self.reference_replacement(self.left) # If two children, move the next highest node to our spot # Remove it # Give it our children # Change the reference to us to be to it else: self.remove_both_references() # Recursive calls depending on value until we find the value elif self.value > value: self.left.remove(value) else: self.right.remove(value) def reference_replacement(self, new): # Checks which parent has a reference to self # replaces reference with argument if self.parent.left == self: self.parent.left = new elif self.parent.right == self: self.parent.right = new
46f686ce625ffa844a521ceca2a0c2e42a1bed5f
erjan/coding_exercises
/freedom_trail.py
2,609
3.921875
4
''' In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword. Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i]: You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i]. If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling. ''' import sys class Solution: def findRotateSteps(self, ring: str, key: str) -> int: m = len(key) n = len(ring) dp = [[sys.maxsize for i in range(n)] for j in range(m)] for i, c in enumerate(ring): if c == key[0]: dp[0][i] = min(i, n - i) for i in range(1, m): for j in range(n): if key[i] == ring[j]: for k in range(n): if key[i - 1] == ring[k]: dp[i][j] = min(dp[i][j], dp[i - 1][k] + min(abs(j - k), n - abs(j - k))) return min(dp[m - 1]) + m -------------------------------------------------------------------------------------------------------------- from collections import defaultdict from functools import cache class Solution: def findRotateSteps(self, ring: str, key: str) -> int: def distance(i, j): if j < i: i, j = j, i return min(j-i, i+len(ring)-j) # try going left or right in ring opts = defaultdict(list) for i, c in enumerate(ring): opts[c].append(i) @cache def dfs(k, i): if k == len(key): return 0 return min(distance(i, j) + 1 + dfs(k+1, j) for j in opts[key[k]]) return dfs(0, 0)
718dab5ae9d416ccfac65658f795e881f41b19b0
guymatz/edx
/mit_6.00.1x/laceRecur.py
617
4.125
4
#!/usr/bin/env python def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ # Your Code Here s1_len = len(s1) s2_len = len(s2) s3 = '' for n in range(min(s1_len, s2_len)): s3 += s1[n] + s2[n] if s1_len > s2_len: s3 += s1[len(s2):] else: s3 += s2[len(s1):] print s3 laceStrings('abcd', 'efgh') laceStrings('abcdijklm', 'efgh') laceStrings('abcd', 'efghopqrs')
df1c91fa3ab0cd8d9e9438dec4b0a781003c7259
MaaziAgwu/MaaziAgwu4
/radius.py
150
4.25
4
pi = 3.142 def areaof(): radius = float(input("Enter the radius of a circle ")) areaof = pi * radius **2 print(areaof) areaof()
2b574c9ff80762c6a72104f02056ec8a9827a1fe
ilee38/practice-python
/coding_problems/CTCI_trees_graphs/build_order.py
717
3.59375
4
#!/usr/bin/env python3 """ Problem 4.7 on CtCI book """ def make_graph(proj_list, dep_list): G = {} for i in range(len(proj_list)): G[proj_list[i]] = [] for j in range(len(dep_list)): k,v = dep_list[j] G[k].append(v) return G def order(G): visited = [] for v in G: if v not in visited: DFS_visit(G, v, visited) return reversed(visited) def DFS_visit(G, v, visited): for elem in G[v]: if elem not in visited: DFS_visit(G, elem, visited) visited.append(v) def main(): p = ['a', 'b','c', 'd', 'e', 'f'] dep = [('a','d'),('f','b'),('b','d'),('f','a'),('d','c')] g = make_graph(p, dep) ordering = order(g) for x in ordering: print(x) if __name__ == '__main__': main()
3d61e7b064ecf7d1a693264bafc2c683427e696d
Carolinegg/test-python
/JogodaVelha.py
716
3.890625
4
def greet(): enter = str(input('\nBem vindo ao jogo da velha! Vamos jogar? \nAbaixo escolha como player x ou o:')) if enter not in "x" or "o": print("Ocorreu um erro, escolha corretamente") return greet() def show_board(): board = [[0 for i in range (3)] for j in range (3)] #mostrar q os zeros sao espacos em branco e tenho q definir coluna e linha print(board) def players(): p1 = 1 p2 = 2 if p1 in show_board: print("x") if p in show_board: print("o") def start(): pass #Onde esta x nao pode o e visse versa. def win_or_stuck(): pass def main(): greet() show_board() players() start() win_or_stuck() main()
7e24470a1fb8defbcb18f173be94a3c046be726f
ivorobey/python_gl_tasks
/Practice session/Equilibrium.py
2,947
4.0625
4
# Equilibrium index of a list is such index that divides the list in two parts with the same total sum. # Here the list is A of length N and Equilibrium index is E: # A[0] + A[1] + ... + A[E−1] == A[E+1] + ... + A[N−2] + A[N−1]. # In other words: the SUM of everything PRIOR to E equals to the SUM of items AFTER. # Simple example - we have a list: a = [3, 1, 3, 2, 2]. Equilibrium index here is 2 because a[0] + a[1] == a[3] + a[4] (3 + 1 == 2 + 2). def get_equilibriums(list_): A=list_ if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there return "Empty list, no integers to work with" else: equi = [] x = 0 length = len(A) rightSum = [] leftSum = [] # while x < length: (removed) # When we do for i in A, we're already iterating over each element i of the list A. # As such, there's no need for the while loop. for i in A: # You switched right and left sum; elements at the 'left' are at the beginning of the list # I also switched the name of the lists to leftList and rightList, to be more descriptive # (a list and a sum are different things) # I switched the i that was in the indexes to x. i is the integer on the list we're iterating over; # its position on the list, on the other hand, is being counted with x. leftList = A[0:x] # Go from 0, since you want to count the first element. # We could also ommit the first index and it would begin from the first element rightList = A[x+1:] # If we ommit the second index, it'll go until the last element if sum(leftList) == sum(rightList): # I changed equi.append(i) to equi.append(x), because i is the value we're iterating over, while # x is the counter (index) of the number being currently evaluated equi.append(x) # return equi (removed) # We don't want to return here. When we call return, the function exits! # What this would do is exit the function if the sum of the left list wasn't equal to the sum of the right. # This isn't what we want, so we'll just remove this # else: (removed) # return -1 (removed) x += 1 # No pass needed; that's another thing entirely, just a nil instruction # Now the loop is done, we have appended to equi all the equilibrium values. # It's time to exit the function by returning the list of equi values. # Since we must return -1 if no equilibrium indices exist, then we have to check for that as well if len(equi) == 0: return -1 else: return equi print(get_equilibriums([-1, 3, -4, 5, 1, -6, 2, 1])) print(get_equilibriums([1, 3, 100, 2, 2]))
3a663170ca6baaa6c960c7838b448f354185d0bc
PipelineAI/pipeline
/stream/jvm/src/main/java/io/pipeline/tensorflow/consumer/src/data.py
523
3.734375
4
import os def get_data(data_directory): """ Given a string directory path, returns a list of file paths to images inside that directory. Data must be in jpeg format. Args: data_directory (str): String directory location of input data Returns: :obj:`list` of :obj:`str`: list of image file paths """ return [ data_directory + f for f in os.listdir(data_directory) if f.endswith('.jpeg') or f.endswith('.jpg') ]
f1291e0f8e978d13779f2290fbcac3fe64e50e11
dasbindus/LearnPython
/2_FuncTest/testFuc.py
353
3.90625
4
#! /usr/bin/env python # -*- coding:utf-8 -*- def age_test(): age = int(raw_input('your age is:')) if age >= 18: print 'You are a adult.\n' elif age >= 12: print 'You are a teenager.\n' else: print 'You are a kid.' def fact(n): if n == 1: return 1 return n * fact(n - 1) # ------------------------------- # age_test(); print fact(10)
850964fe73efc5f55b71e420e5669015206d5449
senapk/poo_2019_2
/s01e01_intro/intro.py
96
3.640625
4
b = 3 c = 3.4 d = "banana" print (b, c, d) v = [3, 2.3, "1", 4] for elem in v: print(elem)
b77e4b3818b9360e4e1b5c9633e0b74030e830a0
vinilinux/python-mundo01
/execicios/desafio010.py
131
3.546875
4
d = float(input('Quanto dinheiro você possui na carteira? R$ ')) us = d / 5.37 print(f'Você pode comprar US$ {us:0.2} dólares')
ca1d512b71f45134e7fdacc18e99dced20fac55f
stellel/web-caesar
/caesar.py
616
3.9375
4
import string lower = string.ascii_lowercase upper = string.ascii_uppercase def rotate_character(char, rot): rotated = "" rot = int(rot) if char in lower: rotated = lower[(alphabet_position(char) + rot) % 26] else: rotated = upper[(alphabet_position(char) + rot) % 26] return rotated def alphabet_position(letter): if letter in lower: position = lower.index(letter) else: position = upper.index(letter) return position def encrypt(text, rot): encrypted = "" for char in text: if char.isalpha(): encrypted += rotate_character(char, rot) else: encrypted += char return encrypted
5ead552bc5c70f9896755440f7ec89d02ec4d058
zonghui0228/rosalind-solutions
/code/rosalind_sort.py
5,742
3.921875
4
# ^_^ coding:utf-8 ^_^ """ Sorting by Reversals url: http://rosalind.info/problems/sort/ Given: Two permutations π and γ, each of length 10. Return: The reversal distance drev(π,γ), followed by a collection of reversals sorting π into γ. If multiple collections of such reversals exist, you may return any one. """ import random # get the all reversal array of a list "s". def _get_reverse_array(s): reverse_arrays = [] for i in range(len(s)-1): for j in range(i+1, len(s)): r_list = s[i:j+1] r_list.reverse() reverse_arrays.append(s[:i] + r_list + s[j+1:]) return reverse_arrays # get the reversal_distance from a list "s1" to another list "s2". def _get_reversal_distance(s1, s2, distance, s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals): # reverse s1 to s2, and reverse s2 to s1 at same time. if s1 & s2: return s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance # get the reveral array of s1. new_s1 = set() s1_s2 = {} for s in s1: reverse_arrays = _get_reverse_array(list(s)) s1_s2[s] = reverse_arrays for r in reverse_arrays: new_s1.add(tuple(r)) s1_s2_reversals_path.append(s1_s2) # get the reveral array of s2. new_s2 = set() s2_s1 = {} for s in s2: reverse_arrays = _get_reverse_array(list(s)) s2_s1[s] = reverse_arrays for r in reverse_arrays: new_s2.add(tuple(r)) s2_s1_reversals_path.append(s2_s1) # thus we reverse s1 and s2 at same time, so distance plus 2. distance += 2 # if s1 and the reversal array of s2 has the same array, distance substract 1. if s1 & new_s2: meet_reversals = list(s1 & new_s2) return s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance-1 # if s2 and the reversal array of s1 has the same array, distance substract 1. if s2 & new_s1: meet_reversals = list(s2 & new_s1) return s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance-1 # if reversal array of s1 and the reversal array of s2 has the same array, return distance. if new_s1 & new_s2: meet_reversals = list(new_s1 & new_s2) return s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance = _get_reversal_distance(new_s1, new_s2, distance, s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals) return s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance # get the endpoints of the interval of the two indices. def _get_invert_endpoints(a, b): a_reverse = [] for i in range(len(a)-1): for j in range(i+1, len(a)): a_reverse = a[:i] + a[i:j+1][::-1] + a[j+1:] if a_reverse == b: return i+1, j+1 # get the collections of reversals sorting π into γ def _get_collections_of_reversals_sorting(s1_s2_reversals_path, meet_reversals, s2_s1_reversals_path): collections_of_reversals_sorting = [] for l in meet_reversals: # print(l) collection_of_reversals_sorting=[] current_array = list(l) for reversals_path in s1_s2_reversals_path[::-1]: for k, v in reversals_path.items(): if current_array in v: i, j = _get_invert_endpoints(list(k), current_array) collection_of_reversals_sorting.append([i, j]) current_array = list(k) break collection_of_reversals_sorting = collection_of_reversals_sorting[::-1] current_array = list(l) for reversals_path in s2_s1_reversals_path[::-1]: for k, v in reversals_path.items(): if current_array in v: i, j = _get_invert_endpoints(list(k), current_array) collection_of_reversals_sorting.append([i, j]) current_array = list(k) break collections_of_reversals_sorting.append(collection_of_reversals_sorting) return collections_of_reversals_sorting if __name__ == "__main__": # test a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [1, 8, 9, 3, 2, 7, 6, 5, 4, 10] # load data # with open("../data/rosalind_sort.txt", "r") as f: # a = [int(i) for i in f.readline().strip().split(" ")] # b = [int(i) for i in f.readline().strip().split(" ")] # main solution distance, s1, s2 = 0, set(), set() s1.add(tuple(a)), s2.add(tuple(b)) s1_s2_reversals_path = [] # the list contains reversals path (dict) from s1 to s2. s2_s1_reversals_path = [] # the list contains reversals path (dict) from s2 to s1. meet_reversals = [] # the reversals met by s1-s2 direction and s2-s1 direction. s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals, distance = _get_reversal_distance(s1, s2, distance, s1_s2_reversals_path, s2_s1_reversals_path, meet_reversals) # 4 print("[INFO] the distance of reverse s1 to s2: {}".format(distance)) # print(s1_s2_reversals_path) # print(s2_s1_reversals_path) # print(meet_reversals) collections_of_reversals_sorting = _get_collections_of_reversals_sorting(s1_s2_reversals_path, meet_reversals, s2_s1_reversals_path) print("[INFO] the number of collections of reversals sorting π into γ: {}".format(len(collections_of_reversals_sorting))) a_collection = random.sample(collections_of_reversals_sorting, k=1)[0] print("[INFO] the reversal distance drev(π,γ): {}".format(len(a_collection))) print("A random collection of reversals sorting π into γ:") print(a_collection) print("done!")
23df01eed735e397844714af5f3383280ba5e3d3
stefifm/Guia07
/prueba_validacion.py
297
3.953125
4
print("Validación de datos") nombre = input("Ingrese un nombre: ") edad = -1 while edad < 0 or edad >= 120: edad = int(input("Ingrese su edad: ")) if edad < 0 or edad >= 120: print("Error. Se pidió que fuera > 0 y menor a 120") print("Su nombre:",nombre) print("Su edad:",edad)
5d244d71930eab8eb80ff710840f0b8c32e3418a
rohanawale/E_tax_with_MySQL
/Completed Project/fully assembled software/fg.py
1,374
3.53125
4
from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder Builder.load_string(''' <GridLayout> canvas.before: BorderImage: # BorderImage behaves like the CSS BorderImage border: 10, 10, 10, 10 source: '../examples/widgets/sequenced_images/data/images/button_white.png' pos: self.pos size: self.size <RootWidget> GridLayout: size_hint: .9, .9 pos_hint: {'center_x': .5, 'center_y': .5} rows:1 Label: text: "I don't suffer from insanity, I enjoy every minute of it" text_size: self.width-20, self.height-20 valign: 'top' Label: text: "When I was born I was so surprised; I didn't speak for a year and a half." text_size: self.width-20, self.height-20 valign: 'middle' halign: 'center' Label: text: "A consultant is someone who takes a subject you understand and makes it sound confusing" text_size: self.width-20, self.height-20 valign: 'bottom' halign: 'justify' ''') class RootWidget(FloatLayout): pass class MainApp(App): def build(self): return RootWidget() if __name__ == '__main__': MainApp().run()
caf475340f0ab67e77cce601e5f90b3f788c0510
jyoon1421/py202002
/Ch3_1.py
129
3.65625
4
size = int( input() ) numbers = list ( input() ) result = 0 for i in range(size): result += int( numbers[i] ) print (result)
d7aa917a00b2f582c7b15c8b40de0462ca274a66
theelk801/pydev-psets
/pset_classes/fromagerie/p6.py
1,200
4.125
4
""" Fromagerie VI - Record Sales """ # Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method. # The record_sale method should do the following: ### Add the sale's profits to profits_to_date attribute. ### Add the number sold to the running total in the sales attribute. ### Subtract the number sold from the stock attribute. ### Check the stock (Hint: Call the check_stock method within the record_sale method.) # Once finished, call record_sale on each sale from the sales_today dict below and print out the name of the cheese, whether it has a low stock alert, the remaining stock value, the running total of units of that cheese sold, and the running total of your profits to date. It should look something like this: """ Parmigiano reggiano - Low stock alert! Order more parmigiano reggiano now. Remaining Stock: 14 Total Sales: 10 Profits to Date: 20 """ sales_today = {provolone: 8, gorgonzola: 7, mozzarella: 25, ricotta: 5, mascarpone: 13, parmigiano_reggiano: 10, pecorino_romano: 8}
8cfcc58e57e776fa2262748b1bcbc066c52527bc
pkulkar/Leetcode
/Python Solutions/1198. Find Smallest Common Element in All Rows.py
1,461
3.984375
4
""" Given a matrix mat where every row is sorted in increasing order, return the smallest common element in all rows. If there is no common element, return -1. Example 1: Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]] Output: 5 Constraints: 1 <= mat.length, mat[i].length <= 500 1 <= mat[i][j] <= 10^4 mat[i] is sorted in increasing order. """ class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: comparision_row = mat[0] minimum_element = float("inf") for i in range(len(comparision_row)): element = comparision_row[i] count = 1 for j in range(1, len(mat)): count += self.binary_search(mat[j], element) if count == len(mat): minimum_element = min(minimum_element, element) if minimum_element == float(inf): return -1 return minimum_element def binary_search(self, arr, element): left, right = 0, len(arr) - 1 while left + 1 < right: mid = left + (right - left) // 2 if arr[mid] == element: return 1 if arr[mid] > element: right = mid - 1 if arr[mid] < element: left = mid + 1 if arr[left] == element: return 1 if arr[right] == element: return 1 return 0 """ Time Complexity: O(mnlgm) Space Complexity: O(m) """
5b333f32aaf7e59f41715f538e979ab4833843d4
rohit4242/BasicsProject
/PythonBasicsproject/faultycalculator.py
1,006
4.1875
4
# faulty calculator while True: operators = ['+', '-', '*', '/'] print(operators) print('Enter your operators') operators_input = input() if operators_input in operators: print('Enter your number:') n1 = int(input()) n2 = int(input()) if operators_input=='+': if (n1==56 and n2==9) or (n1==9 and n2==56): print(77) else: print(n1+n2) elif operators_input=='-': print(n1-n2) elif operators_input=='*': if n1==45 and n2==3 or n1==3 and n2==45: print(555) else: print(n1*n2) elif operators_input=='/': if n1==56 and n2==6 or n1==6 and n2==56: print(4) else: print(n1/n2) elif operators_input=='exit': break else: print('try again')
1f224c00bf9fe84b9d94fa793551339ba7fedec0
meshack-mbuvi/slc-17
/test.py
555
3.65625
4
import unittest from loanAmount import get_Loan_amount class calculator(unittest.TestCase): #test that function works def test_it_works(self): self.assertEquals(get_Loan_amount(100000,12,12),112000) #test for negative values def test_months_not_greater_than_12(self): self.assertTrue(get_Loan_amount(-1,12,14),msg='Amount cannot have negative value') #test for string inputs def test_string_input_not_allowed(self): self.assertTrue(get_Loan_amount('amount',12,12),msg='only number inputs are allowed') if __name__=='__main__': unittest.main()
ec8b749eefeab224e3bf6378a360692ecbd77223
SaishRedkar/HelloBoulder
/textprocessor.py
443
3.734375
4
import re """ A simple module with various Text Processing Capabilities """ class Processor: """ Class for Processing Strings """ def __init__(self, text): self.text = text def count_alpha(self): """ Count number of alphabetic characters in text :return: Number of alphabetic characters """ alpha = re.compile(r'[a-zA-Z]') return len(alpha.findall(self.text))
f4d3cecb454199128b479cad3450e88e836a6acc
sayalimore8722/Python
/Program5.py
671
4.0625
4
def delivery(ftype,quantity,km): costtillsix=9 cost=0 if ftype=='V' or 'v': if km>6: remain=km-6 partialcost=remain*6 cost=partialcost+costtillsix+(120*quantity) elif km>3: remain=km-3 partialcost=remain*3 cost=partialcost+(120*quantity) elif ftype=='N' or 'n': if km>6: remain=km-6 partialcost=remain*6 cost=partialcost+costtillsix+(150*quantity) elif km>3: remain=km-3 partialcost=remain*3 cost=(150*quantity)+partialcost return cost if __name__=='__main__': type=input('Enter food type:') quantity=input('Enter quantity:') km=input('Enter km:') amount=delivery(type,quantity,km) print amount
bae7c9f0291394f9373cde80c508257fd5f8f499
PapaGateau/Python_practicals
/093-Custom_list_class/custom_list.py
852
3.796875
4
class CustomListe(): """Custom list class with two characteristics: - Cannot append numbers - Cannot contain doubles """ def __init__(self, *args): self.valeurs = [v for v in list(args) if not isinstance(v, int)] self.remove_duplicates() def append(self, value): if isinstance(value, int): print("Vous ne pouvez pas ajouter de nombres à la liste") return False if isinstance(value, str): self.valeurs.append(value) if isinstance(value, list): self.valeurs.extend(value) self.remove_duplicates() def remove_duplicates(self): self.valeurs = sorted(list(set(self.valeurs))) # ma_liste = CustomListe("Pierre", "Julien", "Marie", "Marie", 10) # ma_liste.append(5) # ma_liste.append("Pierre") # print(ma_liste.valeurs)
d833c7d3342c1f8f52f7952164a0bedd8091a8d3
daniel-reich/ubiquitous-fiesta
/PLdJr4S9LoKHHjDJC_17.py
376
3.5
4
def identify(*cube): num_ls = [len(i) for i in cube] if max(num_ls) != len(cube): if sum(num_ls) == len(cube)*max(num_ls): return "Non-Full" else: return "Missing {}".format(len(cube)*max(num_ls)-sum(num_ls)) else: if sum(num_ls) == pow(len(cube),2): return "Full" else: return "Missing {}".format(pow(len(cube),2)-sum(num_ls))
931832eb7a9a34f6a8107ee403c52344f9ebbd67
Uthergogogo/LeetCode
/167_Two Sum II - Input array is sorted/167.py
586
3.640625
4
# One-pass Hash Table def twoSum(numbers, target): save = {} for index, elem in enumerate(numbers): need = target - elem if need in save: return [save[need], index + 1] save[elem] = index + 1 # two pointers def twoSum2(numbers, target): left, right = 0, len(numbers)-1 while left < right: if numbers[left] + numbers[right] == target: return [left+1, right+1] elif numbers[left] + numbers[right] < target: left += 1 else: right -= 1 print(twoSum2([1, 3, 4, 5, 6], 11))
e2e7b0ab65bc3870553268c3cf88719eaf746ff9
Manojna52/data-structures-with-python
/cll list.py
2,439
3.671875
4
class node: def __init__(self,item): self.item=item self.next=None class cll: def __init__(self): self.head=None def append(self,item): new_node=node(item) if not self.head: self.head=new_node new_node.next=self.head else: curr=self.head while(curr): curr=curr.next if(curr.next==self.head): break curr.next=new_node new_node.next=self.head def remove(self,value): curr=self.head prev=curr if(value==self.head.item): self.head=self.head.next curr.next=None curr=self.head while(curr): curr=curr.next if(curr.next==prev): break curr.next=self.head while(curr): if(curr.item==value): break prev=curr curr=curr.next if(curr.next==self.head): print("no element found") return prev.next=curr.next curr.next=None def remove_n(self,curr): cg=self.head prev=self.head while(cg!=curr): prev=cg cg=cg.next prev.next=curr.next cg.next=None def printv(self): curr=self.head while(curr): print(curr.item) curr=curr.next if(curr==self.head): break def lent(self): curr=self.head count=0 while(curr): curr=curr.next count=count+1 if(curr==self.head): break return count def josephus(self,value): curr=self.head while(ll.lent()!=1): i=0 while(i!=value): print(i) curr=curr.next i=i+1 ll.remove_n(curr) ll=cll() ll.append(1) ll.append(2) ll.append(3) ll.append(4) ll.append(5) ll.josephus(3) ll.printv()
d9d79e8910836623c831c337989f53a9ce4e5182
AndreyPankov89/python-glo
/lesson21/my-tester.py
5,559
3.578125
4
import random class QuestionStorage: def __init__(self,questions_list): self.questions_list = questions_list def get_all(self): return self.questions_list def append(self,question, answer): if (len(question) == 0): raise Exception('Нельзя добавлять пустой вопрос') if (not answer.isdigit()): raise Exception('Ответ должен быть числом') new_question = Question(question,answer) self.questions_list.append(new_question) def remove(self,text): index = 0 for question in self.questions_list: if (text.upper() in question.question.upper() ): break index += 1 print(f'Вы дествительно хотите удалить вопрос {self.questions_list[index].question}? (y/n) ') confirm = input() if (confirm.lower() == 'y'): self.questions_list.pop(index) class Question: def __init__(self, question,answer): self.__question = question self.__answer = answer def check_answer(self, user_answer): if (user_answer == self.__answer): return True else: return False @property def question(self): return self.__question class User: def __init__(self, user_name): self.__user_name = user_name @property def name(self): return self.__user_name class UserResultStorage: def __init__(self, user): self.__count_right_answers = 0 self.__user_name = user.name self.__result = '' def inc_right_answer(self): self.__count_right_answers += 1 def calculate_results(self, total_count): results = ['Идиот', 'Кретин', 'Дурак', 'Нормальный' ,'Талант', 'Гений'] persentage = self.__count_right_answers / total_count for i in range(6): if (persentage <= (i+1)/6): self.__result = results[i] return results[i] def string_results(self): return [self.__user_name,str(self.__count_right_answers), self.__result] @property def result(self): return self.__result @property def count_right_answers(self): return self.__count_right_answers class File_IO: def __init__(self,filename,sep): self.filename = filename self.sep = sep def __form_output_string(self, *args): return self.sep.join(args) def write(self, *args): file = open(self.filename,'a',encoding='utf-8') file.write(self.__form_output_string(*args)+'\n') file.close() def read(self): file = open(self.filename, 'r', encoding='utf-8') lines = file.readlines() file.close() return [line.strip('\n').split(self.sep) for line in lines] questions_storage = QuestionStorage([ Question('Сколько будет два плюс два умноженное на два?', 6), Question('Бревно нужно рааспилить на 10 частей, сколько нужно распилов?', 9), Question('На двух руках 10 пальшев, сколько пальцев на пяти рука?', 25), Question('Укол делают каждые полчаса, сколько нужно минут для трех уколов?', 60), Question('Пять свечей горело, две потухли, сколько осталось?', 2) ]) def generate_questions_list(count): not_using_questions = [i for i in range(count)] question_list = [] for i in range(count): while True: question_number = random.randint(0, count-1) if (question_number in not_using_questions): question_list.append(question_number) not_using_questions.remove(question_number) break return question_list def print_table(lines): print('{0:^15}|{1:^30}|{2:^30}'.format('Имя','Кол-во правильных ответов','Результат')) for line in lines: name, count, result = line print('{0:<15}|{1:^30}|{2:^30}'.format(name,count,result)) questions = questions_storage.get_all() def quiz(): questions_count = len(questions) questions_list = generate_questions_list(questions_count) result_storage = UserResultStorage(user) for i in range(questions_count): question_number = questions_list[i] print(f'Вопрос {i+1}: {questions[question_number].question}') while True: user_answer_string = input('Ваш ответ: ') if (user_answer_string.isdigit()): user_answer = int(user_answer_string) break else: print('Ответ должен быть числом') if (questions[question_number].check_answer(user_answer)): result_storage.inc_right_answer() result_storage.calculate_results(questions_count) print(f'{user.name}, Ваш результат {result_storage.result}') file.write(*result_storage.string_results()) while True: user = User(input('Как вас зовут? ')) file = File_IO('results.txt',':') quiz() continue_game = input('Начать новый опрос? (y/n) ') if (continue_game.lower() == 'y'): continue else: print_table(file.read()) break
3371ae7fa4461def9176878228214f8a1b1f0984
MatthewVaccaro/Coding-Challenges
/1-10-21/delete_nth.py
251
3.703125
4
def delete_nth(order, max_e): result = [] for i in range(len(order)): counted = result.count(order[i]) if counted != max_e: result.append(order[i]) return result print(delete_nth([20, 37, 20, 21], 1))
af9d05ca793623c109c4def9bfd9923bbf48cea9
JustinSDK/Python35Tutorial
/samples-labs-exercises/samples/CH09/collection_advanced/counter.py
306
3.78125
4
from collections import defaultdict from operator import itemgetter def count(text): counter = defaultdict(int) for c in text: counter[c] += 1 return counter.items() text = 'Your right brain has nothing left.' for c, n in sorted(count(text), key = itemgetter(0)): print(c, ':', n)
f72dd64b1ea02cdade4302d9743f1938d7c7cfb7
whglamrock/leetcode_series
/leetcode261 Graph Valid Tree.py
1,161
4.09375
4
# Typical union find solution. remember the find() and union() methods class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ if n == 0: return False if not edges: return n <= 1 # the path compression will make sure if two nodes are in the same union, the find() will output the same parent def find(x): if parent[x] != x: parent[x] = find(parent[x]) return parent[x] def union(x, y): # when we union 2 parts(each part contains a bunch of nodes) of the tree, the following line won't # update all parents of x set to find(y); # i.e., it will only compress the path in x set first then do the union parent[find(x)] = find(y) parent = range(n) for i, j in edges: x = find(i) y = find(j) # circle exists if x == y: return False union(i, j) # print parent return len(edges) == n - 1
1bb7e86a0ebda1ee1cf2059d19ae92feb66fdeba
Jeffmanjones/python-for-everybody
/10_exercise_10_2.py
854
4.09375
4
""" Exercise 10.2 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. """ name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) hours = {} for line in handle: if "From:" in line: continue elif "From" in line: tmp = line.split( ) tmp = str(tmp[5]).split(":") if tmp[0] not in hours: hours[tmp[0]] = 1 else: hours[tmp[0]]=hours.get(tmp[0],0) + 1 else: continue for k,v in sorted(hours.items()): print(k,v)
0c8c7edd23550169cc9ff92e4a3e08c3ee24ff5a
PittBuzz/Python-code-snippets
/countValleys.py
1,003
4.125
4
import unittest def countValleys(n, s): """ Given a set of steps, either up or down. Count the number of mountains (start at 0, goes up, returns to 0) and the number of valleys (start at 0, goes down, returns to 0). Input: n -- number of steps s -- string describing the steps ('U' or 'D') """ height = [0] for i in range(n): if s[i] == 'U': height.append(height[-1] + 1) elif s[i] == 'D': height.append(height[-1] - 1) zeros = [i for i, x in enumerate(height) if x == 0] valleys = 0 mountains = 0 for i in zeros: if i != 0: if height[i - 1] > 0: mountains += 1 elif height[i - 1] < 0: valleys += 1 return valleys class TestUM(unittest.TestCase): def setUp(self): pass def testCountValleys(self): self.assertEqual(countValleys(8, 'UDDDUDUU'), 1) if __name__ == '__main__': unittest.main()
87923ddb2b5def05d3d32425339d11a3b53500ab
Sebkd/Algorythm
/task6.py
720
4.15625
4
""" Задание 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. """ if __name__ == '__main__': try: number_up = int(input ('Введите номер буквы в алфавите a до z ' '(A до Z) ')) if number_up > 26 or number_up < 0: raise TypeError print(f'Ваш символ "{chr(number_up + 96)}" ') except TypeError: print('Введено число меньше 0 или более 26 английского алфавита') except ValueError: print('Вводить необходимо одно число')
1dd3f665fdddd45557edb50ea28c0fa88ffcba47
JosephLudena/python-base-08-2019
/hw3_3.py
777
4.03125
4
print("circle") def areaCircle(radio): pi=3.1416 area = pi * radio ** 2 return area radio = float(input()) if radio <= 0: print('El radio es incorrecto (<=0)') else: print(areaCircle(radio)) print("rectangle") def arearectangle(base, altura): area= altura*base return area altura=float(input()) base=float(input()) if base <= 0: print('el radio es incorecto') else: print(arearectangle(base, altura)) print("triangle") def areatriangle(lado1, lado2, lado3): s=(lado1+lado2+lado3)/2 area=float(s*(s-lado1)*(s-lado2)*(s-lado3))**(1/2) return area lado1=float(input()) lado2=float(input()) lado3=float(input()) if lado1 <= 0: print('el radio es incorecto') else: print(areatriangle(lado1,lado2,lado3))
4fa44f1dba0a8d4866a9d10a3369af96ad9bd8d7
Tsenghan/Python-study
/Class12/进制转换小程序.py
426
3.75
4
while 1: number=input('请输入一个整数:') if number == 'Q': break else: numeric = int(number) #十六进制 print('十进制-->十六进制:{0:}-->{1:#x}'.format(number,numeric)) #八进制 print('十进制-->八进制:{0:}-->{1:#o}'.format(number, numeric)) #二进制 print('十进制-->二进制:{0:}-->{1}'.format(number, bin(numeric)))
d9d33900207d3d2336e8cffec45473b72f7d1b7b
116pythonZS/YiBaiExample
/044.py
967
3.984375
4
#!/usr/bin/python # -*- coding=utf8 -*- # Created by carrot on 2017/8/28. """ 两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵: """ import random def create3Matrix(): matrix=[] for i in range(0,3): li= [] for j in range(0,3): li.append(random.randint(1,1000)) matrix.append(li) return matrix def print3Matrix(matrix): for line in matrix: print(" ".join("%4d"%(n,) for n in line)) def add3Matrix(x,y): result = [] for i in range(0,len(x)): line = x[i] sumline = [] for j in range(0, len(line)): sumline.append(x[i][j] + y[i][j]) result.append(sumline) return result def main(): X = create3Matrix() print3Matrix(X) print("+") Y = create3Matrix() print3Matrix(Y) print("=") result = add3Matrix(X,Y) print3Matrix(result) if __name__ == "__main__": main()
351bb4027887e49775c3a1c43fb0e6554ca10d1e
8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions
/Chapter03/0008_functools_lru_cache.py
1,342
4.21875
4
""" Listing 3.8 The lru_cache() decorator wraps a function in a "least recently used" cache. Arguments to the function are used to build a hash key, which is then mapped to the result. Subsequent calls with the same arguments will fetch the value from the cache instead of calling the function. The decorator also adds methods to the function to examine the state of the cache (cache_info()) and empty the cache (cache_clear()) The second time those calls are made with the same values, the results appear in the cache. When the cache is cleared and the loops are run again, the values must be recomputed """ import functools @functools.lru_cache() def expensive(a, b): print(f"expensive({a}, {b})") return a * b def main(): MAX = 2 print("First set of calls:") for i in range(MAX): for j in range(MAX): expensive(i, j) print(expensive.cache_info()) print("\nSecond set of calls:") for i in range(MAX+1): for j in range(MAX+1): expensive(i, j) print(expensive.cache_info()) print("\nClearing cache:") expensive.cache_clear() print(expensive.cache_info()) print("Third set of calls:") for i in range(MAX): for j in range(MAX): expensive(i, j) print(expensive.cache_info()) if __name__ == "__main__": main()
1a8d47a3a1f44665557418479cfd884da4e336be
hackeziah/PythonSample
/Warehouse2.py
454
3.671875
4
from tkinter import * win = Tk() win.title("Ware House") toolbar = Frame(win, bg = "cyan") insertButt=Button(toolbar,text="Insert Image", command=doNothing) insertButt.pack(side = LEFT,padx=3,pady=3) printButt=Button(toolbar,text="Print", command=doNothing) printButt.pack(side = LEFT,padx=3,pady=3) toolbar.pack(side=TOP,fill=X) status =Label(win,text="test testing...", bd=2, relief=SUNKEN,anchor=W) status.pack(side = BOTTOM,fill=X) win.mainloop()
e8dbd7145eb1e8e8e62b617437da7a1c1cab53d0
emmanguyen102/CS100
/Week6/rot13.py
1,211
4.375
4
def encrypt(char): """ Encrypts its parameter using ROT13 encryption technology. :param char: str, a character to be encrypted :return: str, <char> parameter encrypted using ROT13 """ regular_chars = ["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"] encrypted_chars = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] new_char = "" if char.lower() in regular_chars: char_index = regular_chars.index(char.lower()) new_char = encrypted_chars[char_index] if char.isupper(): return (new_char.upper()) else: return (new_char) else: return(char) def row_encryption(str): """ Perform a ROT13 transformation for an entire string :param str: str, a random string :return: str, <str> parameter encrypted using ROT13 """ new_str = "" for char in str: new_char = encrypt(char) new_str += new_char return(new_str)
730f62c2b28742f31e0c23c5c2aa0682b3286bc7
xrustle/GB_Algorithms
/01_Algorithms/HomeWork1/Alg_les1_task5.py
713
4.09375
4
# Пользователь вводит две буквы. # Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. char1 = input('Введите любую букву от a до z: ') char2 = input('Введите вторую любую букву от а до z: ') pos1 = ord(char1) - ord('a') + 1 pos2 = ord(char2) - ord('a') + 1 length = abs(pos1 - pos2) - 1 if length < 0: length = 0 print(f'{char1} - буква #{pos1} в алфавите') print(f'{char2} - буква #{pos2} в алфавите') print(f'Количество букв между заданными буквами = {length}')
15107186e824b8d92739f0d62628f3dd1a923717
Kuryashka/itstep
/lesson4/fizzerbuzzer.py
535
3.8125
4
al = [x for x in range(101) if x % 3 == 0] bl = [x for x in range(101) if x % 5 == 0] while True: try: a = int(input("Enter a number in range (1, 100): ")) if a <= 0 or a > 100: print('You entered a wrong number') continue else: break except ValueError: print("AM I A JOKE TO YOU?!") if a in al and a in bl: print('FizzBuzz') else: if a in al: print("Fizz") elif a in bl: print("Buzz") else: print()
2409baf5850cd9c66f37f8f3970931b921bae873
Wizmann/ACM-ICPC
/Codeforces/Educational Codeforces Round 39/B.py
337
3.5
4
def solve(a, b): while a and b: if a >= 2 * b: a %= 2 * b elif b >= 2 * a: b %= 2 * a else: break return (a, b) assert solve(12, 5) == (0, 1) assert solve(31, 12) == (7, 12) if __name__ == '__main__': (a, b) = solve(*map(int, raw_input().split())) print a, b
7dc9b155ecbf75c0f5342fe3293a7afa510bb42f
Ntalemarvin/python
/logical.py
689
4.0625
4
#write a code for that ''' if applicant has high income AND/OR good credit Eligible for a loan ''' has_high_income = False has_good_credit = True #and operator if has_high_income and has_good_credit: print('Eligible for a loan') #or aoperator if has_high_income or has_good_credit: print('Eligible for a loans') # AND: both true # OR: aleast one true #NOT:if true converts to false & the reverse is true ''' if applicant has enough credit and doesn',t have a criminal record Eligible for a loan ''' has_enough_credit = True has_criminal_record = False if has_enough_credit and not has_criminal_record:#has_criminal is converted to true print('Eligible for both loans')
5a9937d76f04cfb8e284cededed72236457daebc
OmarSadigli/crossing-game
/scoreboard.py
645
3.71875
4
from turtle import Turtle FONT = ("Courier", 20, "normal") class Scoreboard: def __init__(self): self.level = 1 def game_over(self): game_over = Turtle() game_over.color("black") game_over.penup() game_over.hideturtle() game_over.write("Game Over", align="center", font=FONT) def score(self): score = Turtle() score.color("black") score.penup() score.hideturtle() score.goto(-220, 260) score.write(f"Level: {self.level}", align="center", font=FONT) score.clear() def update_score(self): self.level += 1
7ceec1b01e4434f4e249bc5bf7e2026729f79a9d
ymsk-sky/atcoder
/abc141/b.py
67
3.515625
4
s=input() print('No'if 'R' in s[1::2] or 'L' in s[::2] else 'Yes')
1105cd1226012eb2d53713771e0da15ae8daaa41
arnabs542/Leetcode-38
/Python/ladder92.py
1,138
3.59375
4
class Solution: """ @param m: An integer m denotes the size of a backpack @param A: Given n items with size A[i] @return: The maximum size """ def backPack(self, m, A): # 背包问题一定用最大总承重当成其中一维 n = len(A) f = [[False] * (m + 1) for _ in range (n + 1)] f[0][0] = True for i in range(1, m): # 用数组里前0个数,能否组成i(i的范围就是从0到m) f[0][i] = False # 所以只有f[0][0]是true,其他都是false for i in range(1, n + 1): f[i][0] = True for j in range(1, m + 1): # if A[i - 1] > j: # 当前物品重量大于总重:false # f[i][j] = False # continue if A[i - 1] <= j: f[i][j] = f[i - 1][j - A[i - 1]] or f[i - 1][j] else: f[i][j] = f[i - 1][j] idx = m while idx > 0: if f[n][idx] == True: return idx idx -= 1 return idx
a13328e9385c9d0ef74875d6ba55670fbf07b6a7
maduoma/Python
/100DaysOfPythonCoding/ControlFlowAndLogicalOperators/IfStatement.py
4,463
4.28125
4
######################################### # If statement ######################################### print("Welcome to rollercoaster!") height = int(input("what is your height? ")) if height >= 120: print("You can ride coaster") else: print("You will have to grow taller to be able to ride.") print("\n") ######################################### # Challenge 3.1 : Even or Odd Number? ######################################### num = int(input("Enter a number? ")) if num % 2 == 0: print("Number entered is an even number!") else: print("Number entered is an odd number") print("\n") ######################################### # Nested if/else statement ######################################### print("Welcome to rollercoaster!") height = int(input("what is your height? ")) if height >= 120: print("You can ride coaster") age = int(input("What is your age?")) if age >= 18: print("Please pay $7") else: print("Please pay $5") else: print("You will have to grow taller to be able to ride.") print("\n") ######################################### # elif between if -- else as many as required ######################################### print("Welcome to rollercoaster!") height = int(input("what is your height? ")) if height >= 120: print("You can ride coaster") age = int(input("What is your age?")) if age < 12: print("Please pay $5") elif age <= 18: print("Please pay $7") else: print("Please pay $12") else: print("You will have to grow taller to be able to ride.") print("\n") ######################################### # Challenge 3.2 : Day 3.2 - BMI Calculator 2.0 ######################################### print("Welcome to BMI Calculator!") height = float(input("Please enter your height?\n")) weight = float(input("Please enter your weight?\n")) bmi = round(weight / (height ** 2)) # bmi = 35 if bmi < 18.5: print(f"Your bmi is {bmi}, you're underweight!") elif bmi < 25: print(f"Your bmi is {bmi}, you have a normal weight!") elif bmi < 30: print(f"Your bmi is {bmi}, you're overweight!") elif bmi < 35: print(f"Your bmi is {bmi}, you're obese!") else: print(f"Your bmi is {bmi}, you're clinically obese!") print("\n") ######################################### # Challenge 3.3 : Day 3.3 - Leap Year ######################################### print("Welcome to Leap Year Challenge!") year = int(input("Which year do you want to check? ")) if year % 4 == 0: print(f"{year} is leap year.") elif year % 100 == 0: print(f"{year} is not leap year.") elif year % 400 == 0: print(f"{year} is leap year.") else: print(f"{year} is not leap year.") print("\n") # import calendar # print(calendar.isleap(1900)) # ========================================= # OR # ======================================== print("Welcome to Leap Year Challenge!") year = int(input("Which year do you want to check? ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(f"{year} is leap year!") else: print(f"{year} is not leap year!") else: print(f"{year} is leap year!") else: print(f"{year} is not leap year!") print("\n") # ========================================= # OR # ======================================== year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) print("\n") # print(float("123,456.908".replace(",", ""))) ######################################### # Multiple If Statements in succession ######################################### print("Welcome to rollercoaster Version 2.!") height = int(input("what is your height? ")) bill = 0 if height >= 120: print("You can ride coaster") age = int(input("What is your age? ")) if age < 12: bill = 5 print("Please pay $5") elif age <= 18: bill = 7 print("Please pay $7") else: bill = 12 print("Please pay $12") wants_photo = input("Do you want photo? Y or N ") if wants_photo == "Y".lower(): bill += 3 print(f"Your final bill is ${bill}.") else: print("Sorry, you will have to grow taller to be able to ride.") print("\n")
b71813b151e26c86e4c33d9199151c72431ed34d
csundara/CSE107
/inclass/car.py
354
4.09375
4
car_speed = int(input('Please enter the speed: ')) if car_speed > 55: print("The police are here") print("You get a ticket ^_^") elif car_speed > 45: print("The police are here") print("You get a warning. Do not over speed again`") else: print("You are safe this timeself.") print("I'm still watching you") print("End Program")
2dcbe08250fd9e217e11912cf355412b912eb314
Ranjana151/python_programming_pratice
/elementsquare.py
299
3.953125
4
#list of first and last 5 element and values are square of number between(1,30) lis=input("Enter the numbers sepeated by space") lis1=list(map(int,lis.split())) number=[] for i in range(1,31): x=i*i number.append(x) print("Numbers are",number[0:5]) print("Numbers are",number[-5:-1])
fe8fd816527fc24638b9e3cd5c99620dd9e797b0
gouwangrigou/Python-Machine-Learning-and-Practice-Kaggle-
/Python Machine Learning and Practice(Kaggle)/chapter_2/code_29.py
2,902
4.125
4
# coding=utf-8 # 决策树分类-预测泰坦尼克号乘客生还情况 # 导入pandas用于数据分析。 import pandas as pd # 利用pandas的read_csv模块直接从互联网收集泰坦尼克号乘客数据。 titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt') # 观察一下前几行数据,可以发现,数据种类各异,数值型、类别型,甚至还有缺失数据。 print(titanic.head()) # 使用pandas,数据都转入pandas独有的dataframe格式(二维数据表格),直接使用info(),查看数据的统计特性。 print(titanic.info()) # 机器学习有一个不太被初学者重视,并且耗时,但是十分重要的一环,特征的选择,这个需要基于一些背景知识。根据我们对这场事故的了解,sex, age, pclass这些都很有可能是决定幸免与否的关键因素。 X = titanic[['pclass', 'age', 'sex']] y = titanic['survived'] # 对当前选择的特征进行探查。 print(X.info()) # 借由上面的输出,我们设计如下几个数据处理的任务: # 1) age这个数据列,只有633个,需要补完。 # 2) sex 与 pclass两个数据列的值都是类别型的,需要转化为数值特征,用0/1代替。 # 首先我们补充age里的数据,使用平均数或者中位数都是对模型偏离造成最小影响的策略。 X['age'].fillna(X['age'].mean(), inplace=True) # 对补完的数据重新探查。 X.info() # 由此得知,age特征得到了补完。 # 数据分割。 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state = 33) # 我们使用scikit-learn.feature_extraction中的特征转换器,详见3.1.1.1特征抽取。 from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) # 转换特征后,我们发现凡是类别型的特征都单独剥离出来,独成一列特征,数值型的则保持不变。 X_train = vec.fit_transform(X_train.to_dict(orient='record')) print(vec.feature_names_) # 同样需要对测试数据的特征进行转换。 X_test = vec.transform(X_test.to_dict(orient='record')) # 从sklearn.tree中导入决策树分类器。 from sklearn.tree import DecisionTreeClassifier # 使用默认配置初始化决策树分类器。 dtc = DecisionTreeClassifier() # 使用分割到的训练数据进行模型学习。 dtc.fit(X_train, y_train) # 用训练好的决策树模型对测试特征数据进行预测。 y_predict = dtc.predict(X_test) # 从sklearn.metrics导入classification_report。 from sklearn.metrics import classification_report # 输出预测准确性。 print(dtc.score(X_test, y_test)) # 输出更加详细的分类性能。 print(classification_report(y_predict, y_test, target_names = ['died', 'survived']))
bd471ae1e9968d8055a3c6486f2ba1d2e51ad717
panda002/Python-Beginner
/MesoJarvis/Pallindrome.py
404
4.09375
4
num = str(input('enter a number : ')) print('the number entered is - ', num) # print (len(num)) j = len(num) # a= (list(range(j-1,-1,-1))) # print (a) for i in (list(range(j - 1, -1, -1))): num2 = num[i] print(num2) for a in (list(range(0, j))): num3 = num[a] print("reverse is : ", num[a]) if num3 == num2: print('Number is Pallindrome') else: print('Number is NOT Pallindrome')
e0685e8a8e9a5a3ab957ddad365d0e9c43cfa772
pmukwende/Final-Project
/Project.py
1,619
3.625
4
import csv import matplotlib.pyplot as plt import pandas as pd def processdatafiles(): filename = 'bostoncrime2021_7000_sample.csv' with open(filename) as f: reader = csv.reader(f) incidentlist=list(reader) f.close() filename = 'BostonPoliceDistricts.csv' with open(filename) as f: reader = csv.reader(f) districtList = list(reader) f.close() return incidentlist, districtList def barchart (incidentlist, districtlist): x=[] y=[] district = {} districtcode = [] count = 0 for row in districtlist: count+=1 if count != 1: district[row[0]]=row[1] districtcode.append(row[0]) for dist in districtcode: count =0 for row in incidentlist: if row[4] == dist: count+=1 x.append(district[dist]) y.append(count) plt.bar(x, y, color = 'r', width = 0.72, label = 'Crimes') plt.xlabel('Districts', labelpad=30) plt.ylabel('Incidents') plt.title('Number of Incidents by District') plt.legend() plt.show() def main(): MENU = """ 2 - See sample Data Q - Quit """ done = False while not done: valid = False while not valid: print(MENU) choice = input("Enter your choice: ") if choice not in "2Q": print("Try again") else: valid = True if choice == "2": barchart (incidentlist, districtlist) else: #print(choice) done = True main()
87a497f19c5ae0a7e727ed568ba6e8cf0a79f6dc
aswinrprasad/Python-Code
/CODED.py/TypeCasting.py
222
4.25
4
#Program to read an integer and a character representing an integer and to print their sum. x=int(input("Enter an integer number :")) ys=str(input("Enter a number as string :")) print "The sum of the two is :",x+int(ys)
a9373a59f6efc0ff055274757582665483b9c618
patelpriyank/LearnPythonHardWay
/LearnPythonHardWay/Exercise9_PrintingPrintingPrinting.py
422
3.75
4
days = "mon tues wed thrs fri sat sun" months = "jan\nfeb\nmar\napr\nmay\njun\njuly\naug\nsep\noct\nnov\ndec" print("here are the days:", days) print("here are the months:", months) print(""" there is something going on here. with three double quotes, we will be able to type as much as we like even 4 lines if we want, or 5, or 6 """) while True: for i in ["/", "-", "|", "\\", "|"]: print("%s\r" %i),
16f52c355a9721d5ea2cd82e984e8dfa8c75c635
Saquib472/Innomatics-Tasks
/Task 3(Python Maths)/02_FindAngle_MBC.py
374
4.03125
4
# Task_3 Q_2: # You are given the lengths AB and BC. # Your task is to find THE ANGLE OF MBC in degrees. # Input Format # The first line contains the length of side AB. # The second line contains the length of side BC. import math a = int(input()) b = int(input()) M = math.sqrt(a**2+b**2) theta = math.acos(b/M ) print(str(round(math.degrees(theta)))+ '\N{DEGREE SIGN}')
0a197b166e48b432ae951a8d21eacf65c0acbf1a
shchukinde/basic_python
/lesson_3/task3.3.py
633
4.21875
4
# Реализовать функцию my_func(), которая принимает три позиционных аргумента, и # возвращает сумму наибольших двух аргументов. def my_func(x, y, z): my_list = [x, y, z] my_list.sort() return my_list[1]+my_list[2] number_x = int(input('Введите первое число:')) number_y = int(input('Введите второе число:')) number_z = int(input('Введите третье число:')) print("Сумма двух наибольших чисел равна: ", my_func(number_x, number_y, number_z))
d954c4a82d03bb04604e78b48e43504363c6d5d6
XyK0907/for_work
/LeetCode/Array/283_move_zeros.py
1,563
3.8125
4
class Solution(object): def moveZeroes(self, nums): """ time O(n) space O(1) :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ slow = 0 while slow < len(nums) and nums[slow] != 0: slow += 1 fast = slow + 1 while fast < len(nums): if nums[fast]: nums[slow], nums[fast] = nums[fast], 0 slow += 1 fast += 1 return nums def moveZeroes_precisetomine(self, nums): """ time O(n) space O(1) :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ tail = 0 for i in range(len(nums)): if nums[i] !=0: nums[tail],nums[i] = nums[i],nums[tail] tail += 1 return nums def moveZeroes_snowball(self, nums): """ time O(n) space O(1) :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ snowballsize = 0 for i in range(len(nums)): if nums[i] == 0: snowballsize += 1 elif snowballsize > 0: nums[i - snowballsize], nums[i] = nums[i], 0 return nums if __name__ == '__main__': solution = Solution() # print(solution.moveZeroes([0,1,0,3,12, 0,0, 5])) print(solution.moveZeroes([1])) # solution.cool_moveZeroes([0,1,0,3,12, 0,0, 5])
52591c237c33188ea405274a6e67d1a3da43e973
timlyo/Year2_programming
/W1_isSubString.py
600
3.625
4
"""Pseudocode for i in string1 if (string1[i] == string2[0]) for j string2 if (string1[iPos + jPos] != string2[j]) break else return True return False """ class Week1: @staticmethod def isSubStringEasyVersion(string1, string2): """sane version""" return string2 in string1 @staticmethod def isSubString(string1, string2): """checks if string 1 is a substring of string 2""" for i in range(len(string1)): if string1[i] == string2[0]: for j in range(len(string2)): if string1[i + j] != string2[j]: break else: return True return False
6bf48f8627cf0649babd66bd33f33821e666971c
GarrettMatthews/Personal_Projects
/DND/items.py
3,377
3.5625
4
""" Returns a randomly generated item that can be magical and/or cursed Garrett Matthews """ import random as rdm class Item: def __init__(self, magical = None, cursed = None): self.adjective = '' self.item_type = '' self.value = '' self.magical = magical self.cursed = cursed self.jewel = '' self.material = '' self.mgc = '' self.crs = '' def description(self): """Returns an adjective for an item""" colors = ["red", "green", "blue", "orange", "purple", "white", "black", "teal", "yellow", "gray"] shades = ["light", '', "dark", "metallic", "matte", "mottled"] jewels = ['diamond', 'ruby', 'sapphire', 'emerald', 'amethyst', 'opal', 'amber', 'topaz', 'lapis lazuli', 'garnet', 'turquoise', 'pearl', 'quartz', 'jade'] materials = ['iron', 'steel', 'wood', 'gold', 'silver', 'brass', 'copper', 'platinum', 'glass'] affixed = ['encrusted', 'inlaid'] color = rdm.choice(colors) if color in ['white', 'black']: shades = ['', "metallic", "matte", "mottled"] shade = rdm.choice(shades) else: shade = rdm.choice(shades) gem = rdm.random() if gem >= 0.75: self.jewel = rdm.choice(jewels) self.jewel += ' ' + rdm.choice(affixed) self.material += rdm.choice(materials) self.adjective = shade + ' ' + color + ' ' + self.jewel def item(self): """Returns a randomly chosen item type""" types = ['staff', 'cup', 'chalice', 'plate', 'crown', 'wand', 'sword', 'shield', 'armor', 'knife', 'weapon', 'ring', 'amulet', 'bracer', 'bracelet', 'boots', 'mirror'] self.item_type = rdm.choice(types) def item_value(self): """Returns a randomly generated value""" value = rdm.randrange(5, 2500, 5) if self.jewel == '': coin = rdm.choice(['cp', 'cp', 'cp', 'sp', 'sp', 'gp']) else: coin = rdm.choice(['sp', 'gp', 'gp', 'gp', 'pp']) if self.material == "platinum": coin = 'pp' elif self.material == "gold": coin = rdm.choice(['gp', 'pp']) elif self.material == "silver": coin = rdm.choice(['sp', 'gp']) elif self.material in ['copper', 'brass']: coin = rdm.choice(['cp', 'sp']) self.value = str(value) + ' ' + coin def magic(self): """Randomly chooses a mild magic affect""" pass def curse(self): """Randomly chooses a curse""" pass def main(self): """Runs the item program, and returns a string containing the item and description""" self.description() self.item() self.item_value() mgc = rdm.random() if mgc > .50: self.magic() if mgc > .85: self.curse() item = "a " + self.adjective + ' ' + self.item_type + ' made of ' + self.material + ' worth ' + self.value if self.mgc != '': item += self.mgc if self.crs != '': item += self.crs return item def __str__(self): item = self.main() prompt = "Item prompt: " prompt += item return prompt def main(): item = Item() print(item) if __name__ == "__main__": main()
7906f9cc6a27bb9605b3a1e2b2c516024709379a
YingjingLu/Cai-Ji
/451/2dp_graph.py
2,963
4
4
""" Represent graph as 2d adjacency matrix for n vertex n x n adjacency matrix with weight, edge has non-negative weights """ INT_MAX = 2**31 - 1 """ Dijkstra’s Algorithm Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Starting from one of the vertex, and propagate to all the reachable vertex In case to find a specific vertex, stop when finding the target node Does not work when the graph has negative weight """ def dijkstras_algorithm( g, src ): """ Args: g: n x n adjacency matrix src <int>: index of the src node return: The weights to reach each vertex The previous node to travel to each vertex """ num_node = len( g ) total_weights = [ INT_MAX for _ in range( num_node ) ] total_weights[ src ] = 0 predecessor = [ None for _ in range( num_node ) ] visited = [ False for _ in range( num_node ) ] queue = set() queue.add( src ) while len( queue ) != 0: # find the q that has the min distance cur_node = None cur_dist = INT_MAX for node in queue: if cur_node is None: cur_node = node cur_dist = total_weights[ node ] else: if total_weights[ node ] < cur_dist: cur_node = node cur_dist = total_weights[ node ] # propagate the weight sum vertex = cur_node queue.remove( cur_node ) visited[ vertex ] = True cur_weight = total_weights[ vertex ] for i in range( num_node ): # if there is an edge if g[ vertex ][ i ] != 0 and visited[ i ] == False: queue.add( i ) new_weight = cur_weight + g[ vertex ][ i ] if new_weight < total_weights[ i ]: predecessor[ i ] = vertex total_weights[ i ] = new_weight return total_weights, predecessor """ Bellman-Ford algorithm """ def bellman_ford( num_vertex, edges, src ): """ Args: num_vertex <int>: number of vertex edges <list>: a list of vertex index ( src, target, weight ) src <int>: the index of the source vertex """ path_weight = [ INT_MAX for _ in range( num_vertex ) ] predecrssor = [ None for _ in range( num_vertex ) ] path_weight[ src ] = 0 for _ in range( num_vertex ): for src, tar, weight in edges: if path_weight[ src ] + weight < path_weight[ tar ]: path_weight[ tar ] = path_weight[ src ] + weight predecrssor[ tar ] = src # check for negative loop: for src, tar, weight in edges: if path_weight[ src ] + weight < path_weight[ tar ]: RuntimeError( " negative weight cycle detected " ) return path_weight, predecrssor """ All Pair shortest path """ """ Traveling Sales Person """
6695ed57e186401c1b8b182e37471d6115fb43b1
a7r3/CollegeStuffs
/OSTL/monthByNumber.py
1,026
4.34375
4
# Creating a dictionary of Months # Key - Month name # Value - The Month sequence number # String containing three-lettered months, splitted by space monthStr = "jan feb mar apr may jun jul aug sep oct nov dec" # Breaking down the string into multiple strings (list), with the # specified breaking point (delimiter they said) monthList = monthStr.split(" ") # Creating an Empty Dictionary monthDict = {} # Making the dictionary useful for i in range(len(monthList)): # Creating key-value pair in monthDict # monthList[i] - Three lettered Month - Key # i + 1 - Month Sequence number - Value monthDict[monthList[i]] = i + 1 # DEBUG eet # print(monthDict) # Ask the user to enter a month monthUser = input("Enter a month (spell properly pls)\n") # Convert the month string provided by user # 1. To lowercase # 2. Get the string from index 0 to 2 monthUser = monthUser.lower()[0:3] # Print the Month number # Not put conditions for wrong three-lettered month, for now print("Month Sequence > %d"%monthDict[monthUser])
7a2f16af5e4ae88b5c4eebf19118de499197554e
PriscylaSantos/estudosPython
/TutorialPoint/03 - Decision Making/2 - IF..ELIF..ELSEStatements.py
898
4.21875
4
#!/usr/bin/python3 #An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. # if expression: # statement(s) # else: # statement(s) # amount = int(input("Enter amount: ")) #Ex: 466 if amount < 1000: discount = amount * 0.05 print("Discount", discount) else: discount = amount * 0.10 print("Discount", discount) print("Net payable:", amount - discount) print("***********") # if expression1: # statement(s) # elif expression2: # statement(s) # elif expression3: # statement(s) # else: # statement(s) amount=int(input("Enter amount: ")) #Ex: 790 if amount<1000: discount=amount*0.05 print ("Discount",discount) elif amount<5000: discount=amount*0.10 print ("Discount",discount) else: discount=amount*0.15 print ("Discount",discount) print ("Net payable:",amount-discount)
baa2c2ee7ef5e10e8c83034de6fb6faea29fd778
rmoore2738/CS313e
/strings.py
2,439
4.28125
4
# File: strings.py # Description: Implements three functions that use # and manipulate strings. # Assignment Number: 8 # # Name: Rebecca Moore # EID: rrm2738 # Email: rebeccamoore32@utexas.edu # Grader: Skyler # # On my honor, Rebecca Moore, this programming assignment is my own work # and I have not provided this code to any other students. # s1 and s2 shall be strings. This function returns the number of chars # in s1 and s2 that match based on position. def num_chars_same(s1, s2): count = 0 for i in range(min(len(s1), len(s2))): if s1[i] == s2[i]: count += 1 return count # s1 shall be a string and num shall be an integer >= 0. # The function returns a stretched version of s1 with each # character repeated. The number of repitions is num times # the position of that character if we were to use 1 based indexing. def stretch(s1, num): result = '' for i in range(len(s1)): num_reps = num * (i + 1) for j in range(num_reps): result = result + s1[i] return result # s1 and s2 shall be strings. # The method returns the number of characters at the end of # s1 and s2 that match. Stops at the first mistmatched character. def length_of_matching_suffix(s1, s2): count = 0 index = -1 while abs(index) <= min(len(s1), len(s2)) and s1[index] == s2[index]: count += 1 index -= 1 return count # Run tests on the functions. Ask the user for input. def main(): num_tests = eval(input('Enter the number of tests per method: ')) print('Testing num chars same function.') test_functions_with_two_string_parameters(num_tests, num_chars_same) print('Testing stretch function.') stretch_tests(num_tests) print('Testing length of matching suffix function.') test_functions_with_two_string_parameters(num_tests, length_of_matching_suffix) # Test the functions that take 2 String parameters. def test_functions_with_two_string_parameters(num_tests, function_to_test): for i in range(0, num_tests): s1 = input('Enter first string: ') s2 = input('Enter second string: ') print(function_to_test(s1, s2)) print() # Test the stretch function. def stretch_tests(num_tests): for i in range(0, num_tests): s1 = input('Enter the string: ') num = eval(input('Enter number of times to repeat: ')) print(stretch(s1, num)) print() main()
83e809c8500adce0f37fa93af8e7cb697c967641
arcaputo3/algorithms
/simulations/quant_sims.py
1,918
3.6875
4
""" Simulating various expectations. """ import numpy as np def throw(iters=10000): """ Calculating expected number of die throws such that each side has shown up at least once. """ count = 0 for _ in range(iters): seen = set() while len(seen) < 6: count += 1 seen.add(np.random.randint(6)) return count/iters print(f"Expected number of times needed to throw a die until all sides seen is roughly {throw()}") def dist_btw_unif(iters=10000): d = 0 for _ in range(iters): x, y = np.random.rand(), np.random.rand() x, y = min(x, y), max(x, y) d += max(x, y-x, 1-y) return d/iters print(f"Expected length of longest side of stick after it is broken into three parts is roughly {dist_btw_unif()}") def halve_integers(n=1000, iters=5000): count = 0 for _ in range(iters): m = n while m > 0: m = np.random.randint(m) count += 1 return count/iters print(halve_integers(), sum(1/i for i in range(1, 1000))) def digit_prod_sum(n=10000): ss = 0 for i in range(n): prod = 1 for v in str(i): prod *= 1 if v == '0' else int(v) ss += prod return ss print(digit_prod_sum()) def coin_gamble(iters=100): total = 0 for _ in range(iters): curr = 0 H, T = 0, 0 while H < 2 or T < 2: curr += 1 if (H >= 2 and T == 1) or (H == 1 and T >= 2): total += curr break c1, c2 = np.random.rand(), np.random.rand() #if (c1 < 1/2 and c2 > 1/2) or (c1 > 1/2 and c2 < 1/2): #break if c1 > 1/2 and c2 > 1/2: T += 2 elif c1 < 1/2 and c2 < 1/2: H += 2 else: H += 1 T += 1 return total / iters print(coin_gamble())
da2a73208a291eaf5daf5573468aaaf9deecce8d
jpmolden/python3-deep-dive-udemy
/section9_ModulesPackagesNamespaces/_129_modules.py
3,142
4.09375
4
# What is a module def func(): a = 10 return a print(func) # Fun is found in the namespace print(globals()) print(locals()) # In the global scope is the local and global scope the same print(f'\tIs the local == gloabl : {locals() == globals()}') print(globals()['func']) f = globals()['func'] print(f is func) print(f()) # a = 100 print(f"The globals contains, a = {globals()['a']}") def func(): a = 10 b = 10 print(f'The function func has locals : {locals()}') func() # # # # What is a module? print(f"\n\n{'*' * 10} What is a module {'*' * 10}") import math # There is a difference between the builtin and the std library functions # The builtins are written in c print(math) import fractions print(fractions) junk = math # The junk label points to the same object print(junk.sqrt(2)) print(globals()['math']) mod_math = globals()['math'] print(mod_math.sqrt(2)) # Using maths looks in the globals dict # When we import it gets loaded into the globals dict print(type(mod_math)) print(type(math)) print(type(fractions)) # If we import again it does not reload the module import math # The reference is added to the globals dict and the system cache import sys print(sys.modules) # This dict contains the module symbol and where it's loaded in memory print(type(sys.modules)) print(sys.modules['math']) # Importing math again from another module it will look inside sys modules and find it # # Introspection print(f"\n\n{'*' * 10} Introspection of a module {'*' * 10}") import math # Print all the attributes in the math module print(math.__dict__) f = math.__dict__['sqrt'] print(f(20)) print(f'\tThe __package__') print(f'\tThe ModuleSpac: Metadata about the object') # # print(f"\n\n{'*' * 10} Introspection of a module written in C {'*' * 10}") import fractions # The fraction.py code has a location print(sys.modules['fractions']) print(dir(fractions)) from pprint import pprint print("\n") pprint(fractions.__dict__) # __file__ where the file is located print(fractions.__dict__['__file__']) # Modules are loaded from a file, are a module type, have a namespace and are a container of global variables # Modules have an execution environment (can run code inside) # There does the module type live import types print(f"\tIs fractions a module type: {isinstance(fractions, types.ModuleType)}") # We can create our own module type mod = types.ModuleType("test", "This is a test module") print(f"\tis mod an instance of the module types: {isinstance(mod, types.ModuleType)}") pprint(mod.__dict__) # How do we add functionality mod.pi = 3.14 mod.hello = lambda: "Hello!" print(mod.__dict__) print(mod.hello()) # Mod is not in the globals print('mod' in globals()) # hello = mod.hello print('hello' in globals()) hello() print(f"\n\n{'*' * 10} Introspection of a module written in C {'*' * 10}") from collections import namedtuple mod.Point = namedtuple("Point", 'x y') p1 = mod.Point(1,1) print(dir(mod)) # A module is just another type of object # Another way PT = getattr(mod, "Point") print(PT(10, 20)) # The same as PT = mod.__dict__['Point'] print(PT(10, 20)) # The namespaces are those dictionaries
0913258895e7bf47438078579e9adaaa193ed854
Rohit-dev-coder/MyPythonCodes
/upperorlowerletter1.py
203
4.21875
4
ch = ord(input("Enter A character: ")) if ch>=65 and ch<=90 : print("uppercase") elif ch>=97 and ch<=122 : print("Lowercase") elif ch>=48 and ch<=57 : print("Number") else: print("Special character")
00b871ac236b8cf37bc3f877a79ecbfed0135e29
jillnguyen/Python-Stack
/Fundamentals/compare-list.py
645
3.953125
4
def compare_list(list1, list2): if len(list1) != len(list2): print(list1, list2, "Two list are not the same") else: my_comparison = True idx = len(list1) for i in range (0, idx): if not list1[i] == list2[i]: my_comparison = False if my_comparison == False: print(list1, list2, "Two lists are of similar length but not the same") else: print(list1, list2,"Two list are identical") a = [1,2,3,4,5] b = [1,2,3,4,5] c = ["hello", "how", 1, 2, 3] d = [1,2,3] compare_list(a,b) compare_list(a,c) compare_list(a,d)
8f1d004e08192779dc1eb996cd12f251bbbe0887
daanyaalkapadia/basic-college-management-with-python
/removeCollege.py
627
3.96875
4
import csv def remove(): lines = list() flag = False rmCollegeId= input("Please enter a College Id to be deleted:") with open('colleges.csv', 'r') as readFile: reader = csv.reader(readFile) for row in reader: lines.append(row) for field in row: if field == rmCollegeId: lines.remove(row) flag = True with open('colleges.csv', 'w', newline='') as writeFile: writer = csv.writer(writeFile) writer.writerows(lines) if(flag == True): print('College with {} removed succesfully'.format(rmCollegeId)) else: print('No college exist with {} as a collegeId'.format(rmCollegeId))
2eccca1fbad0a290da226313231b8d0ef671604e
PrashantRaghav8920/GUVI_PROGRAM
/SET9/iso.py
212
3.53125
4
l=[] s=input() l.append(s) while s!="": s=input() if s!="": l.append(s) for i in l: s=set(i) if len(s)<len(i): print("No") if len(s)==len(i): print("Yes")
99588420df65f613d3e7564792302b6734026766
EngCheeChing/Portfolio
/Data Analyst Nanodegree/Data Wrangling with Python - Open Street Maps/audit_street_types.py
2,452
3.765625
4
""" Your task in this exercise has two steps: - audit the OSMFILE and change the variable 'mapping' to reflect the changes needed to fix the unexpected street types to the appropriate ones in the expected list. You have to add mappings only for the actual problems you find in this OSMFILE, not a generalized solution, since that may and will depend on the particular area you are auditing. - write the update_name function, to actually fix the street name. The function takes a string with street name as an argument and should return the fixed name We have provided a simple test so that you see what exactly is expected """ import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint import mappings osmfile = "cleveland_ohio.xml" street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) expected = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road", "Trail", "Parkway", "Commons"] def audit_street_type(street_types, street_name): # Check to make sure there are no unexpected characters in the street name m = street_type_re.search(street_name) if m: street_type = m.group() if street_type not in expected: # Add the non-standard street names to a set within a dictionary street_types[street_type].add(street_name) # Check if the tag refers to a street name def is_street_name(elem): return (elem.attrib['k'] == "addr:street") def audit(osmfile): osm_file = open(osmfile, "rb") street_types = defaultdict(set) for event, elem in ET.iterparse(osm_file): if elem.tag == "node" or elem.tag == "way": for tag in elem.iter("tag"): if is_street_name(tag): #Check to see if the tag contains a street name audit_street_type(street_types, tag.attrib['v']) # Find the problematic street names osm_file.close() return street_types street_mapping = mappings.street_mapping def clean(name): name = name.split(" ") if name[-1] in street_mapping: name[-1] = street_mapping[name[-1]] name = ' '.join(name) return name count_dict = {} ''' if __name__ == '__main__': street_types = audit(osmfile) for street in street_types: count_dict[street] = len(street_types[street]) ''' for street in mappings.street_mapping: print("{} --> {}".format(street, street_mapping[street]))
38e063dafb381eb1f3428d09ee5fc84186ebe3ea
SOURADEEP-DONNY/WORKING-WITH-PYTHON
/Dictionary Comprehensions/1.py
157
3.96875
4
dict1={} for i in range(11): dict1[i]=i**2 print(dict1) # the code using dictionary comprehension dict2={n:n*n for n in range(11)} print(dict2)
bbdbd3072a1c054b6333421a0b85df2127693e5a
sam-evans/Python-Projects
/Chaos game version 1.py
3,315
3.515625
4
################################################################################################################################################## #Name:Sam Evans #Date:3/28/20 #Description:Chaos Game (Sierpinski Triangle) ################################################################################################################################################## from Tkinter import * from random import randint #2D Point class class Point(object): def __init__ (self, x = 0.0, y = 0.0): self.x = x self.y = y #Decorators @property def x(self): return self._x @x.setter def x(self, value): self._x = value @property def y(self): return self._y @y.setter def y(self, value): self._y = value #Distance Formula def dist(self, other): delta_x = (self._x) - (other._x) delta_y = (self._y) - (other._y) return (delta_x ** 2 + delta_y ** 2) ** 0.5 #Midpoint formula def midpt(self, other): x_co = (self._x + other._x)/2 y_co = (self._y + other._y)/2 return Point(x_co, y_co) #Magic string function def __str__(self): return ("({}), ({})").format(self.x, self.y) # the coordinate system class: (0,0) is in the top-left corner # inherits from the Canvas class of Tkinter class ChaosGame(Canvas): POINT_COLOR = ["red", "black"] POINT_RADIUS = [0, 2] def __init__(self, master): Canvas.__init__(self, master, bg = "white") self.pack(fill = BOTH, expand = 1) def plotPoints(self, n): #initial vertices vertices = [Point(MIN_X, MAX_Y), Point(MAX_X, MAX_Y), Point(MID_X, MIN_Y)] points = [] #plots the 3 vertices in vertices list for i in(vertices): self.plot2(i) #calculates the midpont of the 3 vertices midpt = vertices[0].midpt(vertices[1]) points.append(midpt) self.plot(midpt) #calculates the midpoint of random vertices and plots for i in range (n): midpt2 = points[-1].midpt(vertices[randint(0,(len(vertices)-1))]) points.append(midpt2) self.plot(midpt2) def plot(self, other): #color points black with a Radius of 0 color = self.POINT_COLOR[1] self.create_oval(other.x, other.y, other.x + self.POINT_RADIUS[0] * 2, other.y + self.POINT_RADIUS[0] * 2, outline=color, fill=color) def plot2(self, other): #color points red with Radius of 2 color = self.POINT_COLOR[0] self.create_oval(other.x, other.y, other.x + self.POINT_RADIUS[1] * 2, other.y + self.POINT_RADIUS[1] * 2, outline=color, fill=color) ####################################B###################################################################################################### #main #window size WIDTH = 600 HEIGHT = 520 #number of points NUM_POINTS = 50000 # Min, Mid, and Max x & y values MIN_X = 5 MAX_X = 595 MIN_Y = 5 MAX_Y = 515 MID_X = (MIN_X + MAX_X)/2 #tk window window = Tk() window.geometry("{}x{}".format(WIDTH,HEIGHT)) s = ChaosGame(window) s.plotPoints(NUM_POINTS) window.mainloop()
65f9c08ac828a130db42ed202b63884d1755de1f
swang2000/DP
/Knapsack.py
2,488
3.984375
4
''' Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) 3.3 Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property). knapsack-problem Recommended: Please solve it on “PRACTICE” first, before moving on to the solution. A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset. 1) Optimal Substructure: To consider all subsets of items, there can be two cases for every item: (1) the item is included in the optimal subset, (2) not included in the optimal set. Therefore, the maximum value that can be obtained from n items is max of following two values. 1) Maximum value obtained by n-1 items and W weight (excluding nth item). 2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item). If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the only possibility. 2) Overlapping Subproblems Following is recursive implementation that simply follows the recursive structure mentioned above. ''' # A naive recursive implementation of 0-1 Knapsack Problem # Returns the maximum value that can be put in a knapsack of # capacity W def knapSack(W , wt , val , n): # Base Case if n == 0 or W == 0 : return 0 # If weight of the nth item is more than Knapsack of capacity # W, then this item cannot be included in the optimal solution if (wt[ n -1] > W): return knapSack(W , wt , val , n- 1) # return the maximum of two cases: # (1) nth item included # (2) not included else: return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)) # end of function knapSack # To test above function val = [60, 100, 120] wt = [10, 20, 30] W = 50 n = len(val) print knapSack(W, wt, val, n) # This code is contributed by Nikhil Kumar Singh