blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
23ab00fb5704520dc6bd99fabd951f3fdff77f8c
wickyou23/python_learning
/python3_learning/operators.py
251
4.15625
4
#####Python operators # x1 = 3/2 #float div # x2 = 3//2 #interger div # x3 = 3**2 # x4 = 6%2 # print(x1, x2, x3, x4) #####Operator Precedence # x5 = 1+3*2 # print(x5) #####Augmented Assignment Operator # x6 = 1 # x6 += 1 # print(x6)
false
366ffad8460a65261f57e99b28789147a915e3d0
TimothyCGoens/Assignments
/fizz_buzz.py
613
4.21875
4
print("Welcome back everyone! It's now time for the lighting round of FIZZ or BUZZ!") print("""For those of you following at home, it's simple. Our contestants need to give us a number that is either divisible by 3, by 5, or by both!""") name = input("First up, why don't you tell us your name? ") print(f"""Well {name}, I hope you are ready to go, because the timer starts right NOW! """) number = int(input("Enter a number: ")) if number % 3 == 0 and number % 5 == 0: print("FIZZBUZZ") elif number % 5 == 0: print("BUZZ") elif number % 3 == 0: print("FIZZ!!") else: print("Sorry, you lose!")
true
f2ce2ad7ad3703bb800c7fc2dfd79b6bab76d491
thedern/algorithms
/recursion/turtle_example.py
835
4.53125
5
import turtle max_length = 250 increment = 10 def draw_spiral(a_turtle, line_length): """ recursive call example: run the turtle in a spiral until the max line length is reached :param a_turtle: turtle object "charlie" :type a_turtle: object :param line_length: length of line to draw :type line_length: int :return: recursive function call :rtype: func """ # compare line_length to base-case (max_length) if line_length > max_length: return a_turtle.forward(line_length) a_turtle.right(90) # recursive call return draw_spiral(a_turtle, line_length + increment) def main(): charlie = turtle.Turtle(shape="turtle") charlie.pensize(5) charlie.color("red") draw_spiral(charlie, 10) turtle.done() if __name__ == "__main__": main()
true
bc87f755b34064cc614504c41092be4765251e03
njg89/codeBasics-Python
/importSyntax.py
1,007
4.15625
4
# Designate a custom syntax for a default function like th example 'statistics.mean()' below: ''' import statistics as stat exList = [5,3,2,9,7,4,3,1,8,9,10] print(stat.mean(exList)) ''' # Only utilize one function, like the 'mean' example below: ''' from statistics import mean exList2 = [3,2,3,5,6,1,0,3,8,7] print(mean(exList2)) ''' # Utilize multiple functions while renaming each ''' from statistics import mean as m, stdev as std exList2 = [3,2,3,5,6,1,0,3,8,7] print('The set is: ', exList2,'\n') print('The Mean of the set is: ') print(m(exList2)) print('\nThe Standard Deviation of the set is: ') print(std(exList2)) ''' # Import statistics with all functions without needing to type out the entire 'statistics.mean' function ''' from statistics import * exList2 = [3,2,3,5,6,1,0,3,8,7] print('The set is: ', exList2,'\n') print('The Mean of the set is: ') print(mean(exList2)) print('\nThe Standard Deviation of the set is: ') print(stdev(exList2)) '''
true
66b5826912e87770d5e305e93f2faacba745ac7e
CleonPeaches/idtech2017
/example_02_input.py
499
4.15625
4
# Takes input from user and assigns it to string variable character_name character_name = input("What is your name, adventurer? ") print("Hello, " + character_name + ".") # Takes input from user and assigns it to int variable character_level character_level = (input("What is your level, " + character_name + "? ")) # Checks if input is a positive number if isinstance(character_level, int) == False or character_level <= 0: character_level = (input("Please enter a positive numeric value. "))
true
4e17d157d0abc7d7f36a454b3a3fe62887e98cc4
ian7aylor/Python
/Programiz/GlobKeyWrd.py
654
4.28125
4
#Changing Global Variable From Inside a Function using global c = 0 # global variable def add(): global c c = c + 2 # increment by 2 print("Inside add():", c) add() print("In main:", c) #For global variables across Python modules can create a config.py file and store global variables there #Using a Global Variable in Nested Function def foo(): x = 20 def bar(): global x x = 25 print("Before calling bar: ", x) print("Calling bar now") bar() print("After calling bar: ", x) foo() print("x in main: ", x) #Test global f f = 2 def yes(f): f += 4 return f b = yes(f) print(b)
true
b220370ca9ffd82ea7189e0a5167c9bae233f223
ian7aylor/Python
/Programiz/For_Loop.py
1,260
4.28125
4
#For Loop ''' for val in sequence: Body of for ''' # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list #iterates through list of numbers and sums them together for val in numbers: sum = sum+val print("The sum is", sum) #Range function (start, stop, step size) print(range(10)) print(list(range(10))) #10 values, 0-9 print(list(range(2, 8))) # Goes 2-7, 7 is 8th position print(list(range(2, 20, 3))) # step size is 3 # Program to iterate through a list using indexing genre = ['pop', 'rock', 'jazz'] print(range(len(genre))) # iterate over the list using index for i in range(len(genre)): print("I like", genre[i]) #For loop with else digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.") #Can use a break statement rather than an else # program to display student's marks from record student_name = 'Jules' marks = {'James': 90, 'Jules': 55, 'Arthur': 77} for student in marks: if student == student_name: print(marks[student]) #Prints value associated with key break else: print('No entry with that name found.')
true
1c14df00fa1f6304216b8fd1d7a28186610c3182
rishabmehrotra/learn_python
/Strings and Text/ex6.py
879
4.625
5
#use of f and .format() """F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. f'some stuff here {avariable}'""" #.format() """ The format() method formats the specified value(s) and insert them inside the string's placeholder. txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36) txt2 = "My name is {0}, I'm {1}".format("John",36) txt3 = "My name is {}, I'm {}".format("John",36)""" types_of_people = 10 x = f'There are {types_of_people} people' binary = 'binary' do_not = "don't" y = f'those who know {binary} and those who {do_not}' print(x) print(y) print(f'I said {x}') print(f'.....And... {y}') hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_evaluation.format(hilarious)) w = "This is the left side of...." e = "This is the right side of... string" print(w+e)
true
806969204ed0adab1f751fc6c3aa6ac07eb4cf7d
DonaldButters/Module5
/input_while/input_while_exit.py
1,300
4.28125
4
""" Program: input_while_exit.py Author: Donald Butters Last date modified: 9/25/2020 The purpose of this program is prompt for inputs between 1-100 and save to list. Then the program out puts the list """ #input_while_exit.py user_numbers = [] stopvalue = 404 x = int(input("Please Enter a number between 1 and 100. Type 404 to exit. : ")) while x != stopvalue: while x not in range(1,101): x = int(input("Incorrect. Please enter only numbers 1-100. Type 404 to exit. :")) if x == 404: print("Your are now exiting the program.") break else: user_numbers.append(x) x = int(input("Thank you. " "Your number has been saved. \n" "Enter another number between 1-100\n" "or type 404 to exit. : ")) if x == 404: print('Your numbers are: ') for i in user_numbers: print(i) print('Thank You. Goodbye') '''comments code seems to work as intended. if a user inputs a number between 1-100 they are taken to a promt tells them their number has been saved. it then promts for another number. each promt will also have an exit code to leave the program. The exit codes will promt the use goodbye and exit. The outputs for each test are as expected'''
true
8fe8605311210ea18e381eae1957c3b282f026f6
kzk-maeda/algorithm_and_data_structure
/python/sort/bubble_sort.py
495
4.3125
4
from typing import List # Listのソート範囲の最後尾が最大値となるよう、繰り返し比較処理を実行する def bubble_sort(numbers: List[int]) -> List[int]: len_numbers = len(numbers) for i in range(len_numbers): for j in range(len_numbers - 1 - i): if numbers[j] > numbers[j+1]: numbers[j], numbers[j+1] = numbers[j+1], numbers[j] return numbers if __name__ == '__main__': nums = [2,6,4,1,3] print(nums) print(bubble_sort(nums))
false
c54cbeb7fa6238af2922e6fa980064bc48699791
q737645224/python3
/python基础/python笔记/day04/exercise/right_align.py
1,283
4.25
4
# 练习: # 输入三行文字,让这三行文字依次以20个字符的宽度右对齐输出 # 如: # 请输入第1行: hello world # 请输入第2行: aaa # 请输入第3行: ABCDEFG # 输出结果如下: # hello world # aaa # ABCDEFG # 做完上面的题后思考: # 能否以最长的字符串的长度进行右对齐显示(左侧填充空格) a = input("请输入第1行: ") b = input("请输入第2行: ") c = input("请输入第3行: ") # 方法1 print("%20s" % a) print("%20s" % b) print("%20s" % c) # 方法2 # print(' ' * (20 - len(a)) + a) # print(' ' * (20 - len(b)) + b) # print(' ' * (20 - len(c)) + c) print('----------以最长字符串长度进行右对齐------') # 方法1 # max_length = len(a) # if len(b) > max_length: # max_length = len(b) # if len(c) > max_length: # max_length = len(c) # print("最长的字符串长度为:", max_length) # print(' ' * (max_length - len(a)) + a) # print(' ' * (max_length - len(b)) + b) # print(' ' * (max_length - len(c)) + c) # 方法2 max_length = max(len(a), len(b), len(c)) # fmt = '%' + str(max_length) + 's' # "%数字s" fmt = '%%%ds' % max_length # "%数字s" print('=====>', fmt) print(fmt % a) print(fmt % b) print(fmt % c)
false
ec8d676308de59e6224af6a8eb1416e5c3978502
q737645224/python3
/python基础/python笔记/day09/exercise/print_odd.py
1,084
4.25
4
# 2. 写一个函数,print_odd, 此函数可以传递一个实参,也可以传递两个实参,当传递一个实参时代表结束值 # 当传递两个实参时,第一个实参代表起始值,第二个实参代表结束值 # 打印出以此区间内的全部奇数,不包含结束数: # print_odd(10) # 1 3 5 7 9 # print_odd(11, 20) # 11 13 15 17 19 # 方法1 def print_odd(a, b=0): if b == 0: for x in range(1, a, 2): print(x, end=' ') else: print() else: if a % 2 == 0: # 如果是偶数,变为奇数 a += 1 for x in range(a, b, 2): print(x, end=' ') else: print() def print_odd(a, b=None): if b is None: start = 1 end = a else: start = a end = b # 如果开始的偶数,做校正 if start % 2 == 0: start += 1 for x in range(start, end, 2): print(x, end=' ') print() print_odd(10) # 1 3 5 7 9 print_odd(11, 20) # 11 13 15 17 19 print_odd(10, 20) print_odd(5, 0)
false
90db359ca865a4a29a815f2c0d7a0fc8fbe0ad77
q737645224/python3
/python基础/python笔记/day15/exercise/iterator_set.py
519
4.15625
4
# 有一个集合: # s = {'唐僧', '悟空', '八戒', '沙僧'} # 用 for语句来遍历所有元素如下: # for x in s: # print(x) # else: # print('遍历结束') # 请将上面的for语句改写为 用while语句和迭代器实现 s = {'唐僧', '悟空', '八戒', '沙僧'} # for x in s: # print(x) # else: # print('遍历结束') it = iter(s) # 拿到迭代器 try: while True: x = next(it) print(x) except StopIteration: print('遍历结束')
false
dc7ef8a26abcf8b466fbfdda721744f287a885e6
q737645224/python3
/python基础/python笔记/day03/day02_exercise/score.py
661
4.25
4
# 2. 输入一个学生的三科成绩(三个整数): # 打印出最高分是多少? # 打印出最低分是多少? # 打印出平均分是多少? a = int(input("请输入第一科成绩: ")) b = int(input("请输入第二科成绩: ")) c = int(input("请输入第三科成绩: ")) # if a > b: # if a > c: # print("最大数是:", a) # else: # print("最大数是:", c) # else: # if b > c: # print("最大数是:", b) # else: # print("最大数是:", c) # 先假设 a最大 zuida = a # 再用b去和zuida判断 if b > zuida: zuida = b if c > zuida: zuida = c print("最高分是:", zuida)
false
8abda8068278d4ceba6a2e60d5d76db6e2c02a86
DannyMcwaves/codebase
/pythons/stack/stack.py
1,526
4.125
4
__Author__ = "danny mcwaves" """ i learnt about stacks in the earlier version as a record activation container that holds the variables during the invocation of a function. so when the function is invoked the, the stack stores all the variables in the function and release them as long as their parent functions once the function is done this stack class is just being designed as a prototype of the python stack. it is a list that holds all the data of a function during the operation of a function and release them if possible. """ class Stack: def __init__(self): self.__elements = [] def __str__(self): if self.is_empty(): return None return str(self.__elements) def is_empty(self): # check whether the list is empty or not return self.__elements.__len__() == 0 def push(self, items): # to append a new element to the list self.__elements.append(items) def peek(self): # lets look at the last element in the list if self.is_empty(): return 'EmptyList' return self.__elements[self.__elements.__len__() - 1] def pop(self): # this is supposed to remove the remove the last element in the list if self.is_empty(): return "EmptyList" return self.__elements.pop() def duplicate(self, times): return times * self.__elements def __len__(self): # to return the length of all the elements in the list return self.__elements.__len__()
true
951c7e5183fa5c141cc354c47dadf1b4821c19e8
BlackHeartEmoji/Python-Practice
/PizzaToppings.py
511
4.15625
4
toppings = ['pepperoni','sausage','cheese','peppers'] total = [] print "Hey, let's make a pizza" item = raw_input("What topping would you like on your pizza? ") if item in toppings: print "Yes we have " + item total.append(item) else: print "Sorry we don't have " + item itemtwo = raw_input("give me another topping? ") if itemtwo in toppings: print "Yes we have " + itemtwo total.append(itemtwo) else: print "Sorry we don't have " + itemtwo print "Here are your toppings " print total
true
7fca8ff0cec660dbf2c22d658bad5ba1b6d4a8a4
Aditya-Malik/Edyoda-Assignments
/subArray.py
444
4.3125
4
# 1. Print all sub arrays for a given array. Ex - if array is [2, 7, 5], Output will be: [2] [2, 7] [2, 7, 5] [7] [7, 5] [5]. def subArray(array): n=len(array) for i in range(0,n): for j in range(i,n): k=i sub_array=[] while k<=j: sub_array.append(array[k]) k+=1 if len(sub_array)>0: print(sub_array) subArray([2,7,5])
false
030e3abfd6bce4b33f9f5735aefbc21d94543304
jamarrhill/CS162Project6B
/is_decreasing.py
810
4.15625
4
# Name: Jamar Hill # Date: 5/10/2021 # Description: CS 162 Project 6b # Recursive functions # 1. Base case -> The most basic form of the question broken down # 2. If not base, what can we do to break the problem down # 3. Recursively call the function with the smaller problem # lst = [5, 6, 10, 9, 8, 7, 64, 10] # ^ ^ def is_decreasing(list): return is_decreasing_helper(list, 0, len(list) - 1) # passed in the beginning index and ending index def is_decreasing_helper(list, fstPos, lstPos): if fstPos < lstPos: if list[fstPos] >= list[fstPos + 1]: return is_decreasing_helper(list, fstPos + 1, lstPos) # Recursive call, and also update fstPos else: return False else: return True print(is_decreasing([9, 6, 3, 1]))
true
58a4de9900cdfcc825800f5c2a39f660ece015ab
pnovotnyq/python_exercises
/12_Fibonacci.py
947
4.75
5
#! /usr/bin/env python ''' Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) ''' # def fibonacci(num): # a = 0 # b = 1 # fib = [1] # for n in range(num-1): # c = a+b # fib.append(c) # a = b # b = c # return fib # # if __name__ == '__main__': # num = int(input("Print how many Fibonacci numbers? ")) # if num >= 1: # print(fibonacci(num)) ## As a generator def fibonacci(): a = 0 b = 1 yield a + b for i in range(20): num = next(fibonacci()) print(num)
true
9e81f8e5faf23a690b9a20eb06227c4a779848e4
Goutam-Kelam/Algorithms
/Square.py
813
4.25
4
''' This program produces the square of input number without using multiplication i:= val:= square of i th number ''' try : num = int(raw_input("\n Enter the number\n")) if(num == 0): # FOR ZERO print "\nThe square of 0 is 0\n" exit(1) if (num > 0): #FOR POSITIVE NUMBERS i = 1 val = 1 while( i != num): val = val + i + i + 1 i = i+1 if (num < 0): # FOR NEGATIVE NUMBERS i = -1 val = 1 while( i != num): val = val - i - i + 1 i = i-1 print "\n square of ",num," is ",val except ValueError: print "\nEnter integer values only\n "
true
e8a587f892f49edeaf6927e57113a7eeec0f3495
prasadhegde001/Turtle_Race_Python
/main.py
1,115
4.28125
4
from turtle import Turtle,Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_input = screen.textinput(title="Please Make Your Bet", prompt="Which Turtle Will win the Race? Enter a color") colors = ["red", "orange", "yellow", "green", "blue", "purple"] y_position = [-100, -70, -40, -10, 30, 60] all_turtle = [] for turtle_index in range(0,6): new_turtle = Turtle(shape="turtle") new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.goto(x=-230, y=y_position[turtle_index]) all_turtle.append(new_turtle) if user_input: is_race_on = True while is_race_on: for turtle in all_turtle: if turtle.xcor() > 230: is_race_on = False winning_color = turtle.pencolor() if user_input == winning_color: print(f"You Have Won! The Winning Color is {winning_color}") else: print(f"You Loose! The Winning Color is {winning_color}") turtle.forward(random.randint(0, 10)) screen.exitonclick()
true
d6e91528d13834231a950e675781ddccab502986
shabbir148/A-Hybrid-Approach-for-Text-Summarization-
/fuzzy-rank/Summarizers/file_reader.py
1,100
4.15625
4
# Class to simplify the reading of text files in Python. # Created by Ed Collins on Tuesday 7th June 2016. class Reader: """Simplifies the reading of files to extract a list of strings. Simply pass in the name of the file and it will automatically be read, returning you a list of the strings in that file.""" def __init__(self, name): """\"name\" is the name of the file to open. The file should be a series of lines, each line separated with a newline character.""" self.name = name; def open_file(self): """Reads the file given by the file name and returns its contents as a list of seperate strings, each string being a line in the file.""" with open(self.name) as fp: contents = fp.read().split() fp.close() return contents def open_file_single_string(self): """Reads the file given by the file name and returns its contents as a list of seperate strings, each string being a line in the file.""" with open(self.name) as fp: contents = fp.read() fp.close() return contents
true
b0304411d3408c08056d86457ef288d10ecf461d
pole55/repository
/Madlibs.py
1,360
4.21875
4
"""Python Mad Libs""" """Mad Libs require a short story with blank spaces (asking for different types of words). Words from the player will fill in those blanks.""" # The template for the story STORY = "This morning %s woke up feeling %s. 'It is going to be a %s day!' Outside, a bunch of %ss were protesting to keep %s in stores. They began to %s to the rhythm of the %s, which made all the %ss very %s. Concerned, %s texted %s, who flew %s to %s and dropped %s in a puddle of frozen %s. %s woke up in the year %s, in a world where %ss ruled the world." print "Here we go!" name = raw_input("Enter a name: ") adjective1 = raw_input("Write the adjective: ") adjective2 = raw_input("One more, please: ") adjective3 = raw_input("And the last one: ") verb = raw_input("Input the one verb: ") noun1 = raw_input("and noun: ") noun2 = raw_input("and one more noun, please: ") print "This is where the story can get really fun! Input one of each of the following, please" animal = raw_input("An animal: ") food = raw_input("A food: ") fruit = raw_input("A fruit: ") superhero = raw_input("A superhero: ") country = raw_input("A country: ") dessert = raw_input("A dessert: ") year = raw_input("A year: ") print STORY % (name, adjective1, adjective2, animal, food, verb, noun1, fruit, adjective3, name, superhero, name, country, name, dessert, name, year, noun2)
true
1f48d9529ae94ae0deb313d495ffce1ee57179ec
Apropos-Brandon/py_workout
/code/ch01-numbers/e01_guessing_game.py~
634
4.25
4
#!/usr/bin/env python3 import random def guessing_game(): """Generate a random integer from 1 to 100. Ask the user repeatedly to guess the number. Until they guess correctly, tell them to guess higher or lower. """ answer = random.randint(0, 100) while True: user_guess = int(input("What is your guess? ")) if user_guess == answer: print(f"Right! The answer is {user_guess}") break elif user_guess < answer: print(f"Your guess of {user_guess} is too low!") elif user_guess > answer: print(f"Your guess of {user_guess} is too high!")
true
6e9ae233ec122eeafe301ba8f76cfe4da0972798
liuxingyuxx/cookbook
/date_structure/zip.py
888
4.25
4
#怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)为了对字典值执行计算操作,通常需要使用 zip() 函数先将键和值反转过来 prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } min_price = min(zip(prices.values(), prices.keys())) max_price = max(zip(prices.values(), prices.keys())) print(min_price, max_price) print_sort = sorted(zip(prices.values(), prices.keys())) #执行这些计算的时候,需要注意的是 zip() 函数创建的是一个只能访问一次的迭代器。 比如,下面的代码就会产生错误: price_and_names = zip(prices.values(), prices.keys()) print(max(price_and_names)) #OK print(min(price_and_names)) #Wrong
false
eedde460936b41c711402499160c903855636a3a
Struth-Rourke/cs-module-project-iterative-sorting
/src/searching/searching.py
1,332
4.21875
4
def linear_search(arr, target): # for value in the len(arr) for i in range(0, len(arr)): # if the value equals the target if arr[i] == target: # return the index value return i # # ALT Code: # for index, j in enumerate(arr): # if j == target: # return index return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here # setting lowest element index low_idx = 0 # setting highest element index high_idx = len(arr) - 1 # while the low_idx is less than the high_one while low_idx < high_idx: # find the mid_idx mid_idx = int((low_idx + high_idx) / 2) # if the value is equal to the target if arr[mid_idx] == target: # return the index return mid_idx # if the value is too low if arr[mid_idx] < target: # equate the low_idx and the mid_idx so that you can search the lower # half of the distribution low_idx = mid_idx # else the value is too high else: # equate the high_idx and the mid_idx so that you can search the upper # half of the distribution high_idx = mid_idx return -1 # not found
true
ddf570644ae74b247569a0f9a303abf2906f83b9
Dagim3/MIS3640
/factor.py
381
4.25
4
your_number = int(input("Pick a number:")) #Enter value for factor in range( 1, your_number+1): #Range is from 1 to the entered number, +1 is used as the range function stops right before the last value factors = your_number % factor == 0 #This runs to check that the entered number doesn't have a remainder if factors == True: print (factor) #Prints the number
true
3df59ff6049246c715d31544df192d245fba4da6
Dagim3/MIS3640
/BMIcalc.py
616
4.3125
4
def calculate_bmi(Weight, Height): BMI = 703* (Weight / (Height*Height)) if BMI>= 30: print ('You are {}'.format(BMI)) print ('Obese') elif BMI>= 25 and BMI< 29.9: print ('You are {}'.format(BMI)) print ('Overweight') elif BMI>= 18.5 and BMI<24.9: print ('You are {}'.format(BMI)) print ('Normal Weight') else: print ('You are{}'.format(BMI)) print ('Underweight') Weight = (input ('What is your weight?')) Height = (input ('What is your height?')) Weight = float(Weight) Height = float(Height) calculate_bmi (Weight, Height)
true
69d1287d9328bb83dc8cd52f8a587a90a0614feb
derekdyer0309/interview_question_solutions
/Array Sequences/sentence_reversal.py
1,416
4.40625
4
""" Given a string of words, reverse all the words. For example: Given: 'This is the best' Return: 'best the is This' As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as: ' space here' and 'space here ' both become: 'here space' ###NOTE: DO NOT USE .reverse()### """ def string_reversal(str): #separate words into a list #remove whitespace sentence = list(str.split(' ')) #create list to store indices in reverse order reversed_str = [] #iterate string in reverse order for word in sentence[::-1]: #removes excess whitespace if word is not '': reversed_str.append(word) return " ".join(reversed_str) print(string_reversal(' space before')) #'before space' print(string_reversal('space after ')) #'after space' print(string_reversal(' Hello John how are you ')) # 'you are how John Hello' print(string_reversal('1')) #1 # from nose import nose.tools # class ReversalTest(object): # def test(self,sol): # assert_equal(sol(' space before'),'before space') # assert_equal(sol('space after '),'after space') # assert_equal(sol(' Hello John how are you '),'you are how John Hello') # assert_equal(sol('1'),'1') # print("ALL TEST CASES PASSED") # # Run and test # t = ReversalTest() # t.test(string_reversal)
true
4ba8df598a59c5f1ce1bdf81046b1719d447d277
derekdyer0309/interview_question_solutions
/Strings/countingValleys.py
964
4.21875
4
import math def countingValleys(steps, path): #Make sure steps and len(path) are == or greater than zero if steps == 0: return 0 if len(path) == 0: return 0 if steps != len(path): return 0 #keep track of steps down, up, and valleys sea_level = 0 steps = 0 valleys = 0 #split the string into a list of strings types = list(path.upper()) # check set if a value from ar already exists in our set, if it does we can increase pairs by one and remove the value from the set for val in types: # if the value is D we increment sdown if val == "D": steps -= 1 continue # if value is U we increment up elif val == "U": steps += 1 #check if down is == up and add to valleys if true if steps == sea_level: valleys += 1 #else we add to our set return valleys print(countingValleys(8, "UDDDUDUU"))
true
5b08179675bca8d0be53cc754f0e8eaa6bb3d2ac
AdityaNarayan001/Learning_Python_Basics
/Python Basics/weight_converter.py
440
4.125
4
# Weight converter type = input('To Enter weight in (L)Lbs or (KG)kilogram :- ') if type.upper() == "L": weight = int(input('Enter your Weight in Pound : ')) kg_weight = weight / 0.45 print('Your weight in Kg is ' + str(kg_weight) + ' Kg') elif type.upper() == "KG": weight = int(input('Enter your Weight in KiloGram: ')) l_weight = weight * 0.45 print('Your weight in Pound is ' + str(l_weight) + ' l')
false
acb3c73a5497db189795a56cea70fda0895ed9e5
msinnema33/code-challenges
/Python/almostIncreasingSequence.py
2,223
4.25
4
def almostIncreasingSequence(sequence): #Take out the edge cases if len(sequence) <= 2: return True #Set up a new function to see if it's increasing sequence def IncreasingSequence(test_sequence): if len(test_sequence) == 2: if test_sequence[0] < test_sequence[1]: return True else: for i in range(0, len(test_sequence)-1): if test_sequence[i] >= test_sequence[i+1]: return False else: pass return True for i in range (0, len(sequence) - 1): if sequence[i] >= sequence [i+1]: #Either remove the current one or the next one test_seq1 = sequence[:i] + sequence[i+1:] test_seq2 = sequence[:i+1] + sequence[i+2:] if IncreasingSequence(test_seq1) == True: return True elif IncreasingSequence(test_seq2) == True: return True else: return False # Given a sequence of integers as an array, determine whether it # is possible to obtain a strictly increasing sequence by removing no more than one element from the array. # Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. # Sequence containing only one element is also considered to be strictly increasing. # Example # For sequence = [1, 3, 2, 1], the output should be # almostIncreasingSequence(sequence) = false. # There is no one element in this array that can be removed in order to get a strictly increasing sequence. # For sequence = [1, 3, 2], the output should be # almostIncreasingSequence(sequence) = true. # You can remove 3 from the array to get the strictly increasing sequence [1, 2]. # Alternately, you can remove 2 to get the strictly increasing sequence [1, 3]. # Input/Output # [execution time limit] 4 seconds (py3) # [input] array.integer sequence # Guaranteed constraints: # 2 ≤ sequence.length ≤ 105, # -105 ≤ sequence[i] ≤ 105. # [output] boolean # Return true if it is possible to remove one element from the array in order to # get a strictly increasing sequence, otherwise return false.
true
96eb009a11129f84ea3bb1c98abbc7fc93c0937e
jayceazua/wallbreakers_work
/week_1/detect_cap.py
1,407
4.4375
4
""" Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False """ class Solution: def detectCapitalUse(self, word: str) -> bool: return word.isupper() or word.islower() or word.istitle() # checks that all the letters in the word are upper case # if word.isupper(): # return True # # checks that all the letters in the word are lower case # if word.islower(): # return True # found = False # for i in range(len(word)): # is_upper = word[i].isupper() # if is_upper and found == False and i == 0: # found = True # elif found == False and is_upper: # return False # elif is_upper and found: # return False # return True # usage of characters are correct: # all letters are capital # all letters are not capital # the first letter in the word is capital
true
325c1a34c36080380709be79330a2ded62c4e4fe
jayceazua/wallbreakers_work
/practice_facebook/reverse_linked_list.py
658
4.3125
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ def reverseList(head): # if not head or not head.next: # return head # p = reverseList(head.next) # head.next.next = head # head.next = None # return p previous = None # <- new reversed linked list current = head while current: temp = current.next current.next = previous previous = current current = temp return previous
true
83aa02c1e5f13e596e4858f4d56f50acf6ccc559
jayceazua/wallbreakers_work
/week_1/reverse_int.py
1,049
4.21875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x: int) -> int: # check if the input is a negative number is_negative = False if x < 0: is_negative = True x = abs(x) reversed_num = 0 # 3 while x != 0: reversed_num = (reversed_num * 10) + (x % 10) # x = x // 10 # corner/ edge cases if is_negative: if (reversed_num * -1) < ((2**31) * -1): return 0 return reversed_num * -1 elif reversed_num == 0 or reversed_num > (2**31 - 1): return 0 return reversed_num
true
db18748f39f1d17bfbcf5e28daa511b4b49df53b
jayceazua/wallbreakers_work
/week_1/transpose_matrix.py
1,179
4.28125
4
""" Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [ [1,2,3], [4,5,6], [7,8,9] ] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Note: 1 <= A.length <= 1000 1 <= A[0].length <= 1000 """ class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: temp = [] new_matrix = [] matrix = A # make a reference # since it is on its main diagonal (0,0) -> (1, 0) ...(0, n-1) row_index = 0 column_index = 0 row_length = len(matrix) column_length = len(matrix[0]) # is the matrix a perfect square? # assuming the matrix is a perfect - solution while column_index < column_length: while row_index < row_length: temp.append(matrix[row_index][column_index]) row_index += 1 new_matrix.append(temp) temp = [] row_index = 0 column_index += 1 return new_matrix
true
8c05cf6c225a14f05bc041485267a6a22bdb3929
Crick25/First-Project
/First Project ✓.py
908
4.15625
4
#ask if like basketball, if yes display nba heights the same, if no ask if like football, #if yes display football heights the same, if no to that print you boring cunt #height from 5ft8 to 6ft5 myString = 'User' print ("Hello " + myString) name = input("What is your name?: ") type(name) print("Welcome, " + name + "!") age = input("And how old are you, " + name + "?: ") type(age) height = input("What is your height in CM, " + name + "?: ") type(height) sport = input("Are you a fan of a sport? If so which sport? ") type(sport) infoM = input("Type 'info' to display your saved information ") type(infoM) info = 'info' if infoM == info: print("Here is what you've told me: ") print ("Your name is " + name + ",") print ("you are " + age + " years old,") print (height + "cm tall") print ("and you enjoy watching " +sport + ".")
true
f41b8dc0c69a15541a9c13636a709cfdeacf77b1
iconocaust/csci102-wk11-git
/fibonacci.py
592
4.21875
4
# Galen Stevenson # CSCI 101 - B # WEEK 1 - LAB 1B # fibonacci.py def fib(): fibs = [1, 2] for i in range(1,9): ''' implement Fibonacci sequence to calculate the first 10 Fibonacci numbers, note Fn = Fn-1 + Fn-2 ''' return fibs def main(): print('OUTPUT', fib()) if __name__ == "__main__": main() F0=1 F1=1 F2=F1+F0 F3=F2+F1 F4=F3+F2 F5=F4+F3 F6=F5+F4 F7=F6+F5 F8=F7+F6 F9=F8+F7 F10=F9+F8 F11=F10+F9 print ('The first 10 digits of the Fibonacci Sequence are:') print (' ') print (' ') print(F1, F2, F3, F4, F5, F6, F7, F8, F9, F10)
false
5f0d3e5837cd98a06f4e0234d896f430ad4dc4e3
houdinii/datacamp-data-engineering
/data-engineering/streamlined-data-ingestion-with-pandas/importing-data-from-flat-files.py
1,550
4.25
4
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def get_data_from_csvs(): """ Get data from CSVs In this exercise, you'll create a data frame from a CSV file. The United States makes available CSV files containing tax data by ZIP or postal code, allowing us to analyze income information in different parts of the country. We'll focus on a subset of the data, vt_tax_data_2016.csv, which has select tax statistics by ZIP code in Vermont in 2016. To load the data, you'll need to import the pandas library, then read vt_tax_data_2016.csv and assign the resulting data frame to a variable. Then we'll have a look at the data. Instructions: + Import the pandas library as pd. + Use read_csv() to load vt_tax_data_2016.csv and assign it to the variable data. + View the first few lines of the data frame with the head() method. This code has been written for you. """ # Read the CSV and assign it to the variable data data = pd.read_csv("data/vt_tax_data_2016.csv") # View the first few lines of data print(data.head()) def get_data_from_other_flat_files(): # Load TSV using the sep keyword argument to set delimiter data = pd.read_csv("data/vt_tax_data_2016.csv", sep=',') # Plot the total number of tax returns by income group counts = data.groupby("agi_stub").N1.sum() counts.plot.bar() plt.show() def main(): sns.set() get_data_from_csvs() get_data_from_other_flat_files() if __name__ == '__main__': main()
true
4cb6ced5de1ffb717fb617b881d655510f508cd9
Muneshyne/Python-Projects
/Abstractionassignment.py
1,157
4.375
4
from abc import ABC, abstractmethod class Mortgage(ABC): def pay(self, amount): print("Your savings account balance is: ",amount) #this function is telling us to pass in an argument. @abstractmethod def payment(self, amount): pass class HomePayment(Mortgage): #here we've defined how to implement the payment function from its parent paySlip class. def payment(self, amount): print('Your overdue mortgage payment due is {} '.format(amount)) #needs wildcard to show format(amount) obj = HomePayment() obj.pay("$1400") obj.payment("$1200") """ Abstraction is useful for working on much larger projects when child classes may need to utilize implementation of methods differently from its parent class and other child classes that inherit from the same parent. Think of it like this: You have one parent class of Payment, then child classes need to run different payment options separately from each other, such as Debit, Credit, Gift card, etc. They all take a payment from the customer, but each process needs to be different according to how the banks process them. """
true
bc0ffff09955ac29454d2193c38de89025afe25c
MrLW/python
/chapter_05/demo02.py
215
4.25
4
name = input('what is your name ?') if name.endswith('Bob'): print("Hello Mr.Bob") else: print("Hello LiWen") # python的三目运算符 status = 'friend' if name.endswith("Bob") else "liwen" print(status)
false
7eb969c50bcb0c462c0711f044891b0a6f4bfe58
mgardiner1354/CIS470
/exam1_Q21.py
911
4.21875
4
import pandas as pd #Without using pandas, write a for loop that calculates the average salary of 2020 Public Safety per division of workers in the Cambridge Data Set# import csv #adding csv library total_salary = 0 #defining total salary across all employees emp_count = 0 #defining how many employees work at Cambridge with open('Cambridge_Salaries.csv') as file: csv_reader_object = csv.reader(file) if csv.Sniffer().has_header: next(csv_reader_object) #checks for header and skips it in calculations for row in csv_reader_object: #iterating through csv to calculate total salary and number of employees float_salary = float(row[6]) total_salary += float_salary emp_count += 1 #calculate average by dividing salary by employees avg_salary = total_salary/emp_count print("The average salary in the data set is") print(avg_salary)
true
846ba86bb7a3468ad1ff09035f74e8c992cd093c
lewiss9581/CTI110
/M3LAB_Lewis.py
978
4.1875
4
# The purpose of this program is to calculate user input of their number grades and then output the letter grade # Lewis. # The def main or code being excuted later sets the following variables: A_score = 90, B_score = 80, C_score = 70, D_score = 60, F_score = 50, A_score = 90 B_score = 80 C_score = 70 D_score = 60 F_score = 50 # The user input a integer. score = int(input('Enter grade')) # The code then calculates the letter grade of the user using: 90 >= A_score, 80 >= B_score, 70 >= C_score, 60 >= D_score, 50 >= F_score def main(): if score >=A_score: print('Your grade is: A') elif score >=B_score: print('Your grade is: B') elif score >=C_score: print('Your grade is: C') elif score >=D_score: print('Your grade is: D') else: print('Your grade is: F') # The program then excutes by printing a letter grade as a result of its evaluation of the if statements. main()
true
938e7ec894153df47319fd6d88581ee7c30e6dc8
cx1802/hello_world
/assignments/XiePeidi_assign5_part3c.py
2,558
4.125
4
""" Peidi Xie March 30th, 2019 Introduction to Programming, Section 03 Part 3c: Custom Number Range """ ''' # iterate from 1 to 1000 to test whether the iterator number is a prime number for i in range(1, 1001): # 1 is technically not a prime number if i == 1: print("1 is technically not a prime number.") else: # keep dividing the iterator number by divisors from 2 to the integer smaller than the iterator by 1 for f in range(2, i+1): if i % f == 0: # if the iterator number has a divisor greater than 1 and smaller then itself, # stop at the smallest divisor found and break the loop if f < i: break # if the iterator number only has 1 and itself as its divisors, print out that # the iterator number is a prime number else: print(i, "is a prime number!") ''' # prompt the user to enter a start number and an end number start = int(input("Start number: ")) end = int(input("End number: ")) # the start number and end number must be both positive and the start number must be smaller than the end number # if the two numbers the user supplies don't satisfy both condition, tell the user which condition is not satisfied # and ask the user to enter again until the user supplies valid data while start <= 0 or end <= 0 or start >= end: while start <= 0 or end <= 0: print("Start and end must be positive") print() start = int(input("Start number: ")) end = int(input("End number: ")) while start >= end: print("End number must be greater than start number") print() start = int(input("Start number: ")) end = int(input("End number: ")) # iterate from the start number to the end number to test whether the iterator number is a prime number print() for i in range(start, end+1): # 1 is technically not a prime number if i > 1: # keep dividing the iterator number by divisors from 2 to the integer smaller than the iterator by 1 for f in range(2, i+1): if i % f == 0: # if the iterator number has a divisor greater than 1 and smaller then itself, # stop at the smallest divisor found and break the loop if f < i: break # if the iterator number only has 1 and itself as its divisors, # print out the iterator number else: print(i)
true
a5f10c74f6a140ad75604c9defd3a44e3e0bd4f8
GunjanPande/tutions-python3
/REVISION CONTENT/3. Output/3 end in print function.py
637
4.4375
4
def main(): # below three print statements will print in three separate lines # because default end character/string is "\n" i.e. new line print("Hello") print("hi") print("Namaste") # we can change default end character/string to any thing we want # Hello, hi, Namaste\n print("Hello" , end=", ") print("hi" , end=", ") print("Namaste" , end="\n") # Hello Hi Namaste. # print("Hello", end=" ") print("Hi", end=" ") print("Namaste", end=".\n") # Date print # 5/June/2021 # print(5, end="/") print("June", end="/") print(2021) main()
false
1da87e75e533b3dd33251cc8a75c2fdd699eb236
GunjanPande/tutions-python3
/Challenges/While Loop Challenges/050.py
824
4.15625
4
""" 50 Ask the user to enter a number between 10 and 20. If they enter a value under 10, display the message “Too low” and ask them to try again. If they enter a value above 20, display the message “Too high” and ask them to try again. Keep repeating this until they enter a value that is between 10 and 20 (loop_stopping condition) and then display the message “Thank you” HINT : loop_running_condition = not(loop_stopping condition) """ def main(): num = int(input("Enter a number: ")) while not( 10 < num and num < 20 ): # HINT : loop_running_condition = not(loop_stopping condition) if( num < 10 ): print("Too low.") elif ( num > 20 ): print("Too high.") num = int(input("Enter a number: ")) print("Thank you") main()
true
032151fc2846316feeeabdda96fd724783d7b18e
GunjanPande/tutions-python3
/Challenges/Basics/005.py
404
4.28125
4
# 005 # Ask the user to enter three # numbers. Add together the first # two numbers and then multiply # this total by the third. Display the # answer as The answer is # [answer]. . def main(): num1 = int( input("Enter number 1: ") ) num2 = int( input("Enter number 2: ") ) num3 = int( input("Enter number 3: ") ) answer = (num1 + num2) * num3 print("The answer is " + str(answer)) main()
true
fa45e0bf675adaffdecdf35f3c20c315431b9104
GunjanPande/tutions-python3
/10-12. Loops/oddNo2.py
303
4.15625
4
""" Q - Print first n odd number Take value of n from user ex. if n = 3 print -> 1, 3, 5 Hint: Use odd no. formula """ def main(): n = int(input("Please enter how many odd no.s to print:")) i = 1 while( i <= n ): oddNo = 2 * i - 1 print(oddNo) i = i + 1 main()
false
048fa2b8bddcea58578490c440cc0902c4c026fc
GunjanPande/tutions-python3
/10-12. Loops/FOR LOOPS/forloop1.py
247
4.25
4
names = [] # names list n = int(input("How many names? : ")) for i in range(n): # loop will repeat n times name = input() names.append(name) # advanced for loop (for loop in combination with list) for name in names: print(name)
false
fd14e438d7cded648828192a171e18f8a38f1a95
GunjanPande/tutions-python3
/REVISION CONTENT/4. Input/1. Input.py
1,173
4.125
4
def main(): name = input("Please enter name - ") print("Name - '{}'".format(name)) # ValueError comes during when we the input provided is not of required age = int( input("Please enter age - ") ) print("Age - {}".format(age)) height = float( input("Please enter height - ") ) print("Height - {}".format(height)) # isBoy = bool( input("Are you a boy (true or false) - ") ) # WRONG WAY # 0 if ( input("Are you a boy? (yes or no) - ").lower() == "yes"): isBoy = True else: isBoy = False # 1 isBoy = False # Assume if ( input("Are you a boy? (yes or no) - ").lower() == "yes"): isBoy = True print("isBoy - {}".format(isBoy)) # 2 isBoy = input("Are you a boy? (yes or no) - ").lower() if (isBoy == "yes"): isBoy = True elif(isBoy == "no"): isBoy = False else: print("Invalid Input") isBoy = "" print("isBoy - {}".format(isBoy)) # 3 isBoy = False answer = input("Are you a boy? (yes or no) - ") if ( answer.lower() == "yes" ): isBoy = True if __name__ == "__main__" : main()
false
b2fe7b891e4f40d446d2cb784df8d5f0c5b6b342
GunjanPande/tutions-python3
/22. List Methods/main2.py
700
4.25
4
def main(): # 5. Combining items of two different lists in one single list using the + operator rishavList = ["GTA", "Notebooks", "Bicycle"] harshitList = ["Pens", "Hard disk", "Cover"] shoppingList = rishavList + harshitList print( str(shoppingList) ) # Note - when we use + operator -> what happens is we combine two already existing list to create a new single list containing items from both lists # extend() method list1 = [1, 2, 3, 4, 5 ] list2 = [6, 7, 8, 9] # if we want to add all items of some list2 to an already existing list1 print(list1) print(list2) list1.extend( list2 ) print(list1) print(list2) main()
true
f9a8a7021c76d91edb5ff3d0903a9d9ebb41e1dd
GunjanPande/tutions-python3
/10-12. Loops/wholeNos.py
275
4.21875
4
""" Print WHOLE numbers upto n. Ask value of n from user. """ def main(): print("program to print whole numbers upto n") n = int(input("Enter value of n: ")) i = 0 # whole number starts from 0 while( i <= n ): print( i ) i = i + 1 main()
true
92582e199045c37d0bf11ffc564deb37ca2f4c3e
GunjanPande/tutions-python3
/14. String Methods/StringFunctions-2.py
882
4.28125
4
def main(): name = input("enter a string: ") print(name) # harshit jaiswal # always remember, in coding, couting starts from 0 and it is called # variable_name[start_index: end_index + 1] will give a part of the complete string stored in the variable_name first_name = name[0: 7] print(first_name) # last_name = name[8 : 14] # above gives only jaiswa last_name = name[8 : ] # this will give part of whole string starting from given start index i.e. 8 upto last character print( last_name ) print( name[6: ] ) # gives part of name string from index 6 upto last character print( name[2 : 11]) # gives part of name string from index 2 upto 1 index before 11 ie. from index 2 upto index 10 # one more trick # reverse name = "Rishav" print( name[-1: :-1] ) # will return reverse of the complete string main()
true
d5e67654ccf34d7b953a87ee29c731d7c7c7e9fd
vanshika-2008/Project-97
/NumberGuess.py
616
4.25
4
import random number = random.randint(1 , 9) chances = 0 print("Number Guessing Game") print("Guess a number (between 1 to 9)") while chances<5 : guess = int(input("Enter your guess :")) if(guess == number) : print("Congratulations!! You won the game") if(guess> number) : print("Your guess is higher than", guess) if guess<number : print ("Your number is lesser than" , guess) else: print("Your guess is too high , please guess lower than", guess) chances+=1 if not chances < 5 : print("You lose ☹, the number was ",number)
true
640c540cda422daed64649da63fdf0e50c784131
bainco/bainco.github.io
/course-files/homework/hw01/turtle_programs.py
1,456
4.53125
5
from MyTurtle import * ### TURTLE CHEATSHEET ############################################### # Pretend we have a turtle named: turtle_0 # If we want turtle_0 to go forward 100 steps we just say: # turtle_0.forward(100) # If we want turtle_0 to turn left or right 90 degrees, we just say: # turtle_0.left(90) # turtle_0.right(90) # If we want to turn turtle_0 around, we'd just turn 180 degrees! # turtle_0.left(180) # If we want turtle_0 to change the color of its pen: # turtle_0.pencolor("green") ##################################################################### ### Exercise 1 - Draw a Square using turtle_1 turtle_1 = MyTurtle(x = -300, y = 200) # Your code goes here ### Exercise 2 - Draw a Green Rectangle using turtle_2 turtle_2 = MyTurtle(x = -150, y = 200) # Your code goes here ### Exercise 3 - Draw a red Equilateral Traingle using turtle_3 turtle_3 = MyTurtle(x = 0, y = 200) # Your code goes here ### Exercise 4 - Draw a House! using turtle_4 # Hint: Combine what you know from exercises 1 and 3! turtle_4 = MyTurtle() # your code goes here # P.S. You can't just paste the two solutions together. Think about which direction # your turtle is facing when it stops and starts drawing! It might help to play out # the turtle's motion yourself! ### Optional Bonus - Draw something fun! turtle_5 = MyTurtle(x = 300, y = -300) # Some ideas: a snowflake, a heptagon, a 2-D cube! # Or, you could add windows or doors to your house
false
58cfb075dbcaa11e511c92a6a5d42b336498096f
bainco/bainco.github.io
/course-files/tutorials/tutorial05/warmup/a_while_always_true.py
803
4.125
4
import time ''' A few things to note here: 1. The while loop never terminates. It will print this greeting until you cancel out of the program (Ctl+C or go the Shell menu at the top of the screen and select Interrupt Execution), and "Program terminated" will never print. 2. This is known as an infinite loop. These kinds of loops are useful for animations (or anything that you want to keep running). 3. The time.sleep(1) is important here. Without the pause, the program will execute the code as fast as it can (very fast) and use up all of your RAM (try removing the time.sleep(1) to see what happens). ''' while True: print('Hello! How are you doing today (this will go on forever)?') time.sleep(1) print('Program terminated')
true
dc67ecd32fc7e602e97675510c2d97d2cb2e184b
bainco/bainco.github.io
/course-files/homework/hw01/calculator_programs.py
329
4.21875
4
# Exercise 1: # Exercise 2: # Exercise 3: # Exercise 4: # Hint: to find the length in number of letters of a string, we can use the len function # like so: len("hello"). If we wanted to find the number of characters in a string # that's stored in a variable, we'd instead use the variable's name: len(variable)
true
32ce4bc7ed6d3c02f8c2f9a1f1fe74d56c4eb724
bainco/bainco.github.io
/course-files/lectures/lecture04/turtle_programs.py
837
4.5625
5
from MyTurtle import * ### TURTLE CHEATSHEET ############################################### # Pretend we have a turtle named: turtle_0 # If we want turtle_0 to go forward 100 steps we just say: # turtle_0.forward(100) # If we want turtle_0 to turn left or right 90 degrees, we just say: # turtle_0.left(90) # turtle_0.right(90) # If we want to turn turtle_0 around, we'd just turn 180 degrees! # turtle_0.left(180) # If we want turtle_0 to change the color of its pen: # turtle_0.pencolor("green") # If we want to make a new turtle at a specific x, y coordinate, we use the optional # arguments to the MyTurtle Function like so: # turtle_0 = MyTurtle(x = 100, y = 100) # (If you leave those out, it will default to 0, 0) ##################################################################### turtle_1 = MyTurtle(x = -300, y = 200)
true
8f4230226c46ca9ff049e2289b97df9be0604840
fmacias64/CourseraPython
/miniProject1/miniProject1.py
2,328
4.125
4
import random # Rock-paper-scissors-lizard-Spock template # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors # helper functions def name_to_number(name): # convert name to number using if/elif/else # don't forget to return the result! if(name=="rock"): return 0 elif(name=="Spock"): return 1 elif(name=="paper"): return 2 elif(name=="lizard"): return 3 else: return 4 def number_to_name(number): # convert number to a name using if/elif/else # don't forget to return the result! if(number==0): return "rock" elif(number==1): return "Spock" elif(number==2): return "paper" elif(number==3): return "lizard" else: return "scissors" def rpsls(player_choice): # print a blank line to separate consecutive games print "" # handling of invalid input if(player_choice not in ("rock","Spock","paper","lizard","scissors")): print "%s is an invalid input." % player_choice return "" # print out the message for the player's choice print "Player chooses " + player_choice # convert the player's choice to player_number using the function name_to_number() player_number = name_to_number(player_choice) # compute random guess for comp_number using random.randrange() comp_number = random.randrange(0,5) # convert comp_number to comp_choice using the function number_to_name() comp_choice = number_to_name(comp_number) # print out the message for computer's choice print "Computer chooses " + comp_choice # compute difference of comp_number and player_number modulo five difference = comp_number-player_number # use if/elif/else to determine winner, print winner message a = difference % 5 if(a==1): print "Computer wins!" elif(a==2): print "Computer wins!" elif(a==3): print "Player wins!" elif(a==4): print "Player wins!" else: print "Player and computer tie!" # test your code - LEAVE THESE CALLS IN YOUR SUBMITTED CODE rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors")
true
9499eb017ab1052f331ee3e9bef2e98b0926b5e9
MeghaSah/python_internship1
/day_4.py
681
4.28125
4
# write a prrogram to create a list of n integer values and add an tem to the list numbers = [1,2,3,4,5,6] numbers.append(7) print(numbers) #delete the item from the list numbers.remove(5) print(numbers) # storing largest number to the list largest = max(numbers) print(largest) # storing smallest number to the list smallest = min(numbers) print(smallest) # create a tuple and print the reverse of the created tuple tuple = ('a','b','c','d','e') def Reverse(tuple): new_tuple = tuple[::-1] return new_tuple print(Reverse(tuple)) # create a tuple and convert tuple into list tup = ('ram','shyam', 'hari', 'mohan', 'rahul') print(list(tup))
true
bda340062aed8861e6fb566b06c034619b3ae70f
Jonnee69/Lucky-Unicorn
/05_Lu_statement_generator.py
1,032
4.21875
4
token = input("choose a token: ") COST = 1 UNICORN = 5 ZEB_HOR = 0.5 balance = 10 # Adjust balance based on the chosen and generate feedback if token == "unicorn": # prints unicorn statement print() print("*******************************************") print("***** Congratulations! It's ${:.2f} {} ****".format(UNICORN, token)) print("*******************************************") balance+= UNICORN # wins $5 elif token == "donkey": # prints donkey statement print() print("----------------------------------------------------------") print("| Sorry. It's a {}. You did win anything this round |".format(token)) print("----------------------------------------------------------") balance -= COST # does not win anything (ie: loses $1) else: # prints donkey statement print() print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") print("< Good try. It's a {}. You won back 50c >".format(token)) balance -= ZEB_HOR # 'wins' 50c, paid $1 so loses 50c
true
2403815f758c6f4148d9e57d7dd23ce2d507451d
gabrieleliasdev/python-cev
/ex055.py
1,185
4.21875
4
""" 055 - Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos. """ """ w1 = float(input(f"Type the weight of 1ª person: Kg ")) w2 = float(input(f"Type the weight of 2ª person: Kg ")) w3 = float(input(f"Type the weight of 3ª person: Kg ")) w4 = float(input(f"Type the weight of 4ª person: Kg ")) w5 = float(input(f"Type the weight of 5ª person: Kg ")) wt = [w1, w2, w3, w4, w5] owt = sorted(wt) print(f"\nThis are the weights shown: {wt}") print(f"\nThey are in order: {owt}") print(f"\nThis is the smallest weight '{owt[0]}kg' followed by the largest '{owt[-1]}kg'\n") """ """ larg = 0 small = 0 for weigth in range(1, 6): w = float(input(f"Type the weight of {weigth}ª person: Kg ")) if weigth == 1: larg = w small = w else: if w > larg: larg = w if w < small: small = w print(f"\nThis is the smallest weight '{small}kg' followed by the largest '{larg}kg'\n") """ lst = [] for weigth in range(1, 6): w = float(input(f"Type the weight of {weigth}ª person: Kg ")) lst += [w] print(lst) print("This largest weigth is:", max(lst)) print("This smallest weigth is:", min(lst))
false
72a1c6cee1535bd01a68fae1dc905c774fc5fd26
gabrieleliasdev/python-cev
/ex037.py
752
4.125
4
"""037 - Escreva um programa que leia um número inteiro qualquer e pela para o usuário escolher qual será a base de conversão: 1) para binário 2) octal 3) hexadecimal""" n = int(input("\nType the number you want to convert:\n>>> ")) print("""\nChoose the option for conversion: [a] Convert to Binary [b] Convert to Octal [c] Convert to Hexadecimal\n""") oc = str(input(">>> ")).strip().lower() if oc == 'a': print("\nThis value {} convert to Binary becomes {}\n".format(n, bin(n)[2:])) elif oc == 'b': print("\nThis value {} convert to Octal becomes {}\n".format(n, oct(n)[2:])) elif oc == 'c': print("\nThis valou {} convert to Hexadecimal becomes {}\n".format(n, hex(n)[2:])) else: print("\nChoose one of the options above.\n")
false
fe7bf50c9a7fbde5bce12f2a10d114d978a78526
gabrieleliasdev/python-cev
/ex042.py
784
4.25
4
"""042 - Refaça o Desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: - Equilátero: todos os lados iguais. - Isóceles: dois lados iguais. - Escaleno: todos os lados diferentes.""" s = '-=-'*20 print(s) print('Analisador de Triângulos') print(s) r1 = float(input('First segment: ')) r2 = float(input('Second segment: ')) r3 = float(input('Third segment: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print(f'\nThe above segments "can" form a Triangle!\n{s}\n') if r1 == r2 == r3: print("Is Equilátero!") elif r1 == r2 or r1 == r3 or r2 == r3: print("Is Isóceles!") elif r1 != r2 != r3 != r1: print("Is Escaleno") else: print(f'\nThe above segments "cannot" form a Triangle.\n{s}\n')
false
681fba3f6d5b0595e604367258c96e98a7ac2e83
gabrieleliasdev/python-cev
/ex044.py
1,250
4.125
4
"""044 - Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: - à vista dinheiro/cheque: 10% de desconto. - à vista no cartão: 5% de desconto. - em até 2x no cartão: preço normal - 3x ou mais no cartão: 20% de juros""" v = float(input("\nInform the value of the product: R$ ")) print("\nSelect the paymente method:\n[a] Cash or Check\n[b] Cash on the Card" "\n[c] On the Card for 02 times\n[d] On the Card for 3 times or more") p = str(input(">>> ")).strip().lower() a = v - (v*10/100) b = v - (v*5/100) c = v d = v + (v*20/100) if p == 'a': print("\nProduct value: {:.2f} | Payment method: Cash or Check | Discount: 10% | Will pay: {:.2f}\n".format(v,a)) elif p == 'b': print("\nProduct value: {:.2f} | Payment method: Cash on the Card | Discount: 5% | Will pay: {:.2f}\n".format(v,b)) elif p == 'c': print("\nProduct value: {:.2f} | Paymente method: On the Card for 02 times | No discount | Will pay: {:.2f}\n".format(v,c)) elif p == 'd': print("\nProduct value: {:.2f} | Paymente method: On the Card for 3 times or more | Increase tax 20% | Will pay: {:.2f}\n".format(v,d)) else: print("\nChoose one of the options. Try again!\n")
false
3a0756c16a5479ac6e722d4441ba8d544a327571
gabrieleliasdev/python-cev
/ex085.py
578
4.21875
4
""" Exercício Python 085 Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. """ lst = [[],[]] for i in range(7): i = int(input(f"Type {i+1}ª value » ")) if i % 2 == 0: lst[0].append(i) if i % 2 == 1: lst[1].append(i) print(f"\nFollows even values in ascending order » {sorted(lst[0])}") print(f"\nFollows ood values in ascending order » {sorted(lst[1])}")
false
e200573fe5c9ac5266e5f16453d3468fe1e103f0
ZhaoFelix/Python3_Tutorial
/02.py
1,099
4.125
4
# coding=utf-8 # 类 class Student(object): #定义类属性 name = 'Felix' age = 23 #变量名两个下划线开头,定义私有属性,这样在类外部无法直接进行访问,类的私有方法也无法访问 __sex = 0 #定义构造方法 def __init__(self,name,age,sex): self.name = name self.age = age self.__sex = sex #类方法 def get_sex(self): return self.__sex def set_sex(self,sex): self.__sex = sex #调用 if __name__ == '__main__': student = Student('Felix',12,1) #实例化v成员变量 print(student.age,student.name) #单继承 class TopStudent(Student): top_id = 1024 def __init__(self,name,age,sex,top_id): #调用父类的构造方法 super(TopStudent,self).__init__(name,age,sex) self.top_id = top_id #重写父类方法 # def set_sex(self,sex): # self.__sex = sex+1 # print('重写父类的方法') #调用 if __name__ == '__main__': topStudent = TopStudent('Felix1',45,0,2048) print(topStudent.set_sex(1))
false
65dd78967adb237925b4c3f68f502fb610ed1318
alifa-ara-heya/My-Journey-With-Python
/day_02/Python_variables.py
1,672
4.3125
4
#Day_2: July/29/2020 #In the name 0f Allah.. #Me: Alifa Ara Heya Name = "Alifa Ara Heya" Year = 2020 Country = "Bangladesh" Identity = "Muslim" print(Name) print(Country) print(Year) print(Identity) print("My name is", Name) #Calculating and printing the number of days, weeks, and months in 27 years: days_in_27_years = 365 * 27 months_in_27_years = 12 * 27 weeks_in_27_years = (365 / 7) * 27 print("Days in 27 years: " , days_in_27_years) # Here we can't use plus to concatenate because our variable is integer. String and integer can't be concatenated. print("Months in 27 years: ", months_in_27_years) print("Weeks in 27 years: ", int(weeks_in_27_years)) #Calculating and printing the area of a circle with a radius of 5 units: pi= 3.1417 radius= 5 print("Area of a circle:", pi * radius ** 2) #or we can use the pow() function to do this exactly: print("Area of a circle:", pi * pow(radius,2)) #declaring some more variables: skills= ['hTML', 'CSS', 'Python'] person_info = { 'firstname' : 'Alifa', 'lastname' : 'Hiya', 'country' : 'Bangladesh', 'city' : 'Dhaka' } print(type(person_info)) print(skills) print(person_info) #type casting: #str to list: firstname = 'Alifa' print("First Name:", list(firstname)) # output: ['A', 'l', 'i', 'f', 'a'] #or, firstname = list(firstname) print("First name in list:", firstname) # Declaring variables in one line: name, country, city, age = "Fatema", "Bangladesh", "Rajshahi", 25 print(name) # Fatema print(country) # Bangladesh print(city) # Rajshahi print(age) # 25
true
73465c62f71a8a0a5b83eab5bba074212aa322c3
alifa-ara-heya/My-Journey-With-Python
/day_14/exercise7.py
1,011
4.28125
4
# Day_14: August/10/2020 # In the name 0f Allah.. # Me: Alifa # From: Book : Python for everybody # Chapter:4 (Functions) # Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table: # Score Grade # >= 0.9 A # >= 0.8 B # >= 0.7 C # >= 0.6 D # < 0.6 F # Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string. inp_score = input("Enter score between 0.0 to 1.0: ") try: score = float(inp_score) except: print("Please enter score between the range 0.0 and 1.0") quit() def computegrade(score): if score >= 0.9: print("A") elif score >= 0.8: print("B") elif score >= 0.7: print("C") elif score >= 0.6: print("D") elif score < 0.6: print("F") computegrade(0.85) # B
true
38d16d0908fcbcde5f9aa9a8131fe3691efcee40
alifa-ara-heya/My-Journey-With-Python
/day_33/reg_expressions.py
1,885
4.59375
5
# bismillah # Book: python for everybody (chapter: 11) # Regular Expressions # Search for lines that contain 'From': import re hand = open('.\day_28\mbox-short.txt') for line in hand: line = line.rstrip() if re.search('From:', line): print(line) '''output: From: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: zqian@umich.edu From: rjlowe@iupui.edu From: zqian@umich.edu From: rjlowe@iupui.edu From: cwen@iupui.edu From: cwen@iupui.edu From: gsilver@umich.edu From: gsilver@umich.edu From: zqian@umich.edu From: gsilver@umich.edu From: wagnermr@iupui.edu From: zqian@umich.edu From: antranig@caret.cam.ac.uk From: gopal.ramasammycook@gmail.com From: david.horwitz@uct.ac.za From: david.horwitz@uct.ac.za From: david.horwitz@uct.ac.za From: david.horwitz@uct.ac.za From: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: louis@media.berkeley.edu From: ray@media.berkeley.edu From: cwen@iupui.edu From: cwen@iupui.edu From: cwen@iupui.edu''' # the caret character is used in regular expressions to match “the beginning” of a line. We could change our program to only match lines where “From:” was at the beginning of the line as follows: import re hand = open('.\day_28\mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^From:', line): print(line) '''same output''' # Character matching in regular expressions: import re hand = open('.\day_28\mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^F..m:', line): print(line) '''same output''' # Search for lines that start with From and have an at sign: import re hand = open('.\day_28\mbox-short.txt') for line in hand: line = line.rstrip() if re.search('6From:.+@', line): print(line) '''same output''' # Extracting data using regular expressions: import re s = 'A message from csev@umich.edu to cwen@iupui.edu about meeting @2PM' lst = re.findall('\S+@\S+', s) print(lst) # ['csev@umich.edu', 'cwen@iupui.edu'] # Search for lines that have an at sign between characters import re hand = open('.\day_28\mbox-short.txt') for line in hand: line = line.rstrip() x = re.findall('\S+@\S+', line) if len(x) > 0: print(x)
false
9d3f67cf1ab645c4d5744187c8d53ac6f84df0a6
alifa-ara-heya/My-Journey-With-Python
/day_03/formatting_strings.py
1,864
4.375
4
#Topic: Formatting strings and processing user input & String interpolation: #Day_2: July/30/2020 #In the name 0f Allah.. #Me: Alifa Ara Heya print("Nikita is 24 years old.") print("{} is {} years old".format("John", 24)) print("My name is {}.".format("Alifa")) output="{} is {} years old, and {} works as a {}." #variable print(output.format("John", 24, "John", "web developer")) #or, string_example = "{0} is {1} years old, and {0} works as a {2}." #1st value will always be 0. print(string_example.format("Nikita", 24, "web developer")) #The values inside .foramt is called placeholder. #or, example = "{name} is {age} years old, and {name} works as an {job}." #placeholder and variable print(example.format(name = "Alex", age = 40, job = "engineer")) #or, name= "Jim" age= 26 #Concatenation print(name,"is", age, "years old.") #Output: Jim is 26 years old. #or, name= "Karim" print(name, "is 30 years old.") #or, name3= "Amina" country= "Syria" #Output: Amina lives in Syria. print("{} lives in {}.".format(name3, country)) #variable and string interpolation. #f-string syntax: name4 = "Muhammad" age4 = 30 print(f"{name4} is {age4} years old.") #f-string ব্যবহার করার কারণে আমরা সেকেন্ড ব্র্যাকেটের {curly braces} মধ্যেই যা ইচ্ছা লিখতে পারছি। #Let's calculate Muhammad's age in months by f- string: print(f"{name4} is {age4 * 12} months old.") #Output: Muhammad is 360 months old.
true
4fe2d1fece511b56dc3851f01a2119b4b7575ac7
alifa-ara-heya/My-Journey-With-Python
/day_14/exercise6.py
1,372
4.34375
4
# Day_14: August/10/2020 # In the name 0f Allah.. # Me: Alifa # From: Book : Python for everybody # Chapter:4 (Functions) # Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly. # Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters (hours and rate). The output should be look like this: # Enter Hours: 45 # Enter Rate: 10 # Pay: 475.0 hours = input("Enter hours please: ") rate = input("Enter rate please: ") float_hours = float(hours) float_rate = float(rate) def computepay(hours, rate): multiplied = hours * rate return multiplied regular_pay = computepay(40, float_rate) if float_hours > 40: extra_rate = (float_hours - 40) * (float_rate * 1.5) overtime_pay = regular_pay + extra_rate print("Pay: ", overtime_pay) # instructor's hints: def computepay2(h,r): return 42.37 hrs = input("Enter Hours:") p = computepay2(10,20) print("Pay",p)
true
1c6b11c96f7f9afb0f6ce92883e0433e78f37042
alifa-ara-heya/My-Journey-With-Python
/day_13/coditional_execution.py
2,354
4.53125
5
# Day_13: August/09/2020 # In the name 0f Allah.. # Me: Alifa # From: Book : Python for everybody # chapter: 3 # Conditional operator: print("x" == "y") # False n = 18 print(n % 2 == 0 or n % 3 == 0) # True (the number is divisible by both 2 and 3) x = 4 y = 5 print(x > y) # False print(not x > y) # True print(17 and True) # True x = 4 if x > 0: print("x is positive.") # x is positive. if x < 0: pass # need to handle negative values. # Occasionally, it is useful to have a body with no statements (usually as a place holder for code you haven’t written yet). # In that case, you can use the pass statement, which does nothing. x = 3 if x < 10: print('small') # Alternative execution: if x % 2 == 0: print("x is even.") else: print("x is odd.") # x is odd. # Chained conditionals: x = 9 y = 8 if x < y: print("x is less than y.") elif x > y: print("x is greater than y.") else: print("x is equal to y.") # Nested conditionals: # One conditional can also be nested within another. We could have written the three-branch example like this: if x == y: print('x and y are equal.') else: if x < y: print("x is less than y.") else: print("x is greater than y.") # Nested if statements: # it is good idea to avoid nested conditionals if I can. if 0 < x: if x < 10: print("x is a positive single digit number.") # or, if 0 < x and x < 10: print("x is a positive single digit number.") # Debugging: Be aware of indentation error. x = 5 #y = 2 #print(y) # Traceback because of indentation error. # loop: for i in range(5): print(i) if i > 2: print('Bigger than 2.') print("done with i =", i, ".") print('All done.') # try except: astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print('First', istr) # First -1 astr = '123' try: istr = int(astr) except: istr = -1 print("Second", istr) # Second 123 # Sample try and except: astr = "bob" try: print("hello") istr = int(astr) print("there") except: istr = -1 print("done", istr) # done -1 # try except: rawstr = input("Enter a number: ") try: ival = int(rawstr) except: ival = -1 if ival > 0: print("Nice work") else: print("Not a number")
true
ebfe1976b54c596ca0e4a8355e26f8903e7d42a0
alifa-ara-heya/My-Journey-With-Python
/day_13/exercise 3.1.py
780
4.46875
4
# 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly. hours = input("Enter hours please: ") rate = input("Enter rate please: ") float_hours = float(hours) float_rate = float(rate) regular_pay = 40 * float_rate if float_hours > 40: extra_rate = (float_hours - 40) * float_rate * 1.5 overtime_pay = regular_pay + extra_rate print("Pay: ", overtime_pay)
true
439c26ee1127ae5be9cb49356e83e1456f23d71c
Royalsbachl9/Web-page
/dictionary_attack.py
726
4.125
4
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dictionary.txt","r") print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password #NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords test_password = input("Type in a trial password: ") strippedPassword = test_password.strip() # ^ takes out any eaxtra spaces noFoundPWD = True for line in f: # print (line) if strippedPassword == line.strip(): foundPWD = False print("Sorry, try agin with a new password!") break if nofoundPWD: print("Great password")
true
e0d22fcafd6e0c8ede004ca82ae7ea77165ebc67
Vignesh77/python-learning
/chapter3/src/list_add.py
607
4.34375
4
""" @file :list_add.py @brief :Create the list and add the elements. @author :vignesh """ list_len = input("Enter the length of list :") input_list =[ ] print "Enter the values to list" for index in range(list_len) : list1 = input("") input_list.append(list1) print input_list print "Enter do u want to add values in list" print "yes or no" usr_opt =raw_input("") if usr_opt == 'yes' : print "Enter the index and value" index =input("") value =input("") if index > len(input_list) : print "Invalid option" input_list.insert(index,value) print input_list
true
d3b86b7af656f2fcbf08d7184c04bd0abe1fda81
Daksh/CSE202_DBMS-Project
/pythonConnection.py
1,233
4.34375
4
# Proof of Concept # A sample script to show how to use Python with MySQL import mysql.connector as mysql from os import system, name def clear(): if name == 'nt': # for windows system('cls') else: # for mac and linux system('clear') def createDB(): db = mysql.connect( host = "localhost", user = "root" ) # Cursor is used to execute MySQL Commands cursor = db.cursor() cursor.execute("SHOW DATABASES") databases = cursor.fetchall() if [item for item in databases if 'college' in item] == []: cursor.execute("CREATE DATABASE college") print('"college" Database successfully created :)') else: print('"college" Database already exists!') input("Press Enter to continue...") def createTables(): pass def addData(): pass if __name__ == '__main__': choice = 1 while choice != 0: clear() print('1. Create the "college" Database') print('2. Create all the Relations(Tables)') print('3. Add Data to the Tables') print('0. Exit') print('Enter your choice: ',end='') choice = int(input()) print() if choice == 1: createDB() elif choice == 2: createTables() elif choice == 3: addData() elif choice == 0: break else: print('Please enter a valid choice! :)')
true
b769423ba1874f1202146751959087287fcc8e07
valdergallo/pyschool_solutions
/Tuples/remove_common_elements.py
778
4.40625
4
""" Remove Common Elements ====================== Write a function removeCommonElements(t1, t2) that takes in 2 tuples as arguments and returns a sorted tuple containing elements that are not found in both tuples. Examples >>> removeCommonElements((1,2,3,4), (3,4,5,6)) (1, 2, 5, 6) >>> removeCommonElements(('b','a','c','d'), ('a','b','c')) ('d',) >>> removeCommonElements(('a','b','c'), ('a','b','c')) () >>> removeCommonElements(('a','b'), ('c', 'd')) ('a', 'b', 'c', 'd') >>> removeCommonElements(('b','a','d','c'), ('a','b')) ('c', 'd') """ def removeCommonElements(t1, t2): uncommon = () commons = tuple(set(t1) & set(t2)) all_itens = sorted(t1 + t2) for i in all_itens: if i not in commons: uncommon += (i,) return uncommon
true
63d11c0e40b26c71ca55cbac209df9f89c3ee31d
farhanjaved47/python
/Generators/FibonacciSequenceGenerator.py
649
4.21875
4
""" Farhan Javed farhan.javed47@gmail.com 12/24/2019 Generate a Fibonacci sequence using Python generators """ def fibonacci(n): print('In Fibonacci Generator') if n == 1: yield 1 if n == 2: yield 1 yield 1 if n >= 3: base_number = 1 yield base_number next_number = 1 yield next_number for i in range(n-2): old_next_number = next_number next_number = next_number + base_number base_number = old_next_number yield next_number def main(): fibonacciObject = fibonacci(10) print(list(fibonacciObject)) if __name__ == '__main__':main()
false
8ebb9a939d3b9070c959fd0af7ce6e7e9c2bf723
ramanuj760/PythonProject
/oops cl1.py
508
4.125
4
class A: #print("this is a parent class") #d={"name":"ram"} "this is a sample string" def __init__(self): print("inside construcor") def display(self): print("inside method") class B(A): pass #a is an instance of class A. A() is an object of class A #calling a default constructor #b=B() a=A() print(a.__doc__)# print the string of class which are not in print print(A.__dict__)# it gives all the details of class print(A.__module__) print(A.__name__) a.display()
true
297845ca1a3fc0719816d32e0aa30a324e404299
Aguniec/Beginners_projects
/Fibonacci.py
306
4.21875
4
""" Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. """ number = int(input("Give me a number")) list_of_numbers = [0, 1] for i in range(0, number): a = list_of_numbers[-1] + list_of_numbers[-2] list_of_numbers.append(a) print(list_of_numbers)
true
28f439a0a623ffd4654f51d37a9fe5d5abc84f0f
Aguniec/Beginners_projects
/Reverse Word Order.py
376
4.21875
4
""" Write a program that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. """ def reverse_order(string): words_to_array = string.split() reverse_words_order = a[::-1] return " ".join(reverse_words_order) string = input("Give me a word") print(reverse_order(string))
true
ba0bf66c366c1a195984487975f8ac734263fe52
Prones94/Leet-Code
/vowel_removal.py
2,534
4.25
4
# 1. Remove Vowels From String ''' 1. Restate Problem - Question is asking if given a string, remove all the vowels from that string 'a,e,i,o,u' and then return the string without the vowels 2. Ask Clarifying Questions - How large is the string? - Is there other data types as well besides the string? - If there is multiple vowels within the string, do I remove all of them? - Will the string only contain just lowercase letters? All uppercase? A mixture of both? 3. State Assumptions - Assume the string given is all lowercase letters - The given string does not contain any other data types - For now I can assume the string is smaller than 1000 letters - Most likely an O(n) solution, it doesn't seem that we need to have multiple for loops 4. Brainstorm Solutions - Easiest way would be a for loop, and look for all occurrences of the vowels, then join the string after - Make a temp variable that holds the vowels, then push the vowels into the array once found - Replace all the vowels with an empty string. then return S 5. Think Out Loud - Doesn't seem that we need to think about space complexity, this is more centered around how fast the code outputs a result 6. Explain Rationale 7. Discuss Tradeoffs 8. Suggest Improvements Code Below! ''' class Solution: # Brute Force, using replace() function def removeVowels(self, S: str) -> str: ''' Here I'm using the built-in replace function for a string, which will replace all instances of vowels with an empty string one by one. This will be O(n) ''' S = S.replace("e", "") S = S.replace("a", "") S = S.replace("i", "") S = S.replace("o", "") S = S.replace("u", "") return S # Easier solution, def removeVowels2(self, S: str) -> str: ''' Using an object to hold and then checking if the string contains the vowels object ''' vowel_set = set('aeiou') # Created a new set to hold the vowels string = "" # This will be used to hold the string without the vowels for character in S: # Created index named character to use in for loop if character not in vowel_set: # Checks if each string character is not in the vowel set string += character # If not found, add this character to the string return string # returns the string
true
20124716905e7280df81672bdfe4b95187a57db6
Anubis84/BeginningPythonExercises
/chapter6/py_chapter6/src/chapter6_examples.py
808
4.53125
5
''' Created on Nov 21, 2011 This file shows some examples of how to use the classes presented in this chapter. @author: flindt ''' # import the classes from Ch6_classes import Omelet,Fridge # making an Omelet # Or in python speak: Instatiating an object of the class "Omelet" o1 = Omelet() print( o1 ) print( o1.get_kind() ) # one more o2 = Omelet() print( o2 ) print( o2.get_kind() ) # we need a fridge to get ingredients from f1 = Fridge() print( f1 ) # try to get ingredients from fridge o1.get_ingredients(f1) # try to make the omelet # this wont work since the fridge is empty # o1.mix() # make a new fridge with food in f2 = Fridge( {"cheese":5, "milk":4, "eggs":12}) print( f2 ) # now we can make an omelet o1.get_ingredients(f2) o1.mix() o1.make() print( o1 ) print( o1.cooked )
true
8bcdf622949e650a300e33433de3edfbafdfbebd
jdotjdot/Coding-Fun
/programmingchallenge2.py
2,683
4.1875
4
def __init__(): print('''Programming-Challenge-2 J.J. Fliegelman At least starting off with this now, this strikes me as a a textbook example of the knapsack problem. I'll start with that on a smaller scale, and then see how that scales when we go up to 70 users. As we scale to 70 people, it becomes clear quickly that those with bigger balances and with accounts at banks with smaller rebates are going to have to wait longer to have their accounts settled. When adding complexity to this problem to take into account ''') ###Do some actual testing, testing with both 70 people for that night ### as well as doing that across many nights, with new account holders from operator import truediv class User: def __init__(self, balance, bank): '''balance -> balance input bank -> bank input rebate(bank) -> returns the fixed rebate provided by that bank''' self.balance = balance self.bank = bank self.__rebate(bank) def __rebate(self, bank): if bank == 'BofA': self.rebate = 2.32 elif bank == 'WFC': self.rebate = .73 elif bank == 'Chase': self.rebate = 2.01 elif bank == 'M&T': self.rebate = .50 elif bank == 'BB&T': self.rebate = 1.41 elif bank == 'First National': self.rebate = .79 elif bank == 'PNC': self.rebate = .48 elif bank == 'HSBC': self.rebate = .38 elif bank == 'Bank of the West': self.rebate = 1.33 else: raise ValueError def rebate_per_balance(self): return truediv(self.rebate, self.balance) # truediv used for Python 2.7 compatibility def InputDataSet__(): return [(153.00, 'BofA'), (53.00, 'WFC'), (191.00, 'Chase'), (66.05, 'M&T'), (239.99, 'BB&T'), (137.55, 'First National'), (145.78, 'PNC'), (249.43, 'HSBC'), (43.01, 'Bank of the West')] def UsersetMaker(userlist): return [User(x[0], x[1]) for x in userlist] def LoadKnapsack(userlist, maxsettlement): userlist.sort(key = lambda x: x.rebate_per_balance(), reverse = True) knapsack = [] while sum([x.balance for x in knapsack]) <= maxsettlement and \ len(userlist) > 0: if userlist[0].balance <= maxsettlement - \ sum([x.balance for x in knapsack]): knapsack.append(userlist.pop(0)) else: userlist=userlist[1:] return knapsack def Main(): userlist = UsersetMaker(InputDataSet__()) return LoadKnapsack(userlist, 645) pass if __name__ == "__main__": Main()
true
d6b4a5b0e05d8305f318b22958eba3dc58b3ff5b
bestcourses-ai/math-through-simulation
/monty-hall.py
1,019
4.34375
4
''' https://en.wikipedia.org/wiki/Monty_Hall_problem Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? ''' import numpy as np def monty_hall(switching=True, n_games=10**7): # We can use a Bernoulli distribution (Binomial with 1 trial) to generate a 1 or 0 that represents # whether or not the prize door was selected as the first guess. prize_door_selected = np.random.binomial(1, 1/3, size=n_games) if switching: # When switching you win if the prize door was not your first selection. return np.mean(np.logical_not(prize_door_selected)) else: return np.mean(prize_door_selected) print(monty_hall(switching=True)) # ~.666 print(monty_hall(switching=False)) # ~.333
true
838819204e66a2e58e3a602e0db827d5120c24ed
bestcourses-ai/math-through-simulation
/hht-or-htt.py
836
4.25
4
''' You're given a fair coin. You keep flipping the coin, keeping tracking of the last three flips. For example, if your first three flips are T-H-T, and then you flip an H, your last three flips are now H-T-H. You keep flipping the coin until the sequence Heads Heads Tails (HHT) or Heads Tails Tails (HTT) appears. Is one more likely to appear first? If so, which one and with what probability? ''' import random simulations = 10**5 SIDES = ('H', 'T') wins = 0 for _ in range(simulations): last_3 = [random.choice(SIDES) for _ in range(3)] while last_3 not in (['H', 'H', 'T'], ['H', 'T', 'T']): new_flip = random.choice(SIDES) last_3[0], last_3[1], last_3[2] = last_3[1], last_3[2], new_flip if last_3 == ['H', 'H', 'T']: wins += 1 win_proportion = wins/simulations print(win_proportion)
true
a2a6008f7c2d7b189bbea9f694f4d7cad454ca0d
rapenumaka/pyhton-cory
/Strings/python_strings.py
2,310
4.4375
4
""" Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context". When a function, etc., finishes execution, the namespace is dropped. The variables are dropped. Plus there's a global namespace that's used if the name isn't in the local namespace. Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace. Variables are generally created only in a local namespace. The global and nonlocal statements can create variables in other than the local namespace. """ ## Printing a message on console print("Hello message") ## Create a string variable ### To reverse the String name = "iphone" print(name[::-1]) ## enohpi message = " Hello, there " print(message) quotes = """Shop keeper said " it was Keren's order" """ print(quotes) ## TO ACCESS THE CHARACTER OF THE MESSAGE , using the index ## If you access the index that doesnt exist is word = 'Hello World' print(word[0]) print(word[2]) print("++++++++++++++++++++++++++++++++++++++++++") for letter in word: print(letter) print() print("++++++++++++++++++++++++++++++++++++++++++") ## The range of word print(word[0:5]) ## Hello print(word[6:11]) ## World ### Converter to lower print(word.lower()) ## To lower print(word.upper()) ## To upper print(word.lower().count('hello')) ## 1 print(word.lower().count('l')) ## 1 ## Replace the word .. universe = "Hello Universe" replace1 = universe.replace("Universe","GalAXY") print(universe) print(replace1) ######## Using the formated Strin greet= 'Namaste' my_name='Arvind' my_message = '{}.{}. Welcome'.format(greet,my_name) print(my_message) ##Using the f strings , only available in 3.6+ ## Adding the variables directly using the placeholders greeting = 'Hello' name = 'Micheal' message = f'{greeting},{name.upper()}. Welcome' print(message) #### TO see all the methods accessible to that variables print(dir(message)) ### To get the help on string class print(help(str)) ### To get the help on string lower print(help(str.lower))
true
e33352708de4d7a14e320021cc983a02f00561cc
yang15/integrate
/integrate/store/order.py
862
4.46875
4
""" Example introduction to OOP in Python """ class Item(object): # count = 0 # static variable def __init__(self, name, num_items, unit_price): self.name = name self.num_items = num_items self.unit_price = unit_price print ('Hello world OOP') # Item.count += 1 def total(self): """ Calculate the totla of the Item""" return self.num_items * self.unit_price class Order(object): """ Order of multiple items """ def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) # O(N) complexity very slow for numpy def remove_item(self, item): self.items.remove(item) def order_total(self): summ = 0 for item in self.items: summ += item.total() return summ
true
e336b79128e8b59a036545dade31c816a1e19f42
lukaa12/ALHE_project
/src/BestFirst.py
2,416
4.25
4
import Graph from Path import Path import datetime class BestFirst: """Class representing Best First algorithm It returns a path depending on which country has the highest number of cases on the next day""" def __init__(self, starting_country, starting_date, alg_graph, goal_function): """Initializes BestFirst Algorithm object You specify the country and date you start with and a graph to work with""" self.path = Path(starting_country, starting_date) self.graph = alg_graph self.goal_function = goal_function def finding_path(self): """Main function to find a path according to BestFirst algorithm It returns a path object""" start_country, start_date = self.path.countries[0], self.path.start_date stats = self.graph.get_stats(start_country) # Here is a country which has latest data last_date = datetime.date(stats[0, 2], stats[0, 1], stats[0, 0]) current_country_neighbors = self.graph.get_neighbours(start_country) current_country, current_date = start_country, start_date while current_date != last_date: current_country = self.choose_neighbor_with_max_cases(current_country_neighbors) current_country_neighbors = self.graph.get_neighbours(current_country) current_date += datetime.timedelta(days=1) self.path.add(current_country) self.path.eval(self.graph, self.goal_function) def choose_neighbor_with_max_cases(self, countries_list=None): """Function which chooses the best country to go to next It looks for the biggest number of cases from countries list""" countries_list = countries_list if countries_list else [] try: if not countries_list: raise Exception except Exception as e: print("There are no neighbors to choose from: {0}".format(e)) max_cases = -1 country_with_max_cases = '' for country in countries_list: if self.path.get_profit(self.graph, country, self.goal_function) > max_cases: max_cases = self.path.get_profit(self.graph, country, self.goal_function) country_with_max_cases = country return country_with_max_cases def work(self): """Method which initializes every method essential to find a path""" self.finding_path()
true
7309a377af0802fee1b441108e9bd1768e0044ba
Athenian-ComputerScience-Fall2020/mad-libs-eskinders17
/my_code.py
1,164
4.15625
4
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # name = input("Enter your name: ") town = input("Enter a name of a town: ") feeling = input("Enter how are you feeling now. Happy, sad or bored: ") trip = input("Enter a place you want to visit: ") friend = input("Enter the name of your friend: ") weeks = input("Enter a number: ") birthday = input("When is your birthday: ") cake = input("What is your favorite cake flavour: ") print("Once upon a time a kid named " + name + " lived in a town called " + town + "." ) print("He/she was very " + feeling + " So he/she planned a trip to " + trip + "," + " He/she invited his/her beloved friend " + friend ) print(friend + " and " + name + " enjoyed this trip together for the next " + weeks + " weeks.") print("After " + name + " got back home on " + birthday + ". " + friend + " and other friends throwed him/her a suprise party.") print("They baked him his/her favourite " + cake + " cake. " + "After they finished eating, " + name + " told everyone about his/her trip to " + trip + ".") print("Everone had a good time, that " + birthday + " was a day to remember.")
true
daeaba5d4388308be9aa532cc91b1d8efa32b6b7
Pocom/Programming_Ex
/9_PalindromeNumber/t_1.py
831
4.375
4
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. """ class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False elif x == 0: return True else: str_x = str(x) reversed_str_x = '' for i in range(len(str_x)-1, -1, -1): # for .len() to 0 reversed_str_x += str_x[i] if int(reversed_str_x) == x: return True else: return False # testing t = Solution() print(t.isPalindrome(12321))
true
31fc463b4b6ddf773f3db7ca30d431184562f711
tofritz/example-work
/practice-problems/reddit-dailyprogramming/yahtzee.py
1,614
4.25
4
# The game of Yahtzee is played by rolling five 6-sided dice, and scoring the results in a number of ways. # You are given a Yahtzee dice roll, represented as a sorted list of 5 integers, each of which is between 1 and 6 inclusive. # Your task is to find the maximum possible score for this roll in the upper section of the Yahtzee score card. Here's what that means. # For the purpose of this challenge, the upper section of Yahtzee gives you six possible ways to score a roll. # 1 times the number of 1's in the roll, 2 times the number of 2's, 3 times the number of 3's, and so on up to 6 times the number of 6's. # For instance, consider the roll [2, 3, 5, 5, 6]. If you scored this as 1's, the score would be 0, since there are no 1's in the roll. # If you scored it as 2's, the score would be 2, since there's one 2 in the roll. # Scoring the roll in each of the six ways gives you the six possible scores: 0 2 3 0 10 6 # The maximum here is 10 (2x5), so your result should be 10. ''' rolls = [2, 3, 5, 5, 6] counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} for roll in rolls: for number in counts: if number == roll: counts[number] += roll print counts ''' lst = [2, 3, 5, 5, 6, 800, 200, 200, 200, 200, 200, 300, 300] def yahtzee(rolls): counts = dict.fromkeys(rolls, 0) for roll in rolls: for key in counts: if key == roll: counts[key] += roll values = list(counts.values()) return max(values) print(yahtzee(lst)) def onelineyahtzee(lst): return max([lst.count(x) * x for x in lst]) print(onelineyahtzee(lst))
true
4ab26eb65f520448e489c6707fc46fd16c7e6ecd
venkateshchrl/python-practice
/exercises/stringlists.py
269
4.25
4
def reverse(word): revStr = '' for ch in range(len(word)): revStr += word[len(word)-1-ch] return revStr str = input("Enter a word: ") revStr = str[::-1] if revStr == str: print("This is a Palindrome") else: print("This is NOT a Palindrome")
true
c44cbe7889a04f24d2b8f0df6d435957cb78b27b
GreenDevil/geekbrains_python_algorithms
/les_2/task_2/les_2_task_2.py
575
4.28125
4
# 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, # в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). number = int(input("Введите натуральное число:")) even_num = 0 odd_num = 0 while number > 0: if number % 2 == 0: even_num += 1 else: odd_num += 1 number = number // 10 print(f"Четных чисел - {even_num}, Нечетных чисел - {odd_num}")
false
7958bb9a2065fafa59e99133a7df9008079f6e95
JavaRod/SP_Online_PY210
/students/Tianx/Lesson8/circle.py
849
4.5625
5
# ------------------------------------------------------------------------# # !/usr/bin/env python3 # Title: Circle.py # Desc: Create a class that represents a simple circle # Tian Xie, 2020-05-11, Created File # ------------------------------------------------------------------------# import math class Circle(object): """ A Circle object. """ def __init__(self, radius): self.radius = radius def __str__(self): return f'The radius is {self.radius}' def __repr__(self): return f'Circle({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 * self.radius @classmethod def from_diameter(cls, diameter): self = cls() self.radius = diameter / 2 return self
true
7ce9d86fec01c6c36c6d777bc6888908cfd6b54a
rajeshsvv/Lenovo_Back
/1 PYTHON/6 MOSH/31_35_Dictionaries.py
2,172
4.1875
4
# 31 Dictionaries 2:18:21 # store info in key value pairs """ customer={ "name":"John", "age":30, "is_verified":True } print(customer["age"]) # print(customer["birthdate"]) #keyerror does not exist # print(customer["Name"]) print(customer.get("Name",None)) customer["name"]="Michael" print(customer["name"]) customer["birthdate"]="Jan 1 1990" print(customer["birthdate"]) """ # program on dictionary enter numbers it converts into words k phone=input("Enter numbers:") digit_mapping={ "1":"One", "2":"Two", "3":"Threee", "4":"Four", "5":"Five" } output="" for ch in phone: output+=digit_mapping.get(ch,"!")+" " print(output) # 32 Emoji Converter(https://unicode.org/emoji/charts/full-emoji-list.html) 2:26:21 message=input(">") word=message.split(" ") # print(words) # Hi Dear o/p: ['Hi', 'Dear'] emojis={ ":)":"\U0001F602", ":(":"\U0001F603" } output="" for word in word: output+=emojis.get(word,word)+" " print(output) # 33 FUNCTIONS 2:30:31 """ def greet_user(): print("Hi") print("Greet Message") print("Start") # greet_user # print(greet_user) # print(greet_user()) greet_user() print("Finish") """ # 34 PARAMETERS [passing parameters to functions] ''' def greet_user(name): # name="John" print(f"Hi {name}") print("Greet Message") print("Start") # greet_user # print(greet_user) # print(greet_user()) greet_user("Shalini") greet_user("Ravindra") print("Finish") ''' ''' def greet_users(first_name,last_name): print(f"Hello {first_name} {last_name} !") print("Welcome to India") print("start") greet_users("John","Michael") print("End") ''' # 35 Keyword Arguments 2:39:24 [keyword argument should come after positional arguments remember this] ''' def greet_users(first_name,last_name): print(f"Hello {first_name} {last_name} !") print("Welcome to India") ''' print("start") # greet_users(last_name="John","Michael") print("End") # keywords example=(50,5,0.1) No one can understand which value is for which key # keywords example=(total=50,shipping=5,discount=.1)
false
ec3aac36e8e11d4e5da44a56e9c53588b3ab6877
rajeshsvv/Lenovo_Back
/1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/5_Guru(regex and unit test logging here)/regex.py
1,919
4.65625
5
print("Hello world") ''' Match Function: This method is used to test whether a regular expression matches a specific string in Python. The re.match(). The function returns 'none' of the pattern doesn't match or includes additional information about which part of the string the match was found. syntax: re.match (pattern, string, flags=0) Here, all the parts are explained below: match(): is a method pattern: this is the regular expression that uses meta-characters to describe what strings can be matched. string: is used to search & match the pattern at the string's initiation. flags: programmers can identify different flags using bitwise operator '|' (OR) In the below example, the pattern uses meta-character to describe what strings it can match. Here '\w' means word-character & + (plus) symbol denotes one-or-more. ''' # import re # list=["mouse","cat","dog","no-match","peacock","insects"] # for elements in list: # m=re.match("cat",elements) # # if m: # print(m) # else: # print("nothing") """ Search Function: It works in a different manner than that of a match. Though both of them uses pattern; but 'search' attempts this at all possible starting points in the string. It scans through the input string and tries to match at any location. syntax: re.search( pattern, strings, flags=0) """ # import re # value="cyberdyne" # # g=re.search("(dy.*)",value) # # if g: # print("search:",g.group(0)) # s=re.match("(vi.*)",value) # # if s: # print("match:",m.group(1)) # Split function: ''' The re.split() accepts a pattern that specifies the delimiter. Using this, we can match pattern & separate text data. split()" is also available directly on a string & handles no regular expression. Program to show how to use split(): ''' import re value="two 2 four 4 six 6" res=re.split("\D+",value) print(dir(re)) for elements in res: print(elements)
true
063fc481e2df9783a23b39a2a3ae7b57f2023b1f
rajeshsvv/Lenovo_Back
/1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/1_Dataflair/Intermediate/Generators.py
885
4.21875
4
#A Python generator is a kind of an iterable, like a Python list or a python tuple. # It generates for us a sequence of values that we can iterate on. # You can use it to iterate on a for-loop in python, but you can’t index it # def counter(): # i=1 # while i<10: # yield i # i+=1 # # for i in counter(): # print(i) # def even(x): # while(x>0): # if x%2==0: # yield 'Even' # else: # yield "odd" # x-=1 # for i in even(8): # print(i) # def square_numbers(x): # for i in range(x): # if i**2%2==0: # yield i**2 # # print(list(square_numbers(9))) # mylist=(3,6,9,1,2) # s=(x**2 for x in mylist) # # print(s) # print(next(s)) # print(next(s)) # print(next(s)) # print(next(s)) # print(next(s)) # print(next(s)) # # # # for i in s: # # print(i) # print(type(mylist))
true
890a5a8982009a123d6efcab9dadfa63d4df8fdf
rajeshsvv/Lenovo_Back
/1 PYTHON/4 SENDEX/else_if_statement.py
402
4.125
4
# x = 95 # y = 8 # if x > y: # print("x is greater than y") # if x > 55: # print('x is greater than 55') # elif y < 7: # print('y is greater than 7') # else: # print('x is not greater than y') x = 10 y = 10 z = 10 if x > y: print('x is greater than y') elif x == z: print('x is equal to z') if y == z: print('y is equal to z') else: print('if and elif(s) never run')
false