blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
dbd7424c3d879df7cd7fc8c545c82632a139c3fa
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/marc_charbo/lesson08/circle.py
2,515
4.34375
4
#!/usr/bin/env python3 import logging import logging.config import math #logging.cong file logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('circle_log') class Circle(object): """ create circles and computes various metrics """ def __init__(self,radius): """initialize with radius""" self._radius = radius def __str__(self): """overload str to return circle radius""" return "Circle with radius: {:8.6f}".format(self.radius) def __repr__(self): return "Circle ({})".format(self.radius) def __add__(self, other): """overload add operator to sum circle radius""" return Circle(self.radius + other.radius) # question should this be radius or _radius? def __mul__(self, other): """overload add operator to multiply circle radius by a number""" return Circle(self.radius * other) def __lt__(self, other): """overload less than operator which compares two circle""" return self.radius < other.radius def __gt__(self, other): """overload greater than operator which compares two circle""" return self.radius > other.radius def __eq__(self, other): """overload equal operator which compares two circle""" return self.radius == other.radius def __ne__(self, other): """overload not equal operator which compares two circle""" return self.radius != other.radius @property def radius(self): return self._radius @property def diameter(self): return self._radius * 2 @diameter.setter def diameter(self,diameter): self._radius = diameter / 2 @property def area(self): return math.pi * self.radius ** 2.0 def run(): """ function which runs program """ print ("Started Circle Programm") circles = [] cr1 = Circle(1) circles.append(cr1) cr2 = Circle(2) circles.append(cr2) cr3 = Circle(3) circles.append(cr3) cr4 = Circle(4) circles.append(cr4) cr5 = Circle(5) circles.append(cr5) circles.sort() print("Sorted Circle List") print (circles) def main(): try: logging.info('Started Circle Program') run() except Exception as e: print ('error with task running program\n {}'.format(e)) logging.debug('error with running program\n %s' % e) finally: logging.info('Finished Circle Program') if __name__ == "__main__": main()
true
b486086393002fc1bcf7aa3c946b08250c88c14f
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/alex_skrn/lesson03/slicing.py
2,843
4.59375
5
"""Lesson03 - Assignment 1 - Sequence slicing.""" def exchange_first_last(seq): """Return a copy of seq with the 1st and last items exchanged.""" return seq[-1:] + seq[1:-1] + seq[0:1] def remove_every_other(seq): """Return a copy of seq with every other item removed.""" return seq[::2] def remove_first_last_4_and_every_other(seq): """Return a copy of seq with the first and last 4 items removed. Also removes every other item in between. """ return seq[4:-4:2] def reverse_elements(seq): """Return a copy of seq with the elements reversed (just with slicing).""" return seq[::-1] def reorder_middle_last_first(seq): """Return a copy of seq with the first third moved to the back.""" cut_point = len(seq) // 3 return seq[cut_point:] + seq[:cut_point] # TESTING SECTION def test_exchange_first_last(): """Test the exchange_first_last function.""" a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) def test_remove_every_other(): """Test the remove_every_other function.""" a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) assert remove_every_other(a_string) == "ti sasrn" assert remove_every_other(a_tuple) == (2, 13, 5) def test_remove_first_last_4_and_every_other(): """Test the remove_first_last_4_and_every_other function.""" a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32, 17, 55, 31, 1, 57, 21, 8) assert remove_first_last_4_and_every_other(a_string) == " sas" assert remove_first_last_4_and_every_other(a_tuple) == (5, 17, 31) def test_reverse_elements(): """Test the reverse_elements function.""" a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) assert reverse_elements(a_string) == 'gnirts a si siht' assert reverse_elements(a_tuple) == (32, 5, 12, 13, 54, 2) def test_reorder_middle_last_first(): """Test the reorder_middle_last_first function.""" a_string = "this is a string" a_tuple = (1, 2, 3) a_tuple_2 = (1, 2, 3, 4) a_tuple_3 = (1, 2, 3, 4, 5) a_tuple_4 = (1, 2, 3, 4, 5, 6) assert reorder_middle_last_first(a_string) == "is a stringthis " assert reorder_middle_last_first(a_tuple) == (2, 3, 1) assert reorder_middle_last_first(a_tuple_2) == (2, 3, 4, 1) assert reorder_middle_last_first(a_tuple_3) == (2, 3, 4, 5, 1) assert reorder_middle_last_first(a_tuple_4) == (3, 4, 5, 6, 1, 2) def run_tests(): """Run all tests.""" test_exchange_first_last() test_remove_every_other() test_remove_first_last_4_and_every_other() test_reverse_elements() test_reorder_middle_last_first() if __name__ == '__main__': run_tests()
true
49b2230fec27594c74c3ec2644878d35868eb3f1
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/ScottL/lesson02/grid.py
1,431
4.28125
4
#-------------------------------------------------# # Title: Grid Printer Exercise, working with Functions # Dev: Scott Luse # Date: January 30, 2018 #-------------------------------------------------# # Write a function that draws a grid like the following: ''' + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + ''' # -- Data --# intValue = 0 # -- Processing --# def createOneHorizontal(n): try: for x in range(1, n+1): print("+----" * n + "+") print("| " * (n+1)) print("+----" * n + "+") except Exception as e: print("Error: " + str(e)) # -- Presentation (Input/Output) --# try: print("This program draws a X by Y grid.") # Loop until user exit while (True): # Ask user for grid size strParam = input("Enter size of grid (2, 3, or 4) or type exit: ") # check for user 'exit' or continue if (strParam.lower() == "exit"): break # check for empty size elif (len(strParam) < 1): print("Please enter grid size.") else: intValue = int(strParam) createOneHorizontal(intValue) except Exception as e: print("Python reported the following error: " + str(e))
false
4716ed224cf82af80b02e92cbeb3b3fee415bb1c
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/PadmajaPeri/lesson04/kata_assignment.py
1,885
4.46875
4
#/usr/bin/env python3 """ Program to generate new text given an input text. It uses a dictionary to build trigrams of current text. __author__ == 'Padmaja Peri' """ import random def build_trigram_dict(fd): """ Method to build dictionary of trigrams from a text file """ words_dict = {} text = fd.read().split() idx = 0 # Stop looping when we have only two words left while idx < len(text) - 2: first_word = text[idx] second_word = text[idx + 1] third_word = text[idx + 2] dict_key = first_word + ' ' + second_word if dict_key in words_dict: words_dict[dict_key] += [third_word] else: words_dict[dict_key] = [third_word] idx += 1 return words_dict def generate_new_text(words_dict): """ Method to generate text based on a trigrams dictionary. The Algorithm picks a random key from the dict. It looks up the value for the key. For the next iteration we use the last word from the key and the value and form a new word. We repeat this process till we dont find a key in the dict. :param words_dict: :return: Text String """ # Get a random key from dict to start next_words = random.choice(list(words_dict.keys())) # Variable that holds the text accumulated text_so_far = next_words # Keep repeating the algorithm as long as we find a key in the dict while next_words in words_dict: value_in_dict = random.choice(words_dict[next_words]) text_so_far = text_so_far + ' ' + value_in_dict # New key is concat of last word from current key and the value next_words = next_words.split()[-1] + ' ' + value_in_dict return text_so_far if __name__ == '__main__': with open('sherlock.txt', 'r') as fd: trigram_dict = build_trigram_dict(fd) print(generate_new_text(trigram_dict))
true
902e13b092e1ef68ca16b5b7b6342c434a35e80b
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/daniel_grubbs/lesson04/dict_lab.py
2,069
4.5625
5
#!/usr/bin/env python3 # Lesson 04 # filename: dict_lab.py def main(): """Main function of the program.""" print_header() tasks = "Tasks from lesson04 dictionary assignment.\n" print(tasks) dict_tasks() set_tasks() def print_header(): """Print the header of the program.""" print('------------------------------------') print(' Lesson04') print(' Dictionary Assignment') print('------------------------------------\n') def dict_tasks(): """Perform the dictionary tasks outlined in the lesson. - Dictionaries 1 """ dict_task1 = { 'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate' } print(dict_task1) del dict_task1['cake'] print("Removed 'cake' key from the dictionary, let's take a look at our dictionary now: \n") for k, v in dict_task1.items(): print('{}: {}'.format(k, v)) dict_task1['fruit'] = 'Mango' print(dict_task1.keys()) print(dict_task1.values()) if 'cake' not in dict_task1.keys(): print("'cake' is not in the dictionary. This item of task completed, move on.") else: print("'cake' is in the dictionary.") if 'Mango' in dict_task1.values(): print("'Mango' is in the dictionary. This item of task completed, move on.") else: print("'Mango' is not in the dictionary.") def set_tasks(): """Performing the tasks for 'set'""" s2 = set() s3 = set() s4 = set() for i in range(21): if i % 2: s2.add(i) elif i % 3: s3.add(i) elif i % 4: s4.add(i) print(s2) print(s3) print(s4) if not s3.issubset(s2): print('s3 is not a subset of s2, so False') if s4.issubset(s2): print('s4 is a subset of s2, so True') s1 = set('Python') s1.add('i') print(s1) s5 = ('m', 'a', 'r', 'a', 't', 'h', 'o', 'n') frozen = frozenset(s5) print(s1.union(frozen)) print(s1.intersection(frozen)) if __name__ == '__main__': main()
true
042597809207a63fe4bbefbbad38b1cc2d6a0e33
gongon84/challenge
/challenge6.py
1,615
4.25
4
#1「正解」文字を1文字ずつ出力 print("\n第1問") word = "カミュ" print(word[0]) print(word[1]) print(word[2]) #2「正解」inputを用いて文章を完成させる print("\n第2問") word1 = input("何を書いた?:") word2 = input("誰に送った?:") a = "私は昨日 {}を書いて、{}に送った!".format(word1,word2) print(a) #3「正解」文字の先頭を大文字にする print("\n第3問") b = "aldous Huxley was born in 1894" b = b.capitalize() print(b) #4「正解」文を分割してリストに print("\n第4問") c = "どこで? 誰が? いつ?" c = c.split( ) print(c) #5「不正解」リストを1つの文字列に print("\n第5問") d = ["The","fox","jumped","over","the","fense","."] d = " ".join(d) #不正解部分 d = d[0:-2] + "." print(d) #6「正解」全てのsを¥に変える print("\n第6問") e = "A screaming comes across the sky." e = e.replace("s","$s") print(e) #7「正解」最初にmが出現するインデックス print("\n第7問") f = "Hemingway" f = f.index("m") print(f) #8「正解」クォーと文字が含まれてる文を文字列に print("\n第8問") g = "僕は\"肉\"を食べた" print(g) #9「正解」+と*を使って"three three three"という文字列 print("\n第9問") h = "three" + " three" + " three" i = "three " * 3 i = i.strip() print(h) print(i) #「正解」10 スライスして"、"までの文字列 print("\n10問目") j = "四月の晴れた寒い日で、時計がどれも十三時を打っていた。" number = j.index("、") #10を取得 print(number) j = j[:10] print(j)
false
18155ac857ad44a62616b41f972d71576d4191e8
gongon84/challenge
/challenge4.py
961
4.25
4
def print_string(string): print(string) print_string("Testing: 1, 2, 3.") #1 def squared(x): """ Return x**2. :Param x: float. :return: square of x. """ return x ** 2 x = input("[1]type a number:") x = float(x) print("x ** 2 =",squared(x)) #2 def st(x): return str(x) y = input("[2]文字を入力してください:") print("入力した文字は",st(y)) #3 def five(a,b,x=1,y=2,z=3): return x + y + z + a + b a = input("[3]数字を入力してください") a = int(a) b = input("[3]数字を入力してください") b = int(b) print("a + b + 6 =",five(a,b)) #4 def su(x): return x / 2 def suu(x): return x * 4 z = input("[4]整数を入力してください:") z = float(z) print("z / 2 =",su(z)) c = float(su(z)) print("c * 4 =",suu(c)) #5 d = input("[5]文字を入力してください:") d = str(d) try: print(float(d)) except (ValueError): print("これは入力できません")
false
f6bda5f4740fd0c70e1dcc649970b596813a4a41
rhys-s/Sandbox_2
/Prac_03/password_entry_2.py
1,064
4.1875
4
MINIMUM_LENGTH = 4 MAX_LENGTH = 6 """ def main(): pw = input("Enter password length of at least {} and max of {}: ".format(MINIMUM_LENGTH,MAX_LENGTH)) while len(pw) < MINIMUM_LENGTH or len(pw) > MAX_LENGTH: pw = input("Please Re enter a password length of at least {} and max of {}: ".format(MINIMUM_LENGTH, MAX_LENGTH)) print('*'*len(pw)) main() """ def main(): """Obtain pword and print stars""" pw = get_password(MINIMUM_LENGTH, MAX_LENGTH) asterik_print(pw) def get_password(min_length, max_length): """User enters pword, checks for length standards""" pw = input("Enter password length of at least {} and max of {}: ".format(MINIMUM_LENGTH, MAX_LENGTH)) while len(pw) < min_length or len(pw) > max_length: print('Password is not an appropiate length') pw = input("Enter password length of at least {} and max of {}: ".format(MINIMUM_LENGTH, MAX_LENGTH)) return pw def asterik_print(string): """Prints same amount of asteriks as string length""" print('*' * len(string)) main()
true
1fe37fc16fdf18994abdeb110edf3cbb2a224c33
flinteller/unit_three
/assignment_three.py
2,600
4.25
4
# Flint Eller # 9/24/18 # This program draws a flower based on user input import turtle def get_length_hexagon(): """ asks user the length of the hexagon :return: side length """ length = float(input("What is the side length of the hexagon?")) return length def get_petal_color(): """ asks user the petal color :return: petal color """ petal_color = input("What color should the flower petals be?") return petal_color def get_center_color(): """ asks user center color :return: center color """ center_color = input("What color should the center of the flower be?") return center_color def draw_hex(length, color): """ draws a hexagon with side length and color chosen by user :param length: :param color: :return: """ turtle.color(color) turtle.begin_fill() for x in range(6): turtle.forward(length) turtle.right(60) turtle.end_fill() def draw_flower(): """ Draws side six hexagons as petals around one hexagon in center all using user's color and side length :return: """ # This draws the center hexagon length_hex = get_length_hexagon() petal_color = get_petal_color() draw_hex(length_hex, get_center_color()) # Move to the correct location and draw a hexagon for petal turtle.penup() turtle.left(120) turtle.forward(length_hex) turtle.right(60) turtle.forward(length_hex) turtle.right(60) turtle.pendown() draw_hex(length_hex, petal_color) turtle.penup() turtle.forward(length_hex) turtle.right(60) turtle.forward(length_hex) turtle.left(60) turtle.pendown() draw_hex(length_hex, petal_color) turtle.penup() turtle.left(240) turtle.forward(length_hex) turtle.left(60) turtle.forward(length_hex) turtle.left(60) turtle.pendown() draw_hex(length_hex, petal_color) turtle.penup() turtle.left(240) turtle.forward(length_hex) turtle.right(60) turtle.forward(length_hex) turtle.left(180) turtle.pendown() draw_hex(length_hex, petal_color) turtle.penup() turtle.left(120) turtle.forward(length_hex) turtle.left(60) turtle.forward(length_hex) turtle.left(180) turtle.pendown() draw_hex(length_hex, petal_color) turtle.penup() turtle.left(120) turtle.forward(length_hex) turtle.right(60) turtle.forward(length_hex) turtle.right(60) turtle.pendown() draw_hex(length_hex, petal_color) def main(): draw_flower() main() turtle.exitonclick()
true
587359b239097d3c1acad8496e173a7d7f4be4e3
jalondono/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
420
4.125
4
#!/usr/bin/python3 """Function to count the number of lines insede a file""" def number_of_lines(filename=""): linenum = 0 """ printing a file :param filename: :return: number of lines """ with open(filename, encoding="utf-8") as myFile: while True: line = myFile.readline() if not line: break linenum += 1 return linenum
true
2c51241121083b534a207e6cbd70bdd8e318316b
jalondono/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
249
4.15625
4
#!/usr/bin/python3 """Function de read and print a file""" def read_file(filename=""): """ printing a file :param filename: :return: """ with open(filename, encoding="utf-8") as myFile: print(myFile.read(), end='')
true
72d196da6c5ec30b39d7aaec9472fb382deb1de3
yangpei/StudyPython
/Day1.py
1,026
4.21875
4
print('hello, world') # print()函数也可以接受多个字符串,用逗号“,”隔开,就可以连成一串输出: print('The quick brown fox', 'jumps over', 'the lazy dog') ///////////////////////// name = 1024*768 print(name) # Python程序是大小写敏感的,如果写错了大小写,程序会报错。 ///////////////////////////////// # Tips: Python使用缩进来组织代码块,请务必遵守约定俗成的习惯,坚持使用4个空格的缩进。 # Tips:在文本编辑器中,需要设置把Tab自动转换为4个空格,确保不混用Tab和空格。 ///////////////////////////// print('''line1 line2 line3''') #前后的'''中间写字符,表示多行字符串。 print(r'''line1 line2 line3''') #或者加r也可以 /////////////////////////////////////// #单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符: >>> ord('A') 65 >>> ord('中') 20013 >>> chr(66) 'B' >>> chr(25991) '文'
false
3e655478c1d947a3ec6ecba0785a444490fa48b7
arpancodes/CoffeeMachine__Python
/main.py
2,288
4.21875
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, "money": 0 } def print_report(): print(f'Water: {resources["water"]}ml') print(f'Milk: {resources["milk"]}ml') print(f'Coffee: {resources["coffee"]}g') print(f'Money: ${resources["money"]}') def update_resources(coffee): for key in coffee["ingredients"]: resources[key] -= coffee["ingredients"][key] resources["money"] += coffee["cost"] def process_payment(coffee): print(f"You need to pay ${coffee['cost']}") quarters = int(input("Enter no of quarters: ")) * 0.25 dime = int(input("Enter no of dime: ")) * 0.10 nickles = int(input("Enter no of nickels: ")) * 0.05 pennies = int(input("Enter no of pennies: ")) * 0.01 total = quarters + nickles + dime + pennies if total < coffee["cost"]: print("Sorry that's not enough money. Money refunded.") else: print("Your coffee is ready! Enjoy") update_resources(coffee) if total > coffee["cost"]: print(f'Here is ${round(total - coffee["cost"], 2)} dollars in change.') def process_coffee(coffee_type): print(f"Getting {coffee_type} ready.") coffee_req = MENU[coffee_type] coffee_resources = coffee_req["ingredients"] for key in coffee_resources: if coffee_resources[key] > resources[key]: print(f"Insufficient {key}") return process_payment(coffee_req) isMachineOn = True while isMachineOn: choice = input("What would you like? (espresso/latte/cappuccino): ").lower() if choice == "off": isMachineOn = False elif choice == "report": print_report() elif choice == "espresso" or choice == "latte" or choice == "cappuccino": process_coffee(choice) else: print(f"Couldn't recognise {choice}")
false
071e11f5269450bee89c2edd68ebb9fd7c828f29
anulachoudhary/Leetcode
/sum-list.py
272
4.125
4
# Compute the sum of a list of numbers. # For example: # >>> sum_list([5, 3, 6, 2, 1]) # 17 def sum_list(num_list): """Return the sum of all numbers in list.""" # START SOLUTION output = 0 for num in num_list: output += num return output
true
d8c5d3d9bed45975b3db0ae892470833cb7498ef
anulachoudhary/Leetcode
/days-in-month.py
1,795
4.28125
4
# Given a string with a month and a year (separated by a space), # return the number of days in that month. # Leap years are a bit tricky. A year is a leap year if and only if: # it is evenly divisible by 4 # except if it is divisible by 100, in which case it isn’t # except if it is divisible by 400, in which case it is # So, for example, 1904 was a leap year. 1900 is divisible by 100, so it wasn’t. # 2000 is divisible by 400, so it was. def is_leap_year(year): """Is this year a leap year? Every 4 years is a leap year:: >>> is_leap_year(1904) True Except every hundred years:: >>> is_leap_year(1900) False Except-except every 400:: >>> is_leap_year(2000) True """ if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True # The Input # The month will be given as a number. # >>> for i in range(1, 13): # ... date = str(i) + " 2016" # ... print "%s has %s days." % (date, days_in_month(date)) # 1 2016 has 31 days. # 2 2016 has 29 days. # 3 2016 has 31 days. # 4 2016 has 30 days. # 5 2016 has 31 days. # 6 2016 has 30 days. # 7 2016 has 31 days. # 8 2016 has 31 days. # 9 2016 has 30 days. # 10 2016 has 31 days. # 11 2016 has 30 days. # 12 2016 has 31 days. # >>> days_in_month("02 2015") # 28 def days_in_month(date): """How many days are there in a month?""" # START SOLUTION month, year = date.split() month = int(month) year = int(year) # Account for February if month == 2: if is_leap_year(year): return 29 else: return 28 if month in {1, 3, 5, 7, 8, 10, 12}: return 31 if month in {4, 6, 9, 11}: return 30
true
952e920216bad1b37784864181a6e76af8397465
AslanDevbrat/Show-Me-the-Data-Structures
/Problem 2 File Recursion/File Recursion.py
1,714
4.4375
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if suffix.isnumeric() or len(suffix)==0 : #print('Invalid Suffix') return ['Invalid Syntax'] paths_list=[] if os.path.isfile(path): if path.endswith(suffix): #print(path) return path return for item in os.listdir(path): new_path = os.path.join(path,item) temp =find_files(suffix,new_path) if temp: paths_list.append(temp) #print(os.listdir('./testdir/subdir1')) #print(os.path.isdir('./testdir/subdir1/a.c')) return paths_list def test_func(paths): for path in paths: if type(path) is list: test_func(path) else: print(path) #test 1 print("List all file with extension .c") paths_list =[] test_func(find_files('.c','.')) print('-----------------------------------------------------------------------') #test 2 print("List all files with extension of .h") paths_list =[] test_func(find_files('.h','.')) print('-----------------------------------------------------------------------') # TEST 3 paths_list =[] print("checking with invalid syntax") test_func(find_files('','.')) print('-----------------------------------------------------------------------')
true
79727f7d3e00bde89a8e18a40a9a8e1f6a0c70b5
fhauben/mystuff
/ex15.py
496
4.15625
4
from sys import argv #lines -3 use argv to get a filename script, filename = argv txt = open(filename) #line 5 uses our new command, open print "Here's your file %r:" % filename #line 7 prints a message print txt.read() #line 8 we have something new - # we call a function on txt named read; what you get back from open is a file, and it also has commands you can give it print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
true
eadd0b202a31038d46bea06b228e2a86ff4fd786
ThomasStuart/pythonLessonAPril27
/for_loops.py
2,419
4.375
4
# Lists. # - how to iterate through a list w/out range # - how to iterate through a list with range # - how to add a counter to a list # - how to change the increment amount of a for loop # - hwo to change to a decrementer # - indexing with a list fruits = ['banana', 'apple', 'mango'] # element @ 0 == banana iteration 0 # element @ 1 == apple iteration 1 # element @ 2 == mango iteration 2 ... idex_num = 0 # for element in fruits: # go through the entire list # print( "element @ " ,idex_num, "==", element ) # idex_num += 1 # for whatever in fruits: # go through the entire list # print( "element @ " ,idex_num, "==", whatever ) # idex_num += 1 # <--this line increases the number by 1 each iteartion # # say i didnt want to print the first elemet # for index in range(1, len(fruits) ): # print( fruits[index] ) #list_apple = ['a', 'p', 'p', 'l', 'e'] word = "apple" # print apple character by character starting at a # for character in word: # print(character) # print apple character by character starting at e word = "apple" # 5 characters in the word apple len_apple = len( word ) # 0 1 2 3 4 # word = "a p p l e" # # # start = 4 ,end = -1 , go down by one # for index in range( len(word)-1, -1, -1 ): # print( word[index] ) # my_name = "thomas" # startNumber = 0 # endNumber = len( my_name) # howMuchIncrease = 1 # for number in range(startNumber, endNumber, howMuchIncrease): # print( my_name[number] , end='') even_word = "acefdb" # even_word = "cefd" # even_word = "ef" # even_word = "" # END GOAL: # "front==", a "... end==", b # iteration 0 # "front==", c "... end==", d # iteration 1 # "front==", e "... end==", f # iteration 2 #hint use a for loop and a counter counter = len(even_word)-1 start_index = 0 end_index = len(even_word) # the for loop ran a total of 6 times # but we want the for loop to run a total of 3 times for index in range(start_index, int( end_index/2) ): print( "front==", even_word[index] ," ", end='') print( "end==", even_word[counter]) counter = counter - 1 #hint: # counter = 5 # print( "what is the current value of counter== ", counter ) # # decrease counter by one # counter = counter - 1 # print( "what is the current value of counter== ", counter ) p1 = "racecar" print( p1 )
true
8f59d27eff87a25c9d6106fffb5cf09db394ba10
AbrahamFr/PythonCourse
/essentials/corepy/iterationProtocols.py
459
4.15625
4
# iterable = ['Spring', 'Summer', 'Autumn', 'Winter'] # iterator = iter(iterable) # next(iterator) # next(iterator) # next(iterator) # next(iterator) # next(iterator) def first(iterable): iterable = iter(iterable) try: return next(iterable) except StopIteration: raise ValueError("iteable is empty") print(first(["1st", "2nd", "3rd"])) # List print(first({"1st", "2nd", "3rd"})) # Set print(first(set())) # Empty set
true
efa820e34059d57887ff1e3b698c6cd3ceb070d9
cj3131/210CT-Coursework-Callum-Huntington
/basic10.py
1,265
4.125
4
""" Q10: Given a sequence of n integer numbers, extract the sub-sequence of maximum length which is in ascending order. This program terminates when the entire list has been iterated through. The only valid input is a list of integers, positive or negative. The longest sequence is found by comparing each element to it's next. If the next element is greater, add it to a temporary list. If it is smaller, start a new temporary list. If the temporary list grows longer than the current best list, replace the best list. """ numList = [3,4,7,2,9,6,1,9,13,16,18,20,25] finalList = [] tempList = [] bestSeqLength = 0 for i in numList: #if the next number in the list is larger than the last item in the potential sequence, add it to the sequence if tempList == [] or i >= tempList[-1]: tempList.append(i) #if the current potential sequence is longer than the current best sequence, replace the best sequence. if bestSeqLength <= len(tempList): finalList = tempList bestSeqLength = len(finalList) print("Best so far: ", finalList) #if the sequence is broken, start a new potential sequence. if i < tempList[-1]: tempList = [] print("The best sequence is ", finalList, " of length ", bestSeqLength)
true
aa2bb99b06b552c5f7176e8ba0a61a6db40c860a
gwgowdey/ITSE1479-Intro-to-Scripting-Languages
/Lab 5/Part 1.py
2,091
4.75
5
""" Student: Griffin Gowdey. Instructor: Dorothy Harman. Class Number: ITSE1479-20234 Class Name: Intro to Scripting Languages. Semester: Fall 2020. Part 1. Assignment: See "Turtle Shapes To Program" PDF file in Lab 5 folder for original questions and example graphics. 1.) Draw a square. 2.) Draw a 5-pointed star. 3.) Draw an example of changing line color. If you want to use other colors: https://www.webfx.com/web-design/color-picker/. Specify the colors with a # and the hexadecimal code. There are many color pickers on the web for use, this is just one. 4.) Draw a hexagon shape. 5.) Draw a grid of dots. 5 dots wide and 7 dots high. 6.) Draw any one of the spiral shapes (see PDF in the Lab 5 folder) or create your own spiral shape. """ # Turtle import for all questions/subsections. import turtle # 1.) Draw a square. turtle.forward (50) turtle.left (90) turtle.forward (50) turtle.left (90) turtle.forward (50) turtle.left (90) turtle.forward (50) turtle.left (90) turtle.exitonclick() # 2.) Draw a 5-pointed star. for x in range (5): turtle.forward (400) turtle.right (144) turtle.done turtle.exitonclick() # 3.) Draw an example of changing line color. colors = ["red", "blue", "green", "gray", "orange", "black"] for x in range (100): turtle.forward (5 + x) turtle.right (15) turtle.color (colors[x%6]) turtle.done # 4.) Draw a Hexagon Shape. for x in range (6): turtle.forward (100) turtle.right (60) turtle.exitonclick() # 5.) Draw a grid of dots. 5 dots wide and 7 dots high. grid = turtle.turtle() dot_distance = 10 width = 5 height = 7 grid.penup () grid.setposition (100, 0) for y in range (height): for x in range (width): grid.dot () grid.forward (dot_distance) grid.backward (dot_distance * width) grid.right (90) grid.forward (dot_distance) grid.left (90) turtle.exitonclick() # 6.) Draw any one of the spiral shapes or create your own spiral shape. for x in range (100): turtle.forward (5 + x) turtle.right (15) turtle.done
true
66a81175e07a81351b8a59c2c8615908cc22017c
gwgowdey/ITSE1479-Intro-to-Scripting-Languages
/Lab 1/Part 3.py
1,792
4.21875
4
""" Student: Griffin Gowdey. Instructor: Dorothy Harman. Class Number: ITSE1479-20234 Class Name: Intro to Scripting Languages. Semester: Fall 2020. Part 3. Assignment: An employee’s gross weekly pay equals their hourly wage multiplied by the total number of regular hours plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s gross weekly pay. Note: we are not going to take into consideration taxes. We are calculating gross pay only. Be sure that you display appropriate prompts for input so the viewer knows what to type in. And make sure that your output is identified as: Weekly Gross Pay. Pseudocode: Input: Float for regular hours, overtime hours, and hourly wage. Process: Equation for calculating weekly gross pay. Output: Weekly gross pay. """ # User enters the number of regular hours worked. RegularHours = float (input ("Enter your number of regular hours worked in whole number or decimal format (max of 40.0): ")) # User enters the number of overtime hours worked. OvertimeHours = float (input ("Enter your number of overtime hours worked in whole number or decimal format: ")) # User enters the hourly wage of that employee. HourlyWage = float (input ("Enter your hourly wage in whole number or decimal format: ")) # Display equation for user to calculate Weekly Gross Pay. print ("Weekly Gross Pay = (regular hours worked x your hourly wage) + (overtime hours x (1.5 x your hourly wage))") # Equation for calculating Weekly Gross Pay. print ("Employee weekly gross pay = ") print ((RegularHours * HourlyWage) + (OvertimeHours * (1.5 * HourlyWage)))
true
27d5af48130bdedd18477d41188f7502f9685882
allyrob/presentationgame
/nims_refactored.py
968
4.21875
4
print """ ========================================================================= Thanks for playing Nims Refactored! The goal of the game is to not be the last player to take a bottle of beer down from the wall. A player take down between 1-10 beers during their turn Setup: Player One will decide how many bottles of beer are on the wall Player Two will make the first selection of beers Player One and Two will then take turns removing the beers from the wall until 1 beer remains The player that takes down the last beer loses the game ========================================================================= """ beers = int(raw_input("""Player One: How many bottles of beer on the wall should we start with: choose between 1 and 99""")) if not 0 < beers < 100: print "that's the wrong number of beers" number_of_turns = 0 while (beers > 1): if (number_of_turns %2 != 0): remove_beers
true
c9315a3604e45c63758d9e23912c6d7f3c82cc55
rodolforicardotech/pythongeral
/pythonparazumbis/Lista01/PPZ07.py
219
4.125
4
# 7) Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32 celsius = float(input('Digite a temperatura em Celsius: ')) faren = (9*celsius/5) + 32 print('A temperatura em Fahrenheit é: ', faren)
false
c6ed0e717ab7bb9ecb285e4c8b816a2e9cad12fc
jcrivera2709/WebScrappingWithPython
/Application/ListComprehension.py
857
4.5
4
names = ['Jose', 'Carlos', 'Rivera', 'Santiago'] # Both print the same thing but the list comprehension allows you to go from 4 lines of code to 1 line. l = [] for people in names: l.append(people) print(l) print([people for people in names]) # Adding information to the already made list with list comprehension anotherL = [] for people in names: anotherL.append(people + ' is part of my name.') print(anotherL) print([people + ' is part of my name.' for people in names]) # Small example with list comprehension and manipulation in the list comprehension movies_and_ratings = {"Shrek": 3, "Dark Knight": 8, "Avatar": 10, "Star Wars": 10} movieL = [] for movie in movies_and_ratings: if movies_and_ratings[movie] > 6: movieL.append(movie) print(movieL) print([movie for movie in movies_and_ratings if movies_and_ratings[movie] > 6])
true
fd4b999ab7b0fc93308b6f1878d2edb88eefd454
Dememedp/pet21
/Task21/Task21.py
305
4.375
4
def replace_symbols(str): newstr = "" for letter in str: if letter == "'": newstr += "\"" elif letter == "\"": newstr += "'" else: newstr +=letter return newstr str = input("input a string\n") print(replace_symbols(str))
false
338e050ca59c206ae9d952e19e4a08ba89231b61
QiWang-SJTU/AID1906
/Data Structure And Algorithm/sortint_algorithm_排序算法/Quick/quick_sort.py
1,807
4.1875
4
def quick_sort(list_target, start, end): """ 快速排序算法(默认升序) 最坏时间复杂度 ---> O(n ^ 2) 最优时间复杂度 ---> O(n * log(n)) 不稳定 :param list_target: 待排序列表 :param start: int 起始下标 :param end: int 终止下标 :return: None """ # 递归的退出条件 if start >= end: return # 设定起始元素为要寻找位置的基准元素 mid = list_target[start] # low为序列左边的由左向右移动的游标 low = start # high为序列右边的由右向左移动的游标 high = end while low < high: # 如果low与high未重合,high指向的元素不比基准元素小,则high向左移动 while low < high and list_target[high] >= mid: high -= 1 # 将high指向的元素放到low的位置上 list_target[low] = list_target[high] # 如果low与high未重合,low指向的元素比基准元素小,则low向右移动 while low < high and list_target[low] < mid: low += 1 # 将low指向的元素放到high的位置上 list_target[high] = list_target[low] # 退出循环后,low与high重合,此时所指位置为基准元素的正确位置 # 将基准元素放到该位置 list_target[low] = mid # 对基准元素左边的子序列进行快速排序 quick_sort(list_target, start, low - 1) # 对基准元素右边的子序列进行快速排序 quick_sort(list_target, low + 1, end) # todo 必须掌握快排 if __name__ == "__main__": list01 = [2, 7, 4, 5, 45, 30, 9, 29] print(list01) quick_sort(list01, 0, len(list01) - 1) print(list01)
false
2a9a5ed3321f2042ae31ae94c2c88e7c1f5791cf
DmitryIvanov10/Python
/Lista7/task2.py
806
4.28125
4
# Lesson7, Task2 # import data from modules from sys import argv from temperatures import random_celsius_degree # max temperature in Celsius degrees max_T = 300 # Check if user input is correct if len(argv) != 2: print ("Wrong amount of arguments.") elif not argv[1].isdigit(): print ("Wrong data for amount of generating temperatures") else: # amount of generating temperatures n = int(argv[1]) # create file to write data to (and clear if necessary) with open("celsius.txt","a+") as f: # clear the file open("celsius.txt","w").close() # add a line with commentaries to file f.write("# Temperature in Celsius\n") # add temperature data to file for i in range(n): f.write("{}\n".format(random_celsius_degree(max_T)))
true
2e4ba037bb767614246d17150d0ce7d94cdfd53d
DmitryIvanov10/Python
/Lista4/task2_3.py
1,043
4.125
4
<<<<<<< HEAD # Lesson4, Task2 and Task3 # But actually min is already built-in function for that # Find smaller number def getMinFrom2(a,b): if a<b: return a else: return b # Example a = 10 b = 7.1 print ("Smaller number between %2f and %2f is %2f." % (a, b, getMinFrom2(a,b))) print () def getMin(*args): minNumber = args[0] for number in args: minNumber = getMinFrom2(minNumber, number) return minNumber # Example ======= # Lesson4, Task2 and Task3 # But actually min is already built-in function for that # Find smaller number def getMinFrom2(a,b): if a<b: return a else: return b # Example a = 10 b = 7.1 print ("Smaller number between %2f and %2f is %2f." % (a, b, getMinFrom2(a,b))) print () def getMin(*args): minNumber = args[0] for number in args: minNumber = getMinFrom2(minNumber, number) return minNumber # Example >>>>>>> 0b1190fafe0f850c1325c7e615b1abd120588142 print ("The smallest number in the list is %2f." % getMin(1, 4, -2, 5.1, 10, -3.6, -3.7, -100))
true
8fd954a3e5224ba444049b9f562bba4d60febf3f
Loaezo/WeatherAPI
/ranges/compass.py
2,326
4.6875
5
def wind_direction(degrees): """ Function to convert degrees (360-based) to cardinal points :param degrees: receives the degrees the wind is blowing :return: the orientation as a string """ north = range(0, 11) north_2 = range(348, 360) north_northeast = range(11, 34) northeast = range(34, 56) east_northeast = range(56, 79) east = range(79, 101) east_southeast = range(101, 124) southeast = range(124, 146) south_southeast = range(146, 169) south = range(169, 191) south_southwest = range(191, 214) southwest = range(214, 236) west_southwest = range(236, 259) west = range(259, 281) west_northwest = range(281, 304) northwest = range(304, 326) north_northwest = range(326, 348) if degrees in north: direction = 'north' return direction elif degrees in north_2: direction = 'north' return direction elif degrees in north_northeast: direction = 'north northeast' return direction elif degrees in northeast: direction = 'northeast' return direction elif degrees in east_northeast: direction = 'east northeast' return direction elif degrees in east: direction = 'east' return direction elif degrees in east_southeast: direction = 'east southeast' return direction elif degrees in southeast: direction = 'southeast' return direction elif degrees in south_southeast: direction = 'south southeast' return direction elif degrees in south: direction = 'south' return direction elif degrees in south_southwest: direction = 'south southwest' return direction elif degrees in southwest: direction = 'southwest' return direction elif degrees in west_southwest: direction = 'west southwest' return direction elif degrees in west: direction = 'west' return direction elif degrees in west_northwest: direction = 'west northwest' return direction elif degrees in northwest: direction = 'northwest' return direction elif degrees in north_northwest: direction = 'north northwest' return direction
true
dc342517f9b8239371f16d13027fffb99447a58c
sami127/python_django
/functions_modules/first_function.py
813
4.15625
4
# def func(): # code goes here # func() # def func(a,b): # return a+b # result = func(20,30) # print("result is ",result) # d ={"name":"samiulla","age":27} # d["mobile"] = "9113034848" # print (d) # def dict_func(a,*n): # print("A value is ",a) # print("n value is ", n) # for b in n: # print(b) # dict_func(123,34,34454,454,56565,5,7,4,54,454) # b = lambda variable: expression # b = lambda x: x+10 # print(b(10)) # Filter function in python my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) # Output: [4, 6, 8, 12] # Program to double each item in a list using map() my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list) # Output: [2, 10, 8, 12, 16, 22, 6, 24]
false
7dcf5df5e55420a97624f229667282d23d90dfc6
sami127/python_django
/regex_pwd.py
693
4.15625
4
import re while True: password = input("Enter you password here : ") if (len(password)<8): print("Length of your password is less than 8") elif not re.search("[a-z]", password): print("Atleast one lower case character is required") elif not re.search("[A-Z]", password): print("Atleast one upper case character is required") elif not re.search("[0-9]", password): print("Atleast one number is required") elif not re.search("[!@#$%^&*_]", password): print("Atleast one special character frome '!@#$%^&*_' is required") elif re.search("\s", password): print('White spaces not allowed') else: print("Valid Password") break print("password checked successfully")
true
1ca00a1b0be4ca4999ca236cb21eb86ae5c6cba9
rinatEK/pythonExercises-7_ListComprehensions
/main.py
1,154
4.28125
4
# Created by: Patrick Archer # Date: 21 December 2018 # Copyright to the above author. All rights reserved. """ Directions - COMPLETE: Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. """ import random # ################################################# start_funcs # ################################################# end_funcs/start_main # initial random list random_list1 = [] for r1 in range(random.randrange(5, 50, 5, int)): random_list1.append(random.randrange(1, 100, 1, int)) print("\nRandomly-Generated List:\n" + str(random_list1)) # results list (even element values only) evenElements = [] # "one line of Python that takes this list a and makes a new list that has only the even elements of this list in it" evenElements = [random_list1[x] for x in range(len(random_list1)) if (random_list1[x] % 2 == 0)] print("\nEven elements within the previously-described list:\n" + str(evenElements)) # ################################################# end_main
true
a462b1d8b27a14dc35394767f558ed0ad5963352
NMOT/PycharmProjects1
/python_desafios/ex_1237.py
424
4.15625
4
numero_converter=int(input('Introduza o número inteiro que quer converter!')) base_conversao=str(input('''Digite: 1- Binário 2- Octal 3- Hexadecimal ''')) if base_conversao=='1': print(bin(numero_converter)) elif base_conversao=='2': print(oct(numero_converter)) else: print(hex(numero_converter))
false
09de3fa9582209f97e06d2a2848a674e8a3d7075
LSchaab/Trabajo-Practico-1-de-Objetos
/Ejercicio4y5.py
1,206
4.15625
4
def farenheitACelscius(farenheit): """Recibe: farenheit: <float> Devuelve los grados convertidos a celscius """ celscius = (farenheit - 32) * 5/9 return round(celscius,2) def celsciusAFarenheit(celscius): """Recibe: celscius: <float> Devuelve los grados convertidos a farenheit """ farenheit = (9/5 * celscius) + 32 return round(farenheit,2) def tablaFarenaCel(): """Imprime una tabla de conversion de grados Farenheit a Celscius""" f = 0 while f <= 120: print(str(f)," |", str(farenheitACelscius(f))) f += 10 opcion = int(input("""Ingrese un numero según lo que desee: 1.Pasar grados farenheit a Celscius 2.Pasar grados Celscius a Farenheit: 3.Mostrar una tabla de conversión de Farenheit a Celscius de 10° en 10°: """)) if opcion == 1: far = float(input("Ingrese los grados Farenheit que desea convertir: ")) print(far,"° F equivalen a",farenheitACelscius(far),"° C") if opcion == 2: cel = float(input("Ingrese los grados Celsius que desea convertir: ")) print(cel,"° C equivalen a",celsciusAFarenheit(cel),"° F") if opcion == 3: tablaFarenaCel()
false
e80ecf8147aa96defa52c36d295255ae024fe4bb
aabhishek-chaurasia-au17/python_practice
/DSA/Arry/find_largest-arry.py
350
4.4375
4
""" Python Program to find largest element in an array Input : arr[] = {10, 20, 4} Output : 20 Input : arr[] = {20, 10, 20, 4, 100} Output : 100 """ def largest_arry(arr,a): max = 0 for i in range(1, a): if arr[i] > max: max = arr[i] return max arr = [20, 10, 20, 4, 100] a = len(arr) print(largest_arry(arr,a))
true
98f8d9f1ead1c68e3ba5fa9a348c52f4fa8e4b5c
aabhishek-chaurasia-au17/python_practice
/BasicQus/2list_odd_even.py
563
4.15625
4
""" Exercise 10: Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list. list1 = [10, 20, 23, 11, 17] list 2 = [13, 43, 24, 36, 12] result List is [23, 11, 17, 24, 36, 12] """ def add_odd(a, b): list3 = [] for i in a: if i % 2 == 1: list3.append(i) for j in b: if j % 2 == 1: list3.append(j) return list3 list1 = [10, 20, 23, 11, 17] list2 = [13, 43, 24, 36, 12] print(add_odd(list1,list2))
true
72e08bce6645ee47dc778956138546d8643ec53c
aabhishek-chaurasia-au17/python_practice
/DSA/sorting/merge_sort.py
615
4.15625
4
# Merge Sort """ Given 2 arrays sorted array A and B. we need to merge then and get sorted array C. A =[1,4,6,7,8,9] B =[3,5,14,18] C =[] """ def Merge2sortarray(A,B): n = len(A) m = len(B) p1 = 0 p2 = 0 c = list() while p1 < n and p2 < m: if A[p1] < B[p2]: c.append(A[p1]) p1 += 1 else: c.append(B[p2]) p2+=1 while p1 < n: c.append(A[p1]) p1 += 1 while p2 < m: c.append(B[p2]) p2 +=1 return c A =[1,4,6,7,8,9] B =[3,5,14,18] C =[] print(Merge2sortarray(A,B))
false
3491f1405e6b89f1b4b71b0fb72a40e4302012f5
aabhishek-chaurasia-au17/python_practice
/DSA/Arry/array_rotation.py
656
4.1875
4
# Python Program for Reversal algorithm for array rotation """ Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] """ def reversal(arr, d, start, end): while(start < end): temp = arr[start] arr[start] = arr[end] arr[end] = temp start += 1 end = end -1 def leftrotat(arr,d): n = len(arr) reversal(arr,0, d-1) reversal(arr,d, n-1) reversal(arr,0, n-1) def printarry(arr): for i in range(0, len(arr)): print (arr[i]) if __name__ == "__main__": arr = [1, 2, 3, 4, 5, 6, 7] reversal(arr, 2) print(printarry(arr))
false
6b3b52341e769bdac60fe162adfcbb1a638ee1fe
aabhishek-chaurasia-au17/python_practice
/BasicQus/list_divisible.py
306
4.15625
4
""" Given a list of numbers, Iterate it and print only those numbers which are divisible of 5 """ # Given list is [10, 20, 33, 46, 55] # Divisible of 5 in a list # 10 # 20 # 55 def divisible(a): for i in a: if i % 5 == 0: print(i) lists = [10, 20, 33, 46, 55] divisible(lists)
false
72e954ed2d9b45b96a2d2fc6c79c7d27987dcdc4
aabhishek-chaurasia-au17/python_practice
/DSA/Recursion/factorial.py
288
4.28125
4
# finding the factorial of a number using with recusion. def factorial(n): """ factorial n will find the factorial of a no n. """ if n ==1: return 1 fact = n* factorial(n-1) return fact if __name__=="__main__": print(factorial(5))
true
3aecf27e79810c61c89fe79b040276198be7d38d
kira-Developer/python
/056_Function_And_Return.py
701
4.125
4
# ------------------------- # -- Function And Return -- # ------------------------- # [1] A Function is A Reusable Block Of Code Do A Task # [2] A Function Run When You Call It # [3] A Function Accept Element To Deal With Called [Parameters] # [4] A Function Can Do The Task Without Returning Data # [5] A Function Can Return Data After Job is Finished # [6] A Function Create To Prevent DRY # [7] A Function Accept Elements When You Call It Called [Arguments] # [8] There's A Built-In Functions and User Defined Functions # [9] A Function Is For All Team and All Apps # ---------------------------------------- def function_name() : print('hello python from inside function') function_name()
true
1b1c5fbc5a3e8b8efd64ba9c2ef234721efca995
kira-Developer/python
/082_Generators.py
784
4.46875
4
# ---------------- # -- Generators -- # ---------------- # [1] Generator is a Function With "yield" Keyword Instead of "return" # [2] It Support Iteration and Return Generator Iterator By Calling "yield" # [3] Generator Function Can Have one or More "yield" # [4] By Using next() It Resume From Where It Called "yield" Not From Begining # [5] When Called, Its Not Start Automatically, Its Only Give You The Control # ----------------------------------------------------------------- def mygenerator(): yield 1 yield 2 yield 3 yield 4 function = mygenerator() print(next(function)) print('hello from python') print(next(function)) print(next(function)) print('hello from python') print(next(function)) print('#' * 50) for number in mygenerator() : print(number)
true
39143abe2be1e6985c96bd220dfcf2d4f46d34b2
kira-Developer/python
/108_OOP_Part_6_Class_Methods_and_Static_Methods.py
2,108
4.1875
4
# ------------------------------------------------------------------- # -- Object Oriented Programming => Class Methods & Static Methods -- # ------------------------------------------------------------------- # Class Methods: # - Marked With @classmethod Decorator To Flag It As Class Method # - It Take Cls Parameter Not Self To Point To The Class not The Instance # - It Doesn't Require Creation of a Class Instance # - Used When You Want To Do Something With The Class Itself # Static Methods: # - It Takes No Parameters # - Its Bound To The Class Not Instance # - Used When Doing Something Doesnt Have Access To Object Or Class But Related To Class # ----------------------------------------------------------- class member : not_allowed = ['hell' , 'shit' ,'baloot'] users_num = 0 @classmethod def show_user_count(cls): print(f'we have {cls.users_num} users in our system') @staticmethod def say_hello(): print('hello from static method') def __init__(self, first_name, middle_name, last_name, gender): self.fname = first_name self.mname = middle_name self.lname = last_name self.gender = gender member.users_num += 1 # member.users_num = member.users_num + 1 def full_name(self): if self.fname in member.not_allowed : raise ValueError('name not allowed') else : return f'{self.fname} {self.mname} {self.lname}' def name_with_title(self): if self.gender == 'male': return f'hello mr {self.fname}' elif self.gender == 'female': return f'hello miss {self.fanme}' else: return f'hello {self.fname}' def get_all_info(self): return f'{self.name_with_title()}, your full name is : {self.full_name()}' def delete_user(self): member.users_num -= 1 return f'user {self.fname} deleted' member_one = member('abdullh', 'bander', 'alosami', 'male') print(member.users_num) print(member_one.delete_user()) print(member.users_num) print('#' * 50) member.show_user_count() member.say_hello()
true
8c66ea957d4fcd74b95f49ea02d4584950e27ba3
kira-Developer/python
/092_Exceptions_Handling_Advanced_Example.py
832
4.21875
4
# ----------------------------------- # -- Exceptions Handling -- # -- Try | Except | Else | Finally -- # -- Advanced Example -- # ----------------------------------- the_file = None the_tries = 3 while the_tries > 0 : try: print('enter the file name absolute path to open') print(f'you have {the_tries} tries left') print(r'example : C:\Users\kira\Desktop\python') file_name = input('file name => :').strip() the_file = open(file_name) print(the_file.read()) break except FileNotFoundError : print('file not found please be sure the name is valid') the_tries -= 1 finally: if the_file is not None : the_file.close() print('file close') else : print('all tries is done')
true
7a508af8d2298f61b77cb8a00a787780b22fad51
kira-Developer/python
/073_Built_In_Functions_Part_5_Filter.py
1,003
4.5
4
# ---------------------------------- # -- Built In Functions => Filter -- # ---------------------------------- # [1] Filter Take A Function + Iterator # [2] Filter Run A Function On Every Element # [3] The Function Can Be Pre-Defined Function or Lambda Function # [4] Filter Out All Elements For Which The Function Return True # [5] The Function Need To Return Boolean Value # --------------------------------------------------------------- # Example 1 def checkNumber(num) : return num < 10 mynumbers = [1 , 3 , 5 , 21 , 32 ,10] myresult = filter(checkNumber , mynumbers) for number in myresult : print(number) print('#' * 50) # Example 2 def checkName(name): return name.startswith('k') myNames = ['abdullh' , 'kira' , 'ksa' , 'bander'] myNameResult = filter(checkName , myNames) for name in myNameResult : print(name) print("#" * 50) myNames = ['abdullh' , 'kira' , 'ksa' , 'bander'] for p in filter(lambda name : name.startswith('a') , myNames): print(p)
true
84ef5d9ac0264a3258cdb742b0415195589a78b0
Kohdz/Algorithms
/Elements/Arrays/0_MasterList.py
1,756
4.3125
4
# 1. Write a function to sort even/odd number; put even numbers first and odd numbers at the ends # what is the complexity # A = [1, 2, 3, 4, 5] #[2, 4, 1, 3, 5] # ---------------------------------------------------------------------------------------------------------- # 2. Write a program that takes an array A and an index i into A, and rearranges the elements such that # all elements less than A[i] (the "pivot") appears first, followed by elements equal to the pivot, # followed by elements greater than the pivot. # what is the complexity # ---------------------------------------------------------------------------------------------------------- # 3. Write a program which takes as input an array of digits encoding a non-negative decimal interger D and # updates the array to represent the integer D + 1. For example, if the input is <1, 2, 9> then you should # update the array to <1, 3, 0>. Your algorithm should work even if it is implemented in a language that has # finite-precision arithmetic # what is the complexity # A = [1, 2, 9] #[1, 3, 0] # ---------------------------------------------------------------------------------------------------------- # 4. Write a program that takes two arrays representing integers and returns an integer representing their product # For example since 193707721 x - 761838257287 = -147573952589676412927, if the inputs are < 1, 9, 3, 7, 0, 7, 7, 2, 1 > # and < -7, 6, 1, 8, 3, 8, 2, 5, 7, 2, 8, 7 > , your function should return # < -1, 4, 7, 5, 7, 3, 9, 5, 2, 5, 8, 9, 6, 7, 6, 4, 1, 2, 9, 2, 7 >. # num1 = [1, 9, 3, 7, 0, 7, 7, 2, 1] # num2 = [-7, 6, 1, 8, 3, 8, 2, 5, 7, 2, 8, 7] # ----------------------------------------------------------------------------------------------------------
true
0ef50532f37b94bf08a9f623d75be7fa8077ecb9
Kohdz/Algorithms
/zEtc/AmazonOA/search2DMatrix.py
711
4.125
4
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from top to bottom. def searchMatrix(matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m = len(matrix) if m == 0: return False n = len(matrix[0]) if n == 0: return False y = m-1 x = 0 while x < n and y >= 0: if matrix[y][x] == target: return True elif matrix[y][x] < target: x += 1 else: y -= 1 return False
true
587a4da5f181c0c031fa112c040b83a5721a4443
Kohdz/Algorithms
/LeetCode/easy/29_balBinTree.py
968
4.21875
4
# https://leetcode.com/problems/balanced-binary-tree/ # Given a binary tree, determine if it is height-balanced. # For this problem, a height-balanced binary tree is defined as: # a binary tree in which the left and right subtrees of every node differ in height # by no more than 1. # Example 1: # Given the following tree [3,9,20,null,null,15,7]: # 3 # / \ # 9 20 # / \ # 15 7 # Return true. # Example 2: # Given the following tree [1,2,2,3,3,null,null,4,4]: # 1 # / \ # 2 2 # / \ # 3 3 # / \ # 4 4 # Return false. def isBalanced(root): def get_height(root): if root is None: return 0 left_height, right_height = get_height( root.left), get_height(root.right) if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 return (get_height(root) >= 0)
true
810ac02fe7ecde24a15f3697cd924868f0359be4
Kohdz/Algorithms
/Elements/graphs/01_searchMaze.py
1,481
4.15625
4
# run a DFS starting from the vertex corresponding to the entrance. # if at some point, we discover the exit vertex in the DFS, then there # exists a path from the entrance to the exit. # If we implement recursive DFS then the path would consist of all # the vertices in the call stack corresponding to previous recursive calls # to the DFS routine # we wont use BFS beacuse it does not call for shortest path # also BFS is more complicated to code import collections WHITE, BLACK = range(2) Coordinate = collections.namedtuple('Coordinate', ('x', 'y')) def search_maze(maze, s, e): # perform a DFS to find a feasible path def search_maze_helper(cur): # checks cur is within maze and is a white pixel if not (0 <= cur.x < len(maze) and 0 <= cur.y < len(maze[cur.x]) and maze[cur.x][cur.y] == WHITE): return False path.append(cur) maze[cur.x][cur.y] = BLACK if cur == e: return True if any( map(search_maze_helper, ((Coordinate( cur.x - 1, cur.y), Coordinate(cur.x + 1, cur.y), Coordinate( cur.x, cur.y - 1), Coordinate(cur.x, cur.y + 1))))): return True #cannot find a path. remove the entry added in path.append(cur) del path[-1] return False path = [] if not search_maze_helper(s): return [] # No path between s and e return path
true
8f64b9977e3070eba00cd0a579f1c8b827b304fa
Kohdz/Algorithms
/LeetCode/easy/48_powerOfTwo.py
571
4.1875
4
# https://leetcode.com/problems/power-of-two/ # Given an integer, write a function to determine if it is a power of two. # Example 1: # Input: 1 # Output: true # Explanation: 2^0 = 1 # Example 2: # Input: 16 # Output: true # Explanation: 2^4 = 16 # Example 3: # Input: 218 # Output: false def isPowerOfTwo(n): return n > 0 and (n & (n-1) == 0) n = 4 print(isPowerOfTwo(n)) def isPowerOfTwoII(n): if n < 1: return False powerOfTwo = 1 while powerOfTwo < n: powerOfTwo *= 2 return powerOfTwo == n print(isPowerOfTwoII(n))
true
9bab40828c2c9d2a1757a5bf93d1db7f128393d1
Kohdz/Algorithms
/LeetCode/easy/56_reverseString.py
877
4.15625
4
# https://leetcode.com/problems/reverse-string/ # Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with # O(1) extra memory. # You may assume all the characters consist of printable ascii characters. # Example 1: # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Example 2: # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"] def reverseString(s): sLen = len(s) - 1 for i in range(len(s)//2): tempy = s[i] tempy2 = s[sLen] s[i] = tempy2 s[sLen] = tempy sLen -= 1 return(s) s = ["h", "e", "l", "l", "o"] print(reverseString(s)) def reverseStringHer(s): for i in range(len(s)//2): s[i], s[-i-1] = s[-i-1], s[i]
true
45e4a9d0432d05820f6ca437acfc146e573b856b
aleszreis/100-days-of-code-python
/Miles to KM converter/main.py
668
4.1875
4
from tkinter import * # Janela window = Tk() window.title("Miles to KM converter") window.config(padx=20, pady=20) # Entrada entry = Entry(width=7) entry.grid(column=1, row=0) # Linha 1: linha1 = Label(text="Miles") linha1.grid(column=2, row=0) # Linha 2 label1 = Label(text="is equal to") label1.grid(column=0, row=1) label2 = Label(text=0) label2.grid(column=1, row=1) label3 = Label(text="km") label3.grid(column=2, row=1) # Botão def calculate(): return label2.config(text=float(entry.get()) * 1.609) button = Button(text="Calculate!", command=calculate) button.grid(column=1, row=2) # Fim da janela window.mainloop()
false
ac21e494e6ce187458746fc45058c7871e6bee5e
emurph1/dailyCodingProb
/prob2Uber.py
1,352
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 8 13:22:58 2019 This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6] @author: murph """ def productArray(arr, n): # Allocate memory for the product array prod = [1 for i in range(n)] # Base case if n == 1: return arr[0] else: i, temp = 1, 1 # In this loop, temp variable contains product of # elements on left side excluding arr[i] for i in range(n): prod[i] = temp temp *= arr[i] # Initialize temp to 1 for product on right side temp = 1 # In this loop, temp variable contains product of # elements on right side excluding arr[i] # backwards from the last item for i in range(n - 1, -1, -1): prod[i] *= temp temp *= arr[i] # Print the constructed prod array return prod # Driver Code arr = [1, 2, 3, 4, 5] n = len(arr) print(productArray(arr, n))
true
4e1c922d9907750f212480c7fce210c86b0bff53
SubhamPanigrahi/Python_Programming
/recursion(reverse.num).py
203
4.3125
4
# reversing a number using recursion def reverse(x): if x < 10: print(x,end="") else: print(x%10,end="") reverse(x//10) a = int(input("Enter any number: ")) reverse(a)
true
15fde4748c7372b8e2edfbd7aafaddd6891222dc
SubhamPanigrahi/Python_Programming
/average_odd_even.py
544
4.25
4
# checking the aveage of sum of odd and even numbers even = 0 odd = 0 count_even = 0 count_odd = 0 while True: x = int(input("enter any number(press -1 to exit): ")) if x > 0: if x%2==0: # includes all even numbers even += x count_even +=1 else: # includes all odd numbers odd += x count_odd +=1 elif x==-1: print("The average of even numbers is: ",even/count_even) print("the average of odd numbers is: ", odd/count_odd) break
true
f89be6caadc75707b4bf7ae32425165f5aac4067
SubhamPanigrahi/Python_Programming
/divisible_by_3_or_6.py
205
4.1875
4
# first 50 numbers except those which are divisible by 3 or 6 x = [] for i in range(1,51): if i%3==0 or i%6==0: x.append(i) print("The numbers divisible by 3 or 6 in first 50 numbers are: ",x)
true
2c8c0063712ce0afab0ad7a343e7fd16193aac66
SubhamPanigrahi/Python_Programming
/palindrome.py
337
4.28125
4
# palindrome is something in which the word remains the same whether read from starting or from end def palindrome(str_1): rev = str_1[::-1] if str_1==rev: # checking if palindrome print("This is a palindrome") else: print("This is not a palindrome") x = str(input("enter anything: ")) (palindrome(x))
true
d0dc6e29ab072dfcce4e7f5d2fa78eb8baebb26c
Jadetabony/random_python
/anagram_finder.py
950
4.21875
4
"""Function anagram take a list of words, breaks them down into a list of a list of the individual characters. Then, each list within the new list is sorted. Then list comprehension is used to create a list of indeces in for which there are duplicates in the sorted list. Then I create one last list in which I take the values of original words list that correspond to the indeces in my indx list.""" input_list = ['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star'] def anagram1(words): letters =[] for item in words: char = [] for c in item: char.append(c) letters.append(char) print letters sortd = [] for lst in letters: lst.sort() sortd.append(lst) print sortd indx=[i for i, x in enumerate(sortd) if sortd.count(x) > 1] print indx final = [] for i in indx: final.append(words[i]) print "Final list:", final anagram1(input_list)
true
cd2d6d60b785f45d12e3b4d89a092af0444617eb
sripathyfication/bugfree-octo-dangerzone
/techie-delight/practice/height_trees.py
1,542
4.25
4
#/usr/bin/python ''' Recursive and iterative solution ''' class Node: def __init__(self,val): self.val = val self.left = None self.right = None class Queue: def __init__(self): self.list_ = [] def is_empty(self): ret = False if not self.list_: ret = True return ret def size(self): return len(self.list_) def enqueue(self,val): self.list_.insert(0,val) def dequeue(self): return self.list_.pop() def print_tree(root): if not root: return print_tree(root.left) print root.val print_tree(root.right) def height_recursive(root): if root is None: return 0 return (max(height_recursive(root.left),height_recursive(root.right)) +1) def height_iterative(tree): if not tree: return 0 height = 0 queue = Queue() queue.enqueue(tree) while queue.is_empty() is not True: size = queue.size() while size: node = queue.dequeue() if node.left is not None: queue.enqueue(node.left) if node.right is not None: queue.enqueue(node.right) size -= 1 height +=1 return height if __name__ == '__main__': tree = Node(5) tree.left = Node(3) tree.right = Node(7) tree.left.left = Node(2) tree.left.right = Node(4) tree.right.left = Node(6) tree.right.right = Node(8) print height_recursive(tree) print height_iterative(tree)
true
5e4ac89bf8fd50c84cabaa3b0c1975c63f00f9ae
sripathyfication/bugfree-octo-dangerzone
/techie-delight/linked-list/python/link_list.py
2,221
4.1875
4
#/usr/bin/python # python linked list implementation # todo: add support for sorted insert class list_node: def __init__(self,val): self.val = val self.next = None class singly_linked_list: def __init__(self): self.head = None def get_head(self): return self.head def set_head(self, node): self.head = node def add(self,val): print " .. adding node " + str(val) if self.head is None: self.head = list_node(val) else: self._add_node(self.head,val) def _add_node(self,node, val): if node is None: return else: prev = None while node is not None: prev = node node = node.next prev.next = list_node(val) def remove(self,val): print " .. removing node " + str(val) if self.head is None: return else: self._remove_node(self.head,None,val) def _remove_node(self, node, prev ,val): if node is None: return else: if node.val is val: if node is self.head: self.head = node.next else: if prev is not None: prev.next = node.next node = None else: self._remove_node(node.next,node,val) return def print_list(self): print "singly_linked_list " if self.head is None: print " -- . -- " else: self._print_list(self.head) print "---- . ---- " def _print_list(self,node): if node is None: return else: print str(node.val) + " --> " self._print_list(node.next) # Test driver if __name__ == '__main__': list_ = singly_linked_list() list_.add(1) list_.add(2) list_.add(3) list_.add(4) list_.add(5) list_.print_list() list_.remove(2) list_.print_list() list_.add(2) list_.remove(1) list_.print_list() list_.add(1) list_.print_list() list_.remove(1) list_.print_list()
true
bf846f7a1a3fe7a2bbf7a77a0121847f9ff960fa
sripathyfication/bugfree-octo-dangerzone
/techie-delight/practice/print_all_nodes.py
1,153
4.40625
4
#/usr/bin/python ''' Print all paths from Root to leaf node: -------------------------------------- 1.Do an inorder traversal and keep pushing into a list until a leaf is not encountered. 2.If a leaf is encountered, print the list 3.Recurse over left subtree 4.Recurse over right subtree ''' class Node: def __init__(self,val): self.val = val self.left = None self.right = None def is_leaf(node): if node is None: return False else: if node and node.left is None and node.right is None: return True def print_all_paths(tree,paths): if tree is None: return paths.append(tree.val) if (is_leaf(tree)): print paths print_all_paths(tree.left,paths) print_all_paths(tree.right,paths) if __name__ == '__main__': paths = [] tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.right.left = Node(6) tree.right.right = Node(7) tree.right.left.left = Node(8) tree.right.left.right = Node(9) print_all_paths(tree,paths)
true
3da5c111bcc8d83392f294ddb3e643d6145dd18e
sripathyfication/bugfree-octo-dangerzone
/python/leetcode/fib.py
402
4.15625
4
#!/usr/bin/env python # Fibonacci sequence calculator: # Given a number find the nth in the sequence # Author: Sripathy Ramaswamy # 07/25/2016 import sys def fib(n): if (n <= 1): return n else: return fib (n -1 ) + fib(n -2 ) def main(): n = sys.argv[1] print "Input: %s" % n y = fib(int(n)) print "Fibonacci number is: %d " % y if __name__ == '__main__': main()
false
0e08d6a73918eec7b2afb746fc33dcf8f9f310fe
sripathyfication/bugfree-octo-dangerzone
/techie-delight/array/once.py
815
4.21875
4
#/usr/bin/python # there is a list in which elements occur 3 times, except one element. # find that element that occurs only once. def qsort(array): if not array: return array first = array[0] lesser = filter(lambda x: x < first, array[1:]) greater = filter(lambda x: x >= first, array[1:]) return qsort(lesser) + [first] + qsort(greater) def find_all_elements(array): array = qsort(array) print array for i in range(0, len(array)-1): if array[i] == array[i+1]: prev = None first = 0 else: if first == 1: return prev else: first = 1 prev = array[i] if __name__ == '__main__': array = [1,1,1,12,11,11,11] print array print find_all_elements(array)
true
b31f0054b500bb12543dbf1a56f3378e4005f146
adrianrocamora/kng
/lc/py/226.py
818
4.125
4
# Invert a binary tree. # Left substree is old right subtree inverted. # Right subtree is old left subtree inverted. # Time - O(n) # Space - O(n) class Node: def __init__(self, val): self.val = val self.left = self.right = None def invert_tree(root): if not root: return #return None #root.left, root.right = invert_tree(root.right), invert_tree(root.left) # OR: invert_tree(root.left) invert_tree(root.right) temp = root.left root.left = root.right root.right = temp #return root return # inorder traversal def print_tree(root): if not root: return print_tree(root.left) print(root.val) print_tree(root.right) n = Node(2) n.left = Node(1) n.right = Node(4) n.right.left = Node(3) n.right.right = Node(5) print_tree(n) print() invert_tree(n) print_tree(n)
true
60e7e2b8504ed8ec3eabca44e9d8f46b2667952c
yangdaweihit/haohaolearn
/python/practice/p023_oop.py
681
4.15625
4
# Child 继承自 Parent # Child 要实现对 Parent 的 _familyname 的继承 # 需要在 Child 初始化函数中调用 Parent 的初始化函数 class Parent: def __init__(self): self._familyname = str() pass def read(self, str_name): self._familyname = str_name def getname(self): return self._familyname class Child(Parent): def __init__(self): # 关键的一步 super().__init__() print(self._familyname) pass def modifyname(self): self._familyname += "_self" # a = Child() # a.read("Yang") # a.modifyname() # print(a.getname()) a = dict() a['a'] = 1 a['b'] = 2 a['c'] = 3
false
f97a7ccf9cd4771476b64aad3983889d9aa8a503
mhinojosa24/Jack-Sparrow-Tweet-Generator
/stochastic_sampling.py
1,475
4.15625
4
import random, sys # from class_methods.histogram import * # from histogram import * ''' <-- Functions --> randomized_word() - takes a 'source_text' argument. - stores a text file in a listogram - returns a word based on its frequency test_word() - calculates the total amount of each word based on it's frequency ''' list = 'one fish two fish red fish blue fish' def randomized_word(histogram): total_count = 0 #find what this value is chance = 0.0 #'chance' is the probability of getting a particular word # listogram = list_of_list(histogram) #list of list of unique words and its frequency random_num = random.random() #random number from 0 & 1 hist = histogram.items() # print(hist) #loops through listogram & add the total count of each word for key, value in histogram.items(): # print("value", value[1]) total_count += value for key, value in histogram.items(): chance += value / total_count #divide the words frequency with total count if chance >= random_num: #check the chance of getting a particular based on their probability return key def test_word(): source = sys.argv[1] test = {} for i in range(10000): random_word = randomized_word(source) if random_word not in test: test[random_word] = 1 else: test[random_word] += 1 return test if __name__ == "__main__": print(test_word())
true
db0382e0521e39b6fb1524c16e1ef2489370250e
Beva-Lwash/Python-hardway
/ex3.py
588
4.375
4
print("I will now count my chickens:") print ("Hens", 25.0+30.0/6.0) print("Roosters",100.0-25.0*3.0%4.0) print("Now i will count the eggs:") #Will show the results print(3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0) print("Is is true that 3.0+2.0<5.0-7.0?") #Compare and determine if its false print(3.0+2.0<5.0-7.0) print("What is 3.0+2.0?",3.0+2.0) print("What is 5.0-7.0?",5.0-7.0) print("Oh, that's why it's False.") print("How about some more.") #Uses other comparison print("Is it greater?",5.0>-2.0) print("Is it greater or equal?", 5.0>=-2.0) print("Is it less or equal?",5.0<=-2.0)
true
97d5ad6e1ef50d71ebe2b55cf6c5a6694269aa04
Interloper2448/BCGPortfolio
/Python_Files/murach/exercises/ch02/rectangle.py
477
4.15625
4
#!/usr/bin/env python3 # display a welcome message print("The Rectangle Program") print() # get input from the user input_length = float(input("Enter the Length:\t\t")) input_width = float(input("Enter the Width:\t\t")) # calculate miles per gallon area = input_length * input_width peri = input_length * 2 + input_width * 2 # format and display the result print("Area:\t\t\t\t" + str(area)) print("Perimiter:\t\t\t" + str(peri)) print("\n\rThanks for using the program!")
true
4d6436a61041b56329e1dd269b9ab4b6c7f03e63
Interloper2448/BCGPortfolio
/Python_Files/murach/exercises/ch03/mpg.py
1,226
4.375
4
#!/usr/bin/env python3 while True: # display a welcome message print("The Miles Per Gallon application") print() # get input from the user miles_driven = float(input("Enter miles driven:\t\t\t")) gallons_used = float(input("Enter gallons of gas used:\t\t")) gallon_price = float(input("Enter cost per gallon:\t\t\t")) if miles_driven <= 0: print("Miles driven must be greater than zero. Please try again.") elif gallons_used <= 0: print("Gallons used must be greater than zero. Please try again.") elif gallon_price <= 0: print("The price of a gallon of gas must be greater than 0") else: # calculate and display miles per gallon mpg = round((miles_driven / gallons_used), 2) print("\nMiles Per Gallon:\t\t\t", mpg, sep="") # Total Gas cost gas_cost = round(gallons_used * gallon_price, 1) print("Cost of used gas:\t\t\t", gas_cost, sep="") # Cost per mile mile_cost = round(gas_cost/miles_driven, 1) print("The total cost per mile:\t\t", mile_cost, sep="") inp = input("\n\rGet entries for another trip [y/n]?\t").lower() if inp == "n": break print() print("Bye")
true
f60b8ffc3a8b682c7beea976fb058db9ff6d7bd6
ashenoy2004/mycode
/lab_input/iptaker03.py
360
4.125
4
#!/usr/bin/env python3 user_input = input("Enter your Name:") user_day_of_week = input("Enter Day of Week: ") ## the line below creates a single string that is passed to print() # print("You told me the IPv4 address is:" + user_input) ## print() can be given a series of objects separated by a comma print (f"Hello,{ user_input}! Happy {user_day_of_week}!")
true
7ef7017145a6c4f2a25e5fe94ee86a798660acbe
Junhojuno/TIL-v2
/argparse/01_argparse_positional_arguments.py
529
4.28125
4
import argparse # without '--' or '-', the order of arguments are important. parser = argparse.ArgumentParser() parser.add_argument('echo', help="echo the string you use here") parser.add_argument('square', type=int, help="display a square of a given number") args = parser.parse_args() print(args.echo) print(args.square ** 2) """ $ python 01_argparse.py what 2 >>> what 4 $ python 01_argparse.py 2 what >>> usage: 01_argparse.py [-h] echo square 01_argparse.py: error: argument square: invalid int value: 'what' """
true
470996830973cb738b055eeff73294f99242d55d
MunityVR/Game
/main.py
1,255
4.125
4
# Spaces minsp = 0 maxsp = 500 # Admin's configuration print("Hey Admin!") sw = str(input("Make up a word : ")) guesses = float(input("How many guesses should the user have : ")) h = str(input("Do you want to give the user a hint? y/n : ")) guess = '' gc = 0 # Admin's hint if h == 'y': hint = str(input("What hint do you wanna give to the user, when the user type down \'Hint\' : ")) elif h == 'n': hint = str("I didn\'t give you a hint.") # Spaces - So user can't see what the admin did. while minsp != maxsp: print("") minsp = minsp + 1 print("Hey User!") # The game starts here. while guess != sw or gc != guesses: guess = str(input("Enter a guess : ")) gc = gc + 1 # Events during/end the game. if guess == sw: print("You win!") exit() elif guess == 'Np =>': print("You know something that nobody else knows!") gc = gc - 1 elif guess == 'Amazing Grace': print("Alan Jackson!") gc = gc - 1 elif guess == 'Hint' or guess == 'hint': print("Admin > " + str(hint)) elif guess == 'GCount' or guess == 'gcount': print(str(gc) + "/" + str(guesses)) gc = gc - 1 elif gc == guesses: print("You lose!") exit()
true
5c6f74c1e7badaefe3ffca00515e262497c1f4f6
Tuchev/Python-Basics---september---2020
/07.Exams/Programming Basics Online Exam - 15 and 16 June 2019/04. Cinema.py
699
4.15625
4
capacity = int(input()) command = input() ticket_price = 5 people_count = 0 rest_place = 0 group_sum = 0 total_sum = 0 is_full = False while command != "Movie time!": people_count += int(command) rest_place = capacity - people_count group_sum = int(command) * ticket_price if int(command) % 3 == 0: group_sum -= 5 total_sum += group_sum if people_count > capacity: total_sum -= group_sum is_full = True break command = input() if is_full: print("The cinema is full.") elif command == "Movie time!": print(f"There are {rest_place} seats left in the cinema.") print(f"Cinema income - {total_sum} lv.")
true
63fdcd6cd6456f2215626b551dfbe5590aa4f08f
MakeSchool-17/twitter-bot-python-lesliekimm
/1_lets_build_a_twitter_bot/anagram_generator.py
869
4.25
4
import random # AnagramGenerator class takes a word from the user and scrambles the letters class AnagramGenerator: def __init__(self): self.word = None # gets a word from the user def get_word(self): self.word = input('Please enter a word: ') return # shuffles the letters of the input word def create_anagram(self): # shuffle the letters and put into array shuffled_anagram = random.sample(self.word, len(self.word)) # initialize empty string anagram = '' # go through shuffled_anagram array and concatenate all letters for i in range(0, len(self.word)): anagram += shuffled_anagram[i] return anagram if __name__ == '__main__': my_anagram = AnagramGenerator() my_anagram.get_word() output = my_anagram.create_anagram() print(output)
true
54f9ed72f46d122f6c65b3c0673fbf428b1075ee
ngcthanh2903/mypythoncode-
/repos/untitled3.py
1,563
4.21875
4
import numpy as np import matplotlib.pyplot as plt def derivative(f,a,method='central',h=0.01): '''Compute the difference formula for f'(a) with step size h. Parameters ---------- f : function Vectorized function of one variable a : number Compute derivative at x = a method : string Difference formula: 'forward', 'backward' or 'central' h : number Step size in difference formula Returns ------- float Difference formula: central: f(a+h) - f(a-h))/2h forward: f(a+h) - f(a))/h backward: f(a) - f(a-h))/h ''' return a*2 if method == 'central': return (f(a + h) - f(a - h))/(2*h) elif method == 'forward': return (f(a + h) - f(a))/h elif method == 'backward': return (f(a) - f(a - h))/h else: raise ValueError("Method must be 'central', 'forward' or 'backward'.") x = np.linspace(0,6,100) f = lambda x: ((4*x**2 + 2*x + 1)/(x + 2*np.exp(x)))**x y = f(x) dydx = derivative(f,x) plt.figure(figsize=(12,5)) plt.plot(x,y,label='y=f(x)') plt.plot(x,dydx,label="Central Difference y=f'(x)") plt.legend() plt.grid(True) plt.show() x = np.linspace(0,5*np.pi,100) dydx = derivative(np.sin,x) dYdx = np.cos(x) plt.figure(figsize=(12,5)) plt.plot(x,dydx,'r.',label='Central Difference') plt.plot(x,dYdx,'b',label='True Value') plt.title('Central Difference Derivative of y = cos(x)') plt.legend(loc='best') plt.show()
true
2c66cce8390e3f8fcdb92dfa1ed6110dd498ea9d
LoadingScreen/algorithm_problem_solutions
/checkPerm/checkPermSort.py
639
4.15625
4
# Returns true iff s1 is a permutation of s2 def checkPermSort(s1, s2): if len(s1) != len(s2): print "S1 is NOT a permutation of S2." return False s1s, s2s = sorted(s1), sorted(s2) for i in range(0, len(s1)): if s1s[i] != s2s[i]: print "s1 is NOT a permutation of s2." return False print "s2 is a permutation of s1" return True # time complexity is O(nlogn) # space complexity is O(n) if __name__ == "__main__": while True: s1 = raw_input("Enter the first string.\n>> ") s2 = raw_input("Enter the second string.\n>> ") checkPermSort(s1,s2)
true
ed8d750cef1edc4ae2089cf3795613f0a53ef849
tgsher9329/dictionaries
/friend-counter.py
627
4.28125
4
ramit = { 'name': 'Ramit', 'email': 'ramit@gmail.com', 'interests': ['movies', 'tennis'], 'friends': [ { 'name': 'Jasmine', 'email': 'jasmine@yahoo.com', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': 'jan@hotmail.com', 'interests': ['movies', 'tv'] } ] } # -------- # write a function countFriends() that accepts a dictionary # as an argument and returns a new dictionary that includes a new key friends_count: def countFriends(dic): friends_count = { len(ramit['friends']) } return friends_count result = (countFriends(ramit)) print(result)
false
b12601991f9e9e810919b0372513bff4991bc7e4
gustavofette/SRE_training
/Mapping/phonebook.py
1,275
4.25
4
myPhoneBook = {"Alim": "453-213-4567", "Navean": "123-456-7890", "Gustavo": "987-654-1230", "Veronica": "555-555-1234" } def lookfor(): looking = input("Name: ") found = myPhoneBook.get(looking) if found == None: print("%s is not in the phonebook" % looking) else: print(f' {looking} phone is {myPhoneBook[looking]}') def addone(): nname = input("New Name: ") pphone = input("Phone: ") myPhoneBook[nname] = pphone def delone(): nname = input("New Name: ") if nname in myPhoneBook: del myPhoneBook[nname] else: print(f'{nname} not in the phonebook') while True: print ("My PhoneBook") print ("===============") print ("") print ("1- Look for a name") print ("2- Add a new name") print ("3- Del a name") print ("4- List all") print ("5- Quit") print ("") print ("What do you want to do: ") YourChoice = input() if YourChoice == "1": lookfor() elif YourChoice == "2": addone() elif YourChoice == "3": delone() elif YourChoice == "4": print(myPhoneBook) elif YourChoice == "5": print ("Bye Bye") break else: print("Stop kidding")
true
9ef833268eab9b956a3256472eab5f99739d210b
mnabu55/hyperskill
/Problems/Leap Year/task.py
461
4.28125
4
''' Write a program that checks if a year is leap. A year is considered leap if it is divisible by 4 and NOT divisible by 100, or if it is divisible by 400. So, 2000 is leap and 2100 isn't. Output either "Leap" or "Ordinary" depending on the input. Sample Input 1: 2100 Sample Output 1: Ordinary Sample Input 2: 2000 Sample Output 2: Leap ''' year = int(input()) print("Leap" if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else "Ordinary")
true
4559a948d474514bf1000cdac56c39b180083af5
alexeymanshin/Python
/simple_calculator.py
513
4.21875
4
what = input("Выберете операцию + ; - ; * ; / ?") a = float(input("введите первое число:")) b = float(input('введите второе число:')) if what == '+': c = a + b print(f'Результат {c}') elif what == '-': c = a - b print(f'Результат {c}') elif what == '*': c = a * b print(f'Результат {c}') elif what == '/': c = a / b print(f'Результат {c}') else: print('неверная операция')
false
7d92384fa1ed43ea666f5372deb1fca8a12f1526
Katuri31/Problem_solving_and_programming
/Python/Lab_model_questions/q_4/b.py
290
4.25
4
#Write a function unique to find all the unique elements of a list lst = ['rfd', 'rrfr', 'a', 'a', 'b'] def unique(lst): print("The unique elements in the list are: ") for element in lst: if lst.count(element) == 1: print("\t\t\t\t",element) unique(lst)
true
f82efff741649406321d647fb1d0ac02b9f2fa26
Katuri31/Problem_solving_and_programming
/Python/Lab_model_questions/q_12/q_12.py
334
4.1875
4
tup = () for i in range(3): rn = int(input("Enter the roll number: ")) nm = input("Enter name: ") mrks = int(input("Enter marks: ")) tup += ((rn,nm,mrks),) print(tup) print(tuple('TutorialAICSIP')) ##If in a tuple, no trailing commas are present, the entered element is split into the individual characters
true
05f060f40ffdd87008a8e54810d6472336904efc
danielwhomer/math-stuff
/number_persistence.py
553
4.125
4
import sys #https://en.wikipedia.org/wiki/Persistence_of_a_number #Calculates the number of steps it takes to reduce a number down to a single digit by multiplying its digits #For example when n = 39 #n = 3*9 #n = 2*7 #n = 1*4 #n = 4 #the current known most persistent number is 277777788888899 (11 steps) def persistence(number, steps): if len(str(number)) == 1: return "DONE" digits = [int(i) for i in str(number)] result = 1 for d in digits: result *= d print(result, steps) persistence(result, steps+1) persistence(sys.argv[1], 1)
true
d989d749da7b9b03cd0a931c5be747a8495fa884
ohentony/Aprendendo-python
/Coleções em python/Listas em python/ex009.py
461
4.375
4
# Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. # No final, mostre a matriz na tela, com a formatação correta. matriz = [[],[],[]] for linha in range (0,3): for coluna in range (0,3): matriz[linha].append(int(input(f'Digite um valor para [{linha},{coluna}]: '))) for linha in range (0,3): for coluna in range (0,3): print(f'[{matriz[linha][coluna]:^5}]', end='') print()
false
f5c89bf7ae4244a4425e03cc2282b6fffa591521
ohentony/Aprendendo-python
/Coleções em python/Listas em python/ex006.py
750
4.21875
4
# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo # deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta. expressão = str(input('Digite a expressão: ')).strip() validade = True aux = 0 # Indica a quantidade de parênteses que devem ser fechados if expressão.count( '(' ) == expressão.count( ')' ): for caractere in expressão: if caractere == ')' and aux == 0: validade = False break if caractere == '(': aux += 1 if caractere == ')': aux -= 1 else: validade = False if validade == False: print('Expressão inválida!') else: print('Expressão válida!')
false
bb1a8f70fab622574b10d3226d8bde77ea12548a
ohentony/Aprendendo-python
/Condições em python/ex009.py
721
4.15625
4
'''Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.''' num = int(input('Digite um número inteiro: ')) aux = int(input('Escolha uma das bases para conversão:\n[1] Converter para BINÁRIO\n[2] Converter para OCTAL\n[3] Converter para HEXADECIMAL\nSua opção: ')) if aux == 1: print('{} convertido para BINÁRIO é igual a {}'.format(num,bin(num)[2:])) elif aux == 2: print('{} convertido para OCTAL é igual a {}'.format(num,oct(num)[2:])) elif aux == 3: print('{} convertido para HEXADECIMAL é igual a {}'.format(num,hex(num)[2:])) else: print('Opção inválida')
false
60118e227cc9712c023c929d140a1436a5777e73
ohentony/Aprendendo-python
/Coleções em python/Tuplas em python/ex004.py
761
4.21875
4
""" Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares. """ numbers = (int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: '))) print(f'\n{numbers}') print(f'\nQuantidade de vezes que o número 9 apareceu: {numbers.count(9)}') if 3 in numbers: print(f'O número 3 apareceu primeiro na {numbers.index(3) + 1}ª posição') else: print('O número 3 não foi digitado') print('Números pares: ', end = '') for c in numbers: if c % 2 == 0: print(c, end = ' ') print('\n')
false
4506486b4cfe6df0a6d96235a14bbc3dcd7aa002
ohentony/Aprendendo-python
/Funções em python/ex007.py
725
4.28125
4
# Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o # primeiro que indique o número a calcular e outro chamado show, que será um valor # lógico (opcional) indicando se será mostrado ou não na tela o processo de # cálculo do fatorial. def fatorial(num, show=False): """ -> Calcula o fatorial de num. :param num : O valor a ser calculado. :param show: (Opcional) Mostrar ou não a conta. :return: O valor do fatorial de num. """ fat = 1 for c in range(num,0,-1): if show: print(f'{c} x ' if c > 1 else f'{c} = ',end='') fat *= c return fat #help(fatorial) n = int(input('Digite um número: ')) print(fatorial(n,True))
false
f2cb62cbd884c841f4c11934c6143dbe6b033818
kamieliz/Udemy_Python_Projects
/Lecture 5 - lists, dicts, sets, tuples/lecture_lists.py
1,536
4.53125
5
# What can you do with lists? # sort values in ascending and descending order sort(), sorted() # find values in the list, or details about the list len(), min(),max(),in,indexing, slicing, count() # insert or remove values from the list (including other lists) append(), insert(), extend(), remove(), pop() # grab sub-lists from the list to work with slicing, in-place, copying # iterate through and perform functions/checks on each list item for loops, while loops my_list = [15,6,7,8,35,12,14,4,10] my_str_list = ["comp sci","physics","elec engr","philosophy"] my_strs_list = ["art","econ"] print(f"Ints: {my_list}") print(f"Strings: {my_str_list}") print("Sorting...") my_list.sort() #method sorted_list = sorted(my_list) #function print(sorted_list) print(f"Sorted Ints: {my_list}") print("Finding info....") print("physics" in my_str_list) print(my_str_list.index("physics")) print(len(my_list)) print(len(my_str_list)) print(my_list[-1]) print(min(my_list)) print(max(my_list)) #print(dir(my_list)) shows all the builtin methods for lists print(my_list.count(15)) print("Add/remove...") #append() insert() extend() my_list.append(25) print(my_list) my_list.insert(4,25) print(my_list) #my_str_list.append(my_strs_list) #print(my_list) my_str_list.extend(my_strs_list) print(my_str_list) #pop(), remove() my_str_list.remove("comp sci") print(my_str_list) print(my_str_list.pop()) print(my_str_list) print("Sublists...") print(my_list[-1]) my_list[-1] = 1000 print(my_list) print(my_list[0:5]) for item in my_list: print(item)
true
28e76c0605b9b124586c489395be536f34f49233
Quintonamore/ProgrammingSolutions
/CCI/Chapter_1/1_4.py
701
4.21875
4
# CCI Chapter 1 Problem 4 # Pallindrome permutation, checks to see if the two given strings are the same forwards and backwards. # Value to count the only odd pairing available odd_pairing = 0 def find_other_letter(str): first_char = str[0] char_cntr = 1 for i in range(1, len(str)): if str[i] == first_char: char_cntr += 1 str = str.replace(first_char, '') if char_cntr % 2: return 0 elif len(str): find_other_letter(str) elif : return 1 word = input("Input the string to be tested") if find_other_letter(word): print(word + " is a palindrome permutation") else: print(word + " is not a palindrome permutation")
true
64bf2a053d5b860e3349d923f6b03022bb5b259a
Saikumar9704/20A91A0596_saikumar_CSEB
/primenumber.py
357
4.125
4
#given number is prime number or not num=int(input('enter a number')) if num>1: for i in range(2,num//2): if num%i == 0: print('%d is not a prime number' %num) break else: print('%d is a prime number' %num) else: print('%d is not a prime number') ''' expected output enter a number47 47 is a prime number '''
true
d11c7e479bec85f5ece8f3424770d78c97b0f9bc
CMS28/cms28.github.io
/CSCI125-002/practice/archive/whileloop.py
465
4.21875
4
# test on while loop go = input("Do you want to continue? yes or no ") ''' while go == "yes": print("I am in the while loop") go =input("still want to continue? yes or no") while True: print("I am in the while loop") go = input("if you don't want to continue, enter no ") if go=="no": break #break out of loop print("Ok. I am out of the loop") ''' while count < 0: print(count) count -=1
true
af5b7e16d5fe6b87363b775758541463ff8e758d
CMS28/cms28.github.io
/practice/Yeet/diamond.py
298
4.1875
4
for i in range(9): for j in range(9-i): print(" ", end="") for j in range(9-i,9+i+1): print("*", end="") print() for i in range(9,-1,-1): for j in range(9-i): print(" ", end="") for j in range(9-i,9+i+1): print("*", end="") print()
false
eca0890d6caea58b407572960463bc5fd83363c9
s-markov/geekbrains-python-level1
/les03/task03_01.py
729
4.15625
4
# Реализовать функцию, принимающую два числа # (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, # предусмотреть обработку ситуации деления на ноль. def division(a, b): try: return a / b except ZeroDivisionError: return dividend = float(input("введите делимое >>>")) divider = float(input("введите делитель >>>")) if division(dividend, divider) == None: print("Делитель не может быть равен 0") else: print("Частное = ", division(dividend, divider))
false
2c22aff234b09e43e807105fad0e1f73c7f489e0
jayesh-chavan-au7/Data-Structures-and-Algorithmic
/Dynamic-Programming/Fabonacci-no-best-optimized.py
221
4.125
4
n = int(input()) # O(1) space complexity = By using only previous two no. def Fibonacci(n): a,b = 0,1 for _ in range(n): a,b = b,a+b return a print('Fibonacci no of {} is : '.format(n), Fibonacci(n))
true
87456aad9595daf309a76db7a271a2ff1687cdc9
adriian12/Programacion
/Procedimental/ejercicios propuestos/ejercicio11.py
709
4.125
4
numero_uno = int(input("Introduce el primer numero: ")) numero_dos = int(input("Introduce el segundo numero: ")) numero_tres = int(input("Introduce el tercer numero: ")) print ("Numeros introducidos:", numero_uno, numero_dos, numero_tres) if (numero_uno + numero_dos == numero_tres): print("Se cumple que", numero_tres ,"es igual a ", numero_uno, "+",numero_dos) elif (numero_uno + numero_tres == numero_dos): print("Se cumple que", numero_dos ,"es igual a ", numero_uno, "+", numero_tres) elif (numero_dos + numero_tres == numero_uno): print("Se cumple que", numero_uno ,"es igual a:", numero_dos, "+", numero_tres) else: print("Los numeros no cumplen la condicion")
false
84151fa2b3dc95721b51563a5e129da931b99820
saulelabra/Programming_languages
/ejercicios/scheme - racket/list_comprehension/ejercicio1.py
922
4.46875
4
""" Examples of list comprehension in Python """ def squares(data): result = [] for i in data: if i % 2 == 0:#only returns result when the numer is pair result.append(i * i) return result def sqr(num): return num * num #this function does not return a list, returns an iterable that can be converted into a list def squares_map(data): return list(map(lambda x: x*x, data)) #return map (sqr, data)#equivalent to the lambda function def squares_comprehension(data): #return [x*x for x in data if x % 2 == 0]#only returns result when the numer is pair return [x*x if x%2 == 0 else x*x*x for x in data]#returns square when pair and cube when odd data = [3, 4, 5, 6, 7, 8, 9] print(squares(data)) print(squares_map(data)) print(squares_comprehension(data)) """print(squares([3, 4, 5, 6])) print(squares_map([3, 4, 5, 6])) print(squares_comprehension([3, 4, 5, 6]))"""
true
10825e7d912a0d6ab6bcf4e6e189c6dacf4ca5d1
leiyunhe/Pre-test4OpenMindCLub
/ex12+.py
948
4.34375
4
#Example 1 age = raw_input("How old are you?") height = raw_input("how height are you?") weight = raw_input("how weight are you?") # %r print "So you are %r years old, %r tall and %r weight." % \ (age, height, weight) # %s print "So you are %s years old, %s tall and %s weight." % ( age, height, weight) # Example 2 shows the difference between %s and %r like = '50' hate = 46.667 print "%s %r" % (like, like) print "%s %r" % (hate, hate) print like print hate print like, hate #Example 3 shows why we use %r than %s. apple = raw_input("please type the first number?") orange = raw_input("please type the second number?") print apple + orange #connect two strings because the output type of "raw_input" is string. # !Attention: int() does not work. #print int(apple) + int(orange) #add two (int) numbers print float(apple) + float(orange) # add two (float) numbers print float(apple), int(float(apple)) #int() only change the number
true
cfdb719e4c47ff0e011b58ed82cbd1aed6ac8882
harmonytrevena/python_101
/madlib.py
310
4.5
4
# Small Exercise 3. Madlib # Prompt the user for the missing words to a Madlib sentence using the input function. You can make up your own Madlib sentence. name = input("What is your name? ") subject = input("What is your favorite subject? ") print(name + "'s favorite subject in school is " + subject + ".")
true