blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
18187aef39ed5cdb6edad56d8599bc80586d93f8 | TokarAndrii/PythonStuff | /pythonTasks/data_structures/moreOnList.py | 1,760 | 4.71875 | 5 | # https: // docs.python.org/3.0/tutorial/datastructures.html
# list.append(x)
# Add an item to the end of the list
# equivalent to a[len(a):] = [x].
# list.extend(L)
# Extend the list by appending all the items in the given list
# equivalent to a[len(a):] = L.
# list.insert(i, x)
# Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
# list.remove(x)
# Remove the first item from the list whose value is x. It is an error if there is no such item.
# list.pop([i])
# Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
# list.index(x)
# Return the index in the list of the first item whose value is x. It is an error if there is no such item.
# list.count(x)
# Return the number of times x appears in the list.
# list.sort()
# Sort the items of the list, in place.
# list.reverse()
# Reverse the elements of the list, in place.
a = [66.25, 333, 333, 1, 1234.5]
a.append(237)
print(a)
# [66.25, 333, 333, 1, 1234.5, 237]
a.insert(1, 999)
print(a)
# [66.25, 999, 333, 333, 1, 1234.5, 237]
a.remove(333)
print(a)
# [66.25, 999, 333, 1, 1234.5, 237]
a.pop(1)
print(a)
# [66.25, 333, 1, 1234.5, 237]
find = a.index(237)
print(find)
# 4
print(a.count(333))
# 1
a.sort()
print(a)
# [1, 66.25, 237, 333, 1234.5]
a.reverse()
print(a)
# [1234.5, 333, 237, 66.25, 1]
|
1f3aaa0e48d787f2b1ec361d800cbc8d4606c7af | wicarte/492 | /a3.py | 845 | 4.125 | 4 | #Assignment 3 (W3D4) - William Carter
#What I think will happen before running the code:
#I think the code prompts the user to enter a number, casts
#the number as an int, counts up by 1 on the interval (2, user
#provided number), and prints whenever the outer loop iterator (i)
#is not cleanly divisible by the inner loop iterator (k).
n = input("Please enter a number as an upper limit: ")
n = int(n)
for i in range(2, n):
check_var = True
for k in xrange(2, i):
if (i%k) == 0:
check_var = False
if check_var:
print(i)
#After running the code:
#A number is printed out and another number is printed out as many times
#as the first number's value. For example, if 5 is printed out and 7
#is the next number to be printed, 7 will print 5 different times.
#This pattern continues until the upper bound provided by the user
#is reached.
|
67319ec01a00dda7c5cd281f4f60adc9e4b48912 | AaronTao1990/leetcode | /forfun/partition.py | 1,576 | 3.921875 | 4 | def partition(array, left, right, pivot_index):
pivot_value = array[pivot_index]
array[pivot_index], array[right] = array[right], array[pivot_index]
index = left
for i in range(left, right):
if array[i] < pivot_value:
array[i], array[index] = array[index], array[i]
index = index + 1
array[index], array[right] = array[right], array[index]
return index
def quick_sort(array, left, right):
if left >= right:
return
pivot_index = (left + right) / 2
index = partition(array, left, right, pivot_index)
quick_sort(array, left, index)
quick_sort(array, index+1, right)
def nth_of_array(array, left, right, n):
if left == right:
return array[left]
pivot_index = (left + right) / 2
index = partition(array, left, right, pivot_index)
if index == n:
return array[n]
elif index > n:
return nth_of_array(array, left, index, n)
else:
return nth_of_array(array, index+1, right, n)
def nth_of_array_non_recur(array, left, right, n):
if left == right:
return array[left]
while True:
pivot_index = (left + right) / 2
index = partition(array, left, right, n)
if index == n:
return array[index]
elif index > n:
right = index-1
else:
left = index + 1
if __name__ == '__main__':
array = [6, 2, 5, 3, 1, 4]
#quick_sort(array, 0, len(array)-1)
#print nth_of_array(array, 0, len(array)-1, 1)
print nth_of_array_non_recur(array, 0, len(array)-1, 1)
|
70f1bbd6b0b8cc986da30ecffe9779db8fb5796a | junanyeap/ncnu_1072_python_oldfish | /Bingo.py | 998 | 3.734375 | 4 | import random
def selectNum():
num = input("input a num:")
return num
def printPlate(n,plate):
for key in plate:
if(key % n == 0):
print()
if plate[key] == False:
print("xx"," ",end="")
else :
print(key," ",end="")
def lineCheck(plate,n){
i = 0
j = 0
# left to right
for i in range(len(plate)/n):
}
def bingo(n):
count = 0
line = 0
plate = {}
i = 0
for i in range(n*n):
plate.update({i:False})
print(plate)
random.shuffle(plate)
printPlate(n,plate)
while line < 5 :
num = selectNum()
if num in plate:
print("got this number ~")
plate.update({num:True})
count++
line = lineCheck(plate,n)
else:
print("no number ~")
print("game over,you guessed %s times.",count)
def main():
n = int(input("n: "))
time = bingo(n)
main() |
fd3131dba1c38c6d15723725e1002c468d8a059f | junanyeap/ncnu_1072_python_oldfish | /test.py | 320 | 3.71875 | 4 | #20190226
def main():
# name=input()
# print('hello,', name)
# year=int(input())
# print('hello, ',year*20)
# a = float(input())
# b = float(input())
# result = a**b
# if type(result) == int :
# result = int(result)
# print('hello, ', result)
main()
# |
42a8da5f345d69b6300d7befe18fd3f894e04362 | junanyeap/ncnu_1072_python_oldfish | /3n.py | 1,516 | 3.546875 | 4 | # 0 2 4 : n/2
# 1 3 5 : 3n+1
# given a range a~b, find the maximum cycle length
seqElement = []
def printSeq(n):
if n == 1:
return 1
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
# add to array
seqElement.append(n)
# print(n)
return printSeq(n)+1
def seqlen(n):
if n == 1:
return 1
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
# print(n)
return seqlen(n)+1
# old fish version
def seqlen2(n):
count = 1
while n!=1:
if n % 2 == 0 :
n = n / 2
else :
n = 3 * n + 1
count = count + 1
return count
def findMaxLen(n,m) :
if n > m :
n,m = m,n
i = n
max = 0
for i in range(n,m):
resutl = seqlen(i)
if resutl > max:
max = resutl
printSeq(max)
return max
def main():
# keep reading data
while True:
# input 2 number with space
try:
n, m = map(int,input("input n[SPACE]m : ").split())
print("max number :",findMaxLen(n,m))
print(seqElement)
# if not the input rule, break the program
except:
print("Wrong input")
break
# n = int(input("1st number : "))
# m = int(input("2nd number : "))
# print(seqlen2(n))
# print("got:",seqlen(n))
# print("max number :",findMaxLen(n,m))
# print(seqElement)
main()
# seqlen(3) = 8 |
760096c5d3ae80e8891112216fc366d84cc7e0f6 | junanyeap/ncnu_1072_python_oldfish | /stddev.py | 841 | 3.859375 | 4 | #學號:104213070
#姓名:葉潤安
import math
def meanStddev(data) :
avg = sum(data)/len(data)
stList = []
i = 0
for i in range(len(data)):
# 把計算結果加入list
stList.append((avg - data[i])*(avg - data[i]))
# print(stList)
return avg, math.sqrt(sum(stList)/len(data))
def main():
i = 0
# input 被split()以空白切割成element,並存入nums這個list
nums = input().split()
data = []
# 轉成int
for i in range(len(nums)):
data.append(int(nums[i]))
mean, std = meanStddev(data)
# print("平均 : ",mean," , 標準差 : ", std)
print("AVG : ",mean," , STDDEV : ", std)
print("mine CMD can't display chinese,\nor you can uncomment the chinese print line\nSorry~")
# print(type(std))
main() |
5f9a38190015442a8aacf96c7c1018376ad6da3e | junanyeap/ncnu_1072_python_oldfish | /Square.py | 1,193 | 3.75 | 4 | # 學號 : 104213070
# 姓名 : 葉潤安
def printSquare(data,n):
# 印一下
for i in range(n):
for j in range(n) :
print('{: 03}'.format(data[i][j]),end = " ")
print()
def square(n,data):
# 設定row跟col的初始值(要填入的第一個數字的位置)
# 初始值是 第一個row的正中間,在該位置填入1
row = 0
col = n // 2
data[row][col] = 1
nextPost = 0
# 依序填入 2~n * n
for num in range (2,n*n+1):
# 從起始點位置開始往右上方填入
nextPos = data[(row-1)%n][(col+1)%n]
# 如果超過邊界就跳入另一邊
# 如果要填入數字的地方已經有數字
if nextPos != 0 :
#回到當前數字的下方
data[(row+1)%n][col] = num
row = (row + 1) % n
# else
else :
data[(row-1)%n][(col+1)%n] = num
row = (row - 1)%n
col = (col + 1)%n
# 填入數字
# 呼叫函數印出方陣
printSquare(data,n)
def main():
n = int(input())
data = [[0 for i in range(n)] for j in range(n)]
# print(data)
square(n,data)
main()
|
47a921735d69b577ead0f943186df81d98bc321a | SayanDutta001/Competitive-Programming-Codes | /Google Kickstart April/Bike_Tour.py | 288 | 3.59375 | 4 | def biketour(n, a):
count = 0
for j in range(1, n-1):
if(a[j]>a[j-1] and a[j]>a[j+1]):
count+=1
return count
test = int(input())
for i in range(test):
n = int(input())
a = list(map(int, input().split()))
ans = biketour(n, a)
print("Case #"+str(i+1)+": "+str(ans))
|
e0cdeab9d080c422709b39b0eaf74f3a7ccd31d4 | SayanDutta001/Competitive-Programming-Codes | /A2OJ/Ladder 0-1300/borze.py | 419 | 3.546875 | 4 | def borzecode(s):
ans = []
start = 0
while(start!=len(s)):
if(s[start] == '.'):
ans.append(0)
start += 1
elif(s[start] == '-' and s[start+1] == '.'):
ans.append(1)
start += 2
elif(s[start] == '-' and s[start+1] == '-'):
ans.append(2)
start += 2
return ''.join(map(str, ans))
s = input()
print(borzecode(s)) |
808d72c561d7f971ca4e690e3532807133816314 | SayanDutta001/Competitive-Programming-Codes | /Codechef November Challenge 2020/ADADISH.py | 318 | 3.609375 | 4 | def adadish(n, a):
al, bl = 0, 0
a.sort()
for i in range(len(a)-1, -1, -1):
if al<=bl:
al+=a[i]
else:
bl += a[i]
return max(al, bl)
test = int(input())
for i in range(test):
n = int(input())
a = list(map(int, input().split()))
print(adadish(n, a))
|
035dca7c2c2a88db8dd1f5479abdc8a6134f1859 | SayanDutta001/Competitive-Programming-Codes | /MockVita 2/grooving_monkeys.py | 382 | 3.59375 | 4 | def monkeys(n, a):
lista = a
listb = [0]*len(a)
count = 0
while(listb!=a):
count += 1
listb = [0]*len(a)
for i in range(len(a)):
listb[a[i]-1] = lista[i]
lista = listb
return count
test = int(input())
for i in range(test):
n = int(input())
a = list(map(int, input().split()))
print(monkeys(n, a))
|
75b8a5b4dbe51180636cff7a2befeb74c6fb0bb7 | SayanDutta001/Competitive-Programming-Codes | /AtCoder 168/colon.py | 338 | 3.734375 | 4 | import math
def colon(a, b, h, m):
hour = 0.5 * (h * 60 + m)
minute = 6 * m
angle = abs(hour - minute)
angle = min(360 - angle, angle)
rad = angle*(3.141592653589793238/180)
#print(angle, rad)
ans = math.sqrt(a**2+b**2-(2*a*b*(math.cos(rad))))
return ans
a, b, h, m = map(int, input().split())
print(colon(a,b,h, m))
|
1660bfe842a6bd0ead81b6d0defa574fa1bfac3c | SayanDutta001/Competitive-Programming-Codes | /AtCoder 164/gacha.py | 112 | 3.5625 | 4 | n = int(input())
a = []
count = 0
for i in range(n):
item = input()
a.append(item)
print(len(list(set(a))))
|
734c3a092843b5060875adee4d7154279503dc31 | SayanDutta001/Competitive-Programming-Codes | /Practice Codes/COMPILER.py | 337 | 3.546875 | 4 | def compiler(s):
ans = 0
t = 0
for i in range(len(s)):
if(s[i]=='<'):
t+=1
else:
t-=1
if(t==0):
ans = max(ans, i+1)
elif(t<0):
break
return ans
test = int(input())
for i in range(test):
s = input()
print(compiler(s)) |
49fe7e3218bdc8fc99d1d08dbf08a4b5517a89f5 | SayanDutta001/Competitive-Programming-Codes | /Coursera Algorithmic Toolbox/Week 3/maximum_salary.py | 433 | 3.71875 | 4 | def IsGreaterOrEqual(digit, max_digit):
return int(str(digit)+str(max_digit))>=int(str(max_digit)+str(digit))
def salary(n, a):
ans = []
while a!=[]:
max_digit = 0
for digit in a:
if IsGreaterOrEqual(digit, max_digit):
max_digit = digit
ans.append(max_digit)
a.remove(max_digit)
return ans
n = int(input())
a = list(map(int, input().split()))
print(''.join([str(i) for i in salary(n, a)]))
|
127b51256b348f921c47c5d9dbb0adb4276fc25f | SayanDutta001/Competitive-Programming-Codes | /Codechef August Challenge 2020/LINCHESS.PY | 371 | 3.5625 | 4 | def chess(n, c, a):
win = 0
mini = float('inf')
for i in a:
if(c%i==0):
if(c//i < mini):
mini = c//i
win = i
if(win == 0):
return -1
return win
test = int(input())
for i in range(test):
n, c = map(int, input().split())
a = list(map(int, input().split()))
print(chess(n, c, a))
|
e86376d1f6a1ff0f068b3a6b83f1ea73def071ef | SayanDutta001/Competitive-Programming-Codes | /Algorithms/merge_sorted_arrays.py | 494 | 3.984375 | 4 | def mergesortarr(nums1, m, nums2, n):
for i in range(n-1, -1, -1):
last = nums1[m-1]
j = m-2
while(j>=0 and nums1[j]>nums2[i]):
nums1[j+1] = nums1[j]
j-=1
if(j!=m-2 or last>nums2[i]):
nums1[j+1] = nums2[i]
nums2[i] = last
return nums1, nums2
test = int(input())
for i in range(test):
m = int(input())
nums1 = list(map(int, input().split()))
n = int(input())
nums2 = list(map(int, input().split()))
print(mergesortarr(nums1, m, nums2, n))
|
1923254261c989086badc13750a92c987b34b9ee | SayanDutta001/Competitive-Programming-Codes | /Coursera Algorithmic Toolbox/Week 3/money_change.py | 201 | 3.625 | 4 | def change(n):
coins = [10, 5, 1]
i = 0
count = 0
while(n>0):
if(n>=coins[i]):
n -= coins[i]
count += 1
else:
i += 1
return count
n = int(input())
print(change(n))
|
06e3854ec42cb507701909da375a8e2f6dc62ab7 | Pissuu/6thsempython | /simplecalc.py | 480 | 4.15625 | 4 | print("simple calculator")
print(" enter 1 for *")
print(" enter 2 for /")
print(" enter 3 for +")
print(" enter 4 for -")
choice=int(input())
ans=int
a1=int(input("enter first argument"))
a2=int(input("enter second argument"))
if choice==1:
ans=a1*a2
print("answer is:",ans)
if choice==2:
ans=a1/a2
print("answer is:",ans)
if choice==3:
ans=a1+a2
print("answer is:",ans)
if choice==4:
ans=a1-a2
print("answer is",ans)
|
fd37896e22abf2ab449d255d120b23cc474219b8 | Papergoal/Python | /main.py | 2,902 | 3.515625 | 4 | from tkinter import *
import Bus
import Eleve
import Prof
root = Tk()
root.title("Bus")
root.geometry("500x400")
listBus = []
# Fonction de création d'un Bus
def BusCrea():
b = Bus.Bus(len(listBus))
listBus.insert(len(listBus), 1)
BBus = Button(root, text="Bus "+str(b.getNumBus()), command=lambda: View(b))
Label(root, text="Bus "+str(b.getNumBus()))
BBus.grid(row=1, column=int(b.getNumBus())+3)
#Page qui affiche les boutons pour ajouter des élèves ou des étudiants au bus sélectionné
def View(b):
win = Toplevel(root)
win.title("ajout eleve / prof")
Verife = Button(win, text="vérifier que le bus peut partir", command=lambda: verification(win, b)).pack()
Label(win, text="---------------").pack()
nomProf = Entry(win)
nomProf.pack()
addProf = Button(win, text="ajouter le prof", command=lambda: ajoutProf(nomProf.get(), b)).pack()
Label(win, text="---------------").pack()
nomEleve = Entry(win)
nomEleve.pack()
nomEleve.insert(0, "Le nom de l'éleve")
label = Label(win, text=nomEleve.get()).pack()
classeEleve = Entry(win)
classeEleve.pack()
addEleve = Button(win, text="ajouter l'éléve",command=lambda: ajoutEleve(nomEleve.get(), classeEleve.get(), b)).pack()
#vérifie si le bus peut partir
def verification(win, b):
if int(len(b.Eleves)+len(b.Prof)) > 0:
label = Label(win, text=b.verifierPresent()).pack()
#permet d'ajouter un élève et de l'afficher en dessou du bus
def ajoutEleve(nom, classe, b):
if int(len(b.Eleves)+len(b.Prof)) < int(b.Place) and int(len(b.Eleves)) < int(len(b.Prof))*10 and classe != "":
if b.verifierClasse(classe) == 1:
e = Eleve.Eleve(nom, classe)
b.addEleve(e)
b.attribEleve(e)
btEleve = Button(root, text=nom, bg="white", command=lambda: elevePresent(e, root)).grid(row=int(len(b.Eleves))+int(len(b.Prof)+1), column=int(b.getNumBus())+3)
#la même chose que pour la fonction ajoutEleve mais pour les profs
def ajoutProf(nom, b):
if int(len(b.Eleves)+len(b.Prof)) < int(b.Place):
p = Prof.Prof(nom)
b.addProf(p)
if int(len(b.Prof)) ==1:
buttonProf = Label(root, text=nom, bg="red").grid(row=int(len(b.Eleves)) + int(len(b.Prof) + 1), column=int(b.getNumBus())+3)
else:
buttonProf = Label(root, text=nom, bg="yellow").grid(row=int(len(b.Eleves)) + int(len(b.Prof) + 1), column=int(b.getNumBus())+3)
#passe un élève au statut présent
def elevePresent(e, root):
e.present = 1
#fonction pour changer la couleur du bouton lorsqu'un élève est mis présent (ne marche pas)
#def change_color(root):
# root.btEleve.configure(bg="green")
Button(root, text="Ajouter un Bus", command=BusCrea).grid(row=0, column=0)
Label(root, text="Pour mettre présent un élève cliquez dessus").grid(row=0, column=1)
root.mainloop() |
217ba2b37fb99fafaea0610494b8fd6739d8aa4f | sachinrajeev/Python | /Sachin R/PI.py | 331 | 3.5625 | 4 | #!/usr/bin/py
# print value of PI to a count
import sys
if(len(sys.argv)==1)
print("atleast one input")
exit()
try:
# Convert it into int
val = int(sys.argv[1])
except ValueError:
print("No.. input is not a number.")
exit()
print("%.nf" % (22/7))
|
64eb687f86c87317c7eca6052693ed120c510d60 | mhaetinger/python_ex | /ex022.py | 562 | 3.96875 | 4 | print('=====EXERCÍCIO 22=====')
name = str(input('Digite seu nome completo: ')).strip()
print('Analisando seu nome...')
print('Seu nome em letras maiúsculas é {}'.format(name.upper()))
print('Seu nome em letras minúsculas é {}'.format(name.lower()))
print('Seu nome todo tem {} letras'.format(len(name.replace(' ', ''))))
#print('Seu nome todo tem {} letras'.format(len(name) - name.count(' ')))
print('Seu primeiro nome é {} e tem {} letras'.format((name.split()[0]), len(name.split()[0])))
# para achar o primeiro nome pode se usar name.find(' ') |
ce4aa17426e8fe8b1b4cb93576b72a8acbfc4b16 | mhaetinger/python_ex | /ex030.py | 168 | 4.125 | 4 | print('=====EXERCÍCIO 30=====')
n = int(input('Insert a number: '))
o = n % 2
if o == 0:
print('You number is even!')
else:
print('You number is odd!')
|
7758e77538ef027d140f983941c5b0797f149c8d | mhaetinger/python_ex | /ex016.py | 163 | 3.796875 | 4 | import math
print('=====EXERCÍCIO 16=====')
n = float(input('Digite um número: '))
print('A porção inteira de {} é igual a {}!'.format(n, math.trunc(n)))
|
d6006c5805dc251f4001f02dcbaafda1ef5c01fb | mhaetinger/python_ex | /ex011.py | 236 | 3.6875 | 4 | print('=====EXERCÍCIO 11=====')
la = float(input('Qual a largura da parede? '))
a = float(input('Qual a altura da parede? '))
area = la * a
print('Será necessário {} litros de tintas para pintar {}ms².'.format((area/2), area))
|
50c534c74d055dfa1a4951bd00aec6c804ff75d9 | ToniCorinne/MathFun | /1.py | 166 | 3.765625 | 4 | multiples = 0
for x in range(0,1000):
y = x%3
z = x%5
if y == 0 or z ==0:
multiples = multiples + x
print 'Multiples of 3 and 5 below 1000 summed = ', multiples |
964d8b7225214f956b021b74c279971251e43590 | bpeak/practice-algo | /codesignal/palindrome.py | 322 | 3.6875 | 4 | def checkPalindrome(inputString):
start = 0
end = len(inputString) - 1
while start <= end:
if inputString[start] != inputString[end]:
return False
start += 1
end -= 1
return True
print(checkPalindrome('aabaa'))
print(checkPalindrome('abac'))
print(checkPalindrome('a')) |
97e7312cb54c4972775edfa50c5f90fe56334944 | bpeak/practice-algo | /algobook/왕실의나이트.py | 675 | 3.5625 | 4 | def solution(pos):
col_map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
x = col_map.index(pos[0]) + 1
y = int(pos[1])
directions = ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2))
count = 0
for dx, dy in directions:
next_x = x + dx
next_y = y + dy
if next_x <= 8 and \
next_x >= 1 and \
next_y <= 8 and \
next_y >= 1:
count += 1
return count
print(solution('a1'))
print(solution('c2'))
# cf map없이 아스키테이블 이용해서 x 구하는 방법도 있음
"""
char1 = 'a'
char2 = 'c'
print(ord(char1) - ord('a'))
print(ord(char2) - ord('a'))
""" |
e1760ffce796a0b082592366ac6df6aa0b2735b6 | bpeak/practice-algo | /programmers/문자열최대최소.py | 257 | 3.6875 | 4 | def solution(numbers_string):
numbers = [int(v) for v in numbers_string.split(" ")]
max_number = max(numbers)
min_number = min(numbers)
return f'{str(min_number)} {str(max_number)}'
print(solution('1 2 3 4'))
print(solution('-1 -2 -3 -4')) |
6068c1a8dea9762d8c6943cf0525bc08a399bd68 | bpeak/practice-algo | /programmers/두개뽑아서더하기.py | 238 | 3.78125 | 4 | def solution(numbers):
result = set()
for i in range(0, len(numbers) - 1):
for j in range(i + 1, len(numbers)):
result.add(numbers[i] + numbers[j])
return sorted(list(result))
print(solution([2,1,3,4,1]))
|
e417541797f11e0b9e9d03ccae7d0d9229c247fb | bpeak/practice-algo | /algobook/게임개발.py | 2,152 | 3.578125 | 4 | DIRECTION_TOP = 0
DIRECTION_RIGHT = 1
DIRECTION_BOTTOM = 2
DIRECTION_LEFT = 3
def solution(matrix, y, x, direction):
# 현재위치
curr_x = x
curr_y = y
visited = set()
visited.add((curr_y, curr_x))
while True:
for i in range(4):
# -90도 회전
direction -= 1
if direction == -1:
direction = DIRECTION_LEFT
temp_x = curr_x
temp_y = curr_y
if direction == DIRECTION_TOP:
temp_y -= 1
elif direction == DIRECTION_RIGHT:
temp_x += 1
elif direction == DIRECTION_BOTTOM:
temp_y += 1
elif direction == DIRECTION_LEFT:
temp_x -= 1
if temp_y >= 0 and \
temp_y <= len(matrix) - 1 and \
temp_x >= 0 and \
temp_x <= len(matrix[0]) - 1 and \
matrix[temp_y][temp_x] == 0 and \
(temp_y, temp_x) not in visited:
# 이동
curr_x = temp_x
curr_y = temp_y
visited.add((curr_y, curr_x))
break
else:
# 뒤로이동 ( 반대방향 ex>TOP이면 BOTTOM으로 )
temp_x = curr_x
temp_y = curr_y
if direction == DIRECTION_TOP:
temp_y -= 1
elif direction == DIRECTION_RIGHT:
temp_x += 1
elif direction == DIRECTION_BOTTOM:
temp_y += 1
elif direction == DIRECTION_LEFT:
temp_x -= 1
if temp_y >= 0 and \
temp_y <= len(matrix) - 1 and \
temp_x >= 0 and \
temp_x <= len(matrix[0]) - 1 and \
matrix[temp_y][temp_x] == 0:
# 이동
curr_x = temp_x
curr_y = temp_y
visited.add((curr_y, curr_x))
else:
return len(visited)
print(solution([
[1,1,1,1],
[1,0,0,1],
[1,1,0,1],
[1,1,1,1],
], 1, 1, 0)) |
c47c7406cc3f14e1d39b2ec58b755570a18a32cf | bpeak/practice-algo | /programmers/문자열압축.py | 1,756 | 3.5625 | 4 | def solution(s):
len_s = len(s)
result = len_s
for compress_char_count in range(1, (len_s // 2) + 1):
curr_result = 0
number_of_looping = len_s // compress_char_count if len_s % compress_char_count == 0 else len_s // compress_char_count + 1
curr_compress_target_str = s[0:compress_char_count]
curr_compress_target_str_count = 1
compressed_str = ""
for i in range(1, number_of_looping):
curr_str = s[compress_char_count*i:compress_char_count*(i + 1)]
if curr_str == curr_compress_target_str:
curr_compress_target_str_count += 1
else:
compressed_str += ("" if curr_compress_target_str_count == 1 else str(curr_compress_target_str_count)) \
+ curr_compress_target_str
curr_compress_target_str_count = 1
curr_compress_target_str = curr_str
else:
compressed_str += ("" if curr_compress_target_str_count == 1 else str(curr_compress_target_str_count)) \
+ curr_compress_target_str
if(len(compressed_str) < result):
result = len(compressed_str)
return result
print(solution("aabbaccc")) # 7
print(solution("ababcdcdababcdcd")) # 9
print(solution("abcabcdede")) # 8
print(solution("abcabcabcabcdededededede")) # 14
print(solution("xababcdcdababcdcd")) # 17
"""
포커싱할 문자열 갯수 ( 1 ~ n )
문자열을 포커싱할 문자열 갯수로 나눈 몫 만큼 루핑
1. 포커스 문자를 가져옴 ( 기준 )
2. 다음 문자를 가져옴
같음 => 카운팅
다름 => 카운팅 된 횟수만큼 빌드하고 1. 로
루핑 이후 else 로 정리
""" |
a6db3454e3823a0730eff14fbfc6fc7fd6259eac | bpeak/practice-algo | /leetcode/build-an-array-with-stack-oper.py | 1,153 | 3.6875 | 4 | class Solution:
def buildArray(self, target, n):
if len(target) == 0:
return []
result = [1]
stack = ["Push"]
if target == result:
return stack
for i in range(2, n + 1):
if result[len(result) - 1] not in target:
result.pop()
stack.append("Pop")
stack.append("Push")
result.append(i)
if target == result:
return stack
s = Solution()
print(s.buildArray([1,3],3))
print(s.buildArray([2, 3, 4],4))
# best
# 없으면 바로 빼면 되잖아.
class Solution2:
def buildArray(self, target, n):
if len(target) == 0:
return []
result = [1]
action = ["Push"]
if target == result:
return action
for i in range(2, n + 1):
if result[len(result) - 1] not in target:
result.pop()
action.append("Pop")
result.append(i)
action.append("Push")
if target == result:
return action
solution2=Solution2() |
dd415534023f420ee509261c42b44510ed2644b0 | bpeak/practice-algo | /algobook/BFS.py | 918 | 3.578125 | 4 | from collections import deque
def dfs(graph, start_v):
queue = deque()
queue.append(start_v)
visited = set()
visited.add(start_v)
while len(queue) != 0:
v = queue.popleft()
print(f'{v}')
for adj_v in graph[v]:
if adj_v not in visited:
queue.append(adj_v)
visited.add(adj_v)
dfs([
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7],
], 1)
def dfs_(graph, start_v):
queue = deque()
visited = [False] * 9
queue.append(start_v)
visited[start_v] = True
while len(queue) != 0:
v = queue.popleft()
print(f'{v}')
for v_ in graph[v]:
if not visited[v_]:
queue.append(v_)
visited[v_] = True
abc = 3333333333
def a():
print(abc)
abc = 2322
pass
a() |
4754d136c5827474f7a530d8b8fd8e942a12949b | bpeak/practice-algo | /codesignal/minesweeper.py | 902 | 3.640625 | 4 | def minesweeper(matrix):
result = []
for r in range(0, len(matrix)):
result_row = []
for c in range(0, len(matrix[r])):
s = 0
for dr, dc in ((-1, 1), (0, 1), (1, 1), (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0)):
if r + dr < 0 or c + dc < 0: continue
try:
s += matrix[r + dr][c + dc]
except:
continue
result_row.append(s)
result.append(result_row)
return result
print(minesweeper([
[True, False, False],
[False, True, False],
[False, False, False]])) # [[1, 2, 1], [2, 1, 1], [1, 1, 1]]
print(minesweeper([
[True,False,False,True],
[False,False,True,False],
[True, True, False, True]]))
"""
const directions = [
[ 1,-1], [ 1, 0], [ 1, 1],
[ 0,-1], [ 0, 1],
[-1,-1], [-1, 0], [-1, 1]
];
""" |
c6cfbb026c1deb38e4beeea686b6eb871cf46e89 | bpeak/practice-algo | /algobook/이진탐색.py | 1,089 | 3.8125 | 4 | arr = [1,3,6,7,8,10,34,44,33,22,4,46,55,2,32,5]
arr.sort()
def sequential_search(arr, target):
for i, v in enumerate(arr):
# print('s')
if target == v:
return i
else:
return -1
def binary_search(arr, target, start=0, end=len(arr) - 1):
# print('b')
if start > end :
return -1
mid = ( start + end ) // 2
if target == arr[mid]:
return mid
if target < arr[mid]:
return binary_search(arr, target, start, mid - 1)
else:
return binary_search(arr, target, mid + 1, end)
def binary_search2(arr, target):
start = 0
end = len(arr) - 1
while start <= end:
# print('b2')
mid = ( start + end ) // 2
if target == arr[mid]:
return mid
if target < arr[mid]:
end = mid - 1
else:
start = mid + 1
return -1
print(arr)
print(sequential_search(arr, 44))
print(binary_search(arr, 44))
print(binary_search2(arr, 44))
print(sequential_search(arr, 444))
print(binary_search(arr, 444))
print(binary_search2(arr, 444)) |
58310fc55f882795c52c5b4d7d20634e355365b1 | bpeak/practice-algo | /codesignal/sortByHeight.py | 331 | 3.96875 | 4 | from collections import deque
def sortByHeight(arr):
heights = deque(sorted([v for v in arr if v != -1]))
result = []
for v in arr:
if v == -1:
result.append(-1)
else:
result.append(heights.popleft())
print(result)
print(sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180])) |
431b7ea889ccd70795be88f442bb4c37dd502972 | AthithyaJ/Data-Structures | /trees.py | 790 | 3.671875 | 4 | class Node:
def __init__(self, cargo):
self.cargo = cargo
self.left = None
self.right = None
def check(n):
if n is 'y':
return True
elif n is 'n':
return False
def animal_tree():
ans = input('Are you thinking of an animal?')
if check(ans):
tree = Node('animal')
x = input('Can it fly?')
if check(x):
ba = Node('bird')
tree.left = ba
else:
ma = Node('Land Animal')
tree.right = ma
pro = input('Can the animal bark?')
if check(pro):
do = Node('dog')
ma.left = do
n = input('Is it a dog?')
check(n)
else:
ca = Node('cat')
ma.right = ca
animal_tree()
|
fe91ae90b39080d9df1a574a597e56636bade209 | FatemaSaifee/How-to-solve-it-by-computer-R.G.Dromey | /5.5.2.py | 2,665 | 3.640625 | 4 | # for n/2,n/4,....
def shellsort2(a):
n = len(a)
inc = 0 #steps at which elements are to be sorted
current = 0 #position in chain where x is finally inserted
previous = 0 #indexof elemnet currently begin compared with x
j = 0 #index of lowest elemnt in current chan being sorted
k = 0 #idex of current element bieng inserted
x = 0 #curent value to be inserted
inserted = True #true if insertion can be made
ctr = 0
assert n > 0
inc = n
while inc > 1:
inc = inc / 2
for j in range(1, inc + 1):
k = j + inc
while k <= n :
inserted = False
#print "in while"
x = a[k-1]
current = k
previous = current - inc
while (previous >= j) and not inserted:
if x < a[previous-1]:
a[current-1] = a[previous-1]
current = previous
previous -= inc
#print "in while inner"
else:
inserted = True
ctr += 1
a[current-1] = x
k += inc
print a
print ctr
#for 2^p,...,31,15,7,3,1
def shellsort1(a):
n = len(a)
inc = 0 #steps at which elements are to be sorted
current = 0 #position in chain where x is finally inserted
previous = 0 #indexof elemnet currently begin compared with x
j = 0 #index of lowest elemnt in current chan being sorted
k = 0 #idex of current element bieng inserted
x = 0 #curent value to be inserted
inserted = True #true if insertion can be made
ctr = 0
assert n > 0
inc = n
while inc > 1:
inc = inc / 2 - 1
for j in range(1, inc + 1):
k = j + inc
while k <= n :
inserted = False
#print "in while"
x = a[k-1]
current = k
previous = current - inc
while (previous >= j) and not inserted:
if x < a[previous-1]:
a[current-1] = a[previous-1]
current = previous
previous -= inc
#print "in while inner"
else:
inserted = True
ctr +=1
a[current-1] = x
k += inc
print a
print ctr
a = [1,2,4,54,32,42,4,5,3,2,2,4243,31,43,42,124,4,5,2,4,56,7,5,76]
print "with n/2,n/4..."
shellsort2(a)
print "with 2^p-1,....7,3,1"
shellsort1(a)
#we observe shellsort1 is better!!!!"
|
5a5b87c470cb7a4baa0f11b5bf016fd9191a447c | sysread/py-skewheap | /skewheap/__init__.py | 5,672 | 3.9375 | 4 | import asyncio
def merge_nodes(a, b):
"""Recursively and non-destructively merges two nodes. Returns the newly
created node.
"""
if a is None:
return b
if b is None:
return a
if a[0] > b[0]:
a, b = b, a
return a[0], merge_nodes(b, a[2]), a[1]
def pop_node(root):
"""Removes the top element from the root of the tree. Returns the element
and the merged subtrees.
"""
item, left, right = root
return item, merge_nodes(left, right)
def explain_node_str(root, indent=0):
"""Returns an indendeted outline-style representation of the subtree.
"""
indent_string = " " * indent
buf = f"{indent_string}Node<item={root[0]}>"
if not root[1] and not root[2]:
buf += "\n"
else:
buf += ":\n"
if root[1]:
buf += f"{indent_string} -Left:\n"
buf += explain_node_str(root[1], indent + 1)
if root[2]:
buf += f"{indent_string} -Right:\n"
buf += explain_node_str(root[2], indent + 1)
return buf
class SkewHeap:
"""A skew heap is a min heap or priority queue which ammortizes the cost of
rebalancing using an elegant merge algorithm. All operations on a skew heap
are defined in terms of the merge algorithm.
An interesting side effect of this is that skew heaps can be quickly and
easily merged non-destructively.
Items added to the heap will be returned in order from lowest to highest.
To control the ordering, implement __gt__ on the class of the items being
inserted.
"""
def __init__(self):
self.size = 0
self.root = None
def __repr__(self):
buf = f"SkewHeap<size={self.size}>:\n"
if self.root is None:
buf += " (Empty)"
else:
buf += explain_node_str(self.root, 1)
return buf
def __str__(self):
return self.__repr__()
@classmethod
def merge(cls, *heaps):
"""Non-destructively merges *heaps into a single, new heap. Returns the
new heap.
newheap = SkewHeap.merge(a, b, c, ...)
"""
c = SkewHeap()
for h in heaps:
c.size += h.size
c.root = merge_nodes(c.root, h.root)
return c
@property
def is_empty(self):
"""Returns True if there are no elements in the heap.
"""
return self.size == 0
def put(self, *args):
"""Adds one or more new elements to the heap. Returns the heap's new
size.
"""
for item in args:
self.root = merge_nodes(self.root, [item, None, None])
self.size = self.size + 1
return self.size
def take(self):
"""Removes and returns the top element from the heap. Returns None
if the heap is empty.
"""
if self.is_empty:
return None
self.size = self.size - 1
item, self.root = pop_node(self.root)
return item
def peek(self):
"""Returns the top element from the heap without removing it. Returns
None if the heap is empty.
"""
if self.is_empty:
return None
return self.root[0]
def adopt(self, *heaps):
"""Merges the elements from additional heaps into this one. The other
heaps are left intact.
"""
for h in heaps:
self.size += h.size
self.root = merge_nodes(self.root, h.root)
return self.size
def items(self):
"""Returns a generator of elements in the heap.
"""
while not self.is_empty:
yield self.take()
def drain(self):
"""Removes and returns all elements from the heap as a list.
"""
items = []
while not self.is_empty:
items.append(self.take())
return items
class AsyncSkewHeap:
"""A SkewHeap whose contents can be accessed asynchronously. Calls
to take() will block until an element is available.
"""
def __init__(self):
super().__init__()
self.heap = SkewHeap()
self.ev = asyncio.Event()
self.sem = asyncio.Semaphore(0)
@property
def is_empty(self):
"""True when the heap is empty."""
return self.heap.is_empty
@property
def is_shutdown(self):
"""True once the heap has been shutdown with shutdown()."""
return self.ev.is_set()
def shutdown(self):
"""Shutting down the heap will awaken all pending calls to take(),
returning None to them. Future callers to take() will receive immediate
results. Items may still be added to the heap, but it will no longer
block when calling take().
"""
self.ev.set()
async def join(self):
"""Blocks until the queue has been shut down."""
if not self.is_shutdown:
await self.ev.wait()
async def take(self):
"""Returns the next item in the queue, blocking until one is available
if necessary.
"""
if self.is_shutdown:
return self.heap.take()
async with self.sem:
return self.heap.take()
def put(self, *args):
"""Adds any number of items to the queue."""
for item in args:
self.heap.put(item)
if not self.is_shutdown:
self.sem.release()
def adopt(self, *heaps):
"""Merges other heaps into this one. The other heaps are left intact.
"""
prev_size = self.heap.size
self.heap.adopt(*heaps)
for _ in range(0, self.heap.size - prev_size):
self.sem.release()
|
4eb03facdfc14f3d9c0fe06eeba4e7204166c71d | ngflanders/Project-Euler-Problems | /ProblemsPack/Fourteen.py | 1,223 | 3.765625 | 4 | '''
The following iterative sequence is defined for the set of positive integers:
n : n/2 (n is even)
n : 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 : 40 : 20 : 10 : 5 : 16 : 8 : 4 : 2 : 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
'''
def isEven(n):
return n/2
def isOdd(n):
return 3*n+1
def createSeq(start):
iCount = 2
if (start % 2 == 0):
nxt = isEven(start)
else:
nxt = isOdd(start)
while (nxt != 1):
if (nxt % 2 == 0):
nxt = isEven(nxt)
else:
nxt = isOdd(nxt)
iCount +=1
return iCount
print(createSeq(13))
def seqrange(topend):
longest = 0
startnum = 0
for i in range(1, topend):
leng = createSeq(i)
if leng > longest:
longest = leng
startnum = i
return (longest,startnum)
print(seqrange(1000000)) |
1fe49fc553fed25d876a6354c2345f5c995da58b | ngflanders/Project-Euler-Problems | /ProblemsPack/TwentyFive.py | 888 | 4.03125 | 4 | '''
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
'''
import math
def Fibon(numofdigits=1000):
Fibn = [1, 2] #declaring the list
first = 1
second = 2
x = first + second # add the two previous numbers together
digits = 1
while (digits) < numofdigits: # Fib number up to 4 million
Fibn.append(x) # add Fib number to the list
first = second
second = x
x = first + second
digits = int(math.log10(x))+1
#print(Fibn)
return(len(Fibn)+2)
print(Fibon())
|
487724cadc155347f42d429bbf180d7dffa64b24 | zhouzonglong/ldanew | /python面试宝典/8排序/8.7堆排序.py | 941 | 4.03125 | 4 | import sys
'''
for i in range(0,int((size/2)))[::-1]:
后面【::-1】那么i从最后一个数开始
'''
def adjuct_heap(lists,i,size):
lchild=2*i+1
rchild=2*i+2
maxs=i
if i<size/2:
if lchild<size and lists[lchild]>lists[maxs]:
maxs=lchild
if rchild<size and lists[rchild]>lists[maxs]:
maxs=rchild
if maxs!=i:
lists[maxs],lists[i]=lists[i],lists[maxs]
adjuct_heap(lists,maxs,size)
def buile_heap(lists,size):
for i in range(0,int((size/2)))[::-1]:
adjuct_heap(lists,i,size)
print(lists)
def heap_sort(lists):
size=len(lists)
buile_heap(lists,size)
print('--------------------------------')
for i in range(0,(size))[::-1]:
lists[0],lists[i]=lists[i],lists[0]
adjuct_heap(lists,0,i)
print(lists)
list=[1,2,3,4,5,6,7,8]
print('原始数据:')
print(list)
heap_sort(list)
# print(list)
|
1539c11c5fb4bbfe67cb7ecc0ce0372a2b226b9d | zhouzonglong/ldanew | /python面试宝典/6基本数字运算/6.10求二进制中1的个数.py | 386 | 3.6875 | 4 | '''
方法一:移位法
'''
def getCount(n):
count=0
while n>0:
if (n&1)==1:
count+=1
n=n>>1
return count
print(getCount(10))
'''
方法二:与操作 n&(n-1)---->使得n的二进制1少一个
'''
def get_count(n):
count=0
while n>0:
if n!=0:
n=n&(n-1)
count+=1
return count
print(get_count(10))
|
002fa1b3ad18f742f2b1b23b2e8ad8d81a1a0c63 | zhouzonglong/ldanew | /python面试宝典/8排序/8.6希尔排序.py | 689 | 4.0625 | 4 | def shell_sort(lists):
count = len(lists)
step=2
group=count/step
group_int=int(group)
while group_int>0:
lists=setorss(lists,group_int)
group_int=int(group_int/step)
return lists
def setorss(lists,group):
for i in range(0,group):
count=len(lists)
j=i+group
while j<count:
k=j-group
key=lists[j]
while k>=0:
if lists[k]>key:
lists[k+group]=lists[k]
lists[k]=key
k-=group
j+=group
print(lists)
return lists
list=[7,6,5,4,3,2,1,0]
print('原始数据:')
print(list)
print(shell_sort(list)) |
7fa03342bdd06dd79233885bc3ed7d4240457ecc | zhouzonglong/ldanew | /python面试宝典/4数组/4.16规律的数组查找数x.py | 514 | 3.703125 | 4 | import numpy as np
def findX(arr,x):
m,n=np.array(arr).shape
m-=1
n-=1
j=0
if x<arr[0][0] or x>arr[m][n]:
return False
else:
while n>=0 and j<=m:
if arr[j][n]==x:
return True
elif x>arr[j][n]:
j+=1
else:
n-=1
return False
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print(np.array(arr))
print(findX(arr,1))
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]
# [13 14 15 16]] |
5d0422a6853172deb4480d3db9038c17503f2253 | zhouzonglong/ldanew | /python面试宝典/7排列组合/用122345排列.py | 1,570 | 3.703125 | 4 | '''
要求4不在第三位,3,5不相邻
'''
'''
采用图的方式
'''
class Test:
def __init__(self,arr):
self.number=arr #arr=[1,2,2,3,4,5]
self.visited=[None]*len(self.number)
self.graph=[[None]*len(self.number) for i in range(len(self.number))]
self.n=6
# self.visited=None
# self.graph=None
self.combination=''
self.s=set()
def depthFirstSearch(self,start):
self.visited[start]=True
self.combination+=str(self.number[start])
if len(self.combination)==self.n:
if self.combination.index('4')!=2:
self.s.add(self.combination)
j=0
while j<self.n:
if self.graph[start][j]==1 and self.visited[j]==False:
self.depthFirstSearch(j)
j+=1
self.combination=self.combination[:-1]
self.visited[start]=False
def getAllCombination(self):
i=0
while i<self.n:
j=0
while j<self.n:
print(self.graph[i][j])
if i==j:
print(self.graph[i][j])
self.graph[i][j]=0
else:
self.graph[i][j]=1
j+=1
i+=1
self.graph[3][5]=0
self.graph[5][3]=0
i=0
while i <self.n:
self.depthFirstSearch(i)
i+=1
def printAll(self):
for strs in self.s:
print(strs)
arr=[1,2,2,3,4,5]
t=Test(arr)
t.getAllCombination()
t.printAll() |
fb4d5d08c2d731bdf6a56f08cc40cbc1f6b461f5 | zhouzonglong/ldanew | /python面试宝典/4数组/4.10求数组中连续最大和.py | 1,154 | 3.609375 | 4 | '''
方法一:两重循环
'''
def maxSubArry(arr):
if arr==None or len(arr)<1:
return
maxSum=-2**31
i=0
while i<len(arr):
sums=0
j=i
while j<len(arr):
sums+=arr[j]
if sums>maxSum:
maxSum=sums
j+=1
i+=1
return maxSum
arr=[1,-2,4,8,-4,7,-1,-9,-8,-5,10,-1]
# print(maxSubArry(arr))
'''
方法二:动态规划
'''
def maxSubArry2(arr):
n=len(arr)
End=[None]*n
All=[None]*n
End[n-1]=arr[n-1]
All[n - 1] = arr[n - 1]
End[0]=All[0]=arr[0]
i=1
while i<n:
End[i]=max(End[i-1]+arr[i],arr[i])
All[i]=max(End[i],All[i-1])
print('arr' + str(arr))
print('End'+str(End))
print('All'+str(All))
print('------------------------------------------')
i+=1
return All[n-1]
# print(maxSubArry2(arr))
'''
方法三:优化动态规划
'''
def maxSubArry3(arr):
n=len(arr)
End=All=arr[0]
i=1
while i<n:
End=max(End+arr[i],arr[i])
All=max(End,All)
i+=1
return All
print(maxSubArry3(arr))
'''
找出起始和终止位置
'''
|
bcfd71b0af0e0e40ee9dc8640272b40b61cace79 | Bertkiing/python_learn | /python_func.py | 723 | 3.90625 | 4 |
#无参无返回值
def printHi():
print("Hello,world")
#单参无返回值
def printName(name):
print(name)
# 单参且有返回值
def add(a,b):
return a + b
#测试用例
print(add(4,4))
print(add("Hello","world"))
def intersect(seq1,seq2):
res = []
for x in seq1:
if(x in seq2):
res.append(x)
return res
#测试用例
print(intersect("SPAM","SCAM"))
print(intersect([1,2,3],[3,6]))
def intersect2(s1,s2):
#列表解析表达式
res = [x for x in s1 if x in s2]
return res
print(intersect2("SPAM","SCAM"))
print(intersect2([1,2,3],[2,4]))
#很容易看出上面的函数是——多态的,
# 即:它可以支持多种类型,只要支持扩展对象接口 |
1883995b5365f16305697eff2c4b16ffd1850ad7 | Bertkiing/python_learn | /YouTube/high_level/exception_28.py | 511 | 3.875 | 4 | # age = int(input("What' your fav number?\n"))
# print(age)
"""
很显然,Python中的异常处理关键字没有catch:
try , except , finally
"""
while True:
try:
number = int(input("What is your fav number\n"))
print(18 / number)
break
except ZeroDivisionError:
print("division by zero")
except ValueError:
print("Make sure and enter a number")
except:
print("unknown error !!!")
break
finally:
print("loop complete")
|
c5c7446c3c56c977c3080a9178ab1ae518318d0a | NekohimeMusou/advent-of-code | /day3/part_2.py | 1,335 | 3.75 | 4 | from day3.claim import Claim
from day3.part_1 import INPUT_PATH
def main():
claims = get_input()
unique_claim = find_non_overlapping_claim(claims)
print('Non-overlapping Claim:', unique_claim)
def get_input(path=INPUT_PATH):
"""Get the problem input from the data file.
Reads the file line by line and builds a dict by calling the factory method on
Claim. Invalid claims are filtered out. The keys are the claim IDs.
Params:
path - Path to input file"""
with open(path) as f:
claims = [Claim.from_string(line) for line in f]
return {claim.claim_id: claim for claim in claims if claim is not None}
def find_non_overlapping_claim(claims):
"""Find the claim that doesn't overlap any others, if any.
claims - a dict of claims with claim IDs as keys"""
for claim_id_1, claim_1 in claims.items():
for claim_id_2, claim_2 in claims.items():
# If there's even one overlap, we can stop the inner loop
if claim_id_1 != claim_id_2 and claim_1.intersects(claim_2):
break
else:
# If iteration completed without breaking, we have a winner
return claim_id_1
# If we exhausted all the claims without finding a unique one, there are none
return None
if __name__ == '__main__':
main()
|
0164cbe451903aaf9adca954f6457f14ac92be0f | NekohimeMusou/advent-of-code | /day2/part_2.py | 1,289 | 3.625 | 4 | from itertools import combinations
INPUT_PATH = "input.txt"
SAMPLE_DATA = ['abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz']
def main():
lines = get_input()
prototype_string = find_prototype_string(lines)
print('The prototype string is:', prototype_string)
def get_input(path=INPUT_PATH):
with open(path) as f:
# There shouldn't be any duplicates but this will filter any out
return set(f.readlines())
def find_prototype_string(id_list):
"""Find the two box ids that contain the prototype fabric.
Returns the common characters between the two box IDs.
Params:
id_list -- a sequence containing ids to check, which should be unique strings
"""
# combinations gives us every combination of n items from the list. Perfect! <3
for id_1, id_2 in combinations(id_list, 2):
mismatches = []
for i in range(len(id_1)):
if id_1[i] != id_2[i]:
if mismatches: # We already found a mismatch
break
mismatches.append(i)
else:
# Only reached if we finish with 1 mismatch
n = mismatches[0]
return ''.join((id_1[0:n], id_1[n+1:len(id_1)]))
return None
if __name__ == "__main__":
main()
|
ea21f9827da0570d626bf086ae1eecf06620d134 | NekohimeMusou/advent-of-code | /day1/frequency.py | 1,642 | 4 | 4 | from itertools import cycle
INPUT_PATH = "input.txt"
def main():
lines = get_input()
final_freq = calc_final_frequency(lines)
first_rep = find_repetition(lines)
print("Ending frequency: {0}\nFirst frequency repeated twice: {1}".format(final_freq, first_rep))
# Open the input file and convert each line to a number.
# int() strips whitespace and understands the + symbol
def get_input(path=INPUT_PATH):
with open(path) as f:
# This here's a list comprehension
return [int(x) for x in f.readlines()]
# Calculate the final frequency after all changes in the list.
# Since our starting frequency is known and the operations are transitive
# we can just sum the array for this
def calc_final_frequency(delta_list, initial_freq=0):
return sum(delta_list, initial_freq)
def find_repetition(delta_list, initial_freq=0):
# If I needed to find the nth repetition instead of the 2nd I would use a dict
freqs_tested = {initial_freq}
current_freq = initial_freq
# itertools.cycle gives us a generator that works like an infinitely-repeating list
# This won't actually loop forever since we return when we find our target
for delta in cycle(delta_list):
current_freq += delta
if current_freq in freqs_tested:
# If it's already in the set, this is the second time we've seen it
return current_freq
else:
freqs_tested.add(current_freq)
def time():
import timeit
reps = 1000
output = timeit.timeit('main()', globals=globals(), number=reps)
print(output / reps)
if __name__ == "__main__":
main()
|
c9ffe2d4c402350c820e9de2459699ec65170f85 | sahilthapar/devprep | /data_structures/tests.py | 2,621 | 3.6875 | 4 | import unittest
from linked_list import LinkedList
from stack import StackArray, StackLinkedList
from queue import QueueArray, QueueLinkedList
from binary_tree import BinaryTree
class Test(unittest.TestCase):
def test_linked_list(self):
self.lnk_lst = LinkedList()
self.lnk_lst.append(1)
self.lnk_lst.append(2)
self.lnk_lst.append(3)
self.lnk_lst.delete(3)
self.lnk_lst.prepend(4)
self.lnk_lst.delete(2)
self.assertEqual(self.lnk_lst.toArray(), [4, 1])
# Check reverse functionality
self.lnk_lst.reverse()
self.assertEqual(self.lnk_lst.toArray(), [1, 4])
def test_stack_array(self):
self.stack_array = StackArray()
self.stack_array.push(1)
self.stack_array.push(2)
self.stack_array.push(3)
self.stack_array.pop()
self.stack_array.pop()
self.stack_array.push(2)
self.assertEqual(self.stack_array.toArray(), [2, 1])
self.assertEqual(self.stack_array.peek(), 2)
def test_stack_list(self):
self.stack_list = StackLinkedList()
self.stack_list.push(1)
self.stack_list.push(2)
self.stack_list.push(3)
self.stack_list.pop()
self.stack_list.pop()
self.stack_list.push(2)
self.assertEqual(self.stack_list.toArray(), [2, 1])
self.assertEqual(self.stack_list.peek(), 2)
def test_queue_array(self):
self.queue_array = QueueArray()
self.queue_array.enqueue(1)
self.queue_array.enqueue(2)
self.queue_array.enqueue(3)
self.queue_array.dequeue()
self.queue_array.dequeue()
self.queue_array.enqueue(2)
self.assertEqual(self.queue_array.toArray(), [3, 2])
self.assertEqual(self.queue_array.peek(), 3)
def test_queue_list(self):
self.queue_list = QueueLinkedList()
self.queue_list.enqueue(1)
self.queue_list.enqueue(2)
self.queue_list.enqueue(3)
self.queue_list.dequeue()
self.queue_list.dequeue()
self.queue_list.enqueue(2)
self.assertEqual(self.queue_list.toArray(), [3, 2])
self.assertEqual(self.queue_list.peek(), 3)
def test_binary_tree(self):
self.binary_tree = BinaryTree()
self.binary_tree.add(10)
self.binary_tree.add(4)
self.binary_tree.add(15)
self.binary_tree.add(1)
self.binary_tree.add(12)
self.binary_tree.add(19)
self.binary_tree.add(3)
self.binary_tree.add(8)
self.assertEqual(self.binary_tree.inorder(), [1, 3, 4, 8, 10, 12, 15, 19])
self.assertEqual(self.binary_tree.preorder(), [10, 4, 1, 3, 8, 15, 12, 19])
self.assertEqual(self.binary_tree.postorder(), [3, 1, 8, 4, 12, 19, 15, 10])
self.assertEqual(self.binary_tree.bfs(), [10, 4, 15, 1, 8, 12, 19, 3])
|
54a6fe414bcea659373ff069fee550431a964b6e | jacoblamberson/applied-crypto-assignment-3 | /main.py | 2,803 | 3.84375 | 4 | import binascii
from Crypto.Cipher import AES
import os
# Credit to Chris Coe for this code
# Requires pycrypto, which does indeed work for python3
def encrypt(key, raw):
'''
Takes in a string of clear text and encrypts it.
@param raw: a string of clear text
@return: a string of encrypted ciphertext
'''
if (raw is None) or (len(raw) == 0):
raise ValueError('input text cannot be null or empty set')
cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
ciphertext = cipher.encrypt(raw)
return binascii.hexlify(bytearray(ciphertext)).decode('utf-8')
def decrypt(key, enc):
if (enc is None) or (len(enc) == 0):
raise ValueError('input text cannot be null or empty set')
enc = binascii.unhexlify(enc)
cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
enc = cipher.decrypt(enc)
return enc#.decode('utf-8')
def bxor(b1, b2): # use xor for bytes
result = bytearray()
for b1, b2 in zip(b1, b2):
result.append(b1 ^ b2)
return result
def get_hex_iv():
return binascii.hexlify(os.urandom(16)).decode('utf-8')
def xor_hex_string(a, b):
c, d = binascii.unhexlify(a), binascii.unhexlify(b)
result = bxor(c, d)
return binascii.hexlify(result).decode('utf-8')
# Takes a hex string and binary key
# Returns hex-represented encrypted data
def cbc_encrypt(key, hex):
result = ""
iv = get_hex_iv()
result += iv
hex += 'ff'
while len(hex) % 32 != 0:
hex += '00'
last_block = iv
for i in range(0, len(hex), 32):
before_enc = xor_hex_string(last_block, hex[i:i+32])
last_block = encrypt(key, binascii.unhexlify(before_enc))
result += last_block
return result
# Returns binary result
def cbc_decrypt(key, hex):
result = ""
iv = hex[:32]#binascii.hexlify(decrypt(key, hex[:32])).decode('utf-8')
last_block = iv
for i in range(32, len(hex), 32):
decrypted = binascii.hexlify(decrypt(key, hex[i:i+32])).decode('utf-8')
message = xor_hex_string(decrypted, last_block)
last_block = hex[i:i+32]
result += message
result = result[:result.rfind('ff')]
return binascii.unhexlify(result)
if __name__ == "__main__":
key = bytes("1234567890abcdef1234567890abcdef", encoding='utf-8')
hex_data = binascii.hexlify(bytes("1234567890abcdef1234567890abcdef1234567890abcdefpoi", encoding='utf-8')).decode('utf-8')
ct = encrypt(key, "1234567890abcdef")
dt = decrypt(key, ct)
rnd = get_hex_iv()
print(ct)
print(dt)
print(rnd)
r = xor_hex_string('11', '22')
print(r)
print(xor_hex_string(r, '11'))
print(xor_hex_string(r, '22'))
print(binascii.unhexlify(hex_data))
print(hex_data)
encrypted = cbc_encrypt(key, hex_data)
print(encrypted)
decrypted = cbc_decrypt(key, encrypted)
print(decrypted.decode('utf-8')) |
34ac24c81f34f6c508970e38ac29a0fc037d1a06 | ChavanKarthik/Python | /python_basics/innerClass.py | 648 | 3.5 | 4 | class Student:
def __init__(self, name, rollNo):
self.name = name
self.rollNo = rollNo
self.lap = self.Laptop()
def show(self):
print(s1.name, s1.rollNo)
self.lap.show()
def dontShow(self):
print('Student details are confidential')
print('''Please don't mind''')
class Laptop:
def __init__(self):
self.brand = 'Dell'
self.processor = 'i5'
self.ram = '16 GB'
self.harddisk = '1 TB'
def show(self):
print(self.brand, self.processor, self.ram, self.harddisk)
s1 = Student('Naveen', 123)
s1.show()
|
989384f93c7001535cf89d5936012d75b153193f | ChavanKarthik/Python | /python_basics/method_overriding02.py | 490 | 3.75 | 4 | class A:
def sum(x, y, z):
return x + y + z
def sub(x, y, z):
return (x - y) - z
class B:
def sum(x, y):
return x * y
def sub(x, y):
return x - y
class C:
def sum(x):
return x ** 2
def sub(x):
return (x ** 2) - x
for z in range(2):
for y in range(2):
for x in range(4):
if x < 3:
print('# ', end=" ")
else:
print('# ')
break
|
56431b5a765440925338967d5f5a0a553d75f990 | ChavanKarthik/Python | /python_basics/file_openRead.py | 875 | 3.546875 | 4 | # ss=open("/home/beehyv/Downloads/python/python_basics/file_operations.py") #To open a file
# ss=open("/home/beehyv/Downloads/python/python_basics/file_operations.py","r") #To open a file with read permission
# ss=open("/home/beehyv/Downloads/python/python_basics/file_operations.py","wb") #To open a file with binary write permission
# ss=open("/home/beehyv/Downloads/python/python_basics/file_operations.py","rb") #To open a file with binary read permission
# ss=open("/home/beehyv/Downloads/python/python_basics/file_operations.py","w") #To open a file with write permission
ss = open("/home/beehyv/Downloads/python/python_basics/readFile.txt", 'r')
fileContent = ss.read() # returns whole file data
ss2 = ss.read(15) # returns only first 15 chars
# print(fileContent)
for line in fileContent.split(' '): # returns one character in one line
print(line)
ss.close()
|
448e50c7daf964c85c959353869224576595dc49 | ChavanKarthik/Python | /python_basics/statistic_basic_functions.py | 805 | 3.640625 | 4 | import random
# list of random numbers
# x = random.sample(range(1, 1000), 15)
x = [370, 877, 575, 11, 895, 377, 574, 88, 800, 825, 222, 411, 396, 885, 857, 633]
# print(x)
# to find the sum
def total(x):
summ = 0
for i in x:
summ = i + summ
return summ
# print(total(x))
# to find mean (average)
def average(x):
y = 0
y = total(x) / len(x)
return y
# print(average(x))
# To find median
def median(x):
x = sorted(x)
if len(x) % 2 != 0:
medean = x[(len(x)) // 2]
else:
m = int(((len(x)) / 2) + 0.5)
n = int(((len(x)) / 2) - 0.5)
medean = (x[m] + x[n]) / 2
return medean
# print(median(x))
# to find range of a list
def range1(x):
x = sorted(x)
range1 = x[-1] - x[0]
return range1
# print(range1(x))
|
b436930c1e925b47ff69027f28f7af194ca2b2f5 | ChavanKarthik/Python | /python_basics/Lists.py | 169 | 3.71875 | 4 | a = ['aaa', 'bbb', 'ccc']
print(a)
a.append('ddd')
print(a)
a.pop()
print(a)
print(a[0])
a[0] = 'AAA'
print(a)
a[0] = 'aaa'
temp = a[0]
a[0] = a[2]
a[2] = temp
print(a)
|
7637ca253aebc483cb271fb25e1d551b177b2e69 | ChavanKarthik/Python | /python_basics/loop_nested_list.py | 624 | 3.5625 | 4 | a = list(range(100, 102))
for x in a:
print(x)
for y in list(range(100, 102)):
print(y)
aaa = [[1, 2.5], [3, 4, 10], [101, 105]]
for z in aaa:
if isinstance(z, list):
for w in z:
if w == 10:
print('Found 10')
break
aaa = [1, 2, 5, [3, [9, [10, 10], 10], 4, 10], 101, 105]
def recursiveElementCheck(a, compare):
if isinstance(a, int):
if a == compare:
print("Found ", compare)
exit()
else:
for z in a:
if recursiveElementCheck(z, compare):
return
recursiveElementCheck(aaa, 10)
|
2a1270d9dd27b11f498d00ecfeff60094155eccb | cesarschool/cesar-school-fp-2018-2-lista1-HConcreteKite | /questao_1.py | 183 | 3.75 | 4 | salario = float(input("Digite o seu salario:\n"))
porcentagem = float(input("Digite a porcentagem que foi aumentada:(100%)\n"))
aumento = salario * (porcentagem/100)
print(aumento)
|
80b6910ba6af3cebc271d994cf267f95e0a3b766 | hraj9258/Python-projects | /string_demo.py | 99 | 3.71875 | 4 | b = "Hello, World!"
print(b[2:5])
#Get the characters from position 2 to position 5 (not included): |
3f9ee5b64eb52677e6a78be989f3c76b30d72f68 | hraj9258/Python-projects | /line_statics.py | 541 | 4.09375 | 4 | line=input("Enter a line:")
lowercount=uppercount=0
digitcount=alphacount=digitspace=0
for a in line:
if a.islower():
lowercount +=1
elif a.isupper():
uppercount +=1
elif a.isdigit():
digitcount +=1
elif a.isalpha():
alphacount +=1
elif a.isspace():
digitspace +=1
print("Number of upper case letter:",uppercount)
print("Number of lowercase letters:",lowercount)
print("Number of alphabet:",alphacount)
print("Number of digits:",digitcount)
print("Number of spaces:",digitspace)
|
c846fdeb90d55dd76aaf8708aa892eb6e6af98e7 | hraj9258/Python-projects | /math-square root module.py | 96 | 3.984375 | 4 | import math
x=int(input("Enter Number of which you want square root?>"))
y=math.sqrt(x)
print(y) |
3f2b826c07ff821215d1834961347abbbf33deb4 | hraj9258/Python-projects | /break-e.g.py | 422 | 3.9375 | 4 | #x=y=0
#x=int(input("Please enter first number:"))
#y=int(input("Please enter second number:"))
for y in range(0,1):
x=int(input("Please enter first number:"))
y=int(input("Please enter second number:"))
if y == 0:
print("Devision by zero error!")
break
if y == 1:
print("Devision of",x,"by 1","is",x)
else:
print("Division of",x,"and",y,"is",x/y)
print("Program over!") |
70f28377146bf075e0ec0814373e27b6d463aa04 | git-vish/leetcode-python | /Problems/image_flip.py | 319 | 3.59375 | 4 | __author__ = 'Vishwajeet Ghatage'
__email__ = 'cloudmail.vishwajeet@gmail.com'
__date__ = '10/02/2021'
def solution(a: list[list[int]]) -> list[list[int]]:
result = []
for row in a:
result.append([x ^ 1 for x in row[::-1]])
return result
if __name__ == '__main__':
A = [[1, 1, 0], [1, 0, 0], [0, 1, 0]]
print(solution(A))
|
683d9a7aa292fe75917fc57cef99b7a2f7aeb830 | git-vish/leetcode-python | /Problems/detect_capital.py | 364 | 3.5625 | 4 | __author__ = 'Vishwajeet Ghatage'
__email__ = 'cloudmail.vishwajeet@gmail.com'
__date__ = '19/02/2021'
def solution(word: str) -> bool:
if word.isupper():
return True
elif word.islower():
return True
else:
if word[0].isupper() and word[1:].islower():
return True
return False
if __name__ == '__main__':
W = 'Google'
print(solution(W))
|
978479198ee00ead9a41fda2fb0543f0bf56e041 | git-vish/leetcode-python | /Problems/stairs.py | 287 | 3.875 | 4 | __author__ = 'Vishwajeet Ghatage'
__email__ = 'cloudmail.vishwajeet@gmail.com'
__date__ = '02/02/2021'
def solution(n: int) -> int:
fib = [1, 1]
i = 1
while n >= len(fib):
fib.append(fib[i] + fib[i - 1])
i += 1
return fib[-1]
if __name__ == '__main__':
N = 3
print(solution(N))
|
b1573d7404f6e1215284effec04d446fe76b4e32 | git-vish/leetcode-python | /Problems/frog_jump.py | 797 | 3.90625 | 4 | __author__ = 'Vishwajeet Ghatage'
__email__ = 'cloudmail.vishwajeet@gmail.com'
__date__ = '17/02/2021'
def solution(stones: list[int]) -> bool:
for i in range(3, len(stones)):
if stones[i] > stones[i - 1] * 2:
return False
stones_set = set(stones)
reachable_stones = [(0, 0)]
last_stone = stones[-1]
while reachable_stones:
stone, dist = reachable_stones.pop()
for jump in [dist - 1, dist, dist + 1]:
if jump <= 0:
continue
next_stone = stone + jump
if next_stone == last_stone:
return True
elif next_stone in stones_set:
reachable_stones.append((next_stone, jump))
return False
if __name__ == '__main__':
S = [0, 1, 3, 5, 6, 8, 12, 17]
print(solution(S))
|
c306b17f37759da2e4cf93c9e59b4d14583ef484 | git-vish/leetcode-python | /Problems/fizz_buzz.py | 458 | 3.90625 | 4 | __author__ = 'Vishwajeet Ghatage'
__email__ = 'cloudmail.vishwajeet@gmail.com'
__date__ = '18/01/2021'
def fizz_buzz(n: int) -> list[str]:
lst = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
lst.append('FizzBuzz')
elif i % 3 == 0:
lst.append('Fizz')
elif i % 5 == 0:
lst.append('Buzz')
else:
lst.append(str(i))
return lst
if __name__ == '__main__':
N = 15
print(fizz_buzz(N))
|
3ce50eb47b27161820db8fecadf8d8c977cf2722 | nbenkler/CS110_Intro_CS | /Top down design lab/conversion3.py | 870 | 4.09375 | 4 | #conversion3.py
# Another program to convert Celsius temps to Fahrenheit
def fileIngest(fileName):
inFile = open(fileName, "r")
return inFile
inFile.close()
def conversionCreator(file):
fahrenheitList=[]
for line in file:
celsius = int(line)
fahrenheit = conversion(celsius)
output = str(str(celsius)+" degrees celsius is "+str(fahrenheit)+" degrees in Fahrenheit.")
fahrenheitList.append(output)
return fahrenheitList
def fileOutput(conversionList):
outFile = open('fahrenheitTemps.txt', "w")
outFile.write(conversionList)
outFile.close()
def conversion(c_temp):
f_temp = 9/5 * c_temp + 32
return f_temp
def main():
fileName = eval(input("What is the name of the file you would like to convert? "))
conversionFile = fileIngest(fileName)
conversionResults = conversionCreator(conversionFile)
fileOutput(str(conversionResults))
main() |
1a948637866f58b51f76d1b69c070d67a6a615c8 | nbenkler/CS110_Intro_CS | /HW #5/untitled folder/convertFunctions.py | 955 | 4.15625 | 4 | # Program to read file HW5_Input.txt and convert characters in the file to their unicode, hexadecimal, and binary representations.
#Noam Benkler
#2/12/18
def fileIngest(fileName):
inFile = open(fileName, "r")
return inFile
inFile.close()
def conversionOutput(file):
for line in file:
full = (line)
character = (full[0])
unicode = uniConversion(character)
hexadecimal = hexConversion(unicode)
binary = binConversion(unicode)
output = str("The Character "+str(character)+" is encoded as "+str(unicode)+" in Unicode, which is "+str(hexadecimal)+" in hexadecimal and "+str(binary)+" in binary.")
print (output)
def uniConversion(alphanum):
uni = ord(alphanum)
return uni
def hexConversion(alphanum):
hexa = hex(alphanum) [2:]
return hexa
def binConversion(alphanum):
bina = bin(alphanum) [2:]
return bina
def main():
fileName = "HW5_input.txt"
conversionFile = fileIngest(fileName)
conversionOutput(conversionFile)
main() |
ef7f2f30bc22a979d8ca84bfb143913baa0d4a87 | nbenkler/CS110_Intro_CS | /Classes lab/msdie.py | 482 | 3.578125 | 4 | # msdie.py
# Class definition for an n-sided die.
from random import randrange
class MSDie:
def __init__(self, sides):
self.sides = sides
self.value = 1
def roll(self):
self.value = randrange(1, self.sides+1)
def getValue(self):
return self.value
def setValue(self, value):
self.value = value
def main():
die1=MSDie(12)
print(die1.getValue())
for i in range (10):
die1.roll()
print(die1.getValue())
main() |
590d5ad63a0fcf7f0f27a6352051093acfc9923c | nbenkler/CS110_Intro_CS | /Lab 3/functions.py | 1,026 | 4.4375 | 4 | '''function.py
Blake Howald 9/19/17, modified for Python 3 from original by Jeff Ondich, 25 September 2009
A very brief example of how functions interact with
their callers via parameters and return values.
Before you run this program, try to predict exactly
what output will appear, and in what order. You are
trying to trace the movement of data throughout the
program, and make sure you understand what happens
when. This simple program is very important for you
to understand. If you have figured it out, the rest
of the term will be a lot easier than if you haven't.
'''
def f(n):
print(n)
result = 3 * n + 4
return result
def g(n):
print(n)
result = 2 * n - 3
return result
number = 5
print('number = ', number)
print()
print('Experiment #1')
answer = f(number)
print('f(number) =', answer)
print()
print('Experiment #2')
answer = g(number)
print('g(number) =', answer)
print()
print('Experiment #3')
answer = f(g(number))
print('f(g(number)) =', answer)
print()
|
f5cb1e22fb29818a0c7fd46116e622165d0fa117 | codymccoderson/python | /n to m.py | 232 | 3.984375 | 4 | user_start = int(input("Enter number here: "))
user_end = int(input("Enter number here: "))
print("Here's your list from {0} to {1}! ".format(user_start, user_end))
for i in range(user_start, user_end + 1):
print(i, end = " ") |
1ba278fcdea63ede297556432fc2dde66ce5a103 | codymccoderson/python | /6x4 box.py | 195 | 3.890625 | 4 | for i in range (0, 6):
for j in range (0, 4):
if (i== 0 or i == 5 or j == 0 or j == 3):
print("* ", end = " ")
else:
print(" ", end = " ")
print() |
78ef5fc28e3f4ae7efc5ed523eeffe246496c403 | alexmkubiak/MIT_IntroCS | /week1/pset1_2.py | 413 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 18:00:03 2018
This code determines how many times the string 'bob' occurs in a string s.
@author: Alex
"""
s = 'azcbobobegghakl'
count = 0
index = 0
for index in s:
if s[index] == 'b':
if s[index + 1] == 'o':
if s[index+2] == 'b':
count += 1
print("Number of times bob occurs is: " + str(count))
|
b4c78107103faba10d72939b11d90f123e3f9e4b | UnholyXD/python_coisas | /basicos/FtoC.py | 95 | 3.96875 | 4 | c = float(input("Digite a temperatua em Celsius: "))
f = 9*c/5 + 32
print ('%d Fahrenheit' %f) |
61df59b06113e2086491a4b3f7cc72abfefd0c8f | ykleinman/blind-auction-project | /main.py | 999 | 3.75 | 4 | from replit import clear
from art import logo
user_bid = {}
#STEP-1: Show Logo from art.py
print(logo)
game_over = False
while not game_over:
#STEP-2: Ask for name input
name = input("What is your name? ")
#STEP-3: Ask for bid price
bid_price = int(input("What is your bid? $"))
def activate_bidder(user_name, bid):
#STEP-4: Add name and bid into a dictionary as the key and value.
user_bid[name] = bid_price
activate_bidder(user_name=name, bid=bid_price)
#STEP-5:
other_bidders = input("Are there any other bidders? Type 'yes or 'no'\n")
if other_bidders == "yes":
clear()
activate_bidder(user_name=name, bid=bid_price)
elif other_bidders == "no":
for user in user_bid:
winning_bid = 0
final_bid = user_bid[user]
if final_bid > winning_bid:
winning_bid = final_bid
print(f"The winner is {user} with a bid of ${winning_bid}")
game_over = True
|
8dd6a7e334e75e12f28a05c63c2ac0c911fd527b | riyazclock/RIYAZ | /evennoo.py | 142 | 3.640625 | 4 | a=input().split()
start =int(a[0])
end = int(a[1])
for num in range(start+1, end + 1):
if num % 2 == 0:
print(num, end = " ")
|
88929922d7d71fec7168f12d8e7b4f2d02827a80 | TheChuey/DevCamp | /OverView_Number Types in Python.py | 525 | 3.828125 | 4 | product_id = 123
sale_price = 14.99
tip_percentage = 1/5
new_product = 150
print(sale_price + new_product)
# Number Tyoes
# product id is an integer type is a whole number-all processed when you run the python program
# sale price is a floating type data type-float has a decimal library-floats precision isn't as complex as decimal
# tip percentage is fractions and in the example it represents 20%
# new product is and integer
# LETS COMBINE THEM NOW
# say print and call the sale price and the new product
|
45e63a61065a3cc52163899c4e1e831b7bfec28b | TheChuey/DevCamp | /DataTypesPythong.py | 1,240 | 3.96875 | 4 | """ name = "jesus"
post_count = 42
print (name, post_count)"""
"""
name = 'Kristine' <----variable is called name then the equal sign and then what you want it to store (a string)
post_count = 42 <-----a number variable integer value (post count)
print(name) <----to print the name variable
print(post_count)
"""
meal_completed = True # <--boolean value is always true or false value(is published or not example) use Captital T for true and F for false
sub_total = 100 # <--standard number here equal to 100
tip = sub_total * 0.2 # <--floating point number 0.2(floats and integers are in the number data type)
total = sub_total + tip # <--this says the total is equal to the sub_total plus the tip
receipt = "Your total is " + str(total) # <--want the reciept with a string plus the str(string) and pass in the total in parens
print(receipt)
# Booleans
# Numbers
# Strings wrapper with single or double qutation marks
# Bytes and byte arrays
# None-define a variable but don't want to set the value yet, you use none
# Lists-managing collections
# Tuples-managing collections
# Sets-managing collections
# Dictionaries-managing collections-give ability to have key value pairs
|
9ecd69b1dc1bd808055cea00eabc82428dc12056 | TheChuey/DevCamp | /range_slices_in_pythonList.py | 982 | 4.3125 | 4 | tags = [
'python',
'development',
'tutorials',
'code',
'programing',
'computer science'
]
#tags_range = tags[:-1:2]
tags_range = tags[::-1] # reverses the oder of the list
# slicing function
print(tags_range)
"""
# Advanced Techniques for Implementing Ranges and Slices in Python Lists
tag_range = tags[1:-1:2] # we want every other tag here (place in an interval) -inside the bracket you can pass in the third elemnt(interval(every other tag) the 2 takes every other element)
tag_range = tags[::-1] #slicing -flip the entire order of the list- in bracket-reverse index values-remove second perameter
#above-you would use this
print(tag_range)
#------------------------------------------------------------------------------
tags.sort(reverse=True) #sorting function looks at the alphabetical value-instead of the above example that pulls the index
print(tags)
////////////////////////////////////////////////////////////
""" |
cd1b3b254b02065c149f37195b25041448151b53 | DyadushkaArchi/python_hw | /TESTS_6.py | 793 | 4 | 4 | # Определить является ли строка изограммой,
# т.е. что все буквы в ней за исключением пробелов встречаются только один раз.
# Например, строки 'Питон', 'downstream', 'книга без слов' являются изограммами,
# а само слово 'изограмма' - нет.
def is_isogramm(text):
text = str(text)
letter_frequency = {}
for i in range(len(text)):
key = str(text[i])
if not key == ' ':
if not key in letter_frequency:
letter_frequency[key] = 1
elif key in letter_frequency:
return False
return True
print(is_isogramm('книга без слов'))
|
b00e90a75e71223e27a997bf9e2fd433666cadf3 | DyadushkaArchi/python_hw | /Python_hw_33.py | 490 | 3.609375 | 4 | class Godzilla:
def __init__(self, stomach_volume):
self.stomach_volume = stomach_volume
self.free_stomach_space = stomach_volume
def eat(self, weight):
self.free_stomach_space = self.stomach_volume - weight
return self.free_stomach_space
def is_full(self):
return self.free_stomach_space < (self.stomach_volume // 10)
#(main.py)
#from Python_hw_33 import Godzilla
#g = Godzilla(100)
#print(g.is_full())
#g.eat(93)
#print(g.is_full()) |
fddd74d8a7cbb7641c3d0bfbfb2ee7901639d7f3 | DyadushkaArchi/python_hw | /Python_hw_20.py | 987 | 4.125 | 4 | import random
#==========================================================================
#task 19
#==========================================================================
#Написать функцию для поиска разницы сумм всех четных и всех нечетных чисел среди
#100 случайно сгенерированных чисел в произвольном числовом диапазоне.
#Т.е. от суммы четных чисел вычесть сумму нечетных чисел.
def diff_even_odd(num_limit, lower_bound, upper_bound): # returns int
even_number = 0
odd_number = 0
for i in range(num_limit):
rand_number = random.randint(lower_bound, upper_bound)
print("Rand.number:", rand_number)
if rand_number % 2 == 0:
even_number += rand_number
else:
odd_number += rand_number
result = even_number - odd_number
return result
example = diff_even_odd(4, -20, 0)
print(example)
|
b984b5780e95587e16a88d7eeeda007e84507af8 | DyadushkaArchi/python_hw | /Python_hw_34.py | 536 | 3.859375 | 4 | class CircleDot:
def __init__(self, x, y, x0, y0, radius):
self.coordinate_x = x
self.coordinate_y = y
self.center_coord_x = x0
self.center_coord_y = y0
self.radius = radius
def is_in(self):
equation = ((self.coordinate_x - self.center_coord_x) ** 2 + (self.coordinate_y - self.center_coord_y) ** 2)
return equation <= (self.radius ** 2)
# (main.py)
#from Python_hw_34 import CircleDot
#CircleDot.__init__(CircleDot, 1, 1, 0, 0, 3)
#print(CircleDot.is_in(CircleDot))
|
7b09607a939691ded40feac8213811d6dac2694a | RichelieuRosa/Rice-An-Introduction-to-Interactive-Programming-in-Python-Part-1- | /PongGame.py | 4,686 | 3.671875 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
time = 0
direction = random.choice(["LEFT","RIGHT"])
score1 = score2 = 0
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
direction = random.choice(["LEFT","RIGHT"])
ball_pos = [ WIDTH/2, HEIGHT/2 ]
vel_x, vel_y = random.randrange(120, 240)/60, random.randrange(60, 180)/60
vel = [vel_x, vel_y]
if direction == "RIGHT":
ball_vel = vel
elif direction == "LEFT":
vel[0] = -vel[0]
ball_vel = vel
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, direction # these are numbers
global score1, score2 # these are ints
paddle1_pos = paddle2_pos = HEIGHT/2
paddle1_vel = paddle2_vel = 0
spawn_ball(direction)
def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
gleft = canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
gright = canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
ball_pos[0] = ball_pos[0] + ball_vel[0]
ball_pos[1] = ball_pos[1] + ball_vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Red", "White")
# update paddle's vertical position, keep paddle on the screen
if (HEIGHT-HALF_PAD_HEIGHT) >= paddle1_pos+ paddle1_vel >= HALF_PAD_HEIGHT :
paddle1_pos += paddle1_vel
if (HEIGHT-HALF_PAD_HEIGHT) >= paddle2_pos + paddle2_vel>= HALF_PAD_HEIGHT:
paddle2_pos += paddle2_vel
# draw paddles
# left
canvas.draw_polygon([(2,paddle1_pos-HALF_PAD_HEIGHT),(PAD_WIDTH,paddle1_pos-HALF_PAD_HEIGHT),(PAD_WIDTH,paddle1_pos+HALF_PAD_HEIGHT),
(2,paddle1_pos+HALF_PAD_HEIGHT)],PAD_WIDTH,"White")
# right
canvas.draw_polygon([(WIDTH-2, paddle2_pos-HALF_PAD_HEIGHT),(WIDTH-PAD_WIDTH, paddle2_pos-HALF_PAD_HEIGHT),
(WIDTH-PAD_WIDTH, paddle2_pos+HALF_PAD_HEIGHT),(WIDTH-2, paddle2_pos+HALF_PAD_HEIGHT)],PAD_WIDTH,"White")
# determine whether paddle and ball collide
if ball_pos[0] <= BALL_RADIUS :
if (paddle1_pos- HALF_PAD_HEIGHT) <= ball_pos[1] <= (paddle1_pos+ HALF_PAD_HEIGHT):
ball_vel[0] = (-ball_vel[0])* 1.7
else:
spawn_ball(direction)
score2 +=1
if ball_pos[0] >= WIDTH-BALL_RADIUS:
if (paddle2_pos- HALF_PAD_HEIGHT) <= ball_pos[1] <= (paddle2_pos+ HALF_PAD_HEIGHT):
ball_vel[0] = (-ball_vel[0])* 1.7
else:
spawn_ball(direction)
score1 += 1
# ball reflection- 1
if ball_pos[1] <= BALL_RADIUS or ball_pos[1] >= (HEIGHT- BALL_RADIUS):
ball_vel[1] = -ball_vel[1]
# draw scores
canvas.draw_text(str(score1), [150, 100], 25, 'White')
canvas.draw_text(str(score2), [450, 100], 25, 'White')
def restart():
new_game()
def keydown(key):
global paddle1_vel, paddle2_vel
var = 4
if key == simplegui.KEY_MAP["w"]:
paddle1_vel += -var
elif key == simplegui.KEY_MAP["s"]:
paddle1_vel += var
elif key == simplegui.KEY_MAP["up"]:
paddle2_vel += -var
elif key == simplegui.KEY_MAP["down"]:
paddle2_vel += var
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP["w"]:
paddle1_vel = 0
elif key == simplegui.KEY_MAP["s"]:
paddle1_vel = 0
elif key == simplegui.KEY_MAP["up"]:
paddle2_vel = 0
elif key == simplegui.KEY_MAP["down"]:
paddle2_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", restart, 100)
# start frame
new_game()
frame.start()
|
809584924dd93708dc5886d9118e42a8191a3db5 | ravi4all/Python_Aug_4-30 | /CorePythonAgain/10-Zip/01-Zip.py | 484 | 3.734375 | 4 | countries = ['US','UK','CHINA','INDIA','PAK']
gold = [45,40,55,12,2]
silver = [56,43,87,10,5]
bronze = [76,56,100,21,12]
countriesWithGold = list(zip(countries, gold))
# for c in countriesWithGold:
# print(c)
total = list(zip(countries, gold, silver, bronze))
# for t in total:
# print(t)
for i in range(len(countries)):
g = gold[i]
s = silver[i]
b = bronze[i]
c = countries[i]
print("Total medals by {} are {}".format(c, g+s+b))
|
3fae18870c87d2b07d53699d922dfd1747ffeb78 | ravi4all/Python_Aug_4-30 | /CorePythonAgain/Applications/01-Calculator/03-OneFunctionCalc.py | 761 | 4 | 4 | def calculator(ch,x,y):
if ch == "1":
return x + y
elif ch == "2":
return x - y
elif ch == "3":
return x * y
elif ch == "4":
return x/y
else:
print("Wrong Choice")
def main():
while True:
print("""
1. Add
2. Sub
3. Mul
4. Div
5. Quit
""")
user_choice = input("Enter your choice : ")
num_1 = int(input("Enter first number : "))
num_2 = int(input("Enter second number : "))
todo = {
"1" : calculator,
"2" : calculator,
"3" : calculator,
"4" : calculator,
}
calc = todo.get(user_choice)(user_choice,num_1, num_2)
print(calc)
main()
|
f2f59d0ebd7cc5f2d9a252f3eb98d4b794f82790 | ravi4all/Python_Aug_4-30 | /CorePython/01-BasicPython/03-StringIndexing.py | 830 | 3.5625 | 4 | Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = "Hello Python"
>>> a[0]
'H'
>>> a[1]
'e'
>>> a[0] = "B"
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a[0] = "B"
TypeError: 'str' object does not support item assignment
>>> a[0]
'H'
>>> a[0:4]
'Hell'
>>> a[0:5]
'Hello'
>>> a[-1]
'n'
>>> a[-2]
'o'
>>> a[:5]
'Hello'
>>> a[5:]
' Python'
>>> a[1:100]
'ello Python'
>>> a[100]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a[100]
IndexError: string index out of range
>>> a[0:-1]
'Hello Pytho'
>>> a[::-1]
'nohtyP olleH'
>>> a[0::2]
'HloPto'
>>> a
'Hello Python'
>>> a[0:10:3]
'HlPh'
>>> len(a)
12
>>>
|
709bb0e5e55bdb26c0824b6045a1af43f3eceafd | ravi4all/Python_Aug_4-30 | /CorePythonAgain/GameDevelopment/06-KeyPress.py | 1,220 | 3.703125 | 4 | import pygame
pygame.init()
size = width,height = 600,500
white = 255,255,255
red = 255,0,0
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
FPS = 30
rect_x = 0
rect_y = 0
move_x = 0
move_y = 0
while True:
screen.fill(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_x = 10
move_y = 0
elif event.key == pygame.K_LEFT:
move_x = -10
move_y = 0
elif event.key == pygame.K_DOWN:
move_y = 10
move_x = 0
elif event.key == pygame.K_UP:
move_y = -10
move_x = 0
pygame.draw.rect(screen, red, [rect_x,rect_y,50,50])
rect_x += move_x
rect_y += move_y
if rect_x >= width:
rect_x = -50
elif rect_y >= height:
rect_y = -50
elif rect_x <= -50:
rect_x = width
elif rect_y <= -50:
rect_y = height
pygame.display.update()
clock.tick(FPS)
|
b1c02684e97259cf8998030a90b7ee7898017505 | ravi4all/Python_Aug_4-30 | /CorePythonAgain/05-Functions/06-NestedFunctions.py | 289 | 3.734375 | 4 | # Closures
def outer(msg):
message = msg
def inner():
# print("Message was",message)
return message + ' Python'
return inner
# print(inner())
# outer("Hello world")
# print(outer("Hello"))
a = outer("Hello")
print(a())
print(type(a))
|
38f6ea8b2028ec25dc242c6eac17743b1325a8b4 | asim09/Algorithm | /OOP/diamond_problem.py | 394 | 3.921875 | 4 | #How to call x method from A class and y method from B class
##SOLUTION
class A:
def x(self):
print('A class X method')
def y(self):
print('A class y method')
class B:
def x(self):
print('B class X method')
def y(self):
print('B class y method')
class C(A, B):
def y(self):
pass
B.y(self)
obj = C()
obj.x()
obj.y()
|
09a4ae07c0b9e3c8d1604bfaea0ce58078d52936 | asim09/Algorithm | /data-types/List/sort-list-of-string.py | 256 | 4.1875 | 4 | # Python Program to sort a list according to the length of the elements
a = ['Apple', 'Ball', 'Cat', 'Ox']
for i in range(len(a)):
for j in range(len(a) - i - 1):
if len(a[j]) > len(a[j+1]):
a[j], a[j+1] = a[j+1], a[j]
print(a[-1])
|
7bb3f5cf8312c4e7c0a35236e7f266345854b64d | asim09/Algorithm | /dict.py | 1,765 | 3.5625 | 4 | # class SoftwareEngineer:
#
# def __init__(self,name, age, designation, salary):
# self.name = name
# self.age = age
# self.designation = designation
# self.salary = salary
#
# def code(self):
# print(f"{self.name} is writing code....")
#
# def code_language(self, language):
# print(f"{self.name} is working in {language}...")
#
# def information(self):
# print(f'{self.name} is a {self.designation}')
# se1 = SoftwareEngineer('Asim', 34, 'Consultant', 'xxxxx')
# se2 = SoftwareEngineer('Asim', 34, 'Consultant', 'xxxxx')
# print(se1.code())
# print(se2.code_language('Pythion'))
# print(se2.information())
def is_armstrong(num):
degree = len(str(num))
number_sum = sum([pow(int(i), degree) for i in str(num)])
print(number_sum, num)
return True if number_sum == num else False
# print(is_armstrong(371))
# from operator import mul
# from functools import reduce
#
#
# def factorial(num):
# if num < 1:
# return 'wrong value'
# fact = reduce(mul, [i for i in range(1, num + 1)]) if num > 1 else 1
# return fact
#
#
# num = -1
# print(factorial(num))
str = 'malayalam1my'
# index = - 1
# flag = 1
# for elem in str:
# print(elem + '-------' + str[index])
#
# if elem != str[index]:
# flag = 0
# break
# index = index - 1
#
# if flag:
# print('---tes')
# else:
# print('---No')
# rev_str = str[::-1]
# # print(rev_str)
# if rev_str == str:
# print('Y')
def is_prime(num):
flag = True
if num <= 1:
flag = False
if num > 1:
for i in range(2, num):
if num % i == 0:
flag = False
break
return flag
print(is_prime(8))
|
a002c011c268dd175c5ff505b6f782ff94cce275 | jestupinanb/Contest | /CRIPTO/Python/other.py | 173 | 3.828125 | 4 | import numpy as np
a = [1, 2, 3]
b = [5, 6, 7]
arr = np.array([a])
for i in range(2):
arr = np.concatenate((arr, [b]))
for i in range(1, 3):
print(i)
print(arr)
|
e2dd6c52dcfe57e8ea05af06f66e715380bc00b8 | prabalbhandari04/python_ | /multiplication.py | 70 | 3.859375 | 4 | for i in range(5)
x=input("enter number")
z=z+x
print(z)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.