blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f5bef46daa56f9dbf9a18ddedb786bb7b982fd22 | rohini-nubolab/Python-Learning | /swaplist.py | 280 | 4.1875 | 4 | # Python3 program to swap first and last element of a list
def swaplist(newlist):
size = len(newlist)
temp = newlist[0]
newlist[0] = newlist[size-1]
newlist[size-1] = temp
return newlist
newlist = [12, 15, 30, 56, 100]
print(swaplist(newlist))
| true |
a997569eb3036d6acca7e9e4152511878bd4ed1c | rohini-nubolab/Python-Learning | /length_k.py | 294 | 4.28125 | 4 | # Python program to find all string which are greater than given length k
def length_k(k, str):
string = []
text = str.split(" ")
for i in text:
if len(i) > k:
string.append(i)
return string
k = 4
str = "Python is a programming"
print(length_k(k, str))
| true |
4b0c89c828134415e4ad1da02a50c6dbf49c664e | rohini-nubolab/Python-Learning | /str_palindrome.py | 254 | 4.4375 | 4 | #Python program to check given string is Palindrome or not
def isPalindrome(s):
return s == s[::-1]
s = "MADAM"
result = isPalindrome(s)
if result:
print("Yes. Given string is Palindrome")
else:
print("No. Given string is not Palindrome")
| true |
5eeb7cec2d6ca5a9f2478fe7286f23de9a185114 | jedzej/tietopythontraining-basic | /students/Glogowska_Joanna/lesson_02_flow_control/adding_factorials.py | 269 | 4.28125 | 4 | print('For a given integer, \
print the sum of factorials')
number = int(input('Enter a number: '))
sumoffact = 0
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
sumoffact += factorial
print('The sum of factorials is: ' + str(sumoffact))
| true |
973669615a36fdb152cd81f14b51f6908c7f121b | jedzej/tietopythontraining-basic | /students/biegon_piotr/lesson_02_flow_control/the_number_of_zeros.py | 260 | 4.1875 | 4 | print("The number of zeros\n")
N = int(input("Enter the number of numbers: "))
result = 0
for i in range(1, N + 1):
a = int(input("Enter a number: "))
if a == 0:
result += 1
print("\nYou have entered {:d} numbers equal to 0".format(result))
| true |
65ffa0dbf7bc4a6e052fa5cf4f235ad36c55caec | jedzej/tietopythontraining-basic | /students/Glogowska_Joanna/lesson_01_basics/lesson_01.py | 2,688 | 4.125 | 4 | import math
# Lesson 1.Input, print and numbers
# Sum of three numbers
print('Input three numbers in different rows')
first = int(input())
second = int(input())
third = int(input())
sum = first + second + third
print(sum)
# Area of right-angled triangle
print('Input the length of the triangle')
base = int(input())
print('Input the height of the triangle')
height = int(input())
area = (base * height) / 2
print(area)
# Hello, Harry!
print('What is your name?')
print('Hello, ' + str(input()) + '!')
# Apple sharing
print('Input number of students')
students = int(input())
print('Input number of apples')
apples = int(input())
print('Each student will get ' + str(apples // students) + ' apples')
print(str(apples % students) + ' apples will remain in the basket')
# Previous and next
number = int(input())
print('The next number for the number ' + str(number) + ' is ' +
str(number + 1) + '.')
print('The previous number for the number ' + str(number) + ' is ' +
str(number - 1) + '.')
# School desks
print('There are 3 classes - how many students is in each of them?\n"'
'Input your answers in separate rows')
class1 = int(input())
class2 = int(input())
class3 = int(input())
desks = (
class1 // 2 + class2 // 2 + class3 // 2 +
class1 % 2 + class2 % 2 + class3 % 2
)
print(str(desks) + ' needs to be purchased')
# Lesson 2.Integer and float numbers
# Last digit of integer
intnum = int(input())
print(intnum % 10)
# Tens digit
tensdig = int(input())
print((tensdig % 100) // 10)
# Sum of digits
sum3dig = int(input())
print(((sum3dig % 1000) // 100) + ((sum3dig % 100) // 10) + (sum3dig % 10))
# Fractional part
fract = float(input())
print(fract - int(fract))
# First digit after decimal point
rand = float(input())
firstdig = ((rand * 10) // 1) % 10
print(int(firstdig))
# Car route
print('What distance in km the car covers per day?')
kmperday = int(input())
print('What is the length of the route?')
routelength = int(input())
print(math.ceil(routelength / kmperday))
# Digital clock
print('Number of minutes that passed since midnight')
minsmidn = int(input())
print(str(minsmidn // 60) + ':' + str(minsmidn % 60))
# Total cost
dollars = int(input())
cents = int(input())
numcup = int(input())
print(dollars * numcup + (cents * numcup) // 100, (cents * numcup) % 100)
# Clock face - 1
print('How many hours have passed since minight?')
hours = int(input())
print('How many minutes have passed since minight?')
mins = int(input())
print('How many seconds have passed since minight?')
secs = int(input())
anghr = 360 / 12
angmin = anghr * 1 / 60
angsec = angmin / 60
angle = (anghr * hours) + (angmin * mins) + (angsec * secs)
print(angle)
| true |
4355f566a32a6c866219f64a5725f1be10bc2b43 | jedzej/tietopythontraining-basic | /students/kosarzewski_maciej/lesson_04_unit_testing/collatz/collatz_sequence.py | 434 | 4.3125 | 4 | def collatz(number):
if number <= 0:
raise ValueError
elif number % 2 == 0:
half_even = number / 2
print(half_even)
return half_even
elif number % 2 == 1:
some_odd = (3 * number) + 1
print(some_odd)
return some_odd
if __name__ == "__main__":
value = int(input("Please enter a number, positive, integer: "))
while value != 1:
value = collatz(value)
| true |
f4833bbfde29d3ebcd266957c9c4adc1855ea9a4 | jedzej/tietopythontraining-basic | /students/hyska_monika/lesson_06_dicts_tuples_sets_args_kwargs/Uppercase.py | 459 | 4.375 | 4 | # Function capitalize(lower_case_word) that takes the lower case word
# and returns the word with the first letter capitalized
def capitalize(lower_case_word):
lst = [word[0].upper() + word[1:] for word in lower_case_word.split()]
capital_case_word = " ".join(lst)
print(capital_case_word)
return capital_case_word
text = str((input("Put string - use small letter: ")))
capitalize(text)
print("")
s = "ala's ma kota UK. kk"
capitalize(s)
| true |
1378aaf0c29ff0a9aa1062890506ceb7885e002a | jedzej/tietopythontraining-basic | /students/urtnowski_daniel/lesson_10_organizing_files/selective_copy.py | 2,443 | 4.21875 | 4 | #!/usr/bin/env python3
"""
selective_copy.py: a practice project "Selective Copy" from:
https://automatetheboringstuff.com/chapter9/
The program walks through a folder tree and searches for files with a given
file extension. Then it copies these files from the source location to
a destination folder.
Usage: ./selective_copy.py <extension> <source_path> <destination_path>
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
import sys
import os
import shutil
import random
def get_args():
args_cnt = len(sys.argv)
if args_cnt != 4:
print("Usage: ./selective_copy.py <extension> <source_path> "
"<destination_path>")
return None
else:
extension, source, destination = sys.argv[1:]
if not extension:
print('Error! The extension cannot be an empty string!')
return None
if not os.path.exists(source) or not os.path.isdir(source):
print("Error! The source path: {} is incorrect!".format(source))
return None
if not os.path.exists(destination):
os.makedirs(destination)
elif not os.path.isdir(destination):
print('Error! The destination path leads to a file')
return None
if not os.path.isabs(destination):
destination = os.path.abspath(destination)
return extension, source, destination
def main():
args = get_args()
if args is not None:
extension, source, destination = args
for curr_dir, _, files in os.walk(source):
for file in files:
if file.endswith('.{}'.format(extension)):
if os.path.exists(os.path.join(destination, file)):
name, ext = os.path.splitext(file)
new_name = '{}_{}_{}'.format(name,
random.randint(1, 999999),
ext)
shutil.copy(os.path.join(curr_dir, file),
os.path.join(destination, new_name))
print('File names collision; renaming file {} copied '
'from: {} to {}'.format(file, curr_dir, new_name)
)
else:
shutil.copy(os.path.join(curr_dir, file), destination)
if __name__ == '__main__':
main()
| true |
f406f56d29ee2683f6caefe267c06a0be06139fd | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_01_basic/total_cost.py | 625 | 4.15625 | 4 | # Problem «Total cost» (Medium)
# Statement
# A cupcake costs A dollars and B cents. Determine, how many dollars and cents
# should one pay for N cupcakes. A program gets three numbers: A, B, N.
# It should print two numbers: total cost in dollars and cents.
print('Please input cost of 1 piece in dollars part:')
dollars = int(input())
print('Please input cost of 1 piece in cents part:')
cents = int(input())
print('Please input number of cupcakes:')
number = int(input())
print('Total cost = ' + str((dollars * number) + int((cents * number) / 100)) + ' dollars, ' +
str((cents * number / 100) % 1) + ' cents.')
| true |
dea8bde4d91c6cb0c446a0a0899da9df3d077c14 | jedzej/tietopythontraining-basic | /students/urtnowski_daniel/lesson_08_regular_expressions/automate_the_boring_stuff.py | 2,422 | 4.1875 | 4 | #!/usr/bin/env python3
"""
automate_the_boring_stuff.py: a practice projects: "Regex version of strip"
and "Strong Password Detection" from:
https://automatetheboringstuff.com/chapter7/
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
import re
def regex_strip(input_str, chars=' '):
"""
This function takes a string and does the same thing as the strip() string
method.
:param string input_str: a string to be stripped
:param string chars: characters to be removed form the beginning and the
end of the input string
:return string: the modified string
"""
escaped_chars = re.escape(chars)
strip_regex = re.compile('^([{0}]+)'.format(escaped_chars))
modified_str = strip_regex.sub('', input_str)
strip_regex = re.compile('([{0}]+)$'.format(escaped_chars))
modified_str = strip_regex.sub('', modified_str)
return modified_str
def is_password_strong(password):
"""
This function checks if input string is a strong password
:param password: a string with password for verification
:return bool: True if the passed string is a strong password, False
otherwise
"""
is_strong = True
patterns = [r'^.{8,}$', r'\d+', r'[a-z]+', r'[A-Z]+']
for pattern in patterns:
passwd_regex = re.compile(pattern)
mo = passwd_regex.search(password)
if mo is None:
is_strong = False
break
return is_strong
def main():
# Regex version of strip
for string, chars in [('0900-123-456-789-090-00', '0-9'),
(' ala ma kota ', ' '), ('***aa*.a...', '*.a'),
('bcd ala ma kota cbdc dcdc db ', 'bcd '),
('***** ala ma kota ********', ' *')]:
print("'{}' with stripped char(s): '{}' is: '{}'"
.format(string, chars, regex_strip(string, chars)))
for string in ['ala ma kota ', ' ala ma kota', ' ala ma kota ']:
print("'{}' with stripped white spaces is: '{}'"
.format(string, regex_strip(string)))
print('')
# Strong Password Detection
for password in ['Password5', 'weaK123', '123456789', 'AbcDefghijk',
'Admin1', 'A1B2C3D4E5', '1a2b3c4d5e', 'stR0ngPass', ' ']:
print("'{}' is strong password: {}"
.format(password, is_password_strong(password)))
if __name__ == '__main__':
main()
| true |
bf0ff9aaa89d6b411a58785e8d12becbc3adcc60 | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_01_basics/Lesson2/ex02_07.py | 599 | 4.34375 | 4 | #Statement
#Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock?
#The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59).
#For example, if N = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So the program should print 2 30.
print("Please enter the number of minutes that is passed since midnight: ")
a = int(input())
print("Hours and minutes displayed on digital clock are:")
print(str(a//60)+ ' ' +str(a-(a//60)*60)) | true |
558046852a5d20e15639a0c8244e1518ee776bf4 | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_01_basics/previous_and_next.py | 488 | 4.15625 | 4 | '''
title: prevous_and_next
author: arkadiusz.kasprzyk@tieto.com
date: 2018-03-05
description:
Write a program that reads an integer number and prints its previous and next numbers.
There shouldn't be a space before the period.
'''
print('''Reads an integer number and prints its previous and next numbers.
'''
)
n = int(input("Give an integer: "))
print("The next number to {} is {}".format(n,n+1))
print("The previous number to {} is {}".format(n,n-1))
input("Press Enter to quit the program.") | true |
769a73aa4e312c861c0eb9b54ca793f6121f5c89 | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_05_lists/comma_code.py | 968 | 4.53125 | 5 | """
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument
and returns a string with all the items separated
by a comma and a space, with and inserted before
the last item. For example, passing the previous
spam list to the function would
return 'apples, bananas, tofu, and cats'.
But your function should be able to work
with any list value passed to it.
"""
def transform_string(collection):
string = ""
collection.insert(-1, 'and')
for i in range(len(collection)):
if len(collection) - i > 2:
string += collection[i] + str(", ")
elif len(collection) - i == 2:
string += collection[i] + str(" ")
elif len(collection) - i == 1:
string += collection[i]
return string
def main():
spam = ['apples', 'bananas', 'tofu', 'cats']
print(transform_string(spam))
if __name__ == '__main__':
main()
| true |
a465ed16d43516dda5d529acb4d4e7f0ded681e2 | jedzej/tietopythontraining-basic | /students/kaczmarek_katarzyna/lesson_03_functions/the_length_of_the_segment.py | 706 | 4.15625 | 4 | from math import sqrt
def distance(x1, y1, x2, y2):
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def main():
while True:
try:
x1coordinate = float(input("Type x1 coordinate: "))
y1coordinate = float(input("Type y1 coordinate: "))
x2coordinate = float(input("Type x2 coordinate: "))
y2coordinate = float(input("Type y2 coordinate: "))
print("The distance is:", distance(x1coordinate, y1coordinate,
x2coordinate, y2coordinate))
break
except ValueError:
print("All numbers must be real.")
continue
if __name__ == '__main__':
main()
| true |
1db7a306d1c531fdce7503e61024bf24f3b9ea29 | jedzej/tietopythontraining-basic | /students/lakatorz_izaak/lesson_07_string_datetime/date_calculator.py | 657 | 4.15625 | 4 | # Date calculator - write a script that adds custom number of years,
# days and hours and minutes to current date and displays the result in
# human readable format.
import time
import datetime
def main():
print('Enter years, days, hours and minutes you want to add.')
years, days, hours, mins = [int(x) for x in input().split(' ')]
add_value = (years * 31536000
+ days * 86400
+ hours * 3600
+ mins * 60)
timestamp = time.time()
my_data = datetime.datetime.fromtimestamp(timestamp + add_value)
print(my_data.strftime("%Y-%m-%d %H:%M"))
if __name__ == "__main__":
main()
| true |
9f34d8aba1c553781e6866d34b623f25685d49c4 | jedzej/tietopythontraining-basic | /students/zelichowski_michal/lesson_02_flow_control/the_number_of_zeroes.py | 414 | 4.125 | 4 | """Given N numbers: the first number in the input is N, after that N
integers are given. Count the number of zeros among the given integers
and print it.
You need to count the number of numbers that are equal to zero,
not the number of zero digits. """
# Read an integer:
a = int(input())
zeroes = 0
for x in range(1, a+1):
b = int(input())
if b == 0:
zeroes += 1
# Print a value:
print(zeroes)
| true |
d6647eeab421b36b3a5f985071184e5d36a7fe9c | jedzej/tietopythontraining-basic | /students/pietrewicz_bartosz/lesson_03_functions/the_collatz_sequence.py | 758 | 4.40625 | 4 | def collatz(number):
"""Calculates and prints the next element of Collatz sequence"""
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
return number
def read_number():
number = 0
# read integer from user until it is positive
while number < 1:
print("Enter positive integer: ", sep="", end="")
number = int(input())
if number < 1:
print("The number must be positive!")
return number
def main():
# read number from the user
number = read_number()
# calculate Collatz sequence until function calculating next element
# returns 1
while number != 1:
number = collatz(number)
if __name__ == '__main__':
main()
| true |
45026f81aa56c85fb70b6f60f60d24b8172605d0 | jedzej/tietopythontraining-basic | /students/jemielity_kamil/lesson_01_basics/area_of_right_angled_traingle.py | 208 | 4.28125 | 4 |
length_of_base = float(input("Write a length of the base: "))
height = float(input("Write a height of triangle: "))
area = (length_of_base * height)/2
print("Area of right-angled triangle is: %s" % area)
| true |
c33eb58a3e743b1bcb66e7be1ce1649126092894 | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_06_dictionaries/the_number_of_distinct_words.py | 544 | 4.21875 | 4 | """
Given a number n, followed by n lines of text,
print the number of distinct words that appear in the text.
For this, we define a word to be a sequence of
non-whitespace characters, seperated by one or more
whitespace or newline characters. Punctuation marks
are part of a word, in this definition.
"""
def main():
word_set = set()
rows = int(input())
for i in range(rows):
line = input().split()
for word in line:
word_set.add(word)
print(len(word_set))
if __name__ == '__main__':
main()
| true |
12de4d9871dee7d1bf3bcec9c672832d2f374f2f | jedzej/tietopythontraining-basic | /students/baker_glenn/lesson_3_scripts/exponentiation_recursion.py | 615 | 4.25 | 4 | def exponentiation_recursion(num, exp, calculated_number):
if exp > 1:
exp -= 1
calculated_number = calculated_number * num
exponentiation_recursion(num, exp, calculated_number)
else:
print(str(calculated_number).rstrip('0').rstrip('.'))
while True:
try:
print("Please enter a real number")
number = float(input())
print("Please enter the exponent")
exponent = int(input())
break
except:
print("Please enter a real number first, followed by an integer")
counter = 0
exponentiation_recursion(number, exponent, number)
| true |
bea6cd3642874532f071326c5ddb2e6f7c9eff5c | jedzej/tietopythontraining-basic | /students/serek_wojciech/lesson_02_flow_control/elements_equal_maximum.py | 425 | 4.125 | 4 | #!/usr/bin/env python3
"""The number of elements equal to the maximum"""
def main():
"""Main function"""
max_value = -1
max_count = -1
number = -1
while number:
number = int(input())
if number > max_value:
max_value = number
max_count = 1
elif number == max_value:
max_count += 1
print(max_count)
if __name__ == '__main__':
main()
| true |
8f1b4f06ac87cc4d8bd5a968b8ade41d78ccd877 | jedzej/tietopythontraining-basic | /students/baker_glenn/snakify_lesson_4/factorials_added.py | 210 | 4.1875 | 4 | # script to calculate the factorial
print("enter a number")
number = int(input())
result = 1
results_added = 0
for i in range(number):
result *= (i+1)
results_added += result
print(str(results_added))
| true |
ca92c30e1ed48ad6404ea25fb6ac2aa5710dbc2a | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_02_flow_control/Snakify_Lesson6__2problems/the_second_maximum.py | 697 | 4.34375 | 4 | # Statement
# The sequence consists of distinct positive integer numbers
# and ends with the number 0.
# Determine the value of the second largest element in this sequence.
# It is guaranteed that the sequence has at least two elements.
def second_maximum():
second = 0
print("Enter positive integer number:")
first = int(input())
a = first
while(a != 0):
print("Enter a positive integer number (0 to end processing)):")
a = int(input())
if (a > first):
first, second = a, first
elif (a > second):
second = a
print("The second maximum value is:")
print(second)
if __name__ == '__main__':
second_maximum()
| true |
f0e4d4266a40a28a83c6a92f25da009a8b3b281a | jedzej/tietopythontraining-basic | /students/bedkowska_julita/lesson_03_functions/the_collatz_sequence.py | 283 | 4.28125 | 4 | def collatz(number):
if number % 2 == 0:
result = number // 2
print(result)
return result
else:
result = 3 * number + 1
print(result)
return result
num = int(input('Give the number: '))
while num != 1:
num = collatz(num)
| true |
d57e8619470c765eeedac5d4281d1f9b92748a62 | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_02_flow_control/ladder.py | 591 | 4.3125 | 4 | """
description:
For given integer n ≤ 9 print a ladder of n steps.
The k-th step consists of the integers from 1 to k without spaces between them.
To do that, you can use the sep and end arguments for the function print().
"""
print("""
For given integer n ≤ 9 prints a ladder of n steps.
The k-th step consists of the integers from 1 to k without spaces between them.
""")
n = int(input("n = "))
step = ""
if n > 0 and n <= 9:
for k in range(1, n+1):
step += str(k)
print(step)
else:
print("n is too large; should be between 1 and 9.")
| true |
67c1553add8841549f017b90a6815e9c65d9a8fa | jedzej/tietopythontraining-basic | /students/mariusz_michalczyk/lesson_07_strings/delta_time_calculator.py | 594 | 4.1875 | 4 | from datetime import date, datetime
def get_user_input():
print("Enter future date: ")
entered_y = int(input("Enter year: "))
entered_m = int(input("Enter month: "))
entered_d = int(input("Enter day: "))
return date(entered_y, entered_m, entered_d)
def current_date():
return date(datetime.now().year,
datetime.now().month,
datetime.now().day)
if __name__ == '__main__':
custom_date = get_user_input()
print("Difference between your date and current date is: ")
print(str((custom_date - current_date()).days) + " days")
| true |
55ba081b6820d5a6e5e871c41cdcb2b339954456 | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_01_basics/Lesson1/ex01_05.py | 511 | 4.21875 | 4 | #Statement
#Write a program that reads an integer number
#and prints its previous and next numbers.
#See the examples below for the exact format your answers should take.
# There shouldn't be a space before the period.
#Remember that you can convert the numbers to strings using the function str.
print("Enter an integer value:")
a = int(input())
print("The next number for the number " + str(a) + " is " + str(a + 1) + ".")
print("The previous number for the number " + str(a) + " is " + str(a - 1) + ".") | true |
204037e5dd7a1ef15c58f2063150c72f1995b424 | jedzej/tietopythontraining-basic | /students/biegon_piotr/lesson_02_flow_control/chocolate_bar.py | 473 | 4.21875 | 4 | print("Chocolate bar\n")
n = int(input("Enter the number of portions along the chocolate bar: "))
m = int(input("Enter the number of portions across the chocolate bar: "))
k = int(input("Enter the number of portions you want to divide the chocolate bar into: "))
print("\nIs it possible to divide the chocolate bar so that one part has exactly {:d} squares?".format(k))
if (k % n == 0 and k / n < m) or (k % m == 0 and k / m < n):
print('YES')
else:
print('NO')
| true |
adb1d13da8f60604a0643d325404d5de692fea9b | jedzej/tietopythontraining-basic | /students/swietczak_monika/lesson_02_flow_control/the_number_of_elements_equal_to_maximum.py | 293 | 4.21875 | 4 | the_highest = 0
count = 0
number = int(input("Enter a number: "))
while number != 0:
if number > the_highest:
the_highest = number
count = 1
elif number == the_highest:
count += 1
number = int(input("Enter another number: "))
# Print a value:
print(count)
| true |
47f9e146863f7aba249c6c5893c18f3023ee6a1b | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_05_lists/swap_min_and_max.py | 605 | 4.28125 | 4 | def swap_min_max(numbers):
"""
Parameters
----------
numbers: int[]
Returns
-------
numbers with maximum and minimum swapped.
Only the first occurences of min and max are taken into account.
Examples
--------
print(swap_min_max([3, 0, 1, 4, 7, 2, 6]))
print(swap_min_max([3, 0, 0, 4, 7, 2, 6]))
print(swap_min_max([3, 0, 1, 4, 7, 7, 6]))
"""
if len(numbers) >= 2:
lmin, lmax = min(numbers), max(numbers)
imin, imax = numbers.index(lmin), numbers.index(lmax)
numbers[imin], numbers[imax] = lmax, lmin
return numbers
| true |
4f66840fcd80f91a7a5689b8c39e75525640723d | jedzej/tietopythontraining-basic | /students/urtnowski_daniel/lesson_06_dicts_tuples_sets_args_kwargs/snakify_lesson_10.py | 1,787 | 4.125 | 4 | #!/usr/bin/env python3
"""
snakify_lesson_10.py: Solutions for 3 of problems defined in:
Lesson 10. Sets
(https://snakify.org/lessons/sets/)
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
def read_set_of_integers(items_count):
new_set = set()
for i in range(items_count):
new_set.add(int(input()))
return new_set
def print_set(input_set):
ordered = list(input_set)
ordered.sort()
ordered_len = len(ordered)
print(ordered_len)
if ordered_len == 0:
print('')
else:
[print(num) for num in ordered]
def cubes():
alice_count, bob_count = [int(i) for i in input().split()]
alice_set = read_set_of_integers(alice_count)
bob_set = read_set_of_integers(bob_count)
# common colors
print_set(alice_set & bob_set)
# Alice's unique colors
print_set(alice_set - bob_set)
# Bob's unique colors
print_set(bob_set - alice_set)
def the_number_of_distinct_words_in_some_text():
lines_cnt = int(input())
words = set()
for i in range(lines_cnt):
words |= set(input().split())
print(len(words))
def guess_the_number():
n = int(input())
numbers = set(range(n))
input_string = str(input())
while input_string != 'HELP':
tries = set([int(num) for num in input_string.split(' ')])
input_string = str(input())
if input_string == 'YES':
numbers &= tries
elif input_string == 'NO':
numbers -= tries
else:
break
input_string = str(input())
numbers = list(numbers)
numbers.sort()
print(' '.join([str(num) for num in numbers]))
def main():
cubes()
the_number_of_distinct_words_in_some_text()
guess_the_number()
if __name__ == '__main__':
main()
| true |
7e4ae48b861867e6abbc7ff17617701644e364d7 | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_03_functions/negative_exponent.py | 562 | 4.34375 | 4 | """
Statement
Given a positive real number a and integer n.
Compute an. Write a function power(a, n) to
calculate the results using the function and
print the result of the expression.
Don't use the same function from the standard library.
"""
def power(a, n):
if (n < 0):
return (1 / (a ** abs(n)))
else:
return a ** n
if __name__ == "__main__":
try:
print(power(float(input("Enter real number: ")),
float(input("Enter power number:"))))
except ValueError:
print("Error, invalid value.")
| true |
f6ef5524112318c4507e64dd7c24bec374c71e06 | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_09_reading_and_writing_files/mad_libs.py | 730 | 4.1875 | 4 | """
Create a Mad Libs program that reads in text files
and lets the user add their own text anywhere the word
ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file.
"""
import re
REPLACE_WORDS = ["ADJECTIVE", "NOUN", "ADVERB", "VERB"]
def main():
input_file = open("text_file_input.txt")
output_file = open("text_file_output.txt", 'w')
text = input_file.read()
input_file.close()
text = re.sub('[,.]', '', text)
text = text.split(" ")
for word in text:
if word in REPLACE_WORDS:
print("Please write a word to replace \"" + word + "\":")
word = str(input())
output_file.write(word + " ")
output_file.close()
if __name__ == '__main__':
main()
| true |
e9fdbb006ba374972ff68b0b62f83ff578a8c8cf | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_08_regular_expressions/regex_version_of_strip.py | 818 | 4.5625 | 5 | """
Write a function that takes a string and does the same
thing as the strip() string method. If no other arguments
are passed other than the string to strip, then whitespace
characters will be removed from the beginning and
end of the string. Otherwise, the characters specified in
the second argument to the function will be removed
from the string.
"""
import re
def strip_regex(line, strip=''):
stripped_line = re.compile(r"^ +| +$")
result = stripped_line.sub('', line)
if strip != '':
arg_strip = re.compile(strip)
result = arg_strip.sub('', result)
return result
def main():
print("Please input line to strip:")
line = input()
print("Please input optional parameter")
arg = input()
print(strip_regex(line, arg))
if __name__ == '__main__':
main()
| true |
411c81ea9bc2c6cb7083f38c68f05f7f9e373e10 | jedzej/tietopythontraining-basic | /students/grzegorz_bajorski/lesson_03_functions/input_validation.py | 366 | 4.15625 | 4 | def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
print('Enter number')
number = 0
while 1:
try:
number = int(input())
if collatz(number) != 1:
print(collatz(number))
else:
break
except:
print('enter an integer')
print('Got 1 - break')
| true |
f50a67ca0fb86a594847ff090cedafd1d8631ac1 | jedzej/tietopythontraining-basic | /students/myszko_pawel/lesson_01_basics/15_Clock face - 1.py | 450 | 4.125 | 4 | # H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60).
# Determine the angle (in degrees) of the hour hand on the clock face right now.
# Read an integer:
H = int(input())
M = int(input())
S = int(input())
sec_in_h = 3600
sec_in_m = 60
sec_in_half_day = 43200 #12 * 3600
# Print a value:
# print(a)
total_sec = H*sec_in_h + M*sec_in_m + S
angle = total_sec / sec_in_half_day
print(angle*360) | true |
11dfb2125ddb76cd84df120a4295dc52fe619a27 | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_01_basics/Lesson2/ex02_06.py | 396 | 4.15625 | 4 | #Statement
#A car can cover distance of N kilometers per day. How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M.
print("Please enter how many kilometers per day your car can cover:")
a = int(input())
print("Please enter length of a route:")
b = int(input())
import math
print("It takes " + str(math.ceil(b/a)) + " day(s) to cover a route.") | true |
3095e5ec9ebe36b871411033596b3741754a3fe9 | jedzej/tietopythontraining-basic | /students/pietrewicz_bartosz/lesson_03_functions/the_length_of_the_segment.py | 699 | 4.3125 | 4 | from math import sqrt
def distance(x1, y1, x2, y2):
"""Calculates distance between points.
Arguments:
x1 -- horizontal coordinate of first point
y1 -- vertical coordinate of first point
x2 -- horizontal coordinate of second point
y2 -- vertical coordinate of second point
"""
horiz_len = abs(x2 - x1)
vert_len = abs(y2 - y1)
return sqrt(horiz_len**2 + vert_len**2)
def main():
# Read first point (x1, y1)
x1 = float(input())
y1 = float(input())
# Read second point (x2, y2)
x2 = float(input())
y2 = float(input())
# Calculate distance between points
print(distance(x1, y1, x2, y2))
if __name__ == '__main__':
main()
| true |
82bf7346994efd7061d730228942cf0bc3db4e43 | jedzej/tietopythontraining-basic | /students/zelichowski_michal/lesson_02_flow_control/the_second_maximum.py | 454 | 4.21875 | 4 | """The sequence consists of distinct positive integer numbers
and ends with the number 0. Determine the value of the second largest
element in this sequence. It is guaranteed that the sequence has at least
two elements. """
a = int(input())
maxi = 0
second_max = 0
while a != 0:
if a > maxi:
second_max = maxi
maxi = a
elif a <= maxi:
if a > second_max:
second_max = a
a = int(input())
print(second_max)
| true |
ef537ad5a6899505feab95649248519b313092ef | jedzej/tietopythontraining-basic | /students/sendecki_andrzej/lesson_01_basics/digital_clock.py | 494 | 4.40625 | 4 | # lesson_01_basics
# Digital clock
#
# Statement
# Given the integer N - the number of minutes that is passed since midnight -
# how many hours and minutes are displayed on the 24h digital clock?
# The program should print two numbers: the number of hours (between 0 and 23)
# and the number of minutes (between 0 and 59).
print("Enter the number of minutes from midnight")
m = int(input())
res_h = (m // 60) % 24
res_m = m - (m // 60) * 60
print("It is " + str(res_h) + ":" + str(res_m))
| true |
ef365efc8266522c0dd521d9cd57dbbf1cab1c3b | jedzej/tietopythontraining-basic | /students/medrek_tomasz/lesson_01_basics/fractional_part.py | 322 | 4.15625 | 4 | #!/usr/bin/env python3
try:
given_number = float(input("Please enter a number:\n"))
except ValueError:
print('That was not a valid number, please try again')
exit()
real_part, fractional_part = str(given_number).split(".")
if (fractional_part == "0"):
print("0")
else:
print("0." + fractional_part)
| true |
39307299087bd61598c27d2af3dd1aa8f04d3be5 | jedzej/tietopythontraining-basic | /students/wachulec_maria/lesson_03_functions/the_collatz_sequence_and_input_validation.py | 298 | 4.1875 | 4 | def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
try:
n = int(input('Take me number: '))
while n != 1:
n = collatz(n)
print(n)
except ValueError:
print('Error: I need integer, not string')
| true |
d131c1b41d71cf1ce66624f81b3c105cb64e4bdb | jedzej/tietopythontraining-basic | /students/serek_wojciech/lesson_06_dict/uppercase.py | 349 | 4.1875 | 4 | #!/usr/bin/env python3
"""Uppercase"""
def capitalize(lower_case_word):
"""Change the first letter to uppercase"""
return lower_case_word[0].upper() + lower_case_word[1:]
def main():
"""Main function"""
text = input().split()
for word in text:
print(capitalize(word), end=' ')
if __name__ == '__main__':
main()
| true |
549edc4edb0ed0667b8cbe4eff8e56b398843897 | jedzej/tietopythontraining-basic | /students/BRACH_Jakub/lesson_01_basics/L01P01_Three_Numbers.py | 230 | 4.15625 | 4 | #!/usr/bin/env python3
number_of_factors = 3
summ = 0
for x in range(0, number_of_factors):
#print('Enter the number {0:d} of {1:d}:'.format(x, number_of_factors))
summ = summ + int(input())
print ("{0:d}".format(summ))
| true |
ffdd1515810c94ca20ac8f3e61c5cd339b181e1c | jedzej/tietopythontraining-basic | /students/piechowski_michal/lesson_05_lists/comma_code.py | 348 | 4.25 | 4 | #!/usr/bin/env python3
def join_list(strings_list):
if not strings_list:
return "List is empty"
elif len(strings_list) == 1:
return str(strings_list[0])
else:
return ", ".join(strings_list[:-1]) + " and " + strings_list[-1]
strings_list = ['apples', 'bananas', 'tofu', 'cats']
print(join_list(strings_list))
| true |
57b4d4e7572261d52016a6079ff900ed100db4a4 | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_01_basics/area_of_right-angled_triangle.py | 589 | 4.25 | 4 | '''
title: area_of_right-angled_triangle
author: arkadiusz.kasprzyk@tieto.com
date: 2018-03-05
description:
Write a program that reads the length of the base and the height of a right-angled triangle and prints the area.
Every number is given on a separate line.
'''
print("Reads the length of the base and the height of a right-angled triangle and prints the area.\n"
"Every number is given on a separate line.")
b = float(input("give base length: "))
h = float(input("give height: "))
a = b*h/2
print("The area of the triangle is {}".format(a))
input("Press Enter to quit the program.")
| true |
6fafbc30d64f641d0f4766207dc5a348604ead0c | jedzej/tietopythontraining-basic | /students/baker_glenn/lesson_1_scripts/previous_next.py | 279 | 4.3125 | 4 | # Script to print the previous and next number of a given number
print("enter a number")
number = int(input())
print("The next number for the number " + str(number) + " is " + str(number + 1))
print("The previous number for the number " + str(number) + " is " + str(number - 1))
| true |
423f23d1bce7d52dd7382fc64edc1ef64527c649 | jedzej/tietopythontraining-basic | /students/piatkowska_anna/lesson_03_functions/exponentiation.py | 589 | 4.3125 | 4 | """
Statement
Given a positive real number a and a non-negative integer n.
Calculate an without using loops, ** operator or the built in
function math.pow(). Instead, use recursion and the relation
an=a⋅an−1. Print the result.
Form the function power(a, n).
"""
def power(a, n):
if (n == 0):
return 1
else:
return a * power(a, n - 1)
if __name__ == "__main__":
try:
print(power(float(input("Enter positive real number: ")),
int(input("Enter a power number: "))))
except ValueError:
print("Error, invalid value.")
| true |
4c4aeb55d10a94f8c8db6d4ceb5f73f02aa0fc0f | jedzej/tietopythontraining-basic | /students/urtnowski_daniel/lesson_05_lists/snakify_lesson_7.py | 2,308 | 4.40625 | 4 | #!/usr/bin/env python3
"""
snakify_lesson_7.py: Solutions for 3 of problems defined in:
Lesson 7. Lists
(https://snakify.org/lessons/lists/problems/)
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
def greater_than_neighbours():
"""
This function reads a list of numbers and prints the quantity of elements
that are greater than both of their neighbors
"""
print("Problem: Greater than neighbours")
numbers = [int(a) for a in input().split()]
counter = 0
for i in range(1, len(numbers) - 1):
if numbers[i - 1] < numbers[i] and numbers[i + 1] < numbers[i]:
counter += 1
print(counter)
def swap_min_and_max():
"""
This function reads a list of unique numbers, swaps the minimal and maximal
elements of this list and prints the resulting list.
"""
print("Problem: Swap min and max")
numbers = [int(a) for a in input().split()]
idx_max = 0
idx_min = 0
for i in range(1, len(numbers)):
if numbers[i] > numbers[idx_max]:
idx_max = i
if numbers[i] < numbers[idx_min]:
idx_min = i
if idx_max != idx_min:
numbers[idx_min], numbers[idx_max] = numbers[idx_max], numbers[idx_min]
stringified_nums = [str(num) for num in numbers]
print(' '.join(stringified_nums))
def the_bowling_alley():
"""
This function reads the number of pins and the number of balls to be
rolled, followed by pairs of numbers (one for each ball rolled).
The subsequent number pairs represent the start to stop (inclusive)
positions of the pins that were knocked down with each role. Then it
prints a sequence of characters representing the pins, where "I" is
a pin left standing and "." is a pin knocked down.
"""
print("Problem: The bowling alley")
pins_num, balls_num = [int(num_str) for num_str in input().split()]
pins_states = pins_num * ['I']
for i in range(balls_num):
start, end = [int(num_str) for num_str in input().split()]
for k in range(start - 1, end):
pins_states[k] = '.'
if 'I' not in pins_states:
break
print(''.join(pins_states))
def main():
greater_than_neighbours()
swap_min_and_max()
the_bowling_alley()
if __name__ == '__main__':
main()
| true |
0f1ea0541aced96c8e2fe19571752af04fdf488d | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_01_basic/area_of_right-angled_triangle.py | 408 | 4.1875 | 4 | # Problem «Area of right-angled triangle» (Easy)
# Statement
# Write a program that reads the length of the base and the height of a right-angled triangle and prints the area.
# Every number is given on a separate line.
print('Please input triangle\'s base:')
base = int(input())
print('Please input height of the triangle:')
height = int(input())
print('Triangle\'s area is ' + str((base * height) / 2))
| true |
15720a0a5e835375b857d2efd3f58b305c0d162f | jedzej/tietopythontraining-basic | /students/sendecki_andrzej/lesson_01_basics/hello_harry.py | 262 | 4.53125 | 5 | # lesson_01_basics
# Hello, Harry!
#
# Statement
# Write a program that greets the user by printing the word "Hello",
# a comma, the name of the user and an exclamation mark after it.
print("Enter your name:")
my_name = input()
print("Hello, " + my_name + "!")
| true |
782275fee4250e4a33a7ec8dc3cb46c9074976d5 | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_01_basic/car_route.py | 404 | 4.125 | 4 | # Problem «Car route» (Easy)
# Statement
# A car can cover distance of N kilometers per day.
# How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M.
import math
print('Please input km/day:')
speed = int(input())
print('Please input length:')
length = int(input())
print('Distance can be travelled in: ' + str(math.ceil(length / speed)) + ' days')
| true |
9ad0674a05315b989d111ffec5557c847582c540 | jedzej/tietopythontraining-basic | /students/myszko_pawel/lesson_02_flow_control/14_The number of zeros.py | 405 | 4.125 | 4 | # Given N numbers: the first number in the input is N, after that N integers are given.
# Count the number of zeros among the given integers and print it.
# You need to count the number of numbers that are equal to zero, not the number of zero digits.
# Read an integer:
N = int(input())
# Print a value:
zeroes = 0
for i in range(N):
a = int(input())
if a == 0:
zeroes += 1
print(zeroes) | true |
c8c1963bad864b383a77727973232b4e3b7c392b | danserboi/Marketplace | /tema/consumer.py | 2,594 | 4.34375 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
import time
from threading import Thread
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
Constructor.
:type carts: List
:param carts: a list of add and remove operations
:type marketplace: Marketplace
:param marketplace: a reference to the marketplace
:type retry_wait_time: Time
:param retry_wait_time: the number of seconds that a producer must wait
until the Marketplace becomes available
:type kwargs: a dict with the following format:
{'name': <CONSUMER_ID>}.
:param kwargs: other arguments that are passed to the Thread's __init__()
"""
Thread.__init__(self, **kwargs)
self.carts = carts
self.marketplace = marketplace
self.retry_wait_time = retry_wait_time
def run(self):
"""
Here we make orders for every cart of the consumer.
"""
# we parse every cart of the consumer
for cart in self.carts:
# we create a new cart for the consumer
cart_id = self.marketplace.new_cart()
# we parse every action that is done with the current cart
for action in cart:
# we want to produce the action in the specified number of times
curr_no = action["quantity"]
while curr_no > 0:
# we verify the type of action
if action["type"] == "add":
is_added = self.marketplace.add_to_cart(cart_id, action["product"])
# if the product is successfully added to the cart,
# we decrease the current number
if is_added:
curr_no -= 1
# else, we should wait and try again after
else:
time.sleep(self.retry_wait_time)
# the action of removing is always successful
# so we don't have to verify anything,
# just decrease the current number after
elif action["type"] == "remove":
self.marketplace.remove_from_cart(cart_id, action["product"])
curr_no -= 1
# now we can place the order for this cart
self.marketplace.place_order(cart_id)
| true |
35d8e0f70cfd155ab513ed9b405903a140164f19 | rkp872/Python | /6)Functions/TypesOfArgument.py | 2,926 | 4.65625 | 5 | # Information can be passed into functions as arguments.
# Arguments are specified after the function name, inside
# the parentheses.
#In python we have different types of agruments:
# 1 : Position Argument
# 2 : Keyword Argument
# 3 : Default Argument
# 4 : Variable length Argument
# 5 : Keyworded Variable length Argument
#-------------------------------
# 1 : Position Argument
# while calling the function ,order of passing the values is important
#because the values will be binded with the formal argument in the same order
#this types of argument is called as positional argument
def person(name,age):
print("Name is: ",name)
print("Age is : ",age)
name="Rohit"
age=23
person(name,age)
#person(age,name) This is not the correct way because 23 will go to name and rohit will go to age in the function
#---------------------------------
# 2 : Keyword Argument
#Many a times the function is defined by some other people and is used by some other people.
#So the caller doesn't know the formal agrument order
#In this case keyword argument can be used where we use the keyword with the
# arguments while caling it
def person(name,age):
print("Name is: ",name)
print("Age is : ",age)
name="Rohit"
age=23
person(age=age,name=name)
#--------------------------------------------------
# 3 : Default Argument
#Sometimes caller doesn't provide all the values for the formal argument
#In this case while defining the funtion only we can provide default value for the argument whose value will not be passed by caller
#This type of argument is called default argument
def person(name,age=18):
print("Name is: ",name)
print("Age is : ",age)
name="Rohit"
person(name)
#------------------------------------------
# 4 : Variable length Argument
#sometimes caller may paas more number of arguments than the number of formal agruments
#In that case the formal arguments must be of variable length
# we can create variable length argument by putting * sign before the name of last argument
def sum(a,*b):
sum=a
for i in b: #In the funtion all the passed value will be stored in a tuple with name b,So for accessing it we have to use for loop here
sum=sum+i
print("Sum is ",sum)
sum(10,20)
sum(10,20,30)
sum(10,20,30,40,50,60,40)
#-----------------------------------------------------------
# 5 : Keyworded Variable length Argument
# Foe having meaningful use of the variable length arguments we can also
# specify a keyword with them while passing ,which denotes the what data
# it is storing .Such type of arguments are called as
#Keyworded Variable length Argument
def person(name,**data):
print(name)
for i,j in data.items(): #Foe accessing one data at a time we use item() function
print(i,j)
person("Rohit",age=25,city="Ranchi",Mobile=9123114708)
| true |
e87320897e3f5dfaf10564b9f79b6487649dfcc4 | rkp872/Python | /3)Conditional/SquareCheck.py | 272 | 4.34375 | 4 | #Take values of length and breadth of a rectangle from user and check if it is square or not.
len=int(input("Enter length : "))
bre=int(input("Enter breadth : "))
if(len==bre):
print("Given rectangle is square")
else:
print("Given rectangle is not a square") | true |
1af02fa80c544f52c1f2e4a2f0c767c96b14a4b6 | rkp872/Python | /2)Data Types/Set.py | 726 | 4.21875 | 4 | # Set: Set are the collection of hetrogeneous elements enclosed within {}
# Sets does not allows duplicates and insertion order is not preserved
#Elements are inserted according to the order of their hash value
set1={10,20,20,30,50,40,60}
print(set1)
print(type(set1))
set1.add(36)
print(set1)
set2=set1.copy()
print(set2)
set2.remove(20)
set2.remove(60)
print(set2)
print(set1.difference(set2)) #returns elements which are present in set1 but not in set2
print(set2.difference(set1)) #returns elements which are present in set2 but not in set1
print(set1.intersection(set2)) #Returns intersection of two sets
print(set1.union(set2)) #Returns Union of two sets
print(len(set1)) | true |
d85c3e867c8d10f6b71231e9c581d0f4274ec9c3 | Randy760/Dice-rolling-sim | /Dicerollingsimulator.py | 694 | 4.1875 | 4 | import random
# making a dice rolling simulator
youranswer = ' '
print('Would you like to roll the dice?') #asks if they want to roll the dice
while True:
youranswer = input()
if youranswer == 'yes':
diceroll = random.randint(1,6) #picks a random number between 1 and 6
print(diceroll) #prints the random diceroll
print('Would you like to roll the dice, again?') #asks if they want to roll again
elif youranswer != 'yes': #if their answer is not 'yes' , then the loop is broken
break
print('Thanks for playing!') # prints this once the program reaches the end
| true |
3591366d9968bf42380c2f40c55f8db2ae34052a | keshav1245/Learn-Python-The-Hard-Way | /exercise11/ex11.py | 729 | 4.40625 | 4 | print "How old are you ?",
age = raw_input()
print "How tall are you ?",
height = raw_input()
print "How much do you weight ? ",
weight = raw_input()
#raw_input([prompt])
#If the prompt argument is present, it is written to standard output without a trailing newline. The
#function then reads a line from input, converts it to a string (stripping a trailing newline), and
#returns that. When EOF is read, EOFError is raised. Example:
name = raw_input("What is your name? >> ")
print "So, you're %r old, %r tall and your weight is %r."%(age,height,weight)
print ("Your name is : %s"% name + "\n")*10
#getting a number
marks = float(raw_input("Enter your CGPA : "))
print "CGPA is : ",marks
print ("%s \n %r")%(name,name)
| true |
2f1bd009c20a51bab241ad3c31528b0f0664ed93 | rohan-khurana/MyProgs-1 | /SockMerchantHR.py | 1,687 | 4.625 | 5 | """
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers describing the colors of the socks in the pile.
Constraints
where
Output Format
Return the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Explanation
sock.png
John can match three pairs of socks.
"""
# SOLUTION
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
Sum = 0
for value in Counter(ar).values():
Sum += value//2;
return Sum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
| true |
9f6ee9426e3bd6c017e82c317f0800236cd2dc13 | rohan-khurana/MyProgs-1 | /TestingHR.py | 2,987 | 4.28125 | 4 | """
This problem is all about unit testing.
Your company needs a function that meets the following requirements:
For a given array of integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the smallest one.
If an empty array is passed to the function, it should raise an Exception.
Note: The arrays are indexed from .
A colleague has written that function, and your task is to design separated unit tests, testing if the function behaves correctly. The implementation in Python is listed below (Implementations in other languages can be found in the code template):
def minimum_index(seq):
if len(seq) == 0:
raise ValueError("Cannot get the minimum value index from an empty sequence")
min_idx = 0
for i in range(1, len(seq)):
if a[i] < a[min_idx]:
min_idx = i
return min_idx
Another co-worker has prepared functions that will perform the testing and validate returned results with expectations. Your task is to implement classes that will produce test data and the expected results for the testing functions. More specifically: function get_array() in TestDataEmptyArray class and functions get_array() and get_expected_result() in classes TestDataUniqueValues and TestDataExactlyTwoDifferentMinimums following the below specifications:
get_array() method in class TestDataEmptyArray has to return an empty array.
get_array() method in class TestDataUniqueValues has to return an array of size at least 2 with all unique elements, while method get_expected_result() of this class has to return the expected minimum value index for this array.
get_array() method in class TestDataExactlyTwoDifferentMinimums has to return an array where there are exactly two different minimum values, while method get_expected_result() of this class has to return the expected minimum value index for this array.
Take a look at the code template to see the exact implementation of functions that your colleagues already implemented.
"""
# SOLUTION
def minimum_index(seq):
if len(seq) == 0:
raise ValueError("Cannot get the minimum value index from an empty sequence")
min_idx = 0
for i in range(1, len(seq)):
if seq[i] < seq[min_idx]:
min_idx = i
return min_idx
class TestDataEmptyArray(object):
@staticmethod
def get_array():
# complete this function
return list()
class TestDataUniqueValues(object):
@staticmethod
def get_array():
# complete this function
return [0,1,-1]
@staticmethod
def get_expected_result():
# complete this function
return 2
class TestDataExactlyTwoDifferentMinimums(object):
@staticmethod
def get_array():
# complete this function
return [0,1,-1,-1]
@staticmethod
def get_expected_result():
# complete this function
return 2
| true |
8e07f7fdba8ee6adae646070615b9b8d756462bc | rohan-khurana/MyProgs-1 | /TheXORProblemHR.py | 1,865 | 4.25 | 4 | """
Given an integer, your task is to find another integer such that their bitwise XOR is maximum.
More specifically, given the binary representation of an integer of length , your task is to find another binary number of length with at most set bits such that their bitwise XOR is maximum.
For example, let's say that = "0100" and = 1. The maximum possible XOR can be obtained with = "1000", where XOR = "1100".
Input Format
The first line of input contains an integer, , the number of tests.
The first line of each test contains a binary string representing .
The second line of each test contains an integer, , denoting the maximum number of set bits in .
Constraints
Output Format
Print exactly lines. In the of them, print the string denoting in the test case.
Sample Input 0
2
10010
5
01010
1
Sample Output 0
01101
10000
Explanation 0
For the first case, (x xor y) gives 11111 which is the maximum possible number that can be obtained.
In the second case, (x xor y) gives 11010. Note that any other y would given a lesser xor sum.
"""
#SOLUTION
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'maxXorValue' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING x
# 2. INTEGER k
#
def maxXorValue(x, k):
# Write your code here
x = list(str(x))
value = []
for i in x :
if i == '0' and k >0:
value.append('1')
k -= 1
else :
value.append('0')
value = ''.join(value)
return value
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input().strip())
for t_itr in range(t):
s = input()
k = int(input().strip())
y = maxXorValue(s, k)
fptr.write(y + '\n')
fptr.close()
| true |
f7e30fb9549c6e8c88792ac40d5c59ef0a86edf6 | tonyvillegas91/python-deployment-example | /Python Statements/list_comprehension2.py | 205 | 4.34375 | 4 | # Use a List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
[word[0] for word in st.split()]
| true |
79aa8a94a6c3953ea852f3a087f1f0a89dbd0af7 | hamanovich/py-100days | /01-03-datetimes/program2.py | 1,197 | 4.25 | 4 | from datetime import datetime
THIS_YEAR = 2018
def main():
years_ago('8 Aug, 2015')
convert_eu_to_us_date('11/03/2002')
def years_ago(date):
"""Receives a date string of 'DD MMM, YYYY', for example: 8 Aug, 2015
Convert this date str to a datetime object (use strptime).
Then extract the year from the obtained datetime object and subtract
it from the THIS_YEAR constant above, returning the int difference.
So in this example you would get: 2018 - 2015 = 3"""
date_format = '%d %b, %Y'
return THIS_YEAR - datetime.strptime(date, date_format).year
def convert_eu_to_us_date(date):
"""Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002
Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002).
To enforce the use of datetime's strptime / strftime (over slicing)
the tests check if a ValueError is raised for invalid day/month/year
ranges (no need to code this, datetime does this out of the box)"""
date_format_EU = '%d/%m/%Y'
date_format_USA = '%m/%d/%Y'
return datetime.strptime(date, date_format_EU).strftime(date_format_USA)
if __name__ == "__main__":
main() | true |
d1db24e49d5698c3d9f2b6db4794fa94aebb3e5f | inest-us/python | /algorithms/c1/tuple.py | 642 | 4.15625 | 4 | # Tuples are very similar to lists in that they are heterogeneous sequences of data.
# The difference is that a tuple is immutable, like a string.
# A tuple cannot be changed.
# Tuples are written as comma-delimited values enclosed in parentheses.
my_tuple = (2,True,4.96)
print(my_tuple) # (2, True, 4.96)
print(len(my_tuple)) # 3
print(my_tuple[0]) # 2
print(my_tuple * 3) # (2, True, 4.96, 2, True, 4.96, 2, True, 4.96)
print(my_tuple[0:2]) # (2, True)
# my_tuple[1]=False
# Traceback (most recent call last):
# File "<pyshell#137>", line 1, in <module>
# my_tuple[1]=False
# TypeError: 'tuple' object does not support item assignment | true |
42d484424e2bb30b0bae4e3ea9a9f3cb668d8f8c | jsburckhardt/pythw | /ex3.py | 693 | 4.15625 | 4 | # details
print("I will now count my chickens:")
# counts hens
print("Hens", float(25 + 30 / 6))
# counts roosters
print("Roosters", float(100 - 25 *3 % 4))
# inform
print("Now I will count the eggs:")
# eggs
print(float(3 + 2 + 1 + - 5 + 4 % 2 - 1 / 4 + 6))
# question 5 < -2
print("Is it true that 3 + 2 < 5 - 7?")
# validates 5<-2
print(3 + 2 < 5 - 7)
# 3 + 2
print("What is 3 + 2?", float(3 + 2))
# 5-7
print("What is 5 - 7?", float(5 - 7))
# affirms
print("Oh, that's why it's False")
# informs
print("How about some more.")
# greater than
print("Is it greater?", 5 > -2)
# greater or equal
print("Is it greater or equal?", 5 >= -2)
# less or equal
print("Is it less or equal?", 5 <= -2) | true |
0081ea28bee4c8b24910c6a3a8b3d559431efde5 | lima-BEAN/python-workbook | /programming-exercises/ch7/larger_than_n.py | 1,565 | 4.40625 | 4 | # Larger Than n
# In a program, write a function that accepts two arguments:
# a list and a number, n. Assume that the list contains numbers.
# The function should display all of the numbers in the list that
# are greater than the number n.
import random
def main():
numbers = Numbers()
user_num = UserNum()
Compare(numbers, user_num)
def Numbers():
numbers = []
for x in range(20):
number = random.randint(1, 100)
numbers.append(number)
return numbers
def UserNum():
number = float(input('Choose between 1-100 to compare to a list of 20 random numbers. '))
while number <= 0 or number > 100:
number = float(input('Please choose a number between 1-100 '))
return number
def Compare(numbers, user_num):
greater_than = []
smaller_than = []
equal_to = []
count = 0
for num in numbers:
if num < user_num:
smaller_than.append(num)
elif num > user_num:
greater_than.append(num)
else:
equal_to.append(num)
print()
print('====== Random Numbers Smaller Than Your Number =====')
for num in smaller_than:
count += 1
print(str(count) + '. ' + str(num))
print()
print('====== Random Numbers Greater Than Your Number =====')
for num in greater_than:
count += 1
print(str(count) + '. ' + str(num))
print()
print('====== Random Numbers Equal To Your Number =====')
for num in equal_to:
count += 1
print(str(count) + '. ' + str(num))
main()
| true |
43dc28165ec22f719d9e594091c82366cc574384 | lima-BEAN/python-workbook | /programming-exercises/ch2/distance-traveled.py | 618 | 4.34375 | 4 | ## Assuming there are no accidents or delays, the distance that a car
## travels down the interstate can be calculated with the following formula:
## Distance = Speed * Time
## A car is traveling at 70mph. Write a program that displays the following:
## The distance a car will travel in 6 hours
## The distance a car will travel in 10 hours
## The distance a car will travel in 15 hours
speed = 70
time1 = 6
time2 = 10
time3 = 15
distance1 = speed * time1
distance2 = speed * time2
distance3 = speed * time3
print("Distance 1 is", distance1,
"\nDistance 2 is", distance2,
"\nDistance 3 is", distance3)
| true |
a913e26be57a7dcad82df5ddf127b85933c4c0c0 | lima-BEAN/python-workbook | /programming-exercises/ch5/kinetic_energy.py | 983 | 4.53125 | 5 | # Kinetic Energy
# In physics, an object that is in motion is said to have kinetic energy.
# The following formula can be used to determine a moving object's kinetic
# energy: KE = 1/2 mv**2
# KE = Kinetic Energy
# m = object's mass (kg)
# v = velocity (m/s)
# Write a program that asks the user to enter values for mass and velocity
# and then calls kinetic_energy function to get obj KE
def main():
mass = Mass()
velocity = Velocity()
kinetic_energy = KineticEnergy(mass, velocity)
Results(mass, velocity, kinetic_energy)
def Mass():
m = int(input('How much does the object weigh in kilograms? '))
return m
def Velocity():
v = int(input('What\'s the vehicle\'s velocity in meters/s? '))
return v
def KineticEnergy(m, v):
ke = (1/2) * m * (v**2)
return ke
def Results(m, v, ke):
print()
print('================== Results ========================')
print('Mass:', m, '\tVelocity:', v, '\tKinetic Energy:', ke)
main()
| true |
44ecf7731cf113a646f9fbfb9358a09f5dead62a | lima-BEAN/python-workbook | /programming-exercises/ch8/date_printer.py | 933 | 4.375 | 4 | # Date Printer
# Write a program that reads a string from the user containing a date in
# the form mm/dd/yyyy. It should print the date in the form
# March 12, 2014
def main():
user_date = UserDate()
date_form = DateForm(user_date)
Results(date_form)
def UserDate():
date = input('Enter a date in the format (mm/dd/yyyy): ')
return date
def DateForm(date):
months = [ 'January', 'Feburary', 'March', 'April', \
'May', 'June', 'July', 'August',\
'September', 'October', 'November', 'December' ]
f_date = ''
split_date = date.split('/')
m_date = ''
d_date = split_date[1]
y_date = split_date[2]
for x in range(len(months)):
if int(split_date[0]) == x+1:
m_date = months[x]
f_date = m_date + ' ' + d_date + ', ' + y_date
return f_date
def Results(date):
print()
print('Your formatted date is:', date)
main()
| true |
e8404b90ca40907cfca6018ce0c4bebf8752caec | lima-BEAN/python-workbook | /programming-exercises/ch2/ingredient-adjuster.py | 832 | 4.40625 | 4 | ## A cookie recipe calls for the following ingredients:
## - 1.5 cups of sugar
## - 1 cup of butter
## - 2.75 cups of flour
## The recipe produces 48 cookies with this amount of the ingredients.
## Write a program that asks the user how many cookies he or she wants to
## make, and then displays the number of cups of each ingredient needed
## for the specified number of cookies.
cookies = int(input("How many cookies do you want? "))
# 0.03215 cups of sugar per cookie
sugar = cookies * 0.03125
# 0.02083 cups of butter per cookie
butter = cookies * 0.02083
# 0.05729 cups of flour per cookie
flour = cookies * 0.05729
print("For", cookies, "cookies, you need:",
"\n\t", format(sugar, ".2f"), "cups of sugar",
"\n\t", format(butter, ".2f"), "cups of butter",
"\n\t", format(flour, ".2f"), "cups of flour",
| true |
cbae1470e46184c8a3b830ff5ad9076fe0f1864f | lima-BEAN/python-workbook | /programming-exercises/ch4/population.py | 720 | 4.46875 | 4 | # Write a program that predicts the approximate size of a population of organisms
# The application should use text boxes to allow the user to enter the starting
# number of organisms, the average daily population increase (as percentage),
# and the number of days the organisms will be left to multiply.
number_organisms = int(input("Starting number of organisms: "))
percent_increase = int(input('What is the daily increase (as percenetage): '))
days_to_multiple = int(input('How many days to multiple: '))
print('Day\tPopulation')
for day in range(1, (days_to_multiple+1)):
if day > 1:
number_organisms += (number_organisms * percent_increase)/100
print(day, '\t', format(number_organisms, '.1f'))
| true |
27eda59c433dd226459b8966720505f2c78d0cd1 | lima-BEAN/python-workbook | /programming-exercises/ch10/Information/my_info.py | 794 | 4.46875 | 4 | # Also, write a program that creates three instances of the class. One
# instance should hold your information, and the other two should hold
# your friends' or family members' information.
import information
def main():
my_info = information.Information('LimaBean', '123 Beanstalk St.',
'12 pods', '1-800-LimaBean')
fam1_info = information.Information('GreenBean', '456 Green St.',
'3 beans', '555-My-Greens')
fam2_info = information.Information('BlackBean', '987 Refried St.',
'7 black beans', '222-BLACK-REFRIED')
print('My Info:', my_info.get_name())
print('Fam1 Info:', fam1_info.get_name())
print('Fam2 Info:', fam2_info.get_name())
main()
| true |
8d62cbef5cbe028c9a8d83ddd18c5e52106d9c6b | lima-BEAN/python-workbook | /programming-exercises/ch3/roman-numerals.py | 982 | 4.34375 | 4 | # Write a program that prompts the user to enter a number within the range of 1
# through 10. The program should display the Roman numeral version of that
# number. If the number is outside the range of 1 through 10,
# the program should display an error message.
number = int(input("What number do you want to convert to Roman Numeral? (1-10) "))
if number == 1:
print(number, "is converted to I")
elif number == 2:
print(number, "is converted to II")
elif number == 3:
print(number, "is converted to III")
elif number == 4:
print(number, "is converted to IV")
elif number == 5:
print(number, "is converted to V")
elif number == 6:
print(number, "is converted to VI")
elif number == 7:
print(number, "is converted to VII")
elif number == 8:
print(number, "is converted to VIII")
elif number == 9:
print(number, "is converted to IX")
elif number == 10:
print(number, "is converted to X")
else:
print("Choose a number between 1 and 10")
| true |
f9500fd6cfdd6d846ed4b6fa2b034bd681d3d637 | lima-BEAN/python-workbook | /algorithm-workbench/ch2/favorite-color.py | 220 | 4.21875 | 4 | ## Write Python code that prompts the user to enter his/her favorite
## color and assigns the user's input to a variale named color
color = input("What is your favorite color? ")
print("Your favorite color is", color)
| true |
54b6e4930811ab19c5c64d37afc05fb0a8d69270 | lima-BEAN/python-workbook | /programming-exercises/ch10/Retail/item_in_register.py | 1,023 | 4.25 | 4 | # Demonstrate the CashRegister class in a program that allows the user to
# select several items for purchase. When the user is ready to check
# out, the program should display a list of all the items he/she has
# selected for a purchase, as well as total price.
import retail_item
import cash_register
def main():
add = input('Would you like to add an item to your cart? (y/n) ')
while add == 'Y' or add == 'y':
AddItem()
add = input('Would you like to add another item? (y/n) ')
Total()
Show()
def AddItem():
desc = input('What item would you like? ')
inv = input('How many ' + desc + ' would you like? ')
price = input('What is the price of that item? ')
new_item = retail_item.RetailItem(desc, inv, price)
cash_register.CashRegister.purchase_item(new_item)
def Total():
print('The total amount for the items is:',
cash_register.CashRegister.get_total())
def Show():
print('Items purchased:')
cash_register.CashRegister.show_items()
main()
| true |
14abd73ae4d52d04bfa9c06e700d9191d194f6b3 | lima-BEAN/python-workbook | /programming-exercises/ch5/sales_tax_program_refactor.py | 1,702 | 4.1875 | 4 | # Program exercise #6 in Chapter 2 was a Sales Tax Program.
# Redesign solution so subtasks are in functions.
## purchase_amount = int(input("What is the purchasing amount? "))
## state_tax = 0.05
## county_tax = 0.025
## total_tax = state_tax + county_tax
## total_sale = format(purchase_amount + (purchase_amount * total_tax), '.2f')
##
## print("The purchase amount for the item is $" + str(purchase_amount),
## "\n\tState tax:", format((state_tax * purchase_amount), '.2f'),
## "\n\tCounty tax:", format((county_tax * purchase_amount), '.2f'),
## "\n\tTotal tax:", format((total_tax * purchase_amount), '.2f'),
## "\n\tTotal sale amount is $" + str(total_sale))
COUNTY_TAX = 0.025
STATE_TAX = 0.05
def main():
purchase_amount = float(input('What is the purchasing amount? '))
county_tax = CountyTax(purchase_amount)
state_tax = StateTax(purchase_amount)
total_tax = TotalTax(county_tax, state_tax)
total_sale = TotalSale(purchase_amount, total_tax)
PrintBill(purchase_amount, county_tax, state_tax,
total_tax, total_sale)
def CountyTax(p_amount):
return p_amount * COUNTY_TAX
def StateTax(p_amount):
return p_amount * STATE_TAX
def TotalTax(c_tax, s_tax):
return c_tax + s_tax
def TotalSale(p_amount, t_tax):
return p_amount + t_tax
def PrintBill(p_amount, c_tax, s_tax, t_tax, t_sale):
print('============ Bill Summary ================')
print("Purchase amount:", format(p_amount, '.2f'),
"\nTotal tax:", '\t', format(t_tax, '.2f'),
"\t\t=>","\tCounty tax:", format(c_tax, '.2f'),
"+ State tax:", format(s_tax, '.2f'),
"\nTotal sale:", '\t', format(t_sale, '.2f'))
main()
| true |
3d9deda751cdfa233cdf0c711f3432be950980d3 | tejastank/allmightyspiff.github.io | /CS/Day6/linkedList01.py | 1,399 | 4.21875 | 4 | """
@author Christopher Gallo
Linked List Example
"""
from pprint import pprint as pp
class Node():
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def __str__(self):
return str(self.data)
class linked_list():
def __init__(self):
self.head = None
self.current = None
self.tail = None
def __str__(self):
if self.head is None:
return None
start = self.head
out = "%s" % (start)
while start.next != None:
start = start.next
out += ", %s" % str(start)
return out
def __iter__(self):
self.current = None
return self
def next(self):
if self.head and not self.current:
self.current = self.head
return self.current
elif self.current.next:
self.current = self.current.next
return self.current
else:
raise StopIteration
def add_node(self, node):
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
if __name__ == "__main__":
my_list = linked_list()
my_list.add_node(Node('a'))
my_list.add_node(Node('b'))
my_list.add_node(Node(100))
# print(my_list)
for l in my_list:
print(l)
| true |
611d3db5bf36c987bb459ff19b7ab0a215cfec83 | laurenwheat/ICS3U-Assignment-5B-Python | /lcm.py | 753 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Lauren Wheatley
# Created on: May 2021
# This program displays the LCM of 2 numbers
def main():
a = input("Please enter the first value: ")
b = input("Please enter the second value: ")
try:
a_int = int(a)
b_int = int(b)
if (a_int > b_int):
maximum = a_int
else:
maximum = b_int
while(True):
if(maximum % a_int == 0 and maximum % b_int == 0):
print("LCM is {0}".format(maximum))
break
maximum = maximum + 1
except Exception:
print("That is not a number!!!!!!")
finally:
print("")
print("Thanks for playing <3")
if __name__ == "__main__":
main()
| true |
722c9fef00cc8c68bda1a32eb5964413311f1a2d | smtorres/python-washu-2014 | /Assignment01/school.py | 1,042 | 4.21875 | 4 | from collections import OrderedDict
class School():
def __init__(self, school_name):
self.school_name = school_name
self.db = {}
# Function that adds values and keys to a dictionary. Keys are school grades and each can take as value the name of a kid belonging to that grade.
# It returns a dictionary with the name of the keys
def add(self, name, grade):
if grade in self.db:
self.db[grade].add(name)
else:
self.db[grade] = {name}
# Function that takes as input Grade and delivers the names of the kids that belong to that group.
def grade(self, grade):
if grade not in self.db.keys():
return None
else:
return self.db.get(grade)
print self.db.keys
# Function that sorts and converts the values of the dictionary from sets to tuples.
def sort(self):
new_dic = self.db
for i in range(0, len(new_dic)):
Key = new_dic.keys()[i]
Value = new_dic.values()[i]
Value = list(Value)
Value = tuple(Value)
new_dic[Key] = Value
print new_dic.values
return new_dic
| true |
8a199663c4dc2228104bbab583fd9ecaddcac34d | amitopu/ProblemSet-1 | /NonConstructibleChange/nonConstructibleChange.py | 1,728 | 4.40625 | 4 | def nonConstructibleChangePrimary(coins):
"""
Takes an arrary of coin values and find the minimum change that can't be made by the coins
available in the array.
solution complexity : O(nlogn) time complexity and O(1) space complexity
args:
-----------
coins (array): an array contains available coin values.
output:
-----------
number (int) : represent the minimum amount of change that can't be made by the coins.
"""
# if the array is empty return 1
# if array has single element and greater than 1 return 1
n = len(coins)
if n == 0 or (n == 1 and coins[0] > 1):
return 1
#sort the list of coins
coins.sort()
# add adjacent elements successively
# and check if there is a minimum change that can't be done
sum = 0
for i in range(len(coins)-1):
sum += coins[i]
if coins[i+1] - sum >= 2:
return sum + 1
return sum + coins[n-1] + 1
def nonConstructibleChangeBetter(coins):
"""
Takes an arrary of coin values and find the minimum change that can't be made by the coins
available in the array.
solution complexity : O(nlogn) time complexity and O(1) space complexity and has less lines of code.
args:
-----------
coins (array): an array contains available coin values.
output:
-----------
number (int) : represent the minimum amount of change that can't be made by the coins.
"""
currentChange = 0
# sort the array
coins.sort()
# iterate through the array and find the minimum change and return
# if current itaration stage can't find minimum change add current coin
# with the current change and make new current change.
for coin in coins:
if currentChange + 1 < coin:
return currentChange + 1
currentChange += coin
return currentChange + 1 | true |
e874e83c5936a8dcd28f2f04dde6de4d604c5980 | amitopu/ProblemSet-1 | /ValidateSubsequence/validate_subsequence.py | 795 | 4.3125 | 4 | def isValidSubsequence(array, sequence):
"""
Takes one array and a sequence(another array) and checks if the sequence is the subsequence of the array.
solution complexity : O(n) time complexity and O(1) space complexity
args:
-----------
array : an array of numbers
sequence : an array of numbers
output:
-----------
True : if the sequence is subsequence of the array.
False : if above line is not true.
"""
arr_index = 0
seq_index = 0
#iterate over the array and check if elems in sequence are in the array
while(arr_index <= len(array)-1):
if(array[arr_index] == sequence[seq_index]):
if(seq_index == len(sequence)-1):
return True
seq_index += 1 # take the next element in the sequence
arr_index += 1 # take the next elem in the array
return False | true |
610395c1c0a55d4f8b7099bea152e4feb27dec23 | Patryk9201/CodeWars | /Python/6kyu/one_plus_array.py | 693 | 4.1875 | 4 | """
Given an array of integers of any length, return an array that has 1 added to the value represented by the array.
the array can't be empty
only non-negative, single digit integers are allowed
Return nil (or your language's equivalent) for invalid inputs.
Examples
For example the array [2, 3, 9] equals 239, adding one would return the array [2, 4, 0].
[4, 3, 2, 5] would return [4, 3, 2, 6]
"""
import unittest
def up_array(arr):
if not arr or min(arr) < 0 or max(arr) > 9:
return None
else:
return [int(y) for y in str(int("".join([str(x) for x in arr])) + 1)]
if __name__ == '__main__':
x = up_array([2, 3, 9])
print(x)
unittest.main()
| true |
a03d3d86b25f8f132efb169ad8bd8174a9152ddb | Patryk9201/CodeWars | /Python/8kyu/temperature_in_bali.py | 1,092 | 4.1875 | 4 | """
So it turns out the weather in Indonesia is beautiful... but also far too hot most of the time.
Given two variables: heat (0 - 50 degrees centigrade) and humidity (scored from 0.0 - 1.0),
your job is to test whether the weather is bareable (according to my personal preferences :D)
Rules for my personal preferences
i. if humidity > 0.5 or the heat >= 36, it's unbearable return false
ii. if 25 < heat < 36 and the humidity > 0.4, also unbearable return false
iii. otherwise, it's sunbathing time :), return true
Examples
> heat = 36, humdity = 0.3 -> return false
> heat = 36, humdity = 0.5 -> return false
> heat = 10, humdity = 0.51 -> return false
-> triggered rule 1
> heat = 27, humdity = 0.5 -> return false
-> triggered rule 2
> heat = 27, humdity = 0.4 -> return true
> heat = 25, humdity = 0.5 -> return true
> heat = 33, humdity = 0.38 -> return true
-> triggered rule 3
"""
def bareable(heat, humidity):
return False if heat > 35 or humidity > 0.5 or humidity > 0.4 and 26 <= heat <= 35 else True
if __name__ == '__main__':
x = bareable(0.5, 10)
print(x)
| true |
6151cf5dbcf387ec524efa0e39cf400c69ca1ee7 | yurjeuna/teachmaskills_hw | /anketa.py | 1,580 | 4.25 | 4 | name = input("Hi! What's your name, friend? ")
year_birth = int(input("Ok, do you remember when you were born? \
Let's start with the year of birth - "))
month_birth = int(input("The month of your birth - "))
day_birth = int(input("And the day of your birth, please,- "))
experience = int(input("Have you studied programming before? \
Choose the right option: 1 No 2 On your own 3 On course 4 In the university "))
goal = input("What are your expectations from this course? Continue the phrase: I'm here for ... ")
year_now = int(input("So the last question," + name + ". What's the date of filling this form? \
Let's start with the year of filling - "))
month_now = int(input("The month of filling - "))
day_now = int(input("And the day of filling, please, - "))
if month_birth > month_now:
age = year_now - year_birth
elif month_birth < month_now:
age = year_now - year_birth + 1
elif month_birth == month_now:
if day_birth > day_now:
age = year_now - year_birth
else:
age = year_now - year_birth + 1
print("Thank you, ", name, ". You are ", age, " years old. It's the perfect age.", sep='')
if experience == 1:
print("You haven't any experience in programming.")
elif experience == 2:
print("You tried to study programming on your own.")
elif experience == 3:
print("You have already tried to study programming on some course.")
elif experience == 4:
print("You studied programming in the university.")
print("And now you are here for ", goal, ". So good luck to you! See you on lessons.", sep='')
| true |
9d569685b0d8d137b9ee7a23180289cfdd10488e | ErickaBermudez/exercises | /python/gas_station.py | 1,752 | 4.3125 | 4 | def canCompleteCircuit(gas, cost):
numberOfStations = len(gas)
# checking where it is possible to start
for currentStartStation in range(numberOfStations):
currentGas = gas[currentStartStation]
canStart = True # with the current starting point, we can reach all the points
# go through the circuit
for station in range(numberOfStations):
###### to move in a circular array we use % #######
currentStation = (currentStartStation + station) % numberOfStations
nextStation = (currentStation + 1) % numberOfStations
# reference of this: https://www.geeksforgeeks.org/circular-array/
####################################################
# let's check what happens if we try to go to the next station
currentGas -= cost[currentStation]
# if the cost is greater than our current gas, we cannot afford it
# therefore the currentStartStation is not an option anymore
if currentGas < 0:
canStart = False # this starting point is no longer suitable
break # <-- we try another startStation
# if we could go to the next, we are allowed to put more gas
currentGas += gas[nextStation]
# if we finish the circuit succesfully, we can start at the currentStartStation
# and we don't need to continue checking
if canStart:
return currentStartStation
# if we go through all the options to start and we don't find any solution
return -1
# example
startAt = canCompleteCircuit([5,1,2,3,4], [4,4,1,5,1])
if startAt > 0:
print(startAt)
else:
print("We don't have enough gas </3") | true |
b2ee470fd49b2af6f975b9571c5f7579082da359 | mhkoehl0829/sept-19-flow-control | /Grade Program.py | 515 | 4.125 | 4 | print('Welcome to my grading program.')
print('This program will determine which letter grade you get depending on your score.')
print('What grade did you make?')
myGrade = input('')
if myGrade >= '90':
print('You made an A.')
else:
if myGrade >= '80' and myGrade < '90':
print('You get a B.')
if myGrade >= '70' < myGrade < '80':
print('You earned a C.')
if myGrade >= '60' and myGrade < '70':
print('You get a D.')
if myGrade <= '60':
print('You flunked.') | true |
ec7c0d69a9e98853f063fd32ef431f4f28448d76 | Alleinx/Notes | /Python/Book_Learning_python/fluent_python/cp8/var.py | 875 | 4.5625 | 5 | # This program demonstrate the difference between shallow copy and deep copy
import copy
class Bus:
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
# Defensive programming style, won't modify the original object if it's mutable.
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
if name in self.passengers:
self.passengers.remove(name)
else:
print(name, 'is not in the passenger list of the bus.')
bus1 = Bus(['A', 'B', 'C'])
bus2 = copy.copy(bus1)
bus3 = copy.deepcopy(bus1)
print(id(bus1), id(bus2), id(bus3))
bus1.drop('B')
print(bus2.passengers, ',', bus3.passengers)
print(id(bus1.passengers), id(bus2.passengers), id(bus3.passengers))
bus1.drop('D') | true |
6fd363f6a639b159cc6594901c716fd3415a5402 | 023Sparrow/Projects | /Classic_Algorithms/Collatz_Conjecture.py | 420 | 4.28125 | 4 | #**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1.
def collatz(n):
k = 0
while n != 1:
if n%2 == 0:
n = n/2
else:
n = 3*n+1
k = k+1
return k
# test
print(collatz(5))
print(collatz(19))
print(collatz(2))
| true |
8e5103a6f4fbae5ce65bcd0fed09a9ea0ad16fbe | JohnFoolish/DocumentationDemo | /src/basic_code.py | 1,426 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
This first one is a basic function that includes the code you would need to
add two numbers together!
Why is this function useful?
----------------------------
* It can replace the '+' key!
* It can cause you to bill more hours for less work since the import takes
extra time to type!
* It can serve as a helpful demo.
Written by John Lewis Corker
"""
def basic_numpy(x, y):
"""A very basic addition numpy function.
This function contains a basic numpy docstring that we should be able to
look at and compare.
Usage below:
>>> basic(5, 8)
>>> 13
Parameters
----------
x : int
This is a basic variable that will be added to the y value.
y : int
This is a basic variable that will be added to the x value.
Returns
-------
int
The value of x and y added together
"""
z = x + y
return z
def basic_google(x, y):
"""A basic addition google function.
This function contains a basic google docstring that we should be able to
look at and compare.
Usage below:
>>> basic(5, 8)
>>> 13
Args:
x (int): a basic variable that will be added to the y value
y (int): a basic variable that will be added to the x value
Returns:
int: The value of x and y added together
"""
z = x + y
return z
if __name__ == '__main__':
basic(5, 10) | true |
bf8a718b87bd57002dfd3037c1ea6ceda4ab0261 | TommyThai-02/Python-HW | /hw04.py | 512 | 4.1875 | 4 | #Author: Tommy Thai
#Filename: hw04.py
#Assignment: hw04
#Prompt User for number of rows
rows = int(input("Enter the number of rows:"))
#input validation
while rows < 1:
#Error message
print("Number of rows must be positive.")
#Prompt again
rows = int(input("Enter the number of rows:"))
#After valid input, start loop for printing stars.
while rows > 0:
columns = rows
while columns > 0:
print("*", end = "")
columns -= 1
rows -= 1
print()
| true |
ef3b8d624346cfbc6516b8d44e8cc22001e88ce9 | damodharn/Python_Week1 | /Week1_Algo/Temp_Conversion.py | 755 | 4.25 | 4 | # *********************************************************************************************
# Purpose: Program for checking if two strings are Anagram or not.
# Author: Damodhar D. Nirgude.
# ************************************************************************************************
from Week1_Algo.Utility2 import Utility2
try:
temp = int(input("Input Temperature"))
except ValueError as e:
print(e)
else:
while 1:
print("Select Conversion:\n1: Celsius to Fahrenheit\n2: Fahrenheit to Celsius")
choice = int(input())
if choice == 1 or choice == 2:
converted = Utility2.tempconvert(choice, temp)
print("Converted temp: ", converted)
break
else:
print("Wrong I/p")
| true |
c93849ff244e494864be212fa94d97a591233291 | damodharn/Python_Week1 | /Week1_Functional/StopWatch.py | 868 | 4.28125 | 4 | # *********************************************************************************************
# Purpose: Program for measuring the time that elapses between
# the start and end clicks.
# Author: Damodhar D. Nirgude.
# ************************************************************************************************
import time
print("Enter to start Stopwatch")
input() # Take i/p from User to Start the Stop watch.
startTime = time.time()
print("Enter to Stop Stopwatch")
input() # Take i/p from User to Stop the Stop watch.
stopTime = time.time()
sec = int(stopTime - startTime) # Calculate elapsed time between start and stop in Sec.
if sec < 60: # Checking if elapsed time is less than a minute
print(sec, 'sec')
else:
mint = int(sec/60) # Calculating No. of Minutes
sec = sec % 60 # Calculating remaining Sec
print(mint, 'min', sec, 'sec')
| true |
a1808e94fd51c61a549a7131cf032eb3aa90c8f5 | jsimonton020/Python_Class | /lab9_lab10/lab9-10_q1.py | 642 | 4.125 | 4 | list1 = input("Enter integers between 1 and 100: ").split() # Get user input, and put is in a list
list2 = [] # Make an empty list
for i in list1: # Iterate over list1
if i not in list2: # If the element is not in list2
list2.append(i) # Add the element to list2 (so we don't have to count it again)
count = list1.count(i) # Count the element in list1
print(i, "occurs", count, "time" if count == 1 else "times") # Print the results
'''
Enter integers between 1 and 100: 2 5 6 5 4 3 23 43 2
2 occurs 2 times
5 occurs 2 times
6 occurs 1 time
4 occurs 1 time
3 occurs 1 time
23 occurs 1 time
43 occurs 1 time
'''
| true |
0dbdddafe5f0a2fad6b8778c78ec913561218eea | AndriyPolukhin/Python | /learn/ex02/pinetree.py | 1,500 | 4.21875 | 4 | '''
how tall is the tree : 5
#
###
#####
#######
#########
#
'''
# TIPS to breakdown the problem:
# I. Use 1 while loop and 3 for loops
# II. Analyse the tree rules:
# 4 spaces _ : # 1 hash
# 3 spaces _ : # 3 hashes
# 2 spaces _ : # 5 hashes
# 1 space _ : # 7 hashes
# 0 spaces _ : # 9 hashes
# III. Save the first and the last as 1 hash
# Need to do:
# 1. Decrement spaces by 1 each time through the loop
# 2. Increment the hashes by 2 each time through the loop
# 3. Save spaces to the stump by calculating tree height - 1
# 4. Decrement from tree height until it equals 0
# 5. Print spaces and hashses for each row
# 6. Print stump spaces and then 1 hash
# 1. Ask for the tree height:
# 2. Convert the height string into an integer:
# 3. Variables
# string = space+space+space+space+hash+space+space+space+space
tree_height = input("How tall is the tree: ")
tree_height = int(tree_height)
numberOfSpaces = (tree_height - 1)
hash = "#"
space = " "
string = ""
spaces = ""
hashes = ""
numberOfHashes = (tree_height - numberOfSpaces)
print("Starting number of space _ is {}".format(numberOfSpaces))
print("Starting number of hash # is {}".format(numberOfHashes))
while(tree_height != 0):
for s in range(numberOfSpaces):
spaces += space
print(spaces)
for h in range(numberOfHashes):
hashes += hash
print(hashes)
numberOfSpaces = numberOfSpaces - 1
numberOfHashes += 2
tree_height = tree_height - 1
| true |
a2b98b45cc022cabeb8dd82c582fd1c2f37356fb | AndriyPolukhin/Python | /learn/ex01/checkage.py | 805 | 4.5 | 4 | # We'll provide diferent output based on age
# 1- 18 -> Important
# 21,50, >65 -> Important
# All others -> Not Important
# List
# 1. Receive age and store in age
age = eval(input("Enter age: "))
# and: If Both are true it return true
# or : If either condition is true then it return true
# not : Convert a true condition into a false
# 2. If age is both greater than or equal to 1 and less than or equal to 18 Print Important
if (age >= 1 and age <= 18):
print("Important Birthday")
# 3. If age is either 21 or 50 Important
elif (age == 21 or age == 50):
print ("Important Birthday")
# 4. We check if age is less than 65 and then covnert true to false and vice versa
elif not(age < 65):
print("Not Important Birthday")
# 5. Else Not Important
else:
print("Sorry Not Important")
| true |
06a522784b6f26abb7be62f6bfd8486ffd425db0 | AndriyPolukhin/Python | /learn/ex01/gradeans.py | 437 | 4.15625 | 4 | # Ask fro the age
age = eval(input("Enter age: "))
# Handle if age < 5
if age < 5:
print("Too young for school")
# Special output just for age 5
elif age == 5:
print("Go to Kindergarden")
# Since a number is the result for age 6 - 17 we can check them all with 1 condition
elif (age > 5) and (age <= 17):
grade = age - 5
print("Go to {} grade".format(grade))
# Handle everyone else
else:
print("Go to College")
| true |
25d6aada9d0ae475343ca02fa79a5969565a4b7b | RehamDeghady/python | /task 2.py | 753 | 4.3125 | 4 | print("1.check palindrome")
print("2.check if prime")
print("3.Exit")
operation = int (input ("choose an operation:"))
if operation == 1 :
word = str(input("enter the word"))
revword = word[::-1]
print("reversed word is" ,revword)
if word == revword :
print("yes it is palindrome")
else:
print("No it is not palindrome")
elif operation == 2:
num = int(input("enter a positive number"))
if num<=0:
print(num,"is not a prime number")
else:
for i in range(2,num):
if num%i == 0 :
print(num , "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print("EXIT")
| true |
971f5ec8bb222bbfc91123e24bcccdaf3caece28 | sidsharma1990/Python-OOP | /Inheritance.py | 1,519 | 4.65625 | 5 | ######### Inheritance ######
#####Single inheritance######
###### to inherit from only 1 class####
class fruits:
def __init__(self):
print ('I am a Fruit!!')
class citrus(fruits):
def __init__(self):
super().__init__()
print ('I am citrus and a part of fruit class!')
obj1 = citrus()
##### Multiple inheritance######
###### to inherit from more than 1 class####
class A:
pass
class B:
pass
class C(A,B):
pass
issubclass (C,A) and issubclass (C,B)
'''Output --> True'''
##### Multilevel inheritance######
###### One class from another and another from another ####
####### Grandparents to parents, from parents to you ######
class A:
x = 10
class B(A):
pass
class C(B):
pass
obj1 = C()
obj1.x
'''Output --> 10'''
##### Hierarchical inheritance######
###### More than one class inherits from a Class ####
####### Your parents have 3 children ######
class A:
x = 10
class B(A):
pass
class C(A):
pass
obj1 = C()
obj1.x
issubclass (B,A) and issubclass (C,A)
'''Output --> 10'''
'''Output --> True'''
##### Hybrid inheritance######
###### Combination of any two kinds of inheritance (Hierarchical inheritance and Multiple inheritance)####
####### Class E inherits from Class B n D and both B n D inherits from class A######
class A:
x = 10
class B(A):
pass
class C(A):
pass
class D(A):
pass
class E(B,D):
pass
obj2 = E()
obj2.x
'''Output --> 10''' | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.