blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fce68e45db6a71d3c66ca086addf06afde31d901 | AlGaRitm2020/Algorithms_training_Young_Yandex | /1_Complexity_and_testing_and_special cases/D_equation_with_ the_root.py | 744 | 3.84375 | 4 | a, b, c = (int(input()) for _ in range(3))
# 0 0 0 +
# 0 0 1 +
# 0 1 0
# 0 1 1
# 1 0 0
# 1 0 1
# 1 1 0
# 1 1 1
if c < 0:
print('NO SOLUTION')
elif c == 0:
if b == 0:
if a == 0:
print('MANY SOLUTIONS')
else:
print(0)
elif a == 0:
print('NO SOLUTION')
else:
result = (- b) / a
if int(result) == result:
print(int(result))
else:
print('NO SOLUTION')
else:
if a == 0:
if b == c ** 2:
print('MANY SOLUTIONS')
else:
print('NO SOLUTION')
else:
result = (c ** 2 - b) / a
if int(result) == result:
print(int(result))
else:
print('NO SOLUTION') |
ba70e435756d4e2247eb1e14026607b1cc8a23db | icescrub/code-abbey | /rotate_string.py | 677 | 3.546875 | 4 | def f():
with open('C:\\Users\\Duchess\\Desktop\\Data.txt') as data:
for line in data:
rot, word = line.split()
rot = int(rot)
lst = [c for c in word] # Manipulate string as list, which is easier.
if rot < 0:
lst.reverse()
rotateString(rot,lst)
lst.reverse()
else:
rotateString(rot,lst)
rStr = ''.join(lst)
print(rStr)
def rotateString(rot,lst): # Append first char to end, then delete first char.
for i in range(abs(rot)):
lst.append(lst[0])
del(lst[0])
|
66c9d91f52170d473f6a252b9cd30520e9b39096 | WokLibCodeClub/Rock-Paper-Scissors-with-Turtles | /Template/step1-3.py | 2,143 | 3.640625 | 4 | from turtle import *
from random import randint
from time import sleep
from sys import exit
#############################################
# VARIABLES
#############################################
screen = Screen()
setup(800,700)
screen.register_shape("computer_rock.gif")
screen.register_shape("computer_paper.gif")
screen.register_shape("computer_scissors.gif")
screen.register_shape("you_rock.gif")
screen.register_shape("you_paper.gif")
screen.register_shape("you_scissors.gif")
you = Turtle()
computer = Turtle()
background = Turtle()
referee = Turtle()
for i in screen.turtles():
i.hideturtle()
i.penup()
i.speed(0)
you.goto(-150, 20)
computer.goto(150, 20)
you_hands = ["you_rock.gif", "you_paper.gif", "you_scissors.gif"]
computer_hands = ["computer_rock.gif", "computer_paper.gif", "computer_scissors.gif"]
your_choice = -1
#############################################
# FUNCTIONS
#############################################
def get_choice():
global your_choice
rps = "x"
while rps =="x":
rps = screen.textinput("Your choice!", "rock (r), paper (p) or scissors (s)? ")
if rps == "r":
your_choice = 0
elif rps == "p":
your_choice = 1
elif rps == "s":
your_choice = 2
else:
rps = "x"
play_game()
def play_game():
computer_choice = randint(0, 2)
for i in [3, 2, 1]:
referee.color("red")
referee.write(i, font = ("arial", 100, "bold"), align = "center")
sleep(1)
referee.clear()
you.shape(you_hands[your_choice])
computer.shape(computer_hands[computer_choice])
you.showturtle()
computer.showturtle()
def draw_field():
background.goto(-150, 100)
background.color("green")
background.write("You", font = ("arial", 24, "italic"), align = "center")
background.goto(150, 100)
background.color("blue")
background.write("Computer", font = ("arial", 24, "italic"), align = "center")
#############################################
# MAIN CODE
#############################################
draw_field()
get_choice()
|
0931098ba5ba029e28cb1e0237b1141f7ee8f223 | PaulChirlikov/first-repo | /key_value.py | 378 | 3.9375 | 4 | #Написать программу, которая берет словарь и меняет местами ключи и значения
distionary ={'name': 'Channing', 'surname': 'Tatum'}
for key in distionary:
print(key, distionary[key])
new_distionary = {value:key for key, value in distionary.items()}
for key in new_distionary:
print(key, new_distionary[key])
|
223a5c5880ffcde76b908d9c50471262265605cc | wenzhe980406/PythonLearning | /day16/WangShoot.py | 6,133 | 3.515625 | 4 | # _*_ coding : UTF-8 _*_
# 开发人员 : ChangYw
# 开发时间 : 2019/8/5 21:52
# 文件名称 : WangShoot.PY
# 开发工具 : PyCharm
'''
#1. 创建老王对象
#2. 创建一个枪对象
#3. 创建一个弹夹对象
#4. 创建一些子弹
#5. 创建一个敌人
#6. 老王把子弹安装到弹夹中
#7. 老王把弹夹安装到枪中
#8. 老王拿枪
#9. 老王开枪打敌人
#10. 召唤电脑选手
'''
#玩家
import random
clip_num = 30
gun_list = ["M4A1", "AK47", "Kar-98K"]
clip_list = ["5.56mm", "7.62mm"]
class Player:
def __init__(self,name):
self.name = name
self.HP = 100
#拿枪
def get_gun(self,Gun):
print("玩家%s拿到了枪%s"%(self.name,Gun.name))
#开枪
def play_shoot(self,Gun,clip,bullet,enery_list):
if len(enery_list) > 0:
for i in enery_list:
if i.HP <= 0:
print(i.name,"电脑已被击败一个。")
del enery_list[enery_list.index(i)]
else:
print("电脑已全部被击败,游戏结束")
return False
return Gun.shoot(clip,bullet,enery_list)
class Enery:
def __init__(self):
self.name = "电脑选手"
self.HP = 100
# 开枪
def play_shoot(self,bullet,enery_list,player):
if player.HP == 0:
print("您已被击败,游戏结束。")
return False
return Gun.com_shoot(bullet,enery_list,player)
#枪
class Gun:
def __init__(self,name):
self.name = name
#装上弹匣
def gun_shot(self,clip):
self.name = clip.shot()
#老王开枪
def shoot(self,clip,bullet,enery_list):
clip.show_clip(bullet)
bullet.num -= 1
#随机概率命中
hit_rate = random.random()
if self.name == gun_list[0]:
if hit_rate >= 0.3:
clip.show_clip(bullet)
enery_random = random.choice(enery_list)
enery_random.HP -= 35
print("已命中敌人,干的漂亮!")
if len(enery_list) == 0:
return False
return True
else:
if bullet.num == 0 :
print("游戏结束,没能击中敌人!")
return False
print("尚未命中,加油。")
return True
elif self.name == gun_list[1]:
if hit_rate >= 0.5:
clip.show_clip(bullet)
enery_random = random.choice(enery_list)
enery_random.HP -= 45
print("已命中敌人,干的漂亮!")
if len(enery_list) == 0:
return False
return True
else:
if bullet.num == 0 :
print("游戏结束,没能击中敌人!")
return True
print("尚未命中,加油。")
return True
elif self.name == gun_list[2]:
if hit_rate >= 0.5:
clip.show_clip(bullet)
enery_random = random.choice(enery_list)
enery_random.HP -= 100
print("已命中敌人,干的漂亮!")
if len(enery_list) == 0:
return False
return True
else:
if bullet.num == 0 :
print("游戏结束,没能击中敌人!")
return False
print("尚未命中,加油。")
return True
#电脑开枪
def com_shoot(self,bullet,player):
bullet.num -= 1
#随机概率命中
hit_rate = random.random()
if hit_rate >= 0.8 :
player.HP -= 20
print("老王被击中,剩余HP:%s"%player.HP)
#弹匣:快速扩容弹匣
class Clip:
def __init__(self,name):
self.name = name
self.num = clip_num
#装弹
def shot(self,bullet):
print("已装备%s,正在装弹,子弹为%s,数量为:%d"%(self.name,bullet.name,bullet.num))
#查看剩余子弹
def show_clip(self,bullet):
if bullet.num == 0 :
print("子弹消耗完毕,没有完全消灭敌人。")
return False
print("子弹数量剩余:%d" % (bullet.num))
#子弹
class Bullet:
def __init__(self,name,num = 30):
self.name = name
self.num = num
#给弹
def tobullet(self):
if self.name == '7.62mm' :
print("已检测到%s子弹,正在准备装弹%d颗"%(self.name,self.num))
return [self.name * self.num]
#选装备
def equip(choice_list):
for idx, choice in enumerate(choice_list):
print("%s -- %s\n" % (str(idx + 1).ljust(3), choice), end="")
choice_input = input("请选择一把你想要的装备:")
return gun_list[int(choice_input) - 1]
def main():
while True:
wang = Player("老王")
#选枪
gun_choice = equip(gun_list)
gun = Gun(gun_choice)
wang.get_gun(gun)
num = 5 if gun_choice == "Kar-98K" else 30
#选子弹
bullet_choice = equip(clip_list)
bullet = Bullet(bullet_choice,num)
print("已选择%s和子弹%s,自动配备快速扩容弹匣。"%(gun_choice,bullet_choice))
clip = Clip("快速扩容弹匣")
bullet.tobullet()
clip.shot(bullet)
enery1 = Enery()
enery2 = Enery()
enery3 = Enery()
enery4 = Enery()
enery5 = Enery()
enery_list = [enery1 , enery2 , enery3 , enery4 , enery5]
while True:
a = wang.play_shoot(gun, clip, bullet,enery_list)
for i in enery_list:
i.play_shoot(bullet,enery_list,wang)
if not a:
break
if __name__ == '__main__':
main() |
ad950dc7687f1ee46f10dc86b0bd3b1475d0d9e4 | sujin16/studycoding | /level_3/int_triangle.py | 575 | 3.515625 | 4 | def solution(triangle):
for i,tri in enumerate(triangle):
if i ==0:continue
for j in range(len(tri)):
if j ==0:
triangle[i][j] += triangle[i-1][0]
elif j ==len(tri) -1:
triangle[i][j] += triangle[i-1][-1]
elif triangle[i-1][j-1]> triangle[i-1][j]:
triangle[i][j] += triangle[i-1][j-1]
else: triangle[i][j] += triangle[i-1][j]
return max(triangle[-1])
triangle= [[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]
print(solution(triangle)) |
e67454f08fcd0336612388fc96270ce57ea57617 | rechhabra/Cattis | /unlockpattern.py | 409 | 3.515625 | 4 | from decimal import Decimal
pad = [list(map(int, input().split(" "))) for i in range(3)]
def computeD(n):
nx,ny=0,0
dx,dy=0,0
for i in range(3):
for j in range(3):
if pad[i][j]==n:
nx,ny=i,j
elif pad[i][j]==n+1:
dx,dy=i,j
return Decimal(((dx-nx)*(dx-nx)+(dy-ny)*(dy-ny))**0.5)
print(str(Decimal(sum([computeD(i) for i in range(1,9)])).quantize(Decimal('0.00000001'))))
|
c1bcbd7bd8fe85608a3d0289d2429885012189c3 | saurabhchris1/Algorithm-Pratice-Questions-LeetCode | /Remove_Vowels_from_a_String.py | 477 | 3.671875 | 4 | # Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
#
# Example 1:
#
# Input: "leetcodeisacommunityforcoders"
# Output: "ltcdscmmntyfrcdrs"
# Example 2:
#
# Input: "aeiou"
# Output: ""
class Solution:
def removeVowels(self, S):
dict = {'a': 'a', 'e': 'e', 'i': 'i', 'o': 'o', 'u': 'u'}
res = []
for c in S:
if c not in dict:
res.append(c)
return "".join(res)
|
589400a64f393a3517f861913b041fb3df6f4d3e | ayz73/testl | /classes learning/test_fractions_class.py | 2,400 | 3.734375 | 4 | import unittest
from fractions_class import Fraction
import fractions_class
class fractions_class_test(unittest.TestCase):
def test_gcf(self):
self.assertEqual(fractions_class.gcf(78, 66), 6)
self.assertEqual(fractions_class.gcf(10, 0), 0)
self.assertEqual(fractions_class.gcf(-100, -5), -5)
self.assertEqual(fractions_class.gcf(100, -5), -5)
class fractions_test(unittest.TestCase):
def test_fractions_add(self):
f_1 = Fraction(1, 2)
f_2 = Fraction(1, 4)
self.assertEqual(str(f_1 + f_2), "3/4")
f_2.den = 8
self.assertEqual(str(f_1 + f_2), "5/8")
f_3 = Fraction(-1, 2)
f_4 = Fraction(2, -5)
self.assertEqual(str(f_3 + f_4), "-9/10")
def test_fractions_sub(self):
f_1 = Fraction(1, 2)
f_2 = Fraction(1, 4)
self.assertEqual(str(f_1 - f_2), "1/4")
f_2.den = 8
self.assertEqual(str(f_1 - f_2), "3/8")
f_3 = Fraction(-1, 2)
f_4 = Fraction(2, -5)
self.assertEqual(str(f_3 - f_4), "-1/10")
def test_fractions_mul(self):
f_1 = Fraction(1, 2)
f_2 = Fraction(1, 4)
self.assertEqual(str(f_1 * f_2), "1/8")
f_1.num = 5
f_2.den = 8
self.assertEqual(str(f_1 * f_2), "5/16")
f_3 = Fraction(-1, 2)
f_4 = Fraction(2, -5)
self.assertEqual(str(f_3 * f_4), "1/5")
def test_fractions_truediv(self):
f_1 = Fraction(1, 2)
f_2 = Fraction(1, 4)
self.assertEqual(str(f_1 / f_2), "2/1")
f_1.num = 5
f_2.den = 3
self.assertEqual(str(f_1 / f_2), "15/2")
f_3 = Fraction(-1, 2)
f_4 = Fraction(2, -5)
self.assertEqual(str(f_3 / f_4), "5/4")
def test_get_num(self):
f_1 = Fraction(1, 5)
f_2 = Fraction(3, 4)
self.assertEqual(f_1.get_num(), 1)
self.assertEqual(f_2.get_num(), 3)
f_1.num = 2
f_2.num = 5
self.assertEqual(f_1.get_num(), 2)
self.assertEqual(f_2.get_num(), 5)
def test_get_den(self):
f_1 = Fraction(1, 5)
f_2 = Fraction(3, 4)
self.assertEqual(f_1.get_den(), 5)
self.assertEqual(f_2.get_den(), 4)
f_1.den = 6
f_2.den = 5
self.assertEqual(f_1.get_den(), 6)
self.assertEqual(f_2.get_den(), 5)
if __name__ == "__main__":
unittest.main() |
ca532af18a83a578a9d41b71d37d2bf140276f7f | bostonbrad/Codility_Python | /Binary_Gap.py | 1,882 | 4.21875 | 4 | """
Task: BinaryGap
Goal: Find longest sequence of zeros in binary representation of an integer.
Website: https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
-----------------------------------------------------------
A binary gap within a positive integer N is any maximal sequence of
consecutive zeros that is surrounded by ones at both ends in the binary
representation of N.
For example, number 9 has binary representation 1001 and contains a binary
gap of length 2. The number 529 has binary representation 1000010001 and
contains two binary gaps: one of length 4 and one of length 3. The number
20 has binary representation 10100 and contains one binary gap of length 1.
The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
def solution(N)
that, given a positive integer N, returns the length of its longest binary
gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has
binary representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
N is an integer within the range [1..2,147,483,647].
Complexity:
expected worst-case time complexity is O(log(N));
expected worst-case space complexity is O(1).
"""
def solution(N):
binary = "{0:b}".format(N) # get binary format
split_binary = binary.split("1") # Split into groupings
lengths = []
split_binary_lenght = len(split_binary)
if split_binary[split_binary_lenght - 1] != '': # Check if last element is zeros
split_binary = split_binary[:split_binary_lenght-1] # Delete last element if ends in zeros
for element in split_binary:
lengths.append(element.count('0')) # Append the lenght of each element that contains zeros
return max(lengths) # Return the binary gap
|
469dacf6949a53af582464c94a41596b3951351c | AG3X29M4Nc5DJN0-FNkr5MSgiwR4YxBz/course-AI | /assignment2/knowledgeAgent.py | 7,262 | 3.5 | 4 | from logic import *
from utils import *
from exploration import *
#import time to test performance
import time
#A knowledge base for a wumpusWorld
class wumpusKB():
def __init__(self, wumpusWorld):
self.kb = PropKB()
#Add in the KB basic information
#No pit and wumpus at (0,0)
self.kb.tell(expr("~P00"))
self.kb.tell(expr("~W00"))
#Add the rules of the game
#If square x,y is breezy <==> (adjacent are pits)
for i in range(0,4):
for j in range(0,4):
head = ("B"+str(i)+str(j))
p = adjacentRooms(i,j)
body = "("
for room in p:
body += "P"+str(room[0])+str(room[1])+" | "
body = body[:-2] + ")"
#Add the double implication about pits to the kb
# print(expr(head + " <=> " + body))
self.kb.tell(expr(head + " <=> " + body))
#Add rules for wumpus S <=> (adjacent are wumpus)
for i in range(0,4):
for j in range(0,4):
head = ("S"+str(i)+str(j))
p = adjacentRooms(i,j)
body = "("
for room in p:
body += "W"+str(room[0])+str(room[1])+" | "
body = body[:-2] + ")"
# print(expr(head+ " <=> "+ body))
#Add the double implication about pits to the kb
self.kb.tell(expr(head + " <=> " + body))
#If we have a wumpus, then all adjacent rooms have stench
# for i in range(0,4):
# for j in range(0,4):
# head = ("W"+str(i)+str(j))
# body = "("
# for room in adjacentRooms(i,j):
# body += "S"+str(room[0])+str(room[1])+" & "
# body = body[:-2] + ")"
# print(expr(head + " <=> "+body))
# self.kb.tell(expr(head + " <=> " + body))
#If we have pit, then all adjacent rooms have breeze
# for i in range(0,4):
# for j in range(0,4):
# head = ("P"+str(i)+str(j))
# body = "("
# for room in adjacentRooms(i,j):
# body += "B"+str(room[0])+str(room[1])+" & "
# body = body[:-2] + ")"
# print(expr(head + " <=> "+body))
# self.kb.tell(expr(head + " <=> " + body))
#If we dont smell Stench then no wumpus in adjacent rooms
for i in range(0,4):
for j in range(0,4):
head = ("~S"+str(i)+str(j))
body = "("
for room in adjacentRooms(i,j):
body += "~W"+str(room[0])+str(room[1])+" & "
body = body[:-2] + ")"
# print(expr(head + " <=> "+body))
self.kb.tell(expr(head + " <=> " + body))
#If we dont feel breeze then no pit in adjacent rooms
for i in range(0,4):
for j in range(0,4):
head = ("~B"+str(i)+str(j))
body = "("
for room in adjacentRooms(i,j):
body += "~P"+str(room[0])+str(room[1])+" & "
body = body[:-2] + ")"
# print(expr(head + " <=> "+body))
self.kb.tell(expr(head + " <=> " + body))
#There is at least one wumpus
sentence = "("
for i in range(0,4):
for j in range(0,4):
sentence += "W"+str(i)+str(j)+" | "
sentence = sentence[:-2]+")"
self.kb.tell(expr(sentence))
#For each pair of locations, one of them must be wumpus free
#Build a list of the symbols
wr = []
for i in range(0,4):
for j in range(0,4):
wr.append("W"+str(i)+str(j))
#For each pair
for i in range(0,len(wr)-1):
for j in range(i+1,len(wr)):
p2 = Symbol(wr[j])
#Add the sentence that says at least one of them must be wumpus free
self.kb.tell(expr("~"+wr[i] + " | " + "~"+wr[j]))
#Build a list of symbols
self.symbolList = []
for clause in self.kb.clauses:
for symbol in prop_symbols(clause):
if(symbol not in self.symbolList):
self.symbolList.append(symbol)
#Take current percept as a list and update KB
#[Breeze,Stench,Glitter,Bump,Scream]
def addPercept(self,percept,x,y):
newSymbol = []
#Tell KB we felt BXY or ~BXY (breeze at cell(x,y) )
if(percept[0] == 0):
newSymbol.append("~B"+str(x)+str(y))
#self.kb.tell("~B"+str(x)+str(y))
else:
newSymbol.append("B"+str(x)+str(y))
#self.kb.tell(expr("B"+str(x)+str(y)))
#Tell KB we felt SXY or ~SXY (Stench at cell(x,y) )
if(percept[1] == 0):
newSymbol.append("~S"+str(x)+str(y))
#self.kb.tell("~S"+str(x)+str(y))
else:
newSymbol.append("S"+str(x)+str(y))
#self.kb.tell(expr("S"+str(x)+str(y)))
#Tell KB if we saw glitter or not at cell (x,y)
if(percept[2] == 0):
newSymbol.append("~G"+str(x)+str(y))
#self.kb.tell("~G"+str(x)+str(y))
else:
newSymbol.append("G"+str(x)+str(y))
#self.kb.tell("G"+str(x)+str(y))
#Tell the kb
for s in newSymbol:
self.kb.tell(expr(s))
#Update symbol list
for s in newSymbol:
if(expr(s) not in self.symbolList):
self.symbolList.append(expr(s))
#Return true if room x,y is safe (no wumpus and no pit)
def safe(self,x,y):
#This is the expr we want to test if KB entails
# ( ~Wxy & ~Pxy )
safeExpr = expr("~W"+str(x)+str(y)+" & "+"~P"+str(x)+str(y))
#Tell kb the negation of the expr we want to see if it entails
self.kb.tell(~safeExpr)
#Try dpll
result = dpll(self.kb.clauses,self.symbolList,{})
#Remove our test safeExpr
self.kb.retract(~safeExpr)
#Result = false if there was a contradiction => KB entails our safeExpr
if(result == False):
return True
else:
return False
#Same as before, except we test if (Pij | Wij) is NOT entailed by KB
def possiblySafe(self,x,y):
#This is the expr we want to test if KB entails
#( Wxy | Pxy)
safeExpr = expr("W"+str(x)+str(y)+" | "+"P"+str(x)+str(y))
#Tell kb the negation of the expr we want to see if it entails
self.kb.tell(~safeExpr)
#Try dpll
result = dpll(self.kb.clauses,self.symbolList,{})
#Remove our test safeExpr
self.kb.retract(~safeExpr)
#Result = false if there was a contradiction => KB entails our safeExpr
#We return the negation of entails, we want to return True if KB DOES NOT entails our expr
#in other words, kb cannot prove that the square is unsafe
if(result == False):
return False
else:
return True
|
0749311554fd775da25a2b9975209a20d00efd84 | xxxsssyyy/offer-Goal | /21栈的压入、弹出序列.py | 1,446 | 3.640625 | 4 | # coding:utf-8
class Solution:
def IsPopOrder(self, pushV, popV):
# write code
if pushV==[]:
return True
#https://www.cnblogs.com/xueli/p/4952063.html
# 直接赋值:python中对象的赋值是对象的引用,当把它赋值给另一个变量时,并没有拷贝这个对象
# copy浅拷贝:没有拷贝子对象,所以原始数据改变,子对象会改变
# 深拷贝:包含对象里面的自对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变
a = pushV.copy()
for i in range(len(popV)-1):
if pushV.index(popV[i+1])>pushV.index(popV[i]):
a.pop(a.index(popV[i+1]))
else:
break
a.pop(a.index(popV[0]))
print(popV[i+1:])
a.reverse()
if(a==popV[i+1:]):
return True
else:
return False
class solution1:
# 解题方法为建议辅助栈,模拟进出栈全过程
def isvalidstack(self,pushV,popV):
stack =[]
while popV:
if stack and stack[-1] == popV[0]:
stack.pop()
popV.pop(0)
elif pushV:
stack.append(pushV.pop(0))
else:
return False
return True
if __name__ == '__main__':
solution = solution1()
print(solution.isvalidstack([1,2,3,4,5],[4,5,3,2,1]))
|
19e7386806f2830f225077700037f320f37914a4 | vladvlad23/UBBComputerScienceBachelor | /FundamentalsOfProgramming/Assignment 05-07/operations/statistics.py | 5,882 | 3.53125 | 4 | from movie import searchMovieWithId,getBiggestMovieId
from client import searchClientById
from rental import searchRentalWithId
from dateOperations import *
def moviesDescendingByRentingTimes(movieList,rentalList):
'''
Procedure : will create a list counting how many times each movie has been rented and then
will form an id list containing the indexes from highest to lowest
:param movieList = list of movies
:param rentalList = list of rentals
:return list of movies in descending order by renting times
'''
idList = []
newList = rentalList[:]
frequencyList = [0] * (2*getBiggestMovieId(movieList))
for rental in newList:
frequencyList[rental.getMovieId()]+=1
for i in range(1,len(frequencyList)):
maxId = frequencyList.index(max(frequencyList)) #get the index with max apparitions
if maxId>0:
idList.append(maxId)
frequencyList[maxId] = -1
newList = []
for id in range(0,len(idList)): #go through id list
try:
searchMovieWithId(movieList,idList[id])
newList.append(searchMovieWithId(movieList, idList[id]))
except Exception: #this means that the list indexes have been surpassed
return newList
return newList
def moviesDescendingByRentingDays(movieList,rentalList):
'''
The function will receive a list of movies and a list of rentals. It will return a list of
movie sorted descendingly by renting days
:param movieList: the movie list
:param rentalList: the rental list
:return: list of movies in the given order
'''
# implement dictionary where the first element is the movie id and the second
# element consist of the renting days
movieDictList = []
for movie in movieList:
movieDictionary = {"movieId":movie.getMovieId(),"days":int(0)}
for rental in rentalList:
if rental.getMovieId() == movie.getMovieId():
movieDictionary["days"] += getRentedDays(rental)
movieDictList.append(movieDictionary)
movieDictList = sorted(movieDictList,key=lambda movieDict: movieDict.get("days"),reverse=True)
result = []
for movie in movieDictList:
result.append(searchMovieWithId(movieList, movie["movieId"]))
return result
def getRentedDays(rental):
'''
:param rental: the rental
:return: the number of days a movie has been rented. If not returned yet, return -1
'''
try:
return rental.getReturnDate().getDay() - rental.getRentedDate().getDay()
except Exception as e:
return -1;
def moviesDescendingByRentingDays(movieList,rentalList):
'''
The function will receive a list of movies and a list of rentals. It will return a list of
movie sorted descendingly by renting days
:param movieList: the movie list
:param rentalList: the rental list
:return: list of movies in the given order
'''
# implement dictionary where the first element is the movie id and the second
# element consist of the renting days
movieDictList = []
for movie in movieList:
movieDictionary = {"movieId":movie.getMovieId(),"days":int(0)}
for rental in rentalList:
if rental.getMovieId() == movie.getMovieId():
movieDictionary["days"] += getRentedDays(rental)
movieDictList.append(movieDictionary)
movieDictList = sorted(movieDictList,key=lambda movieDict: movieDict.get("days"),reverse=True)
result = []
for movie in movieDictList:
result.append(searchMovieWithId(movieList, movie["movieId"]))
return result
def clientsDescendingByActivity(clientList,rentalList):
'''
The function will receive a list of clients and a list of rentals. It will return a list of
clients sorted by renting days
:param clientList: the movie list
:param rentalList: the rental list
:return: list of clients in the given order
'''
# implement dictionary where the first element is the movie id and the second
# element consist of the renting days
clientDictList= []
for client in clientList:
clientDictionary = {"clientId":client.getClientId(),"days":int(0)}
for rental in rentalList:
if rental.getClientId() == client.getClientId():
clientDictionary["days"] += getRentedDays(rental)
clientDictList.append(clientDictionary)
clientDictList = sorted(clientDictList,key=lambda clientDict: clientDict.get("days"),reverse=True)
result = []
for client in clientDictList:
result.append(searchClientById(clientList, client["clientId"]))
return result
def lateRentals(movieList,rentalList):
'''
Function will return a list of movies that are late (the current date is past the due date and
the client hasn't returned it yet
:param movieList: the movie list from where the movies will be added to the result
:param rentalList: the rental list where everything is checked
'''
rentalDictList = []
for rental in rentalList:
if not rental.isReturned():
if (getCurrentDate() - rental.getDueDate()).days > 0:
lateRental = {"rentalId":rental.getRentalId(),"daysLate":processLateDays(rental)}
rentalDictList.append(lateRental)
rentalDictList = sorted(rentalDictList,key=lambda rentalDict:rentalDict.get("daysLate"),reverse=True)
result = []
for rental in rentalDictList:
rentalObject = searchRentalWithId(rentalList,rental.get("rentalId"))
result.append(searchMovieWithId(movieList,rentalObject.getMovieId()))
return result
def processLateDays(rental):
'''
Function will return how many days have passed since the due date of a given rental until today
:param rental: the rental to be processed
'''
return untilToday(rental.getDueDate())
|
2778abbc231790d01db39a5d0fab6ddc6fa9be28 | theIncredibleMarek/algorithms_in_python | /merge_sort.py | 1,769 | 4.28125 | 4 | #!/usr/bin/env python3
import math
def sort(input, ascending=True):
print("Original: {}".format(input))
print("Ascending sort: {}".format(ascending))
# empty and one item lists are considered sorted
if((len(input)) <= 1):
return input
output = mergesort(input, ascending)
return output
def mergesort(input, ascending):
length = len(input)
if length <= 1:
return input
# split the input
left = input[:math.ceil(length/2)]
right = input[math.ceil(length/2):]
# sort the left and the right sides
left = mergesort(left, ascending)
right = mergesort(right, ascending)
#merge the sides together
left_point = 0
right_point = 0
index = 0
output = []
while(left_point < len(left) and right_point < len(right)):
if(ascending):
value_1 = left[left_point]
value_2 = right[right_point]
else:
value_1 = right[right_point]
value_2 = left[left_point]
if value_1 > value_2:
output.append(right[right_point])
right_point+=1
else:
output.append(left[left_point])
left_point+=1
if left_point == len(left):
# use either += or list.extend()
output += right[right_point:]
if right_point == len(right):
# extend unfolds the second list
output.extend(left[left_point:])
return output
print(sort([1, 2, 1], False))
print(sort([2, 1, 7, 3, 4, 5, 6, 2, 3, 1], False))
print(sort([1, 2, 3, 4, 5, 6], False))
print(sort([2], False))
print(sort([], False))
print(sort([2, 1]))
print(sort([1, 2, 1]))
print(sort([2, 1, 7, 3, 4, 5, 6, 2, 3, 1]))
print(sort([1, 2, 3, 4, 5, 6]))
print(sort([2]))
print(sort([]))
|
a46ef724946453086c4bb2935a7f202da514669f | RobertoChapa/Python_OOP_Example | /ProceduralProgramming.py | 538 | 3.515625 | 4 | def main():
product1 = 'Milwaukee Drill Gun'
price = 129.99
discountPercent = 5.0
da = discountAmount(price, discountPercent) # discount amount
dp = discountPrice(price, da) # discount price
print(product1, " Discount Price: ${:.2f}".format(dp))
return
def discountAmount(price, discountPercent):
da = price * discountPercent / 100
return da # discount amount
def discountPrice(price, da):
dp = price - da
return dp # discount price
if __name__ == '__main__':
main() |
02abbfd54d67e90ee305b4ca36d57de3d4d8b5a6 | caliche22/ADA | /Tarea3/install.py | 1,626 | 3.609375 | 4 | from sys import stdin
from math import *
# Carlos Arboleda ADA Camilo Rocha
# Install
# se hace uso de Activity Scheduling de la clase y se saca un arreglo con el numero de radares x-d y x+d
#donde d es uno de los catetos del triangulo es decir se hace uso de la libreria math para calcularlo
# con pow y sqrt y sus respectivas condiciones d==y , d!=y d<y o cateto<0 en un plano (x,y)
def solve(islas): ### algoritmo de Activity
islas.sort(key=lambda x : x[1])
ans,n,N = 0,0,len(islas)
while n!=N:
mejor,n,ans = n,n+1,ans+1
while n!=N and islas[n][0]<islas[mejor][1]:
n += 1
return ans
def main():
global islas
contador = 1
inp=stdin
line =inp.readline()
n,d=[int(j) for j in line.split()]
while(n!=0 and d!=0):
islas = []
temporal=False
for i in range(n):
x,y = [ int(i) for i in inp.readline().split() ]
cateto = pow(d,2)-pow(y,2)## pitagoras pow(d,2) (y,2) o puede ser d**2 y**2
if d<y or cateto<0: ## condicion 1
temporal = True
elif d==y: ## condicion 2
a,b = x-d,x+d
islas.append([a,b])
else: ## condicion 3
a,b = x-sqrt(cateto), x+sqrt(cateto)
islas.append([a,b])
if temporal==False:
print("Case "+str(contador)+': '+str(solve(islas)))#se hace uso de la concatenacion + casteando
else:
print("Case "+str(contador)+': '+'-1')#se hace uso de la concatenacion + casteando
contador+=1
line =inp.readline()
n,d=[int(j) for j in inp.readline().split()]
main() |
032ab21c048c41519e1a6bf8b22b50a292692e60 | NeilWangziyu/Leetcode_py | /isSymmetric.py | 2,066 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric_old(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
list_left = []
def return_value_left(root):
if root == None:
return None
if root.left != None:
list_left.append(return_value_left(root.left))
else:
list_left.append(None)
if root.right != None:
list_left.append(return_value_left(root.right))
else:
list_left.append(None)
list_left.append(root.val)
list_right = []
def return_value_right(root):
if root == None:
return None
if root.right != None:
list_right.append(return_value_right(root.right))
else:
list_right.append(None)
if root.left != None:
list_right.append(return_value_right(root.left))
else:
list_right.append(None)
list_right.append(root.val)
return_value_left(root)
print(list_left)
# return_value_right(root)
return_value_right(root)
print(list_right)
if list_right == list_left:
return True
else:
return False
def isSymmetric(self, root: TreeNode) -> bool:
"""
interesting point:构造两种遍历方法
:param root:
:return:
"""
def isSymmetric_core(root1, root2):
if not root1 and not root2:
return True
if not root1 or not root2:
return False
if root1.val != root2.val:
return False
else:
return isSymmetric_core(root1.left, root2.right) and isSymmetric_core(root1.right, root2.left)
return isSymmetric_core(root, root)
|
db4a9351de478356132afdf75ffea7286a6bbe89 | saroj1017/Python-programs | /hangman/hangman-code.py | 4,541 | 4.28125 | 4 | import random
from hangman_art import stages, logo
from hangman_words import word_list
from replit import clear
# clear is module in replit platform you can use other modules to clear the data
#prints the logo from the module hangman_art
print(logo)
# itiallly sets set a varibale that points to false and upon some trigger inputs the variable is set to True
game_is_finished = False
# number of lives remaining initally 7 - 1 =6 , which displays only the rope of the game
lives = len(stages) - 1
# computer chooses a random word from the module handman_words
chosen_word = random.choice(word_list)
# calculates the length of the random word choosen from computer
word_length = len(chosen_word)
# displays the number of words to the user via the "_" symbol
display = []
for _ in range(word_length):
display += "_"
# this while loop will keep on running untill game_is_finished varibale changes to True
while not game_is_finished:
# user inputs a letter to guess @ the starting of the game itself
guess = input("Guess a letter: ").lower()
#Use the clear() function imported from replit to clear the output between guesses.
clear()
if guess in display:
print(f"You've already guessed {guess}")
# lets say word is affix , len = 5
# so 0 = a , 1 = f , 2 =f , 3 = i , 4 = x
# lets say i guessed f then first the index 1 matches so the _ is replaced by the corresponding letter
# same happens for index 2
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(f"{' '.join(display)}")
# next guess was p which is not in the word
if guess not in chosen_word:
print(f"You guessed {guess}, that's not in the word. You lose a life.")
lives -= 1
# end of the game as all lives are lost
if lives == 0:
game_is_finished = True
print("You lose.")
print("correct answer was" ,chosen_word)
# if all guesses fills the display then your o/p is correct and you win
if not "_" in display:
game_is_finished = True
print("You win.")
# at each guess you will be displayed the ascii art for the stage you are currenlty in
print(stages[lives])
# example o/p
# Note that in the below example output all the asicii arts gets cleared and only the lastest ASCII art remains
'''
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/
Guess a letter: y
# shows how many letters are required to fill the word
_ _ _ _ _
You guessed y, that's not in the word. You lose a life.
+---+
| |
O |
|
|
|
=========
Guess a letter: p
_ _ _ _ _
You guessed p, that's not in the word. You lose a life.
+---+
| |
O |
| |
|
|
=========
Guess a letter: s
_ _ _ _ _
You guessed s, that's not in the word. You lose a life.
+---+
| |
O |
/| |
|
|
=========
Guess a letter: a
# note that no life is taken and the letter o/p is filled at the correct position
a _ _ _ _
+---+
| |
O |
/| |
|
|
=========
Guess a letter: n
# i was guessing angry but that was wrong :)
You guessed n, that's not in the word. You lose a life.
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: t
You guessed t, that's not in the word. You lose a life.
+---+
| |
O |
/|\ |
/ |
|
=========
Guess a letter: d
You guessed d, that's not in the word. You lose a life.
You lose.
correct answer was affix
+---+
| |
O |
/|\ |
/ \ |
|
=========
'''
|
7fa8e2f20fdabfc468b3929bbdf0e7817a71b1dd | ewilson/codeclubstarters | /hangman/hangman.py | 680 | 3.921875 | 4 | secret = ''
correct_letters = []
missed_letters = []
def check_letter(letter):
in_word = letter.upper() in secret
if in_word:
correct_letters.append(letter)
else:
missed_letters.append(letter)
return in_word
def hide_word():
display = []
for letter in secret:
if _letter_guessed(letter):
display.append(letter)
else:
display.append('-')
return ' '.join(display)
def solved():
guessed = True
for letter in secret:
if not _letter_guessed(letter):
return False
return guessed
def _letter_guessed(letter):
return letter in correct_letters or letter == ' ' |
cd3276e4fd92c661999b531959916c606ba56d27 | SachinMadhukar09/100-Days-Of-Code | /08.Circular Linked Lis/Day 40/22 August 02 Insert at Beginning.py | 219 | 3.703125 | 4 | def insertBeg(head,x):
temp=head(x)
if head==None:
temp.next=temp
return temp
curr=head
while curr.next!=head:
curr=curr.next
curr.next=temp
temp.next=head
return temp |
be524a5d888aaf6509b3cfd872d87d3c43fa6d60 | daniel-reich/turbo-robot | /ub2KJNfsgjBMFJeqd_15.py | 2,514 | 4.28125 | 4 | """
In this challenge we're going to build a board for a **Minesweeper** game
using **OOP**. Create two classes: `Game` and `Cell`.
`Game` should take in 3 arguments: number of **rows** , number of **columns**
and total number of **mines** , set the default values to 14, 18 and 40
respectively. Each instance should have attributes `.rows`, `.cols` and
`.mines`, equivalent to the values of the three arguments. It should also have
a `.board` attribute, the board shoud be a 2-D list with _rows_ sublists with
_cols_ instances of `Cell`.
A `Cell` should have attributes `.row` and `.col`, set these to its position
on the board. Attributes `.mine` (either `True` or `False`), `.flag` and
`.open` (set both to `False`). Finally an attribute `.neighbors`, indicating
how many of its neighboring cells are mined.
### Tests
game = Game()
game.rows ➞ 14
game.cols ➞ 18
game.mines ➞ 40
height of .board ➞ 14
width of .board ➞ 18
Cells in .board ➞ 252
total mined in cells .board ➞ 40
each Cell .row and .col attributes match its position on the board ➞ True
each Cell .flag and .open attributes are set to False ➞ True
each Cell .neighbors attribute matches the actual amount of neighboring mines ➞ True
### Notes
* Try randomizing the position of the mines.
* Feel free to add as many other attributes or methods as you need.
"""
import random
class Game:
def __init__(self, rows=14, cols=18, mines=40):
self.rows = rows
self.cols = cols
self.mines = mines
self.board = []
self.new_game()
def new_game(self):
# init mine positions
mine_pos = [0]*(self.rows * self.cols)
while sum(mine_pos) < self.mines:
mine_pos[random.randint(0, len(mine_pos) - 1)] = 1
# define Cells
for i in range(self.rows):
self.board.append([])
for j in range(self.cols):
# Check the neighbor chell values
neighbor_values = 0
for m in range(-1,2):
x = i + m
for n in range(-1,2):
y = j + n
if 0 <= x < self.rows and 0 <= y < self.cols and not (m == 0 and n == 0):
neighbor_values += mine_pos[x * self.cols + y]
self.board[i].append(Cell(i, j, mine_pos[i * self.cols + j], neighbor_values))
class Cell:
def __init__(self, row, col, mine, neighbors=0):
self.row = row
self.col = col
self.mine = mine
self.flag = False
self.open = False
self.neighbors = neighbors
|
c363c60b22cda2cdae00e211becffdb188889621 | diogo55/OnlinePythonTutor | /v3/tests/doctest-tests/lab1.py | 2,859 | 3.640625 | 4 | '''
# My first Labyrinth lab
This is the lab description -- write whatever you want in here in
*markdown* format and it will show up as the toplevel docstring for this module
- shawn
- is
- cool
1. code code code
2. write paper
3. profit $$$
woohoo!
'''
def factorial(n):
"""
Lab part 1
lab description in markdown format
Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
------
>>> print [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> print [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> print factorial(30)
265252859812191058636308480000000
>>> print factorial(30L)
265252859812191058636308480000000
>>> print factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
>>> print factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> print factorial(30.0)
265252859812191058636308480000000
>>> print factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
# helper function written by student, not part of the lab
def add(x, y):
return x + y
def slow_multiply(a, b):
"""
Lab part 2
Return the product of 'a' and 'b'
------
>>> print slow_multiply(3, 5)
15
>>> print slow_multiply(5, 3)
15
>>> print slow_multiply(0, 1)
0
>>> print slow_multiply(0, 100)
0
>>> print slow_multiply(-1, 5)
-5
"""
i = 0
prod = 0
for i in range(b):
prod = add(prod, a)
return prod
GLOBAL_DATA = [{"name": "John", "age": 21},
{"name": "Jane", "age": 35},
{"name": "Carol", "age": 18}]
def find_age(person):
"""
Lab part 3
Fetch the age for a given person's name
------
>>> print find_age('John')
21
>>> print find_age('Carol')
18
>>> print find_age('Jane')
35
>>> print find_age('jane')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lab1.py", line 114, in find_age
raise KeyError # not found!
KeyError
>>> print find_age('bobby')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lab1.py", line 114, in find_age
raise KeyError # not found!
KeyError
"""
for e in GLOBAL_DATA:
if e["name"] == person:
return e["age"]
raise KeyError # not found!
|
2dacb9a42546cce32d7f7c6d230b279df4e615c5 | PaGr0m/Courses-FogStream- | /Practice 2/List_2.2.py | 322 | 3.84375 | 4 | # lst = list(input("Enter the numbers"))
lst = [1, 1, 1, -2, 2, -3, -23, -23, -23]
myList = list()
# for index in range(0, len(lst) - 1):
# if ((lst[index] > 0 and lst[index + 1] > 0) or
# (lst[index] < 0 and lst[index + 1] < 0)):
# myList.append([lst[index], lst[index + 1]])
# print(myList[0])
|
a40807c41bede478cde0b09e929186c1bf5a93b1 | pardo13/python | /Practica 1 E3.py | 97 | 3.90625 | 4 | N=int(input("dame int"))
if (N%2==0):
print ("Si es par")
else:
print ("No es par")
|
14fdc47e0da036c1cda4ceecfa644e45c17900c9 | kmdtty/ucspp | /98-Graph/small-world/graph.py | 1,435 | 4.03125 | 4 | """
Example
-------
% more tinyGraph.txt
A B
A C
C G
A G
H A
B C
B H
% python graph.py < tinyGraph.txt
A B C G H
B A C H
C A B G
G A C
H A B
"""
import sys
import itertools
from collections import defaultdict
class Graph():
def __init__(self, f=None, delimiter=" "):
"""Create graph from a file
f -- input file
delimiter -- the delimieter to separate the edges
"""
self.graph = defaultdict(set)
for line in f:
source, destination = line.rstrip().split(delimiter)
self.graph[source].add(destination)
self.graph[destination].add(source)
def add_edge(self, v, w):
"""add edge v-w"""
self.graph[v].add(w)
self.graph[w].add(v)
def vertices(self):
return self.graph.keys()
def edges(self, v):
# TODO:optimize
edges = set()
for v, neighbors in self.graph.items():
edges = edges.union(itertools.product(v, neighbors))
return edges
def neighbors(self, v):
return self.graph[v]
def degree(self, v):
""" number of neighbors of v"""
return len(self.neighbors(v))
def has_vertex(self,v):
""" is v a vertex in the graph?"""
return v in self.graph
def has_edge(self, v, w):
"""is v-w an edge in the graph?"""
return (v,w) in self.edges()
if __name__ == "__main__":
graph = Graph(f=sys.stdin)
v_n = [(v, graph.neighbors(v)) for v in graph.vertices()]
for v, n in v_n:
print("%s %s" % (v, " ".join(n)))
|
866da6d7a9723faa21b8299c8e85579c6618b371 | thirukkumaransv/progarmming | /character.py | 94 | 3.765625 | 4 | ch = input(" ")
if(ord(ch) >= 97 and ord(ch) <= 122):
print("Alphabet")
else:
print("No")
|
153e36ad840072bf79f2108547db1145c67f1aaf | shoni1/sr6 | /sr6..py | 653 | 3.609375 | 4 | try:
n = int(input('Введите кол-во элементов массива: ')) #Кол-во элементов массива
a = [] #Создаем массив
for i in range (n):
a.append(int(input('Введите массив: '))) #Заполняем его
delta = int(input('введите delta: ')) #Вводим дельту
counter = 0 #Создаем счетчик отличающихся элементов
for i in range (len(a)):
if min(a) + delta == a[i]:
counter += 1
print(counter)
except ValueError:
print('Это не число. Введите число.')
|
c10a2a1eba6a09bf5cdf8337aa0dbe4bc7c93cc4 | qagroup-py/python-october-2016-test-Olhaa | /OOP_food.py | 1,174 | 3.8125 | 4 | # coding: utf-8
"""
Implement class structure/hierarchy for following classes:
Basil (базилік)
Beetroor (буряк)
Blueberry (чорниця)
Cabbage (капуста)
Carrot (морква)
Concorde (pear) (груша "Конкорд")
Dill (кріп)
Domestic strawberry (полуниця)
Golden delicious (apple) (яблуко "Голден")
Granny Smith (apple) (яблуко "Гренні Сміт")
Onion (цибуля)
Potato (картопля)
Red globe (grapes) (виноград "Ред Глоб")
Victoria (grapes) (виногдар "Вікторія")
Wild strawberry (суниця)
"""
class Food:
def __init__(self, name):
self.name = name
class Berries(Food):
pass
Blueberry = Berries
Domestic_strawberry = Berries
Wild_strawberry = Berries
class Fruits(Food):
pass
Concorde_Pear = Fruits
Golden_delicious_apple = Fruits
Granny_Smith_apple = Fruits
Red_globe_grapes = Fruits
Victoria_grapes = Fruits
class Greens(Food):
pass
Basil = Greens
Dill = Greens
class Vegetables(Food):
pass
Beetroor = Vegetables
Cabbage = Vegetables
Carrot = Vegetables
Onion = Vegetables
Potato = Vegetables
|
3652cf23194b2709a49b61009c83b7b5dd81e74e | akueisara/leetcode | /P147 Insertion Sort List/solution.py | 1,218 | 4.03125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# https://en.wikipedia.org/wiki/Insertion_sort
# If's often to preform this algo using an Array, here we use a linked list
# Insertion Sort Algo is fast for sorting a "small" array, even faster than quicksort
# Time: O(n^2)
# Space: O(1)
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
sorted_head = ListNode()
curr = head
while curr:
prev = sorted_head
while prev.next and prev.next.val < curr.val:
prev = prev.next
next_node = curr.next
curr.next = prev.next
prev.next = curr
curr = next_node
return sorted_head.next
def _insertionSort(self, nums: List[int]) -> List[int]:
for i in range(0, len(nums)):
tmp = nums[i]
j = i
while j > 0 and nums[j - 1] > tmp:
nums[j] = nums[j - 1]
j = j - 1
nums[j] = tmp
return nums |
40df232bad72079919295e9587d7333cc3c86990 | assassint2017/leetcode-algorithm | /Sum of Left Leaves/Sum_of_Left_Leaves.py | 798 | 3.890625 | 4 | # 64ms 65.08%
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
queue = []
queue.append(root)
sum = 0
while len(queue) > 0:
root = queue.pop(0)
if root.left is not None and root.left.left is None and root.left.right is None:
sum += root.left.val
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return sum |
ebd59d0e8f04b60c76fca5b73892b88cff67206e | CollinErickson/LeetCode | /Python/109_SortedListToBSTv2.py | 2,595 | 3.96875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
s = "(" + str(self.val)
n = self.next
if n is None:
return s + ")"
#print('s', s, n.val)
while n is not None:
s += " -> " + str(n.val)
n = n.next
return s + ")"
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
s = str(self.val)
if self.left is not None:
s += "(" + str(self.left) + ")"
if self.right is not None:
s += "[" + str(self.right) + "]"
return s
class Solution(object):
curnode = None
def sortedListToBST(self, head, bst=None, leftdepth=0):
"""
:type head: ListNode
:rtype: TreeNode
"""
if head is None:
return None
if head.next is None:
return TreeNode(head.val)
self.curnode = head
n = 1
node = head
while node.next is not None:
n += 1
node = node.next
#print('n is', n)
return self.helper(n)
def helper(self, n):
#print('in helper', n)
if n <= 0:
return None
if n==1:
bst = TreeNode(self.curnode.val)
self.curnode = self.curnode.next
return bst
nL = n-1 - (n-1) // 2
nR = n - nL - 1
assert nR>=0
bstL = self.helper(nL)
bst = TreeNode(self.curnode.val)
self.curnode = self.curnode.next
bstR = self.helper(nR)
bst.left = bstL
bst.right = bstR
return bst
sol = Solution()
n1 = ListNode(1)
#print(n1)
#print('sol is', sol.sortedListToBST(n1), "1")
n1 = ListNode(1)
n2 = ListNode(2)
n1.next = n2
#print(n1)
#print('sol is', sol.sortedListToBST(n1))
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
#print(n1)
#print('sol is', sol.sortedListToBST(n1))
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n1.next = n2
n2.next = n3
n3.next = n4
#print(n1)
#print('sol is', sol.sortedListToBST(n1))
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n6 = ListNode(6)
n7 = ListNode(7)
n8 = ListNode(8)
n9 = ListNode(9)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = n8
n8.next = n9
print(n1)
print('sol is', sol.sortedListToBST(n1))
|
5b573db3eed92b7c7a82af5cb1f942e5c3c9ebb9 | deepankerkoul/SudoPlacement19 | /Week 1/Arrays and Searching/Immediate Smaller Number.py | 1,511 | 3.96875 | 4 | '''
Immediate Smaller Element
Given an integer array of size N. For each element in the array, check whether there exist a smaller element on the next immediate position of the array. If such an element exists, print that element. If there is no smaller element on the immediate next to the element then print -1.
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains 2 lines of input:
The first line contains an integer N, where N is the size of array.
The second line contains N integers(elements of the array) sperated with spaces.
Output:
For each test case, print the next immediate smaller elements for each element in the array.
Constraints:
1 ≤ T ≤ 200
1 ≤ N ≤ 107
1 ≤ arr[i] ≤ 1000
Example:
Input
2
5
4 2 1 5 3
6
5 6 2 3 1 7
Output
2 1 -1 3 -1
-1 2 -1 1 -1 -1
Explanation:
Testcase 1: Array elements are 4, 2, 1, 5, 3. Immediate smaller of 2 is immediate smaller of 4, 1 is immediate smaller of 2, no immediate smaller of 1, 3 is immediate smaller of 5, and no immediate smaller for last element exists. So ouput is : 2 1 -1 3 -1.
'''
#code
testcases = int(input())
for case in range(testcases):
size = int(input())
arr = list(input().split())
arr = [int(a) for a in arr]
for elem in range(size):
try:
if arr[elem + 1] < arr[elem]:
print(arr[elem + 1], end= " ")
else:
print(-1, end= " ")
except:
print(-1) |
43c201ead0f36f47e74b7287614f209b4452ea4e | xiaolinian/myCodeAboutCourse_PythonFundamental | /temp/CostCal.py | 359 | 3.828125 | 4 | # 假设每考一次试的费用为X,每次考试通过的概率为P1.求考试通过的成本的数学期望。
def totalcost(X,P1):
totalcost=0
for i in range(1,100):
#print(i)
costith=X*i*P1*pow(1-P1,i-1)
#print(costith)
totalcost+=costith
print(totalcost)
totalcost(4500,0.95)
totalcost(2500,0.4)
|
d7ed1986a0650f43d04e7007ace1219085e8b367 | adsl305480885/leetcode-zhou | /922.按奇偶排序数组-ii.py | 1,704 | 3.5 | 4 | '''
Author: Zhou Hao
Date: 2021-01-28 17:23:23
LastEditors: Zhou Hao
LastEditTime: 2021-01-28 21:16:22
Description: file content
E-mail: 2294776770@qq.com
'''
#
# @lc app=leetcode.cn id=922 lang=python3
#
# [922] 按奇偶排序数组 II
#
# @lc code=start
class Solution:
#方法一:奇偶分开再遍历合并
# def sortArrayByParityII(self, A: List[int]) -> List[int]:
# x_ = [x for x in A if x%2 ==0] #偶
# y_ = [y for y in A if y%2 !=0] #奇
# res = []
# for i in range(len(A)):
# if i %2 ==0:
# res.append(x_[0])
# x_.remove(x_[0])
# else:
# res.append(y_[0])
# y_.remove(y_[0])
# return res
#不分开遍历一次
# def sortArrayByParityII(self, A: List[int]) -> List[int]:
# res = len(A)*[0] #创建指定长度,指定初始元素的列表
# i = 0 #偶
# j = 1 #奇
# for _ in A:
# if _ %2 ==0:
# res[i] = _
# i+=2
# else:
# res[j] = _
# j+=2
# return res
#双指针 奇偶指针
def sortArrayByParityII(self, A: List[int]) -> List[int]:
i = 0 #偶指针
j = 1 #奇指针
while i<len(A) and j<len(A):
if A[i] %2 ==0:
i+=2
if A[j] %2 !=0:
j+=2
# if A[i]%2 !=0 and A[j] %2 ==0:
# print(i,j,A[i],A[j])
if i < len(A) and j < len(A):
print(i,j,A[i],A[j])
A[i],A[j] = A[j],A[i]
return A
# @lc code=end
|
50062c0fe2708bcb0a3abca2a52d3a932fec4ec1 | mrmuli/bootcamp_9_ke | /toy_problems/fibonacci.py | 647 | 3.8125 | 4 |
def fibby(n):
# initialize two counter vaiables
a, b = 0, 1
# create a new list to hold sequence
my_list = [1]
# loop through range of 0 and input
for i in range(0,n):
# fibonacci sequence moderator
# num is a placeholder for the original value of a
num = a
# a is assigned the value of b in the addition via the sequence
a = b
# b is assigned the value of the original 'a' and it's pre-value digit
b = num + b
# added sequence values to list
my_list.append(b)
return my_list
print fibby(20)
# Recursion
def fibbz(n):
if n == 1 or n == 2:
return n
else:
return fibbz(n-1)+fibbz(n-2)
print fibbz(10) |
67e2c400c8718037fab67dfa60dcabb0e67a537c | hyunbeen/python--training | /list/sample4.py | 934 | 4.09375 | 4 | #list/sample4.py
#리스트 연산
a=[1,2,3,4,5]
b=[5,7,8,9,10]
# -,/ 연산은 지원되지 않는다
print("---------------------------------------------");
result = a + b
print(result)
result = a * 2
print(result)
leng = len(result)
print(leng)
# print(a[3]+"hi"); error 강제 형변환 시켜야된다
print("---------------------------------------------");
print(str(a[3])+"hi")
print("---------------------------------------------");
result = str(1)
print(result)
result = str(1.23)
print(result)
result = str(True)
print(result)
result = str([1,2,3])
print(result)
result = str("abc");
print(result)
print("---------------------------------------------");
result = int('1')
print(result)
result = float('1.23')
print(result)
result = bool('True')
print(result)
print("---------------------------------------------");
result = bool(1)
print(result)
result = bool(0)#'0'은 True
print(result)
result = bool(999)
print(result) |
16f8a7df398b466fe71ab06c0c2b90a15653f112 | Vladimyr23/Python-Exercises | /w2prog1.py | 878 | 3.734375 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Vlad
#
# Created: 15/02/2016
# Copyright: (c) Vlad 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
length=raw_input("length of the room in meters")
width=raw_input("width of the room in meters")
CarpetMeterPrice=raw_input("Carpet price 1 sqr meter")
length=float(length)
width=float(width)
CarpetMeterPrice=float(CarpetMeterPrice)
square=length*width
CarpetPrice=CarpetMeterPrice*square
print "Carpet Price for this room is ",CarpetPrice
length=raw_input("length of the garden in meters")
width=raw_input("width of the garden in meters")
length=float(length)
width=float(width)
fence=(length+width)*2-width
print "Fencing length", fence
|
b3963f8d076c4590caf29c7311014324abf7f079 | Edersheckler/Automatas2 | /CalcularAreas.py | 699 | 3.9375 | 4 | import math as mat
#---------------------
# funcion para calcular area
#--------------------------
def calcularArea(r):
area = mat.pi*(mat.pow(r,2))
return area
def calcularDiametro(d):
diam = d*2
return diam
def main():
ciclo = True
while ciclo == True:
print ('Script para calcular area de circunferencia')
radio = float (input ('Introduce el valor del radio: '))
# Invocar los metodos
print ('El area es: ',calcularArea(radio))
print ('El diamtro es: ',calcularDiametro(radio))
resp = input ("Desea hacer otro calculo: (s/n)?")
if (resp == 's' or resp == 'S'):
ciclo = True
else:
ciclo = False
else:
print("Fin del programa..")
if _name_ == "_main_":
main() |
aec0260b73b27752601eb68be633f37357c1821b | Aasthaengg/IBMdataset | /Python_codes/p03130/s902576013.py | 335 | 3.515625 | 4 | from collections import defaultdict
dic = defaultdict(int)
for i in range(3):
p,q = map(int,input().split())
dic[p] += 1
dic[q] += 1
#print(dic)
L = []
for v in dic.values():
L.append(v)
odd = [x%2 ==1 for x in L]
even = [x%2 ==0 for x in L]
if sum(odd) == 2 or sum(even) == 4:
print("YES")
else:
print("NO") |
778d98836c0f3b686dadb9a2bdc4629efa5af5ff | Darlan-Freire/Python-Language | /exe70 - Estatísticas em produtos.py | 936 | 3.828125 | 4 | #Crie um prog que leia o NOME e o PREÇO de VÁRIOS PRODUTOS.
#O prog deverá perguntar se o USUÁRIO vai continuar.
#No final, mostre:
# (a) Qual é o TOTAL DE GASTO na compra.
# (b) Quantos produtos custam MAIS de R$1000.
# (c) Qual é o NOME do produto mais BARATO.
total = MaiorMil = menor = cont = 0
produto = ' '
while True:
nome = str(input('nome do produto:')).strip().title()
custo = float(input('preço R$:'))
total += custo
cont += 1
if custo > 1000:
MaiorMil += 1
if cont == 1 or custo < menor:
menor = custo
produto = nome
print('Cadastro com SUCESSO')
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Quer continuar? [S/N]:')).strip().upper()[0]
if continuar == 'N':
break
print(f'\n(a)Total gasto: {total}\n(b)Produtos custando mais de mil: {MaiorMil}\n(c)Nome do produto mais barato: {produto}')
|
76e6413ec1d805f7889212e90f3da825a01e2d7b | sandhyalethakula/Iprimed_16_python | /Aug-23 Assign Ocollections prathyusha.py | 5,305 | 4.15625 | 4 | '''
Code based assessment
````
1.Question
A student has joined a course costing as per the given table.
If the fee is paid via card, an additional service charge of Rs. 500/- is added but if payment is made through e-wallet, a discount of 5% is given for the payment.
Use this reference table:
python 15000
java 8000
ruby 10000
rust 20000
Write a program to:
PROMPT ASKING THE USER TO CHOOSE:
0 TO QUIT
1 TO ACCEPT & STORE STUDENT DATA - (CREATE) - Collect multiple
2 VIEW ALL THE ENTERED DATA - (READ)
DO AS PER THE USER'S CHOICE.
1. Collect Name, Course, modeOfPayment / store in tuple when finished
2. display all entered data neatly
'''
student_details=[] #empty list to add student course details
choose_a_number=''
ans="y"
while 1:
if choose_a_number =='': #checking the choose_a_number or ans to ask the to enter input as 0 or 1 or 2
print("#"* 10, "STUDENT MANAGEMENT MENU","#"*10)
print('''Choose:
0 to Quit the app,
1 to Create data,
2 to Display data ''')
choose_a_number = input("Enter > ") #Ask user input to perform specific task in list mentioned
ans="y" #changing ans to y to avoid process errors
elif choose_a_number == "0":
print("Quit selected")
print()
num=0
if len(student_details) == 0:
print("Course enrollement is quit..")
print("---Empty no info---")
else:
print("Course enrollement is quit..")
print("Student who enrolled courses")
for i in student_details: #iterate each value in student_details, convert the details into list and print with comma separated
details = list(i)
num+=1
print(" ",str(num)+".",", ".join(details))
print()
choose_a_number = ''
break
elif choose_a_number == "1" and ans == "y": #if choose_a_number is 1 and ans is y then it asks user to enroll course
if len(student_details) == 0:
print("~"*20)
print(" Create selected")
print('''Fees:
Python - 15000,
Java - 8000,
Ruby - 10000,
Rust - 20000
payment mode:
1.Card - 500RS/- Extra charge,
2.E-Wallet - 5% Discount''')
name = input(" Enter name >") #Ask for user's name
course = input(" Enter a course >") #Ask for course number
payment = input(" Enter paymode number >") #Ask payment mode
if course == "python": #checks the course name and procede to fee
if payment == "1":
fee = 15000+500
else:
fee = 15000 - (15000*5/100) #if payment mode is card additional 500 charge apply or choose e-wallet to get 5% discount
elif course == "java":
if payment == "1":
fee = 8000+500
else:
fee = 8000 - (8000*5/100)
elif course == "ruby":
if payment == "1":
fee = 10000+500
else:
fee = 10000 - (10000*5/100)
elif course == "rust":
if payment == "1":
fee = 20000+500
else:
fee = 20000 - (20000*5/100)
if course in "pythonjavarustruby" and payment != '' and name!= '': #if users enters correct details a new tuple is created and append to studet_details list
student_details.append(("Name:- {}".format(name),"Course:- {}".format(course),"Fee:- {}".format(fee)))
ans = input(" Enter y to continue or n to quit > ") #After succesful creation of details ask user to continue or quit enrollment
else:
print("You missed to fill course or payment mode or name check again and Fill the Details!") #if user does'nt enter any details or missed any it asks again
elif ans == "n":
choose_a_number = ''
elif choose_a_number == "2":
print("~"*20)
print(" DISPLAY selected - Student who enrolled courses")
print()
num=0
if len(student_details) ==0:
print("---Empty no info---")
else:
for i in student_details: #iterate each value in student_details, convert the details into list and print with comma separated
details = list(i)
num+=1
print(" ",str(num)+".",", ".join(details))
print()
choose_a_number = '' #changes choose_a_number to empty to end infinite loop |
3513ef10e8e8f7d62b66fdedb87a9b8c3b631b05 | liguanghe/test2 | /try/ex15-test.py | 714 | 3.984375 | 4 | # 用 argv参数变量, 获取文件名。 解包为命令名和文件名
from sys import argv
script, filename = argv
# open是一个命令,跟脚本、input等命令类似,接受一个参数,返回一个值,讲这个值赋予一个变量。
# 在txt上调用了open这个函数 用等号,并且文件名也有txt
print ("Here's your file %r" % filename)
# 用. 后面是命令,无需任何参数
print (txt.read())
print ("Type the filename again:")
# 赋值,文件是输入的文件名
file_again = input("> ")
# 赋值,打开命令,file_again 就是input的内容,文件名
txt_again = open(file_again)
# 用. 后面是命令read read也是一个命令,
print (txt_again.read()) |
c2e90893e27b289c7432be18d897bc53e8037b16 | wan-catherine/Leetcode | /problems/RotateArray.py | 739 | 3.5625 | 4 | class Solution(object):
def rotate_old(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == None or len(nums) < 2:
return
l = k % len(nums)
if l == 0:
return
nums[:] = nums[-1 * l :] + nums[0:len(nums) - l]
def rotate(self, nums, k):
length = len(nums)
k = k % length
def reverse(start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
reverse(0, length - 1)
reverse(0, k-1)
reverse(k, length-1) |
cb0f30cf0cf9081f4b90c9f44c3307bb6d139edd | LukeBreezy/Python3_Curso_Em_Video | /Aula 21/Aula 21b.py | 779 | 4.03125 | 4 | def linha():
print('\033[1;33m=-' * 50, '\033[0m')
# =-=-=-= RETORNANDO VALORES (return) =-=-=-=
# Ao usar um return em uma função, podemos utilizar no escopo global, o valor gerado por ela
def soma(a=0, b=0, c=0):
s = a + b + c
return s
res = soma(10, 5, 2)
print(res)
linha()
print(f'Foram realizadas 3 somas e os resultados são: {soma(10, 5, 2)}, {soma(20, 9, 3)} e {soma(17, 3, 5)}')
linha()
# Outro exemplo
def par(n=0):
"""
Diz se o número é par ou ímpar.
:param n: Valor passado pelo usuário, e é 0 por padrão.
:return: bool
"""
if n % 2 == 0:
return True
else:
return False
num = int(input('Digite um número: '))
if par(num):
print(f'{num} é par.')
else:
print(f'{num} não é par.')
|
08b0c566c53a599e6335cc8cef0b9811afa0606e | srinijadharani/DataStructuresLab | /01/01_g_swap_numbers.py | 367 | 4.3125 | 4 | # 1g. Program to swap two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The numbers before swapping are - num1: {} and num2: {}." .format(num1, num2))
# logic for swapping two numbers
num1, num2 = num2, num1
print("The numbers after swapping are - num1: {} and num2: {}." .format(num1, num2)) |
503a6763fb8f899e13252b931958984e2be48d74 | JoeyShepard/RobotGame | /c/pre-reorganization/bin2hex.py | 1,616 | 4.0625 | 4 | """
Short script to convert to hex format
THIS IS NOT A GENERAL PURPOSE UTILITY!
"""
import sys
print("Generating hex file...")
try:
address=int(sys.argv[1],16)
except:
print(" Error: bad or missing address - "+sys.argv[1])
sys.exit()
try:
read_file=open(sys.argv[2],mode="rb")
except:
print(" Error: input file not found - "+sys.argv[2])
sys.exit()
try:
write_file=open(sys.argv[3],mode="w")
except:
print(" Error: output file can't be opened - "+sys.argv[3])
sys.exit()
def pad(num,zeroes):
return ("0"*zeroes+num)[-zeroes:]
def gen_line(data,address,checksum):
out_str=":"+pad(hex(int(len(data)/2))[2:],2)+pad(hex(address)[2:],4)+"00"+data
checksum+=int(len(data)/2)
out_str+=pad(hex(((checksum&0xFF)^0xFF)+1)[2:],2)
return out_str.upper()+"\n"
read_data=read_file.read()
data_len=len(read_data)
print(" "+sys.argv[3][sys.argv[3].rfind("\\")+1:])
temp=" "+pad(hex(address),4)+" - "+pad(hex(address+data_len),4)
if len(str(data_len))<4: temp+=" ("+str(data_len)
else: temp+=" ("+str(data_len)[:len(str(data_len))-3]+","+str(data_len)[-3:]
print(temp.upper()+" bytes)")
write_data=""
checksum=0
for i in read_data:
write_data+=pad(hex(i)[2:],2)
checksum+=i
if len(write_data)==64:
write_file.write(gen_line(write_data,address,checksum))
write_data=""
checksum=0
address+=32
#Remaining bytes
write_file.write(gen_line(write_data,address,checksum))
#Reset vector
write_file.write(gen_line("00C0",0xFFFC,0x20))
#End of record
#write_file.write(":00000001FF")
#In this case, use batch file to write
|
bbc812b024751f8ecfbe3a270ecbf90710fd4f76 | yunyuntsai/Computer-Vision-HW | /hw3/code/get_tiny_images.py | 1,686 | 3.65625 | 4 | from PIL import Image
import pdb
import numpy as np
from numpy import linalg as LA
def get_tiny_images(image_paths):
'''
Input :
image_paths: a list(N) of string where where each string is an image
path on the filesystem.
Output :
tiny image features : (N, d) matrix of resized and then vectorized tiny
images. E.g. if the images are resized to 16x16, d would equal 256.
'''
#############################################################################
# TODO: #
# To build a tiny image feature, simply resize the original image to a very #
# small square resolution, e.g. 16x16. You can either resize the images to #
# square while ignoring their aspect ratio or you can crop the center #
# square portion out of each image. Making the tiny images zero mean and #
# unit length (normalizing them) will increase performance modestly. #
#############################################################################
#print("training num: ",len(image_paths))
tiny_images =[]
tiny_images = np.zeros([len(image_paths),16 * 16])
for i in range(0,len(image_paths)):
img = Image.open(image_paths[i],'r')
img = img.resize((16,16),Image.BILINEAR)
img = np.array(img)
tiny_images[i] = img.reshape((1,256))
##############################################################################
# END OF YOUR CODE #
##############################################################################
return tiny_images
|
98598d717e875d9a0bb27de6ca314c395846ef8f | houyinhu/AID1812 | /普通代码/practice/达内/python/day10/function_as_args2.py | 297 | 3.734375 | 4 |
# def goodbye(L):
# for x in L:
# print("再见:",x)
#
# def operator(fn,L):
# fn(L)
#
# operator(goodbye,['Tom','Jerry','Spike'])
def myinput(fn):
L = [1,3,5,7,9]
return fn(L)
print(myinput(max))
print(myinput(min))
print(myinput(sum))
|
b2656a3e30f634e5949dd4b961c99a422c900d27 | joelb-2011/Estructura-de-Datos-UNEMI | /Ejercicio 9 - Numeros Iguales.py | 651 | 4.09375 | 4 | class Condicion:
def __init__(self,n1,n2):
self.numero1=n1
self.numero2=n2
numero = self.numero1+self.numero2
self.numero3=numero
def Condicion(self):
if self.numero1 == self.numero2:
print("El Numero 1: {} y Numero 2: {} son iguales".format(self.numero1, self.numero2))
elif self.numero1 < self.numero3:
print("El Numero 1: {} es menor que Numero 3: {}".format(self.numero1, self.numero3))
else:
print("No son iguales.")
print("Fin del metodo.")
condi1 = Condicion(5, 8)
print(condi1.numero3)
print(condi1.Condicion())
|
2bb679e0c5ead6d3d2889acc916584aed2461ced | rohitjain994/Leetcode | /amazon/get-intersection-node.py | 1,070 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
# 2-pointer streatgy
h1 = headA
h2 = headB
while h1!= h2:
h1 = h1.next if h1 else headB
h2 = h2.next if h2 else headA
return h1
#Lenghth streatgy
# l1=self.Listlen(headA)
# l2 = self.Listlen(headB)
# l = abs(l1-l2)
# h1 = headA
# h2 = headB
# if l1>l2:
# for i in range(0,l):
# h1 = h1.next
# else:
# for i in range(0,l):
# h2 = h2.next
# # print(l1,l2,l)
# while h1 != h2:
# h1 = h1.next
# h2 = h2.next
# return h1
# def Listlen(self,headA: ListNode) -> int:
# h1 = headA
# l1 = 0
# while h1:
# l1+=1
# h1 = h1.next
# return l1 |
54d19bedf6e9bf0b5a3e70eca985fe6fdc9acbf6 | MihoKim/bioinfo-lecture-2021-07 | /bioinformatics/bioinformatics_2_5.py | 364 | 3.625 | 4 | # 두 개의 문자열 s1과 s2를 입력받아 s1의 길이가 홀수이고 s2보다 짧으면 s1, s2의 순서로 출력하고,
# 그렇지 않으면 반대 순서로 출력하는 프로그램을 완성하시오.
s1 = str(input("Enter s1: "))
s2 = str(input("Enter s2: "))
if len(s1) % 2 == 1 and len(s1) < len(s2):
print(s1 + s2)
else:
print(s2 + s1)
|
14eb0117f986d979f4e9d20b5d4f78bcd01b83f1 | eduardoramirez/Microsoft-Coding-Challenge | /NDrome/NDrome.py | 1,228 | 3.53125 | 4 | import sys
def isEqual(m,n):
length = len(n)
for i in range(0, length):
if m[i] != n[i]:
return False
return True
def isPali(n):
return n == n[::-1]
##str = raw_input("String: ")##sys.stdin.read(1)
inputs = ["ab|1",
"123456123455|6",
"123456789987654321|9",
"1234abcd|4",
"123456789123456789|9",
"123456789|9",
"12341234|4",
"123456781234|4",
"ab ba|1",
"abcdedcba|1",
"abcddcba|1",
"121212|2",
"123456789789456123|3",
"123456789456123|3",
"123456|6",
"123456123456|6",
"abcdef123456abcdef|6"]
for str in inputs:
length = len(str)
n = 0
for i in range(0,length):
if str[i] == "|":
s = str[:i]
for j in range(i+1,length):
n = n*10 + int(str[j])
length = len(s)
if length < n:
"%s|0" % str
divided = []
if n != 1 and n != length:
for i in range(0, length, n):
divided.append(s[i:i+n])
else:
if isPali(s):
print "%s|1" % str
else:
print "%s|0" % str
continue
flag = False
length = len(divided)
for i in range(0, length/2):
if isEqual(divided[i], divided[length - 1 - i]) != True:
print "%s|0" % str
flag = True
if flag == True:
continue
print "%s|1" % str |
7d187493194b49c93692f47ef1b6906e5dd5efea | QingxinL/MIT-6.00.1x | /ProblemSet/ps6/test.py | 758 | 3.875 | 4 | import string
print(type(string.ascii_lowercase))
def build_shift_dict(shift):
map_cipher = {}
# string.ascii_lowercase
# string.ascii_uppercase
# the key is the origin letter
# the value is the letter after
letters = string.ascii_uppercase + string.ascii_lowercase
for char in letters:
map_cipher[char] = ''
for key, value in map_cipher.items():
pos = letters.find(key)
after = pos + shift
if after > 25:
after -= 26
if key in string.ascii_uppercase:
map_cipher[key] = letters[after]
if key in string.ascii_lowercase:
map_cipher[key] = letters[after].lower()
return map_cipher
print(build_shift_dict(5))
print(build_shift_dict(0))
|
024972a13a4a8bd2e20ec9838e14028744747339 | sweetrain096/rain-s_python | /programmers/level 1/04_k번째수.py | 282 | 3.640625 | 4 | def solution(array, commands):
answer = []
for cnt in range(len(commands)):
i, j, k = commands[cnt]
answer.append(sorted(array[i - 1 : j])[k - 1])
return answer
result = solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]])
print(result) |
5c6d0377189e76affd18213cbe7b5e3414511f6a | gourav47/Let-us-learn-python | /83 Data Hiding.py | 1,433 | 4.34375 | 4 | class Test:
x=10 #static, visible from outside the class
__h=20 #static, hidden variable
print(Test.x)
#print(Test.__h)
#it will print x as 10 but will give error for __h as it gets hidden because of the prefix.
#here what python actually does is, it change the hidden variable name internally
#it adds underscore classname in prefix as _Test__h
#however we can access the __h inside the class itself as shown in below code:
#also we will try to access __h outside the class by the new name which gets change internally
class Test:
x=10 #static, visible from outside the class
__h=20 #static, hidden variable
@staticmethod
def f1():
print(Test.__h)
Test.f1()
print("outside class __h", Test._Test__h)
#technically we can say that there is nothing as private variable in python as we can access it somehow
############ Data Hiding for Insstance Variable #########
class Test:
x=10 #static, Visible from outside the class
__h=20 #static, hidden variable
def __init__(self):
self.__a=100 #private Instance variable
@staticmethod
def f1():
print(Test.__h)
obj=Test()
print(obj.__dict__)
print(obj._Test__a)
#Benifit of using double underscore is that we can use it in base class and derived class
#when we call the variable the it will not get conflict as it will appl the prefx of respective class name
|
7af22abde98a13b89bdcec4e50e56476b5b96bb5 | aseemchopra25/Integer-Sequences | /Central Binomial Coefficients/Central Binomial Coefficient.py | 713 | 3.5625 | 4 | ########################################
### Central Binomial Coefficient ###
########################################
#Example : 1, 2, 6, 20, 70, 252, 924, 3432 ....
#Formula : Check Wikepedia
def coeff(n,k):
c = [[0 for i in range(k+1)] for j in range(n+1)]
for i in range(n+1):
for j in range(min(i,k) + 1):
if(j == 0 or j == i):
c[i][j] = 1
else:
c[i][j] = c[i-1][j-1] + c[i-1][j]
return c[n][k]
find_val = int(input("Enter the nth value to find : "))
print(find_val, "th value in Central Binomial Coefficiecnt is : ", coeff(2*find_val, find_val))
|
a540865f500c0c5d28f1b2407d9a688ff0556c10 | jainilp/Python-Projects | /Ball and Block Game/block.py | 1,366 | 3.5625 | 4 | '''
Name: Jainil Patel
Drexel ID: jbp85
Purpose: This class was used to create the blocks, the user hits.
'''
#imports abstract base class drawable
from drawable import *
#Creates block class
class Block(Drawable):
#Initializes the variables passed in when creating a block object
def __init__(self,x,y):
super().__init__(x,y)
#draw is used to draw the block object, along with the border lines
def draw(self, surface):
#draws the block itself
pygame.draw.rect(surface, (0,43,205), [self._Drawable__x,self._Drawable__y, 15, 15])
#Draws four lines, (the border of the block)
pygame.draw.line(surface, (0,0,0), [self._Drawable__x,self._Drawable__y],(self._Drawable__x,self._Drawable__y+15))
pygame.draw.line(surface, (0,0,0), [self._Drawable__x,self._Drawable__y],[self._Drawable__x+15,self._Drawable__y])
pygame.draw.line(surface, (0,0,0), [self._Drawable__x+15,self._Drawable__y],[self._Drawable__x+15,self._Drawable__y+15])
pygame.draw.line(surface, (0,0,0), [self._Drawable__x,self._Drawable__y+15],[self._Drawable__x+15,self._Drawable__y+15])
#get_rect returns a rectangle surronding the block, and is used in determining if the ball and block intersect
def get_rect(self):
location = super().getLocation()
return pygame.Rect( [location[0], location[1], 15, 15] ) |
3aae8f998e169d2b8c52f07e7e3b8ad9a7e7fa27 | swarnanjali/pythonproject | /tr1h.py | 129 | 3.515625 | 4 | t = int(input(""))
s = 1
for i in range(t):
st = ""
for x in range(0,s):
st+="1 "
print(st.strip())
s+=2
|
2c3e73d7351bca34aee3094bb6804e00f51c7992 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day12/question2.py | 593 | 4.125 | 4 | """Count number of substrings that start and end with 1
if there is no such combination print 0
"""
def generate_substrings(string):
sub_strings = [
string[i:j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)
]
return sub_strings
def count_substrings(sub_string):
count = 0
for element in sub_string:
if element[0] == "1" and element[-1] == "1":
count += 1
return count
if __name__ == "__main__":
string = "1111"
print(generate_substrings(string))
print(count_substrings(generate_substrings(string))) |
eb0267553457299c22d7d2c0c0ef3705cd8e60ca | yzl232/code_training_leet_code | /Reconstruct Itinerary.py | 2,927 | 4.0625 | 4 | '''
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.
'''
class Solution(object):
def findItinerary(self, tickets):
d, ret ={}, [] #sort. d里面放更大的值. 因为递归, JFK在最外面了.. 要反一下.
for a, b in sorted(tickets)[::-1]: #题中提到要是最小的lexi order
if a not in d: d[a] = [] #Eulerian Path. 除了起点, 终点. 都是偶数的degree. Eulerian Circuit, 则全是偶数degree.
d[a].append(b) # 当stuck. 那么说明奇数的degree, 发现了一个终点了.
def helper(x):
while x in d and d[x]: helper(d[x].pop())
ret.append(x)
helper('JFK')
return ret[::-1]
''' 不理解的话, 打印下面的, 配合leetcode图, 就明白了
class Solution(object):
def findItinerary(self, tickets):
d, ret ={}, [] #sort. 反向. 因为后面用了pop.
for a, b in sorted(tickets)[::-1]: #题中提到要是最小的lexi order
if a not in d: d[a] = [] #Eulerian Path. 除了起点, 终点. 都是偶数的degree. Eulerian Circuit, 则全是偶数degree.
d[a].append(b)
def helper(x): # 当stuck. 那么说明奇数的degree, 发现了一个终点了.
while x in d and d[x]:
print x, d[x], ret
helper(d[x].pop())
ret.append(x)
print ret
helper('JFK')
return ret[::-1]
print Solution().findItinerary([["JFK", "A"], ["A", "C"], ["C", "D"], ["D", "B"], ["D", "A"], ["B", "C"], ["C", "JFK"], ["JFK", "D"]])
欧拉通路(Eulerian path):
将机场视为顶点,机票看做有向边,可以构成一个有向图。
通过图(无向图或有向图)中所有边且每边仅通过一次的通路称为欧拉通路,相应的回路称为欧拉回路。具有欧拉回路的图称为欧拉图(Euler Graph),具有欧拉通路而无欧拉回路的图称为半欧拉图。
''' |
c1817cf0fdc22dfedf1f0f003d55ce0bc7774409 | ekta1007/Hello-world | /Logistic_regression_python.py | 7,149 | 3.796875 | 4 | # Running a logistic regression in Python
#code source from http://blog.yhathq.com/posts/logistic-regression-and-python.html
import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m,1:])
for j in xrange(1, arrays[0].size):
out[j*m:(j+1)*m,1:] = out[0:m,1:]
return out
# 1 Load the data
# read the data in
df = pd.read_csv("http://www.ats.ucla.edu/stat/data/binary.csv")
# take a look at the dataset
print df.head()
# admit gre gpa rank
# 0 0 380 3.61 3
# 1 1 660 3.67 3
# 2 1 800 4.00 1
# 3 1 640 3.19 4
# 4 0 520 2.93 4
# rename the 'rank' column because there is also a DataFrame method called 'rank'
df.columns = ["admit", "gre", "gpa", "prestige"]
print df.columns
# array([admit, gre, gpa, prestige], dtype=object)
#2. Summary Statistics & Looking at the data
# summarize the data
print df.describe()
# admit gre gpa prestige
# count 400.000000 400.000000 400.000000 400.00000
# mean 0.317500 587.700000 3.389900 2.48500
# std 0.466087 115.516536 0.380567 0.94446
# min 0.000000 220.000000 2.260000 1.00000
# 25% 0.000000 520.000000 3.130000 2.00000
# 50% 0.000000 580.000000 3.395000 2.00000
# 75% 1.000000 660.000000 3.670000 3.00000
# max 1.000000 800.000000 4.000000 4.00000
# take a look at the standard deviation of each column
print df.std()
# admit 0.466087
# gre 115.516536
# gpa 0.380567
# prestige 0.944460
# frequency table cutting presitge and whether or not someone was admitted
print pd.crosstab(df['admit'], df['prestige'], rownames=['admit'])
# prestige 1 2 3 4
# admit
# 0 28 97 93 55
# 1 33 54 28 12
# plot all of the columns
df.hist()
pl.show()
# 3. Dummy variables
# dummify rank
dummy_ranks = pd.get_dummies(df['prestige'], prefix='prestige')
print dummy_ranks.head()
# prestige_1 prestige_2 prestige_3 prestige_4
# 0 0 0 1 0
# 1 0 0 1 0
# 2 1 0 0 0
# 3 0 0 0 1
# 4 0 0 0 1
# create a clean data frame for the regression
cols_to_keep = ['admit', 'gre', 'gpa']
data = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])
print data.head()
# admit gre gpa prestige_2 prestige_3 prestige_4
# 0 0 380 3.61 0 1 0
# 1 1 660 3.67 0 1 0
# 2 1 800 4.00 0 0 0
# 3 1 640 3.19 0 0 1
# 4 0 520 2.93 0 0 1
# manually add the intercept
data['intercept'] = 1.0
#4. Performing the regression
train_cols = data.columns[1:]
# Index([gre, gpa, prestige_2, prestige_3, prestige_4], dtype=object)
logit = sm.Logit(data['admit'], data[train_cols])
# fit the model
result = logit.fit()
#5. Interpreting the results
# cool enough to deserve it's own gist
print result.summary()
# look at the confidence interval of each coeffecient
print result.conf_int()
# 0 1
# gre 0.000120 0.004409
# gpa 0.153684 1.454391
# prestige_2 -1.295751 -0.055135
# prestige_3 -2.016992 -0.663416
# prestige_4 -2.370399 -0.732529
# intercept -6.224242 -1.755716
#6. Odds ratio
# odds ratios only
print np.exp(result.params)
# gre 1.002267
# gpa 2.234545
# prestige_2 0.508931
# prestige_3 0.261792
# prestige_4 0.211938
# intercept 0.018500
# odds ratios and 95% CI
params = result.params
conf = result.conf_int()
conf['OR'] = params
conf.columns = ['2.5%', '97.5%', 'OR']
print np.exp(conf)
# 2.5% 97.5% OR
# gre 1.000120 1.004418 1.002267
# gpa 1.166122 4.281877 2.234545
# prestige_2 0.273692 0.946358 0.508931
# prestige_3 0.133055 0.515089 0.261792
# prestige_4 0.093443 0.480692 0.211938
# intercept 0.001981 0.172783 0.018500
#7. Digging deeper
# instead of generating all possible values of GRE and GPA, we're going
# to use an evenly spaced range of 10 values from the min to the max
gres = np.linspace(data['gre'].min(), data['gre'].max(), 10)
print gres
# array([ 220. , 284.44444444, 348.88888889, 413.33333333,
# 477.77777778, 542.22222222, 606.66666667, 671.11111111,
# 735.55555556, 800. ])
gpas = np.linspace(data['gpa'].min(), data['gpa'].max(), 10)
print gpas
# array([ 2.26 , 2.45333333, 2.64666667, 2.84 , 3.03333333,
# 3.22666667, 3.42 , 3.61333333, 3.80666667, 4. ])
# enumerate all possibilities
combos = pd.DataFrame(cartesian([gres, gpas, [1, 2, 3, 4], [1.]]))
#combos = pd.DataFrame([gres, gpas, [1, 2, 3, 4], [1.]])
# recreate the dummy variables
combos.columns = ['gre', 'gpa', 'prestige', 'intercept']
dummy_ranks = pd.get_dummies(combos['prestige'], prefix='prestige')
dummy_ranks.columns = ['prestige_1', 'prestige_2', 'prestige_3', 'prestige_4']
# keep only what we need for making predictions
cols_to_keep = ['gre', 'gpa', 'prestige', 'intercept']
combos = combos[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])
# make predictions on the enumerated dataset
combos['admit_pred'] = result.predict(combos[train_cols])
print combos.head()
# gre gpa prestige intercept prestige_2 prestige_3 prestige_4 admit_pred
# 0 220 2.260000 1 1 0 0 0 0.157801
# 1 220 2.260000 2 1 1 0 0 0.087056
# 2 220 2.260000 3 1 0 1 0 0.046758
# 3 220 2.260000 4 1 0 0 1 0.038194
# 4 220 2.453333 1 1 0 0 0 0.179574
8.
|
664487a49ba571f7bd77744fab3fa6f6de554f9a | pwicks86/adventofcode2020 | /13/2.py | 552 | 3.53125 | 4 | from math import gcd
import math
with open("input.txt") as f:
data = f.readlines()
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
busses = [(int(b), ind) for ind, b in enumerate(data[1].split(",")) if b != "x"]
base_bus = busses[0]
base_amt = 0
n = 1
mult = base_bus[0]
for bus in busses[1:]:
while True:
base_mult = base_amt + mult * n
if (base_mult + bus[1]) % bus[0] == 0:
base_amt = base_mult
mult = lcm(mult, bus[0])
n = 1
break
n += 1
print(base_mult) |
31bcaef5cfe9d0e3a5280ce1a4bc65e63bef46c2 | StardustGogeta/Math-Programming | /Python/Unfinished/Euler/187/sieve.py | 1,428 | 3.515625 | 4 | import math, time
##def prime(n):
## for d in range(2, math.floor(math.sqrt(n))+1):
## if not n % d: return False
## return True
##
##def primeSieve(N):
## allNums = range(2, N)
## primes = []
## for n in allNums:
## passing = True
## for p in primes:
## if p > math.sqrt(n):
## break
## if not n % p:
## passing = False
## break
## if passing:
## primes.append(n)
## return primes
# O(n) versus O(n^2) in other primality checks above
def efficientSieve(N):
allNums = list(range(2, N))
primes = []
for i in range(len(allNums)):
n = allNums[i]
if n:
for j in range(i+n, len(allNums), n):
allNums[j] = 0
return list(filter(lambda x: x, allNums))
start = time.perf_counter()
N = 10**8
primes = efficientSieve(N//2)
compos = set()
for i in range(len(primes)):
for j in range(i, len(primes)):
mul = primes[i]*primes[j]
if mul < N: compos.add(mul)
else: break
print(len(compos), time.perf_counter()-start)
##n = 10**6
##start = time.perf_counter()
##p = list(filter(prime, range(2, n)))
##print(time.perf_counter()-start)
##
##start = time.perf_counter()
##p2 = primeSieve(n)
##print(time.perf_counter()-start, p2==p)
##
##start = time.perf_counter()
##p3 = efficientSieve(n)
##print(time.perf_counter()-start, p3==p2)
|
a120c20ade6ab2868a5df51baac30b91eb0b4ab3 | EMIAOZANG/leetcode_questions | /285_inorder_successor_in_BST/main.py | 1,476 | 4.1875 | 4 | '''
how to PASS BY REFERENCE using python:
just use an mutable object, e.g. if you want to pass a reference, wrap the object in a list, and then pass the list as a function, then modify the object by list subsctription
IDEA:
Consider 2 cases:
1) if p has rightChild: then the successor is the leftmost node in the right subtree
2) else: then the successor is the nearest parent along the search path who has right child
thus we only need to record the nearest parent whose rightChild != None
Time Complexity: O(h)
Space Complexity: O(1)
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findInBST(self, root, p, last_p):
if root == None:
return None
if root.val == p.val:
return root
elif root.val > p.val:
last_p[0] = root
return self.findInBST(root.left,p,last_p)
else:
return self.findInBST(root.right,p,last_p)
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
successor = [None]
if p.right != None:
successor[0] = p.right
while successor[0].left != None:
successor[0] = successor[0].left
else:
self.findInBST(root,p,successor)
return successor[0]
|
5d801eae8b52f2e4b26b81bd0f972da93719a68b | xzpjerry/learning | /Coding/playground/general/recurrsive/recurrsively_reverse_str_join.py | 508 | 3.953125 | 4 | #!/usr/bin/env python3
'''
Author: Zhipeng Xie
Topic:
Effect:
'''
import re
def reverseStr(astr):
if len(astr) == 1:
return astr
else:
return astr[1:] + astr[0]
def isPalindrome(astr):
astr = ''.join(re.split(r'[\s\'\;\.\-]', astr)).upper()
print(astr)
if len(astr) <= 1:
return True
if astr[0] == astr[-1]:
return isPalindrome(astr[1:-1])
return False
print(isPalindrome('Go hang a salami; I\'m a lasagna hog.'))
print(isPalindrome('Wassamassaw')) |
406ad445384ed1092863f51f1af4686236e91fde | mattyr3200/Dice-Game | /Game.py | 7,499 | 3.9375 | 4 | from PlayerClass import Player
import sys
import random
import re
def add_new_player():
with open('Players.txt', 'a+') as player_file:
new_player = Player((input("username:\n")), "")
while True:
new_player.password = input("Password:\n")
if len(new_player.password) not in range(6, 12):
print("Make sure your password is at least 6 and less than 12 letters")
elif re.search('[0-9]', new_player.password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]', new_player.password) is None:
print("Make sure your password has a capital letter in it")
else:
break
if (new_player.name + " " + new_player.password) in open('Players.txt').read():
print("sorry that username has been taken")
sys.exit()
player_file.write(new_player.name)
player_file.write(" ")
player_file.write(new_player.password)
player_file.write("\n")
main_menu()
def check_player_1():
player_1_name = input("player 1, please enter your username:\n")
player_1_password = input("player 1, please enter your password: \n")
if (player_1_name + " " + player_1_password) in open('Players.txt').read():
print("you have been cleared")
print("welcome back", player_1_name)
check_player_2(player_1_name, player_1_password)
else:
print("those credentials don't exist sadly")
decision = input("would you like to create a new player(Y/N): \n")
if decision.lower() == "y":
add_new_player()
elif decision.lower() == "n":
sys.exit()
else:
print("taking you back to main menu")
main_menu()
def check_player_2(player_1_name, player_1_pass):
player_2_name = input("player 2, please enter your username:\n")
player_2_password = input("player 2, please enter your password: \n")
if (player_2_name, player_2_password) == (player_1_name, player_1_pass):
print("sorry that is the same as player 1 credentials")
else:
if (player_2_name + " " + player_2_password) in open('Players.txt').read():
print("you have been cleared")
print("welcome back", player_2_name)
round_1(player_1_name, player_2_name)
else:
print("those credentials don't exist sadly")
decision = input("would you like to create a new player(Y/N): \n")
if decision.lower() == "y":
add_new_player()
elif decision.lower() == "n":
sys.exit()
else:
print("taking you back to main menu")
main_menu()
def round_1(player_1, player_2):
round_total = 0
scores_1 = []
scores_2 = []
player_1_total = 0
player_2_total = 0
for rounds in range(1,6):
print("\nwelcome to round", rounds, "\n")
for y in range(2):
dice = random.randint(1, 6)
print(player_1, "round", rounds, ", die", y + 1)
print(dice, "\n")
round_total += dice
scores_1.append(dice)
player_1_total += dice
if len(scores_1) == 2:
if scores_1[0] == scores_1[1]:
print("welcome too the bonus round")
extra_die = random.randint(1, 6)
print("your extra die scored you an extra", extra_die, player_1)
player_1_total += extra_die
round_total += extra_die
else:
print("no bonus round")
if round_total % 2 == 0:
print("Well Done, your number was even and has gained 10 points")
player_1_total += 10
round_total = 0
else:
if (player_1_total - 5) < 0:
player_1_total = 0
else:
print("Unlucky, your number was odd so you loose 5 points")
player_1_total -= 5
round_total = 0
scores_1 = []
print(player_1, "round", rounds, " total is", player_1_total)
input()
for x in range(2):
dice = random.randint(1, 6)
print(player_2, "round", rounds, ", die", x + 1)
print(dice, "\n")
scores_2.append(dice)
player_2_total += dice
if len(scores_2) == 2:
if scores_2[0] == scores_2[1]:
print("welcome too the bonus round")
extra_die = random.randint(1, 6)
print("your extra die scored you an extra", extra_die, player_2)
player_2_total += extra_die
round_total += extra_die
else:
print("no bonus round")
if round_total % 2 == 0:
print("Well Done, your number was even and has gained 10 points")
player_2_total += 10
round_total = 0
else:
if (player_2_total - 5) < 0:
player_2_total = 0
else:
print("Unlucky, your number was odd so you loose 5 points")
player_2_total -= 5
round_total = 0
scores_2 = []
print(player_2, "round", rounds, " total is", player_2_total)
input()
print(player_1, "round", rounds, " total is", player_1_total)
print(player_2, "round", rounds, " total is", player_2_total)
winner(player_1_total, player_2_total, player_1, player_2)
def winner(player_1_total, player_2_total, player_1, player_2):
if player_1_total > player_2_total:
print("well done", player_1, "you Win")
with open("leaderboard.txt", "a+")as the_leaders:
the_leaders.write(player_1)
the_leaders.write(" ")
the_leaders.write(str(player_1_total))
the_leaders.write("\n")
else:
print("well done ", player_2, "you Win")
with open("leaderboard.txt", "a+")as the_leaders:
the_leaders.write(player_2)
the_leaders.write(" ")
the_leaders.write(str(player_2_total))
the_leaders.write("\n")
leaderboard()
def get_score(element):
return element[-3::]
def leaderboard():
names = []
top_5 = []
with open("leaderboard.txt", "r") as leaders:
for lines in leaders:
names.append(lines[0:-1])
names.sort(key=get_score, reverse=True)
for y in range(5):
top_5.append(names[y])
top_5_leaders(top_5)
def top_5_leaders(top_5):
print("These are the top 5 leaders:")
for lead in range(5):
print(lead + 1, ".", top_5[lead])
def main_menu():
print("Main Menu")
print("1.Play Game")
print("2.Add New Player")
print("3.Leaderboard")
choice()
def choice():
user_choice = input("please enter you choice:\n")
if user_choice == "1":
check_player_1()
elif user_choice == "2":
add_new_player()
elif user_choice == "3":
leaderboard()
else:
print("sorry didn't get that input can you please repeat")
choice()
if __name__ == "__main__":
main_menu()
|
210906e7cc0a4c955305425b98d76a76a52d80e3 | tfarnecim/BenchmarkApp | /BenchmarkApp/LINEAR - SEM ORDENAÇÃO.py | 848 | 3.6875 | 4 | import time
import random
# Adicionar as funções de Ordenamento e Pesquisa.
def SemOrdenacao(lista):
pass
def BuscaLinear(lista, item):
comp = 0
posicao = -1
for i in lista:
posicao+=1
comp += 1
if(i == item):
break
print("comparacoes da busca: %d"%(comp))
return posicao
# Programa principal
def main():
lista = list(range(1, 15000+1))
random.shuffle(lista)
inicio = time.time()
posicao = BuscaLinear(lista, 7500)
print("Posicao do item eh %d"%(posicao-2))
fim = time.time()
print("Tempo final da busca: %f"%(fim))
time_BL = fim-inicio
print("O tempo total da busca foi: %f"%(time_BL))
Tempototal =time_BL
print("O tempo total foi: %f" %(Tempototal))
if (__name__ == "__main__"):
main()
|
b5cf73ac080d46588d00ce063156842120d49f2b | ceciless/python | /sTD4/MulListe.py | 2,690 | 4.4375 | 4 | # -*-coding:Latin-1 -*
# etude multiplication et addition de liste point point
class ListMul(list):
# constructeur
def __init__(self,Maliste):
super(ListMul,self).__init__(Maliste)
#ou encore
#list.__init__(self,Maliste)
# ou encore
#self.extend(Maliste) # li.extend(["two", "elements"]) concatne les lments d'une liste.
#ou encore
#for k in Maliste:
# self.append(k)
# methode multiplication point point
# ici surcharge de l'oprateur de multiplication __mul__(self,other):
# version 1 : approche classique
"""def __mul__(self,other):
result = []
for k in range(len(self)):
val1 = self[k]
val2 = other[k]
#print val1, val2
result.append(val1*val2)
return result
"""
#version 2 : une version un peu plus condense
def __mul__(self,other):
return [self[k]*other[k] for k in range(len(self))]
# version 3 : version condense avec lambda et map
#def __mul__(self,other):
# return map(lambda x,y:x*y, self,other)
# surcharge de l'addition
def __add__(self, other):
return [self[k]+other[k] for k in range(len(self))]
# surcharge de la soustraction
def __sub__(self, other):
return [self[k]-other[k] for k in range(len(self))]
##############################################################################################
# methode main (test unitaire,...)
if __name__ == "__main__":
print("Test multiplication de liste")
listeA = ListMul([1,2,3,4,5])
listeB = ListMul([6,7,8,9,0])
listeC = ListMul([-10,11,-12,13,-14])
print("Les listes: ")
print listeA
print listeB
print listeC
print("Multiplication: ")
print listeA*listeB # ici on utilise la surcharge de la multiplication! on RE-dfini la mthode de multiplication de python
#print listeC*listeA*listeB # probleme !
#print (listeC*listeA)*listeB # probleme !
print listeC*(listeA*listeB) # OK !
print("Addition: ")
print listeA+listeB
#print listeC+listeA+listeB # probleme ! concatenation de liste
#print (listeC+listeA)+listeB # probleme ! concatenation de liste
print listeC+(listeA+listeB) # OK !
print("Soustraction: ")
print listeA-listeB
#print listeC-listeA-listeB # probleme !
#print (listeC-listeA)-listeB # probleme !
print listeC-(listeA+listeB) # OK !
|
4b44b9abfe6217c6df5e41a434c56100ef2aac0d | 15194779206/practice_tests | /A_Project/Student_project/student_controller.py | 3,627 | 3.640625 | 4 | '''
class StudentManagerController:
"""
学生逻辑控制器
"""
def __init__(self):
self.__stu_list = []
@property
def stu_list(self): #做成只读属性
return self.__stu_list
def add_student(self, stu):
stu.id =self.__generate_id()
self.__stu_list.append(stu)
def __generate_id(self):
# :return:id 自动生成
if len(self.__stu_list) >0:
id = self.__stu_list[-1].id+1
else:
id = 1
return id
def order_by_score(self): #程序排序
#创建新列表:目的--不影响原有列表
new_list = self.__stu_list[:]
for r in range(len(new_list)-1):
for c in range(r+1,len(new_list)):
if new_list[r].score >new_list[c].score:
new_list[r],new_list[c] =new_list[c],new_list[r]
return new_list
def remove_student(self, id):
"""
删除学生
:param id:
:return:
"""
for item in self.stu_list:
if item.id ==id:
self.stu_list.remove(item)
return True
return False
def update_student(self,stu):
"""
修改学生信息
:return:
"""
for item in self.stu_list:
if item.id ==stu.id:
item.name = stu.name
item.age = stu.age
item.score = stu.score
return True
return False
'''
from A_Project.Student_project.student_model import *
class StudentManagerController:
def __init__(self):
self.__stu_list = [] #学生列表
# self.mo = StudentModel()
@property
def stu_list(self): #获取列表的只读属性
return self.__stu_list
def __generate_id(self):
"""
编号生成
:return:自增id
"""
# if len(self.__stu_list) == 0:
# id = 1
# else:
# id = self.__stu_list[-1].id + 1
# return id
#或是可以简化写
return 1 if len(self.__stu_list) == 0 else self.__stu_list[-1].id + 1
def add_student(self, stu): #添加学生方法
stu.id = self.__generate_id()
self.__stu_list.append(stu)
def remove_student(self,id): #删除学生
for items in self.stu_list:
if items.id == id:
self.stu_list.remove(items)
return True
return False
# print("删除成功")
# else:
# print("删除失败")
def update_student(self,id): #修改学生
for stuID in self.stu_list:
if id in stuID:
print("cunzai")
else:
print("不存在")
def order_by_score(self): #根据成绩排序
list_stu = self.__stu_list[:]#形成新的列表不对原列表操作
for x in range(len(list_stu)-1):
for y in range(x+1,len(list_stu)):
if list_stu[x].score > list_stu[y].score:
list_stu[x],list_stu[y] =list_stu[y],list_stu[x]
return list_stu
#错误思想
# for item in self.__stu_list[:]:
# if item[0].score > item[1].score:
# item[0],item[1] = item[1],item[0]
# c1 = StudentManagerController()
# c1.add_student(StudentModel('zs',11,80))
# c1.add_student(StudentModel('ls',15,90))
# for i in c1.stu_list:
# print(i.id,i.name,i.age,i.score)
|
ef4aa9f32e31f4e105555ea629e699c2c3be28b9 | tamimio/digdes | /py_test/test_3_encrypt.py | 827 | 3.828125 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
symb=' .,!?:;"-+=)(*&^%$#@[]{}\/|'
offset = int (input ("Input offset -> "))
orig_txt = input("Input text -> ")
orig_txt=orig_txt.lower()
enc_txt=""
dec_txt=""
print("Offset: ", offset)
print ("Original text: ", orig_txt)
for i in range(0, len(orig_txt)):
if symb.find(orig_txt[i]) == -1 : # for better encryption # comment this line to encrypt w/ saving spaces and other symbols (as in example)
index = (alphabet.find(orig_txt[i]) + offset) % (len(alphabet)-1)
enc_txt = enc_txt[:i] + alphabet[index] + enc_txt[i+1:]
print("Encrypted text: ", enc_txt)
for i in range(0, len(enc_txt)):
index = (alphabet.find(enc_txt[i]) - offset) % (len(alphabet)-1)
dec_txt = dec_txt[:i] + alphabet[index] + dec_txt[i+1:]
print("Decrypted text: ", dec_txt)
|
458044d826ad100477969ad1b392d7c4fadb3eac | maeng2418/algorithm | /15-2_그래프_탐색.py | 322 | 3.6875 | 4 | def graph_search(g, start):
if len(g[start]) == 0:
return
for i in range(len(g[start])):
print(start, ' -> ', g[start][i])
for i in range(len(g[start])):
graph_search(g, g[start][i])
g = {
1 : [2, 3],
2 : [4, 5],
3 : [],
4 : [],
5 : []
}
graph_search(g, 1) |
12a70b68881d3f1cdb83d235678a9935f76bb702 | huhudaya/leetcode- | /LeetCode/355.设计推特.py | 5,998 | 3.859375 | 4 | # 355涉及推特.py
'''
'''
# 例子
'''
class Twitter {
/** user 发表一条 tweet 动态 */
public void postTweet(int userId, int tweetId) {}
/** 返回该 user 关注的人(包括他自己)最近的动态 id,
最多 10 条,而且这些动态必须按从新到旧的时间线顺序排列。*/
public List<Integer> getNewsFeed(int userId) {}
/** follower 关注 followee,如果 Id 不存在则新建 */
public void follow(int followerId, int followeeId) {}
/** follower 取关 followee,如果 Id 不存在则什么都不做 */
public void unfollow(int followerId, int followeeId) {}
}
Twitter twitter = new Twitter();
twitter.postTweet(1, 5);
// 用户 1 发送了一条新推文 5
twitter.getNewsFeed(1);
// return [5],因为自己是关注自己的
twitter.follow(1, 2);
// 用户 1 关注了用户 2
twitter.postTweet(2, 6);
// 用户2发送了一个新推文 (id = 6)
twitter.getNewsFeed(1);
// return [6, 5]
// 解释:用户 1 关注了自己和用户 2,所以返回他们的最近推文
// 而且 6 必须在 5 之前,因为 6 是最近发送的
twitter.unfollow(1, 2);
// 用户 1 取消关注了用户 2
twitter.getNewsFeed(1);
// return [5]
'''
# 面向对象
'''
class Twitter {
private static int timestamp = 0;
private static class Tweet {}
private static class User {}
/* 还有那几个 API 方法 */
public void postTweet(int userId, int tweetId) {}
public List<Integer> getNewsFeed(int userId) {}
public void follow(int followerId, int followeeId) {}
public void unfollow(int followerId, int followeeId) {}
}
class Tweet {
private int id;
private int time;
private Tweet next;
// 需要传入推文内容(id)和发文时间
public Tweet(int id, int time) {
this.id = id;
this.time = time;
this.next = null;
}
}
// static int timestamp = 0
class User {
private int id;
public Set<Integer> followed;
// 用户发表的推文链表头结点
public Tweet head;
public User(int userId) {
followed = new HashSet<>();
this.id = userId;
this.head = null;
// 关注一下自己
follow(id);
}
public void follow(int userId) {
followed.add(userId);
}
public void unfollow(int userId) {
// 不可以取关自己
if (userId != this.id)
followed.remove(userId);
}
public void post(int tweetId) {
// 注意这里的timestamp不用传,timestamp是一个静态变量
Tweet twt = new Tweet(tweetId, timestamp);
timestamp++;
// 将新建的推文插入链表头
// 越靠前的推文 time 值越大
twt.next = head;
head = twt;
}
}
class Twitter {
private static int timestamp = 0;
private static class Tweet {...}
private static class User {...}
// 我们需要一个映射将 userId 和 User 对象对应起来
private HashMap<Integer, User> userMap = new HashMap<>();
/** user 发表一条 tweet 动态 */
public void postTweet(int userId, int tweetId) {
// 若 userId 不存在,则新建
if (!userMap.containsKey(userId))
userMap.put(userId, new User(userId));
User u = userMap.get(userId);
u.post(tweetId);
}
/** follower 关注 followee */
public void follow(int followerId, int followeeId) {
// 若 follower 不存在,则新建
if(!userMap.containsKey(followerId)){
User u = new User(followerId);
userMap.put(followerId, u);
}
// 若 followee 不存在,则新建
if(!userMap.containsKey(followeeId)){
User u = new User(followeeId);
userMap.put(followeeId, u);
}
userMap.get(followerId).follow(followeeId);
}
/** follower 取关 followee,如果 Id 不存在则什么都不做 */
public void unfollow(int followerId, int followeeId) {
if (userMap.containsKey(followerId)) {
User flwer = userMap.get(followerId);
flwer.unfollow(followeeId);
}
}
/** 返回该 user 关注的人(包括他自己)最近的动态 id,
最多 10 条,而且这些动态必须按从新到旧的时间线顺序排列。*/
public List<Integer> getNewsFeed(int userId) {
// 需要理解算法,见下文
}
}
'''
from collections import defaultdict
from typing import List
import heapq
class Tweet:
def __init__(self, tweetId, timestamp):
self.id = tweetId
self.timestamp = timestamp
self.next = None
def __lt__(self, other):
return self.timestamp > other.timestamp
class Twitter:
def __init__(self):
self.followings = defaultdict(set)
self.tweets = defaultdict(lambda: None)
self.timestamp = 0
def postTweet(self, userId: int, tweetId: int) -> None:
self.timestamp += 1
tweet = Tweet(tweetId, self.timestamp)
tweet.next = self.tweets[userId]
self.tweets[userId] = tweet
def getNewsFeed(self, userId: int) -> List[int]:
tweets = []
heap = []
tweet = self.tweets[userId]
if tweet:
heap.append(tweet)
for user in self.followings[userId]:
tweet = self.tweets[user]
if tweet:
heap.append(tweet)
heapq.heapify(heap)
while heap and len(tweets) < 10:
head = heapq.heappop(heap)
tweets.append(head.id)
if head.next:
heapq.heappush(heap, head.next)
return tweets
def follow(self, followerId: int, followeeId: int) -> None:
if followerId == followeeId:
return
self.followings[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
if followerId == followeeId:
return
self.followings[followerId].discard(followeeId) |
eea969191ab19b1450c0d732e7953c5984400df7 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/119_v2/xmas.py | 493 | 4.09375 | 4 | def generate_xmas_tree(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
star = "*"
max_length = rows * 2 -1
levels = [((row * 2 -1) * star).center(max_length) for row in range(1, rows +1)]
return "\n".join(levels)
# if __name__ == "__main__":
# print(generate_xmas_tree()) |
80b910c4790d71ac0d402eed0af17493bd1ce207 | EHOTIK911/Inform-EGE | /25/25.18.py | 740 | 3.515625 | 4 | """
(№ 3982) Найдите все натуральные числа, N, принадлежащие отрезку [100 000 000; 300 000 000],
которые можно представить в виде N = 2**m•7**n, где m – нечётное число, n – чётное число.
В ответе запишите все найденные числа в порядке возрастания, а справа от каждого числа – сумму m+n.
"""
a = []
for i in range(100000000, 300000000+1):
b = []
for m in range(1,30000):
if m % 2 != 0:
for n in range(1,30000):
if n % 2 == 0:
if i == (2**m)*(7**n):
print(i, m+n)
|
bca7f346b2ada7aabc8b6792e93a90d09ea37ce5 | esphill/course | /PA5/crack.py | 6,946 | 3.96875 | 4 | # CSE 130: Programming Assignment 5
# crack.py
# Jay Ceballos
# A09338030
# jjceball@ieng6.ucsd.edu
from misc import *
import crypt
def load_words(filename,regexp):
"""Load the words from the file filename that match the regular
expression regexp. Returns a list of matching words in the order
they are in the file."""
#>>> from crack import *
#>>> load_words("words",r"^[A-Z].{2}$")
#['A-1', 'AAA', 'AAE', ...]
#>>> load_words("words",r"^xYx.*$")
#[]
final = []
file1 = open(filename)
pattern = re.compile(regexp)
for word in file1.readlines():
word = word.strip()
if pattern.match(word):
final.append(word)
return final
def transform_reverse(str):
"""Return a list with the original string and the reversal of the original
string."""
#>>> transform_reverse("Moose")
#['Moose','esooM']
reversed_l = [str]
rString = str[::-1]
reversed_l[len(reversed_l):] = [rString]
return reversed_l
def transform_capitalize(str):
"""Return a list of all the possible ways to capitalize the input string.
"""
#>>> transform_capitalize("foo")
#['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
placeh = str.lower()
words = [placeh]
j = 0
for element in words:
for character in element:
j = 0
while (j < len(element)):
s = element
s = s[:j] + s[j].upper() + s[j+1:]
if (s not in words): words.append(s)
j += 1
return words
def transform_digits(str):
"""Return a list of all possible ways to replace letters with similar
looking digits according to the following mappings. This should be done
without regard to the capitalization of the input string, however when a
character is not replaced with a digit, it's capitalization should be
preserved."""
#>>> transform_digits("Bow")
#['Bow', 'B0w', '6ow', '60w', '8ow', '80w']
placeh = str
words = [placeh]
j = 0
for element in words:
for character in element:
while(j < len(element)):
s = element
if (s[j] == 'o' or s[j] == 'O'):
s = s[:j] + '0' + s[j+1:]
elif (s[j] == 'z' or s[j] == 'Z'):
s = s[:j] + '2' + s[j+1:]
elif (s[j] == 'a' or s[j] == 'A'):
s = s[:j] + '4' + s[j+1:]
elif (s[j] == 'b'):
s = s[:j] + '6' + s[j+1:]
elif (s[j] == 'B'):
s = s[:j] + '8' + s[j+1:]
if (s not in words): words.append(s)
s = s[:j] + '6' + s[j+1:]
elif (s[j] == 'i' or s[j] == 'I'):
s = s[:j] + '1' + s[j+1:]
elif (s[j] == 'l' or s[j] == 'L'):
s = s[:j] + '1' + s[j+1:]
elif (s[j] == 'e' or s[j] == 'E'):
s = s[:j] + '3' + s[j+1:]
elif (s[j] == 's' or s[j] == 'S'):
s = s[:j] + '5' + s[j+1:]
elif (s[j] == 't' or s[j] == 'T'):
s = s[:j] + '7' + s[j+1:]
elif (s[j] == 'g' or s[j] == 'G'):
s = s[:j] + '9' + s[j+1:]
elif (s[j] == 'q' or s[j] == 'Q'):
s = s[:j] + '9' + s[j+1:]
else: pass
if (s not in words): words.append(s)
j = j + 1
j = 0
return words
def check_pass(plain,enc):
"""Check to see if the plaintext plain encrypts to the encrypted
text enc"""
#>>> check_pass("asarta","IqAFDoIjL2cDs")
#True
#>>> check_pass("foo","AAbcdbcdzyxzy")
#False
return crypt.crypt(plain,enc[:2]) == enc
def load_passwd(filename):
"""Load the password file filename and returns a list of
dictionaries with fields "account", "password", "UID", "GID",
"GECOS", "directory", and "shell", each mapping to the
corresponding field of the file."""
#>>> load_passwd("passwd")
#[{'account': 'root', 'shell': '/bin/bash', 'UID': 0, 'GID': 0, 'GECOS':
#'Corema Latterll', 'directory': '/home/root', 'password': 'VgzdTLne0kfs6'},
#... ]
openFile = open(filename,'r');
passwords = []
for s in openFile:
list1 = ['account','password','UID','GID','GECOS','directory','shell']
list2 = re.split('[:]',s)
dictionary = make_dict(list1,list2)
passwords.append(dictionary)
return passwords
def crack_pass_file(fn_pass,words,out):
"""Crack as many passwords in file fn_pass as possible using words
in the file words"""
#>>> crack_pass_file("passwd","words","out")
#Several minutes pass...
#Ctrl-C
#Traceback (most recent call last):
#...
#KeyboardInterrupt
passwords = load_passwd(fn_pass)
output = open(out,'w')
cracked = []
for passw in passwords:
if ((passw['account'] != '\n') and (passw['password'] != None)):
account = passw['account']
pw = passw['password']
successful_crack = ''
success_or_fail = False
possibles = open(words,'r')
for poss in possibles:
if(success_or_fail == True): break
poss = poss.rstrip()
poss = poss.lower()
if (len(poss) > 8 or len(poss) < 6): pass
else:
reverseList = transform_reverse(poss)
for reverse in reverseList:
success_or_fail = check_pass(reverse,pw)
if(success_or_fail == True):
successful_crack = reverse
cracked.append(account)
output.write(account + '=' + successful_crack + '\n')
output.flush()
break
else: pass
passwords = load_passwd(fn_pass)
for passw in passwords:
if ((passw['account'] != '\n') and (passw['password'] != None)):
if (passw['account'] in cracked): pass
else:
account = passw['account']
pw = passw['password']
successful_crack = ''
success_or_fail = False
possibles = open(words,'r')
j = 479625
for poss in possibles:
print(j)
j = j - 1
if(success_or_fail == True): break
poss = poss.rstrip()
poss = poss.lower()
if (len(poss) > 8 or len(poss) < 6): pass
else:
reverseList = transform_reverse(poss)
for reverse in reverseList:
if (success_or_fail == True): break
digitList = transform_digits(reverse)
for digit in digitList:
success_or_fail = check_pass(digit,pw)
if (success_or_fail == True):
successful_cracked = digit
cracked.append(account)
print(account + '=' + successful_crack + '\n')
output.write(account + '=' + successful_crack + '\n')
output.flush()
break
else: pass |
2d8fb9f3a10c7620447f7ea68ff6f2680064386c | Tijzz/ComptencyAnalysisTool | /SpeechToText.py | 3,780 | 3.59375 | 4 | # importing libraries
import speech_recognition as sr
import os
import csv
from pydub import AudioSegment
from pydub.silence import split_on_silence
from pydub.silence import detect_nonsilent
from datetime import datetime
from playsound import playsound
# Adjust target amplitude
def match_target_amplitude(sound, target_dBFS):
change_in_dBFS = target_dBFS - sound.dBFS
return sound.apply_gain(change_in_dBFS)
# a function that splits the audio file into chunks
# and applies speech recognition
def get_large_audio_transcription(path, filename, r):
"""
Splitting the large audio file into chunks
and apply speech recognition on each of these chunks
"""
# open the audio file using Pydub
sound = AudioSegment.from_wav(path)
# normalize audio_segment to -20dBFS
normalized_sound = match_target_amplitude(sound, -10.0)
print("Length of audio_segment = {} seconds".format(len(normalized_sound) / 1000))
# Print detected non-silent chunks, which in our case would be spoken words.
timestamp_chunks = detect_nonsilent(normalized_sound, min_silence_len=500, silence_thresh=-33, seek_step=1)
print(timestamp_chunks)
# Convert ms to seconds
timestamps = []
for timestamp_chunk in timestamp_chunks:
timestamps.append([timestamp__single_chunk / 1000 for timestamp__single_chunk in timestamp_chunk])
print(timestamps)
print("Finished timestamps:", filename, datetime.now().strftime("%H:%M:%S"))
folder_name = "chunks-" + filename
# create a directory to store the audio chunks
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
whole_text = ""
text_folder_name = "text-translation"
if not os.path.isdir(text_folder_name):
os.mkdir(text_folder_name)
if not os.path.isfile("text-translation/translation_file.csv"):
open("text-translation/translation_file.csv", "x")
text_file = open("text-translation/translation_file.csv", 'a', newline='')
csv_writer = csv.writer(text_file)
# print("Amount of chunks:", len(chunks))
print("TIMESTAMPS LIST LENGTH", len(timestamps))
# Process each chunk
for i, audio_chunk in enumerate(timestamps):
# Export audio chunk and save it in the `folder_name` directory.
audio = sound[audio_chunk[0]*1000:(audio_chunk[1]+0.5)*1000]
chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
# audio.export(chunk_filename, format="wav")
audio.export(chunk_filename, format="wav")
playsound(chunk_filename)
# Recognize the chunk
with sr.AudioFile(chunk_filename) as source:
audio_listened = r.record(source)
# try converting it to text
try:
text = r.recognize_google(audio_listened)
except sr.UnknownValueError as e:
# print("Error:", str(e))
while True:
text = str(input())
if text == "r":
playsound(chunk_filename)
else:
break
csv_writer.writerow([text, [timestamps[i], path]])
else:
text = f"{text.capitalize()}. "
while True:
text = str(input())
if text == "r":
playsound(chunk_filename)
else:
break
csv_writer.writerow([text, [timestamps[i - 1], path]])
# print(chunk_filename, ":", text)
whole_text += text
print("Finished chunk:", i)
# Return the text for all chunks detected
return whole_text
|
43bc5db510a3eae95fcb491c428a6c1d71ca4b81 | yuukou3333/study-python | /init_py/python_init.py | 1,301 | 3.75 | 4 | # 5/14:Hello World 出力
# 6/14:変数とは
# 7/14:データ型
# 8/14:リスト
# 9/14:演算子
# 10/14:条件式
# =========================================
print("Hello World")
# =========================================
num = 1
print(num)
# 大文字小文字は区別される
Num = 2
print(Num)
# 予約語はダメ
# return = 3
# print(return)
# =========================================
# 数値型
num1 = 123
num2 = 1.23
print(type(num1))
print(type(num2))
# 文字列型
str = "Hello"
print(type(str))
# ブール型 Boolean型
a = 1
b = 2
bool = 2 > 1
print(bool) # => True
print(type(bool)) # => <class 'bool'>
# =========================================
# リスト
list = ["sato", "suzuki", "takahashi"]
print(list)
print(list[0])
# 要素の変更
list[1] = "tanaka"
print(list)
# 多次元リスト
list_02 = [ ["sato", "suzuki"], ["takahashi", "tanaka"]]
print(list_02[0][1]) # => suzuki
# =========================================
# 演算子(代入演算子)
x = 10
y = 20
x = x+10
print(x) # => 20
x += 10
print(x) # => 30
x += y
print(x) # => 50
# =========================================
# 条件分岐
age = 0
if age >= 20:
print("adult")
elif age == 0:
print("baby")
else:
print("child")
# =========================================
|
a2d26c672a3e420257e32136a2faf53912faf861 | saundera0436/CTI-110 | /P3T1_AreasOfRectangles_AnthonySaunders.py | 758 | 4.4375 | 4 | #CTI - 110
#Area of a rectangle
#Anthony Saunders
#October 7 2018
#Ask user to input the length and width of rectangle 1.
length1 = int(input("Please enter the length of rectangle 1: "))
width1 = int(input("Please enter the width of rectangle 1 : "))
#Ask user to input the length and width of rectangle 2.
length2 = int(input("Please enter the length of rectangle 2: "))
width2 = int(input("Please enter the width of rectangle 2 : "))
#Calculate the area of rectangles.
area1 = length1 * width1
area2 = length2 * width2
#Determine which area is greater
if area1 > area2:
print ("Rectangle 1 has the greater area")
elif area2 > area1:
print("Rectangle 2 has the greater area")
else:
print ("Both rectangles area is the same")
|
b581de55eec9ae06cb884823758394f350e8ec67 | charleycodes/leetcode | /152_maximum_product_subarray.py | 1,141 | 4.125 | 4 | """Find the contiguous subarray within an array (containing at least one number)
which has the largest product.
For example, given the array [2, 3, -2, 4],
the contiguous subarray [2, 3] has the largest product = 6.
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxi = mini = result = nums[0]
for i in range(1, len(nums)):
possibilities = [(maxi * nums[i]), (mini * nums[i]), nums[i]]
maxi = max(possibilities)
mini = min(possibilities)
result = max(maxi, result)
return result
####################################################
# Testing...
solution = Solution()
print "Input [2, 3, -2, 4], expecting 6. Got >>>", solution.maxProduct([2, 3, -2, 4])
print "Input [-2], expecting -2. Got >>>", solution.maxProduct([-2])
print "Input [3, -1, 4], expecting 4. Got >>>", solution.maxProduct([3, -1, 4])
print "Input [-2, 3, -4], expecting 24. Got >>>", solution.maxProduct([-2, 3, -4])
print "Input [-4, -3, -2], expecting 12. Got >>>", solution.maxProduct([-4, -3, -2])
|
139f5fd80d1c01b8a7909aaabbbe016a7989e085 | kcmuths/Python-work | /pay_debt_month.py | 1,235 | 4.46875 | 4 | ##Write a program that calculates the minimum fixed monthly payment needed in
##order pay off a credit card balance within 12 months. We will not be dealing
##with a minimum monthly payment rate.
##retrieve the input from user
initialBalance = float(raw_input('Enter the outstanding balance on your credit card:'))
interestRate = float(raw_input('Enter the annual credit card interest rate as a decimal:'))
##Intialize state variables
monthlyPayment = 0
monthlyInterestRate = interestRate/12.0
balance = initialBalance
##Test increasing amount of monthlyPayment in increments of $100
##until it can be paid off in a year
while balance > 0:
monthlyPayment += 10
balance = initialBalance
numMonths = 0
##Time until balance can be paid off
while numMonths < 12 and balance > 0:
numMonths += 1
##interest for the month
interest = monthlyInterestRate * balance
balance -= monthlyPayment
balance += interest
#Round final balance to 2 decimal places
balance = round(balance,2)
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonths
print 'Balance:', balance
|
4372b1873e245dedeb8122b07a1c02bf30a8ab4d | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4152/codes/1723_2498.py | 444 | 3.78125 | 4 | hA = int(input("Digite aqui o numero de habitantes a cidade A: "))
hB = int(input("Digite aqui o numero de habitantes a cidade B: "))
pA = float(input("Digite aqui o percentual de crescimento populacional da cidade A: "))
pB = float(input("Digite aqui o percentual de crescimento populacional da cidade B: "))
percA = pA / 100
percB = pB / 100
ano = 0
while (hA < hB):
hA = hA + (hA * percA)
hB = hB + (hB * percB)
ano = ano + 1
print(ano)
|
14c72c37389f705f131968971ac86dcbb3d173b1 | dengs08/pyCAM | /node.py | 504 | 3.84375 | 4 | class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def walk(node):
""" iterate tree in pre-order depth-first search order """
yield node
for child in node.children:
for n in walk(child):
yield n
|
68d80bb61b43159d020a5ec93378c6383adf799c | metmirr/project-euler | /answers/ex6.py | 334 | 3.578125 | 4 | """
Problem 6:
Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.
"""
from functools import reduce
squre1 = reduce(lambda acc, x: x**2 + acc, range(1, 101))
squre2 = reduce(lambda acc, x: x + acc, range(1, 101))**2
print('answer:', squre2 - squre1)
|
7fa79ead132756657f7a3694eb4f29e23de4ee22 | lrlichardi/Python | /tp5/Ej10.py | 304 | 3.890625 | 4 | # Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80,
# 65, 8, 23, 15, 5, 86, 43, 11 y muestre por pantalla el menor y el mayor de los precios
lista_precios = [50 , 75 , 46 , 22 , 80 , 65 , 8 , 23 , 15 , 5 , 86 , 43 , 11]
lista_precios.sort()
print(lista_precios) |
8307ec8f3e8a32e627f3af15f9d0bb339d8b8614 | littlezz/sec-pass-gen | /core/core.py | 2,029 | 3.5 | 4 | from string import ascii_lowercase, ascii_uppercase, digits
import itertools
from hashlib import sha512
__author__ = 'zz'
# allow_letter_mode
# bit mean low, upper, digits
ALL = 7 # 111
EXCLUDE_UPPER = 5 # 101
ONLY_DIGITS = 1 # 001
DEFAULT_MAX_LENGTH = 10
class BaseGenerator:
"""
hash the main password and identification 3 times, then combine them and hash it twice
"""
def __init__(self, password1, max_length=DEFAULT_MAX_LENGTH, allow_mode=ALL):
assert isinstance(allow_mode, int), 'allow_mode must be integer'
assert 0 < allow_mode < 8, 'allow_mode exceed'
assert max_length > 0, 'max_length exceed'
self.max_length = max_length
self.allow_mode = allow_mode
self.password1 = self.hash(password1, times=3)
def _get_allow_char_from_mode(self):
_mode_stack = (ascii_lowercase, ascii_uppercase, digits)
mode = list(int(i) for i in format(self.allow_mode, '0=3b'))
return ''.join(itertools.compress(_mode_stack, mode))
def get_allow_char(self):
return self._get_allow_char_from_mode()
@staticmethod
def hash(val, times=1):
"""
return sha512 hash bytes result
:param val:
:return:
"""
if isinstance(val, str):
temp = val.encode()
else:
temp = val
for i in range(times):
temp = sha512(temp).digest()
return temp
def _get_result_from_bytes(self, bytes_result):
allow_chars = self.get_allow_char()
mod = len(allow_chars)
ret = []
for b in bytes_result[:self.max_length]:
ret.append(allow_chars[b % mod])
return ''.join(ret)
def generate_password(self, identification):
identification = self.hash(identification, times=3)
byte_result = self.hash(self.password1+identification, times=2)
result = self._get_result_from_bytes(byte_result)
return result
class HashGenerator(BaseGenerator):
pass
|
e5352cbf473f7ab375f231e86816504c42194f5e | Navyashree008/functionsQuetions | /loop/kbc_part_1.py | 4,145 | 4.15625 | 4 | question_list = ["How many continents are there?", "What is the capital of India?","NG mei kaun se course padhaya jaata hai?" # teesra question
]
options_list = [
#pehle question ke liye options
["Four", "Nine", "Seven", "Eight"],
#second question ke liye options
["Chandigarh", "Bhopal", "Chennai", "Delhi"],
#third question ke liye options
["Software Engineering", "Counseling", "Tourism", "Agriculture"]]
solution_list = [3,4,1]
# print(question_list[1])
# i = 0
# a = 1
# while i<len(options_list[1]):
# print(a,options_list[1][i])
# a+=1
# i+=1
# i = 0
# while i < len(question_list):
# print(question_list[i]):
# j = 0
# a = 1
# while j <len(options_list[i]):
# print(a,options_list[i][j])
# a+=1
# j+=1
# answer_input = int(input("enter the option number"))
# if answer_input == solution_list[i]:
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# break
# i+=1
# i = 0
# while i < len(question_list):
# print(question_list[i])
# j = 0
# a = 1
# while j <len(options_list[i]):
# print(a,options_list[i][j])
# a+=1
# j+=1
# print("you can even use 50:50 life line")
# answer_input = int(input("enter the option number"))
# if answer_input == solution_list[i] or answer_list == "50:50":
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# break
# i+=1
# i = 0
# while i < len(question_list):
# print(question_list[i])
# j = 0
# a = 1
# while j <len(options_list[i]):
# print(a,options_list[i][j])
# a+=1
# j+=1
# print("you can even use 50:50 life line")
# answer_input = input("enter the option number")
# if answer_input == "50:50":
# if i == 0:
# print("3.seven or 4.eight")
# elif i == 1:
# print("1.Chandigarh or 4.Delhi")
# elif i == 2:
# print("1.software engineering or 2.tourism")
# answer_input_2= int(input("enter no"))
# if answer_input == solution_list[i]:
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# break
# else:
# if answer_input == solution_list[i]:
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# question_list = ["How many continents are there?", "What is the capital of India?","NG mei kaun se course padhaya jaata hai?" # teesra question
# ]
# options_list = [
# #pehle question ke liye options
# ["Four", "Nine", "Seven", "Eight"],
# #second question ke liye options
# ["Chandigarh", "Bhopal", "Chennai", "Delhi"],
# #third question ke liye options
# ["Software Engineering", "Counseling", "Tourism", "Agriculture"]]
# solution_list = [3,4,1]
# i = 0
# while i < len(question_list):
# print(question_list[i])
# j = 0
# a = 1
# while j <len(options_list[i]):
# print(a,options_list[i][j])
# a+=1
# j+=1
# print("you can even use 50:50 life line")
# answer_input = input("enter the option number")
# if answer_input == "50:50":
# if i == 0:
# print("3.seven or 4.eight")
# elif i == 1:
# print("1.Chandigarh or 4.Delhi")
# elif i == 2:
# print("1.software engineering or 2.tourism")
# answer_input_2=int(input("enter no"))
# if answer_input_2 == solution_list[i]:
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# break
# else:
# if answer_input == solution_list[i]:
# print("yeh!,its correct lets move forward")
# else:
# print("sadly your answer is wrong")
# print("you are out of game")
# break
# i+=1 |
8e7959cd4e51eb9199e9ea3d400fc6cf446bfd3b | oeseo/-STEPIK-Python- | /7.9.py | 1,497 | 3.53125 | 4 | """
/step/1
n = int(input())
sum = 0
for i in range(1, n+1):
sum += i
l = [i for i in range(1, sum+1)]
counter = 0
for i in range(1, n+1):
s = []
for j in range(i):
s.append(l[counter + j])
counter += i
print(*s)
/step/2
n = int(input())
for i in range(1, n+1):
l = [str(j) for j in range(1, i)]
l.extend([str(j) for j in range(i, 0, -1)])
print(''.join(l))
/step/3
a, b = int(input()), int(input())
sum, bigsum, num, bignum = 0, 0, 0, 0
for i in range(a, b + 1):
for j in range(1, i + 1):
if i // j == i / j:
sum += j
num = i
if sum > bigsum:
bignum = num
bigsum = sum
if sum == bigsum:
bignum = max(num, bignum)
bigsum = sum
num, sum = 0, 0
print(bignum, bigsum)
/step/4
n = int(input())
for i in range(1, n+1):
counter = 0
for j in range(1, i+1):
if i%j==0:
counter += 1
print(str(i) + '+'*counter)
/step/5
n = int(input())
sum = 0
while n > 9:
while n/10!=0:
sum += n%10
n //= 10
n = sum
sum = 0
print(n)
/step/6
def factorial(n):
sum = 1
for i in range(1, n+1):
sum *= i
return sum
n = int(input())
l = [factorial(i) for i in range(1, n+1)]
print(sum(l))
/step/7
a, b = [int(input()) for i in range(2)]
for i in range(a, b+1):
counter = 0
for j in range(1, i):
if i%j==0:
counter += 1
if counter == 1:
print(i)
"""
|
7861e62dfacfd2dd8f4dd8c45da0667dd65bb85d | jfidelia/Chapter1_exercises | /uniqueCharacters2.py | 236 | 3.90625 | 4 | def is_unique_chars(str):
arr = [False] * 128
for char in str:
index = ord(char)
if arr[index]:
return False
else:
arr[index] = True
return True
print(is_unique_chars("yelp")) |
10ff851fa024a7b7a3c1bb8d985725c9fe8d8fbc | Meena25/python-75-hackathon | /tuples.py | 789 | 4.53125 | 5 | # TUPLES:
#2 tuples are created
tuple1 = ('tact','python')
tuple2 = (1,2,3,4)
print("tup1[0]: ",tuple1[0])
print("tup2[1:3]: ",tuple2[1:3])
""" OUTPUT:
tup1[0]: tact
tup2[1:3]: (2, 3) """
#Updating tuple1
tuple1 = ('python','challenge')
tuple3 = tuple1 + tuple2 # Concatenation of tuple1 and tuple2
print("tuple3 : ",tuple3)
""" OUTPUT :
tuple3 : ('python', 'challenge', 1, 2, 3, 4) """
#Comparing elements of two tuples cmp(tup1,tup2)
#Length of a tuple
print("Length of tuple3 is : ",len(tuple3))
""" OUTPUT:
Length of tuple3 is : 6 """
#Max and min value of a tuple
print("Maximum value of tup2 : ",max(tuple2))
print("Minimum value of tup2 : ",min(tuple2))
"""
OUTPUT:
Maximum value of tup2 : 4
Minimum value of tup2 : 1
"""
|
56c1e96c7393e70111d364e0762c8ba854a6d070 | JaspinderSingh786/Python3BasicsToAdvance | /functions/iterator.py | 255 | 4.28125 | 4 | # iterator function is used to generate a sequence value on by one
b = [1,2,3,4,5,26,7,8,8]
a = iter(b)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
|
3d710d07da1b9ed632328de08939d1f11aa77e13 | cczhouhaha/data_structure | /1010虚拟结点/虚拟结点/哑结点dummy.py | 3,766 | 3.75 | 4 | # 链表相关操作
# 删除某结点
# 虚拟结点:将头结点当做普通结点看待
"""
:Author:Miss zhou
:Creat : 2020/10/10 11:09
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
def __repr__(self):
return f"Node({self.data})"
class Slution:
def __init__(self):
self.head = None
# 删除链表中的特定值
def delete_element(self,head:Node,value):
dummy = Node(0) #先设置一个虚拟变量,且将其指向原来的头结点
dummy.next = head
curr = dummy
while curr.next:
if curr.next.data == value:
curr.next = curr.next.next
else:
curr = curr.next
self.head = dummy.next #此步用在repr中,重新定义头部,打印输出
return dummy.next #返回头结点
# 链表结点两两交换
def change_paris(self,head:Node):
dummy = Node(0)
dummy.next = head
prev = dummy
while prev.next and prev.next.next:
# 指针上岗
slow = prev.next
fast = prev.next.next
# 交换位置
prev.next = fast
slow.next = fast.next
fast.next = slow
# perv前移
prev = prev.next.next
self.head = dummy.next #此步用在repr中,重新定义头部,打印输出
return dummy.next # 返回头结点
# 合并两个有序链表 1.and方法
def merge_twolink(self,l1:Node,l2:Node):
dummy = Node(0)
curr = dummy
while l1 and l2:
if l1.data < l2.data:
curr.next = l1
l1 =l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1 is None:
curr.next = l2
if l2 is None:
curr.next = l1
self.head = dummy.next #此步用在repr中,重新定义头部,打印输出
# return dummy.next
# def __repr__(self):
# current = self.head
# llstr=""
# while current:
# llstr += f"{current}-->"
# current = current.next
# return llstr + "End"
# 合并两个有序链表 2.or方法 若是其中一个链表是空的,将后两个if判断提前.
def merge_twolinks(self,l1: Node, l2: Node):
dummy = Node(0)
curr = dummy
while l1 or l2:
if l1.data < l2.data:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1 is None:
curr.next = l2
break # 用or的话,一定加break
if l2 is None:
curr.next = l1
break # 用or的话,一定加break
return dummy.next
def output(head:Node):
curr = head
# llstr = ""
while curr:
# llstr += f"{curr.data}-->"
print(curr.data)
curr = curr.next
ss = Slution()
if __name__ == '__main__':
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = None
node5 = Node(1)
node6 = Node(3)
node7 = Node(3)
node8 = Node(6)
node5.next = node6
node6.next = node7
node7.next = node8
node8.next = None
# print(ss.delete_element(node1,3))
# print(ss)
# print(ss.change_paris(node1))
# print(ss)
# print(ss.merge_twolink(node1,node5))
# print(ss)
m=ss.delete_element(node1, 3)
print(m)
output(m)
# output(node1)
# print(a)
# print(output(a))
|
c7c837510b2fd8812fbea06187dab54c1a0e82d3 | nesaro/london-code-dojo-27 | /test.py | 1,965 | 3.578125 | 4 | import unittest
from pub import Glass, Customer
class MyTest(unittest.TestCase):
def test_glass(self):
glass = Glass()
self.assertEqual(glass.content, 20)
def test_drink(self):
customer = Customer()
customer.buy_beer()
customer.drink()
self.assertEqual(customer.glass.content, 19)
def test_quaff(self):
customer = Customer()
customer.buy_beer()
customer.quaff()
self.assertEqual(customer.glass.content, 16)
def test_one_off(self):
customer = Customer()
customer.buy_beer()
customer.down_in_one()
self.assertEqual(customer.glass.content, 0)
def test_too_much(self):
customer = Customer()
customer.buy_beer()
customer.down_in_one()
self.assertEqual(customer.glass.content, 0)
self.assertRaises(Exception, customer.quaff)
def test_half_drink(self):
customer = Customer()
customer.buy_beer("half")
customer.drink()
self.assertEqual(customer.glass.content, 9)
def test_half_quaff(self):
customer = Customer()
customer.buy_beer("half")
customer.quaff()
self.assertEqual(customer.glass.content, 6)
def test_half_one_off(self):
customer = Customer()
customer.buy_beer("half")
customer.down_in_one()
self.assertEqual(customer.glass.content, 0)
def test_triple_drink(self):
customer = Customer()
customer.buy_beer("triple")
customer.drink()
self.assertEqual(customer.glass.content, 59)
def test_triple_quaff(self):
customer = Customer()
customer.buy_beer("triple")
customer.quaff()
self.assertEqual(customer.glass.content, 56)
def test_triple_one_off(self):
customer = Customer()
customer.buy_beer("triple")
customer.down_in_one()
self.assertEqual(customer.glass.content, 0)
|
563956ece5db99753c513816a72aaa1dd9902b39 | yournameherex337/lpthw | /ex18.py | 519 | 3.9375 | 4 | # This one is like your script with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok that *args is acutally pointless, we can do it this way
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes none
def print_none():
print "I got nothing."
print_two('devyn', 'ashlin')
print_two_again('devyn', 'ashlin')
print_one('ashlin')
print_none()
|
dad81e08090ad26e4064540735afffddfc072cb7 | adaray/cvp316 | /Blockchain/blockchain.py | 1,882 | 3.71875 | 4 | blockchain = []
def last_value():
if len(blockchain) < 1:
return None
return blockchain[-1]
def get_tx_value():
return float(input('Enter transaction value: '))
def get_user_choice():
return input('\nEnter your choice: ')
def add_value(transaction, last_transaction = [1]):
if last_transaction == None:
last_transaction = [1]
blockchain.append([last_transaction, transaction])
def verify_chain():
#block_index = 0
is_valid = True
for block_index in range(len(blockchain)):
if block_index == 0:
continue
elif blockchain[block_index][0] == blockchain[block_index-1]:
is_valid = True
else:
is_valid = False
break
block_index +=1
return is_valid
# for block in blockchain:
# if block_index == 0:
# block_index+=1
# continue
# elif block[0] == blockchain[block_index-1]:
def print_blockchain():
for block in blockchain:
print('\nOutputting Block\n')
print(block)
else:
print('--' * 15)
while True:
print('\nPlease make a choice: \n')
print('1: Add a new transaction block: ')
print('2: Display current block chain blocks: ')
print('h: Manipulate the chain')
print('q: To quit the program: ')
user_choice = get_user_choice()
if user_choice == '1':
tx_amount = get_tx_value()
add_value(tx_amount, last_value())
elif user_choice == '2':
print_blockchain()
elif user_choice == 'h':
if len(blockchain) >= 1:
blockchain[2]=[1.11]
elif user_choice == 'q':
break
else:
print("\nWrong selection, please try again\n")
if not verify_chain():
print('\nInvalid blockchain')
break
print('\nDone!') |
46e9dba85615a1272b2287253728c311d410749b | srikanthpragada/22_JAN_2018_PYTHON | /fun/lambda_sorted.py | 364 | 3.78125 | 4 | def length(s):
return len(s)
def last_name(s):
return s.split()[-1]
names = ['Bill Gates','Larray Ellison','Micheal Dell','Jeff Bezzos','Larry Page','Steve Jobs']
# for n in sorted(names):
# print(n)
#
# for n in sorted(names,key=length):
# print(n)
# for n in sorted(names,key=last_name):
# print(n)
for n in sorted(names,key = lambda n: n.split()[-1]):
print(n)
|
d2096029c331797d7a2f97661379b448643139a2 | imwarsame/DataStructures | /Python/queue.py | 519 | 4.0625 | 4 | # first element in is first element out
# that's about it
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
queue.append('d')
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0)) #removes element at index 0, then after inserts moves element at index 1 to index 0 i.e. first in the queue
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0)) #results in trace back error, can't remove from any empty queue
print("\nQueue after removing elements")
print(queue)
|
a1338cafef4fdf4e108c2ebe38e6a2ddca9e3d71 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#093 The 'if' function.py | 435 | 4.28125 | 4 | # Create a function called _if which takes 3 arguments: a boolean value bool and
# 2 functions (which do not take any parameters): func1 and func2
#
# When bool is truth-ish, func1 should be called, otherwise call the func2.
#
# Example:
# def truthy():
# print("True")
#
# def falsey():
# print("False")
#
# _if(True, truthy, falsey)
# # prints 'True' to the console
def _if(bool, func1, func2):
func1() if bool else func2()
|
996a9b13f6f483fa6ee30e07046355caad873652 | RRoundTable/Data_Structure_Study | /array/delete_nth.py | 1,478 | 3.78125 | 4 |
# 문제
"""
Given a list lst and a number N, create a new list
that contains each number of the list at most N times without reordering.
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2],
drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3,
which leads to [1,2,3,1,2,3]
"""
exList= [1,2,3,1,2,1,2,3]
# 내가 해결한 방법
def delete(array,n):
unique=[]
for i in array:
if i in unique:
continue
unique.append(i)
count=[0]*len(unique) # 각 인덱스가 count값을 가지고 있는다
result=[]
for i in array:
if count[unique.index(i)]<n:
print(unique.index(i))
result.append(i)
count[unique.index(i)]+=1
return result
print(delete(exList,2))
# 모범답안
"""
collection을 사용하였다
"""
import collections
def delete_ex(array,n):
result=[]
counts=collections.defaultdict(int)
for i in array:
print("array : "+str(i))
print(counts[i])
if counts[i]<n: # count[i] : i성분의 노출빈도를 나타낸다
result.append(i)
counts[i]+=1
return result
def delete_nth(array, n):
result = []
counts = collections.defaultdict(int) # keep track of occurrences
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
print(delete_nth(exList,2))
|
bec9fcf42c1028e8dc702904fd06da5cf5b79bb7 | ChenLiangbo/Learning-python | /sort/search.py | 1,199 | 3.765625 | 4 | #!usr/bin/env/python
# -*- coding: utf-8 -*-
# 第一种
# 无序列表中的查找,随机查找,循环遍历
#第二种 有序表的查找一般使用二分法
#不断从中间选取元素进行查找,这样的时间复杂度是log(n)
#在查找表中不断取中间元素与查找值进行比较,以二分之一的倍率进行表范围的缩小
def binary_search(lis, key):
low = 0
high = len(lis) - 1
time = 0
while low < high:
time += 1
mid = int((low + high) / 2)
if key < lis[mid]:
high = mid - 1
elif key > lis[mid]:
low = mid + 1
else:
# 打印折半的次数
print("times: %s" % time)
return mid
print("times: %s" % time)
return False
# 分查找法虽然已经很不错了,但还有可以优化的地方。
# 有的时候,对半过滤还不够狠,要是每次都排除十分之九的数据岂不是更好?选择这个值就是关键问题,插值的意义就是:以更快的速度进行缩减。
# 插值的核心就是使用公式:
# value = (key - list[low])/(list[high] - list[low])
# 用这个value来代替二分查找中的1/2。 |
e9f3ee963e8eac79cc0924740d1ee4c1fd777ed2 | dewhallez/python_Projects | /ping.py | 366 | 3.828125 | 4 | import os
# define the ping function
def pingComputer():
# Get hostname Ip address
hostname = input("Enter the ip address: ")
# ping host for response
response = os.system("Ping -c 2 " + hostname)
if response == 0:
print(f'{hostname} is up')
else:
print(f'{hostname} is down')
if __name__ == "__main__":
pingComputer()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.