blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
de53f0c53f2535a5f9336d0bdf67d3a17efde0d9 | afeinsod/Computer-Science-Curricula | /Python/In Class Examples/Lists.py | 1,195 | 4.59375 | 5 | #Initializing lists:
#To initiazlie an empty list:
my_list = []
#To initiate a list with values (can contain mixed types):
list2 = [1, "yay", 140.76]
#Finding information about a list:
#To get an item from a list by index:
my_list= [1, 2, 3, 4, 5, 6]
print my_list[0] #will give the first item in the list, which is 1
print my_list[3] #will give the 4th item in the list, which is 4
#To get the length:
length = len(my_list)
print "The length is",length
#To get the largest element of the list:
print "The maximum is", max(my_list)
#To get the smallest element of the list:
print "The minimum is", min(my_list)
#To find out if something is in the list:
print "3 is in the list:",(3 in my_list)
print "14 is in the list:",(14 in my_list)
# Adding to a list:
# To add something at the end of the list:
my_list.append(8)
print my_list
# To insert something at a certain index in the list: insert(index, object)
my_list.insert(6, 7)
print my_list
# To change a value in a list:
my_list[3] = 12
print my_list
# Removing from a list:
# To delete something from a list:
del my_list[2]
print my_list
# To delete a specific object from the list:
my_list.remove(5)
print my_list
|
ef897518c402fdd4dcdba43b882111447226f6a1 | gameinskysky/dspnet | /data/VOC2007/utils.py | 547 | 3.53125 | 4 |
def getpalette(num_cls):
# this function is to get the colormap for visualizing the segmentation mask
n = num_cls
pallete = [0]*(n*3)
for j in xrange(0,n):
lab = j
pallete[j*3+0] = 0
pallete[j*3+1] = 0
pallete[j*3+2] = 0
i = 0
while (lab > 0):
pallete[j*3+0] |= (((lab >> 0) & 1) << (7-i))
pallete[j*3+1] |= (((lab >> 1) & 1) << (7-i))
pallete[j*3+2] |= (((lab >> 2) & 1) << (7-i))
i = i + 1
lab >>= 3
return pallete
|
25b8567493939e065b0172f217f3a9cac98096f6 | Maarten-Vandaele/PyGame | /pygame_1_BasicJumpingSquare.py | 1,613 | 3.703125 | 4 | import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('First Game')
x = 50
y= 425
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
run = True
while run:
# clock to make actions not to quick
pygame.time.delay(100)
# when pressing x pygame quits
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#define keypresses to move rec
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel: #direction + stop at border
x-=vel
if keys[pygame.K_RIGHT] and x < 500 - width - vel:
x+=vel
if not (isJump): # up/down OR jump
if keys[pygame.K_UP] and y > vel:
y-=vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y+=vel
if keys[pygame.K_SPACE]:
isJump = True
else: # jump physics
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
#fill with background color after moving rec otherwise rec will leave trail
win.fill((0,0,0))
# make rectangle object set on window, add collor and dimension parameters
pygame.draw.rect(win, (255,0,0), (x,y, width, height))
#refresh display to show character
pygame.display.update()
pygame.QUIT |
5754752683d770f31a79b3c69f5986ae3c45c43c | crishonsou/modern_python3_bootcamp | /definindo_uma_classe_com_atributos_para_conta_bancaria.py | 681 | 3.65625 | 4 | class BankAccount:
def __init__(self, name, balance = 0):
self.name = name
self.balance = 0
def owner(self):
return f'Hi {self.name}.'
def getBalance(self):
return f'Your balance is ${self.balance:.2f}'
def deposit(self, amount):
self.balance += amount
return f'You made a deposit of: ${amount:.2f}'
def withdraw(self, amount):
self.balance -= amount
return f'You made a withdraw of: ${amount:.2f}'
acct = BankAccount('Darcy')
print(acct.owner())
print(acct.getBalance())
print(acct.deposit(30.0))
print(acct.withdraw(9.0))
print(acct.getBalance())
|
711efa8470ffac6144547d82a28737903b2cceaa | Stheven-Chen/python | /07-Operasi Logika/Main.py | 1,297 | 3.578125 | 4 | # ada operasi logika not, or, and, xor
# Not
print('===========Not')
a = True
c = not a
print('data a: ',a)
print('jika di not')
print('data c: ',c)
# OR (Jika ada truenya maka akan menjadi true)
print('===========OR')
a = True
b = False
c = a or b
print(a, ' OR', b, '=', c)
print('===========OR')
a = True
b = True
c = a or b
print(a, ' OR', b, '=', c)
print('===========OR')
a = False
b = False
c = a or b
print(a, 'OR', b, '=', c)
print('===========OR')
a = False
b = True
c = a or b
print(a, 'OR', b, '=', c)
# AND (Jika ada 2 nilai true baru akan menjadi true)
print('===========and')
a = True
b = False
c = a and b
print(a, ' and', b, '=', c)
print('===========and')
a = True
b = True
c = a and b
print(a, ' and', b, '=', c)
print('===========and')
a = False
b = False
c = a and b
print(a, 'and', b, '=', c)
print('===========and')
a = False
b = True
c = a and b
print(a, 'and', b, '=', c)
# XOR (Akan tre jika hanya 1 sisi yang ada true)
print('===========xOR')
a = True
b = False
c = a ^ b
print(a, ' xOR', b, '=', c)
print('===========xOR')
a = True
b = True
c = a ^ b
print(a, ' xOR', b, '=', c)
print('===========xOR')
a = False
b = False
c = a ^ b
print(a, 'xOR', b, '=', c)
print('===========xOR')
a = False
b = True
c = a ^ b
print(a, 'xOR', b, '=', c) |
269e1ba211dd4a3c9e8b6e7b47a8c7ab5bf84e10 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/1279.py | 153 | 3.578125 | 4 | def word_count(sent):
words = {}
for w in sent.split():
if w not in words:
words[w] = sent.split().count(w)
return words
|
5da20e2fe116b32a60dd7c6fc92746be6fbe0ba2 | painfield/m02_boot_0 | /carreraTortugas/main.py | 1,329 | 3.734375 | 4 | import turtle
import random
class Circuito():
corredores = []
__turtleColor = ('blue','purple','red','orange')
def __init__(self, width, height):
self.__screen = turtle.Screen()
self.__screen.setup(width,height)
self.__screen.bgcolor('lightgray')
self.__startLine = -(width/2)+(2*(width/100))
self.__finishLine = (width/2)-(2*(width/100))
self.__crearTortugas(height/5)
def __crearTortugas(self,posY):
for i in range(4):
newTurtle = turtle.Turtle()
newTurtle.shape('turtle')
newTurtle.color(self.__turtleColor[i])
newTurtle.penup()
newTurtle.setpos(self.__startLine,posY*(i+1)-(posY*2.5))
newTurtle.pendown()
self.corredores.append(newTurtle)
def competir(self):
first = [-(self.__finishLine),'']
while first[0] < self.__finishLine:
for tortuga in self.corredores:
tortuga.fd(random.randint(1,10))
if tortuga.xcor() > first[0]:
first = [tortuga.xcor(),tortuga.color()[0]]
return first[1]
if __name__ == '__main__':
circuito = Circuito(640,480)
#barajas = Circuito(800,300)
print('{} turtle WINS!'.format(circuito.competir()))
|
6e9fd596a1650bc9d9a91244bfa18936db4e3cd6 | ryuhhhh/us_stock_rnn | /get_data/split_data.py | 881 | 3.578125 | 4 | """
csvから以下を取得
- X_train,y_train
- X_valid,y_valid
- X_test,y_test
"""
import numpy as np
import pandas as pd
if __name__ == '__main__':
csv_name = '1day_data.csv'
save_name = '1day'
folder_name = 'not_standard'
day_1_csv = pd.read_csv(f'./got_data/{csv_name}')
day_1_csv = day_1_csv.sample(frac=1, random_state=0)
day_1_csv = day_1_csv.astype({'10per_up':'int8','5per_up':'int8'})
day_1_csv = round(day_1_csv,3)
length = len(day_1_csv)
day_1_test = day_1_csv[:int(length*0.1)]
day_1_valid = day_1_csv[int(length*0.1):int(length*0.25)]
day_1_train = day_1_csv[int(length*0.25):]
day_1_test.to_csv(f'./got_data/data/{folder_name}/{save_name}_test.csv')
day_1_valid.to_csv(f'./got_data/data/{folder_name}/{save_name}_valid.csv')
day_1_train.to_csv(f'./got_data/data/{folder_name}/{save_name}_train.csv')
|
6d40c1f38d0206f28511c7e3280697458553d771 | venanciomitidieri/Exercicios_Python | /019 - Sorteando um item na lista.py | 435 | 3.9375 | 4 | import random
primeiro_nome = input('Digite o primeiro nome: ')
segundo_nome = input('Digite o segundo nome: ')
terceiro_nome = input('Digite o terceiro nome: ')
quarto_nome = input('Digite o quarto nome: ')
lista = [primeiro_nome, segundo_nome, terceiro_nome, quarto_nome]
print('Dos nomes {}, {}, {}, {}. O aluno escolhido foi {}' .format(primeiro_nome, segundo_nome, terceiro_nome, quarto_nome,
random.choice(lista)))
|
bbb9e999cb6d73371115ae32007b2322b54aab7a | Vaan525/Bit_seoul | /Keras/2020-11-10/keras09_split.py | 1,006 | 3.65625 | 4 |
# 1. 데이터
import numpy as np
x = np.array(range(1, 101)) # 테스트 하고싶은 데이터
y = np.array(range(101, 201))
x_train = x[:70]
y_train = y[:70]
x_test = x[:30]
y_test = y[:30]
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# 2. 모델 구성
model = Sequential()
model.add(Dense(300, input_dim=1))
model.add(Dense(500))
model.add(Dense(1200))
model.add(Dense(500))
model.add(Dense(300))
model.add(Dense(1))
# 3. 컴파일, 훈련
model.compile(loss='mse', optimizer='adam',
metrics=['mse'])
model.fit(x_train, y_train, epochs=100, validation_split=0.2)
#validation_data=(x_val, y_val))
# 4. 평가, 예측
# loss, acc = model.evaluate(x, y)
loss = model.evaluate(x_test, y_test)
print("loss : ", loss)
# print("acc : ", acc)
# 4. 예측
y_predict = model.predict(x_test)
print("결과물 : \n : ", y_predict)
# R2
from sklearn.metrics import r2_score
r2 = r2_score(y_test, y_predict)
print("R2 : ", r2)
|
965b8331fd9baed4f2b51b2df2802433bd169dce | jntushar/Hacker-Earth | /Strange Game.py | 1,375 | 3.75 | 4 | """
Alice and Bob are very good friends. They keep on playing some strange games. Today Alice came up with a new game, in which each player gets cards at the start. Each card has it's value printed on it.
The game proceeds as each player chooses a random card and shows it's value. The player having card with higher value wins. As Alice came up with this game, he wants to ensure his win. So he starts to increase value of some cards using an algorithm. To increase the value of a card by , the running time of algorithm is
seconds.
Find the minimum running time of algorithm, ensuring the win of Alice.
Input:
First line of input contains an integer
denoting the number of TestCases.
First line of Each testcase contains two Integers and .
Next two lines of each TestCase contains integers, each denoting value of cards of Alice and Bob respectively.
Output:
Print a single line for each TestCase, running time of algorithm to ensure the win for Alice.
"""
"""---SOLUTION---"""
test = int(input())
i = 0
while i < test:
n, k = [int(x) for x in input().split()]
alice = list(map(int, input().strip().split()))[:n]
bob = list(map(int, input().strip().split()))[:n]
bmax = max(bob)
j = time = 0
while j < n:
if alice[j] <= bmax:
x = (bmax - alice[j]) + 1
time += x * k
j += 1
print(time)
i += 1 |
da262767c6b76e67ebdf5bad0f60d1172570ff3e | Guoli-Zhang/Code | /HelloWorld/Day6/高阶函数.py | 594 | 3.609375 | 4 | num_list = [1, 2, 3, 1, 5, 1, 0, 0, 8, 6]
# def f(x):
# return x * 10
result = list(map(lambda x: x * 10, num_list))
print(result)
word = ["apple", "james", "rose", "enumerate", "print", "functions"]
def f(x):
return x[0].upper() + x[1:]
result = list(map(f, word))
print(result)
words = ["Apple", "james", "Rose", "Enumerate", "print", "functions"]
def f(x):
return x[0].isupper()
result = list(filter(f, words))
print(result)
num_list = [1, 10, 8, 9, 86]
import functools
def f(x1, x2):
return x1 * x2
result = functools.reduce(f, num_list)
print(result)
|
5254d093708ad3804e20b1a5d259cd921a36bb79 | aboua0949/Assignment.2 | /AliAPConcA2Q1.py | 437 | 4.3125 | 4 | #Programming concepts
#Assignment 1
#Question 1
# Ali Abouei / aboua0949
#setpember 28
print("Welcome , This is a length unit convertor ")
print()
x = int(input("Enter the number you want to convert, in meters!"))
inches = (x * 100/2.54)
feet = (inches/12)
yards = (feet/3)
miles = (yards/1760)
print(x,"meters is",inches,"inches!")
print(x,"meters is",feet,"feet!")
print(x,"meters is",yards,"yards!")
print(x,"meters is",mile ,"miles!") |
58956ebff428752b0cc00c63ac656bf9bfc39efc | kashikakhatri08/Python_Poc | /python_poc/python_array_program/array_rotation.py | 1,508 | 4.125 | 4 | def user_input():
global array_container
array_length = int(input("Enter the array length : "))
array_container = [None] * array_length
for i in range(0, array_length):
array_input = int(input("Enter the array element for array[{}] : ".format(i)))
array_container[i] = array_input
shift_by_position = int(input("Enter the number you want to shift the array: "))
return shift_by_position
def array_rotation_by_one():
array_rotate_container = [None] * len(array_container)
j = 0
for i in reversed(range(len(array_container))):
array_rotate_container[j] = array_container[i]
j = j + 1
print(array_rotate_container)
def array_rotation_by_any(shift_by_position):
array_rotate_container = [None] * len(array_container)
j = len(array_rotate_container) - shift_by_position
for i in range(0, len(array_container)):
if j < len(array_rotate_container):
array_rotate_container[j] = array_container[i]
j = j + 1
j = 0
for i in range(shift_by_position, len(array_container)):
array_rotate_container[j] = array_container[i]
j = j + 1
print(array_rotate_container)
def main():
shift_by_position = user_input()
print("array is : {}".format(array_container))
print("given array element in revers: ")
array_rotation_by_one()
print("given array shifted by {} position is :".format(shift_by_position))
array_rotation_by_any(shift_by_position)
main()
|
cf1ccd180163fbbb7770c287bbb2f8af94c3b054 | asmaalsaada/python_stack | /_python/python_fundamentals/hello_world.py | 529 | 4.15625 | 4 | # 1.
print( "Hello World!" )
#2.
name = "Asma"
print( "Hello ", name ) # Hello Asma
print( "Hello "+ name ) # HelloAsma
#3.
name = 23
print( "Hello", name ) # Hello 23
print( "Hello"-- name )
print( "Hello" + name ) # with a + , -- TypeError: can only concatenate str (not "int") to str
# 4.
fave_food1 = "fettuccine"
fave_food2 = "steak"
print("I love to eat {} and {} .".format(fave_food1, fave_food2))
print("I love to eat %s and %s ." % (fave_food1, fave_food2))
print (f"I love to eat {fave_food1} and {fave_food2}." )
|
3f1ada25f08436c2bd922d04b81d0cb388a192c9 | tell-k/code-snippets | /python/snippets/dict_merge.py | 912 | 3.671875 | 4 | #!/usr/bin/env python
#-*- coding:utf8 -*-
t = {'test1': 1, 'test2': 2, 'test3': 3, 'test5': 5}
t2 = {'test1': 2, 'test3': 4, 'test2': 3, 'test4': 4}
#t2.update(dict(map(lambda x: (x, t[x] + t2[x]) if x in t2 else (x, t[x]), t)))
#print sorted(t2.items(), reverse=True)
def merge_dict(d1, d2, merge=lambda x, y: y):
d1 = d1.copy()
d2 = d2.copy()
for k, v in d2.iteritems():
if k in d1:
d1[k] = merge(d1[k], v)
else:
d1[k] = v
d2.update(d1)
return d2
print merge_dict(t, t2) #=> {'test1': 2, 'test3': 4, 'test2': 3, 'test5': 5, 'test4': 4}
print merge_dict(t2, t) #=> {'test1': 1, 'test3': 3, 'test2': 2, 'test5': 5, 'test4': 4}
print merge_dict(t, t2, lambda x, y: x + y) #=>{'test1': 3, 'test3': 7, 'test2': 5, 'test5': 5, 'test4': 4}
print merge_dict(t2, t, lambda x, y: x + y) #=>{'test1': 3, 'test3': 7, 'test2': 5, 'test5': 5, 'test4': 4}
|
24a38fa1f44c1de091ecfc3f8ba6cc7bbb0f8185 | robertomf/python-afi | /ejercicio_dias.py | 508 | 3.84375 | 4 | # -*- coding: utf-8 -*-
diasmes = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
anho = input('Introduce un año: ')
if (anho <= 0):
print ' ** El anho es incorrecto **'
mes = input('Introduce un mes: ')
if (mes < 0 or mes > 12):
print ' ** El mes es incorrecto ** '
dia = input('Introduce un dia: ')
if (dia < 0 or dia > diasmes[mes-1]):
print ' ** El dia es incorrecto ** '
total = 0
for i in range (mes-1):
total += diasmes [i]
total += dia
print 'El numero de dias transcurridos es: ', total
|
3904bc365341e27ac83a9294b628732804c4d6e7 | harsitbaral/Natural-Selection-2.0 | /main.py | 6,200 | 3.734375 | 4 | import random
import draw
import time
import graphs
import csv
"""
PEP8:
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME,
global_var_name, instance_var_name, function_parameter_name, local_var_name
"""
class Apple:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
ANIMAL_POPULATION = 30
APPLE_POPULATION = 30
animals = []
apples = []
round_number = 0
ROUND_LENGTH = 30 # Seconds
time_pen = draw.turtle.Turtle()
time_pen.speed(0)
time_pen.shape('square')
time_pen.penup()
time_pen.hideturtle()
time_pen.goto(25, 6)
time_pen.write("")
round_counter_pen = draw.turtle.Turtle()
round_counter_pen.speed(0)
round_counter_pen.shape('square')
round_counter_pen.penup()
round_counter_pen.hideturtle()
round_counter_pen.goto(25, 3)
round_counter_pen.clear()
round_counter_pen.write(f"Round: {round_number}", move=False, font=("Roboto Bold", 24, "normal"))
csv_file = open('animal_speeds_data.csv', 'r')
data_reader = csv.reader(csv_file)
csv_speeds = []
if len(csv_file.readline()) > 0:
print(csv_file.readline())
user_sees_graph = input("Would you like to see a graph? Y or N\n")
if user_sees_graph.casefold() == 'y':
print(data_reader)
for line in data_reader:
print(line)
if line != ["Round", "Speed"] and line != []:
csv_round_number = line[0]
csv_speeds.append(line[1])
graphs.speed_graph(round_number=int(csv_round_number), animal_speeds=csv_speeds)
else:
print("length is 0")
csv_file.close()
def mutate(**kwargs):
value = kwargs["value"]
chances = kwargs["chances"]
starting_range = kwargs["starting_range"]
ending_range = kwargs["ending_range"]
chance_of_increase = kwargs["chance_of_increase"]
is_float = kwargs["is_float"]
mutation_decider = random.randint(0, 100)
increase_range = range(0, chance_of_increase)
change_direction_decider = random.randint(0, 100)
original_value = value
if mutation_decider <= chances:
# Mutation occurs
if is_float:
change_value = random.uniform(starting_range, ending_range)
else:
change_value = random.randint(starting_range, ending_range)
if change_direction_decider in increase_range:
value += change_value
else:
value -= change_value
print(f"MUTATION: {original_value} to {value}")
else:
print("No mutation :(")
return value
def reproduce(**kwargs):
born_animal_x = draw.ENDING_X / 2
born_animal_y = born_animal_x
born_vision_distance = kwargs["vision_distance"]
born_speed = kwargs["speed"]
born_animal = draw.Animal(born_animal_x, born_animal_y, born_vision_distance, born_speed)
draw.animals.append(born_animal)
def initialize_animals():
global animals
if round_number == 1:
for animal_index in range(ANIMAL_POPULATION):
animal_x = draw.ENDING_X / 2
animal_y = animal_x
vision_distance = draw.STARTING_VISION_DISTANCE
speed = 1
current_animal = draw.Animal(animal_y, animal_y, vision_distance, speed)
draw.animals.append(current_animal)
else:
for _ in animals:
animal_x = draw.ENDING_X / 2
animal_y = animal_x
vision_distance = draw.STARTING_VISION_DISTANCE
speed = 1
current_animal = draw.Animal(animal_y, animal_y, vision_distance, speed)
draw.animals.append(current_animal)
# Call reproduction function
def initialize_food():
for foodIndex in range(APPLE_POPULATION):
apple_x = random.randint(draw.STARTING_X+5, draw.ENDING_X-5)
apple_y = random.randint(draw.STARTING_Y+5, draw.ENDING_Y-5)
current_apple = Apple(apple_x, apple_y, "red")
apples.append(current_apple)
draw.render_apples(apples)
def move_animals():
start_time = round(time.time())
while time.time() - start_time < ROUND_LENGTH:
if (round(time.time()) - start_time) % 1 == 0:
time_pen.clear()
time_pen.write(f"{ROUND_LENGTH - (round(time.time()) - start_time)} S", move=False,
font=("Roboto Bold", 24, "normal"))
draw.move_sprites()
def check_animal_states():
for animal in draw.animals:
if animal.state == "L":
# Animal lives
pass
elif animal.state == "D":
# Animal dies
draw.animal_pen.clear()
draw.animal_pen.hideturtle()
draw.animals.remove(animal)
del animal
else:
# Animal reproduces
for i in range(animal.apples_eaten-2):
print("New baby born")
mutated_speed = mutate(value=animal.speed, chances=100,
starting_range=1, ending_range=2,
chance_of_increase=95, is_float=True)
mutated_vision_distance = mutate(value=animal.vision_distance, chances=100,
starting_range=5, ending_range=10,
chance_of_increase=95, is_float=False)
reproduce(vision_distance=mutated_vision_distance, speed=mutated_speed)
def new_round():
global round_number, apples
if round_number > 0:
# Call the animal_lives function
check_animal_states()
round_number += 1
round_counter_pen.clear()
round_counter_pen.write(f"ROUND {round_number}", move=False, font=("Roboto Bold", 24, "normal"))
if round_number > 1:
draw.clear_objects()
apples.clear()
draw.apple_sprites.clear()
draw.apple_positions.clear()
initialize_animals()
initialize_food()
time_pen.clear()
move_animals()
while True:
new_round()
# draw.finish()
|
fb2bb11296e80a2e4dd6a27e090ca643491f32c7 | pally2409/Hackerrank | /Python/sherlock-and-anagrams.py | 1,087 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
signatures = {}
result = 0
for i in range(len(s)):
wor = ''
for j in range(i, len(s), 1):
signature = [0]*26
wor = wor + s[j]
for letter in wor:
signature[ord(letter) - ord('a')] = signature[ord(letter) - ord('a')] + 1
signature = tuple(signature)
if signature in signatures.keys():
signatures[signature] = signatures[signature] + 1
else:
signatures[signature] = 1
values_sigs = list(signatures.values())
for i in range(len(signatures.keys())):
result = result + int((values_sigs[i]*(values_sigs[i]-1))/2)
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
fptr.write(str(result) + '\n')
fptr.close()
|
372f35c380bb21d3045fbbf1142a91bca3cd8a48 | CarolinaRodrigues/atividades_teste | /atividade_teste/conversor_base_2_10_16.py | 3,271 | 3.71875 | 4 | #Conversão de Bases
#CONVERSÃO DE BASE 2 PARA BASE 10
def base_2_para_base_10(valor_para_converter):
tamanho_valor = len(valor_para_converter)
valor_convertido = 0
i = 0
while tamanho_valor > 0:
numero_posicao_atual = valor_para_converter[tamanho_valor - 1]
tamanho_valor = tamanho_valor - 1
if(numero_posicao_atual == '1'):
valor_convertido = valor_convertido + ((int(numero_posicao_atual) * 2) ** int(i))
i = i + 1
return valor_convertido
#CONVERSÃO DE BASE 2 PARA BASE 16
def base_2_para_base_16(valor_para_converter,base_origem):
base_10 = base_2_para_base_10(valor_para_converter)
return base_10_para_base_x(base_10,16)
#CONVERSÃO BASE 10 PARA BASE X
def base_10_para_base_x(valor_para_converter,base):
valor_para_converter = int(valor_para_converter)
base = int(base)
digits = "0123456789ABCDEF"
remstack = []
while valor_para_converter > 0:
rem = valor_para_converter % base
remstack.append(rem)
valor_para_converter = valor_para_converter // base
base_x = ""
for r in remstack[::-1]:
base_x = base_x + digits[r]
print(base_x)
return base_x
#CONVERSÃO BASE 16
def base_16_numero_letra(letra):
numero = 0
return{
'A':10,
'B':11,
'C':12,
'D':13,
'E':14,
'F':15,
'numero': letra
}.get(letra)
#CONVERSÃO DA BASE 16 PARA BASE 10
def base_16_para_base_10(valor_para_converter):
tamanho_valor = len(valor_para_converter)
numero_posicao_atual = 0
while tamanho_valor > 0:
numero_posicao_atual = numero_posicao_atual + int(base_16_numero_letra(valor_para_converter.upper()[tamanho_valor - 1]))
tamanho_valor = tamanho_valor - 1
return numero_posicao_atual
def base_16_para_base_2(valor_para_converter):
base_10 = base_16_para_base_10(valor_para_converter)
return base_10_para_base_x(base_10,2)
# BASE X
def base_2_para_base_x(valor_para_converter,base_destino):
if(base_destino == '10'):
base_10 = base_2_para_base_10(valor_para_converter)
return base_10
if(base_destino == '16'):
base_10 = base_2_para_base_10(valor_para_converter)
print(base_10)
return base_10_para_base_x(base_10,16)
if(base_destino == '2'):
print("Não é possivel converter base origem igual base destino")
#CONVERSÃO DA BASE 16 PARA BASE X
def base_16_para_base_x(valor_para_converter,base_destino):
if(base_destino == '2'):
return base_16_para_base_2(valor_para_converter)
if(base_destino == '10'):
return base_16_para_base_10(valor_para_converter)
#VALORES DE ENTRADA
def valores_de_entrada(valor_para_converter,base_origem,base_destino):
if base_origem == '2':
return base_2_para_base_x(valor_para_converter,base_destino)
if base_origem == '10':
return base_10_para_base_x(valor_para_converter,base_destino)
if base_origem == '16':
return base_16_para_base_x(valor_para_converter,base_destino)
valor = valores_de_entrada('1010','2','16')
print(str(valor)) |
1d2d32d5a3f924b6eec38908efc0fcd56d877bca | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/sldcar001/question3.py | 604 | 3.84375 | 4 | def vote():
print("Independent Electoral Commission")
print("--------------------------------")
print("Enter the names of parties (terminated by DONE):")
print()
line=[]
voters=[]
ip=input()
while ip!="DONE":
line.append(ip)
a=line.count(ip)
if a==1:
voters.append(ip)
ip=input()
if ip=="DONE":
break
voters.sort()
print("Vote counts:")
output="{0:10} - {1}"
for voter in voters:
print(output.format(voter,line.count(voter)))
vote() |
3b408351330907caf98c21176121bc08835f0bec | HKervadec/Project-Euler | /Problem 042/problem42.py | 1,491 | 3.828125 | 4 | # The nth term of the sequence of triangle numbers is given by, tn = 1/2*n(n+1); so the first ten
# triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its alphabetical position
# and adding these values we form a word value. For example, the word value for SKY is
# 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
# Using words.txt, a 16K text file containing nearly two-thousand common English words,
# how many are triangle words?
# Renvoie le n ieme nombre triangulaire
def genTriangle(n):
return (n*(n+1))/2
# Renvoie la valeur d'un mot
def wordValue(string):
result = 0
for char in string:
result += ord(char) - 64
return result
# *********************************************************************
# Recuperation des mots
file = open("words.txt", "r")
words = file.read().split(',')
file.close
retireGuillemets = lambda word: word[1:-1]
words = map(retireGuillemets, words)
# Trouve longueur max d'un mot
max = 0
for word in words:
max = len(word) if len(word) > max else max
# Calcul des nombres triangulaires
valueMax = max*26 + 1
triangularNumbers = valueMax * [False]
n = 1
triangle = 1
while triangle < valueMax:
triangularNumbers[triangle] = True
n += 1
triangle = genTriangle(n)
# Filtrage
test = lambda word : triangularNumbers[wordValue(word)]
words = filter(test, words)
print(len(words)) |
6f8282cd4b630f329d878d69a146ef1d610bfa15 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4353/codes/1613_1804.py | 197 | 4.0625 | 4 | from math import*
XA=float(input("digite XA: "))
YA=float(input("digite YA: "))
XB=float(input("digite XB: "))
YB=float(input("digite YB: "))
DAB=sqrt((XB-XA)**2+(YB-YA)**2)
print(round(DAB,3)) |
c7ae2d1dcd9215b392be4503faea0c759c5d0fcc | advra/OpenTester | /Question.py | 2,686 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 14 12:20:07 2018
@author: 1172334950C
"""
class Question(object):
"""
This is used as the structure to format questions and retrieve those properties for our tests
number : string
Display element number within the Test Container
question : string
Display string context
answerSet : string[]
Contains answers for each
answer : string
Literal question answer
explain : string
Explanation to the answer
isFlagged : boolean
User can flag answers for review
"""
def __init__(self, number, question, answerSet, answer, explain):
self.number = number
self.question = question
self.answerSet = answerSet
self.answer = answer
self.explain = explain
self.userCorrect = None
self.gradedAnswers = [None] * 4
# user selections
# Flagged answers will be reviewed at the end and also shown in Navigator
self.flagSelection = False
# save our users selection
# assuming 4 possible answers
self.answerSelection = [False] * 4
# Print all the properties for debug.
def __str__(self):
print(self.number)
print(self.question)
print(self.answers)
print(self.answer)
print(self.explain)
# Standard Getters.
def Number(self):
return self.number
def Question(self):
return self.qustion
# Return answer at specific index.
def AnswerSetAt(self, index):
return self.answerSet[index]
def ShowAnswer(self):
return self.answer
def Explain(self):
return self.explain
def IsFlagged(self):
return self.flagSelection
def LoadAnswer(self, index):
return self.answerSelection[index]
def LoadAnswers(self):
return self.answerSelection
def LoadGrade(self):
return self.gradedAnswers
# Call this to check if we have graded the question yet
# None = Not Graded
# True = Right
# False = Wrong
def GotCorrect(self):
return self.userCorrect
def IsRight(self):
self.userCorrect = True
def IsWrong(self):
self.userCorrect = False
# Setters
def SaveState(self, flag, answers):
self.flagSelection = flag
self.answerSelection = answers
def SaveGrade(self, gradedAnswers):
self.gradedAnswers = gradedAnswers
print("Saved Answers: {} {} {} {}".format(gradedAnswers[0],gradedAnswers[1],gradedAnswers[2],gradedAnswers[3]))
|
fd1204c8ce2f93dbc9c8350e816804c0ef569cb5 | natsmith9/mustached-wookie | /magic8Ball.py | 1,549 | 3.640625 | 4 | __author__ = 'Nathan A. Smith'
import random
import time
myMagic8Ball = {1: "Yes",
2: "No",
3: "Maybe",
4: "Reconsider",
5: "Are You Dumb?",
6: "Sure, if that's what you want to do",
7: "Send in the clowns",
8: "Hey, get a load of this guy I'm talking to.",
9: "Jackball, he's my cousin...are you him?",
10: "You Bet.",
11: "I think we have a bad connection.",
12: "Hold on, I can't contact the spirits...Jerry, go grab my bongos.",
13: "There's a tiny man in here...someone call Art Bell",
14: "Consider it over brefkast",
15: "Don't sign any contracts with Gene Gebell",
16: "I hear the Clam Bucket is hiring...maybe you can wait tables.",
17: "Maybe don't quit your day job.",
18: "Why are you asking me?",
19: "Go get it",
20: "Kenny Slag says yes."}
def magic8ball():
input("What do you want? ")
my_rand_num = random.randrange(1, 20)
print("Contacting the Spirit World via Peenman's Crank Radio...")
time.sleep(3)
# print(my_rand_num)
print(myMagic8Ball[my_rand_num])
def main():
play = 'Y'
while play != 'N' and play != 'n':
magic8ball()
play = input("Play again? (Y/N): ")
else:
print("Jeez....finally, I can get rid of this weirded up jackball.")
if __name__ == "__main__":
main()
|
dab768a398322ac40f69ba4ebbf2b21f722f97fc | Eclipsess/LintCode | /BinaryTree/480. Binary Tree Paths.py | 1,300 | 4.15625 | 4 | # Given a binary tree, return all root-to-leaf paths.
#
# Example
# Example 1:
#
# Input:{1,2,3,#,5}
# Output:["1->2->5","1->3"]
# Explanation:
# 1
# / \
# 2 3
# \
# 5
# Example 2:
#
# Input:{1,2}
# Output:["1->2"]
# Explanation:
# 1
# /
# 2
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
current_path = ""
total_paths = []
self.traversal(root, total_paths, current_path)
return total_paths
def traversal(self, root, total_paths, current_path):
if root is None:
return
current_path = '->'.join([current_path, str(root.val)])
# current_path += (str(root.val) + "->")
if root.left is None and root.right is None:
current_path = current_path[2:]
total_paths.append(current_path)
return
self.traversal(root.left, total_paths, current_path[:])
self.traversal(root.right, total_paths, current_path[:])
|
906bc5212bd3552e2e6ea7c94f5fd7d317bb878b | alexro/pypypy | /olymp/graph/basic/bfs.py | 1,004 | 3.546875 | 4 | from collections import deque
from graph.basic.init import *
def bfs(g, v, process_vertex, process_edge):
discovered = [False] * len(g)
processed = [False] * len(g)
parents = [0] * len(g)
queue = deque()
queue.append(v)
discovered[v] = True
while queue:
v = queue.popleft()
process_vertex(v)
processed[v] = True
for child in g[v]:
if not discovered[child]:
queue.append(child)
discovered[child] = True
parents[child] = v
if not processed[child]:
process_edge(v, child)
print(parents)
return parents
def print_parents(p, v):
if v == 0:
print(0)
return
print(v, end='<-')
print_parents(p, p[v])
g = init(100)
add_edge(g, 1, 2)
add_edge(g, 1, 3)
add_edge(g, 100, 3)
print_graph(g)
def p_v(v):
print('v: ', v)
def p_e(v, child):
print('v-e: ', v, child)
p = bfs(g, 1, p_v, p_e)
print_parents(p, 100)
|
12e302202fb304246a63bc821f3412bc426bd621 | YordanPetrovDS/Python_Fundamentals | /_13_FUNCTIONS/_2_Calculations.py | 357 | 3.828125 | 4 | operator = input()
first_number = int(input())
second_number = int(input())
def solve(action, a, b):
if action == "multiply":
return a * b
elif action == "divide":
return a // b
elif action == "add":
return a + b
elif action == "subtract":
return a - b
print(solve(operator, first_number, second_number))
|
b8b37c9adab443bf04d28e0a8fe34d8712130a72 | Jordan-Camilletti/Project-Euler-Problems | /python/40. Champernowne's constant.py | 560 | 3.9375 | 4 | """An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000"""
wrd="."
for n in range(1,1000001):
wrd=wrd+str(n)
#print(wrd)
tot=1
for n in range(len(wrd)):
if(n==1 or n==10 or n==100 or n==1000 or n==10000 or n==100000 or n==1000000):
tot*=int(wrd[n])
print(tot)
|
1637d23ce185c4cb5131a40908b453c6bcb40bb3 | uyupun-archive/prockxy | /musics.py | 1,427 | 3.765625 | 4 | import sqlite3
class Musics:
def __init__(self):
self.conn = sqlite3.connect('database.sqlite')
self.cur = self.conn.cursor()
def create_table(self):
self.cur.execute('CREATE TABLE IF NOT EXISTS musics(id INTEGER PRIMARY KEY AUTOINCREMENT, song_name STRING, artist STRING, cd_jacket STRING)')
self.conn.commit()
return self
def drop_table(self):
self.cur.execute('DROP TABLE IF EXISTS musics')
self.conn.commit()
return self
def insert(self, song_name, artist_name, cd_jacket):
self.cur.execute('INSERT INTO musics(song_name, artist, cd_jacket) VALUES(?, ?, ?)', (song_name, artist_name, cd_jacket))
self.conn.commit()
return self
def find(self, id = 1):
return self.cur.execute('SELECT * FROM musics WHERE id = ?', (str(id), )).fetchone()
def count(self):
return self.cur.execute('SELECT count(*) FROM musics').fetchall()[0][0]
def exists(self, song_name, artist):
self.cur.execute('SELECT * FROM musics WHERE EXISTS(SELECT * FROM musics WHERE song_name = ? AND artist = ?)', (song_name, artist, ))
return True if self.cur.fetchone() else False
def close(self):
self.conn.close()
return self
if __name__ == '__main__':
print('Initializing database ...')
musics = Musics()
musics.drop_table().create_table().close()
print('Succeed!')
|
20c378a273307b566a4c079e7ba413aca3c94c64 | carlos-baraldi/python | /EstruturaSequencial/exercício5.py | 264 | 4.125 | 4 | #Faça um Programa que converta metros para centímetros.
val_metro = float(input('digite um valor em metros para saber o valor correspondente em centímetros '))
val_cent = val_metro * 100
print(f'{val_metro} metros equivale a {val_cent} centímetros')
|
370b0a6692bf09b4ceea4e61a39c1e92d4143fb9 | bel4212a/Curso-ciencia-de-datos | /Semana-2/carro.py | 1,773 | 4.1875 | 4 | class Carro:
"""Representacion basica de un carro"""
def __init__(self, marca, modelo, anio):
"""Atributos del carro"""
self.marca = marca
self.modelo = modelo
self.anio = anio
self.kilometraje = 0 # Se define un atributo por defecto
def descripcion(self):
"""Descripcion del carro segun sus atributos"""
nombre_largo = self.marca + ' ' + self.modelo + ' ' + str(self.anio)
return nombre_largo.title()
def leer_kilometraje(self):
"""Imprimir le kilometraje del carro"""
print("Esta carro tiene un kilometraje registrado de " + str(self.kilometraje) + " Km.")
def actualizar_km(self, valor):
"""modificacion del kilometraje"""
if valor >= self.kilometraje:
self.kilometraje = valor
else:
print("No es permitido reducir el kilometraje del auto.")
def llenar_tanque(self):
"""Permite lennar el tanuqe del vehiculo"""
print("Su tanque ahora esta lleno.")
class CarroElectrico(Carro):
"""Representacion de los vehiculos electricos"""
def __init__(self, marca, modelo, anio):
"""Inicializa atributos de la clase padre"""
"""Tambien inicializa el tamanio de la bateria"""
super().__init__(marca, modelo, anio) # Me permite referirme a los atributos y metodos del padre
self.bateria = 70
def imprimir_bateria(self):
"""Describe el estado de la bateria"""
print("Este vehiculo cuenta con una bateria de " + str(self.bateria) + " Kwh.")
def llenar_tanque():
"""Sobrecarga del metodo llenar tanque para carros electricos"""
print("Los carros electricos no tiene tanque que llenar.") |
dea7f4eacfd08e42c8b59bf95990ce912afee35f | senatn/learning-python | /draw_a_square.py | 361 | 4.125 | 4 | square_length = int(input("Length of the square: "))
stars = square_length
spaces = (square_length-2)
lines = square_length-3
for i in range(stars):
print("*", end="")
print()
for i in range(lines):
print("*", end="")
for i in range(spaces):
print(" ", end="")
print("*")
for i in range(stars):
print("*", end="")
i += 1
print() |
90a637d0ddacfa2055fc08287d17a31f506c0ea7 | bwh1te/Bulls-and-Cows | /bullsncows.py | 980 | 3.734375 | 4 | import random
import re
print """
BULLS & COWS
Guess a four-digit number with unique digits.
If you guessed right digit and it's position - it's a bull.
If you guessed right digit but it's standing on a incorrect position - it's a cow.
Good luck!
"""
number = "".join(map(str, random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 4) ))
#print number #cheatcode
guess = 0
while not guess:
bulls, cows = (0, 0)
x = raw_input("Your try: ")
if re.match('\d{4}', x) and len(x) == 4 and len(set(x)) == 4:
if number == x:
print "Yeah! You're right!"
guess = 1
else:
for position, digit in enumerate(x):
if str(digit) in number:
if number[position] == digit:
bulls += 1
else:
cows +=1
print " Bulls %d Cows %d" % (bulls, cows)
else:
print " Incorrect input format! It should be 4 unique digits!" |
379e4ac9e3721730ea276507fc26a2fdda456d23 | xuefengZhan/python | /_03_高级特性/_02_迭代.py | 1,587 | 3.6875 | 4 | #todo 迭代
# 迭代是一种遍历方式:用for in这种方式遍历我们称为迭代(Iteration)。
#todo 可迭代对象
# 可迭代对象指的就是可以用for in 来迭代遍历的对象
# list,tuple,dict,str 都是可迭代对象 可迭代对象不要求有索引
#todo 3. dict的迭代
# dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。
#todo 3.1迭代key
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print('%s : %i' % (key,d[key]))
#todo 3.2迭代value
for value in d.values():
print('%s ' % value)
#todo 3.3迭代k-v
for item in d.items():
print(item)
#todo 4.str
a='asdgsdf'
for i in a:
print(i)
#todo 5.判断判断一个对象是可迭代对象
# 通过collections模块的Iterable类型判断
from collections import Iterable
isinstance('abc', Iterable)
#todo 6.把一个list变成索引-元素对 python内置函数enumerate
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
l=[1,2,3,4]
len(l)
def findMinAndMax(L):
if len(L) == 0:
return (None, None)
min = L[0]
max = L[0]
for i in L:
if min > i:
min = i
if max < i:
max = i
return (min, max)
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!') |
fef54a4e85bf06a4ad20ffd4fe4a784d10ea6c5b | tashseeto/python | /exercises/variables-and-user-input-exercises.py | 1,578 | 4.25 | 4 | # Question 1
num1A = input("Please type 3 ")
num1B = input("Please type 9 ")
num1A = int(num1A)
num1B = int(num1B)
product = num1A + num1B
print(f"{num1A} + {num1B} = {product}")
num1C = input ("Please type -3 ")
num1B = input("Please type 9 ")
num1C = int(num1C)
num1B = int(num1B)
product = num1C + num1B
print(f"{num1C} + {num1B} = {product}")
num1D = input("Please type 3.0 ")
num1E = input("Please type -9 ")
num1D = float(num1D)
num1E = int(num1E)
product = num1D + num1E
print(f"{num1D} + {num1E} = {product}")
# Question 2
num2A = input("Please type 3 ")
num2B = input("Please type 9 ")
num2A = int(num2A)
num2B = int(num2B)
product = num2A * num2B
print(f"{num2A} * {num2B} = {product}")
num2C = input("Please type -3 ")
num2D = input("Please type 9 ")
num2C = int(num2C)
num2D = int(num2D)
product = num2C * num2D
print(f"{num2C} * {num2D} = {product}")
num2E = input("Please type 3.0 ")
num2F = input("Please type -9 ")
num2E = float(num2E)
num2F = int(num2F)
product = num2E * num2F
print(f"{num2E} * {num2F} = {product}")
# Question 3
num3A = input("Please type 10 ")
num3A = int(num3A)
productA = num3A * 1000
productA = num3A * 100000
print(f"{productA}m")
print(f"{productA}cm")
num3B = input("Please type 5.4 ")
num3B = float(num3B)
productB = (num3B) * 1000
productC = num3B * 100000
productB = int(productB)
productC = int(productC)
print(f"{num3B}km = {productB}m")
print(f"{num3B}km = {productC}cm")
# Question 4
name = input("What is your name? ")
height = input ("What is your height? ")
print(f"{name} is {height}cms tall.")
|
3276c9164d506fbf1a053a9f61c7b7dba267122c | terylll/LeetCode | /Array/11_maxArea.py | 653 | 3.5 | 4 | """
Link: https://leetcode.com/problems/container-with-most-water/description/
"""
"""
@Tag: ["DP", "Array"]
"""
import math
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height - 1)
maxArea = 0
while (left < right):
maxArea = Math.max(
Math.min(height[left], height[right]) * (right - left),
maxArea):
if (height[left] < height[right]):
left += 1
else:
right -=1
return maxArea;
|
e0dc271c5dfff698b82ff08c81f8db232c6d85c6 | 962245899/trabajo-5 | /boleta 2.py | 810 | 3.984375 | 4 | #INPUT
print("ASERRADERO TU BUENA TABLA")
cliente=input("Ingrese el nombre del cliente:")
vendedor=input("ingrese el nombre del vendedor:")
nº_de_tablas=int(input("Ingrese Nº de tablas:"))
precio_unitario=float(input("Ingrese precio unitario:"))
# PROCESSING
total = (precio_unitario * nº_de_tablas)
#verificador
limite=(total>1000)
# OUTPUT
print("#######################")
print("#ASERRADERO TU BUENA TABLA#")
print("# BOLETA DE VENTA")
print("#######################")
print("#")
print("# Cliente: ", cliente)
print("# Item : ",nº_de_tablas," nº_de_tablas")
print("# Precio Unitario : S/.", precio_unitario)
print("# Total : S/.", total)
print("# nombre del vendedor:", vendedor)
print("#######################")
print("el total es menor que el limite?", limite)
|
2b62924140798b7ce6b8cc3ec7ce3462a6537dde | Tolkosino/UniventionApplication | /Univention_Application.py | 684 | 4.03125 | 4 | import random # import random functionality
rndInt = random.randrange(100) # Generate random number between 0 and 100
guess = 101 # placeholder for guess of user
print("I'd like to play a game, bet you can't guess the number im thinking of? Aight, try your luck!")
while rndInt != guess: # while generated number is not equal to guess
guess = int(input("Guess?")) # get user input
if guess < rndInt: #compare guess and randomInt
print ("nah, too small, try again.")
elif guess > rndInt:
print ("Really? Too large my friend.")
print("Yep! You're right. Good job")
|
7d9f0dc68e579994aa49e6ef44c73272a239f2ad | XIAOQUANHE/pythontest | /yu_c/Chapter1-6/get_digits.py | 475 | 3.859375 | 4 | # 1. 写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放到列表中。举例:get_digits(12345) ==> [1, 2, 3, 4, 5]
# insert() 方法语法:L.insert(index,obj)
result = []
def get_digits(n):
if n > 0:
result.insert(0,n%10) # Python 列表 insert() 方法将指定对象插入到列表中的指定位置。 求个位数
# print(n%10) # 5,4,3,2,1
get_digits(n//10)
get_digits(12345)
print(result) |
13ad273a8efb3e46f5262b0a131508e8ad11c558 | jannik-sa/jansa | /python/primenzahlen.py | 331 | 3.609375 | 4 |
x=2
y=3
for i in range(100000):
n=y/x
if int(n)==n:
y=y+1
x=2
elif int(n)!=n:
x=x+1
if x==y:
print(y)
#while x <= y or int(n)==n:
# n=y/x
#
# if int(n)==n:
# print("Ist keine Primenzahl")
# elif int(n)!=n:
# x=x+1
#if x==y:
# print(y)
|
a1189380279c9f5abdafa63ffb9a24bd20406f5e | kellysteele168/Optimization-Algorithms | /Project 1/Project1_A.py | 3,911 | 3.6875 | 4 | """
This program uses the timeit module to calculate the runtime for two dynamic programming models to determine the optimal model. DPKP utilizes a matrix filled with zeros to begin, while DPKP1 does not.
"""
def DynamicProgrammingtest(n, Vmax, Smax, alpha, x):
from random import randint
import timeit
rtdpstore = 0 #keep track of the cumulative running time so far of running the greedy algorithm (normal version) on the create instances
rtdp = 0 #keep track of the cumulative running time so far of running the greedy algorithm (sorted version) on the create instance
C = (n)*(Smax/2)*alpha
for i in range(x):
v = [randint(1, Vmax) for j in range(n)]
s = [randint(1, Smax) for j in range(n)]
#runtime when zeros are stored initially
start = timeit.time.clock()
[Sg, vg] = DPKP(v, s, C)
end = timeit.time.clock()
rtdpstore = rtdpstore+ (end - start)
#runtime when no zeros are stored initially
start = timeit.time.clock()
[Sg, vg] = DPKP1(v, s, C)
end = timeit.time.clock()
rtdp = rtdp + (end - start)
return rtdpstore/x, rtdp/x
#Applies the dynamic programming method to the knapsack problem where v are the values of the n items, s are the sizes of the n items, C is the capacity, and values are not stored.
def DPKP1(v, s, C):
n = len(v)
V = [ [] for j in range (n) ]
X = [ [] for j in range (n) ]
for cp in range(int(C)+1):
if s[n-1] <= cp:
V[n-1].append(v[n-1])
X[n-1].append(1)
else:
V[n-1].append(0)
X[n-1].append(0)
for i in reversed(range(n-1)):
for cp in range(int(C)+1):
if s[i] <= cp:
if v[i] + V[i+1][cp-s[i]] > V[i+1][cp]:
V[i].append(v[i] + V[i+1][cp-s[i]])
X[i].append(1)
else:
V[i].append(V[i+1][cp])
X[i].append(0)
else:
V[i].append(V[i+1][cp])
X[i].append(0)
return V, X
#Applies the dynamic programming method to the knapsack problem where v are the values of the n items, s are the sizes of the n items, and C is the capacity, and values are stored initially
def DPKP(v, s, C):
n = len(v)
V = [ [0 for cp in range(int(C)+1)] for j in range (n) ]
X = [ [0 for cp in range(int(C)+1)] for j in range (n) ]
for cp in range(int(C)+1):
if s[n-1] <= cp:
V[n-1][cp] = v[n-1]
X[n-1][cp] = 1
for i in reversed(range(n-1)):
for cp in range(int(C)+1):
if s[i] <= cp:
if v[i] + V[i+1][cp-s[i]] > V[i+1][cp]:
V[i][cp] = v[i] + V[i+1][cp-s[i]]
X[i][cp] = 1
else:
V[i][cp] = V[i+1][cp]
else:
V[i][cp] = V[i+1][cp]
return V, X
n=3
Vmax=5
Smax=6
alpha=.13
x=4
stored_time,not_stored_time=(DynamicProgrammingtest(n,Vmax,Smax,alpha,x))
print('n:{}\nVmax:{}\nSmax:{}\nalpha:{}\nx:{}\n'.format(n,Vmax,Smax,alpha,x))
print("The run time for the dynamic programming model with the stored values is {:.8f}. \nThe run time for the dynamic programming model without the stored values is {:.8f}.".format(stored_time,not_stored_time))
if stored_time>not_stored_time:
print("The run time for the dynamic programming model without storing values initially is faster than the run time for the dynamic programming model that initally stores values.")
elif stored_time<not_stored_time:
print("The run time for the dynamic programming model storing values initially is faster than the run time for the dynamic programming model that does not initialy store values.") |
8f90c13d758f89244629c66389a1d5d8d9b7c4bb | srankur/DataStructure_Algorithms | /6.006_MIT/Sortings/mergeSort.py | 1,393 | 4.1875 | 4 |
def mergeArr(arr,leftArr,rightArr):
print("Pre Merge Array::", arr)
print("Pre Merge Left Arr:", leftArr)
print("Pre Merge Right Arr:", rightArr)
i=0
j=0
k=0
while(i < len(leftArr) and j < len(rightArr)):
if(leftArr[i] < rightArr[j]):
arr[k] = leftArr[i]
i +=1
k +=1
elif( leftArr[i] > rightArr[j]):
arr[k] = rightArr[j]
j +=1
k +=1
while(i < len(leftArr)):
arr[k] = leftArr[i]
i += 1
k += 1
while (j < len(rightArr)):
arr[k] = rightArr[j]
j += 1
k += 1
print("Post Merge:",arr)
def mergeSort(arr):
if (len(arr) == 1):
print("List has one element, Must be sorted!!")
return
if(len(arr) > 1):
mid = int(len(arr) / 2)
leftArr = arr[:mid]
rightArr = arr[mid:]
print("Pre Split:", arr)
print("Post Split, Left Arr:", leftArr)
print("Post Split, right Arr:", rightArr)
mergeSort(leftArr)
mergeSort(rightArr)
mergeArr(arr, leftArr, rightArr)
else:
print("EmptyList, Nothing to sort!! ")
arr = [76,45,89,34,90,-1,9.6,-2.55]
arr1= [34]
masterarr = [arr,arr1]
for i in masterarr:
print("########################")
print("Sorting List:", i)
print("########################")
mergeSort(i) |
4c0b8ca1e8d86ab11360e29e5cdf704ea170cd79 | jonathan-murmu/ds | /data_structure/leetcode/easy/53 - Maximum Subarray/max_subarray.py | 1,476 | 4.09375 | 4 | '''
https://leetcode.com/problems/maximum-subarray/
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
'''
from itertools import accumulate
def max_sub_array(nums):
# dynamic programming
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
y = nums[i]
x=nums[i] + dp[i - 1]
dp[i] = max(nums[i], nums[i] + dp[i - 1])
return max(dp)
# # divide an conquer
# def helper(beg, end):
# if beg + 1 == end: return nums[beg]
# mid = (beg + end) // 2
# sum_1 = helper(beg, mid)
# sum_2 = helper(mid, end)
# right = max(accumulate(nums[beg:mid][::-1]))
# left = max(accumulate(nums[mid:end]))
# return max(sum_1, sum_2, left + right)
#
# return helper(0, len(nums))
# # kadane Algo
cur_max, max_till_now = 0, -inf
for c in nums:
# cur_max = maximum of cur no and cur_max+cur_no
cur_max = max(c, cur_max + c)
max_till_now = max(max_till_now, cur_max) # which is the max(max_till_now) amoung the cur maxs
return max_till_now
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(max_sub_array(nums))
|
be7cfbeedb0c2a6df04bb57e4bf7539fe0438ce0 | ligb1023561601/CodeOfLigb | /OOP.py | 3,875 | 4.1875 | 4 | # Author:Ligb
# 1.定义一个类,规定类名的首字母大写,括号是空的,所以是从空白创建了这个类
# _init_()方法在创建类的新实例的时候就会自动运行,两个下划线是用来与普通方法进行区分
# self是一个自动传递的形参,指向实例本身的引用,在调用方法时,不必去给它传递实参
# 以self作前缀的变量称之为属性
# 命名规则
# object() 共有方法 public
# __object()__ 系统方法,用户不这样定义
# __object() 全私有,全保护方法 private protected,无法继承调用
# _object() private 常用这个来定义私有方法,不能通过import导入,可被继承调用
# 两种私有元素会被转换成长格式(公有的),称之为私有变量矫直,如类A有一私有变量__private,将会被转换成
# _A__private作为其公有变量,可以被继承下去
class Dog(object):
def __init__(self, name, age):
"""初始化属性name与age"""
self.name = name
self.age = age
def sit(self):
"""类中的函数称为方法"""
print(self.name.title() + " is now sitting!.")
def roll_over(self):
print(self.name.title() + " rolled over!")
my_dog = Dog("he", 2)
my_dog.sit()
my_dog.roll_over()
class Car(object):
"""创建一个汽车类"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 属性具有默认值
def _get_information(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def update_info(self,date):
"""通过方法修改属性"""
self.year = date
def increment_info(self,miles):
"""通过方法进行属性递增"""
self.odometer_reading += miles
def fill_gas_tank(self):
print("This car's gas tank is full!")
my_car = Car("audi", "big", "1993")
my_car_info = my_car._get_information()
print(my_car_info)
# 2.给属性指定默认值
# 3.三种方法进行修改:通过实例修改,通过方法进行设置,通过方法进行递增(类似于方法进行设置)
my_car.model = "small"
# 4.继承
# 在括号中的类称为父类,super()函数可以令子类包含父类的所有实例
# 在Python2.7中,继承语法为
# super(Electric_Car,self)._init_(make,model,year)
# 5.重写父类中的方法,可实现多态,父类中的方法将被忽略,包括init方法,若子类不写,则用父类的init方法
class Battery(object):
"""将电动车的电池相关属性提取出来"""
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def get_mileage(self):
"""显示行驶里程"""
if self.battery_size == 70:
mileage = 240
elif self.battery_size == 85:
mileage = 270
message = "This car can go approxiamately " + str(mileage)
message += "miles on a full charge."
print(message)
class ElectricCar(Car):
def __init__(self,make,model,year):
"""初始化父类属性,并定义电动车独有的属性"""
super().__init__(make, model, year)
self.battery_size = Battery()
def fill_gas_tank(self):
print("Electric Cars do not have a gas tank!")
my_tesla = ElectricCar("Tesla", "medium","2017")
print(my_tesla._get_information())
my_tesla.battery_size.describe_battery()
my_tesla.battery_size.get_mileage()
# 6.将实例用作属性,将类中某些相近的属性再疯封装成小类,然后将这些小类实例化后作为大类的属性,以达到更清晰的结构
# 7.导入类:实现代码的简洁原则,内容在my_car.py中
|
f57cc1db869309669cde38bb40f79bdfae652520 | GuillermoLopezJr/CodeAbbey | /Abbey006/main.py | 244 | 3.71875 | 4 | print("Enter number of test Cases followed by data: ")
SIZE = int(input())
answers = []
for i in range(SIZE):
a, b = map(int, input().split())
answers.append(round(a/b))
print("\nanswer: ")
for ans in answers:
print(ans, end=" ")
|
3dc210b79af27322ab20ca72a69987cac83e3fa8 | clarencenhuang/programming-challenges | /canonical_problems/longest_palindrome_subseq.py | 279 | 3.515625 | 4 |
def longest_palindrome_subseq(s):
def dp(i, j):
ends_eq = s[i] == s[j]
if i == j or ends_eq and j == i + 1:
return j - i + 1
if ends_eq:
return 2 + dp(i+1, j-1)
else:
return max(dp(i+1, j), dp(i, j-1))
|
3d048d6c09248864a097be59370af09aca7a0ed7 | jongbeom11/16PFB-jongbeom | /ex06/ex06.py | 395 | 3.578125 | 4 |
x = "there ard %d types of people." # 10
binary = "binary"
do_not = "don't "
y= "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "T also said: '%s'." % y
hilarious = False
joke_evalution = "Isn't that joke so fuunt?! %r"
print joke_evalution % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e |
73d11a708b3e91f0cb3f1b9a0636cf7861f8f25f | wenjiazhangvincent/leetcode | /1119-112/504.py | 627 | 3.59375 | 4 | class Solution(object):
def __init__(self):
self.res = []
def loop(self, num):
if num < 7:
self.res.append(str(num))
return
else:
self.res.append(str(num % 7))
self.loop(num / 7)
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num >= 0:
self.loop(num)
return ''.join(self.res[::-1])
else:
self.loop(abs(num))
return '-' + ''.join(self.res[::-1])
st = Solution()
num = -7
print st.convertToBase7(num) |
9c6a1e1a90a5761987990076b07bf88bf111f99a | Dawn-Test/Python | /Basics/03-分支语句.py | 820 | 3.921875 | 4 | # if elif else
# 运算符:
# == 是否相等 !=是否不等于 >是否大于 <是否小于 >=是否大于等于 <= 是否小于等于
# 如果成立返回true 不成立返回false
# 练习:登录页面
input_username = input('请输入您的用户名:')
input_password = input('请输入您的密码:')
correct_urername = 'admin'
correct_password = '123456'
# 首先判断用户名是否正确
if input_username == correct_urername:
# 如果用户名正确,再判断密码是否正确
if input_password == correct_password:
print('欢迎 %s 登录系统' % input_username)
else:
print('您的用户名或密码错误!')
else:
print('您的用户名或密码错误!')
#else: 后面不能加任何函数和命令
|
ac192a5826a18ffd43f4c9efce302d01a46c894f | fepettersen/inf3331 | /uke2/averagerandom.py | 1,089 | 3.6875 | 4 | import sys
import random
from numpy import zeros,linspace
if len(sys.argv) == 2:
n = int(sys.argv[1]) #read a number from the commandline
else:
#prvide an error message which makes sense if the above fails
print 'You provided the wrong ammount of commandline arguments \n please specify the number of times to draw a random number.'
sys.exit()
#Initialize variables
numbers = zeros(n)
average = 0
'''
numbers[i] = [random.uniform(-1,1) for i=0,n-1,i++]
average = sum(numbers)/n
'''
for i in numbers:
#Draw n random numbers and sum them up
numbers[i] = random.uniform(-1,1)
average += numbers[i]
average /=n # Finish computing the average
print 'The average of %d randomly drawn numbers between -1 and 1 is %.4f' % (n,average)
'''
fredrik@fredrik-Aspire-V3-571:~/uio/inf3331/uke2$ python averagerandom.py
You provided the wrong ammount of commandline arguments
please specify the number of times to draw a random number.
fredrik@fredrik-Aspire-V3-571:~/uio/inf3331/uke2$ python averagerandom.py 5892
The average of 5892 randomly drawn numbers between -1 and 1 is 0.0080
'''
|
aa905bd42ecc6699010e394b8cc1a87a0777d66d | Randle9000/pythonCheatSheet | /pythonCourseEu/1Basics/32MetaClassesIntro/Ex2.py | 1,291 | 4.09375 | 4 | #We can improve our approach in Ex1.py
# by defining a manager function and avoiding redundant code this way.
# The manager function will be used to augment the classes conditionally.
# the following variable would be set as the result of a runtime calculation:
x = input("Do you need the answer? (y/n): ")
if x == "y":
required = True
else:
required = False
def the_answer(self, *args):
return 42
# manager function
def augment_answer(cls):
if required:
cls.the_answer = the_answer
class Philosopher1:
pass
augment_answer(Philosopher1)
class Philosopher2:
pass
augment_answer(Philosopher2)
class Philosopher3:
pass
augment_answer(Philosopher3)
plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
#This is again useful to solve our problem, but we, i.e. the class designers, must be careful not to forget to call the manager function "augment_answer". The code should be executed automatically. We need a way to make sure that "some" code might be executed automatically after the end of a class definition Ex3.py
# . |
9dbd332942d80c92fa00242dbd510af75115d3ce | tisnik/python-programming-courses | /Python1/examples/list_sort.py | 181 | 3.640625 | 4 | seznam = [5, 4, 1, 3, 4, 100, -1]
print(seznam)
seznam.sort()
print(seznam)
seznam = [5, 4, 1, 3, 4, 100, -1]
print(seznam)
seznam2 = sorted(seznam)
print(seznam)
print(seznam2)
|
61128c97bcd49dcc175cc1b6976b6c22b4f39360 | A432-git/Leetcode_in_python3 | /67_Add Binary.py | 1,356 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 12:53:44 2019
@author: leiya
"""
#1.str,int类型
#2.变量的声明
#3.while循环里变量每次循环的更新
class Solution:
def addBinary(self, a: str, b: str) -> str:
carry = 0
i = len(a) - 1
j = len(b) - 1
res = ''
while i >= 0 or j >= 0 or carry:
if i >= 0:
temp1 = int(a[i])
else:
temp1 = 0
if j >= 0:
temp2 = int(b[j])
else:
temp2 = 0
t = (temp1 + temp2 + carry) % 2
carry = (temp1 + temp2 + carry) // 2
res += str(t)
i -= 1
j -= 1
return res[::-1]
class Solution:
def addBinary(self, a: str, b: str) -> str:
aint = int(a,2) + int(b,2)
return str(bin(aint))[2:]
class Solution:
def addBinary(self, a: str, b: str) -> str:
result,carry,val = "",0,0
for i in range(max(len(a),len(b))):
val = carry
if i < len(a):
val += int(a[-(i+1)])
if i < len(b):
val += int(b[-(i+1)])
carry,val = val // 2,val%2
result += str(val)
if carry:
result += str(1)
return result[::-1]
|
e7f6131cca21132561df5fb2bde280f8b133ae2e | GeorgiyDemo/FA | /Course_I/Алгоритмы Python/Part2/семинары/pract5/task2.py | 820 | 4.4375 | 4 | """
Задача 2:
В массиве найти максимальный элемент с четным индексом.
Другая формулировка задачи: среди элементов массива с четными индексами, найти тот,
который имеет максимальное значение.
"""
import array as ar
from random import randint
main_arr = ar.array("i", [randint(-100, 100) for _ in range(50)])
print("Исходный массив:", main_arr)
max_element = -100
for i in range(len(main_arr)):
if i % 2 == 0 and main_arr[i] > max_element:
max_element = main_arr[i]
print("Индекс {}, элемент: {}".format(i, max_element))
print("Макс элемент с четным индексом: {}".format(max_element))
|
0dbacd0cc3e3b98d35613f5b7c4937d9994ef5e0 | silvercobraa/competitive-programming | /6. String Processing/Ad Hoc String Processing Problems/Regular Expression/00494.py | 187 | 3.53125 | 4 | import sys
for line in sys.stdin:
words = 0
prev = ' '
for c in line:
if c.isalpha() and not prev.isalpha():
words += 1
prev = c
print(words)
|
1df3a46b9dde63024901708aa54087657c2b6b8d | sm11/CodeJousts | /merge.py | 882 | 3.890625 | 4 | def merge(arr1, arr2):
arr3 = []
c1 = 0
c2 = 0
while c1 < len(arr1) and c2 < len(arr2):
if arr1[c1] < arr2[c2]:
arr3.append(arr1[c1])
c1 += 1
else:
arr3.append(arr2[c2])
c2 += 1
if c1 < len(arr1):
arr3.extend(arr1[c1:])
else:
arr3.extend(arr2[c2:])
return arr3
def merge_in(a1, a2):
a3 = a1 + a2
count = 0
print (a3)
for idx in range(len(a1), len(a3)):
val = a3[idx]
pos = idx
while a3[pos-1] > val:
a3[pos] = a3[pos-1]
pos -= 1
a3[pos] = val
return a3
if __name__ == "__main__":
arr1 = [1, 3, 4, 5]
arr2 = [2, 4, 6, 8]
print (merge_in(arr1, arr2))
# for el1 in arr1:
# for el2 in arr2:
# if el1 < el2:
# arr3.append()
|
36c55fc15441acb81dbb3c4558942ca1749133c7 | ruidazeng/online-judge | /Kattis/mjehuric.py | 411 | 3.9375 | 4 | def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
vals[i], vals[i + 1] = vals[i + 1], vals[i]
# Yield gives the "state"
yield vals
vals = [int(x) for x in input().split()]
for state in bubblesort(vals):
print(*state) |
8ad41702b99b7af93f899f19322bbd4c296671c6 | echosand/comp9021 | /ass1-2.py | 1,250 | 3.78125 | 4 | import sys
import math
try:
name=input('Which data file do you want to use?')
with open(name,'r') as f:
data=f.readlines()
matrix=[]
for line in data:
matrix.append(list(map(int,line.split())))
f.close()
except IOError:
print('Sorry, there is no such file.')
sys.exit()
f.close
#print (matrix)
#二分法算法
def divide(A,B):
minvalue=min(B)
maxvalue=max(B)
target=(sum(B))//len(B)
C=B[:]
minus=0
while C[len(C)-1]!=target:
C=B[:]
for i in range(len(A)):
if i < len(C)-1:
C[i]-= minus
minus=target - C[i]+abs(A[i+1]-A[i])
if i==len(C)-1:
C[i]=C[i]-minus
minus=0
if C[len(C)-1] > target:
minvalue=target
if target !=(maxvalue+minvalue)//2:
target=(maxvalue+minvalue)//2
else:
break
if C[len(C)-1]< target:
maxvalue = target
if target !=(maxvalue+minvalue)//2:
target= (maxvalue+minvalue)//2
else:
break
return target
#主程序
#按照距离大小进行排序
matrix=sorted(matrix,key=lambda matrix:matrix[0])
#print(matrix)
distance = []
weight = []
for i in range(len(matrix)):
distance.append(matrix[i][0])
weight.append(matrix[i][1])
#print(distance,weight)
print(f'The maximum quantity of fish that each town can have is {divide(distance,weight)}.')
|
da088bcfcf444bd513ece26748b39806925b0a2f | ROBIN6666/Purchase-Analytics | /Self_challenge/Combine.py | 2,735 | 3.609375 | 4 | import csv
import os
final_order=[]
with open('order.csv', 'r') as csvfile:
rw=csv.reader(csvfile,dialect='excel')
for row in rw:
final_order.append(row)
for a in range(len(final_order)):
final_order[a].pop(0)
for a in range(len(final_order)):
final_order[a].pop(0)
product_order=[]
with open('product.csv', 'r') as csvfile:
rw=csv.reader(csvfile,dialect='excel')
for row in rw:
product_order.append(row)
for a in range(len(product_order)):
product_order[a].pop(0)
product_order[a].pop(1)
for a in range(len(product_order)):
product_order[a].pop(0)
#Merging both the List.
for i in range(len(final_order)):
final_order[i].insert(0,product_order[i])
#Function to convert the List in 1-D array
def Final_list(final_order):
result = [item for sublist in final_order for item in sublist]
return result
def data_preprocessing(report_data):
listToStr = ' '.join([str(row) for row in report_data])
s=""
for i in listToStr:
s=s+i.strip('[]').replace("'",'')
y=s.split(' ')
return y
#Function to calculate the No-of-rows in the List.
def count_rows(_report_data):
FinalD=[]
rows=int(len(_report_data)/3)
for times in range(rows):
newtempD=[]
for i in range(3):
newtempD.append(_report_data[0])
_report_data.pop(0)
FinalD.append(newtempD)
FinalD.pop(0)
return FinalD
print(len(FinalD))
print("file is formated {}".format(row))
print("hello rahul")
print("hello keshab")
print("hello nitesh")
if __name__ == "__main__":
report_data=Final_list(final_order)
_report_data=data_preprocessing(report_data)
_Final_data=count_rows(_report_data)
percentage=[]
for times in _Final_data:
for i in range(2,1,-1):
val1=float(int(times[i]))/(int(times[i-1]))
val1=round(val1,2)
percentage.append(val1*100)
#Merging the percenatge data to the FinalD.
for i in range(len(_Final_data)):
_Final_data[i].insert(3,percentage[i])
print(_Final_data)
#Creating the Report.csv file to store the Final Report collected.
if not os.path.exists("Self_challenge/Data"):
os.makedirs("Self_challenge/Data")
with open('Self_challenge/Data/Real_Combine.csv', 'w') as csvfile:
wr=csv.writer(csvfile,dialect='excel')
wr.writerow(['department_id', 'number_of_orders', 'number_of_first_orders','percentage'])
for row in _Final_data:
# for ele in row:
wr.writerow(row) |
a650d617838f8d5a85ec1004659de8dd7613c99d | angelkin1050/python | /list 개념.py | 1,495 | 4.03125 | 4 | """
여러개의 값을 하나의 변수에 담을 수 있다.
하나의 list변수에 다양한 자료형을 담을 수 있다.
음수 인덱스가 가능하다.(문자열도)하지만 사용을 지양해야 함.
인덱싱 추출값: 데이터만
슬라이싱 추출값: 리스트
"""
season =["봄","여름","가을","겨울"]
grade = [1,2,3]
print(season[0])
print(season[2])
print(season[0] + season[2])
print(grade[1] + grade[2])
hello = "안녕하세요"
print(hello[0:3])
#리스트 인덱싱
print(season[1])
#리스트의 슬라이싱
print(season[0:3])
print(season[0:2])
# 리스트의 길이 구하기 : len
print(len(season))
#리스트 값 수정하기
#grade = [1,2,3]
grade[1] = 5
print(grade)
#리스트 값 삭제하기
# grade = [1,5,3]
del grade[2]
print(grade)
num = [1,2,3,4,5]
del num[2:]
print(num)
#리스트 값 추가하기
#append : 무조건 list 끝에 추가
num.append(3)
num.append(4)
num.append(6)
print(num)
#insert : 원하는 부분에 추가
num.insert(4,5)
print(num)
#중요도 낮음
# 리스트 요소 제거 : remove(x)
#리스트에서 처음으로 나오는 x값 제거
test = [1,2,3,1,2,3]
test.remove(3)
print(test)
#리스트 요소 끄집어 내기 : pop
#리스트의 맨 마지막 요소를 돌려주고
#그 요소를 삭제한다.
popNum = test.pop()
print(popNum)
print(test)
#리스트에 포함된 요소 x의 개수 세기 : count
#[1,2,1,2]
print(test.count(1))
|
77dcc81ec23e65d4e54e3ed1303fdc29907667a0 | geetheshbhat/Flask-CRUD-sqlite3 | /app.py | 2,782 | 3.5625 | 4 | import sqlite3
from flask import Flask, request
from flask_restful import Resource, reqparse
app=Flask(__name__)
@app.route('/create', methods=['GET'])
def create_table():
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="CREATE TABLE IF NOT EXISTS movies (id INTEGER PRIMARY KEY, movie_name text)"
cursor.execute(query)
connection.commit()
connection.close()
return {'message':'table created successfully'},200
@app.route('/create/<string:name>',methods=['POST'])
def add_item(name):
rd=find_one(name)
if rd is None:
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="INSERT INTO movies VALUES(NULL,?)"
cursor.execute(query,(name,))
connection.commit()
connection.close()
return {'message':'Movies added successfully'},200
return {'Message':"Movie already exists"},400
@app.route('/read',methods=['GET'])
def show_movies():
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="SELECT * FROM movies"
rows=cursor.execute(query)
item=[]
if rows:
for row in rows:
item.append({"id":row[0],"Movie Name":row[1]})
return {'movies':item}
return {'Message':'The Database is empty'},400
@app.route('/read/<string:name>',methods=['GET'])
def find_one(name):
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="SELECT * FROM movies where movie_name=?"
rows=cursor.execute(query,(name,))
rd=rows.fetchone()
try:
if rd:
return {"Movie":rd[1]},201
except:
return {"Message":"Movie Not Found"},404
@app.route('/update',methods=['PUT'])
def movie_update():
data=request.get_json()
rd=find_one(data['old_name'])
if rd:
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="UPDATE movies SET movie_name=? where movie_name=?"
row=cursor.execute(query,(data['new_name'],data['old_name']))
connection.commit()
connection.close()
return {'message':'Movie renamed from {} to {}'.format(data['old_name'],data['new_name'])},201
add_item(data['old_name'])
return {'message':"Movie doesn't exist, a new movie has been created"},201
@app.route('/delete/<string:name>',methods=['DELETE'])
def delete_movie(name):
connection=sqlite3.connect('data.db')
cursor=connection.cursor()
query="DELETE FROM movies where movie_name=?"
row=cursor.execute(query,(name,))
connection.commit()
connection.close()
return {"Message":"Movie {} deleted successfully".format(name)},200
if __name__ == '__main__':
app.run(debug=True) |
8617d5c494f1788fc9feacbd51b719a5b984928f | its-Kumar/Python.py | /8_ObjectOrientedProgramming/BankAccount.py | 1,563 | 4.1875 | 4 | """Bank Account Class"""
class Account:
"""Class to represent a Bank Account"""
def __init__(self, owner: str, balance=0):
assert isinstance(owner, str), "owner name should be string"
assert not isinstance(balance, str), "balance should be int or float"
if balance < 0:
raise "balance should not be negative"
self.__owner = owner
self.__balance = balance
@property
def owner(self):
"""Account owner name"""
return self.__owner
@owner.setter
def owner(self, value: str):
assert isinstance(value, str), "owner name should be string"
assert value != "", "owner name should not be empty"
self.__owner = value
@property
def balance(self):
"""Current account balance"""
return self.__balance
def deposit(self, amount: float):
"""Deposit amount to the account"""
self.__balance += amount
print("Deposit Accepted!!")
def withdraw(self, amount: float):
"""Withdraw amount from the account"""
if amount <= self.__balance:
self.__balance -= amount
print("Withdraw Accepted!!")
else:
print("Fund Unavailable!!")
def __str__(self):
return f"{self.__owner} owns this Account with current Balance {self.__balance} !"
ac1 = Account(owner="Jose", balance=500)
ac1.deposit(200)
print(ac1.balance)
ac1.withdraw(400)
print(ac1.balance)
ac1.withdraw(1000)
print(ac1)
|
f4e760857c37441136baffb980ccac2872cd00c3 | sandeshjoy/python-scripts | /dict.py | 213 | 3.65625 | 4 | def add_items(some_dict):
# Add new items to dict
some_dict.update({'k': 3, 'l': 4})
return some_dict
if __name__ == __main__:
some_dict = {'a': 1, 'b': 2}
new_dict = add_items()
print(new_dict)
|
1ac61293da313a3e6b2771f2c8a9265007c5e343 | ttp55/LearnPy | /CodeWars/23.py | 486 | 3.6875 | 4 | # @Time : 2019/8/23 8:42
# @Author : WZG
# --coding:utf-8--
def count_smileys(arr):
x = 0
print(arr)
for i in arr:
if (';' and 'D' in i) or (':' and 'D' in i) or (';' and ')' in i) or (':' and ')' in i):
if i.count('o') == 0:
l = list(i)
if (l[0] == ';') or (l[0] == ':'):
x += 1
else:
return None
return x
print(count_smileys([')', ':(', 'D', ':O', ':;']))
|
fb30f8d4922cf5613862eb7a668a8c41d206ab70 | CarloAviles/PythonTesting | /pythonSelenium/explicitWaitDemo.py | 1,727 | 3.75 | 4 | # Using explicit wait
# A diferencia del modo implicito, esta forma se debe especificar el elemento poel que se va
# a esperar que aparezca, siendo este más eficiente que el Implicito que es global."
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.maximize_window()
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element_by_css_selector("input.search-keyword").send_keys("ber")
time.sleep(4)
count = len(driver.find_elements_by_xpath("//div[@class='products']/div"))
assert count == 3
# Accediendo a través del padre para solo seleccionar los elementos de compra
buttons = driver.find_elements_by_xpath("//div[@class='product-action']/button")
for button in buttons:
button.click()
print("linea 24")
driver.find_element_by_css_selector("img[alt='Cart']").click()
driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click()
print("linea 28")
wait = WebDriverWait(driver, 10)
wait.until(expected_conditions.presence_of_element_located((By.CLASS_NAME, "promoCode")))
print("linea 31")
driver.find_element_by_class_name("promoCode").send_keys("rahulshettyacademy")
driver.find_element_by_css_selector(".promoBtn").click()
print("linea 33")
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "span.promoInfo")))
#espera.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "span.promoInfo")))
print("linea 36")
print(driver.find_element_by_css_selector("span.promoInfo").text)
print("linea 38")
|
6b97834e3013ff12e4c59d5bde5d6b371731e8d2 | Woobs8/data_structures_and_algorithms | /Python/DataStructures/Queues/de_queue.py | 3,396 | 4.1875 | 4 | import argparse
import random
import math
class DEQueue():
"""
A class encapsulating a double-ended queue data structure
Attributes
----------
queue (list)
The list representing the ordered double-ended queue
len (int)
The current length of the queue
max_len (int)
The maximum allowed length of the queue
Methods
-------
append
Insert an element at the back of the queue
append_left
Insert an element at the front of the queue
pop
Remove an element from the back of the queue
pop_left
Remove an element from the front of the queue
"""
def __init__(self, iterable, max_len=None):
self.queue = []
self.len = 0
self.max_len = max_len if max_len else math.inf
if iterable:
for x in iterable:
if self.len < self.max_len:
self.queue.append(x)
self.len += 1
def __repr__(self):
return str(self.queue)
def append(self, data):
"""
Insert an element at the back of the queue
Parameters:
data (Object): element to insert
Returns:
None
"""
if self.len < self.max_len:
self.queue.append(data)
self.len += 1
else:
raise IndexError
def append_left(self, data):
"""
Insert an element at the front of the queue
Parameters:
data (Object): element to insert
Returns:
None
"""
if self.len < self.max_len:
self.queue = [data] + self.queue
self.len += 1
else:
raise IndexError
def pop(self):
"""
Remove an element from the back of the queue
Parameters:
-
Returns:
Object: value of popped element
"""
if self.len > 0:
elmt = self.queue[-1]
self.queue.pop()
self.len -= 1
return elmt
else:
raise IndexError
def pop_left(self):
"""
Remove an element from the front of the queue
Parameters:
-
Returns:
Object: value of popped element
"""
if self.len > 0:
elmt = self.queue[-1]
self.queue = self.queue[1:]
self.len -= 1
return elmt
else:
raise IndexError
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Implementation of a standard and double-ended queue')
parser.add_argument('len', help='length of queue', type=int)
args = parser.parse_args()
n = args.len
# init double-ended queue
de_queue = DEQueue(range(n))
# print initial queue
print(de_queue)
print('Queue length: {}'.format(de_queue.len))
# add elements to queue
de_queue.append(50)
de_queue.append(51)
de_queue.append_left(52)
de_queue.append_left(53)
# print extended queue
print(de_queue)
print('Queue length: {}'.format(de_queue.len))
# pop elements from queue
de_queue.pop()
de_queue.pop()
de_queue.pop_left()
de_queue.pop_left()
# print extended queue
print(de_queue)
print('Queue length: {}'.format(de_queue.len)) |
c0295c476cb83437e2e0836a931c975e7108714e | Skati/boring_stuff | /04_commacode.py | 144 | 3.6875 | 4 | spam = ['apples', 'bananas', 'tofu', 'cats']
def convert(spam):
a=','.join(spam[:len(spam)-1])+' and '+spam[-1]
print(a)
convert(spam)
|
f6f6d76d65cab93ceeb3a4c74a962f10f6ed21ea | ahmedelsers/Exercises_for_Programmers_57_Challenges | /03_printing_quotes.py | 292 | 4.125 | 4 | #!/usr/bin/env python3
quote = input("What is the quote? ")
who_said_it = input("Who said it? ")
print(who_said_it + " says, " + quote)
# Challenge
quotes = {"Obi-Wan Kenobi": "These aren't the droids you're looking for."}
for who, quote in quotes.items():
print(who + " says, " + quote) |
38c1ded804454b86f9ff79f9c82460195c4e53f5 | AnamIslam/PatternRecognitionLab | /Lab 1/PatternExp.py | 271 | 3.6875 | 4 | print("Enter Number of Train Data : ")
inpt = input()
n = int(inpt)
weight = []
height = []
label = []
print("Enter Train Data : \n")
#for i in range(n):
w,h,l = input().split()
m=w+h
print(m)
print(l)
#weight=int(w)
#height=int(h)
#label=l;
|
4d2e546234c723805125a157d98b586cec83027f | HEERAMANI26/python-programming | /for_loop.py | 3,763 | 4.25 | 4 | # for loop
'''n1 =int(input("Enter 1st number:"))
n2 =int(input("Enter 2nd number:"))
for i in range(n1,n2+1):
print(i)'''
# prime number
'''n1 =int(input("Enter 1st number:"))
count =0
for i in range(1,n1+1):
if (n1 % i == 0):
count = count+1
i = i-1
if count ==2:
print(n1)
else:
print("not prime number")'''
#print table
'''n =int(input("Enter number which you want to print:"))
a =0
for i in range(1,10+1):
if i > 0:
print(n*i)'''
#function related problem
'''def add():
a =int(input("Enter 1st number:"))
b =int(input("Enter 2nd number:"))
c =a+b
print(c)
add()'''
#without arguments
'''def fun():
a =int(input("Enter 1st number:"))
b =int(input("Enter 2nd number:"))
sum=0
i=1
while i <=10:
sum+=i
print(sum)
i=i+1
fun()'''
#with argument
'''def mulitplication(a,b):
c =a*b
print(c)
mulitplication(5,-1)'''
#odd even number without no arguments
'''def odd_even():
n =int(input("Enter number:"))
if n % 2==0:
print("even")
else:
print("odd")
odd_even()'''
#odd even with arguments
'''def odd_even(n):
if n % 2 ==0:
print("even number")
else:
print("odd number")
odd_even(9)
'''
# NAWR
'''def add():
a =int(input("Enter 1st number:"))
b =int(input("Enter 2nd number:"))
c =a+b
return c
x =add()
print(x)'''
#WAWR
'''def sub(a,b):
c=a-b
return c
x=sub(5,-10)
print(x)'''
#WANR
'''def add(a,b):
c=a+b
print(c)
a =int(input("Enter 1st number:"))
b =int(input("Enter 2nd number:"))
add(a,b)'''
#default
'''def add(a,b,c=5):
d=a+b+c
print(d)
add(1,2)'''
'''def add(a=5,b,c=5):
d=a+b+c
print(d)
add(1,3,6)'''
#break
'''i=0
while i <=5:
if (i==3):
break
print(i)
i=i+1'''
#continue
'''i=0
while i<=5:
i=i+1
if(i==4):
continue
print(i)'''
#count vowel or consonant
'''a =input("enter your name:")
vowel=0
cons=0
for i in range(0,len(a)):
if (a[i]!=''):
if(a[i] =='a' or a[i] =='e' or a[i] == 'i' or a[i] == 'o' or a[i] == 'u' or a[i] =='A' or
a[i] =='E' or a[i] == 'I' or a[i] == 'O' or a[i] =='U'):
vowel = vowel+1
else:
cons = cons+1
print("total number of vowel",vowel)
print("total number of cons",cons)'''
'''a =["ram","shyam","radha","Geeta","seeta","ram"]
x =a.count("ram")
print(x)
'''
'''a=[]
for i in range(5):
x = input("Enter item to add in list:")
a.append(x)
y =input("Enter value whose frequency wants to count:")
f= a.count(y)
print(a,f)'''
#index
'''a =["ram","seeta","ram","geeta"]
y=a.index("geeta")
print(y)'''
'''a =[]
for i in range(5):
x =input("Enter list which you wants to add:")
a.append(x)
y =input("enter value which you wants to find index value:")
f =a.index(y)
print(a,f)'''
#count
'''a =[]
for i in range(5):
x =input("Enter list which you wants to add:")
a.append(x)
y =input("Enter value which you wants to insert: ")
f =a.insert(3,y)
print(a,f)
'''
'''num =int(input("Enter number:"))
count =0
while (num>0):
count = count+1
num =num//10
print(count)'''
'''num =int(input("Enter number:"))
count=0
for i in range(1,num+1):
if num %i == 0:
count=count+1
i=i-1
if count==2:
print("prime number",num)
else:
print("not prime number",num)
'''
'''i =int(input("Enter number:"))
fac=1
while i>0:
fac =fac*i
i=i-1
print(fac)'''
num =int(input("Enter number:"))
x =0
y=1
z=0
sum =0
while num>0:
sum=sum +
|
c3bd244b9acf0986f6cfd8f58d28dc12011ca25b | byAbaddon/Essentials-Course-with----JavaScript___and___Python | /Python Essentials/3.0 Conditional Statements/07. Area of Figures.py | 411 | 3.890625 | 4 | def area_of_figures(figure):
num_a = float(input())
num_b = 0
if figure == 'rectangle' or figure == 'triangle':
num_b = float(input())
switch = {
'square': num_a * num_a,
'rectangle': num_a * num_b,
'circle': num_a * num_a * 3.14159,
'triangle': num_a * num_b / 2,
}
return f'{switch[figure]:.3f}'
print(area_of_figures(input()))
|
ee82adcd9ad22e464c6bcdc70ac1ba72df08bd19 | jgabdiaz/mycode | /testmod | 100 | 3.625 | 4 | #!/usr/bin/env python3
def Mult_3(x):
if x % 3 = 0:
return True
x=9
print(Mult_3(x))
|
9baa1b24e50bf3e268a89f0b65b902e38dda3f2a | anushreedas/Classification | /a1.py | 7,503 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
"""
a1.py
This program implements least-squares linear classifier and k-nearest neighbor classifier
and plots 1) the training samples 2) the decision boundary separating class 0 and 1,
and 3) the classification regions.
@author: Anushree Das (ad1707)
"""
def least_squares(X,y):
"""
Implements the least-squares linear classifier
:param X: Input Features
:param y: Output Class
:return:
"""
print(' Least-Squares Linear Classifier '.center(50, '#'))
# add extra column of ones to X for calculating dot product with weights with bias bit
X_new = np.hstack((np.ones((len(X), 1)), X))
# calculate weights
beta = (np.linalg.inv(X_new.T.dot(X_new)).dot(X_new.T).dot(y))
# plot decision boundary and classification region
plot_training_samples(X, y)
plot_classification(X,y,'ls',beta=beta)
y_pred = least_squares_predict(X_new,beta)
confusion_matrix(y,y_pred)
def k_nearest_neighbors(X,y,n):
"""
Implements the k-nearest neighbor classifier
:param X: Input Features
:param y: Output Class
:param n: Number of nearest neighbors
:return:
"""
print('\n',(' '+str(n)+'- Nearest Neighbor Classifier ').center(50, '#'))
# plot decision boundary and classification region
plot_training_samples(X, y)
plot_classification(X,y,str(n)+'nn',n=n)
y_pred = nearest_neighbors_predict(X,y,X, n)
confusion_matrix(y, y_pred)
def plot_training_samples(X, y):
"""
Plots the training samples
:param X: Input Features
:param y: Output Class
:return:
"""
plt.xlabel('feature 1')
plt.ylabel('feature 2')
# assign color for each input according to its output class
colors = get_colors(y)
# plot features
plt.scatter(X[:, 0], X[:, 1],marker='o', s=20, facecolors='none',edgecolors=colors)
def plot_classification(X,y,name,beta=None,n=0):
"""
Plots the decision boundary and classification region
:param X: Input Features
:param y: Output Class
:param name: plot name
:param beta: weights for least square classifier
:param n: Number of nearest neighbors for n-nearest neighbors
:return:
"""
# find min and max values of both features
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x_vals, y_vals = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1))
if beta is None:
# k-nearest neighbors classifier
X_all = np.c_[x_vals.ravel(), y_vals.ravel()]
# Predict class for all combinations of values of both features
predictions = nearest_neighbors_predict(X, y, X_all, n)
z = predictions.reshape(x_vals.shape)
# draw decision boundary
plt.contour(x_vals, y_vals, z,linewidths=0.5,levels=[0.9,1], colors=['black'])
else:
# least-squares linear classifier
# different x and y values to get smooth line
x_vals_new, y_vals_new = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
X_all = np.c_[np.ones((len(x_vals_new.ravel()), 1)),x_vals_new.ravel(), y_vals_new.ravel()]
# Predict class for all combinations of values of both features
predictions = least_squares_predict(X_all, beta)
z = predictions.reshape(x_vals_new.shape)
# draw decision boundary
plt.contour(x_vals_new, y_vals_new, z, linewidths=0.5,levels = [0.9,1], colors=['black'])
X_all = np.c_[np.ones((len(x_vals.ravel()), 1)), x_vals.ravel(), y_vals.ravel()]
# Predict class for all combinations of values of both features
predictions = least_squares_predict(X_all,beta)
# assign color for each input according to its output class
colors = get_colors(predictions)
# plot classification region
plt.scatter(x_vals, y_vals, s=0.1, color=colors)
# plt.savefig(name+'_decision_boundary.png')
plt.show()
def get_colors(classlabels):
"""
Returns array of colors based on output labels
:param classlabels: Output labels
:return: array of colors
"""
# assign color for each input according to its output class
colors = []
for c in classlabels:
if c == 0:
colors.append('skyblue')
else:
if c == 1:
colors.append('orange')
return colors
def least_squares_predict(X,beta):
"""
Predict class using least square classifier weights
:param X: Input Features
:param beta: Weights
:return: Output labels
"""
y_pred = threshold(X.dot(beta))
return y_pred
def threshold(y_pred):
"""
Threshold the class probabilities to categorize into class labels 0 or 1
:param y_pred: array of class probabilities
:return: array of class labels
"""
y_pred_thresh = np.zeros(y_pred.shape)
for i in range(len(y_pred)):
if y_pred[i] > 0.5:
y_pred_thresh[i] = 1
else:
y_pred_thresh[i] = 0
return y_pred_thresh
def nearest_neighbors_predict(X_train,y_train,X_test,n):
"""
Predict class using n-nearest neighbors classifier
:param X_train: Training sample input features
:param y_train: Training sample output labels
:param X_test: Test sample input features
:param n: Number of nearest neighbors for n-nearest neighbors
:return: Test sample output labels
"""
y_pred = []
# for every features vector in test sample
for test_sample in X_test:
dist = []
# calculate its distance from every features vector in training sample
for train_sample in X_train:
dist.append(euclidean_dist(test_sample,train_sample))
# find n nearest neighbors
asc_order = np.argsort(dist)
nearest_labels = []
for i in range(n):
nearest_labels.append(y_train[asc_order[i]])
# assign the most common class label from the n nearest neighbors
y_pred.append(max(nearest_labels, key = nearest_labels.count))
return np.array(y_pred)
def euclidean_dist(x,y):
"""
Calculates euclidean distance between two points x and y
:param x: first point
:param y: second point
:return: distance between two points
"""
return math.sqrt(((x[0]-y[0])**2)+((x[1]-y[1])**2))
def confusion_matrix(y,y_pred):
correct_0 = 0
correct_1 = 0
wrong_0 = 0
wrong_1 = 0
for i in range(len(y_pred)):
if y_pred[i] == y[i]:
if y[i] == 0:
correct_0 += 1
else:
correct_1 += 1
else:
if y[i] == 0:
wrong_0 += 1
else:
wrong_1 += 1
print("{:<15} {:^20}".format(' ', 'Ground Truth'))
print("{:>15} {:^10} {:^10}".format('Predictions', 'Blue(0)', 'Orange(1)'))
print('_'*40)
print("{:>15} {:^10} {:^10}".format('Blue(0)',correct_0,wrong_1))
print("{:>15} {:^10} {:^10}".format('Orange(1)',wrong_0,correct_1))
print('_' * 40)
def main():
# load data
data = np.load("data.npy")
# array of features
X = data[:,:-1]
# array of output class for corresponding feature set
y = data[:,-1]
# least-squares linear classifier
least_squares(X,y)
# 1-nn (nearest neighbor) classifier
k_nearest_neighbors(X, y, 1)
# 15-nn (nearest neighbor) classifier
k_nearest_neighbors(X, y, 15)
if __name__ == '__main__':
main()
|
7fb6457b668ad3f28fa62cca7e48d42a2a916cd3 | joao29a/traveling-salesman | /graph_gen.py | 610 | 3.703125 | 4 | #!/usr/bin/python
from sys import argv
from random import random
#generate a complete graph
def main():
if len(argv) > 3:
f = open(argv[1], 'w')
for i in range(1, int(argv[2]) + 1):
pos_x = random()*int(argv[3]) + 1
pos_y = random()*int(argv[3]) + 1
if (.01 > random()):
pos_x = -pos_x
if (.01 > random()):
pos_y = -pos_y
f.write("%d %d %d\n" % (i, pos_x, pos_y))
f.close()
else:
print "Insert file name, total vertices, max distance\n"
if __name__ == '__main__':
main()
|
82e97fb389912265ddaf83c38dd860110ab8105f | Jorewang/LeetCode_Solutions | /657. Robot Return to Origin.py | 496 | 3.625 | 4 | class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
right = left = up = down = 0
for m in moves:
if m == 'R':
right += 1
if m == 'L':
left += 1
if m == 'U':
up += 1
if m == 'D':
down += 1
if right == left and up == down:
return True
else:
return False
|
8f1555b7466734a20a715da46be61f59780311c5 | haveano/codeacademy-python_v1 | /05_Lists and Dictionaries/01_Python Lists and Dictionaries/09_More with for.py | 809 | 4.6875 | 5 | """
More with 'for'
If your list is a jumbled mess, you may need to sort() it.
animals = ["cat", "ant", "bat"]
animals.sort()
for animal in animals:
print animal
First, we create a list called animals with three strings. The strings are not in alphabetical order.
Then, we sort animals into alphabetical order. Note that .sort() modifies the list rather than returning a new list.
Then, for each item in animals, we print that item out as "ant", "bat", "cat" on their own line each.
Instructions
Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list.
Then sort square_list!
"""
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for x in start_list:
square_list.append(x**2)
print square_list
square_list.sort()
print square_list
|
65ee3829f70b1b116d1fde5731cd83ee424699ad | TzStrikerYT/holbertonschool-web_back_end | /0x03-caching/100-lfu_cache.py | 1,749 | 3.75 | 4 | #!/usr/bin/python3
""" BasicCaching module
"""
from base_caching import BaseCaching
class LFUCache(BaseCaching):
"""LIFO Cache"""
def __init__(self):
"""Init the instance"""
super().__init__()
self.stack = []
self.stack_count = {}
def put(self, key, item):
"""Assing a key to a value."""
if key is None or item is None:
return
self.cache_data[key] = item
item_count = self.stack_count.get(key, None)
if item_count is not None:
self.stack_count[key] += 1
else:
self.stack_count[key] = 1
if len(self.cache_data) > BaseCaching.MAX_ITEMS:
to_discard = self.stack.pop(0)
del self.stack_count[to_discard]
del self.cache_data[to_discard]
print("DISCARD: {}".format(to_discard))
if key not in self.stack:
self.stack.insert(0, key)
self.move_to_right(item=key)
def get(self, key):
""" return the value in self.cache_data linked to key."""
value = self.cache_data.get(key, None)
if value is not None:
self.stack_count[key] += 1
self.move_to_right(item=key)
return value
def move_to_right(self, item):
"""Add 1 for all elements less the key"""
length = len(self.stack)
idx = self.stack.index(item)
item_count = self.stack_count[item]
for i in range(idx, length):
if i != (length - 1):
nxt = self.stack[i + 1]
nxt_count = self.stack_count[nxt]
if nxt_count > item_count:
break
self.stack.insert(i + 1, item)
self.stack.remove(item)
|
492f7b200620f4bb54e80c58bb03adca6f5e10f0 | jColeChanged/MIT | /Computer Science 6.00 SC/test.py | 4,673 | 3.703125 | 4 | from random import *
class Card(object):
RANKS = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
SUITS = ["C","D","H","S"]
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep
class Deck(object) :
def __init__(self):
self.cards=[]
def __str__(self):
if self.cards:
rep=""
for card in self.cards:
rep += str(card) + " "
else:
rep= "Empty"
return rep
def addCard(self,card) :
self.cards.append(card)
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.addCard(Card(rank,suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def removeCard(self, card1):
for card in self.cards:
if card.rank == card1.rank and card.suit == card1.suit:
self.cards.remove(card)
def isEmpty(self):
if self.cards == []:
return 1
def deal(self, hands, nCards=999):
nHands = len(hands)
for i in range(nCards):
if self.isEmpty():
break # break if out of cards
else:
card = self.cards[0]
print card
hand = hands[i % nHands]
print i
hand.addCard(card)
self.removeCard(card)
def printHands(self):
print self
class Hand(Deck):
def __init__(self, name=""):
self.cards = []
self.name = name
def __str__(self):
s = "Hand " + self.name
if self.isEmpty():
return s + " is empty\n"
else:
return s + " contains\n" + Deck.__str__(self)
def addCard(self,card) :
self.cards.append(card)
def printHands(self):
print self
class CardGame:
def __init__(self):
self.deck = Deck()
print(self.deck)
self.deck.populate()
print(self.deck)
self.deck.shuffle()
def printHands(self, names):
for name in names:
print "Hand " + name+ " contains"
print OldMaidHand(name)
class OldMaidGame(CardGame):
def printHands(self, names):
for name in names:
print "Hand " + name+ " contains"
print OldMaidHand(name)
def removeAllMatches(self):
count = 0
for hand in self.hands:
count = count + hand.removeMatches()
return count
def playOneTurn(self, i):
if self.hands[i].isEmpty():
return 0
neighbor = self.findNeighbor(i)
pickedCard = self.hands[neighbor].popCard()
self.hands[i].addCard(pickedCard)
print "Hand", self.hands[i].name, "picked", pickedCard
count = self.hands[i].removeMatches()
self.hands[i].shuffle()
return count
def play(self, names):
# remove Queen of Clubs
card1 = Card("Q","C")
print card1
self.deck.removeCard(card1)
print "Queen of Clubs removed."
print self.deck
# make a hand for each player
self.hands = []
for name in names :
self.hands.append(OldMaidHand(name))
self.printHands(names)
# deal the cards
print (self.deck)
self.deck.deal(self.hands,51)
print "---------- Cards have been dealt"
self.printHands(self.hands)
# remove initial matches
matches = self.removeAllMatches()
print "---------- Matches discarded, play begins"
self.printHands(names)
# play until all 50 cards are matched
turn = 0
numHands = len(self.hands)
while matches < 25:
matches = matches + self.playOneTurn(turn)
turn = (turn + 1) % numHands
print "---------- Game is Over"
self.printHands(names)
class OldMaidHand(Hand):
def removeMatches(self):
count = 0
originalCards = self.cards[:]
for card in originalCards:
match = Card(3 - card.suit, card.rank)
if match in self.cards:
self.cards.removeCard(card)
self.cards.remove(match)
print "Hand %s: %s matches %s" % (self.name,card,match)
count = count + 1
return count
game = OldMaidGame()
game.play(["Allen","Jeff","Chris"])
|
a9a5c6845049c8bf840c30b84d00b95b425b46ff | newwhy/python-ch2.8 | /paint.py | 593 | 3.734375 | 4 | #바로 Point를 이 안에서 정의
from point import Point
def test_bound_instance_method():
p = Point()
p.set_x(10)
p.set_y(20)
#print(p.get_x(), p.get_y())
p.show()
print(p.count_of_instance)
def test_unbound_class_method():
p = Point()
Point.set_x(p, 10)
Point.set_y(p, 20)
print(Point.get_x(p), Point.get_y(p))
def test_othermethod():
Point.class_method()
Point.static_method()
def main():
# test_othermethod()
# test_unbound_class_method()
test_bound_instance_method()
if __name__ == '__main__':
main()
|
b49c2ba966e37c93f70b5497d46b568b487bdf26 | m-mcneive/McNeive_ENVS | /src/co2Emmisions.py | 1,198 | 3.875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress
"""
This source had measurements of the carbon emissions of various countries. It also has measurements
of the continents as a whole. These are the measurements that I used because once visualized this will
be easier to read. The program below extracts just the values for the continents as a whole and plots
them on a line graph.
https://ourworldindata.org/co2-emissions
"""
#Reads the CSV
df = pd.read_csv('data/annual-co2-emissions-per-country (1).csv')
#Creates the list that will store the values to be used in the DataFrame
lst = []
continents = ['Africa', 'Asia', 'Europe', 'North America', 'South America']
#Iterates through all rows of the CSV
for row in df.iterrows():
#Checks for rows involving continents as a whole
if row[1][0] in continents:
lst.append([row[1][0], row[1][2], row[1][3]])
data = pd.DataFrame(lst, columns = ['Continent', 'Year', 'Emissions'])
#Pivots the data to be better visualized
data = data.pivot(index='Year', columns='Continent', values='Emissions')
ax = data.plot(title = "CO2 emission by continent")
ax.set_ylabel("Billion tons of CO2")
plt.show()
|
9afe02d9df0261e24cfb45ee7b17b6c2ee4194ce | Do-code-ing/Python_Built-ins | /Methods_Set/difference_update.py | 256 | 3.5625 | 4 | # set_a.difference_update(set_b)
# 집합 a와 집합 b의 차집합을 집합 a에 갱신한다.
a = {1,2,3,4}
b = {3,4,5,6}
a.difference_update(b)
print(a)
# {1, 2}
# 다음과 같이 표현할 수도 있다.
a = {1,2,3,4}
b = {3,4,5,6}
a -= b
print(a) |
c66b9cd5379353ac41204979a9170b576948113d | vaibhavranjith/Heraizen_Training | /Assignment2/Asmt2Q4.py | 557 | 3.75 | 4 | def binarySearch(data,p):
c=0
for i in range(0,len(data)):
pattern=True
if(i+len(p)<len(data)+1):
for j in range(0,len(p)):
if(data[i+j]!=p[j]):
pattern=False
if pattern and i+len(p)<len(data)+1 :
c+=1
print(c)
vowels=['a','e','i','o','u']
s=input("Enter data:")
for i in s:
if i in vowels:
s=s.replace(i,"0")
else:
s=s.replace(i,"1")
print("Modified: "+s)
p=input("Enter a pattern:")
print(binarySearch(s,p))
|
65551a51fbb5efbdfd18af4ac7dfd92a8f524352 | Yogesh-Singh-Gadwal/YSG_Python | /Core_Python/Day-12/42.py | 173 | 3.796875 | 4 | # String
# join
l1 = ['Y','o','g','e','s','h']
print(''.join(l1))
print()
print(' '.join(l1))
print()
print(' - '.join(l1))
print()
print('_'.join(l1))
|
e6e9185bf761fa2d93d92c236a0957092e0a07a9 | deeksha-malhotra/Coding-Interview-Preparation | /Python_/LinkedList/single_linked_list/merge_to_list.py | 899 | 4.125 | 4 | from linked_list import LinkedList
list1 = LinkedList()
list1.append("1")
list1.append("5")
list1.append("7")
list1.append("9")
list1.append("10")
list2 = LinkedList()
list2.append("2")
list2.append("3")
list2.append("4")
list2.append("6")
list2.append("8")
def merge_to_list(list1, list2):
P = list1.head
Q = list2.head
S = None
if not P:
return Q
if not Q:
return P
if P and Q:
if P.data <= Q.data:
S = P
P = S.next
else:
S = Q
Q = S.next
new_head = S
while P and Q:
if P.data <= Q.data:
S.next = P
S = P
P = S.next
else:
S.next = Q
S = Q
Q = S.next
if not P:
S.next = Q
else:
S.next = P
return new_head
merge_to_list(list1, list2)
list1.print_list()
|
e86ebe9d6e4d0635625900d148ba7d9f1bc2e5b7 | havenshi/leetcode | /206. Reverse Linked List.py | 737 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# iteration
dummy = ListNode(0)
while head:
tmp = head.next
head.next = dummy.next
dummy.next = head
head = tmp
return dummy.next
# recursion
return self.doReverse(head, None)
def doReverse(self, head, newHead):
if head is None:
return newHead
tmp = head.next
head.next = newHead
return self.doReverse(tmp, head) |
4629789848d5f08b5e2d1fea2ce34207303c2c72 | shukriev/sad-python-life | /simpleDS/vowels_dict.py | 900 | 3.96875 | 4 | vowels = ['h', 'i', 't', 'c', 'h', 's', 'i', 'k', 'e', 'r', 'a', 'h']
word = input("Provide a word to search for vowels: ")
found = {}
print("Print Vowels First")
print(vowels)
print()
print("Print Found Second")
print(found)
print("------------------------------------")
for letter in word:
if letter in vowels:
if letter in found:
found[letter] += 1
else:
found[letter] = 1
# ----------------------------
# Option 2 by using setdefault
# if letter in found:
# found.setdefault(letter, 0)
# found[letter] += 1
print(found)
print("------------------------------------")
for k in sorted(found):
print(k, "was found", found[k], "times.")
print("------------------------------------")
for k, v in found.items():
print(k, "was found", v, "times.")
print('h' in found)
print('z' in found)
|
f6c42704b454d2f4319cdf83fba20b82f2f8ee81 | chinrw/WeatherBot | /GetWeather_Data.py | 970 | 3.609375 | 4 | #!/usr/bin/env python
import json
import urllib
import urllib2
from pprint import pprint
def get_weather_data(api_key, request_type, location):
# return a dict data that coutains required information
url = 'http://api.wunderground.com/api/%s/%s/%s.json'\
% (api_key, request_type,location)
req = urllib2.Request(url)
content = urllib2.urlopen(req).read()
data = json.loads(content)
return data
def location_autocomplete(input):
"""
return a series of candidates output or return "can't find this place"
"""
url = 'http://autocomplete.wunderground.com/aq?query=%s' %(input)
req = urllib2.Request(url)
content = urllib2.urlopen(req).read()
data = json.loads(content)
return data
if __name__ == "__main__":
cityid = 5141502
location = '/q/zmw:12180.1.99999'
#print get_weather_data(api_key, "conditions",location)
pprint(location_autocomplete("troy"))
|
3849baa2222e81274417969e93cc746d4784e381 | gioiab/py-collection | /challenges/chat/chat_server.py | 7,438 | 3.828125 | 4 | """
Created on 23/11/2015
@author: gioia
This script runs a simple ChatServer built with sockets.
The code is organized as follows:
- the ChatServer class defines the behaviour of the server;
- the main module function simply executes the server.
The programming language used is Python 2.7 and it is assumed you have it installed into your PC.
The operating system of reference is Linux. There are two basic ways to execute this script in Linux:
1 - launching it by the command shell through the python command;
2 - making it executable first and then launching it by the command shell.
Enjoy!
"""
import math
import struct
import socket
import select
import threading
_HOST = '127.0.0.1' # defines the host as "localhost"
_PORT = 10000 # defines the port as "10000"
class ChatServer(threading.Thread):
"""
Defines the chat server as a Thread.
"""
MAX_WAITING_CONNECTIONS = 10 # defines the max number of accepted waiting connections before the rejection
RECV_BUFFER = 4096 # defines the size (in bytes) of the receiving buffer
RECV_MSG_LEN = 4 # defines the size (in bytes) of the placeholder contained at the beginning of the messages
def __init__(self, host, port):
"""
Initializes a new ChatServer.
:param host: the host on which the server is bounded
:param port: the port on which the server is bounded
"""
threading.Thread.__init__(self)
self.host = host
self.port = port
self.connections = [] # collects all the incoming connections
self.running = True # tells whether the server should run
def _bind_socket(self):
"""
Creates the server socket and binds it to the given host and port.
"""
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(self.MAX_WAITING_CONNECTIONS)
self.connections.append(self.server_socket)
def _send(self, sock, msg):
"""
Prefixes each message with a 4-byte length before sending.
:param sock: the incoming socket
:param msg: the message to send
"""
# Packs the message with 4 leading bytes representing the message length
msg = struct.pack('>I', len(msg)) + msg
# Sends the packed message
sock.send(msg)
def _receive(self, sock):
"""
Receives an incoming message from the client and unpacks it.
:param sock: the incoming socket
:return: the unpacked message
"""
data = None
# Retrieves the first 4 bytes from the message
msg_len = sock.recv(self.RECV_MSG_LEN)
# If the message has the 4 bytes representing the length...
if msg_len:
data = ''
# Unpacks the message and gets the message length
msg_len = struct.unpack('>I', msg_len)[0]
# Computes the number of expected chunks of RECV_BUFFER size
chunks = int(math.ceil(msg_len / float(self.RECV_BUFFER)))
for _ in xrange(chunks):
# Retrieves the chunk i-th chunk of RECV_BUFFER size
chunk = sock.recv(self.RECV_BUFFER)
# If there isn't the expected chunk...
if not chunk:
data = None
break # ... Simply breaks the loop
else:
# Merges the chunks content
data += chunk
return data
def _broadcast(self, client_socket, client_message):
"""
Broadcasts a message to all the clients different from both the server itself and
the client sending the message.
:param client_socket: the socket of the client sending the message
:param client_message: the message to broadcast
"""
for sock in self.connections:
is_not_the_server = sock != self.server_socket
is_not_the_client_sending = sock != client_socket
if is_not_the_server and is_not_the_client_sending:
try :
self._send(sock, client_message)
except socket.error:
# Handles a possible disconnection of the client "sock" by...
sock.close() # closing the socket connection
self.connections.remove(sock) # removing the socket from the active connections list
def _run(self):
"""
Actually runs the server.
"""
while self.running:
# Gets the list of sockets which are ready to be read through select non-blocking calls
# The select has a timeout of 60 seconds
try:
ready_to_read, ready_to_write, in_error = select.select(self.connections, [], [], 60)
except socket.error:
continue
else:
for sock in ready_to_read:
# If the socket instance is the server socket...
if sock == self.server_socket:
try:
# Handles a new client connection
client_socket, client_address = self.server_socket.accept()
except socket.error:
break
else:
self.connections.append(client_socket)
print "Client (%s, %s) connected" % client_address
# Notifies all the connected clients a new one has entered
self._broadcast(client_socket, "\n[%s:%s] entered the chat room\n" % client_address)
# ...else is an incoming client socket connection
else:
try:
data = self._receive(sock) # Gets the client message...
if data:
# ... and broadcasts it to all the connected clients
self._broadcast(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
except socket.error:
# Broadcasts all the connected clients that a clients has left
self._broadcast(sock, "\nClient (%s, %s) is offline\n" % client_address)
print "Client (%s, %s) is offline" % client_address
sock.close()
self.connections.remove(sock)
continue
# Clears the socket connection
self.stop()
def run(self):
"""Given a host and a port, binds the socket and runs the server.
"""
self._bind_socket()
self._run()
def stop(self):
"""
Stops the server by setting the "running" flag to close before closing
the socket connection.
"""
self.running = False
self.server_socket.close()
def main():
"""
The main function of the program. It creates and runs a new ChatServer.
"""
chat_server = ChatServer(_HOST, _PORT)
chat_server.start()
if __name__ == '__main__':
"""The entry point of the program. It simply calls the main function.
"""
main()
|
d0e803738e681ddc50692eac607e46a78a47d823 | BennyJane/python-demo | /设计模式/1.0抽象工厂.py | 1,128 | 4 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/11/2
# @Author : Benny Jane
# @Email : 暂无
# @File : 抽象工厂.py
# @Project : Python-Exercise
class PetShop:
def __init__(self, animal_factory=None):
"""PetShop 本身就是一个抽象工厂"""
self.pet_factory = animal_factory
def show_pet(self):
"""animal_factory 需要实现的三个接口:get_pet, speak,get_food"""
pet = self.pet_factory.get_pet()
print("This is a lovely", pet)
print("It says", pet.speak())
print("It eats", self.pet_factory.get_food())
class Dog:
"""Dog 类自身没有实现PetShop所需要的接口"""
def speak(self):
return "woof"
def __str__(self):
return "Dog"
# todo 非继承方式 ==》 可以通过继承实现同样的效果
class DogFactory:
"""当原始类不方便修改的时候,可以使用该工厂模式"""
def get_pet(self):
return Dog()
def get_food(self):
return "dog food"
if __name__ == '__main__':
shop = PetShop()
shop.pet_factory = DogFactory()
shop.show_pet()
print("=" * 20)
|
ba46ac180da4ad1b26648367f7055c7578dc30d6 | gr8rithic/Simple_Codes_Python | /largest of three.py | 197 | 4.0625 | 4 |
a=input("Enter a,b and c \n")
b=input()
c=input()
if a>b and a>c:
print(a," is the largest")
elif b>c and b>a:
print(b," is the largest")
else :
print(c," is the largest")
|
d24853429cf59f596718ecc9589f049c893680cb | magshi/hackbright | /Whiteboarding/Puzzles/task8.py | 533 | 4.40625 | 4 | #!/bin/env python
"""
Given two dictionaries, d1 and d2, update the contents of d1 with the contents of d2, overwriting any existing keys
eg:
d1 = {"a":1, "b":2}
d2 = {"a":3, "c":4}
becomes
d1 = {"a":3, "b":2, "c":4}
"""
d1 = {"a": 5, "c": 7, "d": 9, "q": 15}
d2 = {"a": 6, "e": 13, "g": 6, "q": 1}
def overwrite_dict(d1, d2):
for d2_key, d2_value in d2.iteritems():
if d2_key in d1:
print "Overwriting %r with %r for key %r" % (d1[d2_key], d2_value, d2_key)
d1[d2_key] = d2_value
overwrite_dict(d1, d2) |
48bbd73294c631013d4fc618b84d32dedba74189 | ramjal/python-sandbox | /think_python/chapter_10/exercise10.8.py | 589 | 3.59375 | 4 | import random
def has_duplicates(my_list):
lcopy = my_list[:]
lcopy.sort()
for i in range(len(lcopy)-1):
if lcopy[i] == lcopy[i+1]:
return True
return False
def birthday_paradox():
students = []
for i in range(23):
students.append(random.randint(15, 99))
# print(students)
# students.sort()
# print(students)
return has_duplicates(students)
probability = 0
for i in range(1, 100):
if birthday_paradox() == True:
probability += 1
print('Probability is %%%d' % probability)
# print(birthday_paradox()) |
977b325748fc907d7b13a1976b5b39e59fb9c9c3 | eugeniocarvalho/CursoEmVideoPython | /Python Exercicios/Mundo 1: Fundamentos/4. Condições em Python (if..else)/ex034.py | 371 | 3.796875 | 4 | '''
Escreva um programa que pergunte o salario de um funcionario e calcule o valor de seu aumento
Para salários superiores as 1.250, calule um aumento de 10%,
Para os inferiores ou iguais, o aumento é de 15%
'''
n = float(input('Salario: '))
if n > 1250:
print('Novo salario: R$ {:.2f}'.format(n * 1.1))
else:
print('Novo salario: R$ {:.2f}'.format(n * 1.15))
|
96a4d966350db9b0f44f05a69de682cdae65c5db | kongziqing/Python-2lever | /实战篇/第15章-并发编程/15.6多协程编程/使用gevent模块自动切换.py | 1,539 | 3.5625 | 4 | """
虽然greenlet组件可以实现多协程开发,但是需要由开发者明确地获取指定的切换对象后才可以进行处理,
这样的操作会比较麻烦,而在第三方Python模块中还提供了一个gevent模块,利用此模块还可以实现自动切换处理
本程序利用gevent分别设置了两个协程管理对象,只需要使用sleep()方法就可以自动实现不同协程的操作
"""
import gevent # pip install gevent
info = None # 保存数据
def producer_handle(): # 协程处理函数
global info # 使用全局变量
for item in range(10): # 循环发送数据
if item % 2 == 0: # 发送数据判断
info = "title = 李兴华、content = 软件技术讲师" # 数据生产
else: # 条件不满足
info = "title = yootk、content = www.yootk.com" # 数据生产
print("【生产者】%s" % info) # 输出提示信息
gevent.sleep(1) # 切换延迟
def consumer_handle(): # 协程处理函数
for item in range(10): # 迭代生成数据
print("〖消费者〗%s" % info) # 消费者获取数据
gevent.sleep(1) # 切换延迟
def main(): # 主函数
producer_gevent = gevent.spawn(producer_handle) # 创建协程对象
consumer_gevent = gevent.spawn(consumer_handle) # 创建协程对象
producer_gevent.join() # 协程启动
consumer_gevent.join() # 协程启动
if __name__ == "__main__": # 判断程序执行名称
main()
|
87a0d57d9b17fc0c4c4cd445dd931467fbe81791 | joeylmaalouf/gravity-ball | /gravity_ball.py | 2,923 | 3.890625 | 4 | # JLM - Python Gravity Ball
# Copyright (c) 2014 Joey Luke Maalouf
# import pygame for init, font, display, Rect, event, QUIT, draw
import pygame
#import sys for exit
import sys
#import time for sleep
import time
# -- initialization ------------------------------------------------------------
# Start up pygame with init(), then create and assign our variables.
pygame.init()
# -- objects --
myfont = pygame.font.SysFont("monospace", 16)
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
diameter = 8
startx = starty = 0
ballrect = pygame.Rect(startx, starty, diameter, diameter)
trace = []
# -- colors --
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
# -- forces --
friction = 0.02
gravity = 4
# -- velocity --
Vx = 6.5
Vy = 0
# -- acceleration --
Ax = 0
Ay = gravity
# -- game loop -----------------------------------------------------------------
# This loop iterates once per frame, and each frame should last slightly > 50ms.
# First, we change the acceleration as necessary from friction; then, change the
# velocity by the acceleration and finally, the position by velocity. We make
# sure that the ball isn't offscreen, then we draw everything on the screen.
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
time.sleep(0.05)
# ground friction
if ballrect.bottom >= height:
if abs(Vx) <= friction:
Ax = 0
break
elif Vx < -friction:
Ax = friction
elif Vx > friction:
Ax = -friction
else:
Ax = 0
# change the ball's velocity by its acceleration
Vx += Ax
Vy += Ay
# change the ball's position by its velocity
ballrect.centerx += Vx
ballrect.centery += Vy
# check for the ball bouncing off one of the sides of the screen
if ballrect.left < 0:
Vx = -Vx
if ballrect.right > width:
Vx = -Vx
if ballrect.top < 0:
Vy = -Vy
if ballrect.bottom > height:
Vy = -Vy + Ay
ballrect.bottom = height
# draw the black background, then the red trace dots, then
# the ball's velocity and acceleration, then the ball itself
screen.fill(black)
trace.append(ballrect.center)
for dot in trace:
pygame.draw.circle(screen, red, dot, 1)
vtext = "Vx: %06.2f Vy: %06.2f" % (Vx, Vy)
atext = "Ax: %06.2f Ay: %06.2f" % (Ax, Ay)
vlabel = myfont.render(vtext, 1, white)
alabel = myfont.render(atext, 1, white)
screen.blit(vlabel, (0, 0))
screen.blit(alabel, (0, 16))
pygame.draw.circle(screen, white, ballrect.center, round(ballrect.width/2))
pygame.display.flip()
# finish up by informing the user of how long it took the ball to fully stop
dtext = "done in %03d frames" % len(trace)
dlabel = myfont.render(dtext, 1, green)
screen.blit(dlabel, (width/2-65, height/2-6))
pygame.display.flip()
time.sleep(2)
|
b9d8321147ad2043a93087c2ecc065b1a67820e4 | gHuwk/python_MEPhI | /lab_02/lab_02.py | 1,831 | 3.75 | 4 | # Решение влоб
from random import randint
from math import sin, log, factorial
def main():
print("Введите int k > 0:")
k = int(input())
if k > 0:
x = x_from(k)
print("X = ", x)
ret_z = z(x, k)
print("№{} из последовательности: {}".format(k, ret_z))
print("Сумма первых {} членов:".format(k))
print()
# Решение влоб
print("Медленный способ:", stupid_summa(x, k))
print()
# Решение через модификацию рекурентного соотношенияы
print("Умный способ:", clever_summa(x, k))
table(z, x, k)
else:
print("Некорректный k")
def z(x, k):
d = 2 * k + 1
p = x * k
sign = ((-1) ** k)
return (sign * (x ** d) * sin(p))/(factorial(k) * d)
def x_from(k):
# В задании укаана функция randint. Принимат на вход int, int. Вззял round
return randint(round(log(k + 1)), 2 * k)
def stupid_summa(x, k):
# Решение итеративно складывая
summa = 0
i = 1
while(i <= k):
summa += z(x, i)
print(z(x, i))
i += 1
return summa
def factor_from(x, n):
return ((-1) * (x ** 2) * ((2 * n + 1) * sin(n * x + x)))/(((2*n + 3) * sin(n * x)) * n + 1)
def clever_summa(x, k):
cache = z(x, 1)
summa = 0
factor = factor_from(x, k)
i = 1
while (i <= k):
summa += cache
cache *= factor
print(cache)
i += 1
return summa
def table(func, x, k):
i = 1
while (i <= k):
print("{} {}".format(i, func(x, i)))
i += 1
main()
|
c8300d2da7059f2cca63417e200e7cc4bbc06183 | RahatIbnRafiq/leetcodeProblems | /Tree/501. Find Mode in Binary Search Tree.py | 632 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
d = None
def dfs(self,node):
if node:
self.d[node.val] = self.d.get(node.val,0)+1
self.dfs(node.left)
self.dfs(node.right)
def findMode(self, root):
if not root:return []
self.d = dict()
self.dfs(root)
mode = max([self.d[key] for key in self.d.keys()])
return [key for key in self.d.keys() if self.d[key] == mode]
|
1eaac96dba5db66597e43c0450324abf22740476 | chenya1123236324/python-examples | /function_module/file_operation_example/pandas_write_example.py | 632 | 3.59375 | 4 | # -*- coding:utf-8 -*-
import pandas as pd
__author__ = 'Evan'
def write_excel(file_name, sheets, data):
"""
使用pandas,写入多页工作表到Excel
:param file_name: 需要生成的Excel表格名
:param sheets: 需要写入的工作表名
:param data: 需要写入的数据
:return:
"""
writer = pd.ExcelWriter(file_name)
for sheet in sheets:
df = pd.DataFrame(data)
df.to_excel(writer, sheet_name=sheet, index=False)
writer.save()
writer.close()
if __name__ == '__main__':
write_excel(file_name='example.xlsx', sheets=['sheet1', 'sheet2'], data=[1, 2, 3])
|
203791c77d8a985625e359a97670ff89634ba403 | codingpen-io/codeup | /1930.py | 403 | 3.5 | 4 | memo = {}
def super_sum(k, n):
# print('k', k, 'n', n)
if k == 0:
return n
sum = 0
for i in range(1, n+1):
key = str(k-1)+str(i)
if not key in memo:
memo[key] = super_sum(k-1, i)
sum += memo[key]
return sum
while True:
try:
k, n = map(int, input().split())
print(super_sum(k, n))
except Exception:
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.