blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0845a8058a1f22565907dadcfa4460b724e0f40a | GuuMee/ExercisesTasksPython | /1 Basics/30_units_of_pressure.py | 936 | 4.59375 | 5 | """
In this exercise you will create a program that reads a pressure from the user in kilopascals.
Once the pressure has been read your program should report the equivalent
pressure in pounds per square inch, millimeters of mercury and atmospheres. Use
your research skills to determine the conversion factors between these units.
"""
SQUARE_INCH = 6.895
MILLIMETERS_OF_MERCURY = 7.501
ATMOSPHERE = 101
# Read the input pressure from the user
pressure = float(input("Enter the pressure in kilopascals: "))
# Convert pressure to other units
in_per_square_inch = pressure / SQUARE_INCH
in_millimeters_of_mercury = pressure * MILLIMETERS_OF_MERCURY
in_atmospheres = pressure / ATMOSPHERE
# Display the result
print("Pressure in pounds per square inch will be %.2f" % in_per_square_inch)
print("Pressure in millimeters of mercury will be %.2f" % in_millimeters_of_mercury)
print("Pressure in atmospheres will be %.2f" % in_atmospheres)
| true |
77e332d53b52a2e36485d1a36b3ffd2716122197 | GuuMee/ExercisesTasksPython | /5 Lists/_121_count_the_elements.py | 2,349 | 4.40625 | 4 | """
Python’s standard library includes a method named count that determines how
many times a specific value occurs in a list. In this exercise, you will create a new
function named countRange which determines and returns the number of elements
within a list that are greater than or equal to some minimum value and less than some
maximum value. Your function will take three parameters: the list, the minimum
value and the maximum value. It will return an integer result greater than or equal to
0. Include a main program that demonstrates your function for several different lists,
minimum values and maximum values. Ensure that your program works correctly
for both lists of integers and lists of floating point numbers.
"""
# Determine how many elements in data are greater than or equal to mn and less than mx
# @param data - the list to process
# @param mn the minimum acceptable value
# @param mx the exclusive upper bound on acceptability
# @return the number of elements, e, such that mn <= e < mx
def count_range(data, mn, mx):
# Count the number of elements within the acceptable range
count = 0
for e in data:
# Check each element
if mn <= e < mx:
count += 1
return count
def main():
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Test a case where some elements are within the range
print("Counting the elements in [1..10] that are between 5 and 7...")
print("Result: %d Expected: 2" % count_range(data, 5, 7))
# Test a case where some elements are within the range
print("Counting the elements in [1..10] that are between -5 and 77...")
print("Result: %d Expected: 10" % count_range(data, -5, 77))
# Test a case where some elements are within the range
print("Counting the elements in [1..10] that are between 12 and 17...")
print("Result: %d Expected: 0" % count_range(data, 12, 17))
# Test a case where the list is empty
print("Counting the elements in [1..10] that are between 0 and 100...")
print("Result: %d Expected: 0" % count_range([], 0, 100))
# Test a case with duplicate values
data = [1, 2, 3, 4, 1, 2, 3, 4]
print("Counting the elements in [1, 2, 3, 4, 1, 2, 3, 4] that are",
"between 2 and 4...")
print("Result: %d Expected: 4" % count_range(data, 2, 4))
if __name__ == '__main__':
main()
| true |
9ce4b5a2c382c97c04d06d3b3fb2960644a1c546 | GuuMee/ExercisesTasksPython | /3 Loops/66_compute_a_grade_point_average.py | 1,778 | 4.5 | 4 | """
Exercise 51 included a table that shows the conversion from letter grades to grade
points at a particular academic institution. In this exercise you will compute the
grade point average of an arbitrary number of letter grades entered by the user. The
user will enter a blank line to indicate that all of the grades have been provided. For
example, if the user enters A, followed by C+, followed by B, followed by a blank
line then your program should report a grade point average of 3.1.
You may find your solution to Exercise 51 helpful when completing this exercise.
Your program does not need to do any error checking. It can assume that each value
entered by the user will always be a valid letter grade or a blank line.
"""
A = 4.0
A_MINUS = 3.7
B_PLUS = 3.3
B = 3.0
B_MINUS = 2.7
C_PLUS = 2.3
C = 2.0
C_MINUS = 1.7
D_PLUS = 1.3
D = 1.0
F = 0
sum_grades = 0
count = 0
grade_letter = input("Enter the grade letter: ")
while grade_letter != "":
if grade_letter == "A++" or grade_letter == "A":
sum_grades += A
elif grade_letter == "A--":
sum_grades += A_MINUS
elif grade_letter == "B++":
sum_grades += B_PLUS
elif grade_letter == "B":
sum_grades += B
elif grade_letter == "B--":
sum_grades += B_MINUS
elif grade_letter == "C++":
sum_grades += C_PLUS
elif grade_letter == "C--":
sum_grades += C_MINUS
elif grade_letter == "D++":
sum_grades += D_PLUS
elif grade_letter == "D":
sum_grades += D
elif grade_letter == "F":
sum_grades += F
print("Sum grades", sum_grades)
grade_letter = input("Enter the grade letter: (blank to quit): ")
count += 1
average = sum_grades / (count)
print("The average grade of entered ones: %.2f" % average)
| true |
429e370886bb8a02b6f5bbf15d611128342b985e | GuuMee/ExercisesTasksPython | /6 Dictionaries/_132_postal_codes.py | 2,287 | 4.28125 | 4 | """
In a Canadian postal code, the first, third and fifth characters are letters while the
second, fourth and sixth characters are numbers. The province can be determined
from the first character of a postal code, as shown in the following table. No valid
postal codes currently begin with D, F, I, O, Q, U, W, or Z.
The second character in a postal code identifies whether the address is rural or
urban. If that character is a 0 then the address is rural. Otherwise it is urban.
Create a program that reads a postal code from the user and displays the province
associated with it, along with whether the address is urban or rural. For example,
if the user enters T2N 1N4 then your program should indicate that the postal code
is for an urban address in Alberta. If the user enters X0A 1B2 then your program
should indicate that the postal code is for a rural address in Nunavut or Northwest
Territories. Use a dictionary to map from the first character of the postal code to the
province name. Display a meaningful error message if the postal code begins with
an invalid character.
"""
PROVINCES = {
"Newfoundland": "A",
"Nova Scotia": "B",
"Prince Edward Island": "C",
"New Brunswick": "E",
"Quebed": ["G", "H", "J"],
"Ontario": ["K", "L", "M", "N", "P"],
"Manitoba": "R",
"Saskatchewan": "S",
"Alberta": "T",
"British Columbia": "V",
"Nunavut": "X",
"Northwest Territories": "X",
"Yukon": "Y",
}
NO_WALID = ["D", "F", "I", "O", "Q", "U", "W", "Z"]
def identify_postal_code(string):
province = ""
address = ""
for k in PROVINCES:
for i in range(len(PROVINCES[k])):
if string[0] == PROVINCES[k][i]:
province += k + ", "
elif string[0] in NO_WALID:
province = "The postal code is invalid!"
if string[1] == 0:
address = "rural"
else:
address = "urban"
province_new = province.replace(province[-2], "")
return province_new, address
def main():
print("Enter the postal code (e.g. T2N 1N4):")
line = input()
string = line.upper()
province, address = identify_postal_code(string)
print("It's %s address in %s" % (address, province))
if __name__ == '__main__':
main()
| true |
3537afca8701c17f277c832255b7b12efcd5118a | GuuMee/ExercisesTasksPython | /4_Functions/85_convert_an_integer_to_its_original_number.py | 1,389 | 4.75 | 5 | """
Words like first, second and third are referred to as ordinal numbers. In this exercise,
you will write a function that takes an numeger as its only parameter and returns a
string containing the appropriate English ordinal number as its only result. Your
function must handle the numegers between 1 and 12 (inclusive). It should return an
empty string if a value outside of this range is provided as a parameter. Include a
main program that demonstrates your function by displaying each numeger from 1 to
12 and its ordinal number. Your main program should only run when your file has
not been imported numo another program.
"""
def integer_to_string(num):
if num == 1:
return "first"
elif num == 2:
return "second"
elif num == 3:
return "third"
elif num == 4:
return "fourth"
elif num == 5:
return "fifth"
elif num == 6:
return "sixth"
elif num == 7:
return "seventh"
elif num == 8:
return "eighth"
elif num == 9:
return "ninth"
elif num == 10:
return "tenth"
elif num == 11:
return "eleventh"
elif num == 12:
return "twelfth"
def main():
number = int(input("Enter the integer number (from 1 - 12): "))
string = integer_to_string(number)
print("Your number's original - %s" % string)
if __name__ == '__main__':
main()
| true |
9ef0f06750869ea25e47f00598e56a66a92a4453 | GuuMee/ExercisesTasksPython | /5 Lists/_125_does_a_list_contain_a_sublist.py | 2,044 | 4.375 | 4 | """
A sublist is a list that makes up part of a larger list. A sublist may be a list
containing a single element, multiple elements, or even no elements at all. For example,
[1], [2], [3] and [4] are all sublists of [1, 2, 3, 4]. The list [2, 3] is also a
sublist of [1, 2, 3, 4], but [2, 4] is not a sublist [1, 2, 3, 4] because
the elements 2 and 4 are not adjacent in the longer list. The empty list is a sublist of
any list. As a result, [] is a sublist of [1, 2, 3, 4]. A list is a sublist of itself,
meaning that [1, 2, 3, 4] is also a sublist of [1, 2, 3, 4].
In this exercise you will create a function, isSublist, that determines whether
or not one list is a sublist of another. Your function should take two lists, larger
and smaller, as its only parameters. It should return True if and only if smaller
is a sublist of larger. Write a main program that demonstrates your function.
"""
# The function that determines whether or not one list is a sublist of another.
# @param 'larger' longer list
# @param 'smaller' smaller list
# @return True if and only if smaller list is a sublist of larger
def is_sublist(larger, smaller):
result = False
len_sm = len(smaller)
len_lg = len(larger)
if len_sm <= len_lg:
x = smaller[1] - smaller[0]
for i in range(0, len_lg):
if smaller:
if larger[i] - larger[i - 1] == x:
result = True
elif not smaller:
result = True
elif len_sm > len_lg:
result = "The sublist should be smaller or equal to"
return result
def main():
larger = list(map(int, input("Enter larger list items followed by space (blank for quit): ").split()))
smaller = list(map(int, input("Enter smaller list items followed by space (blank for quit): ").split()))
sublist = is_sublist(larger, smaller)
if sublist == True:
print("Your smaller one is Sublist of larger list!")
else:
print("Your smaller list isn't sublist")
if __name__ == '__main__':
main()
| true |
b2a8a028bc2abebeeb01f1f5bc3466b3b70caa61 | GuuMee/ExercisesTasksPython | /6 Dictionaries/_134_unique_characters.py | 711 | 4.53125 | 5 | """
Create a program that determines and displays the number of unique characters in a
string entered by the user. For example, Hello, World! has 10 unique characters
whilezzzhas only one unique character. Use a dictionary or set to solve this problem.
"""
# Compute the number of unique characters in a string using a dictionary
# Read the string from the user
s = input("Enter a string: ")
# Add each character to a dictionary with a value of True. Once we are done the number
# of keys in the dictionary will be number of unique characters in the string.
characters = {}
for ch in s:
characters[ch] = True
# Display the result
print("That string contained", len(characters), "unique character(s)")
| true |
564cb2f78a42a8646b5356760aef5a2fc4c7504f | GuuMee/ExercisesTasksPython | /5 Lists/_107_avoiding_duplicates.py | 884 | 4.34375 | 4 | """
In this exercise, you will create a program that reads words from the user until the
user enters a blank line. After the user enters a blank line your program should dis�play each word entered by the user exactly once. The words should be displayed in
the same order that they were entered. For example, if the user enters:
"""
# Read a collection of words entered by the user. Display each word entered by
# the user only once, in the same order that the words were entered.
# Begin reading words into a list
words = []
word = input("Enter a word (blank line to quit): ")
while word != "":
# Only add the word to the list if it's not already present in it
if word not in words:
words.append(word)
# Read the next word from the user
word = input("Enter a word (blank lune to quit): ")
# Display the unique words
for word in words:
print(word)
| true |
e9abf62577c80a6c9bea72fcd4addb2785097246 | GuuMee/ExercisesTasksPython | /2 If Statements/39_sound_levels.py | 1,676 | 4.75 | 5 | """
Write a program that reads a sound level in decibels from the user. If the user
enters a decibel level that matches one of the noises in the table then your program
should display a message containing only that noise. If the user enters a number
of decibels between the noises listed then your program should display a message
indicating which noises the level is between. Ensure that your program also generates
reasonable output for a value smaller than the quietest noise in the table, and for a
value larger than the loudest noise in the table.
"""
NOISES = {
"Jackhammer": 130,
"Gss lawnmower": 106,
"Alarm clock": 70,
"Quiet room": 40
}
JACKHAMMER = 130
GAS_LAWNMOVER = 106
ALARM_CLOCK = 70
QUIET_ROOM = 40
sound_level = int(input("Enter the sound level int decibels: "))
if sound_level == JACKHAMMER:
print("This is Jackhammer's sound")
elif sound_level == GAS_LAWNMOVER:
print("This is Gas lawnmower's sound")
elif sound_level == ALARM_CLOCK:
print("This is Alarm clock's sound")
elif sound_level == QUIET_ROOM:
print("This is sound of Quiet room")
elif sound_level < QUIET_ROOM:
print("This sound has the smaller than the quietest noise")
elif sound_level > JACKHAMMER:
print("This sound has the larger than the loudest noise")
elif QUIET_ROOM < sound_level < ALARM_CLOCK:
print("The sound noise between the 'Quiet room' and the 'Alarm clock' noise")
elif ALARM_CLOCK < sound_level < GAS_LAWNMOVER:
print("The sound noise between the 'Alarm clock' and the 'Gas lawnmower' noise")
elif GAS_LAWNMOVER < sound_level < JACKHAMMER:
print("The sound noise between the 'Gas lawnmower' and the 'Jackhammer' noise")
| true |
389b5704929af7f6665197f1cc7aebf7fba817e0 | Tsarcastic/2018_code_wars | /6kyu_kebabize.py | 461 | 4.125 | 4 | """https://www.codewars.com/kata/57f8ff867a28db569e000c4a/train/python ."""
def kebabize(string):
"""Turn from camel case into kebab case."""
kebab = ""
for i in string:
if i.isdigit():
pass
elif kebab == "":
kebab += i.lower()
elif i.isupper():
kebab += "-"
kebab += i.lower()
elif i.islower():
kebab += i.lower()
return kebab
| false |
7b5755046b371d33bac343efb1cd0cb3e62ede8e | Tsarcastic/2018_code_wars | /6kyu_exclamation_marks.py | 623 | 4.21875 | 4 | """
Find the balance.
https://www.codewars.com/kata/57fb44a12b53146fe1000136/train/python
"""
def balance(left, right):
"""Find the balance of left and right."""
def weigh(side):
"""Find the weight of each side."""
weight = 0
for i in side:
if i == "!":
weight += 2
if i == "?":
weight += 3
return weight
left_weight = weigh(left)
right_weight = weigh(right)
if left_weight > right_weight:
return "Left"
elif right_weight > left_weight:
return "Right"
else:
return "Balance"
| true |
389ef03dd353855ebd9f08f9e94b5a17ec249cbf | SuhaybDev/Python-Algorithms | /5_implement_bubble_sort.py | 487 | 4.375 | 4 | def bubbleSort(arr):
n = len(arr)
# Iterate through all array elements
for x in range(n):
for y in range(0, n-x-1):
# Interchange places if the element found is greater than the one next to it
if arr[y] > arr[y+1] :
arr[y], arr[y+1] = arr[y+1], arr[y]
array = [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
# Call bubbleSort function on array
bubbleSort(array)
# Print sorted array
print (array)
| true |
82fe374357589692c9c06b073c60ef25252e475a | Srijha09/Leetcode-Solutions- | /Easy/countPrimes.py | 504 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 1 20:23:58 2021
@author: Srijhak
"""
def countprimes(n):
if n == 0:
return 0
if n == 1:
return 0
primes = [1]*n #create a list consisting of all true
primes[0]=0
primes[1]=0
i = 2
while i<n:
tmp = i
if primes[i]:
tmp+=i
while tmp<n:
primes[tmp]=0
tmp+=i
i+=1
return(sum(primes))
num = 10
print(countprimes(num)) | false |
04ef2144425b8bffa456085932a3cbd90a295c06 | GLOOMYY/FISIC-CALC | /modulo_fisica.py | 1,622 | 4.15625 | 4 |
def distancia():
print("Distancia")
v = float(input("Ingrese la velocidad "))
t = float(input("Ingrese el tiempo "))
d = v * t
print("El resultado es: ", d )
def velocidad():
print("Velocidad")
d = float(input("Ingrese la distancia "))
t = float(input("Ingrese el tiempo "))
v = d / t
print("El resultado es: ", v)
def tiempo():
print("Tiempo")
d = float(input("Ingrese la distancia "))
v = float(input("Ingrese la velocidad "))
t = d / v
print("El resultado es: ", t)
def km_a_m():
print("Kilometros a metros")
km = float(input("Ingrese los kilometros "))
m = km * 1000
print("El resultado es: ", m ," metros")
def hrs_a_s():
print("Horas a segundos")
h = float(input("Ingrese las horas "))
s = h * 3600
print("El resultado es: ", s, " segundos")
def error_absoluto():
print("Error absoluto")
valor_teorico = float(input("Ingrese el valor teorico "))
valor_experimental = float((input("Ingrese el valor experimental ")))
resultado = abs(valor_teorico - valor_experimental)
print("El error absoluto es: ", resultado)
def error_relativo():
print("Error relativo")
error_absolut = float(input("Ingrese el error absoluto "))
valor_teorico = float(input("Ingrese el valor teorico "))
resultado = error_absolut/valor_teorico
print("El error relativo es: ", resultado)
def porcentaje_error():
print("Porcentaje de error")
error_relati = float(input("Ingreese el error relativo "))
resultado = error_relati*(100/100)
print("El porcentaje de error es de: ", resultado, "%")
| false |
624045aebcbcfae035f0d6c7dcdbfc8fc4bb1410 | Abdurrahmans/Data-Structure-And-Algorithm | /SeriesCalculation.py | 386 | 4.15625 | 4 | import math
number=int(input("Enter any positive number:"))
sum = 0
sum = number*(number + 1)/2
print("The sum of series upto {0} = {1}".format(number,sum))
total = 0
total =(number*(number+1)*(2*number+1))/6
print("The sum of series upto {0} = {1}".format(number,total))
total =math.pow(number*(number+1)/2,2)
print("The sum of series upto {0} = {1}".format(number,total)) | true |
b9bdc8a9d9bc5a4bb7a0e416c0034dd6cabf82bf | Abdurrahmans/Data-Structure-And-Algorithm | /SortingAlgorithm/BubbleSortDescendingOrder.py | 551 | 4.1875 | 4 | inputArray = []
ElementCount = int(input("Enter number of element in array:"))
print("Enter {} number".format(ElementCount))
for x in range(ElementCount):
value = int(input("Please inter the {} element of list:".format(x)))
inputArray.append(value)
for i in range(ElementCount-1):
for j in range(ElementCount-i-1):
if inputArray[j] < inputArray[j+1]:
temp = inputArray[j]
inputArray[j]=inputArray[j+1]
inputArray[j+1]=temp
print("The Sorted List in Descending order :",inputArray) | true |
4af43c0a242bc188ae56cad5d6035d6cc3cc40af | candytale55/lambda-challenges-Py_3 | /rate_movie.py | 351 | 4.21875 | 4 | # rate_movie takes a number named rating. If rating is greater than 8.5, return "I liked this movie". Otherwise return "This movie was not very good"
rate_movie = lambda rating : "I liked this movie" if rating > 8.5 else "This movie was not very good"
print rate_movie(9.2)
# I liked this movie
print rate_movie(7.2)
# This movie was not very good
| true |
cf9b83419c713fe08a22f87d40d6bef18538bfa6 | liuhu0514/py1901_0114WORK | /days0121/list列表.py | 698 | 4.59375 | 5 | '''
列表的语法结构:通过一堆方括号包含起来的数据序列,可以存放重复数据
列表:list
可以嵌套
'''
list1=[1,"o",3,["a:","b"]] # 可以嵌套
# 列表数据的查看,可以通过索引/下标进行查看
print(list1[0])
print(list1[3][1])
# 列表中追加数据:append()
list1.append(["l","hu"])
print(list1)
# 列表中指定位置追加数据:insert()
list1.insert(1,["a","m"])
print(list1)
# 删除列表末尾的元素:pop()
list1.pop()
print(list1)
# 删除列表中指定位置的元素:pop(index
list1.pop(2)
print(list1)
# 将列表中指定位置的数据进行替换,直接给对应的索引赋值
list1[0]=[1,2]
print(list1)
| false |
d977a962c7e16af4c634881646cbb0f3e0b4aad7 | abdulahad0001/Prime_number_cheker | /primalitiy.py | 429 | 4.125 | 4 | num1 = int(input("Enter your number:"))
if num1 > 1:
for integer in range(2,num1):
if(num1%integer)==0:
print(num1, "is not a prime number")
break
else:
print("Congrats!", num1,"is a prime number")
print("\n When you're checking for 0 and 1, Note that 0 and 1 are not prime numbers")
#You're not allowed to remove this line, if you share it
print("\n", "Created by Md. Abdul Ahad Khan")
| true |
b1751095b11d6bfb0adcc764e58a0d13ace5a52e | gyuri23/tkinter_examples | /tkinter_grid.py | 1,142 | 4.1875 | 4 | import tkinter
root = tkinter.Tk()
for r in range(3):
for c in range(5):
tkinter.Label(root, text='R%s/C%s' % (r, c),
borderwidth=1).grid(row=r, column=c)
# column : The column to put widget in; default 0 (leftmost column).
#
# columnspan: How many columns widgetoccupies; default 1.
#
# ipadx, ipady :How many pixels to pad widget, horizontally and
# vertically, inside widget's borders.
#
# padx, pady : How many pixels to pad widget, horizontally and
# vertically, outside v's borders.
#
# row: The row to put widget in; default the first row that is still
# empty.
#
# rowspan : How many rowswidget occupies; default 1.
#
# sticky : What to do if the cell is larger than widget. By default,
# with sticky='', widget is centered in its cell. sticky may be the
# string concatenation of zero or more of N, E, S, W, NE, NW, SE, and
# SW, compass directions indicating the sides and corners of the cell
# to which widget sticks.
root.mainloop()
| true |
926bdeb78d59c57aeee972a8e72a816c227833bf | satish3922/ML_python | /sum_magic.py | 1,086 | 4.21875 | 4 | #!/usr/bin/env python3
# Program of magic Addition
#Taking input of 1st Number
num1 = int(input("Enter 1st Number :"))
#Calculating Magic Sum (result = add 2 before num-2)
result1 = '2' + str(num1 - 2)
print("User : ",num1)
print("User : *****")
print("Comp : *****")
print("User : *****")
print("Comp : *****")
print("=============")
print("Sum : ",result1)
print(" ")
#Taking input of 2nd Number
num2=int(input("Enter 2nd Number :"))
#Calculating 2nd result by (each digit in num2 will be subtracted from 9)
result2 = int(len(str(num2))*'9') - num2
print("User : ",num1)
print("User : ",num2)
print("Comp : ",result2)
print("User : *****")
print("Comp : *****")
print("=============")
print("Sum : ",result1)
print(" ")
#Taking input of 3rd Number
num3=int(input("Enter 3rd Number :"))
#Calculating 2nd result by (each digit in num2 will be subtracted from 9)
result3 = int(len(str(num3))*'9') - num3
print("User : ",num1)
print("User : ",num2)
print("Comp : ",result2)
print("User : ",num3)
print("Comp : ",result3)
print("=============")
print("Sum : ",result1)
print(" ")
| true |
17d6cd0b17d82a791c56fd945ec30167335593e6 | juliano60/scripts_exo | /ch2/exo3.py | 259 | 4.15625 | 4 | #!/usr/bin/env python3
## enter a list of strings
## output them in sorted order
print("Enter a list of words on separate lines: ")
words = []
while True:
try:
words.append(input())
except:
break
print()
print(list(sorted(words)))
| true |
4cd35312a195fa64910ac773618152a52f340377 | uccgit/geekthology | /menu_a.py | 1,850 | 4.125 | 4 | import os
# This is the menu system for the game
# The plan is to create custom menus where needed
def display_title_bar():
#clears the terminal screen, and displays a title bar
os.system('cls' if os.name == 'nt' else 'clear')
print "\t*******************************************"
print "\t*** Welcome - The game is an adventure ***"
print "\t*******************************************"
def main_menu_choice():
print "\n[1] Start A New Game."
print "[2] Continue Your Game."
print "[3] Quit The Game."
return raw_input("What would you like to do? ")
def travel_menu_choice():
print "\n[1] Enter 1 to explore"
print "[2] Enter 2 to run"
print "[3] Enter 3 to look around"
print "[4] Enter 4 to leave area"
print "[5] Enter 5 to return to main menu"
return raw_input("What would you like to do? ")
def main_menu():
'''Very basic main menu'''
choice = ''
while choice != '3':
choice = main_menu_choice()
display_title_bar()
if choice == '1':
travel_menu()
elif choice == '2':
print "You see a person standing next to you"
elif choice == '3':
exit(0)
else:
print "I don't understand, please try again"
def travel_menu():
'''Travel Menu'''
choice = ''
while choice != '5':
choice = travel_menu_choice()
display_title_bar()
if choice == '1':
print "You explore the", locations[0], "but find nothing"
elif choice == '2':
print "You run and hide"
elif choice == '3':
print "You look around and see something"
elif choice == '4':
print "You have chosen to leave this area"
elif choice == '5':
main_menu()
else:
break
main_menu()
| true |
85a1aa8da913d587c0161b010dcecb222f10cb99 | stillaman/python-problems | /Python Program to Check Prime Number.py | 211 | 4.15625 | 4 | num = int(input("Enter number:: "))
for i in range (2,num):
if num%i == 0:
print("The Given number is not Prime Number!!")
break
else:
print("The Given Number is a Prime Number!!")
| true |
fbc8cdab7eaa40a0637b7b0535f62d5cded48274 | lucas-jsvd/python_crash_course_2nd | /python_work/modulo_restaurante.py | 998 | 4.40625 | 4 | class Restaurante():
"""Uma classe para descrever restauranes."""
def __init__(self, nome, cozinha):
self.nome = nome
self.cozinha = cozinha
self.num_atendimento = 0
def descricao(self):
print(f'\nNome do restaurante: {self.nome}')
print(f'Tipo de cozinha: {self.cozinha}')
def aberto(self):
print(f'\nO Restaurante, {self.nome}, está aberto.')
def set_num_atendimento(self, num_atendimento):
self.num_atendimento = num_atendimento
def incr_num_atendimento(self, num_atendimento):
self.num_atendimento += num_atendimento
class CarrinhoSorvete(Restaurante):
"""Classe que representa um carrinho de sorvete."""
def __init__(self, nome, cozinha):
super().__init__(nome, cozinha)
self.sabores = ["Chocolate", "Limão", "Morango", "Kiwi", "Umbu"]
def exibe_sabores(self):
print("\nOs sabores disponiveis são: ")
[print(f'\t{sabor}') for sabor in self.sabores]
| false |
193caba1bc562722fefadd6e795713a66e041ba1 | jmanning1/python_course | /IfProgramFlow/adv_ifprogramflow.py | 797 | 4.21875 | 4 | age = int(input("How old are you? "))
#if (age >=16) and (age <= 65): #looks for the Range between 16 and 65
# if 15 < age < 66:
# print("Have a good day at work")
#Brackets (Parentatesis) make things easier to read and also make you intentions in the code clearer.
if (age < 16) or (age > 65): #Or looks for the positive whereas And looks for the negative
print("Enjoy your free time")
else:
print("have a good day at work")
#if (some_condition) or (some weird function that does stuff()):
#do something
#Booleans don't exist in Python
x = "false"
if x:
print("x is true")
x = input("Please Enter some Text ")
if x:
print("You entered '{}'".format(x))
else:
print("Plese enter something")
print(not False)
print(not True)
| true |
5612948f2d4f70a88b2aaa498337f31e950f92e2 | hoomanali/Python | /ProgrammingAssignments/pa2.py | 785 | 4.375 | 4 | # Ali Hooman
# alhooman@ucsc.edu
#
# Programming Assigment 2
# BMI Calculator
#
# BMI = (massKg) / (heightM**2)
print("**** BMI Calculator ****")
# Get weight in pounds
weightPounds = float(input("Your weight (pounds): "))
# Convert to kg ( 1 pound = 0.45 Kg )
massKg = weightPounds * 0.45
# Get height in inches
heightInches = float(input("Your height (inches): "))
# Convert to meters ( Divide by 39.37 )
heightMeters = heightInches / 39.37
# BMI = (massKg) / (heightM**2)
BMI = int( massKg / ( heightMeters**2 ) )
# Print BMI and health tip
if BMI < 18:
print("BMI: ", BMI, ". You are underweight.", sep="")
elif BMI > 30:
print("BMI: ", BMI, ". You are overweight.", sep="")
else:
print("BMI: ", BMI, ". Your weight is healthy.", sep="")
| false |
d7644b4c86ed96dc404b3dd96728d325b6c1bb24 | hoomanali/Python | /ClassProblems/RectArea.py | 766 | 4.40625 | 4 | #
# Ali Hooman
# alhooman@ucsc.edu
# Class Problem 2 - Area of Rectangle
#
# Ask user for inputs for height and width.
# Calculate area of rectangle and print the result
# Calculate circumference
#
# Get height
heightStr = input("Enter height: ")
heightInt = int(heightStr)
# Get width
widthStr = input("Enter width: ")
widthInt = int(widthStr)
# Output area (width * height)
area = heightInt * widthInt
print("Area is ", area)
# Output circumference ( 2*(width + height) )
circumference = 2 * ( widthInt + heightInt )
print("Circumference is ", circumference)
# Output:
# ali@eduroam-169-233-227-170:~/Brogramming/Python/CMPS-5P/ClassProblems$ !!
# python3 RectArea.py
# Enter height: 2
# Enter width: 4
# Area is 8
# Circumference is 12
| true |
36634355781134ba0a2ff1ce4e7c18500e82e8f8 | seanjohnthom/Automatetheboringstuff | /guessing_game.py | 710 | 4.125 | 4 | #this is a guess the number game
import random
print("Hello, what is your name?")
name = input()
print("Hi " + name + "!", "I'm thinking of a number between 1 and 20.")
secret_number = random.randint(1,20)
#This will allow X number of guesses
for guesses_taken in range (1,7):
print("Take a guess")
guess = int(input())
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
break # this will trigger if they guessed correctly
if guess == secret_number:
print("Good Job " + name +"!" +" It took you " + str(guesses_taken) + " guesses!" )
else:
print("Nope. The number I was thinking of was " + str(secret_number))
| true |
148d3eb2808fc8484bf4163fbebef45e5fde9bd7 | akshar-bezgoan/python-home-learn | /Lessons/Apr17/conversation.py | 248 | 4.125 | 4 | print('NOTICE ENTER ONLY IN LOWER-CASE!')
name = raw_input('Hi, what is your name:')
print str('Hello ') + name
mood = raw_input('How are you?:')
print str('I am also ') + mood
q = raw_input('So anything happening today?:')
print ('Me as well')
| true |
e8f510d5b623a730f36e3845d10b97dc00b494f1 | mahesh671/Letsupgrade | /Prime number.py | 307 | 4.15625 | 4 | #this is mahesh kumar
#prime number assignment using functions
def PrimeorNot(n):
for i in range(2,n):
if n%i==0:
return False
else:
pass
return True
number = int(input("Enter the number: "))
if PrimeorNot(number):
print(number,":Number is prime")
else:
print(number,": is not Prime")
| true |
8632095039153860069de824710456d19e8c88ed | Hacksdream/Leetcode_Training | /2.LinkList/linkedlist_tail_insert.py | 886 | 4.15625 | 4 | # -*- coding:utf-8 -*-
class Node():
def __init__(self,data=None):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def print_list(self):
node = self.head
while node:
print(node.data)
node = node.next
def tail_insert(self,new_data):
new_data = Node(new_data)
node = self.head
if node is None:
self.head = new_data
return
last_node = node.next
while last_node.next:
last_node = last_node.next
last_node.next = new_data
n1 = Node("1")
n2 = Node("2")
n3 = Node("3")
n1.next = n2
n2.next = n3
list = LinkedList()
list.head = n1
print("插入前:")
list.print_list()
print("-"*50)
print("插入后:")
list.tail_insert("4")
list.print_list()
| false |
1d470ce86c70853849831afeead8efdb9c54f4ff | Nidhi331/Data-Structures-Lab | /BipartiteGraph.py | 1,867 | 4.21875 | 4 |
#Bipartite graph
# A graph can be divided to two sets such that there is not any two vertices
# in a single set which contain an edge
# S(x) != S(y)
# Can a tree be Bipartite tree?
"""
1
2 3
4 5 6 7
"""
# in the above eg. set1=[1,4,5,6,7] and set2=[2,3] is the solution for Bipartite tree
# so yes a tree can be expressed as bipartite tree, such that alterate level vertices are in one set and the rest other in another ser
# Graph :
"""
1
2 3
4
above is a cyclic graph , s1= [1,4] and s2 = [2,3] is the solution for bipartite graph.
so a graph containing cycle of even length can be expressed as bipartite
graph
another eg.
1
5
2
4
3
(all the gaps are connected)
if s1=[1,3] s2= [2,4] , 5 cannot be put into both s1 and s2. so the graph contating cycle of odd length cannot be expressed as bipatite graph.
"""
"""
color - 0 (unvisited)
1(visited not discovered)
2 (discovered)
"""
def dfs(start,graph,v,par,col,odd) :
v[start] = col
for i in graph[start] :
if v[i]==0 :
dfs(i,graph,v,start,3-col,odd)
elif i!=par and col==v[i]:
#backedge(cycle)
odd = 1
return odd
n,m = map(int,input().split())
adj = {}
for i in range(n) :
adj[i] = []
for i in range(m) :
s,d = map(int,input().split())
adj[s].append(d)
adj[d].append(s)
v = [0 for i in range(n)]
odd_len_cycle = 0
if dfs(0,adj,v,0,1,odd_len_cycle) :
print("No,Graph cannot be bipartite")
else :
print("Yes,Graph is bipartite")
| true |
6f32f9d3a99a0ca2a9d125ec422223c6a080c955 | omarsalem14/python-with-Elzero | /variables_part1.py | 1,020 | 4.78125 | 5 | # ------------------------------------------------------
# --variables --
# ----------------
# syntax => [Variable Name] [Assigment Operator] [Value]
#
# Name Convention and Rules
# [1]Cant start with (a-z A-Z) or Underscore
# [2]I Can't begin with number or Special Charecters {2myVariable},{-myVariable}
# [3]Can include (0-9) or Underscore
# [4]Can't include special characters {=my-Variable}
# [5]Name is not like name [case sensetive]= MyVariable"The Variable" print(myVariable)
# Variable must assigne firstly then u can print it :
# print(myVariable)
# myVariable = "The Variable"
# ------------------------------------------------------
myVariable = "The Variable"
print(myVariable)
MyVariable = "The Variable"
print(MyVariable)
_myVariable = "The Variable"
print(_myVariable)
my100_Variable = "The Variable"
print(my100_Variable)
name = "Omar Gzera" # single word =>Normal
myName = "Omar Gzera" # two word =>camelCase
my_name = "Omar Gzera" # two word =>snake_case
print("name")
print("myName")
print("my_name")
| true |
32ce44f3319596094760a0e74e1b2d75ea60a572 | gorehx/LaboratorioVCSRemoto | /main.py | 466 | 4.15625 | 4 | a=float(input("Ingrese el número a:"))
b=float(input("Ingrese el número b:"))
c=float(input("Ingrese el número c:"))
d=(((b*2)-(4*a*c))*(1/2))
neg=(((-1*b)-(d**(1/2))/2*a))
pos=(((-1*b)+(d**(1/2))/2*a))
if d>0:
print( "La parte negativa es: ", neg , "y la parte postiva es: ", pos)
else:
if d==0:
print("El valor negativo: ", (-d/2*a), "es igual al valor positivo, el cual es:", (-d/2*a))
else:
if d<0:
print("No existe solucion en los numeros reales")
| false |
0321483364f00778472d1783e21c68fc2a5adf69 | DingXiye/PythonDemo | /PythonDemo/src/com/11.类和对象/类.py | 1,501 | 4.21875 | 4 | '''
类
self相当于this
2018年6月9日
@author: dingye
'''
class Photo:
def __init__(self,name):
self.name=name
def kick(self):
print("我叫%s"%self.name)
p=Photo("土豆")
p.kick()
#在属性前加上"__"就变成私有属性 __name为私有属性
class Person:
def __init__(self,name):
self.__name=name
def getname(self):
return self.__name
p1=Person("dopa")
#p1.name
print(p1.getname())
#继承
class Parent:
def h(self):
print("这是父类方法")
class Child(Parent):
pass
c=Child()
c.h()
#组合用来替代多重继承,多重继承会出现代码混乱,出现bug
class Base1:
def __init__(self,name):
self.name=name
class Base2:
def __init__(self,name):
self.name=name
class Pool:
def __init__(self,x,y):
self.base1=Base1(x)
self.base2=Base2(y)
def put(self):
print("base1中%d,base2中%d"%(self.base1.name,self.base2.name))
pool =Pool(2,4)
pool.put()
#默认printb方法中会有一个参数即bb对象,这是Python的绑定机制
class BB:
def printb():
print("this bb")
b=BB()
#b.printb()
#with的实现
class TestWith:
def __enter__(self):
print("in __enter__")
return "with"
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
print("in __exit__")
def getWith():
return TestWith()
with getWith() as f:
print("sample:",f)
| false |
85de4cd34fbbe0459b3a1c5248347d8c2ea462d5 | amaurirg/testes | /Hackerrank/running_time_and_complexity.py | 1,559 | 4.15625 | 4 | """
Objetivo
Hoje estamos aprendendo sobre o tempo de execução!
Tarefa
Um primo é um número natural maior que 1 que não possui divisores positivos além de 1 e ele próprio.
Dado um número, n, determine e imprima se é Prime ou Not prime.
Nota: Se possível, tente criar um algoritmo de primalidade 0 (^ N) ou veja que tipo de otimizações
você usa para um algoritmo 0 (n). Não deixe de conferir o Editorial depois de enviar seu código!
Formato de entrada
A primeira linha contém um inteiro, T, o número de casos de teste.
Cada uma das linhas subsequentes T contém um inteiro, n, para ser testado para primalidade.
Restrições
1 <= T <= 1000
1 <= n <= 2 x 10 ** 9
Formato de saída
Para cada caso de teste, imprima se n é Prime ou Not prime em uma nova linha.
Entrada de amostra
3
12
5
7
Saída de Amostra
Not prime
Prime
Prime
Explicação
Caso de Teste 0: n = 12.
12 é divisível por números diferentes de 1 e ele próprio (ou seja, 2, 3, 6), por isso imprimimos
Not prime em uma nova linha.
Caso de Teste 1: n = 5.
5 é apenas divisível 1 e ele, então imprimimos Prime em uma nova linha.
Caso de Teste 2: n = 7.
7 é somente divisível 1 e ele mesmo, então imprimimos Prime em uma nova linha.
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
def isprime(n):
if n == 1:
return 'Not prime'
for i in range(2, int(n**0.5) + 1):
if n%i == 0:
return 'Not prime'
return 'Prime'
T = int(input())
for i in range(T):
number = int(input())
print(isprime(number)) | false |
ed2d9440951ec26852941721bf5819a670cd7a83 | ishaniMadhuwanthi/Python-Codes | /set3/Code5.py | 312 | 4.28125 | 4 | # Given a two list of equal size create a set such that it shows the element from both lists in the pair
listOne=[2,3,4,5,6,7,8]
listTwo=[4,9,16,25,36,79,68]
print('First List:',listOne)
print('Second List:',listTwo)
result=zip(listOne,listTwo)
resultList=set(result)
print('Result pairs:',resultList)
| true |
a2f6f11239ce6db80e09511c918faaf7968023fd | ishaniMadhuwanthi/Python-Codes | /set3/Code9.py | 407 | 4.375 | 4 | #Given a dictionary get all values from the dictionary and add it in a list but don’t add duplicates
myList={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53,
'july':54, 'Aug':44, 'Sept':54}
print('values of the dictionary:',myList.values())
newList=list()
for item in myList.values():
if item not in newList:
newList.append(item)
print('new List:',newList)
| true |
35ca5475df3b6351d2440e161362534e1150f2b6 | ishaniMadhuwanthi/Python-Codes | /set1/Code9.py | 490 | 4.21875 | 4 | #Given a two list of ints create a third list such that should contain only odd numbers from the first list and even numbers from the second list
def mergeList(listOne, listTwo):
thirdList = []
for i in listOne:
if(i % 2 != 0):
thirdList.append(i)
for i in listTwo:
if(i % 2 == 0):
thirdList.append(i)
return thirdList
print("Merged List is")
listOne = [10, 20, 23, 11, 17]
listTwo = [13, 43, 24, 36, 12]
print(mergeList(listOne, listTwo)) | true |
63aa4993095bde9c5168b6d70b24c724c346e701 | johanesn/CTCI-Practice | /CTCI 5_1.py | 1,360 | 4.3125 | 4 | '''
Insertion : You are given two 32-bit numbers, N and M and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that bits j through i have enough space to fit all of M. That is if M = 10011, you can assume that there are at least 5 bits between j and i. You would not for example, have j=3 and i=2, because M could not fully fit between bit 3 and bit 2.
Example:
Input : N = 10000000000, M = 10011, i = 2, j = 6
Output : N = 10001001100
Solution:
1. Clear the bits j through i in N
2. Shift M so that it lines up with bits j through i
3. Merge M and N
'''
def bit_insertion(n, m, i, j):
m = int(m, 2)
n = int(n, 2)
# This can specify how many bits
allones = ~0
# for example i = 2, j = 4
# 1s before position j, then 0s. left = 11100000
left_mask = (allones << (j+1))
# 1s after position i. right = 11100011
right_mask = ((1 << i) - 1)
# Combine both mask
mask = left_mask | right_mask
# Clear bits j through i then put m in there
n_cleared = n & mask
m_shifted = m << i
result = n_cleared | m_shifted
# convert binary to string
return bin(result)[2:]
if __name__ == '__main__':
print ("This is the implementation of bit insertion CTCI 5_1")
N = '10000000000'
M = '10011'
i = 2
j = 6
result = bit_insertion(N, M, i, j)
print (result)
| true |
15bec55949ce491cb086f8b0809da553e49de0b4 | johanesn/CTCI-Practice | /CTCI 10_5.py | 1,038 | 4.34375 | 4 | # Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.
def sparseSearch (arr, key, low, high):
while low <= high:
mid = int(low + (high-low)/2)
if arr[mid] == '':
left = mid-1
right = mid+1
while True:
print ("inside inf loop")
# out of bounds check
if left < low and right > high:
return -1
elif left >= low and arr[left] != '':
# search left
mid = left
break
elif right <= high and arr[right] != '':
# search right
mid = right
break
left = left - 1
right = right + 1
if arr[mid] == key:
return mid
elif arr[mid] > key:
# search left
high = mid-1
elif arr[mid] < key:
low = mid+1
return -1
if __name__ == '__main__':
arr = ["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""]
res = sparseSearch (arr, "ball", 0, len(arr)-1)
if (res == -1):
print ("Element not found!")
else:
print ("Element found at index: ", res)
| true |
5afda28d2dd3996f26739ea8d527d1414daa725a | johanesn/CTCI-Practice | /TreeTraversal.py | 1,912 | 4.21875 | 4 | # Tree Traversal (Inorder, Preorder and Postorder)
'''
1
/ \
2 3
/ \
4 5
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
> In case of BST, inorder traversal gives nodes in non-decreasing order
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
> Used to create a copy oof the tree.
> Can also be used to get prefix expression on of an expression tree
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
> Used to delete the tree
> Also useful to get the postfix expression of an expression tree
'''
class TreeNode:
def __init__(self, key):
self.left = self.right = None
self.val = key
def print_inorder(root):
if root :
print_inorder(root.left)
print (root.val, end = " ")
print_inorder(root.right)
def print_preorder(root):
if root :
print (root.val, end = " ")
print_preorder(root.left)
print_preorder (root.right)
def print_postorder(root):
if root :
print_postorder(root.left)
print_postorder(root.right)
print (root.val, end = " ")
if __name__ == '__main__':
print ("This is implementation of tree traversal")
root = TreeNode (25)
root.left = TreeNode(15)
root.right = TreeNode(50)
root.left.left = TreeNode(10)
root.left.right = TreeNode(22)
root.right.left = TreeNode(35)
root.right.right = TreeNode(70)
root.left.left.left = TreeNode (4)
root.left.left.right = TreeNode(12)
root.left.right.left = TreeNode(18)
root.left.right.right = TreeNode(24)
root.right.left.left = TreeNode(31)
root.right.left.right = TreeNode(44)
root.right.right.left = TreeNode(66)
root.right.right.right = TreeNode(90)
print ("Inorder traversal of binary tree is")
print_inorder(root)
print ('\n')
print ("Preorder traversal of binary tree is")
print_preorder(root)
print ('\n')
print ("Postorder traversal of binary tree is")
print_postorder(root)
print ('\n')
| true |
b4bd32a3e5a5fa2c5f93f4dc1aa6ed162889ece3 | Pratham-vaish/Harshit-Vashisth-Python-Begginer-Course-Notes | /chapter_1/center_method.py | 335 | 4.21875 | 4 | #center method is used to put any symbol in starting ad ending of a string
print("This program can center your name with any character")
print("Things you have to input :- YOUR NAME,CHARACTER,FREQUENCY")
name, x, y = input('enter your name, the character and how many times : ').split(",")
print(name.center(len(name)+int(y), x)) | true |
31413461c1047082a86d1a9b645b83d1ff5453da | Pratham-vaish/Harshit-Vashisth-Python-Begginer-Course-Notes | /chapter_1/string_methods.py | 414 | 4.1875 | 4 | name = "pRaTHaM VaiSH"
#len() func conts number of characters including spaces
Length = len(name)
print(Length)
#.lower() method changes all characters to lower case
small_letters = name.lower()
print(small_letters)
#.upper() method changes all characters to upper case
big_letters = name.upper()
print(big_letters)
#.count() method counts frequency of a particular character
print(name.count("a"))
| true |
c4b3abc532c6ac9f0d0daeb63c00b5739267879d | Pratham-vaish/Harshit-Vashisth-Python-Begginer-Course-Notes | /chapter_1/input_int.py | 428 | 4.125 | 4 | #we use input function for user in put
#for example
name = input('Enter your name ')
print('Hello ' + name)
#A input_func alwasy take input as string
# for example
age = input("whta is your age ")
print("your age is " + age)
#To take input as a integer we use int_func
number_1=int(input("enter your first number "))
number_2=int(input("enter second one.. "))
total=number_1+number_2
print('total is' + str(total))
| true |
d2d93880bfa842b2804e9d53cd844d780299b353 | Pratham-vaish/Harshit-Vashisth-Python-Begginer-Course-Notes | /chapter_2/if_elif_else.py | 408 | 4.21875 | 4 | name = input("PLEASE ENTER YOUR NAME.. ")
age = int(input("PLEASE ENTER YOUR AGE... "))
if age <= 3:
print(f"Ticket fee for you baby {name} if FREE!!!")
elif age <= 14:
print(f"Ticket fee for you kid {name} is 250rs. ")
elif age <= 60:
print(f"Ticket fee for you sir {name} is 300rs ")
else:
print(f"Ticket fee for you Uncle {name} is FREE!! ")
input("Press Enter key to close..")
| false |
ceb0f904d7c456a0a5328b55f3e2b7e7e0ba5277 | berkcan98/Python_ogrenme | /hata_ayiklama.py | 610 | 4.125 | 4 | for i in range(3):
ilk_sayı=input("ilk sayı:(Programdan çıkmak için q tuşuna basınız.")
if ilk_sayı=="q":
print("çıkılıyor...")
break
elif i ==2:
print("bu alanı 3 kez yanlış doldurdunuz."
"lütfen daha sonra yeniden deneyiniz.")
ikinci_sayı= input("ikinci sayı:")
try:
sayı1=int(ilk_sayı)
sayı2=int(ikinci_sayı)
except ValueError:
print("Sadece sayı girin!")
else:
try:
print(sayı1/sayı2)
except ZeroDivisionError:
print("bir sayıyı 0'a bölemezsiniz.") | false |
f6192a855d61998b6f23cd419da2596421644cb7 | unnatural-X/Study_Introduction | /LiaoPage/example4_if.py | 452 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# input your height and weight
s1 = input('please input your height(m):')
height = float(s1)
s2 = input('please input your weight(kg):')
weight = float(s2)
# calculate BMI
BMI = weight/(height*height)
# output the results
print('Your BMI is: %.1f' % BMI)
if BMI < 18.5:
print('过轻')
elif BMI < 25:
print('正常')
elif BMI < 28:
print('过重')
elif BMI < 32:
print('肥胖')
else:
print('严重肥胖')
| true |
e264ce0306efed9aa8e98b92bbd9f22812617092 | unnatural-X/Study_Introduction | /LiaoPage/example8_functiondef.py | 1,019 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# the solution of quadratic equation
import math # import the math package
def quadratic(a, b, c): # define the function
if a==0:
print('The coefficient of the quadratic term cannot be zero')
elif b*b-4*a*c < 0:
print('The equation doesn\'t have solutions')
elif b*b-4*a*c == 0:
x = -b/(2*a)
return (x,) # 单个返回值时是一个数,改为元组可用len()
else:
x1=(-b+math.sqrt(b*b-4*a*c))/(2*a)
x2=(-b-math.sqrt(b*b-4*a*c))/(2*a)
return x1, x2
# input the coefficient data
a0 = float(input('please input the coefficient of the quadratic term:'))
b0 = float(input('please input the coefficient of the first term:'))
c0 = float(input('please input the coefficient of the zero term:'))
rs = quadratic(a0, b0, c0) # function call
if rs is None:
pass
elif len(rs) == 1:
print('This equation has one solution: x=%s' % rs)
else:
print('This equation has two solutions: x1=%s x2=%s' % (rs[0], rs[1]))
| true |
80740202b28e6126c20c12ceb65cde14c60b3278 | pushpa-ramachandran/DataStructures | /ListAccessingRemovePop.py | 2,773 | 4.53125 | 5 | ############ Accessing the list
print('\n # # # Accessing the list')
list = ['LIST4','LIST5','LIST6']
print(list)
print(list[2])
####### Accessing the multi dimensional list
print('\n # # # Accessing the multi dimensional list')
list = [['LIST4','LIST5','LIST6'],['LIST7','LIST8']]
print(list)
print('list[1] - ' ,list[1])
print('list[1][1] - ',list[1][1])
####### Accessing using NEGATIVE indexing
print('\n # # # Accessing using NEGATIVE indexing')
list = [['LIST4','LIST5','LIST6'],['LIST7','LIST8']]
print(list)
print('list[-1] - last element : ' ,list[-1])
print('list[-2] - second element from the last : ' ,list[-2])
################# Removing elements from the list
####### Remove() function
# Elements can be removed by using remove() function
# An Error arises if element doesn’t exist in the set.
# Remove() method only removes one element at a time
# To remove range of elements, iterator is used.
# Only removes the first occurrence of the searched element
####### Removing elements one at a time
print('\n # # # Removing elements one at a time')
for i in range(1,10):
list.append(i*100)
print(list)
list.remove(500)
print('list.remove(500): ' , list)
####### Removing MULTIPLE elements by iterating
print('\n # # # Removing MULTIPLE elements by iterating')
for i in range(7,10):
list.remove(i*100)
print('for i in range(7,10): list.remove(i*100)): ' , list)
####### pop() function
# Pop() function can also be used to remove and return an element
# By default it removes only the last element of the set
# To remove element from a specific position of the List, index of the element is passed as an argument to the pop() method.
####### Removing by using pop() - no index passed. Removes the last element
print('\n # # # Removing by using pop() - no index passed. Removes the last element')
list.pop()
print('After list.pop()): ' , list)
####### Removing by using pop() - index passed. Removes the element at the index
print('\n # # # Removing by using pop() - index passed. Removes the element at the index')
list.pop(1)
print('After list.pop(1)): ' , list)
### Funcitons list
# Append() Add an element to the end of the list
# Extend() Add all elements of a list to the another list
# Insert() Insert an item at the defined index
# Remove() Removes an item from the list
# Pop() Removes and returns an element at the given index
# Clear() Removes all items from the list
# Index() Returns the index of the first matched item
# Count() Returns the count of number of items passed as an argument
# Sort() Sort items in a list in ascending order
# Reverse() Reverse the order of items in the list
# copy() Returns a copy of the list | true |
cebabf4a4d549717fe1c652d6325f0ef84627078 | renuka123new/Training | /Python-Code/occuranceOfDigit.py | 420 | 4.125 | 4 | #Find total occurrences of each digits (0-9) using function.
def countOcc(n):
l = []
while (n >= 1):
reminder = int(n % 10)
n = n / 10
l.append(reminder)
for i in range(0, 10):
count = 0
for j in l:
if (i == j):
count = count + 1
print("Count of ", i, " = ", count)
num=int(input("Enter any number: "))
countOcc(num)
| true |
3dce5cf1a5665280f3fdf49a71e81f560c4e68fa | Crowbar97/python_hw | /tutor/5_5.py | 681 | 4.15625 | 4 | # Условие
# Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс. Если она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква f в данной строке не встречается, ничего не выводите.
# При решении этой задачи не стоит использовать циклы.
s = input("s = ")
if s.count("f") == 1:
print(s.find("f"))
elif s.count("f") > 1:
print(s.find("f"), s.rfind("f"))
| false |
84c91b2e7671f1f416f689faf267ab1f32626f9f | Crowbar97/python_hw | /tutor/8_5.py | 558 | 4.21875 | 4 | # Условие
# Дана последовательность целых чисел, заканчивающаяся числом 0. Выведите эту последовательность в обратном порядке.
# При решении этой задачи нельзя пользоваться массивами и прочими динамическими структурами данных. Рекурсия вам поможет.
def reverse():
n = int(input("n = "))
if n != 0:
reverse()
print(n)
reverse()
| false |
eaa0624f9710ed758e48c8320f225d9174bacc7b | Crowbar97/python_hw | /tutor/11_1.py | 725 | 4.15625 | 4 | # Условие
# В единственной строке записан текст. Для каждого слова из данного текста подсчитайте, сколько раз оно встречалось в этом тексте ранее.
# Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или символами конца строки.
text = input("text = ").split()
# word counts
wcs = {}
for word in text:
if word in wcs:
wcs[word] = wcs[word] + 1
else:
wcs[word] = 1
print(wcs)
| false |
a737549e9f7efb08b08bde75b0d84edf62395291 | sidsharma1990/Basic-program | /To reverse a text.py | 501 | 4.25 | 4 | text_to_reverese = 'We are working'
def reverse_func(string):
print (string[::-1])
reverse_func (text_to_reverese)
############################
text_to_reverese = 'We are working'
def reverse_func(text_to_reverese):
print (text_to_reverese[::-1])
reverse_func (text_to_reverese)
##########################
text_to_reverese = input ('We are working: ')
def reverse_func(text_to_reverese):
print (text_to_reverese[::-1])
reverse_func (text_to_reverese)
| false |
903f9d4a703e3f625da5f13f6fe084e8894d723b | SymmetricChaos/NumberTheory | /Polynomials/PolynomialIntegerTypeUtils.py | 1,843 | 4.28125 | 4 | def poly_print_simple(poly,pretty=False):
"""Show the polynomial in descending form as it would be written"""
# Get the degree of the polynomial in case it is in non-normal form
d = poly.degree()
if d == -1:
return f"0"
out = ""
# Step through the ascending list of coefficients backward
# We do this because polynomials are usually written in descending order
for pwr in range(d,-1,-1):
# Skip the zero coefficients entirely
if poly[pwr] == 0:
continue
coe = poly[pwr]
val = abs(coe)
sgn = "-" if coe//val == -1 else "+"
# When the coefficient is 1 or -1 don't print it unless it is the
# coefficient for x^0
if val == 1 and pwr != 0:
val = ""
# If it is the first term include the sign of the coefficient
if pwr == d:
if sgn == "+":
sgn = ""
# Handle powers of 1 or 0 that appear as the first term
if pwr == 1:
s = f"{sgn}{val}x"
elif pwr == 0:
s = f"{sgn}{val}"
else:
if pretty == False:
s = f"{sgn}{val}x^{pwr}"
else:
s = f"{sgn}{val}x$^{{{pwr}}}$"
# If the power is 1 just show x rather than x^1
elif pwr == 1:
s = f" {sgn} {val}x"
# If the power is 0 only show the sign and value
elif pwr == 0:
s = f" {sgn} {val}"
# Otherwise show everything
else:
if pretty == False:
s = f" {sgn} {val}x^{pwr}"
else:
s = f" {sgn} {val}x$^{{{pwr}}}$"
out += s
return out | true |
083dcb1dfcad83b453ed7bc8b7fc9eb4f3d61b4d | SymmetricChaos/NumberTheory | /Sequences/Representations.py | 1,839 | 4.125 | 4 | # For alternate representations, generally as strings
from Sequences.Simple import naturals
from Sequences.MathUtils import int_to_roman, int_to_name
def roman_numerals_str():
"""
The positive integers as standard Roman Numerals, returns strings
"""
for n in naturals(1):
yield int_to_roman(n)
def roman_numerals():
"""
The positive integers as standard Roman Numerals in numeric form\n
OEIS A093796
"""
D = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V":5, "I": 1}
for R in roman_numerals_str():
yield tuple([D[letter] for letter in R])
def number_names_str(hyphen=False,use_and=False,long_scale=False):
"""
The English names of the natural numbers, returns strings
Args:
n -- int to be named
hyphen --bool, use hyphens for numbers like forty-eight
use_and -- bool, use the phrasing "hundred and" rather than just "hundred"
long_scale -- bool, use the long scale where (1,000,000 = 'one thousand million')
With short scale goes up to 65 digit numbers
With long scale goes up to 122 digit numbers
"""
for n in naturals():
yield int_to_name(n,hyphen,use_and,long_scale)
if __name__ == '__main__':
from Sequences.Manipulations import simple_test
print("\nNames of Natural Numbers")
simple_test(number_names_str(hyphen=True),16,
"zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen")
print("\nRoman Numerals")
simple_test(roman_numerals_str(), 13,
"I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII, XIII")
print("\nRoman Numerals (numeric)")
simple_test(roman_numerals(), 6,
"(1,), (1, 1), (1, 1, 1), (1, 5), (5,), (5, 1)")
| true |
3007394485bc0fb025ce002bb5a20fff99ebbfa5 | SymmetricChaos/NumberTheory | /Examples/FermatFactorizationExample.py | 935 | 4.375 | 4 |
from Computation.RootFinding import int_root, is_square
print("Fermat's method for factorization relies on the difference squares.")
print("\na^2 - b^2 = (a+b)(a-b)")
print("\nThis means that any number which can be written as the difference of two squares must have a+b and a-b as factors.")
a = 17
b = 6
p = (a+b)*(a-b)
print(f"\nFor example {p} can be factored as {a+b} and {a-b}")
print("\nTo factor a number N we can see that\nN = a^2 - b^2\nimplies\na^2 - N = b^2")
print("\nThat means we find a factorization by repeatedly subtracting squares from N until the result is a square.")
N = 1521
print(f"\nLet's try to factor {N}\n")
a = int_root(N)
factor_found = False
while True:
a += 1
b2 = a**2-N
print(f"a^2 = {a**2}\na^2-N = {b2}\n")
if is_square(b2):
print(f"{b2} is square")
factor_found = True
print(f"We can factor {N} as\n{a-int_root(b2)} * {a+int_root(b2)}")
break
| true |
872833bd837287b5c36a446ae1029f0244a383d0 | miloszfoksinski/EXERCISES_PRACTISEPYTHON | /EXERCISE_11.py | 320 | 4.21875 | 4 | """Ask the user for a number and determine whether the number is prime or not."""
x = int(input('Write Your number to check whether it is prime or not: '))
count = 0
for a in range (1,x+1):
if x%a == 0:
count +=1
if count > 2 :
print('Your number ',x,' is not prime')
else:
print('Your number ',x,' is prime')
| true |
fc3b8a2eee36062324c6f0bf7176a9425c69bf4e | sforrester23/SlitherIntoPython | /chapter7/Question3.py | 930 | 4.15625 | 4 | # Write a program that takes a string as input from the user.
# The string will consist of digits and your program should print out the first repdigit.
# A repdigit is a number where all digits in the number are the same.
# Examples of repdigits are 22, 77, 2222, 99999, 444444
# Building upon the previous exercise,
# write a program that takes a string as input from the user and prints the first number encountered
# along with the starting position of the number.
s = input("Please enter a string: ")
output = ""
i = 0
while i < len(s) - 1 and not (s[i].isnumeric() and s[i] == s[i+1]):
i += 1
j = i
if i >= len(s) - 1 or s[i] != s[i+1]:
print("There is no repdigit in that string.")
else:
while j < len(s) - 1 and s[j].isnumeric() and s[j+1] == s[j]:
output += s[j]
j += 1
output += s[j]
print("The first number in that string is: {}, starting at position: {}".format(output, i))
| true |
ef004154a0a6592c88a2d9cfe3db2657b9510f7a | momchil-lukanov/hack-bulgaria | /programming-0/week-3/problems_construction/triangles.py | 1,013 | 4.15625 | 4 | import math
def is_triangle(a, b, c):
if a + b > c or a + c > b or b + c > a:
return True
else:
return False
print(is_triangle(3, 4, 5))
def area(a, b, c):
p = (a + b + c)/2
s = math.sqrt(p*(p-a)*(p-b)*(p-c))
return s
print(area(3, 4, 5))
def is_pythagorean(a, b, c):
result = ""
if a ** 2 + b ** 2 == c ** 2 or a ** 2 + c ** 2 == b ** 2 or c ** 2 + b ** 2 == a ** 2:
result += "The triangle is pythagorean"
else:
result += "It is not pythagorean"
return result
print(is_pythagorean(3, 4, 5))
def area_list(x):
a = x[0]
b = x[1]
c = x[2]
p = (a + b + c)/2
s = math.sqrt(p*(p-a)*(p-b)*(p-c))
return s
print(area(3, 4, 5))
def max_area(triangles):
result = 0
tr_max_area = 0
for triangle in triangles:
if area_list(triangle) > tr_max_area:
tr_max_area = area_list(triangle)
result = triangle
return result
print(max_area([[3, 4, 5], [7, 8, 9] ]))
| false |
7b3c25989bd57a5f918b5d8fed972f6ff28bc1ec | DevXerxes/Python-Projects | /InheritanceAssignment.py | 931 | 4.40625 | 4 | # Here im defining a parent class with its properties and using a printname method.
class Bikes:
#function to give structure to objects in the class Bikes
def __init__(self, type_of, color):
self.type_of = type_of
self.color = color
#function for defining structure of the printname method for printing
#the attrubutes of a bike(object) in class Bikes
def printname(self):
print(self.type_of, self.color)
# using the Bikes class to create an object, and then executing the printname method:
x = Bikes("Mountain", "Mustard-Yellow")
x.printname()
# Here creating child class ElectricBike with its own attributes
class ElectricBike(Bikes):
engine = 'Dual-Battery'
battery_energy = '500 wh'
load = '250w'
run_time = '2 hours'
#a 2nd child class MotorBike
class MotorBike(Bikes):
speed = '90 mph'
to_decrease = 'brake lever'
| true |
cc0145453f692d5e6e291fc12fef82c2c2c3fbaa | phodiep-other/PythonCertSpring | /week-03/code/super/super_test.py | 616 | 4.34375 | 4 | #!/usr/bin/env python
"""
some example code, demostrating some super() behaviour
"""
class A(object):
def __init__(self):
print "in A __init__"
s = super(A, self).__init__()
class B(object):
def __init__(self):
print "in B.__init__"
s = super(B, self).__init__()
class C(object):
def __init__(self):
print "in C.__init__"
s = super(C, self).__init__()
class D(C, B, A):
def __init__(self):
print "in D.__init__"
super(D, self).__init__()
d = D()
s_c = super(C, d)
print s_c
s_a = super(A, d)
print s_a
s_b = super(B, d)
print s_b
| false |
1124a57ea03b0131c2704274666f39061e05eff7 | Deepakvm18/luminardeepak | /language fundamentals/highestof3.py | 466 | 4.25 | 4 | num1=int(input("enter the first number"))
num2=int(input("enter the second number"))
num3=int(input("enter the third number"))
if(num1>num2):
print("first number is greater than second")
if(num1>num2):
print("num1 is greatest of three numbers")
else:
print("num3 is greatest of three numbers")
elif(num2>num3):
print("num2 is greatest of three numbers")
elif(num1==num2==num3):
print("equal")
else:
print("num3 is greatest")
| true |
e997e5aba7d5a5f546b4a6d94fa9e3336edc0a65 | CodevilJumper/CodeWars | /YourOrder Code Wars.py | 1,241 | 4.15625 | 4 | # Your order, please
#
# INSTRUCTIONS
#
# Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
#
# Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
#
# If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
# Examples
#
# "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
# "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
# "" --> ""
def order(sentence):
"""
Args:
sentence (): string, original string . Each word containing a single digit.
Returns: Ordered string with words in ascending order based on a digit in every word.
"""
dict_words = {}
list_words = sentence.split()
final_sentence = []
for i in list_words:
for char in i:
if char.isdigit():
dict_words[char] = i
dict_words = sorted(dict_words.items())
for i in dict_words:
final_sentence.append(i[-1])
return " ".join(final_sentence)
# TEST
sentence = "4of Fo1r pe6ople g3ood th5e the2"
print(order(sentence))
| true |
e100972f2bd606bf312c57850ac8a7013062b67c | VANSHDEEP15577/TEST-C-121 | /ques5.py | 351 | 4.1875 | 4 | array=[]
w=int(input("ENTER THE NO. OF ELEMENTS YOU WANT:"))
for i in range(0,w):
p=input("ENTER THE ELEMENT:")
array.append(p)
print(array)
array1=[]
we=int(input("ENTER THE NO. OF ELEMENTS YOU WANT:"))
for j in range(0,we):
pe=input("ENTER THE ELEMENT:")
array1.append(pe)
print(array1)
array.extend(array1)
print(array) | false |
4987c269bbe20c3b6b273adba26055ecfdbd1ce5 | peazybabz/Python-Tutorials-for-beginners | /prg10.py | 254 | 4.125 | 4 | #10. Python Program to Check if a Number is Positive, Negative or 0
num = float(input("Input a number: "))
if num > 0:
print("The number ",num,"is a positve number")
elif num == 0:
print(num,"is Zero")
else:
print("It is a negative number")
| true |
552e867ddb90a4311b7336b879bd83581bae359a | peazybabz/Python-Tutorials-for-beginners | /prg8.py | 329 | 4.5 | 4 | #8. Python Program to Convert Kilometres to Miles
#input provided by program
# kilometers = 5.3
#input from user
kilometers = float(input("Enter value in kilometers:"))
#conversion factor
conv_fac = 0.621371
#calculate miles
miles = kilometers * conv_fac
print("%0.2f kilometers is equal to %0.2f miles"%(kilometers,miles))
| true |
e8c56deedf0d6f71ac46b26e9952ed8f49228cbb | titus-ong/chordparser | /src/chordparser/music/roman.py | 2,533 | 4.25 | 4 | class Roman:
"""A class representing Roman numeral notation.
The `Roman` is composed of its `root`, `quality` and `inversion`. When printed, the standard Roman numeral notation is displayed.
Parameters
----------
root : str
The scale degree of the `Roman`. Uppercase if major/augmented and lowercase if minor/diminished.
quality : str
The quality of the `Roman`.
inversion : tuple of int
The inversion of the `Roman` in figured bass notation (e.g. (6, 4) for second inversion).
Attributes
----------
root : str
The scale degree of the `Roman`. Uppercase if major/augmented and lowercase if minor/diminished.
quality : str
The quality of the `Roman`.
inversion : tuple of int
The inversion of the `Roman` in figured bass notation (e.g. (6, 4) for second inversion).
"""
def __init__(self, root, quality, inversion):
self.root = root
self.quality = quality
self.inversion = inversion
self._build_notation()
def _build_notation(self):
inv_str = "".join(map(str, self.inversion))
self._notation = self.root + self.quality + inv_str
def __repr__(self):
return self._notation + " roman chord"
def __str__(self):
return self._notation
def __eq__(self, other):
"""Compare between other `Romans`.
Checks if the other `Roman` has the same `root`, `quality` and `inversion`.
Parameters
----------
other
The object to be compared with.
Returns
-------
boolean
The outcome of the `value` comparison.
Examples
--------
>>> KE = KeyEditor()
>>> SE = ScaleEditor()
>>> CE = ChordEditor()
>>> CRC = ChordRomanConverter()
>>> c_key = KE.create_key("C")
>>> c_scale = SE.create_scale(c_key)
>>> d = CE.create_diatonic(c_scale, 2)
>>> r = CRC.to_roman(d, c_key)
>>> r2 = CRC.to_roman(d, c_key)
>>> r == r2
True
>>> e = CE.create_diatonic(c_scale, 3)
>>> r3 = CRC.to_roman(e, c_key)
>>> r == r3
False
"""
if isinstance(other, Roman):
return (
self.root == other.root and
self.quality == other.quality and
self.inversion == other.inversion
)
if isinstance(other, str):
return str(self) == other
return NotImplemented
| true |
c69ad85e21e632dbecfaaeb0aad6e6a04b43c47c | noodlexpoodle/PY | /Maps.py | 684 | 4.15625 | 4 | from random import shuffle
def jumble(word):
#anagram is a list of the characters
anagram = list(word)
shuffle(anagram) #shuffle the list
return ''.join(anagram)
#words = ['apple','pear','melon']
words = []
i = 1
while i == 1:
word = input('Enter word. Type "Done" to stop ')
if word.lower() != 'done':
words.append(word)
else:
i = 0
#anagram is the orig list, anagramS is the new empty list for the other list to transform into
anagrams = []
#basic loop method
for word in words:
anagrams.append(jumble(word))
print(anagrams)
#map function
print(list(map(jumble,words)))
#list comprehension
print([jumble(word) for word in words])
| true |
87b0708072b055a340b48c4588199b94512f333b | mbrown2330/tip_calculator2 | /tip_calculator2.py | 1,302 | 4.46875 | 4 | # Make a python script tip_calculator.py that takes a user's input at the command line for:
# Cost of the food
# Number of people splitting the bill
# Percentage of the tip
# Hint: you might want to use the input() function for taking user input
# Then, the script should output:
# The total bill (including tip)
# how much each person should pay (you can assume all people will split the bill evenly)
# Assume there is a 10% sales tax. Don't forget to add this into the total bill!
# Note: your tip calculator should be able to handle a bill of any amount
# of many money, with any number of people splitting the bill, and with any tip percentage (including 0 tip)
print('tip_calculator')
print()
#Asking for the total cost or the meal?
total_cost = float(input('Total cost of meal without tip $'))
print()
#Asking for the tip in %
total_tip = int(input('what % tip like to give?'))
print()
#Asking how many adults
num_adults = int(input('How many adults?'))
print()
tip_percent = total_tip /100
total_tip_amount = round(total_cost * tip_percent)
total_bill = round(total_tip_amount + total_cost)
bill_per_person = round (total_bill/ num_adults)
bill_to_pay = round(bill_per_person)
print(f'the meal cost with tip $ {total_bill}')
print()
print(f'each have to pay $ {bill_to_pay}') | true |
93c810befaea331717e552e66a366ccdb4dfdf22 | steveSuave/practicing-problem-solving | /code-wars/expanded-form.py | 566 | 4.34375 | 4 | ##Write Number in Expanded Form
##
##You will be given a number and you will need to return
##it as a string in Expanded Form. For example:
##
##expanded_form(12) # Should return '10 + 2'
##expanded_form(42) # Should return '40 + 2'
##expanded_form(70304) # Should return '70000 + 300 + 4'
##
##NOTE: All numbers will be whole numbers greater than 0.
def expanded_form(num):
res=[]
power=0
while num/10>0:
res.insert(0,str(num%10*10**power))
num//=10
power+=1
ls=list(filter(lambda x: x!="0", res))
return " + ".join(ls) | true |
f37d2e3ea1340ca5ae07a2aab0b33f0a713408fa | DanilooSilva/Cursos_de_Python | /Curso_de_Python_3_do_Basico_Ao_Avancado_Udemy/aula116/metaclasses.py | 809 | 4.28125 | 4 | """
EM PYTHON TUDO É UM OBJETO: Incluindo classes
Metaclasses são as "classes" que criam classes.
type é uma metaclasse (!!!???)
"""
class Meta(type):
def __new__(mcs, name, bases, namespace):
if name == 'A':
return type.__new__(mcs, name, bases, namespace)
if 'b_fala' not in namespace:
print(f'Oi, você precisa criar o método b_fala em {name}.')
else:
if not callable(namespace['b_fala']):
print(f'b_fala precisa ser um método, não atributo em {name}.')
return type.__new__(mcs, name, bases, namespace)
class A(metaclass=Meta):
def fala(self):
self.b_fala()
class B(A):
teste = 'Valor'
def b_fala(self):
print('Oi')
def sei_la(self):
pass
b = B()
b.fala()
| false |
07320850bf2c94779f0ce375fbc78a0f1022d09f | Aegis-Liang/Python3_Mac | /Data Structures & Algorithms/Part01/L03_PythonFunctions.py | 247 | 4.125 | 4 | # Example function 1: return the sum of two numbers.
def sum(a, b):
return a+b
# Example function 2: return the size of list, and modify the list to now be sorted.
def list_sort(my_list):
my_list.sort()
return len(my_list), my_list
| true |
95f1cb5d3eac411483411e06feb7c59e40ff7951 | Aegis-Liang/Python3_Mac | /GUI_Tkinter/T5_Caculator.py | 2,909 | 4.125 | 4 | from tkinter import *
root = Tk()
root.title("Simple Calculator")
e = Entry(root, width=35)
e.grid(row=0, column=0, columnspan=3)
def button_click(number):
e.insert(END, str(number))
def button_add():
global first_number
global math
first_number = int(e.get())
e.delete(0, END)
math = "add"
def button_subtract():
global first_number
global math
first_number = int(e.get())
e.delete(0, END)
math = "subtract"
def button_multiply():
global first_number
global math
first_number = int(e.get())
e.delete(0, END)
math = "multiply"
def button_divide():
global first_number
global math
first_number = int(e.get())
e.delete(0, END)
math = "divide"
def button_equal():
second_number = int(e.get())
if math == "add":
result = first_number + second_number
elif math == "subtract":
result = first_number - second_number
elif math == "multiply":
result = first_number * second_number
elif math == "divide":
result = first_number / second_number
e.delete(0, END)
e.insert(0, str(result))
def button_clear():
e.delete(0, END)
button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1)).grid(row=3, column=0)
button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2)).grid(row=3, column=1)
button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3)).grid(row=3, column=2)
button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4)).grid(row=2, column=0)
button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5)).grid(row=2, column=1)
button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6)).grid(row=2, column=2)
button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7)).grid(row=1, column=0)
button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8)).grid(row=1, column=1)
button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9)).grid(row=1, column=2)
button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0)).grid(row=4, column=0)
button_add = Button(root, text="+", padx=39, pady=20, command=button_add).grid(row=5, column=0)
button_equal = Button(root, text="=", padx=91, pady=20, command=button_equal).grid(row=5, column=1, columnspan=2)
button_clear = Button(root, text="Clear", padx=79, pady=20, command=button_clear).grid(row=4, column=1, columnspan=2)
button_subtract = Button(root, text="-", padx=40, pady=20, command=button_subtract).grid(row=6, column=0)
button_multiply = Button(root, text="*", padx=40, pady=20, command=button_multiply).grid(row=6, column=1)
button_divide = Button(root, text="/", padx=40, pady=20, command=button_divide).grid(row=6, column=2)
root.mainloop()
| false |
5ce751ddd79daaa9a22728fab5c2ac64411158a8 | colioportfolio/final491edited | /main.py | 1,630 | 4.125 | 4 | from bike import Bike
from fordPinto import Car
from parts import Vehicle
checker = 0
checker2 = 0
checker3 = 0
def wrong_bike():
print("Sorry! That currently is not a bike option")
while checker == 0:
user = input("Hi there! is this Wayne or Garth? ")
if user in ["Garth", "garth", "GARTH"]:
bikeType = input("Hello Garth! What kind of bike are you riding? (BMX, mountain, or street?) ")
while checker2 == 0:
if bikeType in ["Bmx", "BMX", "bmx", "mountain", "Mountain", "MOUNTAIN", "street", "Street",
"STREET"] and checker == 0:
checker2 = 1
else:
bikeType = input(
"That is not an option. Please input one of the three choices: BMX, Mountain, or Street ")
while bikeType in ["Bmx", "BMX", "bmx", "mountain", "Mountain", "MOUNTAIN", "street", "Street",
"STREET"] and checker3 == 0:
color = input("I see. What color is your " + bikeType + " bike? ")
print("Understood. Here is some info about your bike class: ")
garthBike = Bike(color, bikeType)
garthBike.info()
checker3 = 1
checker = 1
elif user in ["Wayne", "wayne", "WAYNE"]:
# Create Wayne's car
carColor = input(
"Hi Wayne! I understand you don't have the finances for many options, so you only have a Ford Pinto. What "
"color is it? ")
wayneCar = Car(carColor)
wayneCar.info()
checker = 1
else:
print("Sorry! This is only for Garth or Wayne.")
| true |
16dbab5d36bfd3d910566b8b8fd2a5bc6ae7e7be | mygnu/MIT6.00 | /Nth_prime_number.py | 768 | 4.28125 | 4 | prime_l = []
nth_prime = int(input('Enter a number to find n\'th prime: '))
def next_prime(current):
next_prime = current + 1 # start checking for primes 1 number after the current one
i = 2
while next_prime > i: # check with numbers up to next_prime - 1
if next_prime % i == 0: # if number is divisible
next_prime += 1 # ready to check the next number
i = 2 # reset i to check divisibility again from 2
else:
i += 1 # increment the divisor
return next_prime
if __name__ == '__main__':
current_prime = 2
while len(prime_l) < nth_prime:
prime_l.append(current_prime)
current_prime = next_prime(current_prime)
print('The', str(nth_prime)+'th prime number is', prime_l[-1])
| false |
c51630f8c80dd17412816ad617555820a3ad498e | bogataurus/Temperature-Select | /temperature_select.py | 1,118 | 4.15625 | 4 | radiators_list = ["kitchen","livingRoom","diningRoom","bathroom","bedroom1","bedroom2", "bedroom3"]
temperatur_list = [15, 18, 22, 26, 30, 35, 40, 45]
heating_radiator = ""
temperature = ""
while True:
radiator_select = input ( "Select radiator at list: kitchen, livingRoom , diningRoom , bathroom , bedroom1 , bedroom2, bedroom3: or quit: " )
if radiator_select in radiators_list:
heating_radiator = radiator_select
while True:
temperature_select = int(input("Please enter a temperature at list: 15, 18, 22, 26, 30, 35, 40, 45: "))
if temperature_select in temperatur_list:
temperature = temperature_select
print("Radiator Type: ",heating_radiator , ";", "Temperature: ", temperature)
break
else:
print("Invalid input! Please enter a temperature at list")
elif radiator_select.startswith ( "q" ):
print("exit!")
break
else:
print("Invalid input! Please select radiator at list")
| true |
fcee985fa8c4af5aad96b3ffef49d6489787d75e | hanaum/MIT--6.001x-Python | /ProblemSet1/pset1-vowel search.py | 394 | 4.28125 | 4 | '''Counting Vowels: counts up the number of vowels contained in the string 's'
Valid vowels are 'a','e','i','o','u'
ex:
s = 'azcbobobegghakl' should print "Number of vowels: 5"
MIT-6.001x Python
Hana Um
'''
vowels = 0
for letter in s:
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
vowels += 1
print "Number of vowels: " + str(vowels)
| false |
7982ede29a971bf120c1cf2557348d34e30fb8e6 | ShelMX/gb_algorithm_hw | /lesson_7/hw_07.py | 1,858 | 4.40625 | 4 | __author__ = 'Шелест Леонид Викторович'
"""
Module with the functions that are used in each homework.
"""
import random as rnd
def generate_int_array(low: int = -100, up: int = 99, size: int = 100) -> list:
"""
function generate list of random numbers (int type).
:param low: type int, lower bound of random numbers, included.
:param up: type int, upper bound of random numbers, included.
:param size: type int, qty. of random numbers.
:return: type list, a list of random numbers, given parameters (largest, smallest random numbers and array size).
"""
return [rnd.randint(low, up) for _ in range(size)]
def generate_float_array(low: float = 0.0, up: float = 50.0, size: int = 100, rounding: int = None) -> list:
"""
function generate list of random numbers (float type).
:param rounding: type int: if the value of the parameter is not specified,
then the random number will not be rounded,
otherwise rounding occurs with a specified accuracy.
:param low: type float: lower bound of random numbers, included.
:param up: type float: upper bound of random numbers. The range [a, b) or [a, b] depending on rounding.
:param size: type int: qty. of random numbers.
:return: type list: a list of random numbers, given parameters
(largest, smallest random numbers, array size and round).
"""
if rounding:
return [round(rnd.uniform(low, up), rounding) for _ in range(size)]
return [rnd.uniform(low, up) for _ in range(size)]
def pretty_print(arr):
"""
function print array in line, step = 10.
:param arr: array to print
:return: None
"""
for count, i in enumerate(arr, 1):
print(f"{i:>5}" if isinstance(i, int) else f"{i:>10}",
end=' ' if count % 10 else '\n')
| true |
a14cf45fffea00d2e3309b9851c4e84bad081006 | NathanDDarmawan/AP-programming-exercises-session-10 | /4.py | 313 | 4.15625 | 4 | def calc_new_height():
m = int(input("Enter the current width: "))
n = int(input("Enter the current height: "))
z = int(input("Enter the desired width: "))
ratio = n/m
new_height = z*ratio
print("The corresponding height is:", new_height)
return new_height
calc_new_height()
| true |
cc14e6627e6e867e30021c0dfe9bb1c2b6e01ca0 | Darrenrodricks/PythonProgrammingExercises | /GitProjects/sepIteams.py | 427 | 4.40625 | 4 | # Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a
# comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program:
# without,hello,bag,world Then, the output should be: bag,hello,without,world
items = [x for x in input("Please enter a a comma separated sequence of words: ").split(",")]
items.sort()
print(items) | true |
1f319726aebea1d6d18ef3a9dfd69293025be6f6 | Darrenrodricks/PythonProgrammingExercises | /GitProjects/factorial.py | 423 | 4.1875 | 4 | # Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated
# sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
def factorial(x):
if x == 0:
return 1
return x * factorial(x - 1)
a = int(input("Please enter a number to find the factorial of: "))
print(factorial(a))
| true |
f6c7e0042cd3a6a82751ceeda0a7360c095153e2 | wy7318/Python | /basic/whileProgramming.py | 833 | 4.21875 | 4 | available_exit=["east", "west", "north", "south"] #creating list
choosen_exit=""
while choosen_exit not in available_exit:
choosen_exit=input("please choose direction:")
if choosen_exit == "exit":
print("game over")
break
else:
print("glad you got out")
###################################################################################
#guessing number
import random
highest = 10
answer = random.randint(1, highest)
print("guess a number between 1 and {}".format(highest))
guess = int(input())
while guess != answer:
if guess != answer:
if guess < answer:
print("please guess higher")
else:
print("guess lower")
guess = int(input())
if guess == answer:
print("Well done")
break
else:
print("got it right first time")
| true |
c6ebcc4d45a499061f33c72c4e0d8548ebbdca1d | wy7318/Python | /basic/List.py | 1,744 | 4.125 | 4 | ipAddress = input("please enter an IP address")
print(ipAddress.count(".")) #counting specific character
#===============================================================================#
word_list=["wow", "this", "that", "more"]
#===============================================================================#
word_list.append("plus") #adding word
for state in word_list:
print("word list I have is " + state)
#===============================================================================#
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
number = even + odd #creating new list
number.sort() #sorting number
print(number)
numbers = even + odd
print(numbers)
print(sorted(numbers))#other way of sorting it
number3 = [even, odd] #creating list of two lists
print(number3)
#===============================================================================#
list_1 = [] #creating enpty list 1
list_2 = list() #creating enpty list 2
print("list_1 {}".format(list_1))
print("list_2 {}".format(list_2))
print(list("each character will be stored in list"))#cut and store each character
even_1 = [2, 4, 6, 8]
another_even = even_1 #another_even will become same as even_1, updated
another_even.sort(reverse=True)
print(even_1)
#===============================================================================#
menu=[]
menu.append(["egg", "spam", "bacon"])
menu.append(["milk", "spam", "sausage"])
menu.append(["egg", "spam", "bacon"])
menu.append(["egg", "sausage", "bacon", "milk"])
menu.append(["egg", "spam", "milk"])
print(menu) #print list of list added
for meal in menu:
if "egg" not in meal: #list that does not include egg
print(meal)
for ingredient in meal:
print(ingredient) #print eac item in the list
| true |
3250e52a4c73bb240705e1412ffda922c8694ef5 | yqxd/LEETCODE | /44WildcardMatching.py | 2,329 | 4.1875 | 4 | '''
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input:
s = "acdcb"
p = "a*c?b"
Output: false
'''
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
n = len(s)
m = len(p)
d = [[-1 for j in range(m + 1)] for i in range(n + 1)]
d[0][0] = True
for i in range(1, n + 1):
d[i][0] = False
for i in range(1, m + 1):
if p[i - 1] == '*':
d[0][i] = True
else:
for k in range(i, m + 1):
d[0][k] = False
break
for i in range(1, n + 1):
for j in range(1, m + 1):
if p[j - 1] == '?':
d[i][j] = d[i - 1][j - 1]
elif p[j - 1] == '*':
d[i][j] = d[i - 1][j - 1] or d[i][j - 1] or d[i - 1][j]
elif p[j - 1] == s[i - 1]:
d[i][j] = d[i - 1][j - 1]
else:
d[i][j] = False
return d[n][m]
p = "babbaabaabaaaaabbbbabaababbababbbaabbbbbbbbbababaabbabbaaabaaabbababbaaabbbbababbbaaababbbbababababaaaabbbbabbbabbabbbaaabaabaababbababbbabaaabbbbaaabbbabbabbbbaabaabbabaabababbbababaaabaaabbbabbaaaabab"
q = "baa*b*ab*aa**bb*bbbaab***b*abbb*bbb*b*aa*b*b*ab*********ab*b***abb***a*bbb***a*a*b*baa*b***bb*b**ba*b*"
A = Solution()
print(A.isMatch(p, q))
| true |
ada055efcc03e73f8d40d6c045925997f0bdb453 | greshan/python_assignments | /28.py | 410 | 4.28125 | 4 | #28. Implement a progam to convert the input string to inverse case(upper->lower, lower->upper) ( without using standard library)
str_data = 'Greshan'
result = ''
for char in str_data:
if ord(char) >= 65 and ord(char) <= 90:
result += chr(ord(char) - 32)
print(result)
elif ord(char)<=97 and ord(char) <= 123:
result += chr(ord(char) + 32)
print(result)
print(result)
| true |
f4a5629e49c56439096843cb8e9559d2bfb372b5 | greshan/python_assignments | /11.py | 736 | 4.25 | 4 | #Implement a program with functions, for finding the area of circle, triangle, square.
def main():
print("Area of Circle - 1\n")
print("Area of Triangle - 2\n")
print("Area of Square - 3\n")
num = int(input("Enter num: \n"))
if num == 1:
r = float(input("Enter radius value:\t"))
a = 3.14*r*r
print("\nArea is : ", a)
exit()
if num == 2:
h = float(input("Enter Height values:\t"))
b = float(input("Enter Base values:\t"))
a1 = (h*b)/2
print("\nArea is : " ,a1)
exit()
if num == 1:
s = float(input("Enter side value:\t"))
a2 = s*s
print("\nArea is : " ,a2)
exit()
if __name__=="__main__":
main()
| false |
e0c509792b018be0c9c6b68ad28b8e9271f3dc08 | greshan/python_assignments | /23.py | 212 | 4.34375 | 4 | #23. Implement a program to write a line from the console to a file.
inp = input("Enter text to print in file : \n")
file = open("23.txt","w")
if(file.write(inp)):
print("written to 23.txt")
file.close()
| true |
2fc21a984fd786cef73fbf20698492d822f87fc8 | kellibudd/code-challenges | /get_century.py | 712 | 4.1875 | 4 | import math
def centuryFromYear(year):
"""
Source: Codesignal
Given a year, return the century it is in. The first century spans
from the year 1 up to and including the year 100, the second - from
the year 101 up to and including the year 200, etc.
Test case:
>>> centuryFromYear(1905)
20
>>> centuryFromYear(45)
1
>>> centuryFromYear(1700)
17
"""
base_century = math.floor((year / 100))
year = (year / 100) % 1
if year > 0.00:
year = 1
else:
year = 0
return base_century + year
# doctest
if __name__ == "__main__":
import doctest
result = doctest.testmod()
if result.failed == 0:
print("ALL TESTS PASSED")
| true |
a5f501cc47fc3130f0a1672bd64b6a45e1df35a0 | rhit-catapult/2021-session1 | /individual_tutorials/pygamestartercode-gdhill-master/00-IntroToPython/07_mutation.py | 1,727 | 4.28125 | 4 | """
This module demonstrates MUTATION and RE-ASSIGNMENT.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays,
Derek Whitley, their colleagues.
"""
##############################################################################
# TODO: 2. Read the code, then run it.
# Make sure you understand WHY it prints what it does.
# ** ASK QUESTIONS IF ANY OF IT IS MYSTERIOUS TO YOU. **
# Once you understand the code completely, then change the _TODO_ to DONE.
###############################################################################
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def main():
point1 = Point(10, 20)
point2 = Point(30, 40)
print()
print("Point1 before:", point1.x, point1.y)
print("Point2 before:", point2.x, point2.y)
point3 = blah(point1, point2)
print()
print("Point1 after:", point1.x, point1.y)
print("Point2 after:", point2.x, point2.y)
print("Point3 after:", point3.x, point3.y)
def blah(one_point, another_point):
one_point.x = 111
third_point = one_point
one_point = Point(88, 99)
another_point.x = 333
another_point = one_point
fourth_point = third_point
fourth_point.y = 555
print()
print("one_point inside:", one_point.x, one_point.y)
print("another_point inside:", another_point.x, another_point.y)
print("third_point inside:", third_point.x, third_point.y)
print("fourth_point inside:", fourth_point.x, fourth_point.y)
return fourth_point
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
| true |
88b6094a8fff4e796496c08edfe152e557bf31cf | emildekeyser/tutoring | /fh/opl/Solutions-session5/Solutions-new/ex2b_fibindex.py | 715 | 4.21875 | 4 | def index_of_fib(s):
# The number 1 is the value of fib_1 and fib_2 so we choose to return fib_1
if s == 1:
return 1
s1 = 1
s2 = 1
s3 = s1 + s2
n = 3
# Same calculation as in ex2a but now we keep calculating new fib values until we reach our limit s
while s3 < s:
s1 = s2
s2 = s3
s3 = s1 + s2
# Increment the index of the calculated fib numer
n += 1
# If the limit was reached and it was a fib number (because s3 is one) then we have the index
if s3 == s:
return n
return -1
def main():
s = int(input("Enter a Fibonacci number: "))
print("%d th number of Fibonacci is %d" % (index_of_fib(s), s))
main()
| true |
9f28e77623dd07cb1cf88b3e434b630240e45dc2 | emildekeyser/tutoring | /fh/opl/solutions_session8/ex5.py | 688 | 4.21875 | 4 | # each node in BST is represented as [left_child, value, right_child]
def bst_insert(tree, item):
if len(tree) == 0:
tree.append([])
tree.append(item)
tree.append([])
elif len(tree) == 3:
if item <= tree[1]:
bst_insert(tree[0], item)
else:
bst_insert(tree[2], item)
def bst_search(tree, item):
current_node = tree
path = []
while len(current_node) == 3:
path.append(current_node[1])
if current_node[1] == item:
return current_node, path
elif current_node[1] < item:
current_node = current_node[2]
else:
current_node = current_node[0]
| false |
d0dd68ae68aa8d92162e2ce76116a08131eb8a6f | emildekeyser/tutoring | /fh/opl/oefenzitting_3_opl(1)/E2 Celsius to Fahrenheit.py | 399 | 4.40625 | 4 | input_string = input('Enter the temperature in Celsius: ')
while input_string != 'q':
celsius = float(input_string)
fahrenheit = celsius * 9/5 + 32
print('The temperature in Fahrenheit is:', fahrenheit)
input_string = input('Enter the temperature in Celsius: ')
# for this exercise you cannot use a for loop
# to use a for loop you should know the number of iterations in advance
| true |
74dbd77b513f89ef069d3fda4f67557bb72ed693 | alekssro/CompThinkBioinf | /Week02/src/sort.py | 1,268 | 4.34375 | 4 | def insertion_sort(lst):
"""Sort a list of numbers.
Input: lst -- a list of numbers
Output: a list of the elements from lst in sorted order.
"""
s = []
for x in lst:
# s contains contains all the element we have
# seen so far, in sorted order
smaller = [y for y in s if y <= x]
larger = [y for y in s if y > x]
s = smaller + [x] + larger
return s
def merge(x, y):
"""Merge two lists, x and y.
Input: sorted lists x and y
Output: the merging of x and y -- a list with the elements of x and y in sorted order.
"""
n = len(x)
m = len(y)
z = [None] * (n + m)
def helper(i, j, k):
if i == n:
z[k:] = y[j:]
elif j == m:
z[k:] = x[i:]
elif x[i] < y[j]:
z[k] = x[i]
helper(i+1, j, k+1)
else:
z[k] = y[j]
helper(i, j+1, k+1)
helper(0, 0, 0)
return z
def merge_sort(lst):
"""Sort a list of numbers.
Input: lst -- a list of numbers
Output: a list of the elements from lst in sorted order.
"""
if len(lst) <= 1:
return lst
n = len(lst)
first = merge_sort(lst[:n//2])
second = merge_sort(lst[n//2:])
# first is the sorted first half of the elements
# second is the sorted second half of the elements
return merge(first, second)
lst = [3, 2, 4, 6, 5, 8, 2, 5]
print(insertion_sort(lst))
print(merge_sort(lst))
| true |
87e673cc2faf46fd5d33335586782acbd31fd6bb | candyer/Daily-Coding-Problem | /dcp_12.py | 1,384 | 4.375 | 4 | # Daily Coding Problem: Problem #12
# There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N,
# write a function that returns the number of unique ways you can climb the staircase.
# The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
def solve(n):
'''
time: O(n)
space: O(1)
for given input from 1 to n, the output will be a fibnacci sequence.
'''
a, b = 1, 1
for _ in range(2, n + 1):
b, a = a + b, b
return b
assert solve(4) == 5
assert solve(5) == 8
assert solve(7) == 21
assert solve(10) == 89
# What if, instead of being able to climb 1 or 2 steps at a time,
# you could climb any number from a set of positive integers X? For example,
# if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
def memoize(func):
memo = {}
def helper(n, steps):
if n in memo:
return memo[n]
else:
memo[n] = func(n, steps)
return memo[n]
return helper
@memoize
def solve1(n, steps):
'''
n: a staircase with n steps
steps: all possible steps, no duplicate
'''
if n <= 1:
return 1
res = 0
for step in steps:
if n >= step:
res += solve1(n - step, steps)
return res
# assert solve1(5, [1, 3, 5]) == 5
# assert solve1(5, [1, 2]) == 8
# assert solve1(10, [1, 3, 5]) == 47
# assert solve1(10, [1, 2]) == 89
| true |
a04620b19b1a89931217119f14b0d18b2de4c676 | habraino/meus-scripts | /_prog/_python/_aulas/_dados/string_v1.py | 1,663 | 4.28125 | 4 | # file_name: string.py
'''
Nota: com esse exemplo tu irá minima noção de como trabalhat com "strings"
E o uso de input("") é mesmo que str(input("")), só quando para stings
'''
var = input("Digite qualquer coisa: ")# lê qualquer coisa pelo teclado
# retorna o tamanho da 'palavra' informada
print("O tamanho total é: {}".format(len(var)))
# imprime tudo em maiúscula
print("{} em maiúscula fica: {}".format(var, var.upper()))
# imprime tudo em maiúscula
print("{} em minúscula fica: {}".format(var, var.lower()))
# remove todos os espaços e carateres ASCII
print("Tirando os espaços fica: {}".format(var.strip()))
# conta quantas letras 'a' foram digitadas
print("Quantas letras 'a' foram digitadas? {}".format(var.count('a')))
# procura por letra 'a' e retorna a posição da primeira que encontrar
print("A primeira letra 'a' está em que posição? {}".format(var.find('a')))
# procura por última letra 'a' e retorna sua posição
print("A última letra 'a' está em que posição? {}".format(var.rfind('a')))
# imprime tudo separado
print("Todo separado fica: {}".format(var.split()))
# imprime tudo junto
b = var.split()# separa tudo e armazena em 'b'
junto = ''.join(b)# ajunta todo e armazena em 'junto'
print("Todo junto fica: {}".format(junto))
# imprima tudo em forma de título
print("Em forma de títuloCase fica: {}".format(var.title()))
# imprime a palavra/frase com primeira letra sendo maúscula
print("Primeira letra maíuscula: {}".format(var.capitalize()))
# troca toda letra 'a' caso encontre para '@'
print("Todo 'a' trocado fica: {}".format(var.replace('a', '@')))
| false |
88080fdc0a346368f15042dff08bf4fedc446219 | ganesh1729ganesh/Algos_task_3 | /problem_1_task3.py | 1,058 | 4.125 | 4 |
n = input("Enter the number: ")
#Taking input in the form of string
sumTemp = 0
count = 0
while (len(n) > 1): #only we need to find sum of digits only when it is a non-single digit number
sumTemp = 0
for i in range(len(n)):
sumTemp += int(n[i])# simply to convert the digit in the form of character to int form in each iteration
# converting temporary_sum into
# string str again .
n = str(sumTemp)# for loop to continue AND FOR len method to work
# increase the count for each loop and that gives finally the least no. of times we need to add
count += 1
print(count)
""" TIME COMPLEXITY:
2 loops 1 loop inside another loop , so O(n^2)
SPACE COMPLEXITY:
SINCE onnly one int input and few constant space taking integers
overall space complexity is O(1) """
| true |
b7bf1e1da7246b4d32a3ee82ee44d9e173e18bad | nandha-batzzy/Python-Projects-and-Learning | /Code forces Simple probs/ep11_Healpful maths.py | 1,327 | 4.1875 | 4 | '''Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input
The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.
Output
Print the new sum that Xenia can count.'''
num = input('enter the number to be added: ')
ply = num.replace('+',"")
k = sorted(ply)
c= 0
a = 0
m =""
lst = list()
for i in range(len(num)):
c = c+1
if c%2 == 0:
lst.append("+")
if c%2 != 0:
lst.append(k[a])
a = a+1
for t in lst:
m = m + str(t)
print(m)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.