blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c63ccfe9c85115d36590347dca277ec3032054a7 | Halldor-Hrafn/PythonShenanigans | /Forrit40.py | 332 | 3.515625 | 4 | file = open('nofn.txt')
eList = []
aList = []
for line in file:
word = line.strip()
if 'e' in word:
eList.append(word)
if word[2] == 'a':
aList.append(word)
print('the names with an "e" in them are:', len(eList))
print(aList)
print('The amount of names with "a" as the thrid letter are:', len(aList))
|
a4fb7bad59202e2adf3879b24036d9f6ed36ce97 | Davebreaux/Class | /Python/Day1/functionBasics.py | 2,128 | 4.03125 | 4 | #1
def number_of_food_groups():
return 5
print(number_of_food_groups()) # 5
#2
def number_of_military_branches():
return 5
print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches()) # error function not defined
#3
def number_of_books_on_hold():
return 5
return 10
print(number_of_books_on_hold()) # 5
#4
def number_of_fingers():
return 5
print(10)
print(number_of_fingers()) # 5
#5
def number_of_great_lakes():
print(5)
x = number_of_great_lakes()
print(x) # undefined - I was wrong.
#6
def add(b,c):
print(b+c)
print(add(1,2) + add(2,3)) # 3, 5, none - just errored out.
#7
def concatenate(b,c):
return str(b)+str(c)
print(concatenate(2,5)) # 25
#8
def number_of_oceans_or_fingers_or_continents():
b = 100
print(b) # 100
if b < 10:
return 5
else:
return 10
return 7
print(number_of_oceans_or_fingers_or_continents()) #10
#9
def number_of_days_in_a_week_silicon_or_triangle_sides(b,c):
if b<c:
return 7
else:
return 14
return 3
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3)) # 7
print(number_of_days_in_a_week_silicon_or_triangle_sides(5,3)) # 14
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3) + number_of_days_in_a_week_silicon_or_triangle_sides(5,3)) # 21
#10
def addition(b,c):
return b+c
return 10
print(addition(3,5)) #8
#11
b = 500
print(b) # 500, 500, 300, 500
def foobar():
b = 300
print(b)
print(b)
foobar()
print(b)
#12
b = 500
print(b) # 500, 500, 300, 500
def foobar():
b = 300
print(b)
return b
print(b)
foobar()
print(b)
#13
b = 500
print(b) # 500, 500, 300, 300
def foobar():
b = 300
print(b)
return b
print(b)
b=foobar()
print(b)
#14
def foo():
print(1)
bar()
print(2)
def bar():
print(3)
foo() # 1, 3, 2
#15
def foo():
print(1)
x = bar()
print(x)
return 10
def bar():
print(3)
return 5
y = foo() # 1, 3, 5, 10
print(y) |
1664ad9f7047c4c6fa0834b663f1169ceb590ff8 | Thamaraikannan-R/Condition_Statement | /Div_by_3.py | 177 | 4.15625 | 4 | low=int(input("Enter the low number:"))
high=int(input("Enter the highest number:"))
while(low<=high):
print(low)
if(low%3==0):
print("div3")
low=low+1 |
ec8b6d2d38474be282b0b52c512af546d7a4e321 | NOY10/pyproject | /myalgo/binarysearch2.py | 1,914 | 3.703125 | 4 | class User:
def __init__(self, username, name, email):
self.username = username
self.name = name
self.email = email
def __repr__(self):
return "User(username='{}', name='{}', email='{}')".format(self.username, self.name, self.email)
def __str__(self):
return self.__repr__()
aakash = User('aakash', 'Aakash Rai', 'aakash@example.com')
biraj = User('biraj', 'Biraj Das', 'biraj@example.com')
hemanth = User('hemanth', 'Hemanth Jain', 'hemanth@example.com')
jadhesh = User('jadhesh', 'Jadhesh Verma', 'jadhesh@example.com')
siddhant = User('siddhant', 'Siddhant Sinha', 'siddhant@example.com')
sonaksh = User('sonaksh', 'Sonaksh Kumar', 'sonaksh@example.com')
vishal = User('vishal', 'Vishal Goel', 'vishal@example.com')
users = [aakash, biraj, hemanth, jadhesh, siddhant, sonaksh, vishal]
# print(users)
class UserDatabase:
def __init__(self):
self.users = []
def insert(self, user):
i = 0
while i < len(self.users):
# Find the first username greater than the new user's username
if self.users[i].username > user.username:
break
i += 1
self.users.insert(i, user)
def find(self, username):
for user in self.users:
if user.username == username:
return user
def update(self, user):
target = self.find(user.username)
target.name, target.email = user.name, user.email
def list_all(self):
return self.users
database = UserDatabase()
database.insert(hemanth)
database.insert(aakash)
database.insert(siddhant)
# user = database.find('siddhant')
# print(user)
# print(database.list_all())
database.update(User(username='siddhant', name='Siddhant U', email='siddhantu@example.com'))
class BSTNode():
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = None
tree = BSTNode(jadhesh.username, jadhesh) |
2b931e71b94e197cd2af5bb78e0d1b2d55f6e011 | BishuPoonia/coding | /Python/list_addition.py | 160 | 3.671875 | 4 | def array_sum(ar):
return sum(ar)
ar = list(map(int, input("Enter list items: ").rstrip().split()))
print("Addition on list items:", array_sum(ar))
|
269bf0415e49ce62057ad989ca3e598af3bfd248 | Yue-Xiong/ri_li_cha_xun | /main_code.py | 557 | 4.09375 | 4 | year = int (raw_input('year:\n'))
month = int (raw_input('month:\n'))
day = int (raw_input('day:\n'))
months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
if 0<month<=12:
xuhao = months[month-1]
xuhao +=day
leap = 0
if (year % 4 == 0):
leap = 1
days = [31, 28+leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if day > days[month-1]:
print 'day error!'
else:
if (month > 2) and (leap==1):
xuhao+=1
print 'it is the %dth day of the year.' %xuhao
else:
print 'month error!'
|
87eb6d7ed653f603a457ec790fc94ccf7ddc39ce | pingao2019/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/buddymove_holidayiq.py | 1,850 | 3.71875 | 4 | # module1-introduction-to-sql/buddymove_holidyiq.py
#- Count how many rows you have - it should be 249!
#- How many users who reviewed at least 100 `Nature` in the category also
# reviewed at least 100 in the `Shopping` category?
#- (*Stretch*) What are the average number of reviews for each category?
import pandas as pd
import sqlite3
import os
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..","module1-introduction-to-sql","buddymove_holidayiq.sqlite3")
conn = sqlite3.connect(DB_FILEPATH)
curs = conn.cursor()
df = pd.read_csv("https://github.com/pingao2019/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module1-introduction-to-sql/buddymove_holidayiq.csv")
df.to_sql("buddymove_holidayiq", con=conn, if_exists='replace')
#- Count how many rows you have - it should be 249!
query1 = """
SELECT
count(distinct "User Id") as Rows
FROM buddymove_holidayiq
"""
row = curs.execute(query1).fetchone()
print ("Total Number of Rows:")
print(row[0])
# How many users who reviewed at least 100 Nature in the category
# also reviewed at least 100 in the Shopping category?
query2 = """
SELECT
count(distinct "User Id") as Rows
FROM buddymove_holidayiq
WHERE Nature >= 100 AND Shopping >= 100
"""
row = curs.execute(query2).fetchone()
print ("Number of Nature/Shopping Lovers:")
print(row[0])
# What are the average number of reviews for each category?
query2 = """
SELECT
AVG(Sports) as "Sports Average"
, AVG(Religious) as "Religious Average"
, AVG(Nature) as "Nature Average"
, AVG(Theatre) as "Theatre Average"
, AVG(Shopping) as "Shopping Average"
, AVG(Picnic) as "Picnic Average"
FROM buddymove_holidayiq
"""
row = curs.execute(query2).fetchall()
print ("Averages:")
categories = ['Sports','Religious','Nature','Theatre','Shopping','Picnic']
for i in range(6):
print(categories[i], ":", row[0][i])
conn.commit() |
6e7797562ae56947d39c26f2eeaabf52dc3a7bc8 | amazingcodeLYL/Crawler-practice | /crawler_practice/numpy/numpy5.py | 465 | 3.703125 | 4 | import numpy as np
A=np.arange(12).reshape((3,4))
print(A)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
B=A.copy()
print("B=",B)
# B= [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
#纵向分割
print(np.split(A,2,axis=1))
# [array([[0, 1],
# [4, 5],
# [8, 9]]), array([[ 2, 3],
# [ 6, 7],
# [10, 11]])]
#横向分割
print(np.split(A,3,axis=0))
# [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
|
2e81cbee2da6e44d9397037cf28e3f69a1ff57f9 | sarvparteek/Scientific_computation_2 | /romberg_integration2.py | 592 | 3.71875 | 4 | #script: ex-romberg-todo.py
#author: Luis Paris
import math
import _plot, _numinteq
def f(x): return (x + 1/x) **2 ;
#true integral of f(x)
def Itf(x): return (1/3 * x**3) - 1/x + 2*x;
#evaluation range
x0 = 1
xn = 2
#plot function
_plot.graph(f, xl=x0, xu=xn, title="f(x) = (x + 1/x)^2 ")
#true value of integral of f(x) between x0 and xn
tv = Itf(xn) - Itf(x0)
print("tv = {}".format(tv))
#approx. value of integral of f(x) using romberg's algorithm
av = _numinteq.romberg(f, x0, xn, es100=.5, tv=tv, debug=True)
print("av = {}".format(av))
et = (tv-av)/tv;
print("et = {}".format(et)); |
06b8e1c318e23d6aa360303d8e9fa220baea3f0d | G30RG3PAK/Python_Practice | /RoPaSc.py | 878 | 3.9375 | 4 | import sys
userone = raw_input("What's your name?")
usertwo = raw_input("And...?")
userone_answer = raw_input("%s, choose rock, paper or scissors?" % userone)
usertwo_answer = raw_input("%s, choose rock, paper, or scissors?" % usertwo)
def compare(u1, u2):
if u1 == u2:
return("It's a tie!")
elif u1 == 'rock':
if u2 == 'scissors':
return("Rock Wins!")
else:
return("Paper Wins!")
elif u1 == 'scissors':
if u2 == 'paper':
return("Scissors Wins!")
else:
return("Rock Wins!")
elif u1 == 'paper':
if u2 == 'rock':
return("Paper Wins!")
else:
return("Scissors Wins!")
else:
return("Invalid input! You have not entered rock, paper or scissors")
sys.exit()
print(compare(userone_answer, usertwo_answer))
|
aced2878f93addeb3c887135844ba7c1bd991955 | suprviserpy632157/zdy | /ZDY/Jan_all/pythonbase/January0107/afternoon.py | 1,714 | 3.828125 | 4 | # 写程序,实现以下要求
# 用户输入一个整数代表这个季度,打印这个
# 季度的信息,用户输入的信息不在字典内打印不存在
# seasons={
# 1:'pring has 1,2,3month',
# 2:'summer has 4,5,6month',
# 3:'automn has 7,8,9month',
# 4:'winter has 10,11,12month'
# }
# print(seasons)
# x=int(input("Please input a number(1-4):"))
# d={}
# d[1]='spring has 1,2,3month'
# d[2]='summer has 4,5,6month'
# d[3]='automn has 7,8,9month'
# d[4]='winter has 10,11,12month'
# if x in d:
# print(d[x])
# else:
# print("error")
# d={'name':'zdy','birthday':(1995,2)}
# for k in d:
# print("键",k,'值',d[k])
# 写一个程序,输入一个字符串,写程序统计
# 出这个字符串的字符个数字和每个字符的次数
# s=input("Please input a string:")
# d=dict()
# for i in s:
# #如果是第一次出现这个字符
# if i not in d:
# d[i] = 1
# #如果不是第一次出现这个字符
# else:
# d[i]+=1
# for k in d:
# print("char",k,':',d[k],"per")
# # 生成一个字典,键为数字(10)以内,值为键的平方
# d={x:x**2 for x in range(10)}
# print(d)
# 有如下字符串列表
# L=['tarena','xiaozhang','hello']
# 生成如下字典:
# d={'tarena':6,'xiaozhang':9,'hello':5}
# L=['tarena','xiaozhang','hello']
# d={k:len(k) for k in L}
# print(d)
# 已知有两个字符串列表:
Nos=[1001,1002,1005,1008]
names =['Tom','Jerry','Spike','Tyke']
d={}
for i in range(len(Nos)):
d[Nos[i]]=names[i]
print(d)
# 改写
c={Nos[i]:names[i] for i in range(len(Nos))}
print(c)
a={}
for n in Nos:
a[n]=names[Nos.index(n)]
print(a)
b={n:names[Nos.index(n)] for n in Nos}
print(b) |
aa6b6396af980c6e0d571b39afefbccc5532301e | BarelyMiSSeD/PUBG | /calc_rank.py | 19,247 | 3.5 | 4 | #!/usr/bin/env python3
RANKING_FILE = "current_rankings.txt" # The name of the file holding the current tournament standings
NQ_FILE = "not_qualified.txt" # The file to hold the players without enough games to qualify
GAME_FILE = "game_{}.txt" # The name structure for the file saved for each tournament game
NEW_PLAYER_START_RATING = 1500 # The start rating given to players (first game will adjust from this value)
QUALIFYING_GAME_COUNT = 10 # The number of games a player must play before their rating counts
MINIMUM_PLAYERS = 5 # The minimum players needed for a tournament game
PARTICIPATION_SCORE_BUMPS = True # True = Uses player kills in game in rating adjustment calculation
PRINT_ERRORS = False
# These multipliers are for giving players bumps in their rating to promote more participation. If only one rating
# bump is desired, set the other one to 0.0 to effectively disable it.
# (Set PARTICIPATION_SCORE_BUMPS to True to enable these)
KILLS_MULTIPLIER = 0.5 # The multiplier used for game kills
GAMES_MULTIPLIER = 1.0 # The multiplier is for completed games
VERSION = 2.1
class GameRatings(object):
def __init__(self):
self.__players = []
self.__save_players = []
self.__comments = []
self.__game_data = []
self.__results = []
self.__not_qualified = []
self.__names = []
self.process_data()
@staticmethod
def games_exist():
count = 1
while True:
try:
t = open(GAME_FILE.format(count), 'r')
t.close()
except:
break
count += 1
return count - 1 if count > 1 else 0
def adjustment(self, players, total_players):
# {'name': name, 'position': position, 'kills': kills, 'games': games,
# 'rating': rating, 'prev_kills': previous_kills}
if PARTICIPATION_SCORE_BUMPS:
kills = {}
for player in players:
kills[player['name']] = player['kills']
adjustments = {}
while len(players) > 1:
if players[0]['name'] not in adjustments:
adjustments[players[0]['name']] = []
tr1 = 10 ** (players[0]['rating'] / 400)
second = 1
tr2 = 0
while tr2 != -1:
try:
if players[second]['name'] not in adjustments:
adjustments[players[second]['name']] = []
tr2 = 10 ** (players[second]['rating'] / 400)
adj1 = 20 * (1 - (tr1 / (tr1 + tr2)))
adjustments[players[0]['name']].append(adj1)
adj2 = 20 * (0 - (tr2 / (tr1 + tr2)))
adjustments[players[second]['name']].append(adj2)
second += 1
except IndexError:
tr2 = -1
del players[0]
for player, adj in adjustments.items():
if PARTICIPATION_SCORE_BUMPS:
adjustments[player] = (sum(adj) / (total_players - 1)) + (float(kills[player]) * KILLS_MULTIPLIER)\
+ (1.0 * GAMES_MULTIPLIER)
else:
adjustments[player] = sum(adj) / (total_players - 1)
return adjustments
def get_data(self):
self.__players = []
self.__comments = []
found = 0
qualified = 0
try:
count = 0
try:
file = open(RANKING_FILE, 'r')
lines = file.readlines()
file.close()
for line in lines:
if line.startswith("#"):
self.__comments.append(line)
continue
player = line.split(",")
self.__players.insert(count, {})
self.__players[count]['name'] = player[0]
self.__players[count]['rank'] = int(player[1])
self.__players[count]['rating'] = float(player[2])
self.__players[count]['kills'] = int(player[3])
self.__players[count]['games'] = int(player[4].strip())
count += 1
qualified = count
except FileNotFoundError:
found = -1
try:
file = open(NQ_FILE, 'r')
lines = file.readlines()
file.close()
for line in lines:
player = line.split(",")
self.__players.insert(count, {})
self.__players[count]['name'] = player[0]
self.__players[count]['rank'] = int(player[1])
self.__players[count]['rating'] = float(player[2])
self.__players[count]['kills'] = int(player[3])
self.__players[count]['games'] = int(player[4].strip())
count += 1
except FileNotFoundError:
if found == -1:
found = -3
else:
found = -2
except Exception as e:
if PRINT_ERRORS:
print("Error getting existing data: {}".format([e]))
return found, qualified
def write_data(self):
try:
file = open(RANKING_FILE, 'w')
for line in self.__comments:
file.write(line + "\n")
for player in self.__save_players:
file.write("{0[name]},{0[rank]},{0[rating]},{0[kills]},{0[games]}\n".format(player))
file.close()
file = open(NQ_FILE, 'w')
for player in self.__not_qualified:
file.write("{0[name]},{0[rank]},{0[rating]},{0[kills]},{0[games]}\n".format(player))
file.close()
return True
except Exception as e:
if PRINT_ERRORS:
print("Error writing data: {}".format([e]))
return False
def save_game(self):
count = 1
while True:
try:
t = open(GAME_FILE.format(count), 'r')
t.close()
except:
break
count += 1
try:
file = open(GAME_FILE.format(count), 'w')
file.write("#name, finish position, kills, old_rating, adjustment, new_rating\n")
for player in self.__results:
file.write("{},{},{},{},{},{}\n"
.format(player['name'], player['position'], player['kills'], player['rating'],
player['adjustment'], player['new_rating']))
file.close()
except Exception as e:
if PRINT_ERRORS:
print("Error writing game data: {}".format([e]))
def process_games(self):
count = 1
games_results = []
while True:
try:
g = open(GAME_FILE.format(count), 'r')
lines = g.readlines()
g.close()
rank = 1
player_count = 0
players = []
for line in lines:
if line.startswith("#"):
continue
player_count += 1
player = line.split(",")
name = player[0]
position = int(player[1])
kills = int(player[2])
games = 1
rating = NEW_PLAYER_START_RATING
previous_kills = 0
for p in games_results:
if p['name'] == name:
games = p['games'] + 1
rating = p['rating']
previous_kills = p['kills']
games_results.remove(p)
break
players.append({'name': name, 'position': position, 'kills': kills, 'games': games,
'rating': rating, 'prev_kills': previous_kills})
ordered = []
for p in players:
pos = 0
for r in ordered:
if r['position'] > p['position']:
break
pos += 1
ordered.insert(pos, p)
adjustments = self.adjustment(ordered.copy(), player_count)
for player in ordered:
player['new_rating'] = player['rating'] + adjustments[player['name']]
pos = 0
for p in games_results:
if player['new_rating'] > p['rating'] or p['rating'] == player['new_rating'] and\
player['kills'] > p['kills']:
break
pos += 1
games_results.insert(pos, {})
games_results[pos]['name'] = player['name']
games_results[pos]['rating'] = player['new_rating']
games_results[pos]['kills'] = player['kills'] + player['prev_kills']
games_results[pos]['games'] = player['games']
if count > 1:
rank += 1
except FileNotFoundError:
break
except Exception as e:
print("File {} read exception: {}".format(count, [e]))
count += 1
self.__save_players = games_results
self.__not_qualified = []
pos = len(self.__save_players)
while pos > 0:
pos -= 1
if self.__save_players[pos]['games'] < QUALIFYING_GAME_COUNT:
self.__not_qualified.insert(0, self.__save_players[pos])
del self.__save_players[pos]
for x in range(len(self.__save_players)):
self.__save_players[x]['rank'] = x + 1
for x in range(len(self.__not_qualified)):
self.__not_qualified[x]['rank'] = x + 1
if self.write_data():
print("Processing Existing game files completed.\n")
else:
print("Error processing existing game files.\n")
self.__save_players = []
self.__not_qualified = []
return True
def process_data(self):
print("Starting PUBG Tournament Ranking program {}".format(self.__class__.__name__))
files = self.get_data()
if files[0] > -3:
message = ["Current Player Standings: {} Player Records {} Qualified\n(Name : Rank Rating Kills Games)"
.format(len(self.__players), files[1])]
for player in self.__players:
message.append("{0[name]:6}: {0[rank]:>2} {1:>7} {0[kills]:>6} {0[games]:>5}"
.format(player, round(float(player["rating"]), 2)))
print("\n".join(message))
else:
recorded_games = self.games_exist()
if recorded_games:
process_games = input("There {0} {1} game{2} files but no ranking file. Would you like to process"
" the game{2} file{2} (y/N)? "
.format("are" if recorded_games > 1 else "is", recorded_games,
"s" if recorded_games > 1 else ""))
if not process_games or process_games.lower() == 'n':
print("This is the first recorded game of the tournament.")
else:
if self.process_games():
files = self.get_data()
if files[0] > -3:
message = ["Current Player Standings: {} Player Records {} Qualified\n"
"(Name : Rank Rating Kills Games)"
.format(len(self.__players), files[1])]
for player in self.__players:
message.append("{0[name]:6}: {0[rank]:>2} {1:>7} {0[kills]:>6} {0[games]:>5}"
.format(player, round(float(player["rating"]), 2)))
print("\n".join(message))
else:
print("This is the first recorded game of the tournament.")
print("\n***Input Game Results***")
while True:
try:
total_players = int(input("Number of Players in Game (0 to quit): "))
except ValueError:
print("The value must be a number")
continue
if total_players == 0:
print("Exiting Program.")
exit()
elif total_players < MINIMUM_PLAYERS:
print("The participating players mut be at least {}. Exiting Program.".format(MINIMUM_PLAYERS))
exit()
break
print("\n")
def get_data(num):
for c in range(num):
redo = True
while redo:
name = input("Player Name: ")
while name in self.__names:
print("That name has already been input. Input so far: {}".format(", ".join(self.__names)))
name = input("Player Name: ")
if name not in self.__names:
break
self.__names.append(name)
if name in ["stop", "quit", "done", "exit"]:
break
while True:
try:
position = int(input("Player's Finishing Position: "))
except ValueError:
print("The value must be a number")
continue
break
while True:
try:
game_kills = int(input("Player's kills in Game: "))
except ValueError:
print("The value must be a number")
continue
break
print("Data Entered: {} {} {}".format(name, position, game_kills))
correct = input("Is this correct (Y/n)? ")
if not correct or correct.lower() == 'y':
redo = False
self.__game_data.insert(c, {})
self.__game_data[c]['name'] = name
self.__game_data[c]['position'] = position
self.__game_data[c]['kills'] = game_kills
else:
self.__names.remove(name)
print("\n")
get_data(total_players)
while len(self.__game_data) != total_players:
print("The Players entered does not match the number of players reported as playing.")
get_more = input("Do you want to enter more data (Y/n)? ")
if not get_more or get_more.lower() == "y":
get_data(total_players - len(self.__game_data))
else:
total_players = len(self.__game_data)
for participant in self.__game_data:
games_played = 1
rating = NEW_PLAYER_START_RATING
previous_kills = 0
for player in self.__players:
if player['name'] == participant['name']:
games_played = player['games'] + 1
rating = player['rating']
previous_kills = player['kills']
self.__players.remove(player)
break
participant['games'] = games_played
participant['rating'] = rating
participant['prev_kills'] = previous_kills
for player in self.__game_data:
count = 0
for reorder in self.__results:
if reorder['position'] > player['position']:
break
count += 1
self.__results.insert(count, player)
adjustments = self.adjustment(self.__results.copy(), total_players)
for player in self.__results:
player['adjustment'] = adjustments[player['name']]
player['new_rating'] = player['rating'] + player['adjustment']
self.save_game()
for player in self.__players:
count = 0
for save in self.__save_players:
if player['rating'] > save['rating'] or save['rating'] == player['rating'] and \
player['position'] > save['position']:
break
count += 1
self.__save_players.insert(count, {})
self.__save_players[count]['name'] = player['name']
self.__save_players[count]['rating'] = player['rating']
self.__save_players[count]['kills'] = player['kills']
self.__save_players[count]['games'] = player['games']
for results in self.__results:
count = 0
for save in self.__save_players:
if results['new_rating'] > save['rating'] or save['rating'] == results['new_rating'] and \
results['kills'] > save['kills']:
break
count += 1
self.__save_players.insert(count, {})
self.__save_players[count]['name'] = results['name']
self.__save_players[count]['rating'] = results['new_rating']
self.__save_players[count]['kills'] = results['kills'] + results['prev_kills']
self.__save_players[count]['games'] = results['games']
pos = len(self.__save_players)
while pos > 0:
pos -= 1
if self.__save_players[pos]['games'] < QUALIFYING_GAME_COUNT:
self.__not_qualified.insert(0, self.__save_players[pos])
del self.__save_players[pos]
for x in range(len(self.__save_players)):
self.__save_players[x]['rank'] = x + 1
for x in range(len(self.__not_qualified)):
self.__not_qualified[x]['rank'] = x + 1
self.write_data()
print("New Rankings: {} Qualified\n(Name: Rank Rating Kills Games)".format(len(self.__save_players)))
for player in self.__save_players:
print("{0[name]:6}: {0[rank]:>2} {1:>7} {0[kills]:>6} {0[games]:>5}"
.format(player, round(float(player["rating"]), 2)))
print("\nNot Yet Qualified: {} Players\n(Name: Rating Kills Games)".format(len(self.__not_qualified)))
for player in self.__not_qualified:
print("{0[name]:6}: {1:>7} {0[kills]:>6} {0[games]:>5}"
.format(player, round(float(player["rating"]), 2)))
print("\n")
def main():
if __name__ == '__main__':
GameRatings()
while True:
input_again = input("Do you want to enter another game? (y/N): ")
if not input_again or input_again.lower() == 'n':
break
GameRatings()
main()
|
e51d5701868edaea6763157116f5bd8c2488f5f8 | buddy-israel/pyships_parser | /MyDatabase.py | 287 | 3.53125 | 4 | import sqlite3
import os
import json
conn = sqlite3.connect('WoWs_DB')
c = conn.cursor()
def ship_tbl_select_name_type(ship_id):
c.execute("""
SELECT
ship_name,
type
FROM
tbl_ships
WHERE
ship_id=?
""", (ship_id,)
)
rows = c.fetchall()
for row in rows:
return(row) |
ea00d83da32c5eb2fa435a4fab7cc3791c4fccbb | arnabs542/Competitive-Programming | /Codelearn.io/Code Practice/maxPoint.py | 246 | 3.546875 | 4 | # https://codelearn.io/training/detail?id=632023
def maxPoint(a, b):
ans = []
mark_max = [a[0]]
for i in range(1,len(a)):
mark_max.append(max(a[i],mark_max[i-1]))
for i in b:
ans.append(mark_max[i])
return ans |
f571a3698b380d7cb56f20138ba5efa6848ab58e | This-is-NB/CodeChef | /JUN21_CodeChef/Optimal_Xor_Set.py | 367 | 3.546875 | 4 | import math
def invertBits(num):
x = int(math.log(num, 2.0) + 1)
for i in range(0, x):
num = (num ^ (1 << i));
return num ;
def optimal_xor_set(n,k):
if k ==1:return [n]
if k ==2:return [n,invertBits(n)]
return -1
for i in range(int(input())):
n,k = map(int,input().split())
ans = optimal_xor_set(n,k)
print(*ans) |
7c1caf588db912e3fb2bf2b268002e6d617ebb8f | romcra/romcrap | /romcrap/Extension.py | 2,392 | 4.46875 | 4 | ######################### EXTENSION ######################################
# 1. Write a function that will simulate numbers from a given distribution.
# The function should take one argument for the number of samples and
# a second argument which specifies the distribution
# (Normal, Poisson or Binomial). The function should be able to handle
# additional parameters depending on the distribution chosen,
# e.g. a ‘lambda’ for Poisson samples.
# This function takes one argument for the number of samples and
# a second argument which specifies the distribution (Normal, Poisson or Binomial).
# It asks you to enter the parameters of the distribution (different amount and type of parameters for each distribution).
# It prints the samples (according to the number of samples
# you typed), returns a list that contains a sample per position
# and plots one of the samples as an example.
def distribution_sample(num,dist):
#Libraries
import numpy as np
import matplotlib.pyplot as plt
if dist not in ("Normal","Poisson","Binomial"):
print ("The function doesn't work with that distribution")
print ("Please, enter: Normal,Poisson or Binomial")
else:
print ("DISTRIBUTION_SAMPLE FUNCTION.....")
if dist=="Normal":
mean=input("Enter mean: ")
std=input("Enter std: ")
mean=float(mean)
std=float(std)
random_matrix=np.random.normal(mean,std,size=(num,200))
elif dist=="Poisson":
lam=input("Enter lambda: ")
lam=float(lam)
random_matrix=np.random.poisson(lam,size=(num,200))
else:
trials=input("Enter trials: ")
p=input("Enter probability of success: ")
trials=float(trials)
p=float(p)
random_matrix=np.random.binomial(trials,p,size=(num,200))
list_random=[]
for i in range(0,num):
list_random.append(random_matrix[i,:])
for h,k in enumerate(list_random):
print ("The sample:",h,"is:",k)
print ("\n")
print ("PLOTTING ONE OF THE SAMPLES AS AN EXAMPLE....")
plt.title("One of the samples")
plt.hist(list_random[0])
return list_random
|
a4ac87cf3b5d8ba54a649b617eb9628b1c26f67d | jaymz95/ThompsonsPython | /regex.py | 2,561 | 3.546875 | 4 | # Matching Regular Expressions with Strings using Thompsons Construction and Shunting Yard Algorithm
# James Mullarkey
# Importing functions from other python files
from shunt import toPostfix
from thompsons import compile
def followes(state):
"""Return the set of states that can be reached from state following e arrows"""
# Create a new set, with state as its only member
states = set()
states.add(state)
# Check if state has arrows labelled e from it
if state.label is None:
if state.edge1 is not None: # Check if edge1 is a state
states |= followes(state.edge1) # if theres an edge1, follow it
if state.edge2 is not None: # Check if edge2 is a state
states |= followes(state.edge2) # If there's an edge2, follow it
# Return the set of states
return states
def match(infix, string):
"""Matches string to infix regular expression"""
string = string.lower() # case insensitive matching
infix = infix.lower()
# shunt and compile the regular expression
postfix = toPostfix(infix)
nfa = compile(postfix)
# the current set of states and the next set of states
current, next = set(), set()
# Add the initial state to the current set
current |= followes(nfa.initial)
# loop through set of character in the string
for s in string:
for c in current: # Loop through the current set of states
if c.label == s: # Check if that state is labelled s
next |= followes(c.edge1) # Add the edge1 state to the next set
# Set current to next, and clear out next
current, next = next, set()
# Check if the accept state is in the set of current states
return (nfa.accept in current)
option, test, userInput = -1, 1, 2
# User input menu
while option != 0:
option = input("\nPress 1 to run an array of infix expressions with strings " +
"\nPress 2 to enter a Regular Expression and String to test it \nPress 0 to Quit: ")
# Casting option to an int
option = int(option)
if option == test:
# A few tests
infixes = ["a.b?","a.b.c?", "a.(b|d).c+", "(a.(b|d))*", "a.(b.b)*.c"]
strings = ["ab", "abc", "abbc", "abcc", "abad", "abbbc"]
for i in infixes:
for s in strings:
print(match(i, s), i, s)
elif option == userInput:
infix = input("Please enter an infix Regular Expression: ")
stri = input("Please enter a String to test your Regular Expression: ")
print(match(infix, stri), infix, stri) |
67692d328ae67d39f1700ede3cf7bc09640e8baa | zhy0313/children-python | /教孩子学编程++PYTHON语言版/6.1 GuessingGame.py | 378 | 4.09375 | 4 | import random
# random integer,随机数
the_number = random.randint(1,10)
guess = int(input("Guess a number between 1 and 10: "))
while guess != the_number:
if guess > the_number:
print(guess,"was too high. Try again.")
else:
print(guess,"was too low. Try again.")
guess = int(input("Guess again:"))
print(guess,"was the number! You win!") |
fcc8bf549473510e137686e403dd228a688b36a9 | road-to-koshien/kevin-leetcode-challenge | /LEETCODE/205. Isomorphic Strings.py | 1,228 | 4.03125 | 4 | # https://leetcode.com/problems/isomorphic-strings/
# Given two strings s and t, determine if they are isomorphic.
# Two strings are isomorphic if the characters in s can be replaced to get t.
# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
# Example 1:
# Input: s = "egg", t = "add"
# Output: true
# Example 2:
# Input: s = "foo", t = "bar"
# Output: false
# Example 3:
# Input: s = "paper", t = "title"
# Output: true
# Note:
# You may assume both s and t have the same length.
class Solution(object):
def isIsomorphic(self, s, t):
from collections import Counter
x = Counter(s)
y = Counter(t)
newdict = {}
if len(s) != len(t):
return False
for i,each in enumerate(s):
if x[each] == y[t[i]]:
if each in newdict:
if newdict[each] != t[i]:
return False
if each not in newdict:
newdict[each] = t[i]
continue
else:
return False
return True
|
a1301efd403562cda08ea7d78a21c236d31fa86f | yaoyu2001/LeetCode_Practice_Python | /DataStructure/dynamic_programming.py | 1,918 | 3.5 | 4 | # https://www.youtube.com/watch?v=Jakbj4vaIbE&t=26s
# Dynamic programming Question 1
# Given an array, choose tow of them which have most sum value. These two numbers can't Adjacent
# OPT = optimazition has two situation. Choose or not choose. OPI(i) = max { choose opt(i-2) + arr[i], opt(i-1)}
# When i = 0, only has one choose that is arr[i]
import numpy as np
arr = [1,2,4,1,7,8,3]
# First, recursion method
def recursion_opt(arr,i):
if i == 0:
return arr[0]
elif i == 1:
return max(arr[0], arr[1])
else:
A = recursion_opt(arr, i - 2) + arr[i]
B = recursion_opt(arr, i - 1)
return max(A, B)
print(recursion_opt(arr, 5))
# DP method
def dp_opt(arr):
opt = np.zeros(len(arr))
opt[0] = arr[0]
opt[1] = max(arr[0], arr[1])
for i in range(2,len(arr)):
A = opt[i-2] + arr[i]
B = opt[i-1]
opt[i] = max(A,B)
return opt[len(arr) - 1]
print(dp_opt(arr))
# Question 2 15:35
# Given an array choose some of them to get an answer S
# Subset(arr[i], s) Exit 1: s = 0 return true Exit 2 : when i == 0, arr[0] = s Exit3: if arr[i] > s, return subset(arr, i-1,s)
arr3 = [3,34,4,12,5,2]
def rec_subset(arr, i, s):
if s == 0 : return True
elif i == 0 : return arr[0] == s
elif arr[i] > s:return rec_subset(arr,i-1,s)
else:
A = rec_subset(arr, i-1, s-arr[i])# choose arr[i]
B = rec_subset(arr, i-1,s)# not choose arr[i]
return A or B
def dp_subset(arr,S):
subset = np.zeros((len(arr), s+1), dtype=bool)
subset[:,0] = True
subset[0,:] = False
subset[0,arr[0]] = True
for i in range(1,len(arr)):
for j in range(1,S+1):
if arr[i] > j:
subset[i,j] = subset[i-1,j]
else:
A = subset[i-1,j-arr[i]]
B = subset[i-1, j]
subset[i,j] = A or B
r,c = subset.shape
return subset[r-1,c-1] |
f898ae48a631cd8093c3b388989f62de4238bd7f | N140191/Turtle-Graphics | /tkinter_test.py | 301 | 3.75 | 4 | from tkinter import *
def main():
rt=Tk()
rt.title("My first tkinter App")
rt.minsize(width=300,height=300)
rt.maxsize(width=300,height=300)
button=Button(rt,text="Click!!",width=12,height=1)
button.pack()
rt.mainloop()
if __name__=="__main__":
main()
|
8d7fc03dd07185bb6e3ca78c0c1263d14067d4d4 | bsonge/CodePracticeDump | /10dayStats/MeanMedianMode.py | 1,150 | 3.734375 | 4 | # Input
N = int(input());
arr = input();
arr = list( map(lambda a: int(a) , arr.split(' ')) )
# print(N, arr)
#=====[FUNCTIONS]=====#
def mean(li):
#add all numbers together then divide by total
total = 0
for num in li:
total += num
return round(total/len(li) , 1)
def median(li):
li.sort()
if len(li)%2 == 0:
# return the avg of the middle two entries
return round(( li[int(len(li)/2) - 1] + li[int(len(li)/2)]) / 2 , 1)
else:
# return the middle entry
return li[len(li)/2 + .5]
#MODE: finds the mode of li by making a dict to count occurances of certain numbers
def mode(li):
#create b to hold items and amount of occurances then fill out with occurances
b = {}
for item in li:
b[item] = b[item] + 1 if item in b.keys() else 1
# 1) b entries converted to tuples, represented in lambda as 'a'
# 2) filter out all but the numbers repeated the most
# 3) return the smallest of the most repeated numbers
return min( list(filter( lambda a: a[1] is b[max(b, key= b.get)], b.items() )) )[0]
print(mean(arr))
print(median(arr))
print(mode(arr))
|
6ef753dd792cb8e11895c8461e79df5186d58b2e | patthrasher/codewars-practice | /kyu7-1.py | 661 | 4.03125 | 4 | # Create a function named divisors/Divisors that takes an integer n > 1
# and returns an array with all of the integer's divisors(except for 1 and
# the number itself), from smallest to largest. If the number is prime return
# the string '(integer) is prime' (null in C#) (use Either String a in Haskell
# and Result<Vec<u32>, String> in Rust).
def divisors(integer) :
lst = []
index = 2
while index < (integer + 1) / 2 :
case = integer % index
if case == 0 :
lst.append(index)
index = index + 1
if len(lst) == 0 :
return str(integer) + ' is prime'
else :
return lst
print(divisors(5))
|
f067f3c71f5437b369ac02ba3358ab1a3aa5f04e | aislinnm12/learning_python | /finalproject.py | 1,860 | 4.1875 | 4 | #!/usr/bin/env python3
# final project
# generating random first and last names
import string
import random
from random import randrange
vowels = 'aeiou'
consonants = 'bcdfghijklmnpqrstvwxz'
def get_letter(last_letter=None):
# Check if last letter generated was a consonant
if last_letter:
last_letter = ''.join(last_letter)
last_letter_was_consonant = last_letter in consonants
else:
last_letter_was_consonant = False
# If last letter was a vowel, make it 50% chance to generate a consonant
if not last_letter_was_consonant and bool(random.randint(0, 1)):
last_was_consonant = True
yield random.choice(consonants)
else:
last_was_consonant = False
yield random.choice(vowels)
def generate_word(length, spread=0):
word = list()
for i in range(length + random.randint(1, spread)):
word.append(next(get_letter(last_letter=word[-1:])))
return ''.join(word).capitalize()
if __name__ == '__main__':
print('Generating 10 random names:')
for i in range(10):
print(generate_word(length=5, spread=3))
"""
def generate_lastname(length, spread=0):
word = list()
for i in range(length + random.randint(1, spread)):
word.append(next(get_letter(last_letter=word[-1:])))
return ''.join(word).capitalize()
name = generate_word(length=5, spread=3)+" "+generate_lastname(length=5,spread=3)
for i in range(10):
print(name)
"""
def name_builder(first_name_list_path, last_name_list_path):
first_name_list = []
last_name_list = []
line_appender(first_name_list_path, first_name_list)
line_appender(last_name_list_path, last_name_list)
first_name_selected = name_selector(first_name_list)
last_name_selected = name_selector(last_name_list)
name = first_name_selected+" "+last_name_selected
print(name)
|
3c1d0d70a7b6d1b1d99001f1084e2a51a464ee67 | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_20.py | 483 | 4.34375 | 4 | ##
#Compute the amount of gas in moles
R=8.314
#Read the value of the pressure, volume and temperature from the user
pressure=float(input("Enter the value of the pressure in Pascal:\n"))
volume=float(input("Enter the value of the volume in liters:\n"))
temperature=float(input("Enter the value of the temperature in degrees Kelvin:\n"))
#Compute the amount of gas in moles
n=(pressure*volume)/(R*temperature)
#Display the result
print("The amount of gas in moles is: %.3f moles "%n)
|
35641f41ce345d4ed8032eb8ab9c8a127be08196 | jabrayare/Sort-Algorithms | /selectionSort.py | 472 | 4.1875 | 4 | from typing import List
"""
Sort array A[1..n] of size n by recursively selecting
the maximum element and placing it at the end of the array
"""
def selectionSort(arr: List[int], n: int):
if n < 1:
return
for i in range(0, n):
if arr[i] > arr[n]:
arr[i], arr[n] = arr[n], arr[i]
selectionSort(arr, n-1)
arr = [4,9,1,3,0]
# print(arr)
n = len(arr)
selectionSort(arr, n-1)
print(arr)
"""
Best Case: O(n^2)
Expected Case: O(n^2)
Worst Case: O(n^2)
""" |
175d10548886a942c7786fe7e37142524312c9a2 | victorwongth/hackerrank-solutions | /interview-preparation-kit/string-manipulation/special-string-again/special-string-again.py | 1,547 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/special-palindrome-again/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the substrCount function below.
def substrCount(n, s):
# First build a list that stores strings occurences as sets
# i.e. s = "aabcdaa" would be stored as
# strings = [("a", 2), ("b", 1"), ("c", 1), ("d", 1), ("a", 2)]
strings = []
previous_string = s[0]
count_string = 1
for i in range(1, len(s)):
if s[i] == previous_string:
count_string += 1
else:
strings.append((previous_string, count_string))
previous_string = s[i]
count_string = 1
strings.append((previous_string, count_string))
count = 0
# To count case 1 (e.g. aaa)
for string in strings:
# Occurence Palindromics
# 1 1
# 2 3
# 3 6
# 4 10
# 5 15
# ...
# Which gives Palindromics = 1 + 2 + ... + n = (n * n+1) / 2
count += (string[1]* (string[1] + 1)) // 2
# To count case 2 (e.g. aabaa)
for i in range(1, len(strings) - 1):
if strings[i-1][0] == strings[i+1][0] and strings[i][1] == 1:
count += min(strings[i-1][1], strings[i+1][1])
return(count)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = substrCount(n, s)
fptr.write(str(result) + '\n')
fptr.close()
|
04f2299f286472d033497791bdd7c27d9168b1af | dikoko/practice | /6 Trees/6-07_check_bst.py | 1,827 | 3.515625 | 4 | import math
class BTNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_from_list(inlist):
if not inlist: return
root = BTNode(inlist.pop(0))
wqueue = [root]
while inlist:
node = wqueue.pop(0)
val = inlist.pop(0)
if val:
node.left = BTNode(val)
wqueue.append(node.left)
if inlist:
val = inlist.pop(0)
if val:
node.right = BTNode(val)
wqueue.append(node.right)
return root
def print_inorder(root):
if not root: return
node = root
wstack = []
while node or wstack:
if node:
wstack.append(node)
node = node.left
else:
node = wstack.pop()
print(node.val, end=" ")
node = node.right
print("")
def check_bst(root):
if not root: return False
def _check(node):
if not node:
return True, math.inf, -math.inf # is / min / max
is_left, l_min, l_max = _check(node.left)
is_right, r_min, r_max = _check(node.right)
if not is_left or not is_right:
return False, 0, 0
if l_max < node.val and node.val < r_min:
return True, min(node.val, l_min), max(node.val, r_max)
else:
return False, 0, 0
return _check(root)
if __name__ == '__main__':
inlist1 = [8, 3, 13, 1, 5, 10, 17, None, None, 4, 7, None, 12, 15]
root1 = build_from_list(inlist1)
# print_inorder(root)
inlist2 = [8, 3, 13, 1, 2, 10, 17, None, None, 4, 7, None, 12, 15]
root2 = build_from_list(inlist2)
print(check_bst(root1))
print(check_bst(root2))
|
234c094967e1a77314d4ac8cebe0d39833ce8d38 | isharajan/my_python_program | /avarage no in list.py | 259 | 3.921875 | 4 | n=int(input("enter n no:"))
list1=[]
for i in range(n):
n=int(input("enter the no:"))
list1.append(n)
print(list1)
sum=0
for a in list1:
# print(a)
sum=sum+a
print("sum is",sum)
avarage=sum/len(list1)
print("the avarage is",avarage)
|
3f6a8d539e04223a175c895b82a406ef5bf26d04 | martindavid/code-sandbox | /algorithm/COMP90038/comp90038-assignment2/pareto_optimal.py | 1,441 | 3.796875 | 4 | from __future__ import print_function
point = [
(1, 11), (2, 1), (2, 6), (4, 3), (4, 8), (5,10),
(6, 6), (8, 7), (10, 4), (11, 2), (11, 11), (11, 7), (11, 10), (11, 4), (12, 5)
]
X = []
Y = []
sorted(point, key=lambda x: x[0])
print(point)
temp_point = point[len(point) - 1]
y_max = temp_point[1]
pareto_optimal = []
pareto_optimal.append(temp_point)
for i in range(len(point) - 2, -1, -1):
print(point[i])
if point[i][1] >= y_max:
pareto_optimal.append(point[i])
y_max = point[i][1]
print(pareto_optimal)
"""
// find a set of pareto optimals point of S
// Input : S, a finite set of n distinct point P1(x1, y1), P2(x2, y2), ..., Pn(xn, yn)
// S is an 2 dimensional array -> [[x1, y1],[x2,y2], ..., [xn, yn]]
// Output: a set of pareto optimal point
function FIND_PARETO_OPTIMAL(S)
sorted_s <- QUICK_SORT(S[x]) // sort point by x-axis
len <- length(S)
pareto_optimal <- [] // initiate empty array
pareto_optimal.push(sorted_s[len - 1]) // put last element (highest x-axis value)
y_max <- sorted_s[len - 1][1] // store y-axis from highest x-axis point
for len - 2 to 0 do
// compare max y-axis with the selected point y-axis
if point[i][1] > y_max then
pareto_optimal.push(point)
y_max = point[y]
return pareto_optimal
"""
"""
QuickSort will take O(n log n) and last comparison will running n times, so overall complexity will be O(n log n)
"""
|
8416f6e63d1d4d3a6763df0d49686f3e12910a04 | beneen/nobody-likes-a-for-loop | /tests/test_check_permutation.py | 823 | 3.703125 | 4 | from unittest import TestCase
from string_manipulation.check_permutation import check_permutation
class TestCheck_permutation(TestCase):
def test_check_permutation_empty(self):
self.assertEqual(True, check_permutation("", ""))
def test_check_permutation_empty_1(self):
self.assertEqual(False, check_permutation("", "egg"))
def test_check_permutation_empty_2(self):
self.assertEqual(False, check_permutation("egg", ""))
def test_check_permutation_is_permutation(self):
self.assertEqual(True, check_permutation("egg", "gge"))
def test_check_permutation_not_permutation(self):
self.assertEqual(False, check_permutation("egg", "not"))
def test_check_permutation_repeated_characters(self):
self.assertEqual(False, check_permutation("egg", "eggg"))
|
5523424311e61d3772d9f16eb86a496ef286358f | keasyops/BaseCode | /python/6.net/6.rpc/1.test/1.localhost.py | 157 | 3.734375 | 4 | def sum(a, b):
"""return a+b"""
return a + b
def main():
result = sum(1, 2)
print(f"1+2={result}")
if __name__ == "__main__":
main()
|
546224b3f7a37b6cbe81799c985c8c431d30c77f | JasPass/Projects | /Project_Euler/Problem 14 script.py | 1,461 | 3.671875 | 4 | # Project Euler: Problem 14
#
#
# Which starting number, under one million, produces the longest chain?
import time
# Sets starting time of program
startTime = time.time()
# Function to run the sequence until 1 is reached
def sequence(n, sequence_length=1):
# Checks if (n) is even
if n % 2 == 0:
n /= 2
# If (n) is not even, it must be odd
else:
n *= 3
n += 1
# Counts up the sequence length
sequence_length += 1
# Checks if number is still greater than 1
if n > 1:
# Runs the next iteration of the sequence
return sequence(n, sequence_length)
else:
# If this code is reached, (n) equals 1, and we are done
return sequence_length
# Longest found sequence length and corresponding seed
output = [1, 0]
# Loops through all numbers bellow 1 million
for i in range(2, 10**6):
# Sets the current sequence length
length = sequence(i)
# Checks if the sequence length is greater than
# the previously greatest sequence length
if length > output[1]:
# Sets the new greatest sequence length and seed
output = [i, length]
# Variable to hod answer
ans = output[0]
# Prints out the answer
print('The answer to Project Euler problem 14 is:', ans)
# Sets finishing time of program
stopTime = time.time()
# Prints the time it took the program to execute
print('The computation took', '%.2g' % (stopTime - startTime), 'seconds')
|
fb78f5f6c9f6c5bdbe24a0c63228dfc9bc7c4317 | cce-bigdataintro-1160/winter2020-code | /4-python-advanced-homework/numpy-exercises.py | 1,928 | 4.15625 | 4 | import numpy as np
# 1 - Create your first array with the elements [1,22.4,5,35,4,6.7,3,8,40] and print it. Experiment what the
# following functions do: ndim, shape, size and dtype.
my_array = np.array([1, 22.4, 5, 35, 4, 6.7, 3, 8, 40])
print(my_array)
print(f'my_array.ndim is {my_array.ndim}')
print(f'my_array.shape is {my_array.shape}')
print(f'my_array.size is {my_array.size}')
print(f'my_array.dtype is {my_array.dtype}')
# 2 - Create your first matrix with the elements [['a', 'b'],['c', 'd'],[3, 3]] and print it. Experiment what the
# following functions do: ndim, shape, size and dtype
my_matrix = np.array([['a', 'b'], ['c', 'd'], [3, 3]])
print(my_matrix)
print(f'my_matrix.ndim is {my_matrix.ndim}')
print(f'my_matrix.shape is {my_matrix.shape}')
print(f'my_matrix.size is {my_matrix.size}')
print(f'my_matrix.dtype is {my_matrix.dtype}')
# 3 - Create numpy 1 dimension array using each of the functions arange and rand
range_array = np.arange(0, 10)
print(f'range_array is {range_array}')
random_array = np.random.rand(10)
print(f'random_array is {random_array}')
# 4 - Create numpy 2 dimensions matrix using each of the functions zeros and rand
zeros_matrix = np.zeros((5, 5))
print(f'range_array is {zeros_matrix}')
random_matrix = np.random.rand(4, 4)
print(f'random_array is {random_matrix}')
# 5 - Create an array containing 20 times the value 7. Reshape it to a 4 x 5 Matrix
result_array = np.ones(20) * 7
reshaped_array = result_array.reshape(4,5)
print(reshaped_array)
# 6 - Create a 6 x 6 matrix with all numbers up to 36, then print:
matrix_to_slice = np.arange(1, 37).reshape(6, 6)
print(matrix_to_slice)
print(f'only the first element on it: {matrix_to_slice[0,0]}')
print(f'only the last 2 rows for it: {matrix_to_slice[4:6,:]}')
print(f'only the two mid columns and 2 mid rows for it: {matrix_to_slice[2:4,2:4]}')
print(f'the sum of values for each column: {matrix_to_slice.sum(axis=0)}')
|
99854ce996de0606fe5a797acc32d72cd0818a5f | SatyamJindal/Competitive-Programming | /CodeChef/Chef and prime Queries.py | 720 | 3.703125 | 4 | from math import sqrt
n=int(input())
a=list(map(int,input().split(" ")))
q=int(input())
def isPrime(x):
flag=0
for i in range(2,int(sqrt(x))+1):
if(x%i==0):
flag=1
break
if(flag==1):
return False
else:
return True
def F(L,R,X,Y):
result=0
for i in range(X,Y+1):
if(isPrime(X)):
for j in range(L-1,R):
number=a[j]
exponent=0
while(number%i==0):
exponent+=1
number//=i
result+=exponent
return result
for i in range(q):
L,R,X,Y=map(int,input().split(" "))
print(F(L,R,X,Y))
|
1305ac39181fa5afc93c50679c9657ddf96a9b8a | lfdyf20/Leetcode | /Clone Graph.py | 821 | 3.6875 | 4 | # Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
from collections import deque
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node:
return
nodeCopy = UndirectedGraphNode(node.label)
dic = {node:nodeCopy}
quene = deque( [node] )
while quene:
node = quene.popleft()
for neighbor in node.neighbors:
if neighbor not in dic:
neighborCopy = UndirectedGraphNode( neighbor.label )
dic[neighbor] = neighborCopy
dic[node].neighbors.append( neighborCopy )
quene.append(neighbor)
else:
dic[node].neighbors.append( dic[neighbor] )
return nodeCopy |
867be1f4144834bd20914439283198fd99efbb06 | Daniel-TheProgrammer/Sub-Directory-Update | /dan2.py | 352 | 3.515625 | 4 | from tkinter import*
root=Tk()
topFrame= Frame(root)
top.Frame.pack()
bottomFrame=Frame(root)
bottomframe.pack(side=BOTTOM)
button1= Button(topFrame,text="Button1",fg="red")
button2= Button(topFrame,text="Button2",fg="blue")
button3= Button(topFrame,text="Button3",fg="green")
button4= Button(topFrame,text="Button4",fg="purple")
root.mainloop()
|
13e01313f6b2534b0c74b0f0284565616c9c56c1 | SkyNet214/WPU-INFO | /Python/Graphentheorie/graph.py | 2,453 | 3.703125 | 4 | # graph .py
# Ein Graph ist ein Menge von Knoten und eine Menge von ungerichteten Kanten
# Die Darstellung erfolgt in einer Adjazenzliste mithilfe eines Dictionary
# Knotenwerte sind vorerst nur Zahlen
class Graph():
def __init__ (self, graph={}) -> None :
self.__graph = graph
def vertex_count(self) -> int:
return len(self.__graph) # Anzahl der Knoten
def vertices(self):
"""gibt die Knoten des Graphen aus"""
return list(self.__graph.keys())
def _generate_edges(self):
edges = []
for node in self.__graph:
for neighbour in self.__graph[node]:
edges.append({node,neighbour})
return edges
def edges(self):
""" gibt die Kanten eines Graphen aus """
return self._generate_edges()
# Die wohlformatierte Ausgabe eins Graphen ermoeglichen
def __str__(self) -> str:
res = "vertices:"
for k in self.__graph :
res += str(k) + " "
res += "\nedges: "
for edge in self._generate_edges():
res += str(edge) + " "
return res
def add_edge(self, edge):
(v0, v1) = tuple(edge)
if v0 in self.__graph:
self.__graph[v0].append(v1)
else:
self.__graph[v0] = [v1]
def add_vertex(self, vertex):
if vertex not in self.__graph:
self.__graph[vertex] = []
def contains(self, node):
for i in self.__graph:
if i == node:
return True
for j in self.__graph[i]:
if j == node:
return True
return False
def contains_cycles(self):
def check_neighbours(graph_dict, v0, n):
if n in graph_dict:
for i in graph_dict[n]:
if i == v0 or check_neighbours(graph_dict, v0, i):
return True
return False
for i in self.__graph:
if check_neighbours(self.__graph, i, i):
return True
return False
if __name__ == "__main__":
# Grundlegende Konstruktion des Graphen testen
#d ={1:[1] ,5:[2 ,3]}
d = {1:[2], 2:[3], 3:[4,5,6], 6:[90, 64], 90:[1], 64:[]}
graph = Graph(d)
print(graph)
print("Edges of graph:")
print(graph.edges())
graph.add_edge({2 ,3})
print(graph.edges())
print(graph)
print(graph.contains(20))
print(graph.contains_cycles()) |
cc478b8b42776a196f3c6f081fcae6e24627bb5e | TPei/jawbone_visualizer | /plotting/LineGraph.py | 1,470 | 3.53125 | 4 | __author__ = 'TPei'
import matplotlib.pyplot as plt
from plotting.Plot import Plot
class LineGraph(Plot):
"""
representing a line graph
"""
def __init__(self, data=None):
"""
:param data: data dict {'xdata': [...], 'ydata': [...]}
sets ydata and xdata
:return:
"""
self.data = data
self.ydata = []
self.xdata = []
if 'xdata' in data:
self.xdata = data['xdata']
if 'ydata' in data:
self.ydata = data['ydata']
def get_plot_data(self):
"""
depending on whether or not there is y and xdata available
plot plots accordingly
:return: plt
"""
if len(self.ydata) == 0:
return plt
if len(self.ydata) == len(self.xdata):
if not isinstance(self.ydata[0], list):
plt.plot(self.xdata, self.ydata)
else:
for i in range(0, len(self.ydata)):
plt.plot(self.xdata[i], self.ydata[i])
else:
if not isinstance(self.ydata[0], list):
plt.plot(self.ydata)
else:
for date in self.ydata:
plt.plot(date)
return plt
def plot(self):
self.get_plot().show()
if __name__ == '__main__':
line = LineGraph({'xdata': [1, 2, 3, 4, 5], 'ydata': [1, 4, 9, 16, 25]})
#plt = line.get_plot()
#plt.show()
line.plot() |
88a3907ee633b95bdd77e3bfef567bab4c5ca35c | shonihei/road-to-mastery | /leetcode/distribute-candies.py | 575 | 4.125 | 4 | """
Given an integer array with even length, where different numbers in
this array represent different kinds of candies. Each number means one
candy of the corresponding kind. You need to distribute these candies
equally in number to brother and sister. Return the maximum number of kinds of
candies the sister could gain.
"""
def distributeCandies(candies):
d = dict()
for candy in candies:
d[candy] = d.get(candy, 0) + 1
return int(min(len(candies) / 2, len(d)))
print(distributeCandies([1, 1, 2, 3]))
print(distributeCandies([1, 1, 2, 2, 3, 3])) |
6d80acd8524eecad6714e589a4cc9f40be8d35d8 | ShunKaiZhang/LeetCode | /search_in_rotated_sorted_array_II.py | 1,759 | 4.15625 | 4 | # python3
# Follow up for "Search in Rotated Sorted Array":
# What if duplicates are allowed?
# Would this affect the run-time complexity? How and why?
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
# Write a function to determine if a given target is in the array.
# The array may contain duplicates.
# My solution
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
def bs(nums, l, r, target):
if l >= r:
return l
if nums[l] == target:
return l
if nums[r] == target:
return r
mid = (l + r) // 2
if nums[mid] == target:
return mid
if nums[mid] < nums[l]:
if target > nums[mid] and target < nums[l]:
return bs(nums, mid + 1, r, target)
else:
return bs(nums, l, mid, target)
elif nums[mid] > nums[r]:
if target < nums[mid] and target > nums[r]:
return bs(nums, l, mid, target)
else:
return bs(nums, mid + 1, r, target)
else:
# why -1? becasue of the duplicates, we cannot decide which side, so we can only decrease 1
return bs(nums, l, r - 1, target)
if nums == []:
return False
out = bs(nums, 0, len(nums) - 1, target)
if nums[out] == target:
return True
else:
return False |
631ea9106eccef6e883c579d91569dcbcdc2b6d5 | anhnh23/PythonLearning | /src/theory/control_flow/for_loop.py | 1,569 | 3.765625 | 4 | '''
Created on Dec 8, 2016
@author: ToOro
'''
"""
Behind the scene: for statement calls iter() on the container object.
"""
#--------- How iter() works ---------
s = 'abc'
it = iter(s)
print(next(it))
print(next(it))
print(next(it))
# enumerate() : can be retrieved index and corresponding value
for i, v in enumerate(['tic', 'tac', 'toe']):
print (i, v) # result: 0 tic \n 1 tac \n 2 toe
# zip() : to loop over 2 or MORE sequence at the same time
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print ('What is your {0}? It is {1}.'.format(q, a))
# loop in reversing
for i in reversed(range(1, 10, 2)):
print (i)
# loop and sort
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)): # firstly eliminate duplicated elements with set, then sort
print (f)
# iteritems() : to get key and value at the same time
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print (k, v)
# filter data
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
words=['cat','window', 'defenestrate']
for w in words:
print(w, len(w))
for element in (1,2,3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')
|
b55431ded794822e76e0834f4524e918078e4739 | jashidsany/Learning-Python | /LCodecademy Lesson 10 Classes/LA10.15_Exceptions.py | 978 | 3.828125 | 4 | # An Exception is a class that inherits from Python’s Exception class.
# We can validate this ourselves using the issubclass() function. issubclass() is a Python built-in function that takes two parameters. issubclass() returns True if the first argument is a subclass of the second argument. It returns False if the first class is not a subclass of the second. issubclass() raises a TypeError if either argument passed in is not a class.
# Define your exception up here:
class OutOfStock(Exception):
pass
# Update the class below to raise OutOfStock
class CandleShop(OutOfStock):
name = "Here's a Hot Tip: Buy Drip Candles"
def __init__(self, stock):
self.stock = stock
def buy(self, color):
self.stock[color] = self.stock[color] - 1
if self.stock[color] < 1:
raise OutOfStock
candle_shop = CandleShop({'blue': 6, 'red': 2, 'green': 0})
candle_shop.buy('blue')
# This should raise OutOfStock:
# candle_shop.buy('green')
|
7a500c4181d2d4c793b3856bb84a509db361b861 | Mohit-Maurya/Baisc_Interesting_programs_ | /higher_lower_game/main.py | 1,305 | 3.890625 | 4 | from art import logo, vs
from game_data import data
from replit import clear
import random
#Choose 2 random data
A = random.choice(data)
B = random.choice(data)
#compare A and B 'follower_count'
def compare_AB(a, b):
if a > b:
return "a"
else:
return "b"
#Print logo AND compare A - vs - Against B
def compare_print(compare):
compare_string = f"{compare['name']}, a {compare['description']}, from {compare['country']}."
return compare_string
def gui(A, B):
print(logo)
print("Compare A: " + compare_print(A))
print(vs)
print("Against B: " + compare_print(B))
# main game function
def game(A, B):
score = 0
while True:
gui(A, B)
#print(A['follower_count'], B['follower_count'])
#take input A or B
guess = input("Who has more followers? Type 'A' or 'B': ").lower()
clear()
#if right then increase score by 1 else terminate the game by writing final score.
#print(guess)
if guess == compare_AB(A['follower_count'], B['follower_count']):
score += 1
A, B = B, random.choice(data)
print(f"You're right! Current score: {score}.")
else:
print(f"Sorry, that's wrong. Final score: {score}")
break
game(A, B)
|
24c58cd85a2c825df516adc47509493981256ba2 | parsanoroozi/Pythonw3schools | /src/Tutorial/variable/Variable.py | 1,131 | 4.4375 | 4 |
# multiple variable
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
x = y = z = "Orange"
print(x)
print(y)
print(z)
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
x = "Python is "
y = "awesome"
z = x + y
print(z)
#global variables:
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
#.................................
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
#.................................
def myfunc():
global x
x = "fantastic"
myfunc()
#.................................
print("Python is " + x)
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
#end of global variables
print("Python is " + x)
# typical points about variable
x = 5
y = "John"
print(x)
print(y)
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
x = 5
y = "John"
print(type(x))
print(type(y))
x = "John"
# is the same as
x = 'John'
a = 4
A = "Sally"
# A will not overwrite a
|
910091988637152040d4c50cbddff2e42e092d8a | methjx/educ_de_ba_ver | /bölüm4_oop/objectorientedpro3.py | 1,486 | 4.46875 | 4 | #Inheritance (Kalıtım): Miras Alma
#Person => name, lastname, age, eat(), run(), drink()
#Student(Person), Teacher(Person) gibi class tanımlarsam üstteki görevleri bu classda olmasını isterim
#Animal = > Dog(Animal), Cat(Animal)
class Person():
def __init__(self, fname, lname):
self.isim = fname
self.soyisim = lname
print("Person Created")
def who_am_i(self):
print("I am a person..")
def eat(self):
print("Im eating right now...")
class Student(Person):
def __init__(self, fname, lname, stunum):
Person.__init__(self, fname, lname) ### Bunu yaparak persondaki özellikleri de miras aldım
print("Student Created")
self.numara = stunum
#override
def who_am_i(self):
print("Im student....")
def sayHello(self):
print("Hello student!!!")
class Teacher(Person):
def __init__(self, fname, lname, branch):
super().__init__(fname, lname) #Person.__init__(self, fname, lname) ^^ e alternatif olarak...
self.branch = branch
def who_am_i(self):
print(f"Iam {self.branch}teacher")
p1 = Person("Ali", "Yılmaz")
s1 = Student("Mehmet", "Yılmaz", 4379)
t1 = Teacher("Serkan","Yilmaz","Math")
print(f"p1--> name: {p1.isim} and lastname: {p1.soyisim}")
print(s1.isim + " " + s1.soyisim + " " + str(s1.numara))
p1.who_am_i()
s1.who_am_i()
p1.eat()
s1.eat()
s1.sayHello()
t1.who_am_i() |
ec4b7a7cad3b21a09a3b035092467d67d3b06c03 | SiddarthSingaravel/CS50 | /pset6/mario/less/mario.py | 368 | 3.890625 | 4 | from cs50 import get_int
# getting correct user input
while True:
h = get_int("Height: ")
if h > 0 and h < 9:
break
# initalizing i and j to 0
i = 0
j = 0
# running two loops for printing blocks
for i in range(h):
for j in range(h):
if i + j < h - 1:
print(" ", end="")
else:
print("#", end="")
print() |
ddf24a45c8542eee94779c6b89ab1fa462c005b4 | Vigneshrajvr/Python-Intership-BEST-ENLIST | /day2.py | 639 | 3.765625 | 4 | print('30 days 30 hours challenge');
print("30 days 30 hours challenge");
Hours='thirty';
print(Hours);
Days='Thirty days';
print(Days[0]);
Challenge = "I will win";
print(Challenge[7:10]);
print(len(Challenge));
print(Challenge.lower());
a = "30 Days";
b = "30 hours";
c = a + b;
print(c);
c = a + " " + b;
print(c);
text = "Thirty days and Thirty hours";
x = text.casefold();
print(x);
text1="DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU";
y = text.capitalize();
print(y);
z = text.find('days');
print(z);
text2='rex';
x1 = text2.isalpha();
print(x1);
text3='rex123';
y1 = text3.isalnum();
print(y1);
|
f12983388c8185b6c37e20c7ac62b9f363f08aa1 | tbywaters/cryptopals-solutions | /cryptopalsmod/stringops.py | 1,139 | 4 | 4 | """ A collection of functions which are used for manipulating string when
solving the cryptopals challenges"""
def kequalsv_to_dict(kequalsv_str):
"""Splits a string into chucnks using & as separators. Builds a dictionary
from each chunk using = as a separtor for keys and values.
eg:
'foo=bar&baz=qux&zap=zazzle' -> {'foo':'bar, 'baz':qux, 'zap':'zazzle}
"""
result = {}
splits = kequalsv_str.split('&')
for split in splits:
entry_pair = split.split('=')
# If a split does not contain the character =, add the whole split as
# a key with an empty string value
if len(entry_pair) == 1:
entry_pair.append('')
# If a split contains more than one =, only use the first as a split.
# Keep excess = in the value
if len(entry_pair) > 2:
entry_pair[1] = '='.join(entry_pair[1:])
result[entry_pair[0]] = entry_pair[1]
return result
def remove_meta_chars(input_string, meta_chars):
for char in meta_chars:
input_string = input_string.replace(char, '')
return input_string
|
eba80c6370211b29efd21c98c9298c6385d85875 | lizhihui16/aaa | /pbase/day18/shili/class_method2.py | 363 | 3.734375 | 4 |
class A:
v=0
@classmethod
def get_v(cls):
return cls.v #获取类变量v的值
@classmethod
def set_v(cls,value):
cls.v=value #设置类变量v=value
a=A() #创建的实例对象
print(a.get_v()) #借助对象来调用类方法
a.set_v(100) #借助对象来设置类变量v
print(a.get_v()) #100
print(A.v) #100 |
24a3ef2915a7dbcfff963dff82ad51429f7e5a2f | masonbot/Wave-1 | /Wave 1/makingchanges.py | 302 | 3.765625 | 4 | Cash = int(input("Insert amount of cash in cents:"))
print(Cash//200, "Toonies")
Cash= Cash%200
print(Cash//100, "loonies")
Cash= Cash%100
print(Cash//25, "quarters")
Cash = Cash%25
print(Cash//10, "dimes")
Cash = Cash%10
print(Cash//5, "nickles")
Cash = Cash%5
print(Cash//1, "pennies")
Cash = Cash%1
|
170c155ab5aa03873a78f028a2b35d92b83213e5 | aravindhan2000/test | /odd and even number.py | 290 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
numbers=(1,2,3,4,5,6,7,8,9)
count_odd=0
count_even=0
for i in numbers:
if i%2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
# In[ ]:
|
3c47566c01205069c7403bc785f2cad463134294 | AzimAstnoor/BasicPython | /5r.py | 277 | 3.578125 | 4 | try:
i = int(input('Enter the no.'))
a = []
for i in range(0, i):
b = int(input('Enter the no.'))
a.append(b)
i = i - 1
m = []
for x in a:
if x%2 != 0:
m.append(x)
print(m)
except Exception as Z: print(Z) |
9f8fd7ce49ff5bf9183fb733dd72e99e2273b9df | smartvkodi/learn-python | /4-Python_Flow_Control_Part-1/63-Finding_Smallest_and_Biggest_Number_by_using_if-elif-else.py | 2,448 | 4.34375 | 4 | # 63 - Finding Smallest and Biggest Number by using if-elif-else Statement
msg = '63 Finding Smallest and Biggest Number by using if-elif-else Statement'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''Program-1: Find the biggest Number of 2 given numbers
no1 = int(input('Enter first number:'))
no2 = int(input('Enter second number:'))
max = no1
if no1 < no2:
max = no2
print('The biggest number is:', max)
''')
no1 = int(input('Enter first number:'))
no2 = int(input('Enter second number:'))
max = no1
if no1 < no2:
max = no2
print('The biggest number is:', max)
print('''\nProgram-2: Find the smallest Number of 2 given numbers
no1 = int(input('Enter first number:'))
no2 = int(input('Enter second number:'))
min = no1
if no1 > no2:
min = no2
print('The smallest number is:', min)
''')
no1 = int(input('Enter first number:'))
no2 = int(input('Enter second number:'))
min = no1
if no1 > no2:
min = no2
print('The smallest number is:', min)
print('''\nProgram-3: Find the biggest Number of 3 given numbers
a = int(input('Enter first number:'))
b = int(input('Enter second number:'))
c = int(input('Enter third number:'))
if a>b and a>c:
max = a
elif b>c:
max = b
else:
max = c
print('The biggest number is:', max)
''')
a = int(input('Enter first number:'))
b = int(input('Enter second number:'))
c = int(input('Enter third number:'))
if a>b and a>c:
max = a
elif b>c:
max = b
else:
max = c
print('The biggest number is:', max)
print('''\nProgram-4: Find the smallest Number of 3 given numbers
a = int(input('Enter first number:'))
b = int(input('Enter second number:'))
c = int(input('Enter third number:'))
if a<b and a<c:
min = a
elif b<c:
min = b
else:
min = c
print('The smallest number is:', min)
''')
a = int(input('Enter first number:'))
b = int(input('Enter second number:'))
c = int(input('Enter third number:'))
if a<b and a<c:
min = a
elif b<c:
min = b
else:
min = c
print('The smallest number is:', min)
print('''\nProgram-5: Check if the given number is between 1 and 100
a = int(input('Enter any number:'))
if a>1 and a<100:
print('The entered number is between 1 and 100)
else:
print('The entered number is not between 1 and 100)
''')
a = int(input('Enter any number:'))
if a>=1 and a<=100:
print('The entered number {} is in between 1 and 100'.format(a))
else:
print('The entered number {} is not in between 1 and 100'.format(a))
|
0f52957230c9ac650ffd29d24a6da26701bfc97c | whoisgvb/initial_python | /estruturaRepeticao/018.py | 419 | 4.03125 | 4 | """
Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores.
"""
n = int(input("Digite os laços: "))
maior = 0
menor = 0
for i in range(n):
x = int(input("Digite um número: "))
maior = (maior if maior != 0 and maior > x else x)
menor = (menor if menor != 0 and menor < x else x)
print (f'O maior valor digitado foi {maior} e o menor foi {menor}') |
740aec520fd9e276b6c88177adc00d2749895033 | kesihain/python-challenges | /binary_search.py | 368 | 3.78125 | 4 |
def binary_search(target, my_list):
# your code
low = 0
high = len(my_list)
while low <= high:
i = (low+high)//2
if my_list[i] < target:
low = i+1
continue
if my_list[i] > target:
high= i-1
continue
return i
return None
print(binary_search(56, list(range(1, 201))))
|
4473191b48b90a9576f654df44a01ac1cfbef05d | ivn-svn/Python-Advanced-SoftUni | /Exam/Problem2..py | 2,053 | 3.78125 | 4 | from math import floor
PLAYER = "P"
WALLS = "X"
def create_matrix(size):
return [input().split() for line in range(size)]
def find_player_position(matrix, PLAYER):
for row in range(len(matrix)):
for col in range(len(matrix)):
if matrix[row][col] == PLAYER:
return (row, col)
def in_range(row, column, matrix):
if row in range(len(matrix)) and column in range(len(matrix)):
return True
def read_commands(matrix, player_position, valid_commands, WALLS):
player_row, player_col = player_position
coins = 0
path = []
game_over = False
while True:
if coins >= 100:
break
command = input()
if command in valid_commands:
move_row, move_col = valid_commands[command]
if in_range(player_row + move_row, player_col + move_col, matrix):
player_row += move_row
player_col += move_col
if matrix[player_row][player_col] == WALLS:
game_over = True
break
else:
coins += int(matrix[player_row][player_col])
path.append([player_row, player_col])
else:
game_over = True
break
return game_over, path, coins
def print_result(game, path, coins):
if game:
coins /= 2
print(f"Game over! You've collected {floor(coins)} coins.")
else:
print(f"You won! You've collected {floor(coins)} coins.")
print('Your path:')
for el in path:
print(el)
# data = [
# "1 X 7 9 11",
# "X 14 46 62 0",
# "15 33 21 95 X",
# "P 14 3 4 18",
# "9 20 33 X 0",
# ]
size = int(input())
matrix = create_matrix(size)
player_position = find_player_position(matrix, PLAYER)
valid_commands = {
"up": (-1, 0),
"down": (+1, 0),
"left": (0, -1),
"right": (0, +1)
}
game, path, coins = read_commands(matrix, player_position, valid_commands, WALLS)
print_result(game, path, coins)
|
4e6be706b2542a950565c110e79d2fafd9304b81 | m3schroder/coursefiles | /AI/8-puzzle with a-star/functions.py | 1,277 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Calculates total displaced tiles on the board
def h1(state):
displaced = 0
goal = [[0,1,2],[3,4,5],[6,7,8]]
for i in range(0,3):
for j in range(0,3):
if goal[i][j] != state.__hash__()[i][j]:
displaced += 1
return displaced
# Calculates and returns the sum of the manhatann distance for every tile on the board
def h2(state):
distance = 0
for i in range(0,3):
for j in range(0,3):
x1, y1 = i, j
x2, y2 = int(state.__hash__()[i][j]/3), state.__hash__()[i][j] % 3
distance += abs(x1-x2) + abs(y1 - y2)
return distance
# Returns the number of valid moves avaiable based on the current state of the board
def h3(state):
moves = [state.copy().up(), state.copy().down(), state.copy().left(), state.copy().right()]
valid_moves = []
for move in moves:
if move:
valid_moves.append(move)
return len(valid_moves)+1
# Function used to delegate h calls
def h(state,selection):
if selection == 0:
return 0
elif selection == 1:
return h1(state)
elif selection == 2:
return h2(state)
elif selection == 3:
return h3(state)
else:
exit(1) |
9b9e60f1b2a70826a075bc66c4989ca4277ed93e | JacobSilasBentley/EulerProject | /problem2.py | 835 | 3.90625 | 4 | # Problem 2
#
# Each new term in the Fibonacci sequence is generated by adding the
# previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do
# not exceed four million, find the sum of the even-valued terms.
#
#
# Answer = 4613732
#
import timeit
def method():
""" Returns the sum of all the even fibonacci numbers under 4000000. """
limit = 4000000
sum = 0
previous = 0
i = 1
while i < limit:
t = i
i += previous
previous = t
# Checking if the fibbonacci number is even
if i%2 == 0:
sum += i
return sum
def main():
""" Main Method """
print(method())
if __name__ == "__main__":
main()
|
d31333b29ba5ed90d3453f67056e5792163ea79e | amobdi/faseeh | /fasseh/Parser.py | 2,977 | 3.609375 | 4 | import itertools
from textblob import Word
# class Parser is responsible to parse the tags of the statement to get all nouns, verbs, questions words and generate all patterns
class Parser(object):
# define the tags needed to extract the nouns, the verbs, the question words.
def __init__(self):
self.noun_tags = ['NN','NNS','NNP','NNPS']
self.adjective_tags = ['JJ','JJR','JJS','VBG']
self.question_tags = ['WP','WP$','WRB','WDT']
self.verb_tags = ['VB','VBZ','VBP','VBD','VBG','VP','VPN']
self.neglect = ['is','are','was','were','be','am','do','did','does','doing','done','has','have','had','having']
self.separator = ' H '
# parse the tags to extract the nouns
# args:
# words_tags : list of pair of the word and its tag
# return:
# list of all nouns in the statement
def get_nouns(self,words_tags) :
result = []
string = ''
for idx, (word, tag) in enumerate(reversed(words_tags)) :
if tag in self.noun_tags :
if string :
string = word + ' ' + string
else :
string = word
elif tag in self.adjective_tags and string :
string = word + ' ' + string
elif string :
result.append((len(words_tags)-idx, string))
string = ''
result.reverse()
return result
# parse the tags to extract the question words
# args:
# words_tags : list of pair of the word and its tag
# return:
# list of all question words in the statement
def get_question_words(self,words_tags) :
result = []
for idx, (word, tag) in enumerate(words_tags) :
if tag in self.question_tags :
result.append((idx, word))
return result
# parse the tags to extract the verbs
# args:
# words_tags : list of pair of the word and its tag
# return:
# list of all verbs in the statement
def get_verbs(self,words_tags) :
result = []
for idx, (word, tag) in enumerate(words_tags) :
if tag in self.verb_tags :
verbz = Word(word)
if verbz.lemmatize("v") not in self.neglect and word not in self.neglect:
src_verb = verbz.lemmatize("v")
result.append((idx, src_verb))
return result
# generate all combinations of the keywords of the statement
# args:
# words_tags : list of pair of the word and its tag
# return:
# list of all patterns of the keywords in the statement
def get_all_question_combinations(self, words_tags) :
result = []
nouns = self.get_nouns(words_tags)
question_words = self.get_question_words(words_tags)
verbs = self.get_verbs(words_tags)
statement = []
statement.extend(nouns)
statement.extend(question_words)
statement.extend(verbs)
statement.sort()
statement = [word[1] for word in statement]
for l in range(len(statement), 0, -1) :
sub_lists = list(itertools.combinations(statement, l))
for sub_list in sub_lists :
sample_question = ''
for word in sub_list :
sample_question = sample_question + self.separator + word
sample_question = sample_question + self.separator
result.append(sample_question)
return result |
9826382e86c71a3e0cef23c4d4c5b490d80f3d00 | saikiranrede/Coding-challenges | /rndm_pass_gen.py | 322 | 3.796875 | 4 | import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()'
def pass_char(value):
password = ''
for item in range(value):
password += random.choice(chars)
return password
value = input("Enter a value for number of chars for pass: ")
print(pass_char(int(value)))
|
22fc9af468b039cf0f101d0f662a7bdb72761a37 | CribberSix/finding_earl_minigame | /src/Parser/Parser.py | 4,137 | 4.0625 | 4 |
class Parser:
def __init__(self):
"""
The parser is used to map the user's input to game functionality.
It asks for clarification if it couldn't successfully parse the input.
"""
self.last_input = "" # no concrete usage so far
self.directions\
= ["west", "east", "south", "north", "forward", "forwards", "backward", "backwards", "left", "right"]
def receive_input(self, input_text):
"""
The parser takes the user's input string, splits it on spaces
and tries to map the words to game-functionality.
In case the parser can map a <verb> directly to a game function, it returns sucessfully.
The parser returns unsuccessfully with a message, if:
- too many words were given
- too little words were given
- confusing words were given
- the parser does not know the <verb> or the <object> or any other <parameter>
Expected syntax:
<verb> <optional_pronoun> <optional_descriptive_adjective> <object>
:param input_text:
:return: Tuple
0, ["message"] # unsuccessful
1, [<**args>] # successful
"""
self.last_input = input_text.lower().split()
if self.last_input[0] in ("help", "look", "info", "inventory", "i"):
return self.parse_one_word_command()
elif self.last_input[0] in ("go", "walk"):
return self.parse_go()
elif self.last_input[0] in ("inspect", "read", "take", "drop", "open"):
return self.parse_object_command()
else:
return 0, ["I do not know this verb."]
def parse_one_word_command(self):
if len(self.last_input) > 1:
return 0, [f"I only understood you as far as wanting to {self.last_input[0]}."]
else:
if self.last_input == "i": # map shortcut to game function
self.last_input = "inventory"
return 1, self.last_input
def parse_object_command(self):
# depending on the environment, pass on to GameState if an object is given.
try:
_ = self.last_input[1] # at least one more word has to be given (object), optionally with an adjective
return 1, self.last_input
except IndexError:
return 0, [f"What do you want to {self.last_input[0]}?"]
def parse_go(self):
"""
Expection: 'go <direction>'
- Expects a valid direction as the second input
- Expect no other input
:return: Tuple
0, ["message"] # unsuccessful
1, [<**args>] # successful
"""
# get direction
try:
desired_direction = self.last_input[1]
if desired_direction not in self.directions:
return 0, [f"I only understood you as far as wanting to {self.last_input[0]}."] # no valid direction given
except IndexError:
return 0, [f"Where do you want to {self.last_input[0]} to?"] # no direction given
# test if there is another word
try:
_ = self.last_input[2] # second input is not expected after the direction
if desired_direction in self.directions:
return 0, [f"I only understood you as far as wanting to {self.last_input[0]} {self.last_input[1]}."]
else:
return 0, [f"I only understood you as far as wanting to {self.last_input[0]}."]
except IndexError:
pass # we don't expect any other arguments
# Map various expressions to the game functionality
if desired_direction in ["west", "left"]:
return 1, ["go", "left"]
elif desired_direction in ["north", "forwards", "forward"]:
return 1, ["go", "forward"]
elif desired_direction in ["south", "backwards", "backward"]:
return 1, ["go", "backward"]
elif desired_direction in ["east", "right"]:
return 1, ["go", "right"]
else:
return 1, ["go", desired_direction]
|
cb70103705d5a8e2339d84de05327dc17e9daecf | RAMKUMAR7799/Python-program | /Beginner/binaryornot.py | 134 | 3.640625 | 4 | n=str(input(""))
flag=0
for i in n:
if int(i) not in range(0,2):
flag=1
break
if flag>0:
print("no")
else:
print("yes")
|
214d2f99f71449e8a48ac52902e1f4da7745cdb6 | cafenoctua/100knock2019 | /Naoto/chapter06/knock53.py | 624 | 3.71875 | 4 | '''
53. Tokenization
Stanford Core NLPを用い,入力テキストの解析結果をXML形式で得よ.\
また,このXMLファイルを読み込み,入力テキストを1行1単語の形式で出力せよ.
'''
import re
def Tokenization(input_, output_):
with open(input_) as f, open(output_, "w") as fw:
for line in f:
word = re.search("<word>([a-zA-Z0-9]{2,})</word>", line)
if word is not None:
print(word.group(1), file=fw)
if __name__ == "__main__":
input_ = "nlp.txt.xml"
output_ = "Tokenization_53.txt"
Tokenization(input_, output_)
|
12994e12df90c5506fed6820154f820005f32dc4 | BeeverFeever/Tic-Tac-Toe | /Tic_Tac_Toe-Python/Tic_Tac_Toe.py | 1,804 | 3.84375 | 4 | board = ["-", "-", "-", "-", "-", "-", "-", "-", "-",]
winner = None
def GenerateBoard():
print(f"""{board[0]}|{board[1]}|{board[2]}
{board[3]}|{board[4]}|{board[5]}
{board[6]}|{board[7]}|{board[8]}""")
def GetInput(player):
position = int(input(f"'{player}' Turn, where would you like to place your piece (0-9): "))
position -= 1
run = True
#adds piece to the board - with error checking
while(run == True):
if board[position] == '-':
if player == 'O':
board[position] = 'O'
run = False
if player == 'X':
board[position] = 'X'
run = False
else:
position = int(input("Please enter a valid position, 1-9: "))
position -= 1
def CheckWin(piece):
global winner
#check vertical wins
for i in range(3):
if board[i] == piece and board[i + 3] == piece and board[i + 6] == piece:
winner = piece
#check horizontal wins
for i in range(0, 8, 4):
if board[i] == piece and board[i + 1] == piece and board[i + 2] == piece:
winner = piece
#check diagonal wins
if board[0] == piece and board[4] == piece and board[8] == piece:
winner = piece
if board[i] == piece and board[2] == piece and board[4] == piece:
winner = piece
#check tie
for i in range(len(board)):
if board[i] != 'X' or 'O':
return
elif i == 8:
winner = 'Tie'
def MainGameLoop(isWinner):
while isWinner == None:
#X's turn
GenerateBoard()
GetInput('X')
CheckWin('X')
CheckWin('O')
#O's turn
GenerateBoard()
GetInput('O')
CheckWin('O')
CheckWin('X')
#display who won
if isWinner == 'Tie':
GenerateBoard()
print(f"It is a Tie.")
elif isWinner == 'X' or 'O':
GenerateBoard()
print(f"{isWinner} is the winner.")
MainGameLoop(winner) |
9a076e154a3a9e2cdb8ef2fd35c1e4c55e5b4fe1 | ViniciusMadureira/python-script | /rock_paper_scissors/rock_paper_scissors.py | 859 | 3.890625 | 4 | ### -*- coding: utf-8 -*-
__author__="Vinícius Silva Madureira Pereira <viniciusmadureira@outlook.com"
__date__="$Feb 2, 2017 6:33:19 AM$"
import random
# Main mathematical function of the algorithm: ƒ(n, m) = mⁿ
def player_value(n, m):
return m ** n
def winner(player1, player2):
if player1 == player2:
return 'None'
p1 = player_value(player1, player2)
p2 = player_value(player2, player1)
return get_element(player1) if p1 > p2 else get_element(player2)
def get_element(player_value):
return [key for key, value in elements.items() if value == player_value][0]
elements = {'rock': 2, 'paper': 1, 'scissors': -2}
# Test
for index in range(11):
player1= random.choice(list(elements.items()))[0]
player2= random.choice(list(elements.items()))[0]
print(player1.capitalize() + " vs. " + player2.capitalize() + ": " + winner(elements[player1], elements[player2]).capitalize())
|
3c6395629863f3426d2aa0ec298dae066cd7f798 | mohitarya/python | /assignments/day2/Q2_list.py | 475 | 4.21875 | 4 | """ Day2, Program-2
2) Create a simple list. Can you add integers and
strings in the same string? Show with example.
"""
#Simple List
test_list = [1, 'Hello', 2, 'world']
print "List is::\n\t{0}".format(test_list)
#Addition element in a list
test_list.insert(2, 23)
print "List after insertion at position 2 is::\n\t{0}".format(test_list)
#Remove an item from the list
test_list.remove(23)
print "List after removing an element ::\n\t{0}".format(test_list)
|
6bf843837ab813bfbd2c2cbdbb3a82976a1ab91d | illu12/Company-Analysis-Overviewing-Software | /SA.py | 1,478 | 3.546875 | 4 | #############################
#// Stock Analysis Module //#
#############################
def EPS(a,b):
"""Netincome-dividends/outstanding shares"""
""" profit / shares """
return a/b
def absolutePE(a,b):
""" P/E of current stock price """
""" Price/earnings """
return a/b
def relativePE():
""" P/E of a stock price over a longer period """
return 1
def ROE():
""" Return on Equity """
""" Netincome/shareholders equity """
return a/b
def ROA():
""" Return on Assets """
""" Netincome/total assets """
return a/b
def ROI():
""" Return on Investment """
""" Gains-costs/costs """
return (a-b)/b
def beta():
""" The volatile level of the stock, relatively to the average market stock """
""" b < 1, less volatile than market average stocks """
""" b = 1, equally volatile than market average stocks """
""" b > 1, more volatile than market average stocks """
return 1
def marketCap(a,b):
""" Market valuation of a company """
""" Stock price*outstanding stocks """
return a*b
def intrinsicValue(a,b):
""" Theoretical value of a stock """
""" Equity/total stocks """
return a/b
def Delta(a,b):
""" Difference in market price vs. intrinsic value """
return b-a
"""
ROA - https://www.investopedia.com/terms/r/returnonassets.asp
ROE - https://www.investopedia.com/terms/r/returnonequity.asp
ROI - https://www.investopedia.com/terms/r/returnoninvestment.asp
"""
|
d28c9ae4725f8d918163b7e893f9e3a13521978c | jsapatos/hehexD | /intercambio.py | 257 | 4.15625 | 4 | #Programa para intercambiar dos variables sin una tercera
print "Escribe tu numero"
A = int(raw_input())
print "Escribe tu segundo numero"
B = int(raw_input())
A=A+B
B=A-B
A=A-B
print "El primer numero es:"
print A
print "El segundo numero es:"
print B
|
604dd25d09169ec7ac65c406dcebd193fadb13e7 | lKlausl/Mision-04 | /Triangulos.py | 1,384 | 4.40625 | 4 | #Autor Claudio Mayoral García
#Descripción Dice que tipo de triángulo es dependiendo de los valores que se les asignen a los lados
#Y si no cumple con las características del triángulo manda un mensaje de error
#Esta función regresa el tipo de triángulo que es pero si no es un triángulo regresa un anuncio de error
def esTriangulo(numero, numero2, numero3):
if numero <= 0 or numero2 <= 0 or numero3 <= 0:
return "El triángulo no existe"
if (numero + numero2) <= numero3 or (numero + numero3) <= numero2 or (numero3 + numero2) <= numero:
return "El triángulo no existe"
elif numero**2 + numero2**2 == numero3**2 or numero**2 + numero3**2 == numero2**2 or numero2**2 + numero3**2 == numero**2:
return "Es un triángulo rectangulo"
elif numero == numero2 == numero3:
return "Es un triángulo equilatero"
elif numero == numero2 or numero ==numero3 or numero2 == numero3:
return "Es un triángulo isóceles"
else:
return "Es un triángulo escaleno"
#Función principal, pide valores de los lados del triángulo y manda a imprimir que tipo de triángulo es o si no existe
def main():
numero = int(input("Número: "))
numero2 = int(input("Número: "))
numero3 = int(input("Numero: "))
tipoTriangulo= esTriangulo(numero, numero2, numero3)
print(tipoTriangulo)
#Llama a la función principal
main()
|
ebc30654bc52c95e281fe19cc0a283f1ef5e0f79 | vincent507cpu/Comprehensive-Algorithm-Solution | /LintCode/ladder 06 DFS/旧/816. Traveling Salesman Problem/solution_2.py | 1,792 | 3.859375 | 4 | # brutal DFS + pruning
class Result:
def __init__(self):
self.min_cost = float('inf')
class Solution:
"""
@param n: an integer,denote the number of cities
@param roads: a list of three-tuples,denote the road between cities
@return: return the minimum cost to travel all cities
"""
def minCost(self, n, roads):
# Write your code here
graph = self.construcGraph(roads, n)
result = Result()
self.dfs(1, n, [1], set([1]), 0, graph, result)
return result.min_cost
def construcGraph(self, roads, n):
graph = {
i : {j: float('inf') for j in range(1, n + 1)} \
for i in range(1, n + 1)
}
for a, b, c in roads:
graph[a][b] = min(graph[a][b], c)
graph[b][a] = min(graph[b][a], c)
return graph
def dfs(self, city, n, path, visited, cost, graph, result):
if len(visited) == n:
result.min_cost = min(result.min_cost, cost)
return
for next_city in graph[city]:
if next_city in visited:
continue
if self.has_better_path(graph, path, next_city):
continue
visited.add(next_city)
path.append(next_city)
self.dfs(next_city, n, path, visited, cost + graph[city][next_city], graph, result)
visited.remove(next_city)
path.pop()
def has_better_path(self, graph, path, city):
for i in range(1, len(path)):
if graph[path[i - 1]][path[i]] + graph[path[-1]][city] > \
graph[path[i - 1]][path[-1]] + graph[path[i]][city]:
return True
return False |
ee842214ffef0bddb45d451c2ef2073d652cef03 | xiesongzhang/learn-python-the-hard-way | /ex21sd.py | 476 | 3.640625 | 4 | def sd1(X):
print "i get %r" % X
return 5
print sd1(raw_input(">"))
#a = 30
#b = 5
#c = 78
#d = 4
#e = 90
#f = 2
#i = 100
#j = 2
#print "the puzzle is? %d" % (a+b+(c-d-i/j/2*e*f))
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print subtract(add(24,divide(34,100)),1023)
|
15a925618fab77bb279a7bef349e631f8ecfac04 | vietanhtran2710/projectEuler | /highlyDivisibleTriangularNumber.py | 588 | 3.84375 | 4 | from math import sqrt
from collections import Counter
def isPrime(value):
for i in range(2, int(sqrt(value))):
if value % i == 0:
return False
return True
def getPrimeFactorList(value):
result = []
prime = 2
while (value != 1):
while not isPrime(prime) or value % prime != 0:
prime += 1
result.append(prime)
value //= prime
return result
num = 1
value = 2
while True:
num += value
value += 1
lst = getPrimeFactorList(num)
dct = Counter(lst)
factorCount = 1
for val in dct.values():
factorCount *= (val + 1)
if factorCount + 1 >= 500:
print(num)
break
|
91d57d3e18d6e8a580e824270e77fdd60d727a1d | noahsafeer/RobinHoodTradingBot | /venv/Lib/site-packages/int_date/__init__.py | 4,542 | 3.609375 | 4 | from datetime import datetime, timedelta, date
from dateutil import rrule
import six
__author__ = 'Cedric Zhuang'
def _from_str(date_str, format_str=None):
if format_str is None:
format_str = "%Y%m%d"
try:
ret = datetime.strptime(date_str, format_str).date()
except ValueError:
raise ValueError("input is not a valid date: {}".format(date_str))
return ret
def get_date_from_int(int_date):
"""Convert a ``int`` date to a :class:`datetime` instance
:param int_date: int number which represents a date
:return: datetime instance of the date
"""
date_str = "%s" % int(int_date)
return _from_str(date_str)
def get_int_day_interval(int_left, int_right):
"""get interval (in day) between two int dates
:param int_left: first int date
:param int_right: second int date
:return: difference (in day), negative if second date is earlier
than the first one.
"""
left_date = get_date_from_int(int_left)
right_date = get_date_from_int(int_right)
delta = right_date - left_date
return delta.days
def get_workdays(int_left, int_right):
"""get the number of business days between two int dates.
:param int_left: first int date
:param int_right: second int date
:return: business days, negative if second date is earlier
than the first one.
"""
reverse = False
if int_left > int_right:
reverse = True
int_left, int_right = int_right, int_left
date_start_obj = to_date(int_left)
date_end_obj = to_date(int_right)
weekdays = rrule.rrule(rrule.DAILY, byweekday=range(0, 5),
dtstart=date_start_obj, until=date_end_obj)
weekdays = len(list(weekdays))
if reverse:
weekdays = -weekdays
return weekdays
def get_date_from_diff(i_date, delta_day):
"""calculate new int date with a start date and a diff (in days)
:param i_date: the starting date
:param delta_day: diff (in days), negative means past
:return: result date
"""
d = get_date_from_int(i_date)
d += timedelta(delta_day)
return to_int_date(d)
def to_int_date(the_day):
"""Convert a datetime object or a str/unicode to a int date
A int str could be one of the following format:
2015-01-30
2015/01/30
:param the_day: datetime,date instance or string
:exception: ValueError if input could not be converted
:return: int date
"""
if the_day is None:
ret = None
else:
if isinstance(the_day, six.string_types):
the_day = _convert_date(the_day)
if isinstance(the_day, datetime) or isinstance(the_day, date):
ret = the_day.year * 10000 + the_day.month * 100 + the_day.day
elif isinstance(the_day, six.integer_types):
ret = the_day
else:
raise ValueError("input should be a datetime/"
"date/str/unicode instance.")
return ret
def to_date(int_day):
day = int_day % 100
month = (int_day % 10000 - day) / 100
year = int_day / 10000
return date(int(year), int(month), int(day))
def today():
"""Get the today of int date
:return: int date of today
"""
the_day = date.today()
return to_int_date(the_day)
def _convert_date(date_str):
"""convert a *date_str* to int date
convert string '2015-01-30' to int 20150130
convert string '2015/01/30' to int 20150130
:return: int format of date
"""
ret = None
if '-' in date_str:
ret = _from_str(date_str, "%Y-%m-%d")
elif '/' in date_str:
ret = _from_str(date_str, "%Y/%m/%d")
return ret
def in_year(day, *years):
"""check if day is in years list or year
:param day: date
:param years: list of years or year
:return: true if in, otherwise false
"""
year = int(day / 1e4)
return _in_range_or_equal(year, years)
def in_month(day, *months):
"""check if day is in months list or month
:param day: date
:param months: list of months or month
:return: true if in, otherwise false
"""
month = int(day % 10000 / 100)
return _in_range_or_equal(month, months)
def in_date(day, *dates):
"""check if day is in dates list or date
:param day: date
:param dates: list of dates or date
:return: true if in, otherwise false
"""
the_date = int(day % 100)
return _in_range_or_equal(the_date, dates)
def _in_range_or_equal(value, to_compare):
return value in to_compare
|
553ff70553e087e7326d4d29d5a19a5e05d944fa | GuglielmoS/ProjectEuler | /euler2.py | 730 | 3.890625 | 4 | #!/usr/bin/python
# Each new term in the Fibonacci sequence is generated by adding the previous
# two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not
# exceed four million, find the sum of the even-valued terms.
from util import chronometer
from util import fibonacci_generator
@chronometer
def problem_2():
total_sum = 0
f = fibonacci_generator()
exceed_four_million = False
while not exceed_four_million:
next_number = f.next()
if next_number > 4000000:
exceed_four_million = True
else:
if next_number % 2 != 0:
total_sum += next_number
return total_sum
print problem_2() |
fce119d92ece4618ac3ea01bcdde49c7b5efb6b8 | greenstripes4/CodeWars | /sortbyheight.py | 969 | 4.0625 | 4 | """
Task
Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
[-1, 150, 160, 170, -1, -1, 180, 190].
Input/Output
[input] integer array a
If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position.
Constraints:
5 ≤ a.length ≤ 30,
-1 ≤ a[i] ≤ 200.
[output] an integer array
Sorted array a with all the trees untouched.
"""
def sort_by_height(a):
lst = []
newlst = []
for i in range(len(a)):
if a[i] == -1:
lst.append(i)
else:
newlst.append(a[i])
newlst = sorted(newlst)
for i in lst:
newlst.insert(i,-1)
return newlst
print(sort_by_height([-1, 150, 190, 170, -1, -1, 160, 180]))
|
9e03b1f747e464b5eeeb6ed1e859e4f4ffb8de9f | zhaochuanshen/leetcode | /Anagrams.py | 459 | 3.96875 | 4 | '''
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
'''
class Solution:
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
c = {}
for s in strs:
try:
c[tuple(sorted(s))] += 1
except:
c[tuple(sorted(s))] = 1
return filter(lambda x: c[tuple(sorted(x))] > 1, strs)
|
4d1ef9cad395379a5744ed311358982b2b8a0ccd | nishio/atcoder | /hhkb2020/a.py | 80 | 3.671875 | 4 | S = input().strip()
T = input().strip()
if S == "Y":
T = T.upper()
print(T)
|
7b7a0216d9f3452f53b98ef49c9bb640d650154e | edgarshmavonyan/python_text_generator | /markov_chain/vertex.py | 1,547 | 3.890625 | 4 | """Implementation of vertex of markov chain"""
import numpy as np
from collections import defaultdict
class MarkovVertex:
"""A vertex of a markov chain"""
def __init__(self, current_word):
"""Constructor
:param current_word: str
The word, which is represented by this vertex"""
self.__word = current_word
self.__regime = False
self.__next_words = list()
self.__probabilities = list()
self.__next_words_dict = defaultdict(int)
def __str__(self):
"""Convenient output
:return: current state in string"""
return self.__word
def add_word(self, word: str):
"""Add next word to vertex
:param word: str
A word, which occured after current in text"""
if self.__regime:
raise BaseException
self.__next_words_dict[word] += 1
def lock(self):
"""Lock vertex to calculate probabilities"""
self.__regime = True
self.__next_words = list(self.__next_words_dict.keys())
total = sum(self.__next_words_dict.values())
self.__probabilities = \
[x / total for x in self.__next_words_dict.values()]
del self.__next_words_dict
del total
def get_next(self):
"""A method to get next state of chain randomly
:return: chosen randomly next state of a chain in string"""
if len(self.__next_words) == 0:
return None
return np.random.choice(self.__next_words, p=self.__probabilities)
|
a8862a6e03a312b26a84606c145f859728e89069 | sharmaji27/Leetcode-Problems | /977. Squares of a Sorted Array.py | 814 | 3.9375 | 4 | '''
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
'''
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
answer = [0] * len(A)
l, r = 0, len(A) - 1
while l <= r:
left, right = abs(A[l]), abs(A[r])
if left > right:
answer[r - l] = left * left
l += 1
else:
answer[r - l] = right * right
r -= 1
return( answer) |
86044ac162a15b9bf7b04cf43363e96a7e9ae626 | ngpark7/deeplink_public | /1.DeepLearning/01.Multiple_Neurons/or_gate_linear_two_neurons.py | 1,556 | 3.671875 | 4 | from __future__ import print_function
import numpy as np
import random
class Neuron1:
def __init__(self):
self.w1 = np.array([random.random(), random.random()]) # weight of one input
self.b1 = random.random() # bias
print("Neuron1 - Initial w1: {0}, b1: {1}".format(self.w1, self.b1))
def u1(self, input):
return np.dot(self.w1, input) + self.b1
def f(self, u1):
return max(0.0, u1)
def z1(self, input):
u1 = self.u1(input)
return self.f(u1)
class Neuron2:
def __init__(self, n1):
self.w2 = random.random() # weight of one input
self.b2 = random.random() # bias
self.n1 = n1
print("Neuron2 - Initial w2: {0}, b2: {1}".format(self.w2, self.b2))
def u2(self, input):
z1 = self.n1.z1(input)
return self.w2 * z1 + self.b2
def f(self, u2):
return max(0.0, u2)
def z2(self, input):
u2 = self.u2(input)
return self.f(u2)
class Data:
def __init__(self):
self.training_input_value = np.array([(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)])
self.training_z_target = np.array([0.0, 1.0, 1.0, 1.0])
self.numTrainData = len(self.training_input_value)
if __name__ == '__main__':
n1 = Neuron1()
n2 = Neuron2(n1)
d = Data()
for idx in xrange(d.numTrainData):
input = d.training_input_value[idx]
z2 = n2.z2(input)
z_target = d.training_z_target[idx]
print("x: {0}, z2: {1}, z_target: {2}".format(input, z2, z_target)) |
ad223210ee8796e0b09e49af9a10fa0453d6b711 | Gnanender-reddy/python_program | /DataStructures/Utility1.py | 5,632 | 4.09375 | 4 | """
@Author : P.Gnanender Reddy
@Since : Dec'2019
@Description:This code consists all utilities.
"""
#functions for stack
#creating stack(LIFO manner) class
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
#=======================================================================================================================
#creating code for Queue
class Queue:
def __init__(self):
self.items = []
#This function is for checking for empty
def isEmpty(self):
return self.items == []
#This fucntion is for adding value
def enqueue(self, item):
self.items.insert(0,item)
#This function is for removing value
def dequeue(self):
return self.items.pop()
#This function is for determining size
def size(self):
return len(self.items)
#=======================================================================================================================
# FOR UNORDERED AND ORDERED*******************************************************************************
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList: #creating the class to write all functions which are releated to the linked list
def __init__(self): # constructor of linked list
self.head = None # initially head is initialized with default value
# It adds the node with given data at the end of the list
def add_element(self, data): # this function is used to add the elements any whrere
new_node = Node(data)# creating the node object
if self.head is None: # when head is empty then new node added to head
self.head = new_node
else: # when node is not empty lopp will search until the empty nodes comes
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
return
def display(self): # this function is used to diaplay the data
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
def search(self, x):
# Initialize current to head
current = self.head
# loop till current not equal to None
while current != None:
if current.data == x:
return True # data found
current = current.next
return False # Data Not found
# It inserts data with given node at particular location
# def insert(self, position, data):
# new_node = Node(data)
# new_node.next = position.next
# position.next = new_node
# Delete node with given data
def remove(self, key): # this functionis used to remove the data in all places using data
cur_node = self.head
previous = None
# Traverse through the list
while cur_node.data != key:
previous = cur_node
cur_node = cur_node.next
print(f"Removing {key} from Linkedlist.")
if previous == None:
self.head = cur_node.next
else:
previous.next = cur_node.next
# Count number nodes in linked list
def size(self): # this function is used to find the size of the list
x = 0
temp = self.head
while temp:
x = x + 1
temp = temp.next
print("size of the list is",x)
return x
#=======================================================================================================================
#code for deque
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0,item)
def removeFront(self):
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
#=================================================================================================================#
# Code : Binaryv search tree
# A function to find factorial of a given number
def factorial(n):
res = 1
# Calculate value of [1*(2)*---*
# (n-k+1)] / [k*(k-1)*---*1]
for i in range(1, n + 1):
res *= i
return res
def binomialCoeff(n, k):
res = 1
# Since C(n, k) = C(n, n-k)
if (k > n - k):
k = n - k
# Calculate value of [n*(n-1)*---*(n-k+1)] /
# [k*(k-1)*---*1]
for i in range(k):
res *= (n - i)
res //= (i + 1)
return res
# A Binomial coefficient based function to
# find nth catalan number in O(n) time
def catalan(n):
# Calculate value of 2nCn
c = binomialCoeff(2 * n, n)
# return 2nCn/(n+1)
return c // (n + 1)
# A function to count number of BST
# with n nodes using catalan
def countBST(n):
# find nth catalan number
count = catalan(n)
# return nth catalan number
return count
# A function to count number of binary
# trees with n nodes
def countBT(n):
# find count of BST with n numbers
count = catalan(n)
# return count * n!
return count * factorial(n)
#======================================================================================================================
|
bf7ad0a9b488ffa7f9b2abcc9ee583fdfb52cf9c | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/ceaser_cypher_encryption.py | 324 | 3.75 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet = list(alphabet)
n = input("Enter the sentence to be encrypted ").lower().split(" ")
s = int(input("Enter the number to be shifted by "))
shifted_alphabet = alphabet[s:] + alphabet[:s]
coded = [shifted_alphabet[alphabet.index(j)] for i in n for j in i]
print("".join(coded))
|
14b3a2b56fd797479fd7b046e6fae9b64d35d11a | gmsviderski/python | /lesson_1_1.py | 697 | 4.25 | 4 | """
1. Поработайте с переменными, создайте несколько, выведите на экран, запросите
у пользователя несколько чисел и строк и сохраните в переменные, выведите на
экран.
"""
var_int = 777
var_str = 'Привет, мир!'
var_bool = True
print('Целое число =', var_int)
print('Строка =', var_str)
print('Переменная bool =', var_bool)
var_str_in = input('Как тебя зовут? ')
print('Привет,', var_str_in)
var_int_in = input('Сколько тебе лет? ')
print(f'Ух ты, {var_str_in}, тебе уже {var_int_in} !')
|
00ef18a9e14358571919232233c25dbbd4413a43 | sdamico23/Rosalind | /fibonacci_sequence.py | 222 | 3.671875 | 4 | def fib(n):
if n == 0:
return 0
terms = []
terms.append(0)
terms.append(1)
for i in range(2, n+1):
terms.append(terms[i-1] + terms[i-2])
return terms[n]
print(fib(22))
|
6290e1419cf760476e48960d389f097ed8388d45 | castorfou/mit_600.2x | /lectures/UNIT 3 - Lecture 8 - Monte Carlo Simulations/asset-v1 MITx+6.00.2x+3T2020+type@asset+block@lecture8-segment3/exercise 4.py | 1,550 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 15:33:47 2020
@author: explore
"""
import random
import numpy as np
def drawBalls():
'''
You have a bucket with 3 red balls and 3 green balls.
Assume that once you draw a ball out of the bucket, you don't replace it.
Return a list of 3 balls: [0, 1, 0]
0: red, 1: green
'''
bucket = [0,0,0,1,1,1]
result=[]
for i in range(3):
# print('tirage '+str(i)+' from bucket ', bucket)
tirage = random.choice(bucket)
result.append(tirage)
bucket.remove(tirage)
# print('tirage '+str(i)+' result ', result)
return result
def sameColor(tirage):
if (np.std(tirage) ==0):
return True
return False
def sameColor2(tirage):
somme=0
for i in range(len(tirage)):
somme+=tirage[i]
if ( (somme ==0) | (somme==3)):
return True
return False
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
# Your code here
estimates = 0
for t in range(numTrials):
result_tirage = np.array(drawBalls())
if (sameColor2(result_tirage)):
estimates +=1
return estimates/numTrials
print(drawBalls())
print(noReplacementSimulation(10000)) |
07a98d68b565e9bb91911bba2883692db6463b28 | Hu-Wenchao/leetcode | /prob122_best_time_buy_sell_stock2.py | 1,261 | 3.796875 | 4 | """
Say you have an array for which the ith element is
the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
(ie, buy one and sell one share of the stock
multiple times). However, you may not engage
in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit = 0
for i in xrange(1, len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i] - prices[i-1]
return profit
def maxProfit2(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
low = prices[0]
profit = 0
for i in range(1, len(prices)):
if prices[i] >= prices[i-1]:
continue
elif prices[i] < prices[i-1]:
profit += prices[i-1] - low
low = prices[i]
if prices[-1] > low:
profit += prices[-1] - low
return profit
|
36db4feab82f7372eb90f964f7dd9995bb79331b | Daniel-Wuthnow/python_nov_2017 | /Daniel_Wuthnow/Python_fundamentals/string_lists.py | 937 | 4.28125 | 4 | # words = "It's thanksgiving day. It's my birthday,too!"
# print words.find("day")
# #.replaces(what i am replacing, what will be replacing the first index)
# print words.replace("day", "month")
# x = [1,324,6,3,-8,6]
# #min and max are called and in the () is what is looked through to find the value wanted
# print min(x)
# print max(x)
# x = ["hello",2,54,-2,7,12,98,"world"]
# #prints the first index of x
# print x[0]
# #prints the last value of x. x[-2] would be the second to last index
# print x[-1]
# #makes array with the first value in the first index and the last value into the seconed index
# z = [x[0],x[-1]]
# print z
arr = [19,2,54,-2,7,12,98,32,10,-3,6]
arr = sorted(arr)
print arr
#the second half of the arr
arr2 = arr[len(arr)/2:]
#the first half of the arr
arr3 = arr[:len(arr)/2]
print arr2
print arr3
#in arr2 this function inserts arr3 into index 0 sliding over the other index
arr2.insert(0,arr3)
print arr2
|
a080cbe846b86d10383ef367c2b672e393f52b19 | Awonkhrais/data-structures-and-algorithms | /python/code_challenges/stack-queue-brackets/stack_queue_brackets/bracket.py | 607 | 3.875 | 4 | open_list = ['(','[','{']
close_list = [')',']','}']
def validate_brackets(input):
char_list=[]
for i in input:
if i in open_list:
char_list.append(i)
elif i in close_list:
x = close_list.index(i)
if ((len(char_list) > 0) and (open_list[x] == char_list[len(char_list) - 1])):
char_list.pop()
else:
return False
if len(char_list) == 0:
return True
else:
return False
result=validate_brackets('(){[]}')
print(result)
result1=validate_brackets('[{})')
print(result1)
|
00556813af1268d8a67a49cf645faaa236dc84e4 | avivkiss/cs107-w16 | /block_ciphers/exercise_2.py | 2,377 | 3.734375 | 4 | from crypto.primitives import *
from crypto.tools import *
from crypto.ideal.block_cipher import *
import sys, itertools
"""
Let E be a blockcipher E:{0, 1}^8 x {0, 1}^8 --> {0, 1}^8
Define F: {0, 1}^16 x {0, 1}^16 --> {0, 1}^16 by:
Notes:
Derived from lecture 3 slide 40.
Sizes in comments are bits, sizes in code are in bytes (bits * 8).
"""
# Block & key size in bytes.
block_len, key_len = 2, 2
E = BlockCipher(key_len/2, block_len/2)
def F(k, x):
"""
Blockcipher F made by composition with smaller function E.
:param k: cipher key
:param x: plaintext messager
:return: cipher text
"""
k1, k2 = split(k)
x1, x2 = split(x)
y1 = E.decrypt(k1, xor_strings(x1, x2))
y2 = E.encrypt(k2, bitwise_complement_string(x2))
return y1 + y2
"""
1. [30 points] Prove that F is a blockcipher by giving an efficiently computable
inverse F_I:
"""
def F_I(k, c):
"""
Fill this in, this is the inverse of F.
:param k: cipher key
:param c: cipher text
:return: plain text
"""
return None
"""
2. [20 points] What is the running time of a 4-query exhaustive key-search
attack on F?
--&--
[Answer here].
"""
"""
3. [50 points] Give a 4-query key-recovery attack in the form of an adversary A
specified in code, achieving Adv(kr, F, A) = 1 and having running time
O(2^(8) * T_{E}) (T_{E} is the running time of the encryption function E),
where the big-oh hides some small constant.
"""
def A(fn):
"""
You must fill in this method. This is the adversary that the problem is
asking for.
:param fn: This is the oracle supplied by GameKR, you can call this
oracle to get an "encryption" of the data you pass into it.
:return: return the a string that represents a key guess.
"""
pass
from crypto.games.game_kr import GameKR
from crypto.simulator.kr_sim import KRSim
if __name__ == '__main__':
g = GameKR(F, key_len, block_len)
s = KRSim(g, A)
key = random_string(key_len)
for j in range(100):
message = random_string(block_len)
cypher = F(key, message)
if message != F_I(key, cypher):
print "Your Decryption function is incorrect."
sys.exit()
print "Your Decryption function appears correct."
print "The advantage of your adversary is ~" + str(s.compute_advantage(20))
|
3f965f3781356270b5b379455e7e22f34ff12d9c | OlyaVT/ClassWork | /CW_12.py | 601 | 4.1875 | 4 | # use map metod
names = ['Sam', 'Don', 'Daniel']
names = map(hash,names)
print(list(names))
# find colour red
colors = ['red', 'green', 'black', 'red', 'brown', 'red', 'blue', 'red', 'red', 'yellow']
def is_red(str):
return str == 'red'
new_colors = filter(is_red,colors)
print(list(new_colors))
# use append and map
str_list = ['1','2','3','4','5','7']
num = []
for i in str_list:
num.append(int(i))
num_list = map(int,str_list)
print(num)
# use map to change km to miles
f = lambda x: round(x * 1.6, 2)
miles = [1,2,3]
km = map(f,miles)
print(list(km)) |
f855924b36ae2117cea75ffa1aac126ba15b4e6c | agvaress/algorithms | /recursion/sum_array.py | 271 | 3.796875 | 4 | def array_sum(arr):
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
return arr[0] + array_sum(arr[1:])
print(array_sum([3, 4, 5, 6]))
def len_array(arr):
if len(arr) == 1:
return 1
return 1 + len_array(arr[1:]) |
be505e83b2f651329b84d44e5b6b04b8ff43a2e3 | RickCarletti/P1---Dante | /URIs/1021.py | 736 | 3.53125 | 4 | def AchaNotas(val, listaA, listaB):
retorno = []
for i in listaA:
notas = val // i
retorno.append(notas)
val -= notas*i
for i in listaB:
notas = val // i
retorno.append(notas)
val -= notas * i
# print(round(val, 4))
return retorno
listaDeNotas = [100, 50, 20, 10, 5, 2]
listaDeMoedas = [1, 0.50, 0.25, 0.10, 0.05, 0.01]
entrada = 576.73 # float(input())
resultado = AchaNotas(entrada, listaDeNotas, listaDeMoedas)
tipo = 'nota(s)'
print('NOTAS:')
for index, tupla in enumerate(zip(resultado, list(listaDeNotas + listaDeMoedas))):
if index == 6:
tipo = 'moeda(s)'
print('MOEDAS:')
print(int(tupla[0]), tipo + ' de R$ %.2f' % tupla[1])
|
7e3c7519238dc6622e58ebe9c9643856bd01308e | gy-chen/gyjukebox | /gyjukebox/lyrics/nlp/utils.py | 496 | 3.671875 | 4 | def ngrams(sequence, n):
"""ngrams
Args:
sequence (iterable)
n (int)
Returns:
yield ngrams result
"""
# implementation from nltk
sequence = iter(sequence)
history = []
for _ in range(n - 1):
try:
next_item = next(sequence)
except StopIteration:
return
history.append(next_item)
for item in sequence:
history.append(item)
yield from tuple(history)
del history[0]
|
4bf74cd87ee89e7a29683ba7c1e8f1c977e8340f | NathanNNguyen/challenges | /dynamic_programming/words_sorted_according.py | 901 | 3.640625 | 4 | def isAlienSorted(Words, Order):
Order_index = {c: i for i, c in enumerate(Order)}
# c = {}
# for index, val in enumerate(Order):
# c[index] = val
for i in range(len(Words) - 1):
word1 = Words[i]
word2 = Words[i + 1]
# Find the first difference word1[k] != word2[k].
for k in range(min(len(word1), len(word2))):
# If they compare false then it's not sorted.
if word1[k] != word2[k]:
if Order_index[word1[k]] > Order_index[word2[k]]:
return False
break
else:
# If we didn't find a first difference, the
# Words are like ("add", "addition").
if len(word1) > len(word2):
return False
return True
words = ["zyx", "zyxw", "zyxwy"]
order = "zyxwvutsrqponmlkjihgfedcba"
print(isAlienSorted(words, order))
|
e9b822127040ffcbe6718e31d232ce9a8f433390 | PeterL64/UCDDataAnalytics | /7_Introduction_To_Data_Visualization_With_Matplotlib/2_Plotting_Time_Series/1_Read_Data_With_A_Time_Index.py | 402 | 3.828125 | 4 | # Read data with a time index
# Import pandas as pd
import pandas as pd
# Read in the data from a CSV file called 'climate_change.csv' using pd.read_csv.
# Use the parse_dates key-word argument to parse the "date" column as dates.
# Use the index_col key-word argument to set the "date" column as the index.
climate_change = pd.read_csv('climate_change.csv', parse_dates=['date'], index_col=['date']) |
f39778517e3d6df0cf76d36ade7556448c1d75cc | Meet953/python | /pyrhon/Crucial Info/Exception Handling/to_handle_mulyiple_exceptions.py | 419 | 3.734375 | 4 | # TO HANDLE MULTIPLE EXCEPTIONS..
try:
f=open("myfile.txt")
line=f.readline()
Int=int(s.strip())
calculated_value=101/Int
except IOError:
print"I/O error occured"
except ValueError:
print"Could not convert data to integer"
except ZeroDivisionError:
print"Zero Division Error"
except:
print"Unexpected Error"
else:
print"YEH!! No Exceptions"
|
24a5cdcaafe2992f198813b15a1a7faeeaaf9180 | soldierloko/Curso-em-Video | /Ex_86.py | 428 | 4.34375 | 4 | #Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos do teclado
#No final mostre a matriz na tela, com a formatação correta
matriz = [[0,0,0],[0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
matriz[l][c] = int(input(f'Digite um Valor para [{l}, {c}]: '))
print('-=' *30)
for l in range(0,3):
for c in range(0,3):
print(f'[{matriz[l][c]}]', end='')
print() |
8fb36c9231b48cf3b9ab77b43394d85f3830c08d | LidaRevtova/project4 | /project4.py | 1,904 | 3.96875 | 4 | # У пользователя есть дв варианта, ак зашифровать текст, он сам
# выбирает код и вводит текст
print('Выберите, каким кодом вы хотите зашифровать свой текст: '
'1 - код цезаря, 2 - код выводит текст в обратном порядке'
'')
choice = int(input())
if choice == 1:
ALPH = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и',
'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т',
'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь',
'э', 'ю', 'я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё',
'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п',
'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
'ъ', 'ы', 'ь', 'э', 'ю', 'я']
text = str.lower(input("Введите текст, который вы хотите перевести: "))
offset = int(input("Введите число, на значение которого вы "
"хотите сдвигать текст от 1 до 32: "))
while offset < 1 or offset > 32:
offset = int(input("Ошибка. Введите число, на значение "
"которого вы хотите сдвигать текст от"
" 1 до 32: "))
n = text.count(' ') + 1
print(n)
for i in text:
if i not in ALPH:
word = i
print(word,end="")
else:
word = ALPH[ALPH.index(i) + offset]
print(word.capitalize(), end="")
elif choice == 2:
text = str.lower(input("Введите текст, который вы хотите перевести: "))
print(text[::-1]) |
93b4d6ab8f947ef70c234fa08cf30b348b835424 | Yasin-4030/Assignment-1--Music-Playlist | /Playlist.py | 2,172 | 4.0625 | 4 | from Song import Song
class Playlist: #this class is a linked list
def __init__(self):
self.__first_song = None
# TODO: Create a method called add_song that creates a Song object and adds it to the playlist. This method has one parameter called title.
def add_song(self, title):
node = self.__first_song
if not node: # if no song (node) at all, then ...
self.__first_song = Song(title)
else: # if there is already a node (song)
while node:
if node.get_next_song() == None:
newNode = Song(title)
node.set_next_song(newNode)
break
node = node.get_next_song()
# TODO: Create a method called find_song that searches for whether a song exits in the playlist and returns its index.
# The method has one parameters, title, which is the title of the song to be searched for. If the song is found, return its index. Otherwise, return -1.
def find_song(self, title):
node = self.__first_song
count = 0
while node:
if count == title:
return node.get_title
count += 1
node = node.set_next_song
assert(False)
return -1
# TODO: Create a method called remove_song that removes a song from the playlist. This method takes one parameter, title, which is the song that should be removed.
def remove_song(self, title):
node = self.__first_song
while node:
if node.get_title == title:
node = node.get_next_song()
# TODO: Create a method called length, which returns the number of songs in the playlist.
def length(self):
if not self.__first_song:
return 0
node = self.__first_song
counter = 1
while node:
node = node.get_next_song()
if node:
counter += 1
return counter
# TODO: Create a method called print_songs that prints a numbered list of the songs in the playlist.
# Example:
# 1. Song Title 1
# 2. Song Title 2
# 3. Song Title 3
def print_songs(self):
node = self.__first_song
counter = 0
while node:
counter += 1
print(str(counter) + '.', node.get_title())
node = node.get_next_song() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.