blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cac09d4e227031074f5410dfd921662ab4eab769 | dxb350352/python_learn | /10函数.py | 329 | 3.671875 | 4 | #!/usr/lib/python3
a = [1, 2, 3]
print(a)
a = "d"
print(a)
def go(a, b=1):
print(a, b)
go(a=2)
def gogo(a, *xx, **yy):
print(a)
for t in xx:
print(t, "xx")
for k, v in yy.items():
print(k, v, "yy")
gogo(1, 2, 3, 4, aa=1, bb=2)
sum = lambda a1, a2: a1 + a2
print(sum(1, 2))
print(dir())
|
489ba1128bd957c366c2d019167b5316938c3196 | cryoyan/rs_data_proc | /learning_codes/learn_retry.py | 1,516 | 4.09375 | 4 | #!/usr/bin/env python
# Filename: learn_retry
"""
introduction: some code to understand the retrying model.
# https://github.com/rholder/retrying
# https://pypi.org/project/retrying/
# https://www.jb51.net/article/170781.htm
authors: Huang Lingcao
email:huanglingcao@gmail.com
add time: 02 February, 2021
"""
import datetime
from retrying import retry
count = 0
# stop_max_attempt_number # default is 5 retry, after that, exit
# stop_max_delay # after try amount of this time, exit
# wait_fixed # interval between each time, defautl is 1000 ms
# wait_random_min, # default is 0
# wait_random_max # randomly wait time between min and max, default is 1000 ms
# wait_incrementing_increment, # each retry, it will increase wait time, default increase 100 ms.
# wait_exponential_multiplier,
# wait_exponential_max, # "Wait 2^x *wait_exponential_multiplier milliseconds between each retry,
# x is the previous try numbers, up to wait_exponential_max milliseconds,
# then wait_exponential_max seconds afterwards"
# retry_on_exception:
# retry_on_result
# wrap_exception:
# stop_func
# wait_func
@retry(stop_max_attempt_number=5, wait_random_min=1000, wait_random_max=5000)
def run():
global count
if count > 0:
print(datetime.datetime.now(), "start again, %d th try"%count)
else:
print(datetime.datetime.now(), "start")
count += 1
# raise NameError
# raise IOError
raise ValueError
if __name__ == '__main__':
run() |
86d86437fa88b798840771e3c24241187e3c55b6 | Wangi-C/Python-Data-Structure-Algorithm | /2장(기본자료구조와 배열)/sum_1ton.py | 238 | 3.6875 | 4 | def sum_1ton(n):
result = 0
i = 1
while i < n+1:
result += i
i += 1
return result
x = int(input("x의 값을 입력하세요.:"))
print(f"1부터 {x}까지 정수의 합은 {sum_1ton(x)}입니다.") |
0ba47fc11dbe4502d3f176ed2817f705f6a56f55 | pateljay1397/Hackerrankepython | /hello.py | 1,333 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 18:33:58 2020
@author: patel
"""
import random
def hello():
print("Hello World This Jerry is here")
print(random.randrange(1,15))
hello()
x=10.5
y="Jerry"
print(y[2:5])
print(y[-5:-3]+y[2:5])
x=int(x)
print(x)
x=str(x)
print(len(y))
print(y.strip())
print(y.lower())
print(y.upper())
print(y.replace("J","H"))
print(y.split())
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
age=22
txt ="my age is {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder="I want {} pieces of item {} for {} dollars"
print(myorder.format(quantity,itemno,price))
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
if "apple" in thislist:
print("yes")
thislist.append("Orange")
print(thislist)
thislist.insert(1,"orange")
print(thislist)
list1=["A" "B" "C" "D"]
list2=["1" "2" "3" "4"]
for x in list2:
list1.append(x)
print(list1)
list1.extend(list2)
print(list1)
thislist = ("apple", "banana", "cherry")
y=list(thislist)
y[1]="kiwi"
thislist=tuple(y)
print(thislist)
thisset = {"apple", "banana", "cherry"}
print(thisset)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x=thisdict["brand"]
print(x)
for x,y in thisdict.items():
print(x,y) |
0fc23f8fad34e0ffbf48c8a9b5090385e8403023 | juanfariastk/FunnyAlgorithms | /CountCoins/count_coins.py | 881 | 4.15625 | 4 | def return_coins(user_money : int, coin_list : list) -> list:
"""Function that returns the minimum amount of coins to convert
a given amount of money
Args:
user_money (int): provided amount of money
coin_list (list): list with the value of coins
Returns:
list: minimum amount of coins from the provided list
"""
user_coins = []
for coin in coin_list:
while(user_money >= coin):
user_coins.append(coin)
user_money -= coin
return user_coins
def run() -> None:
"""Run function, asks the user how much money would be converted into coins.
"""
print("How much money is to be converted into coins?")
user_input = int(input())
coin_list = [25, 10, 5, 2, 1]
user_coins = return_coins(user_input, coin_list)
print(user_coins)
if __name__ == "__main__":
run() |
700d98afaea2e687ceafcc9257119a3bdc4fc65e | MUDIT-SINGH001/SEARCHING-AND-SORTING | /middle of 3.py | 85 | 3.6875 | 4 | if A<B and B<C:
print(B)
elif C>A and C<B:
print(C)
else:
print(A)
|
de5eb39f0cb1835031222313c32b72dda0735233 | osamamohamedsoliman/BFS-1 | /Problem-1.py | 1,149 | 3.765625 | 4 | # Time Complexity :O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
# Your code here along with comments explaining your approach
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
#edge case
if not root:
return []
#solution values and pointers arrays
sol =[]
temp = [root]
vals = [root.val]
#while pointers
while temp:
#append values to solution
sol.append(vals)
#temps
newtemp =[]
newvals =[]
#traverse all nodes in this level
for i in temp:
if i.left:
newtemp.append(i.left)
newvals.append(i.left.val)
if i.right:
newtemp.append(i.right)
newvals.append(i.right.val)
#put the new level as old level
temp = newtemp
vals = newvals
#return solx
return sol |
929d5190f5d3c9156071b32b38f2f349ce4df49c | akankaku1998/3-to-10-Sides-Shapes | /main.py | 338 | 3.859375 | 4 | import turtle as t
import random
tim = t.Turtle()
colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
for x in range(3, 11):
tim.color(random.choice(colours))
for y in range(x):
tim.forward(100)
tim.right(360/x)
screen = t.Screen()
screen.exitonclick() |
c696b1c507015801bc043bd64e67f134a6262a64 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2480/61135/299404.py | 228 | 3.5625 | 4 | T=int(input())
for a in range(0,T):
N=int(input())
num=input().split(" ")
num=list(int(b) for b in num)
num=sorted(num,key=lambda x: x%2)
for c in range (0,len(num)):
print(num[c],end=" ")
print() |
c262c2d0598946432f7578822d0c994db64d9a0a | Sheko1/SoftUni | /Python-Fundamentals/Classes-and-Objects/Lab/03_email.py | 1,044 | 3.6875 | 4 | class Email:
def __init__(self, sender, receiver, content):
self.sender = sender
self.receiver = receiver
self.content = content
self.is_send = False
self.mails = []
def send(self):
self.is_send = True
def get_info(self):
return f"{self.sender} says to {self.receiver}: {self.content}. Sent: {self.is_send}"
class MailBox:
def __init__(self):
self.emails = []
def add_email(self, mail):
self.emails.append(mail)
def send_email(self, indexes):
for i in indexes:
self.emails[i].send()
def get_all_info(self):
info = ""
for i in self.emails:
info += f"{i.get_info()}\n"
return info
command = input()
emails = MailBox()
while command != "Stop":
data = command.split(" ", maxsplit=2)
email = Email(data[0], data[1], data[2])
emails.add_email(email)
command = input()
index = [int(i) for i in input().split(", ")]
emails.send_email(index)
print(emails.get_all_info())
|
a8028c387cd7614526d1621c9ac1761441383cad | venkatarahul189/Python-deep-learning | /ICP2/icp2(2).py | 173 | 3.71875 | 4 | set = 0
a = int(input('num:'))
while a != 0:
if (a % 2) == 0:
a = a/2
set = set + 1
else:
a = a - 1
set = set + 1
print(set) |
220b749a1ba503a49b70001665df477ff2b5ca22 | ramneetbrar/Lotto-Draws-Analysis | /finalAssignment.py | 18,849 | 3.984375 | 4 | #global variables:
userInputFile = "" #input file that user chooses to gather data
listOfDraws = [] #list of draws, including all information (lall in provided code)
listOfDatesOfDraws = [] #list of dates of draws from listofdraws(lall)
listOfNumsDrawn = [] #list of draw numbers from listofdraws(lall)
listOfDrawJackpots = [] #list of draw jackpots in draws from listofdraws(lall)
listNumWinners = [] #list of number of winners in draws from listofdraws(lall)
userDataInput = "" #user input to determine whether to end, use all or sel data
numDraws = 0 #number of draws, used to determine range of for loops
userOutputFile = "" #output file that user selects to create
listTo49 = [] #list of number of times each number appears in draws
listOfNumsInRange = [] #list of frequency of nums in ranges
listResults = [] #list for output file (lout)
import turtle
def welcomeFunction():
#this is a void function, its purpose is to welcome the user to the system and to get the names of input files
print("Welcome to the CMPT 120 6-49 Processing System!")
print("===============================================")
print("You will first be asked to provide the INPUT file name; you will be asked to provide the OUTPUT file name later.")
print("The input file should be in this folder, the output file will be created in this folder.")
print("You will be able to provide new names for the files or accept the default names. Both files should have the extension .csv")
#userInputFile =input("Type x for file 'IN_data_draws3.csv', or type a new file name ==>")
#if userInputFile == "x":
# userInputFile = "IN_data_draws3.csv"
return
def inputFileSelection():
#this is a productive function that asks user input for the file of draws to be used, and returns that csv file
userInputFile =input("Type x for file 'IN_data_draws3.csv', or type a new file name ==>")
if userInputFile == "x":
userInputFile = "IN_data_draws3.csv"
return userInputFile
def read_csv_into_list_of_lists(IN_file):
'''
PROVIDED. CMPT 120
A csv file should be available in the folder (where this program is)
A string with the name of the file should be passed as argument to this function
when invoking it
(the string would include the csv extension, e.g "ID_data.csv")
'''
import csv
lall = []
print("\n.... TRACE - data read from the file\n")
with open(IN_file) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for inrow in csv_reader:
print(".......",inrow)
lall.append(inrow)
return lall
def createSeparateLists(listDraws):
listOfDatesOfDraws = []
for i in range(len(listDraws)):
date = (listDraws[i][0])
listOfDatesOfDraws.append(date)
listOfNumsDrawn = []
for i in range(len(listDraws)):
innerListNums = []
for k in range(1,8):
number = listDraws[i][k]
innerListNums.append(number)
listOfNumsDrawn.append(innerListNums)
listOfDrawJackpots = []
for i in range(len(listDraws)):
jackpot = listDraws[i][8]
listOfDrawJackpots.append(jackpot)
listNumWinners = []
for i in range(len(listDraws)):
numWinners = listDraws[i][9]
listNumWinners.append(numWinners)
return listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners
def dataProcess():
#this is a productive function that asks the user for input to select the draws
print("Please choose one of three options: \n Type ALL to process all the data. \n Type SEL to process selected draws. \n Type END to end this program.\n")
validInputs = ["all", "sel", "end",]
userDataInputLocal = ""
while not(userDataInputLocal.lower() in validInputs):
userDataInputLocal = input("\nType ALL, SEL OR END (not case sensitive) ==>")
return userDataInputLocal
def userSelectAll(numDraws):
#this function changes the formatting of the list, to create a list of the numbers drawn within the list of Draws
listOfDraws = []
innerListDraws = []
for i in range(numDraws):
innerListDraws = [listOfDatesOfDraws[i], listOfNumsDrawn[i], listOfDrawJackpots[i], listNumWinners[i]]
listOfDraws.append(innerListDraws)
#print("TRACE !!", listOfDraws)
#print("\nTRACE!!", listOfDraws)
return listOfDraws
def monthFromDataToNum(dateFromList):
#this is a productive function that receives parameters. it takes a month written in date notation and turns it into the corresponding number
months = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
dashOne = dateFromList.index("-")
dashTwo = dashOne + 4
monthString = dateFromList[dashOne + 1: dashTwo]
monthNum = months.index(monthString)
return monthNum
def selectionByMonth(listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots,listNumWinners, numDrawswait ):
print("Please select a month. \n Only the draws associated to this month will be processed.")
userSelectedMonth = ""
validMonthsList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
while not(userSelectedMonth in validMonthsList):
userSelectedMonth = int(input("Please type a month number (1-12) ==>"))
#validation of user input^^
listOfMonthsNums = []
for i in range(len(listOfDatesOfDraws)):
monthNum = monthFromDataToNum(listOfDatesOfDraws[i])
#print("Trace !!", monthNum)
listOfMonthsNums.append(monthNum)
indicesOfUserInput = []
for i in range(len(listOfMonthsNums)):
if userSelectedMonth == listOfMonthsNums[i]:
indicesOfUserInput.append(i)
#print("Trace !!", i)
#print("trace !!", indicesOfUserInput)
numDraws = len(indicesOfUserInput)
listOfDraws = []
innerListDraws = []
for i in range(len(indicesOfUserInput)):
indexListDraws = [listOfDatesOfDraws[indicesOfUserInput[i]], listOfNumsDrawn[indicesOfUserInput[i]], listOfDrawJackpots[indicesOfUserInput[i]], listNumWinners[indicesOfUserInput[i]]]
listOfDraws.append(indexListDraws)
#print("\nTRACE !!",listOfDraws)
listOfDatesOfDraws = updateLists(indicesOfUserInput, listOfDatesOfDraws)
listOfNumsDrawn = updateLists(indicesOfUserInput, listOfNumsDrawn)
listOfDrawJackpots = updateLists(indicesOfUserInput, listOfDrawJackpots)
listNumWinners = updateLists(indicesOfUserInput, listNumWinners)
return listOfDraws, listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners, numDraws
def dateToDayOfWeek(dateFromList):
months = ["", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb"]
daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
dashOne = dateFromList.index('-')
dashTwo = dashOne + 4
k = int(dateFromList[0:dashOne])
monthString = dateFromList[dashOne + 1: dashTwo]
m = int(months.index(monthString))
year = int(dateFromList[dashTwo:]) + 2000
year1 = str(year)
D = int(year1[2:4])
if m == 11 or m == 12:
D = D - 1
C = 20 #because all years after 2000
f = k + ((13*m-1)/5) + D + (D/4) + (C/4) - 2*C
res = daysOfWeek[int(f%7)]
return res
def selectionByDay(listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots,listNumWinners, numDrawswait):
print("Please select a day of the week. \n Only the draws associated to this day will be processed.")
userSelectedDay = ""
validDaysList = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
while not(userSelectedDay.lower() in validDaysList):
userSelectedDay = (input("Please type a day of the week ==>"))
#validation of user input^^
selectedDay = validDaysList.index(userSelectedDay)
listOfDays = []
for i in range(len(listOfDatesOfDraws)):
dayOfWeek = dateToDayOfWeek(listOfDatesOfDraws[i])
print("Trace !!", dayOfWeek)
listOfDays.append(dayOfWeek)
print(listOfDays)
indicesOfUserInput = []
for i in range(len(listOfDays)):
if selectedDay == listOfDays[i]:
indicesOfUserInput.append(i)
print("Trace !!", i)
#print("trace !!", indicesOfUserInput)
numDraws = len(indicesOfUserInput)
listOfDraws = []
innerListDraws = []
for i in range(len(indicesOfUserInput)):
indexListDraws = [listOfDatesOfDraws[indicesOfUserInput[i]], listOfNumsDrawn[indicesOfUserInput[i]], listOfDrawJackpots[indicesOfUserInput[i]], listNumWinners[indicesOfUserInput[i]]]
listOfDraws.append(indexListDraws)
listOfDatesOfDraws = updateLists(indicesOfUserInput, listOfDatesOfDraws)
listOfNumsDrawn = updateLists(indicesOfUserInput, listOfNumsDrawn)
listOfDrawJackpots = updateLists(indicesOfUserInput, listOfDrawJackpots)
listNumWinners = updateLists(indicesOfUserInput, listNumWinners)
return listOfDraws, listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners, numDraws
def updateLists(indicesOfUserInput, listToUpdate):
print(indicesOfUserInput)
print(listToUpdate)
updatedList = []
for elem in indicesOfUserInput:
print(elem)
elem = int(elem)
updatedList.append(listToUpdate[elem])
print(updatedList)
return updatedList
def dataBeingProcessed(listOfDraws):
for i in range(len(listOfDraws)):
print("\n\n","Just to TRACE, the draw being processed is:")
print("Index #", i, "\n Date:", listOfDraws[i][0], "\n Numbers Drawn:", listOfDraws[i][1], "\n Jackpot:", listOfDraws[i][2], "\n Number of Winners", listOfDraws[i][3])
return
def averageJackpot():
listOfAverageJackpots = []
for i in range(len(listOfDrawJackpots)):
jackpot = int(listOfDrawJackpots[i])
numWinners = int((listNumWinners[i]))
if numWinners != 0:
averageJackpot = jackpot//numWinners
listOfAverageJackpots.append(averageJackpot)
else:
averageJackpot = 0
listOfAverageJackpots.append(averageJackpot)
#print("TRACE !!", listOfAverageJackpots)
return listOfAverageJackpots
def maxJackpot():
maxJackpot = 0
indexMax = 0
for i in range(len(listOfDrawJackpots)):
if int(listOfDrawJackpots[i]) > maxJackpot:
maxJackpot = int(listOfDrawJackpots[i])
indexMax = i
dateMaxJackpot = listOfDatesOfDraws[indexMax]
print("\nThe max jackpot was", maxJackpot)
print("The date of the max jackpot was", dateMaxJackpot)
return maxJackpot, dateMaxJackpot
def maxAverageJackpot(listOfAverageJackpots):
maxAverageJackpot = 0
indexMax = 0
for i in range(len(listOfAverageJackpots)):
if int(listOfAverageJackpots[i]) > maxAverageJackpot:
maxAverageJackpot = int(listOfAverageJackpots[i])
indexMax = i
dateMaxAverageJackpot = listOfDatesOfDraws[indexMax]
print("\nThe max average jackpot was", maxAverageJackpot)
print("The date of the max average jackpot was", dateMaxAverageJackpot)
return maxAverageJackpot,dateMaxAverageJackpot
def numTimesDrawn(lst):
print("Number of times each number was drawn:")
listTo49 = [0]*50
for elem in lst:
for num in elem:
number = int(num)
listTo49[number] = listTo49[number] + 1
return listTo49
def numsInRange(listNums):
print("number of numbers in each range - all selected draws considered ranges:")
print(listNums)
listRanges = [0] * 5
for i in range(len(listNums)):
for j in range(len(listNums[i])):
k = 0
while (int(listNums[i][j]) > k*10):
k += 1
listRanges[(k-1)] += 1
#print("TRACE !!", listRanges)
return listRanges
def sixMaxs(listNums):
print("Six most frequently drawn numbers:")
res = ""
for i in range(6):
maxNum = listNums[0]
pos = 0
for j in range(len(listNums)):
if listNums[j] > maxNum:
maxNum = listNums[j]
pos = j
print("number:", pos, "frequency:", maxNum)
res += "number:" + str(pos) + "frequency:" + str(maxNum) + "\n"
listNums[pos] = -1
maxNum = listNums[0]
pos = 0
return res
def turtleRangesDistribution():
validInputs = ["y", "n"]
userInput = ""
while not(userInput.lower() in validInputs):
userInput = input("Do you want to graph the ranges ranges distribution (Y/N) ==>")
if userInput.lower() == "y":
print("yes")
turtle.penup()
turtle.goto(-300,-200)
turtle.pendown()
turtle.pensize(5)
turtle.forward(20)
for i in range(len(listOfNumsInRange)):
turtle.forward(50)
turtle.left(90)
turtle.fillcolor('lightblue')
turtle.begin_fill()
turtle.forward(listOfNumsInRange[i]*50)
turtle.right(90)
turtle.forward(50)
turtle.left(90)
turtle.backward(listOfNumsInRange[i]*50)
turtle.left(90)
turtle.forward(50)
turtle.left(180)
turtle.forward(50)
turtle.end_fill()
turtle.forward(20)
else:
print("no")
return
## TO WRITE TO CSV OUTPUT FILE
def appendResToOutput(numDraws, listResults, listOfDatesOfDraws, listOfNumsDrawn, averageJackpot):
print(numDraws)
for i in range(numDraws):
listResults.append("'" + listOfDatesOfDraws[i] + "'" + ",")
newListNumsDrawn = []
newListNumsDrawn.append(listOfNumsDrawn[i])
listFrequency = numsInRange(newListNumsDrawn)
#print("trace!!", listFrequency)
for elmt in listFrequency:
listResults.append(str(elmt) + ",")
#print("trace!!",listResults)
avgJackpot = averageJackpot()[i]
listResults.append(str(avgJackpot) + "\n")
return
def outputFileSelection():
#this is a productive function that asks user input for the file of draws to be created for output, and returns that csv file
userOutputFile =input("Type x for OUTPUT file name 'OUT_results3.csv', or a new file name ==>")
if userOutputFile == "x":
userOutputFile = "OUT_results3.csv"
return userOutputFile
def writeOutputToFile(listResult,file_name):
'''
PROVIDED. CMPT 120
Assumptions:
1) lout is the list containing all the lines to be saved in the output file
2) file_name is the parameter receiving a string with the exact name of the output file
(with the csv extension, e.g "OUT_results.csv")
3) after executing this function the output file will be in the same
directory (folder) as this program
4) the output file contains just text representing one draw data per line
5) after each line in the file there is the character "\n"
so that the next draw is in the next line, and also
there is (one single) "\n" character after the last line
6) after the output file was created you should be able to open it
with Excell as well
'''
fileRef = open(file_name,"w") # opening file to be written
for line in listResult:
fileRef.write(line)
fileRef.close()
return
##TOP LEVEL
##==============================================================
##==============================================================
welcomeFunction() #introduces user to program
userInputFile = inputFileSelection() #user chooses input file
listOfDraws = read_csv_into_list_of_lists(userInputFile) #input file converted into list of multiple draw lists
print("Trace", listOfDraws)
numDraws = len(listOfDraws)
listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners = createSeparateLists(listOfDraws)
#print("\nTRACE !!",listOfDatesOfDraws,"\n")
#print("\nTRACE !!",listOfNumsDrawn,"\n")
#print("\nTRACE !!",listOfDrawJackpots,"\n")
#print("\nTRACE !!",listNumWinners,"\n")
userDataInput = dataProcess() #gets input from user about what data to process, then in following if/elif processes selected data.
if userDataInput.lower() == "end":
print("end") #trace
#proceed to end
else:
if userDataInput.lower() == "all":
print("\n\n All Data will be processed. \n================================================================")
#print(listOfDraws)
listOfDraws = userSelectAll(numDraws)
elif userDataInput.lower() == "sel":
print("\n\n Selected Data will be processed. \n================================================================") #trace
validInputsSelected = ["m", "d"] #d bonus!!!!!!
userSelectionMethod = ""
while not(userSelectionMethod.lower() in validInputsSelected):
userSelectionMethod = input("Do you want to select by month (M) or day of week (D)? ==>") #D BONUS!!!!!!
if userSelectionMethod.lower() == "m":
listOfDraws, listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners, numDraws = selectionByMonth(listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots,listNumWinners, numDraws)
elif userSelectionMethod.lower() == "d": #BONUS!
listOfDraws, listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots, listNumWinners, numDraws = selectionByDay(listOfDatesOfDraws, listOfNumsDrawn, listOfDrawJackpots,listNumWinners, numDraws)
userOutputFile = outputFileSelection()
dataBeingProcessed(listOfDraws)
print("\n\n","STATS:\n================================================================")
print("Draws Processed:", numDraws)
maxJackpot()
maxAverageJackpot(averageJackpot())
listTo49 = numTimesDrawn(listOfNumsDrawn)
print(listTo49)
listOfNumsInRange = numsInRange(listOfNumsDrawn)
print(listOfNumsInRange)
print(sixMaxs(listTo49))
##Appending to output
listResults=[]
appendResToOutput(numDraws, listResults, listOfDatesOfDraws, listOfNumsDrawn, averageJackpot)
##Writing it
writeOutputToFile(listResults,userOutputFile)
turtleRangesDistribution()
def dateToDayOfWeek(dateFromList):
months = ["", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb"]
daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
dashOne = dateFromList.index('-')
dashTwo = dashOne + 4
k = int(dateFromList[0:dashOne])
monthString = dateFromList[dashOne + 1: dashTwo]
m = months.index(monthString)
year = int(dateFromList[dashTwo:]) + 2000
D = year[2:4]
if m == 11 or m == 12:
D = D - 1
C = 20 #because all years after 2000
f = k + [(13*m-1)/5] + D + [D/4] + [C/4] - 2*C
print(f)
res = daysOfWeek[f%7]
return res
|
9949031a632c2cf49d75013680d76c02aa269778 | michealodwyer26/MPT-Senior | /Labs/Week 7/moneyConverter.py | 1,309 | 3.921875 | 4 | '''
program for euro to dollar conversion using the rate = 1.23
'''
from tkinter import *
# Set up the window
root = Tk()
root.title("Money Converter")
root.geometry("300x200+100+100")
# make the interface
convLabel = Label(root, text="Euro to Dollar Converter")
convLabel.grid(row=0, column=1, columnspan=2)
# euro widgets
euroLabel = Label(root, text="Euro")
euroLabel.grid(row=1, column=0)
euroStr = StringVar()
euroEntry = Entry(root, textvariable= euroStr)
euroEntry.grid(row=1, column=1, columnspan=2)
# dollar widgets
dollarLabel = Label(root, text="Dollar")
dollarLabel.grid(row=2, column=0)
dollarStr = StringVar()
dollarEntry = Entry(root, textvariable= dollarStr)
dollarEntry.grid(row=2, column=1, columnspan=2)
# button widgets
def clearF():
# clear the entrys
euroStr.set("")
dollarStr.set("")
return
clearButton = Button(root, text="Clear", command=clearF)
clearButton.grid(row=3, column=1)
def convertF():
# get the value from eurostr and make it float
euroAmount = float(euroStr.get())
# clear euro to dollar using the given rate
dollarAmount = euroAmount * 1.23
# set the new value to dollarStr
dollarStr.set(str(dollarAmount))
return
convertButton = Button(root, text="Convert", command=convertF)
convertButton.grid(row=3, column=2)
root.mainloop()
|
d82e794a21ed08c918e5529691940d4b49e116a2 | KATO-Hiro/AtCoder | /Others/code_festival/CODE_THANKS_FESTIVAL_2017_A/ProblemB.py | 314 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# CODE THANKS FESTIVAL 2017(Parallel)
# Problem B
if __name__ == '__main__':
s = input()
i = 0
count = 0
while len(s) > 0:
if s[i:] == s[i:][::-1]:
print(count)
exit()
else:
i += 1
count += 1
|
3fc03d86f82c5158eb664dab9e609e7655ef1df4 | tatikondarahul2001/py | /24122020/8.py | 165 | 3.6875 | 4 | d={"R.No":1206,"Name":"Rahul","Course":"B.Tech"}
d["marks"]=46
d["percentage"]=99.4
print(d)
print(d["Course"])
d.pop("Course")
print(d)
print(d.popitem())
print(d)
|
534ca659fc8fcf5a86d392ddbeafa04fb5db22d4 | m-242/passwd_gen | /generator.py | 1,218 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# A simple password generator, outputs X words from a given dic, in camelCase.
import argparse
import random
import sys
import os
def args_parsing_and_checking():
parser = argparse.ArgumentParser()
parser.add_argument(
"--nb_words",
help="The number of words you desire in your password",
default=3,
type=int,
)
parser.add_argument(
"--dictionnary", help="The text file containing your dict, one word per line"
)
args = parser.parse_args()
# check
if not (args.dictionnary):
sys.exit("[!] You must provide a dictionnary")
if not (os.path.isfile(args.dictionnary)):
sys.exit("[!] Invalid dictionnary provided")
return args
def generate_and_print_passwd(x, d):
with open(d, "r") as file:
dictionnary = file.readlines()
psswd = ""
for i in range(x):
psswd += random.choice(dictionnary).title()
psswd = psswd.rstrip() # remove any trailing line
print(psswd)
if __name__ == "__main__":
args = args_parsing_and_checking()
generate_and_print_passwd(args.nb_words, args.dictionnary)
sys.exit()
|
fcea157629d648a72a3a52d87609de7a62839050 | umunusb1/PythonMaterial | /python2/14_Code_Quality/02_unit_test/example.py | 298 | 3.765625 | 4 | # ch6_example.py
def first(num_list1):
num_list1.sort()
return num_list1[0]
def last(num_list):
num_list.sort()
return num_list[-1]
if __name__ == '__main__':
list_nums = [7, 9, 5]
print 'last(list_nums)', last(list_nums)
print 'first(list_nums)', first(list_nums)
|
03a36c0b07f013c120af1d894095a4019b3decc4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2671/60835/295824.py | 903 | 3.796875 | 4 | '''
for q in range(int(input())):
def to_int(bin_res):
res = 0
for x in range(len(bin_res)):
res = res + int(bin_res[x])*(2**x)
return res
n = int(input())
bin_res = "1"*n
res = to_int(bin_res)
print(res)
'''
# Python 3 program to count all
# distinct binary strings with
# two consecutive 1's
# Returns count of n length
# binary strings with
# consecutive 1's
def countStrings(n) :
# Count binary strings without
# consecutive 1's.
# See the approach discussed on be
# ( http://goo.gl/p8A3sW )
a = [0] * n
b = [0] * n
a[0] = b[0] = 1
for i in range(1, n) :
a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1]
# Subtract a[n-1]+b[n-1] from 2^n
return (1 << n) - a[n - 1] - b[n - 1]
# Driver program
for q in range(int(input())):
print(countStrings(int(input())))
# This code is contributed
# by Nikita tiwari.
|
83df86c9c93857be028860ecdcc39d783dfca884 | besseddrest/python-exercises | /leetcode/20-valid-parentheses.py | 1,382 | 4.09375 | 4 | # https://leetcode.com/problems/valid-parentheses/
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
"""
def isValid(self, s: str) -> bool:
# if blank
if len(s) == 0:
return True
# if odd number of chars or starts with closing bracket
if len(s) % 2 == 1 or s[0] in ')}]':
return False
all = []
# create a dict so we know the correct partner chars
partners = {")": "(", "}": "{", "]": "["}
for char in s:
# keep track of opened brackets in order
if char in '([{':
all.append(char)
continue
# if we passed the above check, its a closing bracket
# pop the last character and see if it is the partner of this closing bracket
if all.pop() != partners[char]:
return False
# we've gone through the string, all open brackets should have been popped
return len(all) == 0
# Runtime:
# 20 ms, faster than 97.71% of Python3 online submissions for Valid Parentheses.
#
# Memory Usage:
# 12.6 MB, less than 100.00% of Python3 online submissions for Valid Parentheses. |
90e78eb586104f49f8b642b6dd0f5a3268f51e91 | GORAofSecurity/project1 | /fib.py | 126 | 3.796875 | 4 | #!/usr/bin/python
n = int(input())
num=1
fib0=0
fib1=1
for n in range(1,n):
num=fib1+f0
fib0=fib1
fib1=num
print(num)
|
88fba382e8a2f6b88bfdabcbc4f9e7bc89cd13fb | deboraOli/exercicios-python | /untitled/exer16.py | 321 | 4.0625 | 4 | fruits=["apple","banana","cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
print("--------------")
for y in range(7):
print(y)
print("-----------")
for b in range(2,8):
print(b)
print("--------------")
for c in range(8):
print(c)
else:
print("Finaly finished!") |
894ec7535a2aeb074c52003655b126a1df454c95 | sayunikd/simonsays | /scripts/append_list.py | 329 | 3.625 | 4 | import time
import random
colors = ['R', 'G', 'B', 'Y']
def append_list():
n=random.randint (0,3)
colors.append(colors [n])
color_string = ' ' .join (colors)
for i in range(0,len(colors)):
print colors[i] .lower()
time.sleep(1)
if __name__=='__main__':
try:
append_list()
except KeyboardInterrupt:
print 'Goodbye'
|
01afa8ed8bde2b2a5a0a866d618fc281bcd81282 | PikeyG25/Python-class | /pseudocode example.py | 467 | 4.25 | 4 | ##Pseudocode:
##num1: input from the user;
##num2: inpout from the user;
##
##check numbers if num1 and num2 are all digits
##if both are digits tell user
##if one or the other is a digit tell user
##if neither are digits tell user
num1 =input("enter a number")
num2 =input("enter a number")
if num1.isdigit() and num2.isdigit():
print("both are digits")
elif num1.isdigit() or num2.isdigit():
print("num1 or num2 is a digit")
else:
print("no digits")
|
0eab1b4bb4fc88f133ea39b296c01e023cbe6c7b | jdanray/leetcode | /removeDuplicates3.py | 344 | 3.53125 | 4 | # https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
class Solution(object):
def removeDuplicates(self, s, k):
if not s:
return ""
r = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
r += 1
else:
r = 1
if r == k:
return self.removeDuplicates(s[:i - r + 1] + s[i + 1:], k)
return s
|
d6f1df9df25b43531b21a89d187165969d29228d | grvn/aoc2020 | /09/day9-2.py | 896 | 3.578125 | 4 | #!/usr/bin/env python3
from sys import argv
from itertools import combinations
from collections import deque
def find_fault(input: list, preamble_size: int):
preamble = deque(input[:preamble_size][::-1])
values = input[preamble_size:]
for value in values:
done = True
for x,y in combinations(preamble,2):
if x+y==value:
done = False
break
if done:
return value
preamble.appendleft(value)
preamble.pop()
def main():
preamble_size = int(argv[2])
with open(argv[1]) as f:
input = [int(line.strip()) for line in f]
fault = find_fault(input,preamble_size)
for i in range(len(input)):
total = input[i]
end = i+1
while total < fault:
total += input[end]
end += 1
if total == fault:
r = input[i:end]
print("Encryption weakness:",min(r) + max(r))
exit()
if __name__ == '__main__':
main() |
455a4e3b40f56b4c749229e993553bb3434c0849 | aqueed-shaikh/submissions | /6/zhu_steve/3-madlibs/word.py | 901 | 3.90625 | 4 | import re
VOWEL_PAT = re.compile('[aeiou]')
ADJACENT_VOWEL_PAT = re.compile('[aeiou]{2,}')
class Word:
_word = ""
def __init__(self, word):
self._word = word
def __str__(self):
return self._word
def plural(self):
return self._word + 's'
def gerund(self):
w = self._word
if w[-1] == 'e':
w = w[:-1]
# if does not end with vowel and there is only 1 vowel before the last letter
elif not VOWEL_PAT.search(w[-1]) and not VOWEL_PAT.search(w[-3]):
w += w[-1]
return w + 'ing'
def num_syllables(self):
num_vowels = len(VOWEL_PAT.findall(self._word))
num_adjacent = len(ADJACENT_VOWEL_PAT.findall(self._word))
silent_e = 1 if self._word[-1] == 'e' else 0
return num_vowels - num_adjacent - silent_e
if __name__ == "__main__":
print Word("sit").gerund()
|
bfa777ca55fbf7ae7c7bfd153720cdf8ff6ec509 | Nagendracse1/Competitive-Programming | /backtracking/Ratndeep/nqueen problem.py | 1,070 | 3.53125 | 4 | def safe(chess,row,col,n):
for i in range(row):
if chess[i][col]==1:
return False
temp=col-1
for i in range(row-1,-1,-1):
if temp==-1:
break
if chess[i][temp]==1:
return False
temp-=1
temp = col+1
for i in range(row-1,-1,-1):
if temp==n:
break
if chess[i][temp]==1:
return False
temp+=1
return True
def nqueen(n,chess,row):
if row>=n:
return True
for col in range(n):
if safe(chess,row,col,n):
chess[row][col]=1
if nqueen(n,chess,row+1):
return True
chess[row][col]=0
return False
for _ in range(int(input())):
n = int(input())
if n>1:
chess = [[0 for i in range(n)]for i in range(n)]
row=0
if nqueen(n,chess,row):
for i in chess:
print(*i)
else:
print([1])
|
3c1eff2188a79290f6a11144a836d5c544c264f2 | techehub/pythonbatch20 | /while2.py | 404 | 4.1875 | 4 | while True:
val = input ("Do you want to calculate #")
if val =="Q" or val=="q":
break
a = input("Enter num1 #")
b = input("Enter num2 #")
op = input("Type#")
if op == '+':
result = int(a) + int(b)
elif op == '-':
result = int(a) - int(b)
elif op == '*':
result = int(a) * int(b)
else:
print("Not defined")
print(result)
|
47eb9df6c172d484177439b408a6d186887897c8 | FabioCostaR/aprendendoPYTHON | /Desafio35.py | 467 | 4.125 | 4 | #Desenvolva um programa que leia o comprimento de três retas e dia ao usuario se
#elas podem ou não formar triangulo.
r1 = float(input('digite o tamanho da reta 1 :'))
r2 = float(input('digite o tamanho da reta 2 :'))
r3 = float(input('digite o tamanho da reta 3 :'))
print('-='*20)
if (r1<r2+r3) and (r2<r1+r3) and (r3<r1+r2):
print('Essas retas formam um triangulo')
else:
print('Essas retas não conseguem formar um triangulo')
print('-='*20) |
89428ee4e39f1c11fabe5f86e47ebb5001edd223 | makurek/leetcode | /476-number-complement.py | 954 | 4.25 | 4 | '''
Given a positive integer, output its complement number. The complement strategy is to flip the
bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
'''
def findComplement(num:int) -> int:
# You can't modify the param passed to the function, because it's passing by reference
bits = 0
tmp = num
while tmp:
tmp >>= 1
bits += 1
# Easy way to calc the mask
mask = (1 << bits) - 1
result = num ^ mask
return result
print(findComplement(5)) |
97212ace37ec1fb55643d73f509fda6b6c104d59 | AICDEV/python-uk-training | /basics/03_map.py | 234 | 3.828125 | 4 | ####################
# map
# => https://docs.python.org/3/library/functions.html#map
####################
def square(n):
return n**2
numbers = list(range(1,50))
square_numbers = list(map(square, numbers))
print(square_numbers) |
4c6b752e1c97b1e36a73919934065f3a1106636d | dunber123/CIS2348 | /Homework1/Homework2.19.py | 1,202 | 4.15625 | 4 |
lemon = float(input("Enter amount of lemon juice (in cups):\n"))
water = float(input("Enter amount of water (in cups):\n"))
agave = float(input("Enter amount of agave nectar (in cups):\n"))
serves = float(input("How many servings does this make?\n"))
print('\nLemonade ingredients - yields','{:.2f}'.format(serves), 'servings')
print('{:.2f}'.format(lemon), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agave), 'cup(s) agave nectar\n')
serve_req = float(input("How many servings would you like to make?\n"))
print('\nLemonade ingredients - yields', '{:.2f}'.format(serve_req), 'servings')
serv = serve_req/serves
lemon = lemon * serv
water = water * serv
agave = agave * serv
print('{:.2f}'.format(lemon), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agave), 'cup(s) agave nectar')
print('\nLemonade ingredients - yields', '{:.2f}'.format(serve_req), 'servings')
lemon = lemon / 16
water = water / 16
agave = agave / 16
print('{:.2f}'.format(lemon), 'gallon(s) lemon juice')
print('{:.2f}'.format(water), 'gallon(s) water')
print('{:.2f}'.format(agave), 'gallon(s) agave nectar')
|
cc0ded2172af0ef3cd6dba4433e472b5abcedd73 | Manish-Thakur/Programming | /pattern3.py | 440 | 4.15625 | 4 | # program to print a pattern
n=int(input("Enter the limit: "))
for i in range(1,n+1):
for j in range(1,n+1):
if j>=n+1-i: #check condition, if true then print star else print space
print("*",end='')
else:
print(" ",end='')
print() #this will print a new line
'''
output
------------------
Enter the limit: 5
*
**
***
****
*****
------------------
''' |
5fea6b29a2a33656a53613b12e4072f15c0ead6a | adi19012001/CaptchaGUI | /palindrome.py | 220 | 4.3125 | 4 | # palindrome
a=input("\nEnter word to check whether it is palindrome or not")
b=reversed(a)
if list(a) == list(b):
print("\nThe word is palindrome")
else:
print("\nThe word entered is not a palindrome")
|
55064775b5636945f19c4e9a2a74f640a27fbf64 | rpolnx/python-graphics | /main.py | 677 | 3.640625 | 4 | import matplotlib.pyplot as plt
def main():
print("Generation numbers")
list_x, list_y = generatePoints()
writeFile(list_x, list_y)
draw_graph(list_x, list_y)
# noinspection PyPep8Naming
def writeFile(x, y):
f = open("graphic.txt", "w+")
for i in x:
f.write(str(i) + "==>" + str(y[i]) + "\n")
f.close()
def draw_graph(x, y):
plt.plot(x, y)
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
def generatePoints():
list_x = list(range(-20, 20))
list_y = []
for i in list_x:
y = i*i*i + i * i + 2 * i + 200
list_y.append(y)
return list_x, list_y
if __name__ == "__main__":
main()
|
b63d9aa3e7de3242001900ebbbf3ea1da118d016 | pauvrepetit/leetcode | /165/main.py | 897 | 3.5 | 4 |
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1 = list(map(int, version1.split('.')))
v2 = list(map(int, version2.split('.')))
v1Len = len(v1)
v2Len = len(v2)
if v1Len > v2Len:
v2 += [0] * (v1Len - v2Len)
else:
v1 += [0] * (v2Len - v1Len)
for i in range(len(v1)):
if v1[i] == v2[i]:
continue
elif v1[i] > v2[i]:
return 1
else:
return -1
return 0
print(Solution().compareVersion(version1="0.1", version2="1.1"))
print(Solution().compareVersion(version1="1.0.1", version2="1"))
print(Solution().compareVersion(version1="7.5.2.4", version2="7.5.3"))
print(Solution().compareVersion(version1="1.01", version2="1.001"))
print(Solution().compareVersion(version1="1.0", version2="1.0.0"))
|
9c4c06554b2ca59ad39716b5cf5d9457697e122e | Dochko0/Python | /Python_Fundamentals/02_Python_Intro_Functions_Debugging/tasks/g_greater_two_values.py | 231 | 3.953125 | 4 | value_type = input()
val1 = input()
val2 = input()
def compare_values(a, b):
if a > b:
printable(a)
else:
printable(b)
def printable(greater_value):
print(greater_value)
compare_values(val1, val2)
|
a7085c14c1cc4fc284859602a601298453a515d5 | robertmccraith/Euler | /p51.py | 576 | 3.5625 | 4 | primes = [2,3]
def prime_under(x):
p = primes[-1]
while x > primes[-1]:
p += 2
if len(filter(lambda a: p%a == 0, primes)) == 0:
primes.append(p)
import itertools
from math import sqrt
# for x in itertools.count(10000001,2):
# print x
x = 56003
replacements = []
for i in range(len(str(x))):
rep = []
for j in range(i, len(str(x))):
st = str(x)
for k in range(10):
st[i] = str(k)
st[j] = str(k)
rep.append(int(st))
replacements.append(rep)
primes_under(sqrt(i))
|
0f05f6453345424087a1c7db5bf6d4795730ed18 | BarryZM/dig-text-similarity-search | /dt_sim/data_reader/misc_io_funcs.py | 1,388 | 3.53125 | 4 | import os
import os.path as p
from pathlib import Path
from typing import Union
__all__ = ['check_unique', 'clear_dir']
def check_unique(test_path: Union[str, Path], count_mod: int = 0) -> str:
"""
Checks for path uniqueness.
Appends '_{count_mod}' to path (before file extension) if not unique.
Useful for .index files, which will corrupt if overwritten.
:param test_path: Path to test
:param count_mod: Int to unique-ify test_path
:return: Unique file path in target dir
"""
if p.exists(test_path):
print(f'\nWarning: File already exists {test_path}')
file_pth, file_ext = test_path.split('.')
new_path = ''.join(file_pth.split('_')[:-1]) \
+ f'_{count_mod}.{file_ext}'
print(f' Testing new path {test_path}\n')
count_mod += 1
check_unique(new_path, count_mod=count_mod)
else:
new_path = test_path
return new_path
def clear_dir(tmp_dir_path: Union[str, Path]):
"""
Functionally equivalent to:
$ rm -rf tmp_dir_path
:param tmp_dir_path:
"""
if not p.isdir(tmp_dir_path):
print('Not a directory: {}'.format(tmp_dir_path))
else:
for (tmp_dir, _, tmp_files) in os.walk(tmp_dir_path):
for file in tmp_files:
os.remove(os.path.join(tmp_dir, file))
os.rmdir(tmp_dir_path)
|
80e32d7dcb64ad4a11a5a29fb4c4a1954e9440c4 | galibce003/Python-Functions-Files-and-Dictionaries | /txtFile_open_read_count_1.py | 1,051 | 3.734375 | 4 | x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
y = x.read() #Read just return the strings
print(y[:5])
x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
y = x.readlines() #readlines return a list
#each line will be the value of the list
print(y)
x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
y = x.readlines() #readlines return a list
#each line will be the value of the list
for i in y: #In this time every line will be separated as like the txt file
print(i.strip()) #Strip just remove the extra space between 2 lines.
x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
for i in x: #We can directly iterate from x. But here whole file will be iterated. No slicing allowed.
print(i.strip())
#Count the characters
x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
y = x.read()
print(len(y))
#Count the lines
x = open("C:/Users/Mehedi Hassan Galib/Desktop/Python/gf.txt","r")
y = x.readlines()
print(len(y))
|
80ec15ca3293091968a903e8a046ef8a775a9a29 | eddy0/algorithm | /python/array/345. Reverse Vowels of a String .py | 1,013 | 3.9375 | 4 | """
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
"""
"""
思路:
反转元音字母,
先把 str 转为 list
利用 while 循环, 一个从前往后遍历, 一个从后往前遍历,
swap 指针, 如果不在数组内, 就 start++, end--, 如果双方都满足条件就 swap
"""
class Solution:
def reverseVowels(self, s: str) -> str:
arr = list(s)
vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
start = 0
end = len(s) - 1
while start < end:
if not arr[start] in vowel:
start += 1
if not arr[end] in vowel:
end -= 1
if arr[start] in vowel and arr[end] in vowel:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return ''.join(arr) |
2d00330c91bbf4a8aaddea4530c83a9b0b4afa87 | iamsiva11/Codingbat-Solutions | /string1/combo_string.py | 544 | 4.125 | 4 | """
Given 2 strings, a and b, return a string of the form
short+long+short, with the shorter string on the outside
and the longer string on the inside.
The strings will not be the same length, but they may be empty (length 0).
"""
def combo_string(a, b):
short_str=""
long_str=""
if(len(a)<len(b)):
short_str=a
long_str=b
else:
short_str=b
long_str=a
return short_str+long_str+short_str
print combo_string('Hello', 'hi') # 'hiHellohi'
print combo_string('hi', 'Hello') # 'hiHellohi'
print combo_string('aaa', 'b') # 'baaab'
|
907caf76266344cc2ca53cde8b3c5c97f2763c63 | fafusha/graph-turtle | /graph-turtle.py | 2,690 | 4 | 4 | from math import *
from turtle import *
# Creating an oriented graph graph type
class Graph:
# Initilizing infinite value
INF = 10**10
# Initilizing self
def __init__(self):
self.vertices = {}
self.vertices_count = 0
self.matrix = []
# Determening the ammount of vertices in a graph
def vertices_amount(self):
return self.vertices_count
# Adding vertex to a graph
def add_vertex(self, vertex):
self.vertices_count += 1
self.vertices[vertex] = self.vertices_count - 1
# Expanding matrix
for i in self.matrix:
i.append(self.INF)
self.matrix.append([self.INF]*self.vertices_count)
# Removing vertex from a graph
def remove_vertex(self, vertex):
# Checking if vertex is in graph
if vertex not in self.vertices:
pass
del self.matrix[self.vertices[vertex]]
for i in self.matrix:
del i[self.vertices[vertex]]
vertex_val = self.vertices[vertex]
for key in self.vertices:
if self.vertices[key] > vertex_val:
self.vertices[key] -= 1
del self.vertices[vertex]
self.vertices_count -= 1
# add support for oriented or not
# Setting edge value
def set_edge_value(self, x, y, v):
# Doing it twice, since graph is non-oriented
self.matrix[self.vertices[y]][self.vertices[x]] = v
self.matrix[self.vertices[x]][self.vertices[y]] = v
# Removing edge from graph
def remove_edge(self, x, y):
# Doing it twice, since graph is non-oriented
self.matrix[self.vertices[y]][self.vertices[x]] = self.INF
self.matrix[self.vertices[x]][self.vertices[y]] = self.INF
# Getting edge value
def get_edge_value(self, x, y):
return self.matrix[self.vertices[y]][self.vertices[x]]
## add inf checking or n/a
# Determing if two vericies are adjacent
def adjacent(self, x, y):
return self.matrix[self.vertices[y]][self.vertices[x]] != self.INF
# Creating a list of all adjecnt vertecies to a vertex
#rename to adjacent l
def neighbours(self, x):
lst = []
for y in range(self.vertices_count):
if self.matrix[y][self.vertices[x]] != self.INF:
lst.append(y)
neighb = []
for i in lst:
for vertex, value in self.vertices.items():
if value == i:
neighb.append(vertex)
return neighb
def __str__(self):
output = ""
for j in self.matrix:
output += ' '.join([str(i) for i in j]) + '\n'
return output
|
80156da74b2b016c1835b498467d6991eb86f835 | xwzl/python | /python/src/com/python/learn/obj/PropertyDecorator.py | 1,847 | 4.21875 | 4 | # 既要保护类的封装特性,又要让开发者可以使用“对象.属性”的方式操作操作类属性,除了使用 property() 函数,Python 还提供了 @property 装饰器。
# 通过 @property 装饰器,可以直接通过方法名来访问方法,不需要在方法名后添加一对“()”小括号。
#
# @property 的语法格式如下:
#
# @property
# def 方法名(self)
# 代码块
#
# 而要想实现修改 area 属性的值,还需要为 area 属性添加 setter 方法,就需要用到 setter 装饰器,它的语法格式如下:
#
# @方法名.setter
# def 方法名(self, value):
# 代码块
#
# 除此之外,还可以使用 deleter 装饰器来删除指定属性,其语法格式为:
#
# @方法名.deleter
# def 方法名(self):
# 代码块
#
# 例如,定义一个矩形类,并定义用 @property 修饰的方法操作类中的 area 私有属性
class Rect:
def __init__(self, area):
self.__area = area
self.qq = "腾讯"
# 使用 @property 修饰了 area() 方法,这样就使得该方法变成了 area 属性的 getter 方法。需要注意的是,如果类中只包含该方法,那么 area 属性将是一个只读属性
@property
def area(self):
return self.__area
# 而要想实现修改 area 属性的值,还需要为 area 属性添加 setter 方法,就需要用到 setter 装饰器
# 这样,area 属性就有了 getter 和 setter 方法,该属性就变成了具有读写功能的属性。
@area.setter
def area(self, area):
self.__area = area
@area.deleter
def area(self):
self.__area = 0
rect = Rect("成都")
print(rect.area)
rect.qq = 10
rect.area = 11
print(rect.area)
print(rect.qq)
del rect.area
print("删除后的area值为:", rect.area)
|
7160d6ee1994d460ff133eefb2dd5092836b39ef | nilestate15/PY101HW | /PY101/Week2/HW1/HW1wk2p4.py | 775 | 3.90625 | 4 | #Week 2 HW1
#Niles Tate
#Problem 4 (same as 3 but using with function)
def MK_choose(characters):
#Number of inputs
fighters = 2
#opens file and writes to it
with open(characters, "w") as o:
for i in range(fighters):
p1_choose = input("Please choose character")
#enters users input into file
o.write(p1_choose + "\n")
o.close()
#Append function
def MK_chosen(characters):
#opens file to add new text
with open(characters, "a") as o:
#adds this string to file
o.write("Characters chosen" + "\n")
o.close()
#Module being run standalone by user
if __name__ == "__main__":
characters = "MKcharacters.txt"
#Call functions
MK_choose(characters)
MK_chosen(characters)
|
80bb6cf7326162a3f74b6d130d5b226472b0ce84 | shelkesagar29/Python-Quizes | /list_operations.py | 454 | 4.15625 | 4 | import sys
list1=[1,2,3,4,5,6,7,8,9]
list1.append(10)#adds new item to the end of the list
print(list1)
list1.insert(3,15)#insert new item at given index
print(list1)
print(list1.pop())#Removes and resturns last item in a list
print(list1)
print(list1.pop(2))#Removes and returns element at ith position
print(list1.sort())#print sorted list
print(list1.reverse())#reverse. To get descending order, first sort and then reverse
del list1[0]
print (list1)
|
59b0ef34b763815b2180456fbaf64da7ccf92c53 | imperialself/adventofcode2020 | /day06/part2.py | 1,007 | 3.984375 | 4 | # Find the number of questions (letters) a group answered yes unanimously
# Return sum of all groups' unanimous letters
# https://adventofcode.com/2020/day/6
# Make each group of people into a list within the customs list
customs = []
for group in open('input').read().split('\n\n'):
customs.append(group.splitlines())
# Start fresh
yesCounts = []
# Starts with whatever person 1 had, iterate through each person and remove every remaining letter not present
def countYeses(c):
unanimous = list(c[0]) # Start with whatever person 1 said yes to
for p in c:
for l in c[0]: # More performant than looping through 26 letters every time
if l not in p:
try: # This is going to fail if it's already been removed so we only "try"
unanimous.remove(l)
except ValueError:
pass
yesCounts.append(len(unanimous)) # The length is a count of the remaining letters
# Iterate through all groups and count their yeses
for group in customs:
countYeses(group)
print(sum(yesCounts))
|
ac1f18e6e51788ad966110262cdac4a8aaa991cc | heoblitz/algorithm_study | /백준_알고리즘/10039.py | 122 | 3.78125 | 4 | sum = 0
for _ in range(5):
grade = int(input())
if grade < 40:
grade = 40
sum += grade
print(sum//5) |
7a9f02c4e16c01abf04f5a9f5caaecc2e9152d9d | rafaelperazzo/programacao-web | /moodledata/vpl_data/396/usersdata/294/80995/submittedfiles/av1_programa2.py | 652 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n1= int(input('Digite o primeiro número: '))
n2= int(input('Digite o segundo número: '))
n3= int(input('Digite o terceiro número: '))
n4= int(input('Digite o quarto número: '))
n5= int(input('Digite o quinto número: '))
n6= int(input('Digite o sexto número: '))
s1= int(input('Digite o primeiro número sorteado: '))
s2= int(input('Digite o segundo número sorteado: '))
s3= int(input('Digite o terceiro número sorteado: '))
s4= int(input('Digite o quarto número sorteado: '))
s5= int(input('Digite o quinto número sorteado: '))
s6= int(input('Digite o sexto número sorteado: '))
|
40e80221272b51112ef31de51aa5387287373b9e | Busc/Coding-Interviews | /01 算法和数据操作/11 旋转数组的最小数字.py | 1,128 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
left, right = 0, len(rotateArray)-1
# 考虑到数组本身就是有序的情况
mid = 0
while rotateArray[left] >= rotateArray[right]:
if right - left == 1:
return rotateArray[right]
mid = (right + left) // 2
if rotateArray[left] == rotateArray[mid] and rotateArray[right] == rotateArray[mid]:
# 无法判断最小值在哪一段
return self.orderSearch(rotateArray, left, right)
if rotateArray[mid] >= rotateArray[left]:
# 最小值位于后半段
left = mid
elif rotateArray[mid] <= rotateArray[right]:
# 最小值位于前半段或者就是mid
right = mid
def orderSearch(self, rotateArray, firstInd, lastInd):
minNum = rotateArray[firstInd]
for i in range(firstInd+1, lastInd+1):
if minNum > rotateArray[i]:
minNum = rotateArray[i]
return minNum
|
48c060953fa9f09e82f10984d20550c454334c07 | ethrlrnr/python-misc | /anagrams.py | 2,348 | 4.125 | 4 | def are_anagrams(str1, str2):
str1dict = {}
str2dict = {}
for i in str1:
if ord(i) >= 97 and ord(i) <= 122 or (ord(i) >= 65 and ord(i) <= 90):
if i.lower() not in str1dict:
str1dict[i.lower()] = 0
str1dict[i.lower()] += 1
for i in str2:
if ord(i) >= 97 and ord(i) <= 122 or (ord(i) >= 65 and ord(i) <= 90):
if i.lower() not in str2dict:
str2dict[i.lower()] = 0
str2dict[i.lower()] += 1
if len(str1dict) == len(str2dict) and len(str1dict) > 0:
for i in str1dict:
if i in str2dict and str1dict[i] == str2dict[i]:
continue
else:
return False
else:
return False
return True
#This problem can also be done in multiple ways.
#Firstly, because we are told not to consider spaces and capitalization
#we change our input strings to lower and remove all our spaces.
def are_anagrams(first_word, second_word):
first_word = first_word.lower()
second_word = second_word.lower()
first_word = first_word.replace(' ', '')
second_word = second_word.replace(' ', '')
#For me, the first thought was to store the letters of the first word
#into a list and then iterate through the second word and remove the letter stored
#if it existed in the list.
#SO, I create an empty list called 'letters'
letters = []
#I then iterate through my first word and the append all the characters
for char in first_word:
letters.append(char)
#I then iterate through my second word and see if the letter I am currently
#iterating through is in my list.
#If it is in my list, then I remove that character (this avoids duplicates)
#and if my current letter is not in my list then I automatically return False
#since that means my second word has a letter that my first word doesn't!
for char in second_word:
if char not in letters:
return False
letters.remove(char)
#At the very end when we are done iterating through, I return the boolean value
#of whether my length of list is equal to 0. I do not simply return True because
#there may be cases where my first word will have letters that my second letter
#might not have. ie. first = hello, second = helo (list would still contain 'l')
return len(letters) == 0
|
44b0a0e3fa7b2005f15f7821260caaf10fe17c40 | kiponik/Python | /Lecture3/Task2.py | 595 | 3.609375 | 4 | def user_details(a, b, c, d, e):
print(
"Ваше имя: " + a + "Ваша фамилия: " + b + "Ваш год рождения: " + c + "Ваш email: " + d + "Ваш номер телефона: " + e, sep=' ')
name = input('Введите имя ')
surname = input('Введите фамилия ')
birth_date = input('Введите ваш год рождание ')
email = input('Введите почтовый ящик ')
phone_number = input('Введите ваш номер телефона ')
user_details(a=name, b=surname, c=birth_date, d=email, e=phone_number)
|
69da073d6ffd58d60a95270fe52721b8389be17a | kallemoen/python_projects | /word-counter/main.py | 1,457 | 4.03125 | 4 | # [ ] Open file and remove every special character
# [ ] Split words into a list
# [ ] Cycle through each word creating a dict for each word and counting every time a word is mentioned
# [ ] Cycle through values filtering out top 10 words
# Creates a list of lists from txt file
# traffic_file = open('article.txt', 'r') # Do I need to close this?
# traffic_file = traffic_file.read()
traffic_file = "The invention that could end obesity a michigan surgeon invented an apparatus, that he believes tricks the brain into thinking the stomach is full his full sense device could be a lifesaver for millions of obese americans and, raises questions about how hunger - our most basic human impulse — even works."
special_characters = ["-", ".", ",", "–", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "“", '”']
# remove casing
traffic_file = str.lower(traffic_file)
# remove special special_characters
listed_string = list(traffic_file)
for char in listed_string:
if char in special_characters:
listed_string.remove(char)
else:
pass
traffic_file = "".join(listed_string)
print(traffic_file)
# traffic_file = list(traffic_file.split(" "))
#
# word_occurance_dict = {}
#
# for word in traffic_file:
# if word not in word_occurance_dict:
# word_occurance_dict[word] = 1
# if word in word_occurance_dict:
# word_occurance_dict[word] += 1
# else:
# pass
#
# print(word_occurance_dict)
|
298da6e01025cc6bdda2efffffe7fe5399190141 | dheena18/python | /day11ex4.py | 242 | 4.0625 | 4 | numbers= [1, 2, 4, 5, 7, 8, 10, 11]
def filterOddNum(num):
if(num % 2) == 0:
return False
else:
return True
oddfilter = filter(filterOddNum, numbers)
print("The odd numbers in the list are: ", list(oddfilter)) |
ec84a42c6cd807e3fcaf08902e2cad9470607fbc | DunnyDon/FYP_PredictingHumanBehaviour_Using_CallDetailRecords | /SVM_CrossVal.py | 1,202 | 3.5 | 4 | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn import svm
import pandas as pd
from sklearn.model_selection import cross_val_score
dataframe = pd.read_csv("ML_Data.csv")
dataset = dataframe.values
# split into input (X) and output (Y) variables
#print dataframe.columns, dataframe.shape
columns = dataframe.columns.tolist()
# Filter the columns to remove ones we don't want.
data = [c for c in columns if c not in ["MSISDN", "mod_class","CredCount"]]
target = [c for c in columns if c not in ["MSISDN", "mod_class","in_degree","out_degree","total_degree"]]
print target
all_data = dataframe.sample(frac=1)
x_data = all_data[data]
y_data = all_data[target]
y_data = pd.DataFrame.as_matrix(y_data).ravel()
print x_data.shape,y_data.shape
# Store the variable we'll be predicting on.
X_train, X_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.4, random_state=0)
# Initialize the model class.
clf = svm.SVC(kernel = 'linear',C = 2.5,gamma = 1) # Passing C = 1.1 to SVC improves the results
scores = cross_val_score(clf, x_data, y_data, cv=3)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
|
fa0c0eb525bc5a5be09043d6b300a9aa7c42f724 | smirnown/MyPythonClasses | /data_structures/linked_lists/my_doubly_linked_list.py | 7,873 | 4.09375 | 4 | """This module contains my custom doubly linked list and double node classes."""
class MyDoubleNode:
"""
This is my attempt to code a node for use in doubly linked lists.
It contains pointers to both the next and previous nodes in the list.
"""
def __init__(
self,
value=0
):
"""Initialize the node."""
self.value = value
self.next_node = None
self.previous_node = None
def set_value(
self,
value
):
"""Set value of current node."""
self.value = value
def get_value(
self
):
"""Return value of node."""
return self.value
def set_next_node(
self,
new_node
):
"""Set next node."""
self.next_node = new_node
def get_next_node(
self
):
"""Move to next node."""
return self.next_node
def set_previous_node(
self,
previous_node
):
"""Set the previous node."""
self.previous_node = previous_node
def get_previous_node(
self
):
"""Move to previous node."""
return self.previous_node
class MyDoublyLinkedList:
""""This is my attempt to code a doubly linked list."""
def __init__(
self,
):
"""Initialize the doubly linked list."""
self.first_node = None
self.last_node = None
def print_list(
self
):
"""Prints the contents of the doubly linked list."""
current_node = self.first_node
while current_node:
print(current_node.get_value())
current_node = current_node.get_next_node()
def add(
self,
value
):
"""Adds a new node to the end of the doubly linked list."""
new_node = MyDoubleNode(value)
list_is_empty = self.first_node is None
if list_is_empty:
self.first_node = new_node
self.last_node = new_node
else:
self.last_node.set_next_node(new_node)
new_node.set_previous_node(self.last_node)
self.last_node = new_node
def size(
self
):
"""Returns the size of the linked_list."""
size_of_list = 0
temp_node = self.first_node
while temp_node is not None:
size_of_list += 1
temp_node = temp_node.get_next_node()
return size_of_list
def get_node(
self,
index
):
"""Returns the node at the specified index."""
i = 0
current_node = self.first_node
index_exceeds_number_of_elements_in_list = index >= self.size()
if index_exceeds_number_of_elements_in_list:
print("The specified index exceeds the number of elements in this list.")
return None
while i < index:
current_node = current_node.get_next_node()
i += 1
return current_node
def get_value(
self,
index
):
"""Returns the value from the node at the given index."""
value = self.get_node(index).get_value()
return value
def __insert_node_at_beginning(
self,
new_node
):
"""Inserts a new node at the beginning of a doubly linked list."""
list_is_empty = self.size() == 0
if list_is_empty:
self.add(new_node.get_value())
else:
new_node.set_next_node(self.first_node)
self.first_node.set_previous_node(new_node)
self.first_node = new_node
def __insert_node_in_middle(
self,
new_node,
index
):
"""Inserts a new node anywhere after the beginning of a doubly linked list."""
node_before_inserted_node = self.get_node(index - 1)
node_after_inserted_node = self.get_node(index)
node_before_inserted_node.set_next_node(new_node)
new_node.set_next_node(node_after_inserted_node)
new_node.set_previous_node(node_before_inserted_node)
node_after_inserted_node.set_previous_node(new_node)
def insert(
self,
value,
index
):
"""Inserts a node containing 'value' at 'node_index'."""
new_node = MyDoubleNode(value)
size_of_list = self.size()
inserting_node_at_start_of_list = index == 0
inserting_node_in_middle_of_list = (index > 0) and (index < size_of_list)
inserting_node_at_end_of_list = index == size_of_list
if inserting_node_at_start_of_list:
self.__insert_node_at_beginning(new_node)
elif inserting_node_in_middle_of_list:
self.__insert_node_in_middle(new_node, index)
elif inserting_node_at_end_of_list:
self.add(value)
else:
print("The index specified is out of range.")
def exists(
self,
value
):
"""Checks if the specified value is stored anywhere in the doubly linked list."""
size_of_list = self.size()
index = 0
while index < size_of_list:
if self.get_value(index) == value:
return True
index += 1
return False
def __delete_first_node(
self
):
"""Deletes the first node in the doubly linked list."""
list_is_size_1 = self.size() == 1
if list_is_size_1:
self.first_node = None
self.last_node = None
else:
self.first_node = self.get_node(1)
self.first_node.set_previous_node(None)
def __delete_node_in_middle(
self,
index
):
"""Deletes a node in the middle of the doubly linked list."""
node_after_deleted_node = self.get_node(index + 1)
node_before_deleted_node = self.get_node(index - 1)
node_before_deleted_node.set_next_node(node_after_deleted_node)
node_after_deleted_node.set_previous_node(node_before_deleted_node)
def __delete_last_node(
self
):
"""Deletes the last node in the doubly linked list."""
size_of_list = self.size()
node_before_last_node = self.get_node(size_of_list - 2)
node_before_last_node.set_next_node(None)
self.last_node.set_previous_node(None)
self.last_node = node_before_last_node
def delete_by_index(
self,
index
):
"""Removes the node at the specified index from the doubly linked list."""
last_index = self.size() - 1
deleting_first_node = index == 0
deleting_node_in_middle = (index > 0) and (index < last_index)
deleting_last_node = index == last_index
if deleting_first_node:
self.__delete_first_node()
elif deleting_node_in_middle:
self.__delete_node_in_middle(index)
elif deleting_last_node:
self.__delete_last_node()
else:
print("The index specified is out of range.")
def delete_first_occurrence_of_value(
self,
value_to_be_deleted
):
"""Deletes the first node with the specified value."""
index = 0
size_of_list = self.size()
while index < size_of_list:
current_value = self.get_value(index)
if current_value == value_to_be_deleted:
self.delete_by_index(index)
break
else:
index += 1
def delete_all_occurrences_of_value(
self,
value_to_be_deleted
):
"""Deletes all nodes with the specified value."""
while self.exists(value_to_be_deleted):
self.delete_first_occurrence_of_value(value_to_be_deleted)
|
491b47b0192acf9119f026fbc80bf813ba8590ec | mansoniakki/PY | /If_the_else.py | 499 | 4.0625 | 4 | print("###############using if then else################")
age=17
if age > 17:
print("You can bye liquer")
else:
print("You can not buy liquer")
score=85
print('The grade was: ',end=' ')
if score < 60:
print('F')
elif 60 <= score <70:
print('D')
elif 70 <= score < 79:
print('C')
elif 80 <= score < 90:
print('B')
elif 90 <= score <=100:
print('A')
else:
print("Impossible!")
print("using debug to debug the code")
debug = True
if debug: print("Score was: ",score) |
b179eda7cd4a06582a88b2b9e53c8bf65ae2c5f9 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc035/D/4920287.py | 1,532 | 3.671875 | 4 | import heapq
class PriorityQueue:
def __init__(self):
self.__heap = []
self.__count = 0
def empty(self) -> bool:
return self.__count == 0
def dequeue(self):
if self.empty():
raise Exception('empty')
self.__count -= 1
return heapq.heappop(self.__heap)
def enqueue(self, v):
self.__count += 1
heapq.heappush(self.__heap, v)
def __len__(self):
return self.__count
def dijkstra(graph: list, s: int)->list:
INF = float('inf')
d = [INF] * len(graph)
d[s] = 0
q = PriorityQueue()
q.enqueue((d[s], s))
while not q.empty():
_, u = q.dequeue()
for v, c in graph[u]:
alt = d[u] + c
if alt < d[v]:
d[v] = alt
q.enqueue((d[v], v))
return d
def treasure_hant(N: int, M: int, T: int, A: list, edges: list)->int:
forward = [[] for _ in range(N)]
backward = [[] for _ in range(N)]
for u, v, c in edges:
forward[u-1].append((v-1, c))
backward[v-1].append((u-1, c))
df = dijkstra(forward, 0)
db = dijkstra(backward, 0)
return max((T - df[i] - db[i]) * A[i] for i in range(N))
if __name__ == "__main__":
M = 0
N, M, T = map(int, input().split())
A = [int(s) for s in input().split()]
edges = [tuple(int(s) for s in input().split()) for _ in range(M)]
ans = treasure_hant(N, M, T, A, edges)
print(ans) |
db0af2094e50c2e031355640e74f3cbec3628969 | Margarita-Sergienko/codewars-python | /6 kyu/Find the missing letter.py | 853 | 4.0625 | 4 | # 6 kyu
# Find the missing letter
# https://www.codewars.com/kata/5839edaa6754d6fec10000a2
# Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
# You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
# The array will always contain letters in only one case.
# Example:
# ['a','b','c','d','f'] -> 'e' ['O','Q','R','S'] -> 'P'
# ["a","b","c","d","f"] -> "e"
# ["O","Q","R","S"] -> "P"
def find_missing_letter(chars):
if chars[0].islower():
s = "abcdefghijklmnopqrstuvwxyz"
else:
s = "abcdefghijklmnopqrstuvwxyz".upper()
lst = list(s[s.index(chars[0]):s.index(chars[-1])+1])
chars, lst = set(chars), set(lst)
return list(lst - chars)[0] |
8fa30bb9c7873f2847341b8d64bb84987553a6a5 | Kaushty/Expense-Tracker | /operations.py | 1,031 | 3.59375 | 4 | from helper import getDateRangeFromWeek, getEntriesBetween
def getWeeklyData(startDate, endDate, rangedData):
weeklyData = getEntriesBetween(rangedData, startDate, endDate)
weeklyTotal = 0
print(f'Report from {startDate} to {endDate}')
for index, row in weeklyData.iterrows():
print(row['Date'], row['Name'], row['Amount'])
weeklyTotal += int(row['Amount'])
print(f'The Weekly total for this week is {weeklyTotal}\n')
return weeklyTotal
def printWeeklyData(numOfWeeks, startDate, endDate, rangedData):
'''
Function to return the sliced data in a formatted manner
'''
print(f'\n Displaying report from Date {startDate} to {endDate}\n')
weekCounter = numOfWeeks
while True:
year = endDate.year
week = endDate.isocalendar()[1] - weekCounter + 1
if weekCounter == 0:
break
else:
[ weekStartDate, weekEndDate ] = getDateRangeFromWeek(year, week)
getWeeklyData(weekStartDate, weekEndDate, rangedData)
weekCounter -= 1
return 'Report printed succesfully' |
11b1176796dfb6a7bd908536ad822603cc36bfbe | Kontowicz/Daily-coding-problem | /day_065.py | 821 | 4.21875 | 4 | # Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
def clockwise(row, column, array):
k = 0; l = 0
while (k < row and l < column) :
for i in range(l, column) :
print(array[k][i])
k += 1
for i in range(k, row) :
print(array[i][column - 1])
column -= 1
if ( k < row) :
for i in range(column - 1, (l - 1), -1) :
print(array[row - 1][i])
row -= 1
if (l < column) :
for i in range(row - 1, k - 1, -1) :
print(array[i][l])
l += 1
array = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
row = 4
colum = 5
clockwise(row, colum, array) |
7db3556efc88cd3d511632383bf648e3a4aaecfc | talidemestre/open-source-home-speaker | /archive files/workinghowiwantbutwhy.py | 2,307 | 3.625 | 4 | import time
UserVoiceInput = "set an alarm for five thirty seven"#placeholder voice-interpreted text
UserVoiceInput = UserVoiceInput.lower()
VoiceArray = UserVoiceInput.split(" ")
hourList = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
minuteMono = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
minutePrefix =['twenty','thirty','fourty','fifty','sixty']
minuteSuffix =['one', 'two', 'three', 'four', 'five', "six", "seven", "eight", "nine"]
hour_word = ""
minute_mono_word = ""
minute_prefix_word = ""
minute_suffix_word = ""
AMorPM = "PM" ###DEFAULT PLEASE CHANGE###
hour_detected = False
for word in range(0, len(VoiceArray)):
print (VoiceArray[word])
if hour_detected == False:
for num in range (0, len(hourList)):
if VoiceArray[word] == hourList[num]:
hour_detected = True
hourFoundAt = word
hour_word = VoiceArray[word]
else:
for num in range (0, len(minuteMono)):
if VoiceArray[word] == minuteMono[num]:
minute_mono_word = VoiceArray[word]
for num in range (0, len(minutePrefix)):
if VoiceArray[word] == minutePrefix[num]:
minute_prefix_word = VoiceArray[word]
for num in range (0, len(minuteSuffix)):
if VoiceArray[word] == minuteSuffix[num]:
minute_suffix_word = VoiceArray[word]
##Converting Words into Numbers##
HourString = ''
MinuteString = ''
finalHour=0
finalMinute=0
for i in range (0, len(hourList)):
if hour_word == hourList[i]:
finalHour = i+1
if minute_mono_word == '':
if minute_prefix_word != '':
for i in range (0, len(minutePrefix)):
if minute_prefix_word == minutePrefix[i]:
finalMinute+= 10*((i+2))
if minute_suffix_word != '':
for i in range (0, len(minuteSuffix)):
if minute_suffix_word == minuteSuffix[i]:
finalMinute += i+1
else:
for i in range (0, len(minuteMono)):
if minute_mono_word == minuteMono[i]:
finalMinute = i + 10
|
6a5ca44347b7e9f95d9afd2636104e258b6d0a57 | bacinger/AdventOfCode2018 | /day-11.py | 1,752 | 3.609375 | 4 | serial_number = 5791
"""
1. Find the fuel cell's rack ID, which is its X coordinate plus 10.
2. Begin with a power level of the rack ID times the Y coordinate.
3. Increase the power level by the value of the grid serial number (your puzzle input).
4. Set the power level to itself multiplied by the rack ID.
5. Keep only the hundreds digit of the power level (so 12345 becomes 3; numbers with no hundreds digit become 0).
6. Subtract 5 from the power level.
"""
def calc(x, y, sn):
rack_ID = x + 10
power_level = (rack_ID * y + sn) * rack_ID
hundreds = int(str(power_level)[-3])
return hundreds - 5
a = []
for i in range(300):
a.append([])
for j in range(300):
a[i].append(calc(i, j, serial_number))
total_power = 0
max_power = 0
max_power_pos = (0,0)
for i in range(298):
for j in range(298):
total_power = a[i][j]+a[i+1][j]+a[i+2][j]+a[i][j+1]+a[i+1][j+1]+a[i+2][j+1]+a[i][j+2]+a[i+1][j+2]+a[i+2][j+2]
if total_power > max_power:
max_power = total_power
max_power_pos = (i, j)
print('Part 1:', max_power_pos, max_power)
size = 50 # Size can be 1:300, but 50 is enough
total_power = 0
max_power = 0
max_power_pos = (0,0)
max_size = 1
for i in range(300):
for j in range(300):
for s in range(size):
for x in range(s+1):
for y in range(s+1):
if (i+x < 300) and (j+y < 300):
total_power += a[i+x][j+y]
else:
break
if total_power > max_power:
max_power = total_power
max_power_pos = (i, j)
max_size = s+1
total_power = 0
print('Part 2:', max_power_pos, max_size, max_power) |
81651c66ce69a2c744f27ec502d5fae04b31eb4d | sam20596/programas--phyton | /ENCONTRAR VARIABLES EN UNA LISTA.py | 187 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 11:11:59 2020
@author: Xp
"""
lista=["R1","R2","R3","R4","S1","S2","S3"]
for i in lista:
if "S" in i:
print (i) |
ca719724a5f1bca78ab453588478d400d94187ac | ledovsky/instagram-analysis | /app/utils.py | 1,422 | 3.515625 | 4 | import csv
import requests
import json
def get_json(url, params=None):
'''
Wrapper around requests.get with custom header and json.loads
todo: error handling
'''
headers = {
'Cache-Control': 'no-cache',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ 39.0.2171.95 Safari/537.36',
'Referrer': 'https://www.google.com/',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'ru-RU,en-US,en;q=0.8'
}
r = requests.get(url, params=params, headers=headers)
return json.loads(r.text)
class DictUnicodeProxy(object):
'''
This wrapper class is used to write dicts with unicode to csv files
'''
def __init__(self, d):
self.d = d
def __iter__(self):
return self.d.__iter__()
def get(self, item, default=None):
i = self.d.get(item, default)
if isinstance(i, unicode):
return i.encode('utf-8')
return i
def write_dict_list(dicts, path):
'''
Function to write dict list as csv file
'''
keys = dicts[0].keys()
with open(path, 'w') as f:
dict_writer = csv.DictWriter(f, keys)
dict_writer.writeheader()
for d in dicts:
dict_writer.writerow(DictUnicodeProxy(d))
|
e9fefb7907f53eb6f0eaada5550f3edc5e8adf52 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC333.py | 1,077 | 3.78125 | 4 | # O(n)
# n = numberOfNodes(root)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
res = [0]
self.explore(root, res)
return res[0]
def explore(self, node, res):
if node is None:
return [True, 0, float("-inf"), float("inf")]
isLeftBst, leftQuant, leftMax, leftMin = self.explore(node.left, res)
isRightBst, rightQuant, rightMax, rightMin = self.explore(node.right, res)
subTreeQuant = leftQuant + rightQuant + 1
isSubTreeBst = (
isLeftBst and isRightBst and leftMax < node.val and rightMin > node.val
)
if isSubTreeBst and subTreeQuant > res[0]:
res[0] = subTreeQuant
return [
isSubTreeBst,
subTreeQuant,
max(node.val, leftMax, rightMax),
min(node.val, leftMin, rightMin),
]
|
bdf03d00958c1e5710b4fb207e693be2c8f2089e | Linkstrange/n-queens | /n_queens_solver.py | 1,109 | 3.71875 | 4 | # A class that can solve the n queens problem given a specific board
class NQueensSolver:
def __init__(self, board):
self.solutions = []
self._board_size = board.get_size()
self._board = board
def solve_n_queens(self, col=0):
# If all queens are placed add 1 to the solutions and print the board
if col >= self._board_size:
self.save_solution(self._board.get_board_state())
self._board.print_board()
return
# Try to place this queen in each row of this column
for i in range(self._board_size):
if self._board.is_safe(i, col):
# place this queen on the board on position i, col
self._board.place_queen(i, col)
# recur to place remaining queens
self.solve_n_queens(col + 1)
# remove queen to try next position
self._board.remove_queen(i, col)
def save_solution(self, board_state):
self.solutions.append(board_state)
def get_solutions_count(self):
return len(self.solutions)
|
170d287f7daa880f7a4e26553bf5cf840ac68f6c | iamGauravMehta/Hackerrank-Problem-Solving | /Algorithms/Strings/hackerrank-in-a-string.py | 430 | 3.640625 | 4 | # HackerRank in a String!
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem
q = int(input().strip())
for a0 in range(q):
word = ['h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k']
s = input().strip()
for i in range(len(s)):
if len(word) == 0:
break
if s[i] == word[0]:
word.remove(s[i])
print ("NO" if len(word) > 0 else "YES") |
8d888023490587dc7a2cd754ded26adbe3b77d7b | hpf0532/algorithms_demo | /leetcode/141_环形链表.py | 2,103 | 3.90625 | 4 | # -*- coding:utf-8 -*-
# author: hpf
# create time: 2020/10/25 23:18
# file: 141_环形链表.py
# IDE: PyCharm
# 题目描述
# 给定一个链表,判断链表中是否有环。
#
# 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
#
# 如果链表中存在环,则返回 true 。 否则,返回 false 。
#
# 进阶:
#
# 你能用 O(1)(即,常量)内存解决此问题吗?
# 提示:
#
# 链表中节点的数目范围是 [0, 104]
# -105 <= Node.val <= 105
# pos 为 -1 或者链表中的一个 有效索引 。
# 解法一: 哈希表
# 通过遍历所有节点,判断当前是否在哈希表中出现过,如果出现过则说明有环,否则没有环路
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution1:
def hasCycle(self, head: ListNode) -> bool:
seen = set()
while head:
# 节点重复,有环
if head in seen:
return True
seen.add(head)
head = head.next
return False
# 解法二: 快慢指针
class Solution2:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
# 解法三:快慢指针2
class Solution3:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False |
1352c2a411becf18eb0f1b1a1c64c7b328ab81b5 | MarekKarmelski/python-scripts | /arb_2_rom.py | 834 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert arabic number to roman number function."""
def arb_2_rom(arabic_number):
"""Convert arabic number to roman number function."""
roman_numerals = {
0: [1000, 'M'],
1: [900, 'CM'],
2: [500, 'D'],
3: [400, 'CD'],
4: [100, 'C'],
5: [90, 'XC'],
6: [50, 'L'],
7: [40, 'XL'],
8: [10, 'X'],
9: [9, 'IX'],
10: [5, 'V'],
11: [4, 'IV'],
12: [1, 'I']
}
roman_number = ''
for key, value in roman_numerals.items():
while arabic_number >= value[0]:
roman_number += value[1]
arabic_number -= value[0]
return roman_number
arabic_number = 2945
roman_number = arb_2_rom(arabic_number)
print('%s(%s)' % (roman_number, arabic_number))
|
33f7018c4a59997cbfddf0fe5059dc9e8ed27699 | sunpyopark/CoderByte-Python-Easy | /05-SimpleAdding.py | 462 | 3.59375 | 4 | '''
From CoderByte: "Using the Python language, have the function SimpleAdding(num)
add up all the numbers from 1 to num. For the test cases,
the parameter num will be any number from 1 to 1000."
'''
#1-Add up all the numbers from 1 through num (no more than 1000).
#Return - The result of the addition
def simple_adding(num):
num_holder = 0
for i in range(num):
i = i + 1
num_holder += i
return num_holder
print simple_adding(12)
|
d4e05654b4b79aac510774b28f69a9e1f5f3a25e | kantegory/studying | /algorithms/lab3/bogosort/bogosort.py | 553 | 3.5625 | 4 | from random import *
from time import *
def correct_order(data):
count = 0
while count + 1 < len(data):
if data[count] > data[count + 1]:
return False
count += 1
return True
def bogosort(data):
while not correct_order(data):
shuffle(data) # randomize data
return data
if __name__ == "__main__":
data = [randint(0, 100) for i in range(10)]
start = time()
print("Before: ", data)
data = bogosort(data)
print("After: ", data)
print("%.2f seconds" % (time() - start))
|
f63988293b9a7136ce94ea569fe2f8d037ee3224 | msznajder/allen_downey_think_python | /ch12.py | 5,337 | 4.59375 | 5 | ## Chapter 12 Tuples
## 12.1 Tuples are immutable
# A tuple is a sequence of values.
# The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists.
# The important difference is that tuples are immutable.
t = 'a', 'b', 'c'
# Although it is not necessary, it is common to enclose tuples in parentheses.
t = ('a', 'b', 'c')
# To create a tuple with a single element, you have to include a final comma.
t1 = 'a',
# A value in parentheses is not a tuple.
t2 = ('a')
type(t2) # <class 'str'>
# Another way to create a tuple is the built-in function tuple.
# With no argument, it creates an empty tuple.
t3 = tuple()
# If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence.
t = tuple("lupins")
t # ('l', 'u', 'p', 'i', 'n', 's')
# The bracket operator indexes an element.
t[0]
# The slice operator selects a range of elements.
t[1:3]
# If you try to modify one of the elements of the tuple, you get an error.
# t[0] = 1
# Traceback (most recent call last):
# File "ch12.py", line 48, in <module>
# t[0] = 1
# TypeError: 'tuple' object does not support item assignment
# Because tuples are immutable, you can’t modify the elements.
# But you can replace one tuple with another.
t = ('A',) + t[1:]
t # ('A', 'b', 'c', 'd', 'e')
# This statement makes a new tuple and then makes t refer to it.
# The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).
(0, 1, 2) < (0, 3, 4) # True
(0, 1, 20000000) < (0, 3, 4) # True
## 12.2 Tuple assignment
a = 1
b = 2
a, b = b, a
a, b = 1, 2
# a, b = 1, 2, 3 # error
## 12.3 Tuples as return values
# Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.
def min_max(t):
return min(t), max(t)
## 12.4 Variable-length argument tuples
# Functions can take a variable number of arguments.
# A parameter name that begins with * gathers arguments into a tuple.
def print_all(*args):
print(args)
# The complement of gather is scatter.
# If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator.
t = (7, 9)
# divmod(t)
# Traceback (most recent call last):
# File "ch12.py", line 105, in <module>
# divmod(t)
# TypeError: divmod expected 2 arguments, got 1
divmod(*t)
# Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments.
max(1, 2, 3)
# But sum does not.
# sum(1, 2, 3)
# Traceback (most recent call last):
# File "ch12.py", line 122, in <module>
# sum(1, 2, 3)
# TypeError: sum expected at most 2 arguments, got 3
## 12.5 Lists and tuples
# zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.
s = "abc"
l = [0, 1, 2]
z = zip(s, t)
# The result is a zip object that knows how to iterate through the pairs.
# A zip object is a kind of iterator, which is any object that iterates through a sequence. Iterators are similar to lists in some ways, but unlike lists, you can’t use an index to select an element from an iterator.
list(z) # [('a', 0), ('b', 1), ('c', 2)]
# The result is a list of tuples; in this example, each tuple contains a character from the string and the corresponding element from the list.
# If the sequences are not the same length, the result has the length of the shorter one.
list(zip("Anne", "Elk")) # [('A', 'E'), ('n', 'l'), ('n', 'k')]
# You can use tuple assignment in a for loop to traverse a list of tuples.
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print(letter, number)
# You can traverse two sequences at the same time.
l1 = [1, 2, 3]
l2 = [4, 5, 6]
for x, y in zip(l1, l2):
print(x, y)
# Traverse the elements of a sequence and their indices, you can use the built-in function enumerate.
for idx, val in enumerate("abc"):
print(idx, val)
# The result from enumerate is an enumerate object, which iterates a sequence of pairs.
# Each pair contains an index (starting from 0) and an element from the given sequence.
## 12.9 Glossary
# tuple:
# An immutable sequence of elements.
# tuple assignment:
# An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left.
# gather:
# The operation of assembling a variable-length argument tuple.
# scatter:
# The operation of treating a sequence as a list of arguments.
# zip object:
# The result of calling a built-in function zip; an object that iterates through a sequence of tuples.
# iterator:
# An object that can iterate through a sequence, but which does not provide list operators and methods.
# data structure:
# A collection of related values, often organized in lists, dictionaries, tuples, etc.
# shape error:
# An error caused because a value has the wrong shape; that is, the wrong type or size.
|
8a222ba5145c8b7ec84ea01fa5e2e22971c8a49a | AliOssama/Code-Samples | /Coin heuristic.py | 650 | 4.09375 | 4 | #This program shows the efficiancy of a heuristic development
#This function inputs an array of coins values and the length of that array
def coinValue(coinsV, n):
#initially comparing the far left and right coins
num1=coinsV[0]
num2=coinsV[n-1]
#this will be our max profit
maxValue=0
#i is the year and will be the index as well
for i in range(1, n+1):
maxValue += min(num1*i, num2*i)
if num1 < num2:
num1=coinsV[i]
elif num2 < num1:
num2=coinsV[n-1-i]
return maxValue
#Example of use
coins=[1,2,3,4]
n=len(coins)
print(coinValue(coins, n))
|
76eff488215bf09c94cb2e6939f07530dd84d3ec | LuisTavaresJr/cursoemvideo | /ex47.py | 183 | 3.921875 | 4 | print('Vamos mostrar na tela todos números pares entre 1 a 50!')
for c in range(0, 51):
if c % 2 == 0:
print(c, end=' ')
for c in range(0, 51, 2):
print(c, end=' ')
|
d49324055676a2756bbec94103360ef8e370d288 | gabriel-roque/python-study | /01. CursoEmVideo/Mundo 01/Aula 07 - Operadores Aritimeticos/Desafio09.py | 582 | 3.921875 | 4 | valor = int(input('De qual numero gostaria obter a tabuada: '))
print('-------------')
print('{} x 1 = {}'.format(valor,(valor*1)))
print('{} x 2 = {}'.format(valor,(valor*2)))
print('{} x 3 = {}'.format(valor,(valor*3)))
print('{} x 4 = {}'.format(valor,(valor*4)))
print('{} x 5 = {}'.format(valor,(valor*5)))
print('{} x 6 = {}'.format(valor,(valor*6)))
print('{} x 7 = {}'.format(valor,(valor*7)))
print('{} x 8 = {}'.format(valor,(valor*8)))
print('{} x 9 = {}'.format(valor,(valor*9)))
print('{} x 10 = {}'.format(valor,(valor*10)))
print('-------------') |
d3154ee3ed0ee6e298aa15f5ef1e9a7435b59a51 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2897.py | 2,508 | 3.640625 | 4 | def flip_shit(file):
input_list = file.readlines()
cases = int(input_list[0])
for i in range(1, cases + 1, 1):
pancake_row = input_list[i].split()[0]
size = int(input_list[i].split()[1])
print('Case #' + str(i) + ': ' + str(check_flips(pancake_row, size)))
def check_flips(pancakes: str, size: int) -> str:
original_row = pancakes
flip_history = {original_row}
flips = 0
on_left = True
while pancakes != '+' * len(original_row):
flip_index = -1
#find first - from the left
if on_left:
for char in range(len(pancakes)):
if pancakes[char] == '-':
flip_index = char
break
if flip_index == -1:
on_left = False
else:
pancakes = flipped_some(pancakes, size, flip_index, on_left)
on_left = False
else:
# find first - from the right
for char in range(len(pancakes) - 1, -1, -1):
if pancakes[char] == '-':
flip_index = char
break
if flip_index == -1:
on_left = True
else:
pancakes = flipped_some(pancakes, size, flip_index, on_left)
on_left = True
flips+=1
if pancakes in flip_history:
return 'IMPOSSIBLE'
else:
flip_history.add(pancakes)
return flips
def flipped_some(to_flip:str, size: int, index: int, left: bool) -> str:
if left:
if index + size - 1 >= len(to_flip):
return to_flip
else:
return_str = to_flip[:index]
for i in range(index, index + size, 1):
if to_flip[i] == '+':
return_str += '-'
elif to_flip[i] == '-':
return_str += '+'
return_str += to_flip[index + size:]
else:
if index - size + 1 <= 0:
return to_flip
else:
return_str = to_flip[:index - size + 1]
for i in range(index-size + 1, index + 1, 1):
if to_flip[i] == '+':
return_str += '-'
elif to_flip[i] == '-':
return_str += '+'
return_str += to_flip[index + 1:]
return return_str
flip_shit(open('A-large.in', 'r')) |
604975b34d28c5915cffcc26899f90a98f76c876 | nithyaah16/KATTIS-PROBLEMS | /Sort_of_Sorting.py | 441 | 3.65625 | 4 | state = True
while state==True:
n=int(input())
dic={}
if n != 0:
for i in range(n):
x=input()
if x[0:2] not in dic:
dic[x[0:2]]=[]
dic[x[0:2]].append(x)
else:
dic[x[0:2]].append(x)
dic1=sorted(dic)
for k in dic1:
for words in dic[k]:
print(words)
print("\n")
else:
break
|
bc76ad80a00172ae50b29d2cdcdc09a2eec9a724 | Gingertonic/python-for-rubyists | /oo/oo.py | 824 | 3.796875 | 4 | class Language:
_all = []
def __init__(self, name, eng_name):
self.name = name
self.in_english = eng_name
self.words = {}
self._save()
def _save(self):
self._all.append(self)
def add_word(self, english, translation):
self.words[english] = translation
def _translate(self, word):
return self.words[word]
def how_do_you_say(self, word):
print(f"In {self.name}, '{word}' is '{self._translate(word)}'.")
@classmethod
def print_all(cls):
print("We have the following languages:")
for lang in cls._all:
print(lang.name)
spanish = Language("Español", "Spanish")
german = Language("Deutsch", "German")
spanish.add_word("Hello", "Hola")
spanish.how_do_you_say("Hello")
Language.print_all() |
904dce6db4488af830518510042332f05f9bc3e3 | musram/python_progs | /practice/stack/test_stack.py | 749 | 3.6875 | 4 | from stack import *
def test_stack_push():
animals = Stack()
animals.push("CAT")
assert animals.top.value == "CAT"
animals.push("DOG")
assert animals.top.value == "DOG"
return animals
def test_stack_pop():
animals = test_stack_push()
assert animals.pop() == "DOG"
assert animals.pop() == "CAT"
assert animals.pop() == None
def test_stack_count():
animals = Stack()
animals.push("CAT")
animals.push("DOG")
animals.push("RAT")
animals.push("BAT")
assert animals.count() == 4
assert animals.pop() == "BAT"
assert animals.pop() == "RAT"
assert animals.count() == 2
if __name__ == "__main__":
test_stack_push()
test_stack_pop()
test_stack_count()
|
ea3ab3f3ad8598072df9676ec58a3230a39989f8 | sashakrasnov/datacamp | /26-manipulating-time-series-data-in-python/1-working-with-time-series-in-pandas/01-your-first-time-series.py | 1,006 | 4.875 | 5 | '''
Your first time series
You have learned in the video how to create a sequence of dates using pd.date_range(). You have also seen that each date in the resulting pd.DatetimeIndex is a pd.Timestamp with various attributes that you can access to obtain information about the date.
Now, you'll create a week of data, iterate over the result, and obtain the dayofweek and weekday_name for each date.
'''
import pandas as pd
'''
INSTRUCTIONS
We have already imported pandas as pd for you.
* Use pd.date_range to create seven dates starting from '2017-1-1' at (default) daily frequency. Use the arguments start and periods. Assign the result to seven_days.
* Iterate over each date in seven_days and in each iteration, print the .dayofweek and .weekday_name attributes.
'''
# Create the range of dates here
seven_days = pd.date_range(start='2017-1-1', periods=7)
# Iterate over the dates and print the number and name of the weekday
for day in seven_days:
print(day.dayofweek, day.day_name())
|
2313efd48b20a624818369b8f9fe8c6bb9880570 | 2709-devansh/Number-Guessing-Game | /guessingGame.py | 1,480 | 4.15625 | 4 | import random
number = random.randint(1,9)
chances = 0
while chances < 5:
guess1 = int(input("Enter Your Guess:"))
if guess1 == number:
print("Outstanding, You guessed the number in the 1st Chance")
chances = chances + 1
break
else:
print("Oh! you missed but don't worry you still have four more guesses")
guess2 = int(input("Enter Your Guess:"))
if guess2 == number:
print("Excellent, You guessed the number in the 2nd Chance")
chances = chances + 1
break
else:
print("Oh! you missed but don't worry you still have three more guesses")
guess3 = int(input("Enter Your Guess:"))
if guess3 == number:
print("Very Good, You guessed the number in the 3rd Chance")
chances = chances + 1
break
else:
print("Oh! you missed but don't worry you still have two more guesses")
guess4 = int(input("Enter Your Guess:"))
if guess4 == number:
print("Good, You guessed the number in the 4th Chance")
chances = chances + 1
break
else:
print("Oh! you missed, now you have your last chance")
guess5 = int(input("Enter Your Guess:"))
if guess5 == number:
print("Well, You finally guessed the number")
chances = chances + 1
break
else:
print("OH!! You lost, better luck next time and the number is, ", number)
break
|
7d65c12d474b5ca1432cc36e9ce52eeece5f1c55 | xKuroiUsagix/python-online-marathon | /sprint01/question03.py | 443 | 3.859375 | 4 | def isPalindromeNew(word: str) -> bool:
letters = set(word)
is_only_one = False
if len(word) % 2 == 0:
for i in letters:
if word.count(i) % 2 != 0:
return False
else:
for i in letters:
if word.count(i) % 2 != 0 and not is_only_one:
is_only_one = True
elif word.count(i) % 2 != 0 and is_only_one:
return False
return True
|
94bf0a3465387cc987600b5fbbcf17b0ae069955 | BenTildark/sprockets-d | /DTEC501-Lab5-1/lab5-1-q5.py | 1,319 | 4.28125 | 4 | """
Write a program which asks the user to enter their first name and start and stop(end) values for the loop.
The start value can be greater than or less than the end value.
The program should display
Please enter your first name:
followed by
Hi <FirstName>, please enter the start value:
Thank you <FirstName>, please enter the end value:
Use a for loop to count from the start to the end.
Display the following each time you go around the loop
Line x
where x is the loop counter.
Example
Please enter your first name: dave
Hi Dave, please enter the start value: 1
Thank you Dave, please enter the end value: 5
Line 1
Line 2
Line 3
Line 4
Line 5
"""
# The lines of text you need to use to generate the output are given below for you. Do not alter anything inside the quotes.
# "Please enter your first name: "
# "Hi {}, please enter the start value: "
# "Thank you {}, please enter the end value: "
# "Line {}"
first_name = input("Please enter your first name: ").capitalize()
first_value = int(input("Hi {}, please enter the start value: ".format(first_name)))
second_value = int(input("Thank you {}, please enter the end value: ".format(first_name)))
start = first_value
end = second_value
user_range_count = range(start, end+1)
for count in user_range_count:
print("Line {}".format(count))
|
a94d33802c84144e8ad72b8283e6f2c80d49e1a0 | nonas-hunter/warmup_project | /warmup_project/scripts/finite_state_machine.py | 9,314 | 3.53125 | 4 | #!/usr/bin/env python3
""" This code implements the finite state controller described in https://comprobo20.github.io/in-class/day05.
In this version we will use the ROS smach library
There are three states: moving forward, moving backward, and turning left. The initial state is moving_forward.
The rules for transitioning between these states are as follows.
moving_forward:
- if a bump sensor is activated transition to moving backward
moving_backward:
- once the obstacle in front of the robot is greater than a threshold, transition to turning left
turning_left:
- once 1 second has elapsed, transition to moving_forward
"""
import rospy
import smach
# try using smach viewer as your own risk
# import smach_ros
from geometry_msgs.msg import Twist, Point, Pose, PoseWithCovariance, Twist, Vector3, Quaternion
from tf.transformations import euler_from_quaternion
from std_msgs.msg import Int8MultiArray
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry
import math
class FSM_SQUARE_FOLLOW():
""" This class encompasses the finite state controller ROS Node"""
def __init__(self):
rospy.init_node('square_follow')
# the angular velocity when in the "turning_left" state
# self.angular_velocity = 0.5
# the forward speed when in the "moving_forward" state. The speed is reversed in the "moving_backward" state.
# self.forward_speed = 0.1
# the distance threshold to use to transition from "moving_backward" to turning left
# self.distance_threshold = 0.8
self.vel_pub = rospy.Publisher("cmd_vel", Twist, queue_size=10)
def run(self):
# needed in the case where you send the velocity commands once (in some ways sending the commands repeatedly is
# more robust.
rospy.sleep(1)
# Create a SMACH state machine
sm = smach.StateMachine(outcomes=[])
# Open the container
with sm:
# Add states to the container
smach.StateMachine.add('square_driver', SQUARE_DRIVER(),
transitions={'detected object': 'person_follow'})
smach.StateMachine.add('person_follow', PERSON_FOLLOW(),
transitions={'follow object lost': 'square_driver'})
# Create and start the introspection server
# if you want to try smach viewer, consider uncommenting these lines
# sis = smach_ros.IntrospectionServer('server_name', sm, '/SM_ROOT')
# sis.start()
# Execute SMACH plan
outcome = sm.execute()
class SQUARE_DRIVER(smach.State):
""" Implements the square driver state. """
def __init__(self):
self.subscriber = rospy.Subscriber('/odom', Odometry, self.odom_process)
self.publisher = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
self.laser_scan = rospy.Subscriber('/scan', LaserScan, self.analyze_scan)
smach.State.__init__(self, outcomes=['detected object'])
self.scan_data = []
self.linear_velocity = 0.3
self.angular_velocity = 0.3
self.x = 0
self.y = 0
self.z = 0
self.w = 0
self.z_orientation = 0
self.x_coord = 0
self.y_coord = 0
self.x_dist = 0
self.y_dist = 0
self.message = 0
self.square_completed = False
def analyze_scan(self, msg):
self.scan_data = msg.ranges
def odom_process(self, msg):
self.message = msg
self.x = msg.pose.pose.orientation.x
self.y = msg.pose.pose.orientation.y
self.z = msg.pose.pose.orientation.z
self.w = msg.pose.pose.orientation.w
angles_euler = euler_from_quaternion([self.x,self.y,self.z,self.w], 'sxyz')
self.z_orientation = math.degrees(angles_euler[2])
self.x_coord = msg.pose.pose.position.x
self.y_coord = msg.pose.pose.position.y
# print("X position: " + str(self.x_coord))
# print("Y position: " + str(self.y_coord))
# print("Roll: " + str(self.z_orientation))
def check_square(self):
if(0.95<= self.x_coord <= 1.05 and self.x_dist == 0):
self.publisher.publish(Twist(angular=Vector3(z=self.angular_velocity)))
while(True):
if(90 <= self.z_orientation <= 180):
self.x_dist = 1
break
self.publisher.publish(Twist(angular=Vector3(z=0.0)))
if(0.95<= self.y_coord <= 1.05 and self.y_dist == 0):
self.publisher.publish(Twist(angular=Vector3(z=self.angular_velocity)))
while(True):
if(-180 <= self.z_orientation <= -90):
self.y_dist = 1
break
self.publisher.publish(Twist(angular=Vector3(z=0.0)))
if(-0.05 <= self.x_coord <= 0.02 and self.x_dist == 1):
self.publisher.publish(Twist(angular=Vector3(z=self.angular_velocity)))
while(True):
if(-90 <= self.z_orientation <= 0):
self.x_dist = 2
break
self.publisher.publish(Twist(angular=Vector3(z=0.0)))
if(-0.05 <= self.y_coord <= 0.02 and self.y_dist == 1):
self.publisher.publish(Twist(angular=Vector3(z=self.angular_velocity)))
while(True):
if(0<= self.z_orientation <= 90):
self.x_dist = 2
break
self.publisher.publish(Twist(angular=Vector3(z=0.0)))
self.square_completed = True
def no_object(self, data):
count = 0
for i in range(len(data) - 1):
if(data[i] == math.inf):
count += 1
if(count == 360):
return True
print("no object")
return False
def execute(self, user_data):
r = rospy.Rate(10)
while not rospy.is_shutdown():
if(self.square_completed == False):
self.publisher.publish(Twist(linear=Vector3(x= self.linear_velocity)))
self.check_square()
if(self.no_object(self.scan_data) == False):
# print("detected object")
return 'detected object'
r.sleep()
class PERSON_FOLLOW(smach.State):
""" Implements the moving backward state. """
def __init__(self):
rospy.Subscriber('/scan', LaserScan, self.analyze_scan)
self.publisher = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
self.follow_object = {"cm":0, "dist":0}
self.scan_data = []
self.p0 = 180
self.target_dist = 1.5
self.CM_GAIN = 2
self.APPROACH_GAIN = 1
smach.State.__init__(self, outcomes=['follow object lost'])
def analyze_scan(self, msg):
self.scan_data = msg.ranges
scan = msg.ranges
self.follow_object["dist"] = min(scan)
min_index = scan.index(self.follow_object["dist"])
self.follow_object["cm"] = self.find_cm(scan, min_index)
def find_cm(self, scan, index_original):
step_lower = 0
step_upper = 0
while scan[self.loop_around(index_original + step_lower)] != math.inf:
step_lower -= 1
while scan[self.loop_around(index_original + step_upper)] != math.inf:
step_upper += 1
average = (step_lower + step_upper) / 2
center_mass = self.loop_around(index_original + average)
# print("CM: "+ str(center_mass))
return center_mass
def loop_around(self, num):
return abs(num % 360)
def find_error_cm(self):
cm = self.follow_object["cm"]
error = (self.loop_around((cm + 180))- 180) / 180
print("Error: " + str(error))
return error
def find_error_dist(self):
dist = self.follow_object["dist"]
error = (dist - self.target_dist) / self.target_dist
return error
def controller_output_angular(self, error):
output = error * self.CM_GAIN
print("Controller Output: " + str(output))
return output
def controller_output_linear(self, error):
output = error * self.APPROACH_GAIN
# print("Controller Output: " + str(output))
return output
def no_object(self, data):
count = 0
for i in range(len(data) - 1):
if(data[i] == math.inf):
count += 1
if(count == 360):
return True
print("no object")
return False
def execute(self, user_data):
r = rospy.Rate(5)
while not rospy.is_shutdown():
error_angular = self.find_error_cm()
error_linear = self.find_error_dist()
angular_speed = self.controller_output_angular(error_angular)
linear_speed = self.controller_output_linear(error_linear)
self.publisher.publish(Twist(linear=Vector3(x=linear_speed), \
angular=Vector3(z=angular_speed)))
if(self.no_object(self.scan_data) == True):
# print("follow object lost")
return 'follow object lost'
r.sleep()
if __name__ == '__main__':
node = FSM_SQUARE_FOLLOW()
node.run() |
fc872ec9dfaff8309d28fe326ea01ced8a4518d5 | vivekaxl/LexisNexis | /ExtractFeatures/Data/kracekumar/alphabet_soup.py | 766 | 4 | 4 | T = int(raw_input())
def count_hackercup(sentence):
len_of_sentence = len(sentence)
# Remove all the not required letters from the sentence
eligible_letters = ""
for char in sentence:
if char in "HACKERCUP":
eligible_letters += char
max_words = len(eligible_letters)/len("HACKERCUP")
list_of_max_words = [list("HACKERCUP") for i in range(max_words)]
for char in eligible_letters:
for word_list in list_of_max_words:
if char in word_list:
word_list.remove(char)
break
return max_words - len(filter(None,list_of_max_words))
for tc in range(T):
test_sentence = raw_input()
result = count_hackercup(test_sentence)
print 'Case #%d: %d' % (tc+1, result)
|
a8e369e9631e0237cd88141f80a9098d1717efaf | goateater/MyCode | /python_refresher/python_numbers.py | 308 | 4 | 4 | #!/usr/bin/env python
x = 1
y = 1.234
z = True
print(x)
print(y)
print(z)
x = 3
y = 8
sum = x + y
print(sum)
# Python 3
x = int(input("Enter x: "))
y = int(input("Enter y: "))
sum = x + y
print(sum)
# Python 2
x = int(raw_input("Enter x: "))
y = int(raw_input("Enter y: "))
sum = x + y
print(sum)
|
8731645e9f23d05d0adc162af36559111b41cb2a | NishanthMHegde/NumpyPractice | /MatrixMultiplication.py | 281 | 4.09375 | 4 | import numpy as np
#For matrix multiplication, the number of columns of first array must be equal to number of rows of second array
A = np.matrix([2,4,5,14,16,21]).reshape(2,3)
B = np.matrix([5,-10,15,24,31,-4]).reshape(3,2)
print(A)
print(B)
print(A*B)
print(np.matmul(A, B))
|
d6c4d5350ed627f8f4c5f5b16446d4ac0eeb8388 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2673/60898/317215.py | 228 | 3.671875 | 4 | t=eval(input())
x=eval(input())
if x==4:
y=eval(input())
if y==15:
print(7)
print(10)
else:
print(7)
print(1)
elif x==5:
print(6)
print(1)
elif x==6:
print(4)
print(2)
|
85a4859318af1484646e16a61c564baad5f77fe7 | milindmalkani1/keyValueDataStore | /main.py | 4,718 | 3.5 | 4 | import threading
import json
import os
import time
'''
search for a particular key in the file and converts the entire file
in a python dict obj, will also be use-full
during the reading of a particular key and checking if a key
is present inside the dictionary or not
'''
def searchKey(keyForSearching, givenPathS):
d = {}
with open(os.path.join(givenPathS, 'test.txt'), 'r') as fp:
for line in fp:
splitTimeKey = line.split(":") # splitting the line with (key,value) and (time)
splitKeyValue = splitTimeKey[0].split("-") # splitting the line with (key) and (value)
(key, val, givenTime) = splitKeyValue[0], splitKeyValue[1], splitTimeKey[1] # storing temp in a tuple
d[key] = val, givenTime # storing in the dictionary
if keyForSearching in d:
global value # global variable to get the value so that we can use this further while reading/del in the file
value = d[keyForSearching][0]
global timeValue # to get the time value associated with the key to use while reading/deleting
timeValue = float(d[keyForSearching][1])
return True
else:
return False
'''
create function takes the given path and an optional
time to live value for the key
'''
def create(givenPath, lck, ttl=0):
lck.acquire()
key = input("Enter the key to be inserted: ")
if searchKey(key, givenPath):
print("Error:Key is already present in the file.")
else:
jsonValue = input("Enter the value to the corresponding key: ")
# deserializedJson = json.load(jsonValue)
fileStats = os.stat(os.path.join(givenPath, 'test.txt')) # getting the fileStats
fileSize = fileStats.st_size # getting the file size
if len(key) > 32 or len(jsonValue) > 16 * 1024: # checking if the len of the key > 32 chars/JSON Value > 16KB
print("Error:Invalid input format of key and value.")
elif fileSize > 1024 * 1024 * 1024: # if anytime the size of the file exceeds 1GB
print("Error:File Size has exceeded more than a GB cannot enter more.")
else:
with open(os.path.join(givenPath, 'test.txt'), 'a+') as fp: # writing given key value to the file
internalFileSize = os.path.getsize(os.path.join(givenPath, 'test.txt'))
if internalFileSize > 0:
fp.write("\n")
if ttl == 0:
fp.write(key + "-" + jsonValue + ":" + str(ttl))
else:
fp.write(key + "-" + jsonValue + ":" + str(time.time() + ttl))
lck.release()
'''
read function will take the given path of the file
and reads the inputted key and returns the corresponding value
'''
def read(givenPath, lck):
lck.acquire()
key = input("Enter the key of which corresponding value you want to read: ")
if searchKey(key, givenPath):
if timeValue != 0 and time.time() > timeValue:
print("Error:Time to live value of the key has expired.")
else:
json.dumps(value) # for the serialization of the python object
print("The value is: " + value)
else:
print("Error:Key is not preset in the file.")
lck.release()
'''
delete the given key vale pair from the file
this function will take the given path as ip
'''
def delete(givenPath, lck):
lck.acquire()
key = input("Enter the key whose key value pair you want to delete: ")
if searchKey(key, givenPath):
if timeValue != 0 and time.time() > timeValue:
print("Error:Time to live value of the key has expired.")
else:
with open(os.path.join(givenPath, 'test.txt'), 'r') as fp:
data = fp.readlines()
with open(os.path.join(givenPath, 'test.txt'), 'w') as fp:
for line in data:
if not (line.startswith(key)):
fp.write(line)
else:
print("Error:Key is not present in the file.")
lck.release()
if __name__ == '__main__':
lock = threading.Lock()
path = input('Enter the path of the file: ')
if path:
file = open(os.path.join(path, 'test.txt'), 'a')
file.close()
else:
file = open('test.txt', 'a')
file.close()
# threads = []
# for i in range(0, 50):
# ar = (givenPath, lck, ttl)
# t = threading.Thread(target=create, args=ar)
# threads.append(t)
# t.start()
#
# for t in threads:
# t.join()
# usage of different functionalities calling respective functions with the path and lock as arguments
create(path, lock)
read(path, lock)
delete(path, lock)
|
0394aef6837b864a5adafdf239a6afe3fa5b7853 | santakung-07/CP3-Thanayos-Thongsrinuch | /assignment/Exercise5_1_Thanayos_T.py | 477 | 4.125 | 4 | # exercise 5_1 +, -, *, / เลข 2 จำนวนโดยยรับ input
print("Calculated 2 number\n","Results will be shown as +, -, *, / respectively")
firstNum = int(input("First number: "))
secondNum = int(input("Second number: "))
print(f"{firstNum} + {secondNum} = {firstNum+secondNum}")
print(f"{firstNum} - {secondNum} = {firstNum-secondNum}")
print(f"{firstNum} * {secondNum} = {firstNum*secondNum}")
print(f"{firstNum} / {secondNum} = {firstNum/secondNum}")
|
fd88b03721658283a87f128bcdf782b9526afd9f | Chebroluntihin/pythontrng | /ifcond.py | 165 | 3.90625 | 4 | x=(int(input("Enter an integer")))
y=(int(input("Enter an integer")))
if(x>y):
sum=x+y
print(sum)
elif(x<y):
sub=x-y
print(sub)
else:
print("No") |
4c7572e0124f0ccddae590893ca97f81a82fbd45 | chiheblahouli/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 216 | 3.796875 | 4 | #!/usr/bin/python3
"""
function that return true if object is exactly
"""
def is_same_class(obj, a_class):
"""return true if obj is the exact class a_class, otherwise false"""
return (type(obj) == a_class)
|
6d0702099e71e5065cc3a1bdfeb152995fccdc81 | loki2236/Python-Practice | /src/Ej2.py | 439 | 3.71875 | 4 | #
# Dada una terna de números naturales que representan al día, al mes y al año de una determinada fecha
# Informarla como un solo número natural de 8 dígitoscon la forma(AAAAMMDD).
#
dd = int(input("Ingrese el dia (2 digitos): "))
mm = int(input("Ingrese el mes (2 digitos): "))
yyyy = int(input("Ingrese el año (4 digitos): "))
intdate = (yyyy*10000) + (mm*100) + dd
print("La fecha en formato entero es: ", intdate)
|
aba3dae2e5040c814cbc961753594b28e5100826 | Jamaliela/Modules | /a06_genes_solved.py | 6,423 | 3.84375 | 4 | ######################################################################
# Author: Scott Heggen & Emily Lovell TODO: Change this to your names
# Username: heggens & lovelle TODO: Change this to your usernames
#
# Assignment: A06: It's in your Genes
#
# Purpose: Determine an amino acid sequence given an input DNA sequence
#
######################################################################
# Acknowledgements:
# Original Author: Dr. Jan Pearce
#
# Idea from: http://www.cs.uni.edu/~schafer/1140/assignments/pa9/index.htm
#
# licensed under a Creative Commons
# Attribution-Noncommercial-Share Alike 3.0 United States License.
####################################################################################
def is_nucleotide(sequence):
"""
Checks that the string sequence provided is a valid string
consisting only of the 4 nucleotides A, C, G, and T
Returns True if so, and False otherwise
:param sequence: a DNA sequence
:return: A boolean value indicating if the sequence is valid
"""
valid_string = ["A", "C", "G", "T"]
for letter in sequence:
if letter not in valid_string:
return False
return True
def complement_strand(sequence):
"""
Returns the string which will be the second strand of the DNA sequence
given that Ts complement As, and Cs complement Gs. If given
a bad input, the function returns "Sequencing Error"
:param sequence: A DNA sequence
:return: the complement string for the DNA sequence
"""
complement = "" # This can be used to "build" the complement
letter_dictionary = {"A": "T", "C": "G", "T": "A", "G": "C"}
for letter in sequence:
if letter in letter_dictionary:
complement += letter_dictionary[letter]
else:
return "Sequencing Error"
return complement
def mRNA(sequence):
"""
Replaces each occurrence of the nucleotide T replaced with the nucleotide U.
:param sequence: the DNA sequence
:return: The same sequence with T's replaced by U's
"""
mrna = ""
for letter in sequence:
if letter == "T":
mrna += "U"
else:
mrna += letter
return mrna
def chunk_amino_acid(sequence):
"""
Uses output of mRNA(sequence) and divides it into substrings of length 3,
ignoring any "extra DNA" at the far end returning the relevant substrings in a list.
:param sequence: the DNA sequence
:return: A list where each element is a set of three DNA values
"""
list_of_chunks = []
for i in range(len(sequence)//3):
list_of_chunks.append(sequence[i*3:i*3+3])
return list_of_chunks
def amino_acid_chunks(threecharseq):
"""
Expects a three character string as a parameter and returns
the corresponding single character AminoAcid
:param threecharseq: a sequence of three characters
:return: A string representing the animo acid chunk for that sequence
"""
###################################################################
# This function was already completed correctly! No changes needed!
###################################################################
# We haven't learned about dictionaries yet, but here is one for the extra curious.
# You aren't expected to know what this is yet.
translator = {"GCA": "A", "GCC": "A", "GCG": "A", "GCU": "A",
"AGA": "R", "AGG": "R", "CGA": "R", "CGC": "R", "CGG": "R", "CGU": "R",
"GAC": "D", "GAU": "D",
"AAC": "N", "AAU": "N",
"UGC": "C", "UGU": "C",
"GAA": "E", "GAG": "E",
"CAA": "Q", "CAG": "Q",
"GGA": "G", "GGC": "G", "GGU": "G", "GGG": "G",
"CAC": "H", "CAU": "H",
"AUA": "I", "AUC": "I", "AUU": "I",
"UUA": "L", "UUG": "L", "CUA": "L", "CUC": "L", "CUG": "L", "CUU": "L",
"AAA": "K", "AAG": "K",
"AUG": "M",
"UUC": "F", "UUU": "F",
"CCA": "P", "CCC": "P", "CCG": "P", "CCU": "P",
"AGC": "S", "AGU": "S", "UCA": "S", "UCC": "S", "UCG": "S", "UCU": "S",
"ACA": "T", "ACC": "T", "ACG": "T", "ACU": "T",
"UGG": "W",
"UAC": "Y", "UAU": "Y",
"GUA": "V", "GUC": "V", "GUG": "V", "GUU": "V",
"UAA": "*", "UAG": "*", "UGA": "*"}
if threecharseq in translator.keys():
return translator[threecharseq] # Given any 3 letter sequence, this returns the amino acid for that sequence
else:
return "?" # Returns a question mark if the input is invalid
def sequence_gene(sequence):
"""
The sequence_gene() function takes a a sequence of nucleotides:
A, C, G, and T and returns
the corresponding amino acid sequence.
:param sequence: a string representing a sequence of nucleotides
:return: a string representing the amino acid sequence
"""
###################################################################
# This function was already completed correctly! No changes needed!
###################################################################
aaseq = "" # Amino acid sequence
if is_nucleotide(sequence): # Checks for a valid sequence
comp_strand = complement_strand(sequence) # Finds the complement sequence
mrna = mRNA(comp_strand) # Finds the mRNA of the complement
amino_acid_list = chunk_amino_acid(mrna) # Chunks the mRNA sequence
for amino_acid in amino_acid_list: # Loops through each chunk
aaseq = aaseq + amino_acid_chunks(amino_acid) # Creates the final amino acid sequence
return aaseq # Returns an empty string for any illegal input
def main():
"""
The main() function call which prints the resulting amino acid sequence given a DNA sequence
:return: None
"""
sequence = input("Please enter a valid gene sequence to convert to an amino acid: \n")
print("The input sequence {0} produces the amino acid {1}".format(sequence, sequence_gene(sequence)))
if __name__ == "__main__":
main()
|
1689d15d28983b199d27b49a6b0ca346b148322c | ouoam/CE_Data-Structures | /02.Stack/lab3.py | 1,957 | 4 | 4 | class Stack:
maxSize = 4
def __init__(self):
self.item = []
def push(self, i):
if not self.isFull():
self.item.append(i)
return True
else:
return False
def size(self):
return len(self.item)
def isEmpty(self):
return self.size() == 0
def pop(self):
out = self.peek()
if out != None:
self.item.pop()
return out
def peek(self):
if self.isEmpty():
return None
else:
out = self.item[-1]
return out
def isFull(self):
return self.size() >= self.maxSize
def left(self):
return self.maxSize - self.size()
main = Stack()
temp = Stack()
def depart(carNo):
if main.isEmpty():
print("car", carNo, "cannot depart: soi empty")
return False
elif not carNo in main.item:
print("car", carNo, "cannot depart: No car", carNo)
return False
else:
op = []
print("car", carNo, "depart :")
while main.peek() != carNo:
op.append("pop " + str(main.peek()))
temp.push(main.pop())
op.append("pop " + str(main.peek()))
main.pop()
while not temp.isEmpty():
op.append("push " + str(temp.peek()))
main.push(temp.pop())
print("\t" + ", ".join(op))
print("\tspace left", main.left())
return True
def arrive(carNo):
if not main.isFull():
main.push(carNo)
print("car", carNo, "arrive\t\tspace left", main.left())
return True
else:
print("car", carNo, "cannot arrive : SOI FULL")
return False
def printSoi():
print("print soi =", main.item)
depart(6)
arrive(1)
arrive(2)
arrive(3)
arrive(4)
arrive(5)
printSoi()
depart(7)
depart(2)
printSoi()
depart(1)
depart(4)
printSoi()
depart(9)
depart(2)
depart(3)
printSoi()
arrive(5)
arrive(6) |
5314782f3426695be56e9c0b7b15b94860aaeddc | shreeyamaharjan/AssignmentIII | /A_d.py | 927 | 4.15625 | 4 | def mergeSort(nums):
if n > 1:
mid = n // 2
left_list = nums[:mid]
right_list = nums[mid:]
mergeSort(left_list)
mergeSort(right_list)
i = j = k = 0
while i < len(left_list) and j < len(right_list):
if left_list[i] < right_list[j]:
nums[k] = left_list[i]
i += 1
k += 1
else:
nums[k] = right_list[j]
j += 1
k += 1
while i < len(left_list):
nums[k] = left_list[i]
i += 1
k += 1
while j < len(right_list):
nums[k] = right_list[j]
j += 1
k += 1
lst = []
n = int(int(input("Enter the size of the list : ")))
for i in range(n):
x = int(input())
lst.append(x)
print("The unsorted list is : \n", lst)
mergeSort(lst)
print("The sorted list is :\n ", lst)
|
345343ab5066a28d1d5609ec9d7da58e3fd2d1c1 | okinawaa/Python_basic | /Python_basic/For_one_sentence.py | 431 | 4.03125 | 4 |
#example 1
# students = [5,6,7,8,9]
# print(type(students))
# students = [i+100 for i in students] < ---------
# print(students)
#example 2 :
# students = ["Iron man" , "Thor" , "I am Groot"]
# students = [len(i) for i in students] < ------------
# print(students)
#exmaple 3:
students = ["Iron man" , "Thor" , "I am Groot"]
students = [i.upper() for i in students]
print(students) |
a90aac1fa5632b5f52782329180f88b4a37257d8 | liujigang82/ContainerNum | /textProcessing.py | 3,338 | 3.5625 | 4 | from utils import get_encode_code
global str
# calculate the confidence of the string to be container number. 4 letter + 7 digits
def str_confidence(input_str):
str_list = input_str.split(" ")
numbers = 0
words = 0
for item in str_list:
if len(item) == 4 and item[len(item)-1].lower() == "u":
return 0
numbers = sum(c.isdigit() for c in item) if sum(c.isdigit() for c in item)>numbers else numbers
words = sum(c.isalpha() for c in item) if sum(c.isalpha() for c in item) > words else words
return abs(4-words) + abs(7-numbers)
# check if str is all letters
def isAlpha(input_str):
words = sum(c.isalpha() for c in input_str)
number = sum(c.isdigit() for c in input_str)
if words >= number:
return True
else:
return False
def containDigAlph(input_str):
for i in range(len(input_str)):
if input_str[i].isdigit() or input_str[i].isalpha():
return True
return False
def find_index_word(input_str):
word = ""
digits = ""
sub_str_list = input_str.split(" ")
sub_str_list = [item for item in sub_str_list if item is not ""]
for sub in sub_str_list:
if isAlpha(sub) and len(sub)>=2:
word = sub
if word == "":
return "", input_str
index_sub = sub_str_list.index(word)
if len(word) == 4:
digits = " ".join(sub_str_list[index_sub + 1:len(sub_str_list)])
elif len(word) < 4 and index_sub > 0 and len(word) + len(sub_str_list[index_sub - 1]) <= 4:
word = " ".join(sub_str_list[index_sub-1 : index_sub])
digits = " ".join(sub_str_list[index_sub +1 :len(sub_str_list)])
return word, digits
def find_character_index(input_str, character):
return [ a for a in range(len(input_str)) if input_str[a] == character]
def result_refine(input_str):
for char in input_str:
if not char.isdigit() and not char.isalpha() and not char.isspace():
input_str = input_str.replace(char, "")
text, digits_list = find_index_word(input_str)
result_str = text + " " + digits_list
return result_str
def final_refine(input_str):
sub_str_list = input_str.split(" ")
sub_str_list = [item for item in sub_str_list if item is not ""]
if len(sub_str_list) <= 0:
return input_str
if isAlpha(sub_str_list[0]) and len(sub_str_list[0]) == 4:
last_char = sub_str_list[0][len(sub_str_list[0])-1].lower()
if last_char is not "u":
if last_char == "y" or last_char == "v":
tmp = sub_str_list[0][0:len(sub_str_list[0])-1]
sub_str_list[0] = tmp + "U"
if "0" in sub_str_list[0]:
sub_str_list[0] = sub_str_list[0].replace("0", "O")
else:
return input_str
tmp_text = "".join(sub_str_list[0 :len(sub_str_list)])
if len(tmp_text) == 11:
code = get_encode_code(tmp_text)
if tmp_text[len(tmp_text) - 1] == str(code):
tmp_text = " ".join(sub_str_list[0:len(sub_str_list)])
else:
str_list = list(tmp_text)
str_list[len(tmp_text) - 1] = str(code)
tmp_text = "".join(str_list)
elif len(tmp_text) == 10:
code = get_encode_code(tmp_text)
code_text = str(code)
tmp_text = tmp_text + code_text
return tmp_text
|
56b53c6b4461a62ce27db79f17b68a3c3c7fcc1e | bovenson/notes | /Coding/Algorithm/Code/LeetCode/Python/0000-0050/0018.py | 1,864 | 3.8125 | 4 | #!/bin/python3
# coding: utf-8
"""
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
"""
__author__ = "bovenson"
__email__ = "szhkai@qq.com"
__date__ = "2017-11-08 18:38"
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
_nums = sorted(nums)
_len = len(_nums)
_res = []
for i in range(_len-3):
if i > 0 and _nums[i] == _nums[i-1]:
continue
for j in range(i+1, _len-2):
if j > i + 1 and _nums[j] == _nums[j-1]:
continue
_target = target - _nums[i] - _nums[j]
_l = j + 1
_r = _len - 1
while _l < _r:
_sum = _nums[_l] + _nums[_r]
# print(i, j, _l, _r)
# print(_target, _sum)
if _sum < _target or (_l > j+1 and _nums[_l] == _nums[_l-1]):
_l += 1
elif _sum > _target or (_r < _len-1 and _nums[_r] == _nums[_r+1]):
_r -= 1
else:
# print(_target, _sum)
_res.append([_nums[i], _nums[j], _nums[_l], _nums[_r]])
_r -= 1
_l += 1
return _res
if __name__ == "__main__":
print(Solution().fourSum([1, 0, -1, 0, -2, 2], 0))
print(Solution().fourSum([0, 0, 0, 0], 0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.