blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9ece6a57789ce37c67ded0bdb2b2e5cf367d4cb7 | souljudge/studying | /for_loop.py | 237 | 4.15625 | 4 | mylist=["罗乃霞","崔建军","崔虎巡"]
for name in mylist:
print(name)
for number in range(10):
print(number)
#notice:range(10),其实省略了前面的0,range(0,10)才是原样,右边界限的数一般无法输出 | false |
c6508c8a9db4f03fc0e7ddc2a02a23668f028ee6 | souljudge/studying | /list_comprehension.py | 620 | 4.125 | 4 | #list comprehension 列表解析式
#list生成新list的过程就是list comprehension的一种
#我的需求:从0-10的数字分别乘以2,然后放到新的列表里
# newlist=[]
# for i in range(11):
# newlist.append(i*2)
#
# print(newlist)
# print([i*2 for i in range(11)])
# #这个就是列表解析式写法,将4行代码浓缩为1行
list=['崔虎巡','崔建军','罗乃霞','罗小凡','罗乃将']
# emptylist=[]
# for name in list:
# if name.startswith('崔'):
# emptylist.append(name)
# print(emptylist)
print([name for name in list if name.startswith('崔')])
| false |
cfb42c8f3dfa6aa9368953c40094f8c436986b17 | NAKO41/Classes | /Classes practice pt 1.py | 1,082 | 4.125 | 4 | class FireBall(object):
#this is the class object
#it will be used to track weather an attack hits or not
def __init__(self):
#each ball will start at (0,0)
self.y = 0
self.x = 0
def move_forward(self):
self.x += 1
#create a fireball and make it move forward
fire_ball = FireBall()#creats a fireball and makes a variable = to the class
print(fire_ball)#prints a fire ball
print("the attack has moved", fire_ball.x, "spaces forwards")
fire_ball.move_forward()#this moves the fire ball
print("the attack has moved", fire_ball.x, "spaces forwards")
fire_ball.move_forward()#this moves the fire ball
print("the attack has moved", fire_ball.x, "spaces forwards")
#creat a barage of fireballs and store them in a list
fire_balls = []#creates an empty list
for i in range(5):
#creates a fireball
fire_balls.append(fire_ball)#adds the fireball to the list
for i in range(len(fire_balls)):#this loop wil print the list and make every item unique
print(fire_ball, "fire ball", str(int(i + 1)))
| true |
811aef10c87431213551ed5bbe44a23d8957029e | summerfang/study | /collatzconjecture/collatz_recursion.py | 911 | 4.375 | 4 | # 3n + 1 problem is also called Collatz Conjecture. Please refer to https://en.wikipedia.org/wiki/Collatz_conjecture
# Giving any positive integer, return the sequence according to Collatz Conjecture.
collatzconjecture_list = list()
def collatzconjecture(i):
if i == 1:
collatzconjecture_list.append(i)
return
else:
collatzconjecture_list.append(i)
if i % 2 == 0:
collatzconjecture(int(i/2))
else:
collatzconjecture(int(i*3+1))
while True:
input_string = input("Please input a positive integer:")
try:
input_value = int(input_string)
if input_value > 0:
collatzconjecture(input_value)
break
else:
print("This is not a positive integer.\n")
continue
except ValueError:
print("This is not a positive integer.\n")
print(collatzconjecture_list) | true |
95b01804886ecbe5547f8ae70db88fe5a3f34182 | plmon/python-CookBook | /chapter 3/3.7 处理无穷大和NaN.py | 914 | 4.1875 | 4 | # 3.7 处理无穷大和NaN
# 目标:对浮点数的无穷大、负无穷大和NaN(Not a number)进行判断测试
# 解决方案:
a = float('inf')
b = float('-inf')
c = float('nan')
print(a) # inf
print(b) # -inf
print(c) # nan
# 可以使用math.isinf()和math.isnan()函数判断:
import math
result = math.isinf(a)
print(result) # True
result = math.isinf(b)
print(result) # True
result = math.isnan(c)
print(result) # True
# 无穷大值和nan在数学计算中会进行传播:
x = a + 45
print(x) # inf
# 但是inf存在某些特定的操作会导致未定义的行为并产生nan的结果,nan则是所有情况都为nan:
y = a/a
print(y) # nan
z = a + b
print(z) # nan
# nan不会被判定为相等,因此唯一判断是否为nan的方式就是使用math.isnan():
d = float('nan')
result = (c == d)
print(result) # False
result = c is d
print(result) # False
| false |
1cdd49fcc31773c4ca758c91c36ffa87841d184e | unins/K-Mooc | /package_i/calc_rectangular_area.py | 629 | 4.1875 | 4 | def choice():
shape = int(input("type in shape(rectangle = 1, triangle = 2, circle = 3)"))
if shape == 1:
weight = int(input("\ntype in Rectangle Weight:"))
height = int(input("type in Rectangle Height :"))
return print(("Rectangle area is %d") %(weight*height))
elif shape == 2:
weight = int(input("\ntype in Triangle Weight:"))
height = int(input("type in Triangle Height :"))
return print(("Triangle area is %d") %(weight*height/2))
elif shape == 3:
diameter = int(input("\ntype in Circle diameter:"))
return print(("Circle area is %d") %(diameter*diameter*3.14))
else:
print("Wrong number")
choice()
| true |
8f4073779fbac7eed417ef5880e49c2d7093824e | addison-hill/CS-Build-Week-2 | /LeetCode/DecodeString.py | 2,131 | 4.125 | 4 | """
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
stack_letters [""]
stack_nums []
nums "
result_str "acc
n = 3
t = ""
result_str = accaccacc
"""
# Understand - repeat letters in square brackets by the number outside the square brackets and create a string as result
# Plan - There are 4 characters in the string. We can make an edge case for each one while we loop thru
# It makes sense to create a stack for letters and a stack for numbers
# Once you hit a "]" you push onto stack your letters and nums
# Once you hit a "]" you pop off the letters and pop off the number. Then repeat the letters number times and store in result string
def decodeString(self, str1: str) -> str:
stack_letters = [] # letters stack
stack_nums = [] # num stack
num = "" # to keep track of digits
result_str = "" # keep track of letters and return
for i in str1:
if i.isdigit():
num += i
elif i == "[":
stack_letters.append(result_str)
stack_nums.append(int(num))
# reset so that we don't push what we have already pushed again
num, result_str = "", ""
elif i == "]":
n = stack_nums.pop() # get the last number we pushed
t = stack_letters.pop() # get the last letter(s) we pushed
# take what is in result_str and multiply by n, then add to t
result_str = t + result_str * n
else: # it's a letter
result_str += i
return result_str
| true |
a72db85874ec2f1bf62b9407487068709f9ef8f1 | Lawren123/Randomfiles | /Chatbot2.py | 2,866 | 4.1875 | 4 | # --- Define your functions below! ---
# The chatbot introduces itself and gives the user instructions.
def intro():
print("Hi, my name is Phyllis. Let's talk!")
print("Type something and hit enter.")
# Choose a response based on the user's input.
def process_input(answer):
# Define a list of possible ways the user might say hello.
greetings = ["hi", "hello", "hey", "hey there", "sup"]
# Define a list of possible ways the user might say bye.
farewells = ["bye", "see ya", "goodbye", "quit", "exit"]
if is_valid_input(answer, farewells):
say_goodbye()
return True # The user wants to exit!
elif is_valid_input(answer, greetings):
say_greeting()
elif 'joke' in answer:
say_joke()
else:
say_default()
return False # The chatbot will continue asking for user input.
# Display a greeting message to the user.
def say_greeting():
print("Hey there!")
# Display a farewell message to the user.
def say_goodbye():
print("See you next time!")
# Tell the user an interactive knock-knock joke.
def say_joke():
print("Let me tell you a joke!")
# "Knock knock!" "Who's there"?
valid_responses = ["who's there", "whos there", "who's there?", "whos there?"]
done = False
while not done:
answer = input("Knock knock! ")
answer = answer.lower()
if not is_valid_input(answer.lower(), valid_responses):
print("No, you're supposed to say, 'Who's there?'")
else:
done = True
# "Little old lady." "Little old lady who?"
valid_responses = ["little old lady who", "little old lady who?"]
done = False
while not done:
answer = input("Little old lady. ")
answer = answer.lower()
if not is_valid_input(answer.lower(), valid_responses):
print("No, you're supposed to say, 'Little old lady who?'")
else:
done = True
# Say the punchline!
print("I didn't know you could yodel!")
# Display a default message to the user.
def say_default():
print("That's cool!")
# Check if user_input matches one of the elements
# in valid_responses.
def is_valid_input(user_input, valid_responses):
for item in valid_responses:
if user_input == item:
# If you find a matching response, the input is
# valid for this kind of response.
return True
# If you didn't find a matching response, after
# going through the entire list, the input
# isn't valid for this kind of response.
return False
# --- Put your main program below! ---
def main():
intro()
done = False # Use this to keep track of when the user wants to exit.
while not done:
answer = input("(What will you say?) ")
answer = answer.lower()
done = process_input(answer)
# DON'T TOUCH! Setup code that runs your main() function.
if __name__ == "__main__":
main()
| true |
84bbbf8888bd5646f892d1e3fc700a103c797721 | fer77/OSSU-CS-Curriculum | /intro-cs-python/week1-2/pset1/problem-3.py | 821 | 4.375 | 4 | '''
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
'''
longestSubstring = ''
current = s[0]
prev = s[0]
for c in s[1:]:
if prev <= c:
current += c
else:
if len(current) > len(longestSubstring):
longestSubstring = current
current = c
prev = c
if len(current) > len(longestSubstring):
longestSubstring = current
print ("Longest substring in alphabetical order is:", longestSubstring) | true |
93b861ca4f92a3184cb02bc29d0267c3aa15cb43 | bartoszmaleta/3rd-Self-instructed-week | /loop control statements/while/Loop_control_statements.py | 443 | 4.375 | 4 | # Here is a simple Python example which adds the first ten integers together:
total = 0
i = 1
while i <= 10:
total += i
print(total)
i += 1
print('\n-------------------------------------------- ')
# numbers is a list of numbers -- we don't know what the numbers are!
numbers = [1, 5, 2, 12, 14, 7, 18, 30, 40, 50, 222]
total = 0
i = 0
while i < len(numbers) and total < 100:
total += numbers[i]
print(total)
i += 1
| true |
5f5cf8bcf373e898279ee54dd5ed10fb52383ba7 | bartoszmaleta/3rd-Self-instructed-week | /sorting/sorting_how_ to/lambda_expressions.py | 971 | 4.5625 | 5 | # Small anonymous functions can be created with the lambda keyword.
# This function returns the sum of its two arguments: lambda a, b: a+b.
# Lambda functions can be used wherever function objects are required.
# They are syntactically restricted to a single expression.
# Semantically, they are just syntactic sugar for a normal function definition.
# Like nested function definitions, lambda functions can reference
# variables from the containing scope:
print()
def make_incrementator(n):
return lambda x: x + n
f = make_incrementator(42)
print(f(0))
print(f(1))
print('\n-------------------------------------------- ')
print('\n-------------------------------------------- ')
# The above example uses a lambda expression to return a function.
# Another use is to pass a small function as an argument:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
print(pairs)
sorted_pairs = pairs.sort(key=lambda pair: pair[1])
print(sorted_pairs)
| true |
457bf2de01c95c82b3febd7eae03b35b48042cce | bartoszmaleta/3rd-Self-instructed-week | /functions/exe4 - return_values.py | 564 | 4.25 | 4 |
def calculate_the_factorial_of_a_given_number(given_number_str):
given_number = int(given_number_str)
# total = 1
# given_number = 5
# i = 0
if given_number <= 0:
print("Wrong number. ")
if given_number == 1:
return 1
# for given_number in range(1, given_number + 1):
# total *= given_number - i
# i += 1
return given_number * calculate_the_factorial_of_a_given_number(given_number - 1)
print("The factorial of given number is: ", calculate_the_factorial_of_a_given_number(5))
| true |
213e2dde435c17a0c6484cfc867ebf38d1ba6cf0 | bartoszmaleta/3rd-Self-instructed-week | /Working with Dictionaries, and more Collection types/ranges/ranges.py | 629 | 4.65625 | 5 | # print the integers from 0 to 9
print(list(range(10)))
# print the integers from 1 to 10
print(list(range(1, 11)))
# print the odd integers from 1 to 10
print(list(range(1, 11, 2)))
# We create a range by calling the range function. As you can see, if we pass a single parameter to the range function,
# it is used as the upper bound. If we use two parameters, the first is the lower bound and the second is the upper bound.
# If we use three, the third parameter is the step size. The default lower bound is zero,
# and the default step size is one. Note that the range includes the lower bound and excludes the upper bound. | true |
1183206db30f71bffd121a93b3ebcd5a1ced07cd | kristinbrooks/lpthw | /src/ex19.py | 1,032 | 4.15625 | 4 | # defines the function. names it & defines its arguments. then indent what will be done when the function is called
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
# call the function with number inputs
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
# define variables to be passed to the function
print("Or, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
# call the function with variable inputs
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# call the function with math inputs
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
# call the function with combined variable and math inputs
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
| true |
20dd021a971a341e22644431916fc1fed06763e5 | mousaayoubi/lens_slice | /script.py | 656 | 4.34375 | 4 | #Create toppings list
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
#Create prices list
prices = [2, 6, 1, 3, 2, 7, 2]
#Length of toppings
num_pizzas = len(toppings)
print("We sell "+str(num_pizzas)+" different kinds of pizza!")
#Combine price list with toppings list
pizzas = list(zip(prices, toppings))
#Sort pizzas
pizzas.sort()
print(pizzas)
#Cheapest pizza
cheapest_pizza = pizzas[0]
#Most expensive pizza
priciest_pizza = pizzas[-1]
#Three cheapest pizza
three_cheapest = pizzas[:3]
print(three_cheapest)
#Two dollar slices
num_two_dollar_slices = prices.count(2)
print(num_two_dollar_slices) | true |
27affa01e14c441390538e60af25253600082d9b | tommydo89/CTCI | /17. Hard Problems/circusTower.py | 1,277 | 4.125 | 4 | # A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter
# than the person below him or her. Given the heights and weights of each person in the circus, write
# a method to compute the largest possible number of people in such a tower.
def circusTower(pairs):
pairs.sort() # sorts pairs of height and weight by the 1st element(height)
longest_subseqs = [] # keeps track of all the longest possible subsequences
longest_seq = None
minimum = None
for pair in pairs:
if longest_seq == None: # initializes all the important variables at the start of the loop
longest_subseqs.append([pair])
minimum = pair[1]
longest_seq = [pair]
elif pair[1] < minimum: # adds a new subsequence if this number cannot be added to any of the subsequences thus far
longest_subseqs.append([pair])
minimum = pair[1]
else:
for seq in longest_subseqs: # iterates through each subsequence and appends the pair to the subsequence if valid
last_num = seq[len(seq) - 1][1]
if pair[1] > last_num:
seq.append(pair)
if len(seq) > len(longest_seq): # updates the longest sequence if one occurs
longest_seq = seq
return longest_seq
| true |
24185973d76ecf62fa816c7b2dbeb52cc89397c7 | tommydo89/CTCI | /16. Moderate Problems/pondSizes.py | 1,797 | 4.28125 | 4 | # You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of
# water connected vertically, horizontally, or diagonally. The size of the pond is the total number of
# connected water cells. Write a method to compute the sizes of all ponds in the matrix.
def pondSizes(matrix):
width = len(matrix[0])
height = len(matrix)
traversed = [[0 for x in range(width)] for y in range(height)] # create a copy of the matrix that will be used to mark the traversed cells
pond_sizes = []
for y in range(height):
for x in range(width):
if (traversed[y][x] != 1) and (matrix[y][x] == 0): # only search a cell if it hasn't been traversed and if it is a pond cell
pond_sizes.append(BFS(matrix, traversed, y, x))
return pond_sizes
def BFS(matrix, traversed, y, x):
# if the cell is out of bounds, has been traversed, or if it's not a pound then return 0
if (y < 0) or (y >= len(matrix)) or (x < 0) or (x >= len(matrix[0])) or (traversed[y][x] == 1) or (matrix[y][x] != 0):
return 0
else:
traversed[y][x] = 1 # mark the cell as having been traversed
# recursively breadth-first search all cells surrounding the current cell
BFS_top_left = BFS(matrix, traversed, y - 1, x - 1)
BFS_top = BFS(matrix, traversed, y - 1, x)
BFS_top_right = BFS(matrix, traversed, y - 1, x + 1)
BFS_right = BFS(matrix, traversed, y, x + 1)
BFS_bottom_right = BFS(matrix, traversed, y + 1, x + 1)
BFS_bottom = BFS(matrix, traversed, y + 1, x)
BFS_bottom_left = BFS(matrix, traversed, y + 1, x - 1)
BFS_left = BFS(matrix, traversed, y, x - 1)
return 1 + BFS_top_left + BFS_top + BFS_top_right + BFS_right + BFS_bottom_right + BFS_bottom + BFS_bottom_left + BFS_left
| true |
17a49eb54c369a43f2c3445b291be65936677273 | tommydo89/CTCI | /2. Linked Lists/palindrome.py | 1,058 | 4.3125 | 4 | # Implement a function to check if a linked list is a palindrome.
class Node:
def __init__(self, val):
self.val = val
self.next = None
Node1 = Node(1)
Node2 = Node(0)
Node3 = Node(1)
Node1.next = Node2
Node2.next = Node3
# def palindrome(node):
# reversed_LL = palindrome_recursion(node)
# while (reversed_LL.head != None or node != None):
# if (reversed_LL.val != node.val):
# return False
# return True
# def palindrome_recursion(node):
# newNode = Node(node.val)
# if (node.next == None):
# LL = LinkedList()
# return LL.append(newNode)
# result = palindrome_recursion(node.next)
# return result.append(newNode)
def palindrome(node):
reversed_LL = reverseAndClone(node)
while (node != None and reversed_LL != None):
if (node.val != reversed_LL.val):
return False
node = node.next
reversed_LL = reversed_LL.next
return True
def reverseAndClone(node):
head = None
while (node != None):
nodeClone = Node(node.val)
if (head != None):
nodeClone.next = head
head = nodeClone
node = node.next
return head
| true |
ce2a5c7371177bd7c44bfc1f77c802afe5d37f87 | tommydo89/CTCI | /5. Bit Manipulation/insertion.py | 863 | 4.21875 | 4 | # You are given two 32-bit numbers, N and M, and two bit positions, i and
# j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You
# can assume that the bits j through i have enough space to fit all of M. That is, if
# M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for
# example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.
def insertion(outer, inner, start_index, end_index):
outer = int(outer, 2)
inner = int(inner, 2)
mask = ~((((1<<(end_index - start_index + 1)) - 1) or inner) << start_index) # creates a mask that will allow us to clear the bits from start index to end index
outer = outer & mask # clears the bits from start index to end index
outer = outer | (inner << start_index) # copies the inner bits to start to end
return bin(outer) | true |
8174667c3319d5a75b118e31a583ae58330b3100 | tommydo89/CTCI | /1. Arrays/URLify.py | 435 | 4.15625 | 4 | # Write a method to replace all spaces in a string with '%20'. You may assume that the string
# has sufficient space at the end to hold the additional characters, and that you are given the "true"
# length of the string. (Note: If implementing in Java, please use a character array so that you can
# perform this operation in place.)
def urlify(string):
str_array = string.split()
separator = "%20"
return separator.join(str_array) | true |
5bc76b5c51d6ad868f36e0a0cde6c7f4c9cceb14 | jdingus/discount_calculator | /discount_calculator.py | 847 | 4.25 | 4 | def calculate_discount(item_cost, relative_discount, absolute_discount):
"""
Calculate the discount price of an item in the shopping cart,
First relative_discount is applied then absolute_discount is
applied, final purchase price is the then returned (price)
"""
if relative_discount > 1. or absolute_discount > 1:
raise ValueError("Discounts cannot be above 100%")
if relative_discount < 0 or absolute_discount < 0:
raise ValueError("Discounts cannot be negative!")
price = item_cost
discount_1 = price * relative_discount
if discount_1 == price:
price = 0
return price
price= price - discount_1
discount_2 = price * absolute_discount
if discount_2 == price:
price = 0
return price
price = price - discount_2
return price
def main():
print calculate_discount(100,.5,1.6)
if __name__ == '__main__':
main() | true |
79a592eb784a078a6224ac0105a34aa5dc9432c0 | patixa08/QS | /calculator.py | 1,720 | 4.28125 | 4 | #Funcao de boas vindas ao user
def boasvindas():
print('''
Bem Vindo User!
''')
def calcular():
operation = input('''
Por favor indique o tipo de operação que deseja através dos seguintes caracteres :
+ , - , * , / , ** ou %
''')
#Pedido dos valores para efetuar a operação
valor1 = float( input("Insira um valor: ") )
valor2 = float( input("Insira mais um valor: ") )
if operation == '+':
# Soma
soma = valor1 + valor2
print(valor1,'+',valor2,' = ' , soma)
elif operation == '-':
# Subtracao
subtracao = valor1 - valor2
print(valor1,'-',valor2,' = ' , subtracao)
elif operation == '*':
# Multiplicacao
multi = valor1 * valor2
print(valor1,'*',valor2,' = ' , multi)
elif operation == '/':
# Divisao
div = valor1 / valor2
print(valor1,'/',valor2,' = ' , div)
elif operation == '**':
# Calcular numeros exponenciais
expo = valor1 ** valor2
print(valor1,'**',valor2,' = ' , expo)
elif operation == '%':
# Calcula o resto da divisao
resto = valor1 % valor2
print(valor1,'%',valor2,' = ' , resto)
else:
print('O operador escolhido é inválido')
recalcular()
def recalcular():
calcular_novamente = input('''
Deseja efetuar uma nova operação?
Se sim, digite 'Y', se não, digite 'N'
''')
if calcular_novamente == 'Y':
calcular()
elif calcular_novamente == 'N':
print('Até Breve!:)')
else:
recalcular()
boasvindas()
calcular()
| false |
26362fcee2e89a58574c3d9dc68cff945d8c776a | JacobWashington/python_scripting_food_sales | /my_script.py | 1,850 | 4.28125 | 4 | # Read only
def read_only():
''' a method that only reads the file '''
try:
file1 = open('data.txt')
text = file1.read()
print(text)
file1.close() # the reason for closing, is to prevent a file from remaining open in memory
except FileNotFoundError:
text = None
print(text)
def write_only():
''' a method that only writes to a file '''
file2 = open('more_data.txt', 'w')
# if file exists, it will be overwritten
# if a file does not exist, it will be created
file2.write('tomatoes')
file2.close()
# python will know to close this file, even if there are errors
# with open('data.txt') as f:
# txt = f.read()
# print(txt)
# def read_food_sales():
# all_dates = []
# with open('sampledatafoodsales.csv') as f:
# data = f.readlines()
# for food_sale in data:
# split_food_sale = food_sale.split(',')
# # print(split_food_sale)
# order_date = split_food_sale[0]
# all_dates.append(order_date)
# print(all_dates)
# with open('dates.txt', 'w') as f:
# for date in all_dates:
# f.write(date)
# f.write('\n')
# def append_text():
# ''' append data to an existing file '''
# with open('dates.txt', 'a') as f:
# f.write('01/03/1993')
# print('done')
def read_food_sales():
regions = []
with open('sampledatafoodsales.csv') as f:
data = f.readlines()
for food_sale in data:
split_food_sale = food_sale.split(',')
# print(split_food_sale)
region = split_food_sale[1]
regions.append(region)
print(regions)
if __name__ == '__main__':
# read_only()
# write_only()
# read_food_sales()
# append_text()
read_food_sales()
| true |
ac4a60ec2e36e3595babfe3c7c9a452f947651da | achan90/python3-hardway | /exercises/ex16.py | 1,246 | 4.25 | 4 | # Start import string.
from sys import argv
# Unpack argv to variables.
script, filename = argv
# Print the string, format variable in as raw.
print("We're going to erase {}".format(filename))
# Print the string.
print("If you don't want that, hit CTRL-C.")
print("If you do want that, hit ENTER")
# Prompt for user input.
# raw_input("?")
# Print the string.
print("Opening the files...")
# Open target file in write mode.
target = open(filename, 'w')
# Print the string.
print("Truncating the file. Goodbye!")
# Truncate target file, omitted out as pointless due to opening in write mode.
# target.truncate
# Print the string.
print("Now I'm going to ask you for three lines.")
# Define variable with user input prompt.
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
# Print the string.
print("I'm going to write these to the file.")
# Write string, with string variables formatted in to the target file.
target.write("\n%s \n%s \n%s \n" % (line1, line2, line3))
# Print the string.
print("And finally, we close it.")
# Close target file.
target.close()
# Read the file that you created and print it, using with open so it gets
# automatically closed.
with open(filename) as txt:
print(txt.read())
| true |
bff642d35d826ab6371374cf15a997e00b0581f3 | Sean-McLeod/ICS3U-Unit2-01-Python | /area_of_circle.py | 456 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by Sean McLeod
# Created on November 2020
# This program can calculate the area and perimeter of a circle with
# a radius of 15mm
import math
def main():
# This function calculates the area and perimeter of a circle
print("If a circle has a radius of 15mm:")
print("")
print("Area is {}mm²".format(math.pi*15**2))
print("Perimeter is {}mm".format(2*math.pi*15))
if __name__ == "__main__":
main()
| true |
9e48b08db7c1a798678150d75f5dd30feb0fd8c6 | BulochkaBU/stepik_python_one | /13.py | 561 | 4.34375 | 4 | '''
Условие задачи:
Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого введенного нуля выводит сумму полученных на вход чисел.
Sample Input 1:
5
-3
8
4
0
Sample Output 1:
14
Sample Input 2:
0
Sample Output 2:
0
'''
#Code
# put your python code here
n = int(input())
s = n
while n != 0:
n = int(input())
i = n
s += i
print(s)
| false |
0b98f43b8373fd1ed68230a9cf8c39073d6a9593 | ChadDiaz/CS-masterdoc | /1.2 Data Structures & Algorithms/Number Bases and Character Encoding/ReverseIntegerBits.py | 538 | 4.3125 | 4 | """
Given an integer, write a function that reverses the bits (in binary) and returns the integer result.
Examples:
csReverseIntegerBits(417) -> 267
417 in binary is 110100001. Reversing the binary is 100001011, which is 267 in decimal.
csReverseIntegerBits(267) -> 417
csReverseIntegerBits(0) -> 0
Notes:
The input integer will not be negative.
[execution time limit] 4 seconds (py3)
[input] integer n
[output] integer
"""
def csReverseIntegerBits(num):
binary = bin(num)
reverse = binary[-1:1:-1]
return(int(reverse,2)) | true |
81918ebc623dc5f056379388da9217097124c330 | ChadDiaz/CS-masterdoc | /1.1/Python II/schoolYearsAndGroups.py | 992 | 4.1875 | 4 | '''
Imagine a school that children attend for years. In each year, there are a certain number of groups started, marked with the letters. So if years = 7 and groups = 4For the first year, the groups are 1a, 1b, 1c, 1d, and for the last year, the groups are 7a, 7b, 7c, 7d.
Write a function that returns the groups in the school by year (as a string), separated with a comma and space in the form of "1a, 1b, 1c, 1d, 2a, 2b (....) 6d, 7a, 7b, 7c, 7d".
Examples:
csSchoolYearsAndGroups(years = 7, groups = 4) ➞ "1a, 1b, 1c, 1d, 2a, 2b, 2c, 2d, 3a, 3b, 3c, 3d, 4a, 4b, 4c, 4d, 5a, 5b, 5c, 5d, 6a, 6b, 6c, 6d, 7a, 7b, 7c, 7d"
Notes:
1 <= years <= 10
1 <= groups <=26
'''
def csSchoolYearsAndGroups(years, groups):
returnedList = []
# this is going to loop through the years:
for y in range(1, years + 1):
# this will loop through the groups:
for g in range(1, groups + 1):
returnedList.append(str(y) + chr(g + 96))
return ", ".join(returnedList)
| true |
e4ca5ef5250917fcc4df116e3e79a65ea6a6d14b | thanuganesh/thanuganeshtestprojects | /iterables.py | 2,176 | 4.28125 | 4 | """This function helps to learn about iterables"""
#List is iterable but not iterator
#iterable somthing can be looped over becaz we can loop over list
#how we can say some thing is iterable????
#__iter__() method in iterable then its called iterable
#iterator is object with the state it rembers where its during iteration and iterable called iter as object and it is return iterator
#something is iterable then it contains __iter__ method with in it.
#iteratot know how to get next value __next__() method
#Bascially for llop in the backgroung it is calling iter object and return iterator so it is called iterable
nums = [1, 2, 3, 4]
print(dir(nums))
for num in nums:
print(num)
i_nums = nums.__iter__() #this is something for loop getin the background
i_nums = iter(i_nums)
print(i_nums) #print itself
print(dir(i_nums)) # Shows what are attributes and methods available
print(next(i_nums))
print(next(i_nums))# if this next print next value becaz itetor knows where it is left off
#what for loops to avoid stopIteration error
while True:
try:
item = next(i_nums)
print(item)
except StopIteration:
break
#iteratoy go forward using __next__ no backward
#own class to behave like iterable####################################
class Myrange:
def __init__(self, start, end):
self.value = start
self.end = end
def __iter__(self): # rember if we need iteratable the we need iter method avilable
return self #need to return next if return self here
def __next__(self): #rember iter hace state it knows wer it is left off
if self.value >= self.end:
raise StopIteration
current = self.value
self.value +=1
return current
nums_1 = Myrange(1, 10)
print(next(nums_1))
def my_range(start, end):
curent = start
while curent < end:
yield curent
curent+=1
nums_2 = my_range(1, 5)
print(next(nums_2)) # it is same thing what Myrange calss do but genetor contans iter and next method in-bulit
#iter will run tills the next method avialble
#memory efficent program iterator is best, itarble no
| true |
27c34eafa416a0ada55670ee72004ad292e33a39 | csankaraiah/cousera_python_class | /Python_Assignment/Ch6Strings/ex6_3.py | 292 | 4.15625 | 4 | def count_word(word, ch):
count = 0
for letter in word:
if letter == ch:
count = count + 1
return count
word_in = raw_input("Enter the word: ")
ch_in = raw_input("Enter the character you want to count: ")
count_ch = count_word(word_in, ch_in)
print count_ch
| true |
8210aa7e5b27f65c07b1874f51f5260d1ad387bf | ClarkChiu/learn-python-tw | /src/operators/test_identity.py | 1,203 | 4.46875 | 4 | """恆等運算子
@詳見: https://www.w3schools.com/python/python_operators.asp
恆等運算子用途為比較物件,不僅是比較物件的內容,而是會更進一步比較到物件的記憶體位址
"""
def test_identity_operators():
"""恆等運算子"""
# 讓我們使用以下的串列來說明恆等運算子
first_fruits_list = ["apple", "banana"]
second_fruits_list = ["apple", "banana"]
third_fruits_list = first_fruits_list
# 是(is)
# 比對兩個變數,若這兩個變數是相同的物件,則回傳真值
# 範例:
# first_fruits_list 和 third_fruits_list 是相同的物件
assert first_fruits_list is third_fruits_list
# 不是(is not)
# 比對兩個變數,若這兩個變數不是相同的物件,則回傳真值
# 範例:
# 雖然 first_fruits_list 和 second_fruits_list 有著相同的內容,但他們不是相同的物件
assert first_fruits_list is not second_fruits_list
# 我們將用以下範例展示 "is" 和 "==" 的差異
# 因為 first_fruits_list 內容等於 second_fruits_list,故以下比較將回傳真值
assert first_fruits_list == second_fruits_list
| false |
a9dcb63a962456b3ec45766a3a990135405d7aa7 | premsub/learningpython | /learndict.py | 567 | 4.34375 | 4 | # This program is a learning exercise for dictionaries in perl
# Parse through a dict and print
months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
# print "Enter month>"
# month=raw_input()
# month=int(month)
# Simple command to get an item in a dictionary
# print "The month is %s" % months.get(month)
# Print all elements one by one
for a,b in months.items():
# print a,'is the month of',b
print "%d is the month of %s" % (a,b) | true |
b726154fcdd333f51421a3cc44c9c2aa45cca490 | serenityd/Coursera-Code | /ex1/computeCost.py | 644 | 4.3125 | 4 | import numpy as np
def computeCost(X, y, theta):
"""
computes the cost of using theta as the parameter for linear
regression to fit the data points in X and y
"""
theta=np.mat(theta).T
X=np.mat(X)
y=np.mat(y)
m = y.size
print(X.shape,y.shape,theta.shape)
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta
# You should set J to the cost.
J = 1 / (2 * m) * (X * theta - y).T * (X * theta - y)
print(J.shape)
# =========================================================================
return J
| true |
836e33d711e3f67a14a887a30b464976530ff6d3 | selmansem/pycourse | /variables.py | 1,436 | 4.125 | 4 | # import only system from os
from os import system, name
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# now call function we defined above
clear()
#######################################################################
## The function above is to clean the console each time run the code ##
#######################################################################
# !Rememer python is case sensitive
# and can't start a variable's name with numbers
# 2variablename BAD
# to do it you must use underscore
# _2variablename GOOD
# Save variable with specified name
variablename = "That string"
print(variablename)
# You can set al the variables in one line <like an array>
x, y, z, randomstring = 1, 2, 3, "A random string"
print(x)
print(y)
print(z)
print(randomstring)
# And can print them in th esame line
print(randomstring, x, z, y)
# Conventions
# Tip 1: while you're coding there multiple ways to name a variable. The first one is the most used and common. All them are valid.
book_name = "I robot" # Snake case - using the underscore sign
bookName = "I robot" # Camel case - first character in lowercase
BookName = "I robot" # Pascal case - first character in uppercase
# Tip 2: The recommended way to set a constant is writing the name uppercase
BOOK_NAME = "I robot"
| true |
1e7f8506a5038e42ffe5180d196af4b7e11fb44c | selmansem/pycourse | /numbers.py | 1,247 | 4.21875 | 4 | # import only system from os
from os import system, name
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# now call function we defined above
clear()
#######################################################################
## The function above is to clean the console each time run the code ##
#######################################################################
# To request the user for data, use the input method
## Example: Now we gonna request a number to the user and save it in a variable
age = input("Insert your age: ")
print(age)
# But now the variable is saves as string
print(type(age))
# To convert a string into int, use int function
new_age = int(age)
print(f'Converted {new_age} string into integer and saved into a new variable called new_age')
print(type(new_age))
# Now with the converted string you can operate with the value as an integer
print(new_age + 2)
## Tip 1: You can print a value in the middle of a string by formatting it
## Before declaring the string you must add f, thats mean format
## And inside the string you must add the variable name in braces
| true |
042e3b8c7ad92fa71e3cf7c7e6fbdf33ae97be93 | gdomiciano/intro2python | /python3-4beginners/lessons/loops_for.py | 406 | 4.21875 | 4 | ninjas = ['ryu', 'crystal', 'yoshi', 'ken']
# for ninja in ninjas:
# print(ninja)
# # loop through a section of the list
# for ninja in ninjas[1:3]:
# print(ninja)
for ninja in ninjas:
if ninja == 'yoshi':
print(f'{ninja} - black belt')
else:
print(ninja)
#break a loop
for ninja in ninjas:
if ninja == 'yoshi':
print(f'{ninja} - black belt')
break
else:
print(ninja)
| false |
ece2157471c376a950e06a08cf7cd945ff0c8873 | Tezameru/scripts | /python/pythoncrashcourse/0015_seeing-the-world.py | 2,051 | 4.84375 | 5 | # Seeing the World: Think of at least five places in the world you’d like to
# visit. Store the locations in a list. Make sure the list is not in alphabetical order.
countries = ['Paraguay', 'France', 'Greece', 'Italy', 'Sweden']
# Print your list in its original order. Don’t worry about printing the list neatly,
# just print it as a raw Python list.
print("1. Original Order")
print(countries)
# Use sorted() to print your list in alphabetical order without modifying the
# actual list.
print("2. sorted() to print in alphabetical order")
print(sorted(countries))
# Show that your list is still in its original order by printing it.
print("3. list still in original order")
print(countries)
# Use sorted() to print your list in reverse alphabetical order without changing
# the order of the original list.
print("4. sorted to print list in reverse alphabetical without changing original list")
print(sorted(countries, reverse=True))
# Show that your list is still in its original order by printing it again.
print("5. List still in original order")
print(countries)
# Use reverse() to change the order of your list. Print the list to show that its
# order has changed.
print("6. reverse() to change list oder, then print to show changed order")
countries.reverse()
print(countries)
# Use reverse() to change the order of your list again. Print the list to show
# it’s back to its original order.
print("7. reverse() to change order again, print list to show original order")
countries.reverse()
print(countries)
# Use sort() to change your list so it’s stored in alphabetical order. Print the
# list to show that its order has been changed.
print("8. use sort() to change order of list to alphabetical again, print to show changes")
countries.sort()
print(countries)
# Use sort() to change your list so it’s stored in reverse alphabetical order.
# Print the list to show that its order has changed.
print("9. sort() to change list in reverse alphabetical, then print to show order changed")
countries.sort(reverse=True)
print(countries)
| true |
bfac445de754be4667af5ad4566787a099019e11 | frankShih/LeetCodePractice | /sorting_practice/insertionSort.py | 443 | 4.15625 | 4 |
def insertion_sort(InputList):
# from head to tail
for i in range(1, len(InputList)):
j = i
curr = InputList[i]
# move current element to sorted position (at left part of list)
while (InputList[j-1] > curr) and (j >= 1):
InputList[j] = InputList[j-1]
j=j-1
InputList[j] = curr
inputList = [19, 2, 31, 45, 6, 11, 121, 27]
insertion_sort(inputList)
print(inputList) | true |
13468e46256ebf8586a4a49c1b29674bcff52754 | lingyenlee/MIT6.0001-Intro-to-CS | /ps1b.py | 880 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 9 09:54:12 2019
@author: apple
"""
annual_salary = float(input("Enter your annual salary:"))
semi_annual_raise = float(input("Enter your raise as decimal:"))
portion_saved = float(input("Enter the portion saved:"))
total_cost = float(input("Enter the cost of your dream home:"))
month = 0
current_savings = 0
monthly_savings = annual_salary/12
portion_down_payment = 0.25*total_cost
while current_savings <= portion_down_payment:
monthly_savings = annual_salary/12
current_savings += portion_saved*monthly_savings + current_savings*0.04/12
month += 1
#conditions for increase should be after the calculation, increase
#happen after multiples of 6
if month % 6 == 0:
annual_salary += semi_annual_raise*annual_salary
print("Number of months:", month) | true |
b969117ca7174c1f3f77d2422f64a41fa6dcd8e4 | Goldabj/IntroToProgramming | /Session03_LoopsAndUsingObjects/src/m1e_using_objects_and_zellegraphics.py | 2,391 | 4.34375 | 4 | """
This module uses ZELLEGRAPHICS to demonstrate:
-- CONSTRUCTING objects,
-- applying METHODS to them, and
-- accessing their DATA via INSTANCE VARIABLES (aka FIELDS).
Authors: David Mutchler, Amanda Stouder, Chandan Rupakheti, Katie Dion,
Claude Anderson, Delvin Defoe, Curt Clifton, Matt Boutell,
and their colleagues. December 2013.
"""
#-----------------------------------------------------------------------
# Students: Read and run this program.
#
# Also, WITH YOUR INSTRUCTOR, learn to use the DOT trick:
# rg. and rg.Circle().
# to POP UP help from which you can learn how to use
# objects of a class that you have never seen before.
# (And the HOVER over a class or method to get its code.)
#
# There is nothing to turn in from this file.
# Just use it as an example to see and learn:
# -- How to CONSTRUCT an object
# -- How to APPLY A METHOD to an object (who_dot_doesWhat_withWhat)
# -- How to ACCESS an INSTANCE VARIABLE of an object (who_dot_what)
# -- the DOT andd HOVER pop-up tricks
#-----------------------------------------------------------------------
import rosegraphics as rg
def main():
"""
Uses ZELLEGRAPHICS to demonstrate:
-- CONSTRUCTING objects,
-- applying METHODS to them, and
-- accessing their DATA via INSTANCE VARIABLES (aka FIELDS)
"""
width = 700
height = 400
window = rg.RoseWindow(width, height)
# Construct a rg.Point. Note: the y-axis goes DOWN from the TOP
center_point = rg.Point(300, 100)
point1 = rg.Point(100, 150)
point2 = rg.Point(200, 50)
radius = 50
circle = rg.Circle(center_point, radius)
rectangle = rg.Rectangle(point1, point2)
circle.fill_color = 'orange'
circle.attach_to(window.main_canvas)
window.main_canvas.render(3)
rectangle.attach_to(window.main_canvas)
circle.fill_color = 'blue'
window.main_canvas.render()
corner1 = rectangle.one_corner
corner2 = rectangle.opposite_corner
print(corner1, corner2)
print(rectangle)
window.close_on_mouse_click()
#-----------------------------------------------------------------------
# If this module is running at the top level (as opposed to being
# imported by another module), then call the 'main' function.
#-----------------------------------------------------------------------
if __name__ == '__main__':
main()
| true |
b2ac9f97f436bfd924a71dd23feb0d63ec9c4383 | vladshults/python_modules | /job_interview_algs/fizzbuzz.py | 481 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Created on 24 02 2016
@author: vlad
'''
def multiple_of_3(number):
return number % 3 == 0
def multiple_of_5(number):
return number % 5 == 0
for i in range(1, 100):
if not multiple_of_3(i) and not multiple_of_5(i):
print i
continue
if multiple_of_3(i) and multiple_of_5(i):
print "fizzbuzz"
continue
else:
print ["fizz", "buzz"][multiple_of_5(i)]
| false |
faba8af94dda061f2acc45742658108fc0c5cf7e | ClemXIX/Solo_Learn_Courses | /Python/Beginner/23.2_Leap_Year.py | 978 | 4.5625 | 5 | """
else Statement
You need to make a program to take a year as input and output "Leap year" if it’s a leap year, and "Not a leap year", if it’s not.
To check whether a year is a leap year or not, you need to check the following:
1) If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT leap year.
2) If the year is evenly divisible by 100, go to step 3. Otherwise, the year is a leap year.
3) If the year is evenly divisible by 400, the year is a leap year. Otherwise, it is not a leap year.
Sample Input
2000
Sample Output
Leap year
Use the modulo operator % to check if the year is evenly divisible by a number.
A year is called a leap year if it contains an additional day which makes the number of the days in that year is 366.
This additional day is added in February which makes it 29 days long.
"""
year = int(input())
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year") | true |
d760adfa1d6c6444b0f6c36f6ea35f7904806589 | ClemXIX/Solo_Learn_Courses | /Python/Beginner/20_Tip_Calculator.py | 554 | 4.28125 | 4 | """
Tip Calculator
When you go out to eat, you always tip 20% of the bill amount. But who’s got the time to calculate the right tip amount every time?
Not you that’s for sure! You’re making a program to calculate tips and save some time.
Your program needs to take the bill amount as input and output the tip as a float.
Sample Input
50
Sample Output
10.0
Explanation: 20% of 50 is 10.
To calculate 20% of a given amount, you can multiply the number by 20 and divide it by 100: 50*20/100 = 10.0
"""
bill = int(input())
print(bill * 20 / 100) | true |
f9c5686400afa04ea29ec2e217f18e027857f7c2 | ClemXIX/Solo_Learn_Courses | /Python/Intermediate/2 Functional Programming/12.2_How_Much.py | 499 | 4.125 | 4 | """
Lambda
You are given code that should calculate the corresponding percentage of a price.
Somebody wrote a lambda function to accomplish that, however the lambda is wrong.
Fix the code to output the given percentage of the price.
Sample Input
50
10
Sample Output
5.0
The first input is the price, while the second input is the percentage we need to calculate: 10% of 50 is 5.0.
"""
price = int(input())
perc = int(input())
res = (lambda x, y: (price * perc) / 100)
print(res(price, perc))
| true |
2054b0c9ca187bd13b6e9fc5829e6a63d3136f5b | ClemXIX/Solo_Learn_Courses | /Python/Core_Course/2_Strings_Variables/09.2_More_Lines_More_Better.py | 366 | 4.21875 | 4 | """
Newlines in Strings
Working with strings is an essential programming skill.
Task:
The given code outputs A B C D (each letter is separated by a space).
Modify the code to output each letter on a separate line, resulting in the following output:
A
B
C
D
Consult the Python Strings lesson if you do not remember the newline symbol.
"""
print("""A
B
C
D""")
| true |
4c932287be178731406195e0e49a55acd8bbdb5f | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Exercicios/Ex055.py | 1,084 | 4.34375 | 4 | """ Ex - 055 - Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o
maior e o menor pesos lidos."""
# Como eu fiz
# Cabeçalho:
print(f'{"":=^40}')
print(f'{"> MAIOR PESO LIDO <":=^40}')
print(f'{"":=^40}')
# Var:
maior_peso = 0
menor_peso = 1000
# Laço de repetição:
for pess in range(1, 6):
peso = float(input('Qual o peso da {}° pessoa? (Kg) '.format(pess)))
if peso > maior_peso:
maior_peso = peso
if peso < menor_peso:
menor_peso = peso
print('A pessoa com MAIOR PESO tem {:.1f}Kg'.format(maior_peso))
print('A pessoa com MENOR PESO tem {:.1f}Kg'.format(menor_peso))
# Como o Professor Guanabara Fez
maior = 0
menor = 0
for p in range(1, 6):
peso = float(int('Peso da {}° pessoa: '.format(p)))
if p == 1:
maior == peso
menor == peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor < peso
print('O mairo peso lido foi de {}Kg'.format(maior))
print('O menor peso lido foi de {}Kg'.format(menor)) | false |
c27103282e46a8ffb68ac4452997be9d70f245cc | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Exercicios/Ex102.py | 2,142 | 4.375 | 4 | """ Ex - 102 - Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que
indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será
mostrado ou não na tela o processo de cálculo do fatorial.
"""
# Como eu fiz.
# Definindo função:
def fatorial(num, show=False):
"""
-> Calcula o Fatorial de um número.
:param num: O número a ser calculado.
:param show: (opcional) Mostra ou não a conta.
:return: O valor do Fatorial de um número n.
"""
f = 1
for c in range(num, 0, -1):
if show:
print(c, end='')
if c > 1:
print(' x ', end='')
else:
print(' = ', end='')
f *= c
return f
# Programa principal:
while True:
print(f'{"":-^50}')
nu = int(input('Digite um valor: '))
while True:
mo = str(input('Deseja mostrar o processo de calculo [S/N]: ')).strip().upper()[0]
print(f'{"":¨^50}')
if mo in 'SN':
break
print('ERRO! Resposta inválida!')
if mo == 'S':
mos = True
else:
mos = False
print(f'O fatorial de {nu} é:')
print(f'{fatorial(nu, mos)}')
print(f'{"":¨^50}')
while True:
res = str(input('Quer continuar [S/N]: ')).strip().upper()[0]
if res in 'SN':
break
print('ERRO! Resposta inválida!')
if res == 'N':
break
print(f'{"FINALIZANDO O PROGRAMA!":~^50}')
# Como o Guanabara fez.
def factorial(n, show=False):
"""
-> Calcula o Fatorial de um número.
:param n: O número a ser calculado.
:param show: (opcional) Mostra ou não a conta.
:return: O valor do Fatorial de um número n.
"""
f = 1
for c in range(n, 0, -1):
if show:
print(c, end='')
if c > 1:
print(' x ', end='')
else:
print(' = ', end='')
f *= c
return f
# Programa principal:
print(factorial(5, show=True))
help(factorial)
| false |
515016c99fe0627527569744f6ac27de6260448d | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Aulas Python/Aula014.py | 1,242 | 4.15625 | 4 | """ Aula - 014 - Estrutura de Repetição While (parte 2)."""
# Fase teórica.
''' Vimos as diferenças entre o while e o for.
Chamamos o while de "Estrutura de repetição com teste lógico".
Le-se "while" como "enquanto"
enqunto não maça | while not maçã:
passo | passo
pega | pega
while not maçã:
if chão == v:
passo
if buraco == v:
pular
if moeda == v:
pega
pega
'''
# Fase prática:
'''for c in range(1, 10):
print(c)
print('Fim')'''
'''c = 1
while c < 10:
print(c)
c += 1
print('fim')'''
'''for c in range(1, 5):
n = int(input('Digite um valor: '))
print('Fim')'''
'''n = 1
while n != 0: # Ponto de parada
n = int(input('Digite um valor: '))
print('Fim')'''
'''r = 'S'
while r == 'S':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar [S/N]: ')).upper()
print('Fim')'''
'''n = 1
par = impar = 0
while n != 0:
n = int(input('Digite um valor: '))
if n != 0:
if n % 2 == 0:
par += 1
else:
impar += 1
print('Você digitou {} números pares e {} números impares'.format(par, impar))
'''
| false |
962b33f48f935ac57de975c7df1a7f54209cfe8e | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Aulas Python/Aula010.py | 1,273 | 4.53125 | 5 | """ Aula - 010 - Condições Simples e Compostas: Nesta aula vamos aprender como ultilizar estruturas
condicionais simples e compostas nos programas em Python."""
# Fase Teórica
# Aqui aprendemos o uso do if else, e como contruir a sua identação.
# if variavel.ação_desejada():
# bloco True
# else:
# bloco False
#Ex:
tempo = int(input('Quantos anos tem seu carro? '))
if tempo <= 3:
print('carro novo')
else:
print('carro velho')
print('--FIM--')
# Condição Simplificada.
# No caso de condições simples.
# Ex:
tempo = int(input('Quantos anos tem seu carro? '))
print('carro novo' if tempo <= 3 else 'carro velho')
print('--FIM--')
# Fase prática.
# Prática 1.
nome = str(input('Qual é seu nome? ')).upper()
if nome == 'RENAN':
print('Que nome lindo você tem!')
else:
print('Seu nome é tão normal!')
print('Bom dia {}!'.format(nome.title()))
#Pratica 2.
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota.: '))
n = (n1 + n2)/2
print('A sua média foi {:.1f}'.format(n))
if n >= 6.0:
print('Sua média foi boa! PARABÉNS')
else:
print('Sua média fou ruim! ESTUDE MAIS!')
# ou usando condição simplificada
print('PARABÉNS!' if n >= 6.0 else 'ESTUDE MAIS!')
| false |
7343dd357eb4cd0ea64111b65cca82faa7b8c6e1 | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Exercicios/Ex022.py | 1,645 | 4.5 | 4 | """ Ex-022- Crie um programa que leia o nome completo de uma pessoa
e mostre:
> O nome com todas as letras maiúsculas e minúsculas.
> Quantas letras ao todo (sem considerar espaços).
Quantas letras tem o primeiro nome."""
# Usamos .strip() para descartar espaços vazios antes e depois da string
nome = str(input('Digite seu nome completo: ')).strip()
# Usamos print para imprimir na tela para o usuario
print('Analizando seu nome...')
# Usamos upper() para colocar todas as letras em maiúsculas
print('Seu nome em maiúsculas é {}.'.format(nome.upper()))
# Usamos lower() para colocar todas as letras em minúsculas
print('Seu nome em minúsculas é {}'.format(nome.lower()))
# Usamos len() para saber o tamanho da string e count para contar os espaços vazio entre as palavar
# depois fizemos um subtração da quantidade de letras obtidas com o len() menos a quantidades de espaços
# vazios encontrados pelo count(' ')
print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' ')))
# Usamos o find() para encontrar o primeiro espaço vazio neste caso e separar a primeira pralavra do restante da frase
#print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))
# Criamos um variavel separa e adicionamos o valor do nome com split() para descartar espaços vazios antes e depois
# da string
separa = nome.split()
# Usamos a variavel separa no valor zero para nos estregar apenas a palavra que inicia na posição zero e len() para
# encontra apenas o tamanho da paralava que está na posição zero.
print('Seu primeino nomé é {} e ele tem {} letras'.format(separa[0], len(separa[0])))
| false |
491c6db30d4724556b9f0376b6b291aae9283585 | pranav1214/Python-practice | /lec3/p9.py | 315 | 4.21875 | 4 | # to read a string and count the number of letters, #digits and other
s1 = input("Enter a string: ")
lc, dc, oc = 0, 0, 0
for s in s1:
if (('A' <= s <= 'Z') or ('a' <= s <= 'z')):
lc = lc + 1
elif ('0' <= s <= '9'):
dc = dc + 1
else:
oc = oc + 1
print("Letters: ", lc, "Digits: ", dc, "Other: ", oc)
| true |
01712f7719db69bd26adfd8372710cf9d38c15dc | DunnBC22/BasicPythonProjects | /PlayingWithNumbers.py | 1,067 | 4.28125 | 4 | import math
'''
Take a number that is inputted and split it into 2s and 3s (maximize the number of
3s first). Take those numbers and multiply them together to get the maximum
product of the values.
'''
def defineNumber():
number = input('Please enter a number ')
try:
(isinstance(type(number), int))
except ValueError:
print('Please try again. Only integer values are accepted.')
number = input("Please enter a number ")
else:
number = int(number)
return number
def division(total: int, number: int, modVal: int):
remainder = number % modVal
print('remainder:', remainder)
instances = math.floor(number / modVal)
print('instances:', instances)
internal_total = modVal**instances
print('total:', total)
if (modVal == 3):
division(internal_total, remainder, 2)
else:
finalTotal = total * internal_total
print('The sum of the values is', finalTotal)
quit()
if __name__ == '__main__':
num = defineNumber()
division(0, num, 3)
quit()
| true |
72e8a939273e0c6c8e4c1825e9c23a70b4103ca0 | tarv7/Trabalhos-da-faculdade-UESC | /Codecademy/Python/08 - Laços/08.1 - Laços/12 - Para seu A.py | 206 | 4.125 | 4 | phrase = "Um passaro na mao..."
# Adicione seu laco for
for char in phrase:
if char == 'A' or char == 'a':
print 'X',
else:
print char,
#Nao delete esta declaracao print!
print
| false |
5f77ed8ab840fc2a8bb9280eb2ee7d2652c52738 | tom1mol/python-fundamentals | /dictionaries/dictionaries1.py | 1,050 | 4.71875 | 5 | # Provides with a means of storing data in a more meaningful way
# Sometimes we need a more structured way of storing our information in a collection. To do this, we use dictionaries
# Dictionaries allow us to take things a step further when it comes to storing information in a collection. Dictionaries
# will enable us to use what are called key/value pairs. When using a dictionary, we define our key/value pairs enclosed
# in curly braces ({}). After that, we use a string as our key. Then we use a colon to separate the key from the value,
# and then we have the value.
user = {
"username": "tombombadil",
"first_name": "Tom",
"last_name": "Bombadil",
"age": 100
}
print(user)
# OUTPUT:
# {'username': 'tombombadil', 'first_name': 'Tom', 'last_name': 'Bombadil', 'age': 100}
# NOTES:
# In this case, we have a dictionary called user. This dictionary has four keys (username, first_name, last_name, and age).
# Each of these keys has a value associated with it (“tombombadil”, “Tom”, “Bombadil”, 100).
| true |
6e384bb841ec5c2e5ba365ea1d9082546f9744ac | tom1mol/python-fundamentals | /there-and-back-again/while-loops1.py | 1,798 | 4.5 | 4 | countdown_number = 10
print("Initiating Countdown Sequence...")
print("Lift Off Will Commence In...")
while countdown_number >= 0:
print("%s seconds..." % countdown_number)
countdown_number -= 1
print("And We Have Lift Off!")
# In this example we declare a variable called countdown_number, then we proceed to begin a countdown sequence.
# Then we have our while loop. We create this by starting with the while keyword, followed by a condition.
# In this case, the code inside the while loop will be executed so long as countdown_number is greater than or equal to 0.
# Inside the while block, we print out the countdown_number, followed by the word “seconds”.
# Next, we subtract 1 from the countdown_number, meaning that with each iteration, the countdown_number gets closer to 0.
# Once the countdown_number reaches 0, on the last iteration the countdown_number will be set to -1.
# Since this value is not greater than or equal to 0, the conditional expression of the while loop won’t evaluate to true
# and the while loop will be skipped. After exiting the loop, we simply print out, “And We Have Lift Off!”
# NOTE: Be careful when constructing a while loop. If we’d forgotten to subtract one from the countdown_number at the end of
# each iteration, the loop would have run forever as the condition would have run forever as the condition would always evaluate to
# true. This error is called an infinite loop.
# OUTPUT:
# Python 3.6.1 (default, Dec 2015, 13:05:11)
# [GCC 4.8.2] on linux
# Initiating Countdown Sequence...
# Lift Off Will Commence In...
# 10 seconds...
# 9 seconds...
# 8 seconds...
# 7 seconds...
# 6 seconds...
# 5 seconds...
# 4 seconds...
# 3 seconds...
# 2 seconds...
# 1 seconds...
# 0 seconds...
# And We Have Lift Off!
| true |
be03930099432c1f744dbf25cd4708564f318e6a | tom1mol/python-fundamentals | /break_and_continue/99bottles.py | 1,953 | 4.375 | 4 | for number in range(99, 0, -1):
line_one = "{0} bottle(s) of beer on the wall. {0} bottle(s) of beer"
line_two = "Take one down, pass it around. {0} bottle(s) of beer on the wall\n"
print(line_one.format(number))
print(line_two.format(number - 1))
# OUTPUT:
# Python 3.6.1 (default, Dec 2015, 13:05:11)
# [GCC 4.8.2] on linux
# 99 bottle(s) of beer on the wall. 99 bottle(s) of beer
# Take one down, pass it around. 98 bottle(s) of beer on the wall
# 98 bottle(s) of beer on the wall. 98 bottle(s) of beer
# Take one down, pass it around. 97 bottle(s) of beer on the wall
# ....
# 1 bottle(s) of beer on the wall. 1 bottle(s) of beer
# Take one down, pass it around. 0 bottle(s) of beer on the wall
# NOTES:
# First, we just need a for loop. Our for loop will iterate through the range of numbers between 99 and 0, stepping in -1.
# Each iteration of the loop will get closer to 0. On the following two lines we just declare two string variables
# (line_one and line_two). Instead of including the number of bottles of beer in the string, we’ve used placeholders ({0}).
# And line_two has the newline escape character at the end so we’ll have a clear line break between the verse.
# Then we just print out line_one, which is formatted to include the number from the current iteration of the loop.
# On the first cycle, this will give us:
# 99 bottles of beer on the wall, 99 bottles of beer.
# Then we print out the line_two, which will contain the current number of the iteration – 1 which, on the first iteration,
# will give us:
# Take one down, pass it around, 98 bottles of beer on the wall…
# This pattern will then continue all the way down to 0. See if you change this to print an alternative last verse if the number is
# equal to zero –
# No more bottles of beer on the wall, no more bottles of beer. We’ve taken them down and passed them around; now we’re drunk and
# passed out! | true |
055730012920bf3dd282d898c5a67358c20b8d04 | tom1mol/python-fundamentals | /there-and-back-again/range1.py | 1,241 | 4.78125 | 5 | for item in range(5):
print(item)
# OUTPUT:
# Python 3.6.1 (default, Dec 2015, 13:05:11)
# [GCC 4.8.2] on linux
# 0
# 1
# 2
# 3
# 4
# NOTES:
# Instead of just starting from 0, we can use additional arguments to achieve various sequence combinations.
# We know this by looking at the Python documentation for range() - https://docs.python.org/3/library/stdtypes.html#range.
# Looking at the documentation is a great way of finding out more information about the functions that Python provides.
# range() can take up to three arguments, which are:
# Start - This is the first argument that range() accepts. It is an optional argument and will be given a default value of 0.
# Stop - This is the second argument. It is the number at which to stop our sequence. In order for range() to work, we need to provide
# a stop argument.
# Step - This is the last argument that range() takes. It is also an optional argument. If we don’t provide one,
# Python will default to 1.
# In the last example, we only supplied one argument. Given that the start and step arguments are optional,
# the argument that we provided was the stop argument. This indicates that we want a sequence comprised of 5
# numbers. | true |
b1d992f84b5be48b7acc1ca7490f5119d688b6cd | tom1mol/python-fundamentals | /mutability-and-immutability/mutability-and-immutability3.py | 753 | 4.4375 | 4 | # Tuples, however, are not mutable, meaning that they cannot be changed or modified and have a fixed size
# and fixed values. Therefore if we create a tuple containing two items, then it will always have two items.
# It cannot be changed. If we wanted to use the del keyword on an item in a tuple, then Python will complain.
my_tuple = ("item one", "item two")
del my_tuple[0]
# OUTPUT:
# Python 3.6.1 (default, Dec 2015, 13:05:11)
# [GCC 4.8.2] on linux
# Traceback (most recent call last):
# File "python", line 3, in <module>
# TypeError: 'tuple' object doesn't support item deletion
# Now Python is telling us that the ‘tuple’ object doesn’t support item deletion because a tuple is
# immutable and cannot be changed. | true |
5769f5662f13e5393432a3ca24319a8d90400900 | tho-hoffmann/100DaysOfCode | /Day007/Challenges/ch01.py | 837 | 4.3125 | 4 | #Step 1
word_list = ["aardvark", "baboon", "camel"]
#TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word.
import random
chosen_word = random.choice(word_list)
#TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase.
guess = input("Enter a letter: ").lower()
#TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word.
def isnumber(value):
try:
float(value)
except ValueError:
return False
return True
if isnumber(guess):
print("Please enter a single letter")
elif len(guess) != 1:
print("Please enter a single letter")
else:
for letter in chosen_word:
if letter == guess:
print("Right")
else:
print("Wrong") | true |
1513dc748e97fa9529d7dff58b535f75305b7f74 | Apekshahande/Python_small_project | /rockpapergame.py | 2,386 | 4.21875 | 4 |
from random import randint
def win():# def is pree difine keyword. win is variable name and we pass the prameter inside the parenteses.
print ('You win!')
# return ('You win!')# if we are returen the function then i have to print this function when i will pass then argument.
def lose():# def is pree difine keyword. lose is variable name and we pass the prameter inside the parenteses.
print ('You lose!')
# return ('You lose!')# if we are returen the function then i have to print this function when i will pass then argument.
while True:# our while condition will work infenative.
player_choice = input('What do you pick? (rock, paper, scissors)')# we will ask to pair to give input among this rock ,paper,scissors.
player_choice.strip()# it will take take only tring input .
random_move = randint(0, 2)# random_move is a variable in that (i will assign randint(0,2) it will take randome number 0 to 2 )
moves = ['rock', 'paper', 'scissors']# moves is list of element's.
computer_choice = moves[random_move]#computer choice is equal to moves[random_move] meanse moves index value.
# print(computer_choice)
# player_choice = input('What do you pick? (rock, paper, scissors)')
# player_choice.strip()
if player_choice == computer_choice:# if player_choice is equal to equal to choice then print Draw!
print('Draw!')
elif player_choice == 'rock' and computer_choice == 'scissors': #if , if condition will false then call win function.
# print(win())
win() #call win function / pass the argument in win function.
elif player_choice == 'paper' and computer_choice == 'scissors':
# print(lose())
lose()# call lose function/ pass the argument in lose function.
elif player_choice == 'scissors' and computer_choice == 'paper':
# print(win())
win()
elif player_choice == 'scissors' and computer_choice == 'rock':
# print(lose())
lose()
elif player_choice == 'paper' and computer_choice == 'rock':
# print(win())
win()
elif player_choice == 'rock' and computer_choice == 'paper' :
# print(lose())
lose()
aGain = input('Do you want to play again? (y or n)').strip() #if we want to play again then enter y or enter n.
if aGain == 'n':# if user will write n then it will break.
break
| true |
745e2bb0bbd2a55e7f49c0c788ec1fc8a0d4a0eb | ballib/Forritun1 | /assignment 9 (files and exceptions)/dæmi3.py | 562 | 4.28125 | 4 | def open_file(filename):
file_object = open(filename, "r")
return file_object
def longest(file_object):
longest_word = ''
count = 0
for word in file_object:
strip = word.strip().replace(' ', '')
if len(strip) > len(longest_word):
longest_word = strip
count += 1
return longest_word
def main():
filename = input("Enter filename: ")
file_object = open_file(filename)
longest_word = longest(file_object)
print("Longest word is",longest_word, "of length", len(longest_word))
main() | true |
5290553652abe667784a4526453b6e958b1990c4 | AndrewShmorhunGit/py-learning | /builtin/decorator_fn.py | 2,241 | 4.375 | 4 | """ Decorators with or without arguments """
import functools
def decorator1(fn_or_dec_arg):
"""
Simplest variant
- No need to use named args for decorator
- Different wrapper's for decorator with and without arguments
- Decorator argument can't be a function
"""
if callable(fn_or_dec_arg):
# in this case fn_or_dec_arg is original function
@functools.wraps(fn_or_dec_arg)
def wrapper(*args, **kwargs):
return fn_or_dec_arg(*args, **kwargs)
return wrapper
else:
# in this case fn_or_dec_arg in decorator argument
def fn_wrapper(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return fn_or_dec_arg + fn(*args, **kwargs)
return wrapper
return fn_wrapper
def decorator2(fn=None, dec_arg=''):
"""
- Named arguments for decorator
- One wrapper for both cases
- Function can be passed as decorator argument
"""
def fn_wrapper(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return dec_arg + fn(*args, **kwargs)
return wrapper
if fn is not None:
return fn_wrapper(fn)
return fn_wrapper
def decorator3(fn=None, dec_arg=''):
"""
If called without method, we've been called with optional arguments.
We return a decorator with the optional arguments filled in.
Next time round we'll be decorating method.
"""
if fn is None:
return functools.partial(decorator3, dec_arg=dec_arg)
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return dec_arg + fn(*args, **kwargs)
return wrapper
if __name__ == "__main__":
"""
def func1(arg):
return arg
func1 = decorator1('#dec_arg#')(func1)
func1 = decorator1(func1)
"""
@decorator1 # will be called second
@decorator1('#dec_arg#') # will be called first
def func1(fn_arg):
return fn_arg
@decorator2
@decorator2(dec_arg='#dec_arg#')
def func2(fn_arg):
return fn_arg
@decorator3
@decorator3(dec_arg='#dec_arg#')
def func3(fn_arg):
return fn_arg
assert func1('#fn_arg#') == func2('#fn_arg#') == func3('#fn_arg#')
| true |
d99ee17fad86c162cf30edb35fb4bce5bfcc7007 | fcue/movie_project | /movies.py | 1,224 | 4.3125 | 4 | movies = [
{'title': 'movie 1', 'year': 2001},
{'title': 'movie 2', 'year': 2002},
{'title': 'movie 3', 'year': 2006},
{'title': 'movie 4', 'year': 2004}
]
def add_movie():
get_title = input('Enter the title of the movie: ')
get_year = input('Enter the year: ')
movies.append(
{
'title': get_title,
'year': get_year
}
)
def display_movie():
for movie in movies:
print(f"Movie Title: {movie ['title']}")
print(f"Movie Year: {movie ['year']}")
def find_movie():
get_title = input('Enter the title of the movie: ')
for movie in movies:
if movie['title'] == get_title:
print(f"Movie Title: {movie ['title']}")
print(f"Movie Year: {movie ['year']}")
prompt = 'enter A for adding, D for displaying, F for finding, or Q for quitting: '
def main():
selection = input(prompt)
while selection.lower() != 'q':
if selection.lower() == 'a':
add_movie()
elif selection.lower() == 'd':
display_movie()
elif selection.lower() == 'f':
find_movie()
else:
print('Invalid input')
selection = input(prompt)
main()
| false |
8d84a372cd5822799126eeaaa8421fb745769752 | DanielMagallon/Python-dev | /PrimerosPasos/Curso/Arreglos.py | 1,825 | 4.375 | 4 | calificaciones = {"Luis":3,"Manuel":2,1:"Pedro"} #set
alumnos = ["Juan","Pedro","Daniel","Javier","Lalo"] #list
print(alumnos[0:2])
#Las llaves de rizo {} crean dictionaries o sets. Los corchetes crean lists.
print(calificaciones["Luis"])
print(calificaciones[1])
print(alumnos)
x = 4
d = 2
if x >= 2 and d>=2:
print("d")
if(x<2<5):
pass
if "Juan" in alumnos:
print("Esta juan en los alumnos")
for val in calificaciones:
print(f"Key: {val} with valor {calificaciones[val]}")
print("\nAlumnos: ")
for val in alumnos:
print(val)
alumnos[0] = ["d","a","d"]
print(alumnos[0])
print(alumnos[0][0])
print(alumnos[0][1])
print(alumnos)
print(f"arregl alumnos contiene {len(alumnos)} elementos")
print(f"La posicion 0 de alumnos contiene {len(alumnos[0])} elementos")
print(alumnos[0:2])
print(alumnos[0][0:2])
print(alumnos[2:])
print("Borrando la lista")
alumnos[:] = []
print(alumnos)
alumnos = ["Pedro","Juan",calificaciones]
print("Anidando alumnos y calficaciones",alumnos)
lista = ["Juan",1,4.5]
lista2 = [1,2,3,5,2,2]
print(lista)
print("Añadiendo Luis...")
lista.append("Luis")
print(lista)
print("Limpiando lista con clear")
lista.clear()
print("lista: ",lista)
lista = lista2.copy()
print(lista)
print("Lista2.extends = agrega mas de un elemento de putazo")
print(lista2)
lista2.extend([20,30,])
print(lista2)
lista2.insert(1,1.5)
print(lista2)
print(f"count of 2 in lista2: {lista2.count(2)}")
print("Ordenando lista")
lista2.sort()
print(lista2)
listastr = ["Juan","Danie","Ariel","Water"]
print(listastr)
listastr.reverse()
print("reversa: ",listastr)
listastr.sort()
print("Lista ordenda: ",listastr)
del listastr[0]
del listastr[0]
listastr.remove("Juan")
print(listastr)
listastr.pop()
print(listastr)
for cad in "banana":
print(cad)
car1 = "corvete"
car2 = "viper"
| false |
f9036151afb3f796786f8aefbcff7e35f6da31a7 | h15200/notes | /python/fundamentals.py | 573 | 4.125 | 4 | # using args in for loops <starting, ending, increment>
for i in ["a", "b"]:
print(i) # prints the actual List items
nums = [10, 20, 30]
for i in range(len(nums) - 1, -1, -1):
print("item is", nums[i])
# input, string template literal with `f` for formatted string literal
# try/except dangerous blocks of code
try:
age = int(input("what is your age?\n"))
except Exception:
print("Input must be a valid integer")
quit()
if age <= 0 or age > 150:
print("Must be a realistic age!")
quit()
print(f"that's fantastic that your age is {age}")
| true |
3cea8b8c4d009cf5d049d3df9fb40d2308e7cb1c | cuber-it/aktueller-kurs | /Archiv/Tag1/01_list_tuple_set.py | 852 | 4.53125 | 5 | # Create a list, a tuple, and a set with the same elements
my_list = [1, 2, 3, 3, 4, 5]
my_tuple = (1, 2, 3, 3, 4, 5)
my_set = {1, 2, 3, 3, 4, 5}
# Print the elements in each data structure
print("List:")
for x in my_list:
print(x)
print("Tuple:")
for x in my_tuple:
print(x)
print("Set:")
for x in my_set:
print(x)
# Access the second element in each data structure
print("Second element:")
print(my_list[1])
print(my_tuple[1])
# sets are unordered so you cannot access by index
# Check if 3 is in each data structure
print("Contains 3:")
print(3 in my_list)
print(3 in my_tuple)
print(3 in my_set)
# Add an element to each data structure
my_list.append(6)
# tuples are immutable so they cannot be modified after creation
my_set.add(6)
# Print the updated data structures
print("Updated list:", my_list)
print("Updated set:", my_set)
| true |
10122b6e8d395d9817ccd9fc9c26597ead045439 | cuber-it/aktueller-kurs | /Archiv/Tag1/02_comprehensions.py | 1,216 | 4.125 | 4 | # Creating a list of squares of numbers 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Creating a list of even numbers from another list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4, 6, 8, 10]
# Creating a set of squares of numbers 0 to 9
squares = {x**2 for x in range(10)}
print(squares) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
# Creating a set of even numbers from another set
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evens = {x for x in numbers if x % 2 == 0}
print(evens) # Output: {2, 4, 6, 8, 10}
# Creating a generator that yields squares of numbers 0 to 9
squares = (x**2 for x in range(10))
for square in squares:
print(square)
# Output:
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
# 64
# 81
# Creating a dictionary of squares of numbers 0 to 9
squares = {x: x**2 for x in range(10)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# Creating a dictionary from two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary) # Output: {"a": 1, "b": 2, "c": 3}
| true |
eb8e8072b9526941522dbb22e789573ee8106474 | faizan2sheikh/PythonPracticeSets | /sem2set2/Q11.py | 2,014 | 4.46875 | 4 | # 11. In ocean navigation, locations are measured in degrees and minutes of latitude and longitude. Thus if you’re lying off
# the mouth of Papeete Harbor in Tahiti, your location is 149 degrees 34.8 minutes west longitude, and 17 degrees 31.5
# minutes south latitude. This is written as 149°34.8’ W, 17°31.5’ S. There are 60 minutes in a degree (an older system
# also divided a minute into 60 seconds, but the modern approach is to use decimal minutes instead). Longitude is
# measured from 0 to 180 degrees, east or west from Greenwich, England, to the international dateline in the Pacific.
# Latitude is measured from 0 to 90 degrees, north or south from the equator to the poles. Write code to create a class
# Angle that includes three member variables: int for degrees, a float for minutes, and a char for the direction letter
# (N, S, E, or W). This class can hold either a latitude variable or a longitude variable. Write one method to obtain an
# angle value (in degrees and minutes) and a direction from the user, and a second to display the angle value in
# 179°59.9’ E format. Also write a three-argument constructor. Write a main program that displays an angle initialized
# with the constructor, and then, within a loop, allows the user to input any angle value, and then displays the value.
# You can use the hex character constant ‘\xF8’, which usually prints a degree (°) symbol.
class Angle:
degrees:int
minutes:float
character:str
def __init__(self,deg=0,min=0,char=''):
self.degrees=deg
self.minutes=min
self.character=char
def set_angle(self):
self.degrees=int(input('Enter Degrees: '))
self.minutes=float(input('Enter Minutes: '))
self.character=str(input('Enter Direction: '))
def get_angle(self):
format=str(self.degrees)+str('°')+str(self.minutes)+"'"+self.character
print(format)
while True:
a1=Angle()
a1.set_angle()
a1.get_angle()
| true |
d686267126f4b318cb3620df49471f49e0959099 | faizan2sheikh/PythonPracticeSets | /sem2set2/Q10.py | 1,057 | 4.375 | 4 | # Write code to create a class called Time that has separate member data for hours, minutes, and seconds. Make
# constructor to initialize these attributes, with 0 being the default value. Add a method to display time in 11:59:59
# format. Add another method addTime which takes one argument of Time type and add this time to the current time
# of the self object. Instantiate two objects t1 and t2 to any arbitrary values, display both the objects, add t2 to t1
# and display the result.
class Time:
def __init__(self,h:int=0,m:int=0,s:int=0):
if h<24:self.hours=h
else: print('Invalid hours')
if m<60:self.minutes=m
else: print('Invalid minutes')
if s<60:self.seconds=s
else: print('Invalid seconds')
def displayTime(self):
self.formatted = str(self.hours)+':'+str(self.minutes)+':'+str(self.seconds)
return self.formatted
def addTime(self,t2):
if type(t2)==Time:
pass
t1=Time(12,34,32)
t2=Time(10,23,34)
print(t1.displayTime())
| true |
6f02dbdbbf180593ebfcbc4b8c14d870485491df | deejayM/wagtail_sb_goals | /sb_goals/lib/shared-lib/calendar.py | 1,119 | 4.34375 | 4 | import datetime
def days_in_month(year, month):
"""
Inputs:
year - an integer between datetime.MINYEAR and datetime.MAXYEAR
representing the year
month - an integer between 1 and 12 representing the month
Returns:
The number of days in the input month.
"""
#if month is december, we proceed to next year
def month_december(month):
if month > 12:
return month-12 #minus 12 if cross year.
else:
return month
#if month is december, we proceed to next year
def year_december(year, month):
if month > 12:
return year + 1
else:
return year
#verify if month/year is valid
if (month < 1) or (month > 12):
print ("please enter a valid month")
elif (year < 1) or (year > 9999):
print ("please enter a valid year between 1 - 9999")
else:
#subtract current month from next month then get days
date1 = (datetime.date(year_december(year, month+1), month_december(month+1), 1) - datetime.date(year, month, 1)).days
print (date1) | true |
749d231fdbeeeb0f6b02aac9f9976263baaaffe5 | ashish8796/Codewars | /python-kata/count_smiley_faces.py | 633 | 4.15625 | 4 | '''
Given an array (arr) as an argument complete the function countSmileys
that should return the total number of smiling faces.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
'''
arr = [':D',':~)',';~D',':)']
def count_smileys(arr):
symb = [[':', ';'], ['-', '~',')', 'D']]
count = 0
for val in arr:
if len(val) == 2:
if val[0] in symb[0] and val[1] in symb[1]: count += 1
if len(val) == 3:
if (val[0] in symb[0]) and (val[1] in symb[1] and val[2] in symb[1]): count += 1
return count
print(count_smileys(arr)) | true |
86dc1856142f81e6d7eef77ef5baae3b51d080e7 | ashish8796/Codewars | /python-kata/head_at_wrong_end.py | 675 | 4.28125 | 4 | '''
You're at the zoo... all the meerkats look weird. Something has gone terribly wrong -
someone has gone and switched their heads and tails around!
Save the animals by switching them back. You will be given an array
which will have three values (tail, body, head). It is your job to re-arrange
the array so that the animal is the right way round (head, body, tail).
Same goes for all the other arrays/lists that you will get in the tests:
you have to change the element positions with the same exact logics - simples!
'''
arr = ["tail", "body", "head"]
def fix_the_meerkat(arr):
res = [i for i in arr]
res[2]=arr[0]
return res
print(fix_the_meerkat(arr)) | true |
924e88e3af15706a42d0c15fe319f2149168df54 | kshitijzutshi/Text-Mining-in-Python | /Handling Text in Python.py | 286 | 4.46875 | 4 | #Examples for text handling using python
#!/usr/bin/env python#
-*- coding: utf-8 -*-
text1="Hi my name is Maxwell edward Stark"
text2=text1.split(' ')
print (text2)
for w in text2:
if len(w) > 3:
print(w)
print("Words in caps =")
for w in text2:
if w.istitle():
print(w)
| false |
d22f09a44fdaef9abf9d9acd54100add5aff00e2 | GuileStr/proyectos-py | /AnioB.py | 318 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 14:34:06 2020
@author: palar
"""
def is_leap(year):
leap = False
if year%4==0 and year%100==0 and year%400==0:
leap=True
else:
leap=False
# Write your logic here
return leap
year = int(input())
l = is_leap(year)
print(l) | false |
b366aab4c0bf455cf6129a826658b95ea024cee7 | tommygod3/isc-exercises | /python_exercises/exercise1.py | 651 | 4.21875 | 4 | print("---------- Exercise 1 script ----------")
print("Question 1:")
course = "python"
rating = 10
print(f"Course: {course}, rating: {rating}")
print("Question 2:")
b = 3
c = 4
a = ((b*b) + (c*c))**0.5
print(f"a = {a}")
print("Question 3:")
print(f"a's type: {type(a)}")
print(f"b's type: {type(b)}")
print(f"c's type: {type(c)}")
print("Question 4:")
a = int(a)
print(f"a's type: {type(a)}")
try:
print(a + " squared equals " + b + " squared +" + c + " squared.")
except TypeError as err:
print(f"Type Error! Error message:\n{err}")
print("Done properly:\n" + str(a) + " squared equals " + str(b) + " squared + " + str(c) + " squared.")
| false |
2db69ce29e4f3f12776acbd1b793b29bf5797baa | XjorgeX/Usando-Git | /Listas.py | 798 | 4.125 | 4 | >>> lista = ["abc", 42, 3.1415]
>>> lista[0] # Acceder a un elemento por su ndice
'abc'
>>> lista[-1] # Acceder a un elemento usando un ndice negativo
3.1415
>>> lista.append(True) # Aadir un elemento al final de la lista
>>> lista
['abc', 42, 3.1415, True]
>>> del lista[3] # Borra un elemento de la lista usando un ndice (en este caso: True)
>>> lista[0] = "xyz" # Re-asignar el valor del primer elemento de la lista
>>> lista[0:2] # Mostrar los elementos de la lista del ndice "0" al "2" (sin incluir este ltimo)
['xyz', 42]
>>> lista_anidada = [lista, [True, 42L]] # Es posible anidar listas
>>> lista_anidada
[['xyz', 42, 3.1415], [True, 42L]]
>>> lista_anidada[1][0] # Acceder a un elemento de una lista dentro de otra lista (del segundo elemento, mostrar el primer elemento)
True | false |
c6826de606a4ee7e9bf17c40057a0b9eda0ea76a | imolina218/Practica | /Modulo01/Parte_04_02_products_bill.py | 1,752 | 4.46875 | 4 | # Create a program that have a list of products by code.
# Then the user can choose the product and the amount, the option to choose more than
# one product needs to be available.
# Once the user doesn't want to enter any more products the program will print the
# bill with all the product/s and the quantity
def product_shopping():
confirmation = True
bill_total = ""
total_amount = 0
bill_total_total = "Total amount to pay:..................${}".format(total_amount)
while confirmation:
print("Welcome to the store. This are our products: ")
print("> Monitor.........$120\n> Motherboard.........$200\n> Mouse.........$30\n> Ram.........$20\n"
"> Coolers.........$5\n> Keyboard.........$80\n> Speakers.........$60\n> Router.........$45")
products = {"monitor": 120, "motherboard": 200, "mouse": 30, "ram": 20, "coolers": 5, "keyboard": 80,
"speakers": 60, "router": 45}
select_product = input("Enter the name of the product that you want to buy: ")
select_product = select_product.lower()
amount_product = input("Now enter the amount that you want:")
amount_product = int(amount_product)
price = (products[select_product] * amount_product)
confirmation = input("Do you want to buy more products?").lower()
print("\n\n")
bill = "Product: {} | Amount: {} | Total: ${}\n".format(select_product, amount_product, price)
bill_total += bill
total_amount += price
if confirmation in "yes":
confirmation = True
else:
confirmation = False
print(bill_total)
print(bill_total_total)
product_shopping()
| true |
c7b730f182c1e0068f5e58a51ef99b00723bb95c | imolina218/Practica | /PYnative/lists.py | 2,862 | 4.15625 | 4 | # Take a list and reverse it.
# a_lsit = [100, 200, 300, 400, 500]
# print(a_lsit)
# # a_lsit.reverse()
# print(a_lsit[::-1])
# print(a_lsit)
##################################################
# Concatenate the following two lists index-wise.
# list1 = ["M", "na", "i", "Ke"]
# list2 = ["y", "me", "s", "lly"]
# list3 = [i + j for i, j in zip(list1, list2)]
# list3 = list
# for i, j in zip(list1, list2):
# list3 = i + j
# print(list3)
##################################################
# Given a python list. Turn every time of a list into its square.
# aList = [1, 2, 3, 4, 5, 6, 7]
# list1 = [i**2 for i in aList]
# print(list1)
##################################################
# Concatenate two lists in the following order : ['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']
# list1 = ["Hello ", "take "]
# list2 = ["Dear", "Sir"]
# list3 = [x + y for x in list1 for y in list2]
# print(list3)
##################################################
# Given a two Python list. Iterate both lists simultaneously such that list1
# should display item in original order and list2 in reverse order.
# list1 = [10, 20, 30, 40]
# list2 = [100, 200, 300, 400]
# for x, y in zip(list1, list2[::-1]):
# print(x, y)
##################################################
# Remove the empty strings from the list of strings.
# list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
# list_result = list(filter(None, list1))
# print(list_result)
##################################################
# Add item 7000 after 6000 in the following Python List.
# list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
# list1[2][2].append(7000)
# print(list1)
##################################################
# Given a nested list extend it with adding sub list ["h", "i", "j"] in a such a way that it will look
# like the following list: ['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n'].
# list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# print(list1)
# list_to_add = ["h", "i", "j"]
# print(list_to_add)
# list1[2][1][2].extend(list_to_add)
# print(list1)
##################################################
# Given a Python list, find value 20 in the list, and if it is
# present, replace it with 200. Only update the first occurrence of a value.
# list1 = [5, 10, 15, 20, 25, 50, 20]
# index = list1.index(20)
# list1[index] = 200
# print(list1)
##################################################
# Given a Python list, remove all occurrence of 20 from the list.
list1 = [5, 20, 15, 20, 25, 50, 20]
def remove_element(l_ist, x):
return [l_ist.remove(i) for i in l_ist if i == 20]
# for i in l_ist:
# if i == x:
# l_ist.remove(i)
# print(l_ist)
remove_element(list1, 20)
print(list1)
| false |
492151b1f4d9af62b1ccd1f1d5c762e17306cc88 | jj1165922611/SET_hogwarts | /python_base/base8/base8_1/base8_1.py | 596 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-07-26
# @Author : Joey Jiang
# @File : base8_1.py
# @Software : PyCharm
# @Description: python脚本编写实战(一)
# 1、冒泡排序
def bubble_sort():
list=[1,3,5,2,7,6]
for i in range(len(list)-1):
for j in range(len(list)-i-1):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
print(list)
bubble_sort()
# 2、字典解包
def foo(a,b):
print(a)
print(b)
dict1=dict(a=1,b=2)
dict2=dict(a=1,b=2,c=3)
foo(**dict1)
foo(**dict2) # 执行会报错 | false |
7493f14ffb26d3fdeea0cb65a822ac7609cd3295 | yshshrm/Algorithms-And-Data-Structures | /python/Sorts/quick_sort.py | 920 | 4.15625 | 4 | # Implementation of Quick Sort in Python
# Last Edited 10/21/17 (implemented qsort_firstE(arr))
# Worst case performance: O(n^2)
# Average performance: O(nlogn)
# In this first implementation of quick sort, the choice of pivot
# is always the first element in the array, namely arr[0]
def qsort_firstE(arr):
# if the array is empty, return the empty array
if not arr:
return arr
# otherwise, partition the array around the pivot, and concatenate
# the recursively sorted arrays
else:
left = [x for x in arr[1:] if x < arr[0]]
right = [x for x in arr[1:] if x >= arr[0]]
return qsort_firstE(left) + [arr[0]] + qsort_firstE(right)
# Test case 1.
# quicksorting an empty array returns an empty array
print(qsort_firstE([]))
# Test case 2.
# quicksorting an array with negative, repeating values
print(qsort_firstE([3, 6, 82, 23, -4, -102, 23, -8, 3, 0]))
| true |
5d53368ee0c009da195721291844f7f7ae592799 | sonikku10/primes | /primes.py | 509 | 4.34375 | 4 | import math #Import the math module
def is_prime(num):
'''
This function will determine whether a given integer is prime or not.
Input: An integer.
Output: True/False Statement
:param num:
:return:
'''
if num % 2 == 0 and num > 2: #All even numbers greater than 2 are not prime.
return False
for i in range(3, int(math.sqrt(num)+1), 2): #All odd numbers from 3 up to (but not including its sqrt)+1
if num % i == 0:
return False
return True
| true |
ff085804195df8c213d1a4b6571b6256ccfaa110 | KaraKala1427/python_labs | /task 2/53.py | 339 | 4.125 | 4 | rate = float(input("Enter the rating : "))
if rate == 0:
print("Unacceptable performance")
elif rate>0 and rate<0.4 or rate>0.4 and rate<0.6:
print("Error")
elif rate == 0.4:
print("Acceptable performance", "Employee's raise= $", 2400*0.4)
elif rate >= 0.6:
print("Meritorious performance", "Employee's raise= $", 2400*0.6) | true |
7460834272f861fabf6ae5d9682ad057cdec10b3 | afwcc/CST8279 | /question12.py | 276 | 4.125 | 4 | user_enter_fahrenheit_degrees_string = input("Please enter the fahrenheit degrees")
user_enter_fahrenheit_degrees_float = float(user_enter_fahrenheit_degrees_string)
celsius_degrees_float = float((user_enter_fahrenheit_degrees_float-32)*(5/9))
print(celsius_degrees_float) | false |
f27357315751de19f22270227e3c3bb73c9f977c | oliverschwartz/leet | /longest_univalue_path/longest_univalue_path.py | 1,070 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
if not root: return 0
self.global_max = 0
def longest_path_right_or_left(v):
if not v: return 0
# calculate left and right, then only include them if they're
# the same value as this root
l, r = longest_path_right_or_left(v.left), longest_path_right_or_left(v.right)
l = 1 + l if v.left and v.left.val == v.val else 0
r = 1 + r if v.right and v.right.val == v.val else 0
# global longest_path max is set with current node as root
self.global_max = max(self.global_max, l + r)
# but the max we return, will be either right or left
return max(l, r)
longest_path_right_or_left(root)
return self.global_max
| true |
747249001d522782d1042f4097c370d5989011eb | Shinrei-Boku/kreis_academy_python | /lesson07.py | 817 | 4.125 | 4 | #class 抽象クラス lesson07.py
import abc
class Person(metaclass=abc.ABCMeta):
def __init__(self,name,age):
print("create new Person")
self.__name = name
self.__age = age
def myname(self):
print("my name is {}".format(self.__name))
def myage(self):
print( "{}の{}歳です。".format(self.__name,str(self.__age)))
@abc.abstractmethod
def department(self):
pass
def __del__(self):
print("bye")
class KreisPerson(Person):
def __init__(self,name,age):
super().__init__(name,age)
self.__department = "kreis"
def department(self):
print("所属は{}".format(self.__department))
if __name__ == "__main__":
kon = KreisPerson("kondo","20")
kon.myname()
kon.myage()
kon.department() | false |
5e265310ffb378751e71d486f0f94416c12372ba | OSL303560/Parenitics | /Source codes/Beginning.py | 1,976 | 4.15625 | 4 | import time
from os import system
temp = 0
def startstory():
print("In February 2019, ", end = "")
time.sleep(1)
print("the Hong Kong government proposed the ")
time.sleep(0.5)
print("\nFugitive Offenders and Mutual legal Assistance in Criminal Matters Legislation (Amendment) Bill 2019.")
time.sleep(2)
print("\nThe bill raised concerns and triggered series of protests.")
time.sleep(2)
print("\nThe main movement started in June 2019 and Hong Kong was rocked by protests.")
time.sleep(2)
print("\nCarrie Lam, the chief executive, announced the withdrawal of the bill on "
"4th September but the protests did not stop.")
time.sleep(2)
print("\nFocus changed to the police brutality and indiscriminate arrests during previous protests.")
time.sleep(2)
print("\nProtesters were demanding full democracy rights for HongKongers and there was no sign of dying down.")
time.sleep(2)
print("\nThe message was crystal clear: protests will continue until the five demands are met...\n")
system("pause")
system("cls")
time.sleep(0.5)
def introduction():
print("Welcome!")
time.sleep(1)
print("\nIn this game, you will experience what it's like to be a Hongkonger "
"\ncommunicating with his parents with opposing political views.")
time.sleep(1)
print("\nThe rules are simple. You lose if you pick the wrong choice.")
time.sleep(1)
print("\n(This story is fictitious. Any resemblance to actual events are entirely coincidental.)")
print("(The production team takes no political stance.)\n")
time.sleep(1)
answer = "o"
while answer.lower().strip() != "yes" and answer.lower().strip() != "no":
answer = input("Understand and Continue? (yes/no)")
system("cls")
if answer.lower().strip() == "yes":
pass
else:
print("That's so bad. Goodbye then.")
exit() | true |
190f6a92cad55fa3b8ca1f757f8b6c42eac5f13d | PhilipMottershead/Practice-Python | /Tutorials/Exercise 13 - Fibonacci.py | 656 | 4.4375 | 4 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the number of numbers in the sequence to generate.
starting_number = [1]
def next_number(num):
if num == 1 or num == 2:
return 1
return next_number(num - 1) + next_number(num - 2)
def fibo(num):
new_list = []
while num != 0:
new_list.append(next_number(num))
num = num - 1
new_list.reverse()
return new_list
print(fibo(int(input("Input number of numbers in the Fibonnaci sequence to generate"))))
| true |
cca82bcf32c9f686707d821e20d7232e978d6624 | PhilipMottershead/Practice-Python | /Tutorials/Exercise 01 - Character_Input.py | 802 | 4.1875 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Extras:
# Add on to the previous program by asking the user for another number
# and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
# Print out that many copies of the previous message on separate lines.
# (Hint: the string "\n is the same as pressing the ENTER button)
import datetime
now = datetime.datetime.now()
name = input("What is your name? ")
age = int(input("What is your age? "))
times_to_print = int(input("Input number of times to print :"))
year_at_100 = now.year + 100 - age
print(f"Hi {name} you will be 100 in the year {year_at_100}\n" * times_to_print)
| true |
f48533f2a1fae162aa7356dee9335e772e791424 | GAUTAMSETHI123/PYTHON-PROGRAM | /DIST.py | 213 | 4.125 | 4 | x1=int(input("enter the value:"))
x2=int(input("enter the value:"))
y1=int(input("enter the value:"))
y2=int(input("enter the value:"))
dist=((y2-y1)*2+(x2-x1)*2)*1/2
print("the distance between two points",dist)
| false |
a98ec918c69cf8b6926f80cd0388b716ec1f9b71 | jim-cassidy/foursquare-with-flask | /module/createtable.py | 1,914 | 4.1875 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
# c.execute(create_table_sql)
except Error as e:
print(e)
def main():
database = r"saved.db"
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS list (
names VARCHAR(20) , id VARCHAR(30)) """
# sql_deletetable = """ DROP TABLE scores """
sql_create_projects_table2 = """ CREATE TABLE IF NOT EXISTS scores (
id integer NOT NULL,
satdate date NOT NULL,
score integer NOT NULL
); """
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute(sql_create_projects_table)
print ("executed!!!")
# create a database connection
# conn = create_connection(database)
# conn.execute(sql_deletetable)
# create tables
if conn is not None:
# create projects table
# create_table(conn, sql_create_projects_table)
create_table(conn, sql_create_projects_table)
print ("created")
c = conn.cursor()
c.execute(sql_create_projects_table)
else:
print("Error! cannot create the database connection.")
if __name__ == '__main__':
main()
| true |
00ed0a5bf8383fc9cc31344c481bad2e2ea8cd7e | dr01/python-workbench | /lettfreq.py | 2,125 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Print number of occurrences and frequency of letters in a text
"""
__author__ = "Daniele Raffo"
__version__ = "0.1"
__date__ = "14/10/2018"
import argparse
from string import ascii_lowercase as _alphabet
from collections import Counter as _Counter
def parse_command_line():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description = __doc__)
group = parser.add_mutually_exclusive_group(required = True)
group.add_argument('-f', '--file', dest = 'input_filename', type = argparse.FileType('r'), help = 'File containing the text to analyze')
group.add_argument('-t', '--text', dest = 'input_text', help = 'Text to analyze')
parser.add_argument('-n', '--nonulls', action = 'store_true', help = 'Hide letters with zero frequency')
parser.add_argument('-o', '--total', action = 'store_true', help = 'Include total number of characters and letters')
parser.add_argument('-s', '--sortfreq', action = 'store_true', help = 'Sort by letter frequency, highest first')
return parser
if __name__ == '__main__':
args = parse_command_line().parse_args()
# Get input text from chosen source
if args.input_text is not None:
text = args.input_text
elif args.input_filename is not None:
with args.input_filename as filename:
text = filename.read()
# Analyze input text
frequency = _Counter({c: 0 for c in _alphabet})
frequency.update(c for c in text.lower() if c in frequency)
total_letters = sum(frequency.values())
total_chars = len(text.replace('\n', '')) # do not count newline chars
# Output results
if not args.sortfreq:
output = sorted(frequency.items(), key = lambda x: x[0], reverse = False)
else:
output = sorted(frequency.items(), key = lambda x: x[1], reverse = True)
for c, n in output:
if not (args.nonulls and n == 0):
print('{}:{:>8}{:10.2f}%'.format(c, n, 100 * n / (total_letters or 1)))
if args.total:
print('Total letters: {:>8}\nTotal characters:{:>8}'.format(total_letters, total_chars))
| true |
816706b0788b7bac1bea4c218fa77cec1cdf2492 | Bajpai-30/Coffee-Machine-in-python---hyperskill | /stage4.py | 2,135 | 4.1875 | 4 | amount = 550
water = 1200
milk = 540
coffee = 120
cups = 9
def print_state():
print('The coffee machine has:')
print(f'{water} of water')
print(f'{milk} of milk')
print(f'{coffee} of coffee beans')
print(f'{cups} of disposable cups')
print(f'{amount} of money')
print()
def select_action() -> str:
return input('Write action (buy, fill, take): ')
def select_flavor() -> int:
return int(input('What do you want to buy?'
' 1 - espresso, 2 - latte, 3 - cappuccino: '))
def buy():
global amount, water, milk, beans, cups
flavor = select_flavor()
if flavor == 1: # espresso
assert water >= 250
assert coffee >= 16
money += 4
water -= 250
coffee -= 16
elif flavor == 2: # latte
assert water >= 350
assert milk >= 75
assert coffee >= 20
amount += 7
water -= 350
milk -= 75
coffee -= 20
elif flavor == 3: # cappuccino
assert water >= 200
assert milk >= 100
assert coffee >= 12
amount += 6
water -= 200
milk -= 100
coffee -= 12
else:
raise ValueError(f'Unknown flavor {flavor}')
cups -= 1
def fill():
global water, milk, coffee, cups
water += int(input('how many ml of water do you want to add: '))
milk += int(input('how many ml of milk do you want to add: '))
coffee += int(input('how many grams of coffee'
' do you want to add: '))
cups += int(input('how many disposable cups of coffee'
' do you want to add: '))
def take():
global amount
print(f'I gave you ${amount}')
money = 0
def main():
print_state()
action = select_action()
if action == 'buy':
buy()
elif action == 'fill':
fill()
elif action == 'take':
take()
else:
raise ValueError(f'Unknown command {action}')
print()
print_state()
if __name__ == '__main__':
main() | true |
849f167637b964a3e8d0de273a0a43ad7c3857cd | CiaranGruber/CP1404practicals | /prac_10/extension_test_date.py | 2,244 | 4.4375 | 4 | """
Create the class Date which contains code to add days according to leap years
Date Class. Created by Ciaran Gruber - 28/08/18
"""
import doctest
class Date:
"""Represent the Date"""
month_to_day = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
def __init__(self, day, month, year):
"""Initialise date instance"""
self.day = int(day)
self.month = int(month)
self.year = int(year)
def __str__(self):
"""
Return string version of Date
>>> print(Date(12, 12, 1212))
Date: 12/12/1212
"""
return 'Date: {}/{}/{}'.format(self.day, self.month, self.year)
def add_days(self, days):
"""
Add a certain amount of days to a date. Includes leap years
>>> print(Date(1, 1, 1212).add_days(223134))
Date: 29/11/1822
"""
while days >= 366 or days >= 365 and not self.is_leap_year(): # Adds years until it can't anymore
if self.is_leap_year():
self.year += 1
days -= 366
else:
self.year += 1
days -= 365
days += self.day
self.day = 1
while days > 0:
if days > self.month_to_day[self.month] + 1 or days > self.month_to_day[self.month] and \
not(self.month == 2 and self.is_leap_year()):
if self.month == 12:
self.month = 1
self.year += 1
else:
self.month += 1
days -= self.month_to_day[self.month]
if self.month == 2 and self.is_leap_year():
days -= 1
else:
self.day += days - 1
days = 0
return self
def is_leap_year(self):
"""
Return whether date is a leap year
>>> print(Date(12, 12, 2004).is_leap_year())
True
"""
return self.year % 4 == 0 or self.year % 400 == 0 and not self.year % 100 == 0
if __name__ == '__main__':
new_date = Date(12, 11, 2004)
assert new_date.day == 12
assert new_date.month == 11
assert new_date.year == 2004
doctest.testmod()
| true |
d1dddeb8a44b1cb0f4430fc9971653dced1c7a19 | CiaranGruber/CP1404practicals | /prac_02/exceptions_demo.py | 889 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
Value Error will occur if you use a non-integer
2. When will a ZeroDivisionError occur?
This will occur when the person puts the denominator as a 0
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
This could be avoided by forcing the user to input a number that is not 0 (eg. while denominator == 0 or not
denominator)
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while not denominator:
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.")
| true |
5aa245f1f5016cc8dc8dbf92a64783972b106e4e | CiaranGruber/CP1404practicals | /prac_05/hex_colours.py | 1,062 | 4.1875 | 4 | """
Prints hexadecimal code when user enters colour name.
21/08/18 - Hex Colours. Created by Ciaran Gruber.
"""
COLOURS = {'alice blue': '#f0f8ff', 'antique white': '#faebd7', 'aquamarine 1': '#7fffd4', 'azure 1': '#f0ffff',
'beige': '#f5f5dc', 'blanched almond': '#ffebcd', 'blue': '#0000FF', 'brown': '#a52a2a',
'burlywood': '#deb887', 'cadet blue': '#5f9ea0'}
def main():
"""Main code"""
colour = get_colour()
while colour != '':
print("The colour '{}' is {} in hexadecimal code".format(colour, COLOURS[colour.lower()]))
print()
colour = get_colour()
print()
print('{:^8} | {:^10}'.format('Hex Code', 'Colour'))
print('{0:_<9s}|{0:_<11s}'.format(''))
for colour, hex_code in COLOURS.items():
print('{:8} | {}'.format(hex_code, colour))
def get_colour():
"""Get colour from user input"""
colour = input('Colour: ')
while colour.lower() not in COLOURS and colour != '':
print('Colour not in list')
colour = input('Colour: ')
return colour
main()
| false |
81f48937b938e454999489819a76eb86c83d5e27 | henrikvalmin/visual-sorting-algorithms | /main_menu.py | 957 | 4.1875 | 4 | from sorting import sorting
def __main__():
while True:
print("\nChoose an algorithm to sort with!")
print("1: Bubble Sort")
print("2: Insertion Sort")
print("3: Selection Sort")
print("4: Quick Sort")
print("5: Shell Sort")
choice = input("Use algorithm nr: ")
if choice == "1":
sorter = sorting("Bubble Sort")
sorter.loop("bubble")
elif choice == "2":
sorter = sorting("Insertion Sort")
sorter.loop("insertion")
elif choice == "3":
sorter = sorting("Selection Sort")
sorter.loop("selection")
elif choice == "4":
sorter = sorting("Quick Sort")
sorter.loop("quick")
elif choice == "5":
sorter = sorting("Shell Sort")
sorter.loop("shell")
else:
print("Invalid choice!")
if __name__ == "__main__":
__main__()
| false |
6beb646b7ab8163e5fc1ed77e008d46a0256c332 | satinder01/projecteuler | /9_special_pythagorean_triplet.py | 479 | 4.15625 | 4 | #!/Users/satinderjitsingh/anaconda3/bin/python
'''
Special Pythagorean triplet
Problem 9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import math
a=1
b=2
for a in range(1,1000):
for b in range(1,1000):
c=math.sqrt(a*a + b*b)
if (c==1000-a-b):
print(a*b*c)
exit()
| false |
b0a6f193b22b83b4f6ad92957fef9b6489c08bbc | HenziKou/CIS-211 | /Projects/duck_compiler-master/alu.py | 1,891 | 4.21875 | 4 | """
The arithmetic logic unit (ALU) is the part of the central
processing unit (CPU, or 'core') that performs arithmetic
operations such as addition, subtraction, etc but also
logical "arithmetic" such as and, or, and shifting.
"""
from instr_format import OpCode, CondFlag
from typing import Tuple
class ALU(object):
"""The arithmetic logic unit (also called a "functional unit"
in a modern CPU) executes a selected function but does not
otherwise manage CPU state. A modern CPU core may have several
ALUs to boost performance by performing multiple operatons
in parallel, but the Duck Machine has just one ALU in one core.
"""
# The ALU chooses one operation to apply based on a provided
# operation code. These are just simple functions of two arguments;
# in hardware we would use a multiplexer circuit to connect the
# inputs and output to the selected circuitry for each operation.
ALU_OPS = {
OpCode.ADD: lambda x, y: x + y,
OpCode.MUL: lambda x, y: x * y,
OpCode.SUB: lambda x, y: x - y,
OpCode.DIV: lambda x, y: x // y,
# For memory access operations load, store, the ALU
# performs the address calculation
OpCode.LOAD: lambda x, y: x + y,
OpCode.STORE: lambda x, y: x + y,
# Some operations perform no operation
OpCode.HALT: lambda x, y: 0
}
def exec(self, op, in1: int, in2: int) -> Tuple[int, CondFlag]:
try:
result = self.ALU_OPS[op](in1, in2)
except ArithmeticError:
return 0, CondFlag.V
except ValueError:
return 0, CondFlag.V
if result < 0:
cc = CondFlag.M
elif result == 0:
cc = CondFlag.Z
elif result > 0:
cc = CondFlag.P
else:
assert False, "Shouldn't reach this point"
return result, cc | true |
dc166da896dfb8f0dd23df11aa008e4ee2e8cbb1 | viniciusldn/Learning-Python | /POO - Programação Orientada a Objetos/POO_Geeters_Setters_Estados.py | 1,240 | 4.4375 | 4 | # language: PT
"""
Existem alguns padrões de bas práticas na programação.
É aconselhavél que:
- Classes sejam nomeadas com substantivos e a primeira letra capital.
- Atributos de classe sejam nomeados com substantivos minusculos.
- metodos sejam nomeados com verbos que indiquem sua ação.
- Utilizar typing notations, indicando caracteristicas de funções e metodos.
- indicar a linguagem na qual esta programando no começo do codigo.
"""
# Getters e Setter servem para tratar atributos de uma classe como estados
class Maquina:
def __init__(self, atributo: bool) -> None:
self.__estado = atributo # ligado: True, Desligado: False
def get_estado(self) -> bool:
return self.__estado
def set_estado(self, valor: bool) -> None:
if isinstance(valor, bool): # verifica se a entrada é uma instancia boolean
self.__estado = valor
"""
Tente rodar este codigo direto pelo terminal.
Para isso va para o diretorio do codigo e indique o compilador (python3)
Após a inicialização, três setas ">>>" indicarão que o terminal do python esta rodando
Agora é só importar a classe, instanciar um objeto e testar os metodos
""" | false |
b953de6e34b2eb3e482e94f97f41fe1503d30319 | syedsaad92/MIT-6.0001 | /week3Problem3_printing_all_available_letters.py | 573 | 4.15625 | 4 | # Next, implement the function getAvailableLetters that takes in one parameter - a list of letters, lettersGuessed. This function returns a string that is comprised of lowercase English letters - all lowercase English letters that are not in lettersGuessed.
def getAvailableLetters(lettersGuessed):
temp = ''
import string
alphabets = string.ascii_lowercase
for char in alphabets:
if char not in lettersGuessed:
temp += char
return temp
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
print(getAvailableLetters(lettersGuessed))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.