blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
fef2ed2eaf412fa0a834c78b34b9b44a5539ad8a | vijaykumar0425/hacker_rank | /find_angle_mbc.py | 232 | 3.5625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
import sys
AB = int(sys.stdin.readline())
BC = int(sys.stdin.readline())
sys.stdout.write(str(int(round(math.degrees(math.atan2(AB,BC)))))+'°')
|
87b9e6213dcff364197171e9afeaedb337ffb85d | cloew/KaoEnum | /kao_enum/enum.py | 310 | 4 | 4 |
class Enum:
""" Represents an Enum Value """
def __init__(self, name, value):
""" Initialize the enum """
self.name = name
self.value = value
def __repr__(self):
""" Return the string representation of this code """
return self.name |
a57a741e02e04d1f68da45e92fcbf8185c338f36 | mizanur-rahman/HackerRank | /Python3/30 days of code/Day 15: Linked List/Solutions.py | 992 | 4.0625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
#Complete this method
if (head == None):
head = Node(data)
elif (head.next == None):
head.next = Node(data)
else:
self.insert(head.next, data)
return head
'''The function gets called with the whole linked list.
If the list is empty,
insert the element as the head.
Otherwise if there is no element after the head,
put the data after the head.
Otherwise,
call the function with all of the elements except for the current head'''
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
|
ef5382ae6d2ee520c0557fd3e6a391a23aaee001 | Ashokkommi0001/Python-Patterns-Numbers | /_1.py | 234 | 4.09375 | 4 | def _1():
for row in range(7):
for col in range(7):
if (col==3 or row==6) or (row<3 and row+col==2):
print("*",end="")
else:
print(end=" ")
print()
|
a0767955d16ae2f862b4a531a76a8184e8787d48 | LucasVanni/Curso_Python | /Exercícios/ex031.py | 346 | 3.703125 | 4 | viagem = float(input('Qual a distância da sua viagem? '))
if viagem <= 200:
valor = viagem * 0.5
else:
valor = viagem * 0.45
valor = viagem * 0.5 if viagem <= 200 else viagem * 0.45
print('Você está prestes a começar uma viagem de {}KM.'.format(viagem))
print('E o preço da sua passagem será de R${:.2f}'.format(valor))
|
5fdcd02074edb64c999337c33c6c19bc83969632 | LucasVanni/Curso_Python | /AulasCursoemVideo/Desafio 034.py | 246 | 3.890625 | 4 | salario = float(input('Digite o valor do salário: '))
if salario >= 1250.00:
aumento = (salario * 10/100)
else:
aumento = (salario * 15/100)
print('Com o salário de R${}, irá ter um aumento de R${}'.format(salario, aumento)) |
793d6472ec2b57d50651c22328f73ab33782cfac | LucasVanni/Curso_Python | /AulasCursoemVideo/Desafio 020 - nome dos quatro alunos ordem sorteada.py | 412 | 3.703125 | 4 | import random
n1 = str(input('Digite o nome do primeiro aluno a ser sorteado: '))
n2 = str(input('Digite o nome do segundo aluno a ser sorteado: '))
n3 = str(input('Digite o nome do terceiro aluno a ser sorteado: '))
n4 = str(input('Digite o nome do quarto aluno a ser sorteado: '))
lista = [n1, n2, n3, n4]
random.shuffle(lista)
print('A ordem da lista de apresentação será: ')
print(lista)
|
28727bb99a537272c5e73381d48e565bcf9316c3 | LucasVanni/Curso_Python | /Exercícios/ex017.py | 346 | 3.859375 | 4 | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hip = hypot(ca, co)
hi = (co ** 2 + ca ** 2) ** (1/2)# maneira matemática
print('A hipotenusa vai medir {:.2f}'.format(hip))
print('A hipotenusa no método matemático vai medir {:.2f}'.format(hi))
|
fd589aec05438820a5d63f54515ef62ea4d2f5b1 | mrerikas/Mastery_Python | /find_duplicates.py | 523 | 4.0625 | 4 | def find_duplicates(list):
duplicates = []
for item in list:
if list.count(item) > 1:
if item not in duplicates:
duplicates.append(item)
return duplicates
print(find_duplicates(['a', 'b', 'c', 'a', 'd', 'd', 'e', 'f', 'g', 'f']))
# or without function()
list = ['a', 'b', 'c', 'a', 'd', 'd', 'e', 'f', 'g', 'f']
duplicates = []
for items in list:
if list.count(items) > 1:
if items not in duplicates:
duplicates.append(items)
print(duplicates)
|
14743b046284e9c60f213351695433fd0c763a11 | jcheong0428/psy161_assignments | /sandbox20160216.py | 1,050 | 3.84375 | 4 | def size(A):
i=[]
while type(A)==list:
i.append(len(A))
A=A[0]
return tuple(i)
def slicer(lst,slicelist,i=0):
res = []
if isinstance(slicelist,slice):
return res
else:
print lst, slicelist,
for i,e in enumerate(lst[slicelist[i]]):
print i,e
res.append(slicer(e,slicelist(i),i))
def mygen2(lst,slicelist):
""" Returns a slice of your Array.
Input must be a list of tuples with length the same as dimensions.
Only supports 2 ~ 4 dimensions right now...
Examples
--------
>> a=[[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]]
>> A = Array(a)
>> A.mygen2([slice(0,2),slice(0,2),slice(0,2)])
>> [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
maybe use res.append(recursive function here)
"""
res = []
if isinstance(lst,list)&isinstance(slicelist,list):
s = slicelist[0]
for e in lst[s]:
res.append(list(slicer(e,s)))
lst = list(slicer(e,s))
slicelist.pop(0)
return res |
a085d9ff5c97264c048a0f265806c906647d90df | shyam-de/py-developer | /d2exer1.py | 1,091 | 4.1875 | 4 | # program to check wether input number is odd/even , prime ,palindrome ,armstrong.
def odd_even(num):
if num%2==0:
print("number is even")
else:
print( 'number is odd')
def is_prime(num):
if num>1:
for i in range(2,num//2):
if (num%i)==0:
print('number is not prime')
# print(i,"times",num//i,'is'num)
break
else:
print("number is prime")
else:
print("number is not prime")
def is_arm(num):
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**3
temp//=10
if num==sum:
print("number is armstrong")
else :
print("number is not armstrong")
def is_pal(num):
temp=num
rev=0
while num>0:
dig=num%10
rev=rev*10+dig
num=num//10
if temp==rev:
print("number is palindrome")
else:
print(" numer is not palindrome")
num=int(input("Enter a number "))
print(odd_even(num),is_prime(num),is_arm(num),is_pal(num))
|
c0a5c9e9dffd82f9bf748ed09963ebde4e9c8fd1 | ShimizuKo/AtCoder | /ABC/100-109/109/B.py | 233 | 3.5625 | 4 | N = int(input())
word_list = []
ans = "Yes"
for i in range(N):
word = input()
word_list.append(word)
if i != 0:
if not(word[0] == word_list[i - 1][-1] and word_list.count(word) == 1):
ans = "No"
break
print(ans) |
4d6fdfa22d2fb1555731651c32a588dde6552795 | ShimizuKo/AtCoder | /企業コン/三井住友2019/B.py | 120 | 3.609375 | 4 | N = int(input())
ans = ":("
for x in range(1, N + 1):
n = int(x * 1.08)
if n == N:
ans = x
break
print(ans) |
1a2a51b714e82ae71922c9dfb5d3b002923d53b3 | Crow07/python-learning | /python learning/循环/for.py | 390 | 3.984375 | 4 | for i in range(3):
print('loop',i)
for i in range(0,6,2):
print("loop",i)
age_of_crow = 22
count= 0
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_crow:
print("yes,all right")
break
elif guess_age > age_of_crow:
print("smaller")
else:
print("bigger")
else:
print("you have tried too many times") |
d5f5fc08d19273e530ff46658c3b67804bebf92d | tweatherford/COP1000-Homework | /Weatherford_Timothy_A9_Sort_Search_Rainfall.py | 3,810 | 3.703125 | 4 | '''
Assignment#9: Rainfall Version - Sorts data, searches array, and outputs to file.
Programmer: Timothy Weatherford
Course: COP1000 - Intro to Computer Programming
'''
#Initial Variables
rainArray = []
count = 0
file = open("rainfallData.txt","r")
sortStatus = False
outputFile = open("Weatherford_Timothy_A9_Python_Rainfall_Output.txt", "w")
#Helper Methods
#prints header
def makeHeader(text):
print("=-"*30)
print(text)
print("=-"*30)
#writes headers to file
def writeHeader(text):
global outputFile
outputFile.write("=-"*30 + "\n")
outputFile.write(text + "\n")
outputFile.write("=-"*30 + "\n")
#Appends data to array for us
def appendData(rain):
global rainArray
rainArray.append(float(rain))
#Searches the array for a a rain data of the users choice
def searchArray(outputFile):
outputFile = outputFile
count = 0
targetCount = 0
writeHeader("Rain Data Search")
searchString = input("Please enter rain data to search for:")
global rainArray
for rain in rainArray:
if float(rain) == float(searchString):
targetCount += 1
outputFile.write("Your target rain data of " + str(searchString) + " occured " + str(targetCount) + " times." + "\n")
print("-"*10)
print("Your target rain data of " + str(searchString) + " occured " + str(targetCount) + " times." + "and the output has been saved to the file.")
print("-"*10)
#Iterates array and displays each
def displayArray(sortStatus,outputFile):
outputFile = outputFile
count = 0
global rainArray
if sortStatus == True:
makeHeader("Display all rain data(sorted):")
writeHeader("Display all rain datas(sorted):")
else:
makeHeader("Display all rain data(unsorted):")
writeHeader("Display all rain data(unsorted):")
for rain in rainArray:
count += 1
outputFile.write("Rain Data#" + str(count) + " is:" + str(rainArray[count-1]) + "\n")
print("Rain Data#" + str(count) + " is:" + str(rainArray[count-1]))
print("The output has been prepared to the file. Please quit to save.")
#Sorts array
def sortArray(rainArray,targetCount):
#Bubble sort variables
flag = 0
swap = 0
while flag == 0:
flag = 1
swap = 0
while swap < (int(targetCount)-1):
if rainArray[swap] > rainArray[swap + 1]:
tempRain = rainArray[swap]
rainArray[swap] = rainArray[swap + 1]
rainArray[swap + 1] = tempRain
flag = 0
swap = swap + 1
sortStatus = True
print("-"*10)
print("The rain list has been sorted, please re-run 1 from the main menu to prepare the file for output.")
print("-"*10)
return sortStatus
#Main Menu
def mainMenu():
global targetCount, sortStatus, outputFile
makeHeader("Main Menu")
choice = int(input("Please choose 1 to display and output all rain entries to file, 2 to search rain data, 3 to sort rain data, or 4 to quit(writes file to disk):"))
if choice == 1:
displayArray(sortStatus,outputFile)
mainMenu()
elif choice == 2:
searchArray(outputFile)
mainMenu()
elif choice == 3:
sortStatus = sortArray(rainArray,targetCount)
mainMenu()
elif choice == 4:
outputFile.close()
pass
else:
print("Invalid Selection - Please choose again")
mainMenu()
#RAIN ARRAY INTIALIZATION - This handles startup more or less.
makeHeader("Program Startup - Rain Entry")
targetCount = input("How many rain data points are in the input file?(default 60):")
if targetCount == "":
targetCount = 60
while count < int(targetCount):
count +=1
rain = float(file.readline().strip())
appendData(rain)
mainMenu()
|
f179a86035e710a59300a467e2f3cd4e9f8f0b15 | tweatherford/COP1000-Homework | /Weatherford_Timothy_A3_Gross_Pay.py | 1,299 | 4.34375 | 4 | ##-----------------------------------------------------------
##Programmed by: Tim Weatherford
##Assignment 3 - Calculates a payroll report
##Created 11/10/16 - v1.0
##-----------------------------------------------------------
##Declare Variables##
grossPay = 0.00
overtimeHours = 0
overtimePay = 0
regularPay = 0
#For Presentation
print("Payroll System")
print("=-"*30)
##Input Section##
empName = str(input("Enter the Employee's Full Name:"))
hoursWorked = float(input("Enter Hours Worked:"))
payRate = float(input("Enter " + empName + "'s hourly rate of pay:$"))
print("-"*60)
##Logic Functions##
if hoursWorked > 40:
overtimeHours = hoursWorked - 40
regularPay = 40 * payRate
overtimePay = (payRate*1.5) * overtimeHours
grossPay = regularPay + overtimePay
else:
regularPay = hoursWorked * payRate
grossPay = regularPay
#Output
print("=-"*30)
print("Payroll Report for " + empName)
print("=-"*30)
print("--Hours Worked--")
print("Total Hours Worked:" + str(hoursWorked))
print("Overtime Hours:" + str(overtimeHours))
print("--Pay Information--")
print("Regular Pay:$" + str(format(regularPay, "9,.2f")))
print("Overtime Pay:$" + str(format(overtimePay, "9,.2f")))
print("Total Gross Pay:$" + str(format(grossPay, "9,.2f")))
print("=-"*30)
print("End Payroll Report")
|
f9e3d8e6a7ab0bc54e40128daf95ab132f5360f7 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia4/cwiczenia6.py | 245 | 3.65625 | 4 | a = int(input("Podaj liczbę: "))
b = 0
c = 0
while a % 2 == 0 or a % 3 == 0:
b += 1
if a % b == 0:
if a == b:
break
c = a + b
print(b)
else:
if b == a:
break
continue
|
ef8a51fe8281b47ccb7f0e64986aab70d585982a | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia6/cwiczenia2.py | 521 | 3.640625 | 4 | from statistics import median
tab = []
n = int(input("Podaj początek zakresu: "))
x = int(input("Podaj koniec zakresu zakresu: "))
while True:
if n == 0 or x == 0:
print("Podałeś gdzieś zero")
break
else:
for i in range(n, x):
i += 1
tab.append(i)
tab_2 = tab[0:6]
print("Twoja tablica liczb: ", tab_2)
print("Wartość maksymaalna: ", max(tab_2))
print("Wartość minimalna: ", min(tab_2))
print("Średnia: ", len(tab_2))
print("Mediana: ", median(tab_2))
|
6db7314e823010875b7f68d7defd4b094a144cb2 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia9/cwiczenia2.py | 857 | 3.8125 | 4 | import statistics
tel = {
"Jan": "123456789",
"Robert": "123456789",
"Andrzej": "123456789",
"Karol": "123456789",
"Romek": "123456789",
"Szymon": "123456789",
"Grzegorz": "123456789",
"Karolina": "123456789",
"Anna": "123456789",
"Maja": "123456789"
}
"""for i in range(10):
nazwisko = str(input("Podaj nazwisko: "))
numer = str(input("Podaj numer: "))
tel[nazwisko] = numer
"""
print(tel)
telf = list(tel.keys())[0]
tell = list(tel.keys())[len(tel)-1]
print(telf, tell)
tel[telf] = "b"
tel[tell] = "c"
print(tel)
telm1 = statistics.median_low(tel)
telm2 = statistics.median_high(tel)
print(telm1, telm2)
del tel[telm1]
del tel[telm2]
print(tel)
tel.clear()
tel[input("Podaj nazwisko: ")] = input("Podaj numer tel.: ")
tel[input("Podaj nazwisko: ")] = input("Podaj numer tel.: ")
print(tel)
|
5375af97c9022b28682ef915e1bad014247daf7b | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia7/cwiczenie7.py | 1,282 | 3.5 | 4 | import random
tab_r = []
tab_u = []
tab_w = []
print("Zaczynamy losowanie liczb...")
for i in range(0, 6):
a = random.randint(1, 49)
if a in tab_r:
a = random.randint(1, 49)
tab_r.append(a)
if a not in tab_r:
tab_r.append(a)
print("Wylosowałem")
print("Teraz wprowadź swoje liczby")
for i in range(6):
a = int(input("Wprowadź liczby (1-49): "))
if 1 <= a <= 49:
tab_u.append(a)
else:
a = int(input("Wprowadź jeszcze raz (1-49)"))
tab_u.append(a)
print("Wylosowane liczby to: ", tab_r)
print("Twoje liczby: ", tab_u)
print("Sprawdźmy ile trafiłeś...")
tab_u.sort()
tab_r.sort()
# print(tab_u)
# print(tab_r)
for i in range(0, 6):
if tab_r[i] in tab_u:
tab_w.append(tab_r[i])
i += 1
else:
continue
print("O to co trafiłeś: ", tab_w, ". Trafiłeś więc ", len(tab_w))
if len(tab_w) == 0:
print("Nic nie wygrałeś :(")
elif len(tab_w) == 1:
print("Wygrałeś 2 zł")
elif len(tab_w) == 2:
print("Wygrałeś 5 zł")
elif len(tab_w) == 3:
print("Wygrałeś 1000 zł")
elif len(tab_w) == 4:
print("Wygrałeś 20 000 zł")
elif len(tab_w) == 5:
print("Wygrałeś 500 000 zł")
elif len(tab_w) == 6:
print("Wygrałeś 1 000 000 zł!")
|
80c1d701bc33441af1a566dc9853b1b1a89de84b | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia4/cwiczenia2a.py | 141 | 3.640625 | 4 | x = float(-254)
while x >= -320:
while x % 2 != 0 and x % 5 == 0:
print(x)
x -= 1
else:
x -= 1
pass
|
a703c51fb4b25f59051085a1477c78f14144477d | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia5/polacz91011.py | 935 | 3.640625 | 4 | import random
tab = []
print("1 - Lotto")
print("2 - Multi Multi")
print("3 - Mini Lotto")
w = int(input("Wybierz które losowanie chcesz przeprowadzić: "))
if w == 1:
for j in range(0, 6):
i = random.randint(1, 49)
if i in tab:
i = random.randint(1, 49)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
elif w == 2:
for j in range(0, 20):
i = random.randint(1, 80)
if i in tab:
i = random.randint(1, 80)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
elif w == 3:
for j in range(0, 5):
i = random.randint(1, 42)
if i in tab:
i = random.randint(1, 42)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
else:
print("Błąd.")
|
2cdb9ee58bed41b39c88a0e6995e8d8cf59e6684 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia7/cwiczenia2.py | 168 | 3.515625 | 4 | tab = []
for i in range(0, 10):
a = int(input("Podaj dowolną liczbę: "))
tab.append(a)
i += 1
print("Wybrane elementy: ", tab[1], tab[4], tab[7], tab[9]) |
1d9f8283d44840cf14f3177d10e95a282fae61d7 | BVGdragon1025/-wiczenia | /Semestr 1/Prace zaliczeniowe/Program7.py | 2,396 | 4 | 4 | import dateutil.easter
import datetime
def menu():
print("Witaj w programie!")
print("Co chcesz zrobić? ")
print("[1] Dowiedzieć się co było wczoraj i jutro ")
print("[2] Odkryć w jaki dzień się urodziłeś ")
print("[3] Dowiedzieć się kiedy Wielkanoc")
choice = input("Wybierz funkcję: ")
if choice == "1":
days()
elif choice == "2":
birthday()
elif choice == "3":
easter_day()
else:
print("Zły wybór!")
def days():
# Timedelta ustawiona jest, aby pokazywać dzień do przodu
# (lub dzień do tyłu, zależnie od działania)
# Dzisiejsza data
today = datetime.date.today()
print("Dzisiaj mamy: ", today.strftime("%d-%m-%Y"))
# Wyświetlenie wczorajszej daty
yesterday = today - datetime.timedelta(days=1)
print("Wczoraj mieliśmy: ", yesterday.strftime("%d-%m-%Y"))
# Wyświetlenie jutrzejszej daty
tommorrow = today + datetime.timedelta(days=1)
print("Jutro będzie: ", tommorrow.strftime("%d-%m-%Y"))
def birthday():
# Słownik użyty do tłumaczenia nazw angielskich (raczej logiczne)
day_dict = {"Monday": "Poniedziałek",
"Tuesday": "Wtorek",
"Wednesday": "Środa",
"Thursday": "Czwartek",
"Friday": "Piątek",
"Saturday": "Sobota",
"Sunday": "Niedziela"}
day = int(input("Podaj dzień (liczbowo): "))
month = int(input("Podaj miesiąc (liczbowo): "))
year = int(input("Podaj rok (liczbowo, pełny): "))
full_date = datetime.date(year, month, day)
dom = full_date.strftime("%A")
print("Urodziłeś się w: ", day_dict[dom])
def easter_day():
# Tak, skorzystałem z gotowej funkcji z biblioteki dateutil
# Wiem, powinienem napisać to sam
# Ale to było za dużo dla mnie, aby wykalkulować jeden dzień
# I to jeszcze taki losowy, zależny od pełni, innego święta i przesilenia
# Kto na to wpadł, ja sie pytam
# A na rozwiązanie wpadłem kiedy przeszukując Internety i widząc ten sam algorytm wszędzie
# w końcu ktoś na StackOverflow podał tę bibliotękę i stweirdziłem że to jest lepsze rozwiązanie
# Wartość 3 oznacza współczesną metodę, używaną w Polsce
year = int(input("Podaj rok: "))
print("Wielkanoc wypada w: ", dateutil.easter.easter(year, 3))
menu()
|
caddf242f33906c4946ff9491dd58336338c6072 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia.py | 412 | 3.59375 | 4 | x1 = input("Podaj 1 wartość: ")
x2 = input("Podaj 2 wartość: ")
dod = int(x1)+int(x2) # dodawanie wartosci x1 i x2
odj = int(x1)-int(x2) # odejmowanie wartości x1 i x2
mno = int(x1)*int(x2) # mnozenie wartości x1 i x2
dzi = int(x1)/int(x2) # dzielenie wartosci x1 i x2
print("Wynik dodawania: ", dod)
print("Wynik odejmowania: ", odj)
print("Wynik mnożenia: ", mno)
print("Wynik dzielenia: ", dzi)
|
046ecafc48914b85956a7badd6b8500232a57db4 | lathika12/PythonExampleProgrammes | /areaofcircle.py | 208 | 4.28125 | 4 | #Control Statements
#Program to calculate area of a circle.
import math
r=float(input('Enter radius: '))
area=math.pi*r**2
print('Area of circle = ', area)
print('Area of circle = {:0.2f}'.format(area)) |
362eb0297bbb144719be1c76dc4696c141b72017 | lathika12/PythonExampleProgrammes | /sumeven.py | 225 | 4.125 | 4 | #To find sum of even numbers
import sys
#Read CL args except the pgm name
args = sys.argv[1:]
print(args)
sum=0
#find sum of even args
for a in args:
x=int(a)
if x%2==0:
sum+=x
print("Sum of evens: " , sum) |
a1fe59470da2ee519283240483f8fa24917891b3 | lathika12/PythonExampleProgrammes | /ifelsestmt.py | 316 | 4.375 | 4 | #Program for if else statement
#to test if a number is even or odd
x=10
if x%2==0:
print("Even Number" ,x )
else:
print("Odd Number" , x )
#Program to test if a number is between 1 to 10
x=19
if x>=1 and x<=10:
print(x , " is in between 1 to 10. " )
else:
print(x , " is not in between 1 to 10. " ) |
5a44a5e2780e3c2db32b8dd8a46720fa2682655a | RohitGupta06/RohitPythonAssignments | /Module 2/Exercise II-A/math_eq_b.py | 164 | 4.03125 | 4 | # Evaluate using formula
# Initialization
x = 2
y = 5
# Evaluation
A = ((2 * x) + 6.22 * (x + y)) / (x + y)
# Displaying the result
print("The value of A is",A) |
8715a1bb07778f3099ca3d443663d0721ae908bf | RohitGupta06/RohitPythonAssignments | /Module 2/Exercise II-B/upper.py | 193 | 4.375 | 4 | # Taking the string input from user
user_input = input("Please enter your string: ")
# Changing in upper case
updated_string = user_input.upper()
print("The changed string is:",updated_string) |
57b0f6f47db94524924487b5a6780da8855141f9 | naflymim/vscode-python-pandas-work | /dataframe_ex_01.py | 388 | 3.890625 | 4 | import numpy as np
import pandas as pd
array_2d = np.random.rand(3, 3)
# print(array_2d[0, 1])
# print(array_2d[2, 0])
df = pd.DataFrame(array_2d)
print(df.columns)
print(df)
df.columns = ["First", "Second", "Third"]
print(df.columns)
print(df)
print(df["First"][0])
print(df["Second"][2])
print(df["Third"])
df["Third"].index = ['One', 'Two', 'Three']
print(df["Third"])
print(df)
|
070c621faf5ceb32087b3f9ce6bbc2e3b4b100f7 | carfri/D0009E-lab | /labb2-5a.py | 604 | 3.65625 | 4 | import math
def derivative(f, x, h):
k =(1.0/(2*h))*(f(x+h)-f(x-h))
return k
##print derivative(math.sin, math.pi, 0.0001)
##print derivative(math.cos, math.pi, 0.0001)
##print derivative(math.tan, math.pi, 0.0001)
def solve(f, x0, h):
lastX = x0
new = 0.0
while (abs(lastX) - abs(new) > h) or lastX==new:
new = lastX
lastX = lastX - f(lastX)/derivative(f, lastX, h)
return lastX
def function1(x):
return x**2-1
def function2(x):
return 2**x-1
def function3(x):
x-cmath.e**-x
print solve(function2, 4, 0.00001)
|
7d4b9473e8da1f4df6818bd37ec202a1c9644b32 | fitosegrera/simplePerceptron | /app.py | 662 | 3.546875 | 4 | from perceptron import Perceptron
inputs = [-1,-1,1]
weightNum = len(inputs)
weights = 0
learningRate = 0.01
desired = 1
iterate = True
iterCount = 0
ptron = Perceptron()
weights = ptron.setWeights(weightNum)
while iterate:
print "-"*70
print "Initial Weights: ", weights
sum = ptron.activate(weights, inputs)
print "Sum: ", sum
returned = ptron.updateWeights(learningRate, desired, sum)
print "New Weights: ", returned['newWeights']
if not returned['iterate']:
print "Iterations: ", iterCount
iterate = False
print "-"*70
else:
weights = returned['newWeights']
iterCount = iterCount + 1
|
1097ed658416acf59c22137682dc327629e02078 | DiegoC386/Taller-Estructura-de-Control-For | /Ejercicio_10.py | 627 | 3.75 | 4 | #10. El alcalde de Antananarivo contrato a algunos alumnos de la Universidad Ean
#para corregir el archivo de países.txt, ya que la capital de Madagascar NO es rey julien
#es Antananarivo, espero que el alcalde se vaya contento por su trabajo.
#Utilice un For para cambiar ese Dato
with open('paise.txt') as archivo:
lista=[]
for i in archivo:
lista.append(i)
a=" ".join(lista)
if(a=="Madagascar: rey julien\n"):
break
lista=[]
b=a.index(":")
tamaño=len(a)
lista2=[]
for i in range(0,tamaño):
lista2.append(a[i])
lista2.remove("b")
2==("Antananarivo")
lista2.insert(1,2)
print(lista2)
archivo.close() |
4562ef887b02ca21d7e322717c4b1c6f41b21543 | Anna-Joe/Python3-Learning | /exercise/testfunction/city_functions.py | 266 | 3.625 | 4 | def formatted_city_country(city,country,population=0):
if population!=0:
formatted_string=city.title()+','+country.title()+' - population '+str(population)
else:
formatted_string=city.title()+','+country.title()
return formatted_string
|
99ef2163869fda04dbe4f1c23b46e56c14af7a17 | TredonA/PalindromeChecker | /PalindromeChecker.py | 1,822 | 4.25 | 4 | from math import floor
# One definition program to check if an user-inputted word
# or phrase is a palindrome. Most of the program is fairly self-explanatory.
# First, check if the word/phrase in question only contains alphabetic
# characters. Then, based on if the word has an even or odd number of letters,
# begin comparing each letter near the beginning to the corresponding word
# near the end.
def palindromeChecker():
word = input("Please enter a word: ")
if not word.isalpha():
print("Word is invalid, exiting program.")
elif len(word) % 2 == 0:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != (len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
else:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != floor(len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
answer = input("Would you like to use this program again? Type in " +\
"\'Yes\' if you would or \'No\' if not: ")
if(answer == 'Yes'):
palindromeChecker()
elif(answer == 'No'):
print("Thank you for using my program. Have a great day!")
else:
print("Invalid input. Ending program...")
return
palindromeChecker()
|
d11e7f3d340926f13326a0ed63661d049452ac74 | dovelism/Kmeans_4_Recommendation | /Kmeans4MovieRec.py | 6,850 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@Author:Dovelism
@Date:2020/4/5 11:30
@Description: Kmeans'implement for recommendation,using Movielens
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse import csr_matrix
import helper
# Import the Movies dataset
movies = pd.read_csv('movies.csv')
#movies.head()
# Import the ratings dataset
ratings = pd.read_csv('ratings.csv')
#ratings.head()
print('The dataset contains: ', len(ratings), ' ratings of ', len(movies), ' movies.')
genre_ratings = helper.get_genre_ratings(ratings, movies, ['Romance', 'Sci-Fi'], ['avg_romance_rating', 'avg_scifi_rating'])
#genre_ratings.head()
biased_dataset = helper.bias_genre_rating_dataset(genre_ratings, 3.2, 2.5)
print( "Number of records: ", len(biased_dataset))
#biased_dataset.head()
helper.draw_scatterplot(biased_dataset['avg_scifi_rating'],
'Avg scifi rating', biased_dataset['avg_romance_rating'],
'Avg romance rating')
# turn our dataset into a list
X = biased_dataset[['avg_scifi_rating','avg_romance_rating']].values
# TODO: Import KMeans
from sklearn.cluster import KMeans
# TODO: Create an instance of KMeans to find two clusters
#kmeans_1 = KMeans(n_clusters=2)
# TODO: use fit_predict to cluster the dataset
#predictions = kmeans_1.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions)
# TODO: Create an instance of KMeans to find three clusters
#kmeans_2 = KMeans(n_clusters=3)
# TODO: use fit_predict to cluster the dataset
#predictions_2 = kmeans_2.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions_2)
# Create an instance of KMeans to find four clusters
kmeans_3 = KMeans(n_clusters =4)
# use fit_predict to cluster the dataset
predictions_3 = kmeans_3.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions_3)
# Choose the range of k values to test.
# We added a stride of 5 to improve performance. We don't need to calculate the error for every k value
possible_k_values = range(2, len(X)+1, 5)
#print(possible_k_values)
# Calculate error values for all k values we're interested in
errors_per_k = [helper.clustering_errors(k, X) for k in possible_k_values]
# Look at the values of K vs the silhouette score of running K-means with that value of k
list(zip(possible_k_values, errors_per_k))
# Plot the each value of K vs. the silhouette score at that value
fig, ax = plt.subplots(figsize=(16, 6))
ax.set_xlabel('K - number of clusters')
ax.set_ylabel('Silhouette Score (higher is better)')
ax.plot(possible_k_values, errors_per_k)
# Ticks and grid
xticks = np.arange(min(possible_k_values), max(possible_k_values)+1, 5.0)
ax.set_xticks(xticks, minor=False)
ax.set_xticks(xticks, minor=True)
ax.xaxis.grid(True, which='both')
yticks = np.arange(round(min(errors_per_k), 2), max(errors_per_k), .05)
ax.set_yticks(yticks, minor=False)
ax.set_yticks(yticks, minor=True)
ax.yaxis.grid(True, which='both')
# Create an instance of KMeans to find seven clusters
kmeans_4 = KMeans(n_clusters=7)
# use fit_predict to cluster the dataset
predictions_4 = kmeans_4.fit_predict(X)
# plot
helper.draw_clusters(biased_dataset, predictions_4, cmap='Accent')
biased_dataset_3_genres = helper.get_genre_ratings(ratings, movies,
['Romance', 'Sci-Fi', 'Action'],
['avg_romance_rating', 'avg_scifi_rating', 'avg_action_rating'])
biased_dataset_3_genres = helper.bias_genre_rating_dataset(biased_dataset_3_genres, 3.2, 2.5).dropna()
print( "Number of records: ", len(biased_dataset_3_genres))
biased_dataset_3_genres.head()
X_with_action = biased_dataset_3_genres[['avg_scifi_rating',
'avg_romance_rating',
'avg_action_rating']].values
# TODO: Create an instance of KMeans to find seven clusters
kmeans_5 = KMeans(n_clusters=7)
# TODO: use fit_predict to cluster the dataset
predictions_5 = kmeans_5.fit_predict(X_with_action)
# plot
helper.draw_clusters_3d(biased_dataset_3_genres, predictions_5)
# Merge the two tables then pivot so we have Users X Movies dataframe
ratings_title = pd.merge(ratings, movies[['movieId', 'title']], on='movieId' )
user_movie_ratings = pd.pivot_table(ratings_title, index='userId', columns= 'title', values='rating')
print('dataset dimensions: ', user_movie_ratings.shape, '\n\nSubset example111:')
user_movie_ratings.iloc[:6, :10]
n_movies = 30
n_users = 18
most_rated_movies_users_selection = helper.sort_by_rating_density(user_movie_ratings, n_movies, n_users)
print('dataset dimensions: ', most_rated_movies_users_selection.shape)
most_rated_movies_users_selection.head()
helper.draw_movies_heatmap(most_rated_movies_users_selection)
user_movie_ratings = pd.pivot_table(ratings_title, index='userId', columns= 'title', values='rating')
most_rated_movies_1k = helper.get_most_rated_movies(user_movie_ratings, 1000)
sparse_ratings = csr_matrix(pd.SparseDataFrame(most_rated_movies_1k).to_coo())
# 20 clusters
predictions = KMeans(n_clusters=20, algorithm='full').fit_predict(sparse_ratings)
predictions.shape
type(most_rated_movies_1k.reset_index())
max_users = 70
max_movies = 50
clustered = pd.concat([most_rated_movies_1k.reset_index(), pd.DataFrame({'group':predictions})], axis=1)
helper.draw_movie_clusters(clustered, max_users, max_movies)
# Pick a cluster ID from the clusters above
cluster_number = 6
# filter to only see the region of the dataset with the most number of values
n_users = 75
n_movies = 300
cluster = clustered[clustered.group == cluster_number].drop(['index', 'group'], axis=1)
cluster = helper.sort_by_rating_density(cluster, n_movies, n_users)
print(cluster)
helper.draw_movies_heatmap(cluster, axis_labels=False)
cluster.fillna('').head()
# Pick a movie from the table above since we're looking at a subset
movie_name = "American Beauty (1999)"
cluster[movie_name].mean()
# The average rating of 20 movies as rated by the users in the cluster
cluster.mean().head(20)
# TODO: Pick a user ID from the dataset
# Look at the table above outputted by the command "cluster.fillna('').head()"
# and pick one of the user ids (the first column in the table)
user_id = 5
#print(cluster)
# Get all this user's ratings
user_2_ratings = cluster.loc[user_id, :]
# Which movies did they not rate? (We don't want to recommend movies they've already rated)
user_2_unrated_movies = user_2_ratings[user_2_ratings.isnull()]
print(user_2_unrated_movies.head())
# What are the ratings of these movies the user did not rate?
avg_ratings = pd.concat([user_2_unrated_movies, cluster.mean()], axis=1, join='inner').loc[:,0]
# Let's sort by rating so the highest rated movies are presented first
avg_ratings.sort_values(ascending=False)[:20]
|
bf9df75e6eb4ccf29ec267fbec0836f73ec99394 | pavan142/spellwise | /spellwise/algorithms/soundex.py | 4,076 | 3.59375 | 4 | from typing import List
from ..utils import sort_list
from .base import Base
class Soundex(Base):
"""The Soundex algorithm class for for identifying English words which are phonetically similar
Reference: https://nlp.stanford.edu/IR-book/html/htmledition/phonetic-correction-1.html
"""
def __init__(self) -> None:
"""The constructor for the class"""
super(Soundex, self).__init__()
def _pre_process(self, word: str) -> str:
"""Pre-processor for Soundex
Args:
word (str): The word to be pre-processed
Returns:
str: The pre-processed word
"""
word = word.lower()
word = "".join(_w for _w in word if _w in self._alphabet)
first_letter = word[0]
word = word[1:]
for _w in "aeiouhwy":
word = word.replace(_w, "0")
for _w in "bfpv":
word = word.replace(_w, "1")
for _w in "cgjkqsxz":
word = word.replace(_w, "2")
for _w in "dt":
word = word.replace(_w, "3")
word = word.replace("l", "4")
for _w in "mn":
word = word.replace(_w, "5")
word = word.replace("r", "6")
for _w in "0123456789":
while _w * 2 in word:
word = word.replace(_w * 2, _w)
word = word.replace("0", "")
word = first_letter + word + "0" * 3
word = word[0:4]
return word
def _replace(self, a: str, b: str) -> float:
"""Cost to replace the letter in query word with the target word
Args:
a (str): First letter
b (str): Second letter
Returns:
float: The cost to replace the letters
"""
if a == b:
return 0
return 1
def get_suggestions(self, query_word: str, max_distance: int = 0) -> List[dict]:
"""Get suggestions based on the edit-distance using dynamic-programming approach
Args:
query_word (str): The given query word for suggesting indexed words
max_distance (int, optional): The maximum distance between the words indexed and the query word. Defaults to 0
Returns:
List[dict]: The word suggestions with their corresponding distances
"""
processed_query_word = self._pre_process(query_word)
def search(dictionary_node, previous_row):
"""Search for the candidates in the given dictionary node's children
Args:
dictionary_node (Dictionary): The node in the Trie dictionary
previous_row (list): The previous row in the dynamic-programming approach
"""
for current_source_letter in dictionary_node.children:
current_row = [previous_row[0] + 1]
for i in range(1, len(processed_query_word) + 1):
value = min(
previous_row[i] + 1,
current_row[i - 1] + 1,
previous_row[i - 1]
+ self._replace(
current_source_letter, processed_query_word[i - 1]
),
)
current_row.append(value)
if (
current_row[-1] <= max_distance
and dictionary_node.children[current_source_letter].words_at_node
is not None
):
for word in dictionary_node.children[
current_source_letter
].words_at_node:
suggestions.append({"word": word, "distance": current_row[-1]})
if min(current_row) <= max_distance:
search(dictionary_node.children[current_source_letter], current_row)
suggestions = list()
first_row = range(0, len(processed_query_word) + 1)
search(self._dictionary, first_row)
suggestions = sort_list(suggestions, "distance")
return suggestions
|
88f082a0fed712513d2968e461b00eed445526ab | sss4920/python_list | /python_basic/lab7_5.py | 465 | 3.9375 | 4 | '''
학번과 점수를 dictionary 를 이용하여 5개 정도 정의한다
사용자로부터 학번과 점수를 입력받아 만약 기존에 해당 학번이 없으면 dictionary 에 추가한다
성적이 높은 순으로 출력하라.
'''
a={'201914009':10,'20000000':20,'100000000':30,'342ㅕ49':40,'24234':50}
s = input("학번:")
s1 = int(input("점수:"))
if s not in a:
a[s]=s1
li=sorted(a,key=a.__getitem__,reverse=True)
for x in li:
print(x)
|
8c657b49cd4e298ea17b2b5573e1f7438e49a680 | sss4920/python_list | /python_basic/lab5_10.py | 146 | 4.125 | 4 | """
람다함수를 이용하여 절대값을 출력하라.
l=[-3,2,1]
"""
L = (lambda x:-x if x<0 else x)
l=[-3,2,1]
for f in l:
print(L(f)) |
db36adc273138a78165f9e36a09d17835a172688 | sss4920/python_list | /python_basic/lab02_3.py | 179 | 3.890625 | 4 | """
문제: 원주율을 상수 PI로 정의하고 반지름을 입력받아 원의 넓이를 출력하라
"""
PI=3.141592
r=int(input('반지름: '))
print('넓이:'+str(PI*r*r)) |
6a6547bf2b47de116649d2a8f2465262114b1898 | sss4920/python_list | /python_basic/lab7_6.py | 565 | 3.78125 | 4 | '''
이름: 전화번호를 가지는 딕셔너리를 생성하여 5개의 원소로 초기화하고
이름을 입력하면 해당 전화번호를 출력하고
해당이름이 없다면 전화번호가 없습니다를 출력
마지막에 전체의 이름과 전화번호를 출력
'''
dic = {"김수현":"1111","ㅇㅇ":"2222","ㄱㄱ":"3333","ㄴㄴ":"4444","ㄷㄷ":"5555"}
name = input("이름:")
if name in dic.keys():
print("%s 전화번호는 %s"%(name,dic[name]))
else:
print("해당 전화번호가 없습니다.")
for x in dic:
print(x,dic[x])
|
92b81af21b824c8ce3bf88d939f61f697ba3994f | sss4920/python_list | /python_basic/lab4_7.py | 239 | 3.765625 | 4 | """
팩토리얼 계산과정과 값을 출력하라.
"""
a = int(input("양의 정수:"))
b = " "
sum = 1
for x in range(a,0,-1):
sum *= x
if x != 1:
b+=str(x)+"*"
else:
b+=str(x)
print("%d! ="%a,b,"= %d"%sum)
|
4f4a148d6e3745e74a0c2c4bded6f284cf54a992 | sss4920/python_list | /python_basic/lab5_8.py | 581 | 4.09375 | 4 | """
매개변수로 넘어온 리스트에서 최소값과 최대값을 반환하는 함수 min_max를 정의한다
프로그램에서
ㅣ=[3,5,-2,20,9]를 정의한 후 , min_max를 호출하여 최소값은 m1최대값은 m2에 저장하고 이를 출력하라
"""
def min_max(l):
"""
:param l: 리스트
:return: 최소값,최대값
"""
min1=l[0]
max1=l[0]
for x in l:
if min1>x:
min1=x
if max1<x:
max1=x
return min1,max1
l=[3,5,-2,20,9]
m1,m2=min_max(l)
print("최소값:%d"%m1)
print("최대값:%d"%m2)
|
66f78d22a851951ee3d7a66ade4e75d6e2dbc4e7 | sss4920/python_list | /python_basic/lab2_8.py | 250 | 3.796875 | 4 | """
사용자로부터 x좌표와 y좌표를 입력받아, 원점으로부터의 거리를 출력한다.
"""
from math import *
a = int(input("x좌표:"))
b = int(input("y좌표:"))
distance = sqrt(a*a + b*b)
print("원점까지의 거리",distance)
|
fd35e801070b1beb3e12a927293fd2ec5d16314e | sss4920/python_list | /python_basic/ㅇㅇ.py | 140 | 3.546875 | 4 | test=int(input())
for x in range(test):
a,b=input().split()
a=int(a)
temp=''
for y in b:
temp+=y*a
print(temp)
|
39929223fd0fa0624313263ef16cee26b11cbb50 | sss4920/python_list | /cruscal/1922.py | 809 | 3.6875 | 4 | import sys
input = sys.stdin.readline
def union(array,a,b):
left = find(array, a)
right = find(array, b)
if left>right:
array[left]=right
else:
array[right]=left
def find(array, a):
if a==array[a]:
return a
return find(array,array[a])
def cycle(array, a, b):
if find(array, a)==find(array, b):
return True
return False
computer = int(input())
line = int(input())
array = [] #이거는 그냥 케이스의 배열이고
family = [ i for i in range(computer+1)]
for x in range(line):
temp = list(map(int,input().split()))
array.append(temp)
array.sort(key = lambda x : x[2])
sum=0
for temp in array:
if not cycle(family, temp[0],temp[1]):
union(family,temp[0],temp[1])
sum+=temp[2]
print(sum) |
c0bbb76252f023738872456fb82bfd0e23eb3a50 | kdserSH/Training-Python-SHMCC | /OOP/OOP-CS.py | 970 | 3.984375 | 4 | #实例可以修改实例变量,不能修改类变量,程序调用时优先寻找实例变量,其次再找类变量。
class role(object): #定义类
n = 123 #类变量
def __init__(self,name,role,weapon,life_value=100,money=15000):#构造函数,init是传参数用的,用于调用方法时传参数。
self.name=name #实例变量
self.role=role
self.weapon=weapon
self.life_value=life_value
self.money=money
def get_shot(self): #类的方法、功能
print('Oh no,%s got shot'%self.name)
def shot(self):
print('%s Shooting'%self.name)
def buygun(self,gun_name):
print('%s got %s'%(self.name,gun_name))
r1=role('gsj','police','m4a')#类的实例化(aka初始化一个类)
r2=role('ddd','terroist','ak47')
r1.buygun('ak47')
r2.get_shot()
print(role.n)
r1.name='ak47'
r2.name='m4a'
r1.bulletproof=True
print(r1.bulletproof)
print(r1.n,r1.name)
print(r2.n,r2.name)
|
6e82dc8d6d525baa5c9bd4e27cadc1827cfc9d65 | ravenclaw-10/Python_basics | /lists_prog/avg_of_2lists.py | 355 | 3.90625 | 4 | '''Write a Python program to compute average of two given lists.
Original list:
[1, 1, 3, 4, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 4, 5, 7, 8]
Average of two lists:
3.823529411764706
'''
list1=[1,1,3,4,4,5,6,7]
list2=[0,1,2,3,4,4,5,7,8]
sum=0
for i in list1:
sum+=i
for i in list2:
sum+=i
avg=sum/(len(list1)+len(list2))
print(avg) |
a113879ec0112ff4c269fb2173ed845c29a3b5e5 | ravenclaw-10/Python_basics | /lists_prog/max_occur_elem.py | 708 | 4.25 | 4 | # Element with maximum occurence in a list=[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2] .
#Python program to check if the elements of a given list are unique or not.
n=int(input("Enter the no. of element in the list(size):"))
list1=[]
count=0
max=0
print("Enter the elements of the lists:")
for i in range(0,n):
elem=input()
list1.append(elem)
max_elem=list1[0]
for i in range(0,n):
count=0
for j in range(0,n):
if list1[i]==list1[j]:
count+=1
if max<=count:
max=count
max_elem=list1[i]
if max==1:
print("The given list have unique elements")
else:
print("Maximum occered element:",max_elem) |
44dd23671d3c68a9356024dcf69785c0c520033e | ravenclaw-10/Python_basics | /lists_prog/string_first_last_same.py | 409 | 3.953125 | 4 | '''Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
'''
list1=['abc','xyz','aba','1221']
list2=[]
for i in range(0,len(list1)):
if list1[i][0]==list1[i][-1]:
list2.append(list[i])
print(len(list2)) |
bea7e17c53d59d9b6f9047eeef0bb63995cc5669 | jennywei1995/sc-projects | /StanCode-Projects/break_out_game/breakoutgraphics_extension.py | 17,526 | 3.671875 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
-------------------------
File: Breakoutgraphics_extension.py
Name: Jenny Wei
-------------------------
This program creates a breakout game.
This file is the coder side, which build the important components of the game.
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
import random
# constants
BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing.
BRICK_WIDTH = 40 # Height of a brick (in pixels).
BRICK_HEIGHT = 15 # Height of a brick (in pixels).
BRICK_ROWS = 10 # Number of rows of bricks.
BRICK_COLS = 10 # Number of columns of bricks.
BRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels).
BALL_RADIUS = 10 # Radius of the ball (in pixels).
PADDLE_WIDTH = 75 # Width of the paddle (in pixels).
PADDLE_HEIGHT = 15 # Height of the paddle (in pixels).
PADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels).
INITIAL_Y_SPEED = 7.0 # Initial vertical speed for the ball.
MAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball.
class BreakoutGraphicsExtension:
"""
This class will build the components of the game.
"""
def __init__(self, ball_radius=BALL_RADIUS, paddle_width=PADDLE_WIDTH,
paddle_height=PADDLE_HEIGHT, paddle_offset=PADDLE_OFFSET,
brick_rows=BRICK_ROWS, brick_cols=BRICK_COLS,
brick_width=BRICK_WIDTH, brick_height=BRICK_HEIGHT,
brick_offset=BRICK_OFFSET, brick_spacing=BRICK_SPACING,
title="Jenny Wei's Breakout"):
# Create a graphical window, with some extra space.
self.window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing
self.window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)
self.window = GWindow(width=self.window_width, height=self.window_height, title=title)
# Create a paddle.
self.paddle = GRect(paddle_width, paddle_height, x=(self.window.width - paddle_width) / 2,
y=self.window.height - paddle_offset)
self.paddle.filled = True
self.paddle.fill_color = 'black'
self.window.add(self.paddle)
# Center a filled ball in the graphical window.
self.ball_radius = ball_radius
self.original_x = self.window.width / 2 - self.ball_radius
self.original_y = self.window.height / 2 - self.ball_radius
self.ball = GOval(2 * self.ball_radius, 2 * self.ball_radius,
x=self.original_x, y=self.original_y)
self.ball.filled = True
self.window.add(self.ball)
# Default initial velocity for the ball.
self.__dx = 0
self.__dy = 0
self.original_dx = self.__dx
self.original_dy = self.__dy
# to make sure the ball will go up when it hits the paddle
self.up_initial_y_speed = -INITIAL_Y_SPEED # to make sure the ball will go up when it hits the paddle
# Draw bricks.
for i in range(brick_rows):
for j in range(brick_cols):
self.brick_offset = brick_offset
self.brick_spacing = brick_spacing
self.brick = GRect(brick_width, brick_height, x=0 + i * (brick_width + brick_spacing),
y=self.brick_offset + j * (brick_height + brick_spacing))
self.brick.filled = True
if j // 2 == 0:
self.brick.fill_color = 'tan'
self.brick.color = 'tan'
elif j // 2 == 1:
self.brick.fill_color = 'dark_salmon'
self.brick.color = 'dark_salmon'
elif j // 2 == 2:
self.brick.fill_color = 'indian_red'
self.brick.color = 'indian_red'
elif j // 2 == 3:
self.brick.fill_color = 'slate_gray'
self.brick.color = 'slate_gray'
elif j // 2 == 4:
self.brick.fill_color = 'cadet_blue'
self.brick.color = 'cadet_blue'
self.window.add(self.brick)
self.brick_num = brick_cols * brick_rows
# Initialize our mouse listeners.
onmouseclicked(self.check_game_start)
# to draw the score label
self.score = 0
self.score_label=GLabel(f'Score:{self.score}')
self.score_label.font = '-20'
self.score_label.color = 'black'
self.window.add(self.score_label,x=10, y=self.window.height-10)
# to draw the life label
self.life_label = GLabel(f'Life: ')
self.life_label.font = '-20'
self.life_label.color = 'black'
self.window.add(self.life_label, x=self.window.width-self.life_label.width-20, y=self.window.height - 10)
# to draw the start label
self.start_label = GLabel('Please click the mouse to start!')
self.start_label.font = '-20'
self.start_label.color = 'black'
self.window.add(self.start_label,x=self.window.width / 2 - self.start_label.width / 2,
y=self.window.height / 2 - self.start_label.height / 2 -20)
# to draw the win label
self.win_label=GLabel(f'You win! You got: {self.score}')
self.win_label.font = '-20'
self.win_label.color = 'black'
# to draw the lose label
self.lose_label = GLabel(f'Game over! You got: {self.score}')
self.lose_label.font = '-20'
self.lose_label.color = 'black'
def paddle_move(self, mouse):
"""
The paddle will move while the user move the mouse.
The user's mouse will be at the middle of the paddle
"""
self.paddle.x = mouse.x - self.paddle.width / 2
if self.paddle.x+self.paddle.width>self.window.width:
self.paddle.x = self.window.width - self.paddle.width
if self.paddle.x <= 0:
self.paddle.x = 0
def check_game_start(self, mouse):
"""
once the user click the mouse, the game will start that the function
will give the ball velocity to move.
once the ball is out of the window, the user have to click the mouse again
to drop the ball.
"""
if self.ball.x == self.original_x and self.ball.y == self.original_y:
onmousemoved(self.paddle_move)
self.window.remove(self.start_label)
# give the ball velocity
if self.__dx == 0:
self.__dy = INITIAL_Y_SPEED
self.__dx = random.randint(1, MAX_X_SPEED)
if random.random() > 0.5:
self.__dx = -self.__dx
print(f'{self.__dy}')
def bounce_back(self):
"""
once the ball bump into the wall,
it will bounce back.
"""
if self.ball.x <= 0 or self.ball.x + self.ball.width >= self.window.width:
self.__dx = -self.__dx
if self.ball.y <= 0:
self.__dy = -self.__dy
def check_paddle(self):
"""
To check whether the ball bump into any object, including the brick and the paddle.
If the ball hit the brick, the brick will be cleared,
and it will bounce back if it doesn't hit anything anymore.
once the ball hit the paddle, the ball will bounce back.
"""
left_up = self.window.get_object_at(self.ball.x, self.ball.y)
right_up = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y)
left_down = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height)
right_down = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height)
# when ball hits the paddle
if left_up is self.paddle or right_up is self.paddle:
pass
elif left_down is self.paddle and right_down is None:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle and left_down is self.paddle:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle and left_down is None:
self.__dy = self.up_initial_y_speed
if self.ball.y + self.__dy >= self.paddle.y:
if self.ball.y + self.__dy <= self.paddle.y+self.paddle.height:
if left_down is self.paddle:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle:
self.__dy = self.up_initial_y_speed
# to make the ball faster while the user reach certain scores
if self.score >= 150:
if self.__dy < 0:
self.__dy = -9
elif self.__dy > 0:
self.__dy = 9
if self.score >= 600:
if self.__dy < 0:
self.__dy = -10.5
elif self.__dy > 0:
self.__dy = 10.5
def check_brick(self):
"""
To check whether the ball hits the brick.
If the ball hit the brick, the brick will be cleared,
and it will bounce back if it doesn't hit things anymore.
"""
left_up = self.window.get_object_at(self.ball.x, self.ball.y)
right_up = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y)
left_down = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height)
right_down = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height)
# if the ball's left_up corner hit the brick
if left_up is not None:
if left_up is not self.score_label:
if left_up is not self.life_label and left_up is not self.paddle:
if left_up is not self.paddle:
self.window.remove(left_up)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if left_up.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif left_up.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif left_up.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif left_up.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's right_up corner hit the brick
elif right_up is not None:
if right_up is not self.score_label:
if right_up is not self.life_label:
if right_up is not self.paddle:
self.window.remove(right_up)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if right_up.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif right_up.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif right_up.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif right_up.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's left_down corner hit the brick
elif left_down is not None:
if left_down is not self.score_label:
if left_down is not self.life_label:
if left_down is not self.paddle:
self.window.remove(left_down)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if left_down.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif left_down.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif left_down.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif left_down.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's right_down corner hit the brick
elif right_down is not None:
if right_down is not self.score_label:
if right_down is not self.life_label:
if right_down is not self.paddle:
self.window.remove(right_down)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if right_down.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif right_down.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif right_down.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif right_down.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
def get_dx(self):
"""
to return the value of the dx to the user side
"""
return self.__dx
def get_dy(self):
"""
to return the value of the dy to the user side
"""
return self.__dy
def re_set_ball(self):
"""
once the ball is out of the window, its position will be reset.
It's velocity will be set to 0 again. And the user will have to
click the mouse to continue the game.
"""
self.__dy = 0
self.__dx = 0
self.ball.x = self.original_x
self.ball.y = self.original_y
onmouseclicked(self.check_game_start)
|
7e3d68562bfb27ebe0dec9fd95a2a1e8b488ad60 | LevinWeinstein/attendance_formatter | /attendance.py | 4,733 | 3.625 | 4 | #! /usr/bin/env python3
"""
Filename : attendance.py
Author : Levin Weinstein
Organization : USF CS212 Spring 2021
Purpose : Convert a directory full of attendance lists to a single, aggregated attendance sheet
Usage : ./attendance.py --directory="DIRECTORY" --event=[lecture|lab] > ${OUTPUT_FILE}
"""
import os
import sys
import argparse
class Attendee:
""" A class for an individual Attendee, with a name and an email"""
def __init__(self, name, email):
""" constructor for the Attendee class
:param name: the name of the attendee
:param email: the email of the attendee
"""
self.name = name
self.email = email
def __eq__(self, other):
""" Equals operator for the Attendee class
We're just using email to determine equivalency for the sake of simplicity.
:param other: the other Attendee to which to compare
"""
return self.email == other.email
def __hash__(self):
""" Hash code """
return hash(self.email)
def __str__(self):
""" convert an Attendee to string """
return self.name + ',' + self.email
class Attendance:
""" A class to take the attendance.
Contains methods to:
- add an attendee
- add a whole file
- add a whole directory of files
- a getter for an unmodifiable set of the attendees
- merge another Attendance set
"""
def __init__(self, event_type=""):
""" An initializer for the Attendance """
self._attendees = set()
self.event_type = event_type
def add_attendee(self, line):
""" Method to add an attendee
:param line: the line from which to parse and add an attendee
"""
fields = line.split(',')
if len(fields) == 4:
name, email, _, _ = fields
else:
name, email, _ = fields
new_attendee = Attendee(name, email)
self._attendees.add(new_attendee)
def add_file(self, filename):
""" Method to add all attendees from a file
:param filename: the name of the file
"""
local_attendance = Attendance(self.event_type)
try:
with open(filename) as f:
# Skip the lines above the whitespace, since they are not names
next(f) # skip the top part header line
_, topic, _, _, _, _, _, _ = next(f).split(',')
print(topic, file=sys.stderr)
if self.event_type == "lab" and "code review" in topic.lower():
pass
elif self.event_type not in topic.lower():
print(f"Wrong event type. Skipping {filename}", file=sys.stderr)
return
next(f) # Skip the blank line
next(f) # Skip the header line with the title "Name", "Email", etc
for line in f:
local_attendance.add_attendee(line)
self.merge(local_attendance)
except Exception as e:
print(f"Error parsing file: {filename}: {e}", file=sys.stderr)
def add_all_files(self, root_directory):
"""Adds all files from the given directory
:param root_directory: the directory within which to search for attendance files
"""
for (root, dirs, files) in os.walk(root_directory):
for f in files:
self.add_file(os.path.join(root, f))
def attendees(self):
"""A getter for the _attendees set
:return: an immutable frozenset with the contents of the _attendees set
"""
return frozenset(self._attendees)
def merge(self, other):
"""Merge another Attendance sheet into this one
:param other: the other Attendance sheet with which to merge
"""
self._attendees |= other.attendees()
def __str__(self):
""" convert the Attendance to string """
attendees = sorted(self._attendees, key=lambda person: person.email)
return "\n".join([str(person) for person in attendees])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Convert a directory full of attendance lists to a single, aggregated attendance sheet")
parser.add_argument("-e", "--event", help="The event type. Can be either lecture or lab", required=True)
parser.add_argument("-d", "--directory", help="The directory within which to parse.", required=True)
arguments = parser.parse_args()
attendance = Attendance(arguments.event)
attendance.add_all_files(arguments.directory)
print(attendance)
|
6094c69f6d4fa7a0bb59fc8da0eb7fb379832514 | Boukos/AlgorithmPractice | /recursion/rec_len.py | 328 | 4.1875 | 4 | def rec_len(L):
"""(nested list) -> int
Return the total number of non-list elements within nested list L.
For example, rec_len([1,'two',[[],[[3]]]]) == 3
"""
if not L:
return 0
elif isinstance(L[0],list):
return rec_len(L[0]) + rec_len(L[1:])
else:
return 1 + rec_len(L[1:])
print rec_len([1,'two',[[],[[3]]]]) |
609f6c607a6f8d3f363cd4c983c9c552fc58a6b1 | NIKHILDUGAR/codewars4kyuSolutions | /Snail.py | 352 | 3.59375 | 4 | # https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
def snail(array):
res = []
while len(array) > 1:
res = res + array.pop(0)
res = res + [row.pop(-1) for row in array]
res = res + list(reversed(array.pop(-1)))
res = res + [row.pop(0) for row in array[::-1]]
return res if not array else res + array[0]
|
7788a1f6524ed2aff9aa7b3368ff41b13418a4c4 | Uvernes/DSRI_2021 | /utility/nearest_rotation_matrix.py | 1,761 | 3.515625 | 4 | import numpy as np
import math
import sys
"""
Input
-----
R - 3 by 3 matrix we want to find nearest rotation matrix for
Output
------
Nearest rotation matrix
"""
def exact_nearest_rotation_matrix(R):
A = np.dot(R.transpose(), R)
m = np.trace(A) / 3
Q = A - m * np.identity(3)
q = np.linalg.det(Q) / 2
p = np.sum(np.power(Q, 2)) / 6
sp = math.sqrt(p)
theta = math.atan2(math.sqrt(abs(p**3 - q**2)), q) / 3
ctheta = math.cos(theta)
stheta = math.sin(theta)
l1 = abs(m + 2*sp*ctheta)
l2 = abs(m - sp*(ctheta+math.sqrt(3)*stheta))
l3 = abs(m - sp*(ctheta-math.sqrt(3)*stheta))
a0 = math.sqrt(l1*l2*l3)
a1 = math.sqrt(l1*l2)+math.sqrt(l1*l3)+math.sqrt(l3*l2)
a2 = math.sqrt(l1)+math.sqrt(l2)+math.sqrt(l3)
dem = a0*(a2*a1-a0)
b0 = (a2*(a1**2) - a0 * ((a2**2) + a1))/dem
b1 = (a0+a2*((a2**2) - 2*a1))/dem
b2 = a2/dem
U = np.dot(np.dot(b2, A), A) - np.dot(b1, A) + np.dot(b0, np.eye(3))
return np.dot(R, U)
# --------------- Testing -----------------------#
# tMatrix = np.array([[0.74359, -0.66199, 0.08425],
# [0.21169, 0.35517, 0.91015],
# [-0.63251, -0.65879, 0.40446]])
#
# closest = exact_nearest_rotation_matrix(tMatrix)
# print("Matrix: ")
# print(tMatrix)
# print("Nearest rotation matrix: ")
# print(closest)
# # Matrix multiplication below is eye(3), as expected
# print("Matrix multiplication:")
# np.savetxt(sys.stdout, np.dot(closest, closest.transpose()), '%.5f')
# print("---------------")
# matrix = np.array([[1, 2, 3], [4, 5, 6]])
# print(matrix)
# print(np.sum(matrix))
# print(np.power(matrix, 2))
# print(np.sum(np.power(matrix, 2)))
|
cb227b2f3eb1500e66e84c4461846205e4c4ab63 | eyeCube/Softly-Into-the-Night-OLD | /levels.py | 3,835 | 3.578125 | 4 | '''
levels.py
level design algorithms
'''
import libtcodpy as libtcod
import random
from const import *
import tilemap
# generate
# main procedural level generator
# Parameters:
# Map : TileMap object (pointer)
# level : current dungeon level that we're creating
# nRooms : maximum number of "rooms" to generate on this floor
def generate(Map, level, nRooms=50):
if level == 0:
# create base
Map.cellular_automata(
FUNGUS,FLOOR,8, (-1, -1,-1,-1,0, 1,1,1,1,), simultaneous=True )
# create rooms
elif level == 1:
#unfinished code...
floor = tilemap.TileMap(ROOMW,ROOMH)
hyper = tilemap.TileMap(ROOMW,ROOMH)
for rr in range(nRooms):
build_random_room(hyper)
#try to put this room on the floor
# algorithm assumes a blank TileMap object is passed in
def build_random_room(Map):
#pick a type of room to place on the map
choices = ("cave","box","cross","circle","cavern",)
roomType = random.choice(choices)
if roomType == "cave": #small cave-like room
drunkardWalk(Map, 3, 10, 0.5, (1,1,1,1,1,1,1,1,))
elif roomType == "box": #rectangle
pass
elif roomType == "cross": #two rectangles overlaid
pass
elif roomType == "circle":
pass
elif roomType == "cavern": #large cave
pass
print("New room created of type {}".format(roomType))
#
# drunken walk algorithm
# Parameters:
# walks number of walks to go on
# length length of each walk
# bounciness tendency to remain around origin rather than branch out
# weights iterable w/ directional weights in 8 directions
# - index 0 is 0 degrees, 1 is 45 deg, etc.
def drunkardWalk(Map, walks, length, bounciness, weights):
xp = 15
yp = 15
for i in range(10): # clearing where you start
for j in range(10):
self.tile_change(xp-5+i,yp-5+j,T_FLOOR)
self.tile_change(xp,yp,T_FLOOR)
for i in range(6000):
xp+=int(random.random()*3)-1
yp+=int(random.random()*3)-1
xp=maths.restrict(xp, 0,w-1)
yp=maths.restrict(yp, 0,h-1)
self.tile_change(xp,yp,T_FLOOR)
for x in range(1,4):
for y in range(1,2):
xx=maths.restrict(x+xp-1, 0,w-1)
yy=maths.restrict(y+yp-1, 0,h-1)
self.tile_change(xx,yy,T_FLOOR)
self.tile_change(xp,yp,T_STAIRDOWN)
#
#UNFINISHED...
# file == .lvl file to load from when creating the cells
'''def make_celledRoom(cols,rows,Map,file):
# read from the file
if file[:-4] != ".lvl":
print("ERROR: File '{}' wrong file type (must be '.lvl'). Aborting...".format(file))
raise
mode=0
try:
with open(file, "r") as f:
numCells = f.readline().strip()
cellw = f.readline().strip()
cellh = f.readline().strip()
cy=0
for line in f:
if mode==0:
if line.strip().lower() == "center":
mode=1 #begin reading in the cell data
elif mode==1:
cx=0
for char in line.strip():
if char=='#':
Map.tile_change(cx,cy,)
cx+=1
cy+=1
#
except FileNotFoundError:
print("ERROR: File '{}' not found. Aborting...".format(file))
raise
'''
'''# for each cell in the room
for cc in range(cols):
for rr in range(rows):
# for each tile in each cell
for xx in range(cellw):
for yy in range(cellh):
Map.tile_change(x,y,T_FLOOR)'''
#make_celledRoom(16,12,5,5,)
|
15f68fe0b019bb466d2d7bcfbd83c6baabf2efc4 | eyeCube/Softly-Into-the-Night-OLD | /searchFiles.py | 925 | 4.125 | 4 | #search a directory's files looking for a particular string
import os
#get str and directory
print('''Welcome. This script allows you to search a directory's
readable files for a particular string.''')
while(True):
print("Current directory:\n\n", os.path.dirname(__file__), sep="")
searchdir=input("\nEnter directory to search in.\n>>")
find=input("Enter string to search for.\n>>")
#search each (readable) file in directory for string
for filename in os.listdir(searchdir):
try:
with open( os.path.join(searchdir,filename)) as file:
lineNum = 1
for line in file.readlines():
if find in line:
print(filename, "| Line", lineNum)
lineNum +=1
except Exception as err:
pass
print("End of report.\n------------------------------------------")
|
9b1bc8b4678f0961b00ed39cb8f3f62a1cbab015 | sahilchutani91/facial_keypoints | /models.py | 4,312 | 3.59375 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
# input WXH 96X96, after convolution (96-4)/1 + 1 = 93X93; pooling -> 46X46
# input WXH 46X46, after convolution (46-3)/1 + 1 = 44X44; pooling -> 22X22
# input WXH 22X22, after convolution (22-2)/1 + 1 = 21X21; pooling -> 10X10
# input WXH 10X10, after convolution (10-1)/1 + 1 = 10X10; pooling -> 5X5
# input WXH 224X224, after convolution (224 - 4)/1 + 1; pooling -> 110x110
# input WXH 110X110, after convolution (110 - 3)/1 + 1; pooling -> 54x54
# input WXH 224X224, after convolution (54 - 2)/1 + 1; pooling -> 26x26
# input WXH 224X224, after convolution (26 - 1)/1 + 1; pooling -> 13x13
# Convlution layers
self.conv1 = nn.Conv2d(1, 32, 4)
self.conv2 = nn.Conv2d(32, 64, 3)
self.conv3 = nn.Conv2d(64, 128, 2)
self.conv4 = nn.Conv2d(128, 256, 1)
# Maxpool
self.pool = nn.MaxPool2d(2,2)
# fully connected layers
self.fc1 = nn.Linear(256*13*13,1000 )
self.fc2 = nn.Linear(1000, 1000)
self.fc3 = nn.Linear(1000, 136)
# dropouts
self.drop1 = nn.Dropout(p=0.1)
self.drop2 = nn.Dropout(p=0.2)
self.drop3 = nn.Dropout(p=0.3)
self.drop4 = nn.Dropout(p=0.4)
self.drop5 = nn.Dropout(p=0.5)
self.drop6 = nn.Dropout(p=0.6)
# initializing weights
# initialize convolutional layers to random weight from uniform distribution
for conv in [self.conv1, self.conv2, self.conv3, self.conv4]:
I.uniform_(conv.weight)
# initialize fully connected layers weight using Glorot uniform initialization
for fc in [self.fc1, self.fc2, self.fc3]:
I.xavier_uniform_(fc.weight, gain=I.calculate_gain('relu'))
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
# normalize
self.norm = nn.BatchNorm1d(136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## Full Network
## Input -> conv1 -> Activation1 -> pool -> drop1 -> conv2 -> Activation2 -> pool -> drop2
## -> conv3 -> Activation3 -> pool -> drop3 -> conv4 -> Activation4 -> pool -> drop4 ->
## flatten -> fc1 -> Activation5 -> drop5 -> fc2 -> Activation6 -> drop6 -> fc3
## Activation1 to Activation5 are Exponential Linear Units
## Activation6 is Linear Activation Function
x = self.pool(F.elu(self.conv1(x)))
x = self.drop1(x)
x = self.pool(F.elu(self.conv2(x)))
x = self.drop2(x)
x = self.pool(F.elu(self.conv3(x)))
x = self.drop3(x)
x = self.pool(F.elu(self.conv4(x)))
x = self.drop4(x)
x = x.view(x.size()[0], -1)
x = F.elu(self.fc1(x))
x = self.drop5(x)
x = F.relu(self.fc2(x))
x = self.drop6(x)
x = self.fc3(x)
x = self.norm(x)
return x
|
00573e96c1c60760e541eb3c56859594e59eecc9 | ministry78/pythonStudy | /HeadFirstPython/test.py | 785 | 3.71875 | 4 | # -*- coding: UTF-8 -*-
__author__ = 'drudy'
import random
secret = random.randint(1,100)
guess = 0
tries = 0
print "你好,我是电脑机器人,接下来我们开始一个猜数字的游戏!"
print "游戏规则是:我会随机给1至100的数字,你来猜我给的数字,猜对了有奖品哦!机会只有6次哦!"
while guess != secret and tries < 6:
guess = input("你猜的数字是多少,请输出来?")
if guess < secret:
print "小了哦!还有机会哦"
elif guess > secret:
print "大了哦!还有机会哦"
# tries = tries + 1
if guess == secret:
print "真棒,你猜对了,快去领奖吧!"
else:
print "真抱歉,机会已经用完了哦,祝你下次好运!"
print "真实的数字是", secret
|
551d3fc22b4c95da30104a073383c1e463bd7f5a | mnjey/RSA | /seventh_frame_wordlist_attack.py | 1,667 | 3.609375 | 4 | #By now,we have found that the structure of plaintext frame.
#In this program,we give the prefix of the fourth plaintext frame.And we already have get the sixth plaintext frame which ends with "." and the eighth plaintext frame is " "Logic",we just construct a wordlist of the words which looks meaningful.
import os
import os.path
import sys
import copy
import binascii
import math
os.chdir("./fujian2")
list_dir=os.listdir('.')
frame_list=[]
E_attemp=3
plain_pre="9876543210abcdef000000060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
#The seventh plaintext frame starts with the string,plain_pre.
potential_ending=[' It says',' It said',' That is',' He says',' He said'] #This is our wordlist.The seventh plaintext frame probably ends with these words with length 8.
for frame_file in list_dir:
with open(frame_file) as fd:
code_str=fd.readline()
N=int(code_str[0:256],16) #extract N in the frame
e=int(code_str[256:512],16) #extract e in the frame
c=code_str[512:768].lower() #extract c in the frame
frame_list.append((frame_file,e,N,c))
for item_0 in frame_list: #We just try all the items in the wordlist to see which is the plaintext message.
for item in potential_ending:
plain_num=int(plain_pre+binascii.b2a_hex(item),16)
if(item_0[3].lstrip('0') in hex(pow(plain_num,item_0[1],item_0[2]))):
print "Decoding "+item_0[0]+"......"
print "The plaintext message is "+item
|
dc58c81a1ae7e98ab3f20f62ff3067b576e0f4f9 | sasuketttiit/Hacker-Rank | /hurdle_race.py | 138 | 3.53125 | 4 | def hurdleRace(k, height):
potion = 0
max_jump = max(height)
if k < max_jump:
potion = max_jump - k
return potion
|
bfa76a889d6e60cc8e1cbd408f90217e07da3284 | NagarajuSaripally/PythonCourse | /Methods/nestedStatementsAndScope.py | 727 | 3.75 | 4 | '''
Scope is LEGB rule:
Local: Names assigmned in any way with in a function
E: Enclosing function locals : Names in the local scope of any and all enclosing function
Global : Names assigned at the tope-level of a module file or declared ina def with in the file:
B : Built-in - Names preassigned in the built in names module: open, range, syntax error
'''
name = 'This is a global String'
def greet():
name = "Sammy"
def hello():
print("hello " + name)
hello()
greet()
print(name)
'''
if we use global keyword, if we change any local scope that impacts the global scope:
'''
x = 50
def func():
global x
print(f'X is {x}')
x = 200
print(f'Hey I am locally changed {x}')
func()
print(f'Global X is {x}') |
8774264a6b3b9972dcda87929f0943e96d3906e6 | NagarajuSaripally/PythonCourse | /ObjectAndDataStructureTypes/someFunMethods.py | 8,191 | 4.21875 | 4 | """
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True
"""
def sleep_in(weekday, vacation):
if not weekday or vacation:
return True
else:
return False
"""
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
monkey_trouble(True, True) → True
monkey_trouble(False, False) → True
monkey_trouble(True, False) → False
"""
def monkey_trouble(a_smile, b_smile):
if (a_smile and b_smile) or (not a_smile and not b_smile):
return True
return False
"""
Given two int values, return their sum. Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
"""
def sum_double(a, b):
if a == b:
return (a + b) * 2
else:
return a + b
"""
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
"""
def diff21(n):
subtractedValue = abs(n - 21)
if n > 21:
return 2 * subtractedValue
return subtractedValue
"""
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.
parrot_trouble(True, 6) → True
parrot_trouble(True, 7) → False
parrot_trouble(False, 6) → False
"""
def parrot_trouble(talking, hour):
if talking and ( hour < 7 or hour > 20):
return True
else:
return False
"""
Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.
makes10(9, 10) → True
makes10(9, 9) → False
makes10(1, 9) → True
"""
def makes10(a, b):
if a == 10 or b == 10 or a + b == 10:
return True
else:
return False
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) → True
near_hundred(90) → True
near_hundred(89) → False
"""
def near_hundred(n):
if n in range(90, 111) or n in range(190, 211):
return True
else:
return False
"""
Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.
pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True
"""
def pos_neg(a, b, negative):
if negative:
return (a < 0 and b < 0)
else:
return (a < 0 and b > 0) or (a > 0 and b < 0)
"""
Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged.
not_string('candy') → 'not candy'
not_string('x') → 'not x'
not_string('not bad') → 'not bad'
"""
def not_string(str):
if len(str) >= 3 and str[0] == 'n' and str[1] == 'o' and str[2] == 't':
return str
else:
return 'not ' + str
"""
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).
missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'
"""
def missing_char(str, n):
myString = ''
for index, character in enumerate(str):
if index != n:
myString += character
return myString
"""
Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'
"""
def front_back(str):
if len(str) <= 1:
return str
else:
first = str[-1]
last = str[0]
return first + str[1:len(str)-1] + last
"""
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.
front3('Java') → 'JavJavJav'
front3('Chocolate') → 'ChoChoCho'
front3('abc') → 'abcabcabc'
"""
def front3(str):
if len(str) < 3:
return '' + (str * 3)
else:
return '' + (str[:3] * 3)
"""
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'
"""
def string_times(str, n):
return ''+ str * n
"""
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;
front_times('Chocolate', 2) → 'ChoCho'
front_times('Chocolate', 3) → 'ChoChoCho'
front_times('Abc', 3) → 'AbcAbcAbc'
"""
def front_times(str, n):
if len(str) >= 3:
myString = str[0:3]
return '' + myString * n
else:
return '' + str * n
"""
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
string_bits('Hello') → 'Hlo'
string_bits('Hi') → 'H'
string_bits('Heeololeo') → 'Hello'
"""
def string_bits(str):
return str[::2]
"""
Given a non-empty string like "Code" return a string like "CCoCodCode".
string_splosion('Code') → 'CCoCodCode'
string_splosion('abc') → 'aababc'
string_splosion('ab') → 'aab'
"""
def string_splosion(str):
count = 0
resultString = ""
while count < len(str):
for index, character in enumerate(str):
if(count >= index):
resultString += character
count += 1
return resultString
"""
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') → 1
last2('xaxxaxaxx') → 1
last2('axxxaaxx') → 2
"""
def last2(str):
# Screen out too-short string case.
if len(str) < 2:
return 0
# last 2 chars, can be written as str[-2:]
last2 = str[len(str)-2:]
count = 0
# Check each substring length 2 starting at i
for i in range(len(str)-2):
sub = str[i:i+2]
if sub == last2:
count = count + 1
return count
"""
Given an array of ints, return the number of 9's in the array.
array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3
"""
def array_count9(nums):
count = 0
for num in nums:
if num == 9:
count += 1
return count
"""
Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.
array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False
"""
def array_front9(nums):
return (9 in nums[0:4])
"""
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
"""
def array123(nums):
if len(nums) >= 3:
for ind, lst in enumerate(nums):
if(ind+2) <= len(nums)-1:
if nums[ind] == 1 and nums[ind+1] == 2 and nums[ind+2] ==3:
return True
return False
"""
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0
"""
def string_match(a, b):
count = 0
for ind, character in enumerate(a):
for i, char in enumerate(b):
if (a[ind:ind+2] == b[i:i+2]) and (len(a[ind:ind+2]) > 1) and (len(b[i:i+2])>1) and (ind == i):
count += 1
return count |
8097283ba70a2e1ee33c31217e4b9170a45f2dd1 | NagarajuSaripally/PythonCourse | /StatementsAndLoops/loops.py | 2,014 | 4.75 | 5 | '''
Loops: iterate through the dataypes that are iterable, iterable datatypes in python or in any language
string, lists, tuples, dictionaries
keywords to iterate through these iterables:
#for
syntax
for list_item in list_items:
print(list_item)
'''
# lists:
my_list_items = [1,2,3,4,5,6]
for my_list_item in my_list_items:
print(my_list_item)
# strings
mystring = 'Hello World!'
for eachChar in mystring:
print(eachChar)
#without assigning varibles
for variable in 'Good Morning':
print(variable)
# here instead of each character, we can print what ever the string that we want many times as string length
# so instead of putting a variable name we can use _ there
for _ in 'Hello World!':
print('cool!')
# tuples:
tup = (1,2,3)
for eachTup in tup:
print(eachTup)
# Tuple unpacking, sequence contain another tuples itself then for will upack them
my_tuples = [(1,2),(3,4),(5,6),(7,8),(9,0)]
print("length of my_tuples: {}".format(len(my_tuples)))
for item in my_tuples:
print(item)
# this is called tuple unpacking. techincally we don't need paranthesis like (a,b) it can be just like a,b
for (a,b) in my_tuples:
print(a)
print(b)
#dictionaries:
d = {'k1': 1, 'K2': 2, 'K3': 3}
for item in d:
print(item)
for value in d.values():
print(value)
'''
While loop, it continues to iterate till the condition satisfy
syntax:
while conition:
# do something
while condition:
# do something:
else:
# do something else:
'''
x = 0
while x < 5:
print(f'The current value of x is {x}')
x += 1
while x < 10:
print(f'The current value of x is {x}')
x += 1
else:
print('X is not should not greater than 10')
'''
useful keywords in loops
break, continue, pass
pass: do nothing at all
'''
p = [1,2,3]
for item in p:
#comment
pass # it just passes, in pythong for loops we need at least on statement in loop
print("Passed");
letter = 'something here'
for let in letter:
if let == 'e':
continue
print(let)
for let in letter:
if let == 'e':
break
print(let) |
30cf7566ca858b10b86bf6ffc72826de02134db2 | NagarajuSaripally/PythonCourse | /Methods/lambdaExpressionFiltersandMaps.py | 1,141 | 4.5 | 4 | '''
Lambda expressions are quick way of creating the anonymous functions:
'''
#function without lamda expression:
def square(num):
return num ** 2
print(square(5))
#converting it into lambda expression:
lambda num : num ** 2
#if we want we can assign this to variable like
square2 = lambda num : num ** 2. # we are not going to use this very often, cause lamda function are anonymous
print(square2(5))
print(list(map(lambda num : num **2, [1,2,3,4])))
'''
Map: map() --> map(func, *iterables) --> map object
'''
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
#if I wanna get sqaure for all the list items, we can use map function, instead of for loop, for loop is costly
#Method 1:
for item in map(square, my_nums):
print(item)
#method 2:
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'''
Filter: iterate function that returns either true or false
'''
def check_even(num):
return num % 2 == 0
my_numbers = [1,2,3,4,5,6]
print(list(filter(check_even, my_numbers))) |
06d57c0fd60d591256825eb4992e2eded1d6b70a | GabrieLima-dev/udacity_exercises | /teste.py | 190 | 3.625 | 4 | idade_inteiro = int(input())
idade = idade_inteiro
if idade < 12:
print('crianca')
elif idade < 18:
print('Adolecente')
elif idade < 60:
print('Adulto')
else:
print('Idoso')
|
3f947479dbb78664c2f12fc93b926e26d16d2c34 | ankurkhetan2015/CS50-IntroToCS | /Week6/Python/mario.py | 832 | 4.15625 | 4 | from cs50 import get_int
def main():
while True:
print("Enter a positive number between 1 and 8 only.")
height = get_int("Height: ")
# checks for correct input condition
if height >= 1 and height <= 8:
break
# call the function to implement the pyramid structure
pyramid(height)
def pyramid(n):
for i in range(n):
# the loop that controls the blank spaces
for j in range(n - 1 - i):
print(" ", end="")
# the loop that controls and prints the bricks
for k in range(i + 1):
print("#", end="")
print(" ", end="")
for l in range(i + 1):
# the loop that control the second provided pyramid
print("#", end="")
# goes to the next pyramid level
print()
main()
|
27dc314ba44397a66b2f0916dc25df92d1d8535b | Zeriuno/adventofcode | /2016/d4.py | 1,381 | 3.515625 | 4 | def get_ID_tot(param):
"""
Opens the param file, looks for the real rooms and returns the sum of their sector IDs
"""
tot_ID = 0
list = open(param, "r")
for r in list:
r = Room(r)
if (r.is_real):
tot_ID += room.ID
return tot_ID
class Room:
"""
Room object.
"""
def __init__(self):
"""
Creation of a Room.
room1 = Room(aaaaa-bbb-z-y-x-123[abxyz])
self.checksum contains only the checksum, without the brackets: "abxyz"
self.ID contains only the ID number: 123
self.string contains only the letters of the room, without dashes: "aaaaabbbzyx"
self.is_real is set to True if the name follows the rules of a real room
"""
self.checksum = self.split('[')[-1][:-1]
self.ID = int(self.split('-')[-1].split('[')[0])
self.string = ''
for bit in self.split('-')[:-1]:
self.string += bit
occurrencesletters = []
occurrences = []
for letter in self.string:
if(letter in occurrencesletters):
occurrences[occurrencesletters.index(letter)] += 1
else:
occurrencesletters.append(letter)
occurrences.append(1)
# now occurrences is an unordered list of the occurrences
self.occurrences = collection.Counter(self.string)
if():
self.is_real = True
else:
self.is_real = False
2.b Order the ties alphabetically
3. Check the 5 most frequent letters appear in alphabetical order: self.is_real
1. Take a room name.
|
e10a267a92be6ae4eb564140f7fc1d9fdd80b53e | Everton42/video-youtube-rsa | /criptografia-cifra-de-cesar/criptografia.py | 391 | 3.578125 | 4 | def cripto_cesar(texto,p):
cifra = ''
for i in range(len(texto)):
char = texto[i]
if(char.isupper()):
cifra += chr((ord(char) + p - 65) % 26 + 65)
else:
cifra += chr((ord(char) + p - 97) % 26 + 97)
return cifra
texto = 'Nininini'
p = 28
print('texto: ',texto)
print('padrao: ' + str(p))
print('cifra: ' + cripto_cesar(texto,p))
|
86589672dfb4163954b2b7454a0f7d275bad8938 | nedstarksbastard/LeetCode_Py | /leetcode.py | 3,480 | 3.75 | 4 |
def twoSum( nums, target):
"""
https://leetcode.com/problems/two-sum/description/
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for index, num in enumerate(nums):
if target - num in d.keys():
return [d[target-num], index]
d[num] = index
# nums = [2, 7, 11, 15]
# target = 18
# print(twoSum(nums, target))
def reverse(num):
"""
:type x: int
:rtype: int
"""
#return int(''.join(list(str(x))[::-1]))
if num < -2147483648 or num > 2147483647:
return 0
negativeFlag = False
if (num < 0):
negativeFlag = True
num = -num
prev_rev_num, rev_num = 0,0
while (num != 0):
curr_digit = num % 10
rev_num = (rev_num * 10) + curr_digit
if (rev_num - curr_digit) // 10 != prev_rev_num:
print("WARNING OVERFLOWED!!!\n")
return 0
prev_rev_num = rev_num
num = num // 10
return -rev_num if negativeFlag else rev_num
#print(reverse(1534236469))
def lengthOfLongestSubstring( s):
"""
:type s: str
:rtype: int
"""
i, ans = 0, 0
d = dict()
for j, char in enumerate(s):
if char in d:
i = max(d[char], i)
ans = max(ans, j-i+1) #sliding window
d[char] = j+1
return ans
#lengthOfLongestSubstring("abcabcbb")
def hammingDistance(x, y):
"""
https://leetcode.com/problems/hamming-distance/description/
:type x: int
:type y: int
:rtype: int
"""
def getBinary(num):
import collections
deq = collections.deque()
while (num > 0):
deq.appendleft(num % 2)
num = num // 2
return deq
x, y = getBinary(x), getBinary(y)
length = abs(len(x) - len(y))
if len(x) > len(y):
y.extendleft([0] * length)
else:
x.extendleft([0] * length)
distance = 0
for i, j in zip(x,y):
if i != j:
distance +=1
return distance
#print(hammingDistance(3,5))
def singleNumber(nums):
"""
https://leetcode.com/problems/single-number/description/
:type nums: List[int]
:rtype: int
"""
#return filter(lambda x: nums.count(x)==1, nums).__next__()
#return 2*sum(set(nums)) - sum(nums)
a = 0
for i in nums:
a ^= i
return a
#print(singleNumber([5,2,2]))
def is_one_away(first: str, other: str) -> bool:
"""Given two strings, check if they are one edit away. An edit can be any one of the following.
1) Inserting a character
2) Removing a character
3) Replacing a character"""
skip_difference = {
-1: lambda i: (i, i+1), # Delete
1: lambda i: (i+1, i), # Add
0: lambda i: (i+1, i+1), # Modify
}
try:
skip = skip_difference[len(first) - len(other)]
except KeyError:
return False # More than 2 letters of difference
for i, (l1, l2) in enumerate(zip(first, other)):
if l1 != l2:
i -= 1 # Go back to the previous couple of identical letters
break
# At this point, either there was no differences and we exhausted one word
# and `i` indicates the last common letter or we found a difference and
# got back to the last common letter. Skip that common letter and handle
# the difference properly.
remain_first, remain_other = skip(i + 1)
return first[remain_first:] == other[remain_other:]
print(is_one_away('pale', 'ale')) |
f82577df1e996d7a18832b14f029d767235ee714 | tckl91/02-Pig-Latin | /pig_latin.py | 1,855 | 3.78125 | 4 | def is_vowel(ch):
if ch in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:
return True
else:
return False
def cut(word):
if len(word) == 1:
return (word, '')
else:
for n in range(0, len(word)):
if is_vowel(word[n]):
return (word[:n], word[n:])
def piggify_word(word):
if len(word) == 1:
if is_vowel(word[0]):
return word + 'hay'
else:
return word + 'ay'
else:
if is_vowel(word[0]):
return word + 'hay'
else:
return cut(word)[1] + cut(word)[0] + 'ay'
def clean_word(raw_word):
if len(raw_word) == 0:
return ('')
else:
for n in range (0, len(raw_word)):
if not raw_word[n].isalpha():
return (raw_word[:n], raw_word[n:])
return (raw_word, '')
def get_raw_words (sentence):
return sentence.split()
def piggify_pairs(pair_list):
new_list = []
for n in range (0, len(pair_list)):
pig_word = piggify_word(pair_list[n][0])
add_punctuation = (pig_word, pair_list[n][1])
new_list.append(add_punctuation)
return new_list
def reassemble(pair_list):
sentence = ''
for n in range(0, len(pair_list)):
if n == (len(pair_list) - 1):
sentence += pair_list[n][0] + pair_list[n][1]
else:
sentence += pair_list[n][0] + pair_list[n][1] + ' '
return sentence
def piggify_sentence(sentence):
clean_list = []
for n in get_raw_words(sentence):
clean_list.append(clean_word(n))
return reassemble(piggify_pairs(clean_list))
def main():
sentence = input('Please enter your sentence to be translated into Pig Latin: ')
print (piggify_sentence(sentence))
if __name__ == "__main__":
main()
|
b9233a3d426c1e037e23ca892c7426b8acdaf153 | kenglishhi/kenglish-ics699 | /sandbox/whitespace_test.py | 526 | 3.609375 | 4 | #!/usr/bin/python
from string import *
dna = """
aaattcctga gccctgggtg caaagtctca gttctctgaa atcctgacct aattcacaag
ggttactgaa gatttttctt gtttccagga cctctacagt ggattaattg gccccctgat
tgtttgtcga agaccttact tgaaagtatt caatcccaga aggaagctgg aatttgccct
tctgtttcta gtttttgatg agaatgaatc ttggtactta gatgacaaca tcaaaacata
ctctgatcac cccgagaaag taaacaaaga tgatgaggaa ttcatagaaa gcaataaaat
gcatggtatg tcacattatt ctaaaacaa """
print "BEFORE:"
print dna
for s in whitespace:
dna = replace(dna, s, "")
print "AFTER:"
print dna
|
eeecf3d2b4bf2cee7e59ba996215d4c85d6cd944 | scienceacademy/python_examples | /conditional_examples.py | 274 | 4.09375 | 4 | print("Enter two numbers")
x = int(input("x: "))
y = int(input("y: "))
if x > y:
print("x is bigger")
elif y > x:
print("y is bigger")
else:
print("they're the same")
age = int(input("How old are you? "))
if age > 12 and age < 20:
print("You're a teenage") |
be5f73e2e74a92d9d0c94eef14c6771a6c642a27 | rameym/UW-IT-FDN-100 | /hw5.py | 3,319 | 4.4375 | 4 | #!/usr/bin/env python3
''' Assignment 5
1. Create a text file called Todo.txt using the following data, one line per row:
Clean House,low
Pay Bills,high
2. When the program starts, load each row of data from the ToDo.txt text file
into a Python list. You can use the readlines() method to import all lines as a list.
3. After you load the data into a list, loop through the list and add each item
as a "key,value" pair a new dictionary. Look back through the lecture notes
at "split" and "indexing".
4. After you have added existing data to the dictionary, use the menu structure
included in the template to allow the user to Add or Remove tasks from the
dictionary using numbered choices.
5. Create your menu by adding a print statement that tells the user which
option to select. Something similar to this:
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
6. Save the data from the table into the Todo.txt file when the program exits.
7. For two points, let us know what you would like feedback on and/or have questions about '''
infile = "todo.txt"
# read in ToDo.txt here using readlines
with open(infile, 'r') as todo_file:
lines = todo_file.readlines()
task_dict = {}
# create empty dictionar to store data as we loop
for line in lines:
task = line.split(",")[0].strip()
priority = line.split(",")[1].strip()
task_dict[task] = priority
# add line to add new key to a dictionary here using task ask key and priority as value
while(True):
print ("""
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
""")
strChoice = str(input("Which option would you like to perform? [1 to 5] - "))
print() #adding a new line
# Choice 1 -Show the current items in the table
if (strChoice.strip() == '1'):
for key, val in task_dict.items():
print(key, val)
# loop through the dictionary here and print items
# Choice 2 - Add a new item to the list/Table
elif (strChoice.strip() == '2'):
new_key = input("Enter the additional task: ")
new_value = input("Rank the priority from low to high: ")
task_dict[new_key] = new_value
# add a new key, value pair to the dictionary
# Choice 3 - Remove a new item to the list/Table
elif (strChoice == '3'):
remove_key = input("Enter the task name to remove: ")
if remove_key in task_dict.keys():
del task_dict[remove_key]
else:
input("Your task is not in the dictionary, please check spelling and try again: ")
# locate key and delete it using del function
# Choice 4 - Save tasks to the ToDo.txt file
elif (strChoice == '4'):
with open(infile, 'w') as fh:
# fh.writelines(task_dict)
for key, value in task_dict.items():
fh.write('{},{}\n'.format(key, value))
# open a file handle
# loop through key, value and write to file
# Chocie 5- end the program
elif (strChoice == '5'):
print("Goodbye!")
break #and Exit the program
|
fda998e4ecca4119973210c287411f612af6bc0f | saffiya/quiz_game | /quiz/quiz.py | 1,463 | 4.0625 | 4 | def show_menu():
print("1. Ask questions")
print("2. Add a question")
print("3. Exit game")
option = input("Enter option: ")
return option
def ask_questions():
questions = []
answers = []
with open("questions.txt", "r") as file:
lines = file.read().splitlines()
for i, text in enumerate(lines):
if i%2 == 0:
questions.append(text)
else:
answers.append(text)
number_of_questions = len(questions)
questions_and_answers = zip(questions, answers)
score = 0
for question, answer in questions_and_answers:
guess = input(question + "> ")
if guess == answer:
score += 1
print("right!")
print(score)
else:
print("wrong!")
print("You got {0} correct out of {1}".format(score, number_of_questions))
def add_question():
print("")
question = input("Enter a question\n> ")
print("")
print("OK then, tell me the answer")
answer = input("{0}\n> ".format(question))
file = open("questions.txt","a")
file.write(question + "\n")
file.write(answer + "\n")
file.close()
def game_loop():
while True:
option = show_menu()
if option == "1":
ask_questions()
elif option == "2":
add_question()
elif option == "3":
break
else:
print("Invalid option")
print("")
game_loop() |
75189396066ec93f1ed51015039fa29011aeb5a5 | odayibas/astair | /controller-logic/pmvModel.py | 4,834 | 3.5625 | 4 | import math
import sys
from datetime import datetime
"""
--- Input Parameters ---
Air Temperature (Celsius) -> ta
Mean Radiant Temperature (Celsius) -> tr
Relative Air Velocity (m/s) -> vel
Relative Humidity (%) -> rh
Metabolic Rate (met) -> met (1.2)
Clothing (clo) -> clo (0.3)
External Work (Generally 0) -> work
"""
# This function calls all necessary functions.
def pmv(ta, tr, vel, rh, met, clo, work = 0):
pa = calculatePA(rh, ta)
icl = calculateICL(clo)
mw = calculateMW(met, work)
fcl = calculateFCL(icl)
hcf = calculateHCF(vel)
taa = convertKelvin(ta)
tra = convertKelvin(tr)
tcla = calculateTCLA(taa, ta, icl)
tcl, xn, hc = calculateTCL(icl, fcl, taa, tra, mw, tcla, hcf)
totalLost = calculationTotalLost(mw, pa, met, ta, fcl, xn, tra, tcl, hc)
ts = calculationTS(met)
pmv = calculatePVM(ts, mw, totalLost)
ppd = calculatePPD(pmv)
return pmv, ppd
# This function displays pmv and ppd in screen.
def display(pmv, ppd, cel):
print(f"PMV Value: {pmv}")
print(f"PPD Value: {ppd}")
degree = round(pmv, 0)
print(f'New A/C Degree: {cel + degree}')
# This function calculates pressure.
# Unit -> Pa
def calculatePA(rh, ta):
return rh * 10.0 * math.exp(16.6536 - 4030.183 / (ta + 235.0))
# This function calculates thermal insulation of the clothing.
# Unit -> m^2 * K/W
def calculateICL(clo):
return 0.155 * clo
# This function calculates internal heat production in the human body,
# Using metabolic rate and external work.
# met&work unit -> met
# Unit -> W/m^2
def calculateMW(met, work):
m = met * 58.15 # Convert W/m^2
w = work * 58.15 # Convert W/m^2
return m + w
# This function calculates clothing area factor
def calculateFCL(icl):
if(icl < 0.078):
fcl = 1.0 + 1.29 * icl
else:
fcl = 1.05 + 0.645 * icl
return fcl
# This function calculates heat transfer coefficient by forced convection.
# Unit -> W/(m^2*K)
def calculateHCF(vel):
return 12.1 * (vel**0.5)
# This function converts celsius to kelvin,
# for air temp. and mean radiant temp.
def convertKelvin(temp):
return temp + 273
# -----
# This functions calculate clothing surface temperature.
# Unit -> Celsius (C)
def calculateTCLA(taa, ta, icl):
return taa + (35.5 - ta) / (3.5 * icl + 0.1)
def calculateTCL(icl, fcl, taa, tra, mw, tcla, hcf):
p1 = icl * fcl
p2 = p1 * 3.96
p3 = p1 * 100.0
p4 = p1 * taa
p5 = 308.7 - 0.028 * mw + p2 * (tra/100) ** 4
xn = tcla / 100.0
xf = xn / 50.0
n = 0
eps = 0.00015
hc = 1.0
while(abs(xn-xf) > eps):
xf = (xf + xn) / 2.0
hcn = 2.38 * abs(100.0 * xf - taa)**0.25
if(hcf > hcn):
hc = hcf
else:
hc = hcn
xn = (p5 + p4 * hc - p2 * xf**4.0) / (100.0 + p3 * hc)
n = n + 1
if(n>150):
print("Error")
exit()
tcl = 100.0 * xn - 273.0
return tcl, xn, hc
# -----
# This function calculates total lost.
def calculationTotalLost(mw, pa, m, ta, fcl, xn, tra, tcl, hc):
m = m * 58.15 # Convert met to W/m^2
hl1 = 3.05 * 0.001 * (5733.0 - 6.99 * mw - pa) # heat loss diff. through skin
if(mw > 58.15): # heat loss by sweating
hl2 = 0.42 * (mw - 58.15)
else:
hl2 = 0.0
hl3 = 1.7 * 0.00001 * m * (5867.0 - pa) # latent respiration heat loss
hl4 = 0.0014 * m * (34.0 - ta) # dry respiration heat loss
hl5 = 3.96 * fcl * (xn**4.0 - (tra/100.0)**4.0) # heat loss by radiation
hl6 = fcl * hc * (tcl - ta)
return hl1 + hl2 + hl3 + hl4 + hl5 + hl6 # Sum of loss
# This function calculates thermal sensation transfer coeefficient.
def calculationTS(m):
return 0.303 * math.exp(-0.036 * (m * 58.15)) + 0.028
# This function calculates predicted percentage dissat (PPD).
def calculatePPD(pmv):
return 100 - 95 * math.exp(-0.03353 * (pmv**4) - 0.2179 * (pmv**2))
# This function calculates predicted mean vote (PVM).
def calculatePVM(ts, mw, totalLost):
return ts * (mw - totalLost)
def writeFile(pmv, ppd, tr):
myFile = open('PMVModel.txt', 'a')
myFile.write('\nAccessed on ' + str(datetime.now()) + " PMV: " + str(pmv) + " PPD: " + str(ppd) + " New A/C Degree: " + str(round(pmv, 0) + tr))
# Main Function
if __name__ == "__main__":
if(len(sys.argv) != 7):
print("Error")
sys.exit(1)
tr = float(sys.argv[1]) #25
ta = float(sys.argv[2]) #23.5
vel = float(sys.argv[3]) #0.2
rh = float(sys.argv[4]) #60
met = float(sys.argv[5]) #1.2
clo = float(sys.argv[6]) #0.3
pmv, ppd = pmv(tr, ta, vel, rh, met, clo)
#writeFile(pmv, ppd, tr) |
8e72f93ab40369d2bfcad78fced401e3f3d072ac | rounakbanik/stanford_algorithms | /week6/median.py | 3,203 | 3.53125 | 4 | def find_parent(ele_num):
if ele_num% 2 == 1:
return ele_num/2
return ele_num/2 - 1
def find_children(ele_num):
return 2*ele_num + 1, 2*ele_num + 2
def insertmax(hlow, num):
hlow.append(num)
ele_num = len(hlow) - 1
while ele_num > 0:
if num > hlow[find_parent(ele_num)]:
hlow[ele_num], hlow[find_parent(ele_num)] = hlow[find_parent(ele_num)], hlow[ele_num]
ele_num = find_parent(ele_num)
else:
return hlow
return hlow
def insertmin(hhigh, num):
hhigh.append(num)
ele_num = len(hhigh) - 1
while ele_num > 0:
if num < hhigh[find_parent(ele_num)]:
hhigh[ele_num], hhigh[find_parent(ele_num)] = hhigh[find_parent(ele_num)], hhigh[ele_num]
ele_num = find_parent(ele_num)
else:
return hhigh
return hhigh
def deletemax(hlow):
index = len(hlow) - 1
hlow[index], hlow[0] = hlow[0], hlow[index]
hlow.pop()
ele_num = 0
while 2*ele_num +1 < index:
c = find_children(ele_num)
if c[1] > index-1:
hlow.append(-1* float("inf"))
if hlow[ele_num] < hlow[c[0]] or hlow[ele_num] < hlow[c[1]]:
maxi_index = hlow.index(max(hlow[c[0]], hlow[c[1]]))
hlow[ele_num], hlow[maxi_index] = hlow[maxi_index], hlow[ele_num]
ele_num = maxi_index
else:
if hlow[-1] == -1*float("inf"):
hlow.pop()
return hlow
if hlow[-1] == -1*float("inf"):
hlow.pop()
return hlow
def deletemin(hhigh):
index = len(hhigh) - 1
hhigh[index], hhigh[0] = hhigh[0], hhigh[index]
hhigh.pop()
ele_num = 0
while 2*ele_num + 1 < index:
c = find_children(ele_num)
if c[1] > index-1:
hhigh.append(float("inf"))
if hhigh[ele_num] > hhigh[c[0]] or hhigh[ele_num] > hhigh[c[1]]:
mini_index = hhigh.index(min(hhigh[c[0]], hhigh[c[1]]))
hhigh[ele_num], hhigh[mini_index] = hhigh[mini_index], hhigh[ele_num]
ele_num = mini_index
else:
if hlow[-1] == float("inf"):
hhigh.pop()
return hhigh
if hhigh[-1] == float("inf"):
hhigh.pop()
return hhigh
median_sum = 0
hlow = []
hhigh = []
median_arr = []
vertices = []
with open("Median.txt") as f:
for line in f:
num = int(line)
vertices.append(num)
if len(hlow) == 0 and len(hhigh) == 0:
hlow.append(num)
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
else:
if len(hlow) > 0:
maxi = hlow[0]
else:
maxi = -1*float("inf")
if len(hhigh) > 0:
mini = hhigh[0]
else:
mini = float("inf")
if num < maxi:
hlow = insertmax(hlow, num)
elif num > mini:
hhigh = insertmin(hhigh, num)
else:
hlow = insertmax(hlow, num)
if len(hlow) > len(hhigh) + 1:
ele = hlow[0]
hlow = deletemax(hlow)
if -1*float("inf") in hlow:
hlow.remove(-1*float("inf"))
hhigh = insertmin(hhigh, ele)
elif len(hhigh) > len(hlow) + 1:
ele = hhigh[0]
hhigh = deletemin(hhigh)
if float("inf") in hhigh:
hhigh.remove(float("inf"))
hlow = insertmax(hlow, ele)
if len(hlow)> len(hhigh):
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
elif len(hhigh) > len(hlow):
median_sum = median_sum + hhigh[0]
median_arr.append(median_sum)
else:
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
print median_sum%10000
|
b91c80ad878426912f994ee6f2112d62416acf0e | SagarikaNagpal/Python-Practice | /QuesOnOops/PythonTuples.py | 154 | 4.09375 | 4 | tuple = ('abcd',786,2.23,'john',70.2)
tinyTuple = (123,'john')
print(tuple)
print(tinyTuple)
print(tuple[1:3])
print(tinyTuple+tuple)
print(tinyTuple*3)
|
18d9399b5e6fe4e0c089b392e7fd436dcb0cc790 | SagarikaNagpal/Python-Practice | /QuesOnOops/D-15.py | 263 | 4.0625 | 4 | # Question D15: WAP to input 10 values in a float array and display all the values more than 75.
floatArray=[34.9,65.3,56.3,50.7,54.7,87.9,76.8]
for val in floatArray:
if(val>75):
print("The numbers which are greater than 75 are : ",val)
|
49d3fbe78c86ab600767198110c6022be77fefe9 | SagarikaNagpal/Python-Practice | /QuesOnOops/F-9.py | 507 | 4.1875 | 4 | # : Write a function that has one character argument and displays that it’s a small letter, capital letter, a digit or a special symbol.
# 97-122 65-90 48-57 33-47
def ch(a):
if(a.isupper()):
print("upper letter")
elif(a.islower()):
print("lower letter")
elif (a.isdigit()):
print("is digit")
else:
print("Special")
a=input("ch is: ")
print(ch(a)) |
fe87fda53fd053e70d978d0204461c0aeb69058a | SagarikaNagpal/Python-Practice | /QuesOnOops/A-25.py | 137 | 3.8125 | 4 | a=int(input("a is: "))
b=int(input("b is: "))
print("before swapping")
print(a)
print(b)
print("After Swaping")
a,b=b,a
print(a)
print(b) |
7099d78eb77a62ea5960a55130123ca386f261e1 | SagarikaNagpal/Python-Practice | /QuesOnOops/B-39.py | 105 | 3.953125 | 4 | num = int(input("Num for its table: "))
for i in range(1,11):
print("table of",num,"*",i,"=",num*i) |
934c3fb94a7536650b6810b5a50467f84faf2952 | SagarikaNagpal/Python-Practice | /tiny_progress/list/Python program to print odd numbers in a List.py | 402 | 3.875 | 4 | def listCreate():
n = int(input('Number of elements in list: '))
l =[]
for i in range(n):
l.append(int(input('element is: ')))
return l
def odd(l):
odd = []
for i in l:
if i%2 ==1:
odd.append(i)
return odd
def main():
first = listCreate()
second= odd(l=first)
print(f'odd num is {second}')
if __name__ == '__main__':
main()
|
a131bce1690e9cef62f40819824fd3e6c7cf0d51 | SagarikaNagpal/Python-Practice | /QuesOnOops/C-15.py | 430 | 4.03125 | 4 | # to check a string for palindrome.
# also work with b-79
# String="aIbohPhoBiA"
# String1=String.casefold()
# Rev_String=reversed(String1)
# if(list(String1)==list(Rev_String)):
# print("The string is palindrome")
# else:
# print("no its not")
s= input("string: ")
s1 = s.casefold()
print(s1)
rev = reversed(s)
print("rev",rev)
if(list(s1)==list(rev)):
print("string is palindrome")
else:
print("no its not")
|
3aa25f3fba06beaa6fecf9403e4de839549e2660 | SagarikaNagpal/Python-Practice | /QuesOnOops/A-5.py | 132 | 4.15625 | 4 | radius= int(input("radius is:"))
circu= 2*3.14*radius
area=3.14*radius
print("circumfrence is: ",circu)
print("area is: ",area)
|
e0675cb6771465070dbd479f662a7e3e8f9eef2a | SagarikaNagpal/Python-Practice | /QuesOnOops/B30.py | 181 | 3.90625 | 4 | # Question B30: WAP to print counting from 10 to 1.
# Question B31: WAP to print counting from 51 to 90.
for i in range(10,0,-1):
print(i)
for f in range(50,91):
print(f) |
696000f189c565377613191ebbaf86299cf6614f | SagarikaNagpal/Python-Practice | /tiny_progress/basic/A1.py | 302 | 3.890625 | 4 | # Question A1: WAP to input roll number, name, marks and phone of a student and display the values.
from tokenize import Name
rollNum = int(input("RollNumber : "))
name = (input("Name: "))
marks = int(input("Marks: "))
phone = int(input("Phone: "))
print(rollNum,name,marks,phone)
print(type(Name)) |
fc996b4899875fbf48ca5b5e4da4a4f194cbef70 | SagarikaNagpal/Python-Practice | /QuesOnOops/B8.py | 452 | 3.640625 | 4 | # Question B8: WAP to input the salary of a person and calculate the hra and da according to the following conditions:
# Salary HRA DA
# 5000-10000 10% 5%
# 10001-15000 15% 8%
name = str(input("name"))
sal = int(input("sal is: "))
HRA = 1
DA = 1
if((sal>5000 and sal< 1000)):
HRA = (0.1*sal)
DA = (0.5 *sal)
if((sal>10001 and sal <15000)):
HRA = (1.5*sal)
DA = (0.8*sal)
print()
print("HRA", HRA)
print("DA", DA)
|
43462ac259650bcea0c4433ff1d27d90bbc7a09e | SagarikaNagpal/Python-Practice | /QuesOnOops/C-4.py | 321 | 4.40625 | 4 | # input a multi word string and produce a string in which first letter of each word is capitalized.
# s = input()
# for x in s[:].split():
# s = s.replace(x, x.capitalize())
# print(s)
a1 = input("word1: ")
a2 = input("word2: ")
a3 = input("word3: ")
print(a1.capitalize(),""+a2.capitalize(),""+a3.capitalize()) |
c56fecfa02ec9637180348dd990cf646ad00f77f | SagarikaNagpal/Python-Practice | /QuesOnOops/B-78.py | 730 | 4.375 | 4 | # Write a menu driven program which has following options:
# 1. Factorial of a number.
# 2. Prime or Not
# 3. Odd or even
# 4. Exit.
n = int(input("n: "))
menu = int(input("menu is: "))
factorial = 1
if(menu==1):
for i in range(1,n+1):
factorial= factorial*i
print("factorial of ",n,"is",factorial)
elif(menu==2):
if(n>1):
for i in range (2,n):
if(n%i)==0:
print("num ",n,"is not prime")
break
else:
print("num", n ,"is prime")
break
else:
print("num is not prime")
elif(menu==3):
if(n%2 ==0):
print(n,"is even")
else:
print(n, "is odd")
else:
print("exit!")
|
7b8acefe0e74bdd25c9e90f869009c2e3a24a4fc | SagarikaNagpal/Python-Practice | /QuesOnOops/C-13.py | 213 | 4.40625 | 4 | # to input two strings and print which one is lengthier.
s1 = input("String1: ")
s2 = input("String2: ")
if(len(s1)>len(s2)):
print("String -",s1,"-is greater than-", s2,"-")
else:
print(s2,"is greater") |
96e4195413797d376b936e6b5d1b04aaa8c01cac | SagarikaNagpal/Python-Practice | /QuesOnOops/C-14.py | 61 | 4.15625 | 4 | # to reverse a string.
s = input("string: ")
print(s[::-1])
|
e09aad9458b0eceb8a8acfc23db8a78637e3ebfe | SagarikaNagpal/Python-Practice | /tiny_progress/list/Python program to swap two elements in a list.py | 809 | 4.25 | 4 | # Python program to swap two elements in a list
def appendList():
user_lst = []
no_of_items = int(input("How many numbers in a list: "))
for i in range(no_of_items):
user_lst.append(int(input("enter item: ")))
return user_lst
def swapPos(swap_list):
swap_index_1 = int(input("Enter First Index for swapping: "))
swap_index_2 = int(input("Enter Second Index for swapping: "))
swap_list[swap_index_1], swap_list[swap_index_2] = swap_list[swap_index_2], swap_list[swap_index_1]
return swap_list
def main():
saga_list = appendList()
print("List Before Swapping: ", saga_list)
print("List Sorted: ", sorted(saga_list))
swapped_list = swapPos(swap_list=saga_list)
print("List After Swapping: ", swapped_list)
if __name__ == '__main__':
main()
|
04ac72941293d872cecb6d12f3cf1ba2d8747452 | SagarikaNagpal/Python-Practice | /QuesOnOops/Removing_Duplicates.py | 511 | 3.984375 | 4 | # Question: Complete the script so that it removes duplicate items from list a .
#
# a = ["1", 1, "1", 2]-- "1 is duplicate here"
# Expected output:
#
# ['1', 2, 1]
# ********************Diifferent Approach***********************
# a = ["1",1,"1",2]
# b = []
# for i in a:
# if i not in b:
# b.append(i)
# print(list(set(a)))
# ********************Diifferent Approach***********************
from collections import OrderedDict
a = ["1", 1, "1", 2]
a = list(OrderedDict.fromkeys(a))
print(a)
|
a33e791b4fc099c4e607294004888f145071e6ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A22.py | 254 | 4.34375 | 4 | #Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.
import math
a=int(input("num: "))
sq = int(math.pow(a,2))
cube =int (math.pow(a,3))
if a%2==0:
print("sq of a num is ",sq)
else:
print(cube) |
cd04469d80121d7c9f10221c30f0bf4963d888d1 | SagarikaNagpal/Python-Practice | /QuesOnOops/D-7.py | 83 | 3.9375 | 4 | # Question D7: WAP to reverse an array of floats.
arr = [1,2,3,4]
print(arr[::-1]) |
470e9fa497bef6af068fa708ac1c2fb68569c71c | SagarikaNagpal/Python-Practice | /QuesOnOops/C-11.py | 140 | 4.1875 | 4 | # WAP to count all the occurrences of a character in a given string.
st = "belief"
ch = input("chk: ")
times = st.count(ch)
print(times) |
0cdf4fb881b84941e0ff4f29600092f65a65d001 | SagarikaNagpal/Python-Practice | /QuesOnOops/B-8.py | 416 | 4.0625 | 4 | name = input("name of an employee: ")
salary = int(input("input of salary: "))
HRA = 0
DA = 0
if(salary> 5000 and salary <10000):
print("Salary is in between 5000 and 10000")
HRA = salary *0.1
DA = salary * 0.05
elif(salary>10001 and salary<15000):
print("Salary is in between 10001 and 15000")
HRA = salary * 0.15
DA = salary * 0.08
print(name)
print(salary)
print(HRA)
print(DA)
|
169945565fd5ffb9c590d7a38715b3a08a8280ff | SagarikaNagpal/Python-Practice | /QuesOnOops/A-10.py | 248 | 4.34375 | 4 | # to input the number the days from the user and convert it into years, weeks and days.
days = int(input("days: "))
year = days/365
days = days%365
week = days/7
days = days%7
day = days
print("year",year)
print("week",week)
print("day",day)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.