blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
0e1fed18a9d5170586d7d6a0687b9d73919b3e68 | SOURADEEP-DONNY/WORKING-WITH-PYTHON | /File Handling/filee.py | 220 | 3.71875 | 4 | f=open("Abhi.txt","r")
s=f.readlines()
print(s)
longest=" "
for i in s:
if(len(i)>len(longest)):
longest=i
l=len(longest)
print("Longest Line: ",longest)
print("Length of longest line: ",l)
|
0894e717570faf276766743af228ebc40e489cf4 | fogugy/gb_algorithm | /#3_16.01/task7.py | 525 | 4 | 4 | # В одномерном массиве целых чисел определить два наименьших элемента.
# Они могут быть как равны между собой (оба являться минимальными), так и различаться.
import random as rnd
ls = [rnd.randint(0, 10) for x in range(10)]
min1 = float('inf')
min2 = float('inf')
for x in ls:
if x < min1:
min1 = x
continue
elif x < min2:
min2 = x
print(ls)
print([min1, min2]) |
2541b850b8cb2c6c420852367e57395f3eea8d7e | madihamallick/Py-games | /Hangman/main.py | 5,955 | 3.796875 | 4 | import pygame, math, random
#setup display
pygame.init() #initializing pygame module
WIDTH, HEIGHT= 800,500 #width and height in pixels background (where we want our game to be played)
win = pygame.display.set_mode((WIDTH,HEIGHT)) #creating dimensions for pygame, accepts tuple only
pygame.display.set_caption("Hangman Game") #give name to the game
#button variables
radius = 20
gap= 15
letters = []
startx= round((WIDTH - (radius * 2 + gap) * 13) / 2) #getting the x pos after some space, where we start at, /2-->coz one side
starty= 400 #x is more imp so set any value of y
A= 65
for i in range(26): #tells which button we are on
x= startx + gap * 2+ ((radius * 2 + gap)* (i%13))
#gap * 2 ---> to give gap b/w r.h.s & l.h.s of screen
#((radius * 2 + gap) ---> distance b/w each new button drawn
#(i%13)) #(i%13) --> coz we are counting from 0 to 13 as soon as it will reach 13 it will start recounting it till 13. eg: 13 % 13 =0, 1 % 13= 1, 2 % 13= 2, 15 % 13 = 2, so its looping over.
y= starty + ((i//13) * (gap + radius * 2))
letters.append([x, y, chr(A+i), True]) #chr(A+i)--> to keep track of letter in each button
#load images
images = []
for i in range(7):
img = pygame.image.load("hangman" + str(i) + ".png")
images.append(img)
#game variables
hangman_status = 0 #the hangman img will display accordingly
list_of_words= ["abruptly","avenue","awkward","azure","galaxy","gossip","icebox","injury","ivory","ivy","jackpot","jaundice","joyful","juicy","jukebox","jumbo","kiwifruit","matrix","microwave","nightclub","nowadays","oxidize","oxygen","peekaboo","pixel","pneumonia","puppy","puzzling","queue","quizzes","quorum","rhythm","rickshaw","scratch","staff","strengths","stretch","subway","syndrome","thumbscrew","transcript","transplant","twelfth","unknown","unworthy","unzip","uptown","vodka","vortex","walkway","wave","wavy","whiskey","whizzing","wizard","wristwatch","xylophone","yachtsman", "youthful","yummy","zigzag" ,"zodiac" ,"zombie"]
word = random.choice(list_of_words).upper()
#print(word)
guessed = [] #to keep track of guessed words
#colors
white = (255,255,255)
BLACK =(0,0,0)
BLUE= (180, 219, 251)
PINK= (232, 90, 202)
#fonts
LETTER_FONTS= pygame.font.SysFont('comicsans', 40) #-> font name, size
WORD_FONTS = pygame.font.SysFont('comicsans', 60)
TITLE_FONTS = pygame.font.SysFont('comicsans', 70)
def draw():
win.fill(BLUE) #setting the bg color with rgb values (0-255)
#draw title
text = TITLE_FONTS.render("HANGMAN GAME", 1, BLACK)
win.blit(text, (WIDTH/2 - text.get_width()/2, 20)) #here we set width of title at very center and height to somewhat top
#draw word
display_word= "" #this will keep on adding correct letters as we guess
for i in word:
if i in guessed: #if letter we click is guessed correctly, or present in the word we have to guess
display_word += i + " "
else:
display_word += "_ "
text = WORD_FONTS.render(display_word, 1, BLACK) #rendering diplay_word and displaying it on screen
win.blit(text, (400, 200)) #drawing it on screen
#draw buttons
for i in letters:
x, y, ltr, visible = i #suppose i= [4,5] so x= 4 and y= 5, unpacking data
if visible:
pygame.draw.circle(win, BLACK, (x, y) , radius, 3) #saying pygame to draw circle on win(window), color black, (x, y)-> center where draw the button, 3px-> radius for the circle
text = LETTER_FONTS.render(ltr,1,BLACK) #using font we just created, we render the text on screen,
#ltr-> text you want to render, BLACK --> color you want to render with
win.blit(text, (x - text.get_width()/2, y - text.get_height()/2) ) #what we want to draw(here text), where
#text.get_width()--> tells how wide is the surface 'text' that we created
win.blit(images[hangman_status],(150,100)) #to draw image/some kind of surface, give image and location
pygame.display.update() #to reflect any kind of changes we have to update
#win/loose msg printing msg on screen
def display_message(message):
pygame.time.delay(1000)
win.fill(PINK)
text = WORD_FONTS.render(message,1,BLACK)
win.blit(text, (WIDTH/2 - text.get_width()/2, HEIGHT/2 - text.get_height()/2)) #printing the won msg right at the center
pygame.display.update()
pygame.time.delay(3000) #will display the msg on screen for 3 secs
#setup game loop
FPS = 60 #max speed of game is 60 frames/sec
clock= pygame.time.Clock() #to make loop run at this speed
run = True #var to control while loop
while run:
clock.tick(FPS) # use 'clock' to make sure our loop runs in the FPS speed
draw()
for i in pygame.event.get(): #any event(any click by user) that happens will be stored inside i
if i.type == pygame.QUIT:
run = False
if i.type == pygame.MOUSEBUTTONDOWN: #getting position of mouse when pressed on screen
m_x, m_y = pygame.mouse.get_pos()
for i in letters:
x, y, ltr, visible = i
if visible: #checking for collision
dis= math.sqrt((x - m_x)**2 + (y- m_y)**2)
#adding distance from x and y, and take root, determining distance b/w tow points, we the get distance b/w mouse postion and side of button
if dis< radius:
i[3] = False # so it will set the last element of i i.e visible to false
guessed.append(ltr)
if ltr not in word:
hangman_status += 1
#print(ltr)
#print(pos) --> prints position of mouse
draw() #when we win/loose the msg displays, but the last letter added is not shown on screen, so to show
#we redraw each time we click on screen, then check
#checking for winner
won = True
for i in word:#loops through all letters in word
if i not in guessed:#if it not in guessed letter
won = False
break
if won:
display_message("Wohooo...!! You Won!")
break
if hangman_status == 6:
display_message(f"Oopss..!! It was {word} You Lost!")
break
pygame.quit()
|
1bdbb75314505cfd33dc3517d3dfc662836382cd | Swarajsj/Python-Programes- | /Function5.py | 622 | 4.09375 | 4 | # %%
# Program to print the minimum value
def minimum(a, b):
if a < b:
return a
elif b < a:
return b
else:
return "Both the numbers are equal"
minimum(100, 100)
# %%
# Wap to find the distance between to points
#((x2-x1)**2 + (y2-y1)**2)**0.5
def distance(x1, x2, y1, y2):
dx = (x2-x1)**2
dy = (y2-y1)**2
d = (dx + dy)**0.5
return d
distance(2, 4, 8, 10)
# %%
# Reason why we need functions
sum = 0
for i in range(1, 26):
sum = sum + i
print(sum, end=' '"\n")
for i in range(50, 71):
sum = sum + i
print(sum, end=' ')
|
549e724d9d6d9540777d1e19947dc81491c6fef5 | Denisov-AA/Python_courses | /HomeWork/Lection8_TestWork/Task_10.py | 1,352 | 3.921875 | 4 | class Money:
def __init__(self, ruble: int, penny: int):
self.ruble = ruble
self.penny = penny
self.sum = self.ruble * 100 + self.penny
def __add__(self, other):
return f"{(self.sum + other.sum) // 100}, {(self.sum + other.sum) % 100}"
def __sub__(self, other):
return f"{(self.sum - other.sum) // 100}, {(self.sum - other.sum) % 100}"
def __truediv__(self, n):
return f"{(int(self.ruble / n))}, {int(self.sum / n - int(self.ruble / n) * 100)}"
def __gt__(self, other):
return f"{print(self.sum > other.sum)}"
def __lt__(self, other):
return f"{print(self.sum < other.sum)}"
def __ge__(self, other):
return f"{print(self.sum >= other.sum)}"
def __le__(self, other):
return f"{print(self.sum <= other.sum)}"
def __eq__(self, other):
return f"{print(self.sum == other.sum)}"
def __ne__(self, other):
return f"{print(self.sum != other.sum)}"
def get_money(self):
return f"{print(f'{self.ruble}, {self.penny}')}"
def set_course(self, course):
self.course = course
def get_currency(self):
self.currency = (self.sum / (self.course * 100))
return f"{print(self.currency)}"
bablo = Money(6500, 65)
# Test
bablo.get_money()
bablo.set_course(65)
bablo.get_currency()
|
95433e3119a998bcb19e39a514d0d341d6e162b5 | Jeta1me1PLUS/learnleetcode | /459/459repeatedSubstring.py | 666 | 3.734375 | 4 | # Basic idea:
# First char of input string is first char of repeated substring
# Last char of input string is last char of repeated substring
# Let S1 = S + S (where S in input string)
# Remove 1 and last char of S1. Let this be S2
# If S exists in S2 then return true else false
# Let i be index in S2 where S starts then repeated substring length i + 1 and repeated substring S[0: i+1]
def repeatedSubstringPattern(str):
"""
:type str: str
:rtype: bool
"""
if not str:
return False
bb=str+str
ss = (str + str)[1:-1]
return ss.find(str) != -1
print(repeatedSubstringPattern("asas")) |
4037474e2f6b89a585a9d553e5200d4d92a49e75 | rhty/atcoder | /python/graph/union_find.py | 1,165 | 3.75 | 4 |
from typing import Dict
class UnionFind:
par: Dict[int, int]
siz: Dict[int, int]
def __init__(self, N: int) -> None:
self.par = {i: -1 for i in range(N)}
self.siz = {i: 1 for i in range(N)}
def root(self, x: int) -> int:
if self.par[x] == -1:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
def is_same(self, x: int, y: int) -> bool:
return self.root(x) == self.root(y)
def unite(self, x: int, y: int) -> bool:
x = self.root(x)
y = self.root(y)
if x == y:
return False
if self.siz[x] < self.siz[y]:
y, x = x, y
self.par[y] = x
self.siz[x] += self.siz[y]
return True
def size(self, x: int) -> int:
return self.siz[self.root(x)]
if __name__ == "__main__":
N, M = map(int, input().split())
uf = UnionFind(N)
for i in range(M):
a, b = map(int, input().split())
uf.unite(a, b)
# 連結成分の個数を求める
res = 0
for x in range(N):
if uf.root(x) == x:
res += 1
print(res)
|
fbe9229cc84b8fbbc9f601bdd10ecabec5a7ed3c | kambehmw/algorithm_python | /atcoder/NS20200420/A2.py | 171 | 3.8125 | 4 | s = input()
sr = s[::-1]
for c1, c2 in zip(s, sr):
if c1 == c2 or (c1 == "*" or c2 == "*"):
continue
else:
print("NO")
exit()
print("YES")
|
14cfdd5f4038be57303e78f3b14ea1559fba913d | zhouhaosame/leetcode_zh | /1-60/23_merge_k_Sorted_lists.py | 4,514 | 3.828125 | 4 | def merge_k_sorted_linked_lists(lists):
from functools import reduce
def merge_two_sorted_linked_list(l1, l2):
if l1 and l2:
if l1.val < l2.val:
head = pre = l1
l1 = l1.next
else:
head = pre = l2
l2 = l2.next
while (l2 != None and l1 != None):
if l2.val < l1.val:
pre.next = l2
l2 = l2.next
pre = pre.next
else:
pre.next = l1
l1 = l1.next
pre = pre.next
if l1 == None and l2 != None:
pre.next = l2
else:
pre.next = l1
return head
elif l1:
return l1
else:
return l2
return reduce(merge_two_sorted_linked_list,lists,[])
#最好赋一个初值,要不然输入时空的话,可能会出现问题
"""自己写的超时了,别人的faster 50%"""
def merge_divide_and_conquer(lists):
def merge2Lists(l1, l2):
head = point = ListNode(0)#point代替了pre,并且,直接生成了头结点
while l1 and l2:
if l1.val <= l2.val:
point.next = l1
l1 = l1.next
else:
point.next = l2
l2 = l1
l1 = point.next.next
point = point.next#也就是说point永远是在l1指针的前面
if not l1:
point.next = l2
else:
point.next = l1
return head.next
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount - interval, interval * 2):
#即使amount=2,i还是能够取到0.应该说是先取0,然后内部,然后+2,与amount-interval比较
lists[i] = merge2Lists(lists[i], lists[i + interval])
interval *= 2
return lists[0] if amount > 0 else lists
def similar_two_sorted_lists(lists):
if len(lists)==1:return lists[0]
def min_node(nodes):
#要确保nodes都不为空
min=nodes[0].val
min_node=nodes[0]
index=0
for i in range(len(nodes)):
if min>nodes[i].val:
min=nodes[i].val
min_node=nodes[i]
index=i
return min_node,index
def del_empty_node(lists):
lists_temp=[]
for i in lists:
if i!=None:
lists_temp.append(i)
return lists_temp
lists=del_empty_node(lists)
if lists:
pre,index_min=min_node(lists)
node1=lists[index_min]
lists[index_min]=node1.next
head=pre
while(lists):
lists=del_empty_node(lists)
if len(lists)==1:
pre.next=lists[0]
return head
find_node,index_min=min_node(lists)
pre.next=find_node
pre=pre.next
lists[index_min] = lists[index_min].next
return head
else:return []
#别人的优化之后的方法
import queue
def mergeKLists(lists):
head = point = ListNode(0)
q =queue.PriorityQueue()
for l in lists:
if l:
q.put((l.val, l))
while not q.empty():
val, node = q.get()
point.next = ListNode(val)
point = point.next
node = node.next
if node:
q.put((node.val, node))
return head.next
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def brute_force(lists):
nodes = []
head = point = ListNode(0)
for l in lists:
while l:
nodes.append(l.val)
l = l.next
for x in sorted(nodes):
point.next = ListNode(x)
point = point.next
return head.next
#这种暴力法反而比我之前的两种方法都要快,这说明我的方法有待精简
s1=[1]
s2=[1]
s3=[2]
head1=l1=ListNode(-1)
head2=l2=ListNode(-1)
head3=l3=ListNode(-1)
for i in range(len(s1)):
l1.next=ListNode(s1[i])
l1=l1.next
for i in range(len(s2)):
l2.next=ListNode(s2[i])
l2=l2.next
for i in range(len(s3)):
l3.next=ListNode(s3[i])
l3=l3.next
lists=[head1.next,head2.next,head3.next]
#l=merge_k_sorted_linked_lists(lists)
"""之前这里没有注释掉,因为lists是全局变量,所以当然改变啦,导致结果出错"""
#l=similar_two_sorted_lists(lists)
l=mergeKLists(lists)
while(l!=None):
print(l.val)
l=l.next |
0ac5161b91ac886b4c1a5b89651b3ca938a67104 | DanLEE278/Python_practice | /15.3. 다중상속.py | 1,962 | 3.71875 | 4 | # 다중 상속은 하나의 클래스가 두개 이상의 다른 클래스들을 받을때 사용
# 2개의 클라스가 a, b가 있다고 가정할때 a 클라스를 b 클라스에 상속시킬 수 있다
class unit:
def __init__(self, name, hp): # 여기서 __init__은 생성자이다
self.name = name
self.hp = hp
print("{0} 유닛이 생성되엇습니다.".format(self.name))
print("체력 {0}, 체력 {1}".format(self.hp, self.hp))
# 공격 유닛
class AttackUnit(unit): # 상속하려는 클래스를 넣어줌
def __init__(self, name, hp, damage):
# 유닛에서 만들어진 생성자를 호출
unit.__init__(self, name, hp) # 유닛의 생성자인 name hp 호출
self.damage = damage
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]".format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
self.hp -= damage
print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 날 수 있는 유닛
class flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed))
# 공중 유닛 공격 클래스
class flyableAttackUnit(AttackUnit, flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, damage)
flyable.__init__(self, flying_speed)
#
valkyrie = flyableAttackUnit("발키리", 100, 10, 15) # 클래스를 호출할때 self 를 모두 넣어줌
valkyrie.fly(valkyrie.name, "3시") #
valkyrie.attack("3시") |
cfcfcfab84b2a3a1ad91254cf48ef2a1f7ac6b37 | gokul1998/Python | /while.py | 54 | 3.75 | 4 | a = "madam"
b = a[::-1]
if a==b:
print("yelllllo") |
198d365b56e298180b8eb47c68782045c86095c3 | Artem-Markula/Python-Shool-s-Programs- | /3 Глава/Персональный привет.py | 666 | 3.609375 | 4 | quote ="Думаю. на мировом рынке можно будет продать штук пять компьютеров."
print("Исходная цитата : ")
print(quote)
print("\nOнa же в верхнем регистре:")
print(quote.upper())
print("\nB нижнем регистре:")
print(quote.lower())
print("\nKaк заголовок:")
print(quote.title())
print("\nC ма-а-аленькой заменой:")
print(quote.replace("штyк пять", "несколько миллионов"))
print("\nA вот опять исходная цитата:")
print(quote)
input("\n\nHaжмитe Enter. чтобы выйти.")
|
cb54ea0ba8c3bd3f0a83fec201df7d13d30a7f8f | Greek-and-Roman-God/Athena | /codingtest/week05/sangsu.py | 221 | 3.578125 | 4 | #상근이 동생 상수
def reverse_num(num):
reverse=list(str(num))
reverse.reverse()
reverse=("".join(reverse))
return reverse
a, b=map(int, input().split())
a=reverse_num(a)
b=reverse_num(b)
print(max(a,b)) |
213c365782ea4fa4aae03388c92f7070171ec5bb | tizhad/python-tutorials | /printfor/printfor.py | 119 | 3.71875 | 4 | # number = int(input())
# for i in range (1,number):
# print (str(number))
print(*range(1, int(input())+1), sep='') |
a21610560f45d0c0a1305080efe9045f184c094a | suarlin29/python3 | /tarea33ejercicios.py/edad exacta 27.py | 197 | 3.65625 | 4 | ##suarlin paz
## 27
print ("bienvenido al programa".center(50, "*"))
nacimiento = int(input("ingrese anio de nacimiento "))
DATO2 = 2019
edad = DATO2 - nacimiento
print("tu edad es:.{}".format(edad))
|
fd1f369f5d960a4655ec15673942ee956c4a99a0 | taunoe/Test-pyhon-2 | /pt1/1.4a.py | 163 | 3.5625 | 4 | ainepunktid = input("Sisestage ainepunktide arv:")
nadalad = input("Sisestage nädalate arv:")
ajakulu = (int(ainepunktid)*26)/int(nadalad)
print(round(ajakulu)) |
7d15e49bf978ed32b7ab9659f655205b1c6b6ae1 | weed478/wdi4 | /zad2.py | 713 | 3.6875 | 4 | end = None
tab = [[2, 8, 24, 42, 1], [7, 8, 15, 3, 5], [3, 8, 7, 1, 6], [3, 5, 7, 9, 1], [1, 7, 5, 3, 332]]
tabBe = [[2, 8, 24, 42, 2], [7, 8, 15, 3, 5], [3, 8, 7, 1, 6], [3, 5, 7, 9, 1], [1, 7, 5, 3, 332]]
def only_odd(num):
while num > 0:
num, digit = divmod(num, 10)
if digit % 2 == 0:
return False
end
end
return True
end
def hehe(tab):
for row in tab:
has_only_odd = False
for n in row:
if only_odd(n):
has_only_odd = True
break
end
end
if not has_only_odd:
return False
end
end
return True
end
print(hehe(tab))
print(hehe(tabBe))
|
5774c4c68ffd1b19fd48165e638abd5ca4698c08 | Vedarth/Deep-Learning | /Course_1/week_3/layer_sizes.py | 833 | 4.09375 | 4 | def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
### START CODE HERE ### (≈ 3 lines of code)
n_x = np.shape(X)[0] # size of input layer
n_h = 4
n_y = np.shape(Y)[0] # size of output layer
### END CODE HERE ###
return (n_x, n_h, n_y)
def main():
X_assess, Y_assess = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))
|
471aa47f4449ac04c5f00ecd1ffb43d47b3f79f0 | deepwzh/leetcode_practice | /21.py | 1,146 | 4.0625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# print(not l1, not l2)
head = None
node1 = l1
node2 = l2
node = None
if not l1 and not l2:
return []
if not l1 and l2:
return l2
elif l1 and not l2:
return l1
if l1.val < l2.val:
head = ListNode(node1.val)
node1 = node1.next
else:
head = ListNode(node2.val)
node2 = node2.next
node = head
while node1 and node2:
if node1.val < node2.val:
node.next = ListNode(node1.val)
node1 = node1.next
else:
node.next = ListNode(node2.val)
node2 = node2.next
node = node.next
if node1:
node.next = node1
else:
node.next = node2
return head |
643f2f4eaf03e102e8ce5bf30bb4529c075f2070 | TusharDimri/Python | /Raising Exceptions in Python.py | 793 | 4.25 | 4 | # Exceptions are raised in python using 'raise' keyword.Exceptions are user defined exception
a = input("Enter your name")
if a.isnumeric():
raise Exception("Name cannot be numeric")
# Assume that the task following above code is bulky.It will save a lot of time if we raise excetpion it will prevent us
# from ding things the wrong way.
print("Important Task")
# There are many built in exceptions in Python,Do check it out online.
# Another Example
a = int(input("Enter a number"))
b = int(input("Enter a number"))
if b == 0:
raise Exception("0 division Error")
else:
print(int(a/b))
# Another Example
c = input("Enter your name")
try:
print(c)
except Exception as e:
if c == "Tushar":
raise ValueError("Access Denied")
print("Exception Handled")
|
ed4d3496db68011bfb0cd4aeaf970d7eacc86a56 | dongyifeng/algorithm | /python/interview/link/7_link_ring.py | 1,165 | 3.890625 | 4 | #coding:utf-8
class ListNode:
def __init__(self,val):
self.val = val
self.next = None
# 判断一个单链表中是否有环
# 这里也是用到两个指针。如果一个链表中有环,也就是说用一个指针去遍历,是永远走不到头的。因此,我们可以用两个指针去遍历,一个指针一次走两步,一个指针一次走一步,如果有环,两个指针肯定会在环中相遇。时间复杂度为O(n)
def containsRing(root):
if root is None:return False
fast = root
slow = root
while fast is not None and slow is not None:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(4)
root.next.next.next.next = ListNode(5)
root.next.next.next.next.next = ListNode(6)
root.next.next.next.next.next.next = root.next.next.next
print containsRing(root)
root1 = ListNode(1)
root1.next = ListNode(2)
root1.next.next = ListNode(3)
root1.next.next.next = ListNode(4)
root1.next.next.next.next = ListNode(5)
root1.next.next.next.next.next = ListNode(6)
print containsRing(root1)
|
eb6a991321ec6d1881631ba4e39b07e759685cd4 | Algorithm2021/minjyo | /구현/1251.py | 431 | 3.59375 | 4 | from itertools import combinations
answer = ""
word = input()
newWord = []
for part in combinations(range(1, len(word)),2): # word[:0] is empty list
newWord.append((word[:part[0]])[::-1] + (word[part[0]:part[1]])[::-1] + (word[part[1]:])[::-1])
answer = newWord[0]
for word in newWord[1:]:
i = 0
while word[i] == answer[i]:
i += 1
if word[i] < answer[i]:
answer = word
print(answer)
|
71e3d568e2430c04113b92a691b0abe6002ad708 | rtejaswi/python | /class2.py | 1,531 | 3.75 | 4 | # parent class
class Person( ):
def __init__(self, name, idnumber,post,salary=False):
self.name = name
self.idnumber = idnumber
self.post = post
self.salary = salary
def display(self):
print(self.name)
print(self.idnumber)
print(self.post)
print(self.salary)
print('-------------')
@staticmethod
def change():
m=int(input('enter amount'))
n=int(input('enter choice\n 1 add\n 2 sub'))
if n==1:
self.salary = self.salary+m
elif n==2:
self.salary = self.salary-m
else:
print('nothing')
# child class
class Employee( Person ):
def __init__(self, name, idnumber, post, salary=False):
self.name = name
self.idnumber = idnumber
self.salary = salary
self.post = post
@staticmethod
def change():
if self.salary == False:
self.salary=(int(input('enter the salary')))
else:
print('nothing')
def display(self):
print(self.name)
print(self.idnumber)
print(self.post)
print(self.salary)
print('-------------')
a1 = Person('Sachin',786007,'tester')
a2 = Person('Tejaswi',786007,'developer',600000)
#b1 = Employee('Naveen',7367878,'analyst')
#b2 = Employee('Nimish',7367878,'developer',450000)
a1.display()
a2.display()
#b1.display()
#b2.display()
a1.change()
a2.change()
a1.display()
a2.display()
#b1.change()
#b2.change()
#b1.display()
#b2.display()
|
a67c178eb52e847d7d814a6d32f4f5e173a181d0 | BKBetz/ML | /P3/test/neurontest_wrong.py | 3,611 | 3.75 | 4 | import unittest
from P3.code.neuron import Neuron
from P3.code.neuronlayer import NeuronLayer
from P3.code.neuronnetwork import NeuronNetwork
"""
De neuron werkt niet alleen met 0 en 1 outputs maar kan ook bijvoorbeeld 0.3 als output krijgen.
Dit komt doordat een neuron gebruikt maakt van de sigmoid functie
dus de antwoorden zullen nooit hetzelfde zijn als bij een perceptron.
De perceptron heeft een stepfunction wat betekent dat het alleen 0 of 1 als output kan hebben.
Een neuron kan een output tussen de 0 en 1 hebben.
Hieronder staan de tests met de perceptron waardes in een neuron
"""
class NeuronTestWrong(unittest.TestCase):
def testNOT(self):
t1 = Neuron([-1], 0.5)
layer_1 = NeuronLayer([t1])
network = NeuronNetwork([layer_1])
outputs = []
# round the number that you get from feedforward...the function returns a list so we get the first item with [0]
o1 = round(network.feed_forward([1])[0])
o2 = round(network.feed_forward([0])[0])
outputs.append(o1)
outputs.append(o2)
# De invert werkt gewoon met dezelfde waardes
self.assertEqual([0, 1], outputs)
def testAND(self):
t1 = Neuron([0.5, 0.5], -1)
layer_1 = NeuronLayer([t1])
network = NeuronNetwork([layer_1])
outputs = []
for x in range(0, 2):
for y in range(0, 2):
# round the number that you get from feedforward...the function returns a list so we get the first item with [0]
o = round(network.feed_forward([x, y])[0])
outputs.append(o)
self.assertNotEqual([0, 0, 0, 1], outputs)
def testOR(self):
t1 = Neuron([0.5, 0.5], -0.5)
layer_1 = NeuronLayer([t1])
network = NeuronNetwork([layer_1])
outputs = []
for x in range(0, 2):
for y in range(0, 2):
# round the number that you get from feedforward...the function returns a list so we get the first item with [0]
o = round(network.feed_forward([x, y])[0])
outputs.append(o)
self.assertNotEqual([0, 1, 1, 1], outputs)
def testNOR(self):
t1 = Neuron([-1, -1, -1], 0)
layer_1 = NeuronLayer([t1])
network = NeuronNetwork([layer_1])
outputs = []
for x in range(0, 2):
for y in range(0, 2):
for z in range(0, 2):
# round the number that you get from feedforward...the function returns a list so we get the first item with [0]
o = round(network.feed_forward([x, y, z])[0])
outputs.append(o)
self.assertNotEqual([1, 0, 0, 0, 0, 0, 0, 0], outputs)
def testHalfAdder(self):
t1 = Neuron([1, 1], -1)
t2 = Neuron([-1, -1], 1.5)
t3 = Neuron([1, 1], -2)
# carry
t4 = Neuron([0, 0, 1], -1)
# sum
t5 = Neuron([1, 1, 0], -2)
layer_1 = NeuronLayer([t1, t2, t3])
layer_2 = NeuronLayer([t4, t5])
network = NeuronNetwork([layer_1, layer_2])
outputs = []
for x in range(0, 2):
for y in range(0, 2):
# round the number that you get from feedforward...the function returns a list.
# We need to round both items in the list so we seperate it with [0] and [1]
o = [round(network.feed_forward([0, 0])[0]), round(network.feed_forward([0, 0])[1])]
outputs.append(o)
self.assertNotEqual([[0, 0], [0, 1], [0, 1], [1, 0]], outputs)
|
89a278410ca989bafd474faf0d6a164b54eb4c16 | Klose6/Leetcode | /863_all_nodes_distance_in_bt.py | 1,230 | 3.546875 | 4 | """
863 all node distance K in binary tree
*each node value is unique
"""
import collections
class Node(object):
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class solution(object):
def distanceK(self, root, target, K):
def dfs(node, parent=None):
if node:
root.parent = parent
dfs(root.left, parent=root)
dfs(root.right, parent=root)
dfs(root)
queue = collections.deque([(target, 0)])
visited = [target]
while queue:
if queue[0][1] == K:
return [node.val for node, d in queue]
node, d = queue.popleft()
for nei in (node.parent, node.left, node.right):
if nei and nei not in visited:
visited.append(nei)
queue.append((nei, d + 1))
return []
def distanceK1(self, root, target, K):
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left:
connect(child, child.left)
if child.right:
connect(child, child.right)
connect(None, root)
bfs = [target.val]
seen = set(bfs)
for i in range(K):
bfs = [y for x in bfs for y in conn[x] if y not in seen]
seen |= set(bfs)
return bfs
|
322ce6ec39a49ba60d6f1bdec75e44144ff3dc05 | sogoodnow/python-study | /week1/week1_multi99.py | 3,978 | 3.984375 | 4 | # 使用while和for…in两个循环分别输出四种九九乘法表效果(共计8个)。
# 学员姓名:邱国昌
# 日期:2018-03-15
# 用于控制行间隔
LINE_SPACE = 25
def work1():
"""
1.九九乘法表
"""
# ========for in 左上三角=========
print("===="*LINE_SPACE+"\n")
print("for in左上三角" + "\n")
# 生成10行
for i in range(1, 10):
# 生成列
for j in range(1, i+1):
# 格式化输出
print("{}×{}={}".format(j, i, i*j), end=" ")
# 换行
print("\n")
# ========for in 左下三角=========
print("===="*LINE_SPACE+"\n")
print("for in左下三角" + "\n")
# 生成10行
for i in range(9, 0, -1):
# 生成列
for j in range(1, i+1):
# 格式化输出
print("{}×{}={}".format(j, i, i*j), end=" ")
# 换行
print("\n")
# ========for in 右上三角=========
print("===="*LINE_SPACE+"\n")
print("for in右上三角" + "\n")
# 生成10行
for i in range(1, 10):
# 生成格式空格
for k in range(1, 10-i):
print(end=" ") # 打印算式间的空格
# 生成列
for j in range(1, i+1):
# 格式化输出
print("{}×{}={:2}".format(j, i, i*j), end=" ")
# 换行
print("\n")
# ========for in 右下三角=========
print("===="*LINE_SPACE+"\n")
print("for in右下三角" + "\n")
# 生成10行
for i in range(9, 0, -1):
# 生成格式空格
for k in range(1, 10-i):
print(end=" ") # 打印算式间的空格
# 生成列
for j in range(1, i+1):
# 格式化输出
print("{}×{}={:2}".format(j, i, i*j), end=" ")
# 换行
print("\n")
# ========while 左上三角=========
print("===="*LINE_SPACE+"\n")
print("while 左上三角" + "\n")
while i < 10: # 从1到9遍历
j = 1 # 每次进入循环时把j重置为1
while j < i+1: # 每行行数i 乘以 列 j,行数和列数是相等的,例如9行9列,5行5列
print("{}×{}={:2}".format(j, i, i*j), end=" ")
j += 1
print("")
i += 1
# ========while 左下三角=========
print("===="*LINE_SPACE+"\n")
print("while 左下三角" + "\n")
i = 9 # 注意,此处i值由改变
while (i < 10) and (i > 0):
j = 1
while j < i+1:
print("{}×{}={:2}".format(j, i, i*j), end=" ")
j += 1
print("")
i -= 1
# ========while 右上三角=========
print("===="*LINE_SPACE+"\n")
print("while 右上三角" + "\n")
while i < 10:
m = 1 # 初始m为1
'''while 与 for in有区别, for in 中的临时变量定义后为函数局部变量,函数域内可用,并且值会改变
while 中的变量需要显示定义 ,如此处的 while m ,需在使用前定义m=1
'''
while m < 10-i:
print(end=" ") # 打印算式间的空格
m += 1
j = 1
while j < i+1:
print("{}×{}={:2}".format(j, i, i*j), end=" ")
j += 1
print("")
i += 1
# ========while 右下三角=========
print("===="*LINE_SPACE+"\n")
print("while 右下三角" + "\n")
i = 9 # 第一行打印乘数为9的行
while (i < 10) and (i > 0): # 从9 开始遍历,每次减去1
m = 1 # 初始m为1,空格控制变量,初始值为1 ,表示打印一个单位的空格
while m < 10-i: # 需打印的空格数为,10减去当前乘数
print(end=" ") # 打印算式间的空格
m += 1
j = 1
while j < i+1:
print("{}×{}={:2}".format(j, i, i*j), end=" ")
j += 1
print("")
i -= 1
return 1 # 函数正常结束后,返回1
|
d214cfe75dc6b11d620c75247b21f2953ceda2dc | izham-sugita/python3-tutorial | /py-function.py | 1,737 | 4.125 | 4 | '''
def functionname(parameters):
"function comment"
function_suite
return [expression]
'''
def printme( str ):
"This function prints the string input"
print( str )
return
def foo(arg1):
return 2*arg1
#calling the function
#str = "This is the string to print"
#printme(str)
#pass by value
def changeme( mylist ):
"This changes a passed list"
print ("Value before: ", mylist)
mylist[2] = 50
print ("Value after: ", mylist)
return
#mylist = [10,20,30]
#changeme(mylist)
# *vartuple is a tupple, more or less like a dynamic array
def printinfo( *vartuple ):
for var in vartuple:
print( var )
return
#printinfo(1, 2, 3, 4)
def sum( arg1, arg2 ):
total = arg1 + arg2
print("Inside the function : ", total)
return total
#addition = sum(10,20)
#print(addition) # will print "None" because nothing is returned
def sum2( arg1, arg2, arg3):
arg3[0] = arg1[0] + arg2[0]
return
def sum3(arg1,arg2,arg3):
arg3 = arg1 + arg2
print(arg3,'Inside function')
return
def sum4(arg1, arg2, arg3):
arg3[:] = arg1[:] + arg2[:]
return
if __name__ == '__main__':
str="New"
print(sum(10,10))
str = "Sugita"
printme(str)
a=[10]
b=[10]
c=[0]
sum2(a,b,c)
print(c[0])
del a,b,c
a =1
b =2
c =0
sum3(a,b,c)
print(c)
del a,b,c
import numpy as np
a = np.ndarray(shape=(1), dtype=int)
b = np.ndarray(shape=(1), dtype=int)
c = np.ndarray(shape=(1), dtype=int)
a[0] = 1
b[0] = 2
c[0] = 0
sum4(a,b,c)
print(c[0]) #will return 3 because np.ndarray is mutable.
|
2b36fed842e7072b6c65905b3ef13ec29185f905 | zzy1120716/my-nine-chapter | /ch09/0654-sparse-matrix-multiplication.py | 1,854 | 3.78125 | 4 | """
654. 稀疏矩阵乘法
给定两个 稀疏矩阵 A 和 B,返回AB的结果。
您可以假设A的列数等于B的行数。
样例
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
"""
"""
方法一:普通方法
"""
class Solution:
"""
@param A: a sparse matrix
@param B: a sparse matrix
@return: the result of A * B
"""
def multiply(self, A, B):
# write your code here
m, n, s = len(A), len(B), len(B[0])
C = [[0] * s for _ in range(m)]
for i in range(m):
for j in range(s):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
"""
方法二:先找到所有非零的点
"""
class Element: # point in matrix
def __init__(self, val, row, col):
self.val = val
self.row = row
self.col = col
class Solution:
"""
@param A: a sparse matrix
@param B: a sparse matrix
@return: the result of A * B
"""
def multiply(self, A, B):
# write your code here
elements_A = self._get_non_zero_elements(A)
elements_B = self._get_non_zero_elements(B)
C = [[0] * len(B[0]) for _ in range(len(A))]
for elem_A in elements_A:
for elem_B in elements_B:
if elem_A.col == elem_B.row:
C[elem_A.row][elem_B.col] += elem_A.val * elem_B.val
return C
def _get_non_zero_elements(self, A):
elements = []
for row in range(len(A)):
for col in range(len(A[0])):
if A[row][col] == 0:
continue
elements.append(Element(A[row][col], row, col))
return elements
|
8348cc761201d381073673ad444ea3837fb9bea3 | MortZx/Project-Euler | /Python/problem001.py | 622 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 12:15:26 2018
@author: MortZ
Project Euler Problem 1
"""
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
from timeit import default_timer as timer
# Check if number is divisible by 3 or 5 and add to the sum
def compute():
ans = sum(i for i in range(1000) if (i % 3 == 0 or i % 5 == 0))
return ans
if __name__ == "__main__":
start = timer()
print(compute())
end = timer()
print(end - start) |
0da0d569b9c14fd0616615e3a810aaff1b28a70d | tsitokely/pdsnd_github | /bikeshare.py | 10,332 | 4.28125 | 4 | import time
import pandas as pd
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def separator(size):
if size.lower() =='big':
print('-' * 40)
elif size.lower() =='little':
print('-' * 20)
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington).
# use a while loop to ensure that the selection is not empty
while True:
# use a while loop to ensure the right input for the variable city
while True:
city = input('Please enter a city name from: chicago, new york city or washington: ')
# Transform the input to a string in lower format to ensure compatibility with correct data
city = str(city).lower()
# check if the input is one of the correct city then break the loop or display an error message
if city in CITY_DATA.keys():
break
else:
print('Error: you did not type a correct city name:\ninput:"{}"\n'.format(city))
separator('little')
# get user input for month (all, january, february, ... , june)
# use a while loop to ensure the right input for the variable month
while True:
month = input('Please enter a month or type "all" if you would like to get all months:\n')
# Transform the input to a string in lower format to ensure compatibility with correct data
month = str(month).lower()
# Create a list of month names
months = ('all', 'january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december')
# check if the input is one of the correct month name then break the loop or display an error message
if month in months:
break
else:
print('Error: you did not type a correct month name:\ninput:"{}"\n'.format(month))
separator('little')
# get user input for day of week (all, monday, tuesday, ... sunday)
# use a while loop to ensure the right input for the variable day
while True:
day = input('please enter a day name or type "all" if you would like to get all days of the week:\n')
# Transform the input to a string in lower format to ensure compatibility with correct data
day = str(day).lower()
# Create a list of days name
week_days = ('all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday')
# check if the input is one of the correct day name then break the loop or display an error message
if day in week_days:
break
else:
print('Error: you did not type a correct day name:\ninput:"{}"\n'.format(day))
separator('little')
if load_data(city, month, day).empty:
print('There is no data in the selection, please choose a valid data with valid month name or day name')
print('input= city:', city, ' month: ', month, 'day: ', day)
print('You are required to choose a new dataset\n')
separator('big')
prompt = input("--Please type a key to continue--\n")
else:
break
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# read the related csv file
df_ = pd.read_csv(CITY_DATA[city])
# transform the 'Start Time' column to a datetime data
df_['Start Time'] = pd.to_datetime(df_['Start Time'])
# extract the month name from the 'Start Time' column then create the new column month
df_['month'] = df_['Start Time'].dt.month_name()
# extract the day name from the 'Start Time' column then create the new column day
df_['day'] = df_['Start Time'].dt.day_name()
# if filters are required on month or day
# filter on input month
if month != 'all':
# put in format title the month and day as those columns are in that format
month = month.title()
df_ = df_[df_['month'] == month]
# filter on input day-"if" is used as it is possible that both month and day condition are true at the same time
if day != 'all':
# put in format title the month and day as those columns are in that format
day = day.title()
df_ = df_[df_['day'] == day]
return df_
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
prompt = input("")
# Check the computation time of the time_stats function
start_time = time.time()
# display the most common month
print("The most common month in the selected data is: {}".format(df['month'].mode()[0]))
# display the most common day of week
print("The most common day of week in the selected data is: {}".format(df['day'].mode()[0]))
# display the most common start hour
# for that purpose, an extract of the hour from start time is required first
df['hour'] = df['Start Time'].dt.hour
print("The most common start hour in the selected data is: {}".format(df['hour'].mode()[0]))
print("\nThis took %s seconds." % (time.time() - start_time))
separator('big')
prompt = input("--Please type a key to continue--\n")
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
prompt = input("")
start_time = time.time()
# display most commonly used start station
print("The most commonly used start station in the selected data is: {}".format(df['Start Station'].mode()[0]))
# display most commonly used end station
print("The most commonly used end station in the selected data is: {}".format(df['End Station'].mode()[0]))
# display most frequent combination of start station and end station trip
# for that purpose, we need to concatenate the start and end station
df['start and end station'] = df['Start Station'] + ' -> ' + df['End Station']
print("The most frequent combination of start station and end station trip in the selected data is:{}".format(
df['start and end station'].mode()[0]))
print("\nThis took %s seconds." % (time.time() - start_time))
separator('big')
prompt = input("--Please type a key to continue--\n")
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
prompt = input("")
start_time = time.time()
# display total travel time
print("The total travel time in the selected data is: {} days".format(round(df['Trip Duration'].sum()/86400, 2)))
# display mean travel time
print("The total travel time in the selected data is: {} minutes".format(round(df['Trip Duration'].mean()/60, 2)))
print("\nThis took %s seconds." % (time.time() - start_time))
separator('big')
prompt = input("--Please type a key to continue--\n")
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
prompt = input("")
start_time = time.time()
# Display counts of user types
print("Printing the count for types...")
separator('big')
print(pd.DataFrame(df['User Type'].value_counts()))
separator('little')
prompt = input("--Please type a key to continue--\n")
# Display counts of gender
try:
print("Printing the count for gender...")
separator('big')
print(pd.DataFrame(df['Gender'].value_counts()))
except KeyError:
print("There's no Gender column in the selected dataset ")
prompt = input("--Please type a key to continue--\n")
# Display earliest, most recent, and most common year of birth
try:
print("Printing the statistics for year of birth...")
separator('big')
print("The earliest year of birth is: {}".format(int(df['Birth Year'].min())))
print("The most recent year of birth is: {}".format(int(df['Birth Year'].max())))
print("The most common year of birth is: {}".format(int(df['Birth Year'].mode())))
except KeyError:
print("There's no Birth Year column in the selected dataset ")
separator('big')
print("\nThis took %s seconds." % (time.time() - start_time))
prompt = input("--Please type a key to continue--\n")
separator('big')
def display_raw_data(df):
counter = 0
while True:
raw_data = input('\nWould you like to see 5 lines of raw data? yes or no\n')
if raw_data.lower() == 'yes':
display = df.iloc[counter:counter+5]
if display.empty:
print('\nEnd of file reached, no more data to display\n')
prompt = input("--Please type a key to continue--\n")
break
else:
print(display)
counter += 5
else:
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_raw_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
e3aa39ff8e3177cd33a0b55bf600d490f271ca55 | julgachancipa/holbertonschool-machine_learning | /math/0x03-probability/normal.py | 1,725 | 3.890625 | 4 | #!/usr/bin/env python3
"""Normal distribution"""
pi = 3.1415926536
e = 2.7182818285
def erf(x):
"""error function encountered in
integrating the normal distribution"""
a = (2 / (pi**(1/2)))
b = (x - ((x**3)/3) + ((x**5)/10) - ((x**7)/42) + ((x**9)/216))
return a * b
class Normal:
"""Represents an normal distribution"""
def __init__(self, data=None, mean=0., stddev=1.):
"""Initialize Normal"""
self.data = data
if data is None:
if stddev <= 0:
raise ValueError('stddev must be a positive value')
self.stddev = float(stddev)
self.mean = float(mean)
else:
if type(data) != list:
raise TypeError('data must be a list')
if len(data) < 2:
raise ValueError('data must contain multiple values')
self.mean = sum(data) / len(data)
s_dif = []
for d in data:
s_dif.append((d - self.mean)**2)
self.stddev = (sum(s_dif) / len(s_dif))**(1/2)
def z_score(self, x):
"""Calculates the z-score of a given x-value"""
return (x - self.mean) / self.stddev
def x_value(self, z):
"""Calculates the x-value of a given z-score"""
return self.stddev * z + self.mean
def pdf(self, x):
"""Calculates the value of the PDF for a given x-value"""
aux = ((x - self.mean) / self.stddev)**2
return (1 / (self.stddev * (2 * pi)**(1/2))) * e**((-1/2) * aux)
def cdf(self, x):
"""Calculates the value of the CDF for a given x-value"""
aux = (x - self.mean)/(self.stddev * (2**(1/2)))
return (1/2) * (1 + erf(aux))
|
7593db82398cd5fc4d4f070ba89f8cee00856015 | Randle9000/pythonCheatSheet | /pythonCourseEu/1Basics/17Regex/Examples.py | 915 | 4.34375 | 4 | s = "Regular expressions easily explained!"
print("easily" in s)
#########################
print()
import re
x = re.search("cat","A cat and a rat can't be friends.")
print(x)
x = re.search("cow","A cat and a rat can't be friends.")
print(x)
#############################
print()
if re.search("cat", "A cat and a rat can't be friends."):
print("Some kind of cat has been found :-)")
else:
print("No cat has been found :-)")
##########################
print()
if re.search("cow","A cat and a rat can't be friends."):
print("Cats and Rats and a cow.")
else:
print("No cow around.")
a = re.search(r'.at','cat, bat, dog')
print(a)
#######################
import re
line = "He is a German called Mayer."
if re.search(r"M[ae][iy]er",line): print("I found one!")
#re.match # match(re_str, s) checks for a match of re_str merely at the beginning of the string.
|
661c063e1769baac227226468e8b7036688371c8 | rasibkn/rasib | /ir4.py | 78 | 3.765625 | 4 | a=12
b=0
if(a>b):
print("a is greater than b")
else:
print("b is greater a") |
f6d80c56d8959645c641a3fb0210985c32737e5e | penroselearning/pystart_code_samples | /14 Dictionary - Shopping Cart.py | 502 | 4 | 4 |
# Shopping Cart
shopping_cart = {'eggs':3.50,
'milk':4.50,
'cheese':3.75,
'yoghurt':2.75,
'butter':3.00,
'more cheese':1.75}
shopping_cart.update({'ketchup':4.50})
shopping_cart.update({'milk':4.75})
total_bill = 0
print("Final Shopping Cart")
print('-'*30)
for goods,price in shopping_cart.items():
total_bill += price
print(f'{goods.title():15} ${price}')
print('-'*30)
print(f'{"Total Bill":15} ${total_bill}')
shopping_cart.pop('cheese')
print(f'{number} x {x+1} = {number * (x+1)}') |
c1a95ff927274e2212e29b4068a5ce8943f1e119 | aryabiju37/Python-mini-Proects | /oop/animal_multiple_inheritance.py | 746 | 4 | 4 | class Aquatic:
def __init__(self,name):
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self,name):
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land"
class Penguin(Ambulatory,Aquatic):
def __init__(self,name):
super().__init__(name)
#if you are not inheriting using super you need to send the self too
# Aquatic().__init__(self,name=name)
mister_penguin = Penguin("Mr Penguin")
print(mister_penguin.walk())
print(mister_penguin.swim())
print(mister_penguin.greet()) |
f182d6e25a8e1604bc2da6d14fffe60c405366d1 | Songbz1999/pythonForFinance | /lesson2/PY-2-1.py | 559 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 15:29:27 2018
@author: Thinkpad
"""
'''
1. Write a program that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order.
For example, say I type the string:
My name is Steven
Then I would see the string:
Steven is name My
shown back to me.
'''
def get_sent():
l = input("give me a long string containing multiple words:")
word = l.split()
ans = word[::-1]
return ans
a = get_sent()
print(' '.join(a)) |
c6be48cffe3ba313002e695c88128d682c9f2c62 | wihoho/LearningPython | /src/Syntax/4) ShowCurrentTime.py | 326 | 3.703125 | 4 | import time
currentTime = time.time()
totalSeconds = int(currentTime)
currentSeconds = totalSeconds % 60
totalMinutes = totalSeconds // 60
currentMinute = totalMinutes % 60
totalHours = totalMinutes // 60
currentHour = totalHours % 24
print("Current time is",currentHour,":",currentMinute,":",currentSeconds) |
ae77ad8f0577281f8286c3aef417bee9f884ee07 | ZENALC/jsonpickle | /Play Environment/playCode.py | 2,722 | 3.671875 | 4 | # Demonstration Code
import jsonpickle
class Student:
def __init__(self):
self.name = None
self.age = 50
self.hairColor = "Black"
self.ethnicity = None
self.eyeColor = "Black"
self.enrolled = True
self.x = [1, 2, 3, 4, 5, 6, 7]
def __str__(self):
try:
return "{} is {} years old".format(self.name, self.age)
except Exception as e:
return "Error: " + str(e)
# Function that shows null values not being encoded
def classExample():
"""
For some classes, it can be much more concise to ignore/drop any field that is null. Could there be an optional
parameter that enables this?
"""
# Null Values Decoding
mihir = Student()
print("\nStart of class example:")
withNull = jsonpickle.encode(mihir)
withoutNull = jsonpickle.encode(mihir, nullValues=False)
print("JSON Data with null info :", withNull)
print("JSON Data without null info:", withoutNull)
withNullDecoded = jsonpickle.decode(withNull)
withoutNullDecoded = jsonpickle.decode(withoutNull)
print("Decoded object with null info :", withNullDecoded)
print("Decoded object without null info:", withoutNullDecoded)
print()
# Function that shows null values not being encoded in a dict
def dictExample():
print("Start of dict example:")
sampleDict = {"name": "Mihir", "age": 21, "hairColor": "black", "eyeColor": None, "ethnicity": None,
"isStudent": True}
encodedDictWithNull = jsonpickle.encode(sampleDict, nullValues=True)
encodedDictWithoutNull = jsonpickle.encode(sampleDict, nullValues=False)
print("This is the encoded dict with null values :", encodedDictWithNull)
print("This is the encoded dict without null values:", encodedDictWithoutNull)
print()
# Function that shows functions can be encoded in JSON format
def functionExample():
print("Start of function encoding example")
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
filename = "functionDump.json"
with open(filename, "w") as f:
functionEncoded = jsonpickle.encode(fibonacci, encodeFunctionItself=True)
f.write(functionEncoded)
print("Encoded function:", functionEncoded)
print("Function has been dumped to", filename)
print()
# classExample()
# dictExample()
functionExample()
with open("functionDump.json", 'r') as f:
jsonCode = f.read()
fibonacci = jsonpickle.decode(jsonCode, encodeFunctionItself=True)
print("PRINTED CONTENT OF FUNCTION CODE:\n\n" + fibonacci)
exec(fibonacci)
for i in range(10):
print(fibonacci(i))
|
320877388ad7c70c6bdf488d10e534065f3b84e9 | Kookey/pythonworks | /9/9.5/try/die.py | 469 | 3.828125 | 4 | from random import randint
class Die():
"""摇骰子"""
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
x = randint(1, self.sides)
print(x)
die = Die()
die.roll_die()
print("\n")
for x in range(1, 11):
die.roll_die()
print("10面的色子")
die_10 = Die(sides=10)
for x in range(1, 11):
die_10.roll_die
print("20面的色子")
die_20 = Die(sides=20)
for x in range(1, 11):
die_20.roll_die()
|
cb1b8757ad57bc180e6d5cc5b50d8946843e0642 | daniil172101/RTR108 | /darbi/Py4E/OOP/python_diary_OOP_1_20200722.py | 400 | 4.125 | 4 | stuff = list() # Construct an object of type list
stuff.append('python') # Adds in a list an item 'python'
stuff.append('chuck') # Adds in a list an item 'chuck'
stuff.sort() # Sort list in alphabetical order
# The next 3 lines prints the item of a list with a parameter of zero.
print (stuff[0])
print (stuff.__getitem__(0))
print (list.__getitem__(stuff,0))
|
f7a0d41ae132905a2749f351e906dd37898ab46d | chenc19920308/python_untitled | /Function/Practice/fact_func.py | 693 | 4.375 | 4 | #use recursin
# def factorial(n):
# if n == 1:
# return 1
# else:
# return n * factorial(n-1)
# number = int(input("your number:"))
# print("your number's factorial:%d"%factorial(number))
# no recursion
# def factorial(n):
# result = n
# for i in range(1,n):
# result *= i
# return result
# number = int(input("your number:"))
# print("your number's factorial:%d"%factorial(number))
# no recursion and use while
# def factorial(n):
# count = 1
# result = 1
# while count <= n:
# result *= count
# count += 1
# return result
# number = int(input("your number:"))
# print("your number's factorial:%d"%factorial(number))
|
6aedcad22ce79e128bd2a9da5898a016ba8dd72b | Akash5454/100-Days-Coding | /pathSum.py | 474 | 4 | 4 | """
Path Sum: Given a binary tree and a sum, determine if the tree has a root-to-leaf path
such that adding up all the values along the path equals the given sum.
"""
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
sum = sum - root.val
if not root.left and not root.right:
return sum == 0
else:
return hasPathSum(root.left, sum) or hasPathSum(root.right, sum)
|
273fd3c2ab00d368067a8c84ca337ed2201899f8 | tianzhujiledadi/python | /排序算法比较/堆排序.py | 1,263 | 3.984375 | 4 |
def MAX_Heapify(heap,HeapSize,root):#在堆中做结构调整使得父节点的值大于子节点
left = 2*root+1
right = left + 1
larger = root
if left < HeapSize and heap[larger] < heap[left]:
larger = left
if right < HeapSize and heap[larger] < heap[right]:
larger = right
if larger != root:#如果做了堆调整则larger的值等于左节点或者右节点的,这个时候做对调值操作
heap[larger],heap[root] = heap[root],heap[larger]
MAX_Heapify(heap, HeapSize, larger)
def Build_MAX_Heap(heap):#构造一个堆,将堆中所有数据重新排序
HeapSize = len(heap)#将堆的长度单独拿出来方便
for i in range((HeapSize -2)//2,-1,-1):#从后往前出数
MAX_Heapify(heap,HeapSize,i)
def HeapSort(heap):#将根节点取出与最后一位做对调,对前面len-1个节点继续进行堆调整过程。
Build_MAX_Heap(heap)
for i in range(len(heap)-1,-1,-1):
heap[0],heap[i] = heap[i],heap[0]
MAX_Heapify(heap, i, 0)
return heap
if __name__ == '__main__':
import random
import time
a=[]
for i in range(10000):
a.append(random.randint(0,10000))
print(a)
start=time.time()
print(HeapSort(a))
end=time.time()
print(end-start) |
1618c67eef065a364eb5b21cb2d82371ca22fd17 | billsu2013/pyschool | /04-04.py | 229 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 12:58:16 2018
@author: dell
"""
def addNumbers(num):
a=0
for i in range (1,num+1):
a=a+i
return a
b=addNumbers(0)
print (b)
|
f2e5f4910fbdd7cbdcd2571db51cf08039396dc0 | aFuzzyBear/Python | /python/Scripts/ran_number.py | 595 | 3.609375 | 4 | #print random lottery numbers
import random
"""
Make two lists
One is a random number list with a maximum of 6 numbers
Second list is 2 numbers randomly generated.
"""
lotto = range(0,52)
print lotto
def num_gen():
gen = random.randint(1,51)
return gen
ball1 = num_gen()
ball2 = num_gen()
ball3 = num_gen()
ball4 = num_gen()
ball5 = num_gen()
ball6 = num_gen()
print ball1
print ball2
print ball3
print ball4
print ball5
print ball6
list = []
list.append(ball1)
list.append(ball2)
list.append(ball3)
list.append(ball4)
list.append(ball5)
list.append(ball6)
print list.sort()
|
d9ccefb5e37d8d4efc1f84461501fcd763cf94f6 | Ratnakarmaurya/Data-Analytics-and-visualization | /working with data/03_Html with pyhton.py | 567 | 3.59375 | 4 | import numpy as np
from pandas import Series,DataFrame
import pandas as pd
from pandas import read_html
#Lets grab a url for list of failed banks
url ="http://www.fdic.gov/bank/individual/failed/banklist.html"
"""
IMPORTANT NOTE: NEED TO HAVE beautiful-soup INSTALLED as well as html5lib !!!!
"""
# Grab data from html and put it intop a list of DataFrame objects!
dframe_list = pd.io.html.read_html(url)
dframe_list
#Grab the first list item from the data base(list of datas) and set as a DataFrame
dframe = dframe_list[0]
dframe.columns.values
|
f82628cdefcfe7e2e3164179cf2dff742ed92f49 | prashanthr11/HackerRank | /Python/Collections/Collections.deque().py | 359 | 3.59375 | 4 | from collections import deque
l = deque()
for i in range(int(input())):
s = list(map(str, input().split()))
if len(s) == 2:
if s[0] == "append":
l.append(s[1])
if s[0] == "appendleft":
l.appendleft(s[1])
else:
if s[0] == "pop":
l.pop()
else:
l.popleft()
print(*l)
|
3c5295c33ee8875735b0f0615f6afa5ebbf7a874 | JasmineIslamNY/Thinkful | /discount_calculator/discount_calculator.py | 3,175 | 4.25 | 4 | import argparse
def calculate_discount(item_cost, relative_discount, absolute_discount):
"""
Calculate the discounted price of item given the item cost,
a relative discount, and an additional price discount
"""
item_cost = float(item_cost)
relative_discount = float(relative_discount)
absolute_discount = float(absolute_discount)
if relative_discount < 1:
relative_discount *= 100
discounted_price = (item_cost - (item_cost * (relative_discount / 100)) - absolute_discount)
if discounted_price < 0:
discounted_price = 0
#trying to get rid of extra digits
discounted_price *= 100
discounted_price = int(discounted_price)
discounted_price /= 100.00
return discounted_price
def validate_entry(entry):
""" Validate for positive number or 0 """
try:
entry = float(entry)
if (entry < 0):
entry = -1
except TypeError:
entry = -1
return entry
def make_parser():
""" Construct the command line parser """
description = "This app allows you to enter a cost and discounts to get the discounted price"
parser = argparse.ArgumentParser(description = description)
parser.add_argument("Cost", help="The cost before discount")
parser.add_argument("Percentage", help="Enter the % discount without the % sign, e.g. 10 for 10%")
parser.add_argument("Dollar", help="Enter the $ discount without the $ sign, e.g. 20 for $20")
return parser
def get_amounts():
""" This will get the cost and discounts from the user if CLI inputs are invalid """
print "Some of your entries were invalid, please re-enter..."
item_cost = raw_input("Please enter how much the item cost: ")
relative_discount = raw_input("Please enter the discount amount: ")
absolute_discount = raw_input("Please enter the $ amount discount: ")
return item_cost, relative_discount, absolute_discount
def discount_calculator(item_cost, relative_discount, absolute_discount):
cost = validate_entry(item_cost)
relative = validate_entry(relative_discount)
absolute = validate_entry(absolute_discount)
if (cost == -1 or relative == -1 or absolute == -1):
print "Invalid number entered for cost and/or discount"
raise ValueError("Invalid entry")
# return -1 - in production would remove the ValueError and just prompt user to reinput values
else:
discounted_price = calculate_discount(cost, relative, absolute)
print "Discounted price is ${:.2f}".format(discounted_price)
return discounted_price
def main():
parser = make_parser()
args = parser.parse_args()
item_cost = args.Cost
relative_discount = args.Percentage
absolute_discount = args.Dollar
discounted_price = discount_calculator(item_cost, relative_discount, absolute_discount)
if discounted_price == -1:
item_cost, relative_discount, absolute_discount = get_amounts()
discounted_price = discount_calculator(item_cost, relative_discount, absolute_discount)
return discounted_price
if __name__ == "__main__":
main() |
2d8936e602a5fe0d95f7e0b47fb18523dce0ebfe | channing342/Python | /Day6/exercise0602.py | 273 | 3.703125 | 4 | #-*- coding: UTF-8 -*-
#File Name : exercise0601.py
#Edit : Channing Liu
#Time Date : 20160631
a = int(raw_input("Number a: "))
b = int(raw_input("Number b: "))
if a == b:
print (" a = b ")
elif a > b:
print (" a > b ")
elif a < b:
print (" a < b ")
else:
print ( Null )
|
c8f319077ae4cd194bc3e9c2ebcdc97bb3fcff2d | JoKerDii/Thinkpy-mySol | /Exercise5.5.py | 886 | 4.40625 | 4 | def draw(t, length, n):
"""Draw a tree
The branch length depends on both length arg and n arg (length*n)
The number of node is n
"""
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
# recursion begins from "n-1" because the tree becomes binary from "n-1"
# this is the left part from the "n-1" because the "draw" function follows the "turr left" command
draw(t, length, n-1)
# turn twice of the angle of right to make sure the symmetry, because the point has turned left for an angle
t.rt(2*angle)
# this is the right part from the "n-1" because the "draw" function follows the "turn right" command
draw(t, length, n-1)
# every recursion turn an angle to the original direction and go back to the node
t.lt(angle)
t.bk(length*n)
# test
# import turtle
# bob = turtle.Turtle()
# draw(bob, 10, 5)
|
a6f1c479169374a74da41f29de127a78a66a3124 | Ellviss/python | /l1/l4.py | 378 | 3.578125 | 4 | def get_sum(one,two,delimiter='&'):
one = str(one)
two = str(two)
#res = str(print(f'{one}{delimiter}{two}'))
return f'{one}{delimiter}{two}'
get_sum("Learn","python",)
print (get_sum("Learn","python",))
print(get_sum("Learn","python").upper())
def format_price(price):
price=int(price)
return 'Цена: '+str(price)+' руб.'
print(format_price(56.24)) |
db8f85e78fa9bc967343333b9766e2c8cf4ecb63 | sky-dream/LeetCodeProblemsStudy | /[0242][Easy][Valid_Anagram]/Valid_Anagram.py | 1,192 | 3.640625 | 4 | class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s)!=len(t):
return False
else:
#结果字典
dic = {}
#先遍历s,数每个字符出现的次数,存在字典dic中,key是字符,value是出现次数
for i in s:
if i in dic:
dic[i] +=1
else:
dic[i] = 1
#遍历t,遇见相同字符,就在dic中减一;遇见不同字符,直接返回false
for i in t:
if i in dic:
dic[i] -= 1
else:
return False
#遍历结果字典,是否每个value都为0
for i in dic:
if dic[i] != 0:
return False
return True
def main():
str1 = "anagram";
str2 = "nagaram";
Solution_obj = Solution()
result = Solution_obj.isAnagram(str1, str2);
print("In c code,result value is "+("FALSE" if result is False else "TRUE"));
if __name__ =='__main__':
main() |
877b71605f13814e9b802b96ef0d2f18f1aa4ece | Charles-IV/python-scripts | /recursion/fibbonachi.py | 232 | 3.65625 | 4 | from time import sleep
def add(x,y):
z = x + y # perform calculation
print(z) # output result
sleep(0.2) # HOLD! STOP! WAIT, to not kill my computer
add(y, z) # perform next calculation
print("0\n1")
add(0, 1)
|
ea1d94b162095516451d8d4af21ed5693b5e19d6 | BenThomas33/practice | /python/csdn/binary_tree2dlink.py | 666 | 3.78125 | 4 | """
# 1
convert a binary tree to double linked list
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from structs import binary_tree
def convert(root):
a, b, c, d = root, root, root, root
if root.left:
a, b = convert(root.left)
root.left = b
b.right = root
if root.right:
c, d = convert(root.right)
root.right = c
c.left = root
return a, d
def main():
n = binary_tree.array2tree([10, 6, 14, 4, 8, 12, 16])
a, d = convert(n)
tmp = a
while tmp:
print tmp.data
tmp = tmp.right
if __name__ == '__main__':
main()
|
4ca41cc5247699c3bfdf7480f0f4fd1200f278de | yejiiha/BaekJoon_step | /Practice 1/5543.py | 526 | 3.734375 | 4 | # Print minimum price
price_list_burger = []
price_list_drink = []
price_list_set = []
sum = 0
for a in range(0, 3):
a = int(input())
if 100 <= a <= 2000:
price_list_burger.append(a)
for b in range(0, 2):
b = int(input())
if 100 <= b <= 2000:
price_list_drink.append(b)
for i in range(0, 3):
price_list_set.append(price_list_burger[i] + price_list_drink[0] - 50)
price_list_set.append(price_list_burger[i] + price_list_drink[1] - 50)
price_list_set.sort()
print(price_list_set[0])
|
bbd79fb44eff6b792110bab2160eb5426f66f849 | bowrainradio/Python_Adventure | /Day_02(fahrenheit-converter&BMI-calculator&Pizza-order).py | 1,104 | 4.28125 | 4 | #Fahrenheit converter
f_temp = int(input("Temperature outside in Farenhite?\n"))
c_temp = round(((f_temp - 32) * 5/9), 2)
print(f"Your temperature in Celsius is: {c_temp}")
height = float(input("What's your height in m(for example: 1.4)\n"))
weight = float(input("What's your weight in kg\n"))
#BMI
bmi = round(weight / (height ** 2))
print(f"Your bmi is: {bmi}")
if bmi < 18.5:
print("You're underweight")
elif bmi < 25:
print("You have a normal weight")
elif bmi < 30:
print("You're overwight")
elif bmi < 35:
print("You're obese")
else:
print("You're clinically obese!")
# Pizza order program
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, L\n")
add_pepperoni = input("Do you want pepperoni? Y or N\n")
extra_cheese = input("Do you want extra cheese? Y or N\n")
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
else:
bill += 25
if add_pepperoni == "Y":
if size == "S":
bill += 2
else:
bill += 3
if extra_cheese == "Y":
bill += 1
print(f"Your total bill is {bill}") |
021979a7afe0edc0ea645537bf48a264941d5b09 | cook2298/Bellevue | /ClassProject.py | 2,444 | 4.0625 | 4 | '''
This program connects to openweathermap API to allow the user to input city or zip code to get current weather data for that location
Author: Jacob Cook
Written: 10/13/2020
'''
import requests
import json
APIID = "c98593e412245c9ce904a86281016ff1"
def inputData():
print("Please enter a zip code or city name: ")
return input()
def determineType(l): #use a try catch to check if input is zip or City
try:
l = int(l)
return "zip"
except ValueError:
return "city"
def cityAPICall(l): #copied partly from https://knasmueller.net/using-the-open-weather-map-api-with-python
url = "https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=imperial" % (l,APIID)
print("Connecting to Open Weather API...")
response = requests.get(url).json()
if response["cod"] == 200:
print("Connection Successful!")
return response
else:
return "error"
def zipAPICall(l): #copied from https://knasmueller.net/using-the-open-weather-map-api-with-python
url = "https://api.openweathermap.org/data/2.5/weather?zip=%s&appid=%s&units=imperial" % (l,APIID)
print("Connecting to Open Weather API...")
response = requests.get(url).json()
if response["cod"] == 200:
print("Connection Successful!")
return response
else:
return "error"
def formatAndDisplay(rawData):
print("City:", rawData["name"])
print("Temp:", rawData["main"]["temp"], "F°")
print("Feels Like: ", rawData["main"]["feels_like"], "F°")
print("Air Pressure: ", rawData["main"]["pressure"], "hPa")
print("Humidity:", rawData["main"]["humidity"], "%")
print("Wind Speed:", rawData["wind"]["speed"])
def main():
loopAgain = "yes"
while loopAgain == "yes":
location = inputData()
locType = determineType(location)
if locType == "city":
rawData = cityAPICall(location)
else:
rawData = zipAPICall(location)
if rawData == "error":
print("Error, invalid input.")
else:
formatAndDisplay(rawData)
print("Would you like to enter another? [yes or no]")
loopAgain = input()
print("Thanks for using Jacob's Weather App! Brought to you by OpenWeatherMap")
print("Learn more about this API at: https://openweathermap.org/")
main()
|
e5054432dcd9dba811d509469dfb86d98a12730a | mRrvz/bmstu-python | /sem_02/lab_02/zashita.py | 1,807 | 4.03125 | 4 | from tkinter import *
def change_text(list_to_sort):
for i in range(len(list_to_sort)):
label_sort["text"] += str(list_to_sort[i]) + " "
label_sort["text"] += "\n\n"
def bubble_sort(entry):
label_sort["font"] = "Arial 10"
list_to_sort = entry.get()
list_to_sort = list(map(int, list_to_sort.split()))
#print(list_to_sort)
label_sort["text"] = ""
change_text(list_to_sort)
count = 0
for i in range(len(list_to_sort)):
barrier = True
for j in range(len(list_to_sort) - 1):
count += 1
if list_to_sort[j + 1] < list_to_sort[j]:
list_to_sort[j + 1], list_to_sort[j] = list_to_sort[j], list_to_sort[j + 1]
barrier = False
change_text(list_to_sort)
if barrier:
break
if count == len(list_to_sort) - 1:
label_sort["font"] = "Arial 12"
label_sort["text"] = ""
change_text(list_to_sort)
label_sort["text"] += "\n\nМассив уже отсортирован!"
else:
label_sort["text"] += "Количество итераций: " + str(count)
root = Tk()
root.geometry("600x300")
root.maxsize(width=300, height=600)
root.minsize(width=300, height=600)
root.title("Сортировка пузырьком с баррьером")
entry_array = Entry(root)
start_sort = Button(root, text="Сортировать!", command=lambda:bubble_sort(entry_array))
label_sort = Label(root, text="Введите массив для сортировки", justify=CENTER, font="Arial 10", bg="green")
label_sort.place(x=20, y=90, width=265, height=490)
entry_array.place(x=10, y=18, width=280)
start_sort.place(x=10, y=40, width=280, height=30)
|
4275ffe5d5dc971d153d1f5a1bd593eab4666901 | WilliamPerezBeltran/studying_python | /prueba_evalart_2020.py | 3,094 | 3.859375 | 4 | import pdb
from copy import copy, deepcopy
myArray = [13,12,4,3,15]
pivote = True
data = None
for x in myArray:
if pivote:
data = x
pivote = False
else:
if x < data:
data =x
# return data
print(data)
# ==============================
n = 5
fila = n
columna = n
matriz = []
for i in range(fila):
matriz.append([])
for j in range(columna):
matriz[i].append(None)
pivote = True
for i in range(len(matriz)):
# pdb.set_trace()
for j in range(len(matriz[i])):
if pivote:
matriz[i][j] = "X"
pivote = False
else:
matriz[i][j] = "_"
pivote = True
# for x in matriz:
# print(x)
for i in range(len(matriz)):
# pdb.set_trace()
for j in range(len(matriz[i])):
print(matriz[i][j], end = '')
print()
# ==============================
print()
print()
print()
print("""
Pregunta 3
Escribir un programa utilizando Python que encuentre los dos elementos del arreglo que sumados dan 10. Se deben imprimir ambos números como resultado separados por un espacio (en el orden en que aparecen en el arreglo).
Por ejemplo, para el arreglo (1,3,4,2,7,0) el resultado seria: 3 7
""")
# myArray = [ 1,3,4,2,7,0 ]
# # pdb.set_trace()
# for x in range(len(myArray)):
# # newArray = myArray
# # newArray = myArray
# newArray = deepcopy(myArray)
# try:
# newArray.pop(x)
# except Exception as e:
# pdb.set_trace()
# for y in newArray:
# if myArray[x]+y == 10:
# print("%d %d"%(myArray[x],y))
# print()
# # print("entro")
# # pdb.set_trace()
myArray = [ 1,3,4,2,7,0 ]
pivote = True
for x in range(len(myArray)):
newArray = deepcopy(myArray)
newArray.pop(x)
for y in newArray:
if myArray[x]+y == 10 and pivote:
print("%d %d"%(myArray[x],y))
pivote = False
# print("entro")
# pdb.set_trace()
print("""
Pregunta 4
Se tiene una X en la esquina superior izquierda de
un área de 4x4. Se tiene una matriz con 10 elementos.
Cada 2 elementos de la matriz corresponden a un movimiento,
el primero en el eje horizontal y el segundo en el eje
vertical. El numero indica las unidades a moverse y el
signo la dirección (positivo para derecha o abajo,
negativo para izquierda o arriba)
Por ejemplo, para la matriz myArray:=(1,2,-1,1,0,1,2,-1,-1,-2)
La X se moverá una unidad a la derecha y dos hacia abajo, luego una unidad a la izquierda y una abajo y así sucesivamente. El programa a escribir debe imprimir la posición final de la X. Para representar los lugares donde la X no se encuentra utilizar la letra O. Si la instrucción obliga a la X a salir del área de 4x4 la X permanecerá en el borde, sin salir. Para el arreglo presentado el resultado se vería así:
OXOO
OOOO
OOOO
OOOO
""")
n=4
fila = n
columna = n
matriz = []
for i in range(fila):
matriz.append([])
for j in range(columna):
matriz[i].append(None)
pivote = True
for i in range(len(matriz)):
for j in range(len(matriz[i])):
if pivote:
matriz[i][j] = "X"
pivote = False
else:
matriz[i][j] = "_"
pivote = True
for i in range(len(matriz)):
for j in range(len(matriz[i])):
print(matriz[i][j], end = '')
print()
|
ac04b41381fdf0d3d4f36fcecd14608c28d5bde5 | mostiguy/Euler | /Euler project no 50.py | 1,455 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime,
contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive
primes?
"""
import time
from math_functions import prime_sieve
from math_functions import is_prime
start_time = time.time()
target = 1000000
prime = prime_sieve(int(target/2))
l_prime = len(prime)
max_psum = 0
max_consecutive = 0
max_prime = 0
p_list = []
start = 0
# Build a list of prime sums and the number of consecutive prime
for start in range(0,int(l_prime/2)):
p_sum = 0
p_list.clear()
for a in range(start,int(l_prime)):
p_sum += prime[a]
p_list.append(p_sum)
c = a+1-start
p_list.append(c)
if (is_prime(p_sum) and (p_sum < target)):
if (c > max_consecutive):
max_consecutive = c
max_psum = p_sum
if p_sum > target:
break
#print("Prime sum list and consecutive prime",p_list)
print("Prime sum and consecutive prime",max_psum,max_consecutive)
elapsed_time = time.time() - start_time
print ("Elapse time: {:.2f} sec".format(elapsed_time))
|
b4316aa8615e3f917da72a99e0649257da103811 | Negar-Sadreddini/aparat-API | /FULL - Final Project.py.py | 9,751 | 3.5 | 4 | import requests
import json, csv
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
informative_url = 'https://www.aparat.com/api#videobytag'
# This is a link which explains how we can extract data from Aparat's API, By reading it we decided to scrap Aparat's videos by their defferent tags(videobytag).
url_sports = 'https://www.aparat.com/etc/api/videobytag/text/%D9%88%D8%B1%D8%B2%D8%B4%DB%8C'
url_educational = 'https://www.aparat.com/etc/api/videobytag/text/%D8%A2%D9%85%D9%88%D8%B2%D8%B4%DB%8C'
url_nature = 'https://www.aparat.com/etc/api/videobytag/text/%DA%AF%D8%B1%D8%AF%D8%B4%DA%AF%D8%B1%DB%8C'
url_entertainment = 'https://www.aparat.com/etc/api/videobytag/text/%D8%AA%D9%81%D8%B1%DB%8C%D8%AD%DB%8C'
url_funny = 'https://www.aparat.com/etc/api/videobytag/text/%D8%B7%D9%86%D8%B2'
urls = [url_sports,url_educational,url_nature,url_entertainment,url_funny]
n = int(input('Number of pages')) # n is the number of pages we evaluate for each tag. Each page gives us information for 20 videos.
results = []
for url in urls:
for count in range(n):
print(count)
raw = requests.get(url = url)
response = raw.json()
# Response is a dictionary that it's first key's(videobytag) value, is a list of dictionaries of videos different information such as title,visit_cnt and duration.
url = response['ui']['pagingForward']
time.sleep(0.3) # We need to make halt in web scraping in order to avoid getting error and dropping out of the website!
for value in response['videobytag']:
results.append(value)
#print(results) # Results is a list of all information about all the videos. items of this list are dictionaries.
title_list,duration_list,visit_cnt_list = [],[],[]
for dict in results:
title_list.append(dict['title'])
duration_list.append(dict['duration'])
visit_cnt_list.append(dict['visit_cnt'])
df_dict = {'sports_title':title_list[0:(n*20)],'sports_duration':duration_list[0:(n*20)],'sports_visit_cnt':visit_cnt_list[0:(n*20)], \
'education_title':title_list[(n*20):(n*2*20)],'education_duration':duration_list[(n*20):(n*2*20)],'education_visit_cnt':visit_cnt_list[(n*20):(n*2*20)], \
'nature_title':title_list[(n*2*20):(n*3*20)],'nature_duration':duration_list[(n*2*20):(n*3*20)],'nature_visit_cnt':visit_cnt_list[(n*2*20):(n*3*20)], \
'entertainment_title':title_list[(n*3*20):(n*4*20)],'entertainment_duration':duration_list[(n*3*20):(n*4*20)],'entertainment_visit_cnt':visit_cnt_list[(n*3*20):(n*4*20)], \
'funny_title':title_list[(n*4*20):(n*5*20)],'funny_duration':duration_list[(n*4*20):(n*5*20)],'funny_visit_cnt':visit_cnt_list[(n*4*20):(n*5*20)]}
df = pd.DataFrame(df_dict)
print(df[df['sports_visit_cnt'] == max(df['sports_visit_cnt'])]['sports_title'])
print(df[df['education_visit_cnt'] == max(df['education_visit_cnt'])]['education_title'])
print(df[df['nature_visit_cnt'] == max(df['nature_visit_cnt'])]['nature_title'])
print(df[df['entertainment_visit_cnt'] == max(df['entertainment_visit_cnt'])]['entertainment_title'])
print(df[df['funny_visit_cnt'] == max(df['funny_visit_cnt'])]['funny_title'])
plt.bar(['Sports','Education','Nature','Entertainment','Funny'],[np.mean(df['sports_visit_cnt']),np.mean(df['education_visit_cnt']),np.mean(df['nature_visit_cnt']), \
np.mean(df['entertainment_visit_cnt']),np.mean(df['funny_visit_cnt'])],width=0.8)
plt.title('Comparision between Tags popularity')
plt.xlabel('Tags')
plt.ylabel('Mean Popularity')
plt.savefig('General collation barchart.png')
plt.show()
# With the help of scatter plot we can find outlyer data, and also general pattern!
plt.subplot(2,3,1)
plt.scatter(df['sports_duration'],df['sports_visit_cnt'],color='pink',label='For Sports')
plt.title('Sports')
plt.xlabel('Duration(s)')
plt.ylabel('Visit Count')
plt.legend()
plt.subplot(2,3,2)
plt.scatter(df['education_duration'],df['education_visit_cnt'],color='blue',alpha=.2,label='For Education')
plt.title('Education')
plt.xlabel('Duration(s)')
plt.legend()
plt.subplot(2,3,3)
plt.scatter(df['funny_duration'],df['funny_visit_cnt'],color='red',alpha=0.4,label='For Funny')
plt.title('Funny')
plt.xlabel('Duration(s)')
plt.legend()
plt.subplot(2,3,4)
plt.scatter(df['entertainment_duration'],df['entertainment_visit_cnt'],color='purple',alpha=0.4,label='For Entertainment')
plt.title('Entertainment')
plt.xlabel('Duration(s)')
plt.ylabel('Visit Count')
plt.legend()
plt.subplot(2,3,5)
plt.scatter(df['nature_duration'],df['nature_visit_cnt'],color='green',label='For Nature',alpha=0.2)
plt.title('Nature')
plt.xlabel('Duration(s)')
plt.legend()
plt.savefig('General scatter plots for each tag.png')
plt.show()
# Now we need to level duration, in order to evaluate the impact of video's duration on it's view count:
def leveling(n):
if n <= 20:
n = 'too short'
elif n>15 and n<=60:
n = 'short'
elif n>60 and n<=180:
n = 'medium'
elif n>180 and n<=900:
n = 'long'
else:
n = 'too long'
return n
df['sports_duration'] = list(map(lambda x: leveling(x),df['sports_duration']))
df['entertainment_duration'] = list(map(lambda x: leveling(x),df['entertainment_duration']))
df['education_duration'] = list(map(lambda x: leveling(x),df['education_duration']))
df['nature_duration'] = list(map(lambda x: leveling(x),df['nature_duration']))
df['funny_duration'] = list(map(lambda x: leveling(x),df['funny_duration']))
sports_duration = df.groupby('sports_duration').groups
sports_too_short_mean = np.mean([df.loc[value]['sports_visit_cnt'] for value in sports_duration['too short']])
sports_short_mean = np.mean([df.loc[value]['sports_visit_cnt'] for value in sports_duration['short']])
sports_medium_mean = np.mean([df.loc[value]['sports_visit_cnt'] for value in sports_duration['medium']])
sports_long_mean = np.mean([df.loc[value]['sports_visit_cnt'] for value in sports_duration['long']])
sports_too_long_mean = np.mean([df.loc[value]['sports_visit_cnt'] for value in sports_duration['too long']])
education_duration = df.groupby('education_duration').groups
education_too_short_mean = np.mean([df.loc[value]['education_visit_cnt'] for value in sports_duration['too short']])
education_short_mean = np.mean([df.loc[value]['education_visit_cnt'] for value in education_duration['short']])
education_medium_mean = np.mean([df.loc[value]['education_visit_cnt'] for value in education_duration['medium']])
education_long_mean = np.mean([df.loc[value]['education_visit_cnt'] for value in education_duration['long']])
education_too_long_mean = np.mean([df.loc[value]['education_visit_cnt'] for value in education_duration['too long']])
nature_duration = df.groupby('nature_duration').groups
nature_too_short_mean = np.mean([df.loc[value]['nature_visit_cnt'] for value in nature_duration['too short']])
nature_short_mean = np.mean([df.loc[value]['nature_visit_cnt'] for value in nature_duration['short']])
nature_medium_mean = np.mean([df.loc[value]['nature_visit_cnt'] for value in nature_duration['medium']])
nature_long_mean = np.mean([df.loc[value]['nature_visit_cnt'] for value in nature_duration['long']])
nature_too_long_mean = np.mean([df.loc[value]['nature_visit_cnt'] for value in nature_duration['too long']])
entertainment_duration = df.groupby('entertainment_duration').groups
entertainment_too_short_mean = np.mean([df.loc[value]['entertainment_visit_cnt'] for value in entertainment_duration['too short']])
entertainment_short_mean = np.mean([df.loc[value]['entertainment_visit_cnt'] for value in entertainment_duration['short']])
entertainment_medium_mean = np.mean([df.loc[value]['entertainment_visit_cnt'] for value in entertainment_duration['medium']])
entertainment_long_mean = np.mean([df.loc[value]['entertainment_visit_cnt'] for value in entertainment_duration['long']])
entertainment_too_long_mean = np.mean([df.loc[value]['entertainment_visit_cnt'] for value in entertainment_duration['too long']])
funny_duration = df.groupby('funny_duration').groups
funny_too_short_mean = np.mean([df.loc[value]['funny_visit_cnt'] for value in funny_duration['too short']])
funny_short_mean = np.mean([df.loc[value]['funny_visit_cnt'] for value in funny_duration['short']])
funny_medium_mean = np.mean([df.loc[value]['funny_visit_cnt'] for value in funny_duration['medium']])
funny_long_mean = np.mean([df.loc[value]['funny_visit_cnt'] for value in funny_duration['long']])
funny_too_long_mean = np.mean([df.loc[value]['funny_visit_cnt'] for value in funny_duration['too long']])
plt.subplot(2,3,1)
plt.bar(['Too Short','Short','Medium','Long','Too Long'],[sports_too_short_mean,sports_short_mean,sports_medium_mean,sports_long_mean,sports_too_long_mean])
plt.title('Sports')
plt.subplot(2,3,2)
plt.bar(['Too Short','Short','Medium','Long','Too Long'],[education_too_short_mean,education_short_mean,education_medium_mean,education_long_mean,education_too_long_mean])
plt.title('Education')
plt.subplot(2,3,3)
plt.bar(['Too Short','Short','Medium','Long','Too Long'],[nature_too_short_mean,nature_short_mean,nature_medium_mean,nature_long_mean,nature_too_long_mean])
plt.title('Nature')
plt.subplot(2,3,4)
plt.bar(['Too Short','Short','Medium','Long','Too Long'],[entertainment_too_short_mean,entertainment_short_mean,entertainment_medium_mean,entertainment_long_mean,entertainment_too_long_mean])
plt.title('Entertainment')
plt.subplot(2,3,5)
plt.bar(['Too Short','Short','Medium','Long','Too Long'],[funny_too_short_mean,funny_short_mean,funny_medium_mean,funny_long_mean,funny_too_long_mean])
plt.title('Funny')
plt.savefig('General barcharts for the relation of duration and visit count for each label.png')
plt.show()
#sns.jointplot(x=df[['sports_duration']],y=df['sports_visit_cnt'],data=df,kind='kde')
#plt.show()
|
34cf18d662080576faa63780a77856327b49aec3 | z727354123/pyCharmTest | /2018-01/01_Jan/21/_04_eq.py | 1,098 | 3.890625 | 4 | class Person:
def __init__(self, age=15):
self.age = age
# 默认比较 引用地址
def __eq__(self, other):
print('__eq__', self.age, other.age, end=" , ")
return False
def __ne__(self, other):
print('__ne__', self.age, other.age, end=" , ")
return False
def __gt__(self, other):
print('__gt__', self.age, other.age, end=" , ")
return True
def __lt__(self, other):
print('__lt__', self.age, other.age, end=" , ")
return True
def __bool__(self):
return False
# def __ge__(self, other):
# print('__ge__', self.age, other.age, end=" , ")
# return True
def __le__(self, other):
print('__le__', self.age, other.age, end=" , ")
return True
# TypeError: '>' not supported between
# instances of 'Person' and 'Person'
p1 = Person()
p2 = Person(16)
print(p1 == p2)
# 没有 __eq__ 就是 not(p1 == p2)
print(p1 != p2)
# 这里不会调用 __gt__ & __eq__
# 只会调用 not __le__
print(p1 >= p2)
print(p1 <= p2)
# print(p1 < p2 > p1)
print(not p1) |
16cd06e7bb4be8f3baa3017b40032643e0a9a266 | ElderVivot/python-cursoemvideo | /Ex094_ListaPessoasDict.py | 1,477 | 3.90625 | 4 | pessoa = {}
lista_pessoas = []
soma_idade = 0
while True:
# adiciona os dados da pessoa
pessoa['nome'] = str(input('Digite o nome: '))
pessoa['sexo'] = str(input('Digite o sexo (M/F): '))
pessoa['idade'] = int(input('Digite a idade: '))
soma_idade += pessoa['idade']
# copia o dado da pessoa atual para uma lista
lista_pessoas.append(pessoa.copy())
# limpa o dicionário (não obg mas desejável)
pessoa.clear()
print('-'*20)
# questiona se quer continuar ou não, e o while valida a resposta informada
continuar = str(input('Deseja continuar [S/N]: ')).strip().upper()
while continuar not in ('S, N'):
continuar = str(input('Valor incorreto, digite S para continuar e N para parar: ')).strip().upper()
if continuar == "N":
break
print('-'*50)
print(lista_pessoas)
print('-'*50)
media_idade = soma_idade / len(lista_pessoas)
print(f"A) Foram cadastradas {len(lista_pessoas)} pessoas.")
print(f"B) A média de idade do grupo é {media_idade:.2f}")
print(f"C) As mulheres cadastradas foram: ", end='')
for i in range(0, len(lista_pessoas)):
if lista_pessoas[i]["sexo"] == 'F':
print(f'{lista_pessoas[i]["nome"]}, ', end='')
print()
print(f"D) A lista das pessoas que estão acima da média são: ")
for pes in lista_pessoas:
if pes["idade"] > media_idade:
print(f'\t-', end='')
for k, v in pes.items():
print(f"{k} = {v}; ", end='')
print()
|
928e1faf6558ba262ba7f70d2fdfe341b3fbfc72 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5455.py | 809 | 3.828125 | 4 | # raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(raw_input()) # read a line with a single integer
def tidynumber(n):
number = str(n)
if len(number) == 1:
return True
first = int(number[0])
second = int(number[1])
if first > second:
return False
else:
recurse = int(number[1:])
return tidynumber(recurse)
def tidyloop(n):
array=[]
for i in range(0,n+1):
if tidynumber(i):
array.append(i)
return array[-1]
for i in xrange(1, t + 1):
n = int(raw_input())
m = tidyloop(n)
print "Case #{}: {}".format(i, m)
# check out .format's specification for more formatting options
|
ff13df3b814893b286b26bd4d7a071764b60b92c | Sebasfc10/inteligencia_python | /ejer.py | 7,896 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 4 14:55:38 2021
@author: jeha2
"""
y = (((5+2+5)**2) * 5+8/2 - 30) / 2 * 5 - 3
z = 5
n = ((((8+2-4)**2)*5+8+7/2 -30*5) / 2*5-3)**5 + 15 *3 - 9/3
m = ((z)**2)*3+n
y = (((((z+2-n)**2)*m+8/2-30)/2*5-3)**5+15*3-9/3)**2-5/4
print(y)
#ejercicios con solucion a la problematica resuelta en python
"""
1 - Haga un algoritmo que calcule la masa de la siguiente fórmula:
Masa = (presión * volúmen) / (0.37 * (temperatura + 460))
"""
presion = float(input('ingrese la presion: '))
volumen = float(input('ingrese la volumen: '))
temperatura = float(input('ingrese la temperatura: '))
masa = (presion * volumen)/(0.37 * (temperatura + 460))
print(f'esta es la masa calculada: {masa}')
"""
2 - Calcular el número de pulsaciones que una persona debe tener por
cada 10 segundos de ejercicio, si la fórmula es:
Num. Pulsaciones = (200 – edad) /10.
"""
edad = float(input('ingrese aqui sue edad: '))
numP = (200 - edad)/10
print(f'tu numero de pulsaciones por 10 segundo son: {numP}')
"""
Tres personas deciden invertir su dinero para fundar una empresa.
Cada una de ellas invierte una cantidad distinta. Obtener el porcentaje
que cada quien invierte con respecto a la cantidad total invertida.
"""
p1 = float(input('que cantidad deseas invertir, socio 1: '))
p2 = float(input('que cantidad deseas invertir, socio 2: '))
p3 = float(input('que cantidad deseas invertir, socio 3: '))
porcentajE = (p1 + p2 + p3)/3
print(f'este es el porcentaje de cada uno al momento de invertir: {porcentajE}')
"""
Un banco da a sus ahorradores un interes de 1.5% sobre el monto
ahorrado. Teniendo como dato de entrada el saldo inicial del
ahorrador determine el saldo final.
"""
saldo = float(input('ingrese su saldo: '))
interes = saldo * 1.5/100
suma = saldo + interes
print(f'su ganancia por intereses es: {suma}')
"""
Una empresa le hace los siguientes descuentos sobre el sueldo base
a sus trabajadores: 1% por ley de politica pública, 4% por seguro
social, 0.5% por seguro forzoso y 5% por caja de ahorro. Realice un algoritmo que determine el monto de cada descuento y el monto total
a pagar al trabajador.
"""
sueldo = float(input('Ingrese su sueldo: '))
LPP = sueldo * 1/100
SS = sueldo * 4/100
SF = sueldo * 0.5/100
CH = sueldo * 5/100
suma = sueldo + LPP + SS + SF + CH
print(f'Es el total a pagar al trabajador: {suma}')
"""
El periódico el Informador cobra por un aviso clasificado un monto
que depende del número de palabras, tamaño en cetímetros y
número de colores. Cada palabra tiene un costo de $20.000, cada
centímetro tiene un costo de $15.000 y cada color tiene un costo de
$25.000. Realice un algoritmo que determine el monto a pagar por un
aviso clasificado.
"""
palabra = float(input('ingrese el numero de palabras: '))
palabras = palabra * 20000
cm = float(input('ingrese cuantos centimetros tiene el anuncion: '))
cms = cm * 15000
color = float(input('ingrese cuantos colores tiene: '))
colores = color * 25000
suma = palabras + cms + colores
print(f'este es el costo real que tendria tu anuncio clasificado : {suma}')
"""
Una empresa paga a sus empleados un bono por antigüedad que
consiste en $100.000 por el primer año laboral y $120.000 por cada
año siguiente. Realice un algoritmo que determine el monto del bono
a pagar a un trabajador que tiene varios años en la empresa
"""
año = float(input('Ingresa tus años en la empresa: '))
sueldo = float(input('ingrese su sueldo: '))
if año == 1:
suma = sueldo + 100000
print(f'es su primer año laboral y su bono sera de 100k + salario,queda en : {suma}')
else:
suma = sueldo + 120000
print(f'ya lleva varios años, su bono es de 120k + sueldo y queda en: {suma}')
"""
Una Universidad le paga a sus profesores $20.000 la hora y le hace
un descuento del 5% por concepto de caja de ahorro. Determine el
monto del descuento y el monto total a pagar al profesor.
"""
horas = float(input('ingrese su horas de trabajo: '))
sueldo = horas * 20000
CH = sueldo * 5/100
descuento = sueldo - CH
print(f'Su sueldo es {sueldo} pero se le descuenta {CH} de caja de ahorro, su sueldo final es {descuento}')
"""
Un centro de comunicaciones alquilan tarjetas para realizar llamadas
y cobran el monto consumido de la tarjeta mas un recargo del 20%.
Teniendo como dato de entrada el monto inicial y el monto final de la
tarjeta, determine el costo de la llamada.
"""
montoI = float(input('El monto inidial es: '))
recargo = montoI * 20/100
montof = montoI + recargo
print(f'el monto final de la tarjeta es: {montof}')
"""
En una fototienda cobran por el revelado de un rollo $1.500 por cada
foto. Realice un algoritmo que determine el monto a pagar por un
revelado completo sabiendo que adiconalmente le cobran el IVA
(16%).
"""
xrollo = float(input('¿de cual tipo es tu rollo de 24 o 36 fotos?: '))
xfoto = xrollo * 1500
iva = xfoto * 16/100
costoF = xfoto + iva
print(f'el total a pagar es : {costoF} (incluye iva)')
"""
. En un hospital existen tres áreas: Ginecología, Pediatría y
Traumatología. El presupuesto anual del hospital se reparte
conforme a la siguiente tabla:
"""
dinero = float(input('ingrese el dinero que va destinado al hospital: '))
ginecologia = dinero * 40/100
trauma = dinero * 30/100
pediatra = dinero * 30/100
print(f'el dinero que va destinado a el sector de la ginecologia es {ginecologia}, el dinero que va para el sector de la traumatologia es {trauma} y el dinero que destinado al ultimo sector que es pediatria es {pediatra}')
"""
Una video tienda alquila DVD a $1.500 el día. Tiene una promoción
que consiste en dejar gratis el alquiler de una película. Realice un
algoritmo que teniendo como dato de entrada el total de películas
alquiladas, y el número de días de alquiler, determine el monto a
pagar.
"""
dias = float(input('ingrese los dias de alquiler : '))
precio = dias * 1500
print(f'el total a pagar es {precio} y el total de peliculas a alquilar son {dias}')
"""
Una Agencia de viajes cobra por un Tour a Cartagena $25.000
diarios por persona. Realice un algoritmo que determine el monto a
pagar por una familia que desee realizar dicho Tour sabiendo que
también cobran el 12% de IVA.
"""
integrante = float(input('cuanto integrantes de la familian van al tour : '))
costo = integrante * 25000
iva = costo * 12/100
final = costo + iva
print(f'el total a pagar por una familia con {integrante} integrantes es de {final}')
"""
Un Hotel 5 Estrellas de Santa Marta tiene una promoción para sus
clientes. Cobra por una habitación $100.000 el primer día y por el
resto $200.000 por día. Realice un algoritmo que determine el valor
total a pagar por la habitación si la estadía fue de varios días.
"""
NEstadia = int(input('ingrese el numero de dias en el que se va a quedar en el hotel : '))
habitacion = 0
if NEstadia == 1:
habitacion = 100000
print(f' solo te hospedaras un dia con un costo de {habitacion}')
if NEstadia > 1:
habitacion = NEstadia * 200000
print(f'te alojas {NEstadia} dias con un valor de {habitacion}')
"""
El banco del Pueblo da microcréditos a empresarios para ser
cancelados en un lapso de 2 años (24 meses). Al monto del
préstamo se le cobra un interés del 24%. El empresario debe pagar
la mitad del préstamo en 4 cuotas especiales y la otra mitad en 20
cuotas ordinarias. Realice un algoritmo que teniendo como dato de
entrada el monto del préstamo, determine el monto total a pagar por
el préstamo, el monto de las cuotas especiales y el monto de las
cuotas ordinarias.
"""
monto = float(input('ingrese el monto del prestamo que solicito : '))
iva = monto * 24/100
final = monto + iva
es = (final / 2) /4
ordinario = (final / 2)/ 20
print(f'se debe pagar el monto total {final} pero los primeros cuantro meses se deben pagar {es} y la otra mitad del prestamo se debe pagar en 20 cuotas de {ordinario}')
"""
Muchas gracias.
""" |
a834dfb52b41f3251fc3b93280e02b51f16fbf3e | PotentialPie/leetcode-python | /algorithm/leetcode-14.py | 1,349 | 3.84375 | 4 | #coding=utf-8
# 这题能告诉我们什么呢?
# 1. python的break只能跳出一重循环,但是return可以立刻终止,可以利用这个特性
# 2. 利用一个额外的flag变量来判断是否再break外一层
# 3. 判断输入是不是空list
class Solution:
def longestCommonPrefix(self, m):
# """
# :type strs: List[str]
# :rtype: str
# """
# min_max_len = min([len(s) for s in strs])
# common_prefix = ''
# for prefix_index in range(min_max_len):
# for i in range(1, len(strs)):
# if strs[0][prefix_index] != strs[i][prefix_index]:
# return common_prefix
# common_prefix = common_prefix + strs[0][prefix_index]
# return common_prefix
#一个牛逼的解法
if not m:
return ''
# since list of string will be sorted and retrieved min max by alphebetic order
s1 = min(m)
print(s1)
s2 = max(m)
print(s2)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i] # stop until hit the split index
return s1
solution = Solution()
print(solution.longestCommonPrefix(["flower","flow","flight"]))
print(solution.longestCommonPrefix(["dog","racecar","car"]))
print(7462266+149408+200000+285174+1790251)
|
d158d822113431930de98b60f7faf0567c0aceb6 | Devang-25/Interview-Process-Coding-Questions | /Amazon/Delete_Node_Without_HeadPointer.py | 1,739 | 4.03125 | 4 | class Node(object):
def __init__(self,dataVal,nextNode=None):
self.data = dataVal
self.next = nextNode
def getData(self):
return (self.data)
def setData(self,val):
self.data = val
def getNextNode(self):
return (self.next)
def setNextNode(self,val):
self.next = val
class LinkedList(object):
def __init__(self,head=None):
self.head = head
self.size = 0
def getSize(self):
return (self.size)
def addNode(self,data):
newNode = Node(data)
newNode.setNextNode(self.head)
self.head = newNode
self.size += 1
return True
def printNode(self):
curr = self.head
while curr:
print (curr.data)
curr = curr.getNextNode()
def deleteNode(self,value):
prev = None
curr = self.head
while curr:
if curr.data == value:
if prev:
prev.setNextNode(curr.getNextNode())
else:
self.head = curr.getNextNode()
self.size -= 1
return True
prev = curr
curr = curr.getNextNode()
return False
myList = LinkedList()
print (myList.getSize())
print ("______*Inserting*_______")
myList.addNode(5)
myList.addNode(10)
myList.addNode(15)
myList.addNode(20)
myList.addNode(25)
print ("printing")
myList.printNode()
print ("Deleting")
myList.deleteNode(10)
myList.deleteNode(20)
myList.deleteNode(5)
myList.addNode(90)
myList.addNode(2000)
print (myList.getSize())
myList.printNode() |
a29ce68fc18f7ca0c633037f4ed3ce6aa6140cd8 | gabriellaec/desoft-analise-exercicios | /backup/user_395/ch20_2019_04_04_17_06_39_236290.py | 139 | 3.828125 | 4 | a = input('Qual seu nome?')
if a == 'Chris' or a == 'chris':
print ('Todo mundo odeia o Chris')
else:
print ('Olá, {0}'.format(a)) |
ccd5438c7a16943922815beb7a71a13061c5c252 | hbradlow/solver | /server/parser/gui.py | 2,335 | 3.5 | 4 | import Tkinter as tk
class Point2D:
def __init__(self, position, radius=3, fill="red", outline="black"):
self.position = position #a numpy array
self.radius = radius
self.fill = fill
self.outline = outline
def __repr__(self):
return "<Point2D: " + str(self.position) + ">"
def draw(self,canvas):
canvas.create_oval( self.position[0]-self.radius,
self.position[1]-self.radius,
self.position[0]+self.radius,
self.position[1]+self.radius,
fill=self.fill,outline=self.outline)
class Box2D:
def __init__(self,origin,size):
self.origin = origin
self.size = size
self.fill = 'red'
def __repr__(self):
return "<Box2D: " + str(self.origin) + " -> " + str(self.size) + ">"
def draw(self,canvas):
canvas.create_rectangle(self.origin[0],self.origin[1],
self.origin[0]+self.size[0],self.origin[1]+self.size[1],fill=self.fill)
class Line2D:
def __init__(self,start,end):
self.start = start
self.end = end
def __repr__(self):
return "<Line2D: " + str(self.start) + " -> " + str(self.end) + ">"
def draw(self,canvas):
canvas.create_line(self.start[0],self.start[1],self.end[0],self.end[1])
class Visualizer:
def __init__(self,root,width,height,key_callback=None):
self.drawables = [] #list of drawable objects
self.frame = tk.Frame(root)
self.frame.focus_set()
self.canvas = tk.Canvas(self.frame,bg="white",width=width,height=height)
self.canvas.pack()
self.frame.pack()
print 'key_callback', key_callback
self.frame.bind("<Key>",key_callback)
def add_drawable(self,drawable):
"""
Adds a drawable to the visualizer.
"""
self.drawables.append(drawable)
def clear(self):
self.drawables = []
def run(self):
self.draw()
def draw(self):
self.canvas.delete(tk.ALL)
for drawable in self.drawables:
drawable.draw(self.canvas)
def add_line(points,visualizer):
prev = None
for n in points:
visualizer.add_drawable(Point2D(n,fill="red"))
if prev is not None:
visualizer.add_drawable(Line2D(prev,n))
prev = n
|
7300cef5f44688fce8e6f4d308c21efa342774ae | khill-turbo/python-fun | /thirty-days/day10/binary-numbers.py | 648 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def countConsecOnes(n):
binaryN = f'{n:b}'
#print("binaryN = ", binaryN)
stringN = str(binaryN)
#print("stringN = ", stringN)
# get the length of the string
j = len(stringN)
while(j >= 1):
# start from max length and search to smaller
maxOnes = "1"*j
if maxOnes in stringN:
#print(maxOnes)
# break as soon as the max length found
break
j += -1
total = len(maxOnes)
return(total)
if __name__ == '__main__':
n = int(input())
n = countConsecOnes(n)
print(n)
|
67160da368deb0057c85fc97f424bc888beb99cc | danylagacione/Codility | /Lesson3/TapeEquilibrium.py | 2,221 | 3.65625 | 4 | # Uma matriz não vazia A que consiste em N números inteiros é fornecida. A matriz A representa números em uma fita.
#
# Qualquer número inteiro P, tal que 0 <P <N, divide esta fita em duas partes não vazias: A [0], A [1], ...,
# A [P - 1] e A [P], A [ P + 1], ..., A [N - 1].
#
# A diferença entre as duas partes é o valor de: | (A [0] + A [1] + ... + A [P - 1]) - (A [P] + A [P + 1] + .. . + A [N - 1]) |
#
# Em outras palavras, é a diferença absoluta entre a soma da primeira parte e a soma da segunda parte.
#
# Por exemplo, considere a matriz A de modo que:
#
# A [0] = 3
# A [1] = 1
# A [2] = 2
# A [3] = 4
# A [4] = 3
# Podemos dividir esta fita em quatro lugares:
#
# P = 1, diferença = | 3 - 10 | = 7 # o P é onde a lista vai ser fatiada/cortada
# P = 2, diferença = | 4 - 9 | = 5
# P = 3, diferença = | 6 - 7 | = 1
# P = 4, diferença = | 10 - 3 | = 7
# Escreva uma função:
#
# solução def (A)
#
# que, dada uma matriz não vazia A de N números inteiros, retorna a diferença mínima que pode ser alcançada.
#
# Por exemplo, dado:
#
# A [0] = 3
# A [1] = 1
# A [2] = 2
# A [3] = 4
# A [4] = 3
# a função deve retornar 1, conforme explicado acima.
#
# Escreva um algoritmo eficiente para as seguintes suposições:
#
# N é um número inteiro dentro do intervalo [ 2 .. 100.000 ];
# cada elemento da matriz A é um número inteiro dentro do intervalo [ -1.000 .. 1.000 ].
# função abs ela retorna o valor absoluto do número que foi especificado
a = [3,1,2,4,3]
def solution(a):
corte1 = a[0] # corta a primeira fatia da lista a = [0]
corte2 = sum(a[1:]) # soma as fatias restantes da lista a partir da posição 1
diferenca_minima = abs(corte1 - corte2) # tiro o a[0] - a soma da do segundo corte(o que restou da lista)
for item in range(1, len(a)-1): # pega a partir do primeiro índice, passa por toda a lista e corta novamente o primeiro item da lista
corte1 += a[item]
corte2 -= a[item]
if abs(corte1 - corte2) < diferenca_minima:# a função abs retorna o valor absoluto do número que foi dado, no caso corte1 - corte2
diferenca_minima = abs(corte1 - corte2)
return diferenca_minima
print(solution(a))
|
e76aeb3a14edb222b40acb4cb3adada0492bed03 | adebayo5131/Python | /Basic python.py | 629 | 3.96875 | 4 | greet = 'Hello my name is'
for i in enumerate(greet):
print(i)
print('\n')
for j in enumerate(greet[0:5]):
print(j)
#List Comprehension
list = [1,2,3,4,5]
print('\n')
print([i**2 for i in list])
items = [['Bayo',20],['shaina',10]]
print(items[1][1]* 2)
print('\n')
#Lambda(), Map() and Filter()
for i in map(lambda x: x*2, list):
print(i)
print('\n')
for i in filter(lambda x: x>3,list):
print(i)
print('\n')
word = str.split( 'Here is how to use the split')
print(sorted(word,key=len))
print('\n')
sl = ['A','B','a','C', 'c']
sl.sort(key=str.lower)
print(sl)
print('\n')
sl.sort()
print(sl)
|
286222e0b8daa4a7cfab29fee794130f48e0acc9 | Easwar737/Python | /Leetcode(Easy) - Python/Two sum.py | 524 | 3.921875 | 4 | """Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order."""
# I have manually given the input. This one works perfectly for other testcases too.
nums=[2,7,11,15]
target=9
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if(nums[i]+nums[j]==target):
return [i,j] |
d76b0f3a4d1b9d0e7baf653019e2f703706a7356 | abhijitdey/coding-practice | /facebook/arrays_and_strings/13_one_edit_distance.py | 3,782 | 3.78125 | 4 | """
Given two strings s and t, return true if they are both one edit distance apart, otherwise return false.
One operation can be either a delete, an insert, or a replacement
"""
class Solution:
def editDistance(self, word1: str, word2: str) -> int:
"""
Returns the min number of operations required to convert "word1" to "word2"
Dynamic programming problem - LEETCODE HARD
Example: If word1 = "abd" and word2 = "acd", the answer should be 1 as only one operation (replace b with c) is required
Use two pointers i and j to traverse through both the strings
Two cases:
1. Chars at i and j match -- means we don't need any operation
- So, just move to the next indices (i+1, j+1)
2. Chars do not match -- need to apply one of the three operations
a. Insert:
- If you insert a char to word1, then for next round your i pointer remains the same while j moves ahead by 1 -- (i, j+1)
b. Delete:
- If you delete a char in word1, then i -> i + 1 while j remains at the same position -- (i+1, j)
c. Replace:
- For this operation, we are just replace the char in word1 with the char in word2 at position j
- So, updated pointers will be (i+1, j+1) but at the cost of one operation like the above two
- Use a 2D caching array that stores the number of operations required for each substring
a b d
a 3
c 2
d 1
3 2 1 0
In the above matrix, we look at each row and column and see how many operations are required to convert string in the row to string in the column
- For example, substring on the 4th column (row 0) is empty and to convert it to substring "acd", we need 3 insert operations (it is one of the base cases)
"""
cache = [
[float("inf") for i in range(len(word2) + 1)] for j in range(len(word1) + 1)
]
# Add base cases to bottom row and last column
for j in range(len(word2) + 1):
cache[len(word1)][j] = len(word2) - j
for i in range(len(word1) + 1):
cache[i][len(word2)] = len(word1) - i
# Use bottom up approach to fill the table
for row in range(len(word1) - 1, -1, -1):
for col in range(len(word2) - 1, -1, -1):
if word1[row] == word2[col]:
cache[row][col] = cache[row + 1][col + 1]
else:
cache[row][col] = 1 + min(
cache[row + 1][col],
cache[row][col + 1],
cache[row + 1][col + 1],
)
return cache[0][0]
def isOneEditDistance(self, s: str, t: str) -> bool:
if len(s) > len(t):
# We want to make sure that the first string is of smaller length
# This will make our if conditions easier to code and understand
return self.isOneEditDistance(t, s)
for i in range(len(s)):
if s[i] != t[i]:
# Two cases:
# a. If both strings are of same length, the remaining substring must match
# as we can only replace the unmatched characters
if len(s) == len(t):
return s[i + 1 :] == t[i + 1 :]
# Else, we can add one char at index i to make them match
else:
return s[i:] == t[i + 1 :]
# At the end, we want to make sure that the lengths of the strings actually only differ by 1 to satisfy the DELETE operation
return len(s) + 1 == len(t)
|
6d659c409f316f9eb59e594105f1bf908f0c2619 | Hecvi/Tasks_on_python | /task96.py | 1,225 | 3.71875 | 4 | # Даны два действительных числа x и y. Проверьте, принадлежит ли точка
# с координатами(x,y) заштрихованному квадрату (включая его границу).
# Если точка принадлежит квадрату, выведите слово YES,иначе выведите слово
# NO. На рисунке сетка проведена с шагом 1
# Решение должно содержать функцию IsPointInSquare(x, y), возвращающую True,
# если точка принадлежит квадрату и False, если не принадлежит. Основная
# программа должна считать координаты точки, вызвать функцию IsPointInSquare
# в зависимости от возвращенного значения вывести на экран необходимое
# сообщение.Функция IsPointInSquare не должна содержать инструкцию if
def IsPointInSquare(x, y):
return abs(x) + abs(y) <= 1
if IsPointInSquare(float(input()), float(input())):
print('YES')
else:
print('NO')
|
996be59906d257e36c81bb25b30d7fa40c692a16 | anonymokata/0a836320-4374-11ea-9cf5-1a2702f082d9 | /WordSearchSolver.py | 2,227 | 3.875 | 4 | from WordSearchBlock import WordSearchBlock
import sys
class WordSearchSolver(object):
"""
This is the solver. It is instantiated with a text file containing the specified format.
Once instantiated, it can solve() the puzzle, finding all of the words listed on the first
line of the text file.
"""
linecount = None
words_to_find = None
rawblock = None
def __init__(self, filename):
"""
Provide full or partial patth to a filename containing a wordsearch puzzle in the appropriate format.
"""
self.linecount = 0
self.words_to_find = list()
self.rawblock = list()
f = open(filename)
for line in f.readlines():
if (',') not in line:
raise ValueError("Invalid input, this line doesn't contain a comma anywhere.")
if (self.linecount == 0):
self.words_to_find = line.strip().split(',') #list of words
else:
self.rawblock.append(line.strip().split(',')) #raw block of letters
self.linecount += 1
self.wsb = WordSearchBlock(self.rawblock)
def solution(self):
"""
Get all slices from the WordSearchBlock as WordSearchLine objects. These objects are
easy to query simply using Python's "in" operator. If a word is discovered,
the Line object will hold the result internally. Just get the result out and
move on to the next word.
"""
slices = self.wsb.getAllSlices()
results = list()
#for each slice, look for every word in the list
for slice in slices: #that is cool
for word in self.words_to_find:
if word in slice:
results.append(slice.get_result_as_string(0)) #assume only one result found, that's why we look for result zero
results.sort()
outputstr = "\n".join(results)
return outputstr
def main():
"""
Will allow running of arbitrary word puzzes by providing the filename at the commandline:
WordSearchSolver.py <filename>
"""
wss = WordSearchSolver(sys.argv[1])
print(wss.solution())
if __name__ == "__main__":
main()
|
302096af42506826c91a50278c7d741fc6ae9bfc | AmelishkoIra/it-academy-summer-2021 | /task1_hw5.py | 934 | 4.125 | 4 | """Функции из Homework5 для тестирования"""
def input_number(a):
"""
Написать программу которая находит ближайшую степень двойки к введенному
числу.
"""
for i in range(0, 1000):
if 2 ** i >= a:
if 2 ** i - a > a - 2 ** (i - 1):
return 2 ** (i - 1)
break
else:
return 2 ** i
break
def max_divisor(number):
"""
Вводится число, найти его максимальный делитель, являющийся степенью
двойки.
"""
exponent = 0
while 2 ** exponent <= number:
if number % (2 ** exponent) == 0:
divisor = (2 ** exponent)
exponent = exponent + 1
else:
break
return divisor
|
3d26d0f8c9c6bfd7c5c8b40767df45f6fa2a631d | AmirHossam/Tic-Tac-Toe | /main.py | 4,737 | 4.15625 | 4 | #to clear screen
from IPython.display import clear_output
import random
def display_board(board):
clear_output()
print(' ' + board[7] + ' | ' + board[8] + ' | '+ board[9])
print('-----------')
print(' ' + board[4] + ' | ' + board[5] + ' | '+ board[6])
print('-----------')
print(' ' + board[1] + ' | ' + board[2] + ' | '+ board[3])
#Function that takes a player input
def player_input():
marker = ' '
#Ask the player 1 to choose X or O
while not (marker == 'X' or marker == 'O'):
marker = input("Player 1 : Do you want X or O ?").upper()
#if the player 1 chose X so he will pick X and the Player 2 picks O
if marker == 'X':
return ('X','O')
#if the player 1 chose O so he will pick O and the player 2 picks X
else:
return ('O','X')
#Function takes in the board list object , a marker ('X' or 'O')
#and desired position (number 1-9)
#and assigns it to the board
def place_marker (board,marker,position):
board[position]= marker # it will assign the letter X or O to the location
#Function that takes in a board and check if someone won ?
#it takes 2 arguments "Test_board" and "X or O"
#it prints True if the Chosen Player won
def win_check(board,mark):
#the possibilites to let some1 win
return ((board[7]== mark and board[8]== mark and board[7]== mark)or
(board[4]== mark and board[5]== mark and board[6]== mark) or
(board[1]== mark and board[2]== mark and board[3]== mark) or
(board[1]== mark and board[5]== mark and board[9]== mark) or
(board[3]== mark and board[5]== mark and board[7]== mark) or
(board[2]== mark and board[5]== mark and board[8]== mark) or
(board[1]== mark and board[4]== mark and board[7]== mark) or
(board[3]== mark and board[6]== mark and board[9]== mark))
#Function uses random module to decide which player starts first
def choose_first():
#random.randint(0,1) => returns a number between 0 and 1
if random.randint(0,1)==0:
return 'Player 2 will start'
else :
return 'Player 1 will start'
#Function that returns true or falce if there is a free space
def space_check(board,position):
return board[position] == ' '
#Function that check each position in the board is full or not
def full_board_check(board):
for i in range(1,10):
if space_check(board,i):
return False
return True
#Function asks the player about the next play (1-9)
#uses the "Space Check Function" to check if the next play position
#is free or not
def player_choice(board):
position=0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position):
position = int(input("Choose your next play : (1-9)"))
return position
#Function asks the players if they want to play again
#returns boolean expression
#use .startwith('y') to return True if he writes yes
def replay():
return input('Do you want to play again ?\n Enter Yes or No\n').lower().startswith('y')
#Application :
print("Welcome To XO Game")
while True:
theBoard = [' ']*10
player1_marker,player2_marker = player_input()
turn = choose_first()
print(turn)
play_game = input("Are you ready to start ?\nEnter Yes or No.\n").lower()
if play_game[0]=='y':
game_on = True
else :
game_on = False
#>>>Fault is here
while game_on:
if turn == 'Player 1':
#Player's 1 Turn
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard,player1_marker,position)
if win_check(theBoard,player1_marker):
display_board(theBoard)
print("Congratulations , Player 1 won the game")
game_on = False
else :
if full_board_check(theBoard):
display_board(theBoard)
print("The game is a draw")
break
else:
turn = 'Player 2'
else :
#Player2's turn
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard,player2_marker,position)
if win_check(theBoard,player2_marker):
display_board(theBoard)
print("Congratulations , Player 2 won the game")
game_on = False
else :
if full_board_check(theBoard):
display_board(theBoard)
print("the game is a draw!")
break
else:
turn = 'Player 1'
if not replay():
break |
decc8c9f66fe4f9445a21d915cf2a894de3c01d9 | yaHaart/hometasks | /Module23/common_calc_func.py | 675 | 3.90625 | 4 | def calc(temp_list):
if temp_list[1] == '+':
summa = int(temp_list[0]) + int(temp_list[2])
elif temp_list[1] == '-':
summa = int(temp_list[0]) - int(temp_list[2])
elif temp_list[1] == '*':
summa = int(temp_list[0]) * int(temp_list[2])
elif temp_list[1] == '//':
summa = int(temp_list[0]) // int(temp_list[2])
elif temp_list[1] == '%':
summa = int(temp_list[0]) % int(temp_list[2])
elif temp_list[1] == '/':
summa = int(temp_list[0]) / int(temp_list[2])
else:
raise TypeError('Что-то пошло не так. Скорее всего я не знаю такой знак')
return summa |
7cb1525c882944e79790b8aa6412b6e12bc78f05 | diegobonilla98/Test_on_Reinforcement_Learning | /Environment.py | 677 | 3.703125 | 4 | # model of the world. Gives observations and rewards. Changes state based on actions.
import random
class Environment:
def __init__(self):
self.steps_left = 10
def get_observation(self):
# current observation to the agent
return [0., 0., 0.]
def get_actions(self):
# get the actions the agent can execute
return [0, 1]
def is_done(self):
# episode is over
return self.steps_left == 0
def action(self, action):
# handles the actions and returns the rewards
if self.is_done():
raise Exception("Game is Over")
self.steps_left -= 1
return random.random()
|
88f4f9c9c2e50927031ef3753cbdfa07b99952e0 | nonvisual/algorithms | /data_structures/red_black_tree.py | 5,179 | 3.9375 | 4 | '''
Created on Apr 10, 2018
Properties of red-black tree
1. Every node is either red or black.
2. The root is black.
3. Every leaf (NIL) is black.
4. If a node is red, then both its children are black.
5. For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
@author: vladimirfux
'''
from enum import Enum
from data_structures.binary_search_tree import BinaryTree
from platform import node
class Color(Enum):
RED = 1
BLACK = 2
class ColoredNode(object):
'''
classdocs
'''
def __init__(self, parent, left_child, right_child, key, value, color):
'''
Constructor
'''
self.parent = parent
self.left_child = left_child
self.right_child = right_child
self.key = key
self.value = value
self.color = color
class RedBlackTree(BinaryTree):
def __init__(self):
self.root = None
# override
def insert(self, key, value):
if(key != None):
if(self.root == None):
self.root = ColoredNode(None, None, None, key, value, Color.RED)
node = self.root
else:
x = self.root
y = None
while(x != None):
if(key <= x.key):
y = x
x = x.left_child
else:
y = x
x = x.right_child
node = ColoredNode(y, None, None, key, value, Color.RED)
if(y == None):
self.root = node
elif(key <= y.key):
y.left_child = node
else:
y.right_child = node
self.__fix_insert_rb(node)
def __fix_insert_rb(self, z):
while z.parent != None and z.parent.color == Color.RED:
if z.parent == z.parent.parent.left_child:
y = z.parent.parent.right_child
if y != None and y.color == Color.RED:
z.parent.color = Color.BLACK
y.color = Color.BLACK
z.parent.parent.color = Color.RED
z = z.parent.parent
elif z == z.parent.right_child:
z = z.parent
self.__left_rotate(z)
else:
z.parent.color = Color.BLACK
z.parent.parent.color = Color.RED
self.__right_rotate(z.parent.parent)
# symmetric for left uncle
else:
y = z.parent.parent.left_child
if y != None and y.color == Color.RED:
z.parent.color = Color.BLACK
y.color = Color.BLACK
z.parent.parent.color = Color.RED
z = z.parent.parent
elif z == z.parent.left_child:
z = z.parent
self.__right_rotate(z)
else:
z.parent.color = Color.BLACK
z.parent.parent.color = Color.RED
self.__left_rotate(z.parent.parent)
self.root.color = Color.BLACK
# override
def delete(self, key):
pass
def __left_rotate(self, x):
y = x.right_child
x.right_child = y.left_child
if y.left_child != None:
y.left_child.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.left_child:
x.parent.left_child = y
else: x.parent.right_child = y
y.left_child = x
x.parent = y
def __right_rotate(self, y):
x = y.left_child
# right child of x -> left child of y
y.left_child = x.right_child
if x.right_child!=None:
x.right_child.parent = y
# fix parent of x
if y.parent == None:
self.root = x
elif y == y.parent.left_child:
y.parent.left_child =x
else:
y.parent.right_child = x
x.parent = y.parent
y.parent = x
x.right_child = y
def print_in_order(self):
self.__print_in_order(self.root)
def __print_in_order(self, node):
if(node != None):
self.__print_in_order(node.left_child)
print(str(node.key) + "=" + ("R" if node.color == Color.RED else"B") + ", ")
self.__print_in_order(node.right_child)
''' fixing red black properties, while loop maintains
a. Node ́ is red.
b. If ́:p is the root, then ́:p is black.
c. If the tree violates any of the red-black properties,
then it violates at most one of them, and the violation is
of either property 2 or property 4. If the tree violates property 2,
it is because ́ is the root and is red. If the tree violates property 4,
it is because both ́ and ́:p are red.'''
|
719ebea0caf67a6011f754a62fb53a06370dda5f | ThomasLee1998/Python-Project | /start of calculator.py | 4,243 | 4 | 4 | def add():
print 'Enter your first number.'
num1 = int(raw_input())
x = 1
y = 2
list1 = []
while x == 1:
print 'Enter another number. If you would like to find the answer, type "add"'
num = raw_input()
if num != 'add':
if y == 2:
list1.append(num1)
list1.append(num)
y = 1
elif y == 1:
list1.append(num)
if num == 'add':
total = 0
for i in list1:
total = total + int(i)
print 'Your answer is ' + str(total)
x = 2
def average():
print 'Enter a number'
num1 = int(raw_input())
x = 1
y = 2
list1 = []
while x == 1:
print 'Enter another number. If you would like to find the average, type "stop."'
num = raw_input()
if num != 'stop':
if y == 2:
list1.append(num1)
list1.append(num)
y = 1
elif y == 1:
list1.append(num)
if num == 'stop':
total = 0
for i in list1:
total = total + int(i)
total = total / len(list1)
print 'Your answer is ' + str(total)
x = 2
def subtract():
print 'Enter your first number.'
num1 = int(raw_input())
print 'Enter your second number.'
num2 = int(raw_input())
print 'would you like to 1.) First Number - Second Number or 2.) Second Number - First Number?'
yes = raw_input()
if yes == '1':
num3 = num1 - num2
print 'Your answer is ' + str(num3)
if yes == '2':
num3 = num2 - num1
print 'Your answer is ' + str(num3)
def multiply():
print 'Enter your first number.'
num1 = int(raw_input())
print 'Enter your second number.'
num2 = int(raw_input())
num3 = num1 * num2
print 'Your answer is ' + str(num3)
def divide():
print 'Enter your first number.'
num1 = int(raw_input())
print 'Enter your second number.'
num2 = int(raw_input())
print 'Would you like to do 1.) First Number / Second Number, or 2.) Second Number / First Number?'
no = raw_input()
if no == '1':
num3 = num1 / num2
print 'Your answer is ' + str(num3)
if no == '2':
num3 = num2 / num1
print 'Your answer is ' + str(num3)
def pothag():
print 'Enter the length of the first leg.'
leg1 = int(raw_input())
print 'Enter the length of the second leg. Press space and enter if there is no second leg.'
leg2 = raw_input()
if leg2 == ' ':
print 'Enter the length of the hypotenuse.'
hyp = int(raw_input())
hyp = hyp * hyp
leg1 = leg1 * leg1
leg2 = hyp - leg1
leg2 = leg2**.5
print 'Your answer is ' + str(leg2)
else:
leg1 = leg1 * leg1
leg2 = int(leg2) * int(leg2)
leg3 = leg1 + int(leg2)
leg3 = leg3**.5
print 'The hypotenuse is ' + str(leg3)
def square():
print 'Enter your base number.'
num = int(raw_input())
print 'to the power of-'
num2 = int(raw_input())
num3 = num**num2
print 'Your answer is ' + str(num3)
def sqroot():
print 'Enter a number you would like to find the square root of.'
num = int(raw_input())
num2 = num**.5
print 'your answer is ' + str(num2)
x = 1
while(x==1):
print ' '
print ' '
print 'Would you like to add, subtract, multiply, or divide? Type "more" for more options, or type "end" to end.'
modifier = raw_input()
if modifier == 'end':
x=2
print 'Ended!'
if modifier == 'add':
add()
if modifier == 'subtract':
subtract()
if modifier == 'multiply':
multiply()
if modifier == 'divide':
divide()
if modifier == 'more':
print 'Would you like to use the 1.) Pothagorean theorem, 2.) square something 3.) square root 4.) average'
more = raw_input()
if more == '1':
pothag()
if more == '2':
square()
if more == '3':
sqroot()
if more == '4':
average()
else:
print 'Invalid input.' |
9b748315182a69d402d898eedb1f6b53b36fce96 | zerghua/leetcode-python | /N1971_FindifPathExistsinGraph.py | 2,482 | 4.0625 | 4 | #
# Create by Hua on 3/21/22.
#
"""
There is a bi-directional graph with n vertices, where each vertex is
labeled from 0 to n - 1 (inclusive). The edges in the graph are represented
as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a
bi-directional edge between vertex ui and vertex vi. Every vertex pair is
connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex
source to vertex destination.
Given edges and the integers n, source, and destination, return true if
there is a valid path from source to destination, or false otherwise.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2
Example 2:
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.
Constraints:
1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
There are no duplicate edges.
There are no self edges.
"""
class Solution(object):
def bfs(self, graph, source, destination, n):
visit = [0]*n
q = list()
q.append(source)
while q:
e = q.pop()
visit[e] = 1
if e == destination:
return True
for adj in graph[e]:
if visit[adj] ==0:
q.append(adj)
return False
def validPath(self, n, edges, source, destination):
"""
:type n: int
:type edges: List[List[int]]
:type source: int
:type destination: int
:rtype: bool
easy-medium, 20 - 30 mins, long code, easy to have syntax bugs.
thought: BFS? push all adjacent of source edge into stack, and
go through them, if encounter dest then return true, else false.
a bit long code, need to construct a graph edges and then do BFS.
defaultdict provides a default value for a list of disctionary.
03/21/2022 15:14 Accepted 2851 ms 115.3 MB python
"""
# construct graph
graph = defaultdict(list)
for e in edges:
graph[e[0]].append(e[1])
graph[e[1]].append(e[0])
return self.bfs(graph,source, destination,n)
|
dca6d97965b6aabf937b887ad24790828ff18797 | AnamitraMandal/Intro-to-Webd | /GCD_using_Recursion.py | 150 | 3.890625 | 4 | def GCD(a,b):
if a%b==0:
return b
else:
return GCD(b,a%b)
n1=int(input())
n2=int(input())
gcd=GCD(n1,n2)
print(gcd)
|
e3f133fd3ee8a59290ec6fdb1675e5dec8fafcf5 | gsrr/leetcode | /leetcode/941. Valid Mountain Array.py | 480 | 3.53125 | 4 | import collections
def ans(A):
if len(A) < 3:
return False
i = 0
j = len(A) - 1
while i < len(A) - 1 and A[i + 1] - A[i] > 0:
i += 1
while j > 0 and A[j - 1] - A[j] > 0:
j -= 1
if i == 0 or j == len(A) - 1:
return False
return i == j
class Solution(object):
def validMountainArray(self, A):
"""
:type A: List[int]
:rtype: bool
"""
return ans(A)
|
d7590139c75e998120417f6c50a0e85ca9b50193 | DJaymeGreen/WackyWheel | /ww.py | 5,866 | 3.984375 | 4 | """D Jayme Green
Implementation of a doubly, circularly Linked List in Python
"""
from myList import *
import random
class Player():
__slots__ = ("Money")
"""
Makes a player object which contains the amount of money
param startMoney int initial money player will start with
return player Player newly created
"""
def mkPlayer(startMoney):
player = Player()
player.Money = startMoney
return player
"""
Creates the players and sets there money
param startMoney int initial money players will
start with
return tuple Tuple of created Players
"""
def setPlayers (startMoney):
player1 = mkPlayer (startMoney)
player2 = mkPlayer (startMoney)
player3 = mkPlayer (startMoney)
return (player1, player2, player3)
"""
Reads the file and creates the list
param file File that has wheel data
return List List of modified data of wheel data
"""
def readFile(file):
filename = open(file)
aList = []
for line in filename:
line = line.lstrip('$')
line = line.rstrip('\n')
aList += line.split(",")
aList = [int(i) for i in aList]
#print(line)
return aList
"""
Makes a linkedList and sets the wheel using the values
from the list from the file
param pylst Modified file which contains wheel data
return myList linkedList representing the wheel
"""
def setWheel (pylst):
myList = mkList()
for i in range (0, len(pylst)-1):
add(myList,pylst[0])
if myList.size >1:
forward(myList)
pylst.pop(0)
myList = addLast(myList, pylst[0])
return myList
"""
Randomly chooses whether the wheel will spin clockwise
or counterclockwise
return boolean true Clockwise, false counterclockwise
"""
def isclockwise():
randomNum = random.randint(0,1)
if randomNum == 0:
return True
else:
return False
"""
Gets a random number between 2 and
the linkedList size in order to find how
many steps the wheel should spin
param myList List containing the wheel
return int randomNum for steps wheel win spin
"""
def getNumofMoves(myList):
randomNum = random.randint(2,size(myList))
return randomNum
"""
Moves the wheel in either clockwise or counterclockwise for
x many steps (calling getNumofMoves) and returns the item there
param myList List containing the wheel
param player Player doing the move
return void
"""
def move(myList, player):
direction = isclockwise()
numofMoves = getNumofMoves(myList)
print("Clockwise:", direction, "numofMoves:", numofMoves)
for i in range (0, numofMoves):
if (direction == True):
forward(myList)
else:
backward(myList)
print(myList.cursor.data)
amount = myList.cursor.data
if direction == True:
player.Money += amount
else:
player.Money -= amount
remove(myList)
"""
Prints the winner after the game has been played
param myList List containing the wheel
param player1 1st player
param player2 2nd player
param player3 3rd player
return void
"""
def printWinner(myList, player1, player2, player3):
if ((player1.Money <= 0 and player2.Money <= 0) and player3.Money > 0):
print("Player3 wins!")
elif((player2.Money <= 0 and player3.Money <= 0) and player1.Money > 0):
print("Player1 wins!")
elif((player1.Money <= 0 and player3.Money <= 0) and player2.Money > 0):
print("Player2 wins!")
elif(size(myList) >= 3):
print("Ran out of spins, no true winners...")
elif(player1.Money > player3.Money and player1.Money > player2.Money):
print("Player1 wins!")
elif(player2.Money > player3.Money and player2.Money > player1.Money):
print("Player2 wins!")
elif(player3.Money > player1.Money and player3.Money > player2.Money):
print("Player3 wins!")
"""
Main code that runs the game. Continues loop where each player goes and continues
till the end of the game. States winner at the end
"""
def playGame():
file = input( "Enter filename (type d for default file): " )
#file = "F:/Jayme/Documents/Academics/Y1S1/CSCI 141/WackyWheel/test.txt"
#file = "C:/Users/Jayme/Documents/College Academics/Y1S1/CSCI/test.txt"
aList = readFile(file)
player1, player2, player3 = setPlayers(int(aList[0]))
aList.pop(0)
myList = setWheel(aList)
#printList(myList)
numofRounds = 1
out = 0
while (size(myList) >=3 and out <2 ):
print("START Round:" , numofRounds, " Players are: Player1:", player1.Money,
"Player2:", player2.Money, "Player3:", player3.Money)
if (player1.Money > 0):
print("Player1 spins")
amount = move(myList, player1)
print("Player1 account balance:", player1.Money)
if player1.Money <= 0:
print("Player1 has been eliminated!")
out += 1
if (player2.Money > 0):
print("Player2 spins")
amount = move(myList, player2)
print("Player2 account balance:", player2.Money)
if player2.Money <= 0:
print("Player2 has been eliminated!")
out += 1
if (player3.Money > 0):
print("Player3 spins")
amount = move(myList, player3)
print("Player3 account balance:", player3.Money)
if player3.Money <= 0:
print("Player3 has been eliminated!")
out +=1
numofRounds += 1
print( "Ending Results: Player1:", player1.Money,
"Player2:", player2.Money, "Player3:", player3.Money)
printWinner(myList, Player1, Player2, Player3)
playGame()
|
7df773b65e7702200ba41fc806ea3e2ead470585 | Aasthaengg/IBMdataset | /Python_codes/p03937/s124419629.py | 792 | 3.53125 | 4 | def main():
H, W = map(int, input().split())
board = list()
for i in range(H):
board.append(list(input()))
stat = [[False for i in range(W)] for j in range(H)]
go = True
i = j = 0
stat[i][j] = True
while go:
if (i < H) and (j + 1 < W) and board[i][j + 1] == "#":
j = j + 1
stat[i][j] = True
elif (i + 1 < H) and (j < W) and board[i + 1][j] == "#":
i = i + 1
stat[i][j] = True
else:
break
ans = True
for i in range(H):
for j in range(W):
if board[i][j] == "#" and stat[i][j] == False:
ans = False
if ans:
print("Possible")
else:
print("Impossible")
if __name__ == "__main__":
main() |
580d7c29c424e9f0351aec2a96161af24bf89fd6 | MintuKrishnan/subrahmanyam-batch | /16.matrix/intro.py | 505 | 4.0625 | 4 | """
Matrix
"""
A = [
[1, 2, 3],
[4, 5, 6],
[8, 9, 10]
]
row = 1
n = len(A) # no of rows
m = len(A[0]) # no of cols
# for i in range(m):
# print(A[row-1][i])
# col = 3
# for i in range(n):
# print(A[i][col-1])
# for i in range(n):
# for j in range(m):
# print(A[i][j], end=" ")
# print()
# print the diagnol of a matrix
# r = 0
# c = 0
# while r < n and c < m:
# print(A[r][c])
# r+=1
# c+=1
for i in range(min(m, n)):
print(A[i][i]) |
5d5e0faba6ea7abecc0ee5670f6fe9811235000c | Arctanxy/learning_notes | /machinelearning/study/lintcode/PAT/PAT_ADVANCED/cut integer.py | 354 | 3.796875 | 4 | def run():
N = int(input())
for i in range(N):
num = input()
num1 = int(num[:int(len(num)/2)])
num2 = int(num[int(len(num)/2):])
if num1 == 0 or num2 == 0:
print('No')
continue
if int(num) % (num1 * num2) == 0:
print('Yes')
else:
print("No")
run()
|
db2feb86ead28b70d22a18a9717e876fb879953a | GlaucoPhd/Python_Zero2Master | /CreatingOurOwnObjects114.py | 561 | 3.828125 | 4 | # Always class name singular
# __init__ Magic Method
# First Parameter when we write a code Class
# Define a self. only one user can be assigned to it
# Write code dynamic,
# Give a special attribute for a user only is available to him
class PlayerCharacter:
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print('run')
player1 = PlayerCharacter('Glauco', 1)
player2 = PlayerCharacter('Thiago', 9)
player2.attack = 50
print(player1.name)
print(player2.age)
print(player2.attack)
print(player1)
|
a8aa8463649be98371ce3d51d11ef7e011eda24f | Gerald-Izuchukwu/Task-3 | /No_5_sum_two_given_integers.py | 307 | 4.15625 | 4 | # A python that sums up up two integers
# if the result is between 15 and 20, it returns 20
# if not it returns the answer
#
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enetr the second number: "))
sum = num1 + num2
if sum in range(15,20):
print(int(20))
else:
print(sum) |
45ecbe39604e235d51fa240dd1304543a98037c1 | hijkzzz/leetcode | /LintCode/79. 最长公共子串.py | 719 | 3.609375 | 4 | class Solution:
"""
@param A: A string
@param B: A string
@return: the length of the longest common substring.
"""
def longestCommonSubstring(self, a, b):
if len(a) == 0 or len(b) == 0:
return 0
# write your code here
# 使用c[i,j] 表示 以 Xi 和 Yj 结尾的最长公共子串的长度
r = 0
c = [[0 for j in range(len(b) + 1)] for i in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
c[i][j] = c[i - 1][j - 1] + 1
else:
c[i][j] = 0
r = max(c[i][j], r)
return r |
2e7a5d453353ed004cea32d3679e07e97f355ba7 | ChannithAm/PY-programming | /Advance-Python/oop/property.py | 907 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : property.py
# Author : Channith Am <amcnith@gmail.com>
# Date : 21.01.2019
# Last Modified Date: 22.01.2019
# Last Modified By : Channith Am <amcnith@gmail.com>
class Email:
def __init__(self, address):
self._email = address # A private attribute
def _set_email(self, value):
if '@' not in value:
print("This is not an email address.")
else:
self._email = value
def _get_email(self):
return self._email
def _del_email(self):
print("Erase this email attribute!!!")
del self._email
# The interface provides the public attribute email
email = property(_get_email, _set_email, _del_email,
'This property contains the email.')
m1 = Email("kp1@othermail.com")
print(m1.email)
m1.email = "kp2@othermail.com"
print(m1.email)
m1.email = "kp2.com"
del m1.email
|
0531a368ff8ca410c4ee0a403e376e7562c35c89 | Smarty18/Academy_Python | /Controllati_Lunedì22/IstogrammaConInput.py | 591 | 3.96875 | 4 | def istogramma():
var = True #variabile booleana che non diventa mai false per non bloccare il while
st = ""
while var:
numero = int(input("Inserisci un valore:")) #numero di *
if numero == 0: #comando per interrompere l'esecuzione e mandare in stampa l'istogramma
break
elif numero<0:
print ("Inserisci un numero positivo")
numero = input ("Inserisci un valore: ")
for i in range (0,numero):
st = st + "*"
st = st + "\n"
print(st)
istogramma()
|
5292cde519daba07a20ff81b020b2bbd79d34393 | txjzwzz/leetCodeJuly | /Search_for_a_Range.py | 1,735 | 4.0625 | 4 | #-*- coding=utf-8 -*-
__author__ = 'txjzw'
"""
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
"""
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index = [len(nums), -1]
self.binarySearch(nums, target, 0, len(nums)-1, index)
return index if index[1] != -1 else [-1, -1]
def binarySearch(self, nums, target, i, j, index):
if i > j:
return
mid = i + ((j-i) >> 1)
if nums[mid] < target:
self.binarySearch(nums, target, mid+1, j, index)
elif nums[mid] > target:
self.binarySearch(nums, target, i, mid-1, index)
else:
index[0] = min(index[0], mid)
index[1] = max(index[1], mid)
if mid-1>=0 and nums[mid-1] == target:
self.binarySearch(nums, target, i, mid-1, index)
if mid+1 <= len(nums)-1 and nums[mid+1] == target:
self.binarySearch(nums, target, mid+1, j, index)
if __name__ == '__main__':
solution = Solution()
nums = [5, 7, 7, 8, 8, 10]
print solution.searchRange(nums, 8)
print solution.searchRange(nums, 7)
print solution.searchRange(nums, 6)
nums = []
print solution.searchRange(nums, 0)
nums = [5]
print solution.searchRange(nums, 0)
print solution.searchRange(nums, 5)
nums = [2, 2]
print solution.searchRange(nums, 2) |
bcd8243e4845aeb36a48eaa08e7bb27830621fb0 | hkdeman/algorithms | /python/data-structures/tree.py | 600 | 3.640625 | 4 | from tnode import TNode
class Tree:
def __init__(self):
self.root = None
self.size = 0
def get_root(self):
return self.root
def size(self):
return self.size
def set_root(self,node):
self.root = TNode(node)
self.size+=1
def __str__(self):
return str(self.root)
# Tree test
# t= Tree()
# t.set_root("1")
# root = t.get_root()
# m1 = TNode("2")
# m2 = TNode("3")
# m3 = TNode("4")
# root.add_children(TNode(m1,parent=root))
# root.add_children(TNode(m2,parent=root))
# root.add_children(TNode(m3,parent=root)) |
88fef796bf89a2c3daaa46af1e481d24eba4a33f | Apostol095/gotham | /calculator.py | 1,498 | 3.953125 | 4 | def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a,b):
return a/b
calc_dict = {
'+': add,
'-': sub,
'*': mul,
'/': div,
}
def main():
check1= True
while check1 == True:
try:
first_number = float(input('Введите первое число: '))
check1 = False
except ValueError:
print('Ошибка.Введите число еще раз: ')
operation_chek = True
while operation_chek == True:
try:
operation = input('Выберете операцию из доступных: ' + str(list(calc_dict.keys()))).strip()
if "+" and "-" and '*' and '/' not in operation:
continue
operation_chek = False
break
except (KeyError, ValueError) :
print('Сделайте выбор еще раз ')
check2= True
while check2 == True:
try:
second_number = float(input('Введите второе число: '))
check2 = False
except ValueError:
print('Ошибка.Введите число еще раз: ')
res = None
if operation in calc_dict.keys():
res = calc_dict[operation](first_number , second_number) # add(first_number , second_number)
if res is not None:
print('Результат = ', res)
main()
#check() |
48c1440f24f30794e4ca0e28ad22520598eb47f3 | yaminikanthch/Python-Work | /sessions/tictactoe/board188v1 | 2,068 | 3.8125 | 4 | #!/usr/bin/python
import sys
import os
def won(player):
cleanBoard(pos)
print "Player %s won the game!" %(player)
sys.exit()
def draw_game(dg):
cleanBoard(pos)
print "The game is a tie break!"
sys.exit()
def cleanBoard(sel):
print "\n"
print " %s | %s | %s " %(sel[0],sel[1],sel[2])
print "............."
print " %s | %s | %s " %(sel[3],sel[4],sel[5])
print "............."
print " %s | %s | %s " %(sel[6],sel[7],sel[8])
print "\n"
def winCheck(win):
if win[0]=='X' and win[1]=='X' and win[2]=='X':
#won("X")
#Board should be displayed
#Game Over, Press 1 to restart
#sys.exit()
return 'X'
elif win[3]==win[4]==win[5]=='X':
return 'X'
elif win[6]==win[7]==win[8]=='X':
return 'X'
elif win[0]==win[3]==win[6]=='X':
return 'X'
elif win[1]==win[4]==win[7]=='X':
return 'X'
elif win[2]==win[5]==win[8]=='X':
return 'X'
elif win[0]==win[4]==win[8]=='X':
return 'X'
elif win[2]==win[4]==win[6]=='X':
return 'X'
elif ((win[3]==win[4]==win[5]=='O') or (win[6]==win[7]==win[8]=='O') or (win[0]==win[3]==win[6]=='O') or (win[1]==win[4]==win[7]=='O') or (win[2]==win[5]==win[8]=='O') or (win[0]==win[4]==win[8]=='O') or (win[2]==win[4]==win[6]=='O') or (win[0]=='O' and win[1]=='O' and win[2]=='O')):
return 'O'
return False
def chooseTurn(player):
print "This is player %s turn " %(player)
if player == 'X':
player = 'O'
else:
player = 'X'
return player
pos = [" "," "," "," "," "," "," "," "," "]
pturn='X'
turn=0
while True:
cleanBoard(pos)
n_player = chooseTurn(pturn)
userinput = int(raw_input("Enter you choice in the range of 1-9 : "))
if userinput > 0 and userinput < 10:
t=userinput-1
if pos[t] == " ":
pos[t] = pturn
pturn = n_player
turn=turn+1
os.system('clear')
if turn==9:
draw_game(turn)
val=winCheck(pos)
if val=='X':
won(val)
elif val=='O':
won(val)
else:
os.system('clear')
print "Position alreay in use, choose another one"
else:
os.system('clear')
print "Invalid number!, please enter numbers in the range 1 to 9\n\n"
|
7246d7b2c17a0371d88a34f3596866502a803bb8 | olivcarol/Project-Robotics-Company | /Project: Robotics Company.gyp | 5,179 | 4.53125 | 5 | #Create a python class called DriveBot. Within this class, create instance variables for motor_speed, sensor_range, and direction. All of these should be initialized to 0 by default. After setting up the class, create an object from the class called robot_1. Set the motor_speed to 5, the direction to 90, and the sensor_range to 10:
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
print(robot_1.motor_speed)
print(robot_1.direction)
print(robot_1.sensor_range)
#In the DriveBot class, add a method called control_bot which accepts parameters: new_speed and new_direction. These should replace the associated instance variables. Create another method called adjust_sensor which accepts a parameter called new_sensor_range which replaces the sensor_range instance variable. Afterwards, use these methods to rotate the robot 180 degrees at 10 miles per hour with a sensor range of 20 feet:
class DriveBot:
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.control_bot(10, 180)
robot_1.adjust_sensor(20)
print(robot_1.motor_speed)
print(robot_1.direction)
print(robot_1.sensor_range)
#Upgrade the constructor in the DriveBot class in order to accept three optional parameters. The constructor can accept motor_speed (which defaults to 0 if not provided), direction (which defaults to 180 if not provided, and sensor_range (which defaults to 10 if not provided). These parameters should replace the associated instance variables. Test out the upgraded constructor by initializing a new robot called robot_2 with a speed of 35, a direction of 75, and a sensor range of 25:
class DriveBot:
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
print(robot_2.motor_speed)
print(robot_2.direction)
print(robot_2.sensor_range)
#Create a class variable called all_disabled which is set to False. Next, create two more class variables called latitude and longitude. Set both of those variables to equal -999999. A third robot has been created below the first two robots. Set the latitude of all of the robots to -50.0 at once. Additionally, set the longitude of the robots to 50.0 and set all_disabled to True:
class DriveBot:
# Creating the class variables:
all_disabled = False
latitude = -999999
longitude = -999999
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
robot_3 = DriveBot(20, 60, 10)
#Changing the latitude, longitude, and all_disabled values for all three robots:
DriveBot.longitude = 50.0
DriveBot.latitude = -50.0
DriveBot.all_disabled = True
print(robot_1.latitude)
print(robot_2.longitude)
print(robot_3.all_disabled)
#Within the DriveBot class, create an instance variable called id which will be assigned to the robot when the object is created. Every time a robot is created, increment a counter (stored as a class variable) so that the next robot will have a different id. For example, if three robots were created: first_robot, next_robot, and last_robot; first_robot will have an id of 1 next_robot will have an id of 2 and last_robot will have an id of 3:
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
DriveBot.robot_count += 1
self.id = DriveBot.robot_count
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
robot_3 = DriveBot(20, 60, 10)
print(robot_1.id)
print(robot_2.id)
print(robot_3.id) |
1b4a658867e65d32f977b74d482d5587f481eaac | Eger37/algoritmization | /lab_6/lab_6_1.py | 2,660 | 4.09375 | 4 | # 1. За датою d, m, y визначити дату наступного і попереднього дня. В програмі врахувати
# наявність високосних років.
# Сугак Даниїл Васильович 1 курс група 122Б
# def previous_day(day, month, year):
# day -= 1
# month -= 1
# if day < 1:
# month -= 1
# day = months_list[month][1]
# if month < 0:
# year -= 1
# previous_day = f'previous day: {day}:{months_list[month][0]}:{year}'
days = range(1, 32)
months = range(1, 13)
years = range(1901, 2020)
while True:
while True:
try:
d = int(input('day: '))
if d not in days:
print('Не правильное количество дней')
continue
break
except ValueError:
print('only digit')
while True:
try:
m = int(input('months: '))
if m not in months:
print('Не правильное количество month')
continue
break
except ValueError:
print('only digit')
while True:
try:
y = int(input('years: '))
if y not in years:
print('Введите другой год из диапазона 1901 - 2019')
continue
break
except ValueError:
print('only digit')
days_in_february = 28
if y % 4 == 0:
days_in_february = 29
months_list = [['Январь', 31], ['Февраль', days_in_february], ['Март', 31], ['Апрель', 30], ['Май', 31],
['Июнь', 30], ['Июль', 31],
['Август', 31], ['Сентябрь', 30], ['Октябрь', 31], ['Ноябрь', 30], ['Декабрь', 31]]
if d > months_list[m - 1][1]:
print('Не правильное количество дней')
continue
day, month, year = d, m, y
day -= 1
month -= 1
if day < 1:
month -= 1
day = months_list[month][1]
if month < 0:
year -= 1
previous_day = f'previous day: {day}:{months_list[month][0]}:{year}'
day, month, year = d, m, y
day += 1
month -= 1
if day > months_list[month][1]:
month += 1
day = 1
if month > 11:
month = 0
year += 1
next_day = f'next day: {day}:{months_list[month][0]}:{year}'
print(previous_day)
print(next_day)
if input('Нажмите "Enter" (введите пустую строку (\'\')) для перезапуска: ') == '':
continue
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.