blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8219c6056ea0113993bdaa15d456d56f3483afff | gaya38/devpy | /Python/assignment/pes-python-assignments-2x.git/22.py | 686 | 4.125 | 4 | import math
print "perform all the trignomatric operations on given numbers"
x=input("Enter the x value in radians:")
y=input("Enter the x value radians:")
print "acos value of x:",math.acos(x)
print "asin value of x:",math.asin(x)
print "atan value of x:",math.atan(x)
print "atan values of x and y:",math.atan2(y,x)
print "converts angle x from radians to degrees",math.degrees(x)
x=input("Enter the x value in degrees:")
y=input("Enter the y value in degrees:")
print "cos value of x:",math.cos(x)
print "hypot value of x and y:",math.hypot(x,y)
print "sin value of x:",math.sin(x)
print "tan value of x:",math.tan(x)
print "converts angle x from degrees to radians",math.radians(x)
| true |
45c81e5a0dd1f3537faecf1a24a3ca25fc17b868 | gaya38/devpy | /Python/assignment/pes-python-assignments-2x.git/Mypackage/TuplePackage.py | 1,139 | 4.28125 | 4 | def tupbig():
tup1=('sun','mon','tue','wed','thu','fri','sat')
print "tuple1:",tup1
tup2=('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec')
print "concatenation of tuple2 and tuple1:",tup2+tup1
tup1=(1,2,3,4,5)
tup2=(4,5,2,3,1,7,8,9)
tup3=(5,6,2)
a=len(tup1)
b=len(tup2)
c=len(tup3)
print "The biggest tuple is:"
if (a>b and a>c):
print "tup1"
elif(b>c):
print "tup2"
else:
print "tup3"
del tup1
tup2=list(tup2)
tup2.append(10)
print tup2
def tupcmp():
tup1=(1,2,3,4,5)
tup2=(4,5,2,3,1,7,8,9)
List=[3,4,2,1,5,8]
print "tuple1:",tup1
print "tuple2:",tup2
print "List:",List
print "Comparison of two tuples:",cmp(tup1,tup2)
print "length of the tuple1:",len(tup1)
print "length of the tuple2:",len(tup2)
print "maximum element of the tuple1:",max(tup1)
print "minimum element of the tuple1:",min(tup1)
print "maximum element of the tuple2:",max(tup2)
print "minimum element of the tuple2:",min(tup2)
List=tuple(List)
print "converting the list into tuple:",List
| false |
93ce9584577775999be0def15e982d515eb6925d | gaya38/devpy | /Python/TVS/27.py | 225 | 4.375 | 4 | import string
a=raw_input("Enter the string to check whether it is palindrome or not:")
b=''.join(reversed(a))
if (a==b):
print "The given string is palindrome"
else:
print "The given string is not a palindrome"
| true |
e534e73d57e92556421e78a70302f613fbb4237a | gaya38/devpy | /Python/assignment/pes-python-assignments-2x.git/45.py | 267 | 4.3125 | 4 | def palindrome(n):
i=''.join(reversed(n))
if (i==n):
return 1
else:
return 0
n=raw_input("Enter the n value:")
k=palindrome(n)
if (k==1):
print "The given string is a palindrome"
else:
print "The given string is not a palindrome"
| true |
5bd66cd08d98ef78ed671a5bca8dd20d2c87615a | SmallGreens/python_cookbook | /src/Basic/1DataType.py | 2,151 | 4.5 | 4 | if __name__ == '__main__':
'''
Link: https://docs.python.org/3.8/tutorial/introduction.html
主要内容:
python 简单算术运算;
python 简单字符串表示;
python list 的相关操作 -- [] -- 为 list
'''
# use python as calculator
print(5 ** 2) # ** 表示 幂 运算
print(5 ^ 2) # 位异或
print(5/2) # 除法会自动将整数转为浮点数,输出 2.5
print(5//2) # 如果想得到整数部分,使用双 `//`, 输出 2
a = 5 + 5j
b = 1 + 1j
print(a * b) # python 支持复数运算 == 10j
# 字符串相关操作
print('Hello "double quotes"') # 可以单引号表示字符串,这时 里面可以用 双引号无需转义
print("Hello 'single quote' ") # 同上
print("use '\\' to escape quotes: \"")
print(r'C:\name') # 使用 r + 字符串,后面的 '\' 将不表示转义
print('first line'
' second line') # 相邻字符串可以自动拼接成单行 -- 字符串变量不行
print(3 * 'Hello ' + 'world!') # 字符串拼接
word = "Python"
print(word[-1]) # 输出 'n', python 中支持 负的 index,表示从 string 尾部开始数
# string 是 immutable 的,word[0] = 'J' 会报错
print(len(word)) # len() 函数,获取 word 的长度
# List 相关操作 -- 这里 的 list 比较像 java 中的数组,但对数组中的元素类型没有限制。虽然一般的,list 中元素为同一类型,但并不强制。
test = [1, 'a', 45]
print(test)
print(type(test[0])) # <class 'int'>
print(type(test[1])) # <class 'str'>
square = [1, 4, 9, 16, 25]
print(square) # 直接打印出 [1, 4, 9, 16, 25] -- 比 java:Arrays.toString(square) 方便太多!!
square[0] = 0 # 数组 是 mutable 的
square.append(6 ** 2) # 向数组中添加元素
words = ['a', 'b', 'c']
arr = [square, words] # 支持多维数组且数组中的元素不需要都为同一类型。这里二维数组的第一个元素是整数数组,第二个为 string 数组
| false |
1a10267b248eebb8e6aa081ca01f8078c776b1d1 | Neethu-Ignacious/Python-Programs | /ceaser_cypher.py | 1,032 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
def ceaser_cypher(my_string,shift_num):
"""This function will find the ceaser cypher encrypted value"""
#initializing the string
cypher = ''
#traversing through the input string
for string in my_string:
if string == '':
cypher = cypher + string
#encrypting uppercase characters
elif string.isupper():
cypher = cypher + chr((ord(string) + shift_num - 65) % 26 + 65)
#encrypting lowercase characters
else:
cypher = cypher + chr((ord(string) + shift_num - 97) % 26 + 97)
return cypher
#getting input string and shift number
input_string = input("Enter the string:")
input_shift_num = int(input("Enter the shift number:"))
#printing the original string
print("\nOriginal string is:",input_string)
#function call to find the encrypted string
print("\nEncrypted string is:",ceaser_cypher(input_string,input_shift_num))
# In[ ]:
| true |
dda53b487106190adbfe2961af80c8355d66dee0 | awarnes/twitter_maze | /twitter_maze/char_freq.py | 1,420 | 4.21875 | 4 | """
Use letter frequency tables to generate a list of letters as they are likely to appear in English.
"""
from math import ceil
def get_data(filename):
with open(filename, 'r') as file:
text = file.read()
return text
def letter_frequency(filename):
"""
Build a list of each letter according to the frequency table.
"""
data = get_data(filename)
lines = data.split('\n')
letters = list()
for letter in lines[:-1]: # Why is there an extra empty string at the end of lines?
pair = letter.split()
times = ceil(float(pair[1]))
freq = list(pair[0] * times)
letters += freq
return letters
def punc_frequency(filename):
"""
Build a list of each punctuation mark according to the frequency table
"""
data = get_data(filename)
lines = data.split('\n')
marks = list()
for mark in lines[:-1]:
pair = mark.split()
times = ceil(float(pair[1]) / 5) # Make this extensible by replacing 5 with the min of the frequencies somehow
huh = list(pair[0] * times)
marks += huh
return marks
def char_frequency(letter_file, punc_file):
"""
Combine letters, punctuation, and spaces.
"""
letters = letter_frequency(letter_file) * 10
marks = punc_frequency(punc_file)
spaces = list(' ' * 30)
all_chars = letters + marks + spaces
return all_chars
| true |
df8f240ade94a547e42d831e7f55b878bd525999 | pjchavarria/algorithms | /leetcode/graph-valid-tree.py | 2,109 | 4.125 | 4 | # https://leetcode.com/problems/graph-valid-tree/
# Given n nodes labeled from 0 to n - 1 and a list of undirected edges
# (each edge is a pair of nodes), write a function to check whether these
# edges make up a valid tree.
# For example:
# Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
# Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
# Hint:
# Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return?
# Is this case a valid tree? Show More Hint
# Note: you can assume that no duplicate edges will appear in edges. Since
# all edges are undirected, [0, 1] is the same as [1, 0] and thus will not
# appear together in edges.
import collections
class Solution(object):
def validTree(self, n, edges):
if len(edges) != n - 1: # Check number of edges.
return False
elif n == 1:
return True
visited_from, neighbors = 0, 1
# A structure to track each node's [visited_from, neighbors]
nodes = collections.defaultdict(lambda: [-1, []])
for edge in edges:
nodes[edge[0]][neighbors].append(edge[1])
nodes[edge[1]][neighbors].append(edge[0])
if len(nodes) != n: # Check number of nodes.
print "c"
return False
# BFS to check whether the graph is valid tree.
visited = {}
q = collections.deque()
q.append(0)
while q:
i = q.popleft()
visited[i] = True
for node in nodes[i][neighbors]:
if node != nodes[i][visited_from]:
if node in visited:
return False
else:
visited[node] = True
nodes[node][visited_from] = i
q.append(node)
return len(visited) == n
print Solution().validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]]), True
print Solution().validTree(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]), False
print Solution().validTree(4, [[0, 1], [2, 3]]), False
| true |
ecacc381c96c0e1b9814ad74caa2e3d058e10abd | jackandrea54/C4T39-NDN | /Lesson4/Ex1.py | 339 | 4.25 | 4 | month = int(input("What month of year: "))
if month <= 0 or month >= 13:
print("Không hợp lệ")
if month >= 2 and month <= 4:
print("It's Xuân")
elif month >= 5 and month <= 7:
print("It's Hạ")
elif month >= 8 and month <= 10:
print("It's Thu")
elif month == 11 or month == 12 or month ==1:
print("It's Đông") | true |
a2f8e0db1c4fd12702b81f469f7272a1043d21ec | azonmarina/AdventOfCode | /d1p2.py | 1,067 | 4.125 | 4 | # --- Part Two ---
# Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on.
# For example:
# ) causes him to enter the basement at character position 1.
# ()()) causes him to enter the basement at character position 5.
# What is the position of the character that causes Santa to first enter the basement?
# import fileinput
floor = 0
first = True
# For fileinput.input we read each line of our file
for line in fileinput.input("input1"):
#For each line we read each element in the file
#We use enumerate so it returns a 2 Tuple with the position (step) and the value in line
for step,i in enumerate(line):
if i == "(":
floor = floor + 1
else:
floor = floor - 1
if floor == -1 and first:
print "the position of the user is {}".format(step+1)
first = False
print "floor's number is {}".format(floor)
| true |
de69a08b2631b852c928d185602639f5333b02ed | kcwong395/SecurityTechnology_Note | /Classical Ciphers/Substitution/VigenereCipher/vigenere_encrypt.py | 697 | 4.28125 | 4 | # This function intends to encrypt plaintext with Vigenere Cipher
def VigenereEncrypt():
plainText = input("Plaintext: ")
key = input("Key: ")
cipher = ""
i = 0
for letter in plainText:
if 'a' <= letter <= 'z':
if i >= len(key):
i = 0
letter = chr((ord(letter) + ord(key[i]) - 2 * ord('a')) % 26 + ord('a'))
i += 1
elif 'A' <= letter <= 'Z':
if i >= len(key):
i = 0
letter = chr((ord(letter) + ord(key[i]) - 2 * ord('A')) % 26 + ord('A'))
i += 1
cipher += letter
return cipher
while True:
print("Ciphertext: " + VigenereEncrypt() + '\n')
| false |
57f5e5350f0291391bd60f8e4fe85db54528e4a4 | rdaniela00/proyectos | /python/ejercicio2for.py | 531 | 4.21875 | 4 | #Crea un programa que pida por teclado introducir una contraseña.
#La contraseña no podrá tener menos de 8 caracteres ni espacios en blanco. Si la contraseña es correcta,
#el programa imprime “Contraseña OK”. En caso contrario imprime “Contraseña errónea”
micontraseña=input(" escribe la contraseña")
contador=0
for i in range(len(micontraseña)):
if micontraseña[i]==" ":
contador=1
if len(micontraseña)<8 or contador>0:
print("la contraseña no es correcta")
else:
print("la contraseña es correcta") | false |
6a775f67b5afe8b2332024c0dc1fb598b8b4b476 | ethanmatthews/KCC-Intro-Mon-Night | /tanner.py | 721 | 4.125 | 4 | # input
weight = float(input("How much does your package weigh?"))
#processes and outputs
if weight > 0 and weight <= 2 :
print("Your shipment will cost $" + str(1.5 * weight) + " at a rate of $1.50 per pound.")
elif weight > 2 and weight <= 6 :
print("Your shipment will cost $" + str(3 * weight) + " at a rate of $3.00 per pound.")
elif weight > 6 and weight <= 10 :
print("Your shipment will cost $" + str(4 * weight) + " at a rate of $4.00 per pound.")
elif weight > 10 and weight <= 1000 :
print("Your shipment will cost $" + str(4.75 * weight) + " at a rate of $4.75 per pound.")
elif weight > 1000 :
print("Too heavy! Keep it under 1000lns!")
else :
print("Error! Unviable package weight!") | true |
4039b0fc58b49b412dff90db8eebe14f725ea4dd | Maximilien-Lehoux/open_food_fact | /menu.py | 1,891 | 4.25 | 4 | from configuration import CATEGORIES
class Menu:
def __init__(self):
pass
def main_menu(self):
"""main menu of the program which indicates the choices"""
print("1 : choisir une catégorie")
print("2 : Voir mes produits substitués")
print("3 : réinitialiser la base de donnée")
print("4 : Quitter le programme")
choice = ""
while choice not in ["1", "2", "3", "4"]:
choice = input("""Choisissez une option (si vous utilisez le
programme pour la première fois, réinitialisez la base de donnée
avec le choix 3 : """)
return choice
def menu_category(self):
"""when the choice "1" is made, the category menu displays the 5
categories chosen in the configuration file"""
choice = ""
while choice not in range(0, len(CATEGORIES)+1):
choice = input("Choisissez une catégorie d'aliment : ")
choice = int(choice)
choice = str(choice)
return choice
def menu_products(self, number_products_saved):
"""in the product menu, the user chooses one"""
choice = 0
while choice <= 0 or choice > number_products_saved:
choice = input("""Choisissez un aliment que vous souhaitez
substituer : """)
choice = int(choice)
choice = str(choice)
return choice
def menu_choice_substitute(self, number_products_saved):
"""the user chooses one of the substitutes"""
choice = 0
while choice <= 0 or choice > number_products_saved:
choice = input("""Choisissez un substitut que vous souhaitez
sauvegarder en notant son nombre
correspondant : """)
choice = int(choice)
choice = str(choice)
return choice
| false |
5edbfd47f420b83d8f9978f31010e0b345cb1ede | siddiqmo10/Python | /user_input.py | 427 | 4.125 | 4 | # Ask a user their weight (in pounds), convert it to kilograms and print on the terminal
weight = input("What is your weight ? ")
# weight_kilo = float(weight) / 2.20462
weight_kilo = int(weight) * 0.45
print("Your weight in kilograms is :", weight_kilo)
# Solution by mosh
weight_lbs = input("Weight (lbs): ")
weight_kg = int(weight_lbs) * 0.45
print(weight_kg)
# i over complciated it will change to int instead of float | true |
68cdba8e2e287307d4bc9c39352126a7ddfdb813 | siddiqmo10/Python | /if_else.py | 1,209 | 4.25 | 4 | is_hot = False
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cool day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
# Exercise
price = 1000000
is_credit_good = True
if is_credit_good:
down_payment = price * 0.1
else:
down_payment = price * 0.2
print(f"Down payment: $ {down_payment}")
# ---------------------------------------
# Logical Operators
has_high_income = True
has_good_credit = True
has_criminal_record = True
if has_high_income and has_good_credit:
print("Eligible for loan")
if has_good_credit and not has_criminal_record:
print("Eligible for loan")
# wont print becuase True and False
# ---------------------------------------
print("---------------------------------------")
# Comparison Operators
temperature = 30
if temperature > 30:
print("It's a hot a day")
else:
print("It's not a hot day")
# Exercise
name = input("Name:")
namelen = len(name)
if namelen < 3:
print("Name must be at least 3 characters")
elif namelen > 50:
print("Name must be a maximum of 50 characters")
else:
print("Name looks good")
| true |
28b434b6172f276e49129f781f9634f62cd2af18 | EstephaniaCalvoC/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 234 | 4.21875 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
"""Replace all occurrences of an element by another in a new list"""
new_list = list(map(lambda x: replace if x == search else x, my_list))
return new_list
| true |
8dbf72c25aa71284d593cfce89ef2180fee0e848 | and-he/Python-Fun | /goldbach.py | 2,623 | 4.375 | 4 | #the goal of this program is to piggy back off of goldbach's conjecture which is:
#is every even number the sum of 2 prime numbers?
#this program will ask for input an even number, and return the two prime numbers that sum up to it
#ex: 6 returns 3 + 3
user_input = int(input("Please enter an even number: "))
#we could just compute a list of the primes for the number, then iterate through the list of primes and subtract the current iteration
#from the input, and see if the leftover result is in the list of primes < user_input
#so ex: user_input = 112, we want to compute a list of all prime numbers between 1 and 112:
#[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109]
#actually notice that there is not always a unique pair of primes, either I can return just one pair, or return all pairs
#how would i return all pairs?
#first let's worry about how we will return a list of all primes < user_input
#we will use the sieve of eratosthenes
#say we have a list of numbers [2, user_input] -> [2, 16] -> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#first we consider the first element to be unmarked, which is 2, and we move down the list of numbers and mark off/remove all the elements that are
#a multiple of 2 and we will get -> [2, 3, 5, 7, 9, 11]
#now we move the cursor to the element after 2, which is 3 and repeat the same process and we will get -> [2, 3, 5, 7, 11]
#if we continued the process for the remaining elements of the list, we'd get -> [2, 3, 5, 7, 11]
def sieve(n):
# the blueprint for this algorithm is to fill an array of booleans that is the size of n + 1
# each index is a correspondence with the naturals 1 -> n
# false is not prime
# true is prime
# by default all values will be true
# as we mark the naturals/sieve through the naturals, we mark the values as false
bool_list = [True]*(n+1)
result = []
# we can remove all the even numbers (except 2) since they are composite
for i in range(4, n+1, 2):
bool_list[i] = False
for comparee in range(3, n+1):
for compared in range(comparee**2, n+1):
if compared%comparee == 0:
bool_list[compared] = False
for i in range(2, n+1):
if bool_list[i]:
result.append(i)
return result
primes = sieve(user_input)
# print(primes)
answers = []
for prime in primes:
difference = user_input - prime
pair = []
if difference in primes and prime <= user_input/2:
pair.append(prime)
pair.append(difference)
answers.append(pair)
print(answers)
| true |
a27871da9ac79cd761e8b6a3a5fcc5dc5a823120 | Vitalik39/itea_october | /lesson_1/task2.py | 232 | 4.21875 | 4 | capitals = {
'Canada' : 'Ottawa',
'Ukraine' : 'Kiev',
'USA' : 'Washington'
}
countries = ['Canada', 'Ukraine', 'USA', 'China',]
for country in countries:
if country in capitals:
print(capitals.get(country)) | false |
564846c5d1349f5a38acc4b4e1bea7842fb77f5d | gevertoninc/python101 | /general/for_loops.py | 291 | 4.125 | 4 | for letter in 'Giraffe attack':
print(letter)
friends = ['Joey', 'Chandler', 'Ross']
for friend in friends:
print(friend)
range_variable = range(10)
print(range_variable)
for index in range_variable:
print(index)
for index in range(1, 9):
print(index)
| true |
7e6a68df15c72c3316443741e5f565b88e318aac | kolyasalubov/Lv-585.2.PythonCore | /HW7/lypovetsky/7.1_positive-negatives.py | 510 | 4.125 | 4 | # https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives
def count_positives_sum_negatives(arr):
positive = 0
negatives = 0
if arr == []:
return []
else:
for i in arr:
if i > 0:
print(f"if i > 0: {i}")
positive += 1
else:
print(f"if i < 0: {i}")
negatives += i
return list(map(int, (str(positive), str(negatives))))
print(count_positives_sum_negatives(
[]))
| false |
16ad03ce1cf964b4ae2ee305554de3a21bdd3705 | andytfma/python-project-euler | /5% difficulty problems/solution9.py | 549 | 4.1875 | 4 | # 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.
def pyth(a, b):
c = (a*a + b*b)**(0.5)
sum = a + b + c
product = a*b*c
if sum == float(int(sum)):
if int(sum) == 1000:
print(a, b, c, sum, product)
def BEEPBEEPscan():
for a in range(0, 500):
for b in range(0, 500):
pyth(a, b)
BEEPBEEPscan() | false |
59e4b29ef8f608a19178e32bd0cefa8fa0387f8c | pasang2044/mycode | /class_project/multfunc.py | 409 | 4.15625 | 4 | #!/usr/bin/env python3
total = 1
number_list =[]
n = int(input("Enter the desired list size "))
print("\n")
for i in range(0,n):
print("Enter the number at index", i)
item = int(input())
number_list.append(item)
print("Here is your list ", number_list)
for elements in range (0, len(number_list)):
total = total * number_list[elements]
print("The multiplied total of the list: ", total)
| true |
aea9c31852b64b641983b815a9a3605912cc05b6 | nsylv/PrisonersDilemma | /printtable.py | 1,255 | 4.4375 | 4 | ''' Basic table-printing function
Given a list of the headers and a list of lists of row values,
it will print a human-readable table.
Toggle extra_padding to true to add an extra row of the spacer
character between table entries in order to improve readability
'''
def print_table(headers,rows,extra_padding=False,spacer=' '):
lengths = []
for i in range(len(headers)):
h = headers[i]
longest = 0
if len(str(h)) > longest:
longest = len(str(h))
for r in rows:
if len(str(r[i])) > longest:
longest = len(str(r[i]))
lengths.append(longest)
#Make the template for each row in the table
template = ' {{: <{}}} |'*len(headers)
template = template.format(*lengths)
#Format the template for the header
heading = template.format(*headers)
#Print out the header
print heading
#Print a spacer row between the header and the data
print '-'*len(heading)
#Print out the rows
for row in rows:
print template.format(*row) #do the printing
if extra_padding: #if extra padding is desired
print spacer*len(heading) #print out a row of the spacer character
return template
| true |
2a74f76989be41bdb34af5bdea9e5f05cf7ca406 | Osaroigb/Space-Invaders | /scoreboard.py | 1,698 | 4.125 | 4 | from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.user_score = 0
self.lives = 3
self.display_score()
def display_score(self):
"""A function that displays the scoreboard"""
self.penup()
self.color("green")
self.hideturtle()
self.setpos(-300, -250)
self.setheading(0)
self.pensize(3)
self.pendown()
self.forward(590)
self.penup()
self.setpos(220, -300)
self.write(f"Score:{self.user_score}", False, "center", ("Courier", 20, "normal"))
self.setpos(-230, -300)
self.write(f"Lives:{self.lives}", False, "center", ("Courier", 20, "normal"))
def update_score(self):
"""A function that updates the score by 1 point whenever a bullet kills an alien"""
self.clear()
self.user_score += 1
self.display_score()
def update_live(self):
"""A function that reduces spaceship by 1 whenever a missile kills a spaceship"""
self.clear()
self.lives -= 1
self.display_score()
def losing_message(self):
"""A function that displays the losing message"""
self.penup()
self.color("red")
self.hideturtle()
self.setpos(0, 0)
self.write(f"Game Over! You Lost!", False, "center", ("Courier", 35, "normal"))
def winning_message(self):
"""A function that displays the winning message"""
self.penup()
self.color("green")
self.hideturtle()
self.setpos(0, 0)
self.write(f"Game Over! You Won!", False, "center", ("Courier", 35, "normal"))
| false |
2585278282d8a452124efbcf32c61a2998398b7f | NguyenVanThanhHust/Python_Learning | /RealPython/Automatic Docs with MkDocs/calculator/calculations.py | 1,310 | 4.53125 | 5 | """Provide several sample math calculations.
This module allows the user to make mathematical calculations.
Examples:
>>> from calculator import calculations
>>> calculations.add(2, 4)
6.0
>>> calculations.multiply(2.0, 4.0)
8.0
>>> from calculator.calculations import divide
>>> divide(4.0, 2)
2.0
The module contains the following functions:
- `add(a, b)` - Returns the sum of two numbers.
- `subtract(a, b)` - Returns the difference of two numbers.
- `multiply(a, b)` - Returns the product of two numbers.
- `divide(a, b)` - Returns the quotient of two numbers.
"""
import os
from typing import Union
def add(a: Union[int, float], b: Union[int, float]) -> float:
"""
Compute and return the sum of two numbers.
Examples:
>>> add(2.0, 3.0)
5.0
>>> add(1, 2)
3.0
Args:
a (float): a number represent first addend in the addition
b (float): a number represent second addend in the addition
Returns:
float: a number representing the arithmic sum of 'a' and 'b'
"""
return float(a+b)
def substract(a, b):
return float(a - b)
def multiply(a, b):
return float(a * b)
def divide(a, b):
if b == 0:
raise ZeroDivisionError("division by zero")
return float(a/b)
| true |
9a0fb9a5358f06ff3574d823cc21c898345543bd | mrgold92/python | /03-Colecciones-y-JSON/conjuntos.py | 507 | 4.25 | 4 | #----------------------------------------------------------------#
# Los conjuntos son una colección de elementos sin índice,
# se dice que está desordenado.
#
# En un conjunto se pueden añadir y eliminar elementos.
#
# Para acceder a los valores tenemos que recorrer la colección
# con for.
#-----------------------------------------------------------------#
set1 = {"java", "python", "android", "java"}
set1.add("ruby")
set1.discard("java")
print(len(set1))
print(set1)
for s in set1:
print(s)
| false |
c0fd682a41ac8134a5bb9e12111649f8f0bf712b | mrgold92/python | /AA-Ejercicios/B.py | 797 | 4.28125 | 4 | #------------------------------------------------------#
# B1. Pregunta un número al operador y muestra el resultado
# de multiplicarlo por PI. Utiliza la constante "math.pi"
# y recuerda incluir "import math"
#
# B2. Muestra la raíz cuadrada del mismo número.
#
# B3. Muestra el arco coseno del mismo número.
#------------------------------------------------------#
import math
def multPi(numero):
return numero*math.pi
def raiz(numero):
return math.sqrt(numero)
def arcoCoseno(numero):
return math.acos(numero)
# B1
numero = int(input("Dime un número: "))
print(f"{numero} * PI = {multPi(numero)}")
# B2
if(numero >= 0):
print(f"Raíz de {numero} = {raiz(numero)}")
# B3
if numero >= -1 and numero <= 1:
print(f"Arco Coseno de {numero}: {arcoCoseno(numero)}")
| false |
a56fbd07ba5b17e6aa13ed7efb3601ee17fc6195 | Pengux1/Pengux1.github.io | /Notes/Python/FIT1045/ech.py | 251 | 4.15625 | 4 | #Selection
if 5 < 7:
print("Maths!")
else:
print("What the heck?")
#Iteration
#Both will print 0-4 in order.
for i in range(0, 5):
print(i)
Num = 0
while Num < 5:
print(Num)
Num += 1 | true |
7a2c881a73df253ed483d24d9ccfa8ff6cf20152 | anatulea/Educative_challenges | /Arrays/08_right_rotate.py | 679 | 4.21875 | 4 | '''Given a list, can you rotate its elements by one index from right to left'''
# Solution #1: Manual Rotation #
def right_rotate(lst, k):
k = k % len(lst)
rotatedList = []
# get the elements from the end
for item in range(len(lst) - k, len(lst)):
rotatedList.append(lst[item])
# get the remaining elements
for item in range(0, len(lst) - k):
rotatedList.append(lst[item])
return rotatedList
print(right_rotate([10, 20, 30, 40, 50], abs(3)))
# Solution #2: Pythonic Rotation
def right_rotate(lst, k):
# get rotation index
k = k % len(lst)
return lst[-k:] + lst[:-k]
# print(right_rotate([10, 20, 30, 40, 50], abs(3))) | true |
330cfb9e1f991f85362a4a521898ace96eb050a4 | anatulea/Educative_challenges | /Linked Lists/09_union&intersection.py | 2,794 | 4.25 | 4 | '''
The union function will take two linked lists and return their union.
The intersection function will return all the elements that are common between two linked lists.
Input #
Two linked lists.
Output #
A list containing the union of the two lists.
A list containing the intersection of the two lists.
Sample Input #
list1 = 10->20->80->60
list2 = 15->20->30->60->45
Sample Output #
union = 10->20->80->60->15->30->45
intersection = 20->60'''
# my solution
from LinkedList import LinkedList
from Node import Node
def union(list1, list2):
if list1.is_empty():
return list2
if list2.is_empty():
return list1
myset= set()
curr= list1.head_node
while curr:
if curr.data not in myset:
myset.add(curr.data)
else:
list1.delete(curr.data)
curr= curr.next_element
curr2 = list2.head_node
while curr2:
if curr2.data not in myset:
myset.add(curr2.data)
list1.insert_at_tail(curr2.data)
curr2= curr2.next_element
return list1
# Returns a list containing the intersection of list1 and list2
def intersection(list1, list2):
if list1.is_empty():
return list2
if list2.is_empty():
return list1
myset= set()
curr= list1.head_node
while curr:
if curr.data not in myset:
myset.add(curr.data)
curr= curr.next_element
myset2 = set()
curr2= list2.head_node
while curr2:
if curr2.data in myset:
myset2.add(curr2.data)
curr2= curr2.next_element
curr3= list1.head_node
while curr3:
if curr3.data not in myset2:
list1.delete(curr3.data)
curr3= curr3.next_element
else:
curr3= curr3.next_element
return list1
# EDUCATIVE SOLUTION
def union(list1, list2):
# Return other List if one of them is empty
if (list1.is_empty()):
return list2
elif (list2.is_empty()):
return list1
start = list1.get_head()
# Traverse the first list till the tail
while start.next_element:
start = start.next_element
# Link last element of first list to the first element of second list
start.next_element = list2.get_head()
list1.remove_duplicates()
return list1
def intersection(list1, list2):
result = LinkedList()
current_node = list1.get_head()
# Traversing list1 and searching in list2
# insert in result if the value exists
while current_node is not None:
value = current_node.data
if list2.search(value) is not None:
result.insert_at_head(value)
current_node = current_node.next_element
# Remove duplicates if any
result.remove_duplicates()
return result | true |
10d00777aa19db0147bad5f4b72b1b473e51b20e | Daniel-Choiniere/python-sequences | /number_lists.py | 440 | 4.375 | 4 | even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
print(min(even))
print(max(even))
print(min(odd))
print(max(odd))
print()
print(len(even))
print(len(odd))
print()
print("mississippi".count("s"))
print("mississippi".count("iss"))
# combines the odd list to the even list
print()
even.extend(odd)
print(even)
# sorting does not create a new list, it arranges the items in the list
even.sort()
print(even)
even.sort(reverse=True)
print(even)
| true |
2376ba55fc9ae154d9030b6c8d4e60345b1c259c | Scotth72/codePractice | /code/practice.py | 617 | 4.34375 | 4 | # print("Hello world")
# Find all the pairs of two integers in an unsorted array that sum up to a given S. For example, if the array is [3, 5, 2, -4, 8, 11] and the sum is 7, your program should return [[11, -4], [2, 5]] because 11 + -4 = 7 and 2 + 5 = 7.
# Given
# have an array of unsorted
# - the sum
# plan
# for loop
# for loop
# if statement
# return answer
# return "no match"
arr = [3, 5, 2, -4, 8, 11]
sum = 7
def find_pair(s, arr ):
for i in range( len(s) -1):
for j in range(i +1, len(s)):
if s(i) + s(j) == sum:
print( i, j)
return
| true |
93c68c98109dea9dc261130dd6a3d7e70f199300 | malikmubeen1/codingground | /Python exercises/BMI.py | 346 | 4.3125 | 4 | # BMI program
print "What is your weight, in pounds?",
weight = 0.453592*int(raw_input())
print "What is your height, in inches?",
height = 0.0254 * int(raw_input())
BMI = weight / (height*height)
print "Your BMI is %r" % BMI
if BMI >= 30:
print "Wow, you are obese. lose some weight plz."
elif BMI >= 25:
print "You are overweight"
| true |
8d951869b445287cc9d0c253f4b6474b475ec8e1 | Helloworld616/algorithm | /SWEA/실습/p_str_01_문자열뒤집기/sol1.py | 639 | 4.1875 | 4 | '''
1. 내장함수(x)
2. 직접 짜기
3. 재귀로 짜기
'''
# 1. 반복문
word = 'abcdef'
reversed_word = ''
for i in range(len(word)-1, -1, -1):
reversed_word += word[i]
print(reversed_word)
# 2. 재귀
def reversing(word, idx):
if idx == 0:
return word[idx]
return word[idx] + reversing(word, idx-1)
word = 'abcdef'
reversed_word = reversing(word, len(word)-1)
print(reversed_word)
# 3. 리스트 활용
word = 'abcdef'
word_list = list(word)
for i in range(len(word_list)//2):
word_list[i], word_list[len(word_list)-i-1] = word_list[len(word_list)-i-1], word_list[i]
print(''.join(word_list))
| false |
f831823fe70f4be4084c66950a77037c1915cce9 | kotalbert/poc1 | /hw1.py | 2,881 | 4.15625 | 4 | print type(3.14)
def clock_helper(total_seconds):
"""
Helper function for a clock
"""
seconds_in_minute = total_seconds % 60
print clock_helper(90)
val1 = [1, 2, 3]
val2 = val1[1:]
val1[2] = 4
print val2[1]
def appendsums(lst):
"""
Repeatedly append the sum of the current last three elements of lst to lst.
"""
sum_of_last_three = 0
# main loop
for i in range(25):
# sum the last three items in the list
last_item_index = len(lst)-1
sum_of_last_three = lst[last_item_index] + lst[last_item_index-1] + lst[last_item_index-2]
lst.append(sum_of_last_three)
sum_three = [0, 1, 2]
appendsums(sum_three)
print sum_three[20]
### ###
class BankAccount:
""" Class definition modeling the behavior of a simple bank account """
__balance = 0
__fees_paid = 0
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self.__balance = initial_balance
def deposit(self, amount):
"""Deposits the amount into the account."""
self.__balance += amount
def withdraw(self, amount):
"""
Withdraws the amount from the account. Each withdrawal resulting in a
negative balance also deducts a penalty fee of 5 dollars from the balance.
"""
self.__balance -= amount
if self.__balance < 0:
self.__balance -= 5
self.__fees_paid += 5
def get_balance(self):
"""Returns the current balance in the account."""
return self.__balance
def get_fees(self):
"""Returns the total fees ever deducted from the account."""
return self.__fees_paid
## Testing ##
print "Testing class."
my_account = BankAccount(10)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(20)
my_account.withdraw(5)
my_account.deposit(10)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(30)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(50)
my_account.deposit(30)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(10)
my_account.deposit(20)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
print my_account.get_balance(), my_account.get_fees()
| true |
5c598337966f1c32ade87d174bce38b1c1243973 | paladugul/assignments | /samba/assignmt15.py | 614 | 4.28125 | 4 | #! user/dell/python
#15. take a string from the user and check contains atleast one small letter or not?
input1= raw_input("Enter a string to check it contains atleast one lowercase letters or not: ")
for i in input1:
if i==i.lower() and i.isalpha():
print "String contains lowercase letters"
break
else:
print "String doesnt contains lower case letters"
output:
Enter a string to check it contains atleast one lowercase letters or not: PYTHOn
String contains lowercase letters
Enter a string to check it contains atleast one lowercase letters or not: WELCOME
String doesnt contains lower case letters | true |
59350092748d02241dd354c3b325cf9752ac614f | shuvabiswas12/Python-Basic | /Strings/string.py | 2,301 | 4.34375 | 4 |
# string in python
# Note: In python there is no character type. Instead of this there has string type
str = "Bangladesh"
print(str)
str = 'Bangladesh'
print(str)
# str = 'Bangladesh's' # here is show an error because of apostropi(')
str = "Bangladesh's" # now its ok
print(str)
str = 'Bangladesh\'s' # an apostropi can be written as this
print(str)
# string can be access by this way in bellow ...
print(str[0])
print(str[1])
print(str[2]) # ....
print("\n")
# string can be access by loop by this way ...
for c in str:
print(c)
# the way that can remove the space after the string ...
str = "Bangladesh "
l = len(str)
print("Len before the operation: ", l)
str = str.rstrip()
l = len(str)
print("Len after the operation: ", l)
print("\n\tProgram Terminated\t\n")
# the way that can remove the space before string ...
str = " Bangladesh"
l = len(str)
print("Len before the operation: ", l)
str = str.lstrip()
l = len(str)
print("Len after the operation: ", l)
print("\n\tProgram Terminated\t\n")
# the way that can remove the space in string both after and before ...
str = " Bangladesh "
l = len(str)
print("Len before the operation: ", l)
str = str.strip()
l = len(str)
print("Len after the operation: ", l)
print("\n\tProgram Terminated\t\n")
str = "Bangladesh is my county. I am in now 24 years old. This years is 2018"
print(str.find("is")) # for finding any sub-string in a string we use find() method.
# if the sub string is found then that method is return the position if not found than its return -1 .
print("\n\tProgram Terminated\t\n")
# replace a string using replace() method
str = "this is county. this is country. this is country"
str = str.replace("this", "This") # this method return a new string after replace any string
print(str)
print("\n\tProgram Terminated\t\n")
str = "Bangladesh is my county. I am in now 24 years old. This years is 2018"
print(str.count("is")) # count function return the value of matching string
print("\n\tProgram terminated\t\n")
# string concat ...
print("<-------------> 4 <---------->")
name = 'My name is ' + 'Hello:Nick:World'.split(':')[1]
print(name)
# ---------------------------------------------------------------
| true |
54b5318910750abb85cbffbc6d119194865c8934 | shuvabiswas12/Python-Basic | /List/list comprehensions.py | 919 | 4.375 | 4 |
# list comprehensions exmaple
# ------------------------------------------------
# program 1
li = [1,2,3,4]
new_li = []
for i in li:
new_li.append(2*i)
print(new_li)
print("program terminated\n\n")
## we can write this program as below using list comprehensions -- >>
new_li = [2*i for i in li]
print(new_li)
print("program terminated\n\n")
# program 2
li = list(range(1, 11))
even = []
for item in li:
if item % 2 == 0:
even.append(item)
print(even)
print("program terminated\n\n")
## we can write this program as below using list comprehensions --- >>
lst = list(range(1, 11))
even = [item for item in lst if item % 2 == 0]
print(even)
print("program terminated\n\n")
# program 3
# write a program to create a list of square of element of another list
new_lst = list(range(1, 20, 2))
print(new_lst)
square_lst = [x*x for x in new_lst]
print(square_lst)
print("program terminated\n\n")
| false |
6bb4e11f3b53e280b5ed3a23d354af5c56e8652a | PedroBernini/ipl-2021 | /set_0/p0_1_2.py | 538 | 4.28125 | 4 | # Programa para calcular a distância euclidiana entre um ponto (px,py) no plano e uma linha especificada pela equação geral da reta.
px = 1
py = 2
a = 3
b = 4
c = 5
def getDistance(point, equation):
numerator = abs((equation['a'] * point['x']) + (equation['b'] * point['y']) + equation['c'])
denominator = (equation['a'] ** 2 + equation['b'] ** 2) ** 0.5
return numerator / denominator
point = {
'x': px,
'y': py
}
equation = {
'a': a,
'b': b,
'c': c
}
out = getDistance(point, equation)
print(out) | false |
8c61d82abc97b735788109c1eec2acf6bf3bef1e | kiranpjclement/Playground_Python | /square_root.py | 300 | 4.40625 | 4 | """11. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer' """
inputno=int(input("What number you want to compute square root for: > "))
output=inputno**(1/2)
outputint=int(output)
print(outputint) | true |
779091c1b5101f3a546fbb1c4fb32dde383e60ad | cmaxcy/project-euler | /Euler25.py | 715 | 4.125 | 4 | '''
Gets the fibonacci number at 'index'
Assumes 0th term is 0, 1st is 1, 2nd is 1, etc...
'''
def get_fib(index):
# used to traverse fibonacci sequence
a = 0
b = 1
# a becomes b, b becomes sum of a and b
for i in range(index):
a, b = b, a + b
return a
'''
Gets length of digits making up number
get_len(89) is 2
'''
def get_len(number):
# easier than dividing by 10 until 0
return len(str(number))
'''
Finds the first fibonacci number with over 1000 digits
'''
def find_num():
for i in range(10000):
# if length of the number is over 1000
if get_len(get_fib(i)) >= 1000:
return i | true |
60d9ecb7448bcb8f5b1a0008bd1c82c95b5ccf8e | mivalov/HackerRank-py | /src/validate_postal_codes.py | 2,433 | 4.5 | 4 | """ Validate postal codes
A valid postal code P have to fulfill both requirements:
1. P must be a number in range from 100000 to 999999 inclusive.
2. P must not contain more than one alternating repetitive digit pair.
Alternating repetitive digits are digits which repeat immediately after
the next digit. In other words, an alternating repetitive digit pair is
formed by two equal digits that have just a single digit between them
For example:
121426 # Here, 1 is an alternating repetitive digit.
523563 # Here, NO digit is an alternating repetitive digit.
552523 # Here, both 2 and 5 are alternating repetitive digits.
The task is to provide two regular expressions 'regex_integer_in_range' and
'regex_alternating_repetitive_digit_pair'. Where:
- 'regex_integer_in_range' should match only integers from
100000 to 999999 inclusive.
- 'regex_alternating_repetitive_digit_pair' should find alternating
repetitive digits pairs in a given string.
Both these regular expressions will be used by the provided code template to
check if the input string P is a valid postal code using the following
expression:
(bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)
Input Format:
Locked stub code in the editor reads a single string denoting P from stdin
and uses provided expression and your regular expressions to validate
if P is a valid postal code
Output Format:
You are not responsible for printing anything to stdout. Locked stub code
in the editor does that.
Sample Input:
110000
Sample Output:
False
Explanation:
11 0 '0' 0 '0': (0, 0) and ('0', '0') are two alternating digit pairs.
Hence, it is an invalid postal code.
Note:
A score of 0 will be awarded using 'if' conditions in your code.
You have to pass all testcases to get a positive score.
"""
import re
# For the regex patterns -> Do not delete 'r'!
regex_integer_in_range = r'^\d{6}$'
regex_alternating_repetitive_digit_pair = r'(\d)(?=\d\1)'
P = input()
print(f'regex_integer_in_range: '
f'{bool(re.match(regex_integer_in_range, P))}')
print(f'regex_alternating_repetitive_digit_pair: '
f'{len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2}')
print('result:',
bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)
| true |
f829a0d8e21315ac40f0471fc066b9c95d144f39 | Brother-Blue/Coding-Challenges | /project_euler/2.py | 554 | 4.15625 | 4 | """"
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."""
a = 0
def fibonacci(cur, prev):
if cur > 4_000_000:
return cur
if cur % 2 == 0:
global a
a += cur
print(a)
return fibonacci(cur + prev, cur)
if __name__ == '__main__':
fibonacci(1, 0) | true |
e11478d6d576d63de76c27cc52c959abfb11c8d2 | alchemistake/random-code-challenges | /maximize_the_product/find_maximum_product.py | 1,916 | 4.15625 | 4 | from functools import reduce
from operator import mul
def find_maximum_product(sequence: list):
if not all([type(x) == int for x in sequence]):
raise TypeError("Every elements must be integer.")
# I am assuming that you want 0 if there is no elements, alternatively It can throw an error here.
if len(sequence) == 0:
return 0
# I am assuming that you want the whole product if there is less than 3 elements.
if len(sequence) < 3:
return reduce(mul, sequence)
# All negatives is a special case:
# If we have access to positives we want smallest negatives to have maximum absolute value
# If we don't have any positives we are trying to find largest negatives to minimize the lost.
if all([x < 0 for x in sequence]):
negatives = sequence[:3]
negatives.sort(reverse=True)
for x in sequence[3:]:
for i, y in enumerate(negatives):
if x > y:
negatives.insert(i, x)
negatives.pop()
break
return reduce(mul, negatives)
# If you want to generalize this to product of k, it is better to use heaps rather than lists.
top_negatives = [0, 0]
top_positives = [0, 0, 0]
# Going through each elements to find smallest negatives and largest positives.
for x in sequence:
if x < 0:
for i, y in enumerate(top_negatives):
if x < y:
top_negatives.insert(i, x)
top_negatives.pop()
break
elif x > 0:
for i, y in enumerate(top_positives):
if x > y:
top_positives.insert(i, x)
top_positives.pop()
break
# Comparing + * + * + VS. - * - * + cases.
return max(reduce(mul, top_positives), reduce(mul, top_negatives) * top_positives[0])
| true |
8afe594b1a6cce3fae41b4c950337628059db87d | xerifeazeitona/PCC_Data_Visualization | /chapter_15/examples/rw_visual_2_multiple_walks.py | 545 | 4.15625 | 4 | """
One way to use the preceding code to make multiple walks without having
to run the program several times is to wrap it in a while loop
"""
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
# Make a random walk.
rw = RandomWalk()
rw.fill_walk()
# Plot the points in the walk.
plt.style.use('classic')
fig, ax = plt.subplots()
ax.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break
| true |
96874a5866ccf2b650fa299c74570eb14b82f31e | mpkrass7/Practice-Python | /ex2.py | 1,486 | 4.4375 | 4 | #Ask the user for a number.
#Depending on whether the number is even or odd,
#print out an appropriate message to the user.
#Hint: how does an even / odd number react differently when divided by 2?
#Extra 1: If number is a multiple of 4, print another message
#Extra 2: Ask the user for two numbers, one to check (num) and one to divide by (check)
#if check divides evenly by num, tell that to user. Otherwise print something else
#def check_int(x):
# if x != int(x):
# print "The number is not an integer"
# given_number = int(raw_input("Please type an integer as a base number: "))
# else:
# print "The number is an integer"
#Function added for extra 1
def even_odd():
while True:
try:
given_number = int(raw_input("Please type an integer as a base number: "))
break
except ValueError:
print ("Not a valid number. Try again")
print given_number
#check_int(given_number)
if (given_number % 2) != 0:
print "The number is odd"
elif (given_number % 4) == 0:
print "The number is a multiple of four"
elif (given_number % 2) == 0:
print "The number is even"
second_number = float(raw_input("Please provide an integer as a divisor "))
#check_int(second_number)
if (given_number % second_number) != 0:
print "The numbers do not divide evenly"
else:
print "The numbers divide evenly"
even_odd()
#function created for extra two
| true |
2f16964fa19697e72e538fe41e50df96fa3bddea | manas3789/Hacktoberfest | /Beginner/03. Python/bubble_sort.py | 297 | 4.15625 | 4 | # bubble sort
def bubble_sort(array):
for i in range(len(array) - 1):
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
return array
array = [2, 3, 5, 4, 1]
print(bubble_sort(array))
| false |
8099d8d00d74d6ffcc1f8076ba517002650ff6e9 | manas3789/Hacktoberfest | /Beginner/03. Python/SalsShipping.py | 2,086 | 4.53125 | 5 | """
Sal runs the biggest shipping company in the tri-county area, Sal’s Shippers.
Sal wants to make sure that every single one of his customers has the best, and most affordable experience shipping their packages.
In this project, you’ll build a program that will take the weight of a package and determine the cheapest way to
ship that package using Sal’s Shippers.
Sal’s Shippers has several different options for a customer to ship their package.
They have ground shipping, which is a small flat charge plus a rate based on the weight of your package.
Premium ground shipping, which is a much higher flat charge, but you aren’t charged for weight.
They recently also implemented drone shipping, which has no flat charge, but the rate based on weight
is triple the rate of ground shipping.
Write a program that asks the user for the weight of their package and then tells them
which method of shipping is cheapest and how much it will cost to ship their package using Sal’s Shippers.
"""
def cost_ground_shipping(weight):
if weight<=2:
return weight*1.50+20.00
elif weight>2 and weight<=6 :
return weight*3.00+20
elif weight>6 and weight<=10:
return weight*4.00+20.00
elif weight>10:
return weight*4.75+20
x=cost_ground_shipping(8.4)
print(x)
premium_ground_shipping=125
def cost_drone_shipping(weight):
if weight<=2:
return weight*4.50
elif weight>2 and weight<=6 :
return weight*9.00
elif weight>6 and weight<=10:
return weight*12.00
elif weight>10:
return weight*14.25
y=cost_drone_shipping(1.5)
print(y)
def cheapest_shipping_method(weight):
ground=cost_ground_shipping(weight)
premium=premium_ground_shipping
drone=cost_drone_shipping(weight)
if ground<premium and ground<drone:
method="Standard Ground"
cost=ground
elif premium<ground and premium<drone:
method="Premium Ground"
cost=premium
else:
method="Drone"
cost=drone
print(" The cheapest option is %.2f with %s shipping." %(cost,method))
cheapest_shipping_method(4.8)
cheapest_shipping_method(41.5) | true |
15ab0dd5426b2fc750c5236a0cd92623ee95559d | manas3789/Hacktoberfest | /Beginner/03. Python/InsSort.py | 729 | 4.34375 | 4 | #Insertion Sort
def insertionSort(ar):
#the outer loop starts from 1st index as it will have at least 1 element to compare itself with
for i in range(1, len(ar)):
#making elements as key while iterating each element of i
key = ar[i]
#j is the element left to i
j = i - 1
#checking condition
while j>=0 and key<ar[j]:
ar[j+1] = ar[j]
j = j - 1
ar[j+1] = key
#taking input from user separated by delimiter
inp = input('Enter a list of numbers separated by commas: ').split(',')
#typecasting each value of the list into integer
ar = [int(num) for num in inp]
insertionSort(ar)
print('The Sorted list is :',ar)
| true |
4d659d9295f6f2a2d03bac745bb710d799624848 | sarahfig824/AutomobileClass- | /ITS320_CTA2_OPTION2.py | 2,487 | 4.3125 | 4 | #------------------------------------------------------------------------
# Program Name:Vehicle Data
# Author:Sarah Figueroa
# Date:10/19/19
#------------------------------------------------------------------------
# Pseudocode: This program will allow the User to type the Brand, Make, Model, Odometer Readings, and Gas Mileage and the
# program will then print out the car information in summary.
# Definition of get_number- these values are to be entered at numbers rather than letter values, if the user imputs a
# letter they will then get a message to input a number.
# Auto_details = The program will output a statement for the user to respond to and then prompot them enter a value.
# The format is designed for the system to prompt the user to enter data based on the value in the following format- Data Item - Input- Output
# The Auto Details dictionary is enclosed in brackets encompasing all the information for the program to give to the user to
#respond to.
#Print(Auto Details)- will prompt the program to print the input and outputs of the program in a summary format
#-----------------------------------------------------------------------
# Program Inputs: Brand, Model, Year, Starting Odometer number, Ending Odometer number, Gas Mileage number
# Program Outputs: 'Miles per gallon': Gas Mileage number, 'Car Model': Model, 'Ending odometer': Ending odometer number,
# Starting Odometer': Starting Odometer number, 'Car Brand': Brand , 'Model Year': Year
#------------------------------------------------------------------------
def get_number(hint):
while True:
try:
value = int(input(hint))
except ValueError:
print('Please input a number')
continue
else:
break
return value
#Using this get_number definition will define how these values should be entered by the user. Without this definition the
#user would be able to type letters instead of numbers for the year, odometer readings and gas mileage.
Auto_details = {'Car brand': input('Car brand:'),
'Car model': input('Car model:'),
'Model Year': get_number('Model Year:'),
'Starting odometer reading': get_number('Starting odometer reading:'),
'Ending odometer reading': get_number('Ending odometer reading:'),
'Miles per gallon': get_number('Miles per gallon:')}
print(Auto_details) | true |
99e19389eff7549c75a105a19d80ef6fc2de535d | rafaelwitter/UFSC | /POO/Aula_9.1.py | 352 | 4.1875 | 4 | ###############################################
#Recebe um numero x e potencializa ao numero y#
###############################################
def main():
x = int(input("Digite um numero para ser potencializado: "))
y = int(input("Digite o numero de potencia: "))
print(potencia(x,y))
def potencia(x, y):
a = x ** y
print(a)
main() | false |
03779db4fc85a214f25fef8d4bfcdf20af746dec | 224apps/Leetcode | /1400-1500/1496.py | 1,216 | 4.125 | 4 | '''
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise.
Example 1:
Input: path = "NES"
Output: false
Explanation: Notice that the path doesn't cross any point more than once.
Example 2:
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.
Constraints:
1 <= path.length <= 10^4
path will only consist of characters in {'N', 'S', 'E', 'W}
'''
class Solution:
def isPathCrossing(self, path: str) -> bool:
dir= ['N', 'S', 'E', 'W']
h = set()
x, y = 0, 0
h.add((0,0))
for p in path:
if p == dir[0]:
x += 1
if p == dir[1]:
x -= 1
if p == dir[2]:
y -= 1
if p == dir[3]:
y += 1
if (x,y) in h:
return True
h.add((x,y))
return False | true |
1687a783543e00e9307f3c501526b3b094cd2919 | jasonkwong11/ultimate-python | /ultimatepython/data_structures/tuple.py | 562 | 4.4375 | 4 | def main():
# This is a tuple of integers
immutable = (1, 2, 3, 4)
print(immutable)
# It can be indexed like a list
assert immutable[0] == 1
# It can be iterated over like a list
for number in immutable:
print("Immutable", number)
# But its contents cannot be changed. As an alternative, you can
# create new tuples from existing tuples
bigger_immutable = immutable + (5, 6)
print(bigger_immutable)
smaller_immutable = immutable[0:2]
print(smaller_immutable)
if __name__ == "__main__":
main()
| true |
bc999276aa750f609d826efac98166e5034e5256 | ganeshzilpe/Guess_the_number | /GuessTheNumber.py | 2,945 | 4.40625 | 4 | #-------------------------------------------------------------------------------
# Name: Guess the Number
# Purpose:
#
# Author: Ganesh
#
# Created: 11/06/2015
# Copyright: (c) Ganesh 2015
# Licence: <your licence>
#Description:
# There are two ranges 0-100 and 0-1000. Computer randomely select one
# number within this range. For range 0-100, 7 chances given to the playerand for range 0-1000,
# 10 chances given to user. User guess the number and computer prompts lower or
# higher clue if the guess is not the number. Based on the clue, the player will play
# for next guess. If chances are exhaused, then new game starts. Player can change the
# range and new game starts.
# This mini project is developed with simplegui library which is available on
# coursera.org online provided by Rice university. Therefore, it is not part of
# source code.
#-------------------------------------------------------------------------------
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui, random, math
secret_number = 0
num_range =100
numberOfTurn = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
global numberOfTurn
print ""
if(num_range == 1000):
print "New game. Range is from 0 to 1000"
print "Number of remaining guesses is 10"
numberOfTurn = 10
else:
print "New game. Range is from 0 to 100"
print "Number of remaining guesses is 7"
numberOfTurn = 7
secret_number = random.randrange(0, num_range)
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global num_range
num_range = 100
new_game()
return
def range1000():
# button that changes the range to [0,1000) and starts a new game
global num_range
num_range = 1000
new_game()
return
def input_guess(guess):
print ""
global secret_number
global numberOfTurn
# main game logic goes here
print "Guess was",int(guess)
numberOfTurn -= 1
print "Number of remaining guesses is ",numberOfTurn
if(int(guess) == secret_number):
print "Correct!"
new_game()
return
if numberOfTurn<1:
print "You ran out of guesses."
new_game()
return
if(int(guess)>secret_number):
print "Lower!"
elif(int(guess)<secret_number):
print "Higher!"
# create frame
frame = simplegui.create_frame("Guess the number", 300, 300)
# register event handlers for control elements and start frame
frame.add_button("Range is [0, 100]", range100, 200)
frame.add_button("Range is [0, 1000]", range1000, 200)
frame.add_input("input the guess", input_guess, 100)
# call new_game
new_game()
| true |
501a66ab24c0213e3ddabadb2937f104f684b593 | raberin/hackerrank-questions | /PY/price_check.py | 1,251 | 4.15625 | 4 | """
Given product list and their prices, check if the products being sold have price discrepencies
Example:
products = [egg, milk, cheese]
productPrices = [2.89, 3.29, 5.79]
productSold = [egg, egg, milk, cheese]
productSoldPrices = [2.89, 2.99, 3.29, 5.79]
Answer => The 2nd batch of eggs sold were sold for 0.10 cents higher there is 1 price discrepency
"""
def price_check(products, product_prices, product_sold, sold_price):
# Create a map to hold all products and prices
map = {}
for i in range(len(products)):
map[products[i]] = product_prices[i]
# Create result and increment when theres a price discrepency
result = 0
# Loop through sold products/prices and cross check with map to see if theres a discrepency
for i in range(len(product_sold)):
# Check map's values and compare with sold prices
if map[product_sold[i]] != sold_price[i]:
result += 1
else:
continue
return result
products = ["egg", "milk", 'cheese']
productPrices = [2.89, 3.29, 5.79]
productSold = ["egg", "egg", "milk", 'cheese']
productSoldPrices = [2.89, 2.99, 3.29, 5.79]
print(price_check(products, productPrices,
productSold, productSoldPrices)) # Answer is 1
| true |
ca0576358a06e4a040e2fd4b47118d8e841e3b77 | floryken/Ch.07_Graphics | /7.2_Picasso.py | 1,670 | 4.4375 | 4 | '''
PICASSO PROJECT
---------------
Your job is to make a cool picture.
You must use multiple colors.
You must have a coherent picture. No abstract art with random shapes.
You must use multiple types of graphic functions (e.g. circles, rectangles, lines, etc.)
Somewhere you must include a WHILE or FOR loop to create a repeating pattern.
Do not just redraw the same thing in the same location 10 times.
You can contain multiple drawing commands in a loop, so you can draw multiple train cars for example.
Please use comments and blank lines to make it easy to follow your program.
If you have 5 lines that draw a robot, group them together with blank lines above and below.
Then add a comment at the top telling the reader what you are drawing.
IN THE WINDOW TITLE PLEASE PUT YOUR NAME.
When you are finished Pull Request your file to your instructor.
'''
import arcade;x=50;w=33.3;i=0;y=44
arcade.open_window(500,500,"Kenny Flory");arcade.set_background_color(arcade.color.BLACK);arcade.start_render()
#Moon
arcade.draw_circle_filled(250,425,50,arcade.color.ASH_GREY)
arcade.draw_circle_filled(250,390,15,arcade.color.BATTLESHIP_GREY)
#Buildings
arcade.draw_rectangle_outline(50,175,100,350,arcade.color.WHITE)
arcade.draw_triangle_outline(0,350,50,450,100,350,arcade.color.WHITE)
arcade.draw_line(0,350,100,350,arcade.color.BLACK)
arcade.draw_rectangle_outline(150,75,100,150,arcade.color.WHITE)
arcade.draw_rectangle_outline(250,125,100,250,arcade.color.WHITE)
arcade.draw_rectangle_outline(400,150,200,300,arcade.color.WHITE)
#doors
for i in range(3):
arcade.draw_rectangle_filled(x,10,15,20,arcade.color.WOOD_BROWN)
x+=100
arcade.finish_render();arcade.run() | true |
3708119728b42de1c8cbb2dd36d7578db2bacb6f | coder-hello2019/Stanford-Algorithms | /Week 1/mergesort.py | 1,431 | 4.40625 | 4 | # Merge sort implementation, done for practice
def mergesort(unsorted):
# base case - if the list has only 1 element, it is sorted
if len(unsorted) <= 1:
return unsorted
# recursive case
else:
# use // so that we can deal with uneven numbers of lists
midpoint = len(unsorted) // 2
# split the list into 2 sections and call mergesort on those
left = unsorted[:midpoint]
right = unsorted[midpoint:]
print(left, right)
# then merge the sorted sub-lists
sortedLeft = mergesort(left)
sortedRight = mergesort(right)
sorted = []
# merge the sorted sub-lists
# what do we do when one list runs out before the other?
for i in range(len(unsorted)):
if len(sortedLeft) == 0:
sorted.extend(sortedRight)
break
elif len(sortedRight) == 0:
sorted.extend(sortedLeft)
break
elif sortedLeft[0] <= sortedRight[0]:
sorted.append(sortedLeft[0])
sortedLeft = sortedLeft[1:]
else:
sorted.append(sortedRight[0])
sortedRight = sortedRight[1:]
return sorted
print(mergesort([5,6,3,1,5]))
print(mergesort([94, 34231, 4, 6837, 45, 34]))
print(mergesort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]))
print(mergesort([]))
print(mergesort([1,1,1,1,1,1]))
| true |
5286f96c82e6f4c175607bbed007e45946bebf52 | luo-songtao/TheAlgorithmsNotesInPython | /src/sort/count_sort.py | 2,068 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: Luo-Songtao
# Email: ryomawithlst@gmail/outlook.com
def count_sort(array, k):
"""计数排序
计数排序是一个非基于比较的排序算法。其核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。 作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。
计数排序算法运行步骤:
- 找出待排序的数组中最大和最小的元素;
- 统计数组中每个值为i的元素出现的次数,存入数组C的第i项;
- 对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加);
- 反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1。
算法复杂度:
- 时间复杂度:
- 最坏::math:`O(n+k)`
- 平均::math:`O(n+k)`
- 最好::math:`O(n+k)`
- 空间复杂度::math:`O(n+k)`
- 稳定性:稳定
Args:
array (list): 待排序数组
k (int): 数组中元素的上界(整数)
Returns:
list: 新创建的已排序数组
Example:
>>> the_array = [41, 22, 36, 7, 21, 27, 18, 3, 79, 8, 43, 27, 45, 36, 84, 7, 47]
>>> count_sort(the_array, max(the_array))
[3, 7, 7, 8, 18, 21, 22, 27, 27, 36, 36, 41, 43, 45, 47, 79, 84]
"""
count_array = [0 for i in range(k+1)]
result_array = [0 for i in range(len(array))]
# 计数
for i in range(len(array)):
count_array[array[i]] += 1
# 统计
for i in range(1, k+1):
count_array[i] += count_array[i-1]
for j in range(len(array)-1, -1, -1):
result_array[count_array[array[j]]-1] = array[j]
count_array[array[j]] -= 1
return result_array
if __name__ == '__main__':
the_array = [41, 22, 36, 7, 21, 27, 18, 3, 79, 8, 43, 27, 45, 36, 84, 7, 47]
result = count_sort(the_array, max(the_array))
print(result) | false |
c119ebb9d32790c530d2e3ae67e283ac2ee2fba2 | zhcheng1/CodingCampusExercise | /Exercises/Exercise3.py | 866 | 4.1875 | 4 |
def converter_2():
user_input = raw_input("Please enter a speed in miles/hour: ")
while not user_input.isdigit():
user_input = raw_input("Please enter an integer as a speed in miles/hour: ")
return user_input
inmile = int(converter_2())
#convert to meter
inmeter = inmile * 1609.34
#convert to barley/day
inbarley = inmeter * 117.647 * 24
#convert to furlong/fortnight
infurlong = inmeter * 1.09361 / 220 * 24 * 7 * 2
#convert to Mach
inmach = inmeter * 3.28084 / 3600 / 1130.0
#convert to percent of speed of light
inlight = inmeter / 3600 / 299792458
print "Original speed in mph is: %.1f" %inmile
print "Converted to barleycorn/day is : %.3f" %inbarley
print "Converted to furlong/fortnight is : %.1f" %infurlong
print "Converted to Mach number is : %s" %inmach
print "Converted to the percentage of the speed of light is : %s" %inlight
| true |
fdded5977a51cec4156ecdad7d6620ba750333e9 | cdojo/Introduction-to-Python-and-Hacking-with-Python | /0x02 - Basics of Python/0x04 - Python Operators/code/operators.py | 1,348 | 4.125 | 4 | #!/usr/bin/python
print("Arithemetic Operators")
x = 15
y = 4
# Output: x + y = 19
print("x + y = ", x+y)
# Output: x - y = 11
print("x - y = ", x-y)
# Output: x * y = 60
print("x * y = ", x*y)
# Output: x / y = 3.75
print("x / y = ", x/y)
# Output: x // y = 3
print("x // y = ", x//y)
# Output: x ** y = 50625
print("x ** y = ", x**y)
print
print("Comparision Operators")
x = 10
y = 12
# Output: x > y is False
print("x > y is ", x > y)
# Output: x < y is True
print("x < y is ", x < y)
# Output: x == y is False
print("x == y is ", x == y)
# Output: x != y is True
print("x != y is ", x != y)
# Output: x >= y is False
print("x >= y is ", x >= y)
# Output: x <= y is True
print("x <= y is ", x <= y)
print
print("Logical Operators")
x = True
y = False
# Output: x and y is False
print("x and y is", x and y)
# Output: x or y is True
print("x or y is", x or y)
# Output: not x is False
print("not x is", not x)
print
print("Identify Operators")
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
print
print("Membership Operators")
x = 'Hello World'
y = {1: 'a', 2: 'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y) | false |
999660ef248cbd4b59410a92d2f6d6e13cd10fcd | EvaSedlarova/pyladies | /03/du.py | 548 | 4.1875 | 4 | if 2 > 1:
print("True")
else:
print("False")
if 1 < 2:
print("True")
else:
print("False")
if 'abc' == 'abc':
print("True")
else:
print("False")
if 'aaa' < 'abc':
print("True")
else:
print("False")
if 'abc' > 'Abc':
print("True")
else:
print("False")
if 'abC' < 'abc':
print("True")
else:
print("False")
if 'abc' < 'abcde':
print("True")
else:
print("False")
if 'abc' < 'ábč':
print("True")
else:
print("False")
if 'abc' != 10:
print("True")
else:
print("False") | false |
8fa4f90dd6bb533275aaaae0f08c96bdc65b4110 | Bhargavpraveen/Basic-programs | /Fibonacci.py | 212 | 4.28125 | 4 | def fibonacci():
n=int(input('How many fibonacci terms do you want to display ? '))
a,b,lst=0,1,[]
for _ in range(n):
lst.append(a)
a,b=b,a+b
return lst
print(fibonacci())
| false |
68424f86e37f0625a5ae3ebaa262fdba0e70487b | NandaJS/SurfPyN | /string_ex5_count dig_print.py | 543 | 4.15625 | 4 | def get_num():
number = (input("Enter an integer : "))
return (number)
def count_dig(num):
count = len(str(num))
if count == 1:
print num+7
else:
if count == 2:
power = str(num ** 5)
print power[-2:]
else:
if count == 3:
number2 = (input("Enter another integer : "))
add = str(num + number2)
print add[-3:]
else:
print "Its not a 3 digit number"
num = get_num()
count_dig(num)
| false |
d73d52a7f6dd3afa09857234454f83a202f73ff4 | jgarmendia/Intro-Python | /files/2-guess_the_number.py | 2,058 | 4.21875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# initialize global variables used in your code
secret_number = 0
remaining = 7
# define event handlers for control panel
def range100():
# button that changes range to range [0,100) and restarts
global secret_number, remaining
secret_number = random.randrange(0, 100)
remaining = 7
print "New Game. Range is 0 to 100"
print "Number of remaining guesses is 7"
print " "
def range1000():
# button that changes range to range [0,1000) and restarts
global secret_number, remaining
secret_number = random.randrange(0, 1000)
remaining = 10
print "New Game. Range is 0 to 1000"
print "Number of remaining guesses is 10"
print " "
def get_input(guess):
# main game logic goes here
global secret_number, remaining
guess = int(guess)
if guess < secret_number:
print "Your guess was", guess
print "Higher!"
remaining += -1
print "You have", remaining, "remain(s)"
print " "
elif guess > secret_number:
print "Your guess was", guess
print "Lower!"
remaining += -1
print "You have", remaining, "remain(s)"
print " "
elif guess == secret_number:
print "Your guess was", guess
print "Correct, you win with", remaining, "remain(s)."
print " "
range100()
else:
print "Restart the game"
if remaining == 0:
print "You lose, secret number was", secret_number
print " "
range100()
# create frame
frame = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements
frame.add_button("Range 0 to 100", range100, 200)
frame.add_button("Range 0 to 1000", range1000, 200)
frame.add_input("Enter your guess", get_input, 200)
# start frame
frame.start()
range100() | true |
1bacfd41430a0dd155bd67e54f8d421202d5ef9b | claytonandersoncode/Projects | /PythagoreanTriples.py | 1,386 | 4.40625 | 4 | def pythagorean(a,b,c):
"""formula for pythoagorean triangles."""
result =((pow(a,2) + pow(b,2)) == pow(c,2))
if result == True:
return("This is a pyhthagorean triple")
else:
return("This is not a pythagorean triple, please try again")
def main():
while True:
try:
side1 = int(input("Enter first side: "))
side2 = int(input("Enter second side: "))
side3 = int(input("Enter third side: "))
if side1 > side2 and side1 > side3:
c = side1
a = side2
b = side3
print (pythagorean(a,b,c))
print('___________________________________________')
elif side2 > side1 and side2 > side3:
c = side2
a = side1
b = side3
print (pythagorean(a,b,c))
print('___________________________________________')
else:
c = side3
a = side2
b = side1
print (pythagorean(a,b,c))
print('___________________________________________')
except ValueError:
print('Please input a valid integer. Starting Over')
print('___________________________________________')
main()
| false |
fa58535a49a03759048aff85582fbce5c5d38c44 | EddieAzzi/me | /week2/exercise1.py | 1,494 | 4.75 | 5 | """
Commenting skills:
TODO: above every line of code comment what you THINK the line below does.
TODO: execute that line and write what actually happened next to it.
See example for first print statement
"""
import platform
# I think this will print "hello! Let's get started" by calling the print function.
print("hello! Let's get started") # it printed "hello! Let's get started"
#A list of words is used to show what "some_words" is equal to. e.g. an example of "some words" would be "does" and "line".
some_words = ['what', 'does', 'this', 'line', 'do', '?']
#This will print a single word in the list above.
for word in some_words:
print(word)
#This will print a number (labelled as "x") of words from the list above.
for x in some_words:
print(x)
#This will print every word in the list above. Possibly creating the sentence, "what does this line do?". OR this will simply print "some_words", which equals to the list.
print(some_words)
#The amount of elements in the list is greater than 3. If a word contains more than 3 words, it will print the word.
if len(some_words) > 3:
print('some_words contains more than 3 words')
#The useful function is defined by the returned tuple. This is then printed.
def usefulFunction():
"""
You may want to look up what uname does before you guess
what the line below does:
https://docs.python.org/3/library/platform.html#platform.uname
"""
print(platform.uname())
#The useful function
usefulFunction()
| true |
cb5431d51aa8df52f2d5b83c429bfa841220381e | GregoryMNeal/Digital-Crafts-Class-Exercises | /Python/List_Exercises/smallest_number.py | 428 | 4.15625 | 4 | # Imports
# Functions
def find_smallest():
numbers = [1,2,5,4,3]
# Find the largest number first
largest = 0
for i in numbers:
if i > largest:
largest = i
# Find the smallest number
smallest = largest
for i in numbers:
if i < smallest:
smallest = i
# Print the smallest number
print(smallest)
# Main
if __name__ == "__main__":
find_smallest()
| true |
7b3291e14ea6273e216bae60d43fa8344497e4c8 | cyyrusli/hr30dayschallenge | /day17.py | 862 | 4.3125 | 4 | # Day 17 coding challenge - More exceptions
# Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and
# p, as parameters and returns the integer result of n**p. If either n or p is negative, then the method must throw
# an exception with the message: n and p should be non-negative.
class Calculator:
def power(self, n, p):
try:
if n < 0:
return 'n and p should be non-negative'
elif p < 0:
return 'n and p should be non-negative'
except ValueError:
return 'Not an integer'
ans = n**p
return ans
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e) | true |
d4acd840883861d18188bcd3fc5c626f3663a3e7 | FL45h-09/TryHackMe | /Adven_of_Cyber-2/Day-15_python/test.py | 315 | 4.15625 | 4 |
names = ["Skidy", "DorkStar", "Ashu", "Elf", "Vishal"]
#name = input("Whats your name??")
#print("Your name is: ", name)
#if name in names:
# print("You are in the list, Welcome to Club Zingat...")
#else:
# print("You are not in the list!!")
for name in names:
print(name)
for i in range(1, 9):
print(i) | false |
8c6a656cec052ed2c3ae2498bd07a54cde601512 | meghakailas/Sayone-Training | /SAYONETASKS/PythonTasks/AssignmentSet1/pgm2.py | 217 | 4.3125 | 4 | #program to generate list and tuple
L=[]
T=()
data=input("Enter elemnts separated by comma:")
elements=data.split(",")
for i in elements:
L.append(i)
print("The list is:",L)
T=tuple(L)
print("The tuple is:",T)
| true |
b904a7242e9d05c0298a6cc6ec133d09f346df4c | Evrgreen/Data-Structures | /stack/stack.py | 1,149 | 4.25 | 4 |
import sys
sys.path.append("../singly_linked_list")
from singly_linked_list import LinkedList
"""
A stack is a data structure whose primary purpose is to store and
return elements in Last In First Out order.
1. Implement the Stack class using an array as the underlying storage structure.
Make sure the Stack tests pass.
2. Re-implement the Stack class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Stack tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Stack?
"""
# class Stack:
# def __init__(self):
# self.size = 0
# self.data = []
# # self.storage = ?
# def __len__(self):
# return len(self.data)
# def push(self, value):
# self.data.append(value)
# def pop(self):
# if len(self.data):
# return self.data.pop()
class Stack(LinkedList):
def push(self, value):
self.add_to_tail(value)
def pop(self):
return self.remove_tail()
my_stack = Stack()
my_stack.push(1)
print(my_stack)
print(f'length is {len(my_stack)}')
| true |
5f2f750fddc4cd6eff008f8da06ccc3621a28295 | MohammadReza-Ahmadi/python-tutorial | /samples/list_comprehension.py | 573 | 4.21875 | 4 | a = [1, 3, 5, 7, 9, 11]
print("a=", a)
c = []
for x in a:
c.append(x * 2)
print(c)
# now do up increase using list comprehension:
d = [x * 2 for x in a]
print(d)
d = [x * 3 for x in a]
print(d)
d = [x ** 2 for x in a]
print(d)
d = [x ** 2 for x in range(2, 5)]
print(d)
print("---- create a descending range:")
for x in range(6, 0, -1):
print(x)
print("------ create squared list:")
f1 = []
for x in range(6, 0, -1):
f1.append(x ** 2)
print(f1)
print("------ create squared list by list comprehensive:")
f2 = [x ** 2 for x in range(6, 0, -1)]
print(f2)
| false |
78c2d0bf8b1f7d98616666fa111fb23cb01251f2 | pushp360/CCC | /Python/Sorting/SelectionSort.py | 605 | 4.25 | 4 | """
Contributed by: Anushree Khanna
Email-ID: anushreek@ieee.org
"""
#Selection Sort uses the concept of finding the minimum element in the unsorted part of the list and adding it to the end of the already sorted subarray.
def SelectionSort(arr):
for i in range(len(arr)):
currentmin=i
for j in range(i+1,len(arr)):
if arr[currentmin]>arr[j]:
currentmin=j
arr[i],arr[currentmin]=arr[currentmin],arr[i]
return arr
"""
Sample Input Case:
Input:
SelectionSort([2,45,98,-11,0,3])
Output:
[-11, 0, 2, 3, 45, 98]
"""
| true |
e6a32b3ff12b7dd3f58f57dda47f9e74182b430d | oratusxd/Estudos_IGTI | /Python/Aulas/aula_pratica.py | 2,055 | 4.65625 | 5 | #Programação orientada a objetos
#Tudo em python é objeto ( que tem propósitos e que o método/função é o caminho para se chegar no propósito)
lista = [1,2,3,4,5,6,7,8,9,10]
print (type(lista)) # Uma forma de saber se é uma função, você vai colocar parenteses ( em textos e sim tem excessões)
print (lista)
x= 42
print(x)
print(type(x))
y = 4.34
print(type(y))
def f(x):
return x + 1
print(type(x))
import math # ele é uma forma de importat pacotes
print(type(math))
x = [3,6,9]
y = [45,"abc"]
print(x[1])
x = [3,6,9]
x[1] = 99 # O método x[1] adiciona o valor em uma posição expecífica (mas, ele substitui o valor velho, pelo novo)
x.append (42) # lembre-se que o append tem a função de adicionar o valor que a gente quer no final da lista
print (x)
y = [45,"abc"]
last = y.pop() # Imprime o ultimo valor de um conjunto de valores indexados
print(last)
# Como que cria classes-> Ela se divide no cabeçalho e corpo
class animal : #Cabeçalho
pass # Corpo ; O pass serve pra continuar a classe/executar a classe- é bem mais complexo ok
if__name__ = '__main__' #
x = animal()
y = animal()
y2 = y
print (y==y2)
print (y==x)
class animal :
pass
x = animal()
y = animal()
x.name= 'Gato'
x.born_year ='2020'
x.pelo = 'branco'
print (x.name)
print(x.born_year)
print(x.pelo)
x.name= 'Cachorro'
x.born_year ='2019'
x.pelo = 'preto'
print (x.name)
print(x.born_year)
print(x.pelo)
'''print(x.__dict__)
print(list.__dict__)
print(tuple.__dict__)
print(dict.__dict__)
print(set.__dict__)'''
#Criando funções para o gato dizer oi
def oi(obj):
print('Miau. Eu sou gato ' + obj.name + ' !')
class animal:
pass
x = animal()
x.name='Bilbo'
oi(x)
def miau(obj): # def de definição, ele define a função
print('Miau')
def ronronar(obj):
print('prprprprp')
class animal :
miar = miau
ronronar = ronronar
x = animal()
x.name = 'Bilbo'
animal.miar(x)
animal.ronronar(x)
| false |
8b2c6cfba8cc675ec4f1c51d58abcdf7fab61b1e | oratusxd/Estudos_IGTI | /Python/Aulas/aula5_2.py | 401 | 4.1875 | 4 | # Criando varíveis de exemplo
a = 50
b = 100
c = 50
#print (a,b,c)
if a == c :
print('A é igual a C')
if a != b :
print ('A é diferente de B')
if a < b:
print('A é menor do que B')
if a <= c:
print('A é menor ou igual do que C')
if b > c:
print('B é maior do que C') # Se tem 2 pontos no código, é obrigatório ter o recuo / identação
| false |
9af89e2a99ed1c6c282b3d9f5834cd7a2c9fa290 | oratusxd/Estudos_IGTI | /Python/Aulas/aula6_3.py | 204 | 4.125 | 4 | '''
Funcionamento do range e os seus argumentos - ele é usado em conjunto com o range
inicio =
termino =
salto =
range ( inicio,termino,salto)'''
for i in range (0,51,10):
print(i)
| false |
1c8620b52f2d2675100cccd5aee9b68d5c13d90c | snehilk1312/Python-Progress | /day_on_date.py | 202 | 4.34375 | 4 | #You are given a date. Your task is to find what the day is on that date.
import datetime as dt
my_date=input()
my_date=dt.datetime.strptime(my_date,'%m %d %Y')
print((my_date.strftime('%A')).upper())
| true |
154d27a9124bebd38888bd10201e6b6c638c91eb | dineshhnaik/python | /PythonSamples/RemoveDuplicates.py | 371 | 4.125 | 4 | # Remove duplicates in list
numbers = [2,6, 4, 5, 6, 5, 8]
duplicate_numbers = []
for num in numbers:
if numbers.count(num) > 1 and num not in duplicate_numbers:
duplicate_numbers.append(num)
print(f'Numbers before removing duplicates: {numbers}')
for num in duplicate_numbers:
numbers.remove(num)
print(f"Numbers after removing duplicates: {numbers}")
| true |
26246efe4044ffc3b014bb3268e3fec04fdd5d40 | hanssenamanda/Chatbot | /n.py | 1,345 | 4.25 | 4 | user_name = input("Hello, Human. What's your name? ")
print(user_name)
while True:
original_user_response = input("My name is cas. What kind of movie would you like to hear about? ")
user_response = original_user_response.lower()
print(user_response)
if "romcom" in user_response:
print("the newest movie in 2021 is Coming 2 America that is rated pg-13")
break
if user_response == "romcom":
print("the newest movie in 2021 is Coming 2 America that is rated pg-13")
break
if "horror" in user_response:
print("the newest movie in 2021 is wrong turn that is rated R")
break
if user_response == "horror":
print("the newest movie in 2021 is wrong turn")
break
if "comedy" in user_response:
print("the newest movie in 2021 is Tom and jerry that is rated pg")
break
if user_response == "comedy":
print("the newest movie in 2021 is Tom and jerry that is rated pg")
break
if "quit" in user_response:
print("is exactly 'quit'")
break
if user_response == "quit":
print("is exactly 'quit'")
break
print("interesting.... \ngood bye")
#outside while loop
#print("good bye") | true |
a0803e18a4ca89904abfbd89e575e7de1a69c3fd | llgeek/leetcode | /628_MaximumProductofThreeNumbers/solution.py | 380 | 4.1875 | 4 | """
sorted based
key point is to find three largest numbers, and two smallest numbers
time complexity: O(nlgn)
"""
class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
left = nums[0]*nums[1]*nums[-1]
right = nums[-1]*nums[-2]*nums[-3]
return max(left, right)
| true |
fb86cc6af7306d64d8b433a8388113c9aaaf8199 | RPMeyer/intro-to-python | /Intro to Python/Homework/CSC110_2 Ch03/hw_03_ex_05.py | 1,612 | 4.34375 | 4 | # Assume you have the assignment xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
# (a) Write a loop that prints each of the numbers on a new line.
# (b) Write a loop that prints each number and its square on a new line.
# (c) Write a loop that adds all the numbers from the list into a variable called total.
# You should set the total variable to have the value 0 before you start adding them up,
# and print the value in total after the loop has completed.
# (d) Print the product of all the numbers in the list. (product means all multiplied together)
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
# (a) Write a loop that prints each of the numbers on a new line.
for i in xs:
print("{}".format(i))
# (b) Write a loop that prints each number and its square on a new line.
for i in xs:
iSquared = i**2
print("{} and its square is: {}".format(i,iSquared))
# (c) Write a loop that adds all the numbers from the list into a variable called total.
# You should set the total variable to have the value 0 before you start adding them up,
# and print the value in total after the loop has completed.
xsTotal = 0
for i in xs:
print("The current sum of the list, {}, plus the next int, {}, is {}".format(xsTotal, i, xsTotal +i))
xsTotal = xsTotal + i
print("The sum of integers in the list xs is {}".format(xsTotal))
# (d) Print the product of all the numbers in the list. (product means all multiplied together)
xsProducts = xs[0]
for i in xs[1:]:
xsProducts = xsProducts * i;
print("{}".format(xsProducts))
print("The product of every integer in the list 'xs' is {}".format(xsProducts))
| true |
2514e006315c3b31b7c989ed486807216918772a | RPMeyer/intro-to-python | /Intro to Python/In Class WS/Chapter_4/WS_Ch04-08.py | 1,151 | 4.25 | 4 | # **********************************************
# WS ch4_8
#
# Write a function, trngl_perim(x1,y1,x2,y2,x3,y3), which takes the
# coordinates of the 3 vertices of a triangle as parameters and
# which returns the perimeter of the triangle. Write a helper
# function, distance(x1,y1,x2,y2), which returns the distance
# between 2 points, which will be in the definition of
# trngl_perim(x1,y1,x2,y2,x3,y3). Check that both functions are
# working correctly.
#
# Find the perimeter of the triangle whose vertices are (1,2),(3,4),(5,6).
# ***********************************************
import math
def distance(x1, y1, x2, y2): #HELPER FUNCTION
'''returns the distance between 2 points (x1, y1) (x2, y2)'''
xDist = x2 - x1
yDist = y2 - y1
dist = math.sqrt(xDist**2 + yDist**2)
return dist
def trngl_perim(x1, y1, x2, y2, x3, y3):
'''takes the coordinates of the 3 vertices (points) of a triangle and which returns perimeter'''
side1 = distance(x1, y1, x2, y2)
side2 = distance(x2, y2, x3, y3)
side3 = distance(x3, y3, x1, y1)
perimeter = side1+side2+side3
return perimeter
print(trngl_perim(1,2,3,4,5,6))
| true |
745246db47ad2549111992f447622e7449722c73 | RPMeyer/intro-to-python | /Intro to Python/Homework/CSC110_2_Ch08/hw_08_ex_07.py | 706 | 4.125 | 4 | # HW:7,8,10
#
#Write a function that reverses its string argument, and satisfies these tests:
# test(reverse("happy") == "yppah")
# test(reverse("Python") == "nohtyP")
# test(reverse("") == "")
# test(reverse("a") == "a")
import sys
def test(did_pass):
''' print result of a test '''
linenum = sys._getframe(1).f_lineno # get the callers line
if(did_pass):
msg = 'Test at line {} ok.'.format(linenum)
else:
msg = ('Test at line {} FAILED'.format(linenum))
print(msg)
def reverse(string):
'''reverses string argument'''
return string[::-1]
test(reverse("happy") == "yppah")
test(reverse("Python") == "nohtyP")
test(reverse("") == "")
test(reverse("a") == "a")
| true |
0d92b0d863287499008ab5be8993e4c280ce5937 | renukrishnan/pythondjangoluminar | /flowcontrols/decisionmaking/assessment1.py | 260 | 4.125 | 4 | #read two numbers
# print true if sum of two numbers is equal to 100 or anyone num is 100
#else print false
num1=int(input("Enter num1:"))
num2=int(input("enter num2:"))
if((num1+num2==100)|(num1==100)|(num2==100)):
print(" True")
else:
print("false") | true |
7a3347411ce42377266da5cf58186b8a6b0fb13f | Yeshitha/AMI-Course-Material | /Lab1/Lab1 Ex3.py | 1,062 | 4.125 | 4 | todo = []
def print_list():
tasks = ['1. insert a new task', '2. remove a task', '3. show all existing tasks', '4. close the program']
for i in tasks:
print(i)
def insert():
print('The name of the task you would like to enter into the list?')
new_task = input()
todo.append(new_task)
def remove():
print('Enter the task you want to remove?')
y = str(input())
todo.remove(y)
def show():
if len(todo) == 0:
print('The list is empty!')
else:
print(todo)
print('todo_manager')
print('Insert the number corresponding to the action you want to perform:')
print_list()
print('Please enter a number:')
while 1 == True:
x = int(input())
if x == 1:
insert()
print('Please enter a number:')
elif x == 2:
remove()
print('Please enter a number:')
elif x == 3:
show()
print('Please enter a number:')
elif x == 4:
print('Program will terminate now')
break
else:
print('Please enter a number between 1 and 4')
| true |
1a9d9943803daca244f7a54c46c6cc7f5819b3c0 | romulovieira777/Programacao_em_Python | /Exercícios e Soluções/exercicio_04.py | 1,719 | 4.34375 | 4 | """
Calcular a média de um aluno que cursou a disciplina de Programação I, a partir da leitura das notas M1, M2 e M3;
passando por um cálculo da média aritmética. Após a média calculada, devemos anunciar se o aluno foi aprovado,
reprovado ou pegou exame.
- Se a média estiver entre 0.0 e 4.0, o aluno está reprovado
- Se a média estiver entre 4.1 e 6.0, o aluno pegou exame
- Se a média for maior do que 6.0, o aluno está aprovado
- Se o aluno pegou exame, deve ser lida a nota do exame. Se a nota do exame for maior do que 6.0,
está aprovado, senão; está reprovado.
"""
# Criando Três Variáveis do Tipo Float
m_01 = float(input('Enter your first note: '))
m_02 = float(input('Enter your second note: '))
m_03 = float(input('Enter your third note: '))
# Criando uma Variável para Calcular a Média
average = (m_01 + m_02 + m_03) / 3
# Criando a Estrutura de Condição
if (average >= 0.0) and (average <= 4.0):
# Imprimi o Valor na se a Primeira Condição for Verdadeira
print('Student is disapproved!')
# Se a Primeira Condição for Falsa Executa esse Elif
elif (average >= 4.1) and (average <= 6.0):
# Se o Aluno ficou de Exame Digitar a Nota do Exame
exam = float(input('Enter exam grade: '))
# Criando a Estrutura de Condição para a Nota do Exame
if exam >= 6.0:
# Imprimi o Valor na Tela se a Nota for Maior que 6.0
print('Student passed the exam!')
# Se a Nota for Menor que 6.0 Executa esse Else
else:
print('Student failing the exam!')
# Se a Primeira e a Segunda Condição forem Falsas Executa esse Elif
else:
# Imprimi o Valor na Tela se a Primeira e a Segunda Condição forem Falsas
print('Student is approved!')
| false |
54d7e3f4f3b2f50c04460c50b96ad10f929d10e3 | romulovieira777/Programacao_em_Python | /Exercícios e Soluções/exercicio_07.py | 1,567 | 4.53125 | 5 | """
Ler uma temperatura em graus Celsius e apresentá-la convertida em graus Fahrenheit.
A fórmula de conversão é F = (9 * C + 160) / 5, na qual F é a temperatura em Fahrenheit e
C é a temperatura em graus Celsius.
- Função para ler e retorna o valor da temperatura (não recebe parâmetro).
- Função para fazer o cálculo (recebe como parâmetro a temperatura em graus Celsius).
- Função para mostrar o resultado, recebendo como parâmetro o valor e fazendo a impressão.
"""
# Criando uma Função que lê a Temperatura em Graus Celsius e Declarando uma Variável
def read_temperature():
# Usuário passa o Valor da Temperatura através do input
temperature = float(input('Enter the temperature in degress Celsus: '))
# Retorna o Valor da Temperatura
return temperature
# Criando uma Função para Converter a Temperatura em Celsius para Fahrenheit e Declarando uma Variável
def calculation(temperature_celsus):
# Convertendo o Valor da Temperatura Celsius para Fahrenheit
temperature_fahrenheit = (9 * temperature_celsus + 160) / 5
# Retorna o Valor da Temperatura Convertido para Fahrenheit
return temperature_fahrenheit
# Criando uma Função para Mostrar o Cálculo da Temperatura na tela e Criando uma Variável
def show(temperature_fahrenheit):
# Imprimindo o Valor na Tela
print(temperature_fahrenheit)
# Chamando as Três Funções Criadas e Criando Três Variáveis
temperature_celsus = read_temperature()
temperature_fahrenheit = calculation(temperature_celsus)
show(temperature_fahrenheit)
| false |
06c489de7776f92c90b4d37e14c49ea562a31161 | Aaradhyaa717/Palindrome-Finder | /Palindrome_finder.py | 737 | 4.59375 | 5 | def palindrome_finder(string):
'''
This function checks if a given string is a palindrome or not.
Example:
Word
Radar Palindrome
Bat Not a palindrome
'''
string_lowercase = string.lower()
#this will makesure there is no confusion in upper and lower case of same letter.
string_reversed= string_lowercase[::-1]
if string_lowercase == string_reversed:
return("Yes!" + string +" is a palindrome.")
else:
return("Opps!"+ string + " is not a palindrome. Try again!")
return(string)
print(palindrome_finder("47"))
print(palindrome_finder("Civic"))
| true |
2d3a0a13ba6fe9a4a6e9dd1e95d492685838c1a5 | juju515/2nd_year | /2. Code Examples/1- Python review/Python Basic Syntax/ex10_functions_call_stack.py | 2,046 | 4.375 | 4 |
#--------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
#--------------------------------------------------------
#---------------------------
# FUNCTION fun1
#---------------------------
def fun1():
# 1. The function has a couple of local vairables: x1 and x2
x1 = 3
x2 = 4
# 2. It then prints the String "Hello"
print("Hello")
# 3. Finally, it calls to the function fun3
fun3()
#---------------------------
# FUNCTION fun2
#---------------------------
def fun2():
# 1. The function defines a local variable: z
z = False
# 2. It then prints the String "Hola"
print("Hola")
# ---------------------------
# FUNCTION fun3
# ---------------------------
def fun3():
# 1. The function defines a local variable: y
y = "Bonjour"
# 2. It then prints the value of the variable
print(y)
# 3. Finally, it calls to the function fun2
fun2()
#-----------------------
# FUNCTION my_main
#-----------------------
def my_main():
# 1. The function first calls to the function fun1
fun1()
# 2. It then calls to the function fun3
fun3()
#---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
#---------------------------------------------------------------
if __name__ == '__main__':
# 1. The execution of the Python program first calls to the function my_main
my_main()
#2. Then it does nothing else. The execution has then finished.
| true |
bec1d1a7e86a85fb1db4d97a1bda12b24617849a | juju515/2nd_year | /2. Code Examples-2/2. Code Examples/1- Python review/Python Basic Syntax/ex13_function_return.py | 2,365 | 4.5 | 4 |
#--------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
#--------------------------------------------------------
#---------------------------
# FUNCTION return_nothing
#---------------------------
def return_nothing(x):
x = x + 1
#---------------------------
# FUNCTION return_one_value
#---------------------------
def return_one_value(x):
x = x + 1
# 1. Before finishing, the function can return the value of a variable
return x
#----------------------------------
# FUNCTION return_multiple_values
#----------------------------------
def return_multiple_values(x):
y = x + 1
z = "Hello"
t = True
# 1. Before finishing, the function can return the value of several variables
return (y, z, t)
#-----------------------
# FUNCTION my_main
#-----------------------
def my_main():
# 1. We create an integer variable and print its value
var1 = 3
return_nothing(var1)
print(var1)
print("------------")
# 2. We can assign to a variable the value returned to the function
new_var = 5
new_var = return_one_value(var1)
print(new_var)
print("------------")
# 3. We can even assign the value returned to the same variable we are calling the function with
print(var1)
var1 = return_one_value(var1)
print(var1)
print("------------")
# 4. We can assign to variables the values returned by a function
(v1, v2, v3) = return_multiple_values(var1)
print(v1)
print(v2)
print(v3)
#---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
#---------------------------------------------------------------
if __name__ == '__main__':
# 1. The execution of the Python program first calls to the function my_main
my_main()
| true |
646705a55145ed4a54d44212827d5afc1296530b | juju515/2nd_year | /2. Code Examples-2/2. Code Examples/1- Python review/Python Compound Types/1. Lists/ex05_lists_remove.py | 1,910 | 4.4375 | 4 |
#--------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
#--------------------------------------------------------
# ----------------------------
# FUNCTION my_main
# ----------------------------
def my_main():
# 1. We create a list
my_list = [11, 5, 3, 7]
print(my_list)
del my_list[1:3]
print(my_list)
# 1. We can use del[position] to delete a concrete index of the list
# However, once again, if we try to access to an element out of the range of the list, then the program will just raise an error.
# Thus, in order to avoid that, we previously use len(list) so as to compute the length of the list
if (len(my_list) > 2):
del my_list[2]
print(my_list)
# 2. Likewise, we can use delete(value) to remove the first appearance of value in the list.
# The problem is that, once again, if this value is not in the list, then the program will raise an error.
# Thus, we can use the function 'in' to check the membership of the value we want to remove
if 5 in my_list:
my_list.remove(5)
print(my_list)
if 9 in my_list:
my_list.remove(9)
print(my_list)
#---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
#---------------------------------------------------------------
if __name__ == '__main__':
my_main()
| true |
90fa7123fc275425e47e009a5739be9b973330b0 | juju515/2nd_year | /2. Code Examples-2/2. Code Examples/1- Python review/Python Compound Types/3. Strings/ex01_strings.py | 2,322 | 4.71875 | 5 |
#--------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
#--------------------------------------------------------
# ----------------------------
# FUNCTION my_main
# ----------------------------
def my_main():
# 1. We create an empty tuple
my_tuple1 = ()
# 2. We create a second tuple
print("-----------------------------")
my_tuple2 = (3, 4.5, True, [1,2])
print(my_tuple2)
# 3. We can access to the elements of the tuple in the same way we access to the lists ones.
print("-----------------------------")
print(my_tuple2[2])
# 4. We can get the length of the tuple
print("-----------------------------")
print(len(my_tuple2))
# 5. We can check if an element belongs to a tuple
print("-----------------------------")
value1 = 4.5 in my_tuple2
value2 = 11 in my_tuple2
print(value1)
print(value2)
# 6. Max of a tuple
print("-----------------------------")
my_tuple3 = (3, 9, 7, 5)
value1 = max(my_tuple3)
print(value1)
# 7. Number of appearances
print("-----------------------------")
my_tuple4 = (3, 9, 3, 5)
value1 = my_tuple4.count(3)
print(value1)
value2 = my_tuple4.count(11)
print(value2)
# 8. Find the index
print("-----------------------------")
my_tuple4 = (3, 9, 3, 5)
value1 = my_tuple4.index(9)
print(value1)
# 9. Tuple comprehension
print("-----------------------------")
my_tuple4 = (3, 9, 3, 5)
value1 = [x for x in my_tuple4 if x > 4]
print(value1)
#---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
#---------------------------------------------------------------
if __name__ == '__main__':
my_main()
| true |
1e06b45f0e721b0fe7f59aa745427b9954fb7d2f | yestherlee/samplefiles | /Homework 2.py | 1,912 | 4.125 | 4 | #Homework 2 by Ye Eun (Esther) Lee
#Establish Monopoly property group data
psize = {'purple':2, 'light blue':3,'maroon':3, 'orange':3, 'red':3, 'yellow':3, 'green':3, 'dark blue':2}
pcost = {'purple':50, 'light blue':50,'maroon':100, 'orange':100, 'red':150, 'yellow':150, 'green':200, 'dark blue':200}
#Establish number to word dictionary
wordform = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve'}
#Input color block user is building on
color = input('Which color block will you be building on?' )
#Input money user has to spend
money = input('How much money do you have to spend?' )
money = int(money)
#Retrieve cost of houses on property from dictionary
cost = pcost[color]
#Calculate number of houses that can be built
houses = money // cost
#Retrieve size of property from dictionary
size = psize[color]
#Calculate evenly distributed number of houses on each property, and remainder to be distributed
num_equal_houses = houses//size
remainder = houses%size
#Identify how many properties will receive extra houses
extra_houses = remainder
#Identify how many properties will receive equal distribution of houses
equal_houses = size - extra_houses
#Determine how many houses those properties with more will receive
num_extra_houses = num_equal_houses + 1
#Convert output numbers to words
word_size = wordform[size]
word_houses = wordform[houses]
word_eqhouses = wordform[equal_houses]
word_num_equal_houses = wordform[num_equal_houses]
word_extra_houses = wordform[extra_houses]
word_num_extra_houses = wordform[num_extra_houses]
#Output result
print('There are',word_size,'properties and each house costs', cost)
print('You can build',word_houses,'houses --', word_eqhouses, 'will have', word_num_equal_houses, 'and', word_extra_houses, 'will have', word_num_extra_houses)
| false |
2734b3f4d4d517988076c52e3f293c89893d34d3 | stldraxvii/code | /prime.py | 341 | 4.15625 | 4 | from factors import list_factors
def find_primes(num):
factors = list_factors(num)
primes = []
for j in factors:
if factors[j] == 'Prime':
primes.append(j)
return primes
def main():
num = input("Enter a number:")
num = int(num)
print(find_primes(num))
if __name__ == '__main__':
main()
| true |
6e20aea0cc4e8f6fc50e006d7f12e92a294e47ba | sirejik/software-design-patterns | /behavioral_patterns/visitor/visitor.py | 1,837 | 4.125 | 4 | """
Describes the operation performed on each object from some structure. The visitor pattern allows you to define a new
operation without changing the classes of these objects.
"""
from __future__ import annotations
from abc import ABCMeta, abstractmethod
class Element(metaclass=ABCMeta):
@abstractmethod
def accept(self, visitor: Visitor):
pass
class ConcreteElementA(Element):
def accept(self, visitor: Visitor):
visitor.visit_concrete_element_a(self)
@staticmethod
def operation_a():
print('operation_a')
class ConcreteElementB(Element):
def accept(self, visitor: Visitor):
visitor.visit_concrete_element_b(self)
@staticmethod
def operation_b():
print('operation_b')
class Visitor(metaclass=ABCMeta):
@abstractmethod
def visit_concrete_element_a(self, element: ConcreteElementA):
pass
@abstractmethod
def visit_concrete_element_b(self, element: ConcreteElementB):
pass
class ConcreteVisitor1(Visitor):
def visit_concrete_element_a(self, element: ConcreteElementA):
print(self.__class__.__name__)
element.operation_a()
def visit_concrete_element_b(self, element: ConcreteElementB):
print(self.__class__.__name__)
element.operation_b()
class ConcreteVisitor2(Visitor):
def visit_concrete_element_a(self, element: ConcreteElementA):
print(self.__class__.__name__)
element.operation_a()
def visit_concrete_element_b(self, element: ConcreteElementB):
print(self.__class__.__name__)
element.operation_b()
element_a = ConcreteElementA()
element_b = ConcreteElementB()
visitor1 = ConcreteVisitor1()
visitor2 = ConcreteVisitor2()
element_a.accept(visitor1)
element_a.accept(visitor2)
element_b.accept(visitor1)
element_b.accept(visitor2)
| true |
ddbc376e5c5fffee92550f6c0711e2442207b847 | barsuk2/python_algos_gb | /Урок 2. Практическое задание recurs/Урок 2. Коды примеров/task_2.py | 459 | 4.21875 | 4 | """Рекурсия против цикла
Вывод чисел по убыванию, начиная с текущего и до нуля
"""
def count_cycle(i):
"""Цикл"""
while i >= 0:
print(i)
i -= 1
count_cycle(3)
def count_recur(i):
"""Рекурсия"""
print(i)
# базовый случай
if i <= 0:
return
# рекурсивный случай
count_recur(i-1)
count_recur(3)
| false |
a13c99cd13cf9add0a87b290dd1ab8d9749608a8 | kreechan123/Python-Basics | /decision_making.py | 308 | 4.125 | 4 | def decision_making():
x = input("Please enter a number between 1,4 and 3:")
if x == 1:
print('You type "I"')
elif x == 4:
print('You type "LIKE"')
elif x == 3:
print('You type "YOU"')
else:
print("Oops! pick number from 1,4 and 3 only!")
decision_making() | true |
5d1ee65e84a15418f9d9739d224223277ee2be8e | LynnePLex/100-days-of-python | /day _two_ bmi-cal.py | 475 | 4.3125 | 4 | height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
#We can check what type the above variables are
#print(type(height))
#print(type(weight))
#converting the str() into float() and int()
a_height = float(height)
b_weight = int(weight)
#calculating the both data types
result = b_weight / a_height ** 2
#Converted into a whole number
bmi = int(result)
print(bmi)
#Output: enter your height in m: 1.6
# enter your weight in kg: 44
# 17
| true |
a0fe4e2348f8b0495cf62dccdc11a6aa8da351fb | bongsang/coding | /binary_gap.py | 1,978 | 4.21875 | 4 | # 1. BinaryGap
# Find longest sequence of zeros in binary representation of an integer.
"""
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
def solution(N)
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].
"""
import numpy as np
def solution(N):
# write your code in Python 3.6
N_bin = bin(N).replace('0b', '')
# print(N_bin)
current_count = 0
best_count = 0
for i in range(len(N_bin)):
checkpoint = N_bin[i]
if checkpoint == '1':
if current_count > best_count:
best_count = current_count
current_count = 0
elif checkpoint == '0':
current_count += 1
# print(f'{i}: {current_count}')
return best_count
if __name__ == '__main__':
# 561892, 74901729, 1376796946
np.random.seed(77)
N = np.random.randint(1, 1376796946)
N = 561892
zero_count = solution(N)
print(f'{N}: {bin(N)}: {zero_count}')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.