blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9ffc86036d180e3c720348674ba0a62fd1c7c23e
LalithK90/LearningPython
/privious_learning_code/String/StringCenter()Method.py
394
4.21875
4
str = "this is string example....wow!!!" print("str.center(40, 'a') : ", str.center(40, 'a')) # The method center() returns centered in a string of length width. Padding is done using the specified fillchar. # Default filler is a space. Syntax # # str.center(width[, fillchar]) # # Parameters # # width − This is the total width of the string. # # fillchar − This is the filler character.
true
9c181fba8db69a77b8d2e09e085b0330d83bb11a
aifulislam/Python_Demo_Five_Part
/program7.py
1,729
4.71875
5
#07/October/2020-------- #Python Operator------- #Python Arithmetic Operator-------- print("Python Arithmetic Operator--------") x = 8 y = 2 print(x+y) x = 8 y = 2 print(x-y) x = 8 y = 2 print(x*y) x = 8 y = 2 print(x/y) x = 9 y = 2 print(x%y) x = 8 y = 4 print(x**y) x = 8 y = 4 print(x//y) #Python Assignment Operator-------- print("Python Assignment Operator--------") x = 5 print(x) x = 5 x += 3 print(x) x = 5 x -= 3 print(x) x = 5 x *= 3 print(x) x = 5 x /= 3 print(x) x = 7 x %= 3 print(x) x = 5 x //= 3 print(x) x = 5 x **= 3 print(x) x = 5 x &= 3 print(x) x = 5 x |= 3 print(x) x = 5 x ^= 3 print(x) x = 5 x >>= 3 print(x) x = 5 x <<= 3 print(x) #Python Comparison Operator-------- print("Python Comparison Operator--------") x = 5 y = 3 print(x==y) x = 5 y = 3 print(x!=y) x = 5 y = 3 print(x>y) x = 5 y = 3 print(x<y) x = 5 y = 3 print(x>=y) x = 5 y = 3 print(x<=y) #Python Logical Operator-------- print("Python Logical Operator--------") x = 5 print(x > 3 and x < 12 ) x = 5 print(x > 3 or x < 12 ) x = 5 print(not(x > 3 and x < 12 )) #Python Identity Operator-------- print("Python Identity Operator--------") x = ["Apple", "Banana"] y = ["Apple", "Banana"] z = x print(x is y) print(x is z) print(x == y) #Python Membership Operator-------- print("Python Membership Operator--------") x = ["apple","banana"] print("banana" in x) x = ["apple","banana"] print("orange" not in x) #Python Bitwise Operator-------- print("Python Bitwise Operator--------") #& and #| or #^ XOR #~ NOT #<< Zero fill left shift #>> Signed fill Right shift
false
ba0eb3697461b90f82dac8753cc9ce4cb97dc657
aifulislam/Python_Demo_Five_Part
/program13.py
1,508
4.21875
4
#13/October/2020-------- #Python---while--Loop----- #Python---for--Loop----- i = 1 while i < 6: print(i) i+=1 print("break---------") i = 1 while i < 15: print(i) if (i == 10): break i += 1 print("Continue---------") i = 0 while i < 6: i += 1 if i== 3: continue print(i) print("Continue---------") i = 0 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") #Python---for--Loop----- fruits = ["Apple", "Banana", "Orange"] for x in fruits: print(x) for x in "banana": print(x) fruits = ["Apple", "Banana", "Orange"] for x in fruits: print(x) if x == "banana": break fruits = ["Apple", "Banana", "Orange"] for x in fruits: if x == "Banana": break print(x) fruits = ["Apple", "Banana", "Orange"] for x in fruits: if x == "Banana": break print(x) fruits = ["Apple", "Banana", "Orange"] for x in fruits: if x == "Banana": continue print(x) #Using the range() function------- for x in range(6): print(x) for x in range(2,6): print(x) for x in range(2,20,2): print(x) #Else in for Loop----- for x in range(5): print(x) else: print("Finally finished") #Nested Loops--- adj = ["red", "big", "nice",] fruits = ["Apple", "Banana", "Orange"] for x in adj: for y in fruits: print(x,y) #Pass loop-- for x in [0 , 1, 2]: pass
false
b9008846665e4ebad55a4ce314651fe99a190011
aifulislam/Python_Demo_Five_Part
/program6.py
890
4.21875
4
#06/October/2020-------- #Python Booleans------- #True or False-------- print(10>9) print(10==9) print(10<9) a = 80 b = 133 if a > b: print("a is greater than b.") else: print("b is greater than a.") print(bool("Hello")) print(bool(15)) x = "Hello" y = 15 print(bool(x)) print(bool(y)) print(bool("abc")) print(bool(123)) print(bool(["Apple","banana","orange"])) #False----- print(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool({})) print(bool([])) class myclass(): def __len__(self): return True #return False #return 0 #return 1 myobj = myclass() print(bool(myobj)) def myFunction(): return True if myFunction(): print("Yes!") else: print("No!") x = 100 print(isinstance(x, int)) x = 100.50 print(isinstance(x, float))
false
ca09433b3b42f4053288524ad61ad69f67d13659
scivarolo/py-ex04-tuples
/zoo.py
481
4.25
4
# Create a tuple named zoo zoo = ("Lizard", "Fox", "Mammoth") # Find an animal's index print(zoo.index("Fox")) # Determine if an animal is in your tuple by using value in tuple lizard_check = "Lizard" in zoo print(lizard_check) # Create a variable for each animal in the tuple (lizard, fox, mammoth) = zoo # Convert to a list zoo_list = list(zoo) # Extend list with more animals zoo_list.extend(["Giraffe", "Zebra", "Quokka"]) # Convert back to a tuple zoo = tuple(zoo_list)
true
2c0da1b242caabe0009335f12095c5cec1779976
AliCanAydogdu/Intro_to_Python
/chapter2_Lists.py
2,565
4.53125
5
#Here's a simple example of a list bicycles = ['trek','canonndale','redline','specialized' ] print(bicycles[0]) print(bicycles[0].title()) #Index Numbers Start at 0, Not 1 # At Index -1, python returns the last item, at index -2 second item from the end of list, so on. #Using Individual Values from the list bicycles = ['trek','canonndale','redline','specialized' ] message = "My first bicycle was a " + bicycles[2].title() + '.' print(message) #Changing an item in the list motorcycles =["Honda","Kawasaki","Yamaha"] print(motorcycles) motorcycles[0]="Ducati" print(motorcycles) #Adding Elements to a List #Appending Elements to the end of a list motorcycles =["Honda","Kawasaki","Yamaha"] print(motorcycles) motorcycles.append("Ducati") print(motorcycles) #Creating an empty list and adding elements with append motorcycles = [] motorcycles.append("Honda") motorcycles.append("Kawasaki") motorcycles.append("Yamaha") print(motorcycles) #Inserting Elements into a List #You can add a new element at any position in your list by using the insert() motorcycles =["Honda","Kawasaki","Yamaha"] motorcycles.insert(0,"Ducati") print(motorcycles) #Removing Elements from a list #Removing an Item Using the del Statement motorcycles =["Honda","Kawasaki","Yamaha"] print(motorcycles) del motorcycles[0] print(motorcycles) #Removing an Item Using the pop() Method motorcycles =["Honda","Kawasaki","Yamaha"] print(motorcycles) popped_motorcycle = motorcycles.pop() print(motorcycles) print(popped_motorcycle) #Popping Items from any position in a list motorcycles =["honda","kawasaki","yamaha"] first_owned = motorcycles.pop(0) print("The first motorcycle I owned was a " + first_owned.title()) #Removing an Item by Value motorcycles =["honda","kawasaki","yamaha"] print(motorcycles) motorcycles.remove("yamaha") print(motorcycles) #Organizing a List #Sorting a list permanently with the sort() method cars = ["bmw", "audi", "toyota", "subaru"] cars.sort() print(cars) #Sorting the list in reverse alphabetical order cars = ["bmw", "audi", "toyota", "subaru"] cars.sort(reverse = True) print(cars) # Sorting a list temporarily with the sorted() function 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) #Printing a list in reverse order cars = ["bmw", "audi", "toyota", "subaru"] print(cars) cars.reverse() print(cars) #Finding the length of a list cars = ["bmw", "audi", "toyota", "subaru"] len(cars)
true
d5b41acd88de4996f061b79ef73ec60fa68ce747
yami2021/PythonTests
/Assignment/area_traingle_new.py
585
4.125
4
def check_user_input(input): try: # Convert it into integer val1 = float(input) return val1 #return val1 #print("Input is an integer number. Number = ", val) except ValueError: print("No.. input is not a number. It's a string") area() def area(): input1 = input("Enter the base of triangle ") base = check_user_input(input1) input2 = input("Enter the height of the triangle") height = check_user_input(input2) area = base * height /2 print("The calculated area is {}".format(area)) area()
true
6b000f4ecd08235fe57b54a58d7dbe8a7d5a530f
markplotlib/treehouse
/basic-python/Lists/list_intro.py
2,201
4.1875
4
# quiz of lists dict_of_lists = { 'list("Paul")': list("Paul"), 'list(["Paul"])': list(["Paul"]), 'list(["Paul", "John"])': list(["Paul", "John"]) } def quiz_of_lists(dict_of_lists): for key, value in dict_of_lists.items(): print("=" * 44) print("What is the length of this list? ") print(" " + str(key)) guess = int(input("Your guess is: ")) answer = len(value) if bool(guess==answer): print("Correct!") else: print("Sorry. The answer is " + str(answer)) input("Press Enter") def insert_first(): # putting Jesus first in the Beatles pass # beatles.insert(0, "Jesus") def quiz_del(): print("=" * 44) print(''' surname = "Rasputin" advisor = surname del surname What is stored in the variable advisor? A) 'Rasputin' B) NameError, advisor not found C) None, the object has been deleted ''') guess = input() while guess.upper() != "A": print("Nope, guess again.") guess = input() print("Well done! That's right! del just deletes the label, not the value. surname is no longer available, but advisor still is.") def multidimensional_list(): pass ''' travel_expenses = [ [5.00, 2.75, 22.00, 0.00, 0.00], [24.75, 5.50, 15.00, 22.00, 8.00], [2.75, 5.50, 0.00, 29.00, 5.00], ] print("Travel Expenses") week_number = 1 for week in travel_expenses: print("****") print("* Week #{}: ${}".format(week_number, sum(week))) week_number += 1 ''' quiz_of_lists(dict_of_lists) quiz_del() insert_first() multidimensional_list() def display_wishlist(display_name, wishes): print(display_name + ":") suggestions = wishes.copy() suggested_gift = suggestions.pop(0) print("=========>" + suggested_gift + "<=========") for suggestion in suggestions: print("* " + suggestion) print() input("view the wishlist feature") games = ["Bomberman", "Captain Chaos", "X-Men"] display_wishlist("games", games) beatles = list(["Paul", "John"]) others = list(["George","Ringo"]) beatles.extend(others)
true
685094695eacff77c8838ef8ba06c56b31819d95
himrasmussen/solitaire-fyeah
/testsuite.py
1,621
4.125
4
class Table(): """A class modelling the table.""" def __init__(self, deck): """Initialize the rows and stacks.""" self.stack = Stack() self.columns = {i: [] for i in range(7)} #? self.acestacks = OrderedDict() for suit in "hearts diamonds spades clubs".split(): self.acestacks[suit] = [] """Cast the solitaire.""" for column in range(6, 0, -1): for row in range(column): self.columns[column].append(deck.cards.pop()) self.columns[column][-1].orientation = 'down' for column in range(7): self.columns[column].append(deck.cards.pop()) self.columns[column][-1].orientation = 'up' def view(self): """ The string representation of the table. A nicely formatted table. """ for suit, stack in self.acestacks.items(): try: print('|' + stack[-1] + '|', end='') except IndexError: print('|' + suit.center(13) + '|', end='') print() max_column_len = max([len(column) for column in self.columns.values()]) for column in range(6, -1, -1): for row in range(max_column_len): try: print(self.columns[column][row], end='') except IndexError: print(''.center(15), end='') print() print() try: print('|' + self.stack.cards[-1] + '|') except IndexError: print('|' + 'The Stack'.center(13) + '|') table = Table("d")
true
0e80cfb3ac5ea66678c4b99ad82e536098e09789
darrenpaul/open-pipeline
/environment/modules/data/op_dictionary.py
771
4.1875
4
def merge_dictionaries(original=None, new=None): """ This will merge two dictionaries together, the original dictionary will be updated in memory. Keyword Arguments: original {dictionary} -- The original dictionary new {dictionary} -- The new dictionary """ for key, val in new.iteritems(): if isinstance(val, dict): if key in original: merge_dictionaries(original=original[key], new=val) else: original[key] = val else: if isinstance(val, list): if key in original: val = val + original[key] else: original[key] = val else: original[key] = val
true
0c28a6e808b0ee6bf59d613d4c006b7914626eef
Pixelus/Programming-Problems-From-Programming-Books
/Python-crash-course/Chapter7/multiples_of_ten.py
218
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 29 2018 @author: PixelNew """ number = input("Enter a number please: ") if(int(number) % 2 == 0): print("Your number is even.") else: print("Your number is odd.")
true
adbd6615816af81a918cbbba0886d80be36b7879
evaseemefly/InterviewTest
/基础知识总结/demo_值类型与引用类型.py
645
4.1875
4
''' str是否为值类型 ''' str_a="abcde" # str_b=str_a str_b="abcde" str_c=str_a str_a="cedfg" print("str_a:%s,id:%s"%(str_a,id(str_a))) print("str_b:%s,id:%s"%(str_b,id(str_b))) print("str_c:%s,id:%s"%(str_c,id(str_c))) # print(str_b[0:2]) # str_b[0:2]="fg" # print(id(str_b)) print("-----------") ''' 对于引用类型 list或字典 ''' list_a=[1,2,3] list_b=[2,3,4] list_c=list_a list_c[2]=6 print("list_a:%s,id:%s"%(list_a,id(list_a))) print("list_b:%s,id:%s"%(list_b,id(list_b))) print("list_c:%s,id:%s"%(list_c,id(list_c))) print("-----------") int_a=1 int_b=1 int_c=int_a int_a=2 print(id(int_a)) print(id(int_b)) print(id(int_c))
false
c7fcd6f3f827e756c6758eb9fb489bf51873e091
javacode123/learn_python
/chapter4/anonymous_func.py
490
4.15625
4
# -*- coding: utf-8 -*- # 匿名函数使用 lambda x: x * x 相当于 def f(x): return x * x print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6]))) # 匿名函数也是一个函数对象,可以进行赋值给一个变量,匿名函数可以有效防止函数重名 f = lambda x: x * x print(f, f(5)) # 测试,构造匿名函数 def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) l = list(filter(lambda x: x % 2 == 1, range(1, 20))) print(l == L)
false
c895b752f72217d3b4afe224554d861b6f09be75
chaitanyamean/python-algo-problems
/Array/monotonic.py
454
4.125
4
'''Given a non-empty array of integers, find if the array is monotonic or not ''' def isMonotonic(array): isNonIncreasing = True isNonDecreasing = True for i in range(1, len(array)): if array[i] < array[i -1]: isNonDecreasing = False if array[i] > array[i-1]: isNonIncreasing = False return isNonDecreasing or isNonIncreasing print(isMonotonic([-1, -5, -10, -1100, -1100, -1101, -1102, -9001]))
true
df2952366ddca95d50978caaba441a94abefdf6a
AlexB196/python-exercises
/.idea/shopping.py
590
4.1875
4
shopping_list = ["milk", "pasta", "eggs", "spam", "bread", "rice"] #list is created with square brackets # for item in shopping_list: # if item != "spam": # print("Buy " + item) #CONTINUE! - mai jos # for item in shopping_list: # if item == "spam": #cand gaseste "spam", il sare si trece la urmatorul item # continue #cand ajunge sa fie executed, tot ce este in loop va fi ignorat # print("Buy " + item) #BREAK - mai jos for item in shopping_list: if item == "spam": break #cand ajunge sa fie executat, loop-ul se termina print("Buy " + item)
false
cd6d93b45427751279adf4560ebe1717562133f9
AlexB196/python-exercises
/.idea/augmenteda_inaloop_challenge.py
521
4.40625
4
number = 10 multiplier = 8 answer = 0 # add your loop after this comment for i in range(multiplier): i = number answer += i #IMPORTANT! I don't have to use i above. I can simply type answer += number #the loop will end when the condidition becomes false, but I dont have to use that i print(answer) #in the code above, I want to print the answer which is number * multiplier #but I want to do this by adding up the number for {multiplier} times - make the sum #and I also wanna use augmented assignment
true
bd3e9521b7c49cfbbed1c9e2a62aefc31a827540
AlexB196/python-exercises
/.idea/motorbike.py
252
4.25
4
bike = {"make": "Honda", "model": "250 dream", "color": "red", "engine_size": 250} print(bike["engine_size"]) print(bike["color"]) #bike is a dictionary #we can access different entry from the dictionary - doesn't matter if it's a number #or a string
true
5bc0264a032c7a163c6724ebdfbbb406c53027eb
mariomf/pythonPractice
/Calculadora.py
1,624
4.1875
4
def realizar_operacion(opcion): if opcion == '1': try: a = int(input("Dame un numero ")); b = int(input("Dame otro numer ")); except ValueError: print("Eso no es un numero"); else: suma = a + b; print("La suma es: " + str(suma)); elif opcion == '2': try: a = int(input("Dame un numero ")); b = int(input("Dame otro numer ")); except ValueError: print("Eso no es un numero"); else: suma = a - b; print("El resultado es: " + str(suma)); elif opcion == '3': try: a = int(input("Dame un numero ")); b = int(input("Dame otro numer ")); except ValueError: print("Eso no es un numero"); else: suma = a * b; print("El resultado es: " + str(suma)); elif opcion == '4': try: a = int(input("Dame un numero ")); b = int(input("Dame otro numer ")); except ValueError: print("Eso no es un numero"); else: suma = a / b; print("El resultado es: " + str(suma)); flag = 'si'; while flag == 'si': print("\n"+"Bienvanido a la calculadora"+"\n"+ "Estas son las operaciones que puedes ralizar:"+"\n"+ "1 - Suma"+"\n"+ "2 - Resta"+"\n"+ "3 - Multiplicacion"+"\n"+ "4 - Division"+"\n") opcion = input("Introduce el numero de operacion quieres realizar: "); realizar_operacion(opcion) flag = input("Deseas continuar? si/no ");
false
c280890b699b21cedad4771f4fa22dff35292bc8
alexnicholls1999/Python
/BMI.py
252
4.1875
4
#User Enters weight in Kilograms print ("What is your weight? (kg)?") weight = int(input()) #User Enters Height in Metres print ("What is your height? (m)") height = float(input()) #Users BMI print ("Your bmi is","{0:.2f}".format(weight/height**2))
true
7327f9ba8d63593e2526440e5c587bcb307f9285
KhinYadanarAung/CP1404_Practicals
/Prac_05/color_names.py
502
4.34375
4
COLOR_NAMES = {"ALICEBLUE": "#f0f8ff", "ANTIQUEWHITE": "#faebd7", "ANTIQUEWHITE1": "#ffefdb", "ANTIQUEWHITE2": "#eedfcc", "ANTIQUEWHITE3": "#cdc0b0", "ANTIQUEWHITE4": "#8b8378", "AQUAMARINE1": "#7fffd4", "AQUAMARINE2": "#76eec6", "AQUAMARINE4": "#458b74", "AZURE1": "#f0ffff"} color = input("Enter color name: ").upper() while color != "": if color in COLOR_NAMES: print(color, "is", COLOR_NAMES[color]) else: print("Invalid color name") color = input("Enter color name: ")
false
7440bcf10ad32f5ceb3d333722616fd6311edff4
ValentinaSoldatova/Data_Science
/Алгоритмы и структуры данных на Python./7/les_7_task_2.py
2,118
4.125
4
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив, #заданный случайными числами на промежутке [0; 50). # Выведите на экран исходный и отсортированный массивы. # вариант 1 from random import randint MAX_SIZE = 50 def merge_sort(array): if len(array) < 2: return array mid = len(array) // 2 left_part = array[:mid] right_part = array[mid:] left_part = merge_sort(left_part) right_part = merge_sort(right_part) return merge_list(left_part, right_part) def merge_list(list_1, list_2): result = [] i = 0 j = 0 while i < len(list_1) and j < len(list_2): if list_1[i] <= list_2[j]: result.append(list_1[i]) i += 1 else: result.append(list_2[j]) j += 1 result += list_1[i:] result += list_2[j:] return result numbers = [randint(0, 50) for _ in range(MAX_SIZE)] print(numbers) print(merge_sort(numbers)) # вариант 2 def merge_sort(array): def merge(fst, snd): res = [] i, j = 0, 0 while i < len(fst) and j < len(snd): if fst[i] < snd[j]: res.append(fst[i]) i += 1 else: res.append(snd[j]) j += 1 res.extend(fst[i:] if i < len(fst) else snd[j:]) return res def div_half(lst): if len(lst) == 1: return lst elif len(lst) == 2: return lst if lst[0] <= lst[1] else lst[::-1] else: return merge(div_half(lst[:len(lst)//2]), div_half(lst[len(lst)//2:])) return div_half(array) SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 50 array = [random.uniform(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print('Массив:', array, sep='\n') print('После сортировки:', merge_sort(array), sep='\n')
false
d6955c89a330de6c7627929e25be196741a7b298
Deep455/Python-programs-ITW1
/python_assignment_1/21.py
289
4.15625
4
def spliting(arr,n): return [arr[i::n] for i in range(n)] a=input("enter the elements of list seperated by commas : ").split(",") arr=list(a) n=int(input("enter size of splitted list u want to see :")) print("list : ") print(arr) print("list after spliting : ") print(spliting(arr,n))
true
ddd8cc2fe85fe0019c7bf9906542d47df1a68c18
Deep455/Python-programs-ITW1
/python_assignment_1/4.py
242
4.1875
4
def inserting(string,word): l=len(string) l=l//2 new_string=string[:l]+word+string[l:] return new_string string=input("enter a string : ") word=input("enter a word u want to insert : ") new_string=inserting(string,word) print(new_string)
true
85cca267caf2f35474c4786c9b939d30dc4e4450
shubham79mane/tusk
/reverse_link_list.py
1,515
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 5 09:50:42 2021 @author: mane7 """ #!/bin/python3 import math import os import random import re import sys class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = DoublyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node node.prev = self.tail self.tail = node def print_doubly_linked_list(node): while node: print(node.data,end=" ") node = node.next # # Complete the 'reverse' function below. # # The function is expected to return an INTEGER_DOUBLY_LINKED_LIST. # The function accepts INTEGER_DOUBLY_LINKED_LIST llist as parameter. # # # For your reference: # # DoublyLinkedListNode: # int data # DoublyLinkedListNode next # DoublyLinkedListNode prev # # def reverse(head): while head: head.prev,head.next=head.next,head.prev c=head head=head.prev return c t = int(input()) for t_itr in range(t): llist_count = int(input()) llist = DoublyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) llist1 = reverse(llist.head) print_doubly_linked_list(llist1)
true
fbcf813a88bdde668127ea04d433328e777fa1ff
tothricsaj/-pythonLearnForMyself
/functions/multipleReturnValues/main.py
969
4.125
4
if __name__ == "__main__": print('hello multiple return values :S\n') ############################################ # using object ----> class Test: def __init__(self): self.str = "This is a string value" self.integer = 23 def func(): return Test() f = func() print(f.str) print(f.integer) print(f.__dict__) print('\n') ############################################ # using tuples -------> def tuple_func(): return 'Tuple string', 42 str, integer = tuple_func() print(str) print(integer) print('\n') ############################################ # using dictionary -----------> def dic_func(): d = dict() d['str'] = 'Dictionary String' d['x'] = 2323 return d d = dic_func() print(d) print(d["str"]) print(d["x"]) print('\n') ############################################
false
1aa5306e1469f2dbfd4ce0891a9abd7c25570c02
fahrettinokur/python
/tuple.py
647
4.1875
4
tupleliste =(2,3,4,"Adana",(5,7,6),[]) liste=[2,3,4,"Adana",[5,8,9],()] #tuple de amaç tek seferde içlerine yazılarını yazrsın sonradan değiştiremesin. print(type(tupleliste)) print(type(liste)) print(tupleliste) print(liste) print(len(tupleliste)) print(len(liste)) print("\n\n\n\n\n") print(tupleliste[-2]) print(liste[-2]) print("\n\n\n\n\n") print(tupleliste[1:2]) #gördüğünüz üzere virgül var print(liste[1:2]) tupledeger =("fahrettin") print(type(tupledeger)) #burada python bunu tuple olarak alğılamıyor onun için şu yapımalı tupledeger1 =("fahrettin",) print(type(tupledeger1))
false
07a18fe8e58daff9a1f9a5761336e54106400513
fahrettinokur/python
/iteratörler.py
278
4.1875
4
sehir=["Adana","Ankara","izmir","mersin"] iteratör=iter(sehir) print(next(iteratör)) print(next(iteratör)) print(next(iteratör)) print(next(iteratör)) print("\n") #aslında ikisi aynı şey for içinde iteratorler var for i in sehir: print(i)
false
142d08a7ad923f75fd02732b4512f47af3c4b452
potatonumbertwo/Thinkp-CS-1101
/unit_4_assignment.py
1,332
4.25
4
import time start_time = time.time() def is_power(a, b): # """ define a function that a is a power of b if a is divisible by b # and a/b is a power of b ,returns True if a is a power of b""" if a == b: # base case of two arguments are equal return True if b == 1: return False # base case of the second argument is 1 isADivisibleByB = is_divisible(a, b) == 1 # assign is_divisible() to a variable to check is_divisible is True isADiviedByBIsPowerofB = a / b % b == 0 # variable checks a/b is power of b ,== mean equal here if isADivisibleByB and isADiviedByBIsPowerofB: return True # call itself recursively else: return False def is_divisible(x, y): if x % y == 0: return True else: return False print("is_power(10, 2) returns: ", is_power(10, 2)) print("is_power(27, 3) returns: ", is_power(27, 3)) print("is_power(1, 1) returns: ", is_power(1, 1)) print("is_power(10, 1) returns: ", is_power(10, 1)) print("is_power(3, 3) returns: ", is_power(3, 3)) print(time.time() - start_time) # print(6.508827209472656e-05 - 7.486343383789062e-05) # is_power(10, 2) returns: False # is_power(27, 3) returns: True # is_power(1, 1) returns: True # is_power(10, 1) returns: False # is_power(3, 3) returns: True # 7.295608520507812e-05
false
8a49408a77dba2167a07fc63cbbec7feb256e035
potatonumbertwo/Thinkp-CS-1101
/Unit7_discussion.py
2,114
4.1875
4
# 11.2 def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d # print(histogram('potato')) # knights = {'gallahad': 'the pure', 'robin': 'the brave'} # >>> for k, v in knights.items(): # ... print(k, v) ''' # 11.3 Looping and dictionaries def print_hist(h): for c in h: print(c, h[c]) h = histogram('potato') # print_hist(h) for key in sorted(h): # sorted order print(key, h[key]) # 11.4 Reverse lookup def reverse_lookup(d, v): # search pattern for k in d: if d[k] == v: return k raise LookupError() # built-in exception it can take a detail error message word = histogram('potato') key = reverse_lookup(word, 2) print(key) ''' # 11.5 Dictionaries and lists # 12.5 Lists and tuples ''' Tuple can be useful with loops over list because zip function returns a list of tuple each tuple can contain a element corresponding with another element from the lists ''' items = ['potato', 'apple pair', 'banana', 'steak'] prices = [0.99, 2.45, 0.45, 6.78] discount = [0, 0.45, 0, 0.8] def zip_example(): for i in zip(items, prices, discount): print(i) zip_example() ''' Output: ('potato', 0.99, 0) ('apple pair', 2.45, 0.45) ('banana', 0.45, 0) ('steak', 6.78, 0.8) ''' def enumerate_example(): for index, element in enumerate(items): print(index, element) enumerate_example() ''' Output: 0 potato 1 apple pair 2 banana 3 steak The result from enumerate is an enumerate object, which iterates a sequence of pairs; each pair contains an index (starting from 0) and an element from the given sequence ''' ''' Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair. ''' def items_example(): for key, value in grades.items(): print(key, value) grades = {'math': 99, 'english': 90, 'science': 95, 'physics': 100, 'chemistry': 3} items_example() ''' Output: math 99 english 90 science 95 physics 100 chemistry 3 ''' my_list = [3, 2, 1] print(my_list.sort())
false
cb6b0d3fe2cf81a12a4ca2caee1789b48975c6f5
SophiaTanOfficial/John-Jacob
/speak.py
2,137
4.25
4
# Let's use some methods to manipulate the string stored in name. name = "John Jacob Jingleheimer Schmidt" # 1. Use print and a built-in method to print out the string "jOHN jACOB jINGLEHEIMER sCHMIDT" print(name.swapcase()) # 2. Use print and a built-in method to print out the string "JOHN JACOB JINGELHEIMER SCHMIDT" print(name.upper()) # 3. Use print and a built-in method to count how many times the letter i is in Mr. Schmidt's name. count = name.count('i') print(count) # 4. Use print and a built-in method to print out Mr. Schmidt's name, but with all the instances of the letter i removed or deleted. print (name.replace('i', "")) # 5. Use print and a built-in function to find out how many characters are in Mr. Schmidt's name. ## NOTE that since this is a funciton and not a method, the best solution won't be on the string methods page - you'll need to Google this one. print(str(len(name) - name.count(' '))) # 6. Use a built-in method to replace every letter J with the letter G instead. Bonus point if you can say the result out loud without laughing. print (name.replace('J', 'G')) # 7. Chain a few methods together to print out the string with all the vowels removed. def remove_vowels(name): vowels = ('a', 'e', 'i', 'o', 'u') for x in name.lower(): if x in vowels: name = name.replace(x, "") print(name) # 8. Try to print the name as four separate strings by using a function that will split it up like this: ["John", "Jacob", "Jingleheimer", "Schmidt"] print (name.replace(" ", ", ")) # 9. Print out only the first four letters of the string. firstFourLetters = name[:4] print (firstFourLetters) # 10. Print out only the first ten letters of the string but make them all uppercase. firstTenLetters = name[:12] print(firstTenLetters.upper()) # 11. CHALLENGE: Try to print out the string "tdimhcS remiehelgniJ bocaJ nhoJ" (which is the name backwards) def reverse(name): str = "" for i in name: str = i + str return str print (reverse(name)) # 12. CHALLENGE: Chain two methods together to print out the string "TDIMHCS REMIEHELGNIJ BOCAJ NHOJ", (which is the name in uppercase and backwards). print (reverse(name).upper())
true
c07018bd5edc5de46ddd36e9bff3e7c6b2a773b8
ledigofig/Selenium_com_Python_dunosauro
/Curso Introdutorio de python/16_listas_1.py
1,568
4.4375
4
#lista é definida poor [] minha_lista_compras = ['sabão', 'sabonete', 'arroz', 'moster',10,[1,2,3] ] #minha_lista_compras for item in minha_lista_compras: print(item) ''' [leandro]@[Curso Introdutorio de python]python -i 16_listas.py >>> minha_lista_compras[0] 'sabão' >>> minha_lista_compras[1] 'sabonete' >>> minha_lista_compras[2] 'arroz' >>> minha_lista_compras[3] 'moster' >>> ------------------------------- #pegando por posição [leandro]@[Curso Introdutorio de python]python -i 16_listas.py sabão sabonete arroz moster 10 [1, 2, 3] >>> minha_lista_compras[-1] [1, 2, 3] >>> minha_lista_compras[-1][-1] 3 >>> minha_lista_compras[-1][0] 1 ---------------------------------------- slice - listas [leandro]@[Curso Introdutorio de python]python -i 16_listas.py sabão sabonete arroz moster 10 [1, 2, 3] >>> minha_lista_compras[-1] [1, 2, 3] >>> minha_lista_compras[-1][-1] 3 >>> minha_lista_compras[-1][0] 1 >>> nomes = ['Eduardo','leandro','Rosangela','Theo','Mariaclara'] >>> nomes[-1] 'Mariaclara' >>> nomes[0:-1] ['Eduardo', 'leandro', 'Rosangela', 'Theo'] >>> nomes[0:-2] ['Eduardo', 'leandro', 'Rosangela'] >>> nomes[0:2] ['Eduardo', 'leandro'] >>> nomes::2] File "<stdin>", line 1 nomes::2] ^ SyntaxError: invalid syntax >>> nomes[::2] ['Eduardo', 'Rosangela', 'Mariaclara'] >>> 'Leandro' [::-1] 'ordnaeL' ---------------- Comandos x.append() inseri na ultima posição x.remove() remove x.insert() inseri na posição desejada x.pop() *tira um valor x.count() counta um valor x.reverse() mostra a lista de traz para frente '''
false
f0e8a498b38f965754c666887ae93fb7d5d2b0ed
MrzvUz/python-in-100-days
/day-002/day-2-1-exercise.py
1,440
4.4375
4
'''Data Types Instructions Write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 + 5 = 8 Warning. Do not change the code on lines 1-3. Your program should work for different inputs. e.g. any two-digit number. Example Input 39 Example Output 3 + 9 = 12 12 e.g. When you hit run, this is what should happen: https://cdn.fs.teachablecdn.com/iyJTPDDRRJCB1gmdVQMS Hint Try to find out the data type of two_digit_number. Think about what you learnt about subscripting. Think about type conversion.''' # 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 user_number = list(two_digit_number) sum_number = int(user_number[0]) + int(user_number[1]) print(sum_number) # Solution: # 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 #Check the data type of two_digit_number print(type(two_digit_number)) #Get the first and second digits using subscripting then convert string to int. first_digit = int(two_digit_number[0]) second_digit = int(two_digit_number[1]) #Add the two digits togeter two_digit_number = first_digit + second_digit print(two_digit_number)
true
8467d45c9f556014374caff485162cbe8d314ec7
MrzvUz/python-in-100-days
/day-008/day-8-2-prime_numbers.py
1,865
4.21875
4
'''Prime Numbers Instructions Prime numbers are numbers that can only be cleanly divided by itself and 1. https://en.wikipedia.org/wiki/Prime_number You need to write a function that checks whether if the number passed into it is a prime number or not. e.g. 2 is a prime number because it's only divisible by 1 and 2. But 4 is not a prime number because you can divide it by 1, 2 or 4. https://cdn.fs.teachablecdn.com/s0gceS97QD6MP5RUT49H Here are the numbers up to 100, prime numbers are highlighted in yellow: https://cdn.fs.teachablecdn.com/NZqVclSt2qAe8KhTsUtw Example Input 1 73 Example Output 1 It's a prime number. Example Input 2 75 Example Output 2 It's not a prime number. Hint Remember the modulus: https://stackoverflow.com/questions/4432208/what-is-the-result-of-in-python Make sure you name your function/parameters the same as when it's called on the last line of code. Use the same wording as the Example Outputs to make sure the tests pass.''' #Write your code below this line 👇 # My wrong solution: def prime_checker(number): while number > 1 and number in range(0, 101): if number % 2 == 0: print(f"{number} is not a prime number") break elif number // number: print(f"{number} is a prime number") break else: print("Please, provide a number.") continue #Write your code above this line 👆 #Do NOT change any of the code below👇 n = int(input("Check this number: ")) prime_checker(number=n) ### Correct solution: def prime_checker(number): is_prime = True for i in range(2, number): if number % i == 0: is_prime = False if is_prime: print("It's a prime number.") else: print("It's not a prime number.") n = int(input("Check this number: ")) prime_checker(number=n)
true
0edc5492367bdb71b7065c4d7a93d7b2d205cdfb
subho781/MCA-PYTHON-Assignment4
/assignment 4 Q7.py
407
4.21875
4
def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] print("Enter number of elements: ", end="") n = int(input()) arr = [] for i in range(0, n): num = int(input("Enter element:")) arr.append(num) bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print (arr[i], end=" "),
false
f609d07c8ad736d1d4385e74e097a6169843977b
marnyansky/stepik-python-for-beginners-complex-solutions
/unit317559 step8.py
843
4.125
4
""" URL: https://stepik.org/lesson/334150/step/8?unit=317559 boolean for a:b:c string (a: palindrome, b: prime, c: even) example: 1221:101:22 """ # my solution: def is_valid_password(p): is_palindrome = False nums = [int(i) for i in p.split(':')] if str(nums[0]) == str(nums[0])[::-1] and len(nums) == 3: is_palindrome = True primes = 1 for i in range(2, nums[1]+1): if nums[1] % i == 0: primes += 1 is_prime = primes == 2 is_even = nums[2] % 2 == 0 return is_palindrome and is_prime and is_even # alternative solution 1: def is_valid_password(password): password = password.split(':') return (password[0] == password[0][::-1]) and (len([i for i in range(1, int(password[1])+1) if int(password[1]) % i == 0]) == 2) and (int(password[2]) % 2 == 0)
false
16e24a3e920b264002ab263cc9a3302ac047f84b
marnyansky/stepik-python-for-beginners-complex-solutions
/unit307930.py
758
4.28125
4
""" https://stepik.org/lesson/324754/step/8?thread=solutions&unit=307930 На первой строке вводится символ решётки и сразу же натуральное число nn — количество строк в программе, не считая первой. Далее следует nn строк кода. Нужно вывести те же строки, но удалить комментарии и символы пустого пространства в конце строк. Пустую строку вместо первой строки ввода выводить не надо. """ n = input() for _ in range(int(n[1:])): s = input() if '#' in s: s = s[:s.find('#')] print(s.rstrip())
false
5efb9895e06699d9d2f5752779a144d73bcbd40c
CassMarkG/Python
/operations.py
1,422
4.15625
4
#Declaration of variables a = 23 b = 12 c = 2.402 name = "Tshepo" surname = "Gabonamang" #Basic operations full_name = name + surname #concatenate strings sum = a + b product = a*b sumth = a**b #exponent bb = b**2 divc = a / b subtract = a - b divs = a%b #Assignment Operators c += b d = e = f = g = h = i = 5 d -= 12 e *=0.5 f /= 2 g **= 2 h %= 3 i //= d #Comparison Operators a == b b != d a < c i > d a <= 9 b >= b #Logical Operators print(True and True) print(True or False) print(True and False) print(True and not False) print(True and False)#row 2 print(True or False) print(True and not False) #String Operators var1, var2, var3 = "Tshepo", "Gobonamang", "I love Python" print(var1 + " " + var2) print(var3*2) print(var3[:6] + " " +var1) print(var2 + " " + var3[2:]) print("lov" in var3) print("lov" in var2) print("lov" not in var3) print("lov" not in var2) #A code that calculates area of a circle and working with user inputs var4 = input("Enter the value of the radius :") #input expects a string carea = 3.142 * int(var4) * 2 # cast that string to an integer print("The area of this circle is: %d" % (carea)) #Calculating a simple interest rate, principal_amount, time - 0.03, 28000, 6 si = principal_amount*rate*time print("The simple interest of %d for %d years at %d percent, is %2.f"%(principal_amount, time, (100*rate),si))
true
91e9f270dd26983d882ccb478eb8bb276c2ee93c
deboranrosa/Exercicios-Python
/Módulo_2/ESTRUTURA-DE-DADOS/Exercicios/Exercicio4.py
1,159
4.3125
4
# Crie 3 conjuntos conforme estrutura a seguir: # setx = set(["apple", "mango"]) # sety = set(["mango", "orange"]) # setz = set(["mango"]) # Faça as seguintes operações sobre conjuntos: # a) Faça a união dos três conjuntos e imprima o resultado # b) Verifique quais os elementos comuns do conjunto setx e sety e imprima o resultado # c) Verifique se o conjunto setx é subconjunto do conjunto sety e setz utilizando # issubset() # d) Verifique quais elementos do conjunto setx não existem em sety setx = set(["apple", "mango"]) sety = set(["mango", "orange"]) setz = set(["mango"]) # a) Faça a união dos três conjuntos e imprima o resultado uniaoSets = setx | sety | setz print(uniaoSets) # b) Verifique quais os elementos comuns do conjunto setx e sety e imprima o resultado comumSetxSety = setx & sety print(comumSetxSety) # c) Verifique se o conjunto setx é subconjunto do conjunto sety e setz utilizando issubset() subconjSetXY = setx.issubset(sety) subconjSetXZ = setx.issubset(setz) print(subconjSetXY) print(subconjSetXZ) # d) Verifique quais elementos do conjunto setx não existem em sety difSetXeSetY = setx - sety print(difSetXeSetY)
false
671220044cb30d7674abe64eb720fbcc42ae1043
nhernandez28/Lab7
/disjointSetForest.py
2,168
4.21875
4
""" CS2302 Lab6 Purpose: use a disjoint set forest to build a maze. Created on Mon Apr 8, 2019 Olac Fuentes @author: Nancy Hernandez """ # Implementation of disjoint set forest # Programmed by Olac Fuentes # Last modified March 28, 2019 import matplotlib.pyplot as plt import numpy as np from scipy import interpolate def DisjointSetForest(size): r = np.zeros(size,dtype=np.int) - 1 #print(r) return r def find(S,i): # Returns root of tree that i belongs to if S[i]<0: return i return find(S,S[i]) def union(S,i,j): # Joins i's tree and j's tree, if they are different ri = find(S,i) rj = find(S,j) if ri!=rj: # Do nothing if i and j belong to the same set S[rj] = ri # Make j's root point to i's root '''def draw_dsf(S): scale = 30 fig, ax = plt.subplots() for i in range(len(S)): if S[i]<0: # i is a root ax.plot([i*scale,i*scale],[0,scale],linewidth=1,color='k') ax.plot([i*scale-1,i*scale,i*scale+1],[scale-2,scale,scale-2],linewidth=1,color='k') else: x = np.linspace(i*scale,S[i]*scale) x0 = np.linspace(i*scale,S[i]*scale,num=5) diff = np.abs(S[i]-i) if diff == 1: #i and S[i] are neighbors; draw straight line y0 = [0,0,0,0,0] else: #i and S[i] are not neighbors; draw arc y0 = [0,-6*diff,-8*diff,-6*diff,0] f = interpolate.interp1d(x0, y0, kind='cubic') y = f(x) ax.plot(x,y,linewidth=1,color='k') ax.plot([x0[2]+2*np.sign(i-S[i]),x0[2],x0[2]+2*np.sign(i-S[i])],[y0[2]-1,y0[2],y0[2]+1],linewidth=1,color='k') ax.text(i*scale,0, str(i), size=20,ha="center", va="center", bbox=dict(facecolor='w',boxstyle="circle")) ax.axis('off') ax.set_aspect(1.0) plt.close("all") S = DisjointSetForest(8) print(S) draw_dsf(S) union(S,7,6) print(S) draw_dsf(S) union(S,0,2) print(S) draw_dsf(S) union(S,6,3) print(S) draw_dsf(S) union(S,5,2) print(S) draw_dsf(S) union(S,4,6) print(S) draw_dsf(S)'''
true
f7a3d0fb6075fb2b8de4735b927687651386f815
octospark/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp-for-2021
/TurtleRace/main.py
1,040
4.25
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] turtles = [] is_race_on = False vertical_pos = -75 for color in colors: t = Turtle("turtle") t.color(color) t.penup() t.goto(-230, vertical_pos) vertical_pos += 30 turtles.append(t) if user_bet: is_race_on = True while is_race_on: for turtle in turtles: if turtle.xcor() > 230: is_race_on = False winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} turtle is the winner!") else: print(f"You've lost! The {winning_color} turtle is the winner!") random_distance = random.randint(1, 10) turtle.forward(random_distance) screen.exitonclick()
true
1cacc5ee0b82ed052b05a7f6a70ba7ee2941d978
3fraa/100_days_of_programming_python
/L27.py
826
4.28125
4
a = b = 10 c = 3 if a > b : print("a is greater than b") elif a < b : print("a is less than b") else : print("a is equal to b") if len("Afraa") == len("Laila"): print("Afraa ana Laila have the same number of characters") print("a is equal to b") if a == b else print("a is not equal to b") print("<") if a < b else print(">") if a > b else print("=") print() if a > c and b > c : print("c is the LOWEST number") if a > c or b < c : print("mayb a greater than c or b less than c") print() if c < 20 : print("Less than twenty") if c < 10 : print("and less than ten") if c < 5 : print("and less than five") else : print("but not less than five") else : print("but not less than ten") else : print("Greater than twenty") print()
false
59ce1e1eb4fbc635af46b2ccb0f3d578aea98afd
3fraa/100_days_of_programming_python
/L16.py
656
4.4375
4
List = ["Afraa" , "Amal"] Tuple = ("Noha" , "Laila") print("List = " , List) print("Tuple = " , Tuple) print() List = [] Tuple = () print("List = " , List) print("Tuple = " , Tuple) print() List = [3] # if we write as follows //Tuple = (3) #it will look like item not tuple ,so we must add comma item = 3 item1 = (3) Tuple = (3,) print("List = " , List) print("item = " , item) print("item1 = " , item1) print("Tuple = " , Tuple) print() Tuple1 = (3, 4.3, "Afraa" ) print("Tuple1 = " , Tuple1) print(Tuple1[2]) # Afraa print() for x in Tuple1: print(x) print() #del Tuple1 #print("Tuple1 = " , Tuple1) #will give us error print(Tuple1[0:2])
false
70c8efd8209fc40a4085139f86bdc57e11f01346
roy355068/Algo
/Greedy/435. Non-overlapping Intervals.py
1,667
4.15625
4
# Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. # Note: # You may assume the interval's end point is always bigger than its start point. # Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. # Example 1: # Input: [ [1,2], [2,3], [3,4], [1,3] ] # Output: 1 # Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. # Example 2: # Input: [ [1,2], [1,2], [1,2] ] # Output: 2 # Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. # Example 3: # Input: [ [1,2], [2,3] ] # Output: 0 # Explanation: You don't need to remove any of the intervals since they're already non-overlapping. # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e # The idea is that, if we sort the array with data's endpoints, we can tell if the data point # (interval) is good or not by looking at if the starting points of following intervals fall before # the current end points class Solution(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[Interval] :rtype: int """ if not intervals: return 0 intervals.sort(key = lambda x : x.end) end = intervals[0].end # goodCount is the number of elements that don't need to be removed goodCount = 1 for i in xrange(1, len(intervals)): if intervals[i].start >= end: goodCount += 1 end = intervals[i].end return len(intervals) - goodCount
true
54bd1b88a5ad75d1b4b7169cad68a4ee4aa5839b
roy355068/Algo
/Trees/109. Convert Sorted List to BST.py
2,264
4.1875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ if not head: return None prev, slow, fast = None, head, head """ prev : the tail node of the left part of the linked list fast : the tail node of the right part of the linked list it'll move twice as fast as slow pointer slow : the middle node of the whole linked list. In order to build a balanced tree, we need to find the middle node and split the whole linked list into halves """ while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next """ if prev exists, meaning that there's a tail in the left linked list. Break the linked list by setting the tail's next node a None. And then use the left and right parts to construct left and right subtrees if there's no prev exists, meaning that there's no more nodes in the left subtree, set the head to None and use the head to construct the subtree """ if prev: prev.next = None else: head = None root = TreeNode(slow.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(slow.next) return root def sortedListToBSTWithHelperFunction(self, head): if not head: return None return self.helper(head, None) def helper(self, head, tail): if head == tail: return None slow, fast = head, head while fast != tail and fast.next != tail: slow = slow.next fast = fast.next.next root = TreeNode(slow.val) root.left = self.helper(head, slow) root.right = self.helper(slow.next, tail) return root
true
4b44ac5cf8b0313a395dbcabd38f1bca1a3759b9
roy355068/Algo
/Design Problems/341. Flatten Nested List Iterator.py
2,279
4.1875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): # Add all element in nestedList from the rear into the stack (self.s) # So that the stack could return the very first element when popping def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.s = [] for i in xrange(len(nestedList) - 1, -1, -1): self.s.append(nestedList[i]) def next(self): """ :rtype: int """ return self.s.pop().getInteger() def hasNext(self): """ :rtype: bool """ # check the first element in the nestedList # if the element is an integer, directly return True and let the next() function # to do the popping and data extracting # else if the current element is an Integer List, unpack it # by calling the getList() function and append all the element in the list from # the back into the stack (same reason as the initial nestedList) while self.s: curr = self.s[-1] if curr.isInteger(): return True self.s.pop() for i in xrange(len(curr.getList()) - 1, -1, -1): self.s.append(curr.getList()[i]) return False # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
312b5b4a69cf844e106f163e1168eefd5f708d18
Siddhantmest/Data-Structures-and-Algorithms
/insertion_sort.py
471
4.1875
4
print('Welcome to the algorithm for Insertion Sort') print('Input the list you want to sort, numbers separated by space:') inplist = list(float(item) for item in input().split()) def insertionsort(a): for i in range(1,(len(a))): key = a[i] j = i - 1 while (j >= 0) and (key < a[j]): a[j+1] = a[j] j -= 1 a[j+1] = key return a print('Sorted list:', insertionsort(inplist))
true
9474fa96b17cfc4ac3b2bf363d2c2e0f6b0dd808
whyhelin/python3_test
/helin_07/OOP_sub.py
1,653
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Animal(object): def run(self): print('Animal is running...') class Timer(object): def run(self): print('Start...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') def run_twice(animal): animal.run() animal.run() a = Animal() d = Dog() c = Cat() print('a is Animal?', isinstance(a, Animal)) print('a is Dog?', isinstance(a, Dog)) print('a is Cat?', isinstance(a, Cat)) print('d is Animal?', isinstance(d, Animal)) print('d is Dog?', isinstance(d, Dog)) print('d is Cat?', isinstance(d, Cat)) # 对于静态语言(例如Java)来说, # 如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类, # 否则,将无法调用run()方法。 # # 对于Python这样的动态语言来说,则不一定需要传入Animal类型。 # 我们只需要保证传入的对象有一个run()方法就可以了: # 这就是动态语言的“鸭子类型”, # 它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”, # 那它就可以被看做是鸭子。 # Python的“file-like object“就是一种鸭子类型。 # 对真正的文件对象,它有一个read()方法,返回其内容。 # 但是,许多对象,只要有read()方法,都被视为“file-like object“。 # 许多函数接收的参数就是“file-like object“, # 你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。 run_twice(c) run_twice(Timer())
false
f9f8e7ffa801170f3e4ebcc8334335398756b439
alaqsaka/learnPython
/madlibs.py
828
4.125
4
# Python project: madlibs print("Welcome to madlibs game\n") print("Madlibs is phrasal template word game which consists of one player prompting others for a list of words to substitute for blanks in a story before reading aloud.") name = input("What is your name? ") age = input("How old are you? ") dreamJob = input("What is your dream job? ") reason = input("Why you choose " + dreamJob + "? ") hobby = input("What is your hobby? ") famousPeople = input("Who is your favorite famous person? ") reason2 = input("Why do you like " + famousPeople +"? ") madlibs = f"Hi, my name is {name}, i'm {age} years old. I want to be {dreamJob} because {reason}. My Hobby is {hobby}. I really like {famousPeople} because\ {reason2} and i really like that. Drink water, stay hydrated, and stay productive, {name}" print(madlibs)
true
5b40cb33ef3132079b45b3db4a5c9d11ab3467a3
BoomerPython/Week_1
/DSA_BoomerPython_Week1.py
649
4.1875
4
# This file provides an overview of commands # & code demonstrated in week 1 of the DSA 5061 Python course. # Additional course materials depict the code shown here via # the command line and also using a notebook. # The basics - math 2+3 # Storing results ans = 2 + 3 print(ans) # Printing to the screen print("Boomer - Sooner!") # Storing a greeting greeting = "Boomer Sooner!" not_a_greeting = "Woo Pig!" print(greeting) #Checking a state and printing a greeting if ans > 3: print(greeting) #Checking a state and printing an alternative if ans < 3: print(greeting) else: print(not_a_greeting)
true
80690807b5f4f514b81f2f4c7c104e2744bd64f1
vivek2188/Study
/Datacamp/Python/Intermediate/Dictinoaries , Pandas/pandas_4.py
645
4.15625
4
''' Your read_csv() call to import the CSV data didn't generate an error, but the output is not entirely what we wanted. The row labels were imported as another column without a name. Remember index_col, an argument of read_csv(), that you can use to specify which column in the CSV file should be used as a row label? Well, that's exactly what you need here! Python code that solves the previous exercise is already included; can you make the appropriate changes to fix the data import? ''' # Import pandas as pd import pandas as pd # Fix import by including index_col cars = pd.read_csv('cars.csv',index_col=0) # Print out cars print(cars)
true
d1dd589301484e3010bd0d84c84bc8956cea50f7
gustavoc77/Desafios-Python
/desafio018.py
561
4.125
4
# faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. import time from math import radians, sin, cos, tan angulo = float(input('Digite um ângulo: ')) print('...........CALCULANDO.........') loop = 0 time.sleep(1.2) seno = sin(radians(angulo)) cosseno = cos(radians(angulo)) tangente = tan(radians(angulo)) print('''O ângulo de {}º tem o SENO de {:.2f}º o COSSENO de {:.2f}º e a TANGENTE de {:.2f}º '''.format(angulo,seno,cosseno,tangente))
false
f7652c5bfc3bb0645c86615dace8ff63ae12d624
ava6969/P0
/Task2.py
1,341
4.125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ # # tel, _,_, call_time = zip(*calls) # dict_ = {} # # max_ct = 0 # max_t = '' # for t, c in zip(tel, call_time): # if int(c) > max_ct: # max_ct = int(c) # max_t = t # rec_dict = {} for call in calls: if call[1] not in rec_dict: rec_dict.update({call[1]: int(call[3])}) else: rec_dict[call[1]] += int(call[3]) if call[0] not in rec_dict: rec_dict.update({call[0]: int(call[3])}) else: rec_dict[call[0]] += int(call[3]) longest_duration = max(rec_dict.items(), key=lambda x: x[1]) print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(*longest_duration)) # print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(max_t, max_ct))
true
f84e297229c0cabf70c42e2889358cb8403b389e
rahcode7/Programming-Practice
/Python/Concepts/Classes.py
943
4.28125
4
## Classes & String Formatting #def main(): #print("Before MyClass") # class MyClass: # variable = "temp" # def f1(self): # print("Message inside {0} {1} class".format("my","first")) #myobject1 = MyClass() # print(myobject1.variable) #print(myobject1.f1) # if __name__ == '__main__': # myobject1 = MyClass() # print(myobject1.f1) # print("After class assignment") ## Constructor Method ## __init__ - is the method initiated whenever a class object is created ## self is the parameter that the methods have a way of referring to object attributes # Code Reference - https://www.digitalocean.com/community/tutorials/how-to-construct-classes-and-define-objects-in-python-3 class Shark: def __init__(self,name): self.name = name def swim(self): print(self.name + "is swimming") def main(): sammy = Shark("Sammy") sammy.swim() if __name__ == "__main__": main()
true
57eb528ea3768dc2148dd8cef09857ace841a58f
Mr-hongji/pythonNote
/一本册子/类继承.py
474
4.15625
4
''' 继承 语法: 子类(父类) ''' #创建父类交通工具类 -- Vehicle class Vehicle: speed = 0 #速度 def driver(self, distance): #distance : 路程 print float(distance / self.speed) #创建子类汽车类 -- Car 继承父类Vehicle class car(Vehicle): fuel = 0 speed = 60 driver(100) #创建子类自行车类 -- bike 继承父类Vehicle class bike(Vehicle): speed =
false
6eccdfa3b33b04759e30e781823eb57adc8b5d83
AlexandrSech/Z49-TMS
/students/Solovey/Homework/HW_4/task_4_5.py
786
4.1875
4
''' 5) Составить список чисел Фибоначчи содержащий 15 элементов. ''' # example_1 number_1 = number_2 = int(input('Enter a starting number:')) max_nums = int(input('Enter numbers maximum:')) fib_list = [] fib_list.append(number_1) fib_list.append(number_2) for i in range(2, max_nums): number_1, number_2 = number_2, number_1 + number_2 fib_list.append(number_2) print(fib_list) print('\n\n') # example_2 number_1 = number_2 = int(input('Enter a starting number:')) max_nums = int(input('Enter numbers maximum:')) fib_list = [] fib_list.append(number_1) fib_list.append(number_2) i = 0 while i < max_nums - 2: number_1, number_2 = number_2, number_1 + number_2 fib_list.append(number_2) i += 1 print(fib_list)
false
415f3857a95482a91d93336a23b14181d9052cd6
AlexandrSech/Z49-TMS
/students/Hantsevich/l11/task_11_2.py
2,590
4.3125
4
""" Создать класс Car. Атрибуты: марка, модель, год выпуска, скорость(поумолчанию 0). Методы: увеличить скорости(скорость + 5), уменьшени ескорости(скорость - 5), стоп(сброс скорости на 0), отображение скорости, разворот(изменение знака скорости). Все атрибуты приватные. """ class Car: __mark: str # Марка __model: str # Модель __year: int # Год выпуска __speed: int = 0 # Скорость __side: str = '+' # Направление def __init__(self, mark, model, year, speed): self.__mark = mark self.__model = model self.__year = year self.__speed = speed @property def mark(self): return self.__mark @mark.setter def mark(self, mark): if mark.lower().isalpha(): self.__mark = mark else: print("Wrong Mark") def model(self): return self.__model @property def year(self): return self.__year @year.setter def year(self, year): if 1887 < year < 2021: self.__year = year else: print("This auto was not/ is not invented") @property def speed(self): return self.__speed @speed.setter def speed(self, speed): if speed > 350: print("You cant be that fast, u know?!") else: self.__speed = speed def speed_up(self): # Увеличение скорости if self.__speed >= 346: print('U cant be so fast') elif self.__speed <= 345: self.__speed += 5 return self.__speed def speed_down(self): # Уменьшение скорости if self.__speed <=5: self.__speed = 0 print('You stopped') elif self.__speed > 5: self.__speed -= 5 return self.__speed def stop(self): # Остановка self.__speed = 0 return self.__speed def revere(self): # Разворот if self.__side == '+': self.__side = '-' else: self.__side = '+' def display(self): # Текущая скорость print(self.__side, self.__speed) a = Car('Bra', 'Bru', 1992, 200) print(a.mark, a.model(), a.year, a.speed) a.speed_up() a.display() a.revere() a.display() a.speed_down() a.display() a.stop() a.display()
false
18fec9e775d49a779a1fb68976e0729aa2e0088f
AlexandrSech/Z49-TMS
/students/Volodzko/Task_5/task_5_7.py
610
4.21875
4
""" Дана целочисленная квадратная матрица. Найти в каждой строке наи-больший элемент и поменять его местами с элементом главной диагонали """ matrix = [[5, 8, 2, 3], [7, 11, 1, 8], [9, 4, 6, 5], [2,12,1,3]] for i in matrix: print(i) print("\n") for item, value in enumerate(matrix): max_value = 0 for j in range(len(matrix[item])): if matrix[item][j] > max_value: max_value = matrix[item][j] matrix[item][item] = max_value for i in matrix: print(i)
false
1a22b93c6f135a7ec4bddb61f5941de770f72887
AlexandrSech/Z49-TMS
/students/Volodzko/Task_2/task_2_4.py
235
4.15625
4
""" Создать строку равную введенной строку без последних двух символов """ my_string = input("Введите строку: ") string_result = my_string[:-2] print(string_result)
false
204ba1c7911c19d5eaf4e5c26fd77e325a36ad8e
AlexandrSech/Z49-TMS
/students/Stalybka/hw_7/task_7_1.py
1,650
4.125
4
""" 1. Написать 12 функций по переводу: 1. Дюймы в сантиметры 2. Сантиметры в дюймы 3. Мили в километры 4. Километры в мили 5. Фунты в килограммы 6. Килограммы в фунты 7. Унции в граммы 8. Граммы в унции 9. Галлон в литры 10. Литры в галлоны 11. Пинты в литры 12.Литры в пинты Примечание: функция принимает на вход число и возвращает конвертированное число""" def inch_to_cm(inch): cm = inch * 2.54 return f'{inch} inch(es) = {cm} cm' def cm_to_inch(cm): inch = cm / 2.54 return f'{cm} cm = {inch} inch(es)' def mile_to_km(mile): km = mile * 1.609 return f'{mile} mile(s) = {km} km' def km_to_mile(km): mile = km / 1.609 return f'{km} km = {mile} mile(s)' def pound_to_kg(pound): kg = pound * 0.4536 return f'{pound} pound(s) = {kg} kg' def kg_to_pound(kg): pound = kg / 0.4536 return f'{kg} kg = {pound} pound(s)' def ounce_to_g(ounce): g = ounce * 28.3495 return f'{ounce} ounce(s) = {g} g' def g_to_ounce(g): ounce = g / 28.3495 return f'{g} g = {ounce} ounce(s)' def gallon_to_l(gallon): l = gallon * 4.54609 return f'{gallon} gallon(s) = {l} l' def l_to_gallon(l): gallon = l / 4.54609 return f'{l} l = {gallon} gallon(s)' def pint_to_l(pint): l = pint * 0.568261 return f'{pint} pint(s) = {l} l' def l_to_pint(l): pint = l / 0.568261 return f'{l} l = {pint} pint(s)'
false
d5faeebd8b29511a9ae7cacb171e081adb03c0d2
AlexandrSech/Z49-TMS
/students/Sachuk/HomeWork - Lesson 7/task_7_1_and_7_2.py
2,538
4.125
4
# Написать 12 функций по переводу: # Дюймы в сантиметры # Сантиметры в дюймы # Мили в километры # Километры в мили # Фунты в килограммы # Килограммы в фунты # Унции в граммы # Граммы в унции # Галлон в литры # Литры в галлоны # Пинты в литры # Литры в пинты def number(): while True: x = input('Please, enter the number: ') if x.isdigit(): break else: print(' I TOLD YOU!!!!!READ CAREFULLY!!! Enter the number: ') return x def conversion(): print('Welcome to my little console conversion! Enter the number and get rusult.\n' '1 - Дюймы в сантиметры\n' '2 - Дюймы в сантиметры\n' '3 - Сантиметры в дюймы\n' '4 - Мили в километры\n' '5 - Километры в мили\n' '6 - Фунты в килограммы\n' '7 - Килограммы в фунты\n' '8 - Унции в граммы\n' '9 - Граммы в унции\n' '10 - Литры в галлоны\n' '11 - Пинты в литры\n' '12 - Литры в пинты\n') while True: choice = number() if choice == '0': print("Noooooooooooooooo, please COME BACK!!!!! How did you know how to get out of here?\n " "Don't tell me you read the assignment carefully") break elif int(choice) > 0 and int(choice) <= 12: print('How many units do you want to convert?') y = number() y = int(y) convetation = {} convetation['1'] = y * 2.54 convetation['2'] = y * 0.39 convetation['3'] = y * 1.6 convetation['4'] = y * 0.62 convetation['5'] = y * 0.0003048 convetation['6'] = y * 3280.84 convetation['7'] = y * 28.3495 convetation['8'] = y * 0.035274 convetation['9'] = y * 3.78541 convetation['10'] = y * 0.264172 convetation['11'] = y * 0.473176 convetation['12'] = y * 2.11338 print(f'Your result is equal : {convetation[choice]} \n We start a new conversion!\n' f'There is no way out of here (c) John Cramer!!! Aha-ha-ha-ha!. Look UP!') print(conversion())
false
3ea416e93667a35f1ee7117ba4db9dbc257a1456
quenrythane/DataCampExercises
/2 Data Types for Data Science in Python/3 Sets for unordered and unique data.py
2,177
4.15625
4
# Sets are created from a list list_1 = ['a', 'b', 'c', 'd', 'e'] list_2 = ['d', 'e', 'f', 'g', 'h'] # creating sets set_1 = set(list_1) set_2 = set(list_2) # compare list and sets print("list_1: -> ", list_1) print('set_1: -> ', set_1) print("list_2: -> ", list_2) print('set_2: -> ', set_2, '\n') # .union() (or) print('# .union() (or)') union_set_1 = set_1.union(set_2) union_set_2 = set_2.union(set_1) print('union_set_1: ->', union_set_1) print('union_set_2: ->', union_set_2) print("union_set_1 == union_set_2 ?: ->", union_set_1 == union_set_2, '\n') # .intersection() (and) print('# .intersection() (and)') intersection_set_1 = set_1.intersection(set_2) intersection_set_2 = set_2.intersection(set_1) print('intersection_set_1: ->', intersection_set_1) print('intersection_set_2: ->', intersection_set_2) print("intersection_set_1 == intersection_set_2 ?: ->", intersection_set_1 == intersection_set_2, '\n') # .difference() (-) print('# .difference() (-)') difference_set_1 = set_1.difference(set_2) difference_set_2 = set_2.difference(set_1) print('difference_set_1: ->', difference_set_1) print('difference_set_2: ->', difference_set_2) print("difference_set_1 == difference_set_2 ?: ->", difference_set_1 == difference_set_2, '\n') # .add(item) print('# .add(item)') print('print(set_1): ->', set_1) set_1.add('z') print("'z' added: ->", set_1) set_1.add('a') print("'a' added: ->", set_1, '\n', "<- nothing happend because 'a' was already there (and sets doesn't keep same values", '\n') # .update(item/array) print('# .update(item/array)') set_1.update('w') print("'w' added: ->", set_1) set_1.update(['y', 'x']) print("'x' and 'y' added: ->", set_1) set_1.update('a', 'b') print("'a' and 'b' added: ->", set_1, "<- nothing happend because 'a' was already there (and sets doesn't keep same values", '\n') # .discard() print('# .discard()') print('print(set_2): ->', set_2) set_2.discard('h') print("'h' discarded: ->", set_2, '\n') # .pop() take no arguments print('# .pop()') print('print(set_2): ->', set_2) print('pop: ->', set_2.pop()) print("poped set_2: ->", set_2, '\n')
false
2a76c4744485d2c22d0f63dbfc8ea3dc4e584e97
ClaireDrummond/52167-Assessments
/Factorial.py
1,230
4.5
4
# Claire Drummond 2018-03-20 # Factorial Numbers Exercise 6 def factorial(n): #return the factorial of n num = 1 # Setting the variable num as 1 while n >= 1: #while n is less than or equal to 1 num = num * n # mulitply num x n n = n - 1 # setting the new variable as n - 1 return num print("The factorial of number 5 is:",factorial(5)) print("The factorial of number 7 is:",factorial(7)) print("The factorial of number 10 is:",factorial(10)) # Alternative Solution # ref: https://stackoverflow.com/questions/5136447/function-for-factorial-in-python from math import factorial # Function is in Math Module print("The factorial of number 5 is:",factorial(5)) print("The factorial of number 7 is:",factorial(7)) print("The factorial of number 10 is:",factorial(10)) # Alternative Solution Option from Topic 7 Notes on Functions # ref: https://nbviewer.jupyter.org/github/ianmcloughlin/python-fundamentals-notes/blob/master/functions-modules.ipynb def factorialb(m): #defining this solution as factorialb - factorial option b """Return the factorialb of m.""" ans = 1 for i in range(2, m + 1): ans = ans * i return ans print(factorialb(5)) print(factorialb(7)) print(factorialb(10))
false
a61e1f86a84ad1e6cbcea3290f29bea3d5838683
jamesli1111/ICS3U---PYTHON
/pythonquestions-fullprograms/question_1.py
262
4.375
4
''' prompts user for 2 integers, divide them, and state remainder ''' integer1 = int(input("Integer 1: ")) integer2 = int(input("Integer 2: ")) print(f"The quotient of {integer1} and {integer2} is {integer1//integer2} with a remainder of {integer1%integer2}")
true
b5ee90f664b959be85129db381087cf7950bb868
sonalalamkane/Python
/Q6.py
818
4.25
4
# Question 6: # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. # Suppose the following input is supplied to the program: # Hello world! # Then, the output should be: # UPPER CASE 1 # LOWER CASE 9 # Hints: # In case of input data being supplied to the question, it should be assumed to be a console input. sentence=raw_input("Enter sentence=") upper_count=0 lower_count=0 """ It will print the count of the How many upper case letters are present in the given string and how many lower case letters present in the given sentence. """ for x in sentence: if(x.isupper()): upper_count=upper_count+1 else: lower_count=lower_count+1 print"Number of Upper letters in sentence=%d"%upper_count print"Number of lower letters i sentence=%d"%lower_count
true
db501086065365425c81252a0954f70f524604c8
CodingGimp/learning-python
/fizz_buzz.py
409
4.15625
4
name = str(input('Please enter your name: ')) number = int(input('Please enter a number: ')) word = '' if number % 3 == 0 and number % 5 == 0: word = 'FizzBuzz' elif number % 3 == 0: word = 'Fizz' elif number % 5 == 0: word = 'Buzz' else: word = 'is neither a fizzy or a buzzy ' print('Wassup ' + name + '!') print('The number ' + str(number) + '...') print('is a ' + word + ' number!')
false
453d3fd5e296d4e654831da9d19808ef3644e49d
CodingGimp/learning-python
/RegEx/sets_email.py
262
4.28125
4
''' Create a function named find_emails that takes a string. Return a list of all of the email addresses in the string. ''' import re def find_emails(s): return re.findall(r'[-\w\d+.]+@[-\w\d.]+', s) print(find_emails("kenneth.love@teamtreehouse.com, @support, ryan@teamtreehouse.com, test+case@example.co.uk"))
true
3da13a6d7df49ccc0dd1fa2499a5c86c1ebf9383
josbp0107/data-structures-python
/arrays.py
1,487
4.34375
4
from random import randint import random """ Code used for Create an array in python Methods: 1. Length 2. List representation 3. Membership 4. Index 5. Remplacement """ class Array: """Represent an Array""" def __init__(self, capacity, fill_value=None): """ Args: capacity(int): static size of the Array fill_value(any, optional): Value at each position. Default is None. """ self.capacity = capacity self.items = list() for i in range(capacity): self.items.append(fill_value) def __len__(self): """Return capacity of the array.""" return len(self.items) def __list__(self): """Return list of elements in array.""" return list(self.items) def __iter__(self): """Supports traversal with a for loop.""" return iter(self.items) def __getitem__(self,index): """Subscrit operator for a access at index.""" return self.items[index] def __setitem__(self,index,new_item): """Subscrit operator for remplacement at index.""" self.items[index] = new_item def __replace__(self): """Return list with items modified by random values""" return [ self.__setitem__(i,random.randint(0,100)) for i in range(self.capacity) ] def __sumArrays__(self): """Return sum of all elements in array""" return sum(self.items)
true
6e65533248035d6bc795c08999bf995d0a66036d
gilgamesh7/learn-python
/conditionals/tstCond.py
436
4.15625
4
def tstIf(num1,num2): if (num1 < num2): retVal="{0} is less than {1}".format(num1, num2) elif (num1 > num2): retVal="{0} is less than {1}".format(num2,num1) else: retVal="{0} and {1} are equal".format(num1,num2) return retVal if __name__ == '__main__': num1=input("Enter Number 1 : ") num2=input("Enter Number 2 : ") print(tstIf(num1,num2)) exit(1)
true
34fadd2875a55ebb8120f48354b99d3b14262599
Bobby-Wan/Daily-Coding-Problems
/problem27.py
900
4.34375
4
# This problem was asked by Facebook. # Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). # For example, given the string "([])[]({})", you should return true. # Given the string "([)]" or "((()", you should return false. def are_symmetrical(left, right): return (left == '(' and right == ')') or \ left == '[' and right == ']' or \ left == '{' and right == '}' def is_brace(c): return c in ['(',')','{','}','[',']'] def is_balanced(string): stack = list() for char in string: if stack and is_brace(char) and are_symmetrical(stack[-1], char): stack.pop() else: stack.append(char) return not stack def main(): assert is_balanced('[][]') assert is_balanced('([])[]({{}})') print('Hooray!') if __name__ == '__main__': main()
true
2a7ea48223400152b52a3846123a8e0d33ad0373
Bobby-Wan/Daily-Coding-Problems
/problem7.py
816
4.125
4
# This problem was asked by Facebook. # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. For example, '001' is not allowed. def decoding_ways(str): if len(str) == 0: return 1 if len(str) == 1: return 1 length=len(str) if length >= 2: if int(str[0:2]) > 26: return decoding_ways(str[1:]) else: if str[1] == '0': return decoding_ways(str[2:]) return decoding_ways(str[1:]) + decoding_ways(str[2:]) def main(): string = '111' print(decoding_ways(string)) if __name__ =='__main__': main()
true
23dc26b31f41fe446d251f868c6c9d8023ffd043
Bobby-Wan/Daily-Coding-Problems
/problem29.py
1,233
4.375
4
# This problem was asked by Amazon. # Run-length encoding is a fast and simple # method of encoding strings. The basic idea is # to represent repeated successive characters as # a single count and character. For example, # the string "AAAABBBCCDAA" would be encoded # as "4A3B2C1D2A". # Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid. def encode(string): count=1 result = '' for i in range(len(string)): if i == len(string) - 1: result += str(count) + string[i] elif string[i] != string[i+1]: result += str(count) + string[i] count = 1 else: count += 1 return result def is_digit(c): return c>='0' and c<='9' def decode(string): count = '' result = '' for i in range(len(string)): if(is_digit(string[i])): count += string[i] else: for _ in range(int(count)): result += string[i] count = '' return result def main(): print(decode(encode('AAAABBBCCDAA'))) if __name__ == '__main__': main()
true
0f9bd2ac1e4f40d6a9214eca321e8fbadcffb5b4
qwang1/my-practice
/trim.py
355
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格 def trim(s): while s[0:1] == ' ': s = s[1:] while s[-1:0] == ' ': s = s[0:-1] return s # test print(trim('ABC')) print(trim(' ABC')) print(trim(' ABC ')) print(trim('ABC ')) print(trim(' ABC '))
false
c1572b2f22444c58025bed5aadc12f1dcc5478cc
danielcinome/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
543
4.34375
4
#!/usr/bin/python3 """function that adds 2 integers. Returns an integer: the addition of a and b a and b must be integers or floats, otherwise raise a TypeError exception with the message a must be an integer or b must be an integer """ def add_integer(a, b=98): """ a and b must be integers or floats """ if type(a) != int and type(a) != float: raise TypeError("a must be an integer") if type(b) != int and type(b) != float: raise TypeError("b must be an integer") return int(a) + int(b)
true
c7ccc320d1ef482d187b0c21fbb2803d6e508835
ECE4574-5574/Decision_System
/phase_1/cache.py
1,184
4.25
4
""" Authored by Sumit Kumar on 3/22/2015 Description : Decorator class - Caches output/return values of a function for a particular set of arguments, by writing/reading a dictionary in the JSON format from a cache file. Usage : To use the caching capabilities, have the decorator coupled with the calling function as follows: @cacheClass def myFunction(myArguments): # Do something with the arguments return myReturnValue """ import collections import json class cacheClass(object): def __init__(self, func): self.func = func try: # Try reading from a cache file. self.cache = json.load(open("cache.txt")) except: self.cache = {} def __call__(self, *arguments): if arguments in self.cache: print "In Cache" return self.cache[arguments] else: value = self.func(*arguments) argumentsString = ' '.join(arguments) self.cache[argumentsString] = value try: #Write the cache to a file. json.dump(self.cache, open("cache.txt",'w')) except: print "here" pass return value
true
5981f5d47820ce2cdf0ebfdf0a979d5a76bceb90
Keitling/algorithms
/python/Math/newtons_sqrt_recursive.py
1,318
4.375
4
""" To compute sqrt(x): 1) Start with an initial estimate y (let's pick y = 1). 2) Repeatedly improve the estimate by taking the mean of y and x/y. Example: Estimation Quotient Mean 1 2 / 1 = 2 1.5 ((2 + 1) / 2) 1.5 2 / 1.5 = 1.333 1.4167 ((1.333 + 1.5) / 2) 1.4167 2 / 1.4167 = 1.4118 1.4142 ((1.4167 + 1.4118) / 2) 1.4142 ... ... """ def sqrt(x): """ Calculates the square root of x, recursively. """ def sqrt_iter(guess): """ Improves the guess until it's close enough to x. """ if is_good_enough(guess): return guess # return the estimate if it is close enough to x else: return sqrt_iter(improve(guess)) # improve the estimate def is_good_enough(guess): """ Is the estimate close enough? The difference of x and the square of the guess must be smaller to some epsilon value to be good enough; 0.001 on this case. """ return abs(guess * guess - x) / x < 0.001 def improve(guess): """ Improve the current estimate. Mean of: guess and x / guess. """ return (guess + x / guess) / 2 return sqrt_iter(1.0) # starts the recursion, using 1.0 as starting guess
true
9f688ff6f0859d6c004c467cb76a8c6e5eb6d4a5
Keitling/algorithms
/python/Sorting/insertion_sort.py
1,408
4.28125
4
def insertion_sort(alist): return_list = alist for index in range(1, len(return_list)): value = return_list[index] i = index - 1 while i >= 0: if value < return_list[i]: # Swap: return_list[i + 1] = return_list[i] return_list[i] = value i -= 1 else: break return return_list # Another implementation: def InsertionSort(array): """Insertion sorting algorithm""" i = 0 j = 0 n = len(array) for j in range(n): key = array[j] i = j - 1 while (i >= 0 and array[i] > key): array[i + 1] = array[i] i = i - 1 array[i + 1] = key # Another implementation: def insertion_sort_bin(seq): for i in range(1, len(seq)): key = seq[i] # invariant: ``seq[:i]`` is sorted # find the least `low' such that ``seq[low]`` is not less then `key'. # Binary search in sorted sequence ``seq[low:up]``: low, up = 0, i while up > low: middle = (low + up) // 2 if seq[middle] < key: low = middle + 1 else: up = middle # insert key at position ``low`` seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:] # TESTS: list1 = [5, 4, 2, 3, 1] insertion_sort_bin(list1) print list1
true
7ef864e9be1a823d3cfd0ff3fb192f67772f319f
Keitling/algorithms
/python/Recursion/recursion_vs_iteration.py
1,967
4.1875
4
# ---------------------------------------------------------------- # Measurement of running time difference between recursion # and iteration in Python. # # To use this code from the command line: # python recursion_vs_iteration.py number_of_tests test_depth # For example, to make 100 tests with 200 recursion and # iteration depth: # python recursion_vs_iteration.py 100 200 # That will print the total and average time of the test. # # To use this code from interpreter: # Change the values of number_of_tests and test_depth variables, # then run. # ---------------------------------------------------------------- import time import sys # Increments the stack depth allowed. Need this to make deep recursion tests. sys.setrecursionlimit(50000) # ======================== # Defining the functions: # ======================== def iteration(depth): for i in range(depth): pass return True def recursion(depth): if depth == 0: return True else: depth -= 1 return recursion(depth) # ======================== # Testing: # ======================== number_of_tests = int(sys.argv[1]) test_depth = int(sys.argv[2]) # iteration running time: iteration_start = time.time() for e in range(number_of_tests): iteration(test_depth) iteration_total = time.time() - iteration_start iteration_average = iteration_total / number_of_tests # recursion runnign time: recursion_start = time.time() for e in range(number_of_tests): recursion(test_depth) recursion_total = time.time() - recursion_start recursion_average = recursion_total / number_of_tests # ======================== # Prints: # ======================== print "" print "Results for {0} tests with {1} depth, in seconds: ".format(number_of_tests, test_depth) print "" print "Iteration: total = {0} average = {1}".format(iteration_total, iteration_average) print "Recursion: total = {0} average = {1}".format(recursion_total, recursion_average) print ""
true
7f5e24b711062965396d53c1c8b4345c2b6e2f69
JoshMcKinstry/Dork_Game_team_octosquad
/dork/character.py
1,614
4.125
4
''' A character module that creates an abstract representation of a character ''' class Character(): ''' A class that models an character object ''' def __init__(self, name, position, inventory): self.name = name self.position = position self.inventory = inventory def has_item(self, item_name): """ This function determines if the player is holding an item. Parameters: item_name (dict): A dictionary of possible items Returns: item_name (bool): True if the player holds the item, false otherwise. """ return item_name in self.inventory def delete_item(self, item_name): """ This function removes an item from the character Parameters: item_name (dict): A dictionary of possible items Returns: A string indicating the state of the item. """ if self.has_item(item_name): self.inventory.remove(item_name) return (self.name + ' has lost ' + item_name + '.', True) return (self.name + ' does not hold ' + item_name + '.', False) def add_item(self, item_name): """ This function adds an item to the character. Parameters: item_name (dict): A dictionary of possible items. Returns: A string verifying that he player has the item. """ self.inventory.append(item_name) return self.name + ' now holds ' + item_name
true
6d462c11f9045377e64fc354d182761a64e1248b
nickbrenn/Intro-Python
/src/dicts.py
755
4.28125
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. waypoints = [ { "lat": 43, "lon": -121, "name": "a place" }, { "lat": 41, "lon": -123, "name": "another place" }, { "lat": 43, "lon": -122, "name": "a third place" } ] # Write a loop that prints out all the field values for all the waypoints for point in waypoints: print("======================") for k, v in point.items(): print(k, v) # Add a new waypoint to the list waypoints.append({"lat": 0, "lon": 10, "name": "GNEW wheypoint"}) print("\n", waypoints[-1])
true
5854e4129437c03fbfa9b9f4d39deacbb82f623b
XiangyuDing/Beginning-Python
/Beginning/python3_cookbook/ch02/13-adjust_text.py
584
4.34375
4
# 2.13 字符串对齐 text = 'Hello World' left = text.ljust(20) right = text.rjust(20) center = text.center(20) print(left) print(right) print(center) right = text.rjust(20,'=') print(right) center = text.center(20,'*') print(center) print(format(text,'>20')) print(format(text,'<20')) print(format(text,'^20')) print(format(text,'=>20s')) print(format(text,'*^20s')) print('{:>10s}{:>10s}'.format('Hello','World')) x = 1.2345 print(format(x,'>10')) print(format(x,'^10.2f')) print('%-20s' % text) print('%20s' % text) # https://docs.python.org/3/library/string.html#formatspec
false
9241a3a056057f197e74376ce9b6dc10562704e3
MarcusQuigley/MIT_Python
/IronPythonApplication1/Lecture7/PathCompleteTest.py
603
4.1875
4
def maxOfThree(a,b,c) : """ a, b, and c are numbers returns: the maximum of a, b, and c """ if a > b: bigger = a else: bigger = b if c > bigger: bigger = c return bigger #print(maxOfThree(2, -10, 100)) #Commented section is the answer #print'--------' #print(maxOfThree(7, 9, 10)) #print'--------' #print(maxOfThree(6, 1, 5)) #print'--------' #print(maxOfThree(0, 40, 20)) #print'--------' print(maxOfThree(10, 100, -20)) print'--------' print(maxOfThree(99, 0, 20)) print'--------' print(maxOfThree(1, 60, 300)) print'--------'
false
f3d3ad6bf1b48814dd6a613d93b71e164b0e1b60
theresaoh/initials
/initials.py
409
4.15625
4
def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ initials = "" names = fullname.split() for name in names: initials += name[0] return initials.upper() def main(): user_input = input("What is your full name? ") print("The initials of", user_input, "are:", get_initials(user_input)) if __name__ == '__main__': main()
true
9ad9da51c85299d9790c80d1c7301ba20de83eec
jereamon/non-descending-sort
/non_descending_sort.py
1,685
4.375
4
def non_descend_sort(input_array): """ sorts array into non-descending order and counts the number of swaps it took to do so. """ swap_count = 0 while True: # We'll need a copy of our array to loop over so we're not modifying # the same array we're looping over. input_array_copy = input_array[:] # This will become True if we've swapped any values. swap_indicator = False # Using enumerate here will provide us with the # index of each array value and the value itself. for index, value in enumerate(input_array_copy[:-1]): # check if the next value in the array is less than the current value if input_array_copy[index + 1] < value: # Save the current and next array values to temporary variables higher_value = input_array[index] lower_value = input_array[index + 1] # Then swap the places of ↑ those ↑ values in the array input_array[index] = lower_value input_array[index + 1] = higher_value swap_count += 1 swap_indicator = True if not swap_indicator: break print(input_array) print("Swap Count: " + str(swap_count)) # Some random lists for testing with. test_list_1 = [1, 2, 3, 4, 5, 1, 2, 2, 1, 2, 3, 3, 23, 23, 1, 21,2, 12, 1, 4, 24, 24] test_list_2 = [54, 32, 234234, 234, 12, 123, 23, 1, 2, 3, 3, 3, 3] test_list_3 = [1, 2, 2, 2, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2] non_descend_sort(test_list_1) print() non_descend_sort(test_list_2) print() non_descend_sort(test_list_3) print()
true
1c1efd615542f80f351978faf21cfd762832374c
GuilhermeUtech/udemy-python
/S12/map.py
494
4.15625
4
#lambda def fahrenheit(T): return (9/5)*T + 32 temp = [9,22,40,90,120] for t in temp: print(fahrenheit(t)) #map() -> cara isso é show de bola: redução de tamanho de código = aplica uma função sobre algum iterável #Essa função, em Python, serve para aplicarmos uma função a cada elemento de uma lista, retornando uma nova # lista contendo os elementos resultantes da aplicação da função. print(list(map(fahrenheit, temp))) print(list(map(lambda t:(9/5)*t+32,temp)))
false
aea6710202bb1c7eb72d48776f310f9699fa8901
GuilhermeUtech/udemy-python
/S8/metodos_especiais.py
473
4.125
4
#Aula sobre métodos especiais class Book(object): def __init__(self, titulo, autor, paginas): print("livro criado") self.titulo = titulo self.autor = autor self.paginas = paginas def __str__(self): return "Título: {a}".format(a = self.titulo) def __len__(self): return self.paginas def __del__(self): print("Livro destruído") livro = Book("livro sobre python", "Jorge bengola", 123) print(livro)
false
f8b92e0d180a0d0c39b292293c3d54139b61d532
Arina-prog/Python_homeworks
/homework 6/task_6_1.py
680
4.3125
4
#Create constant collection of numbers, print first size of the collection and elements on even positions # Создавайте постоянный набор чисел, печатайте первый размер коллекции и элементы на четных позициях #####tuple##### numbers = (15, 24, 36, -56, 89, 24, -13, 88,) print(len(numbers)) even_pos_num = numbers[::2] print('even positions num:', even_pos_num) ################################## numbers = [15, 24, 36, -56, 89, 24, -13, 88] count = 0 even_num = [] for num in numbers: if num % 2 == 0: count += 1 even_num.append(num) print(even_num) print(len(numbers))
false
b7cf3c1ab939e0a1d9bcdae9ceda7e468436e7d0
Arina-prog/Python_homeworks
/homeworks 5/task_5_15.py
585
4.125
4
# Define a collection of pets, that stores types of pet and its name, # find how many pets have name Johny and print the number #Определите коллекцию домашних животных, в которой хранятся типы питомца и его имя, # найдите, сколько домашних животных имеют имя Джонни, и распечатайте номер pets = {"pig": "Johny", "cat": "Murzik", "dog": "Johny", " mouse": "Jery"} count = 0 for pet in pets.values(): if pet == "Johny": count += 1 print(count)
false
ceb5e1e308b6b8ecb19d05043efc6a5b594a1af4
Arina-prog/Python_homeworks
/homeworks 5/task_5_16.py
794
4.1875
4
# Create a collection for storing hotel visitors (name, country), input several visitors from console, # print how many visitors are now in hotel, what is their country, what is their name # Создайте коллекцию для хранения посетителей отеля (название, страна), введите несколько посетителей с консоли, # распечатайте, сколько посетителей сейчас в отеле, какая их страна, как их зовут hotel = {"Ani": "Armenian", "Gary": "Russian", "Jek": "UK"} # hotel = {} count = 0 number = int(input("number visitors:\n")) while(count < number): hotel[input("name:\n ")] = input("country:\n ") count += 1 print(len(hotel)) print(hotel)
false
093720f7c20640d74d7575e31ed14b203c40ba77
Arina-prog/Python_homeworks
/homework 6/task_6_2.py
582
4.21875
4
# Create a collection for storing unique book names, add some of them from console and print results # Создайте коллекцию для хранения уникальных названий книг, # добавьте некоторые из них из консоли и распечатайте результаты #####set#### book = {"Margo taguhin", "Musa leran 40 or@", "Vardananq"} count = int(input("input book name count>3: \n")) # book.append(input('Write your favorite Book name: ')) while(len(book) < count): book.add(input("input book name:\n ")) print(book)
false
61f08f63460e8e550907de25069430fabfb4f5c0
Arina-prog/Python_homeworks
/homework 7/task_7_6.py
1,844
4.5
4
# Create a calculator with different functions: 1) input numbers (one or more); # 2) calculate different power for inputed numbers; # 3) calculate how many numbers are greater than some specific number; # 4) calculate how many numbers are even; 5) get number which power 3 is greater than 100 # Создайте калькулятор с различными функциями: # 1) ввод чисел (одного или нескольких); # 2) вычислить разную степень для введенных чисел; # 3) посчитать, на сколько чисел больше определенного числа; # 4) посчитайте, сколько чисел четное; # 5) получить число, степень которого 3 больше 100 def power(arr, degri): lis = [] for i in arr: result = pow(i, degri) lis.append(result) return lis def greater(arr, const_num=25): lis = [] for i in arr: result = i - const_num if result < 0: lis.append("no greater") else: lis.append(result) return lis def power_3(arr): lis = [] for i in arr: result = pow(i, 3) if result > 100: lis.append(i) lis.append(result) return lis def even(arr): colc = 0 for i in arr: if i % 2 == 0: colc += 1 return colc count = int(input("input count number:\n")) colc = 0 const_num = 23 def inputer(colc, count): lis = [] while(colc < count): num = int(input("number: ")) lis.append(num) # degri = int(input("input degri\n")) colc += 1 # return (power(lis, degri)) # return (greater(lis, const_num)) # return (power_3(lis)) return (even(lis)) print(inputer(colc,count))
false
9ce8dd9b48fbc9282af6eb4943d8570a98ddd5e4
Arina-prog/Python_homeworks
/homeworks 5/task_5.2.py
254
4.5
4
# Input a string and get substring from start to some position # 2... Введите строку и получите подстроку от начала до некоторой позиции str1 = "tt magistr 1 curs" print(str1[:9]) print(str1[0:9])
false
a27516780c8286565c152f79c268337a74b07393
Arina-prog/Python_homeworks
/homeworks 5/task_5.1.py
320
4.25
4
# Input one string, define another one, concatenate them and print the result # 1,,* Введите одну строку, определите другую, объедините их и распечатайте результат str1 = "hellow" str2 = input("input string:\n") result = str1 + " " + str2 print(result)
false
38251a25f706269fea9f094a6354c755cd5ca692
samuduesp/learn-python
/namecondition.py
243
4.125
4
name = input("What is your name: ") if len(name) >= 6: print("your name is long") elif len(name) >= 5: print("your name is not long") elif len(name) >= 4: print ("your name is short") else: print("your name is very short")
false
9e53024d91ab04a183c86568702f998adb035d3b
samuduesp/learn-python
/work/work.py
677
4.125
4
new = {} numbers = int(input("how many numbers: ")) for i in range(numbers): name =input("enter name of the person? ") age =input("enter age of the person?") bday =input("enter your bday?: ") key = input("name") value = input("enter value") theme =input("enter year") fruits[key] = value = theme myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } x=myfamily['child1']['name'] print(x) y = myfamily.keys() for x in y: print(myfamily[x]['name',age])
true
0c286bd36a24a29c6c2bc152aac5e53c9b9d4d87
martinstangl/iWeek_IntroducingPython
/x01_first_steps/00a_hello_world_basic_data_types.py
1,742
4.34375
4
from datetime import datetime print("Hello world!") # ein Kommentar a = 5 # eine variable print(a) print(type(a)) # Typ wird zur Laufzeit ermittelt a = "5" print(a) print(type(a)) # Typ wird zur Laufzeit ermittelt a = True print(a) print(type(a)) # Typ wird zur laufzeit ermittelt a = "5" b = "1" print(a+b) # Datum birthday = datetime(2021, 3, 8) print(birthday.strftime("%a, %x")) # https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior diff = datetime.now() - birthday print(diff) print("##### Geburtstag eingeben #####") # jahr = input("Bitte Jahr eingeben: ") # monat = input("Bitte Monat eingeben:") # tag = input("Bitte Tag eingeben:") # # print("Eingaben über die Konsole sind immer vom Typ String! D.h. wir müssen die Eingaben" # " 'casten', um mit ihnen zu rechnen") # # jahr = int(jahr) # monat = int(monat) # tag = int(tag) # # birthday = datetime(jahr, monat, tag) # diff = datetime.now() - birthday # print("Sie sind heute ",diff," Tage alt") ''' Aufgabe 1 Schreiben Sie ein kleines Skript, welches ein Geburtsdatum einliest und den Wochentag des kommenden Geburtstags ausgibt ''' # 1. Eingabe Geburtstag (Tag, Monat, Jahr) über die Console und Eingabedaten in Variablen speichern # 2. aktuelles Jahr über datetime.now() abrufen und in einer Variable speichern, # --> https://docs.python.org/3/library/datetime.html#datetime.datetime.year # 3. Jahr um 1 erhöhen (==> nächstes Jahr) # 4. Ein datetime-Objekt mit dem kommenden Geburtstag erstellen # --> blub = datetime(jahr, monat, tag) # 5. Wochentage ausgeben, Formatierung siehe: # --> https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
false
30bb1d3499fbb0a84409ae8b1abe12755dd69117
rupol/Computer-Architecture-Lecture
/02_bitwise/bit_masking.py
789
4.125
4
instruction = 0b10100010 # shifting by 6 should leave us with first two values shifted = instruction >> 6 # print(bin(shifted)) # 0b10 # what if we wanted to extract the two numbers in the middle? # first, convert so the bits in the middle are the last two digits shifted = instruction >> 3 # print(bin(shifted)) # 0b10011 # it's still not isolated, so now we'll need to remove all the preceding numbers (turn to 0s) # apply mask mask = 0b00000011 & shifted # print(bin(mask)) middle_two = (instruction >> 3) & 0b00000011 # print(bin(middle_two)) b = (instruction >> 5) & 0b00000001 # print(bin(b)) c = (instruction >> 4) & 0b00000001 print(bin(c)) flag = 0b00000101 # 00000LGE l = (flag >> 2) & 0b00000001 g = (flag >> 1) & 0b00000001 e = (flag >> 0) & 0b00000001 print(l, g, e)
true
c4cb355044d3e5c03ad2038193af42832b91ffbc
samratkaley/Developer
/Python/07_List.py
972
4.28125
4
# list Declaration:- list1 = ["Samrat","Omkar",50,315,500]; print (list1); list2 = [1,2,3,4,5,10]; list3 = [9,8,6] list4 = list1 + list2; # Concatenate two list print (list4); print (list1[2:4]); # print Range list print (list1[2:3]+list2[4:5]); #Concatinating two number from range print (list1[2]+list2[3]); # Adding two numbers print (list1[-1]); # Print last element of the list print (len(list1)); # Length of the list list1.append(50); # append function print (list1); print (list1.count(50)); # total count of specified element list2.extend(list3); # Add or combine two list print (list2); print (list1.index("Omkar")); # Index posotion of element print (list2.pop()); # remove element from last position print (list2); print (list2.remove(10)); # Remove the element by passing value print (list2); list2.reverse(); # Reverse the order of the element print (list2); list2.sort(); # Sort all the elements print (list2);
true
9924ed16860c153be1779753b7e31d51cf1b229f
ethan-mace/Coding-Dojo
/Python v4/Python Fundamentals v4/Python Fundamentals/Functions Basic 1/functions_basic1.py
1,932
4.25
4
# #1 Prints 5 # def a(): # return 5 # print(a()) # #2 Prints 5 + 5 # def a(): # return 5 # print(a()+a()) # #3 Prints 5. 'return' ends the functions prior to the next line # def a(): # return 5 # return 10 # print(a()) # #4 Same as #3 # def a(): # return 5 # print(10) # print(a()) # #5 Prints 5 from within the function. x has no value since there is no return # def a(): # print(5) # x = a() # print(x) # # 6 no return causes error # def a(b,c): # print(b+c) # print(a(1,2) + a(2,3)) # #7 Strings are concatenated rather than added # def a(b,c): # return str(b)+str(c) # print(a(2,5)) # #8 spaces on line 45 rather than tabs cause error # def a(): # b = 100 # print(b) # if b < 10: # return 5 #     else: #         return 10 # return 7 # print(a()) # #9 compares integers and returns designated result # def a(b,c): # if b<c: # return 7 # else: # return 14 # return 3 # print(a(2,3)) # print(a(5,3)) # print(a(2,3) + a(5,3)) # #10 returns b + c, will never return 10 unless b + c = 10 # def a(b,c): # return b+c # return 10 # print(a(3,5)) # #11 prints variations of b # b = 500 # print(b) # def a(): # b = 300 # print(b) # print(b) # a() # print(b) # #12 same as #11, just with a fancy return thrown in # b = 500 # print(b) # def a(): # b = 300 # print(b) # return b # print(b) # a() # print(b) # #13 ...same thing, with more steps # b = 500 # print(b) # def a(): # b = 300 # print(b) # return b # print(b) # b=a() # print(b) # #14 Calls a(), which prints 1, then calls b(), which prints 3, then returns to a(), which prints 2 # def a(): # print(1) # b() # print(2) # def b(): # print(3) # a() # #15 same thing, more steps # def a(): # print(1) # x = b() # print(x) # return 10 # def b(): # print(3) # return 5 # y = a() # print(y)
true
668c178f0cbe2ee64a0041d5ed97c2ab271614c5
yuryanliang/Python-Leetcoode
/Daily_Problem/20191004 Count Number of Unival Subtrees.py
911
4.21875
4
"""Hi, here's your problem today. This problem was recently asked by Microsoft: A unival tree is a tree where all the nodes have the same value. Given a binary tree, return the number of unival subtrees in the tree. For example, the following tree should return 5: 0 / \ 1 0 / \ 1 0 / \ 1 1 The 5 trees are: - The three single '1' leaf nodes. (+3) - The single '0' leaf node. (+1) - The [1, 1, 1] tree at the bottom. (+1) Here's a starting point: """ class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def count_unival_subtrees(root): # Fill this in. pass if __name__ == '__main__': a = Node(0) a.left = Node(1) a.right = Node(0) a.right.left = Node(1) a.right.right = Node(0) a.right.left.left = Node(1) a.right.left.right = Node(1) print(count_unival_subtrees(a))
true
145d92f103d9191f48c5646c0ea84b7c098d6eca
yuryanliang/Python-Leetcoode
/recursion/101 symmetric tree.py
1,605
4.375
4
""" Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 """ # Definition for a binary tree node. class Node: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root): if not root: return True return self.helper(root.left, root.right) def helper(self, left, right): if not left and not right: return True if (left and not right) or (right and not left) or (left.val != right.val): return False return self.helper(left.left, right.right) and self.helper(left.right, right.left) def main(): root = Node(1) root.left = Node(2) root.right = Node(2) print(Solution().isSymmetric(root)) class Solution: def isSymmetric(self, root): if not root: return True stack = [] stack.append(root.left) stack.append(root.right) while stack: l, r = stack.pop(), stack.pop() if not l and not r: continue if (not l and r) or (l and not r) or (l.val != r.val): return False stack.append(l.left) stack.append(r.right) stack.append(l.right) stack.append(r.left) return True if __name__ == '__main__': main()
true