blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
688a13e792aa6360f053a959a75465c995a4e141
ivenpoker/Python-Projects
/online-workouts/codewars/python/who_likes_it.py
1,268
4.15625
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Recreation of facebook feature on post likes. # # # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 10, 2020 # # # ####################################################################################### def likes(persons: list) -> str: if len(persons) == 1: return f"{persons[0]} likes this" elif len(persons) == 2: return f"{' and '.join(persons)} like this" elif len(persons) == 3: return f"{', '.join(persons[0:2])} and {persons[2]} like this" else: return f"{', '.join(persons[0:2])} and {len(persons[2:])} others like this" if __name__ == "__main__": print(likes(["Peter"])) print(likes(["Jacob", "Alex"])) print(likes(["Max", "John", "Mark"])) print(likes(["Alex", "Jacob", "Mark", "Max"]))
false
304265dfa644a0a918469e1b41a0fdb3d9da1b12
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-II/program-1.py
2,107
4.3125
4
#!/usr/bin/env python3 ######################################################################################## # # # Program purpose: Takes a sequence of numbers and determines if all the numbers # # are different from each other. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 4, 2019 # # # ######################################################################################## import random def create_random_list(size=10): """ Generates of random list with size, made of random integers :param size: Size of the list to generate :return: List of integers with random data (based on size of list) """ mainList = [] for i in range(size): mainList.append(random.choice(range(size))) # append random integers based on 'size' return mainList def items_unique_1(seq=None): if seq is None: return True tmpList = [] for x in seq: if x in tmpList: return False else: tmpList.append(x) return True def items_unique_2(seq=None): if seq is None: return True return len(seq) == len(set(seq)) if __name__ == "__main__": listA = create_random_list(size=15) listB = [1, 2, 3, 4, 5] print(f"List-A: {listA}") print(f"List-B: {listB}") print(f"Does list have unique elements: {'YES' if items_unique_1(listA) else 'NO'}") print(f"Does list have unique elements: {'YES' if items_unique_1(listB) else 'NO'}") print("\n---------------------------------\n") # using a different formula print(f"List-A: {listA}") print(f"List-B: {listB}") print(f"Does list have unique elements: {'YES' if items_unique_2(listA) else 'NO'}") print(f"Does list have unique elements: {'YES' if items_unique_2(listB) else 'NO'}")
true
0c2cf06ed3569e3e25ab38c4f62ee0ab66b297a3
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Array/program-11.py
1,208
4.28125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Removes the first occurrence of a specified element from an array # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : January 20, 2019 # # # ############################################################################################ import array as arr from random import randint def random_integer_array(low: int, high: int, size: int) -> arr: if size < 0: raise ValueError(f"Invalid specified size '{size}' for new array") new_array = arr.array('i', [randint(low, high) for _ in range(size)]) return new_array if __name__ == "__main__": new_data = random_integer_array(low=0, high=10, size=8) print(f'New data: {new_data}') # removing item at index 5 ind = 5 new_data.pop(5) print(f'After removing the 5th item from array: {new_data}')
true
f51e2bb44c79f272531909ef953507a8ec42a9b2
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Tuple/program-1.py
980
4.3125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Creates a tuple. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 13, 2019 # # # ############################################################################################ import random def create_tuple() -> tuple: return random.randint(0, 10), random.randint(0, 10) if __name__ == "__main__": temp_A = () # Create an empty tuple temp_B = tuple() # Create tuple with built-in print(f'Tuple A: {temp_A}\nTuple B: {temp_B}') print(f'Random tuple: {create_tuple()}')
false
f4fda2b23527023db3eabfa8f5c91a542950e25a
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/String/program-49.py
1,440
4.5
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Count the number of vowels in a string and displays them. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : October 24, 2019 # # # ####################################################################################### vowels = 'aeiou' def get_user_string(mess: str): is_valid = False user_data = '' while is_valid is False: try: user_data = input(mess) if len(user_data) == 0: raise ValueError('Please provide a string to work with'); is_valid = True except ValueError as ve: print(f'[ERROR]: {ve}') return user_data def process_vowels(main_str: str): data_info = dict(vowel_count=0, vowels=[]) for char in main_str: if char in vowels: data_info['vowel_count'] += 1 data_info['vowels'].append(char) return data_info if __name__ == "__main__": main_data = get_user_string(mess='Enter a string: ') new_data = process_vowels(main_str=main_data) print(f'String vowel info: {new_data}')
true
f97087b4424c744da0481db1d3e116a5e759d720
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Collections/program-10.py
1,188
4.125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Removes all the elements of a given deque object. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 27, 2019 # # # ############################################################################################ from random import randint from collections import deque def create_new_deque(low: int, high: int, size: int) -> deque: if size < 0: raise ValueError(f'Invalid size ({size}) for new deque') return deque([randint(low, high) for _ in range(size)]) if __name__ == "__main__": new_deque = create_new_deque(low=0, high=20, size=10) print(f'New deque data: {new_deque}') new_deque.clear() # remove all elements from deque print(f'Deque after clearing all data: {new_deque} | length: {len(new_deque)}')
true
16e470595f1378dfbebe8eef7a3f631cfffb321f
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Array/program-14.py
1,435
4.3125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Finds if a given array of integers contains any duplicate element # # Returns true if any value appears at least twice in the said # # array and return false if every element is distinct. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : January 20, 2019 # # # ############################################################################################ import array as arr from random import randint def random_int_array(low: int, high: int, size: int) -> arr: if size < 0: raise ValueError(f"Invalid size '{size}' for new array") new_array = arr.array('i', [randint(low, high) for _ in range(size)]) return new_array def test_duplicate(main_data: arr) -> bool: temp_set = set(main_data) return len(temp_set) != len(main_data) if __name__ == "__main__": new_data = random_int_array(low=0, high=30, size=8) print(f'Main data: {new_data}') print(f'Duplicate present: {test_duplicate(main_data=new_data)}')
true
b806b3e583ace21f9afed336df004aa2fa180a4a
ivenpoker/Python-Projects
/Projects/Project 0/Strings/find-a-string.py
760
4.28125
4
#!/usr/bin/env python3 """ Program Purpose: Finds the number of occurrences of a substring in a string Program Author : Happi Yvan Author email : ivensteinpoker@gmail.com """ def count_substring(main_str, substr): cnt = 0 for ind in range(len(main_str)): if main_str[ind] == substr[0]: if main_str[ind: (ind + len(substr))] == substr: cnt += 1 return cnt def main(): user_str = input("\n\tEnter a string: ").strip() substr = input("\tEnter substring: ").strip() print("\tOccurrences of '%s' in '%s': %d\n" % (substr, user_str, count_substring(user_str, substr))) if __name__ == "__main__": print("\n\t========[ PROGRAM: Count the occurrences of substring in string ]========") main()
true
58fa3647c7ae5a5c3dcd6bdab13ec33333cb3d39
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Dictionary/program-8.py
1,479
4.125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Merges two dictionaries. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 28, 2019 # # # ############################################################################################ import random def random_dictionary(low: int, high: int, size: int) -> dict: if size < 0: raise ValueError(f'Invalid size [{size}] for dictionary') rand_keys = [random.randint(low, high) for _ in range(size)] rand_values = [random.randint(low, high) for _ in range(size)] return {k: v for (k, v) in zip(rand_keys, rand_values)} def merge_dicts(dict_A: dict, dict_B: dict) -> dict: new_dict = dict_A.copy() new_dict.update(dict_B) return new_dict if __name__ == "__main__": rand_dict_A = random_dictionary(low=0, high=10, size=6) rand_dict_B = random_dictionary(low=5, high=15, size=6) print(f'Random dictionary A: {rand_dict_A}') print(f'Random dictionary B: {rand_dict_B}') print(f'After merging dicts: {merge_dicts(dict_A=rand_dict_A, dict_B=rand_dict_B)}')
false
ff15ad9f31ec1c7e8569eb3b99ef7f6d9848d94e
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-26.py
873
4.28125
4
# !/usr/bin/env python3 ############################################################################# # # # Program purpose: Displays a histogram from list data # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : July 14, 2019 # # # ############################################################################# # URL: https://www.w3resource.com/python-exercises/python-basic-exercises.php def histogram(someList, char): for x in someList: while x > 0: print(f"{char}", end='') x = x-1 print(f"\n") if __name__ == "__main__": randList = [3, 7, 4, 2, 6] histogram(randList, '*')
false
63c7368f355c5d756bbab974a750d3b0d5a0097f
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Condition Statements and Loops/program-32.py
1,428
4.3125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Determines if a letter is a vowel or a constant. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : January 28, 2019 # # # ############################################################################################ main_vowels = 'aeiou' def obtain_user_char(input_mess: str) -> str: user_char, valid = '', False while not valid: try: user_char = input(input_mess).strip() if len(user_char) != 1: raise ValueError(f"Invalid input. Must be a single character") valid = True except ValueError as ve: print(f'[ERROR]: {ve}') return user_char def is_vowel(some_char: str) -> bool: return some_char.lower().isalpha() and some_char.lower() in main_vowels if __name__ == "__main__": main_char = obtain_user_char(input_mess='Enter a letter of the alphabet: ') if is_vowel(some_char=main_char): print(f"{main_char} is a vowel") else: print(f"{main_char} is a constant")
true
e228c757e008dec126ed42ba6af77ba45325b71e
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Tuple/program-9.py
1,316
4.125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Finds duplicate tuples in a list of tuples. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 19, 2019 # # # ############################################################################################ import random def rand_tuples(low: int = 0, high: int = 10, size: int = 10): if size < 0: raise ValueError("Invalid size for new list. Must be > 0") return [(random.randint(low, high), random.randint(low, high)) for _ in range(size)] def find_repeated(tuple_list: list) -> list: dups = [] for (a, b) in tuple_list: if tuple_list.count((a, b)) >= 2 and (a, b) not in dups: dups.append((a, b)) return dups if __name__ == "__main__": new_tuples = rand_tuples(low=0, high=5, size=10) print(f'Random tuples: {new_tuples}') print(f'Repeated tuples: {find_repeated(tuple_list=new_tuples)}')
true
7ff194e935cbb0ed55e5654c7aff2e27779e4ce4
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Sets/program-14.py
1,104
4.375
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Finds the maximum and minimum value in a set. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 27, 2019 # # # ############################################################################################ from random import randint def random_set(low: int, high: int, size: int) -> set: if size < 0: raise ValueError(f'Invalid size ({size}) for new set') return set([randint(low, high) for _ in range(size)]) if __name__ == "__main__": new_set_data = random_set(low=0, high=10, size=15) print(f'New set data: {new_set_data}') print(f'Max data in set: {max(new_set_data)}') print(f'Min data in set: {min(new_set_data)}')
true
d2204090dfd3fc3f2f4263d0bb9c2b36426920e2
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Condition Statements and Loops/program-24.py
1,140
4.25
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Prints letter 'L' to the console. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : January 27, 2019 # # # ############################################################################################ def print_letter_P(): result_str = "" for row in range(0, 7): for column in range(0, 7): if (column == 1 or ((row == 0 or row == 3) and 0 < column < 5) or ( (column == 5 or column == 1) and (row == 1 or row == 2))): result_str = result_str + "*" else: result_str = result_str + " " result_str = result_str + "\n" print(result_str) if __name__ == '__main__': print_letter_P()
true
fdec6e46563750cf7f6ce5080accea488ee5c058
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/prorgam-148.py
931
4.3125
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Check if an variable is of integer type or string type. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 3, 2019 # # # ####################################################################################### if __name__ == '__main__': firstInt = int(input("Enter first integer: ")) secondInt = int(input("Enter second integer: ")) if firstInt % secondInt == 0: print(f"Integer {firstInt} IS divisible by {secondInt}") else: print(f"Integer {firstInt} IS NOT divisible by {secondInt}")
false
68a74d8b7620918b541d0bd7c085056805b9ffc5
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-145.py
1,912
4.21875
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Test if a variable is a list or tuple or set. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 3, 2019 # # # ####################################################################################### def find_type(someVar=None): if someVar is None: raise TypeError("Invalid argument") typeInfo = str(type(someVar)) if typeInfo.find("str") >= 0: return "str" elif typeInfo.find("int") >= 0: return "int" elif typeInfo.find("tuple") >= 0: return "tuple" elif typeInfo.find("list") >= 0: return "list" elif typeInfo.find("set") >= 0: return "set" else: return "[unknown]" if __name__ == '__main__': varA = {1, 2, 3, 4, 5} # set varB = [1, 2, 3, 4, 5] # list varC = (1, 2, 3, 4, 5) # tuple print(f"Type for varA: {find_type(varA)}") print(f"Type for varB: {find_type(varB)}") print(f"Type for varC: {find_type(varC)}") print("-------------------------") # OR we could just do this if isinstance(varA, set): print(f"Type for varA is set") if isinstance(varB, list): print(f"Type for varB is list") if isinstance(varC, tuple): print(f"Type for varC is tuple") print("--------------------------") # OR we could just do this again as such... if type(varA) is set: print("varA is a set") if type(varB) is list: print("varB is a list") if type(varC) is tuple: print("varC is a tuple")
true
94a0a3e129036cb5cece670cdcc8b3669f28e94f
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Dictionary/program-11.py
1,368
4.34375
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Multiply all values in a dictionary. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 28, 2019 # # # ############################################################################################ import random def random_dictionary(low: int, high: int, size: int) -> dict: if size < 0: raise ValueError(f'Invalid size [{size}] for dictionary') key_list = [random.randint(low, high) for _ in range(size)] value_list = [random.randint(low, high) for _ in range(size)] return {k: v for (k, v) in zip(key_list, value_list)} def multi_all_values(some_dict: dict) -> int: temp = 1 for key in some_dict.keys(): temp *= some_dict[key] return temp if __name__ == "__main__": new_dict = random_dictionary(low=0, high=20, size=10) print(f' Generated dictionary data: {new_dict}') print(f'After multiplying all items: {multi_all_values(some_dict=new_dict)}')
false
5d29193af663c95bc73bc1c23159e68e18dae2b4
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-II/program-50.py
1,680
4.28125
4
#!/usr/bin/env python3 ################################################################################## # # # Program purpose: Finds a replace the string "Python" with "Java" and the # # string "Java" with "Python". # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 22, 2019 # # # ################################################################################## def read_string(mess: str): valid = False user_str = "" while not valid: try: user_str = input(mess).strip() valid = True except ValueError as ve: print(f"[ERROR]: {ve}") return user_str def swap_substr(main_str: str, sub_a: str, sub_b: str): if main_str.index(sub_a) >= 0 and main_str.index(sub_b) >= 0: i = 0 while i < len(main_str): temp_str = main_str[i:i + len(sub_a)] if temp_str == sub_a: main_str = main_str[0:i] + sub_b + main_str[i+len(sub_a):] else: temp_str = main_str[i:i + len(sub_b)] if temp_str == sub_b: main_str = main_str[0:i] + sub_a + main_str[i+len(sub_b):] i += 1 return main_str if __name__ == "__main__": data = read_string(mess="Enter some string with 'Python' and 'Java': ") print(f"Processed string is: {swap_substr(main_str=data, sub_a='Python', sub_b='Java')}")
true
929dcc288a2c67fcb986f620ec6922e53ac15ff3
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/List/program-37.py
1,181
4.28125
4
#!/usr/bin/env python 3 ############################################################################################ # # # Program purpose: Finds common item in two lists. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 18, 2019 # # # ############################################################################################ import random def random_int_list(low: int, high: int, size: int) -> list: return [random.randint(low, high) for _ in range(size)] def find_common_list_item(listA: list, listB: list) -> list: return list(set(listA) & set(listB)) if __name__ == "__main__": list_A = random_int_list(low=6, high=20, size=15) list_B = random_int_list(low=2, high=16, size=10) print(f'List A: {list_A}') print(f'List B: {list_B}') print(f'Common list items: {find_common_list_item(listA=list_A, listB=list_B)}')
true
845bc9a2e104a57de51950cfc7d31672aaa72c56
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/List/program-27.py
1,335
4.4375
4
#!/usr/bin/env python 3 ############################################################################################ # # # Program purpose: Finds and prints the second smallest element in list. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 12, 2019 # # # ############################################################################################ import random def random_int_list(low: int, high: int, size: int) -> list: return [random.randint(low, high) for _ in range(size)] def obtain_2nd_smallest(main_data: list) -> int: if len(main_data) < 2: return main_data[0] # sort the list in ascending order, use `set` to remove duplicates, use `list` to obtain a list # since `sets` don't support indexing, finally return the 2nd element. return list(set(sorted(main_data)))[1] if __name__ == "__main__": list_data = random_int_list(low=0, high=15, size=15) print(f'Generated list: {list_data}') print(f'Second smallest element in list: {obtain_2nd_smallest(main_data=list_data)}')
true
43a682a376e9f51cd58e1971b5fbdf82fb55b175
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-27.py
974
4.15625
4
# !/usr/bin/env python3 ############################################################################# # # # Program purpose: Concatenates content of list as string and return # # the results. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : July 17, 2019 # # # ############################################################################# # URL: https://www.w3resource.com/python-exercises/python-basic-exercises.php def concat_list(some_list): val = '' for x in some_list: val += str(x) return val if __name__ == "__main__": aList = [123, 'val', 'demo', 'test', 123.23] print(f"Main list: {aList}\nConcatenated list as string: {concat_list(aList)}")
true
66b44eba55e6ff56521ad073e4e008d1df35d217
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-60.py
933
4.46875
4
# !/usr/bin/env python3 ################################################################################### # # # Program purpose: Calculates the hypotenuse of a right angled triangle. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : August 10, 2019 # # # ################################################################################### def compute_hypotenuse(sideA, sideB): import math return math.sqrt(math.pow(int(sideA), 2) + math.pow(int(sideB), 2)) if __name__ == "__main__": sideA = int(input("Enter value for side A: ")) sideB = int(input("Enter value for side B: ")) print(f"Hypotenuse is: {int(compute_hypotenuse(sideA=sideA, sideB=sideB))}")
false
eeabe248a29797ff5ca5903db5337caae51a91cb
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Dictionary/program-17.py
1,703
4.125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Remove duplicates from a dictionary. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 10, 2019 # # # ############################################################################################ import random def random_dict(low: int, high: int, key_size: int) -> dict: if key_size < 0: raise ValueError(f'Invalid key size for new dict. Must be > 0') rand_keys = [random.randint(low, high) for _ in range(key_size)] rand_values = [random.randint(low, high) for _ in range(key_size)] return {k: v for (k, v) in zip(rand_keys, rand_values)} def remove_dict_duplicate(main_dict: dict) -> dict: unique_values = set(list(main_dict.values())) unique_dict = dict() for value in unique_values: for (k, v) in zip(main_dict.keys(), main_dict.values()): if v == value: unique_dict[k] = value break return unique_dict if __name__ == "__main__": new_dict = random_dict(low=0, high=2, key_size=10) print(f'Generated dict -> {new_dict} | {new_dict.values()} | size -> {len(new_dict)}') filtered_dict = remove_dict_duplicate(main_dict=new_dict) print(f' Filtered dict -> {filtered_dict} | {filtered_dict.values()} | size -> {len(new_dict)}')
true
fd8e9bdf57eafb8c2ad17cf9040cdea4007a8b58
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/List/program-24.py
1,154
4.625
5
#!/usr/bin/env python 3 ############################################################################################ # # # Program purpose: Appends two list. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 12, 2019 # # # ############################################################################################ import random def create_int_list(low: int, high: int, size: int) -> list: return [random.randint(low, high) for _ in range(size)] def append_lists(list_A: list, list_B: list) -> list: return list_A + list_B if __name__ == "__main__": list_1 = create_int_list(low=1, high=10, size=5) list_2 = create_int_list(low=2, high=15, size=6) print(f'List A: {list_1}') print(f'List B: {list_2}') print(f'After appending list: {append_lists(list_A=list_1, list_B=list_2)}')
true
a4e9f6772c5901a9f53761f1cece05d4ac4429a5
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-II/program-15.py
1,067
4.125
4
#!/usr/bin/env python3 ######################################################################## # # # Program purpose: Program to check the priority of the four # # operators (+, -, *, /) # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 6, 2019 # # # ######################################################################## __operators__ = "+-/*" __parenthesis__ = "()" __priority__ = { '+': 0, '-': 0, '*': 1, '/': 1 } def test_higher_priority(operatorA, operatorB): return __priority__[operatorA] >= __priority__[operatorB] if __name__ == "__main__": print(test_higher_priority('*', '-')) print(test_higher_priority('+', '-')) print(test_higher_priority('+', '*')) print(test_higher_priority('+', '/')) print(test_higher_priority('*', '/'))
false
8e6dc3e040681cc0397a0dc2ccbf2fd7d06dc580
MihaelaGaman/InterviewProblemsSolved
/algorithms_python/sortedArraysMedian.py
2,490
4.125
4
""" Median of two sorted arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ if len(nums1) < len(nums2): n = len(nums1) m = len(nums2) a = nums1 b = nums2 else: n = len(nums2) m = len(nums1) a = nums2 b = nums1 median = 0 i = 0 j = 0 min_index = 0 max_index = n while (min_index <= max_index) : i = int((min_index + max_index) / 2) j = int(((n + m + 1) / 2) - i) # i == n => no elements from a in the second half # j == 0 => no elements from b in the first half # Searching on right if (i < n and j > 0 and b[j - 1] > a[i]) : min_index = i + 1 # i = 0 => no elements from a in the first half # j = m => no elements from b in the second half # Searching on left elif (i > 0 and j < m and b[j] < a[i - 1]) : max_index = i - 1 # here we have the halves searched for else : # no elements from nums1 in the first half # => return the last element in b if (i == 0) : median = b[j - 1] # no elements in the first half from b # => return the last element in a elif (j == 0) : median = a[i - 1] else : median = max(a[i - 1], b[j - 1]) break # Compute the median. # odd no of elems => one middle element if ((n + m) % 2 == 1) : return median # no elems from a in the second half if (i == n) : return ((median + b[j]) / 2.0) # no elems from b in the second half if (j == m) : return ((median + a[i]) / 2.0) return ((median + min(a[i], b[j])) / 2.0) # Test 1 nums1 = [1, 3] nums2 = [2] print "Test1: ", findMedianSortedArrays(nums1, nums2) # Test 2 nums1 = [1, 2] nums2 = [3, 4] print "Test2: ", findMedianSortedArrays(nums1, nums2)
true
d720d43bfd485ac2e79a694357a105f2f1234feb
tonyhauuk/Non-project
/app/base_sort/merge_sort.py
917
4.125
4
# from arrays import Array def mergeSort(array): temp = list(len(array)) merge_sort(array, temp, 0, len(array) - 1) def merge_sort(array, temp, left, right): if left < right: middle = (left + right) // 2 merge_sort(array, temp, left, middle) merge_sort(array, temp, middle + 1, right) merge(array, temp, left, middle, right) def merge(array, temp, left, middle, right): start = left center = middle + 1 for i in range(left, right + 1): if start > middle: temp[start] = array[center] center += 1 elif center > right: temp[i] = array[start] start += 1 elif array[start] < array[center]: temp[i] = array[start] start += 1 else: temp[i] = array[center] center += 1 for i in range(left, right + 1): array[i] = temp[i]
true
9c5e06bc86a28ec1612dff3d407c9d97de79b0c5
Dheerajdoppalapudi/Data-Structures
/simplecircularlinkedlist.py
2,215
4.21875
4
class Node: def __init__(self, data, next = None): self.data = data self.next = next class CircularLinkedList: def __init__(self): self.head = None def insertion(self, data): # adds a new node at the starting of the list newNode = Node(data) if self.head is None: self.head = newNode newNode.next = self.head else: temp = self.head while temp: if temp.next == self.head: newNode.next = self.head temp.next = newNode return temp = temp.next def deletion(self): # deletes a node at starting of the list if self.head is None: print("List is empty, nothing to delete") elif self.head is self.head.next: # when there is only one node left in the linked list self.head = None else: temp = self.head while temp: if temp.next == self.head: self.head = self.head.next temp.next = self.head return temp = temp.next def isEmpty(self): if self.head is None: print("List is Empty") else: print("List is not Empty") def showList(self): if self.head is None: print("List is Empty") else: temp = self.head while temp: print(temp.data, end=' ') if temp.next == self.head: break temp = temp.next object = CircularLinkedList() while True: print("----------------------------------") print('1 -> Insertion ') print('2 -> Traversal ') print('3 -> IsEmpty ') print('4 -> Deletion ') print('Press Any Key to Exit the Program') option = int(input('Enter the option ')) if option == 1: data = int(input('Enter the data ')) object.insertion(data) elif option == 2: object.showList() elif option == 3: object.isEmpty() elif option == 4: object.deletion() else: print('Program Terminated ') break
true
f19beb1539f76c8716f39728ac4d15d09ddcc227
rajasoun/coach-lab
/data_structures/list_set/list.py
1,093
4.125
4
#!/usr/bin/env python3 # function to get details about a python data structure def tell_about(data_structure): print("ID: ", id(data_structure)) print("Type: ", type(data_structure)) print("Length: ", len(data_structure)) print("Contents: ", data_structure) def get_input_numbers_as_list(): input_prompt="Enter Numbers [use space for seperation] : \n" # map() function returns a map object after applying the given function to each item of a given iterable (list, tuple etc.) # input() function to take input from the user # rsplit() method returns a list of strings after breaking the given string from right side by the specified separator - default is space # split() method splits a string into a list num_list=list(map(int,input(input_prompt).rstrip().split())) return num_list def largest_number_in_list(number_list : list): return(max(number_list)) ## List Data Stucture Basics # empty list fruits = [] tell_about(fruits) # Get List of Numbers number_list = get_input_numbers_as_list() # Print Largest Number print(largest_number_in_list(number_list))
true
9796895199fda25d769fc1212128497ba1800233
meenu-siva/IBMLabs
/sample2.py
281
4.34375
4
num1 = float(input("enter the number:")) num2 = float(input("enter the number:")) num3 = float(input("enter the number:")) if num1 >= num2 and num1 >= num3: largest = num1 elif num2 >= num1 and num2 >= num3: largest = num2 else: largest = num3 print(largest)
false
d3284b99e5b750e2cd3b2a19af741fb2e6e137f0
Lorenhub/Python
/Ordering.py
501
4.1875
4
print('''ORDERING 1.MAX 2.MIN 3.ASCENDING 4.DESCENDING''') type = input("Enter operation: ").lower() numbers = input("Enter numbers: ") number = numbers.split(",") if type == "max": print("Result: ", max(number)) elif type == "min": print("Result: ", min(number)) elif type == "ascending": number.sort() print("Result: ", ", ".join(number)) elif type == "descending": number.sort() number.reverse() print("Result: ", ", ".join(number)) else: print("Invalid option.")
false
e3f3a9d022301167edef6d49f2eded105adc3555
Fibiola/Sand
/PythonFun/PiglatinToEnglish.py
588
4.28125
4
original = raw_input("Give me a pig latin word to translate to English ") #Pig defined word for words starting with vowel #Pyg defined word for words starting with not_vowel. pig = "way" pyg = "ay" word = original.lower() removedAY = word[:-2] removedWAY = word[:-3] first = word[1] new_word = removedAY[-1] + removedAY[:-1] if len(word) > 0 and original.isalpha(): if first == "a" or first =="e" or first == "i" or first == "o" or first == "u" print new_word else print new_word else print "not a word" # we dont know if it was a word that previously contained a wovel or not.
true
7eb67296cbb4fa2437f8d1a3ad609c4eb195caa9
ankan-mazumdar/python_repo
/python_numpy_distribution.py
1,072
4.28125
4
''' Normal Distribution The Normal Distribution is one of the most important distributions. It is also called the Gaussian Distribution after the German mathematician Carl Friedrich Gauss. It fits the probability distribution of many events, eg. IQ Scores, Heartbeat etc. Use the random.normal() method to get a Normal Data Distribution. It has three parameters: loc - (Mean) where the peak of the bell exists. scale - (Standard Deviation) how flat the graph distribution should be. size - The shape of the returned array. Example Generate a random normal distribution of size 2x3: ''' from numpy import random x = random.normal(size=(2, 3)) print(x) x = random.normal(loc=1, scale=2, size=(2, 3)) #Generate a random normal distribution of size 2x3 with mean at 1 and standard deviation of 2: print(x) #Visualization of Normal Distribution- The curve of a Normal Distribution is also known as the Bell Curve because of the bell-shaped curve. from numpy import random import matplotlib.pyplot as plt import seaborn as sns sns.distplot(random.normal(size=1000), hist=False) plt.show()
true
77926f74cec39c677273be3d05fc696ac184308e
danilusikov0913/lr2
/individual.py
284
4.15625
4
print('Найдите гипотенузу прямоугольного треугольника, если известны его катеты') a = float(input('Катет a=')) b = float(input('Катет b=')) S = ((a**2) + (b**2))**(1/2) print('Гипотенуза - %.2f' % S)
false
540c4817e0482a8f5aaab31270187ede3fd98984
nileshpythonista/Python_Interview_Practise
/Dictionary.py
2,983
4.1875
4
Dictionary: Hashtable based Collection of heteroginious items in (pair of Key & value) enclosed in curly brackets {} Duplicates not allowed () --> in context of only Keys Dictionaries are used to store data values in key:value pairs. Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name. thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964} Accessing Items: x = thisdict["model"] x = thisdict.get("model") x = thisdict.keys() x = thisdict.fromkeys() x = thisdict.values() x = thisdict.items() Add / Update Items: thisdict["year"] = 2018 thisdict.update({"year": 2020}) Remove Items: thisdict.pop("model") thisdict.popitem() --> Removes the Last items del thisdict["model"] del thisdict --> Complete Dictionary thisdict.clear() Dictionary Methods: get() Returns the value of the specified key keys() Returns a list containing the dictionary's keys fromkeys() Returns a dictionary with the specified keys and value values() Returns a list of all the values in the dictionary items() Returns a list containing a tuple for each key value pair update() Updates the dictionary with the specified key-value pairs setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary Loops in Dictionary: To obtain the Keys from Dictionary Way-1: for x in thisdict: print(x) Way-2: for x in thisdict.keys(): print(x) To obtain the Values from Dictionary Way-1: for x in thisdict: print(thisdict[x]) Way-2: for x in thisdict.values(): print(x) To obtain the Items from Dictionary Way-1: for x, y in thisdict.items(): print(x, y) Dictionary Comprehensions: names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] print zip(names, heros) Problem Statement: I want a dict{'name': 'hero'} for each name,hero in zip(names, heros) Genral Way: my_dict = {} for name, hero in zip(names, heros): my_dict[name] = hero print my_dict Dict Comprehension: my_dict = {name for name, hero in zip(names, heros)} --> To merge both list my_dict = {name for name, hero in zip(names, heros) if name != 'peter'}
true
20318a5cf046d693a302cca422cc570d25aed7d3
GSSSVenkatReddy/MyBelfricsData
/python/basics/dictionary.py
290
4.25
4
classmates={"akhil":"brainstorm","surya":"big mf","hari":"masters in MS"} print(classmates) # Dictionary composed of : key & value pairs print(classmates["akhil"]) print(classmates["surya"]) print(classmates["hari"]) for k,v in classmates.items(): print(k+":"+v)
false
25f9f23956d9250758adeadfb4f5143f457f59e1
VisalYun/Python_for_beginner
/Week1/Exercise/05_min.py
278
4.15625
4
num1 = int(input("Enter a number: ")) num2 = int(input("Enter a second number: ")) if num1<num2: print("Result : "+str(num1)+" < "+str(num2)) elif num1>num2: print("Result : "+str(num2)+" < "+str(num1)) elif num1==num2: print("Result : "+str(num1)+" == "+str(num2))
false
86d9ba94f237310104368f7447abda8b290d793f
KaranPupneja1317/typography-turtle
/typography-advanced.py
1,277
4.71875
5
#Python programming to draw pentagon in turtle programming import turtle t = turtle.Turtle() for i in range(5): t.forward(100) #Assuming the side of a pentagon is 100 units t.right(72) #Turning the turtle by 72 degree #Python programming to draw hexagon in turtle programming import turtle   t = turtle.Turtle() for i in range(6):    t.forward(100) #Assuming the side of a hexagon is 100 units    t.right(60) #Turning the turtle by 60 degree #Python programming to draw heptagon in turtle programming import turtle t = turtle.Turtle() for i in range(7): t.forward(100) #Assuming the side of a heptagon is 100 units t.right(51.42) #Turning the turtle by 51.42 degree #Python programming to draw octagon in turtle programming import turtle t = turtle.Turtle() for i in range(8): t.forward(100) #Assuming the side of a octagon is 100 units t.right(45) #Turning the turtle by 45 degree #Python programming to draw polygon in turtle programming import turtle t = turtle.Turtle() numberOfSides = int(input('Enter the number of sides of a polygon: ')) lengthOfSide = int(input('Enter the length of a side of a polygon: ')) exteriorAngle = 360/numberOfSides for i in range(numberOfSides): t.forward(lengthOfSide) t.right(exteriorAngle)
false
198611fcad72e56c2609d0ae590bd7b71c2c5eb6
ngsw12/uncategorized
/PrimeNumberChecker.py
725
4.1875
4
# inputされた数字が素数かどうか調べる import math def isPrime(x): #整数xが素数かどうかを判定する if x < 2: return False #2未満に素数はないため if x == 2 or x == 3 or x == 5 :return True #2,3,5は素数 if x % 2 == 0 or x % 3 == 0 or x % 5 == 0 : return False # 2,3,5 の倍数は合成数 # 試し割り : 疑似素数(2,3,5 でも割り切れない数字)で割っていく prime = 7 step = 4 while prime <= math.sqrt(x): if x % prime == 0: return False prime += step step = 6 - step return True inputNumber = input('値を入力 : ') if isPrime(int(inputNumber)): print( inputNumber + 'は素数です') else: print(inputNumber + "は素数ではありません")
false
c4acdaed0ee628489784fcc241d2233e51be34b6
infx511-s18/lecture_demos
/script.py
1,042
4.375
4
# A module for drawing a chart with the turtle import turtle # import module # Define window size as constants window = turtle.Screen() # create a window for the turtle to draw on window.title("Turtle Demo") # the title to show at the top of the window WINDOW_WIDTH = 400 # size constants for easy changing WINDOW_HEIGHT = 300 window.setup(WINDOW_WIDTH, WINDOW_HEIGHT) # set window size (width, height) window.setworldcoordinates(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) # coord system # # Create the turtle my_turtle = turtle.Turtle() my_turtle.speed("fast") # how fast the turtle should move my_turtle.penup() my_turtle.goto(100, 100) my_turtle.pendown() # start drawing again my_turtle.forward(100) # # Move the turtle to draw my_turtle.left(60) # turn left my_turtle.forward(120) # move forward my_turtle.right(120) # turn left my_turtle.forward(120) # move forward # Make turtle graphics appear and run; wait for the user to close the screen # This MUST be the last statement executed in the script window.mainloop()
true
28c06fddcebbe1a405e70caeb41862645065b472
yemarn510/YM_Python
/Access_Log/AccessLogOutput.py
1,060
4.28125
4
import re import AccessLog def show_errormsg(): """ This function is for printing the error message for files that does not exist """ print("\nTarget file does not exist, please put correct path for the file") print() def show_all_line(file_name, search_word): """ This function is for printing every line in the files args : file_name : file_name : search_word : '' """ files = open(file_name, 'r') for lines in files: print(lines) files.close() def does_not_exist_file(): """ This function is for printing if the user doesn't input the first command line argument """ print("\nPlease input the file name\n") def output_array(array_to_print): """ This function is for printing the array which includes the word that the user wants to search arg : arry_to_input : the array with lines that include the search words """ for lines in array_to_print: print(lines)
true
55db362131978d3ed2e6057c3c11b8084159acae
NYRChang/my-first-python-app
/app/functions.py
1,132
4.125
4
# custom-functions/my_functions.py # TODO: define temperature conversion function here # TODO: define gradebook function here #1.8C + 32 = Fahrenheit def celsius_to_fahrenheit(celsius_temp): f_temp = (c*1.8 + 32) return f_temp #Grade Scale def numeric_to_letter_grade(score): if (score > 90): return ("A") elif (score > 80): return ("B") else: return ("C") if __name__ == "__main__": print("--------------------") print("CUSTOM FUNCTIONS EXERCISE...") c = 0 print("--------------------") print("THE CELSIUS TEMP IS:", c, "DEGREES") f = celsius_to_fahrenheit(c) print("THE FAHRENHEIT EQUIVALENT IS:", f, "DEGREES") score = input("Please input a numeric letter grade (from 0 to 100): ") #score = float.input("Please input a numeric number") score = float(score) # todo: ensure the provided input value is valid before passing it into the function below print("--------------------") print("THE NUMERIC SCORE IS:", score) grade = numeric_to_letter_grade(score) print("THE LETTER-GRADE EQUIVALENT IS:", grade)
true
f4688cb6a3f8b03fec04a8ec0266586275e2f114
hstiwana/my_python_learning
/games/rock_paper_scissors.py
2,567
4.25
4
#!/usr/bin/env python # This script is to emulate classic game of "rock" "paper" "scissors" # we are going to use functions from 2 classes "sys" and "random" import sys, random # Some variables to keep the count wins = 0 ties = 0 losses = 0 # main gain loop while True: print(f'Stats: Wins({wins}) Losses({losses}) ties({ties})') while True: #User input loop, keep looping unless user selects a valid option playerMove=input('Please select an option: (r)ock, (p)aper, (s)scissor, (q)uit : ') # Print final score if user decided to quit using option q if playerMove == 'q': print() print('All right, exiting game ....') print() print() print(f'Your Final Game Scores: Wins({wins}) Losses({losses}) ties({ties})') print() sys.exit() elif playerMove == 'r': print('Rock versus... ',end=' ') break elif playerMove == 'p': print('Paper versus... ',end=' ') break elif playerMove == 's': print('Scissor versus... ',end=' ') break print('Try again, Valid options are: r, p, s or q') # Lets get a random number from a function "randint" randomNumber = random.randint(1,3) # Assign computerMoves to match with a randomly generated number if randomNumber == 1: computerMove = 'r' print('Rock') elif randomNumber == 2: computerMove = 'p' print('Paper') elif randomNumber == 3: computerMove = 's' print('Scissor') # Compare playerMove and ComputerMoves to get results if playerMove == computerMove: print('It is a Tie!') ties += 1 # Increment count elif playerMove == 'r' and computerMove == 's': print('Rock breaks Scissor, You Win!') wins += 1 # Increment count elif playerMove == 'p' and computerMove == 'r': print('Paper covers Rock, You Win!') wins += 1 # Increment count elif playerMove == 's' and computerMove == 'p': print('Scissor cut Paper, You Win!') wins += 1 # Increment count elif playerMove == 'r' and computerMove == 'p': print('Paper covers Rock, You Loss!') losses += 1 # Increment count elif playerMove == 'p' and computerMove == 's': print('Scissor cut Paper, You Loss!') losses += 1 # Increment count elif playerMove == 's' and computerMove == 'r': print('Rock breaks Scissor, You Loss!') losses += 1 # Increment count
true
45781811e469cbfb7c9f540e4059929c39bf0ffa
arnaldosantosjr/projetos_de_pyton
/operadoresAritimeticos.py
753
4.25
4
# Esse programa consisste em fazer operações aritméticas entre números. # Usaremos o + para adição; # Usaremos o - para subtração; # Usaremos o * para multiplicação; # Usaremos o / para divisão; # Usaremos ** para potência; # Usaremos // para divisão inteira; # Usaremos % para resto da divisão ( Ou módulo). n1= int(input('Digite um valor:\n')) n2= int(input('Digite outro valor:\n')) sm= n1 +n2 sub = n1 - n2 pr = n1 * n2 div = n1 /n2 print('A soma entre esses valores é {}, a subtração é {}, o produto é {}, e a divisão é {:.3f}.'.format(sm, sub, pr, div)) pot = n1 ** n2 dvi = n1//n2 rd = n1 % n2 print('A potência de {} elevado a {} é {}, a divisão inteira é {}, e o resto ou módulo é {}.'.format(n1, n2, pot, dvi, rd))
false
7053eace460aff855e63ffab6a6e8e82ca18c1b5
karzuan/python-mastertickets
/masterticket.py
1,476
4.25
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 def calculate_price(number_of_tickets): result = number_of_tickets * TICKET_PRICE + SERVICE_CHARGE return result user = input("What's your name? ") while(tickets_remaining>0): print("Hey {}! There are {} tickets remaining ".format(user, tickets_remaining)) try: number_of_tickets = int(input("How many tickets would you like to buy, {}? ".format(user))) # if there are less tickets then they want if ( tickets_remaining - number_of_tickets < 0): raise ValueError("Sorry, we don't have that much tickets. There are only {} remaining. Try to buy less...".format(tickets_remaining)) except ValueError as err: print("Please, try again...") print("({})".format(err)) else: total_cost = calculate_price(number_of_tickets) print("The total cost of your ofder gonna be ${}! (Service Charge ${} is included) ".format(total_cost, SERVICE_CHARGE)) decision = input("Would you like to confirm the order?( y/n ) ") if decision == "y": print("SOLD! Thank you for the purchase {}!".format(user)) tickets_remaining = tickets_remaining - number_of_tickets print("The remaining amount of tickets is {}.".format(tickets_remaining)) else: print("The remaining amount of tickets is {}.".format(tickets_remaining)) else: print("We are sold out!")
true
9deb97944291e90afbcbab0a75e305ad05e5ffbf
hsssgddtc/Basis_Training
/Numbers/Combination.py
659
4.125
4
#This is the solution under Numbers category for project https://github.com/hsssgddtc/Basis-Training """ We have numbers 1,2,3,4. How many different three-digit numbers can they combined without duplicate digits? Print them all.""" Numbers = [1,2,3,4] Combination = [] Sum = 0 for i in range(1,Numbers.__len__()+1): for j in range(1,Numbers.__len__()+1): for k in range(1,Numbers.__len__()+1): if(i!=j and j!=k and k!=i): Combination.append("{}{}{}".format(i,j,k)) Sum += 1 print "There are {} combinations as following:{}".format(Sum,Combination) #print "{}{}{}".format(a,b,c)
true
5a675709838796dd7e27f7e3a4bfb55ef46b3ee9
kotykd/python_sample
/sample.py
1,363
4.21875
4
# This is a comment # Something that has quotes is a string which is text # Something like this 12 is an int or integer # Below is a variable repeat = "R" # Below is a loop, so while repeat equals "R" it will do everything below it while repeat == "R": # Below is the print function, which prints whatever you put in the parentheses print("Ask your mathematical question.") print("Possible options are: +, -, x") # Below is the input function and whatever you type in after you see the prompt will be saved in the variable a a = input("Enter the operator you want to use: ") # This is an if statement or a "conditional" so if what you type into the above prompt is "+" then it will do everything below it if a == "+": a1 = input("Enter the first number you want to add: ", ) # Below is the int() command which will turn "12" into 12 i1 = int(a1) a2 = input("Enter the second number you want to add: ", ) i2 = int(a2) print(i1 + i2) if a == "x": a1 = input("Enter the first number you want to multiply: ", ) i1 = int(a1) a2 = input("Enter the second number you want to multiply: ", ) i2 = int(a2) print(i1 * i2) if a == "-": a1 = input("What number would you like to start with? ", ) i1 = int(a1) a2 = input(f"Enter the number you would like to subtract from {i1}? ") i2 = int(a2) print(i1 - i2) # Hope this helped!
true
2b9068da589280676567aadbd9b7809e2af60fac
aarun115/Solutions-of-Euler-in-Python
/problem_9.py
601
4.25
4
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. # ----------------------------------------------------- def check_pathagorean_triplets(): for c in range(5, 1000): for b in range(1, c): a = 1000 - (c + b) # given a +b + c = 1000 if a*a + b*b == c*c: return a * b * c def main(): print(check_pathagorean_triplets()) if __name__ == '__main__': main()
false
3398ac0acaee48e7b39312b4134c3572edd9235e
lachilles/skills-assessment
/skills-dictionaries/advanced.py
1,558
4.34375
4
"""Advanced skills-dictionaries. **IMPORTANT:** these problems are meant to be solved using dictionaries and sets. """ def top_chars(phrase): """Find most common character(s) in string. Given an input string, return a list of character(s) which appear(s) the most the input string. If there is a tie, the order of the characters in the returned list should be alphabetical. For example:: >>> top_chars("The rain in spain stays mainly in the plain.") ['i', 'n'] If there is not a tie, simply return a list with one item. For example:: >>> top_chars("Shake it off, shake it off.") ['f'] Do not count spaces, but count all other characters. """ return [] def word_length_sorted(words): """Return list of word-lengths and words. Given a list of words, return a list of tuples, ordered by word-length. Each tuple should have two items --- a number that is a word-length, and the list of words of that word length. In addition to ordering the list by word length, order each sub-list of words alphabetically. For example:: >>> word_length_sorted(["ok", "an", "apple", "a", "day"]) [(1, ['a']), (2, ['an', 'ok']), (3, ['day']), (5, ['apple'])] """ return [] ##################################################################### # You can ignore everything below this. if __name__ == "__main__": print import doctest if doctest.testmod().failed == 0: print "*** ALL TESTS PASSED ***" print
true
59fd6db86ea756bcac4d7b3d65e3c3837a5607d3
Ziydwesh/Pre-Bootcamp-Coding-Challenges
/Task7.py
360
4.34375
4
# To convert temperature in Celsius to Fahrenheit celsius = float(input("Enter temperature:")) fahrenheit = (celsius * 1.8) + 32 print("Temperature in Fahrenheit is", fahrenheit) # To convert temperature in Fahrenheit to Celsius fahrenheit = float(input("Enter temperature:")) celsius = (fahrenheit -32) / 1.8 print("Temperature in Celsius is", celsius)
false
1e2058e2b01b47e7e1e0c0724519077321b3e7e3
rushigandhi/cs-playground
/Algorithms/Sorting/Merge Sort/merge_sort.py
1,188
4.1875
4
# O(nlog(n)) best, average, and worst case time complexity # O(n) space complexity def merge_sort(input_list): # return if list only has one element if len(input_list) <= 1: return # find the middle index and use it to split the list mid = len(input_list)//2 lower = input_list[:mid] upper = input_list[mid:] # recursively call merge_sort on the upper and lower halves merge_sort(lower) merge_sort(upper) # this part is for sorting upper and lower into one i = j = k = 0 while i < len(lower) and j < len(upper): # choose the lower[i] since it is smaller if lower[i] < upper[j]: input_list[k] = lower[i] i += 1 # choose the upper[j] since it is smaller else: input_list[k] = upper[j] j += 1 # increment the position counter for the combined list k += 1 # fill in the remaining elements from lower while i < len(lower): input_list[k] = lower[i] i += 1 k += 1 # fill in the remaining elements from upper while j < len(upper): input_list[k] = upper[j] j += 1 k += 1
true
ae3201db34ee96d9f63feedb43481c0782b0de8c
monjerry/interview-questions
/sum_in_array.py
483
4.125
4
def sumInArray(array, suma): hashDict = {} for item in array: # If the item is in the array it means there is a number that will # up to the sum if item in hashDict: return True else: # Set the key to be the number that needs to be in the array to add # up to the sum hashDict[suma - item] = True return False array = [3, 5, 2,7 ,3] print sumInArray(array, 6) print sumInArray(array, 100)
true
77418bd3b43ecd51befd625b9e1b49b5ab52e835
aourchan/Project_Delta
/user_response.py
1,824
4.34375
4
""" This function: (1) Prompts the user for a response (2) Checks the type of the user response (3) If user responded with appropriate type passes user response on (4) Else If the user responded in an inappropriate manner asks for another prompt (5) If new prompt is still incorrect type then print out user score info and quit""" # This function is looking for an integer response from the user def user_response(): # Prompt that will be ask user for their response Prompt = "Your Response-> " # Number of times that we have tried to get a type appropriate user answer try_count = 0 # Number of times that we want to try to get a type appropriate user answer before quitting try_max = 2 # True when user gives a type appropriate response good_response = False while try_count <= try_max: # Get the user response user_answer = raw_input(Prompt) # Check if quit command was initiated by user if user_answer == 'q' or user_answer == 'Q': quit() # Check if user entered a fraction in a/b format if "/" in user_answer: user_answer = float(user_answer[0:user_answer.index("/")]) / float(user_answer[user_answer.index("/")+1:]) # Check if the user answer is an int try: user_answer = int(user_answer) return user_answer except ValueError: # If value is not an int check if value is float try: user_answer = float(user_answer) return user_answer except ValueError: # If value is also not a float then prompt user for new response try_count = try_count + 1 if try_count > try_max: print "You didn't enter a number again, we will quit for now." quit() else: print "Oops, it seems like you didn't enter a number. Try again." # This function is looking for a string response from the user def user_response_string(): temp = 1
true
48cb48d78e10cda94f58af5319c21a12a908bed3
rafaelrbnet/Guanabara-Mundo-01
/desafio035.py
1,083
4.375
4
""" DESENVOLVA UM PROGRAMA QUE LEIA O COMPRIMENTO DE TRÊS RETAS E DIGA AO USUARIO SE ELAS PODEM OU NÃO FAZER UM TRIÂNGULO Sabemos que um triângulo é formado por três lados que possuem uma determinada medida, mas essas não podem ser escolhidas aleatoriamente como os lados de um quadrado ou de um retângulo, é preciso seguir uma regra. Só irá existir um triângulo se, somente se, os seus lados obedeceram à seguinte regra: um de seus lados deve ser maior que o valor absoluto (módulo) da diferença dos outros dois lados e menor que a soma dos outros dois lados. Veja o resumo da regra abaixo: | b - c | < a < b + c | a - c | < b < a + c | a - b | < c < a + b """ a = float(input('digite o tamanho em cm da lateral A do triângulo: ')) b = float(input('digite o tamanho em cm da lateral B do triângulo: ')) c = float(input('digite o tamanho em cm da lateral C do triângulo: ')) ta = (b - c) < a < b + c tb = (a - c) < b < a + c tc = (a - b) < c < a + b print('As medidas informadas {} formar um triângulo'.format('PODEM' if ta and tb and tc else 'NÃO PODEM'))
false
02b60763e26ccdee9ff8488209fca3a012fe1441
Kailashcj/tpython
/Iterations n Recursion/triangle.py
270
4.25
4
import math def is_triangle(): print('Provide three sides of triangle') s1 = int(input()) s2 = int(input()) s3 = int(input()) if (s1 + s2) < s3 or (s1 + s3) < s2 or (s2 + s3) < s1: print('NO') else: print('yes') is_triangle()
false
028d45820d394929668367966f14284579f89618
Kailashcj/tpython
/hackerrank/geeks/anagram.py
508
4.15625
4
#!/bin/python3 import re def is_anagram(str1, str2): pattern = r'[\s*&%#.\'^?]+' s1 = re.sub(pattern, "", str1) s2 = re.sub(pattern, "", str2) if len(s1) != len(s2): return False for c in s1: if c not in s2: return False return True def main(): print('input first string') str1 = input() print('input second string') str2 = input() result = is_anagram(str1, str2) print(result) if __name__=='__main__': main()
false
fbbce0af61bc47c9d559ed2eb09d1df65d418b42
Artem-Efremov/CodeWars
/Strings/Sorting Replase Reverse/6kyu_Replace With Alphabet Position.py
1,222
4.25
4
""" In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc. As an example: alphabet_position("The sunset sets at twelve o' clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" as a string. """ def alphabet_position(text): return ' '.join(str(ord(i.lower()) - 96) for i in text if i.isalpha()) import string import random def ap(text): text = text.lower().strip() return " ".join([str(ord(x) - ord("a") + 1) for x in text if x in string.ascii_letters] ) print("Tests for each letter:") for letter in string.ascii_lowercase: test.assert_equals(alphabet_position(letter), ap(letter)) print("Randomly generated tests:") for i in range(100): x = "" for j in range(6): x += random.choice(string.ascii_lowercase) print("Testing \"{0}\":".format(x)) test.assert_equals(alphabet_position(x), ap(x)) print("Number tests:") for i in range(15): n = "" for l in range(10): n += str(random.randint(1, 9)) test.assert_equals(alphabet_position(n), ap(n))
true
cb637f67126e1b01feeacbb0077fc88c94bc3246
Artem-Efremov/CodeWars
/Strings/Sorting Replase Reverse/6kyu_I'm longer than you.py
1,744
4.34375
4
""" https://www.codewars.com/kata/5963314a51c68a26600000ae/solutions/python Create a function longer that accepts a string and sorts the words in it based on their respective lengths in an ascending order. If there are two words of the same lengths, sort them alphabetically. Look at the examples below for more details. longer("Another Green World") => Green World Another longer("Darkness on the edge of Town") => of on the Town edge Darkness longer("Have you ever Seen the Rain") => the you Have Rain Seen ever Assume that only only Alphabets will be entered as the input. Uppercase characters have priority over lowercase characters. That is, longer("hello Hello") => Hello hello Don't forget to rate this kata and leave your feedback!! Thanks """ def longer(s): words = s.split(' ') words.sort(key=lambda x: (len(x), x)) return ' '.join(words) from random import randint Test.describe("Sample Tests") Test.assert_equals(longer("Another Green World"), "Green World Another") Test.assert_equals(longer("Darkness on the edge of Town"), "of on the Town edge Darkness") Test.assert_equals(longer("Have you ever Seen the Rain"), "the you Have Rain Seen ever") Test.assert_equals(longer("Like a Rolling Stone"), "a Like Stone Rolling") Test.assert_equals(longer("This will be our Year"), "be our This Year will") Test.assert_equals(longer("hello Hello"), "Hello hello") Test.describe("Random Tests") soln=lambda s:' '.join(sorted(sorted(s.split(" ")),key=len)) for k in range(44): a,b="","qwertyuiopasdfghjklzxcvbnm" for i in range(randint(1,5)): c=randint(0 ,25) d=randint(0 ,26) if c>d:c,d=d,c a+=b[c:d]+" " a = a.strip(" ") Test.assert_equals(longer(a),soln(a))
true
e77016fc1ae923068612b6cae79c79920f2714c2
Artem-Efremov/CodeWars
/Arrays/Find, count/6kyu_Fibonacci, Tribonacci and friends.py
2,416
4.25
4
""" If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work. Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on. Well, guess what? You have to build a Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence. xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94} xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16} xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6} xbonacci {1,1} produces the Fibonacci sequence """ def Xbonacci(signature,n): result = signature[:n] len_object = len(signature) while len(result) < n: result.append(sum(result[-len_object:])) return result[:n] Test.describe("Basic tests") Test.assert_equals(Xbonacci([0,1],10),[0,1,1,2,3,5,8,13,21,34]) Test.assert_equals(Xbonacci([1,1],10),[1,1,2,3,5,8,13,21,34,55]) Test.assert_equals(Xbonacci([0,0,0,0,1],10),[0,0,0,0,1,1,2,4,8,16]) Test.assert_equals(Xbonacci([1,0,0,0,0,0,1],10),[1,0,0,0,0,0,1,2,3,6]) Test.assert_equals(Xbonacci([1,0,0,0,0,0,0,0,0,0],20),[1,0,0,0,0,0,0,0,0,0,1,1,2,4,8,16,32,64,128,256]) Test.assert_equals(Xbonacci([0.5,0,0,0,0,0,0,0,0,0],10),[0.5,0,0,0,0,0,0,0,0,0]) Test.assert_equals(Xbonacci([0.5,0,0,0,0,0,0,0,0,0],20),[0.5,0,0,0,0,0,0,0,0,0,0.5,0.5,1,2,4,8,16,32,64,128]) Test.assert_equals(Xbonacci([0,0,0,0,0,0,0,0,0,0],20),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]) Test.assert_equals(Xbonacci([1,2,3,4,5,6,7,8,9,0],9),[1,2,3,4,5,6,7,8,9]) Test.assert_equals(Xbonacci([1,2,3,4,5,6,7,8,9,0],0),[]) Test.describe("Random tests") from random import randint def Xsol(s,n): l=len(s) while len(s)<n: s+=[sum(s[-l:])] return s[:n] for _ in range(40): sign=[randint(0,20) for x in range(randint(1,20))] n=randint(1,50) Test.it("Testing for signature: "+str(sign)+" and n: "+str(n)) Test.assert_equals(Xbonacci(sign[:],n),Xsol(sign,n),"It should work for random inputs too")
true
fc6e2e85f8b795e939afb856576409511268850a
Artem-Efremov/CodeWars
/Strings/Regex/7kyu_Regex validate PIN code.py
1,914
4.21875
4
""" ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. eg: validate_pin("1234") == True validate_pin("12345") == False validate_pin("a234") == False """ def validate_pin(pin): return (len(pin) == 4 or len(pin) == 6) and pin.isdigit() def validate_pin(pin): return len(pin) in (4, 6) and pin.isdigit() import re def validate_pin(pin): return bool(re.match(r'^(\d{4}|\d{6})$',pin)) Test.assert_equals(validate_pin("1"),False, "Wrong output for '1'") Test.assert_equals(validate_pin("12"),False, "Wrong output for '12'") Test.assert_equals(validate_pin("123"),False, "Wrong output for '123'") Test.assert_equals(validate_pin("12345"),False, "Wrong output for '12345'") Test.assert_equals(validate_pin("1234567"),False, "Wrong output for '1234567'") Test.assert_equals(validate_pin("-1234"),False, "Wrong output for '-1234'") Test.assert_equals(validate_pin("1.234"),False, "Wrong output for '1.234'") Test.assert_equals(validate_pin("00000000"),False, "Wrong output for '00000000'") Test.assert_equals(validate_pin("a234"),False, "Wrong output for 'a234'") Test.assert_equals(validate_pin(".234"),False, "Wrong output for '.234'") Test.assert_equals(validate_pin("1234"),True, "Wrong output for '1234'") Test.assert_equals(validate_pin("0000"),True, "Wrong output for '0000'") Test.assert_equals(validate_pin("1111"),True, "Wrong output for '1111'") Test.assert_equals(validate_pin("123456"),True, "Wrong output for '123456'") Test.assert_equals(validate_pin("098765"),True, "Wrong output for '098765'") Test.assert_equals(validate_pin("000000"),True, "Wrong output for '000000'") Test.assert_equals(validate_pin("123456"),True, "Wrong output for '123456'") Test.assert_equals(validate_pin("090909"),True, "Wrong output for '090909'")
true
4d18f6634d0631e81e12103de02839a615862e44
Artem-Efremov/CodeWars
/Strings/7kyu_Alphabet war.py
1,494
4.1875
4
""" There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. Task Write a function that accepts fight string consists of only small letters and return who wins the fight. When the left side wins return Left side wins!, when the right side wins return Right side wins!, in other case return Let's fight again!. The left side letters and their power: w - 4 p - 3 b - 2 s - 1 The right side letters and their power: m - 4 q - 3 d - 2 z - 1 The other letters don't have power and are only victims. Example AlphabetWar("z"); //=> Right side wins! AlphabetWar("zdqmwpbs"); //=> Let's fight again! AlphabetWar("zzzzs"); //=> Right side wins! AlphabetWar("wwwwwwz"); //=> Left side wins! """ def alphabet_war(fight): left_side = {'w': 4, 'p': 3, 'b': 2, 's': 1} right_side = {'m': 4, 'q': 3, 'd': 2, 'z': 1} res = 0 for i in fight: if i in left_side: res += left_side[i] elif i in right_side: res -= right_side[i] return "Left side wins!" if res > 0 else "Right side wins!" if res < 0 else "Let's fight again!" def alphabet_war(fight): d = {'w' : 4, 'p' : 3, 'b' : 2, 's' : 1, 'm' : -4, 'q' : -3, 'd' : -2, 'z' : -1} result = sum(d[c] for c in fight if c in d) return 'Left side wins!' if result > 0 else ('Right side wins!' if result < 0 else 'Let\'s fight again!')
true
df68d74961ecef1d0098565d60b7ded8baebf36d
ananchai397/01-python-crash-course-part1
/01 python crash course part1 - quiz8.py
887
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #กำหนดให้ A = [1, 2, 3, 4, 5] และ B = [2, 3, 1, 3, 2] จงเขียน Map แบบ Multiple-list operations โดยให้ B ยกกำลังด้วย A พร้อมกับแสดงผล A = [1, 2, 3, 4, 5] B = [2, 3, 1, 3, 2] answer = map (lambda x, y: y**x, A, B) print(list(answer)) # In[4]: #จงเขียนชื่อนักเรียน เลขที่ และคะแนนสอบไฟนอล พร้อมกับใช้คำสั่ง Zip() ในการจับคู่พร้อมกับแสดงผลลัพธ์ที่ถูกต้อง name = ["dajim", "Daboyway", "joeyboy", "Jazz JSPKK", "Fhero"] number = [1,2,3,4,5] point = [75, 80, 69, 72, 43] show = list(zip(name, number, point)) print(show) # In[ ]:
false
8b2b6a872da25e56e6becbdd4ef3d74a433ee69c
am1507/Fresco
/fresco.py
2,554
4.4375
4
#Create an empty list 'emplist1' using list operation. emplist1=list() #Print 'emplist1' print(emplist1) #Append to empty list 'emplist1' created above with element 9. emplist1.append(9) #Append another element 10 to 'emplist1' emplist1.append(10) #Print 'emplist1' print(emplist1) #Create an empty list 'emplist2' using []. emplist2=[] #Print 'emplist2' print(emplist2) #Extend the empty list 'emplist2' created above with elements 'a', 'b', 'c'. emplist2.extend(['a','b','c']) #Print 'emplist2' print(emplist2) #Extract the last element of 'emplist2' and assign it to variable 'e'. e=emplist2[-1] #Print 'emplist2' print(emplist2) #Print the variable 'e'. print(e) ############################################################################ #Generate the list 'k1' having five continuous numbers starting from 0. k1 = list(range(0,5)) #Print 'k1' print(k1) #Generate the list 'k2' having five continuous numbers starting from 10. k2 =list(range(10,15)) #Print 'k2' print(k2) #Generate the list 'k3' having even numbers between 10 and 20 (including both of them too). k3 =list(range(10,21,2)) #Print 'k3' print(k3) #Generate the list 'k4' having numbers from 100 to 1 in decreasing order, which are also multiple of 25. k4 =list(range(100,0,-25)) #Print 'k4' print(k4) ######################################################################################## #Create two sets 'a', and 'b' with following values. a = set(('10','20','30','40')) # #a = ('10','20','30','40') # b = set(('30','60')) #b = ('30','60') # #Determine the following # # Union; store the output in variable 'u' and print it. u = a.union(b) print(u) # Intersection; store the output in variable 'i' and print it. i = a.intersection(b) print(i) # Difference between set 'a' and 'b'; store the output in variable 'd' and print it. d =a.difference(b) print(d) # Symmetric difference; store the output in variable 'sd' and print it. sd = a.symmetric_difference(b) print(sd) # # Create an empty Dictionary, 'd1' using 'dict' function d1 =dict() # print 'd1' print(d1) # Create a Dictionary 'd2' with Key values p-play , t-talk d2 ={'p' : 'play', 't' : 'talk'} # print 'd2'. print(d2) # Add two new key values : v-vibe, d-docs d2.update({'v':'vibe','d':'docs'}) # print 'd2' print(d2) # Remove the key value pair, 'v' - vibe, from 'd2' del(d2(['v']) # print 'd2' print(d2) # #
true
81f2cb588feb77c3392bd4b5721b80a9467e2102
artinesrailian/Python_W3school
/19-Iterators.py
2,278
4.5625
5
#An iterator is an object that contains a countable number of values. #An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. #Technically, in Python, an iterator is an object which implements the iterator protocol, #which consist of the methods __iter__() and __next__(). #Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. MyTuple = ("Apple", "Banana", "Orange") MyIt = iter(MyTuple) print(next(MyIt)) print(next(MyIt)) print(next(MyIt)) #We can also use a for loop to iterate through an iterable object: for x in MyTuple: print(x) #Iterate the characters of a string MyString = "banana" for x in MyString: print(x) #The for loop actually creates an iterator object and executes the next() method for each loop. #To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. #As you have learned in the Python Classes/Objects chapter, #all classes have a function called __init__(), #which allows you to do some initializing when the object is being created. #The __iter__() method acts similar, you can do operations (initializing etc.), #but must always return the iterator object itself. #The __next__() method also allows you to do operations, and must return the next item in the sequence. class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) #The example above would continue forever if you had enough next() statements, or if it was used in a for loop. #To prevent the iteration to go on forever, we can use the StopIteration statement. #In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times: class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)
true
9da94dca8975ade2a7ed9b0a4b56ff5f9554d88f
artinesrailian/Python_W3school
/1-HelloWorld.py
539
4.15625
4
#This is the hello wolrd example print("Hello, World!") #This is the indention example if 5 > 2: print("Five is greater than two!") #This is variable types example x = 5 y = "Hello, World!" #Mulitline comment example """ This is a comment written in more than just one line, In fact Python discards the strings that are not assigned to a variable or not used, during the execution. So you can write as many lines of comments using triple quotes and write your comment in between. Python will never do anything with this section. """
true
f1158293894488fbfd015562cd6e8c8af2406785
artinesrailian/Python_W3school
/17-Classes.py
2,214
4.34375
4
#Python classes and objects """ Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ #To create a class use the keyword class class MyClass: x = 5 #Now we can use the class named MyClass to create objects p1 = MyClass() print(p1.x) #The __init__() Function """ The examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in __init__() function. All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: """ class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age) #Methods. Objects can also contain methods. Methods in objects are functions that belong to the object class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() #The self parameter is a reference to the current instance of the class, #and is used to access variables that belong to the class #It does not have to be named self, #you can call it whatever you like, #but it has to be the first parameter of any function in the class class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() #You can modify properties on objects like this: p1.age = 40 #You can delete properties on objects by using the del keyword del p1.age #You can delete objects by using teh del keyword del p1 #class definitions cannot be empty, but if you for some reason have a class definition with no content, #put in the pass statement to avoid getting an error. class Person: pass
true
a6cbda0f07201c5e946c6c24fe118b3766275672
python-kurs/exercise-2-RobFisch
/second_steps.py
2,017
4.21875
4
# Exercise 2 # Satellites: sat_database = {"METEOSAT" : 3000, "LANDSAT" : 30, "MODIS" : 500 } # The dictionary above contains the names and spatial resolutions of some satellite systems. # 1) Add the "GOES" and "worldview" satellites with their 2000/0.31m resolution to the dictionary [2P] sat_database["GOES"] = 2000 sat_database["WORLDVIEW"] = 0.31 print("I have the following satellites in my database:") # 2) print out all satellite names contained in the dictionary [2P] print(sat_database.keys()) # 3) Ask the user to enter the satellite name from which she/he would like to know the resolution [2P] y = input("Von welchem satelliten möchtest du die Auflösung wissen? (Bitte in Großbuchstaben)") if y == "METEOSAT": print("METEOSAT hat eine Auflösung von 3000 Metern.") elif y == "LANDSAT": print("LANDSAT hat eine Auflösung von 30 Metern.") elif y == "MODIS": print("MODIS hat eine Auflösung von 500 Metern.") elif y == "GOES": print("GOES hat eine Auflösung von 2000 Metern.") elif y == "WORLDVIEW": print("WORLDVIEW hat eine Auflösung von 0.31 Metern.") else: print("Ich habe dich leider nicht verstanden.") #sat_database # #for key,val in sat_database: # x = input("Von welchem Satelliten möchtest du die Auflösung erfahren?") # if x =0 (sat_database.keys()) # print(sat_database.values) #print("Die Auflösung von {} ist {} Meter.".format(val, key)) # 4) Check, if the satellite is in the database and inform the user, if it is not [2P] if y in sat_database: print("Der Satellit befindet sich im Datensatz.") else: print("Der Satellit befindet sich nicht im Datensatz.") # 5) If the satellite name is in the database, print a meaningful message containing the satellite name and it's resolution [2P] Aufl = (sat_database.get(y)) if y in sat_database: print("Der wunderschöne Satellit {} besitzt eine tolle Auflösung von {} Metern".format(y,Aufl)) else: print("Es gibt nichts zu sagen.")
false
0a9f9ab41d470e29a1fb208a393d4322a49a6813
Renato-moura/ExercicioListaDicionario
/exercicio_dict_2.py
1,865
4.21875
4
#2 Uma pista de Kart permite 10 voltas para cada um de 6 corredores. Escreva um programa que leia todos os tempos em segundos e os guarde em um dicionrio, em que a chave e o nome do corredor. Ao final diga de quem foi a melhor volta da prova e em que volta; e ainda a classificao final em ordem (1o o campeo). O campeo e o que tem a menor media de tempos. lista = [] piloto0 = {} piloto1 = {} corredor = 0 while corredor < 2: volta = 0 registro = {} registroLista = {} print("----------------------------------") nome = input("nome do piloto ("+str(corredor+1)+") : ") while volta < 2: print("volta de numero: "+str(volta+1)) tempo = int(input("tempo em segundos: ")) registroLista[volta] = tempo #registroLista["volta"+str(volta)] = volta registro[nome]=registroLista if corredor == 0: piloto0 = registro.copy() elif corredor == 1: piloto1 = registro.copy() print("piloto0: ",piloto0) print("--------------------") print("piloto1: ",piloto1) print("--------------------") print("corredor :",corredor) print("--------------------") volta +=1 lista.append(nome) corredor += 1 print("----------------------------------") media=0 piloto="" pilotoTempo="" soma = 0 faster = 0 voltaRec = 0 j=0 while j<2: i=0 while i<2 : faster = piloto0[lista[j]][i] piloto = lista[j] voltaRec = i if piloto0[lista[j]][i] < faster: faster = piloto0[lista[j]][i] piloto = lista[j] voltaRec = i soma += piloto0[lista[j]][i] i+=1 media = soma = soma/len(lista) pilotoTempo = lista[j] if media < soma: media = soma pilotoTempo = lista[j] j+=1 print(faster,piloto,voltaRec) print(media, pilotoTempo)
false
44f58ee8b6cb0eabd048752deb6567d229e1c8fc
Zahidsqldba07/HackeRank-1
/Python/Nested-Lists.py
2,027
4.40625
4
''' Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input Format The first line contains an integer, N, the number of students. The 2N subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade. Constraints 2<=N<=5 There will always be one or more students having the second lowest grade. Output Format Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. Sample Input 0 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Sample Output 0 Berry Harry Explanation 0 There are 5 students in this class whose names and grades are assembled to build the following list: python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] The lowest grade of 37.2 belongs to Tina. The second lowest grade of 37.21 belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line. ''' from collections import OrderedDict n = int(raw_input()) ar = {} for i in range(0, n): tmp_name = raw_input() tmp_marks = float(raw_input()) ar[tmp_name] = tmp_marks # Entering them in the ordered dictionary val_ar = [] for i in ar: tmp_val = ar[i] val_ar.append(tmp_val) # print (val_ar) --> Marks of all Students set_val = set(val_ar) val_ar = list(set_val) val_ar.sort() # print (val_ar) --> Distinct marks of students sorted in ascending order sec_mark = val_ar[1] final_ar = [] for i in ar: if (sec_mark == ar[i]): final_ar.append(i) # print (final_ar) --> Array having people with second lowest marks final_ar.sort() for i in final_ar: print (i)
true
df19c98a4164f590dc512ce1111a0dd47bface54
mengyucode/driving
/driving.py
372
4.125
4
country = input('where are you from: ') age = input('how old are you: ') age = int(age) if country == 'taiwan': if age >= 18: print('you can have driver liscence') else: print('you can not have driver liscnece') elif country == 'america': if age >= 16: print('you can drive') else: print('you cannot drive') else: print('you can only enter taiwan or america')
false
1586a9b63655537e470aa719c88e5cceed354ee8
JanithMS/mycaptain_python_march2021
/Task3.py
846
4.375
4
#Write Python code to create a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Use dictionaries. # function for printing frequency in desending order def fun2(mydict): def fun1(mydict): for k in mydict: if mydict[k] == max(mydict.values()): p = str(k)+" = "+str("{0:0=2d}".format(mydict[k]))+" " mydict.pop(k) return p m = len(mydict) x = "" for l in range(m): x = x + fun1(mydict) return x inputstring = input("Please enter a string: ") def most_frequent(a): a = a.lower() b = dict() for i in set(a): n = 0 for j in list(a): if i == j: n += 1 b[i] = n return fun2(b) print(most_frequent(inputstring))
true
e4bad3bd49983b88fd1abeff53260d3a4517c7c1
Amigo723/Random-Password-Generator
/CEASER Encryption.py
600
4.21875
4
Ptext = input("enter th message which you want to Encrypt : ") char1 = "abcdefghijklmnopqrstuvwxyz" char2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = int(input("Enter the key value : ")) Cipher = " " if Ptext.isupper(): for i in Ptext: position = char2.find(i) newPosition = (position + key) % 26 Cipher += char2[newPosition] elif Ptext.islower(): for i in Ptext: position = char1.find(i) newPosition = (position + key) % 26 Cipher += char1[newPosition] else: print("You entered the wrong text : ") print("your Encrypted message is : " + Cipher)
false
0317d55a5d5989f9d1c57d401110d04141ddfe63
guimmp92/python
/anagrams.py
1,618
4.3125
4
#!/usr/bin/python # vim: foldlevel=0 """ How to check if a string contains an anagram of another string? Example: The string "coding interview questions" contains an anagram of the string "weivretni". http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/ """ from collections import defaultdict def solution(a, b): """ >>> solution("coding interview questions", "weivretni") True >>> solution("coding interviw questions", "weivretni") False >>> solution("coding interview questions", "abcde") False """ tracker = [0] * 256 for i in range(len(b)): tracker[ord(b[i])] += 1 lo = 0 for hi in range(len(a)): tracker[ord(a[hi])] -= 1 while hi-lo+1 > len(b): tracker[ord(a[lo])] += 1 lo += 1 if hi-lo+1 == len(b) and all([c == 0 for c in tracker]): return True return False def solution1(a, b): """ >>> solution1("coding interview questions", "weivretni") True >>> solution1("coding interviw questions", "weivretni") False >>> solution1("coding interview questions", "abcde") False """ target_hash, rolling_hash = 0, 0 for i in range(len(b)): target_hash += ord(b[i]) // 101 rolling_hash += ord(a[i]) // 101 i = 0 for j in range(len(b), len(a)): if rolling_hash == target_hash: return True rolling_hash += ord(a[j]) // 101 rolling_hash -= ord(a[i]) // 101 i += 1 return False if __name__ == "__main__": import doctest doctest.testmod()
true
dee98c807896d0ca1bc15ada0ed2717b6d6681f8
richardrugg/UoP-CS1101-RR
/unit4-journal.py
489
4.1875
4
import math # import the math module so we can use the sqrt function def hypotenuse(a, b): # finds hypotenuse of a right triangle using the Pythagorean Theorem return math.sqrt(a ** 2 + b ** 2) # adding some test prints to confirm if working properly print("Test Output for Function 'hypotenuse':") print("Result of hypotenuse(3,4):", hypotenuse(3, 4)) print("Result of hypotenuse(2,3):", hypotenuse(2, 3)) print("Result of hypotenuse(7,9):", hypotenuse(7, 9))
true
ac0670638ca5618b00605a92584413744f34c283
richardrugg/UoP-CS1101-RR
/unit4-discussion.py
391
4.21875
4
def subtract(x, y): return x - y def divide(x, y): return x / y print(divide(5, (subtract(1, 1)))) # the output of the subtract function is zero # leading the divide function to divide by zero # while zero is a logical output of the divide function # it's logical use outside of the function is the issue # this also is a precondition issue for the divide function
true
bd80546698d52a598d04eeab55295192508b02df
richardrugg/UoP-CS1101-RR
/unit4-programming.py
1,052
4.40625
4
def is_between(x, y, z): # is y between or equal to x and z? if x <= y <= z: return True else: return False def is_divisible(x, y): # is x divisible by y? if x % y == 0: return True else: return False def is_power(a, b): # is a power of b? if a == 1 and b == 1: # 1 is a power of 1 and a special case # this is here to avoid infinite recursion for a & b = 1 return True elif b == 1: # 1 is the only power of 1 # this avoids false positives for this special value return False elif is_divisible(a, b) == 1 and is_power(a / b, b) == 0: return True else: return False # test cases to exercise the is_power function print("is_power(10, 2) returns: ", is_power(10, 2)) print("is_power(27, 3) returns: ", is_power(27, 3)) print("is_power(1, 1) returns: ", is_power(1, 1)) print("is_power(10, 1) returns: ", is_power(10, 1)) print("is_power(3, 3) returns: ", is_power(3, 3))
false
b40e000f6e9b5f61b6bfe5f037b197e610adc717
mHernandes/codewars
/6kyu_decode_the_morse_code.py
1,940
4.4375
4
""" In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superseded by voice and digital data communication channels, it still has its use in some applications around the world. The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·. NOTE: Extra spaces before or after the code have no meaning and should be ignored. In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words. Your task is to implement a function that would take the morse code as input and return a decoded human-readable string. For example: decodeMorse('.... . -.-- .--- ..- -.. .') #should return "HEY JUDE" NOTE: For coding purposes you have to use ASCII characters . and -, not Unicode characters. All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. link to kata: https://www.codewars.com/kata/54b724efac3d5402db00065e """ morse_code = '.... . -.-- .--- ..- -.. .' def decodeMorse(morse_code): return ' '.join(''.join(MORSE_CODE[i] for i in word.split(' ')) for word in morse_code.strip().split(" ")) def main(): texto = decodeMorse(morse_code) print(texto) if __name__ == "__main__": main()
true
94c50a1b8487a3a52382612ee3cb88ae6eccc561
KOO-AL3X/css225
/loop 3.py
477
4.3125
4
#Alex Feliciano #10/28/2020 #this ask the user how many sides and makes it for them import turtle wn = turtle.Screen() alex = turtle.Turtle() sides = input ("Number of sides in polygon?" ) length = input ("Length of the sides in polygon?" ) colorname = input ("Color of polygon?" ) fcolor = input ("Fill color of polygon?") alex.color = (colorname) alex.fillcolor = (fcolor) for i in range(sides): alex.forward (length) alex.left (360 / sides)
true
969450d88dc88f32c6d41406ab9d1445cd2e7f41
KOO-AL3X/css225
/module 9.py
804
4.15625
4
#Alex Feliciano #12/06/2020 #thisaskig for you name and then the user would answer and #then it would say hello and the name usertext = input("what is your name ") print("Hello", usertext) # this say hello world infinte #im going to put it in comments so i could do the other question #just take it off the comment to use this function #while True: #print("hello world") #the third question if the number is divisble by 2 its true if not then its false and do it again # im going to put it in a comment so i could do the other question #def even(n): # n % 2 = true # if else return false # hould generate a random number ‘n’ #between 1 and 100, then print each number from 1 to n. #import random #def numbers(): # x = random.randint(0,100) #print(1,n)
true
40fbddc6c155dce00253f06ae036fc4bb1b7bbb5
zzy1120716/my-nine-chapter
/catagory/DataStructure/OOP/0222-setter-and-getter.py
944
4.53125
5
""" 222. Getter与Setter 实现一个School的类,包含下面的这些属性和方法: 一个string类型的私有成员name. 一个setter方法setName,包含一个参数name. 一个getter方法getName,返回该对象的name。 样例 Java: School school = new School(); school.setName("MIT"); school.getName(); // 返回 "MIT" 作为结果 Python: school = School(); school.setName("MIT") school.getName() # 返回 "MIT" 作为结果 """ # __name 表示私有变量 class School: def __init__(self): self.__name = '' ''' * Declare a setter method `setName` which expect a parameter *name*. ''' # write your code here def setName(self, name): self.__name = name ''' * Declare a getter method `getName` which expect no parameter and return * the name of this school ''' # write your code here def getName(self): return self.__name
false
6b5332e8dc7223987785c38084ff7734dff9695d
zzy1120716/my-nine-chapter
/catagory/DataStructure/Stack/0022-flatten-list.py
1,102
4.46875
4
""" 22. 平面列表 给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。 样例 给定 [1,2,[1,2]],返回 [1,2,1,2]。 给定 [4,[3,[2,[1]]]],返回 [4,3,2,1]。 挑战 请用非递归方法尝试解答这道题。 注意事项 如果给定的列表中的要素本身也是一个列表,那么它也可以包含列表。 """ class Solution(object): # @param nestedList a list, each element in the list # can be a list or integer, for example [1,2,[1,2]] # @return {int[]} a list of integer def flatten(self, nestedList): # Write your code here stack = [nestedList] flatten_list = [] while stack: top = stack.pop() if type(top) == list: for elem in reversed(top): stack.append(elem) else: flatten_list.append(top) return flatten_list if __name__ == '__main__': print(Solution().flatten([1, 2, [1, 2]])) print(Solution().flatten([4, [3, [2, [1]]]]))
false
f97fff24bd34a40427c0edd48673aaf254af6106
zzy1120716/my-nine-chapter
/catagory/BinaryTree/0072-construct-binary-tree-from-inorder-and-postorder-traversal.py
1,109
4.21875
4
""" 72. 中序遍历和后序遍历树构造二叉树 根据中序遍历和后序遍历树构造二叉树 样例 给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2] 返回如下的树: 2 / \ 1 3 注意事项 你可以假设树中不存在相同数值的节点 """ # Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param inorder: A list of integers that inorder traversal of a tree @param postorder: A list of integers that postorder traversal of a tree @return: Root of a tree """ def buildTree(self, inorder, postorder): # write your code here if not inorder: return root = TreeNode(postorder[-1]) root_pos = inorder.index(postorder[-1]) root.left = self.buildTree(inorder[:root_pos], postorder[:root_pos]) root.right = self.buildTree(inorder[root_pos + 1:], postorder[root_pos:-1]) return root if __name__ == '__main__': print(Solution().buildTree([1, 2, 3], [1, 3, 2]))
false
7a2514faa31b63fdbb3395a6d95b79105bc49f0b
lakshmi2812/dive_into_python
/dasherize_number.py
1,578
4.5
4
# Write a method that takes in a number and returns a string, placing # a single dash before and after each odd digit. There is one # exception: don't start or end the string with a dash. # # You may wish to use the `%` modulo operation; you can see if a number # is even if it has zero remainder when divided by two. # # Difficulty: medium. def dasherize_number(num): str_num = str(num) list_num = list(str_num) new_list = list(range(len(list_num))) x = 0 while x < len(list_num): n = int(list_num[x]) if n % 2 == 1: if x == 0: new_list[x] = list_num[x] + '-' elif x == len(list_num) - 1: new_list[x] = '-' + list_num[x] else: if int(list_num[x-1]) % 2 == 1 and int(list_num[x+1]) % 2 == 1: new_list[x] = list_num[x] elif int(list_num[x-1]) % 2 == 1 and int(list_num[x+1]) % 2 == 0: new_list[x] = list_num[x] + '-' elif int(list_num[x-1]) % 2 == 0 and int(list_num[x+1]) % 2 == 1: new_list[x] = '-' + list_num[x] else: new_list[x] = list_num[x] x+=1 final_string = ''.join(new_list) return final_string # These are tests to check that your code is working. After writing # your solution, they should all print true. print(dasherize_number(203) == "20-3") print(dasherize_number(303) == "3-0-3") print(dasherize_number(333) == "3-3-3") print(dasherize_number(3223) == "3-22-3")
true
ee3f6fa31d4650ee2ee0c373f410d18f38164b5e
Octoberr/letcode
/hard/RegularExpressionMatching.py
1,259
4.25
4
""" Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". create by swm 2018/05/31 """ class Solution(object): def isMatch(self, text, pattern): memo = {} def dp(i, j): if (i, j) not in memo: if j == len(pattern): ans = i == len(text) else: first_match = i < len(text) and pattern[j] in {text[i], '.'} if j+1 < len(pattern) and pattern[j+1] == '*': ans = dp(i, j+2) or first_match and dp(i+1, j) else: ans = first_match and dp(i+1, j+1) memo[i, j] = ans return memo[i, j] return dp(0, 0) if __name__ == '__main__': sl = Solution() s = "mississippi" p = "mis*is*p*." print(sl.isMatch(s, p))
true
6f1432b1b04d04506a0dbff1672cf01939f0d537
fp-computer-programming/cycle-5-labs-p22dhealy
/lab_5-2.py
336
4.21875
4
#author: DMH 10/27/21 user1 = input("Please enter the first string:") user2 = input("Please enter the second string:") if user2 > user1: print("The first string is less than the second string") if user2 < user1: print("The first string is larger than the second string") if user1 == user2: print("The strings are equal")
true
ee91ca96596a29a823b37a589accdde6430ad0ba
shahzeb-jadoon/Portfolio
/heapsort.py
2,629
4.25
4
# heap_sort.py # Heap Sort # By: Shahzeb Jadoon def heapify(lst, index, lst_size): """ Helping function for build_heap() that makes sure the items in the position of index are where they are supposed to be pre: lst is a list of items that is not sorted in nondecreasing order. lst_size is the size of the lst provided. index is the position of item which is being verified whether it is in the correct position in the heap post: places the item in position index in its correct place """ k = (2 * (index + 1)) - 1 if k < lst_size: if k + 1 < lst_size: if lst[2 * (index + 1)] > lst[k]: k = 2 * (index + 1) if lst[k] > lst[index]: lst[k], lst[index] = lst[index], lst[k] heapify(lst, k, lst_size) else: if lst[k] > lst[index]: lst[k], lst[index] = lst[index], lst[k] heapify(lst, k, lst_size) def build_heap(lst, lst_size): """ Builds a heap from a provided lst pre: lst is a list of items that is not sorted in nondecreasing order. lst_size is the size of the lst provided post: converts the lst into a heap (in-place algorithm) """ for index in range((lst_size//2) - 1, -1, -1): heapify(lst, index, lst_size) def heap_sort(lst): """ Sorts the give lst using heap sort algorithm pre: lst is a list of items that is not sorted in nonddecreasing order post: sorts lst after converting it into a heap. """ lst_size = len(lst) build_heap(lst, lst_size) while lst_size > 0: lst[0], lst[lst_size - 1] = lst[lst_size - 1], lst[0] lst_size -= 1 heapify(lst, 0, lst_size) def main(): """ This program demonstrates how heap sort works post: prints the unsorted and sorted list """ print("This program allows the user to visualize heap sort on a list of a size") lst_size = int(input("provided by the user, thus, enter list size: ")) lst = [] for i in range(lst_size): lst.append(randrange(0, 5000)) print("\nThe list is:\n", lst, "\n") key_pressed = str(input("Would you like to see a heap made from this list? (Y/N) ")) if key_pressed[0].lower() == "y": build_heap(lst, lst_size) print("\nThe heap is:\n", lst, "\n") heap_sort(lst) key_pressed = str(input("Press <enter> to see the sorted list")) print("\nThe sorted list is:\n", lst) if __name__ == "__main__": from random import randrange main()
true
ffa968a1dd4891e3be9477171dfe2c28395aa936
yeargin2021/Top-10-Easy-Python-Project-Ideas-For-Beginners
/value_converter.py
2,334
4.46875
4
def convert_temperature(): print("\nWhich conversion do you want to choose:-") print("1. Celsius to Faranheit") print("2. Faranheit to Celsius") choice = int(input("Enter your choice: ")) if choice == 1: temp = float(input("Enter temperature in celsius: ")) print(f"{temp} degree celsius is equal to {(temp*9/5)+32} degree faranheit.\n") elif choice == 2: temp = float(input("Enter temperature in faranheit: ")) print(f"{temp} degree faranheit is equal to {(temp-32)*5/9} degree celsius.\n") else: print("Invalid input...please try again\n") def convert_currency(): print("\nWhich conversion do you want to choose:-") print("1. Dollar to pound") print("2. Pound to Dollar") choice = int(input("Enter your choice: ")) if choice == 1: value = float(input("Enter currency in dollars: ")) print(f"{value} dollars in pounds will be {value*0.73}\n") elif choice == 2: value = float(input("Enter currency in pounds: ")) print(f"{value} pounds in dollars will be {value/0.73}\n") def convert_lengths(): print("\nWhich conversion do you want to choose:-") print("1. Centimeters to foot and inches") print("2. Foot and inches to centimeter") choice = int(input("Enter your choice: ")) if choice == 1: value = float(input("Enter length in cm: ")) inches = value/2.54 feet = inches/12 print(f"{value} centimeters in equal to {feet} feet and {inches} inch\n") elif choice == 2: feet = float(input("Enter length in feet: ")) inches = float(input("Enter length in inches: ")) length = (feet*12 + inches)*2.54 print(f"{feet} feet and {inches} inches in centimeters will be {length}\n") print("===== Welcome to Value Converter =====") while 1: print("Which option would you like to choose:-") print("1. Convert temperature") print("2. Convert currency") print("3. Convert lengths") print("4. Exit") choice = int(input("Enter your choice: ")) if choice == 1: convert_temperature() elif choice == 2: convert_currency() elif choice == 3: convert_lengths() elif choice == 4: print('Exiting...') exit(0)
true
0d0cc567113b73e17ca87cd6c596a88a9d017af2
timparker14/python-scripts
/Room_Size_Machine.py
1,090
4.25
4
def area(): print("Ok, the room has an area of ", length * width, " Meters.") def perimeter(): print("And a perimeter of ", (length + width) * 2, " Meters.") length = float(input("I will work out the area and perimeter of your room for you.\n" "Please enter the rooms length in meters:\n >")) width = float(input("Please enter the width of the room in meters:\n >")) print("Calculating...") area() perimeter() while True: def area(): print("Ok, the room has an area of ", length * width, " Meters.") def perimeter(): print("And a perimeter of ", (length + width) * 2, " Meters.") choice = input("Would you like to do another y/n:\n>") if choice == "y": length = float(input("I will work out the area and perimeter of your room for you.\n" "Please enter the rooms length in meters:\n >")) width = float(input("Please enter the width of the room in meters:\n >")) print("Calculating...") area() perimeter() else: break print("Ok, Bye :)")
true
262f94be311595e485e24643271ff73f23befd53
Timofej8971/lab-8
/zd1.py
1,134
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # создайте словарь, связав его с переменной school , и наполните данными, # которые бы отражали количество учащихся в разных классах # (1а, 1б, 2б, 6а, 7в и т. п.). # Внесите изменения в словарь согласно следующему: # а) в одном из классов изменилось # количество учащихся, б) в школе появился новый класс, # с) в школе был расформирован # (удален) другой класс. Вычислите общее количество учащихся в школе. if __name__ == '__main__': school = {'1b': 30, '3z': 25, '2a': 10, '5b': 22} print(school) school['2a'] = 25 print(school) school.setdefault('3v', 34) print(school) school.pop('1b') print(school) result = 0 for i in school: result += school.get(i, '') print(f"Общее количесвто учащихся: {result}")
false
e83b741aae286cc9a7dd51c289d8a45ceb98dba3
Prosper1kwo/HangmanGame
/store_functions.py
893
4.21875
4
''' These functions store data to be used in the game. ''' from random import randint from hangman_words import animal_words, fruit_words, country_words def guess_store(answer, past_guess): ''' Stores the letters you have guessed into a list to be displayed ''' if answer in past_guess: pass elif answer != "" or answer != " ": past_guess.append(answer) else: print("Invalid Input") return past_guess def rand_word(hint): ''' This function returns a random word from a list of words based on the single hint the user picked ''' sol = "" if hint == "f": sol = fruit_words[randint(0, len(fruit_words) - 1)] elif hint == 'a': sol = animal_words[randint(0, len(animal_words) - 1)] elif hint == "c": sol = country_words[randint(0, len(country_words) - 1)] pass return sol
true
35503f802d53925fd159ae999326832cdb0dabae
KaranKaur/Leetcode
/326 - Power of three.py
256
4.53125
5
""" Given an integer, write a function to determine if it is a power of three. """ def pow_three(n): if n <= 0: return False while n % 3 == 0: n /= 3 return True if n == 1 else False print(pow_three(81)) print(pow_three(30))
true
7d7dc03f1ae3372efc61977c0c5f03a478fa0beb
KaranKaur/Leetcode
/448 - No disappeared in an array.py
529
4.125
4
""" Given an array of integers where a[i] belongs to (1,n) (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. """ def disappeared_num(nums): """ :type nums: List[int] :rtype: List[int] """ return list((set(range(1,len(nums)+1))) - set(nums)) print(disappeared_num([4,3,2,7,8,2,3,1]))
true
df1fdd7feb1c9f5dc5e7901bcec0c6767ffffa73
KaranKaur/Leetcode
/231 - Power of Two.py
329
4.375
4
""" Given an integer, write a function to determine if it is a power of two. Example: Input: 1 Output: true Input: 16 Output: true Input: 218 Output: false """ def pow_two(n): if n <= 0: return False while n % 2 == 0: n /= 2 return True if n == 1 else False print(pow_two(218)) print(pow_two(0))
true
9ab7c74cf6d8eb1434764ce6d0299df099398ce8
Cassiexyq/Program-Exercise
/lintcode/228-链表的中点.py
655
4.125
4
# -*- coding: utf-8 -*- # @Author: xyq """ Definition of ListNode 链表长度每增长2,后移一位 """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: the head of linked list. @return: a middle node of the linked list """ def middleNode(self, head): # write your code here if not head or not head.next or not head.next.next: return head pre = head cur = head.next.next while cur.next and cur.next.next: pre = pre.next cur = cur.next.next return pre.next
true
5369f58f34acd44564b5030360874f0ba785acc6
sen-l/testLs
/其他版本/第七天/06-类属性和实例属性.py
1,549
4.40625
4
# 自定义一个类 class Person(object): # 国家 country = '中国' def __init__(self, name, age): self.name = name self.age = age # xiaoming = Person('小明', 22) # # 使用实力属性:对象名.实力属性名 # print(xiaoming.name) # # # 修改实例属性:对象名.实例属性名 = 值 # xiaoming.name = '小小明' # print(xiaoming.name) # # 使用类属性 # # 01:类名.类属性名 # print(Person.country) # # 02:对象名.类属性名 # xiaoming = Person('小明', 20) # # # 修改类属性 # # 01:类名.类属性名 = 值 # Person.country = '中华' # print(Person.country) # # 02:不存在(对象名。类属性名 = 值) # xiaoming = Person('小明', 22) # # python认为你是给对象设置实例属性(只是和类属性名相同而已),和类属性不是同一个内存空间 # xiaoming.country = '中华啊' # print(id(xiaoming.country)) # print(id(Person.country)) # # 关于类属性 内存问题 # xiaoming1 = Person('小明1', 20) # xiaoming2 = Person('小明2', 22) # # 类属性python只会开辟一份内存(他是代表这个类的属性这个类python中只有一个) # print(id(xiaoming1.country)) # print(id(xiaoming2.country)) # print(id(Person.country)) # 类属性好处??? # 为了节约内存 # 为了后期业务需求更改,可以提高开发效率 # 自定义一个类 class Person(object): def __init__(self, name, age, country): # 实例属性 self.name = name self.age = age self.country = country
false
1ae692d2962b6279a6d241a019f1e51d0411b36f
sen-l/testLs
/其他版本/第四天/16-匿名函数.py
2,287
4.375
4
# 匿名函数:对函数的简写 # 无参数无返回值的函数 def my_print(): print("hello world!!!") my_print() # 表达式的定义 f = lambda : print("hello python!!!") # 执行 f() # 等价于 (lambda : print("hello python!!!"))() # 无参数有返回值的函数 def my_pi(): return 3.14 print(my_pi()) # 表达式的定义 f = lambda : 3.14 print(f()) # 定义一个有参数无返回值的函数 def my_print2(name): print("你好%s" % name) my_print2("老李头") # 定义一个有参数有返回值的函数 def add2num(a, b): return a + b print("add2num函数返回值为:%d" % add2num(3, 5)) f = lambda a, b : a + b print("f函数返回值为:%d" % f(10, 20)) # 函数作为参数传递 # 表达式 f = lambda x, y : x + y # 函数 def fun(a, b, opt): print("a = %d" % a) print("b = %d" % b) result = opt(a, b) print("result = %d " % result) # 调用函数 fun(1, 2, lambda x, y : x + y) def add3num(x, y): return x + y f = lambda x, y : x + y def fun2(a, b, opt): result = opt(a, b) print("result = %d " % result) fun2(10, 11, f) print("-----------------------------------------------") # 自定义排序(最外层肯定是列表) my_list = [1, 4, -10, 20, 3] my_list.sort() print(my_list) stus = [{"name": "张三", "age": 18}, {"name": "李武", "age": 19}, {"name": "王琦", "age": 17}] stus2 = [{"name": "zhangsan", "age": 18}, {"name": "liwu", "age": 19}, {"name": "wangqi", "age": 17}] print("未排序之前:%s" % stus) # 按照年龄排序 stus.sort(key=lambda my_dict:my_dict["age"]) print("按年龄排序之后:%s" % stus) # 按照名字排序 # 使用的每个名字的首字母排序(规则是按ascii码完成的) # 格式: 列表名.sort(key=lambda 列表的元素(临时变量): 临时变量[key]) stus2.sort(key=lambda my_dict:my_dict["name"]) print("按名字排序之后:%s" % stus2) # 列表中的列表嵌套 my_list = [[12, 8, 9], [7, 10, 11], [9, 10, 22]] # 按照列表元素(小列表)最后一个元素排序 # 格式: 列表名.sort(key=lambda 列表的元素(临时变量): 临时变量[下标索引]) my_list.sort(key=lambda new_list:new_list[2], reverse=True) print(my_list) my_list.sort(key=lambda new_list:new_list[0], reverse=True) print(my_list)
false
e6a4b9d657647798c3039e7d9374dc1340b9a7f2
sen-l/testLs
/其他版本/第六天/14-子类重写父类的同名属性和方法.py
1,218
4.125
4
# 自定义一个师傅类-(古法) class Master(object): # 构造方法 def __init__(self): self.kongfu = '古法煎饼果子配方' # 擅长做煎饼果子 def make_cake(self): print("按照<%s>制作煎饼果子" % self.kongfu) # 自定义一个新东方(现代) class School(object): # 构造方法 def __init__(self): self.kongfu = '现代煎饼果子配方' # 擅长做煎饼果子 def make_cake(self): print("按照<%s>制作煎饼果子" % self.kongfu) # 自定义一个徒弟类 class Prentice(Master, School): # 构造方法 def __init__(self): self.kongfu = '猫氏煎饼果子配方' # 擅长做煎饼果子 # 子类继承了父类,子类重写了父类已有的方法 # 重写:子类继承父类,做自己特有的事情 def make_cake(self): print("按照<%s>制作煎饼果子" % self.kongfu) # 自定义对象:大猫 damao = Prentice() # 如果子类的方法名(子类已经重写父类的方法)和父类的相同的时候,默认会使用子类的方法 # 为什么会使用子类的属性(kongfu),子类重写了父类已有的__init__方法 damao.make_cake()
false
39e7e8a9edc732ddf0acc37e078bad6fe72e0060
Joshmannb/6.0001-Introduction-to-Computer-Science-and-Programming-in-Python
/ps4/ps4a.py
2,466
4.25
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. ''' if len(sequence) == 1: # base case: when sequence is singleton, return sequence return sequence else: # recursive step: in each step, each element can be extended inserting new letter in every position ''' recursive step: in each step, each element can be extended inserting new letter in every position example: with element like 'ab', and a new letter 'c', the extended elements are 'cab', 'acb' and 'abc'. 'c' is inserted in the first, the second and the third place of 'ab'. ''' new_sequence = [] for i in get_permutations(sequence[:-1]): # the permutations of sequence without the last element for j in range(len(i)+1): # every element in permutations new_sequence.append(i[:j] + sequence[-1] + i[j:]) # is extended with last element in sequence return new_sequence # if __name__ == '__main__': # if set(['ab', 'ba']) == set(get_permutations('ab')): # print('-'*20) # print('SUCCESS: Permutation of "ab"') # else: # print('FAILURE: get_permutations() is wrong with input "ab"') # if set(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) == set(get_permutations('abc')): # print('-'*20) # print('SUCCESS: Permutation of "abc"') # else: # print('FAILURE: get_permutations() is wrong with input "abc"') # if set(['dabc', 'adbc', 'abdc', 'abcd', 'dacb', 'adcb', 'acdb', 'acbd', 'dbac', 'bdac', 'badc', 'bacd', 'dbca', 'bdca', 'bcda', 'bcad', \ # 'dcab', 'cdab', 'cadb', 'cabd', 'dcba', 'cdba', 'cbda', 'cbad']) == set(get_permutations('abcd')): # print('-'*20) # print('SUCCESS: Permutation of "abcd"') # else: # print('FAILURE: get_permutations() is wrong with input "abcd"')
true
476122fcd33525b838e1f7755e456930c3524c8a
MichaelYoungGo/DataStruction_Python
/Chapter 8/8.5 快速排序(升序).py
863
4.28125
4
# -*- coding: utf-8 -*- # @Time : 2018/12/12 0012 下午 5:47 # @Author : 杨宏兵 # @File : 8.5 快速排序(升序).py # @Software: PyCharm def quick_sort(lists, left, right): if left >= right: return lists key = lists[left] low = left hight = right while left < right: while left < right and lists[right] >= key: right -= 1 lists[left] = lists[right] while left < right and lists[left] <= key: left += 1 lists[right] = lists[left] lists[right] = key quick_sort(lists, low, left-1) quick_sort(lists, left+1, hight) return lists if __name__ == "__main__": lists = [3, 4, 2, 8, 9, 5, 1] print('__________排序前:_____________') print(lists) print('__________排序后:_____________') print(quick_sort(lists, 0, len(lists)-1))
true
f16cccff06380e3e28a2a778bda8e0835b04961b
avi527/Array
/duplicateElements.py
242
4.28125
4
# Python program to print the duplicate elements of an array arr = [1, 2,1, 3, 4, 2, 7, 8, 8, 3]; for i in range(0,len(arr)): for j in range(0,i): #print(arr[i],arr[j]) if arr[i] == arr[j]: print("duplicate array is",arr[i])
true