blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
56e63c8573d5763914cc034fa746d8f591e804d0
hannavw/dsf_exercises
/snack_names_2.py
1,402
4.25
4
# NEW # Make a dictionary: friends = [ { "friend": "Marleen", }, { "friend": "Femke", }, { "friend": "Nienke", }, ] # Ask user for input index = 0 while index < 3: name_length = len(friends[index]["friend"]) friends[index]["length"] = name_length snack = input(f"{friends[index]['friend']}, what's your favourite snack? ") friends[index]["snack"] = snack index = index + 1 index = 0 for item in friends: print(f"{friends[index]['friend']}, you're favourite snack is {friends[index]['snack']}.") print(f"You're name has {friends[index]['length']} characters. ") index = index + 1 # OLD ## Put my friends in a list #friends = ["Marleen", "Femke", "Nienke"] #snacks = [] # ## Ask each friend for snack and add snack to a list #index = 0 #for friend in friends: # snack = input(friend + ", What's your favourite snack? ") # snacks.append(snack) # index = index + 1 # ## Loop through friends and place a snack from the snack-list after each friend. #index = 0 #for friend in friends: # length = len(friends[index]) # snack = snacks[index] # print(friend + ", you're favourite snack is: " + snack + ", and you're name has " + str(length) + " characters.") # index = index + 1
false
e19960770dbbfd23b640cf6812d02e8d87666faf
Kajal2000/Python_Udemy_Course
/ex_7.py
1,628
4.5
4
from collections import OrderedDict # Question 1: Create an empty dictionary called life_book of type OrderedDict. # From Python 3.6 onwards dictionaries maintain the order in which they were # created, however, this coding environment uses an earlier version of Python 3. # Therefore, use OrderedDict in this case, example my_dict = OrderedDict(). # Once created, use the print function to print it. ## Write your code below, 2 lines life_book = OrderedDict() print(life_book) # End question 1 # Question 2: Add the following key, value pair to the life_book dictionary # 'pet' -> 'dog', so the key is pet and the value is dog and then print it. ## Write your code below, 2 lines life_book["pet"]="dog" print(life_book) # End question 2 # Question 3: Add the following key, value pairs to the dictionary # 'second_pet' -> 'cat' # 'first_child' -> 'boy' # 'second_child' -> 'girl' # Once added, print the dictionary. ## Write your code below, variable lines life_book["second_pet"]="cat" life_book["first_child"]="boy" life_book["second_child"]="girl" print(life_book) # End question 3 # Question 4: Update the value associated with key 'pet' to be 'hamster', then # print the dictionary. ## Write your code below, 2 lines life_book["pet"]='hamster' print(life_book) # End question 4 # Question 5: Given the dictionary below, use the items() method and save # the value of all the key value pairs to the variable courses_iterable. my_courses = {'a':'python', 'b':'javascript', 'c':'ruby on rails', 'd':'machine learning', 'e':'ai'} courses_iterable = my_courses.items() ## Write your code below, 1 line # End question 5
true
b824f56dc6fbc4daa9238f9570b69f4690eaf5eb
yiyisf/python_tools
/simple/random_chars.py
573
4.125
4
import random """ 生成随机字符串,至少包含一个大写/小写/数字 """ char_set = "abcdefghijklmnopqrstuvwxyz" upper_char_set = char_set.upper() pw_len = 8 pwlist = [] for i in range(pw_len//3): pwlist.append(char_set[random.randrange(len(char_set))]) pwlist.append(upper_char_set[random.randrange(len(upper_char_set))]) pwlist.append(str(random.randrange(10))) for i in range(pw_len- len(pwlist)): pwlist.append(char_set[random.randrange(len(char_set))]) print("".join(pwlist)) random.shuffle(pwlist) pwstr = "".join(pwlist) print(pwstr)
false
6f0a8f2072e8dec5407499f04777e0d887bbb9ae
duttashi/wrangler
/python-3/experiments/expr_spin_certain_words_in_string.py
2,493
4.34375
4
""" Question: Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test" This question was asked on Codewars website. PROGRAM LOGIC -------------------- Declare two empty lists called list_str_to_words and list_spin_words. split the string into words on basis of spaces and save to a list_str_to_words. Iterate over the list and count the character length of each word. If the word length is greater than 5 then reverse the word and write to list_spin_words if the word length is not greater tha 5, add the word to list_spin_words --------------------- Created on Wed Oct 7 15:35:34 2020 @author: Ashish """ # declare global string variable some_string = "Hey fellow warriors" # declare global lists list_str_to_words, list_spin_words, rev_word_list = [], [], [] print(list_spin_words) # split string into a list of words list_str_to_words = some_string.split() # print(list_str_to_words) # find word length for word in list_str_to_words: # print(str) if(len(word) > 5): # print(word) # add word to list list_spin_words.append(word) else: rev_word = " ".join(reversed(word)) list_spin_words.append(rev_word) str_to_return = " ".join(list_spin_words) # print(list_spin_words) print("Original string is: ", some_string) print("Conditional reversed string is: ", str_to_return) # create a custom function using the above code logic # function will accept a strig as input and return the reverse string def conditional_reverse_string(some_string): list_str_to_words = some_string.split() for word in list_str_to_words: # print(str) if(len(word) > 5): # print(word) # add word to list list_spin_words.append(word) else: rev_word = " ".join(reversed(word)) list_spin_words.append(rev_word) str_to_return = " ".join(list_spin_words) return(str_to_return) # Invoke the function print(conditional_reverse_string(some_string))
true
9123eb5c6bb10745e8d294379fcf2e5f568d2906
cesareferrari/Exercises
/recursion/reverse_string_solution.py
365
4.46875
4
""" Write a function that takes a string and outputs the string reversed. Use recursion (call the function inside the function). """ def reverse_string(string): if len(string) == 0: return string else: return reverse_string(string[1:]) + string[0] string = "Hello, World!" result = reverse_string(string) print(result == "!dlroW ,olleH")
true
6012d6a46724303b50ec846471f5f3c0ffb75bfa
kevfallon97/algorithms_and_data_structures
/array_sequences/anagram_check.py
770
4.15625
4
''' ANAGRAM CHECK PROBLEM STATEMENT Given two strings, check to see if they are anagrams. An anagram is when the two strings can be written using the exact same letters (so you can just rearrange the letters to get a different phrase or word). For example: "public relations" is an anagram of "crap built on lies." "clint eastwood" is an anagram of "old west action" Note: Ignore spaces and capitalization. ''' # SOLUTION 1 def anagram_1(s1, s2): s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() return sorted(s1) == sorted(s2) # SOLUTION 2 def anagram_2(s1, s2): s1 = list(s1.replace(' ', '').lower()) s2 = list(s2.replace(' ', '').lower()) for letter in s1: if letter in s2: s2.remove(letter) else: return False return True
true
b371703aaa423d32be96d8a99047f214619d3276
kevfallon97/algorithms_and_data_structures
/array_sequences/array_pair_sum.py
788
4.25
4
''' ARRAY PAIR SUM PROBLEM STATEMENT Given an integer array, output all the unique pairs that sum to a specific value k. So the input: pair_sum([1,3,2,2], 4) would return 2 pairs: (1,3) (2,2) Note: For testing purposes, return the number of pairs identified ''' # SOLUTION def pair_sum(nums, k): pairs = set() # hold unique pairs in set for i, numA in enumerate(nums[:-1]): # for every elem in list, check for pair with remaining elements for numB in nums[i+1:]: if numA + numB == k: # check if pair sum to k pairs.add((numA, numB)) # add valid pair provided they are unique return pairs # return set of unique pairs nums = [1,3,2,2,2] pairs = pair_sum(nums, 4) print(f"Number of pairs: {len(pairs)}") print(f"Unique pairs: {pairs}")
true
7f15ec5260ba537d9de81a7bb3450feae56eb083
ParaBeIlum/Python_Homeworks
/GeekBrains/Урок 1. Введение в Алгоритмизацию и простые алгоритмы на Python/lesson_1_task_1.py
975
4.25
4
# 1. Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. # Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. operation = input('Введите тип битовой операции (унарные/бинарные): ') if operation == 'унарные': print(f'Побитовый сдвиг числа 5 вправо на 2 знака: 5 >> 2 = {5 >> 2}') print(f'Побитовый сдвиг числа 5 влево на 2 знака: 5 << 2 = {5 << 2}') elif operation == 'бинарные': print(f'Побитовая операция "AND" над числами 5 и 6: 5 & 6 = {5 & 6}') print(f'Побитовая операция "OR" над числами 5 и 6: 5 | 6 = {5 | 6}') print(f'Побитовая операция "XOR" над числами 5 и 6: 5 ^ 6 = {5 ^ 6}')
false
6d1801b115990e2a3ef9dcd8a165121e5b87a5c1
ParaBeIlum/Python_Homeworks
/GeekBrains/Урок 1. Введение в Алгоритмизацию и простые алгоритмы на Python/lesson_1_task_4.py
944
4.1875
4
# 4. Пользователь вводит две буквы. Определить, на каких местах # алфавита они стоят, и сколько между ними находится букв. print("Введите 2 строчных буквы английского алфавита, будет вычислено, какое место " "в алфавите занимает каждая буква и сколько букв находится между ними") letter1 = input("Введите первую букву: ").lower() letter2 = input("Введите вторую букву: ").lower() letter1pos = ord(letter1) - 96 letter2pos = ord(letter2) - 96 posDiff = abs(letter1pos - letter2pos) - 1 print(f'Буква "{letter1}" занимает место {letter1pos}\n' f'Буква "{letter2}" занимает место {letter2pos}\n' f'Между ними букв: {posDiff}')
false
04e5801a64567b5278cdb6a31b86f5d9992f74fe
aluisq/Python
/estrutura_repeticao/ex13.py
379
4.15625
4
numero = abs(int(input("Digite um número: "))) while numero % 2 != 0: print(""" __________________________ Número inválido __________________________ """) numero = abs(int(input("Digite um número: "))) if numero % 2 == 0: for i in range(0,numero + 2, 2): print(i) else: print("Algo está errado.")
false
ae005f3eee91d52dac933f43a6cd9ed9afdd364e
LibraZYJ/python-learn
/基本语法/Day14/元组.py
1,014
4.21875
4
""" Python中的元祖与列表类型也是一种容器数据类型,可以用一个变量(对象)来存储多个数据, 不同之处在于元祖的元素不能修改,在前面的代码中我们已经不止一次使用过元祖了,顾名思义 我们把多个元素组合到一起就形成了一个元祖,所以它和列表一样可以保存多条数据。 @Date 2020.4.7 """ # 定义元祖 t = ('Zhao', 20, True, '南京') print(t) # 获取元祖中的元素 print(t[0]) print(t[3]) # 遍历元祖中的值 for member in t: print(member) # 重新给元祖赋值 # 发生异常: TypeError # 变量t重新引用了新的元祖原来的元祖被垃圾回收 t = ('QQ', 22, True, '江苏南京') print(t) # 将元祖转换成列表 person = list(t) print(person) # 列表是可以修改它的元素的 person[0] = 'Li' person[1] = 25 print(person) # 将列表转换成元祖 print(tuple(person)) fruits_list = ['apple', 'banana', 'orange'] fruits_tuple = tuple(fruits_list) print(fruits_tuple)
false
2dbc889c1895c3e7f030cce40d0157ca0ece2ed0
eduardknezovic/chess-blindfold-trainer
/app/main.py
1,169
4.34375
4
""" In this we are to create an app that will be used to check our knowledge of square colors of the chessboard. """ import random def get_y_or_n(): value = input("Leave empty if white, enter anything for black:") if value == "": return True else: return False def generate_set_of_squares(): result = [] is_white = True for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']: is_white = not is_white for number in range(1, 9): square = (letter, number) item = (square, is_white) result.append(item) is_white = not is_white return result def main(): all_squares = generate_set_of_squares() result_to_text = {True: "WHITE", False: "BLACK"} user_outcome_to_text = {True: "WIN!", False: "FAIL!"} while True: square, is_white = random.choice(all_squares) string_square = square[0] + str(square[1]) print(string_square) user_is_white = get_y_or_n() print(f"{user_outcome_to_text[user_is_white==is_white]} The square {string_square} is {result_to_text[is_white]}") if __name__ == "__main__": main()
true
6069ced4148ac08f8c362dc32f7bc6ef5e370eba
Suyen-Shrestha/Python-Assignment-II
/Solution9.py
728
4.125
4
def binary_search(sequence,item): lower = 0 upper = len(sequence) - 1 while lower <= upper: mid_index = (lower+upper) // 2 if sequence[mid_index] == item: return mid_index elif sequence[mid_index] < item: lower = mid_index + 1 else: upper = mid_index - 1 return -1 sample_li = [5,9,6,23,54,68,17,32] print(f'The sample list: {sample_li}') sample_li.sort() # sorting is require for performing binary search. print(f'The list after sorting: {sample_li}') print(f'The index of "17" in sorted list using binary search: {binary_search(sample_li,17)}') print(f'The index of "2" in sorted list using binary search: {binary_search(sample_li,2)}')
true
779abb883726bc1adfb10aef750f7865c144f14b
James-E-Sullivan/BU-MET-CS521
/Module-4/HW_10.1_Sullivan_James.py
2,001
4.25
4
""" 10.1 (Assign grades) Write a program that reads a list of scores and then assigns grades based on the following scheme: A if score >= best - 10 B if score >= best - 20 C if score >= best - 30 D if score >= best - 40 F otherwise """ def grade_score(student_score, max_score): """ Assigns a grade based on a student's score and the maximum score :param student_score: The student score(int or float) :param max_score: The maximum score (int or float) :return student_grade: """ if student_score >= max_score - 10: student_grade = 'A' elif student_score >= max_score - 20: student_grade = 'B' elif student_score >= max_score - 30: student_grade = 'C' elif student_score >= max_score - 40: student_grade = 'D' else: student_grade = 'F' return student_grade def find_best_score(input_scores): """ Evaluates user input scores and returns the greatest score :param input_scores: List of scores (integers) :return best_score: Returns greatest score in the list """ # Starts best score at 0. Assumes no negative scores are possible. best_score = 0 # Iterates through scores and updates best_score if a better score found for student_score in input_scores: new_score = student_score if new_score > best_score: best_score = new_score return best_score while True: try: score_list = [int(input_score) for input_score in input( 'Enter scores (integers separated by spaces): ').split()] student_number = 0 for score in score_list: grade = grade_score(score, find_best_score(score_list)) print('Student', student_number, 'score is', score, 'and grade is', grade) student_number += 1 break # User prompted again if they enter invalid input except ValueError: print("Could not convert input to integer. Please try again.")
true
00c33f31786aecdb7653ad1bf73bcc3d59934bec
James-E-Sullivan/BU-MET-CS521
/Module-3/HW_5.1_Sullivan_James.py
1,347
4.15625
4
""" (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeroes). Your program ends with the input '0'. Display the average as a floating-point number. """ positives = 0 negatives = 0 count = 0 total = 0 while True: # User prompted for integer user_int = eval(input("Enter an integer, the input ends if it is 0: ")) # If user enters 0 before entering an integer, user prompted again if user_int == 0 and count == 0: print("You didn't enter any number") continue # If user enters 0 after entering at least 1 int, loop exits elif user_int == 0 and count > 0: break # If user enters int, count incremented, int added to total, and # positives or negatives incremented, depending on value. else: count += 1 total += user_int if user_int > 0: positives += 1 elif user_int < 0: negatives += 1 # Prints positives, negatives, total, and average values print("The number of positives is", positives) print("The number of negatives is", negatives) print("The total is", total) print("The average is", total / count)
true
8e3cd86bbb8bd9b80c248992fc9a30c2f13a16f3
chriscent27/calculator
/calculator.py
740
4.1875
4
def addition(num1, num2): return num1 + num2 def subtraction(num1, num2): return num1 - num2 def multiplication(num1, num2): return num1 * num2 def division(num1, num2): return num1 / num2 def Calculate(): num1, operation, num2 = (input("Enter operation eg(2 + 5): ").split()) num1 = int(num1) num2 = int(num2) if(operation == '+'): result = addition(num1, num2) elif(operation == '-'): result = subtraction(num1, num2) elif(operation == '*'): result = multiplication(num1, num2) elif(operation == '/'): result = division(num1, num2) else: result = 'INVALID CHOICE' print("Result is: ", result) #tes if __name__ == '__main__': Calculate()
false
0a081246bfd34447d50703260786251be84cd860
kash991064/pythontest1
/akash8.py
499
4.125
4
#set---is a collection of data #s1 = set() #print(type(s1)) #s_from_list =set([1,2,3,4]) #print(s_from_list) #print(type(s_from_list)) # or #list1 = (110,232,363,414,525) #list_set1 = set(list1) #print(list_set1) # how to add elements in set--(set add only unique value) s1 = set() s1.add(1) s1.add(23) print(s1) # another example s1 = set() s1.add(1) s1.add(23) s2 = s1.union({23,45,66,77}) print(s1,s2) # intersction s1 = set() s1.add(1) s2 = s1.intersection({1,45,66,77}) print(s1,s2)
true
00a077ed9b2ec9c41824738cb088f0d3455715b8
ibnahmadCoded/how_to_think_like_a_computer_scientist_Chapter_11
/collission_checker.py
2,282
4.1875
4
from study import * class Rectangle: """ A class to manufacture rectangle objects """ def __init__(self, posn, w, h): """ Initialize rectangle at posn, with width w, height h """ self.corner = posn self.width = w self.height = h def __str__(self): return "({0}, {1}, {2})".format(self.corner, self.width, self.height) def grow(self, delta_width, delta_height): """ Grow (or shrink) this object by the deltas """ self.width += delta_width self.height += delta_height def move(self, dx, dy): """ Move this object by the deltas """ self.corner.x += dx self.corner.y += dy def area(self): """Returns area of rectangle object""" return self.width * self.height def perimeter(self): """Returns perimeter of rectangle object""" return 2 * (self.width + self.height) def flip(self): """swaps the height and the width of the object""" w = self.width self.width = self.height self.height = w def contains(self, point): a = point.x >= self.corner.x and point.x < self.width b = point.y >= self.corner.y and point.y < self.height return a and b def same_coordinates(self, rectangle): return (self.corner.x == rectangle.corner.x) and (self.corner.y == rectangle.corner.y) def get_all_points(self): """returns all points in rectangle object""" points = [] a = list(range(self.corner.x, self.width + 1)) b = list(range(self.corner.y, self.height + 1)) for i in a: for j in b: p = (i, j) points.append(p) return points def collision(self, rectangle): """checks if the object collides with another rectangle""" if self.same_coordinates(rectangle): return True else: points = rectangle.get_all_points() #gets all points in d rectangle for point in points: if self.contains(point): #if point falls in d object, there's collision return True return False
false
51655d62767619c3c32bd5015e9eeb655481088e
mh-yesilyurt/globalaihub_
/last_homework.py
1,463
4.15625
4
for i in range (0,3): name=input("Enter your Name and Surname: ") if name=="Hakan Yesilyurt": print("Welcome") break elif i==3 and name!="Hakan Yesilyurt": print("Please try again later.") exit() courses=[] for k in range(0,5): lesson=input("Enter the lesson you want to take (if you don't want to take more lessons, press Q): ") if lesson.upper()=="Q": break else: courses.append(lesson) if len(courses)<3: print("You failed in a class.") chosen_course=input("Enter the course you want to take exams: ") midterm_grade=input("Enter your Midterm Grade: ") final_grade=input("Enter your Final Grade: ") project_grade=input("Enter your Project Grade: ") course={"Course Name":chosen_course,"Midterm":midterm_grade,"Final":final_grade,"Project":project_grade} total_grade=int(course["Midterm"])*0.3+int(course["Final"])*0.5+int(course["Project"])*0.2 if total_grade>= 90 : print(f"You got AA from \"{chosen_course}\" course") elif total_grade>=70 and total_grade<90: print(f"You got BB from \"{chosen_course}\" course") elif total_grade>=50 and total_grade<70: print(f"You got CC from \"{chosen_course}\" course") elif total_grade>=30 and total_grade<50: print(f"You got CC from \"{chosen_course}\" course") elif total_grade<30: print(f"You got FF from \"{chosen_course}\" course. You have failed, please work harder next time.")
true
847730cc2367f1f94934d4ed241f3a7deea00c0d
JinbeiZame/Study-python-language
/dictionary.py
2,265
4.4375
4
"""Dictionary เก็บข้อมูลได้หลาย ๆ ค่าในตัวแปรเดียวกัน แต่คุณสมบัติพิเศษของดิกชันนารีคือมีข้อมูลตั้งแต่ 2 ค่าขึ้นไปและมีความสัมพันธ์กัน การประกาศตัวแปร การเพิ่มข้อมูล การแสดงผลข้อมูล การกำหนดตำแหน่งที่ต้องการ และการสลับตำแหน่งคีย์ของข้อมูล """ #INSERT people = {'boy':'gonge','girl':'minnie','animal':'dog','natural':'rain'} people['socialnetwork'] = 'facebook' #added #print(people) #result run after : {'boy': 'gonge', 'girl': 'minnie', 'animal': 'dog', 'natural': 'rain', 'socialnetwork': 'facebook'} #UPDATE people['animal'] = 'rabbit' #updated #print(people) #result run after : {'boy': 'gonge', 'girl': 'minnie', 'animal': 'rabbit', 'natural': 'rain', 'socialnetwork': 'facebook'} #DISPLAY DATA IN DICTIONARY company = {'silicon valley':['facebook','yahoo','microsoft','google','apple','instagram','happy'],'facebook':'mark suckerberg','apple':'stave job'} #print(company.keys()) #result run after : dict_keys(['silicon valley', 'facebook', 'apple']) #print(company.values()) #result run after : dict_values([['facebook', 'yahoo', 'microsoft', 'google', 'apple', 'instagram', 'happy'], 'mark suckerberg', 'stave job']) #print(company.items()) #result run after : dict_items([('silicon valley', ['facebook', 'yahoo', 'microsoft', 'google', 'apple', 'instagram', 'happy']), ('facebook', 'mark suckerberg'), ('apple', 'stave job')]) # print(company) #result run after : {'silicon valley': ['facebook', 'yahoo', 'microsoft', 'google', 'apple', 'instagram', 'happy'], 'facebook': 'mark suckerberg', 'apple': 'stave job'} day = {'1':'monday','2':'tuesday','3':'wednesday','4':'thursday','5':'friday','6':'saturday','7':'sunday'} number = day.keys() day_pop = day.pop('2') print(day_pop) #delete '2':'tuesday' print(day) #result run after : {'1': 'monday', '3': 'wednesday', '4': 'thursday', '5': 'friday', '6': 'saturday', '7': 'sunday'}
false
b876d58642577425d6049f1cb02dd95ff8decd99
djtiedemann/riddles
/spheres-weight/spheresWeight.py
2,640
4.15625
4
# https://fivethirtyeight.com/features/can-you-flip-the-magic-coin/ # the general idea is to break the spheres up into 3 groups and make sure their weights are the same. # say we have n spheres. we'll create an array of size n that's made up of 1, 2, 3. each index represents the nth sphere and the value represents the grouping: # so say we have the following # sphere number: 123456 # 122322 # # this represents the following division: # 1: 1 # 2: 2, 3, 5, 6 # 3: 4 # # this is a valid solution if 1^3 = 2^3 + 3^3 + 5^3 + 6^3 = 4^3 # # # so for each number of spheres, we generate all valid arrays of size n made up of 1,2,3. we then test each of those arrays to see if the combination creates a split where the sum # is equal. if so, that's the right number class SphereSolver: def divideSpheres(self, numSpheres): print('checking: ' + str(numSpheres)) grouping = [] for i in range(0, numSpheres): grouping.append(1) isLastGrouping = False while(not isLastGrouping): isValid = self.validateGrouping(grouping) if(isValid): print('winner') (grouping, isLastGrouping) = self.generateNextGrouping(grouping) # generate the next valid grouping. basically we search from the right to find the first value that isn't a 3, increment that value by 1 and set all values to the right equal to 1 # returns false if it isn't the last grouping and true if it is def generateNextGrouping(self, grouping): #print(grouping) # we can always assign the first sphere to group 1 without changing the problem, so we can go to 0 instead of -1 for index in range(len(grouping) - 1, 0, -1): if(grouping[index] == 3): continue if(grouping[index] == 2): grouping[index] = 3 if(grouping[index] == 1): grouping[index] = 2 for i in range(index+1, len(grouping)): grouping[i] = 1 return (grouping, False) return (grouping, True) # a grouping is valid if all of the spheres in each grouping have the same weight def validateGrouping(self, grouping): sum1 = 0 sum2 = 0 sum3 = 0 for i in range(0, len(grouping)): if(grouping[i] == 1): sum1 = sum1 + (i+1)**3 if(grouping[i] == 2): sum2 = sum2 + (i+1)**3 if(grouping[i] == 3): sum3 = sum3 + (i+1)**3 #print('checking ' + str(grouping)) #print('sum 1: ' + str(sum1)) #print('sum 2: ' + str(sum2)) #print('sum 3: ' + str(sum3)) return sum1 == sum2 and sum2 == sum3 sum = 0 solver = SphereSolver() for i in range (18, 19): # the weight of the spheres is proportional to the volume which is proportional to the radius cubed sum = sum + i**3 if sum % 3 == 0: solver.divideSpheres(i)
true
1c5dbc3157d316e4c59177ed1004b4d71e1ed12d
partho-maple/coding-interview-gym
/leetcode.com/python/148_Sort_List.py
1,616
4.25
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Recursive approach using merge sort. Time O(nlogn). Space O(n) since it's recursive approach. To make it iterative, implement the merge sort iteratively class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head fastNode, slowNode = head.next, head # divide the list into two parts by fast-slow pointer technique while fastNode and fastNode.next: fastNode = fastNode.next.next slowNode = slowNode.next secondHalf = slowNode.next slowNode.next = None # cut down the first part leftHalf = self.sortList(head) rightHalf = self.sortList(secondHalf) return self.mergeTwoLists(leftHalf, rightHalf) def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1 or not l2: return l1 if l1 else l2 p1, p2, p1Prev = l1, l2, None while p1 and p2: if p1.val < p2.val: p1Prev = p1 p1 = p1.next else: if p1Prev: p1Prev.next = p2 p1Prev = p2 p2 = p2.next p1Prev.next = p1 if not p1: p1Prev.next = p2 return l1 if l1.val < l2.val else l2
true
6f0762bdd72bf42621795deb59ae70fa4902914b
andre-Hazim/Unit_3-03
/rock_paper_scissors.py
1,991
4.125
4
# created by Andre # created on october 3, 2017 # created for isc3u # created for unit 3-03 daily assignment # a rock paper scisoors program import ui from numpy import random def rock_touch_up_inside(sender): #This checks the number of students entered versus the constant (25 stuents) computer_choice = random.randint(1,3) #process if computer_choice == 1: #output view['computers_choice_label'].text = "Rock" view['who_won_label'].text = "It's a tie" elif computer_choice == 2: view['computers_choice_label'].text = "Paper" view['who_won_label'].text = "You lost!" elif computer_choice == 3: view['computers_choice_label'].text = "Scissor" view['who_won_label'].text = "You won!" def paper_touch_up_inside(sender): #This checks the number of students entered versus the constant (25 stuents) computer_choice = random.randint(1,3) #process if computer_choice == 1: #output view['computers_choice_label'].text = "Rock" view['who_won_label'].text = "You won!" elif computer_choice == 2: view['computers_choice_label'].text = "Paper" view['who_won_label'].text = "It's a tie" elif computer_choice == 3: view['computers_choice_label'].text = "Scissor" view['who_won_label'].text = "You lost!" def scissor_touch_up_inside(sender): #This checks the number of students entered versus the constant (25 stuents) computer_choice = random.randint(1,3) #process if computer_choice == 1: #output view['computers_choice_label'].text = "Rock" view['who_won_label'].text = "You lost!" elif computer_choice == 2: view['computers_choice_label'].text = "Paper" view['who_won_label'].text = "You won!" elif computer_choice == 3: view['computers_choice_label'].text = "Scissor" view['who_won_label'].text = "It's a tie" view = ui.load_view() view.present('sheet')
true
552c18b57ebb23e689c9307c986ea1b2bad01fdc
ylana-mogylova/Python
/Examples/palidrome.py
480
4.34375
4
# if word is palindrome input_word = "waabbcbbaaw" def palindrome(input_string): revert_string = "" index = len(input_string) - 1 while index >= 0: revert_string += input_string[index] index -= 1 if input_string == revert_string: return True else: return False if __name__ == "__main__": if palindrome(input_word): print("word is palindrome") else: print("word is not palindrome")
false
57f37f19ad326a3af0fe1151ccb68e4d5d2a0f1f
ylana-mogylova/Python
/Examples/number_occur_substr_in_str.py
710
4.21875
4
""" Write a function to count how many times the substring appears in the larger String. """ large_string = "abcpotqwrpot" substring = "pot" def count_substr_occur(input_string, input_substring): counter = 0 start_index = 0 flag = True while flag: find_index = input_string.find(input_substring, start_index) if find_index == -1: flag = False else: counter += 1 start_index = find_index + len(input_substring) return counter if __name__ == "__main__": print("Substring %s appears %s number(s) in the string %s" % ( substring, count_substr_occur(large_string, substring), large_string))
true
5e0acd1f29a4f27e94bc17199f9746c294832d17
delisco/algorithm
/sorts/bubble_sort.py
1,177
4.15625
4
''' @__date__ = 2020.02.29 @author = DeLi ''' import time def bubble_sort(a_list): """ Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([]) [] >>> bubble_sort([-23, 0, 6, -4, 34]) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True """ list_length = len(a_list) for i in range(list_length-1): swapped = False for j in range(list_length-1-i): if a_list[j] > a_list[j+1]: swapped = True a_list[j], a_list[j+1] = a_list[j+1], a_list[j] # Show the sorting process # print(a_list) if not swapped: break # Stop iteration if the collection is sorted. return a_list if __name__ == "__main__": start = time.process_time() print(bubble_sort([3, 6, 7, 1])) print(f"Processing time: {time.process_time() - start}")
true
8686d027c1526889ee5d3bc739cc4a7f4ad44e28
eniskurban98/Python-Projects
/fibonaccinumbers.py
774
4.1875
4
# Fibonacci numbers while True: user_input = input('How many steps do you want for create fibonacci series? Type exit to stop:> ') if user_input == 'exit': print('You are quitting from the fibonacci numbers program...') break else: try: a = 0 b = 1 user_input = int(user_input) fibonaccinumlist = [] if user_input == 0 or user_input < 0: print('Please enter a positive number') else: for i in range(user_input): fibonaccinumlist.append(a) a, b = b, a + b print(f'For first {user_input} step, fibonacci numbers are: {fibonaccinumlist}') except ValueError: print('Please provide a valid number.')
true
bce23272f3089164b2737adc3ae19e711c681242
debbycosoi/Activities_Intro_to_Python
/Activity8-MarielCosoi.py
596
4.375
4
# In this file you are to: # Write a Program to check the greatest among 3 numbers. # Write a Program to imitate a Traffic light. Think about the information you need to generate to # make your program mimic the real world. a=1 b=7 c=3 if (a>b): print("A is the greatest number") elif(b>c): print("B is the greatest number") else: print("C is the greatest number") green = "green" yellow = "yellow" red = "red" light = green print(f"the light is {light} so you have to") if(light == green): print("go") elif(light == yellow): print("slow down") else: print("stop")
true
ff642a983c6b0b05b6ee01647ad0b27cba2a4032
pinaxtech/hellocode
/alphabet.py
201
4.15625
4
n = input("Enter a character: ") if(n=='A' or n=='a' or n=='E' or n =='e' or n=='I' or n=='i' or n=='O' or n=='o' or n=='U' or n=='u'): print(n, "is a Vowel") else: print(n, "is a Consonant")
false
c6dd39f9a500b01dcb8afdebf50d7d2e78c242c2
ethender/pythonlearn
/Lectures/Lecture3/lecture.py
1,325
4.15625
4
##x = int(raw_input('Enter an integer')) ##ans = 0 ##while ans*ans*ans < abs(x): ## ans = ans + 1 ## #print 'Current guess =', ans ## ##if ans*ans*ans != abs(x): ## print x, 'is not a perfect cube' ##else: ## if x < 0: ## ans = -ans ## print 'Cube root of '+str(x)+' is '+str(ans) ###Find The cube root of a perfect cube ## ##x = int(raw_input('Enter an integer: ')) ##for ans in range(0, abs(x)+1): ## if ans**3 == abs(x): ## break ##if ans**3 != abs(x): ## print x, 'is not perfect cube' ##else: ## if x < 0: ## ans = -ans ## print 'Cube root of '+str(x)+' is '+str(ans) #Approximation ##x = 25 ##epsilons = 0.01 ##numGuesses = 0 ##ans = 0.1 ##while (abs(ans**2) = x) >= epsilons and ans <= x: ## ans += 0.00001 ## numGuesses += 1 ##print 'numGuesses =', numGuesses ##if abs(ans**2 = x) >= epsilons: ## print 'Failed on square root of ',x ##else: ## print ans, 'is close to square root of ',x x = 12345 epsilon = 0.01 numGuesses = 0 low = 0.0 high = x ans = (high + low )/2.0 while (abs(ans**2 = x) >= epsilon and ans <= x): #print low , high, ans numGuesses += 1 if ans**2 < x: low = ans else: high = ans ans = (high + low)/2.0 #print 'numguesses =', numGuesses print ans, 'is close to square root of ',x
false
989b4ee75c7584e4b59fcb0ac42e51c2de51b532
Stevemz09/Hello-World
/Number digits.py
781
4.25
4
''' Find the number of digits in a given integer ''' num = int(input("Enter the number :")) # Enter the number using keyboard div = 1 # Start with 1 the first power of 10 in the integer division while num// 10**div != 0: # Check the condition: is the quotient of the # integer division num divided by 10 to the power of div # while loop it keeps executing the loop body as long as the condition is true. # integer division num divided by 10 to the power of div # not equal to zero? div = div + 1 # If yes execute the loop body print("the number :", num, "has ", div, "digits") # if no, get out of the loop and print # the message
true
0c62653ae1900ca3497a3053b44cc220622aca9f
Stevemz09/Hello-World
/prime_num.py
350
4.3125
4
''' Find whether a given number is PRIME using a for loop ''' num = int(input("Enter your number :")) for divisor in range(2, num): print(divisor) # if num % divisor == 0: # print(divisor ) # print( "The number is not prime, it has a divisor: ", divisor) # exit() #print("The number is prime") #exit()
true
4e6a83486a7803b9d52cdd5d3872cb99c87095c9
nmanley73/Tasks
/Task2_bmi.py
268
4.4375
4
# Program calculates somebody's BMI # Create Variables and input values Weight = float(input("Enter weight:")) Height = float(input("Enter height:")) # Calculate BMI BMI = Weight / ((Height/100)**2) # Print out result print("BMI is", round(BMI,2), "metres squared")
true
b5786eba9fefaea6b43d2389d93dba0f899c8802
farukara/Automate-Boring-Stuff
/files/Ch7 regex version of strip.py
751
4.4375
4
#! Python3 # Regex version of strip. import re def regex_ver_strip(text, remove=''): """ strips optional remove (defaults space)from text using regex""" if remove: extras = re.compile(r'^(%s*)'%remove) mo = extras.sub('', text) mo = mo[::-1] mo = extras.sub('', mo) mo = mo[::-1] return mo else: spaces = re.compile(r'^(?: *)(.+)') mo = spaces.findall(text) mo = mo[0][::-1] mo = spaces.findall(mo) mo = mo[0][::-1] return mo if __name__ == '__main__': text = ' $ Hello World 12 ' print(regex_ver_strip(text)) # strip spaces text = 'tt$ Hello World 12tt' print(regex_ver_strip(text, remove='tt')) # strip tt
false
fead3b2d65931a5e6a7bbb648436f0c053339f66
gospodenkods/python_basic
/homeworks/les1/task1.py
803
4.4375
4
""" 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. """ firs_variable = "Sunday" next_variable = "Moscow" last_variable = 10 print(firs_variable, 'Day of week') print(next_variable, 'City where you live') print(last_variable, 'Your favorite number') firs_variable = input('What day is today?\n') next_variable = input('What city do you live in?\n') last_variable = input('What you favorite number?\n') summary_line = f"Day of week '{firs_variable}' city where you live '{next_variable}' \ Your favorite number '{last_variable}'" print(summary_line)
false
bc845943c04f4a7572eae88f0a89163e7cafd854
shinoherrera/ML_project
/Decisiontree.py
2,742
4.375
4
#Here we call the essential libraries to help with our ML Algorithm import matplotlib.pyplot as plt #necessary to help with our data visualization import pandas as pd #help with working on multi-dimensional arrays from sklearn.tree import DecisionTreeClassifier #the main libaries that will help with the learning/training from sklearn import tree #using this to build a decision tree based on the code data_set = pd.read_csv("test_data/train.csv") #read the data set by giving the function a path to where it is clf =DecisionTreeClassifier() #this is our classifier that'll take in data and perform the #training dataset x_train = data_set.iloc[0:21000,1:].values #will use the first 21k rows, and will not use the first column because it includes the answer train_label = data_set.iloc[0:21000,0].values #train label is what our x_train will be comparing itself to clf.fit(x_train,train_label) #now we call the DTC function and fit the x_train and train_label to it #testing data x_test = data_set.iloc[21000:,1:] #Now we will use the rest of the rows of data to test our training model actual_label = data_set.iloc[21000:,0].values #give it some information to check itself with Pred=clf.predict(x_test) #Now we want to start the prediction by using x_test count=0 #initializing a counter in order to be able to calculate accuracy for i in range(0,21000): #we start the for-loop and tell it how many times to run count +=1 if Pred[i] == actual_label[i] else 0 # will add 1 to the count if it guesses right,wont add if wrong print("Accuracy= ",(count/21000)*100) #print statement that'll print after each iteration or about 21000 times fig = plt.figure(figsize=(10,10)) #plt.fig will call on the matplotlib to construct a decision tree figure of the code above F = tree.plot_tree(clf,filled=True) #clf is the classifier and the filled statement just assigns different colors to different nodes fig.savefig("decision_tree.png") #save the figure as a png named decision_tree that is included in the report text_representation = tree.export_text(clf) #just some extra way of visualize what each of the nodes say though it does get really messy and hard to follow print(text_representation)
true
ada91a70d3d157f9e4ac4b629a87e5200392629f
MEENUVIJAYAN/python
/python lab 3/logical.py
236
4.34375
4
#Program to perform logical operations x =True y =True print(x and not y) print(not x and y) print(not x and not y) print(x or not y) print(not x or y) print(not x or not y) print("Precedence order is") print("Not->And->Or")
true
274da6fa73ea02888de1175d2f706f46bbbf7e57
William-cordingley/CP1404
/Lectures/Lecture_04/lecture.py
233
4.21875
4
""" How many Vowels in a Name or String that has been inputted """ name = input("Name: ") vowels = "AEIOUaeiou" count = 0 for i in name: if i in vowels: count += 1 print("There is {} vowels in {} ".format(count, name))
true
8a3f4d95e5e7034409f7d519d6f166036a24838b
bakerb0473/cti110
/P3HW2_SoftwareSales_Baker.py
886
4.125
4
# CTI-110 # P3H2 - Software Sales # Bonnita Baker # 6/24/2018 # This program will ask the user to enter the number of packages purchased # it will display the amount of the discount # and the total purchase cost with the discount applied # If the quantity is less than 10 there is no discount package = 99 quantity = float(input("How many packages are your ordering? ")) if quantity < 10: print("Total: $ ", package) if quantity >= 10 and quantity <= 19: print("Total: $ ", (package * quantity) - (package * quantity) * .10) if quantity >= 20 and quantity <= 49: print("Total: $ ", (package * quantity) - (package * quantity) * .20) if quantity >= 50 and quantity <= 99: print("Total: $ ", (package * quantity) - (package * quantity) * .30) if quantity >= 100: print("Total: $ ", (package * quantity) - (package * quantity) * .40)
true
821499c9657944823af32525f42ec3e4a1387a77
Coralma/python-learning
/basic/basicIterator.py
1,552
4.375
4
# 迭代器 # 迭代是Python最强大的功能之一,是访问集合元素的一种方式。。 # 迭代器是一个可以记住遍历的位置的对象。 # 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。 # 迭代器有两个基本的方法:iter() 和 next()。 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 for x in it: print (x, end=" ") print(); # next() 函数: import sys # 引入 sys 模块 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 while True: try: print(next(it)) except StopIteration: sys.exit() # 生成器 # 在 Python 中,使用了 yield 的函数被称为生成器(generator)。 # 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。 # 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回yield的值。并在下一次执行 next()方法时从当前位置继续运行。 # 以下实例使用 yield 实现斐波那契数列: def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit()
false
7e3eeba883995a42a99a18df17d87ba8d94a6799
hkhurram147/ESC180
/lab02.py
2,272
4.34375
4
# Lab 2: Calculator current_value = 0 operations = [] # Lab 3 def get_current_value(): pass # Problem 2: def display_current_value(): global current_value print("Current value: " + str(current_value)) def add_to_operations(): global current_value, operations operations.append(current_value) if len(operations) >= 3: del operations[0] # Problem 3: Addition def add(to_add): global current_value, operations # global is used to update the current_value, # if not used, the updates would only be local to this function current_value += to_add add_to_operations() def subtract(to_subtract): global current_value, operations current_value -= to_subtract add_to_operations() # Problem 5: Multiplication and Division def mult(to_multiply): global current_value, operations current_value *= to_multiply add_to_operations() def divide(to_divide): global current_value, operations if (to_divide != 0): current_value /= to_divide add_to_operations() # Problems with the division function: # It may lead to floats that are imprecise saved = "" # Problem 6: Memory and Recall def memory(): # saves the current value global current_value, saved saved = str(current_value) def recall(): # restores the saved value global current_value, saved current_value = int(saved) # Problem 7: Undo def undo(): """restores the previous value that appeared on screen before the current value""" # pressing undo twice restores the original value global current_value, operations # solution: since there are only 2 values stored, swap operations[0], operations[1] = operations[1], operations[0] current_value = operations[-1] # global variable representing the current file as main if __name__ == "__main__": print("Welcome to the calculator program") display_current_value() # 0 add(5) # 5 subtract(2) display_current_value() # 3 undo() display_current_value() # 5 undo() display_current_value() # 3 mult(10) display_current_value() # 30 undo() undo() display_current_value() # 30 undo() undo() undo() display_current_value() # 3
true
52fa8fa88a6728dd8c377c0074caee5f57861f59
tcu93/py4e_exercises
/9dicts01.py
760
4.1875
4
'''Suppose you are given a string and you want to count how many times each letter appears.''' word1 = 'brontosaurus' dict1 = dict() # Create dict from string (word1) for c in word1: # for c'th element of word1 dict1[c] = dict1.get(c, 0) + 1 # c'th elem of dict1 = value of that elem + 1 print(dict1) print(dict1['r']) ''' THIS ALSO WORKS for x in word1: y = x.split() if x not in dict1: # confusing -- x acts as both letter & index at same time dict1[x] = 1 # this is value, not key else: dict1[x] += 1 ''' # Check for presence of particular key value if 'b' in dict1: print('true') # Create list of dict1 keys k1 = list(dict1.keys()) print(k1) # Create list of dict1 values v1 = list(dict1.values()) print(v1)
true
9cdbe833a1f8786cbc027acba3099a5b9338be08
tcu93/py4e_exercises
/2vars3.py
341
4.1875
4
'''Exercise 3 Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25 ''' crt_product = lambda arg1, arg2: arg1 * arg2 hours = int(input('Enter Hours: ')) rate = int(input('Rate: ')) #pay = hours * rate #print(f'Pay: {pay}') print('Pay:', crt_product(hours, rate))
true
11cbeb799bdf0b595f369bc1db8096dae310fb2a
Jemmy-Hong/myPython
/pyPro/cn/py/chap3/cars.py
842
4.40625
4
#sort排序,永久改变列表 # cars = ['bmw', 'audi', 'toyota', 'subaru'] # print(cars) # cars.sort() # print(cars) # cars.sort(reverse=True) # print(cars) #sorted函数,临时排序,不改变列表元素位置,同样有reverse=True参数 # cars = ['bmw', 'audi', 'toyota', 'subaru' ] # print("Here is the original list:") # print(cars) # # print("\nHere is the sorted list:") # print(sorted(cars)) # # print("\nHere is the original list again:") # print(cars) #倒着打印列表(永久性改变列表) # cars = ['bmw', 'audi', 'toyota', 'subaru'] # print(cars) # # cars.reverse() # print(cars) #确定列表的长度 # cars = ['bmw', 'audi', 'toyota', 'subaru'] # print(len(cars)) #获取列表的最后一个元素 motorcycles = ['honda', 'yamaha', 'suzuki' ] print(motorcycles[-1]) motorcycles = [] print(motorcycles[-1])
false
01269ea0a69f1fd48fefc05c429edb7641d95e61
Shadowztorm/python-practice
/listprac.py
1,567
4.21875
4
# 1. Let us say your expense for every month are listed below, # 1. January - 2200 # 2. February - 2350 # 3. March - 2600 # 4. April - 2130 # 5. May - 2190 # # Create a list to store these monthly expenses and using that find out, # # 1. In Feb, how many dollars you spent extra compare to January? # 2. Find out your total expense in first quarter (first three months) of the year. # 3. Find out if you spent exactly 2000 dollars in any month # 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list # 5. You returned an item that you bought in a month of April and # got a refund of 200$. Make a correction to your monthly expense list # based on this exp=[2200,2350,2600,2130,2000] # 1. In Feb, how many dollars you spent extra compare to January? print("In Feb money spent compared to january is ", exp[1]-exp[0],"$") # 2. Find out your total expense in first quarter (first three months) of the year. print("Total expense in first quarter is ", sum(exp[0:3])) # 3. Find out if you spent exactly 2000 dollars in any month print("Did I spent 2000$ in any month? ", 2000 in exp) # 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list exp.append(1980) print("June month expense",exp) # 5. You returned an item that you bought in a month of April and # got a refund of 200$. Make a correction to your monthly expense list # based on this exp[3]=exp[3]-200 print("Returned money of april and got discount",exp)
true
f4ff2a3508fc767eac67126559a03fd239c82b63
barawalojas/Python-tutorial
/Season 02 - Python Fundamentals/Episode 16 - Functions.py
1,032
4.59375
5
# Functions """ We Studied functions like zip, print, enumerate, etc.., but here we'll study how to define your own function. """ """ def is a python keyword used for defining functions. # def greet(): here, greet() is the function, we've defined and (:) colon is to be followed as of syntax.. """ def greet(): name = input('Enter your name : ') print(f'Hello, {name}') """ Now, if we run the code, python will run from the first line of code, and recognize that we've defined a function greet() only, and comes out of the body, overall if we run the above chunk of code, it will not run the body of the function, so we need to call the function..., """ greet() """ -- OUTPUT -- Enter your name : Pythobit Hello, Pythobit """ # we can only call the function, after defining the function only, if we call the function before defining the function, # it will give an Traceback error.. """ Variables created inside function, die at the end of the function.., """ # So, if you print(name) # OUTPUT - Traceback error..!
true
07bbbbe40e1c56bb0b03697cb7bdec93394161b4
barawalojas/Python-tutorial
/Season 02 - Python Fundamentals/Episode 01 - if statements.py
1,979
4.34375
4
# if Statements """if statements allow our programs to make decision depending on the boolean""" friend = 'Rolf' username = input('Enter your name : ') if True: print('Hello friend..!') # Above code will print 'Hello friend..!' only if the user input name as Rolf, otherwise nothing. """ !! -- as true will be always true, so the print statement will be printed always. -- !! """ if username == friend: print('Hello friend..!') # Output - Enter your name : bob """ -- What will happen here is that python checks if username is equal to friend, if yes, then it will run the print statement inside it. else nothing will be printed -- """ """ SYNTAX if username == friend }- Boolean Comparison, : }- Colon depicts the start of the body. body }- indentation is necessary, so python knows that these statements are inside if statements.""" """as soon as you terminate the space in front of print statements, python will give an error..""" """ if [Bool]: -- if true, returns print statment, otherwise else print() else: print() using if and else at same time also known as "Compound if-Statement" -- """ # Things you put inside if condition, doesn't needs to be a bool comparison. friends = ['Charlie','Smith'] family = ['Johny','Bob'] username = input('Enter your name : ') if username in friends: print('Hello friend..!') elif username in family: print('Hello Family..!') else: print('I Don\'t know you..!') """ !! -- !! IMPORTANT THINGS TO NOTICE !! -- !! """ # 01. Take care of INDENTATION, mostly beginners make a lot mistake in this """ 02. AN Example - of not giving indentation properly will give an error.. """ """ if username = friend: print('Hello friend ..!') print('hello bello') -- Right here this statement will give an error, python interprets this as an error. """ # 03. from now onwards, i won't be giving the outputs, you have to try yourself.. # Any editor you like, i prefer to PyCharm..
true
54e664190c974dd17397667d9f91935f6c1b132a
barawalojas/Python-tutorial
/Season 02 - Python Fundamentals/Episode 11 - List Comprehension.py
2,181
4.625
5
# List Comprehension # Suppose we have list of numbers as given below : numbers = [0,1,2,3,4] # and we want to double all the number in the list, i.e: each number to be multiplied by doubled_numbers = [] for number in numbers: doubled_numbers.append(number * 2) print(doubled_numbers) # OUTPUT - [0, 2, 4, 6, 8] # Above method is long and time consuming to run, # so, we'll use list comprehension instead doubled_numbers = [number * 2 for number in numbers] print(doubled_numbers) # OUTPUT - [0, 2, 4, 6, 8] # Above method is way easier than that 5 line code above. """ Also we can use range, instead of using a list.. """ doubled_numbers = [number * 2 for number in range(10)] print(doubled_numbers) # OUTPUT - [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # Examples # 01. friend_ages = [22,31,35,37] ages = [f'My friend is {age} years old' for age in friend_ages] print(friend_ages) # OUTPUT - [22, 31, 35, 37] # 02. names = ['Rolf', 'Bob' ,'Jen'] lower = [name.lower() for name in names] print(lower) # OUTPUT - ['rolf', 'bob', 'jen'] # Above method will give print the letters in lowercase # Above method comes best use in user_input..tasks.. #friend = input('Enter your name : ') friends = ['Rolf','Anne','Jen','Bob','Charlie'] # friends_lower = [name.lower() for name in friends] #if friend in friends: # print(f'{friend} is one of your friend.') # OUTPUT - Enter your name : Rolf # Rolf is one of your friend. # for the best use friend = input('Enter your name : ') friends = ['Rolf','Anne','Jen','Bob','Charlie'] friends_lower = [name.lower() for name in friends] #if friend.lower() in friends_lower: # print(f'{friend} is one of your friend.') # OUTPUT - Enter your name : jen # jen is one of your friend. # we can also do title casing, meaning that the first letter will be capital and rest letters as lowercase. print(f'{friend.title()} is one of your friend.') # OUTPUT - Enter your name : jen # Jen is one of your friend.
true
c430e45aabc74b8fad06b15ab7a05a8a2f11cad3
Nadeemk07/Rock-Paper-Scissors
/Rock Paper Scissor.py
1,286
4.21875
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' choice=int(input("What do you want to Choose 0 for rock, 1 for paper, 2 for scissors\n")) print("You choose\n") if(choice==0): print(rock) elif(choice==1): print(paper) elif(choice==2): print(scissors) list=[rock,paper,scissors] computer_choice=random.choice(list) print("Computer choose") print(computer_choice) if(choice==0 and computer_choice==rock): print("No one wins") if(choice==0 and computer_choice==paper): print("You Lose") if(choice==0 and computer_choice==scissors): print("You won") if(choice==1 and computer_choice==rock): print("You won") if(choice==1 and computer_choice==paper): print("Tie") if(choice==1 and computer_choice==scissors): print("You lose") if(choice==2 and computer_choice==rock): print("You lose") if(choice==2 and computer_choice==paper): print("You won") if(choice==2 and computer_choice==scissors): print("Tie")
false
3db329e28cc4475ab59303785dcb2c78a6b7a8c6
dentalmisorder/PythonUdemy
/basics (not actual projects)/logicalNbool.py
427
4.21875
4
#boolean print(2 > 1) #true 2 is greater then 1 print(2 <= 1) #false 2 is not lower or equal then 1 print(2 != 1) #true 2 is not equal 1 print(2 == 2) #true 2 is equal 2 #logical print(2 == 2 and 2 > 1) #true, 2 is equal to 2 and 2 greater then 1 print(2 == 2 or 2 < 1) #true, 2 is equal to 2 (cause OR operator needs only 1 true) print(not 2 == 2) #false cause NOT operator gets the oposite of what expected (expected true)
true
b4cdbf06e668f46be3f18b1e7c914d73d75064ce
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/class-updated/script7_heranca.py
2,685
4.78125
5
#!/usr/bin/env python3 # heranca """Nos inicializamos nossa variavel last_name com a string "Fish" porque sabemos que a maioria dos peixes tera isso como seu sobrenome.""" # Parent Class # class Fish: # def __init__(self, first_name, last_name="Fish"): # self.first_name = first_name # self.last_name = last_name # # # # adicinando metodos # def swim(sef): # print("The Fish is swimming") # # def swim_backwards(self): # print("The Fish can swim in backwards") """Adicionamos os metodos swim () e swim_backwards () a classe Fish, para que cada subclasse tambem possa usar esses metodos. """ """Construir uma classe pai segue a mesma metodologia que construir qualquer outra classe, exceto que estamos pensando sobre quais metodos as classes filhas poderao usar uma vez que as criarmos.""" # Child Class # class Trout(Fish): # pass # 2------------------------------------------- class Fish: def __init__(self, first_name, last_name="Fish", skeleton='Bone', eyelids=False): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim(sef): print("The Fish is swimming") def swim_backwards(self): print("The Fish can swim in backwards") class Trout(Fish): pass # vamos criar um objeto da classe Trout que ainda nao possui nenhum metodo proprio terry = Trout("Terry") print(terry.first_name + " " + terry.last_name) terry.swim() terry.swim_backwards() print(terry.eyelids) print(terry.skeleton) """Nos criamos um objeto Trout terry que faz uso de cada um dos metodos da classe Fish, embora nao tenhamos definido esses metodos na classe filha Trout. Nos so precisavamos passar o valor de "Terry" para a variavel first_name porque todas as outras variaveis ​​foram inicializadas. """ # vamos criar outra subclasse Clownfish class Clownfish(Fish): def live_with_anemone(self): print("The clownfish is coexisting with sea anemone.") print() # vamos instanciar o objeto clownfish casey = Clownfish("Casey") print(casey.first_name + " " + casey.last_name) casey.swim() casey.swim_backwards() casey.live_with_anemone() """A saida mostra que o objeto Clownfish casey e capaz de usar os metodos Fish __init __ () e swim (), assim como seu metodo de classe filho de live_with_anemone ().""" """As classes filhas herdam os metodos da classe pai a que pertencem, portanto, cada classe filha pode fazer uso desses metodos dentro dos programas.""" """ Referencia: https://www.digitalocean.com/community/tutorials/ understanding-class-inheritance-in-python-3"""
false
3cdba55cf89594113473cdd16ef2fcf4c6be9e28
frclasso/2nd_Step_Python_Fabio_Classo
/Cap01-Elementos-de-sintaxe-especifica/02_list_comprehension/extras/comprehension2.py
294
4.15625
4
"""In fact, lists, sets, dictionaries, and generators can all be built with comprehensions """ print([ord(x)for x in 'spam']) # List of character ordinals print({ord(x)for x in 'spam'}) # Set print({x : ord(x)for x in 'spam'}) # Dictionary print((ord(x)for x in 'spam')) # Generator of values
true
4e9e683720ec7e5386244e90a89e720bbea2d514
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/empregados.py
1,593
4.34375
4
#!/usr/bin/env python3 # -*-coding:utf-8 -*- class Employee: 'Classe Base para todos os empregados/Commom base class for all employees.' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print(f"Total de empregados: {Employee.empCount}") def displayEmployee(self): print("Nome: ", self.name, "-", "Salario: R$", self.salary) #This would create the first object of Eployee class emp1 = Employee('Zara', 2000) #This would create the second object of Eployee class emp2 = Employee('Manni', 5000) # Acessing Attributes emp1.displayEmployee() emp2.displayEmployee() print("Total Employee {}".format(Employee.empCount)) # Adicionando, modificando e deletando atributos # emp1.salary = 3000 # altera o valor do salario # emp1.name = 'Joseph' # altera o nome do empregado 1 #emp1.displayEmployee() #del emp1.salary # Verificar atributos dos objetos # print(hasattr(emp1, 'salary')) # Retorna True se o atributo 'salary' existir # print(getattr(emp1, 'salary')) # Retorna o valor do atributo 'salary' # setattr(emp1, 'salary', 4000) # Define o novo valor # print(getattr(emp1, 'salary')) # delattr(emp1,'salary') # Deleta o atributo 'salary' # print(hasattr(emp1, 'salary')) # Verificar atributos de classe print("Employee.__doc__:", Employee.__doc__) print("Employee.__name__:", Employee.__name__) print("Emplyee.__module: ", Employee.__module__) print("Employee.__bases__: ", Employee.__bases__) print("Employee.__dict__: ", Employee.__dict__)
false
936b135496ab68554a661f1fd381fabb2dee8c08
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/class-updated/script8.py
2,728
4.9375
5
#!/usr/bin/env python3 # Sobreescrevendo metodos da classe Pai """Ate agora, examinamos a classe filha Trout que utilizou a palavra-chave pass para herdar todos os comportamentos Fish da classe pai e outra classe filha, Clownfish, que herdou todos os comportamentos da classe pai e tambem criou seu proprio metodo exclusivo. especifico para a classe filho. As vezes, no entanto, queremos usar alguns dos comportamentos da classe pai, mas nao todos eles. Quando mudamos os metodos de classe pai, nos os substituimos.""" """Ao construir classes pai e filho, e importante manter o design do programa em mente para que a substituicao nao produza codigo desnecessario ou redundante.""" """Diante disso, substituiremos o metodo construtor __init __ () e o metodo swim_backwards (). Nao precisamos modificar o metodo swim (), pois os tubaroes sao peixes que podem nadar. Vamos dar uma olhada nesta classe infantil: """ class Fish: def __init__(self, first_name, last_name="Fish", skeleton='Bone', eyelids=False): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim(sef): print("The Fish is swimming") def swim_backwards(self): print("The Fish can swim in backwards") class Shark(Fish): def __init__(self, first_name, last_name="Shark", skeleton='Cartilage', eyelids=True): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim_backwards(self): print("The Fish can not swim in backwards, but can sink backwards") """Nos substituimos os parametros inicializados no metodo __init __ (), para que a variavel last_name seja agora igual a string "Shark", a variavel esqueleto agora e igual a string "cartilage", e a variavel eyelids agora esta definida para o valor booleano True. Cada instancia da classe tambem pode substituir esses parametros. O metodo swim_backwards () agora imprime uma string diferente da que esta na classe pai Fish, porque os tubaroes nao sao capazes de nadar para tras da maneira que os peixes com ossos conseguem. """ # instanciando um objeto shark sammy = Shark("Sammy") print(sammy.first_name+ " "+sammy.last_name) sammy.swim() sammy.swim_backwards() print(sammy.eyelids) print(sammy.skeleton) """A classe secundaria Shark substituiu com exito os metodos __init __ () e swim_backwards () da classe pai Fish, enquanto tambem herdava o metodo swim () da classe pai. Quando houver um numero limitado de classes filhas que sao mais exclusivas do que outras, a substituicao dos metodos de classe pai pode ser util"""
false
c28c4ab306be61d3067b915c907685ef11bd43d5
frclasso/2nd_Step_Python_Fabio_Classo
/Cap01-Elementos-de-sintaxe-especifica/03_dict_comprehension/extras/01_exemplo1.py
232
4.125
4
#!/usr/bin/env python3 # dict comprehension criando um dicionario apartir do for i converte int em str como key d = {str(i):i for i in [1,2,3,4,5]} print(d) # http://cmdlinetips.com/2018/01/5-examples-using-dict-comprehension/
false
ec301abb2c01e8acdaabc92785acfaa2a249504e
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/class-updated/script10.py
2,842
4.25
4
#!/usr/bin/env python3 # Heranca multipla """Herança múltipla é quando uma classe pode herdar atributos e métodos de mais de uma classe pai. Isso pode permitir que os programas reduzam a redundância, mas também pode introduzir uma certa complexidade e ambigüidade, portanto, isso deve ser feito pensando no projeto geral do programa. Para mostrar como funciona a herança múltipla, vamos criar uma classe-filha Coral_reef que herda de uma classe Coral e uma classe Sea_anemone. Podemos criar um método em cada um e, em seguida, usar a palavra-chave pass na classe-filha Coral_reef: """ class Coral: def community(self): print("Coral lives in community") class Anenome: def protect_clowfish(self): print("The anenome is protecting the clownfish.") class CoralReef(Coral, Anenome): pass """A classe Coral tem um método chamado community () que imprime uma linha, e a classe Anemone possui um método chamado protect_clownfish () que imprime outra linha. Então nós chamamos ambas as classes na tupla de herança. Isso significa que Coral está herdando de duas classes pai.""" # instanciando um objeto CoralReef() great_barrier = CoralReef() great_barrier.community() great_barrier.protect_clowfish() """A saída mostra que os métodos de ambas as classes pai foram efetivamente usados ​​na classe filha. A herança múltipla nos permite usar o código de mais de uma classe pai em uma classe filha. Se o mesmo método for definido em vários métodos pai, a classe filha usará o método do primeiro pai declarado em sua lista de tupla. Embora possa ser usado com eficácia, a herança múltipla deve ser feita com cuidado para que nossos programas não se tornem ambíguos e difíceis para outros programadores entenderem. """ """Conclusão Este tutorial passou pela construção de classes pai e de classes filhas, substituindo métodos e atributos pai em classes filhas, usando a função super () e permitindo que classes filhas herdassem de várias classes pai. A herança na codificação orientada a objetos pode permitir a adesão ao princípio DRY (não se repita) de desenvolvimento de software, permitindo que mais seja feito com menos código e repetição. A herança também obriga os programadores a pensar em como estão projetando os programas que estão criando para garantir que o código seja eficaz e claro.""" """A programação orientada a objetos (OOP) se concentra na criação de padrões reutilizáveis ​​de código, em contraste com a programação procedural, que se concentra em instruções explícitas em seqüência. Ao trabalhar em programas complexos em particular, a programação orientada a objetos permite reutilizar códigos e escrever códigos mais legíveis, o que, por sua vez, os torna mais fáceis de manter."""
false
c07f6f5d58d0bda201befe51f092eb47a2732940
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/representation.py
556
4.25
4
#!/usr/bin/env python3 class bunny: def __init__(self, n): self._n = n def __repr__(self): return f'repr: the number of bunnies is {self._n}' def __str__(self): return f'str: the number of bunnies id {self._n}' x = bunny(47) #print(repr(x)) print((x)) # RETIRANDO REPR, DA PREFERENCIA PARA STRING METHOD # print(chr(128406) * 10) # print(chr(128527) * 10) # Emojis http://graphemica.com/ """Para mais informacoes e exemplos de Funcoes Built-in acessem: https://docs.python.org/3/library/functions.html """
false
d27c8f4a3a48ac6ffed4ae610676c24a64736f72
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/class-updated/script5_metodos_construtores.py
2,742
4.8125
5
#!/usr/bin/env python3 """O método construtor O método construtor é usado para inicializar dados. É executado assim que um objeto de uma classe é instanciado. Também conhecido como o método __init__, será a primeira definição de uma classe e se parece com isso: """ # class Shark: # # def __init__(self): # print("This is the constructor method") # # def swim(self): # print("The shark is swimming") # # def be_awsome(self): # print("The shark is being awesome.") # # sammy = Shark() # sammy.swim() # sammy.be_awsome() """Se você adicionou o método __init__ acima à classe Shark no programa acima, o programa produziria o seguinte sem modificar nada dentro da instanciação sammy:""" # output """This is the constructor method The shark is swimming The shark is being awesome.""" """ Isso ocorre porque o método construtor é inicializado automaticamente. Você deve usar este método para realizar qualquer inicialização que você gostaria de fazer com seus objetos de classe. Em vez de usar o método do construtor acima, vamos criar um que use uma variável de nome que possamos usar para atribuir nomes a objetos. Vamos passar o nome como parâmetro e definir self.name igual ao nome: """ # class Shark: # # def __init__(self, name): # self.name = name # # # def swim(self): # #referenciando a variavel name # print(self.name + "is swimming") # # def be_awsome(self): # print(self.name + "is being awesome.") """Finalmente, podemos definir o nome do sammy do objeto Shark como igual a "Sammy", passando-o como um parâmetro da classe Shark:""" # def main(): # sammy = Shark("Sammy") # sammy.swim() # sammy.be_awsome() # # if __name__=="__main__": # main() """Vemos que o nome que passamos para o objeto está sendo impresso. Definimos o método __init__ com o nome do parâmetro (juntamente com a palavra-chave self) e definimos uma variável dentro do método. Como o método construtor é automaticamente inicializado, não precisamos chamá-lo explicitamente, apenas passar os argumentos entre parênteses após o nome da classe quando criamos uma nova instância da classe. Se quiséssemos adicionar outro parâmetro, como a idade, poderíamos fazer isso passando-o para o método __init__:""" class Shark: def __init__(self, name, age): self.name = name self.age = age def swim(self): #referenciando a variavel name print(self.name + "is swimming") def be_awsome(self): print(self.name + "is being awesome.") def main(): sammy = Shark("Sammy", 34) sammy.swim() sammy.be_awsome() if __name__=="__main__": main()
false
60fe114c0e0981b625a2c5f2bcf60053b87c2828
frclasso/2nd_Step_Python_Fabio_Classo
/Cap02_Classes_e_Programacao_Orientada_a_Objetos/class-updated/script3_juntando_tudo.py
1,916
4.8125
5
#!/usr/bin/env python3 """Trabalhando com variáveis ​​de classe e instância juntas Variáveis ​​de classe e variáveis ​​de instância costumam ser utilizadas ao mesmo tempo, portanto, vamos ver um exemplo disso usando a classe Shark que criamos. Os comentários no programa descrevem cada etapa do processo.""" class Shark: # variaveis de classe animal_type = 'fish' location = 'ocean' # metodo construtor com as variaves de instancia name e age def __init__(self, name, age): self.name = name self.age = age # metodo para definir a variavel followers def set_follwers(self, followers): print("This user has " + str(followers) + " followers") def main(): sammy = Shark('Sammy', 32) print(sammy.name) print(sammy.age) print(sammy.location) print() # segundo objeto stevie = Shark('Stevie', 34) print(stevie.name) print(stevie.age) print(stevie.location) print(stevie.animal_type) if __name__=="__main__": main() """Aqui, usamos as variáveis ​​class e instance em dois objetos da classe Shark, sammy e stevie.""" """ Conclusão Na programação orientada a objetos, as variáveis ​​no nível da classe são referidas como variáveis ​​de classe, enquanto as variáveis ​​no nível do objeto são chamadas de variáveis ​​de instância. Essa diferenciação nos permite usar variáveis ​​de classe para inicializar objetos com um valor específico atribuído a variáveis ​​e usar variáveis ​​diferentes para cada objeto com variáveis ​​de instância. O uso de variáveis ​​específicas de classe e de instância pode garantir que nosso código siga o princípio DRY para reduzir a repetição no código.""" """referencias: https://www.digitalocean.com/community/tutorials/ understanding-class-and-instance-variables-in-python-3"""
false
9c4251d34eff84b1451c32763c238b5ebbd45762
frclasso/2nd_Step_Python_Fabio_Classo
/Cap01-Elementos-de-sintaxe-especifica/06_itertools2.py
462
4.125
4
#!/usr/bin/env python3 # Itertools Part 2 import itertools ## Permutations, order matters election = {1:'Barb', 2:'Karen', 3:'Erin'} # for p in itertools.permutations(election): # print(p) # for p1 in itertools.permutations(election.values()): # print(p1) ## Combinations: Order does not matter colorsForPainting = ["Red", "Blue", "Purple", "Orange", "Yellow", "Pink"] for c in itertools.combinations(colorsForPainting, 2): # 2 elements print(c)
true
d0110beec760bf30f9c8cef83d025d67872b1b80
Belindalinx/Time_to_Practice
/Complex Datastructures/Complex Datastructures.py
1,361
4.28125
4
#Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. person = [{"name": "Alice", "age": "25", "hobbies": ["music", "art", "coloring"]}, {"name": "Bob", "age": "27", "hobbies": ["science", "gaming", "sleep"]}, {"name": "Corgi", "age": "3", "hobbies": ["ball", "run", "eat"]} ] #Use a list comprehension to convert this list of persons into a list of names (of the persons). """ name = [] for i in person: for k, v in i.items(): if k == "name": name.append(v) """ name=[i["name"] for i in person] print(name) #Use a list comprehension to check whether all persons are older than 20. """ age = [] for i in person: for k, v in i.items(): if k == "age": age.append(int(v)) if all(age) > 20: print("All persons are older than 20.") else: print("All persons are not older than 20.") """ age=all([int(i["age"]) >20 for i in person]) print(age) #Copy the person list such that you can safely edit the name of the first person (without changing the original list). c_person = [i.copy() for i in person] c_person[0]["name"] = "Gina" print(person) print(c_person) #Unpack the persons of the original list into different variables and output these variables. a, b, c, = person print(a) print(b) print(c)
true
c14ae5ba10c5384fda85b575af34916f9b25924a
chen13545260986/hello_python
/6并发编程/2线程/1线程.py
962
4.125
4
""" 1进程 进程是最小的内存分配单位 进程中至少含有一个线程 进程中可以开启多个线程 2线程 线程是进程中的执行单位 线程被CPU执行的最小单位 线程之间资源共享 开启一个线程所需要的时间要远远小于开启一个进程 python 与 2线程 Cpython解释器在解释代码过程中容易产生数据不安全的问题 GIL 全局解释器锁 锁的是线程 """ from threading import Thread import time # def func(n): # time.sleep(1) # print(n) # # # 线程并发执行 # for i in range(10): # # 将这个函数注册到一个线程 # t = Thread(target=func,args=(i,)) # t.start() """ 多线程中数据的共享 """ def func(n): global a a += n print(a) a = 100 lst = [] for i in range(10): # 注册线程并启动 t = Thread(target=func,args=(i,)) t.start() lst.append(t) for t in lst: t.join() print(a)
false
040a30a9bf29b237ccb4ef75489a5d307d03fe61
naveen-nayan/pyproto
/Hello.py
2,562
4.75
5
print("Hello World\n") # Creating a list List = [] # Creating a List with the use of string List1 = ["Hello"] # Creating a List with the use of multiple string List2 = ["Good", "Morning"] # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List3 = [["Good", "Morning"], ["Hello"]] # Print nested list print(List3) # Creating a List with # the use of Numbers # (Having duplicate values) List4 = [1, 2, 4, 4, 3, 3, 3, 6, 5] # Creating a List with # mixed type of values # (Having numbers and strings) List5 = [1, 2, 'Good', 4, 'Morning', 6, 'Hello'] # Addition of Elements # in the List List.append(1) List.append(2) List.append(4) # Adding elements to the List # using Iterator for i in range(1, 4): List.append(i) # Inserting element to list insert(index, value) List.insert(2, 13) print(List) # Addition of multiple elements # to the List at the end # (using Extend Method) List.extend([8, 'Hello', 'World']) # accessing a element using # negative indexing # print the last element of list print(List[-1]) # print the third last element of list print(List[-3]) # Removing elements from List # using Remove() method List.remove(8) # Creating a List List7 = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'] print("Intial List: ") print(List7) # Print elements of a range # using Slice operation Sliced_List = List7[3:8] print("\nSlicing elements in a range 3-8: ") print(Sliced_List) # Print elements from a # pre-defined point to end Sliced_List = List7[5:] print("\nElements sliced from 5th " "element till the end: ") print(Sliced_List) # Printing elements from # beginning till end Sliced_List = List7[:] print("\nPrinting all elements using slice operation: ") print(Sliced_List) print(List7) # Negative Index list slicing # Creating a List List8 = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'] print("Initial List: ") print(List8) # Print elements from beginning # to a pre-defined point using Slice Sliced_List = List8[:-6] print("\nElements sliced till 6th element from last: ") print(Sliced_List) # Print elements of a range # using negative index List slicing Sliced_List = List8[-6:-1] print("\nElements sliced from index -6 to -1") print(Sliced_List) # Printing elements in reverse # using Slice operation Sliced_List = List[::-1] print("\nPrinting List in reverse: ") print(Sliced_List) for item in list: print(item)
true
509df17b2dc3eea4823eb50d9c548c53ae3261a7
playerlove1/python_practice
/basic/Prime_number.py
599
4.125
4
#這是python求質數的範例 #求質數所用的方式:小於該整數一半以下的數 都無法整除該整數則為質數 #接收輸入的參數 input_number=int(input('輸入數字:')) #該整數除以2的商 half_input_number=input_number//2 #迴圈(由 i=2 跑到一半+1) for i in range(2,half_input_number+1): #如果該數被一半以下的數整除(即取餘數為0) if(input_number%i)==0: print(input_number,"不是質數,可被",i,"整除") break #此為for迴圈的else敘述 當迴圈沒有被任何break中斷時會執行的敘述 else: print(input_number,"是質數")
false
72b0a8b9551ee1f989b8bd262d9890988e542461
playerlove1/python_practice
/basic/object.py
2,504
4.15625
4
#Python的所有東西都是Object,每個object都有 id(),type(),print()的函式 #list(串列) simple_list=[1,"two",True] print(simple_list) # 即在串列的最後接上"新元素"字串 simple_list.append("新元素") print(simple_list) # 即移除串列中最後一個元素 simple_list.pop() print(simple_list) #即為將"two"元素由串列中移除 simple_list.remove("two") print(simple_list) #即為在list index為0的位置插入 "zero"的元素 simple_list.insert(0,"zero") print(simple_list) #透過len函數取得串列長度 len(simple_list) #也可在[]中指定index值 直接進行修改 simple_list[len(simple_list)-1]=len(simple_list)-1 print(simple_list) #刪除index 1以後的元素(包含index=1) 若輸入為 del simple_list[:] 即為清空該串列 del simple_list[1:] print(simple_list) # "[:]"對串列使用等於建立一個新串列,每個索引值都會參考到舊串列中每個所印位置的元素 #也就是所謂的淺層複製 (Shallow copy) copy_list=simple_list[:] print(copy_list) #將list使用"*"運算 將會對list內容進行 淺層複製 (Shallow copy) double_list=simple_list*2 print(double_list) #將list使用"+"運算 將會建立一個新的物件 長度等於兩個串列的和 並合併兩個串列 add_list=copy_list+double_list print(add_list) #set (集合) admins_set={"root","fong","s"} users_set={"user1","user2","s"} #交集 print("交集:",admins_set&users_set) #聯集 print("聯集:",admins_set|users_set) #差集 print("差集:",admins_set-users_set) #XOR :排除共同元素 print("XOR:",admins_set^users_set) #父集>子集 子集<父集 (> 與 < 回傳布林值 主要判斷兩個集合是否有父集與子集的關係) #dictionary 即為key value 的模式 類似Java的map passwords_dict={"user1":123,"user2":456} #同義於 passwords=dict(user1=123,user2=456) #可以直接使用passwords["user1"]取得該變數的值 但若名稱不存在 則會拋出KeyError #因此可以透過get取得 若不存在則回傳None(deault) 可在後面加入字串修改default回傳的結果 print(passwords_dict.get("user3","變數不存在")) # 使用update() 增加元素 passwords_dict.update({"user3":789}) print(passwords_dict) # 使用pop() 刪除元素 passwords_dict.pop("user3") print(passwords_dict) #可以使用passwords_dict.items()取得tuple #可以使用passwords_dict.keys()取得key #可以使用passwords_dict.value()取得value #Tuple 像list一樣 但list是可變動 tuple是不可變動
false
0158a3c83488fbc7bcd3a27a2cdb781c1fb836bf
tbremm/Hacker_Rank_Python
/map_and_lambda_function.py
1,775
4.6875
5
# Let's learn some new Python concepts! You have to generate a list of the first fibonacci numbers, being the first # number. Then, apply the map function and a lambda expression to cube each fibonacci number and print the list. # # Concept # The map() function applies a function to every member of an iterable and returns the result. It takes two parameters: # first, the function that is to be applied and secondly, the iterables. # Let's say you are given a list of names, and you have to print a list that contains the length of each name. # # >> print (list(map(len, ['Tina', 'Raj', 'Tom']))) # [4, 3, 3] # # Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function # that has only one line in its body. It proves very handy in functional and GUI programming. # # >> sum = lambda a, b, c: a + b + c # >> sum(1, 2, 3) # 6 # # Note: # Lambda functions cannot use the return statement and can only have a single expression. Unlike def, which creates a # function and assigns it a name, lambda creates a function and returns the function itself. Lambda can be used inside # lists and dictionaries. # # Input Format # One line of input: an integer N. # # Constraints # 0 < N < 15 # # Output Format # A list on a single line containing the cubes of the first N fibonacci numbers. cube = lambda x: x * x * x # complete the lambda function def fibonacci(num_fib_terms): # return a list of fibonacci numbers if num_fib_terms == 0: return [] if num_fib_terms == 1: return [0] fibs = [0, 1] # Fib series always starts with [0, 1] for _ in range(2, num_fib_terms): fibs.append(fibs[-1] + fibs[-2]) return fibs n = int(input()) print(list(map(cube, fibonacci(n))))
true
c84bf6274eb980f1db1fb2816fdddaeba36909e6
nmelgar/python_for_students
/loops.py
372
4.1875
4
pizza_toppings = ["cheese","pepperoni","mushrooms"] #for loop after the FOR it goes whatever i want to call it for topping in pizza_toppings: message = f"I would like {topping} on my pizza" print(message) my_numbers = [1, 2, 3] my_square_numbers = [] for number in my_numbers: my_square_numbers.append(number**2) print(my_square_numbers)
true
e1f4534a4ffcd110bb7f4c6929831e2ecc749f92
Chiedu99/Unit10
/Unit 10.py
1,233
4.1875
4
# Chiedu Nduka-Eze 11/22/16 Unit 10 # This program creates a pyramid with 5 rows of different colored bricks import pygame, sys from pygame.locals import * import brick pygame.init() mainSurface = pygame.display.set_mode((500, 400), 0, 32) BLUE = (0, 0, 255) RED = (255, 0, 0) BLACK = (0, 0, 0) GREEN = (0, 255, 0) GOLDROD = (184, 131, 11) WHITE = (255, 255, 255) mainSurface.fill(WHITE) listColors = [BLACK, GREEN, GOLDROD, BLUE, RED] SPACES = 5 height = mainSurface.get_height() numberOfBricks = 9 widthOfBrick = (mainSurface.get_width() - ((numberOfBricks + 1) * SPACES ))/ 9 xPos = SPACES yPos = height - 25 rowNumber = 0 # This loop creates a brick, places them, and changes the color for all 5 rows for color in listColors: # This indents the first brick of each row xPos = rowNumber * (widthOfBrick + SPACES) for x in range(numberOfBricks): pie = brick.Brick(mainSurface, 25, widthOfBrick, color) pie.draw(xPos, yPos) xPos += (widthOfBrick + SPACES) yPos -= 30 xPos = SPACES numberOfBricks -= 2 rowNumber += 1 pygame.display.update() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
true
c8a9544cf61cbc8a85148ee53fd579dca64a51db
nar0se/NCI
/Challenges/challenge6.py
2,561
4.28125
4
# Write an application for Cody's Car Care Shop that shows a user a list of available services: # - Oil Change # - Tire Rotation # - Battery Check # - Brake Inspection # ​ # Allow the user to enter a string that corresponds to one of the options and display the option # and its price as $25, $22, $15, or $5, accordingly. Display an error message if the user enters # an invalid item. # ​ # It might not be reasonable to expect users to type long entries such as 'Oil Change' accurately. # as long as the user enters the first three characters of service, the choice is considered valid. # ​ # Create a list with all the available services and another with the list of prices in another # file and import them to the main file. # ​ # Create a list of lists and print all elements of every list # ​ # Create a list containing lists of tuple, an array, two dictionaries, a set, two strings, two floats, two integers, two # booleans. Print each element of the list import json, os from json import dumps, loads from os import system # from prices import * # from services import * system('cls') counter = 0 path = './Challenges/services.txt' services = ['Oil Change', 'Tire Rotation', 'Battery Check', 'Brake Inspection'] with open (path, 'w') as file: file.write('This is the list of services we provide') file.close() with open(path, 'a') as file: file.write(f'\n{services}') file.close() path = './Challenges/prices.txt' prices = ['25', '22', '15', '5'] with open(path, 'w') as file: file.write('This is the list of prices for our services') file.close() with open(path, 'a') as file: file.write(f'\n{prices}') file.close() cselect = str(input('Please select one of our services >> ')) dselect = cselect.lower() string = dselect[0:3] if (string) == 'oil': string = services[0] print(string) elif (string) == 'tir': string = services[1] elif (string) == 'bat': string = services[2] elif (string) == 'bra': string = services[3] listofservices = dumps(services) print(listofservices) listofprices = dumps(prices) print(listofprices) listoflists = [ ['Oil Change', 'Tire Rotation', 'Battery Check', 'Brake Inspection'] ['25', '22', '15', '5'] ] # while True: # content = input('What content do you want to add to the file? >> ') # with open(path, 'a') as file: # file.write(f'\n{content}') # file.close() # response = input('Do you want to add more content [Y/N]? >> ') # if(str.upper(response) == 'N'): # break
true
e149e67b55d68e45e070ffd9c164b52afcbde777
kuranyukie/Projects
/Python/2020/Python3-Cookbook-1.2.py
1,119
4.125
4
# -*- coding: UTF-8 -*- # 1.2 解压可迭代对象赋值给多个变量 a = (1,2,3,4,5) x1, *x, x2 = a print(f'{x1 = }') # x1 = 1 print(f'{x = }') # x = [2, 3, 4] print('*x = ', *x) # *x = 2 3 4 print(f'{x2 = }') # x2 = 5 # 星号表达式在迭代元素为可变长元组的序列时是很有用的。 records = [ ('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4), ] def do_foo(x, y): print('foo', x, y) def do_bar(s): print('bar', s) for tag, *args in records: if tag == 'foo': do_foo(*args) elif tag == 'bar': do_bar(*args) # 理解 x / *x / **x 的区别 def fun1(x, y = 'hello') : return (str(x) + str(y)) def fun2(**x) : return fun1(*x) # 此时的*x = (a, b) 是两个参数 def fun3(**x) : return fun1(x) # 此时的x = {'a': 1, 'b': 2} 是一个参数 def fun4(*x) : return fun1(x) # 此时的x = (1, 2) 是一个参数 def fun5(*x) : return fun1(*x) # 此时的*x = (1, 2) 是两个参数 print(fun2(a=1,b=2)) # ab print(fun3(a=1,b=2)) # {'a': 1, 'b': 2}hello print(fun4(1, 2)) # (1, 2)hello print(fun5(1, 2)) # 12
false
95e01befa693e7805497c80c00eeb2fc166d4a04
kuranyukie/Projects
/Python/2018/exercise/Ch5.py
1,097
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 30 19:24:35 2018 @author: Yukie """ """ Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,17,19,23...]) can be added before exceeding n. Associate this number with the variable k. """ def is_prime(a): if a == 0 or a == 1: return False for i in range(2,a): if a % i == 0: return False return True def test(n): sum = 0 k = -1 num = 2 while sum <= n: if is_prime(num): sum += num k += 1 num += 1 return(k) # print(test(1)) for i in range(20): print("test:", i, "result:", test(i)) """ interest rate """ p = float(input("Enter current bank balance:")) i = float(input("Enter interest rate:")) t = float(input("Enter the amount of time that passes:")) def calc(p,i,t): f = p * (1 + i) ** t return f print(calc(p,i,t))
true
aad1b6a40b920be33aae31e7ebe184409efcea55
santosh241/python-exercise
/function.py
1,445
4.1875
4
def main(): print("hello world!") main() print("print mee") # # # #built_in_function # a=9 # b=8 # c=sum((a,b)) # print(c) # #user_define_function # a=9 # b=8 # c=a+b # print(c) def function(a,b): print("your are in function one" , a+b) function(6,7) # def function1(a,b): """ this method use for add two number""" average=(a+b)/2 return average v=function1(6,8) print(v) print(function1.__doc__) # # def wish(): return "hello good morning" print(wish()) # # def sum(a,b): print("sum of two number",a+b) sum(5,10) a=int(input("enter your first value")) b=int(input("enter your second value")) def sum(c,d): print("sum of two numbers",a+b) sum(a,b) # def sum(c,a=10,b=20): print("sum of two number",a+b+c) sum(a=20,c=10) # class Circle: pi = 3.14 ##########Circle gets instantiated with a radius (default is 1) def __init__(self, radius=1): self.radius = radius self.area = radius * radius * Circle.pi ####Method for resetting Radius def setRadius(self, new_radius): self.radius = new_radius self.area = new_radius * new_radius * self.pi ### Method for getting Circumference def getCircumference(self): return self.radius * self.pi * 2 c = Circle() print('Radius is: ',c.radius) print('Area is: ',c.area) print('Circumference is: ',c.getCircumference())
true
39c13556ed9b929cac6f24576fdbe0ce596a7e7c
killerCult/Basic-Python-Codes
/guess.py
1,092
4.1875
4
''' You, the user, will have in your head a number between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high, too low, or your number. At the end of this exchange, this program should print out how many guesses it took to get your number. ''' # Killer_Cult begin = 50 #Start with middle number between 1 and 100 flag = 0 #Indicate if correct guess or not high = 100 #Default high, subject to change low = 0 #Default low, subject to change count = 0 #Count the number of guesses while flag==0: count+=1 print "Is the number", begin,"? (yes/no):" guess = raw_input() if guess=="yes": print "Correct Guess" print "Took", count, "tries" flag = 1 elif guess=="no": print "Wrong Guess" print "Was the guess higher or lower? (higher/lower)" hl = raw_input() if hl=="higher": high = begin begin = begin - ((high-low)/2) elif hl=="lower": low = begin begin = begin + ((high-low)/2) else: print "Invalid Input" else: print "Invalid Input"
true
6ee12f8281d9f8af9bfd1ba3d40cee89bebf577b
Ariz23746/MyPrograms-python
/array-usingClass.py
1,647
4.21875
4
class Array: # Constructing a Constructor def __init__(self): self.length = 0 self.array = {} # --------------------------------------------------------------------# # Function to return our array:- def ourArray(self, index): return self.array[index] # --------------------------------------------------------------------# # Function to add element at the last index of an array :- def push(self, item): self.array[self.length] = item self.length = self.length + 1 return self.array # --------------------------------------------------------------------# # Function to remove element from the last index of an array :- def pop(self): del(self.array[self.length - 1]) self.length = self.length - 1 return self.array # --------------------------------------------------------------------# # Function to delete an element from desire index of an array def delete(self, index): item = self.array[index] # O(1) while(index < self.length - 1): # O(n) self.array[index] = self.array[index + 1] index = index + 1 self.length = self.length - 1 # O(1) self.array[self.length] = item # O(1) del(self.array[self.length]) # O(1) return self.array # O(1) # time complexity will be O(5 + n) = O(n) # --------------------------------------------------------------------# arr = Array() arr.push('hi') arr.push('my') arr.push('name') arr.push('is') arr.push('Ariz') print(arr.push('khan')) print(arr.delete(5))
true
84eebe7fad08c17ad92b04069eb631cd9016459b
natwilkinson/advent-of-code-2020
/day_02/day_2.py
1,312
4.15625
4
# Advent of Code - Day 2 def get_valid_passwords(filename): """ Finds valid password count using part 2 rules. """ f = open(filename, "r") valid_passwords = 0 for line in f: data = line.split() [min_num, max_num] = [int(x) - 1 for x in data[0].split("-")] if has_valid_password_part_2(min_num, max_num, data[1][0], data[2]): valid_passwords += 1 return valid_passwords def has_valid_password_part_1(min_num, max_num, target, password): """ Determines the validity of a password for Part 1. A password is valid if the target character is in the password >= min_num and <= max_num. """ target_count = 0 for char in password: if char == target: target_count += 1 if target_count > max_num: return False if target_count < min_num: return False return True def has_valid_password_part_2(index_1, index_2, target, password): """ Determines the validity of a password for Part 2. A password is valid if the target character is found at index_1 or index_2, but not both (exclusive or). """ if (password[index_1] == target) is not (password[index_2] == target): return True return False print(get_valid_passwords("input_day_2.txt"))
true
16e145e6deef9b5ccbc72ab067d4c684fab50890
younes-alouani/MITx_6.00.1x_edx
/FInal_Exam/Problem4.py
1,366
4.125
4
""" Date : 26/02/2018 Program COntext : 6.00.1 EDX course """ def primes_list(N): ''' N: an integer Returns a list of prime numbers ''' #### """ Private function that returns : True if a number is Prime False if not """ def isPrime(number) : import math if number == 0 or number == 1 : return False elif number == 2 : return True else : maxDenom = int(math.sqrt(number)) for denom in range(2,maxDenom+1): if number % denom == 0 : return False return True ##### primesList = [] for n in range(N+1) : if isPrime(n) : primesList += [n] return primesList """ Tests """ #Test 1 : N = 0 print("Test 1 result is : ",primes_list(N)) if primes_list(N) == [] : test1 = "Test 1 passed" else : test1 = "Test 1 failed" #Test 2 : N = 3 print("Test 2 result is : ", primes_list(N)) if primes_list(N) == [2,3] : test2 = "Test 2 passed" else : test2 = "Test 2 failed" #Test 3 : N = 11 print("Test 3 result is : ", primes_list(N)) if primes_list(N) == [2,3,5,7,11] : test3 = "Test 3 passed" else : test3 = "Test 3 failed" print(test1) print(test2) print(test3) #All tests done - 10/10 full MARK
true
f3929ace00207f0fb2396de21a57d6cdd3d6ad13
Aakash-Rajbhar/Library-Management-System
/library_manage_system.py
2,351
4.40625
4
#Implement a student library system using oops where student can borrow a book from the list of books. #Create a seperate library & student class. Your program must be menu driver.You are free to choose methods and atributes of your choice to implement the functionality. class Library: def __init__(self, listofBooks): self.books = listofBooks #This is for displaying the Books def displayAvailableBooks(self): print("Books present in the Library are : ") for book in self.books: print("* "+book) def borrowBook(self,bookName): if bookName in self.books: print(f"You have been isued {bookName}. Please keep it safe and return it within 30 days.") self.books.remove(bookName) return True def returnBook(self, bookName): self.books.append(bookName) print("Thanx for returning this book I hope you enjoyed it. Have a great day Ahead!!") #----------------------Student------------------------------------------------------ class Student: def requestBook(self): self.book = input("Enter the name of book you want to borrow : ") return self.book def returnBook(self): self.book = input("Enter the name of the book you want to return : ") return self.book if __name__ == "__main__" : centralLibrary = Library(["Jungle Book", "Arabian Nights", "Avengers", "Honeycomb", "Inception", "Matrix", "King Kong", "Vistas", "Flamingo", "RD Sharma"]) student = Student() while (True): try: Wlcm_msg = "************************ WELCOME TO THE CENTRAL LIBRARY **************************\n* Please Choose an option\n1. Show the List of books.\n2. Request for a book.\n3. Add/Return a book.\n4. Exit" print(Wlcm_msg) a = int(input("Enter a choice : ")) if a == 1: centralLibrary.displayAvailableBooks() elif a == 2 : centralLibrary.borrowBook(student.requestBook()) elif a == 3 : centralLibrary.returnBook(student.returnBook()) elif a == 4 : print("Thanx for coming to the CENTRAL LIBRARY....") exit() else : print("Invalid Choice.") except : print("Sorry Something wrong")
true
ef6b1aca554648b945706f3398a8d1178da33bd7
pallavijoshi92/Python_General_codes
/Palindrome.py
450
4.28125
4
#program to check if a given number/string is a palindrome import sys def isPalindrome(given): given="".join(given.split()) if len(given)==0: print "No string entered" sys.exit() for i in range(len(given)//2): if given[i]!=given[-1-i]: return False return True if __name__=="__main__": given=raw_input("Enter string/number:") print isPalindrome(given)
true
2d9b398818845fb013e96c97dae162326c492778
carolinecav/test
/card.py
251
4.125
4
suits = ["hearts","clubs","diamonds","spades"] values = ["2","3","4","5","6","7","8","9","10","jack","queen","king","ace"] count = 0 for value in values: for suit in suits: print(value + " of "+ suit) count = count +1 print(count)
false
acb9996d891d2f6955b56ed3d95a5a501d65542e
aditiabhang/my-python-stuff
/concepts_practice/problem_solving/fancy_number.py
1,817
4.125
4
''' Given a mobile number and some conditions for a fancy number, find if the given number is fancy. A 10 digit mobile number is called fancy if it satisfies any of the following three conditions. 1. A single number occurs three consecutive times. Like 777. 2. Three consecutive digits are either in increasing or decreasing fashion. Like 456 or 987. 3. A single digit occurs four or more times in the number. Like 9859009976 – here the digit 9 occurs 4 times. ''' import collections def cond1(number_str): for i in range(len(number_str)-2): if (number_str[i] == number_str[i+1] and number_str[i+1] == number_str[i+2]): return True else: return False def cond2(number_str): for i in range(len(number_str)-2): if (number_str[i] < number_str[i + 1] and number_str[i + 1] < number_str[i + 2] or number_str[i] > number_str[i + 1] and number_str[i + 1] > number_str[i + 2]): return True else: return False # def cond3(number_str): # countdict = collections.Counter(number_str) # for keys in countdict: # if countdict[keys] > 4: # return True # else: # return False def isFancy(num_str): if (cond1(num_str) or cond2(num_str)): #or cond3(num_str) return True else: return False # Driver program mobile_number = '1746294766666' if (isFancy(mobile_number)): print("Yes. You got a fancy number!") else: print(" Neahh, thats not a fancy number.") # s = '90999904835545' # # l2 = [] # # for i in s: # # l2.append(i) # # print(l2) # listy = [n for n in s] # my_dict = collections.Counter(listy) # print(my_dict) # for keys in my_dict: # if my_dict[keys] > 4: # print("YES") # else: # print("NO")
true
ef978c8a5467f6394fc5ce375b075c5afae369d9
tarushsinha/pyLearn
/1.7 RegExp.py
311
4.25
4
## Regular Expressions ## --> Powerful tool for string manipulation ## Useful for pattern matching, and string substitutions ## Regular expressions in Python can be accessed with the `re` module import re pattern = r"spam" if re.match(pattern, "spamspamspam"): print("match") else: print("no match")
true
0bd4bf89f8afb934d4f092034aaebe120dd0805c
Mims20/turtle_race
/main.py
1,241
4.3125
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title='Make a Bet', prompt='Which turtle will win? Enter a color: ') colors = ['yellow', 'orange', 'red', 'green', 'blue', 'purple'] y_coordinate = [-100, -60, -20, 20, 60, 100] all_turtles = [] for turtle_index in range(0, 6): new_turtle = Turtle(shape="turtle") new_turtle.penup() new_turtle.color(colors[turtle_index]) new_turtle.goto(x=-240, y=y_coordinate[turtle_index]) all_turtles.append(new_turtle) is_race_on = False if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: if turtle.xcor() > 230: # checks to see if a turtle has reached the finish line is_race_on = False winner_turtle = turtle.pencolor() # get the color of the winner if user_bet == winner_turtle: print(f"You've Won! {winner_turtle} turtle won the race") else: print(f"You've Lost! {winner_turtle} turtle won the race") # randomizing the forward distance each turtle takes forward_distance = random.randint(0, 10) turtle.forward(forward_distance) screen.exitonclick()
true
4bf9285fbecc7434a559b8a0c38461850cd9cf8b
orangeshushu/LeetCode
/206. Reverse Linked List.py
634
4.125
4
''' Reverse a singly linked list. click to show more hints. Hint: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ p =head res = [] while p: res.insert(0, p.val) p = p.next p = head for i in res: p.val = i p = p.next return head
true
d6eb2b2a0ef3f34e8c872d6a69b4d91211c60e1b
sgriffin10/BIDA
/Class Activity #1/PyBasics__2__Variables_Types.py
708
4.28125
4
#Variables x = 4 # x is of type int x = "Sally" # x is now of type str print(x) #To combine both text and a variable, Python uses the + character: x = "awesome" print("Python is " + x) #If you try to combine a string and a number, Python will give you an error: # Uncomment the 3 lines below to test this out. # Select the lines you want to uncomment and click Control-/ (i.e. control + forward slash) # x = 5 # y = "John" # print(x + y) #To verify the type of any object in Python, use the type() function: x = 1 # int y = 2.8 # float z = "Hello" # complex print(type(x)) print(type(y)) print(type(z)) #Casting: Specify a Variable Type y = int(2.8) # y will be 2 print(y)
true
42f3f3eef47765bca4caa3d6f32a334bd815093a
sgriffin10/BIDA
/Class Activity #1/PyBasics__3__Conditional.py
1,432
4.28125
4
#Conditional Statements #IF..ELSE a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") #shorthand print("b is greater than a") if b > a else print("a and b are equal") if a == b else print("a is greater than b") # #WHILE Loop # i = 1 # while i < 6: # print(i) # # i += 1 # #With the break statement we can stop the loop even if the while condition is true # i = 1 # while i < 6: # print(i) # if i == 3: # break # i += 1 # #With the continue statement we can stop the current iteration, and continue with the next # i = 0 # while i < 6: # i += 1 # if i == 3: # continue # print(i) # # FOR Loops # #A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) # fruits = ["apple", "banana", "cherry"] # for x in fruits: # print(x) # for x in "banana": # print(x) # for x in range(6): # print(x) # else: # print("Finally finished!") # adj = ["red", "big", "tasty"] # fruits = ["apple", "banana", "cherry"] # for x in adj: # for y in fruits: # print(x, y) for x in "banana": print(x) for x in range(6): print(x) else: print("Finally finished!") adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
false
359112b336e60bbb88aefb54a313e9a4612382a3
AngusBangus/Python
/python/caesar.py
2,473
4.4375
4
# Exercise 1: Convert a string of characters to a list of numbers by taking the ASCII value of the numbers def chars_to_nums(c): char = [] sizeofList = len(c) i = 0 while i < sizeofList: char.append(ord(c[i])) i += 1 return char # Provide the correct implementation of this function return "Not the correct result 1 " print chars_to_nums("HELLO WORLD") # Exercise 2: Convert a list of numbers to a string of characters by converting the ASCII values to characters def nums_to_chars(n): # Provide the correct implementation of this function i = 0 num = [] sizeofList = len(n) while i < sizeofList: num.append(chr(n[i])) i += 1 return num return "Not the correct result 2" print nums_to_chars([40, 37, 44, 44, 47, 0, 55, 47, 50, 44, 36]) # Exercise 3: Implement an encode procedure for the Caesar cipher. It should take in the plaintext as a string, the key as an integer, and a modulus as an integer, which corresponds to the size of the alphabet, and produce the appropriate ciphertext. In most cases the modulus will be 95, since there are 95 printable ASCII characters that we can use. The pair (key, mod) makes up the encryption key. def caesar_encode(plaintext, key, mod): # Provide the correct implementation of this function #grab ascii values and change according to the key, i = 0 string = "" sizeofList = len(plaintext) while i < sizeofList: string+= (chr((ord(plaintext[i]) + key)%mod)) i += 1 return string return "Not the correct result 3" print caesar_encode("HELLO", 3, 95) # Exercise 4: Implement the decode procedure for the Caesar cipher. It should take in the ciphertext and the encryption key, and produce the plaintext. def caesar_decode(ciphertext, key, mod): i = 0 string = "" sizeofList = len(ciphertext) while i < sizeofList: string+= (chr((ord(ciphertext[i]) - key)%mod)) i += 1 return string # Provide the correct implementation of this function return "Not the correct result 4" print caesar_decode("KHOOR", 3, 95) # Exercise 5: Assuming the following string was encoded with the Caesar cipher, using some unknown encryption key, recover the plaintext. Type your answer in the string 'ex_5_plaintext' below, do not include any characters in the string, other than the recovered plaintext: ex_5_ciphertext = "-HIIJSYCMY=IIF" print caesar_decode(ex_5_ciphertext, 89, 95) ex_5_plaintext = "3NOOPYISCOOL" print "The message is:", ex_5_plaintext
true
1180e2154deb033234fe9d300b002974ec568a8d
VincentGFL/python_challenge
/programs/twob.py
1,079
4.46875
4
''' Given a string containing lowercase letters (a-z) and numbers, determine whether the string contains more numbers, more letters, or an equal number of both. If the string contains an invalid character (not a-z or 0-9) it should be ignored. If no numbers or letters are present, the default response should be “equal”. countstring("abc123") -> "equal" countstring("hello123") -> "letters" countstring("sdf12345") -> "numbers" countstring("1£2$aAbBcC") -> "letters" countstring("ASD£!((") -> "equal" ''' def countstring(string): letter = 0 number = 0 for index in string: if index.isalpha(): letter += 1 elif index.isalnum(): number += 1 continue if letter == 0 or number == 0: return "equal" elif letter > number: return "letters" elif number > letter: return "number" else: return "equal" print(countstring("abc123")) print(countstring("hello123")) print(countstring("sdf12345")) print(countstring("1£2$aAbBcC")) print(countstring("ASD£!(("))
true
30ca13e3529c756573a0b0e7867bc5bfd763b50c
gitdxb/learning-python
/free-python/udemy-free-python/course-2/control-flow.py
1,359
4.15625
4
#if statement #Turn light on and off light = False if light: light = False else: light = True print(light) ##The above code the same with 'light = not light'. output: false # Odd or even number a = int(input("Please enter a number: ")) #Use int() to convert input to interger if a % 2 == 0: print("You just entered an even number!") else: print("That is an odd number!") #FOR STATEMENT for number in range(1,11): print(number) _list = [True, 123,1212,345,1212,42, "tomorrow"] for items in _list: print(items) #Or print only first 5 items #for items in _list[:5] # print(items) #find top 3 value items _list = [1,2,3,5,7,87,12,4323,653,999,343,88888,32,0,23] max1 = max2 = max3 = min(_list) for x in _list: if x > max3: max1 = max2 max2 = max3 max3 = x elif x > max2: max1 = max2 max2 = x elif x > max1: max1 = x print(max1) print(max2) print(max3) #write a program that checks if a list contains a sublist a = [7,11,23,34,56,89,1] b = [23,34] is_sub_list = False for i in range(len(a)): if(a[i] == b[0]): n = 1 while(n < len(b)) and a[i + n] == b[n]: n += 1 if(n == len(b)): is_sub_list = True print(is_sub_list) #Continue condition for i in rang(1,11): if i % 2 == 0: continue print(i)
true
91d29bae42fd0a9193987d204c9ca3c8126ff616
kamilzazi/Python_Bootcamp_Krakow
/1_podstawy_pgg/zad_11.py
1,333
4.375
4
""" Napisz program, który na podstawie pozycji gracza (x, y) na planszy w przedziale od 0 do 100 wyświetli jego przybliżone położenie (centrum, prawy górny róg, górna krawędź, . . . ) lub informację o pozycji poza planszą. Przyjmij wartość 10 jako margines krawędzi. Przykładowy komunikat programu: Podaj pozycję gracza X: 95 Podaj pozycję gracza Y: 95 Gracz znajduje się w prawym górnym rogu. """ x = int(input("Podaj pozycję gracza X: ")) y = int(input("Podaj pozycję gracza Y: ")) # if x >= 0 and x <= 10: -> if 0 <= x <= 10: # elif x > 10 and x <= 90: -> elif 10 < x <= 90: if 0 <= x <= 10: if 0 <= y <= 10: print("lewy dolny róg") elif 10 < y <= 90: print("lewy krawędź") elif 90 < y <= 100: print("lewy górny róg") else: print("jesteś poza planszą") elif 10 < x <= 90: if 0 <= y <= 10: print("lewa krawędź") elif 10 < y <= 90: print("centrum") elif 90 < y <= 100: print("góna krawędź") else: print("jesteś poza planszą") elif 90 < x <= 100: if 0 <= y <= 10: print("prawy dolny róg") elif 10 < y <= 90: print("prawa krawędź") elif 90 < y <= 100: print("prawy górny róg") else: print("jesteś poza planszą") else: print("poza planszą")
false
5e519eced0ecafc616024ba968a4db8d7a7c4fb4
cdong5/Dog-Walking-Excerciser
/GUI.py
2,255
4.28125
4
# Created by Calvin Dong - 12/30/2018 # Learning tkinter and random Library from random import * from tkinter import * def exercise(): # Reads a txt file named exercises # Places each line of text into a list # Uses the list to generate exercises exerciselist = [] file = open('exercises.txt', 'r') for line in file: ex = line.strip() exerciselist.append(ex) len_exlist = int(len(exerciselist)) ran_ex = exerciselist[randint(0,len_exlist-1)] return ran_ex def num_sec_ex(): # Creates a random number of reps to do for exercise ex_time = randint(10, 20) return ex_time def gen_ex(): # Creates a Label of the exercise and number of reps # Places into the application textframe = Frame(root) textframe.pack() e1 = Label(textframe, text=(f'{exercise()} for {num_sec_ex()} reps')) e1.pack() def num_sec_walk(): # Creates a random variable to tell how long to walk walk_time = randint(120,240) return walk_time def gen_walking(): # Generates a label to tell how long to walk for # Places into the application textframe = Frame(root) textframe.pack() e2 = Label(textframe, text=(f'Walk for {round(num_sec_walk()//60, 2)} minutes')) e2.pack() return e2 def create_list(): # Creates a random list of exercises and walking time # Gets the time you have, and creates a list of exercises to fit in the time time = entry_box.get() current_time = 0 total_time = int(time)*60 while current_time < total_time: gen_walking() gen_ex() current_time += num_sec_ex() current_time += num_sec_walk() # Formating and organization of the GUI root = Tk() root.title('Dog Walk Exerciser') labelframe = Frame(root) labelframe.pack(side=TOP) top_label = Label(labelframe, text='Dog Walk Exerciser').pack(side=TOP) Entry_frame = Frame(root) Entry_frame.pack(side=TOP) entry_label = Label(Entry_frame, text='How Long?') entry_label.pack(side="left", padx=2) entry_box = Entry(Entry_frame) entry_box.pack(side="left", padx=2, pady=2) gen_frame = Frame(root) gen_frame.pack(side=TOP) gen_button = Button(gen_frame, text='Generate', command= create_list) gen_button.pack(pady=2) root.mainloop()
true
cf7c96d4d93b347ef3df853f46725ef048951754
enanibus/biopython
/curso_python/ejemplos/banco.py
988
4.125
4
#! /usr/bin/env python class Banco(): """ Simula las transacciones de un banco""" __clientes = {} def __init__(self, saldo, interes = 2): self.__interes = interes self.__saldo = saldo def Prestamo(self, cliente, dinero): if self.__saldo <= dinero: print "Andamos escasos de dinero :)." else: if cliente in self.__clientes: self.__clientes[cliente] += dinero else: self.__clientes[cliente] = dinero self.__saldo -= dinero def Devolucion(self, cliente): if not cliente in self.__clientes: return "No eres cliente nuestro." else: self.__saldo += (self.__clientes[cliente] + (self.__clientes[cliente] * self.__interes)) del self.__clientes[cliente] def setSaldo(self, saldo): self.__saldo = saldo def getSaldo(self): return self.__saldo def setInteres(self, interes): self.__interes = interes def getInteres(self): return self.__interes saldo = property(getSaldo, setSaldo) interes = property(getInteres, setInteres)
false
5952c4e0a05fdabbc468cf305d8edbc210cfeb2a
Dim-Nike/Py_start
/lessons_2/variables.py
2,417
4.125
4
# ------TRIGGER__PY_START------ word = "Some" # String number = 7 # Integer num_2 = 5.68132 # Float bool = False # Boolean word = "Результат:" number -= 5 x = 8 res = number % x a = z = q = 10 w, r, b = 12, "Word", True print(word, res, w, r, b) age = input("Введите ваш возраст: ") print("Ваш возраст", age) # -------HOMEWORK-------- # TODO Нахождение числа Создайте программу, которая будет принимать число (n), введенное пользователем, и выдавать # результат в виде (n + n * 2). # TODO Работа с переменными # Создайте переменную со значением 46 и переменную со значением "string". Последнюю переменную умножьте на 5. # Выведите на экран обе переменные. # TODO Простые переменные # Создайте переменные со значениями: 5, F, Привет, 90.2. # Создайте переменную, которую нельзя будет изменить и установите ей значение 67. # Выведите переменную со значением "Привет" на экран. # TODO Разделение числа на символы # Напишите программу, которая будет получать от пользователя число с 4 числами. # Реализуйте разделение этого числа на отдельные цифры. # Пример: # Число 5934 # Результат 5, 9, 3, 4 # TODO Получение данных от пользователя # Создайте программу, что будет запрашивать данные пользователя: имя, фамилию, возраст и выводить их на экран. # TODO Математические операции # Создайте программу, которая будет запрашивать три переменные у пользователя и после их получения выводить на экран математически операции над ними: # сумма # вычитание # деление # умножение # остаток при делении
false
86759b830fd23e3b4ce3e7b72f6285678b184784
floydchenchen/leetcode
/116-populating-next-right-pointers-in-each-node.py
2,965
4.25
4
# 116. Populating Next Right Pointers in Each Node # Given a binary tree # # struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; # } # Populate each next pointer to point to its next right node. If there is no next right node, # the next pointer should be set to NULL. # # Initially, all next pointers are set to NULL. # # Note: # # You may only use constant extra space. # Recursive approach is fine, implicit stack space does not count as extra space for this problem. # You may assume that it is a perfect binary tree (ie, all leaves are at the same level, # and every parent has two children). # Example: # # Given the following perfect binary tree, # # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # After calling your function, the tree should look like: # # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ / \ # 4->5->6->7 -> NULL # Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # recursive solution def connect(self, root): if not root or not root.left: return root.left.next = root.right if root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) # iterative solution def connect1(self, root): while root and root.left: next = root.left while root: root.left.next = root.right root.right.next = root.next and root.next.left root = root.next root = next # universal iterative solution for 116 and 117 def connect(self, root): cur = root # loopcur nodeƶͨdown_ptr¼ while cur: # create two dummy pointer nodes right_ptr, down_ptr = Node(-1), Node(-1) # ֻdown_ptrָһߵnodeҵԺͲ down_ptr_found = False # loopcur nodeƶͨright_ptr¼ while cur: # Ϊdown_ptrright_ptrʼһnodedown_ptrָparentһߵnode if cur.left: if not down_ptr_found: down_ptr.next = cur.left down_ptr_found = True right_ptr.next = cur.left right_ptr = right_ptr.next if cur.right: if not down_ptr_found: down_ptr.next = cur.right down_ptr_found = True right_ptr.next = cur.right right_ptr = right_ptr.next cur = cur.next cur = down_ptr.next return root
true
0ffda0479b8b905b89affa0271a628933b5fd92f
floydchenchen/leetcode
/752-open-the-lock.py
2,913
4.1875
4
# 752. Open the Lock # You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. # # The lock initially starts at '0000', a string representing the state of the 4 wheels. # You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. # Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. # Example 1: # Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" # Output: 6 # Explanation: # A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". # Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, # because the wheels of the lock become stuck after the display becomes the dead end "0102". # Example 2: # Input: deadends = ["8888"], target = "0009" # Output: 1 # Explanation: # We can turn the last wheel in reverse to move from "0000" -> "0009". # Example 3: # Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" # Output: -1 # Explanation: # We can't reach the target without getting stuck. # Example 4: # Input: deadends = ["0000"], target = "8888" # Output: -1 class Solution: # two-way BFS def openLock(self, deadends: List[str], target: str) -> int: # helper function to help move up and down def move(s: str, pos: int, up: bool) -> str: s = list(s) if up and s[pos] == '9': s[pos] = '0' if not up and s[pos] == '0': s[pos] = '9' else: s[pos] = str(int(s[pos]) + 1) if up else str(int(s[pos]) - 1) return ''.join(s) deads = set(deadends) q1, q2, visited = set(), set(), set() step = 0 q1.add('0000') q2.add(target) while q1 and q2: temp_q1 = set() for s in q1: if s in deads: continue if s in q2: return step visited.add(s) # move one digit at each position up and down for i in range(4): up = move(s, i, True) if up not in visited: temp_q1.add(up) down = move(s, i, False) if down not in visited: temp_q1.add(down) step += 1 # q1 and q2 q1 = q2 q2 = temp_q1 return -1
true
0e8182fc17ff332c6930b1e85c6615707661d1a2
floydchenchen/leetcode
/150-evaluate-reverse-polish-notation.py
1,703
4.125
4
# 150. Evaluate Reverse Polish Notation # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # # Note: # # Division between two integers should truncate toward zero. # The given RPN expression is always valid. That means the expression would always evaluate to a # result and there won't be any divide by zero operation. # Example 1: # # Input: ["2", "1", "+", "3", "*"] # Output: 9 # Explanation: ((2 + 1) * 3) = 9 # Example 2: # # Input: ["4", "13", "5", "/", "+"] # Output: 6 # Explanation: (4 + (13 / 5)) = 6 # Example 3: # # Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] # Output: 22 # Explanation: # ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 # = ((10 * (6 / (12 * -11))) + 17) + 5 # = ((10 * (6 / -132)) + 17) + 5 # = ((10 * 0) + 17) + 5 # = (0 + 17) + 5 # = 17 + 5 # = 22 class Solution: def evalRPN(self, tokens): """ :type tokens: 1List[str] :rtype: int """ def operation(op, second, first): if op == "*": return first * second elif op == "/": # since python // is different than java /: python always does floor division # https://stackoverflow.com/questions/5535206/negative-integer-division-surprising-result return int(first / second) elif op == "+": return first + second else: return first - second result = [] for token in tokens: if token.lstrip("-").isdigit(): result.append(int(token)) else: result.append(operation(token, result.pop(), result.pop())) return result.pop() sol = Solution() print(sol.evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]))
true
27fe6d0149fa51fd5e9ff87d321bbc575238f416
floydchenchen/leetcode
/366-find-leaves-of-binary-tree.py
1,493
4.25
4
# 366. Find Leaves of Binary Tree # Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, # repeat until the tree is empty. # # # # Example: # # Input: [1,2,3,4,5] # # 1 # / \ # 2 3 # / \ # 4 5 # # Output: [[4,5,3],[2],[1]] # # # Explanation: # # 1. Removing the leaves [4,5,3] would result in this tree: # # 1 # / # 2 # # # 2. Now removing the leaf [2] would result in this tree: # # 1 # # # 3. Now removing the leaf [1] would result in the empty tree: # # [] # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None from collections import defaultdict class Solution: # recursive divide and conquer + dictionary def findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ # 和depth是反的,leaf时是order为0,root的order是max(left, right) + 1 def order(root, dic): if not root: return 0 left, right = order(root.left, dic), order(root.right, dic) level = max(left, right) + 1 dic[level].append(root.val) return level dic, result = defaultdict(list), [] order(root, dic) for i in range(1, len(dic) + 1): result.append(list(dic[i])) return result
true
51378900f7fedfe0974f3da45c274d008581d4ce
floydchenchen/leetcode
/588-design-in-memory-file-system.py
2,328
4.28125
4
# 588. Design In-Memory File System # Design an in-memory file system to simulate the following functions: # ls: Given a path in string format. If it is a file path, return a list that only contains this file's name. If it is a directory path, return the list of file and directory names in this directory. Your output (file and directory names together) should in lexicographic order. # mkdir: Given a directory path that does not exist, you should make a new directory according to the path. If the middle directories in the path don't exist either, you should create them as well. This function has void return type. # addContentToFile: Given a file path and file content in string format. If the file doesn't exist, you need to create that file containing given content. If the file already exists, you need to append given content to original content. This function has void return type. # readContentFromFile: Given a file path, return its content in string format. # Example: # Input: # ["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"] # [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]] # Output: # [null,[],null,null,["a"],"hello"] # https://assets.leetcode.com/uploads/2018/10/12/filesystem.png from collections import defaultdict class TrieNode: def __init__(self): self.children = defaultdict(TrieNode) self.content = "" class FileSystem(object): def __init__(self): self.root = TrieNode() #find and return TrieNode at path. def find(self, path): curr = self.root # no nested path if len(path) == 1: return self.root for word in path.split("/")[1:]: curr = curr.children[word] return curr def ls(self, path): curr = self.find(path) # file path, return file name if curr is a file if curr.content: return [path.split('/')[-1]] # if directory, return children keys return sorted(curr.children.keys()) def mkdir(self, path): self.find(path) def addContentToFile(self, filePath, content): curr = self.find(filePath) curr.content += content def readContentFromFile(self, filePath): curr = self.find(filePath) return curr.content
true
25d0869cffcf30ed5612478ba699701be0b6396c
floydchenchen/leetcode
/043-mutiply-strings.py
1,929
4.21875
4
# 43. Multiply Strings # Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, # also represented as a string. # # Example 1: # # Input: num1 = "2", num2 = "3" # Output: "6" # Example 2: # # Input: num1 = "123", num2 = "456" # Output: "56088" # Note: # # The length of both num1 and num2 is < 110. # Both num1 and num2 contain only digits 0-9. # Both num1 and num2 do not contain any leading zero, except the number 0 itself. # You must not use any built-in BigInteger library or convert the inputs to integer directly. # 思路: product和sum做法不同,不像sum一样两个pointer从右到左扫过,而是每一位都可能过很多遍(下面的例子) # 所以注意在每次操作之后 product[tempPos] %= 10 # 1. 先建一个len(num1) + len(num2) 大的product list # 2. 两个数从后往前,两个for-loop做乘法(如下图) # 3. 为了避免2*3=6而不是06这种情况,将leading zeros去掉 # _ _ _ 1 2 3 # x _ _ _ 4 5 6 # ------------- # 7 3 8 # 6 1 5 # 4 9 2 # ------------- # 5 6 0 8 8 class Solution: def multiply(self, num1, num2): # 1. 先建一个len(num1) + len(num2) 大的product list product = [0] * (len(num1) + len(num2)) # 2. 两个数从后往前,两个for-loop做乘法 for i in range(len(num1) - 1, -1, -1): for j in range(len(num2) - 1, -1, -1): product[j + i + 1] += int(num1[i]) * int(num2[j]) product[j + i] += product[j + i + 1] // 10 product[j + i + 1] %= 10 # print(product) # 3. 为了避免2*3=6而不是06这种情况,将leading zeros去掉 start_index = 0 while start_index < len(product) - 1 and product[start_index] == 0: start_index += 1 return ''.join(map(str, product[start_index:])) print(Solution().multiply("2","3"))
false
ce0e25ce4367119a43a29bf4c85711ac93d8deb7
floydchenchen/leetcode
/226-invert-binary-tree.py
1,583
4.15625
4
# 226. Invert Binary Tree # Invert a binary tree. # # Example: # # Input: # # 4 # / \ # 2 7 # / \ / \ # 1 3 6 9 # Output: # # 4 # / \ # 7 2 # / \ / \ # 9 6 3 1 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # recursive, divide and conquer def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return root # divide and conquer # 这里一定要写成1行,不然需要temp去存root.right的值(因为它会改变) root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root # BFS, level order traversal def invertTree1(self, root): if not root: return root q = [root] while q: node = q.pop(0) node.left, node.right = node.right, node.left if node.left: q.append(node.left) if node.right: q.append(node.right) return root # iterative DFS, stack def invertTree2(self, root): if not root: return root stack = [root] while stack: node = stack.pop() node.left, node.right = node.right, node.left if node.left: stack.append(node.left) if node.right: stack.append(node.right) return root
true
4273cd45078991b43b59bb232b6206161bed0798
geiyer/python
/Module01/math-operators.py
383
4.125
4
print('Welcome to Python') print('Addition: (2+7): ' + str(2+7)) print('subsctraction: (2-7) : ' + str(2-7)) print('Multiplication: (2*7):' + str(2*7)) print('Division: (7/2): ' + str(7/2)) print('Modulus: (7%2): ' + str(7%2)) print('Floor division: (8//3): ' + str(7//2)) print('Exponent: (2**3)' + str(2**3)) # Comments # Line 2 # Line 3 """ Comments are written here. """
false