blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0f93b3d44b227bfde3335a4084ea6f391ab7623b | devansh5/DSA | /Sorting/bubblesort.py | 393 | 3.6875 | 4 | def bubblesort(a,n):
for i in range(n-1):
flag=False
for j in range(n-1):
if a[j]>a[j+1]:
flag=True
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
if flag==False:
break
return arr
n=int(input())
arr=list(map(int,input().split()))[:n]
print(bubblesort(arr,n))
|
3110cbca7fde295570a8494efb17a9f435b712cc | huigefly/Python | /design/singleton/2.py | 669 | 3.6875 | 4 | class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '__instance'):
print('before new')
print(cls)
cls.__instance = object.__new__(cls, *args, **kwargs)
print('after new')
cls.__instance.__Singleton_Init__(*args, **kwargs)
return cls.__instance
def __init__(self):
print("__init__")
def __Singleton_Init__(self):
print("__Singleton_Init__")
class BB(Singleton):
pass
class CC(Singleton):
pass
c = CC()
c1 = CC()
b=BB()
b.a=2
c.a=3
print(id(c), id(c1))
print(b.a, c.a) |
4b4da8845c0d68d9aa8eca1662b339ae7d81da9f | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/278/82056/submittedfiles/testes.py | 253 | 3.5625 | 4 | x1 = 0
x2 = 100
soma = 0
x1+=1
while (x1<=x2):
if x1%2==0:
soma+=x1
x1+=1
print("%.d" %(soma))
print("\n")
x1=0
x2=100
soma=0
while (true):
x1+=1
if x1>=x2:
break
if x1%2==0:
soma+=x1
print("%.d" %(soma))
|
f137e1d39b78906968d106ab0b5a0395a98a2bcf | mmrraju/Coding-interview-preparation | /Linked Lists/04_Remove_linkedList_elements.py | 1,198 | 3.734375 | 4 | """Given the head of a linked list and an integer val, remove all the nodes of
the linked list that has Node.val == val, and return the new head."""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
def push(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def removeElement(head, val):
dummy_head = Node(-1)
dummy_head.next = head
curr_node = dummy_head
while curr_node.next != None:
if curr_node.next.data == val:
curr_node.next = curr_node.next.next
else:
curr_node = curr_node.next
return dummy_head.next
ll = LinkedList()
ll2 = LinkedList()
for i in range(int(input("Enter the number of elements: "))):
ll.push(int(input()))
ll2.head = removeElement(ll.head, 4)
ll2.printList()
|
98e6b2e7253df153b9c5078c11e52477ef9c6c33 | habroptilus/AOJ | /v0/v001/0012.py | 2,478 | 3.625 | 4 | class vector(object):
def __init__(self,a,b):
self.x=b.x-a.x
self.y=b.y-a.y
@staticmethod
def cross_product(a,b):
return a.x*b.y-a.y*b.x
class vertex(object):
def __init__(self,a):
self.x=a[0]
self.y=a[1]
class circle(object):
def __init__(self,p,r):
self.px=p.x
self.py=p.y
self.r=r
class triangle(object):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
import math
self.ab=math.sqrt((self.a.x-self.b.x)**2+(self.a.y-self.b.y)**2)
self.bc=math.sqrt((self.b.x-self.c.x)**2+(self.b.y-self.c.y)**2)
self.ca=math.sqrt((self.c.x-self.a.x)**2+(self.c.y-self.a.y)**2)
c=self.ab
a=self.bc
b=self.ca
self.cosA=(b**2+c**2-a**2)/(2*b*c)
self.cosB=(a**2+c**2-b**2)/(2*a*c)
self.cosC=(b**2+a**2-c**2)/(2*b*a)
self.sinA=math.sqrt(1-self.cosA**2)
self.sinB=math.sqrt(1-self.cosB**2)
self.sinC=math.sqrt(1-self.cosC**2)
self.sin2A=2*self.sinA*self.cosA
self.sin2B=2*self.sinB*self.cosB
self.sin2C=2*self.sinC*self.cosC
def area(self):
import math
s=(self.ab+self.bc+self.ca)/2
S=math.sqrt(s*(s-self.ab)*(s-self.bc)*(s-self.ca))
return S
def circumscribed(self):
R=self.ab/(2*self.sinC)
px=(self.sin2A*self.a.x+self.sin2B*self.b.x+self.sin2C*self.c.x)/(self.sin2A+self.sin2B+self.sin2C)
py=(self.sin2A*self.a.y+self.sin2B*self.b.y+self.sin2C*self.c.y)/(self.sin2A+self.sin2B+self.sin2C)
px=round(px,3)
py=round(py,3)
R=round(R,3)
p=vertex((px,py))
return circle(p,R)
def isin(self,p):
AB=vector(self.a,self.b)
BC=vector(self.b,self.c)
CA=vector(self.c,self.a)
AP=vector(self.a,p)
BP=vector(self.b,p)
CP=vector(self.c,p)
if (vector.cross_product(AB,AP)>0 and vector.cross_product(BC,BP)>0 and vector.cross_product(CA,CP)>0)or(vector.cross_product(AB,AP)<0 and vector.cross_product(BC,BP)<0 and vector.cross_product(CA,CP)<0):
return 'YES'
else:return 'NO'
A=[]
B=[]
C=[]
p=[]
import sys
for line in sys.stdin:
a,b,c,d,e,f,g,h=list(map(float,line.split()))
A.append(vertex((a,b)))
B.append(vertex((c,d)))
C.append(vertex((e,f)))
p.append(vertex((g,h)))
for i in range(len(A)):
Triangle=triangle(A[i],B[i],C[i])
print(Triangle.isin(p[i]))
|
24b81a3cde65d168b270a31bf400833882bcdb98 | himanshu98-git/python_notes | /whle lup.py | 1,672 | 4.03125 | 4 | #while loop....
#while loops depend on the condtion. when condition false then while loop is terminated it doesnt give any output
"""
x=1
while x<5:
print("hello",x)
x+=1
print("terminated")
"""
"""
x=0
while x<5:
print("hello",x)
x+=1
print("terminated")
x=1
while x<=10:
x+=1
"""
"""
n=int(input("Enter n=="))
i=0
sum=1
while i<=n:
sum=sum+i
i=i+1
print("i====",i)
print("sum========",sum)
print("average=======",sum/n)
"""
"""
#now use while with else
x=0
while x<15:
print("loop on work")
x=x+1
else:
print("loop terminated")
"""
"""
#try to build ing=finite loop
while True:
print("hello")
"""
"""
#nested while
x=0
while x<6:
print("x==",x)
x=x+1
y=0 # if we put y's value globally then it achieve its value
while y<3:
print("y=",y)
y=y+1
"""
#print("*********Transfer statement***********")
#break-at specfic condition we terminate the execution of the loop forcely
#continue
#pass
"""
for i in range(1,100):
if ((i%5==0)&(i%7==0)):
break
else:
print("umber==",i)
"""
for i in range(1,100):
if ((i%5==0)&(i%7==0)):
continue
else:
print("umber==",i)
"""
for i in range(1,100):
if ((i%5==0)&(i%7==0)):
pass# it uses to pass condition
else:
print("umber==",i)
"""
#combine wrking of breask and continue ---->
"""
for i in range(1,1000):
if(i%2==0):
continue
elif(i==501):
break
else:
print(i)
"""
|
e51c8077dcc79f81db29bfd1e1999cbd60f20298 | arnabid/QA | /utility/combinations.py | 546 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 13 20:08:29 2017
@author: arnab
"""
"""
generate all 2^n combinations
"""
def comb1(s):
comb1Util("", s)
def comb1Util(prefix, s):
print (prefix)
for i in range(len(s)):
comb1Util(prefix + s[i], s[i+1:])
def comb2(s, k):
comb2Util("", s, k)
def comb2Util(prefix, s, k):
if k == 0:
print (prefix)
return
for i in range(len(s)):
comb2Util(prefix + s[i], s[i+1:], k-1)
if __name__ == '__main__':
s = "ABC"
#comb1(s)
comb2(s, 2) |
f200e60af34002ef61d9d5c3ec2d4a420a2863d7 | camilaffonseca/Learning_Python | /Prática/ex012.py | 256 | 3.578125 | 4 | # coding: utf-8
# Aluguel de carros
distancia = float(input('Distância percorrida em Km: '))
dias = int(input('Quantos dias alugados? '))
preço = (0.15 * distancia) + (60 * dias)
print(f'O valor total a pagar por {dias} dias e {distancia}Km é de R${preço}')
|
fde3087ee2c8cd47bab8f3e80933aefbdcd69ff7 | gerglion/aoc2020 | /day01/solution.py | 1,567 | 3.890625 | 4 | #!/usr/local/bin/python3
import sys
num_list = []
def read_file(inputfile):
f = open(inputfile,"r")
for x in f:
num_list.append(int(x))
f.close()
def find_goal_sum1(goal):
ans = 0
for big in num_list:
for small in num_list[:0:-1]:
if big + small == goal:
print(big,small)
ans = big * small
break
else:
continue
break
print(ans)
return ans
def find_goal_sum2(goal):
ans = 0
for big in num_list:
for small in num_list[:0:-1]:
for mid in num_list[-2:0:-1]:
if big + small + mid == goal:
print(big,small,mid)
ans = big * small * mid
break
else:
continue
break
else:
continue
break
print(ans)
return ans
def main():
# Command line input
if len(sys.argv) > 2:
sum_goal = sys.argv[2]
input_file = sys.argv[1]
elif len(sys.argv) > 1:
sum_goal = 2020
input_file = sys.argv[1]
else:
sum_goal = 2020
input_file = 'inputtest.txt'
print(input_file,sum_goal)
read_file(input_file)
num_list.sort(reverse=True)
print(num_list)
#Solve Part 1
print("Part 1")
answer1 = find_goal_sum1(sum_goal)
print("Answer 1:",answer1)
#Solve Part 2
print("Part 2")
answer2 = find_goal_sum2(sum_goal)
print("Answer 2:",answer2)
if __name__ == '__main__':
main()
|
fa04afa4528ce26dd9cc5682410de9fb6b47ae7e | gjq91459/mycourse | /Scientific Python/Numpy/06.basic-functions.py | 755 | 3.859375 | 4 | ############################################################
#
# basic functions
#
############################################################
import numpy as np
np.set_printoptions(precision=3)
a = np.array( np.random.random(12) * 100, dtype="int" ).reshape(3,4)
print a
# perform operations along specified axis
print np.average(a, axis=0)
print np.average(a, axis=1)
# sort data
print np.msort(a)
print np.sort(a, axis=0)
print np.sort(a, axis=1)
# insert elements: insert(array, positions, items)
print a
b = np.insert(a, (1,5,9), (-1,-2,-3) ); print b
b = np.insert(a, (1,5,9), (-1,-2,-3) ).reshape(3,5); print b
b = np.append(a, (-1,-2,-3,-4) ).reshape(4,4); print b
b = np.round_(a ** 1.1, 2); print b
1
|
15b738ff17b198389fa84dc497795e78a5675ee5 | GabrielF9/estudo-tecnologias | /python/bin2dec/bin2dec.py | 468 | 3.703125 | 4 | # Using normal multiplication logic
def bin2dec_v1(_bin):
decimal = 0
count = 0
for b in _bin[::-1]:
decimal += int(b)*(2**count)
count += 1
return decimal
# Using the same logic but with list comprehension
def bin2dec_v2(_bin):
return sum([2**i for i in range(len(_bin)) if int(_bin[::-1][i]) == 1])
if __name__ == "__main__":
raw_binary = input('Digite um número binário: ')
print(bin2dec_v1(raw_binary))
print(bin2dec_v2(raw_binary)) |
7906f29c66c30989aa611eb81cc39e2648aef928 | saji021198/set-10 | /recursively.py | 125 | 3.5625 | 4 | N=int(input())
while(N>0):
if (N%2)!=0:
print(N)
break
else:
N=N//2
|
4150b5a5f0cbf1398ff139eb485d65af9aefd229 | alpha4408/Find-mean-and-mode | /find mean and mode of a list.py | 774 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # **Find mean and mode of a list of numbers **
# In[31]:
"""
Find mean and mode of a list of numbers
"""
import statistics
class math_cal:
def __init__(self,listNumber):
self.listNumber = listNumber
def mean_list(self,listNumber):
total = 0
for i in range(0,len(listNumber)):
total = total + listNumber[i]
mean = total/len(listNumber)
print(f"The mean of this list is {mean} ")
def mode_list(self,listNumber):
result = statistics.mode(listNumber)
print(f"The mode of the list is {result}")
object1 = math_cal([1,1,1,5,3,6])
object1.mean_list([1,1,1,5,3,6])
object1.mode_list([1,1,1,5,3,6])
# In[ ]:
|
c01b712ed26c7f2cfe1acbc5bb1d00c000a8766e | MiyamonY/quick-python | /chap3/chap3.py | 4,965 | 4 | 4 | # /usr/bin/env python3
# -*- coding:utf-8 -*-
x = 5 + 2 - 3 * 2
print(x)
# 割り算
print(5 / 2)
# 切り捨て
print(5 // 2)
# 余り
print(5 % 2)
print(2 ** 8)
print(1000000001 ** 3)
print(4.3 ** 2.4)
print(3.5e30 * 2.77e45)
print(10000000001.0 ** 3)
print((3+2j) ** (2+3j))
x= (3 + 2j) * (4 + 9j)
print(x)
print(x.real, x.imag)
print(round(3.49))
import math
print(math.ceil(3.49))
# Bool
x = False
print(x)
print(not x)
# Trueは1,Falseは0のように振る舞う
y = True * 2
print(y)
# リスト
print([])
print([1])
print([1,2,3,4,5,6,8,12])
print([1, "two", 3, 4.0, ["a", "b"], (5,6)])
# インデックス指定
x = ["first", "second", "third", "fourth"]
print(x[0])
print(x[2])
print(x[-1])
print(x[-2])
print(x[1:-1])
print(x[0:3])
print(x[-2:-1])
print(x[:3])
print(x[-2:])
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x[1] = "two"
print(x)
x[8:9] = []
print(x)
x[5:7] = [6.0, 6.5, 7.0]
print(x)
print(x[5:])
# リストのメソッド
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(len(x))
# xはそのまま
print([-1, 0] + x)
x.reverse()
print(x)
# タプル
print(())
print((1,)) # 要素が一つしかない場合カンマが必要
print((1,2,3,4,5,6,12))
print((1,"two", 3, 4.0, ["a", "b"], (5, 6)))
x = [1,2,3,4]
print(tuple(x)) # リストからタプルへ
x = (1,2,3,4)
print(list(x)) # タプルからリストへ
## 文字列
x = "live and let \t \tlive"
print(x.split()) # 空白文字でsplitする
print(x.replace(" let \t \tlive", "enjoy life"))
import re # 正規表現
regexpr = re.compile(r"[\t ]+")
print(regexpr.sub(" ", x))
# print関数の使い方
e = 2.718
x = [1, "two", 3, 4.0, ["a", "b"], (5,6)]
print("The constant e is:", e, "and the list x is:", x)
print("the value of %s is %.2f" % ("e", e))
## 辞書
#キーは変更不能な型でないといけない
x = {1:"one", 2:"two"}
x["first"]="one"
x[("Delorme", "Ryan", 1995)] = (1,2,3)
print(list(x.keys()))
print(x[1])
# 要素が存在しない場合、getはオプションでユーザー定義の値を返す
print(x.get(1, "not available"))
print(x.get(4, "not available"))
print(x.get(4)) # 要素が存在しない場合、例外でなくNoneを返す
## 集合
x = set([1,2,3,1,3,5])
print(x)
print(1 in x)
print(4 in x)
f = open("myfile", "w")
print(f.write("First line with necessary newline character\n"))
print(f.write("Second line to write to the file \n"))
f.close()
f = open("myfile", "r")
line1 = f.readline()
line2 = f.readline()
f.close()
print(line1, line2)
import os
print(os.getcwd())
os.chdir(os.path.join("/home", "ym", "Documents"))
filename = os.path.join("/home", "ym", "project", "quick-python", "chap3", "myfile")
print(filename)
f = open(filename, "r")
print(f.readline())
f.close()
## 制御フロー
x = 5
if x < 5:
y = -1
z = 5
elif x > 5:
y = 1
z = 11
else:
y = 0
z = 10
print(x, y, z)
# whileループ
u, v, x, y = 0, 0, 100, 30
while x > y:
u = u + y
x = x - y
if x < y + 2:
v = v + x
x = 0
else:
v = v + y + 2
x = x - y - 2
print(u, v)
# forループ
item_list = [3, "sring1", 23, 14.0, "string2", 49, 64, 70]
for x in item_list:
if not isinstance(x, int):
continue
if not x % 7:
print("found an integer divisivle by seven %d" % x)
break
## 関数定義
def funct1(x, y , z):
value = x + 2*y + z ** 2
if value > 0:
return x + 2 * y +z**2
else:
return 0
u, v = 3, 4
print(funct1(u, v, 2))
print(funct1(u, z=v, y=2))
def funct2(x, y=1, z=1):
return x + x*y + z**2
print(funct2(3, z=4))
def funct3(x, y=1, z=1, *tup):
print((x,y,z) + tup)
funct3(2)
funct3(1,2,3,4,5,6,7,8,9)
def funct4(x, y=1, z=1, **dict):
print(x, y, z, dict)
funct4(1, 2, m=5, n=9, z=3)
## 例外
class EmptyFileError(Exception):
pass
filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"]
for file in filenames:
try:
f = open(file, 'r')
line = f.readline() # IOErrorが発生する可能性がある
if line == "":
f.close()
raise EmptyFileError("%s: is empty" % file)
except IOError as error:
print("%s : could not be opened: %s" %(file, error.strerror))
except EmptyFileError as error:
print(error)
else:
print("%s: %s" % (file, f.readline()))
finally: # 例外が発生したかどうかに関わらず常に実行される
print("Done processing", file)
## モジュール
import sys
print(sys.path)
os.chdir(os.path.join("/home", "ym", "project", "quick-python", "chap3"))
import wo
wo.words_occur()
# モジュールのリロード
import imp
imp.reload(wo)
## オブジェクト指向プログラミング
import sh
c1 = sh.Circle()
c2 = sh.Circle()
print(c1)
print(c2)
print(c2.area())
c2.move(5, 6)
print(c2)
|
1a2dc5cc1765e76d372274dd7b79f1024ab096f9 | george39/hackpython | /modulos/modulo_calculadora.py | 402 | 3.671875 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
def sumar(valor1, valor2):
print("La suma es: {}".format(valor1 + valor2) )
def restar(valor1, valor2):
print("La resta es: {}".format(valor1 - valor2) )
def dividir(valor1, valor2):
print("La division es: {}".format(valor1 / valor2) )
def multiplicar(valor1, valor2):
print("La multiplicacion es: {}".format(valor1 * valor2) )
|
c9521baef0ef69641e8dd3798ba552b7c403b5e2 | yoyocheknow/leetcode_python | /150_Evaluate_Reverse_Polish_Notation.py | 1,196 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack=[]
while(tokens):
t=tokens.pop(0)
if t=='+':
operator1=stack.pop()
operator2=stack.pop()
res=operator1+operator2
stack.append(res)
elif t=='-':
operator1 = stack.pop()
operator2 = stack.pop()
res = operator2 - operator1
stack.append(res)
elif t=='*':
operator1 = stack.pop()
operator2 = stack.pop()
res = operator1 * operator2
stack.append(res)
elif t=='/':
operator1 = stack.pop()
operator2 = stack.pop()
res = operator2 // operator1 if operator2 * operator1 > 0 else (operator2 + (-operator2 % operator1)) // operator1
stack.append(res)
else:
stack.append(int(t))
return stack[0]
if __name__ == "__main__":
r = Solution().evalRPN(["4","3","-"])
print r |
a0f32433b8a4e63eb530e28fb60894be9847657d | doguhanyeke/30dayChallenge | /day2.py | 839 | 3.5 | 4 | import math
class Solution:
def isHappy(self, n: int) -> bool:
def is_one(num: int) -> bool:
str_num = str(num)
# print(str_num)
sum_num = 0
for i in str_num:
# print(i)
sum_num += int(i)
return sum_num == 1
def happy_calc(num: int) -> int:
str_num = str(num)
length = len(str_num)
sqr_num = 0
for i in str_num:
sqr_num += int(math.pow(int(i), 2))
return sqr_num
d = dict()
number = n
while not is_one(number):
number = happy_calc(number)
if number in d:
return False
else:
d[number] = 1
return True
s = Solution()
res = s.isHappy(200)
print(res) |
1595a26a907b6a2ec61ed4c05a82c89b56bbc3ee | Miesvanderlippe/ISCRIP | /Oplevering 2/palindroom-s1096607-ifict-poging1.py | 706 | 4.09375 | 4 | import math
def is_palindrome(word: str) -> bool:
# Word length
word_length = len(word)
# Half word length, floored. This ensures middle character isn't checked
# if the word is of uneven length
half_length = math.floor(word_length / 2)
# First half of the word
first_half = word[0:half_length]
# Second half reversed
second_half = ''.join(reversed(word[word_length - half_length::]))
# If those match, it's a palindroom
return first_half == second_half
if __name__ == '__main__':
with open(input("File:\n")) as f:
for line in f:
stripped = line.strip().lower()
if is_palindrome(stripped):
print(stripped)
|
da00c15c1b70bb29a68798d126d19b711fb94296 | mmueller/project-euler | /p56.py | 699 | 4.125 | 4 | #!/usr/bin/env python
"""
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^b, where a, b < 100, what is the
maximum digital sum?
"""
from digits import get_digits
if __name__ == '__main__':
maxsum = 0
for a in range(0, 100):
for b in range(0, 100):
s = sum(get_digits(a**b))
if s > maxsum:
maxsum = s
maxa = a
maxb = b
print "%d^%d = %d" % (maxa, maxb, maxa**maxb)
print "Sum: %d" % maxsum
|
a0a8500d2a300552c18cc18e428039e3e2cb2863 | Presac/Tic-Tac-Toe | /Players.py | 8,073 | 3.9375 | 4 | from random import randint, choice
from collections import Counter
from Board import Board
# Player class for saving name and which sign to use
class Player():
def __init__(self, name, sign):
"""
Initialize a human player
:param name: the name of the player
:param sign: the sign the player plays with
"""
self.name = name
self.sign = sign
self.type = 'human'
# Asks for and returns a 2 part value from an input
def getInput(self, board):
"""
Get the input for a human player
:param board: the board to play on
"""
# while True:
# print('Choose row and coloumn (col row): ', end='')
# # Try for input, in case the user doesn't input two values
# try:
# x, y = input().split(' ')
# except ValueError:
# print('Input is not 2 values.')
# continue
# # Check if any of the two values is not an int
# if not (x.isdigit() and y.isdigit()):
# print('Input is not a number. Letters won\'t work.')
# continue
# # Check if the values confine to the board
# if board.isWithinBoard(int(x) - 1, int(y) - 1):
# break
# print('The choice is not within the range of the board.')
# return board.twoDToOneD(int(x) - 1, int(y) - 1)
while True:
print('Choose a field: ', end='')
x = input()
# Check if any of the two values is not an int
if not x.isdigit():
print('Input is not a number. Letters won\'t work.')
continue
# Check if the values confine to the board
if board.isWithinBoard(int(x) - 1):
break
print('The choice is not within the range of the board.')
return int(x) - 1
def getCharacter(self, board):
return board.getCharacter(self.sign)
# AI inherits from player
class AI(Player):
def __init__(self, name, sign, difficulty):
"""
Initialize a ai player
:param name: the name of the player
:param sign: the sign the ai plays with
:param difficulty: the difficulty the ai should play at
"""
super().__init__(name, sign)
# Will be used when different difficulties are made
self.difficulty = int(difficulty)
self.type = 'ai'
# Get input depending on difficulty
def getInput(self, board):
"""
Get an input depending on the difficulty
"""
if self.difficulty == 0:
return self.chooseRandom(board)
elif self.difficulty == 1:
return self.smart(board)
else:
return self.chooseFuture(board)
# Choose a random free field
def chooseRandom(self, board):
"""
Choose a random value from a number of free fields from the board
:param board: the board to choose the free fields from
:returns: an int
"""
free = board.freeFields()
if len(free) > 0:
i = randint(0, len(free) - 1)
else:
return None
return free[i]
# Choose a free field depending on what is already taken
def smart(self, board):
"""
A "smart" ai to choose between the available fields depending on the
threat level of each field.
:param board: the board to choose a field from
:returns: an int
"""
free = board.freeFields()
states = []
# Check each free field for their state
for n in free:
# Get the diagonal lines
diagonal = [board.diagonal(0), board.diagonal(1)]
# Get the state of the fields row and column
# As every field has them, they will always be checked
state = self.merge_dicts(self.checkLine(board.row(n)),
self.checkLine(board.column(n)))
# Check if the field is in one of the diagonals
if n == 0 or n == 8: # Upper left and lower right corner
state = self.merge_dicts(state, self.checkLine(diagonal[0]))
elif n == 2 or n == 6: # Upper right and lower left corner
state = self.merge_dicts(state, self.checkLine(diagonal[1]))
if n == 4: # Center
state = self.merge_dicts(state, self.checkLine(diagonal[0]))
state = self.merge_dicts(state, self.checkLine(diagonal[1]))
# Save the field number in state together with
# the state of the field
states.append({**{'n': n}, **state})
# Get a list with all the win fields
win = [state['n'] for state in states if state['win'] is True]
if len(win) > 0:
# No need to go further, as this will finish the game
return choice(win)
# Get a list with all the loss fields
lose = [state['n'] for state in states if state['lose'] is True]
if len(lose) > 0:
# No need to go further. Not choosing the field will end the game
return choice(lose)
# Get a list with all the threat fields (towards the player)
threats = {state['n']: state['threat']
for state in states if state['threat'] != 0}
if len(threats) > 0:
# Sort by order of highest threat
ctr = Counter(threats).most_common()
# Get the fields with the highest threat
maxes = [k for k, v in ctr if v == ctr[0][1]]
return choice(maxes)
return self.chooseRandom(board)
def checkLine(self, line):
"""
Checks the state of list
:param line: a list
:returns: a list of the different states the line has
"""
state = {'win': False, 'lose': False, 'threat': 0}
lineSet = set(line)
# full or empty
if len(lineSet) == 1:
pass # None
if len(lineSet) == 2:
# Count the number of empty fields
# Either a win or a possible loss
if line.count(0) == 1:
state['win'] = self.sign in line
state['lose'] = self.sign not in line
# A threat can be made
if self.sign in line and line.count(0) == 2:
state['threat'] = 1
return state
# a minimax type of chooser
def chooseFuture(self, board, depth=6):
# Depth will make it only look a certain amount of steps forward
# 6 seems to be the deepest it have to go to never loose
def max_value(fields, depth):
if depth == 0:
return 0
if board.isTerminal(fields):
return board.utilityOf(fields, self.sign)
v = -infinity
for (a, s) in board.successorsOf(fields):
v = max(v, min_value(s, depth - 1))
return v
def min_value(fields, depth):
if depth == 0:
return 0
if board.isTerminal(fields):
return board.utilityOf(fields, self.sign)
v = infinity
for (a, s) in board.successorsOf(fields):
v = min(v, max_value(s, depth - 1))
return v
def argmax(iterable, func):
return max(iterable, key=func)
infinity = float('inf')
fields = board.fields[:]
action, fields = argmax(board.successorsOf(fields), lambda a: min_value(a[1], depth))
return action
@staticmethod
def merge_dicts(x, y):
"""
Returns a merge of two dictionaries. The values need to be either
Bool or numbers
:param x: the first dictionary
:param y: the second dictionary
:returns: a dictionary
"""
z = {}
for k, v in x.items():
z[k] = v or y[k] if type(v) is bool else v + y[k]
return z
|
44a9a4ecd2307690023fa09d7f3de589d509d2b2 | MHuang2001/COMP3308 | /Assignment 1/src/ThreeDigits.py | 11,259 | 3.71875 | 4 |
import re
import sys
import numpy as np
import math
def main():
alg = sys.argv[1]
with open(sys.argv[2]) as f:
lines = f.read().splitlines()
if len(lines) == 2 or len(lines) == 3:
start = lines[0]
goal = lines[1]
forbids = []
if len(lines) == 3:
forbids = lines[2].split(",")
else:
print("Invalid input.")
sys.exit()
start_idx = convert_input(start)
goal_idx = convert_input(goal)
forbidden = [convert_input(i) for i in forbids]
if alg == "B":
return bfs(start_idx, goal_idx, forbidden)
elif alg == "D":
return dfs(start_idx, goal_idx, forbidden)
elif alg == "I":
return ids(start_idx, goal_idx, forbidden)
elif alg == "G":
return greedy(start_idx, goal_idx, forbidden)
elif alg == "A":
return a_star(start_idx, goal_idx, forbidden)
elif alg == "H":
return hill(start_idx, goal_idx, forbidden)
else:
print("Search algorithm not defined.")
def convert_input(s):
return [int(i) for i in s]
def print_answer(nums):
print(','.join(list(map(lambda idx: ''.join(map(str, idx)), nums))))
# BFS
def bfs(start_idx, goal_idx, forbidden):
queue = [(start_idx, [], [0,0,0])] # current_idx, path, last_move
visited = []
while queue:
current_idx, path, last_move = queue.pop(0) # remove first element from queue
visited.append((current_idx, last_move)) # record expanded nodes
if len(visited) >= 1000:
print("No solution found.")
print_answer(list(map(lambda p: p[0], visited))) # gets path element from visited tuple
return
path.append(current_idx)
if current_idx == goal_idx:
print_answer(path)
print_answer(list(map(lambda p: p[0], visited)))
return
for i in range(3):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] -=1
if n[i] >= 0 and n not in forbidden and (n, move) not in visited:
queue.append((n, path[:], move))
n = current_idx[:]
n[i] += 1
if n[i] <= 9 and n not in forbidden and (n, move) not in visited:
queue.append((n, path[:], move))
#DFS
def dfs(start_idx, goal_idx, forbidden):
stack = [(start_idx, [], [0,0,0])]
visited = []
while stack:
current_idx, path, last_move = stack.pop() # remove first element from stack
visited.append((current_idx, last_move)) # record expanded nodes
if len(visited) >= 1000:
print("No solution found.")
print_answer(list(map(lambda p: p[0], visited))) # gets path element from visited tuple
return
path.append(current_idx)
if current_idx == goal_idx:
print_answer(path)
print_answer(list(map(lambda p: p[0], visited)))
return
for i in range(2, -1, -1):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] +=1
if n[i] <= 9 and n not in forbidden and (n, move) not in visited:
stack.append((n, path[:], move))
n = current_idx[:]
n[i] -= 1
if n[i] >= 0 and n not in forbidden and (n, move) not in visited:
stack.append((n, path[:], move))
#IDS
def ids(start_idx, goal_idx, forbidden):
visited = []
ids_depth = 0
while True:
stack = [(start_idx, [], [0,0,0], 0)]
while stack:
current_idx, path, last_move, depth = stack.pop() # remove first element from stack
if depth > ids_depth:
continue
visited.append((current_idx, last_move, ids_depth)) # record expanded nodes
if len(visited) >= 1000:
print("No solution found.")
print_answer(list(map(lambda p: p[0], visited))) # gets path element from visited tuple
return
path.append(current_idx)
if current_idx == goal_idx:
print_answer(path)
print_answer(list(map(lambda p: p[0], visited)))
return
for i in range(2, -1, -1):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] +=1
if n[i] <= 9 and n not in forbidden and (n, move, ids_depth) not in visited:
stack.append((n, path[:], move, depth + 1))
n = current_idx[:]
n[i] -= 1
if n[i] >= 0 and n not in forbidden and (n, move, ids_depth) not in visited:
stack.append((n, path[:], move, depth + 1))
ids_depth += 1
def heuristic(start,goal):
if start == None:
return math.inf
return sum([abs(a-b) for a,b in zip(start,goal)])
#Greedy
def greedy(start_idx, goal_idx, forbidden):
queue = PriorityQueue()
queue.add((start_idx, [], [0,0,0]), heuristic(start_idx, goal_idx))
visited = []
while queue.size > 0:
current_idx, path, last_move = queue.remove_min() # remove first element from queue
visited.append((current_idx, last_move)) # record expanded nodes
if len(visited) >= 1000:
print("No solution found.")
print_answer(list(map(lambda p: p[0], visited))) # gets path element from visited tuple
return
path.append(current_idx)
if current_idx == goal_idx:
print_answer(path)
print_answer(list(map(lambda p: p[0], visited)))
return
for i in range(3):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] -=1
if n[i] >= 0 and n not in forbidden and (n, move) not in visited:
queue.add((n, path[:], move), heuristic(n, goal_idx))
n = current_idx[:]
n[i] += 1
if n[i] <= 9 and n not in forbidden and (n, move) not in visited:
queue.add((n, path[:], move), heuristic(n, goal_idx))
#A*
def a_star(start_idx, goal_idx, forbidden):
queue = PriorityQueue()
queue.add((start_idx, [], [0,0,0]), heuristic(start_idx, goal_idx))
visited = []
while queue.size > 0:
current_idx, path, last_move = queue.remove_min() # remove first element from queue
visited.append((current_idx, last_move)) # record expanded nodes
if len(visited) >= 1000:
print("No solution found.")
print_answer(list(map(lambda p: p[0], visited))) # gets path element from visited tuple
return
path.append(current_idx)
if current_idx == goal_idx:
print_answer(path)
print_answer(list(map(lambda p: p[0], visited)))
return
for i in range(3):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] -=1
if n[i] >= 0 and n not in forbidden and (n, move) not in visited:
queue.add((n, path[:], move), heuristic(n, goal_idx)+len(path))
n = current_idx[:]
n[i] += 1
if n[i] <= 9 and n not in forbidden and (n, move) not in visited:
queue.add((n, path[:], move), heuristic(n, goal_idx)+len(path))
#Hill-climbing
def hill(start_idx, goal_idx, forbidden):
visited = [start_idx]
current_idx = start_idx
last_move = [0,0,0]
while current_idx != goal_idx:
if len(visited) >= 1000:
print("No solution found.")
print_answer(visited) # gets path element from visited tuple
return
best_idx = current_idx
best_last_move = last_move
for i in range(3):
if last_move[i] == 1:
continue
move = [0, 0, 0]
move[i] = 1
n = current_idx[:]
n[i] -=1
if n[i] >= 0 and n not in forbidden and n not in visited and (heuristic(best_idx, goal_idx) >= heuristic(n, goal_idx)):
best_idx = n
best_last_move = move
n = current_idx[:]
n[i] += 1
if n[i] <= 9 and n not in forbidden and n not in visited and (heuristic(best_idx, goal_idx) >= heuristic(n, goal_idx)):
best_idx = n
best_last_move = move
if best_idx == current_idx:
print("No solution found.")
print_answer(visited)
return
visited.append(best_idx)
current_idx = best_idx
last_move = best_last_move
print_answer(visited)
print_answer(visited)
class PriorityQueue():
def __init__(self):
self.queue = [0 for _ in range(1000)]
self.size = 0
self.count = 0
def add(self, val, priority):
self.queue[self.size] = (val, priority, self.count)
self.size += 1
self.count += 1
self.sift_up(self.size - 1)
def remove_min(self):
if self.size == 0:
return None
minimum = self.queue[0]
self.size -= 1
self.queue[0] = self.queue[self.size]
self.sift_down(0)
return minimum[0]
def left_child(self, i):
return (i * 2) + 1
def right_child(self, i):
return (i * 2) + 2
def parent(self, i):
return (i - 1) // 2
def has_left_child(self, i):
return self.left_child(i) < self.size
def has_right_child(self, i):
return self.right_child(i) < self.size
def sift_up(self, i):
if i == 0:
return
p_idx = self.parent(i)
_, pp, pc = self.queue[p_idx]
_, cp, cc = self.queue[i]
if pp < cp or (pp == cp and pc > cc):
return
# parent priority higher, or equal and count lower
self.queue[p_idx], self.queue[i] = self.queue[i], self.queue[p_idx]
self.sift_up(p_idx)
def sift_down(self, i):
if not self.has_left_child(i):
return
l_idx = self.left_child(i)
_, lp, lc = self.queue[l_idx]
_, cp, cc = self.queue[i]
min_c = l_idx
min_cc = lc
min_cp = lp
if self.has_right_child(i):
r_idx = self.right_child(i)
_, rp, rc = self.queue[r_idx]
if rp < lp or (rp == lp and rc > lc):
min_c = r_idx
min_cc = rc
min_cp = rp
if cp < min_cp or (cp == min_cp and cc > min_cc):
return
self.queue[min_c], self.queue[i] = self.queue[i], self.queue[min_c]
self.sift_down(min_c)
if __name__ == "__main__":
main() |
f4eebbc8456bc699865bb6a034274c7b20e0f0d3 | gustavomarquezinho/python | /study/w3resource/exercises/python-basic/001 - 030/python-basic - 022.py | 193 | 3.71875 | 4 | # 022 - Write a Python program to count the number 4 in a given list.
def fourCount(pNumbers):
return pNumbers.count(4)
print(fourCount([1, 2, 9, 4, 3, 4]), fourCount([4, 2, 3, 4, 4, 0])) |
49049727ef4674de6d27290fc04ba181d6745b54 | SenpaiKirigaia/Laboratory-work-1-sem | /Turtle 1/Turtle11.py | 194 | 3.609375 | 4 | import turtle as t
a = 10
t.speed(10)
t.setheading(90)
for i in range(5):
for i in range(36):
t.forward(a)
t.left(10)
for i in range(36):
t.forward(a)
t.right(10)
a = a+1
|
1c19ff205574964d06f4c7786fa625e3f074d2fe | scantwell/cs_fundementals | /algorithms/mergesort.py | 946 | 4.28125 | 4 | #!/usr/bin/python
def mergesort(_list):
if len(_list) < 2:
return _list
mid = len(_list)/2
left, right = _list[:mid], _list[mid:]
mergesort(left)
mergesort(right)
merge(left, right, _list)
def merge(left, right, _list):
nleft = len(left)
nright = len(right)
i = j = k = 0
while i < nleft and j < nright:
if left[i] <= right[j]:
_list[k] = left[i]
i += 1
else:
_list[k] = right[j]
j +=1
k += 1
# Append the remainder of left to the _list
while i < nleft:
_list[k] = left[i]
i += 1
k += 1
# Append the remained of right to the _list
while j < nright:
_list[k] = right[j]
j += 1
k += 1
if __name__ == '__main__':
print 'Welcome to the implementation of Mergesort algorithm'
a = [2,3,1,22,5,3]
b = [1]
c = []
d = [30, -2, 4]
print 'Unsorted Lists \na:{} \nb:{} \nc:{} \nd:{}'.format(a,b,c,d)
for l in [a,b,c,d]:
mergesort(l)
print 'Sorted List \na:{} \nb:{} \nc:{} \nd:{}'.format(a,b,c,d)
|
c28b57b9fc871f7dddac8179dd0466b0c7fdb8c8 | maxweldsouza/rosalind | /solutions/lexf.py | 140 | 3.875 | 4 | from itertools import product
def lexf(symbols, n):
for x in product(symbols, repeat=n):
print ''.join(x)
lexf('ABCDEFGH', 3)
|
b8776d2c4534962ae1e9e529c36e8a5389d2d0f2 | adnanjaber/Money-Change | /MoneyChange.py | 548 | 4.125 | 4 | number = int(input("Enter the Amount of Israeli money you want:"))
s = {1, 2, 5, 10, 20, 50, 100, 200}
#this function finds the biggest number that is smaller than the input number
def find_biggest(s, number):
result = 0
for k in s:
if k > result and k <= number:
result = k
return result
result = []
while sum(result) != number:
current_result=number-sum(result)
if sum(result) < number:
result.append(find_biggest(s, current_result))
print("There you go: ")
print(result)
|
ec05336e93cc1398b506f06b4a4ff92584e8e0de | ivankonatar/SP-Homework05 | /T2.py | 1,449 | 4.65625 | 5 | """ T2. Write a Python program that can simulate a simple calculator, using the console as the
exclusive input and output device. That is, each input to the calculator, be it a number, like
12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input,
you should output to the Python console what would be displayed on your calculator."""
def calculate():
operation = input('''
+ for addition
- for subtraction
* for multiplication
/ for division
Please type in the math operation you would like to complete: ''')
num1 = int(input('Enter the number 1: '))
num2 = int(input('Enter the number 2: '))
if operation == '+':
print('{} + {} = '.format(num1, num2))
print(num1 + num2)
elif operation == '-':
print('{} - {} = '.format(num1, num2))
print(num1 - num2)
elif operation == '*':
print('{} * {} = '.format(num1, num2))
print(num1 * num2)
elif operation == '/':
print('{} / {} = '.format(num1, num2))
print(num1 / num2)
else:
print('You have not typed a valid operator, please run the program again.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate() |
c20caf370d194b9662c07e2a956fabc729cc6e50 | tapsevarg/1st-Semester | /Session 11/Activity 5 v2.py | 1,764 | 3.921875 | 4 | # This is an automated Monty Hall problem solver
import random
def hide_prize(doors):
prize = random.choice(doors)
return prize
def generate_choice(doors):
choice = random.choice(doors)
return choice
def test_samples1():
winners1 = 0
doors1 = ["door 1", "door 2", "door 3"]
for count1 in range(0, 100, 1):
prize = hide_prize(doors1)
choice = generate_choice(doors1)
if prize is choice:
winners1 += 1
scoreboard = [winners1]
return scoreboard
def test_samples2(scoreboard):
winners2 = 0
doors2 = ["door 1", "door 2", "door 3"]
for count in range(0, 100, 1):
prize = hide_prize(doors2)
choice = generate_choice(doors2)
if doors2[0] is not prize and doors2[0] is not choice:
if choice is doors2[1]:
choice = doors2[2]
else:
choice = doors2[1]
elif doors2[1] is not prize and doors2[1] is not choice:
if choice is doors2[0]:
choice = doors2[2]
else:
choice = doors2[0]
else:
if choice is doors2[0]:
choice = doors2[1]
else:
choice = doors2[0]
if prize is choice:
winners2 += 1
scoreboard.append(winners2)
return scoreboard
def output_results(scoreboard):
print("The computer initially picked the correct door:")
print(scoreboard[0], " times out of 100.")
print("By swapping after a goat is eliminated," +
" the correct door is picked:")
print(scoreboard[1], " times out of 100.")
def main():
scoreboard = test_samples1()
scoreboard = test_samples2(scoreboard)
output_results(scoreboard)
main()
|
b080ccfcb5b7365337766af7d64bf1cd1182ce5b | dmitryokh/python | /ДЗ-5. Функции и рекурсия/X. Только квадраты.py | 364 | 3.6875 | 4 | from math import sqrt
count = 0
def backsq(a):
if int(a) != 0:
a = int(input())
backsq(a)
if sqrt(a) == int(sqrt(a)) and a != 0:
count += 1
print(a, " ", sep="", end="")
a1 = int(input())
a = a1
backsq(a)
if sqrt(a1) == int(sqrt(a1)):
print(a1)
count += 1
print(count)
if count == 0:
print(count)
|
e7cd674d1044aa3f6e994731d5de37cc3850df47 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/510.py | 297 | 3.578125 | 4 | def word_count(prompt):
wordArray = prompt.split()
wordCount = {}
for word in wordArray:
currentValue = 0
try:
currentValue = wordCount[word]
except:
pass
wordCount.update({word: currentValue + 1})
return wordCount
|
9c6b04513e8ac673ef1365bd3d8de1ccba8d5716 | Em3raud3/leetcode | /932_beautiful_array.py | 850 | 3.578125 | 4 | class Solution:
def beautifulArray(self, n: int) -> List[int]:
permutation = list()
i = 0
while len(permutation) != n:
if i == 0:
permutation = [1]
else:
for num in range(len(permutation)):
if num == 0:
odd = list()
even = list()
odd_num = (2*permutation[num]) - 1
even_num = (2*permutation[num])
if odd_num <= n:
odd.append(odd_num)
if even_num <= n:
even.append(even_num)
if num == len(permutation) - 1:
permutation = odd + even # ! need a better way to do this part
i += 1
return(permutation)
|
20e2c57db181e2d637e5b671446543abc7215cae | inyong37/Study | /V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 3.py | 500 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Modified Author: Inyong Hwang (inyong1020@gmail.com)
# Date: *-*-*-*
# 모두의 알고리즘 with 파이썬
# Chapter 3. 동명이인 찾기 1
def find_same_name(a):
n = len(a)
result = set()
for i in range(0, n - 1):
for j in range(i + 1, n):
if a[i] == a[j]:
result.add(a[i])
return result
name = ['Tom', 'Jerry', 'Mike', 'Tom']
print(find_same_name(name))
name2 = ['Tom', 'Jerry', 'Mike', 'Tom', 'Mike']
print(find_same_name(name2))
|
b3856816dff7100af669490f1c3c48a4a6b7c9b1 | dstch/my_leetcode | /Depth-first Search/Max Area of Island.py | 1,725 | 4 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: dstch
@license: (C) Copyright 2013-2019, Regulus Tech.
@contact: dstch@163.com
@file: Max Area of Island.py
@time: 2019/9/19 17:16
@desc: Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
"""
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
self.nextstep = [[0, 1], [1, 0], [0, -1], [-1, 0]]
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
self.step = 0
self.dfs(grid, i, j)
res = max(res, self.step)
return res
def dfs(self, grid, x, y):
if x < 0 or y < 0 or x > len(grid) - 1 or y > len(grid[0]) - 1 or grid[x][y] != 1:
return
grid[x][y] = -1
self.step += 1
for i in range(len(self.nextstep)):
self.dfs(grid, x + self.nextstep[i][0], y + self.nextstep[i][1])
|
199b9af6aa153ac7438af45e31ad3c9aca05c19f | AliciaVilchez/t06_Vilchez_Orlandini | /chambergo/Simple2.py | 318 | 3.515625 | 4 | #Programa 02
import os
usuario,cant_de_horas_por_dia="",0
#INPUT VIA OS
usuario=os.sys.argv[1]
cant_de_horas_por_dia=int(os.sys.argv[2])
#PROCESSING
#Si el numero de horas supera 12, mostrar "adiccion a las redes sociales"
if(cant_de_horas_por_dia > 12 ):
print(usuario, "adiccion a las redes sociales")
#fin_if
|
c7c24292fc473079cf9065adeacabed3b27efbe1 | nic0mp/rangers75_prework | /python-prework/test2.py | 2,124 | 4.15625 | 4 | # def hello_name(user_name):
# print("hello " + user_name + "!")
# hello_name("Chunks")
#Question 2
# Print first 100 odd numbers between 1 and 100 in Python.
# odd_numbers = list(range(1,100,2))
# print(odd_numbers) MY ANSWER
#print all odd numbers bet 1 and 100
# def add100():
# print([value for value in range(1, 100, 2)])
# add100()
#Print first 100 odd numbers
# def first_100():
# numbers = list(range(0,201))
# for number in numbers:
# if number % 2 != 0:
# print(number)
# first_100()
#Question 3
# Please write a Python function, max_num_in_list to return the max number of a given list.
# def max_num_in_list(a_list):
# print(max(a_list))
# max_num_in_list([1, 2, -5, -7, 9, -12])
# def max_num(a_list):
# max_value = max(a_list)
# return max_value
# print(max_num([2,3,5,8,7]))
# test = max_num([2,3,5,8,7])
#Question 4
# Write a function to return if the given year is a leap year. A leap year is divisible by 4,
# but not divisible by 100, unless it is also divisible by 400.
# The return should be boolean Type (true/false).
# def is_leap_year(year):
# if (((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)):
# print("True")
# else:
# print("False")
# is_leap_year(2004)
# def is_leap_year(a_year):
# if a_year % 4 == 0 and (a_year % 400 == 0 or a_year % 100 != 0):
# print(True)
# else:
# print(False)
# is_leap_year(2022)
#Question 5
# Write a function to check to see if all numbers in list are consecutive numbers.
# For example, [2,3,4,5,6,7] are consecutive numbers, but [1,2,4,5] are not consecutive numbers.
# The return should be boolean Type.
# def is_consecutive(a_list):
# return sorted(a_list) == list(range(min(a_list),max(a_list)+1))
# print(is_consecutive([1,2,3,5,6,]))
def is_consecutive(a_list):
i =0
status = True
while i < len(a_list) - 1:
if a_list[i] + 1 == a_list[i+1]:
i+=1
else:
status = False
break
print(status)
is_consecutive([1,2,3,5,6,])
is_consecutive([1,5,3,2])
|
95f4dd028dd850790f618864393fbe45b880bad0 | AbdulMohamed1994/temperature-converter | /main.py | 2,013 | 3.609375 | 4 | from tkinter import *
import tkinter as tk
#defin formular
def convert_C():
if E1:
fahrenheit = float(E1.get())
celcius = (fahrenheit-32)*5/9
result_entry.insert(0, celcius)
def convert_F():
if E2:
celcius = float(E2.get())
fahrenheit = (celcius*9/5)+32
result_entry.insert(0, fahrenheit)
#window
win = Tk()
#Labelfram and entry 1
l1=LabelFrame(win,text='Celcius To Fahrenheit',padx=40, pady=40, bg='light blue')
l1.pack(fill="both")
l1.place(x=30, y=50)
E1=Entry(l1,state='disable')
E1.pack()
def Cel_Active():
E1.configure(state='normal')
if E2 == normal:
E1.configure(state='disable')
#Button C - F
b1=Button(win,text='Activate -Celcius to Fahrenheit', command=Cel_Active, bg='light blue')
b1.place(x=30, y=250)
#label frame and entry 2
l2=LabelFrame(win, text='Fahrenheit to Celcius',padx=40, pady=40, bg='light pink')
l2.pack(fill="both")
l2.place(x=310, y=50)
E2=Entry(l2,state='disable')
E2.pack()
#defin btn
def Far_Active():
E2.configure(state='normal')
if E1 == normal:
E2.configure(state='disable')
#Button 2 F -C
b2=Button(win,text='Activate -Fahrenheit to Celcius', command=Far_Active, bg='light pink')
b2.place(x=330, y=250)
#Exit Button
def exit():
win.destroy()
exit_btn = Button(win,text = "Quit", command=exit, bg='white')
exit_btn.place(x=500, y=430)
#result button C - F
result_bnt=Button(win, text='Calculate C - F',command=convert_C, bg='light blue')
result_bnt.place(x=30, y=330)
#result button F - C
result_bnt=Button(win, text='Calculate F - C',command=convert_F, bg='light pink')
result_bnt.place(x=435, y=330)
#result entry
result_entry=Entry(win, bg='white')
result_entry.place(x=220, y=330)
#Clear button
def Clear():
E1.delete(0, END)
E2.delete(0, END)
result_entry.delete(0,END)
Clear_btn=Button(win, text='Clear',command=Clear, bg='white')
Clear_btn.place(x=495, y=380)
win.title('Temperature Convector')
win.geometry('600x500')
win.mainloop()
|
fa8dd2018d7a7bf519244d1a3fe121d558c1e462 | dartmouth-pbs/psyc161-hw-factorial | /factorial.py | 706 | 3.671875 | 4 | #!/usr/bin/env python
"""Module for estimation of factorial (Homework #1)
Note: this is just a skeleton for you to work with. But it already
has some "bugs" you need to catch and fix.
"""
def factorial(n):
# TODO Define your logic for factorial here
return # TODO!
def test_factorial():
assert factorial(1) == 1
# TODO: add more
if __name__ == '__main__':
# This is a way to determine either file was "executed", so if it was
# imported (by e.g. pytest) as a library, we should not run code
# below
nconditions = raw_input("Please enter number of conditions: ")
norders = factorial(nconditions)
print("Number of possible trial orders: " + str(norders)
|
7839dff1009ecac3a6053ec5cf2363dd83d4343f | Saquib472/Innomatics-Tasks | /Task 3(Python Maths)/04_Power_MODPower.py | 364 | 4.03125 | 4 | # Task_3 Q_4:
# You are given three integers: a, b, and m. Print two lines.
# On the first line, print the result of pow(a,b). On the second line, print the result of pow(a,b,m).
# Input Format
# The first line contains , the second line contains , and the third line contains .
a = int(input())
b = int(input())
m = int(input())
print(pow(a,b))
print(pow(a,b,m)) |
42b70291ce8192abae69d711feee3ecb2524bca7 | edmanolusanya/second-trial | /numberGame.py | 320 | 3.84375 | 4 |
def MyNumber():
count = 0
for i in range(0,100):
count += 1
print(count)
if(i % 3 == 0):
print("fizz")
elif(i % 5 == 0):
print("buzz")
elif(i % 3 == 0 and i % 5 == 0):
print("fizzbuzz")
MyNumber()
|
cba5f1216a756b1c00a8a6a99206968ed4901846 | JyotshnaReddyE/PythonAssignments | /Task 1/Question1.py | 205 | 4.0625 | 4 | #1. Create three variables in a single line and assign values to them in such a manner that each one of them belongs to a different data type.
a , b , c = 1, 2.01, "string"
print(a)
print(b)
print(c) |
8c164a41219dd43790f85017d34e9f8f5f5b7c3e | Aaryan-R-S/Python-Tutorials | /Tutorials/18break&cont.py | 320 | 3.84375 | 4 | i = 0
# Forever loop
while (True) :
if (i<=10) :
i = i+1
continue #don't leave the loop & don't read the code written in loop (after this)
print(i, end=' ')
i = i+1
if (i==45) :
break #leave the loop without reading code written in loop (after this)
print(i)
print('Stopped!') |
e30641e2500efdb928f97f57e9028efd0229eb17 | Aasthaengg/IBMdataset | /Python_codes/p03502/s794608193.py | 108 | 3.515625 | 4 | a=input()
b=int(a)
s=0
for i in range(len(a)):
s=s+int(a[i])
if b%s==0:
print("Yes")
else:
print("No") |
4b5cec40981bc80ec799091cbb87f18eb54dac43 | nathanwbrei/SquareTubeTangle | /lsys.py | 2,001 | 3.9375 | 4 | from random import random
class LSystem(object):
""" Implements a Lindenmeyer System. """
def __init__(self, alphabet, axiom, rules, depth):
"""
alphabet: {'A' : func_a, 'B' : func_b, ...}
A dictionary mapping each symbol to a callback, e.g. for graphics.
axiom: 'AB...'
The initial string
rules: {'A' : 'AB', ... [deterministic]
'B' : [(0.5, 'AB'), (0.3, 'AAB')], ...} [nondeterministic]
Maps each symbol character to its replacement string. If not
deterministic, maps each symbol to a list of tuples of the form
(probability, replacementstring). Rule types can be mixed.
depth:
The initial number of iterations to be computed
"""
self.alphabet = alphabet
self.state = axiom
self.rules = rules
for i in range(depth):
self.generate()
def generate(self):
""" Apply one iteration of production rules to the current state. """
def rand(l):
""" Randomly choose a tuple (prob, val) from l; return val. """
x = random(); total = 0
for p,v in l:
total += p
if x<total:
return v
return v
def transform(a):
""" Returns the correct replacement string for the given symbol. """
if a not in self.rules:
return a
elif isinstance(self.rules[a], list): # BAD
return rand(self.rules[a])
else:
return self.rules[a]
self.state = ''.join([transform(a) for a in self.state])
def show(self):
""" Draws the L-system to screen, using the callbacks associated
with each symbol in alphabet.
"""
for a in self.state:
if a in self.alphabet:
self.alphabet[a]()
|
3e76148525270936f8e00c4bc6882c8cbc428bc1 | lj72808up/ML_Handcraft | /preproccess/HandleDatasets.py | 4,191 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
def getDataset():
data = pd.read_csv("../../datasets/census.csv")
#print(data.shape)
# 将数据切分成特征和对应的标签
# income 列是我们需要的标签,记录一个人的年收入是否高于50K。 因此我们应该把他从数据中剥离出来,单独存放。
income_raw = data['income']
features_raw = data.drop('income',axis=1)
# 对于高度倾斜分布的特征如'capital-gain'和'capital-loss',常见的做法是对数据施加一个对数转换,
# 将数据转换成对数,这样非常大和非常小的值不会对学习算法产生负面的影响。并且使用对数变换显著降低了由于异常值所造成的数据范围异常。
# 但是在应用这个变换时必须小心:因为0的对数是没有定义的,所以我们必须先将数据处理成一个比0稍微大一点的数以成功完成对数转换。
skewed = ['capital-gain','capital-loss']
features_raw[skewed] = data[skewed].apply(lambda x:np.log(x+1)) # numpy操作dataframe
# 规一化数字特征 : 让每个特征转变为(x-min)/(max-min) 0~1
# 除了对于高度倾斜的特征施加转换,对数值特征施加一些形式的缩放通常会是一个好的习惯。在数据上面施加一个缩放并不会改变数据分布的形式
# (比如上面说的'capital-gain' or 'capital-loss');但是,规一化保证了每一个特征在使用监督学习器的时候能够被平等的对待。
# 注意一旦使用了缩放,观察数据的原始形式不再具有它本来的意义了,就像下面的例子展示的。
# 运行下面的代码单元来规一化每一个数字特征。我们将使用sklearn.preprocessing.MinMaxScaler来完成这个任务。
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
numerical = ['age','education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_raw[numerical] = scaler.fit_transform(data[numerical])
# 独热编码 : 很多回归分类模型, 是基于欧氏距离来进行的, 而有些数据的feature, 是文字进行分类而不是数字类型.
# eg : 某个feature成绩的值为{优,良,中}. 这三个文字分类在转换成数字时, 不能简单地变成{1,2,3}, 否则'优'和'中'的欧氏距离变成根号2,
# 大于'优'和'良'欧氏距离1, 而分类feature的分类值应该相似度一致(欧式距离一致), 因此, 需要进行独热编码, 把一个feature拆成3个feature.
# 把优,良,中 提升成feature, 取消成绩feature. 原来成绩为优的, 现在的"优"feature变成1 . (此时优,良,中三个点变成(1,0,0),(0,1,0),(0,0,1)), 欧式距离都是1
# TODO:使用pandas.get_dummies()对'features_raw'数据进行独热编码
features = pd.get_dummies(features_raw)
# TODO:将'income_raw'编码成数字值
income = pd.get_dummies(income_raw).iloc[:,1:] # 只取收入大于50k作为输出字段
#print("income: %s"%income)
# 打印经过独热编码之后的特征数量
encoded = list(features.columns)
print "{} total features after one-hot encoding.".format(len(encoded))
# 混洗和切分数据
# 现在所有的 类别变量 已被转换成数值特征,而且所有的数值特征已被规一化。和我们一般情况下做的一样,我们现在将数据(包括特征和它们的标签)切分成训练和测试集。
# 其中80%的数据将用于训练和20%的数据用于测试。然后再进一步把训练数据分为训练集和验证集,用来选择和优化模型。
# 导入 train_test_split
from sklearn.model_selection import train_test_split
# 将'features'和'income'数据切分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, income, test_size = 0.2, random_state = 0,stratify = income)
# 将'X_train'和'y_train'进一步切分为训练集和验证集
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=0,stratify = y_train)
return X_train, X_val, X_test, y_train, y_val, y_test |
d205f3ed1c61da5be38703fb348a5c3827f45049 | thecodingsophist/algorithms | /calc_fib.py | 1,110 | 3.953125 | 4 | # Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def calc_fib_matrices(n):
# this method uses matrix exponentiation, where a is the matrix
# [[1,1], [1,0]] and n is the nth fibonacci number
fib = [[1,1],
[1,0]]
mul = [[1,1],
[1,0]]
fib_list = [0, 1]
if n == 0:
return "Enter a number greater than 0"
elif n == 1:
return [0]
elif n == 2:
return fib_list
for i in range(n-2):
a = fib[0][0] * mul[0][0] + fib[0][1] * mul[1][0]
#
b = fib[0][0] * mul[0][1] + fib[0][1] * mul[1][1]
#
c = fib[1][0] * mul[0][0] + fib[1][1] * mul[1][0]
#
d = fib[1][0] * mul[0][1] + fib[1][1] * mul[1][1]
mul[0][0] = a
mul[0][1] = b
mul[1][0] = c
mul[1][1] = d
print("mul = [[" + str(mul[0][0]) + "," + str(mul[0][1]) + "], [" + str(mul[1][0]) + "," + str(mul[1][1]) + "]]")
fib_list.append(mul[0][1])
return fib_list
n = int(input())
print(calc_fib_matrices(n))
|
f55ac58271fc05faa9eefcc3daefe77a8d0f011c | dal07065/CS10 | /Final Review/cards (dictionary).py | 2,228 | 3.75 | 4 | import random
deck = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
def create_deck()->dict:
#dictionary = {'Ace of Spades':1, '2 of Spades':2, '3 of Spades':3
global deck
cards = {}
for deckType in deck:
for i in range(1, 14):
if i == 1:
string = "Ace" + " of " + deckType
cards[string] = i
elif i == 11:
string = "Jack" + " of " + deckType
cards[string] = 10
elif i == 12:
string = "Queen" + " of " + deckType
cards[string] = 10
elif i == 13:
string = "King" + " of " + deckType
cards[string] = 10
else:
string = str(i) + " of " + deckType
cards[string] = i
for card in cards:
print(card, ":", cards[card], sep='')
if card.find("King") == 0:
print()
return cards
# **without using a dictionary**
##def deal_cards(numCards:int, cards:dict)->None:
## global deck
## for num in range(numCards):
## deckType = random.randint(0,4)
## cardValue = random.randint(1, 13)
## if cardValue == 1:
## string = "Ace" + " of " + deck[deckType]
## elif cardValue == 11:
## string = "Jack" + " of " + deck[deckType]
## elif cardValue == 12:
## string = "Queen" + " of " + deck[deckType]
## elif cardValue == 13:
## string = "King" + " of " + deck[deckType]
## else:
## string = str(cardValue) + " of " + deck[deckType]
## **using a dictionary**
def deal_cards(numCards:int, cards:dict)->None:
global deck
totalValue = 0
for num in range(numCards):
card = random.choice(list(cards.keys()))
value = cards.pop(card)
print(card)
totalValue += value
print("Total Value:", totalValue)
def main():
cards = create_deck()
rounds = int(input("How many rounds to deal cards? "))
print()
for num in range(rounds):
howManyCards = int(input("How many cards should I deal? "))
deal_cards(howManyCards, cards)
print()
if __name__ == "__main__":
main()
|
dfdc47ad4235b712f3651100345ffe55ae47bd17 | funofzl/MyArgParse | /zipexplore.py | 2,810 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
import argparse
import string
import threading
import zipfile
import os
#读取参数
parser = argparse.ArgumentParser(description='Here is the help!')
parser.add_argument('-i','--input',required=True, type=argparse.FileType('r'),dest='input_file', help='the zip-file you \'d like to explore')
parser.add_argument('-o','--output',type=argparse.FileType('w'),dest='output_file')
parser.add_argument('-l', '--length', type=int, choices=range(10))
parser.add_argument('-m', '--max_length', type=int, choices=range(10))
args = parser.parse_args()
# print('exists: ',os.path.exists(args.input_file.name))
# exit(0)
def check_file():
global args
if args.input_file:
zipfile_name = args.input_file.name
# 判断文件是否合法
if os.path.exists(zipfile_name) and zipfile_name[-4:] == '.zip':
try:
zFile = zipfile.ZipFile(zipfile_name)
return zFile
except:
exit(0)
else:
print('please input the correct filename of type zip')
print(parser.format_usage())
exit(0)
else:
print(parser.format_help())
#默认最大为10位
max_length = 10
if args.length:
max_length = args.length
length_exist = True
else:
length_exist = False
if args.max_length:
max_length = args.max_length
length = 1 #默认从length = 1开始
print(max_length, length)
#提供爆破基
keys = string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation
def explore(zFile, passwd):
print(passwd)
try:
print('begin..')
zFile.extractall(pwd=passwd)
print('[*] Found password %s' % passwd)
return True
except:
return False
def loop_for(base_str, zFile):
global length
global max_length
for i in keys:
password = (base_str + i)
print('password',password)
if length_exist:
print(length)
if length == max_length:
if explore(zFile, bytes(password,encoding='utf-8')): #可用多线程
return True
else:
length += 1
loop_for(password, zFile)
else:
print('no here')
if explore(zFile, password):
return True
if length < max_length:
length += 1
loop_for(password, zFile)
length -= 1
return False
def main(zFile):
# if length == 1:
# for i in keys:
# if explore(zFile, i):
# return True
# else:
loop_for('', zFile)
# if __name__ == "__main__":
#
zFile = check_file()
# zFile.extractall(pwd=b'12345')
# print(zFile.namelist())
main(zFile)
|
ea717157f309433f8fc9ba9c50b15d96cb32a352 | 106070020/hw4 | /hw04-functions-106070020-master/hw4_gcd.py | 286 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def compute_gcd(a,b):
while(b!=0):
c=a%b
a=b
b=c
return a
while True:
break
a = int(input("輸入第一個數字: "))
b = int(input("輸入第二個數字: "))
print(a, '和', b, '的最大公因數是', compute_gcd(a, b))
|
c5d635c16ce931e18d0078c62176044aba701f05 | zenovy/nand2tetris-vm | /VMTypes.py | 859 | 3.546875 | 4 | from enum import Enum
class CommandType(Enum):
ADD = "add"
SUB = "sub"
NEG = "neg"
EQ = "eq"
GT = "gt"
LT = "lt"
AND = "and"
OR = "or"
NOT = "not"
PUSH = "push"
POP = "pop"
LABEL = "label"
GOTO = "goto"
IF_GOTO = "if-goto"
FUNCTION = "function"
RETURN = "return"
CALL = "call"
def is_arithmetic(self):
return self in (self.ADD, self.SUB, self.NEG, self.EQ, self.GT, self.LT, self.AND, self.OR, self.NOT)
class Segment(Enum):
static = None
constant = 0
pointer = 3
temp = 5
local = "LCL"
argument = "ARG"
this = "THIS"
that = "THAT"
def is_symbol(self):
return self == self.local or self == self.argument or self == self.this or self == self.that
def is_number(self):
return self == self.pointer or self == self.temp
|
ef5dfa8df1e62089c3110a90f218f488ca1f013a | lemeryb/yahtzee | /Yahtzee.py | 3,095 | 4.34375 | 4 | # Sam and Ben
# Yahtzee
import random as rand
# Sets a variable which tells the user how many times they've tried to roll the dice for the section they've decided to persue. (Ex: They rolled it once, they rolled it twice, now three times)
attempts = 0
# Sets a variable which is used for the program to discern how many sections are available for the user to go through.(Ex: Chance, three of a kind, four of a kind,etc.) This just tells us how many sections there will be.
choices = 3
# Declares a list which will be used to determine if the user has already completed this section in the past. (Ex: If the user already has their ones filled out they should not be able to fill it out again.)
selected = [""]
# Creates a list that is as big as how many sections that are available for the user to go through Ex: Chance, three of a kind, four of a kind,etc.)
for i in range(choices):
selected.append("")
def add_scores(ones, twos, threes, fours, fives, sixes, yahtzee, chance):
total = ones + twos + threes + fours + fives + sixes + yahtzee + chance
return (total)
def welcome():
# start_game = int(input("Hello do you want to play yahtzee? (Press 1 to play or 2 to exit): "))
start_game = 1
if start_game == 1:
print("Beginning a game of Yahtzee..")
roll = [0, 0, 0, 0, 0]
play_game(roll)
else:
print("Exiting the game..")
exit()
# Runs through a for loop and appends a random integer to each element in the list so that we know which values the user rolled.
def roll_dice(roll):
for i in range(len(roll)):
roll[i] = rand.randint(1, 6)
print("You rolled " + str(roll))
# Deals with each roll attempt to get better values in each section.
def rolls_for_turn(roll):
global attempts
# Asks the user if they are happy with their score. If not, they are free to roll again.
final_score = int(input(
"Would you like to use all of the numbers you rolled for your turn?\nPress 1 to end the turn:\nPress 2 to reroll the dice: "))
if final_score == 1:
pass
# If the user chose to reroll make sure the user knows that they are using an additional attempt and reroll the dice. Rinse and repeat until attempt 3.
elif final_score == 2:
attempts +=1
print("Attempt: " + str(attempts)); roll_dice(roll)
return()
def play_game(roll):
global attempts
attempts += 1
print("Attempt: " + str(attempts))
roll_dice(roll)
section_to_go_for = int(input("""Press 1 to go for your ones
Press 2 to go for your twos
Press 3 to go for your threes"""))
# Verifies that the user hasn't already previously chosen the same selection to go for.
if selected[section_to_go_for] == -1:
print("You already have a score for this section! Please select another option.")
play_game(roll)
elif selected[section_to_go_for] != -1:
choice = selected[section_to_go_for]
selected[section_to_go_for] = -1
while attempts < 3:
rolls_for_turn(roll,choice)
welcome()
def user_spreadsheet():
pass
|
73e41a5e5ed370ef26ee2e3c6249db68c1d78dd3 | rubens17rodrigues/alien_invasion | /ship.py | 2,118 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Classe para armazenar as informações da nave"""
def __init__(self, ai_settings, screen):
"""Inicializa a espaçonave e define sua posição inicial."""
super(Ship, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
# Carrega a imagem da espaçonave e obtém seu rect
self.image = pygame.image.load('images/spaceship.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Inicia cada nova espaçonave na parte inferior central da tela
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#Armazena um valor decimal pra o centro da nave
self.centerx = float(self.rect.centerx)
self.centery = float(self.rect.centery)
# Flag de movimento
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
def update(self):
"""Atualiza a posição da nave de acordo com a flag de movimento."""
if self.moving_right and self.rect.right < self.screen_rect.right:
self.centerx += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.centerx -= self.ai_settings.ship_speed_factor
if self.moving_up and self.rect.top > 0:
self.centery -= self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.centery += self.ai_settings.ship_speed_factor
# Atualiza o objeto rect de acordo com self.center
self.rect.centerx = self.centerx
self.rect.centery = self.centery
def blitme(self):
"""Desenha sua espaçonave em sua posição atual."""
self.screen.blit(self.image, self.rect)
def center_ship(self):
"""Centraliza a nava na tela."""
self.centerx = self.screen_rect.centerx
self.centery = self.screen_rect.bottom - (0.5 * self.rect.height)
|
666e3f2ad8f8601e658f4aadb51bc038815c6696 | TimeMachine00/practicePy | /ghijp1/array asking user, search and give index.py | 319 | 3.84375 | 4 | from array import *
vals=array('i',[])
n = int(input('enter the length of a array'))
for i in range(n):
x=int(input('enter next value'))
vals.append(x)
print(vals)
search=int(input('enter val for search'))
k=0
for e in vals:
if e==search:
print(k)
break
k+=1
print(vals.index(search)) |
976dc59932f7f10fa7e4ef2ce65302fd6e11583e | saikiranmadimi/ctci | /icake/reverse_string_in_place.py | 327 | 3.890625 | 4 | def reverse_string(s):
s = list(s)
s = s[::-1]
s = ''.join(s)
return s
# print reverse_string('hello')
# T: O(n), S: O(1)
def reverse_string(s):
s = list(s)
# left pointer
l = 0
# right pointer
r = len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return ''.join(s)
print reverse_string('hello')
|
1020f200857aef084ffd366a0f5d40ba9a065ceb | Rushi21-kesh/30DayOfPython | /Day-4/Day_4_Adnan_Samol.py | 267 | 3.984375 | 4 | # Day-4
stars = int(input("Enter the row to display:"))
def draw(stars):
starCount = 0
for i in range(0, stars+1):
for j in range(0, i):
print("*", end='')
starCount += 1
print("")
print(starCount)
draw(stars)
|
a28241c4d7c7e9530980ee1b404393e341568c9c | OnlyBelter/machine-learning-note | /probability_basic/LLN_and_CLT/LLN.py | 1,200 | 3.71875 | 4 | import random
import matplotlib.pyplot as plt
def flip_plot(min_exp, max_exp):
"""
Assumes min_exp and min_exp positive integers; min_exp < max_exp
Plots results of 2**min_exp to 2**max_exp coin flips
抛硬币的次数为2的min_exp次方到2的max_exp次方
一共进行了 2**max_exp - 2**min_exp 轮实验,每轮实验抛硬币次数逐渐增加
"""
ratios = []
x_axis = []
for exp in range(min_exp, max_exp + 1):
x_axis.append(2**exp)
for numFlips in x_axis:
num_heads = 0 # 初始化,硬币正面朝上的计数为0
for n in range(numFlips):
if random.random() < 0.5: # random.random()从[0, 1)随机的取出一个数
num_heads += 1 # 当随机取出的数小于0.5时,正面朝上的计数加1
num_tails = numFlips - num_heads # 得到本次试验中反面朝上的次数
ratios.append(num_heads/float(num_tails)) # 正反面计数的比值
plt.title('Heads/Tails Ratios')
plt.xlabel('Number of Flips')
plt.ylabel('Heads/Tails')
plt.plot(x_axis, ratios)
plt.hlines(1, 0, x_axis[-1], linestyles='dashed', colors='r')
plt.show()
flip_plot(4, 16)
|
45d57a91c5fa6e28bfb448d19658cf520a3e2409 | YashVardhan-Programmer/Characters-and-Words-Counter | /countwords.py | 311 | 4.0625 | 4 | sentence = input("Enter The Sentence: ")
characterCount = 0
wordsCount = 1
for i in sentence:
characterCount = characterCount+1
if i == ' ':
wordsCount = wordsCount+1
print("No. of words in the sentence are:", wordsCount)
print("No. of characters in the sentence are:", characterCount) |
51c8f7090aaa990c0d30d1516c1c0db8cccd0cf2 | AnastasiaTomson/english_learning | /learn_english.py | 3,203 | 3.78125 | 4 | import fileinput
import random
import os
import shutil
def cls():
os.system('clear')
def read_file():
input_file = open('not_learning.txt', 'r+', encoding='utf-8-sig')
return input_file.readlines()
def write_file(file_name):
input_file = open(file_name, 'w+', encoding='utf-8-sig')
return input_file
def answer(learn_now):
print('Готовы проверить свои знания?\nЕсли готовы, нажмите Enter')
true = 0
n = read_file()
learning = write_file('learning.txt')
if input() == '':
cls()
for key, val in sorted(learn_now.items(), key=lambda x: random.random()):
print('Переведите: {}'.format(val))
count = 0
word = ''
while word != key:
word = str(input()).lower()
print('Ответ: {}'.format(word))
if word == key:
true += 1
print('ВЕРНО!)')
learning.write('{}-{}\n'.format(key, val))
for row in n:
if row == '{}-{}\n'.format(word, val):
row.replace(row, '')
else:
count += 1
print('Не верно. Попробуйте еще раз!')
if count >= 5:
print('Показать ответ? Если да, нажмите Enter.')
if input() == '':
print('Ответ: {}'.format(key))
word = key
input_file = open('not_learning.txt', 'a', encoding='utf-8-sig')
input_file.write('{}-{}\n'.format(key, val))
else:
print('Переведите: {}'.format(val))
return true
def show_words(words):
learn_now = dict()
input_file = open('not_learning.txt', 'w', encoding='utf-8-sig')
for i, (key, val) in enumerate(sorted(words.items(), key=lambda x: random.random())):
if i >= 10:
input_file.write('{}-{}\n'.format(key, val))
else:
print(key + ': ' + val)
learn_now[key] = val
words.pop(key)
input_file.close()
return answer(learn_now)
def main():
while True:
print('Если Вы хотите продолжить обучение нажмите +\nЕсли Вы хотите начать заново нажмите -')
a = str(input())
if a == '-':
shutil.copyfile('base_english.txt', 'not_learning.txt')
elif a == '+':
pass
else:
break
en = read_file()
en_word = {}
while len(en) != 2:
row_list = en[0].split('-')
en_word[row_list[0].replace('\n', '').lower()] = row_list[1].replace('\n', '').lower()
en.remove(en[0])
true = show_words(en_word)
print('Введено правильно: {}\nВведено не правильно: {}'.format(true, 10-true))
print('Статистика: {} из {}'.format(true, 10))
if __name__ == '__main__':
main()
|
f7cf0e4674be6f769949100c1d5cee0317eb9315 | theothershore2019/basic_01_python_basic | /hm_06_个人信息.py | 335 | 3.765625 | 4 | """
姓名:小明
年龄:18 岁
性别:是男生
身高:1.75 米
体重:75.0 公斤
"""
# 在 Python 中定义变量是不需要指定变量的类型的
# Python 可以根据 = 等号右侧的值,自动推导出变量中存储数据的类型
name = "小明"
age = 18
gender = True
height = 1.75
weight = 75.0
print(name)
|
bef2d7698838d49f6318b91d6c29cfb320107e2a | poojavarshneya/algorithms | /level_order_traversal.py | 2,164 | 3.984375 | 4 | from collections import defaultdict
from queue import Queue
class LinkedNode:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.root = None
def insertNode(self, val):
node = LinkedNode(val)
if self.root is None:
self.root = node
return
root = self.root
while root.next:
root = root.next
root.next = node
def print(self):
root = self.root
while (root):
print(root.data, end = " ")
root = root.next
print(end = "\n")
class Node:
def __init__(self,data):
self.val = data
self.left = None
self.right = None
def levelOrderTraversalWithLists(root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
#result = defaultdict(list)
result = []
if not root:
return result
nodes = [root]
while nodes:
vals, nodes_next = [],[]
for node in nodes:
vals.append(node.val)
if (node.left):
nodes_next.append(node.left)
if (node.right):
nodes_next.append(node.right)
nodes = nodes_next
result.append(vals)
return result
def levelOrderTraversalWithLinkedLists(root):
result = []
if root is None:
return result
nodes = [root]
while nodes:
ll_result = LinkedList()
node_next = []
for node in nodes:
ll_result.insertNode(node.val)
if node.left:
node_next.append(node.left)
if node.right:
node_next.append(node.right)
nodes = node_next
result.append(ll_result)
return result
def test1():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
result = levelOrderTraversalWithLists(root)
print(result)
result = levelOrderTraversalWithLinkedLists(root)
for ll in result:
ll.print()
test1()
|
a681e1ce9bc4b282318eaf5d3b7fdd1af3d08c83 | totoma3/Baekjoon-Algorithm | /2562번.py | 479 | 3.734375 | 4 | #9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
#예를 들어, 서로 다른 9개의 자연수
#3, 29, 38, 12, 57, 74, 40, 85, 61
#이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.
num_list=[]
for i in range(0,9):
a=int(input())
num_list.append(a)
max_num = max(num_list)
print(max_num)
print(num_list.index(max_num)+1)
|
06826cedc33c52d0fb5e19b68debc0c475e0d9b2 | roca77/Coding | /ai_tictactoe.py | 5,568 | 4.15625 | 4 | import copy
import random
# Setting a board with an empty list of list
board = [
['','',''],
['','',''],
['','','']
]
# A function to display the board
def displayboard(board):
print(board[0][0] + " | " + board[0][1] + " | " + board[0][2])
print(board[1][0] + " | " + board[1][1] + " | " + board[1][2])
print(board[2][0] + " | " + board[2][1] + " | " + board[2][2])
# A function to take input from user, validate entry, and prompt for a new choice
def taking_input(board, player_letter):
try:
position = int(input("Maichata, Please enter a number between 1-9: "))
position = position - 1
selection = (position // 3, position % 3)
if (8 >= position) and (position >= 0) and (board[selection[0]][selection[1]] == ''):
board[selection[0]][selection[1]] = player_letter
return
else:
print("Try another position; this is already used!")
except ValueError:
print("You can only pick numbers between 1-9. Try again!")
# AI function that allows Computer to make moves
def computer_move(board, computer_letter, human_player_letter):
open_positions = openposition(board)
temporary_board = copy.deepcopy(board)
middle_position = board[1][1]
#random_position = random.choice(open_positions)
for position in open_positions:
move_to_position(temporary_board, computer_letter, position)
if is_winner(temporary_board, computer_letter)==True:
move_to_position(board, computer_letter, position)
displayboard(board)
break
else:
temporary_board = copy.deepcopy(board)
# Blocking move
move_to_position(temporary_board, human_player_letter, position)
if is_winner(temporary_board, human_player_letter)==True:
move_to_position(board, computer_letter, position)
displayboard(board)
break
elif (1,1) in open_positions:
# Middle position
temporary_board = copy.deepcopy(board)
board[1][1]=computer_letter
displayboard(board)
break
elif position in [(0,0),(0, 2), (2, 0), (2, 2)]:
temporary_board = copy.deepcopy(board)
move_to_position(board, computer_letter, position)
displayboard(board)
break
else:
#board[random_position[0]][random_position[1]]=computer_letter
temporary_board = copy.deepcopy(board)
# A function to find available position
def openposition(board):
openp = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j]=='':
openp.append((i, j))
return(openp)
# A function to move to specific position
def move_to_position(board, letter, position):
board[position[0]][position[1]]= letter
# A function to randomly pick who goes first
def who_goes_first():
if random.randint(0, 1)==0:
return 'human_player'
else:
return 'computer'
# Ask human player to be either X or O
def choose_player_letter():
letter = ''
while (letter not in ['X', 'O']):
letter = input('Do you want to be X or O?\n').upper()
return letter
# a function to tell if there is a tie or if the game should continue
def game_tie(openp):
if len(openp) < 2:
return True
else:
return False
def is_winner(board, current_player):
if board[0][0] == board[0][1] == board[0][2]==current_player or board[1][0]==board[1][1]==board[1][2]==current_player or board[2][0]==board[2][1]==board[2][2]==current_player or board[0][0]==board[1][1]==board[2][2]==current_player or board[0][2]==board[1][1]==board[2][0]==current_player or board[0][0]==board[1][0]==board[2][0]==current_player or board[0][1]==board[1][1]==board[2][1]==current_player or board[0][2]==board[1][2]==board[2][2]==current_player:
return True
else:
return False
def play_game():
while True:
turn = who_goes_first()
print('The ' + turn + ' will go first')
human_player_letter = choose_player_letter()
if human_player_letter == 'X':
computer_letter ='O'
else:
computer_letter = 'X'
game_on = True
while(game_on):
if turn == 'human_player':
taking_input(board, human_player_letter)
displayboard(board)
if is_winner(board, human_player_letter)==True:
print(human_player_letter +" wins this tic tac toe game!")
displayboard(board)
game_on= False
break
elif game_tie(board) == True:
print("This game is a draw between the players. Start a new game.")
game_on= False
else:
turn = 'computer'
elif turn == 'computer':
computer_move(board, computer_letter, human_player_letter)
if is_winner(board, computer_letter)==True:
print(computer_letter + " wins this tic tac toe game!")
game_on= False
break
elif game_tie(board) == True:
print("This game is a draw between the players. Start a new game.")
game_on= False
else:
turn = 'human_player'
play_game() |
bc22f81758f3e28f83384ea956b851af73c761ec | AndreyIvantsov/PythonEx | /ex05.py | 3,063 | 3.9375 | 4 | # -*- coding: utf-8 -*-
my_name = 'Андрей'
my_age = 47 # лет
my_height = 178 # см
my_weight = 76 # кг
my_eyes = 'Карие'
my_teeth = 'Белые'
my_hair = 'Русые'
print('Давайте погворим о человеке по имени %s' %my_name)
print('Его рост составляет %d см.' %my_height)
print('Он весит %d кг.' %my_weight)
print('На самом деле это не так много.')
print('У него глаза %s и волосы %s.' %(my_eyes, my_hair))
print('Его зубы обычно %s, хотя он любит пить кофе.' %my_teeth)
# эта строка довольно сложная, не ошибитесь!
print('Если я сложу %d, %d и %d, то получу %d' %(my_age, my_height, my_weight, my_age + my_height + my_weight))
# --------------------------------------------------------------------------------------------- #
# Формат Что плучится #
# --------------------------------------------------------------------------------------------- #
# '%d', '%i', '%u' Десятичное число #
# '%o' Число в восьмиричной системе счисления #
# '%x' Число в шестнадцатиричной системе счисления (буквы в нижнем регистре) #
# '%X' Число в шестнадцатиричной системе счисления (буквы в верхнем ренистре) #
# '%e' Число с плавающей точкой экспонентой (буквы в нижнем регистре) #
# '%E' Число с плавающей точкой экспонентой (буквы в верхнем регистре) #
# '%f', '%F' Число с плавающей точкой (обычный формат) #
# '%g' Число с плавающей точкой с экспонентой (экспонента в нижнем регистре) #
# '%G' Число с плавающей точкой с экспонентой (экспонента в верхнем регистре) #
# '%c' Символ (строка из одного символа или число - код символа) #
# '%r' Строка (литерал python) #
# '%s' Строка (как обычно воспринимается пользователем) #
# '%%' Знак '%' #
# --------------------------------------------------------------------------------------------- # |
7ebc9ee2e2774d301ee195a83722afc4511e3a1e | mgmorales1/CNN-cats-dogs | /CNN/convolutional.py | 1,060 | 3.953125 | 4 | import numpy as np
class Conv3x3:
# A Convolution layer using 3x3 filters.
def __init__(self, num_filters):
self.num_filters = num_filters
# filters is a 3d array with dimensions (num_filters, 3, 3)
# We divide by 9 to reduce the variance of our initial values
self.filters = np.random.randn(num_filters, 3, 3)/9
def iterate_regions(self, image):
'''
Generates all possible 3x3 image regions using valid padding.
- image is a 2d numpy array
'''
h, w = image.shape
for i in range(h - 2):
for j in range(w - 2):
im_region = image[i: (i+3), j:(j+3)]
yield im_region, i, j
def forward(self, input):
'''
Performs a forward pass of the conv layer using the given input.
Returns a 3d numpy array with dimensions (h, w, num_filters).
- input is a 2d numpy array
'''
h, w = input.shape
output = np.zeros((h - 2, w - 2, self.num_filters))
for im_region, i, j in self.iterate_regions(input):
output[i, j] = np.sum(im_region * self.filters, axis=(1, 2))
return output |
05987044017700b32a9ce4b77f61ed8b3e47f345 | heman577/WebScrapping_python | /age_years.py | 799 | 3.71875 | 4 | #x=input('enter the value in years;')
#y=int(x)
#z=(y*365)
#print(z)
#print('you are ',z,'days old')
#user_response=input('enter the integer value:')
#x=int(user_response)
#y=x*x -12*x+11
#print(y)
#user_response=int(input('enter the integer value:'))
#my_list=['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY']
#print(my_list[user_response])
#sample_list=[2,10,3,5]
#average=(sample_list[0]+sample_list[1]+sample_list[2]+sample_list[3]) /4
#print(average)
#x= 10
#if x > 5 :
# x = x + 5
#if x < 12 :
# x = x + 5
#if x == 15 :
# x = x + 5
# print(x)
my_list = [ 'dog' ,'cat' ,'worm' ,2.3]
if 'doc' in my_list:
my_list[1]= 4
else:
my_list[2]= 6
print (my_list[1]),my_list[2])
|
d8d746cfe0524222536d33a8f62dbedd3e0b3eeb | magdeevd/gb-python | /homework_4/second.py | 828 | 4.09375 | 4 | def main():
"""
2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего
элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Результат: [12, 44, 4, 10, 78, 123].
"""
l = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = [item for index, item in enumerate(l[1:]) if item > l[index]]
print(result)
if __name__ == '__main__':
main()
|
009a764f30abdeae8efd679a634694c213e8b99d | madhavinamballa/de_anza_pythonbootcamp | /loops/solved/while_loop.py | 178 | 4.09375 | 4 | #=======while loop print 1 to 10 numbers
number=1
while number<=10:
print(number)
number=number+1
#========for loop================
for num in range(10):
print(num) |
7602cccd19bbe7481365a449240eb82cccecb4c3 | Alex0Blackwell/python-projects | /space-text-animation.py | 542 | 3.828125 | 4 | # Text animation where a space goes through the string
import time as t
def spaceAnim(phrase):
# Runs in time O(n)
phrase += ' ' # Need an extra iteration to not print the last letter twice
L = len(phrase)
c = 0
while(c < 2): # Do animation 2 times
for i in range(L):
if(i == L-1 or phrase[i] != ' '):
beg = phrase[:i]
end = phrase[i:]
print(beg + ' ' + end, end='\r')
t.sleep(0.1)
c += 1
spaceAnim("Some sample sentence")
|
6aed7a3c453ce140a80d9189b8e59bc739659250 | tayciryahmed/data-structures-and-algorithms | /add-two-numbers.py | 1,067 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = ListNode()
curry = 0
root = ans
while l1 and l2:
_sum = l1.val + l2.val + curry
curry = _sum//10
ans.next = ListNode(_sum %10)
ans = ans.next
l1, l2 = l1.next, l2.next
while l1:
_sum = l1.val + curry
curry = _sum//10
ans.next = ListNode(_sum %10)
ans = ans.next
l1 = l1.next
while l2:
_sum = l2.val + curry
curry = _sum//10
ans.next = ListNode(_sum %10)
ans = ans.next
l2 = l2.next
while curry:
ans.next = ListNode(curry %10)
ans = ans.next
curry = curry//10
return root.next
|
bbf8f813be8f7143bf113f1a13ad6170b374e37b | kimjoshjp/python | /loop_3.py | 169 | 4.125 | 4 | #
#
#
#
answer = []
while len(answer) < 3:
new_name = input("Please add a new name: ").strip().capitalize()
answer.append(new_name)
print("Sorry list is full")
|
ea997879fddb718a7a1ea941b475934721edab75 | IamFive/note | /note/python/recipel.py | 1,313 | 3.6875 | 4 | class RomanNumeralConverter(object):
def __init__(self, roman_numeral):
self.roman_numeral = roman_numeral
self.digit_map = {
"M":1000,
"D":500,
"C":100,
"L":50,
"X":10,
"V":5,
"I":1
}
def convert_to_decimal(self):
val = 0
for char in self.roman_numeral:
val += self.digit_map[char]
return val
import unittest
class RomanNumeralConverterTest(unittest.TestCase):
def setUp(self):
print 'setup'
def tearDown(self):
print 'teardown'
def test_parsing_millenia(self):
value = RomanNumeralConverter("M")
self.assertEquals(1000, value.convert_to_decimal())
def test_no_roman_numeral(self):
value = RomanNumeralConverter(None)
self.assertRaises(TypeError, value.convert_to_decimal)
def test_empty_roman_numeral(self):
value = RomanNumeralConverter("")
self.assertTrue(value.convert_to_decimal() == 0)
self.assertFalse(value.convert_to_decimal() > 0)
if __name__ == "__main__":
unittest.main()
|
81652de510eb2ac59ce5badd2c05ac0591194cf9 | andonyan/Python-Fundamentals | /dictionaries exercise/company users.py | 535 | 3.890625 | 4 | companies = {}
while True:
tokens = input().split(' -> ')
if tokens[0] == 'End':
for key, value in sorted(companies.items(), key=lambda x: x[0]):
print(f'{key}')
for emp in value:
print(f'-- {emp}')
break
else:
company = tokens[0]
employee = tokens[1]
if company not in companies:
companies[company] = [employee]
else:
if employee not in companies[company]:
companies[company].append(employee)
|
ad0069c44ba4ef1d15c0fe5ced9161e5a6cdb97a | AlessandroCanel/Cybersecurity | /Base64.py | 768 | 3.796875 | 4 | # Let's see how this base 64 stuff works
import base64
def based():
with open('InputBase64.txt', 'r') as file:
phase = file.read()
c = input("decode or encode? ")
times = int(input("How many times? "))
while times != 0:
if c == "encode":
phase = base64.b64encode(bytes(phase, "utf-8"))
phase = phase.decode("utf-8")
times -= 1
elif c == "decode":
phase = base64.b64decode(phase)
times -= 1
else:
print("Wrong input")
times -= times
# basically this hot trash of a code simply transforms into binary and then into ascii
if c == "decode":
phase = phase.decode("utf-8")
print(phase, file=open("output.txt", "a"))
|
1ec8425a6da6ca4450aa59f9c032667c1d7f57a6 | jgriffith23/cci-python | /ch3/queue_ll.py | 2,390 | 3.9375 | 4 | """Implements a queue using reqs from Cracking the Coding Interview Ch 3.
Should be O(1) for all operations.
Philosophical question: Should I be returning Nodes when I dequeue, or
should I be returning the data? I'd argue the data, so the interface
btw the two queue types is the same.
"""
from linkedlist import LinkedList
class Queue():
"""A queue. FIFO.
Operations: enqueue(item), dequeue(), peek(), is_empty()
Make a queue:
>>> karaoke_playlist = Queue()
Anything in the queue?
>>> karaoke_playlist.is_empty()
True
If there's nothing in the karaoke queue, how can we sing like crazy
people? Let's add songs.
>>> karaoke_playlist.enqueue("Try Everything -- Shakira")
>>> karaoke_playlist.enqueue("Sing -- Pentatonix")
>>> karaoke_playlist.enqueue("Best Day of My Life -- American Authors")
Anything in the queue now?
>>> karaoke_playlist.is_empty()
False
Sweeeet. Now we can belt some tunes. Which song is first?
>>> karaoke_playlist.peek()
'Try Everything -- Shakira'
Let's sing it!
>>> song = karaoke_playlist.dequeue()
Are we singing the right song?
>>> print(f"Now singing: {song}")
Now singing: Try Everything -- Shakira
Looks about right. What's next?
>>> karaoke_playlist.peek()
'Sing -- Pentatonix'
We can take a break now...
But let's see how our repr comes out, anyway.
>>> print(karaoke_playlist)
<Queue Front: Sing -- Pentatonix>
"""
def __init__(self):
"""Initialize queue."""
self.items = LinkedList()
def __repr__(self):
"""A human-readable representation of the queue instance."""
return f"<Queue Front: {self.peek()}>"
def is_empty(self):
"""Return True if no items in queue. Return False otherwise."""
return self.items.head is None
def enqueue(self, item):
"""Place an item at the back of the queue."""
self.items.append(item)
def dequeue(self):
"""Remove the item at the front of the queue and return it."""
front_item = self.items.head
self.items.remove(self.items.head.data)
return front_item.data
def peek(self):
"""Check the item at the front of the queue and return it."""
return self.items.head.data
|
3810176ee9bc3612d38bf86c028788acfab09b16 | wards21-meet/meet2019y1lab4 | /funturtle.py | 1,297 | 3.6875 | 4 | import turtle
turtle.bgcolor('purple')
turtle.shape('turtle')
finn=turtle.clone()
finn.shape('square')
finn.goto(100,0)
finn.goto(100,100)
finn.goto(0,100)
finn.goto(0,0)
charlie=turtle.clone()
charlie.shape('triangle')
charlie.left(90)
charlie.forward(100)
charlie.goto(50,150)
charlie.goto(100,100)
finn.penup()
finn.goto(-400,0)
finn.pendown()
finn.goto(-400,200)
finn.stamp()
finn.goto(-200,200)
finn.stamp()
finn.goto(-200,0)
finn.stamp()
finn.goto(-400,0)
finn.clearstamps()
ward=turtle.clone()
ward.penup()
ward.goto(350,0)
ward.pendown()
ward.pensize(5)
ward.color('yellow')
ward.left(90)
ward.forward(150)
ward.left(90)
ward.forward(75)
ward.color('white')
ward.left(90)
ward.forward(150)
gg=turtle.clone()
gg.penup()
gg.goto(350,0)
gg.pendown()
gg.color('green')
gg.pensize(10)
gg.right(90)
gg.forward(150)
gg.left(90)
gg.forward(75)
gg.color('blue')
gg.left(90)
gg.forward(150)
turtle.penup()
turtle.goto(0,-300)
turtle.pendown()
#Movement
def up():
turtle.forward(10)
def down():
turtle.back(10)
def right():
turtle.right(45)
def left():
turtle.left(45)
turtle.onkeypress (up, "w")
turtle.onkeypress (down, "s")
turtle.onkeypress (right, "d")
turtle.onkeypress (left, "a")
turtle.pensize(20)
turtle.pencolor('red')
turtle.listen()
turtle.mainloop()
|
73cd60fcaea5e5611568f337320029c9ed9ea743 | LeeeeDain/Algorithm | /프로그래머스/래벨2_DFSBFS_타겟넘버.py | 243 | 3.546875 | 4 | def solution(numbers, target):
answer_list = [0]
for i in numbers:
answer_list = list(map(lambda x: x+i, answer_list)) + list(map(lambda x: x-i, answer_list))
return answer_list.count(target)
print(solution([1,1,1,1,1],3)) |
33c14aa8717aa84c4830b1e41dfd06996ab135ed | Ben-Baert/Exercism | /python/hexadecimal/hexadecimal.py | 196 | 3.640625 | 4 | from string import hexdigits
def hexa(hex_string):
return sum(hexdigits.index(current_digit) * 16**current_position for current_position, current_digit in enumerate(hex_string.lower()[::-1])) |
4bef4dbda6842b1988760934b72ad4007ca80c6b | Jayabharathi-Thangadurai/program | /leap.py | 100 | 3.75 | 4 | year=int(input())
if year%400==0 or (year%100)!=0 and year%4==0:
print("yes")
else:
print("no")
|
3179e131f93eb19fa5f48d5c90d179b8e654ba30 | daimengqi/Coding4Interviews-python-DMQ | /Coding4Interviews-python-DMQ/剑指offer/053-表示数值的字符串/code.py | 974 | 3.890625 | 4 | class Solution:
# s字符串
def isNumeric(self, s):
# write code here
sign, point, hasE = False, False, False
for i in range(len(s)):
if s[i].lower() == 'e':
if hasE: return False
if i == len(s)-1: return False
hasE = True
elif s[i] == '+' or s[i] == '-':
if sign and s[i-1].lower() != 'e': return False
if not sign and i > 0 and s[i-1].lower() != 'e': return False
sign = True
elif s[i] == '.':
if hasE or point: return False
point = True
elif ord(s[i]) < ord('0') or ord(s[i]) > ord('9'):
return False
return True
# 解法二
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
f = float(s)
return True
except:
return False |
32ecb9b4cfe42fc63007e72ac3c8778fa8121ad5 | huang-zp/pyoffer | /my_queue.py | 646 | 4.125 | 4 | class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack_in.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
else:
return self.stack_out.pop() |
66b4844c7e17191f58f27ac4b1cba6907805e5ea | pranavv999/js-graphs | /pyfiles/indian.py | 1,026 | 3.75 | 4 | import csv
# We are refering data from year 2004 to 2014
def extract_data(file):
"""Return the population data for India for year 2004 to 2014"""
population_data = {
"gTitle": "Indian Population For Year 2004 - 2014",
"xLabels": [
"2004",
"2005",
"2006",
"2007",
"2008",
"2009",
"2010",
"2011",
"2012",
"2013",
"2014",
],
"xText": "Years",
"yText": "Population in millions",
}
population = []
with open(file, mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
if (row["Region"] == "India" and
row["Year"] in population_data["xLabels"]):
# truncating values
value = int(float(row["Population"]) / 1000)
population.append(value)
population_data["data"] = population
return population_data
|
6f0c96fb181d53b3210c99d4477af49546067aec | Brkgng/HackerRank_Solutions | /Warmups/time-conversion.py | 415 | 3.796875 | 4 | #
# See the problem
# https://www.hackerrank.com/challenges/time-conversion/problem
#
#
def timeConversion(s):
if s[-2:] == "AM":
if s[:2] == "12":
return "00" + s[2:-2]
return s[:-2]
if s[:2] == "12":
return s[:-2]
return str(int(s[:2]) + 12) + s[2:-2]
# if __name__ == '__main__':
# s = input()
# print(timeConversion(s))
n = 10 / 2
print( 2 % -2 == 0)
|
daf69275ea6a376dca21b8fa90b2518106acd33f | itsolutionscorp/AutoStyle-Clustering | /assignments/python/anagram/src/88.py | 404 | 3.671875 | 4 | from collections import Counter
def detect_anagrams(word, word_list):
if word in word_list:
return []
word_c = Counter(word.lower())
word_list_counters = dict(zip(word_list, (Counter(w.lower()) for w in word_list)))
anagrams = [w for w in word_list_counters if (word_list_counters[w] == word_c) and (w != word)]
anagrams.reverse()
return anagrams
|
5a71aad09b865045b9d1d72cb0e4e3906fd90074 | lusineduryan/ACA_Python | /Basics/Homeworks/Homework_6/Exercise_2_fast determinant.py | 615 | 4.21875 | 4 | # https://www.khanacademy.org/math/algebra-home/alg-matrices/alg-determinants-and-inverses-of-large-matrices/v/finding-the-determinant-of-a-3x3-matrix-method-1
def fast_deter(arg):
res = 0
N1 = arg
for i in range(len(arg)):
if i > 0:
N1 = N1[1:]
N1.append(arg[i-1])
N2 = N1[::-1]
prod1, prod2 = 1, 1
for j in range(len(N1)):
prod1 *= N1[j][j]
for k in range(len(N2)):
prod2 *= N2[k][k]
temp_res = prod1 - prod2
res += temp_res
return res
A = [[0,2,3], [1,3,4], [2,4,6]]
print(fast_deter(A))
|
a6a7437b89d7de2801c54933df145a5b0c3123b3 | yesiaikan/pythonlearn | /luoji/myfor.py | 154 | 3.5 | 4 | __author__ = 'muli'
for i in range(1,4,2):
print(i)
else:
print("-----------")
for i in xrange(5):
print(i)
print(range(2, 5, 2)) |
0d28a1976c05fcd891f962c408721f5c2f675d70 | roxanacaraba/Learning-Python | /25-Frequently-Asked-Python-Programs/Clear_a_list.py | 460 | 4.125 | 4 | list=[6,0,4,1]
print("List before clear:", list)
#Varianta 1 folosind clear()
#list.clear()
#print("List after clear:", list)
#Varianta 2 : initializes the list with no value
#list=[]
#print("List after clear:", list)
#Varianta 3 utilizand "*=0", aceasta metoda inlatura toate elementele si o face goala
#list *=0 #deletes the list
#print("List after clear:", list)
#Varianta 4
del list[1:3] # 0 4
print(list)
del list[:] # toata lista
print(list)
|
31daf353c4116031af0f029ec76d0379c1c4b067 | orsenthil/coursedocs | /gatech/cs8803-O01/circular_motion.py | 6,635 | 4.375 | 4 | # -----------------
# USER INSTRUCTIONS
#
# Write a function in the class robot called move()
#
# that takes self and a motion vector (this
# motion vector contains a steering* angle and a
# distance) as input and returns an instance of the class
# robot with the appropriate x, y, and orientation
# for the given motion.
#
# *steering is defined in the video
# which accompanies this problem.
#
# For now, please do NOT add noise to your move function.
#
# Please do not modify anything except where indicated
# below.
#
# There are test cases which you are free to use at the
# bottom. If you uncomment them for testing, make sure you
# re-comment them before you submit.
from math import *
import random
# --------
#
# the "world" has 4 landmarks.
# the robot's initial coordinates are somewhere in the square
# represented by the landmarks.
#
# NOTE: Landmark coordinates are given in (y, x) form and NOT
# in the traditional (x, y) format!
landmarks = [[0.0, 100.0], [0.0, 0.0], [100.0, 0.0], [100.0, 100.0]] # position of 4 landmarks
world_size = 100.0 # world is NOT cyclic. Robot is allowed to travel "out of bounds"
max_steering_angle = pi/4 # You don't need to use this value, but it is good to keep in mind the limitations of a real car.
# ------------------------------------------------
#
# this is the robot class
#
class robot:
# --------
# init:
# creates robot and initializes location/orientation
#
def __init__(self, length = 10.0):
self.x = random.random() * world_size # initial x position
self.y = random.random() * world_size # initial y position
self.orientation = random.random() * 2.0 * pi # initial orientation
self.length = length # length of robot
self.bearing_noise = 0.0 # initialize bearing noise to zero
self.steering_noise = 0.0 # initialize steering noise to zero
self.distance_noise = 0.0 # initialize distance noise to zero
def __repr__(self):
return '[x=%.6s y=%.6s orient=%.6s]' % (str(self.x), str(self.y), str(self.orientation))
# --------
# set:
# sets a robot coordinate
#
def set(self, new_x, new_y, new_orientation):
if new_orientation < 0 or new_orientation >= 2 * pi:
raise ValueError, 'Orientation must be in [0..2pi]'
self.x = float(new_x)
self.y = float(new_y)
self.orientation = float(new_orientation)
# --------
# set_noise:
# sets the noise parameters
#
def set_noise(self, new_b_noise, new_s_noise, new_d_noise):
# makes it possible to change the noise parameters
# this is often useful in particle filters
self.bearing_noise = float(new_b_noise)
self.steering_noise = float(new_s_noise)
self.distance_noise = float(new_d_noise)
############# ONLY ADD/MODIFY CODE BELOW HERE ###################
# --------
# move:
# move along a section of a circular path according to motion
#
def move(self, motion): # Do not change the name of this function
alpha, d = motion
if abs(alpha) > max_steering_angle:
raise ValueError, "alpha greater than max_steering_angle"
if d < 0.0:
raise ValueError, "going backwards is not allowed."
beta = ((1.0 * d) / self.length) * tan(alpha)
if beta < 0.001:
x_p = self.x + (d * cos(self.orientation))
y_p = self.y + (d * sin(self.orientation))
else:
R = (1.0 * d) / beta
cx = self.x - (sin(self.orientation) * R)
cy = self.y + (cos(self.orientation) * R)
x_p = cx + (sin(self.orientation + beta) * R)
y_p = cy - (cos(self.orientation + beta) * R)
theta_p = (self.orientation + beta) % (2 * pi)
result = robot(self.length)
result.set_noise(self.bearing_noise, self.steering_noise, self.distance_noise)
result.set(x_p, y_p, theta_p)
return result
# make sure your move function returns an instance
# of the robot class with the correct coordinates.
############## ONLY ADD/MODIFY CODE ABOVE HERE ####################
## IMPORTANT: You may uncomment the test cases below to test your code.
## But when you submit this code, your test cases MUST be commented
## out. Our testing program provides its own code for testing your
## move function with randomized motion data.
## --------
## TEST CASE:
##
## 1) The following code should print:
## Robot: [x=0.0 y=0.0 orient=0.0]
## Robot: [x=10.0 y=0.0 orient=0.0]
## Robot: [x=19.861 y=1.4333 orient=0.2886]
## Robot: [x=39.034 y=7.1270 orient=0.2886]
##
##
length = 20.
bearing_noise = 0.0
steering_noise = 0.0
distance_noise = 0.0
myrobot = robot(length)
myrobot.set(0.0, 0.0, 0.0)
myrobot.set_noise(bearing_noise, steering_noise, distance_noise)
motions = [[0.0, 10.0], [pi / 6.0, 10], [0.0, 20.0]]
T = len(motions)
print 'Robot: ', myrobot
for t in range(T):
myrobot = myrobot.move(motions[t])
print 'Robot: ', myrobot
## IMPORTANT: You may uncomment the test cases below to test your code.
## But when you submit this code, your test cases MUST be commented
## out. Our testing program provides its own code for testing your
## move function with randomized motion data.
## 2) The following code should print:
## Robot: [x=0.0 y=0.0 orient=0.0]
## Robot: [x=9.9828 y=0.5063 orient=0.1013]
## Robot: [x=19.863 y=2.0201 orient=0.2027]
## Robot: [x=29.539 y=4.5259 orient=0.3040]
## Robot: [x=38.913 y=7.9979 orient=0.4054]
## Robot: [x=47.887 y=12.400 orient=0.5067]
## Robot: [x=56.369 y=17.688 orient=0.6081]
## Robot: [x=64.273 y=23.807 orient=0.7094]
## Robot: [x=71.517 y=30.695 orient=0.8108]
## Robot: [x=78.027 y=38.280 orient=0.9121]
## Robot: [x=83.736 y=46.485 orient=1.0135]
##
##
##length = 20.
##bearing_noise = 0.0
##steering_noise = 0.0
##distance_noise = 0.0
##
##myrobot = robot(length)
##myrobot.set(0.0, 0.0, 0.0)
##myrobot.set_noise(bearing_noise, steering_noise, distance_noise)
##
##motions = [[0.2, 10.] for row in range(10)]
##
##T = len(motions)
##
##print 'Robot: ', myrobot
##for t in range(T):
## myrobot = myrobot.move(motions[t])
## print 'Robot: ', myrobot
## IMPORTANT: You may uncomment the test cases below to test your code.
## But when you submit this code, your test cases MUST be commented
## out. Our testing program provides its own code for testing your
## move function with randomized motion data.
|
5653f4d749ad89f9b4e56323b3333f685ba9afe3 | anurag3753/courses | /david_course/Lesson-07-Classes_and_Objects/holding_v1.py | 1,985 | 3.828125 | 4 | """Understanding the classes:-
We are not using Holding(object) syntax, because in python3 all the classes by default
inherit from object classes
"""
class Holding:
def __init__(self, name, date, shares, price):
self.name = name
self.date = date
self.shares = shares
self.price = price
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
"""
Lets see a stripped down version of read_portfolio written usign the classes
"""
import csv
def read_portfolio(filename):
portfolio = []
with open(filename, 'r') as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
h = Holding(row[0], row[1], int(row[2]), float(row[3]))
portfolio.append(h)
return portfolio
def main():
h = Holding('tcs', '25apr', 100, 1500)
print(h.shares) # It access the value stored in shares for instance `h`
print(h.cost()) # It does the calculation on shares and price
"""
h.cost() == (h.cost)()
It turns out that h.cost() is two completely seperate things going on :-
- (h.cost) # 1st part is the lookup of the attribute
- if lookup is successfull, then there is a function call done for that i.e. (h.cost) ()
You can also do one without the other, like
>>> c = h.cost # it returns a method attached to the holding object
>>> c()
"""
# Using list comprehension on the objects to compute the total portfolio valuation
holding = read_portfolio("stocks_dummy.csv") # Read the portfolio into a list of objects
valuation = sum([h.shares* h.price for h in holding])
print(valuation)
## Everything works as it is, as we were doing it before, but now we are creating instances and using the .(dot)
## operator to do the same computation
if __name__ == "__main__":
main() |
149924670b5e81bb5d879155c2068e91a99a6546 | qqlzfmn/AutomateTheBoringStuffWithPython | /PatternMatching/stripRegex.py | 483 | 3.546875 | 4 | import re
def stripRegex(str, char=' '):
# re.compile()的参数本质上是一个字符串,所以可以用字符串拼接的方式写
# 要提取出中间的字符串,就需要变成非贪心模式,否则将会匹配后续的分割字符
regex = re.compile(r'^[' + char + r']*(.+?)[' + char + r']*$')
return regex.search(str).group(1)
print(stripRegex(' fnewuih564asui '))
print(stripRegex('-------------- fnewuih564asui ----------', '-'))
|
da31b78ea66c60f1fdcc55dea87a1f5aa77e694f | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/285.py | 945 | 3.625 | 4 | fair_squares = []
def is_fair(n):
return all(a == b for a,b in zip(str(n), reversed(str(n))))
def precompute_fair_squares():
for i in range(1, 10 ** 7 + 1):
if is_fair(i):
i2 = i ** 2
if is_fair(i2):
# print(i2)
fair_squares.append(i2)
def binary_search(x, is_upper_bound):
a = 0
b = len(fair_squares)
while b - a > 1:
c = (b + a) // 2
if fair_squares[c] < x:
a = c
elif fair_squares[c] > x:
b = c
else:
return c
if fair_squares[a] == x:
return a
elif is_upper_bound:
return a
else:
return b
def solve(A, B):
lowest = binary_search(A, False)
highest = binary_search(B, True)
# print(lowest, highest)
return highest - lowest + 1
def main():
T = int(input())
for case in range(1, T + 1):
A, B = map(int, input().split())
print("Case #%d: %s" % (case, solve(A, B)))
if __name__ == "__main__":
precompute_fair_squares()
main()
|
c3750ae75a5d41864a666cb9e9465783305eb396 | nashirj/PathPlanner | /pathfinding.py | 2,128 | 3.859375 | 4 | def a_star(arena, start, end):
'''Implementation of algorithm from this video: https://www.youtube.com/watch?v=-L-WgKMFuhE
'''
open_nodes = {}
closed_nodes = {}
open_nodes[start] = start.f_cost
while open_nodes:
# https://stackoverflow.com/questions/3282823/get-the-key-corresponding-to-the-minimum-value-within-a-dictionary/3282904#3282904
current = min(open_nodes, key=open_nodes.get)
del open_nodes[current]
closed_nodes[current] = current.f_cost
# print_nodes_for_debugging(open_nodes, "open_nodes")
# print_nodes_for_debugging(closed_nodes, "closed_nodes")
if current.x == end.x and current.y == end.y:
# TODO: return the path itself, find a way to reconstruct and visualize
return current.f_cost
# TODO: change this to a class method in node?
neighbors = find_neighbors(arena, current, closed_nodes)
for neighbor in neighbors:
if neighbor.dist_from_node(current) < neighbor.g_cost or neighbor not in open_nodes:
neighbor.g_cost = neighbor.dist_from_node(start)
neighbor.h_cost = neighbor.dist_from_node(end)
neighbor.f_cost = neighbor.g_cost + neighbor.h_cost
neighbor.parent = current
if neighbor not in open_nodes:
open_nodes[neighbor] = neighbor.f_cost
return None
def find_neighbors(arena, current, closed_nodes):
directions = [[1,0], [0,1], [-1,0], [0,-1]] # allow for movement in the up, down, left, right directions, no diagonals
neighbors = []
for direction in directions:
if 0 <= current.x+direction[0] < arena.height and 0 <= current.y+direction[1] < arena.width:
node = arena.board[current.x+direction[0]][current.y+direction[1]]
if node.is_traversable() and node not in closed_nodes:
neighbors.append(node)
return neighbors
def print_nodes_for_debugging(nodes, name):
print("nodes in {}:".format(name))
for node in nodes:
print('\t{}'.format(node))
print()
|
cacd744bf14997dc534f07cf1e5c5253875f8e1a | baewonje/iot_bigdata_- | /python_workspace/01_jump_to_python/5_APP/1_Class/188_4_cal_class4.py | 1,170 | 3.609375 | 4 | class FourCal:
# first = 0
# second = 0 # 중간에 멤버 변수를 정의할 수 있어도 명시적으로 클래스
# 멤버 변수를 class 다음에 지정하는 것은
# 프로그램 유지보수와 가독성에 더 좋다고 볼 수 있다.
def setdata(self,first, second):
self.first = first # 멤버 변수가 없음에도 객체생성이후에
# 클래스의 멤버변수를 생성하는 것이 가능하다.
self.second = second
def print_number(self):
print("first: %d, second: %d"%(self.first,self.second))
# self를 사용하지 않으면 멤버함수에서 사용하는 지역변수로 인식한다.
# 따라서 아래 코드는 빌드시 에러를 발생하게 된다.
# pritn("first: %d, second : %d"%(firse,second))
# a = FourCal(1,2) # 2개의 인자를 갖는 생성자가 없으므로 에러를 발생한다.
a= FourCal()
a.setdata(1,2) # 객채 생성이후의 멤버 변수 값을 설정할 때 사용한다.
a.print_number()
print(id(a.first))
b = FourCal()
b.setdata(3,2)
b.print_number()
print(id(b.first))
|
c6c3cc1b8f1e6142c254251a7f21aa3ec40bd5a9 | Xia-Dai/Data-exploration-Python | /countchar_quiz.py | 459 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 20 17:05:41 2017
@author: Daisy
Email: dxww01@gmail.com
Never too late or old to study!
"""
#count alpha
def countchar(str):
list1 = [0]*26
for i in range(0,len(str)):
if (str[i] >= 'a' and str[i] <= 'z'):
list1[ord(str[i])-97] += 1
print list1
if __name__ == '__main__':
str = "Hope is a good thing."
str = str.lower()
countchar(str) |
8baa27d1b4008b21a659f86bf32fa18254b4b7a7 | paras2106/brampton | /Hi.py | 71 | 3.5 | 4 | # DECLARE Myname : STRING
Myname = "Paras"
print("Hi ",Myname)
input()
|
c5d55e95a8cd505986ec8114211e1140a9b9bd0e | palakbaphna/pyprac | /Conditions if, then, else/10minimumOf2Numbers.py | 202 | 4.25 | 4 | #Given the two integers, print the least of them.
a = int(input("a = ?"))
b = int(input("b = ?"))
if a < b:
print("least of them is a = %s" %a)
elif b < a:
print("least of them is b = %s" %b)
|
0f646b0e942bca83ca6e2770cc7e2c37fbf4e32e | testcg/python | /code_all/day15/exercise01.py | 619 | 4.28125 | 4 | """
练习1:定义函数,根据年月日,计算星期。
输入:2020 9 15
输出:星期二
"""
import time
def get_week_name(year,month,day):
"""
获取星期名称
:param year:年份
:param month:月份
:param day:天
:return:星期名称
"""
# "2021/03/18 11:48:56","%Y/%m/%d
tuple_time = time.strptime(f"{year}/{month}/{day}","%Y/%m/%d")
index = tuple_time[-3]
list_week_name = [
"星期一","星期二","星期三","星期四","星期五","星期六","星期日"
]
return list_week_name[index]
print(get_week_name(2021,3,18)) |
9765eba70256582e8b0bf354ae20df1f8d55149d | AIClubUA/Weekly-Meetings | /September 2018/Week of 9-24-2018/basic-csv-processing/kagglepre.py | 983 | 3.625 | 4 | import pandas as pd
df = pd.read_csv("train.csv")
df.fillna(0, inplace=True)
print(df.head())
"""
predict death or life (1 or 0)
GOAL: process data so that we have our inputs in a logical order on a per person basic
"""
labels = df['Survived']
features = list(df.columns)
features.remove("Survived") # removes "Survived" from index 1
#print(features)
# this is a dataframe pointing to the 'df' variable
inputs = df[features]
# this is a dictionary memory independant
inputs = inputs.to_dict('list')
age = inputs["Age"]
agesum = 0
count = 0
for item in age:
print(item)
if item > 0:
#agesum = agesum + item
agesum += item
count += 1
avg = int(agesum / count)
print("avg:", avg)
newage = []
for item in age:
if item > 0:
newage.append(int(item))
else:
newage.append(avg)
print()
print(" original:", age[:10])
print("corrected:", newage[:10])
inputs["Age"] = newage
print("from inputs:", inputs["Age"][:10])
|
945209eb540f84ad30975ee1a657f50b347de7d7 | alexchou094/Python200804 | /Day2-6.py | 765 | 3.859375 | 4 | nP = input("how many student in your class?")
nP = int(nP)
total = 0
avg = 0
name = []
grade = []
for i in range(nP):
N = input("Please enter students' name : ")
name.append(N)
G = input("Please enter the student's grade : ")
grade.append(G)
for i in range(nP):
total = total + int(grade[i])
print("The total grade is : ",total)
avg = total / nP
print("The average value is : ",avg)
H = 0
Hp = 0
for i in range(nP):
if int(grade[i]) > H:
H = int(grade[i])
Hp = str(name[i])
print("The highest grade is",Hp,' : ',H,"point")
L = 0
Lp = 0
for i in range(nP):
if int(grade[i]) < L:
L = int(grade[i])
Lp = str(name[i])
print("The lowest grade is",Lp,' : ',L,"point")
|
0a81901deee7820bcc78a20d33b9aa319056c661 | ZanderYan-cloud/PythonRepository | /GuessnumberGame/cn/csu/python/intDemo.py | 1,000 | 3.578125 | 4 | #1. x 是数字的情况:
print(int(3.14) ) # 3
print(int(2e2)) # 200
#int(100, 2) # 出错,base 被赋值后函数只接收字符串
#2. x 是字符串的情况:
print(int('23', 16) ) # 35
#int('Pythontab', 8) # 出错,Pythontab不是个8进制数
#3. base 可取值范围是 2~36,囊括了所有的英文字母(不区分大小写),十六进制中F表示15,那么G将在二十进制中表示16,依此类推....Z在三十六进制中表示35
#print(int('FZ', 16)) # 出错,FZ不能用十六进制表示
print(int('F', 36)) # 575
print(int('z', 36)) # 575
print(int('Fz', 36)) # 575
#4. 字符串 0x 可以出现在十六进制中,视作十六进制的符号,同理 0b 可以出现在二进制中,除此之外视作数字 0 和字母 x
print(int('0x10', 16)) # 16,0x是十六进制的符号
#int('0x10', 17) # 出错,'0x10'中的 x 被视作英文字母 x
print(int('0x10', 36)) # 42804,36进制包含字母 x
|
45dc3bc04089b469a4ba2fd8d6525b97679d9d72 | 18516264210/MachineLearning | /python00/day04/Gaojiehanshu.py | 713 | 4.21875 | 4 |
# 高阶函数(通俗的讲就是函数返回函数)
# 函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
def f1(x,y):
return x+y
def calc(x):
# 接收的是一个函数名,加()执行传递过来的函数
return x(1,2)
# 这里将函数作为参数传递到另一个函数中进行执行
n = f1
print(calc(n))
print("-----------------------------------------------")
# 这里的函数返回的是一个元组,在外层获取参数后使用下标的形式获取到对应的函数和参数
def f2(x,y):
# abs是内置函数,返回绝对值
return abs,x,y
res = f2(1,2)
print(res[0](res[1]+res[2]))
|
507b132247785a0143d19bc32cebac469e18447f | yojimat/100_plus_Python_Programming_Exercises | /day_6_desafio_100_ex_python.py | 1,924 | 4.15625 | 4 | ####################################
print("\nQuestão 16:")
print("Use a list comprehension to square each odd number in a list.")
print("The list is input by a sequence of comma-separated numbers.")
print("Suppose the following input is supplied to the program:")
print("--> 1,2,3,4,5,6,7,8,9")
print("Then, the output should be:")
print("--> 1,9,25,49,81")
print("\nHints:")
print("In case of input data being supplied to the question, it should be assumed to be a console input.")
print("\nMinha solução:")
def questao16():
lista_numeros = input(
"Escreva uma sequência de numeros separados por vírgulas: ").split(",")
#lista_numeros = "1,2,3,4,5,6,7,8,9".split(",")
lista_impares_ao_quadrado = ",".join(
[str(pow(int(char), 2)) for char in lista_numeros if int(char) % 2 != 0])
print(lista_impares_ao_quadrado)
print("\nQuestão 17:")
print("Write a program that computes the net amount of a bank account based a transaction log from console input.")
print("The transaction log format is shown as following:")
print("--> D 100")
print("--> W 200")
print("* D means deposit while W means withdrawal.")
print("Suppose the following input is supplied to the program:")
print("--> D 300")
print("--> D 300")
print("--> W 200")
print("--> D 100")
print("Then, the output should be:")
print("--> 500")
print("\nHints:")
print("In case of input data being supplied to the question, it should be assumed to be a console input.")
print("\nMinha solução:")
def questao17():
print("D para depósito, W para saque, enter para finalizar a inserção")
caixa = 0
while True:
operacao = input("Insira uma operação -> ").split()
if not operacao:
break
if operacao[0] == "D":
caixa += int(operacao[1])
else:
caixa -= int(operacao[1])
print(caixa)
if __name__ == "__main__":
questao16()
questao17()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.