blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
630afbcab875ba20023877706a42d4e70fd09315
|
nileshhadalgi016/python3
|
/For loop in python.py
| 834
| 4.25
| 4
|
"""
Python For Loops
- Techie Programmer
A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
"""
# Looping Through a String
for x in "banana":
print(x)
# The break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
# The continue Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
# The range() Function
for x in range(1,6,2):
print(x)
# Else in For Loop
for x in range(6):
print(x)
else:
print("Finally finished!")
# Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
# The pass Statement
for x in [0, 1, 2]:
pass
| true
|
25b76979d4c22ea67555610bb4f64dc8f713d8f8
|
Sevansu/Python-Tasks-Basic-to-Advance
|
/Task 2/task_2_01_A.py
| 1,151
| 4.15625
| 4
|
#1. Create two python files. say 'task_2_01_A.py' and 'task_2_01_B.py'. Create a class in the 'task_2_01_A.py' having some attributes and functions and constructor defined in the class. Create a method outside that class in the file 'task_2_01_A.py'. Use that class and its attributes and mehtods and the method that is defined outside the class in the file 'task_2_01_B.py'.
class SimpleInterest:
#variables
m = ""
p = 0
r = 0
t = 0
#constructor
def __init__(self, Message, PrincipleAmount, RateOfInterest, Time):
self.m = Message
self.p = PrincipleAmount
self.r = RateOfInterest
self.t = Time
#class methods
def showMessage(self):
print(self.m)
def InterestGenerator(self):
x = (self.p*self.r*self.t)/100
print(x)
person1 = SimpleInterest(Message="seva", PrincipleAmount=60000, RateOfInterest=2, Time=2)
person2 = SimpleInterest(Message="nsu", PrincipleAmount=100000, RateOfInterest=3, Time=5)
person1.showMessage()
person1.InterestGenerator()
person2.showMessage()
person2.InterestGenerator()
| true
|
6d3bbf1614e30f76dcbe63a9091b78e635e6fbc3
|
AlexPolGit/Python-Projects
|
/strings_test.py
| 623
| 4.5625
| 5
|
#strings_test.py
#Testing out string functions Python
string = "python is a programming language"
print "\nOriginal string:"
print string
print "\nAs a sentence:"
print string.capitalize() + "!"
print "\nLength of string:"
print len(string)
print "\nNumber of g's: "
print string.count("g")
print "\nIs alphabetic? Is numeric? Is alphanumeric?"
print string.isalpha(), string.isdigit(), string.isalnum()
print "\nUppercase all:"
print string.upper()
print "\nTitle-cased:"
print string.title()
print "\nBack to lower:"
print string.lower()
print "\nSplit into words:"
for word in string.split(" "):
print word
| true
|
015964ff2101192be30278b7e38b9e8e6254c937
|
kulvirvirk/Python_Number
|
/main.py
| 770
| 4.125
| 4
|
#declare some math variables
x = 6
y = 2.2
print('x = 6 \ny = 2.2\n')
#perform some math functions
sum = x + y;
print('sum is: ' + str(sum))
substraciton = x - y
print('difference is: ' + str(substraciton))
multiplication = x * y
print('multiplication is: {:0.2f}'.format( multiplication))
# output is formated
# Where:
# : introduces the format spec
# 0 enables sign-aware zero-padding for numeric types
# .2 sets the precision to 2
# f displays the number as a fixed-point number
division = x/y
print('division is: {:0.2f}'.format(division))
exponent = x**y
print('exponent is: ' + str(exponent))
mod = x%y #remainder
print('remainder is: ' + str(mod))
div = x//y #quotient of a division
print('quotient is: ' + str(div))
print(round(4.5))
print(abs(-20))
| true
|
c23356283979892d890518e937c29992ff6efdde
|
naughtona/COMP10001
|
/Tute-10/fibonacci.py
| 964
| 4.46875
| 4
|
def fibonacci_r(n: int) -> int:
''' uses recursion to calculate fibonacci number
`n`: a non-negative integer
returns: the fibonacci number for `n`
'''
# base case #1
if n == 0:
return 1
# base case # 2
elif n == 1:
return 1
# recursive case
else:
# each `n` is the sum of two preceding ones
return fibonacci_r(n - 1) + fibonacci_r(n - 2)
def fibonacci_i(n: int) -> int:
''' uses iteration to calculate fibonacci number
`n`: a non-negative integer
returns: the fibonacci number for `n`
'''
# fibonacci number accumulator
fib_n = 1
fib_0 = f_two_back = 1
fib_1 = f_one_back = 1
for _ in range(2, n + 1):
# each `n` is the sum of two preceding ones
fib_n = f_one_back + f_two_back
# update `f_one_back` and `f_two_back`
f_one_back, f_two_back = fib_n, f_one_back
return fib_n
| false
|
cfa75fa7477dcd832853b4a34a13d889c8f708ce
|
QLGQ/learning-python
|
/prime.py
| 1,139
| 4.21875
| 4
|
#-*-coding:utf-8-*-
#Set a condition for exiting the loop
def main(maximum=1000):
pr = primes(maximum)
for n in pr:
if n < maximum:
print(n)
else:
break
#Construct a sequence of odd numbers starting from 3
def _odd_iter(maximum):
n = 1
while n < maximum:
n = n + 2
yield n
#Construct a filter function to filter the sequence of previous constructs
#lambda:Anonymous function and The return value is the result of the expression.
def _not_divisible(n):
return lambda x: x % n > 0
#Define a generator, and continue to return to the next prime number
'''
filter: Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
'''
def primes(maximum):
yield 2
it = _odd_iter(maximum)
n = next(it)
yield n
while True:
try:
it = filter(_not_divisible(n), it)
n = it.pop(0)
yield n
except Exception:
break
#invoke function
main(10000)
| true
|
9f580eff78dd811bae154193b94535881327d541
|
PunjabiTadka/FIT1008_Assignment1
|
/29202515_Assessment1/Task4_A.py
| 2,469
| 4.375
| 4
|
"""
@author: Amrita Kaur
@since: 16/3/2018
@modified: 17/3/2018
"""
def populateList(size):
"""
This function takes in the size as an argument,
and accepts 'size' number of inputs from the user, stores them in
a list and returns it
@:param size: The number of inputs to accept from the user
@:return: my_list: The list containing 'size' number of numbers
@pre-condition: -
@post-condition: -
@complexity: Worst-Case: O(n)
@complexity: Best-Case: O(n)
@exeception(raises): -
"""
# Allocate the memory to store the list
my_list = [0] * size
print("Enter the temperatures: ")
for i in range(size):
item = int(input())
my_list[i] = item
return my_list
def bubble_sort(myList):
"""
This function sorts a given list of integers in place
using the bubble sort algorithm
@:param myList: List of numbers to sort
@:return: None
@pre-condition: -
@post-condition: The given list 'myList' is sorted in place
@complexity: Worst-Case: O(n^2)
@complexity: Best-Case: O(n^2)
@exeception(raises): -
"""
size = len(myList)
for i in range(size):
for j in range(0, size-i-1):
if myList[j] > myList[j + 1]:
temp = myList[j]
myList[j] = myList[j+1]
myList[j+1] = temp
return myList
def count(size, myList):
"""
This function counts the frequency of each number in the list and prints it
@:param size: size of the list
@:param myList: The list of numbers
@:return: None
@pre-condition: -
@post-condition: -
@complexity: Worst-Case: O(n^2)
@complexity: Best-Case: O(n^2)
@exeception(raises): -
"""
bubble_sort(myList)
i = 0
while i < size:
count = 0
for j in range(i, size):
if j == size - 1:
count += 1
print(str(myList[i]) + " appears " + str(count) + " times")
i = j
break
if myList[j] == myList[i]:
count += 1
continue
else:
print(str(myList[i]) + " appears " + str(count) + " times")
i = j - 1
break
i += 1
n = int(input("Enter the size of the list: "))
my_list = populateList(n)
count(n, my_list)
| true
|
d629ec1ddb5e77cb43a491ab39e285928d659a23
|
taarunsinggh/class-work
|
/33.py
| 682
| 4.34375
| 4
|
#3-3. Your Own List: Think of your favorite mode of transportation, such as a
#motorcycle or a car, and make a list that stores several examples. Use your list
#to print a series of statements about these items, such as “I would like to own a
#Honda motorcycle.”
transport=['bus','motorcycle','scooter','train','flight']
print("I commute to my work everyday by "+transport[0])
print("Back in India I had a "+transport[1])
print("I also owned a "+transport[2]+" which I found to be more comfortable than the "+ transport[1])
print("In India mostly I travelled by "+transport[3]+" for domestic travel")
print("The "+transport[4] +" that I took to come to USA was 20 hours long")
| true
|
7f579387832a0fe9dc55fdfa1e0651560d3710d7
|
taarunsinggh/class-work
|
/31.py
| 289
| 4.34375
| 4
|
#Names: Store the names of a few of your friends in a list called names. Print
#each person’s name by accessing each element in the list, one at a time.
names=['Vibhor','Deven','Mohit','Rajbeer','Swapnil']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
| true
|
c7a2dd3611c38269715fd6fce7459bb2e6b46e5b
|
daniloiiveroy/MyPythonTraining
|
/02-list_tuple_set/app.py
| 2,989
| 4.125
| 4
|
# from typing_extensions import TypeVarTuple
courses = ["History", "Math", "Physics", "CompSci"]
print(courses) # List
print(courses[2]) # Specific course via index
print(courses[-1]) # Last item
print(courses[0:2]) # List of items
print(courses[2:]) # List of items
# Append function
courses.append("Art I")
print(courses)
# Insert function
courses.insert(1, "Art II")
print(courses)
# Insert List function Adding list
new_courses = ["Computer", "Science"]
courses.insert(-1, new_courses)
print(courses)
# Extend function Adding value at the end
new_courses = ["Filipino", "MAPEH"]
courses.extend(new_courses)
print(courses)
# Remove Function
courses.remove(("Filipino"))
courses.remove(("Art I"))
print(courses)
# Pop Function Removing last value in list
courses.pop()
print(courses.pop())
print(courses)
# Reverse Function
courses.reverse()
print(courses)
# Sort Function
sort_courses = courses
sort_courses.sort()
print(sort_courses)
nums = [3, 5, 4, 1, 2]
nums.sort()
print(nums)
# Sort Reverse Function
sort_courses.sort(reverse=True)
print(sort_courses)
# Sort without altering original list Function
print(sorted(courses))
# Min, Max and Sum Function
print(min(nums))
print(max(nums))
print(sum(nums))
# Search function
print(courses.index("CompSci"))
# Search if exist
print("Math" in courses)
# for loop function
for course in courses:
print(course)
# for loop with enumerate function
for course in enumerate(courses):
print(course)
for index, course in enumerate(courses):
print(index, course)
# for loop with index start
for index, course in enumerate(courses, start=1):
print(index, course)
# list to string
course_str = ", ".join(courses)
print(course_str)
# split string function
print(course_str.split(", "))
list_1 = ["History", "Math", "Physics", "CompSci"]
list_2 = list_1
print(list_1)
print(list_2)
# replacing list data via index
list_1[0] = "Art III"
print(list_1)
print(list_2)
# tuples
tuple_1 = ("History", "Math", "Physics", "CompSci")
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# replacing list data via index
# tuple_1[0] = "Art III"
print(tuple_1)
print(tuple_2)
# Sets removes duplicate data
cs_courses = {"History", "Math", "Physics", "CompSci", "Math"}
print(cs_courses)
# set searching
print("Math" in cs_courses)
# intersection like inner join
it_courses = {"Boilogy", "Math", "Chemistry", "CompSci"}
print(cs_courses.intersection(it_courses))
# union function
print(cs_courses.union(it_courses))
# empty lists
empty_list = []
empty_list = list()
# empty tuples
empty_tuple = ()
empty_tuple = tuple()
# empty sets
empty_set = {} # this isn't right! It's a dict
empty_set = set()
coordinates = (1, 2, 3)
x, y, z = coordinates
print(x, y, z)
customer = {
"name": "Dan",
"age": 27,
"is_verified": True
}
customer["name"] = "DAV"
print(customer.get("name"))
### excercise
'''
clear
& "D:/Program Files/Python39/python.exe" d:/Solutions/PythonTraining/02-list_tuple_set/app.py
'''
| true
|
61e8f246443d5a0213fccd12288967be3e9eb4e9
|
daniloiiveroy/MyPythonTraining
|
/10-input/app.py
| 2,111
| 4.28125
| 4
|
#### input function
"""
name = input("What is your name?")
print(name)
birth_year = input("Birth year: ")
age = 2021 - int(birth_year)
print(age)
w_lbs = input("What is your weight(in lbs)?")
w_kg = int(w_lbs) * 0.45359237
print(w_kg)
"""
#### input chars validation
"""
name = input("What is your name?")
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 50:
print("Name must be a maximum of 50 characters")
else:
print("Awesome name", name)
"""
#### input convertion
"""
weight = int(input("Weight: "))
metric = input("(L)bs or (K)g: ")
output = 0
if metric.upper() == "K":
output = weight / 0.45359237
print(f"You are {output} kilogram.")
elif metric.upper() == "L":
output = weight * 0.45359237
print(f"You are {output} pounds.")
else:
print("Please choose proper weight/metric.")
"""
#### input while loop break
"""
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess: "))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("You loser!")
"""
#### input game excercise
print("start - to start car")
print("stop - to stop car")
print("quit - to exit")
car_status = ""
started = False
while True:
car_status = input(">").lower()
if car_status == "start":
if started:
print("Car already started!.")
else:
started = True
print("Car started....Ready to go!")
elif car_status == "stop":
if not started:
print("Car already stopped!")
else :
started = False
print("Car stopped.")
elif car_status == "help":
print(
"""
start - to start car
stop - to stop car")
quit - to exit"""
)
elif car_status == "quit":
break
else:
print("I don't understand that...")
memory_status = car_status
"""
clear
& "D:/Program Files/Python39/python.exe" d:/Solutions/PythonTraining/10-input/app.py
& "C:/Python39/python.exe" E:/Solutions/PythonTraining/09-input/app.py
"""
| false
|
7d31ad86b378446d2397312cfec27c90e9aebf9f
|
fadikoubaa19/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/4-append_write.py
| 235
| 4.15625
| 4
|
#!/usr/bin/python3
""" module that contains the append write"""
def append_write(filename="", text=""):
""" appends a string to end of txt file"""
with open(filename, 'a', encoding='utf-8') as f:
return f.write(text)
| true
|
bdc0c9be95f2bc224281624a42fa6347abf4c7ff
|
MapleDa/Python
|
/topic13_files_io.py
| 1,241
| 4.15625
| 4
|
#T13Q1
#The open method returns a file object. Syntax: open(name[, mode]). where mode
#can be 'r' (read), 'w'(write) or 'a'(append). The default mode is 'r'.The
#close method closes an opened file object.
filename = 'tmp.txt'
mode = 'w'
f = open(filename, mode) # open a file
f.write('hello') # write to file
f.close() # close a file
#T13Q2
#Create a function that appends the name and email to the end of a named file.
def addEmail(filename, name, email):
mode = 'a'
f = open(filename, mode) # replace the mode
f.write("%s %s\n" % (name, email))
f.close()
return f # do not remove this line
#T13Q4
#read([size]). Read size bytes from the file, unless EOF is hit. If size is
#omitted or negative, the full data is returned.
def readFile(filename):
f = open(filename)
count = 0
lines = 0
while 1:
char = f.read(1)
if not char: break
count+=1
if(char == '\n'):
lines+=1
f.close() # close file
return (count, lines)
#T13Q6
#Write a function to read the scores and compute the average score of the
#class. (Ignore the first line which contains the field headers).
print(readFile('test.txt'))
| true
|
95c8cd2f0e63aab72f9862fc611ca54ed30970ce
|
dansmyers/IntroToCS
|
/Examples/2-Conditional_Execution/is_positive.py
| 222
| 4.28125
| 4
|
"""
Test if an input number is positive, negative, or zero
"""
value = int(input('Type a number.'))
if value > 0:
print('Positive.')
elif value < 0:
print('Negative.'
else:
print('Zero.')
print('Done.')
| true
|
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03
|
alosoft/bank_app
|
/bank_class.py
| 2,453
| 4.3125
| 4
|
"""Contains all Class methods and functions and their implementation"""
import random
def account_number():
"""generates account number"""
num = '300126'
for _ in range(7):
num += str(random.randint(0, 9))
return int(num)
def make_dict(string, integer):
"""makes a dictionary of Account Names and Account Numbers"""
return {string: integer}
class Account:
"""
This Class contains Balance and Name with functions like Withdraw, Deposit and Account History
"""
def __init__(self, name, balance=0, total_deposit=0, total_withdrawal=0):
"""Constructor of __init__"""
self.name = name.title()
self.balance = balance
self.records = [f'Default Balance: \t${self.balance}']
self.total_deposit = total_deposit
self.total_withdrawal = total_withdrawal
self.account = account_number()
def __str__(self):
"""returns a string when called"""
return f'Account Name:\t\t{self.name} \nAccount Balance:\t${str(self.balance)} ' \
f'\nAccount History:\t{self.records} \nAccount Number:\t\t{ self.account}'
def __len__(self):
"""returns balance"""
return self.balance
def history(self):
"""returns Account Information"""
return self.records
def print_records(self, history):
"""Prints Account Records"""
line = ' \n'
print(line.join(history) + f' \n\nTotal Deposit: \t\t${str(self.total_deposit)} '
f'\nTotal Withdrawal: \t${str(self.total_withdrawal)} '
f'\nTotal Balance: \t\t${str(self.balance)} ')
def deposit(self, amount):
"""Deposit function"""
self.total_deposit += amount
self.balance += amount
self.records.append(f'Deposited: ${amount}')
return f'Deposited: ${amount}'
def withdraw(self, amount):
"""Withdrawal function"""
if self.balance >= amount:
self.total_withdrawal += amount
self.balance -= amount
self.records.append(f'Withdrew: ${amount}')
return f'Withdrew: ${amount}'
self.records.append(
f'Balance: ${str(self.balance)} '
f'is less than intended Withdrawal Amount: ${amount}')
return f'Invalid command \nBalance: ${str(self.balance)} ' \
f'is less than intended Withdrawal Amount: ${amount}'
| true
|
0faa10eb9f27bfeb219c7330240439dd74392e65
|
plazmer/prodb_py
|
/2018/01/01_Moldobaev.py
| 2,918
| 4.15625
| 4
|
import re
# Работа со списками
# Написать код для функций ниже
# Проверка производится в функции main()
# 00. Пример. Дан список (list) строк. Вернуть число - количество строк, у которых
# 1. длина строки 2 и больше
# 2. первый и последний символ одинаковые
def func00(words):
count = 0
for w in words:
if len(w)>=2 and w[0]==w[-1]:
count += 1
return count
# 01. Из списка строк вернуть список в отсортированном по алфавиту порядке, но строки
# начинающиеся с числа (0-9) должны идти после строк, начинающихся с букв
# Подсказка: можно создать два списка, отсортировать их по отдельности перед объединением
def func01(words):
# здесь код и не забыть вернуть хоть что-то
number_list = []
word_list = []
for word in words:
if re.match(r'(\d+\w*)', word) is not None:
number_list.append(word)
else:
word_list.append(word)
return sorted(word_list) + sorted(number_list)
# 02. Отсортировать по последнему
# Дан список не пустых tuples, вернуть список, отсортированный по возрастанию
# последнего элемента tuple
def func02(tuples):
# здесь код и не забыть вернуть хоть что-то
return sorted(tuples, key = lambda tup: tup[1])
# используется для проверки,
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
# Запускает проверку
def main():
print('func00')
test(func00(['abba', 'xyz01', 'nn', 'y', '444']), 3)
test(func00(['', 'a', 'ab', 'cvc', 'jj']), 2)
test(func00(['rrr', 'db', 'pro', 'hello']), 1)
print('func01')
test(func01(['1aa', '2bb', 'axx', 'xzz', 'xaa']),
['axx', 'xaa', 'xzz', '1aa', '2bb'])
test(func01(['ccc', 'bbb', '9aa', 'xcc', 'xaa']),
['bbb', 'ccc', 'xaa', 'xcc', '9aa'])
test(func01(['mix', 'xyz', '6apple', 'xanadu', 'aardvark']),
['aardvark', 'mix', 'xanadu', 'xyz', '6apple'])
print('func02')
test(func02([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(func02([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(func02([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
if __name__ == '__main__':
main()
| false
|
a4d288d865bd0661a99061a385f54229f461be0f
|
brunorafael96/Calculo_area_retangulo_circulo
|
/Calculo_Area/Calculo_Area/Calculo_Area.py
| 790
| 4.3125
| 4
|
print ("Bem-vindo ao programa de calculo da area de Retangulos e Circulos")
print ("-----------------------------------------------")
print ("Programa criado por Bruno Rafael")
print ("================================")
#Menu de escolha do usurio
print ("Escolha a forma que deseja calcular a area:")
print ("Digite a para calcular area do retangulo")
print ("Digite b para calcular area do circulo")
#escolha do usurio
escolha = input("Digite a opcao desejada: ")
#calculando a area
if escolha =="a":
altura = int(input("Qual a altura do Retangulo: "))
largura = int(input("Qual a largura do Retangulo: "))
area = (altura*largura)
print(area);
else:
raio = int(input("Digite o Raio do circulo: "))
area2 = 3.14 * (raio**2)
print ("A area do circulo e ", area2)
| false
|
c333d408b37574b13a5f92fb68825e4725ac223e
|
samdish7/COSC420
|
/Notes/Py/pyfuncs.py
| 1,104
| 4.25
| 4
|
# Python functions are defined with the
# "def" keyword, then the name, list of
# parameters, then a colon.
# note that functions do not have
# return types, and parameters do not
# have types (but you can provide them
# anyway)
# scopes in python are delineated not by
# curly braces (as in c/c++) but by tabs
# you can use spaces to indent or tabs,
# but don't mix-and-match
def func():
# all following indented lines are
# bound to the "func" block
print("hello from func")
# non type-hinted version
def funcParams(a,b,c):
# using python's "f-strings"
print(f"a: {a}")
print(f"b: {b+10}")
print(f"c: {c}")
return 10 # return looks the same
# hinted version
def funcParams2(
a : str,
b : int,
c : float) -> int :
# using python's "f-strings"
print(f"a: {a}")
print(f"b: {b+10}")
print(f"c: {c}")
return "10" # return looks the same
def main():
print("Start of program")
print("about to call the function:")
func() # call the funcion
#val = funcParams(15, 10, 3.4)
val = funcParams2(15, 10, 3.4)
print(val)
# back in the top-level scope
main()
| true
|
72f6a15f8adc58899ea401ee378d2e9ddc5367ae
|
bryyang/unirioja
|
/TEMA3/secCar.py/palindromo.py
| 286
| 4.125
| 4
|
# Introducir una cadena de caracteres e indicar si es un palíndromo. Una palabra
# palíndroma es aquella que se lee igual adelante que atrás.
cad = input("Introduce una cadena:")
if cad.lower() == cad[::-1].lower():
print("Es un palíndromo")
else:
print("No es un palíndromo")
| false
|
6fd3b644ed043a8b288065be615f638f9436e8b0
|
awlange/project_euler
|
/python/p72.py
| 1,834
| 4.1875
| 4
|
import time
from p27 import get_primes_up_to
def farey(n):
"""
Thanks for the help Wikipedia!
Python function to print the nth Farey sequence, either ascending or descending.
"""
a, b, c, d = 0, 1, 1, n
print "%d/%d" % (a,b)
while c <= n:
k = int((n + b)/d)
a, b, c, d = c, d, k*c - a, k*d - b
print "%d/%d" % (a,b)
def phi(n, primes=None):
"""
totient function of n for general use later
below, we use a sieve approach and don't use this function
"""
if not primes:
primes = get_primes_up_to(n)
result = float(n)
for p in primes:
if p > n:
break
elif n % p == 0:
result *= 1.0 - 1.0/float(p)
return int(result)
def phi_float(n, primes=None):
"""
totient function of n for general use later
below, we use a sieve approach and don't use this function
"""
if not primes:
primes = get_primes_up_to(n)
result = float(n)
for p in primes:
if p > n:
break
elif n % p == 0:
result *= 1.0 - 1.0/float(p)
return result
def main():
start = time.time()
# Using formula found on Wikipedia under Farery sequence
MAX_N = 1000000
primes = get_primes_up_to(MAX_N)
prime_divs = [[] for _ in xrange(MAX_N+1)]
for p in primes:
m = p
while m <= MAX_N:
prime_divs[m].append(p)
m += p
# Now compute the totient for each using the provided primes, and compute the Farey length
answer = 0
for m in xrange(2, MAX_N + 1):
totient = float(m)
for p in prime_divs[m]:
totient *= 1.0 - 1.0/float(p)
answer += int(totient)
print answer
print "Time: {}".format(time.time() - start)
if __name__ == '__main__':
main()
| true
|
ec3d2376bf613dbc7f9559e3ef2cad2d4b717cb4
|
awlange/project_euler
|
/python/p38.py
| 886
| 4.15625
| 4
|
# What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated
# product of an integer with (1,2, ... , n) where n > 1?
digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
len_digits = len(digits)
len_digits_plus_one = len(digits) + 1
is_pan_range = range(1, len_digits_plus_one)
MAX_PANDIGITAL = 987654321
# 9 * 1 = 9 <-- largest first digit
# x * 2 = 87654321 <-- largest rest of digits
# So, x = 43827161 <-- largest multiplier
# Known not to be the largest: 918273645
def is_pandigital(sn):
for d in digits:
if d not in sn:
return False
return True
largest = 918273645
for i in range(9, 43827161):
m = i
sn = str(m)
while len(sn) < 9:
m += i
sn += str(m)
if len(sn) == 9:
isn = int(sn)
if isn > largest and is_pandigital(sn):
largest = isn
print largest
| false
|
f9b7c11118c0e2ccf65dab75f01d0cdb1001532a
|
nrglll/katasFromCodeWars
|
/string_example_pigLatin.py
| 1,052
| 4.375
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 15:44:33 2020
@author: Nurgul Aygun
"""
# =============================================================================
# Kata explanation:
# Move the first letter of each word to the end of it, then add "ay" to
# the end of the word. Leave punctuation marks untouched.
#
# Examples
# pig_it('Pig latin is cool') # igPay atinlay siay oolcay
# pig_it('Hello world !') # elloHay orldway !
# =============================================================================
import string
def pig_it(text):
new_words = []
for w in text.split():
if w[::] not in string.punctuation:
new_words += [w[1::] + w[0] + "ay"]
else:
new_words += w
return " ".join(new_words)
# =============================================================================
# print(pig_it('Panem et circenses')) # anemPay teay ircensescay
# print(pig_it('Hello world !')) # elloHay orldway !
# =============================================================================
| true
|
2fdb8c0b1434cf8ce72e7c6f6840166c8d72ffd5
|
azka97/practice1
|
/beginner/PrintInput.py
| 642
| 4.125
| 4
|
#input() will by default as String
#basic math same as other language, which is +,-,/,*
#exponent in python notated by '**'
#There's '//' which is used for devided number but until how many times it will be reach the first number. Was called ' Integer Division'
#Modulus operator notated by '%'. This is the remain number of some formula. example: 7 % 3 = 1 because 7/3= 6 with one remain number which is "1" or its called remainder
#'type' for calling what type of a Variable is
print('Pick a number :')
num1 = input()
print('Pick a number again :')
num2 = input()
print(type(num2))
Jumlah = int(num1)+int(num2)
print(Jumlah)
| true
|
b2a2f7598364273be0ca0a62e3339fe7cf4f2695
|
LalitGsk/Programming-Exercises
|
/Leetcode/July-Challenge/prisonAfterNDays.py
| 1,700
| 4.125
| 4
|
'''
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
'''
class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
_dict = {}
self.cells = cells
for i in range(N):
s = str(self.cells)
if s in _dict:
loop_len = i- _dict[s]
left_days = (N-i)%loop_len
return self.prisonAfterNDays(self.cells, left_days)
else:
_dict[s] = i
prev = self.cells[0]
for j in range(1,7):
curr, next = self.cells[j], self.cells[j+1]
self.cells[j] = 1 - (prev^next)
prev = curr
self.cells[0], self.cells[7] = 0,0
return self.cells
| true
|
5409e790168cb5f59ad3e1f4ef8dc63914cf2245
|
MadhanBathina/python
|
/odd even count of in between intigers of two numbers.py
| 519
| 4.21875
| 4
|
Start=int(input('Starting intiger :'))
End=int(input('Ending intiger :'))
if Start < 0 :
print('1 ) The numbers lessthan 0 is not supposed to be count as either odd or even.')
print('2 ) {0} to -1 are not considered as per the above statement.'.format(Start))
Start = 0
oddcount = 0
evencount= 0
for i in range (Start, End+1) :
if i % 2 == 0 :
evencount += 1
else :
oddcount += 1
print ('evencount={0}.'.format(evencount))
print ('oddcount={0}.'.format(oddcount))
| true
|
84b5d6b336751efd0e7f9a6bde1a8ad50e5631f2
|
RohiniRG/Daily-Coding
|
/Day39(Bit_diff).py
| 896
| 4.28125
| 4
|
# You are given two numbers A and B.
# The task is to count the number of bits needed to be flipped to convert A to B.
# Examples :
# Input : a = 10, b = 20
# Output : 4
# Binary representation of a is 00001010
# Binary representation of b is 00010100
# We need to flip highlighted four bits in a
# to make it b.
# Input : a = 7, b = 10
# Output : 3
# Binary representation of a is 00000111
# Binary representation of b is 00001010
# We need to flip highlighted three bits in a
# to make it b.
# ***************************************************************************************************
def countBitsFlip(a,b):
ans = a ^ b
count = 0
while ans:
count += 1
ans &= (ans-1)
return count
one = int(input('Enter 1st number: '))
two = int(input('Enter 2nd number: '))
print('The number of bits to be flipped: ', countBitsFlip(one, two))
| true
|
f35713a8ec7b2fbf0a0c957c023e74aa58cd55db
|
randyarbolaez/codesignal
|
/daily-challenges/swapCase.py
| 232
| 4.25
| 4
|
# Change the capitalization of all letters in a given string.
def swapCase(text):
originalLen = len(text)
for i in text:
if i.isupper():
text += i.lower()
else:
text += i.upper()
return text[originalLen:]
| true
|
89f316d8298d5ccbdbac841a9a6f3eea5d67d8e4
|
randyarbolaez/codesignal
|
/daily-challenges/CountDigits.py
| 259
| 4.1875
| 4
|
# Count the number of digits which appear in a string.
def CountDigits(string):
totalNumberOfDigits = 0
for letterOrNumber in string:
if letterOrNumber.isnumeric():
totalNumberOfDigits += 1
else:
continue
return totalNumberOfDigits
| true
|
69663c4050dbcfc286850f7182b9769d53fb6305
|
eflipe/developer_exercises_python
|
/simple/simple.py
| 2,282
| 4.21875
| 4
|
'''
Hacer una función que genere una lista de diccionarios
que contengan id y edad, donde
edad sea un número aleatorio entre 1 y 100 y la longitud de la
lista sea de 10 elementos. Retornar la lista.
Hacer otra función que reciba lo generado en la primer
función y ordenarlo de mayor a menor.
Printear el id de la persona más joven y más vieja.
Devolver la lista ordenada.
'''
import random
from operator import itemgetter
def list_of_dicts():
'''
Genera una lista de diccionarios de 10 elementos.
Las keys son "ID" y "Edad" donde edad es un número
aleatorio entre 1 y 100.
:return: list
>>> test_list_of_dicts = list_of_dicts()
>>> len(test_list_of_dicts) == 10
True
>>> 1 <= test_list_of_dicts[0]["Edad"] <= 100
True
'''
LONG_LIST = 10
list_dicts = []
for element in range(1, LONG_LIST + 1):
context_dict = {
'ID': element,
'Edad': random.randint(1, 101),
}
list_dicts.append(context_dict)
return list_dicts
def sort_list(list_dicts):
'''
Recibe una lista y la ordena de mayor a menor.
Printea el "ID" de la persona de mayor edad y la de menor edad.
Devuelve la lista ordenada.
:param list_dicts: list
:return: list
>>> ejemplo_lista = [{'ID': 1, 'Edad': 51}, {'ID': 2, 'Edad': 54}, {'ID': 3, 'Edad': 31}, {'ID': 4, 'Edad': 74}, {'ID': 5, 'Edad': 21}, {'ID': 6, 'Edad': 19}, {'ID': 7, 'Edad': 77}, {'ID': 8, 'Edad': 62}, {'ID': 9, 'Edad': 85}, {'ID': 10, 'Edad': 29}]
>>> sort_list(ejemplo_lista)
ID y edad de persona mayor:
ID: 9, Edad: 85
ID y edad de persona menor:
ID: 6, Edad: 19
[{'ID': 9, 'Edad': 85}, {'ID': 7, 'Edad': 77}, {'ID': 4, 'Edad': 74}, {'ID': 8, 'Edad': 62}, {'ID': 2, 'Edad': 54}, {'ID': 1, 'Edad': 51}, {'ID': 3, 'Edad': 31}, {'ID': 10, 'Edad': 29}, {'ID': 5, 'Edad': 21}, {'ID': 6, 'Edad': 19}]
'''
sorted_list = sorted(list_dicts, key=itemgetter('Edad'), reverse=True)
print(f'ID y edad de persona mayor:\nID: {sorted_list[0]["ID"]}, Edad: {sorted_list[0]["Edad"]}')
print(f'ID y edad de persona menor:\nID: {sorted_list[-1]["ID"]}, Edad: {sorted_list[-1]["Edad"]}')
return sorted_list
if __name__ == '__main__':
import doctest
doctest.testmod()
| false
|
d008f4f9d0f64f72bbda7be1909e5ae71f2cf1fc
|
Fittiboy/recursive_hanoi_solver
|
/recursive_hanoi.py
| 707
| 4.25
| 4
|
step = 0
def move(fr, to):
global step
step += 1
print(f"Step {step}:\tMove from {fr} to {to}")
def hanoi(fr, to, via, n):
if n == 0:
pass
else:
hanoi(fr, via, to, n-1)
move(fr, to)
hanoi(via, to, fr, n-1)
n = input("\n\nHow many layers does your tower of Hanoi have?\t")
try:
n = int(n)
except:
pass
while type(n) is not int or n < 1:
n = input("Please enter a positive number as the tower's height!\n\t")
try:
n = int(n)
except:
pass
print("\nTo solve the tower in the least possible moves, follow these instructions:")
input("(press Enter to start)\n")
hanoi(1, 3, 2, n)
print(f"\nCompleted in {step} steps.\n")
| true
|
34a1160271b9db20ca0eca1839bc991abc0a2351
|
coderboom/Sample
|
/chapter05/slice_test.py
| 830
| 4.1875
| 4
|
"""
切片模式:[start:end:step]
start:切片开始位置,默认为0
end:切片截止位置,但不包括该位置,默认是列表长度
step:切片步长,默认是1个步长,当步长是负数时,表示反向切片,这时候start的数值应该大于end的数值
重点:切片操作返回的是一个新的list,不会改变原list
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[1:9:2])
"""
带点技术的操作
"""
a[:0] = [1, 2] # 在列表头部插入元素
a[3:3] = [5] # 将3这个位置的元素改变成5
a[:3] = [1, 2, 3] # 将前三个元素更改成1,2,3
a[3:] = [4, 5, 6, 7] # 将3位置以后的元素更改成4,5,6,7
a[::2] = [0] * 3 # 各一个修改一个
a[::3] = ['a', 'b', 'c'] # 各一个修改一个
a[:3] = [] # 删除元素
"""
删除元素 del
"""
del a[:3]
del a[::3]
| false
|
7aa978fad9e053f9d0541bb07585ba90027fcd6e
|
Digit4/django-course
|
/PYTHON_LEVEL_ONE/Part10_Simple_Game.py
| 2,536
| 4.21875
| 4
|
###########################
## PART 10: Simple Game ###
### --- CODEBREAKER --- ###
## --Nope--Close--Match-- ##
###########################
# It's time to actually make a simple command line game so put together everything
# you've learned so far about Python. The game goes like this:
# 1. The computer will think of 3 digit number that has no repeating digits.
# 2. You will then guess a 3 digit number
# 3. The computer will then give back clues, the possible clues are:
#
# Close: You've guessed a correct number but in the wrong position
# Match: You've guessed a correct number in the correct position
# Nope: You haven't guess any of the numbers correctly
#
# 4. Based on these clues you will guess again until you break the code with a
# perfect match!
# There are a few things you will have to discover for yourself for this game!
# Here are some useful hints:
def num_len_check(x):
if(x.isnumeric()):
if (len(x) > 3):
print("Oops! you've entered too many numbers, please try lesser numbers.")
elif (len(x) < 3):
print("You must enter at least 3 numbers, please try more numbers.")
else:
return False
else:
print("Please Enter numeric values only")
return True
def num_validity_converstion(num):
if (num.isnumeric()):
valid_nums = list(map(int, num))
return valid_nums
def game_rules(actual_digits, guessed_digits):
match, close, nope = 0, 0, 0
for i in guessed_digits:
flag = False
for j in actual_digits:
if (j == i):
if (guessed_digits.index(i) == actual_digits.index(j)):
match += 1
flag = True
break
else:
close += 1
flag = True
break
if (not flag):
nope += 1
return [match,close,nope]
# Try to figure out what this code is doing and how it might be useful to you
import random
digits = list(range(10))
random.shuffle(digits)
print(digits[:3])
# Another hint:
# Think about how you will compare the input to the random number, what format
# should they be in? Maybe some sort of sequence? Watch the Lecture video for more hints!
digits_matched = False
while (not digits_matched):
guess = input("What is your guess? ")
print(guess)
if (num_len_check(guess)):
continue
guessed_nums = num_validity_converstion(guess)
clues_arr = game_rules(digits[:3], guessed_nums)
if (clues_arr[0] == 3):
digits_matched = True
if (not digits_matched):
print("Here's the result of your guess:")
print ("Matches:%d\tClose:%d\t\tNope:%d\t" %(clues_arr[0],clues_arr[1],clues_arr[2]))
else:
print("Hooray!! YOU WIN!!")
| true
|
67a64d653913f1c4a706347ec55165f0c57412ac
|
cesarmarcanove/Remesas
|
/Codigos/Python/remesa5py3.py
| 1,268
| 4.21875
| 4
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
print("Ingrese monto en dolares a enviar la remesa: $")
env = float(input())
print("Cuantas personas desea enviar: ")
p = float(input())
print("") # no hay forma directa de borrar la pantalla con Python estandar
print(" ")
# Cantidad de personas
# backup: p <- 8;
# Tasa pais emisor
tasa1 = 20
# Tasa Pais recibidor
tasa2 = 10
# Dividiendo la cantidad de remesa por cada 8 personas
unit = env/p
print(" El Monto de la remesa es de: $",env)
print(" Tienes ",p," personas para dar la remesa por enviar.")
print(" La cantidad unitaria es de: $",unit," dolares por persona.")
print(" ")
print(" La Tasa en el pais emisor (ejm: Suiza) es: $",tasa1," dolares.")
print(" La Tasa en el pais recibidor (Venezuela) es: $",tasa2," dolares. ")
# Calculos
# Resta de remesa en el pais emisor
reme1 = (unit-tasa1)
# Resta de remesa en el pais recibidor
reme2 = (reme1-tasa2)
print(" ")
print(" Cantidad en dolares en el pais emisor (ejm: Suiza) despues de la Tasa: $",reme1)
print(" Cantidad en dolares en el pais recibidor (Venezuela) despues de la Tasa: $",reme2)
input() # a diferencia del pseudoco, espera un Enter, no cualquier tecla
| false
|
d05dd4b1903d781d594e0b125266c3a58706382b
|
jon-moreno/learn-python
|
/ex3.py
| 769
| 4.34375
| 4
|
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
print "What does comma","do?"
#comma separates different objects in a print statement that should be
#printed on the same line, adding a space b/w objects
#if you put a comma at end of print stmt, it will prevent a newline
#Single and double quotes work the same until you need to delimit one
| true
|
1edaebb9de5aff4e3aa4e56d610ae3267069df11
|
snu-python/pythonbook
|
/lab/lab8_2.py
| 1,538
| 4.15625
| 4
|
#!/usr/bin/env python
"""This file is provided for educational purpose and distributed for class use.
Copyright (c) by Jinsoo Park, Seoul National University. All rights reserved.
File name.....: lab8_2.py
Description...: Sample solution for Lab 8-2.
This program demonstrates how to use a nested conditional
statement.
"""
__author__ = 'Jinsoo Park'
__version__ = '0.1'
__email__ = 'snu.python@gmail.com'
x = 7 # 변수 x에 7을 할당한다.
y = 15 # 변수 y에 15을 할당한다.
z = 5 # 변수 z에 5을 할당한다.
if x > y: # x가 y보다 크면
if x > z: # x가 z보다 크면
print(y + z) # y + z를 출력한다.
else: # x가 z보다 크지 않으면
print(x + y) # x + y를 출력한다.
else: # x가 y보다 크지 않으면
if z > y: # z가 y보다 크면
print(x + y) # x + y를 출력한다.
else: # z가 y보다 크지 않으면
print(x + z) # x + z를 출력한다.
# !!!!! END of lab8_2.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
| false
|
cdb1e82b5ef9b5dd5465d8367fbed6bcd791e774
|
snu-python/pythonbook
|
/lab/lab8_4.py
| 845
| 4.28125
| 4
|
#!/usr/bin/env python
"""This file is provided for educational purpose and distributed for class use.
Copyright (c) by Jinsoo Park, Seoul National University. All rights reserved.
File name.....: lab8_4.py
Description...: Sample solution for Lab 8-4.
This program demonstrates how to use a for statement with
range().
"""
__author__ = 'Jinsoo Park'
__version__ = '0.1'
__email__ = 'snu.python@gmail.com'
alist = list(range(1,11)) # 1부터 10까지의 정수를 포함하는 리스트를 변수 alist에 할당한다.
print(alist) # 변수 alist를 출력한다.
for i in alist: # alist에 속한 각 정수 i가
if i % 3 == 2: # 3으로 나눈 나머지가 2이면
print(i) # i를 출력한다.
# !!!!! END of lab8_4.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
| false
|
631922ad9ea661de547af2af1a1500fb5ec4c065
|
maahokgit/Python-Assignments
|
/Assigments/Assignment4/AManNamedJed/aManNamedJedi.py
| 2,037
| 4.28125
| 4
|
"""
Student Name: Edward Ma
Student ID: W0057568
Date: November 16, 2016
A Man Named Jedi
Create a program that will read in a file and add line numbers to the beginning of each line.
Along with the line numbers, the program will also pick a random line in the file and convert it to all capital letters.
All other lines in the program will be converted to lowercase letters. The program will then write the resulting lines
out to a second file and display the contents of each file on the console.
"""
import csv #use cool csv function bruh
import random #to allow random number to be made! wooooooah!
fileName = "AManNamedJed.txt"
fileName2 = "AManNamedJed2.txt" #second file name
accessMode = "r" #to read the file
accessMode2 = "w" #to write the file
print("***ORIGINAL TEXT***\n")
with open(fileName, accessMode) as INPUT:
#Read the file contents
dataPlaceholder = csv.reader(INPUT)
datalist = [] #a list with each line as value
counter = 0
data = []
for row in dataPlaceholder:
counter += 1 #add line number to the list!
print(' '.join(row))
data = str(counter)+": "+str(' '.join(row))
datalist.append(data)
randomLine = random.randint(0,(len(datalist))) #set random number to go as far as length of the list
print("\n***NEW TEXT***\n")
with open(fileName2, accessMode2) as OUTPUT:
for counter in range(len(datalist)):
if counter == randomLine:
#IF the row is samn as random number, change it to uppercase
#If not, make it lowercase
OUTPUT.write(datalist[randomLine].upper()+str("\n"))
else:
OUTPUT.write(datalist[counter].lower()+str("\n"))
with open(fileName2, accessMode) as SHOW: #Read new file, and print out what happened!
#Read the file contents
dataPlaceholder = csv.reader(SHOW)
datalist1 = [] #a list with each line as value
for row in dataPlaceholder:
datalist1.append(row)
for row in datalist1:
print(' '.join(row))
| true
|
54b3407b8081d12dd367de06980258e6f0e179b1
|
rusivann/Rep_Nata_Pyneng
|
/5_PyBaseScripts/task_5_4.py
| 949
| 4.1875
| 4
|
#vhodnie dannie - 2 spiska
num_list = [10, 2, 30, 100, 10, 50, 11, 30, 15, 7]
word_list = ['python', 'ruby', 'perl', 'ruby', 'perl', 'python', 'ruby', 'perl']
#zapros parametrov u polzovatelya. te, которые будем искать
numindex = int(input('Vevdite chislo: '))
wordindex = input('Vvedite slovo: ')
#переворачиваем списки сзаду наперёд
num_list.reverse()
word_list.reverse()
#вывод на экран для контроля перевёрнутых списков
print(num_list)
print(word_list)
#вывод искомого индекса последнего встречающегося элемента. т.е. перевернули список,
#использовали функцию index и вычли индекс из длины списка для коррекции
print((len(num_list) - 1) - num_list.index(numindex))
print((len(word_list) - 1) - word_list.index(wordindex))
| false
|
ef552df18f1f97c7c05ba73ad9b78e3f34cd7481
|
wook2124/Python-Challenge
|
/#1/#1.12 for in.py
| 416
| 4.15625
| 4
|
# for문
# x라는 변수는 for문이 실행되면서 만들어짐
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
for x in days:
print(x)
for x in [1, 2, 3, 4, 5]:
print(x)
# for loop 중단
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
for x in days:
if x == "Wed":
break
else:
print(x)
# Python에선 str도 배열임
# str, tuple or list를 순차적으로 나타냄
for x in "Young Wook":
print(x)
| false
|
55701fa458fc998a4d3fe5e38afec0808d36e88f
|
matthewlee1/Codewars
|
/create_phone_number.py
| 484
| 4.125
| 4
|
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
#Example:
# create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
def create_phone_number(n):
f = "".join(map(str, n[:3]))
s = "".join(map(str, n[3:6]))
t = "".join(map(str, n[6:10]))
return "({}) {}-{}".format(f,s,t)
myNumber = [8,6,0,7,5,1,2,6,8,7]
print(create_phone_number(myNumber))
| true
|
9116283a58b98e8debeea1bb279fc1988d9e0f1a
|
Ahameed01/tdd_challenge
|
/weather.py
| 1,015
| 4.125
| 4
|
# Assume the attached file port-harcourt-weather.txt contains weather data for
# Port Harcourt in 2016. Download this file and write a program that returns the
# day number (column one) with the smallest temperature spread (the maximum
# temperature is the second column, the minimum the third column).
filename = "port-harcourt-weather.txt"
def weatherReport():
with open(filename) as file:
file.next()
next(file)
dayList = []
dailyTempSpread = []
for line in file:
line.strip()
splitted_line = line.split()
try:
dayListNum = int(splitted_line[0])
dailyHigh = int(splitted_line[1])
dailyLow = int(splitted_line[2])
except Exception as e:
pass
dailyTempSpread.append(dailyHigh - dailyLow)
dayList.append(dayListNum)
weatherDict = dict(zip(dayList, dailyTempSpread))
print weatherDict
weatherReport()
| true
|
225160859f926e7f08af188dbceb46c9c81a35b1
|
carrba/python-stuff
|
/pwsh2python/functions/ex1.py
| 369
| 4.125
| 4
|
#!/usr/bin/python3.6
def divide (numerator, denominator):
myint = numerator // denominator
myfraction = numerator % denominator
if myfraction == 0:
print("Answer is", myint)
else:
print("Answer is", myint, "remainder", myfraction)
num = int(input("Enter the numerator "))
den = int(input("Enter the denominator "))
divide (num, den)
| true
|
ca02219c4ec546314f18f7f2779f815833e13951
|
arohigupta/algorithms-interviews
|
/hs_interview_question.py
| 1,794
| 4.21875
| 4
|
# def say_hello():
# print 'Hello, World'
# for i in xrange(5):
# say_hello()
#
# Your previous Plain Text content is preserved below:
#
# This is just a simple shared plaintext pad, with no execution capabilities.
#
# When you know what language you'd like to use for your interview,
# simply choose it from the dropdown in the top bar.
#
# You can also change the default language your pads are created with
# in your account settings: https://coderpad.io/profile
#
# Enjoy your interview!
#
#
# // Given a string of numbers between 1-9, write a function that prints out the count of consecutive numbers.
# // For example, "1111111" would be read as "seven ones", thus giving an output of "71". Another string like "12221" would be result in "113211".
# // "" -> ""
def look_and_say(input):
# split input
# result_array
# set counter to 1
i = 0
counter = 0
# num_arr = list(input)
result = ""
if input:
current_char = input[0]
# loop over num_arr
while i < len(input):
# if not num_arr[i] and not num_array[i+1]:
# break
# if num_arr[i] == num_arr[i+1]
# counter += 1
if current_char == input[i]:
counter += 1
# else
# result_array.append(counter)
# result_array.append(num_array[i]
# counter = 1
else:
# print "else"
result = result + str(counter) + str(current_char)
current_char = input[i]
counter = 1
i += 1
result = result + str(counter) + str(current_char)
else:
result = ""
return result
print look_and_say("99992222888hhhhheeeelllloooo88833332222")
| true
|
b687c97076dba795663606e9dc2c30408cf47d31
|
arohigupta/algorithms-interviews
|
/fizz_buzz_again.py
| 673
| 4.1875
| 4
|
#!/usr/bin/env python
"""fizz buzz program"""
def fizz_buzz(fizz_num, buzz_num):
"""function to print out all numbers from 1 to 100 and replacing the numbers
completely divisible by the fizz number by 'Fizz', the numbers completely
divisible the buzz number by 'Buzz' and the numbers completely divisible by
both by 'FizzBuzz'
"""
for i in range(1, 101):
# loop to go from 1 included to 101 excluded
if i % (fizz_num*buzz_num) == 0:
print "FizzBuzz",
elif i % fizz_num == 0:
print "Fizz",
elif i % buzz_num == 0:
print "Buzz",
else:
print i,
fizz_buzz(7, 5)
| true
|
0ddd67e8196a7c21f532dadc2afd69586bc8d228
|
marykamau2/katas
|
/python kata/even_odd/even_odd.py
| 221
| 4.34375
| 4
|
def even_odd():
num = int(input('Enter number to find whether is even or odd\n'))
if num % 2 ==0:
print(f"{num} is an even number")
else:
print(f"{num} is an odd number")
even_odd()
| false
|
59df6da3c92f45d1fabcbcc6411cba06e0fe1a82
|
yingzk/leetcode_python3
|
/LCP1.py
| 1,284
| 4.3125
| 4
|
"""
LCP 1. 猜数字
小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次?
输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。
示例 1:
输入:guess = [1,2,3], answer = [1,2,3]
输出:3
解释:小A 每次都猜对了。
示例 2:
输入:guess = [2,2,3], answer = [3,2,1]
输出:1
解释:小A 只猜对了第二次。
限制:
guess的长度 = 3
answer的长度 = 3
guess的元素取值为 {1, 2, 3} 之一。
answer的元素取值为 {1, 2, 3} 之一。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/guess-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def game(self, guess: List[int], answer: List[int]) -> int:
num = 0
for i in range(3):
if guess[i] == answer[i]:
num += 1
return num
if __name__ == '__main__':
result = Solution().game([1, 2, 3], [1, 2, 3])
print(result)
| false
|
aa7d509d810a2c2aed89ffbf7ffd63a04a094702
|
AmandaCasagrande/Entra21
|
/08-10-20 Funções/Exercicio 5.py
| 809
| 4.1875
| 4
|
#--- Exercício 5 - Funções
#--- Crie uma função para calculo de raiz
#--- A função deve ter uma variável que deternine qual é o indice da raiz(raiz quadrada, raiz cubica...)
#--- Leia um número do console, armazene em uma variável e passe para a função
#--- Realize o calculo da raiz e armazene em uma segunda variável e retorne
#--- Imprima o resultado e uma mensagem usando f-string, fora da função
#Importa biblioteca e define função;
import math
def calcularRaiz(num, indice):
raiz = float(math.pow(num, 1/indice))
return raiz
#Entrada de parâmetros;
print(f"** Cálculo de raiz **")
num = float(input("Digite o valor: "))
indice = int(input("Determine o índice da raiz: "))
#chamada da função;
raiz = calcularRaiz(num, indice)
print(f"A raiz é {raiz:.2f}")
| false
|
441329bf024a6db66f938d86543d361dba98d2b6
|
Moondance-NL/Moondance-NL
|
/ex1.py
| 792
| 4.5
| 4
|
print("I will now count my chickens:")
# we are calulating the number of hens and roosters
print("Hens", 25.0 + 30.0 /6.0)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
# we are calculating the number of eggs
print(3.0 + 2.0 + 1-5 + 4 % 2-1 / 4.0 + 6.0)
# we are attemting to find the answer
print("Is it true that 3 + 2 < 5 - 7?")
# we are doing a calc to get at the truth
print(3 + 2 < 5 - 7)
# doing the math
print("what is 5 -7?", 5 - 7)
# and more math
print("Oh, that's why it's false.")
#eurika!
print ("How about some more.")
#what do you think?
print("Is it greater?", 5 > -2)
#getting to the heart of the matter
print("Is it greater or equal", 5 >= -2)
#discovering the real real
print("Is it less or equal?", 5 <= -2)
#maybe not
| true
|
c73ae82e5ebb3620f75fe89425d294858dc6a4f9
|
krishnabojha/Insight_workshopAssignment4
|
/Question5.py
| 559
| 4.3125
| 4
|
########## sorting the list of tuple
info_tuple=('krishna','ojha',1)
more_tuple=(('jeevan','rai',2),('hari','magar',3),('bikash','khanal',4),('binod','gauli',5))
people=[]
dictionary={0:'first name',1:'last name',2:'age'}
people.append(info_tuple)
for i in more_tuple:
people.append(i)
people.sort()
for num in range(len(dictionary)):
print('Enter {} to sort by {} , '.format(num,dictionary[num]))
a=int(input())
people.sort(key=lambda x:x[a])
print('The sorted tuple by ',dictionary[a],' : \n')
for tup in range(len(people)):
print(people[tup])
| false
|
4733713d4de3ca0f91ff841167162ff8f963c445
|
chuymedina96/coding_dojo
|
/chicago_codes_bootcamp/chicago_codes_python/python_stack/python/fundamentals/practice_strings.py
| 2,028
| 4.78125
| 5
|
print ("Hello world")
#Concatentaing strings and variables with the print function.
# multiple ways to print a string containing data from variables.
name = "zen"
print("My name is,", name)
name = "zen"
print("My name is " + name)
#F-strings (Literal String Interpolation)
first_name = "zen"
last_name = "Coder"
age = 27
print(f"My name is {first_name} {last_name} and I am {age} years old.") #this is the new way to do it :)
first_name = "Chuy"
last_name = "Medina"
age = 23
food = "sushi"
print(f"Hello, my first name is {first_name} and my last name is {last_name}, and also my current age is {age}. I also really enjoy {food}, but I ain't trying to get Mercury poisoning though")
# String.format() method.
first_name = "Zen"
last_name = "Coder"
age = 27
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age)) #putting in variables in the order in which they should fill the brackets.
# output: My name is Zen Coder and I am 27 years old.
print("My name is {} {} and I am {} years old.".format(age, first_name, last_name))
# output: My name is 27 Zen and I am Coder years old.
name = "Jesus Medina"
food = "pizza and sushi"
print("Hello, I really like {} and my name is {}".format(food, name))
# This is an even older way of string interpolation.
# Rather than curly braces, the % symbol is used to indicate a placeholder, a %s for a string and %d for a number. After the string, a single % separates the string to be interpolated from the values to be inserted into the string, like so:
hw = "Hello %s" % "world" # with literal values
py = "I love Python %d" % 3
print(hw, py)
# output: Hello world I love Python 3
name = "Zen"
age = 27
print("My name is %s and I'm %d" % (name, age)) # or with variables
# output: My name is Zen and I'm 27
# Built-In String Methods
# We've seen the format method, but there are several more methods that we can run on a string. Here's how to use them:
x = "hello world"
print(x.title()) # this is so weird
# output:
"Hello World"
| true
|
aa9eb750a1e0c98949015dd27e7d2c5ff2805a75
|
MrFichter/RaspSort1
|
/main.py
| 947
| 4.375
| 4
|
#! /usr/bin/python
#sort a file full of film names
#define a function that will return the year a film was made
#split the right side of the line a the first "("
def filmYear(film):
return film.rsplit ('(',1)[1]
#load the file into a list in Python memory
#and then close the file because the content is now in memory
with open ("filmList.txt", "r") as file:
filmList = file.read().splitlines()
#sort by name using library function
##Me: This is one way to sort.
filmList.sort()
#sort by year using key to library function - the film list
#must end with a year in the format (NNNN)
filmList.sort(key=filmYear)
##Me: This is another way to sort.
##'key =' expects a function. Many times, people use lambda
##notation to quickly create a function. The function is called
##'exactly once for each input record.' wiki.python.org/moin/HowTo/Sorting
##More on lambda notation: htt://tinyurl.com/pylambda
for film in filmList:
print (film)
| true
|
16476b4d24d16e37cb1d39f2ba7936024c36049c
|
MrFlava/justforfun
|
/numerical_methods/lab1.py
| 803
| 4.1875
| 4
|
"""
Лабораторная работа #1
Вариант 9
"""
import math
print("Имеется такое нелинейное уравнение : 2*x^2 - 0.5^x -3 = 0")
a = float(input('Введите левую границу: '))
b = float(input('Введите правую границу: '))
epsi = 0.0001
f = lambda x: 2*math.pow(x,2) - math.pow(0.5, x) - 3
def main(a, b, f):
x = (a + b)/2
while math.fabs(f(x)) >= epsi:
x = (a + b)/2
a, b = (a,x) if f(a)*f(x) < 0 else (x,b)
print('a = ',float('{:.3f}'.format(a)),'; b = ',float('{:.3f}'.format(b)),'; x = ', float('{:.3f}'.format(x)),'; f(x) = ',float('{:.3f}'.format(f(x))))
return (a+b)/2
print('В итоге, ответом можно считать значение: ',main(a,b,f))
| false
|
e5e977a9161532cc3edbc877583722fedb5237f2
|
habib-zawad/temperature_converter
|
/Temperature_converter.py
| 1,389
| 4.34375
| 4
|
type1 = input("What type of temperature you want to convert: ")
type2 = input("What type of temperature you want to convert to: ")
temp1 = int(input("Give any temparature: "))
def celsius() :
celsius_to_kelvin = ((temp1*100)/5) - 273
celsius_to_fahrenheit = ((temp1*9)/5)+32
if type2 == "kelvin" :
print(f"Your Given Temperature in kelvin is: {celsius_to_kelvin}")
elif type2 == "fahrenheit":
print(f"Your Given Temperature in fahrenheit is: {celsius_to_fahrenheit}")
def fahrenheit() :
fahrenheit_to_kelvin = (100*(temp1-32)/9)+273
fahrenheit_to_celsius = 5/9 * (temp1 - 32)
if type2 == "celsius" :
print(f"Your Given Temperature in celsius is: {fahrenheit_to_celsius}")
elif type2 == "kelvin" :
print(f"Your Given Temperature in kelvin is: {fahrenheit_to_kelvin}")
def kelvin() :
kelvin_to_fahrenheit = (9*(temp1-273)/100)-32
kelvin_to_celsius = ((temp1 - 273)*5)/100
if type2 == "fahrenheit":
print(f"Your Given Temperature in fahrenheit is: {kelvin_to_fahrenheit}")
elif type2 == "celsius" :
print(f"Your Given Temperature in celsius is: {kelvin_to_celsius}")
if type1 == "celsius":
celsius()
elif type1 == "fahrenheit":
fahrenheit()
elif type1 == "kelvin":
kelvin()
else:
print("Your Given Type is not in our database")
| false
|
6f45f96db8842b4d33ac2b175bd374be223586fb
|
Jatin345Anand/Python
|
/AdvancePython/Regex/02-EmailValidate.py
| 215
| 4.125
| 4
|
import re
pattern = '([a-z | 0-9]\w+([.]\w+)|(\w+))([@]\w+([. | -]\w+)+|([.]\w+))'
email_id = input("Enter emailID : ")
if re.match(pattern, email_id):
print("Email Valid")
else:
print("Invalid")
| false
|
5fa02380f2b135d461422edd160ce54ce6155bfc
|
Jatin345Anand/Python
|
/CorePython_Evening/Programs/02-Patterns.py
| 299
| 4.1875
| 4
|
# for i in range(1,6):
# print("*" * i)
# for i in reversed(range(1,6)):
# print("*" * i)
# for i in range(1,7):
# for j in range(1,i+1):
# print(i, end="")
# print()
for i in range(0,5):
for j in range(1,6):
print(j, end="-----")
print()
| false
|
78aa440d42b3f7014e1b789c18f2e7eff465fbce
|
tanigawahcu/Algorithm-Queue-Python-List-Standard
|
/my_queue3.py
| 1,277
| 4.25
| 4
|
# 参考URL
# - https://note.nkmk.me/python-collections-deque/
#
from collections import deque
class MyQueue:
def __init__(self):
self.arr = deque()
# enqueue
def enqueue(self, val):
self.arr.append(val)
# dequeue
def dequeue(self) :
return self.arr.popleft()
# スタックの中身を文字列に変換
def to_string(self):
return self.arr.__str__()
if __name__ == "__main__" :
# 最大の大きさが6の空のキューを生成
my_queue = MyQueue()
# enqueue前のキューの状態を表示
print("enqueue前のキューの状態")
print("値: ", my_queue.to_string())
print()
# 要素のプッシュ
my_queue.enqueue(6)
my_queue.enqueue(2)
my_queue.enqueue(3)
my_queue.enqueue(7)
my_queue.enqueue(9)
# enqueue後のキューの状態を表示
print("enqueue後のキューの状態")
print("値: ", my_queue.to_string())
print()
# dequeue 2回
x = my_queue.dequeue()
print("dequeueした値:",x)
y = my_queue.dequeue()
print("dequeueした値:",y)
print()
# dequeue 後のキューの状態を表示
print("enqueue後のキューの状態")
print("値: ", my_queue.to_string())
print()
| false
|
24f0d8e088b03f8cf0f4b9d56b1b60cc46e43475
|
zhoubofsy/persistence_calculation
|
/common.py
| 563
| 4.15625
| 4
|
#!/usr/bin/env python2.7
# coding:utf-8
#
# 计算阶乘方法
#
def factorial(n, s = 1):
if n <= 1 or n < s :
return 1
return reduce(lambda x,y:x*y, range(s,n+1))
#
# 计算组合方法
#
def combination(up,down):
if up > down:
return -1
result = factorial(down) / (factorial(up) * factorial(down - up))
return result
if __name__ == '__main__':
# test factorial
ret = factorial(3)
print("factorial(3) = %d" % ret)
# test combination
ret = combination(3,5)
print("combination(3,5) = %d" % ret)
| false
|
5ddd37de5416a1aca026182914fc7ea873916c5b
|
NataliaMiroshnik/GeekBrains
|
/HW3/task4.py
| 671
| 4.1875
| 4
|
x = float(input('Введите положительное число'))
while x < 0:
x = float(input('Упс. Введено отрицательное число. Введите еще раз положительно число'))
y = int(input('Введите отрицательно число'))
while y > 0:
y = int(input('Упс. Введено положительно число. Введите еще раз отрицательно число'))
# def my_func= lambda x, y: x ** y
def my_func(x, y):
count = 0
result = 1
while count != (-y):
result *= (1/x)
count +=1
return result
print(my_func(x, y))
#print(pow(x,y))
| false
|
df80aedb4695956eb49f9be9b4954eaa246f951e
|
PeaWarrior/learn-py
|
/ex_07/ex_07_02.py
| 914
| 4.28125
| 4
|
# Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
# X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
# Enter the file name: mbox.txt
# Average spam confidence: 0.894128046745
# Enter the file name: mbox-short.txt
# Average spam confidence: 0.750718518519
fileHandle = open(input('Enter the file name: '))
sum = 0
count = 0
for line in fileHandle :
if 'X-DSPAM-Confidence:' in line :
firstSpaceInLine = line.find(' ')
sum = sum + float(line[firstSpaceInLine + 1 : ].rstrip())
count = count + 1
print('Average spam confidence:', sum/count)
| true
|
469b980fe77547f9eb561ce3f32765d59fe955b7
|
PeaWarrior/learn-py
|
/ex_12/ex_12_04.py
| 716
| 4.125
| 4
|
# Exercise 4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved HTML document and display the count of the paragraphs as the output of your program. Do not display the paragraph text, only count them. Test your program on several small web pages as well as some larger web pages.
# http://dr-chuck.com/dr-chuck/resume/bio.htm
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter URL: ')
html = urlopen(url, context=ctx)
soup = BeautifulSoup(html, 'html.parser')
print('Number of p tags:', len(soup('p')))
| true
|
dda3db3cfe5bc83d4fe5e6f2fc0b8390b612d190
|
carlosbognar/Estudos
|
/IF-Aninhamento.py
| 234
| 4.1875
| 4
|
# Exemplo de ANINHAMENTO de IF
x = int(input("Entre com um numero inteiro: "))
if x < 0:
x = 0
print("Negativo foi alterado para zero")
elif x == 0:
print("Zero")
elif x == 1:
print("Single")
else:
print("More")3
| false
|
3a0901237a66a5715908ee743799495d3fb0585a
|
carlosbognar/Estudos
|
/Strings-Find-Text.py
| 550
| 4.40625
| 4
|
#########################################################################
# O método FIND permite encontrar um texto / substring em um string
# FIND retorna a posição em que o texto foi encontrado
# Se o valor não for encontrado, retorna -1
########################################################################
s1 = 'Eu gosto de programar em Python'
print(s1.find("E")) # irá retornar o valor 0 --> primeira posição
print(s1.find("gosto")) # irá retornar o valor 3
print(s1.find("x")) # x não existe no string, logo retorna -1
| false
|
a26b5cd237a7e7b869ccaca6b95de07006966e8f
|
carlosbognar/Estudos
|
/Listas-Pilha.py
| 626
| 4.34375
| 4
|
# O Objetivo é utilizar uma Lista como Pilha (STACK)
# POP-Lista: Retira um elemento da Pilha (POP)
a = [1, 12, 8, 23, -45, 7, 6, 10, 'Carlos', 'Eduardo']
a.pop() # Retira o elemento 'Eduardo' da Lista - Último
a.pop() # Retira o elemento 'Carlos da Lista - Último
a.pop() # Retira o elemento 10 da Lista - Último
for x in a:
print(x, end=' ')
print()
a.append(34) # Insere o elemento 34 no final da Lista
for x in a:
print(x, end=' ')
# Exemplo de retirada de um elemento de uma posição especifica da Lista
print()
a.pop(2) # Retira o segundo elemento da Lista
for x in a:
print(x, end=' ')
| false
|
b987329024f5b6288fe91e12fc6ca46c605c5440
|
carlosbognar/Estudos
|
/Listas-Append-List.py
| 338
| 4.34375
| 4
|
# APPEND-Lista: Adiciona uma uma Lista em outra Lista.
# Note que a Lista adicionada é tratada como um único elemento
a = [1, 2, 12, 23, 45, 67, 'Carlos', 'Eduardo']
b = ['x', 'y', 'z']
a.append(b) # Adiciona a lista b na lista a. A lista b é tratada como um único elemento
for x in a:
print(x, end=' ')
print()
print(a[-1])
| false
|
ef208f4362977df250747f5406710b1c60264887
|
carlosbognar/Estudos
|
/Strings-Number-Of-Worlds.py
| 374
| 4.15625
| 4
|
#########################################################################
# O método LEN combinado com o método SPLIT permite a contagem do número
# de palavras em uma determinada linha
########################################################################
s = input("Entre com uma linha de texto: ")
print("O numero de palavras na linha é %d " % (len(s.split(" "))))
| false
|
066da0f2759113dc0b1289705f92311fe6abb01e
|
JamieJ12/Team-23
|
/Functions/Function_6.py
| 2,655
| 4.15625
| 4
|
def word_splitter(df):
"""
The function splits the sentences in a dataframe's column into
a list of the separate words.:
Arguments: The variable 'df' is the pandas input.
Returns: df with the added column named 'Splits Tweets'
Example:
Prerequites:
>>> twitter_url = 'https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/twitter_nov_2019.csv'
>>> twitter_df = pd.read_csv(twitter_url)
Inputs:
>>>twitter_df.copy().head()
Tweets Date
0 @BongaDlulane Please send an email to mediades... 2019-11-29 12:50:54
1 @saucy_mamiie Pls log a call on 0860037566 2019-11-29 12:46:53
2 @BongaDlulane Query escalated to media desk. 2019-11-29 12:46:10
3 Before leaving the office this afternoon, head... 2019-11-29 12:33:36
4 #ESKOMFREESTATE #MEDIASTATEMENT : ESKOM SUSPEN... 2019-11-29 12:17:43
>>>word_splitter(twitter_df.copy())
Output
Tweets Date Split Tweets
0 @BongaDlulane Please send an email to mediades... 2019-11-29 12:50:54 [@bongadlulane, please, send, an, email, to, m...
1 @saucy_mamiie Pls log a call on 0860037566 2019-11-29 12:46:53 [@saucy_mamiie, pls, log, a, call, on, 0860037...
2 @BongaDlulane Query escalated to media desk. 2019-11-29 12:46:10 [@bongadlulane, query, escalated, to, media, d...
3 Before leaving the office this afternoon, head... 2019-11-29 12:33:36 [before, leaving, the, office, this, afternoon...
4 #ESKOMFREESTATE #MEDIASTATEMENT : ESKOM SUSPEN... 2019-11-29 12:17:43 [#eskomfreestate, #mediastatement, :, eskom, s...
... ... ... ...
195 Eskom's Visitors Centres’ facilities include i... 2019-11-20 10:29:07 [eskom's, visitors, centres’, facilities, incl...
196 #Eskom connected 400 houses and in the process... 2019-11-20 10:25:20 [#eskom, connected, 400, houses, and, in, the,...
197 @ArthurGodbeer Is the power restored as yet? 2019-11-20 10:07:59 [@arthurgodbeer, is, the, power, restored, as,...
198 @MuthambiPaulina @SABCNewsOnline @IOL @eNCA @e... 2019-11-20 10:07:41 [@muthambipaulina, @sabcnewsonline, @iol, @enc...
199 RT @GP_DHS: The @GautengProvince made a commit... 2019-11-20 10:00:09 [rt, @gp_dhs:, the, @gautengprovince, made, a,...
"""
# Get Tweets from DataFrame
tweets = df["Tweets"].to_list()
# Split the Tweets into lowercase words
split_tweets = [tweet.lower().split() for tweet in tweets]
# Add Split Tweets to own column
df["Split Tweets"] = split_tweets
return df
| true
|
4617883396bfe24d19ab40f77451291f088721ec
|
yuanxu-li/careercup
|
/chapter6-math-and-logic-puzzles/6.8.py
| 1,714
| 4.28125
| 4
|
# 6.8 The Egg Drop Problem: There is a building of 100 floors. If an egg drops
# from the Nth floor or above, it will break. If it's dropped from any floor
# below, it will not break. You're given two eggs. Find N, while minimizing the
# number of drops for the worst case.
# Here I denote floors from 0 to 99
import random
import math
import pdb
def brute_force():
n = random.randint(0, 100)
for i in range(100):
if i == n:
return i
drops = 0
break_floor = 20
def drop(floor):
global drops
drops += 1
return floor >= break_floor
def find_breaking_floor(k):
""" When we use egg1, we could skip floors each time and reduce the range, like when we drop egg1 from 10th floor it is Ok,
but broken from 20th floor, then we should search from 11th floor through 19th floor using egg2. Because egg2 is our last choice,
we should use the safest linear search. Then how should we minimize the total number of drops for the worst case?
The idea to keep drops(egg1) + drops(egg2) steady, meaning to keep the worst case almost the same as the best case. Then each time
we drop egg1 one more time adding drop(egg1) by 1, we should reduce the increment by 1 thus reducing drop(egg2) by 1.
>>> find_breaking_floor(30)
30
>>> find_breaking_floor(50)
50
>>> find_breaking_floor(70)
70
"""
global break_floor
global drops
break_floor = k
interval = 14
previous = 0
egg1 = interval
drops += 1
# drop egg1
while not drop(egg1) and egg1 <= 100:
interval -= 1
previous = egg1
egg1 += interval
# drop egg2
egg2 = previous + 1
while egg2 < egg1 and egg2 <= 100 and not drop(egg2):
egg2 += 1
return -1 if egg2 > 100 else egg2
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
89b2cab05c4ecf1a2a10c60fa306ef7f8ea79bed
|
yuanxu-li/careercup
|
/chapter16-moderate/16.24.py
| 845
| 4.15625
| 4
|
# 16.24 Pairs with Sum: Design an algorithm to find all pairs of integers within
# an array which sum to a specified value.
from collections import Counter
def pairs_with_sum(arr, k):
"""
put all elements into a Counter (similar to a dict), for each value, search for the complementary value
>>> pairs_with_sum([1, 2, 3, 1, 5, 3, 4, 9, 4, 6, 2, 2, 2, 2], 4)
[[1, 3], [1, 3], [2, 2], [2, 2]]
"""
c = Counter(arr)
result = []
while c:
value1, count1 = c.popitem()
# the value matches itself
if k - value1 == value1:
for _ in range(count1 // 2):
result.append([value1, value1])
# find matching value
count2 = c.pop(k - value1, None)
if count2 is None:
continue
for _ in range(min(count1, count2)):
result.append([value1, k - value1])
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
3bf4269c79a0b223fad38ae3a178a5e7c5212fe2
|
yuanxu-li/careercup
|
/chapter10-sorting-and-searching/10.2.py
| 966
| 4.46875
| 4
|
# 10.2 Group Anagrams: Write a method to sort an array of strings so that all the anagrams are
# next to each other.
from collections import defaultdict
def group_anagrams(strings):
"""
create a dict to map from a sorted string to a list of the original strings, then simply all strings mapped
by the same key will be grouped together. If the length of string are considered constant, time complexity
is only O(n), since we only have to loop over the array twice, first time to generate the dict, second time
to loop over the keys to group anagrams mapped by the same key
>>> group_anagrams(["asd", "atr", "tar", "pppp", "dsa", "rta", "eryvdf"])
['atr', 'tar', 'rta', 'asd', 'dsa', 'pppp', 'eryvdf']
"""
d = defaultdict(list)
for s in strings:
sorted_s = "".join(sorted(s))
d[sorted_s].append(s)
new_strings = []
for sorted_s in d:
new_strings.extend(d[sorted_s])
return new_strings
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
7837501cf9c4e8589734f09883875d0fff5c2062
|
yuanxu-li/careercup
|
/chapter8-recursion-and-dynamic-programming/8.4.py
| 1,436
| 4.25
| 4
|
# 8.4 Power Set: Write a method to return all subsets of a set.
def power_set(s, memo=None):
""" For a set, each we add it to the final list, and run the algorithm against its one-item-less subset
>>> power_set(set([1,2,3,4,5]))
[{1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}, set(), {4}, {3, 5}, {3}, {3, 4}, {2, 4, 5}, {2, 5}, {2}, {2, 4}, {2, 3, 5}, {2, 3}, {2, 3, 4}, {1, 3, 4, 5}, {1, 4, 5}, {1, 5}, {1}, {1, 4}, {1, 3, 5}, {1, 3}, {1, 3, 4}, {1, 2, 4, 5}, {1, 2, 5}, {1, 2}, {1, 2, 4}, {1, 2, 3, 5}, {1, 2, 3}, {1, 2, 3, 4}]
"""
returned = False
if memo is None:
memo = []
returned = True
if s not in memo:
memo.append(s)
for elem in s:
power_set(s - set([elem]), memo)
if returned == True:
return memo
def power_set_updated(s):
"""
Actually the previous method is a top-down approach, and now let's consider a bottom-up approach. Since it is
bottom-up, we do not have to worry about the duplicated cases and thus can ignore memo. We start from
when set size is 0, 1, 2, up to n.
>>> power_set_updated(set([1,2,3,4,5]))
"""
# base case
if len(s) == 0:
return [set()]
# recursive case
item = s.pop()
all_subsets = power_set_updated(s)
more_subsets = []
for subset in all_subsets:
new_subset = subset.copy()
new_subset.add(item)
more_subsets.append(new_subset)
all_subsets.extend(more_subsets)
return all_subsets
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
858dd659ac6bb2648fca973c6695abcdccddd951
|
yuanxu-li/careercup
|
/chapter5-bit-manipulation/5.8.py
| 1,585
| 4.28125
| 4
|
# 5.8 Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels
# to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split
# across rows). The height of the screen, of course, can be derived from the length of the array and the width.
# Implement a function that draws a horizontal line from (x1, y) to (x2, y).
# The method signature should look something like:
# drawLine(byte[] screen, int width, int x1, int x2, int y)
import pdb
def draw_line(screen, width, x1, x2, y):
""" find the indices of x1 and x2, fix the bytes of x1 and x2 and in between.
>>> screen = [0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> draw_line(screen, 24, 4, 22, 1)
>>> screen[3]
15
>>> screen[4]
255
>>> screen[5]
254
"""
if width % 8 != 0:
raise Exception("width is not multiple of 8!")
x1_ind = y * (width // 8) + x1 // 8
x1_offset = x1 % 8
x2_ind = y * (width // 8) + x2 // 8
x2_offset = x2 % 8
# fix the bytes between x1 and x2
for ind in range(x1_ind + 1, x2_ind):
screen[ind] = 255
# if x1 and x2 are in different bytes
if x1_ind != x2_ind:
# fix the byte of x1
mask = (1 << (8 - x1_offset)) - 1
screen[x1_ind] |= mask
# fix the byte of x2
mask = (1 << (x2_offset + 1)) - 1
mask <<= (8 - x2_offset - 1)
screen[x2_ind] |= mask
# if x1 and x2 are in the same byte
else:
mask1 = (1 << (8 - x1_offset)) - 1
mask2 = (1 << (x2_offset + 1)) - 1
mask2 <<= (8 - x2_offset - 1)
screen[x1_ind] |= (mask1 & mask2)
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
81a90ce343ff4d49098ada9f12429821aed4e57b
|
yuanxu-li/careercup
|
/chapter16-moderate/16.16.py
| 1,330
| 4.125
| 4
|
# 16.16 Sub Sort: Given an array of integers, write a method to find inices m and n such
# that if you sorted elements m through n, the entire array would be sorted. Minimize n - m
# (that is, find the smallest such sequence).
# EXAMPLE
# Input: 1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19
# Output: (3, 9)
import pdb
def sub_sort_brute_force(arr):
"""
In this method, we simply sort the array, and find the part of the sorted array where it is
different from the original array.
Time Complexity:
1. sorting the array takes O(nlogn)
2. searching from the beginning and end of the array takes O(n)
>>> sub_sort_brute_force([1, 2, 3, 4, 5, 6, 7])
(0, 0)
>>> sub_sort_brute_force([1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19])
(3, 9)
"""
sorted_arr = sorted(arr)
# search from the beginning to find m, where it starts to differ from the original array
m = 0
while m < len(arr):
if sorted_arr[m] != arr[m]:
break
m += 1
# if the sorted array is identical to the original array, which means the original array is already sorted
if m == len(arr):
return (0, 0)
# search from the end to find n, where it starts to differ from the original array
n = len(arr) - 1
while n > m:
if sorted_arr[n] != arr[n]:
break
n -= 1
return (m, n)
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
b49ddf7666de93c2f767510cc8354e4e556009cb
|
yuanxu-li/careercup
|
/chapter8-recursion-and-dynamic-programming/8.10.py
| 1,215
| 4.1875
| 4
|
# 8.10 Paint Fill: Implement the "paint fill" function that one might see on many image editing programs.
# That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color,
# fill in the surrounding area until the color changes from the original color.
def paint_fill(array, row, col, new_color, old_color=None):
"""
>>> array = [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> paint_fill(array, 1, 3, 9)
True
>>> array
[[9, 9, 9, 9], [9, 9, 9, 9], [1, 1, 1, 1], [1, 1, 1, 1]]
"""
# alternative for initial call
if old_color is None:
old_color = array[row][col]
# if the point is off limit
if row < 0 or row >= len(array) or col < 0 or col >= len(array[0]):
return False
# if arrives at the border of old color
if array[row][col] != old_color:
return True
# change the color of this point, and recursively change its neighbors
array[row][col] = new_color
paint_fill(array, row+1, col, new_color, old_color)
paint_fill(array, row, col+1, new_color, old_color)
paint_fill(array, row-1, col, new_color, old_color)
paint_fill(array, row, col-1, new_color, old_color)
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
d62dee378aee2ad5621da0821e3d26bb801e741b
|
yuanxu-li/careercup
|
/chapter4-trees-and-graphs/4.3.py
| 1,264
| 4.125
| 4
|
# 4.3 List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the
# nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists)
from collections import deque
class Node:
def __init__(self):
self.left = None
self.right = None
def list_of_depths(self):
"""
>>> n0 = Node()
>>> n1 = Node()
>>> n2 = Node()
>>> n3 = Node()
>>> n4 = Node()
>>> n5 = Node()
>>> n6 = Node()
>>> n7 = Node()
>>> n0.left = n1
>>> n0.right = n2
>>> n1.left = n3
>>> n1.right = n4
>>> n2.left = n5
>>> n2.right = n6
>>> n3.left = n7
>>> l = n0.list_of_depths()
>>> len(l[0])
1
>>> len(l[1])
2
>>> len(l[2])
4
>>> len(l[3])
1
"""
depth_lists = [[self]]
queue = deque()
queue.appendleft(self)
while queue:
temp_list = []
# for a specific depth
while queue:
node = queue.pop()
if node.left:
temp_list.append(node.left)
if node.right:
temp_list.append(node.right)
# if this depth still has nodes
if len(temp_list) > 0:
# store the list of the depth
depth_lists.append(temp_list)
for node in temp_list:
queue.appendleft(node)
return depth_lists
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
905d3e94a6e6ab1bcd68bd26b6839baf5b178bd4
|
yuanxu-li/careercup
|
/chapter1-arrays-and-strings/1.7.py
| 1,623
| 4.34375
| 4
|
# 1.7 Rotate Matrix: Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate
# the image by 90 degrees. Can you do this in place?
def rotate_matrix(matrix):
""" Take a matrix (list of lists), and rotate the matrix clockwise
>>> rotate_matrix([[1,2,3],[4,5,6],[7,8,9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
>>> rotate_matrix([])
[]
"""
length = len(matrix)
# first, flip along the main diagonal
for i in range(length):
for j in range(i+1, length):
# swap two elements
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# second, flip left and right
for i in range(length):
for j in range(int(length/2)):
# swap two elements
matrix[i][j], matrix[i][length-1-j] = matrix[i][length-1-j], matrix[i][j]
return matrix
def rotate_matrix_modified(matrix):
""" Rotate a matrix with a layer-by-layer approach
>>> rotate_matrix_modified([[1,2,3],[4,5,6],[7,8,9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
>>> rotate_matrix_modified([])
[]
"""
length = len(matrix)
for layer in range(int(length / 2)):
for i in range(length - 1 - layer):
# left, top, right, bottom <- bottom, left, top, right
offset = layer + i
matrix[length - 1 - offset][layer],\
matrix[layer][offset],\
matrix[offset][length - 1 - layer],\
matrix[length - 1 - layer][length - 1 - offset]\
=\
matrix[length - 1 - layer][length - 1 - offset],\
matrix[length - 1 - offset][layer],\
matrix[layer][offset],\
matrix[offset][length - 1 - layer]
return matrix
def main():
import doctest
doctest.testmod()
if __name__ == "__main__":
main()
| true
|
0db6f0e7aaf5666e4b839fc40d977672988b32cd
|
yuanxu-li/careercup
|
/chapter10-sorting-and-searching/10.4.py
| 1,487
| 4.15625
| 4
|
# 10.4 Sorted Search, No size: You are given an array-like data structure Listy which lacks a size method. It does, however,
# have an elementAt(i) method that returns the element at index i in O(1) time. If i is beyond the bounds of the data structure,
# it returns -1. (For this reason, the data structure only supports positive integers.) Given a Listy which contains sorted,
# positive integers, find the index at which an element x occurs. If x occurs multiple times, you may return any index.
def find_index(arr, x):
"""
The naive approach is O(n) by searching through the entire array.
A better approach would be using binary search, but one problem remains:
we do not know the array length.
Therefore we split this problem into two steps:
1. find the length n in O(logn) time, by increasing n from 1, to 2, 4, 8
until element_at returns -1 which means it is out of bound
2. apply binary search to this array in O(logn)
>>> find_index([1,2,5,7,9,10], 9)
4
>>> find_index([1,2,5,7,9,10], 3)
-1
"""
# find the length
n = 1
while element_at(arr, n) != -1:
n *= 2
# binary search
low = 0
high = n - 1
while low <= high:
mid = (low + high) // 2
mid_value = element_at(arr, mid)
if mid_value == x:
return mid
elif mid_value > x or mid_value == -1:
high = mid - 1
else:
low = mid + 1
return -1
def element_at(arr, i):
if i in range(len(arr)):
return arr[i]
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
cfe6b37df8a61267c86f0623c3c3cec9b1f495a3
|
RenanGouveia/LingProg
|
/2018 09 18/ativ1.py
| 1,069
| 4.28125
| 4
|
"""
Crie a classe Linha que tem dois atributos, coordenada1 e coordenada2.
Cada coordenada é uma tupla que carrega duas coordenadas cartesianas (x,y) que
denotam pontos do segmento de reta. Faça métodos que calculem o comprimento
do segmento de reta e sua inclinação.
"""
class Linha:
def __init__(self, coordenada1, coordenada2):
self.coordenada1 = coordenada1
self.coordenada2 = coordenada2
def calculo():
x1 = int(input(f'Digite o valor de x1: '))
y1 = int(input(f'Digite o valor de y1: '))
x2 = int(input(f'Digite o valor de x2: '))
y2 = int(input(f'Digite o valor de y2: '))
coordenada1 = (x1, y1)
coordenada2 = (x2, y2)
try:
horizontal = coordenada2[1] - coordenada1[1]
vertical = coordenada2[0] - coordenada1[0]
comprimento = ((horizontal ** 2) + (vertical ** 2) ** (1/2))
print('Inclinação da Reta: ', horizontal/vertical, 'Comprimento: ', comprimento)
except IOError:
print('Não deu certo')
finally:
print('Finally deu certo')
calculo()
| false
|
594c8696b31b94ca23f15fdb499fa79a08c970fe
|
Mythologos/Pythonic-Pursuits-Course-Material
|
/Exercise Answers/Lecture 2 & Bridge 2 - Sample Answers/tenChallenge.py
| 718
| 4.125
| 4
|
# Lecture 2, Exercise 3:
def when_ten_v2(number):
if number == 10:
print("Done!")
elif number > 10:
print("Too high!")
when_ten_v2(number - 1)
else:
print("Too low!")
when_ten_v2(number + 1)
def when_ten_v3(number):
difference: int = number - 10
if difference == 0:
print("Done!")
elif difference > 0:
print("Too high!")
number = number - difference
elif difference < 0:
print("Too low!")
number = number - difference
print(number)
print(difference)
print("when_ten_v2:")
when_ten_v2(10)
when_ten_v2(15)
when_ten_v2(5)
print("")
print("when_ten_v3:")
when_ten_v3(10)
when_ten_v3(15)
when_ten_v3(5)
| false
|
7c0e1d9a77cfb59763f5067ce087deb67eeb2181
|
w4jbm/Python-Programs
|
/primetest.py
| 1,018
| 4.125
| 4
|
#!/usr/bin/python3
# Based on code originally by Will Ness:
# https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621
#
# and updated by Tim Peters.
#
# https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621
#
def psieve():
import itertools
yield from (2, 3, 5, 7)
D = {}
ps = psieve()
next(ps)
p = next(ps)
assert p == 3
psq = p*p
for i in itertools.count(9, 2):
if i in D: # composite
step = D.pop(i)
elif i < psq: # prime
yield i
continue
else: # composite, = p*p
assert i == psq
step = 2*p
p = next(ps)
psq = p*p
i += step
while i in D:
i += step
D[i] = step
# Driver code to check above generator function
for value in psieve():
print(value)
| true
|
d2dcd6ce2a0e54b4c95acca0dafb9d3aa95c8920
|
lxw0109/JavaPractice
|
/Sort/Bubble/pBubble.py
| 1,235
| 4.21875
| 4
|
#!/usr/bin/python2.7
#File: pBubble.py
#Author: lxw
#Time: 2014-09-19 #Usage: Bubble sort in Python.
import sys
def bubbleSort(array):
bound = len(array) - 1
while 1:
i = 0
tempBound = 0
swap = False
while i < bound:
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
tempBound = i
swap = True
i += 1
if swap:
bound = tempBound
else:
break
def main():
print("---------------------------------------------")
print("| Usage: Program ArrayLength |")
print("| If no ArrayLength offered, 5 is default. |")
print("---------------------------------------------\n")
arrSize = 5
argc = len(sys.argv)
if argc == 2:
arrSize = int(sys.argv[1])
elif argc != 1:
sys.exit("Too much parameters.")
numbers = []
print("Input {} numbers:(each line with only 1 number) ".format(arrSize))
for i in range(arrSize):
number = input()
numbers.append(number)
bubbleSort(numbers)
print(numbers)
if __name__ == '__main__':
main()
else:
print("Being imported as a module.")
| true
|
b06883d59473eb92521e61b581674978f79755f5
|
TylorAtwood/Hi-Lo-Game
|
/Hi_Lo_Game.py
| 1,455
| 4.34375
| 4
|
#!/usr/bin/env python3
#Tylor Atwood
#Hi-Lo Game
#4/14/20
#This is a def to inlcude the guessing game.
def game():
#Immport random library
import random
#Declare varibles. Such as max number, generated random number, and user's number guess
max = int(input("What should the maximum number for this game be?: "))
print("\n")
num = random.randint(1,max)
guess = int(input("Guess my number: "))
#While loop for guessing number
while guess != num:
if guess > num:
print("Your guess is too high") #Number is higher than generated random number
print("\n")
guess = int(input("Guess my number: "))
if guess < num:
print("Your guess is too low")#Number is lower than generated random number
print("\n")
guess = int(input("Guess my number: "))
if guess == num:
print("You guessed my number!") #User guess the number right
print("\n")
restart = input("Do you wish to play again? (Y/N)") #Asking the user to restart guessing game. This is why I declared the game as a def.
if restart == "Y":
game() #restarts game. Goes back to the top of the program.
else: print("Thanks for playing!") #If the user does not want to restart. It ends the program
exit #Exits program
game()
| true
|
4633ab38739af5a13ff2c08c368d59fbb2ad0646
|
qianrongping/python_xuexi
|
/Python_基础/python_数据类型转换.py
| 213
| 4.1875
| 4
|
# 5. eval() --计算在字符串中的有效Python表达式,并返回一个对象
str2 = '1'
str3 = '1.1'
str4 = '(1000,2000,3000) '
str5 = '[1000,2000,3000]'
print(type(eval(str2)))
print(type(eval(str3)))
| false
|
14703a10efdf73974802db15a4d644aa7b9854ea
|
Garima2997/All_Exercise_Projects
|
/PrintPattern/pattern.py
| 327
| 4.125
| 4
|
n = int(input("Enter the number of rows:"))
boolean = input("Enter True or False:")
if bool:
for i in range(0, n):
for j in range(i + 1):
print("*", end=" ")
print("")
else:
for i in range(n, 0, -1):
for j in range(i):
print("*", end=" ")
print("")
| true
|
2587f2a265238875e932ffcbaaa1b028abbf7929
|
Jakksan/Intro-to-Programming-Labs
|
/Lab8 - neighborhood/pythonDrawingANeighborhood/testingShapes.py
| 1,890
| 4.15625
| 4
|
from turtle import *
import math
import time
def drawTriangle(x, y, tri_base, tri_height, color):
# Calculate all the measurements and angles needed to draw the triangle
side_length = math.sqrt((0.5*tri_base)**2 + tri_height**2)
base_angle = math.degrees(math.atan(tri_height/(tri_base/2)))
top_angle = 180 - (2 * base_angle)
# Lift pen to prevent stray lines
penup()
# Go to some x and y coordinates
goto(x, y)
setheading(0)
# Fill the triangle with some color
fillcolor(color)
begin_fill()
pendown()
# Draw the triangle
forward(tri_base)
left(180 - base_angle)
forward(side_length)
left(180 - top_angle)
forward(side_length)
# Stop filling and lift pen
end_fill()
penup()
def drawRectangle(x, y, rec_width, rect_height, color):
# Lift pen to prevent stray lines
penup()
# Go to some x and y coordinates
goto(x, y)
setheading(0)
# Set fill color, put pen back onto canvas
pendown()
fillcolor(color)
begin_fill()
# Draw the rectangle
for side in range(2):
forward(rec_width)
left(90)
forward(rect_height)
left(90)
# Stop filling and lift pen
end_fill()
penup()
def drawCircle(x, y, radius, color):
# Lift pen to prevent stray lines
penup()
# Go to some x and y coordinates
goto(x, y)
setheading(0)
setpos(x, (y-radius))
# Put pen down, then start filling
pendown()
fillcolor(color)
begin_fill()
# Draw the circle
circle(radius)
# Stop filling and lift pen
end_fill()
penup()
# drawTriangle(60, 60, 25, 40, "blue")
# drawTriangle(100, -100, 70, 20, "pink")
#
# drawRectangle(60, -60, 60, 40, "yellow")
# drawRectangle(-100, 100, 25, 60, "green")
#
# drawCircle(-60, 60, 15, "green")
# drawCircle(150, 120, 30, "purple")
input()
| true
|
8d6fb45b0bc9753d718e558815a6e70178db88fd
|
Vasilic-Maxim/LeetCode-Problems
|
/problems/494. Target Sum/3 - DFS + Memoization.py
| 1,041
| 4.1875
| 4
|
class Solution:
"""
Unlike first approach memoization can make the program significantly faster then.
The idea is to store results of computing the path sum for each level in some data
structure and if there is another path with the same sum for specific level than
we already knew the number of paths which will match the target value. That
phenomena appears only if one value is repeated several times in 'nums' list.
"""
def findTargetSumWays(self, nums: list, target: int) -> int:
return self.calculate(nums, target, 0, 0, {})
def calculate(self, nums: list, target: int, val: int, lvl: int, memo: dict) -> int:
if lvl >= len(nums):
return int(val == target)
key = f"{lvl}-{val}"
if key in memo:
return memo[key]
left_sum = self.calculate(nums, target, val - nums[lvl], lvl + 1, memo)
right_sum = self.calculate(nums, target, val + nums[lvl], lvl + 1, memo)
memo[key] = left_sum + right_sum
return memo[key]
| true
|
5fa3c31eda3e66eeb0fb0de5b7d11f90b03eea6e
|
notsoseamless/python_training
|
/algorithmic_thinking/Coding_activities/alg_further_plotting_solution.py
| 1,138
| 4.15625
| 4
|
"""
Soluton for "Plotting a distribution" for Further activities
Desktop solution using matplotlib
"""
import random
import matplotlib.pyplot as plt
def plot_dice_rolls(nrolls):
"""
Plot the distribution of the sum of two dice when they are rolled
nrolls times.
Arguments:
nrolls - the number of times to roll the pair of dice
Returns:
Nothing
"""
# initialize things
rolls = {}
possible_rolls = range(2, 13)
for roll in possible_rolls:
rolls[roll] = 0
# perform nrolls trials
for _ in range(nrolls):
roll = random.randrange(1, 7) + random.randrange(1, 7)
rolls[roll] += 1
# Normalize the distribution to sum to one
roll_distribution = [rolls[roll] / float(nrolls)
for roll in possible_rolls]
# Plot the distribution with nice labels
plt.plot(possible_rolls, roll_distribution, "bo")
plt.xlabel("Possible rolls")
plt.ylabel("Fraction of rolls")
plt.title("Distribution of rolls for two six-sided dice")
plt.show()
plot_dice_rolls(10000)
| true
|
c2a0a60091658bb900d0fcf3c629c3f284288fa5
|
dennisjameslyons/magic_numbers
|
/15.py
| 882
| 4.125
| 4
|
import random
#assigns a random number between 1 and 10 to the variable "magic_number"
magic_number = random.randint(1, 10)
def smaller_or_larger():
while True:
try:
x = (int(input("enter a number please: ")))
# y = int(x)
except ValueError:
print("Ever so sorry but I'm going to need a number.")
continue
else:
break
if x < magic_number:
print("guess too small. guess some more.")
return smaller_or_larger()
elif x > 10:
print("make sure your guess is smaller than 11.")
return smaller_or_larger()
elif x > magic_number:
print("guess too great. try again, you'll get it.")
return smaller_or_larger()
else:
print("Cherrio, you've done it, the magic number is yours! ")
print(magic_number)
smaller_or_larger()
| true
|
779abded16b15cb8eb80fe3dc0ed36309b9cec59
|
MFahey0706/LocalMisc
|
/N_ary.py
| 1,399
| 4.1875
| 4
|
# ---------------
# User Instructions
#
# Write a function, n_ary(f), that takes a binary function (a function
# that takes 2 inputs) as input and returns an n_ary function.
def n_ary_A(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
def n_ary_f(x, *args):
if args: # if not f(x); note this is being called more than needed via recursion
if len(args)> 1: # if not f(x,y)
return f(x, n_ary_f(args[0],*args[1:])) #recursive call, use * to expand tuple to list of args
else:
return f(x, args[0]) #handle f(x,y) case
return x #handle f(x) case
return n_ary_f
def n_ary_B(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
def n_ary_f(x, *args):
if args: # if not f(x), ie f(x,None), or f(x,[]), (which is what args[0:] pnce empty)
return f(x, n_ary_f(args[0],*args[1:])) #recursive call, use * to expand tuple to list of args
return x #handle f(x) case
# return x if not args else f(x, n_ary_f(*args)) <<< conditional return & *args will expand into args[0], *args[1:]
return n_ary_f
t = lambda i,j: i + j
t_seqA = n_ary_A(t)
t_seqB = n_ary_B(t)
print t(2,3)
print t_seqA(1,2,3,4,5)
print t_seqB(1,2,3)
| true
|
4738082f42766a81e204ce364000a790a959fdf1
|
JeffreyAsuncion/PythonCodingProjects
|
/10_mini_projects/p02_GuessTheNumberGame.py
| 917
| 4.5
| 4
|
"""
The main goal of the project is
to create a program that
randomly select a number in a range
then the user has to guess the number.
user has three chances to guess the number
if he guess correct
then a message print saying “you guess right
“otherwise a negative message prints.
Topics: random module, for loop, f strings
"""
import random
high_end = 100
# be able to generate a random number
num = random.randint(1, high_end)
print(num)
guess = int(input("Enter your guess: "))
if guess == num:
print("You Chose Wisely.")
else:
print("You Chose Poorly.")
# import random
# number = random.randint(1,10)
# for i in range(0,3):
# user = int(input("guess the number"))
# if user == number:
# print("Hurray!!")
# print(f"you guessed the number right it's {number}")
# break
# if user != number:
# print(f"Your guess is incorrect the number is {number}")
| true
|
5fdfca0bc449b2c504dbba99a02664f760028b5c
|
gpreviatti/exercicios-python
|
/MUNDO_01/Aula_09/Ex22.py
| 543
| 4.25
| 4
|
#crie um programa que leia o nome completo de uma pessoa e mostre:
# o nome com todas as letras maiúsculas
# o nome com todas as letras minúsculas
# quantas letras ao todo (sem considerar espaços)
# quantas letras tem o primeiro nome
nome = input('Digite seu nome completo ')
print('Nome em maiúsculo {}'.format(nome.upper().strip()))
print('Nome em minúsculo {}'.format(nome.lower().strip()))
print('Quantidade de letras sem espaços: {}'.format(len(nome) - nome.count(' ')))
print('O primeiro nome tem {} letras'.format(nome.find(' ')))
| false
|
38afc6c688dba92012aca122db3c8277b388cd63
|
gpreviatti/exercicios-python
|
/MUNDO_01/Aula_06/Ex04.py
| 650
| 4.125
| 4
|
#faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas suas informações possiveis
algo = input('Digite algo: ')
print('É um número? {}'.format(algo.isnumeric()))
print('É alfabético? {}'.format(algo.isalpha()))
print('É alfanúmerico? {}'.format(algo.isalnum()))
print('É um caracter decimal? {}'.format(algo.isdecimal()))
print('Todos os caracteres estão em mínusculo? {}'.format(algo.islower()))
print('Todos os caracteres estão em maíusculo? {}'.format(algo.isupper()))
print('Existem apenas espaços em branco? {}'.format(algo.isspace()))
print('Pode ser impresso? {}'.format(algo.isprintable()))
| false
|
c25aef7ae5651beae279649a5d46c483132f5351
|
gpreviatti/exercicios-python
|
/MUNDO_02/Aula_12/Ex36.py
| 843
| 4.15625
| 4
|
#escreva um programa para aprovar o emprestimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal sabendo que ela não pode exceder 30% do salário ou então o emprestimo será negado
casaVlr = float(input('Digite o valor total da casa: '))
salario = float(input('Digite o valor do seu salário: '))
anos = int(input('Em quantos anos quer pagar a casa?: '))
prestMens = casaVlr/anos
if prestMens > salario * 0.3:
print('O valor da prestação é de: {} que EXCEDE 30% do seu salario que é de {}'.format(prestMens,salario))
print('EMPRESTIMO NEGADO')
else:
print('O valor da prestação é de: {} que NÃO EXCEDE 30% do seu salario que é de {}'.format(prestMens,salario))
print('EMPRESTIMO CONCEDIDO')
| false
|
ff88f375bd9e0ff5d34a60155fac35faaf3c8329
|
sec2890/Python
|
/Python Fundamentals/bike.py
| 840
| 4.15625
| 4
|
class Bike:
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print("This bike has a price of",self.price,", a maximum speed of",self.max_speed, "and a total of", self.miles, "miles on it.")
return self
def ride(self):
print("Riding")
self.miles += 10
return self
def reverse(self):
print("Reversing")
if self.miles >= 5:
self.miles -= 5
return self
new_bike1 = Bike(199,"25mph")
new_bike1.ride().ride().ride().reverse().displayInfo()
new_bike2 = Bike(399, "32mph")
new_bike2.ride() .ride().reverse().reverse().displayInfo()
new_bike3 = Bike(89, "14mph")
new_bike3.reverse().reverse().reverse().displayInfo()
| true
|
5c39348a5738894cfffbc2784a86f666d11a4b5b
|
orlewilson/poo-rcn04s1
|
/exemplos/1-classe-objeto/exemplo3.py
| 1,029
| 4.34375
| 4
|
"""
Disciplina: Programação Orientada a Objetos
Turma: RCN04S1
Professor: Orlewilson Bentes Maia
Data: 23/08/2016
Autor: Orlewilson B. Maia
Descrição: Exemplo de criação de classe em Python
"""
#Definindo Classe
class Aluno():
#Definição dos atributos
nome = ""
endereco = ""
dataNascimento = ""
nomeCurso = ""
bolsista = False
#Fim da classe Aluno -----------------------------
# Programa Principal
#Criando objeto a partir de uma classe
aluno1 = Aluno()
#Atribuindo valores aos atributos do objeto aluno1
aluno1.nome = input("Digite seu nome:")
aluno1.endereco = input("Digite seu endereço:")
aluno1.dataNascimento = input("Digite sua data de nascimento:")
aluno1.nomeCurso = input("Digite seu curso: ")
aluno1.bolsista = input("Você é bolsista?")
# Imprimir conteúdos do objeto aluno1
print("Nome: " + aluno1.nome + "\n")
print("Endereço: " + aluno1.endereco + "\n")
print("Data Nascimento: " + aluno1.dataNascimento + "\n")
print("Nome Curso: ", aluno1.nomeCurso, "\n")
print("Bolsista: " + str(aluno1.bolsista) + "\n")
| false
|
4c6c69d142032702b7fe7772a642d397f7f8fe3b
|
orlewilson/poo-rcn04s1
|
/exercicios/fibonacci.py
| 478
| 4.25
| 4
|
"""
Disciplina: Programação Orientada a Objetos
Professor: Orlewilson B. Maia
Turma: RCN04S1
Autor: Orlewilson B. Maia
Data: 29/11/2016
Descrição: Classe para representar dados de um
Fibonacci
"""
class Fibonacci():
def fib(self,n):
if (n == 1 or n == 2):
return 1
else:
return self.fib(n-2) + self.fib(n-1)
def imprimirSequencia(self,n):
for x in range (1, n):
print (str(self.fib(x)) + " + ", end='')
print ("")
teste = Fibonacci()
teste.imprimirSequencia(10)
| false
|
31a8662d4b9af6881f9237ff5fb57287fd792c28
|
CBJNovels/python_study
|
/venv/Training/P3_Training_list.py
| 2,599
| 4.1875
| 4
|
# list=['a','b','c']
# #增加及插入
# list.append('d')
# list.insert(4,'e')
# print(list)
#
# #删除及弹出
# del list[4]
# print(list)
# try:
# print(list[4])
# except:
# print('不存在list[4]')
# #注意修改值要记得存入
# print(list.pop())
# print(list)
# list.pop(2)
# print(list)
# #移出相应值
# try:
# list.remove('b')
# print(list)
# except:
# print('列表只剩一个元素时,则变为元素对应类型的变量')
#组织列表
# list=['b','c','a','d']
# print(list)
# #临时排序
# print(sorted(list),end='')
# print(sorted(list,reverse=True),end='')#逆序输出
# print(list)
# #排序
# list.sort()
# print(list,end='')
# list.sort(reverse=True)
# print(list)
#逆序排列
# list.reverse()
# print(list)
#确定列表长度
# print(len(list))
#输出最后一个元素
# print(list)
# print(list[len(list)-1])
# print(list[-1])
#操作列表
#遍历列表
# list=['a','b','c','d']
# for l in list:
# print(l,end=' ')
#列表元素操作
#Example
# squares=[]
# for value in range(1,11):
# squares.append(value**2)
# print(squares)
# #实验
# list=['please','remember','me']
# for l in list:
# print(l.title(),end=' ')
#列表统计计算
# list=[1,2,3,4,5,6,7,8,9,0]
# print(list)
# print(min(list))
# print(max(list))
# print(sum(list))
#列表解析
#输出1到10的平方
# squares=[value**2 for value in range(1,11)]
# print(squares)
#输出1到10的立方
# squares=[value**3 for value in range(1,11)]
# print(squares)
#百万输出
# squares=[value for value in range(0,1000001)]
# for i in range(0,1000000):
# print(squares[i])
#输出奇数
# squares=[value for value in range(1,21,2)]
# for i in range(0,len(squares)):
# print(squares[i],end=' ')
#输出3的倍数 Unfinshed
# squares=[value%3==0 for value in range(3,31)]
# for i in range(0,len(squares)):
# print(squares[i])
#列表切片
# list=['a','b','c','d']
# print(list)
# print(list[:2])
# print(list[1:])
# print(list[1:3])
# print(list[-len(list):])#len(list)值为4
# for l in list[-3:]:
# print(l.upper(),end=' ')
#复制列表
# list=['1','2','3','4','5']
# l=list[:]#切片复制
# l_relevance=list#直接关联
# list.append('Can you look it?')
# print(list)
# print(l)
# print(l_relevance)#直接关联,操作相互,猜测是地址关联
#元组(元组元素不可修改)
# tuple=('1','2','3','4','5')
# print(tuple)
# try:
# tuple[0]=2
# except:
# print('修改元组第一个元素,修改失败,元组元素不可更改')
# tuple=('a','b','c','d','e')
# print(tuple)
# print('元组变量可更改')
| false
|
14989dacdda1f7c8cf589f5bdf556c9cbcd6db0e
|
fhylinjr/Scratch_Python
|
/learning dictionaries 1.py
| 1,196
| 4.1875
| 4
|
def display():
list={"ID":"23","Name":"Philip"}
print(list)#prints the whole list
for n in list:
print(n)#prints the keys
print(list.keys())#alternative
print(list["Name"])#prints a specific value
print(list.get("Name"))#alternative
'''list["Name"]="Joe"#change a value in a list'''
print(list)
print(list.values())#returns all the values
print(list.items())#returns every item
for x,y in list.items():
print(x,y)#returns items column-wise
print(len(list))#returns number of items
list["Age"]=25#adds new item to list
print(list)
list.pop("Age")#removes item from list
print(list)
list.popitem()#removes last item in list
print(list)
'''del list''' #deletes the whole list
'''list.clear()'''#removes all items and leaves dict. empty
'''list.update({"color":"red"})'''
dict2=list.copy()#copies items from one dictionary to another
dict2=dict(list)#alternative
k=("key1","key2")#attaches keys to values
y=0
list.fromKeys(k,y)
list.setdefault("username","Philip")#first checks if key exist if not then creates this item
display()
| true
|
ef2e6441e658300cd9257daad5b6c31559544330
|
fhylinjr/Scratch_Python
|
/first run.py
| 365
| 4.1875
| 4
|
Age=int(input("Enter your Age"))
if Age>=0 and Age<=1:
print("You are a baby")
elif Age>1 and Age<=3:
print("You are a toddler")
elif Age>3 and Age<=4:
print("You are a toddler and are in preschool")
elif Age>=5 and Age<10:
print("You are in grade school")
elif Age>=10 and Age<18:
print("You are a teenager")
else:
print("You are an adult")
| false
|
4bbadc10900a6ea43dc032411c7d65dca29666e4
|
aevri/mel
|
/mel/lib/math.py
| 2,583
| 4.375
| 4
|
"""Math-related things."""
import math
import numpy
RADS_TO_DEGS = 180 / math.pi
def lerp(origin, target, factor_0_to_1):
towards = target - origin
return origin + (towards * factor_0_to_1)
def distance_sq_2d(a, b):
"""Return the squared distance between two points in two dimensions.
Usage examples:
>>> distance_sq_2d((1, 1), (1, 1))
0
>>> distance_sq_2d((0, 0), (0, 2))
4
"""
assert len(a) == 2
assert len(b) == 2
x = a[0] - b[0]
y = a[1] - b[1]
return (x * x) + (y * y)
def distance_2d(a, b):
"""Return the squared distance between two points in two dimensions.
Usage examples:
>>> distance_2d((1, 1), (1, 1))
0.0
>>> distance_2d((0, 0), (0, 2))
2.0
"""
return math.sqrt(distance_sq_2d(a, b))
def normalized(v):
"""Return vector v normalized to unit length.
Usage examples:
>>> normalized((0, 2))
(0.0, 1.0)
"""
inv_length = 1 / distance_2d((0, 0), v)
return (v[0] * inv_length, v[1] * inv_length)
def angle(v):
"""Return the angle between v and 'right'.
Usage examples:
>>> angle((1, 0))
0.0
>>> angle((-1, 0))
180.0
>>> angle((0, 1))
-90.0
>>> angle((0, -1))
90.0
"""
cos_theta = normalized(v)[0]
theta = math.acos(cos_theta)
if v[1] > 0:
theta = -theta
return rads_to_degs(theta)
def rads_to_degs(theta):
return theta * RADS_TO_DEGS
def raise_if_not_int_vector2(v):
if not isinstance(v, numpy.ndarray):
raise ValueError(
"{}:{}:{} is not a numpy array".format(v, repr(v), type(v))
)
if not numpy.issubdtype(v.dtype.type, numpy.integer):
raise ValueError("{}:{} is not an int vector2".format(v, v.dtype))
# -----------------------------------------------------------------------------
# Copyright (C) 2015-2020 Angelos Evripiotis.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------ END-OF-FILE ----------------------------------
| true
|
b25a60e2013b9451ba7eb8db5ead8f56e5a59fcd
|
Pdshende/-Python-for-Everybody-Specialization-master
|
/-Python-for-Everybody-Specialization-master/Coursera---Using-Python-to-Access-Web-Data-master/Week-6/Extracting Data from JSON.py
| 1,695
| 4.1875
| 4
|
'''
In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553)
Actual data: http://python-data.dr-chuck.net/comments_353540.json (Sum ends with 71)
You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
'''
import time
start = time.time()
import urllib.request, urllib.parse, urllib.error
import json
#Data collection
link = input('Enter location: ')
print('Retrieving', link)
html = urllib.request.urlopen(link).read().decode()
print('Retrieved', len(html), 'characters')
try:
js = json.loads(html)
except:
js = None
cn = 0
sm = 0
for item in js['comments']:
cn += 1
sm += int(item['count'])
print('Count:', cn)
print('Sum:', sm)
end = time.time()
print("The total excecution Time for this code is sec", (end-start))
'''
Output: -
Enter location: http://py4e-data.dr-chuck.net/comments_417438.json
Retrieving http://py4e-data.dr-chuck.net/comments_417438.json
Retrieved 2717 characters
Count: 50
Sum: 2178
The total excecution Time for this code is sec 2.7438461780548096
'''
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.