blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0fa5f57b1351604b6f1c7d8858d26909637ca57b
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithm on string/week4/kmp.py
827
4.125
4
# python3 import sys def find_pattern(pattern, text): """ Find all the occurrences of the pattern in the text and return a list of all positions in the text where the pattern starts in the text. """ result = [] # Implement this function yourself conc=pattern+'$'+text values=[0]*len(conc) last=0 for i in range(1, len(conc)): while last>=0: if conc[i]==conc[last]: last+=1 values[i]=last break else: if last!=0: last=values[last-1] else: break pl=len(pattern) for i in range(pl, len(conc)): if values[i]==pl: result.append(i-pl-pl) return result if __name__ == '__main__': pattern = sys.stdin.readline().strip() text = sys.stdin.readline().strip() result = find_pattern(pattern, text) print(" ".join(map(str, result)))
true
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
ed1decde6fc97b53b1ab2026b61be047f22125ca
rajeshsvv/Lenovo_Back
/1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/1_Dataflair/Beginner/4_tuple_functions.py
1,416
4.28125
4
# Python Tuples Packing b=1,2.0,"three", x,y,z=b print(b) print(type(b)) percentages=(99,95,90,89,93,96) a,b,c,d,e,f=percentages # print(a,b,d,e,f,c) # print(type(percentages)) # print(percentages[1]) # print(percentages[2:-1]) # print(percentages) # print(percentages[:-2]) # print(percentages[2:-3]) # print(percentages[:]) # del percentages[:2] tuple does not support item deletion # print(percentages) # del percentages # print(percentages) # percentages[3]=9 tuple does not support item assignment # print(percentages) # 13. Built-in List Functions #A lot of functions that work on lists work on tuples too. # A function applies on a construct and returns a result. It does not modify the construct # sum() max() min() any() # all() tuple() sorted() len() h=max(('Hi','hi','Hello')) print(h) # b=max(('Hi', 9)) # not supported between instances of 'int' and 'str' # print(b) a=any(('','0','')) #If even one item in the tuple has a Boolean value of True, then this function returns True print(a) b=any(('',0,'')) #The string ‘0’ does have a Boolean value of True. If it was rather the integer 0 print(b) # # list=[1,2,3,4,5,6] # print(tuple(list)) # string1="string" print(tuple(string1)) # # set1={2,1,3} # print(tuple(set1)) # print(set1) #
true
3e1029de5c6d8dd891f5b0265d6f9bd28a2ee562
rajeshsvv/Lenovo_Back
/1 PYTHON/7 PROGRAMMING KNOWLEDGE/11_If_else_if.py
603
4.125
4
''' x=100 if x!=100: print("x value is=",x) else: print("you entered wrong value") ''' ''' x=100 if x==100: print("x is =") print(x) if x>0: print("x is positive") else: print("finish") ''' name=input("Enter Name:") if name=="Arjun": print("The Name is",name) elif name=="Ashok": print("The Name is",name) elif name=="Shankar": print("The Name is",name) else: print("Name Entered was wrong") ''' x=10 if x>0: print("x is positive") if (x % 2 == 0): print("x is even") else: print("x is odd") else: print("x is negative") '''
true
4ee34cde27b1028f5965db21d5adcd3311859a62
rajeshsvv/Lenovo_Back
/1 PYTHON/2 COREY SCHAFER/PART 1/25_File Objects Reading and Writing.py
2,058
4.59375
5
# File Object How to read and write File in Python using COntext manager # Reading(r) Writing(w) Appending(a) or Reading and Writing(r+) Operations on File Default is Reading if we dont mention anything # context manager use is no need to mention the close the file it automatically take care about that. # with open("text File.txt", "r") as f: # pass # print(f.closed) with open("text File.txt", "r") as f: f_content = f.read() f_content = f.read(100) print(f_content, end="") # f_content = f.read(100) # print(f_content, end="") # f_content = f.readlines() # f_content = f.readline() # print(f_content, end="") # f_content = f.readline() # print(f_content, end="") # for line in f: # print(line, end="") # print(f.closed) #no need to mention this line when we are in context manager it will take care of that # print(f.read()) #IO operation on closed file error it gets # size_to_read = 10 # f_contents = f.read(size_to_read) # print(f_contents, end="") # f.seek(0) # f_contents = f.read(size_to_read) # print(f_contents) # print(f.tell()) # while len(f_contents) > 0: # print(f_contents, end="*") # f_contents = f.read(size_to_read) # f.write("test") # with open("text2.txt", "w") as f: # # pass # pass in the sense dont do anything rightnow with this function use it later otherwise no error k # f.write("Test") # f.seek(0) # f.write("R") # read and write operations # with open("text File.txt", "r") as rf: # with open("text_copy.txt", "w") as wf: # for line in rf: # wf.write(line) # for pics purpose we use rb and wb because pics are in string mode its not work actually # we havee to convert in binary mode so for that we use rb and wb # with open("Nazria.jpg", "rb") as rf: # with open("Nazria_1.jpg", "wb") as wf: # # for line in rf: # # wf.write(line) # chunk_size = 4096 # rf_chunk = rf.read(chunk_size) # while len(rf_chunk) > 0: # wf.write(rf_chunk) # rf_chunk = rf.read(chunk_size)
true
1c068daa9bc712bd4ce6d49ed728da8666c080a9
rajeshsvv/Lenovo_Back
/1 PYTHON/3 TELUSKO/42_Filter_Map_Reduce.py
1,155
4.34375
4
# program to find even numbers in the list with basic function # def is_even(a): # return a%2==0 # # nums=[2,3,4,5,6,8,9] # # evens=list(filter(is_even,nums)) # print(evens) # program to find even numbers in the list with lambda function # nums=[2,3,4,5,6,8,9] # # evens=list(filter(lambda n:n%2==0,nums)) # print(evens) # # program to double the numbers in the list with normal function # # def update(a): # return a*2 # nums=[2,3,4,5,6,8,9] # evens=list(filter(lambda n:n%2==0,nums)) # doubles=list(map(update,evens)) # print(evens) # print(doubles) # program to double the numbers in the list with lambda function # nums=[2,3,4,5,6,8,9] # evens=list(filter(lambda n:n%2==0,nums)) # doubles=list(map(lambda n:n*2,evens)) # print(evens) # print(doubles) # program to add two numbers in the list in the list with reduce function from functools import reduce # def Add_All(a,b): # return a+b nums=[2,3,4,5,6,8,9] evens=list(filter(lambda n:n%2==0,nums)) doubles=list(map(lambda n:n*2,evens)) # sum=reduce(Add_All,doubles) sum=reduce(lambda a,b:a+b,doubles) # with lambda function print(evens) print(doubles) print(sum)
true
3c0c21e334d161aa174acd2875a8b8bf9afdc56d
rajeshsvv/Lenovo_Back
/1 PYTHON/2 COREY SCHAFER/PART 1/4.2_Sets.py
689
4.25
4
# sets are unorder list of items and no duplicates in it means it throws the duplicate values and in output it gives unique values k #strange when we execute each time set its output order will be change strnage right cs_courses={"History","Math","Physics","ComputerScience"} print(cs_courses) cs_courses={"History","Math","Physics","ComputerScience","ComputerScience","Physics"} print(cs_courses) print("Math" in cs_courses) ; print("Path" in cs_courses); cs_courses={"History","Math","Physics","ComputerScience"} art_courses={"History","Math","Art","Design"} print(cs_courses.intersection(art_courses)) print(cs_courses.difference(art_courses)) print(cs_courses.union(art_courses))
true
f6e317ef55d8b358a5b2a97a8366375d876d1afd
rajeshsvv/Lenovo_Back
/1 PYTHON/2 COREY SCHAFER/PART 2/33_Generators.py
1,324
4.5
4
# Generators have advantages over Lists # Actual way to find the square root of the numbers # def sqaure_numbers(nums): # result = [] # for i in nums: # result.append(i * i) # return result # my_numbers = sqaure_numbers([1, 2, 3, 4, 5]) # print(my_numbers) # through Generator we can find the square root of the numbers # Generators don't hold entire list in memory it gives one by one result # def sqaure_numbers(nums): # for i in nums: # yield(i * i) # my_numbers = sqaure_numbers([1, 2, 3, 4, 5]) # print(my_numbers) # it generates object instead of ressult # # print(next(my_numbers)) # # # print(next(my_numbers)) # # print(next(my_numbers)) # # print(next(my_numbers)) # # print(next(my_numbers)) # # instead of use next keyword create for loop so it will give line by line output # for num in my_numbers: # print(num) # simplify the above code in list comprehension way k # my_numbers = [i * i for i in [1, 2, 3, 4, 5]] # list comprehension way u will get print(my_numbers) result also # print(my_numbers) my_numbers = (i * i for i in [1, 2, 3, 4, 5]) # list comprehension way for generatos.u dont get print(my_numbers) result here.for loop requird print(list(my_numbers)) # if we add list to my numbers then no need of for loop we get result k
true
9f919efc97f5d420ac4e5fe9bcc7894ae34bb20d
dehvCurtis/Fortnight-Choose-Your-Own-Adventure
/game.py
754
4.1875
4
print ("Welcome to Fortnite - Battle Royal") #When the gamer first starts the game print ("Your above Tilted Towers do you jump?.") print('Do you want to jump') ## raw_input gets input from the user ## Here, we take the input, and *assign* it to a variable called 'ans' answer = input("please type yes or no ") ## conditionals ## see if the user's answer is interesting or not if answer=="yes": print ("That was foolish! You are now dead.") ## elif means "else-if" elif answer == "no": print ("That was wise! You are alive, but thoroughly bored.") ## else is a 'catch-all' for "any condition not all ready covered" else: print ("I don't know what to do, based on what you said, which was, |", ans, "|") print ("Thank you for playing!")
true
2122beb8f83cb24f1c617d9fb388abdf42becd63
Laurentlsb/Leetcode
/leetcode/editor/en/[101]Symmetric Tree.py
2,992
4.375
4
#Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # # # 1 # / \ # 2 2 # / \ / \ #3 4 4 3 # # # # # But the following [1,2,2,null,3,null,3] is not: # # # 1 # / \ # 2 2 # \ \ # 3 3 # # # # # Note: #Bonus points if you could solve it both recursively and iteratively. # Related Topics Tree Depth-first Search Breadth-first Search #leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # iteration # class Solution: # def isSymmetric(self, root: TreeNode) -> bool: # if not root: # return True # left_stack = [root] # right_stack = [root] # while left_stack and right_stack: # node_left = left_stack.pop() # node_right = right_stack.pop() # if (node_left is None and node_right is not None) or (node_left is not None and node_right is None): # return False # elif node_left is None and node_right is None: # pass # # if node_left and node_right: # if node_left.val != node_right.val: # return False # else: # left_stack.append(node_left.right) # left_stack.append(node_left.left) # right_stack.append(node_right.left) # right_stack.append(node_right.right) # return True # recursion class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.check(root.left, root.right) def check(self, l, r): if not l and not r: return True elif (not l and r) or (l and not r): return False elif l.val != r.val: return False else: return self.check(l.left, r.right) and self.check(l.right, r.left) # 递归,比较左右最外侧的边缘节点,再依次向内,对称比较(分析一个最简单的三层结构就好) # class Solution: # def isSymmetric(self, root: TreeNode) -> bool: # if root is None: # return True # # if root.left is None and root.right is not None: # return False # elif root.left is not None and root.right is None: # return False # elif root.left == root.right is None: # return True # else: # if root.left.val != root.right.val: # return False # else: # return self.isSymmetric(root.left) and self.isSymmetric(root.right) # # wrong idea, since you were checking if the subtree is symmetric #leetcode submit region end(Prohibit modification and deletion)
true
b27939b3a840c30900ec11f6c41372108c8a78d0
njenga5/python-problems-and-solutions
/Solutions/problem62.py
224
4.46875
4
''' Question 62: Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. Hints: Use unicode() function to convert. ''' word = 'Hello world' word2 = unicode(word, 'utf-8') # print(word2)
true
b8b8639b7244a36bce240fd61986e799027c1c4e
njenga5/python-problems-and-solutions
/Solutions/problem47.py
396
4.15625
4
''' Question 47: Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions. ''' nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] nums3 = map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)) print(list(nums3))
true
cd526869d4d51b2b674b9335c89ad71efddde994
njenga5/python-problems-and-solutions
/Solutions/problem59.py
621
4.34375
4
''' Question 59: Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: google In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. ''' import re emails = input(': ') match = re.search('([a-z]+)@([a-z]+)(\.[a-z]+)', emails) if match: print(match.group(2))
true
4eac214e15a3d21aef858726865d0e633c8e799d
njenga5/python-problems-and-solutions
/Solutions/problem49.py
293
4.15625
4
''' Question 49: Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). Hints: Use map() to generate a list. Use lambda to define anonymous functions. ''' nums = [i for i in range(1, 21)] print(list(map(lambda x: x**2, nums)))
true
878e52902b63ed79cd80fd9ceefe909528bc7abd
njenga5/python-problems-and-solutions
/Solutions/problem28.py
210
4.1875
4
''' Question 28: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. ''' def convert(n): return str(n) print(convert(5))
true
62ed099d5b99fafc9fa44d21f696402333524451
romitheguru/ProjectEuler
/4.py
821
4.125
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def num_reverse(n): reverse = 0 while n: r = n % 10 n = n // 10 reverse = reverse * 10 + r return reverse def is_palindrome(n): reverse = num_reverse(n) return (n == reverse) def solve(): large = 0 combination = None for i in range(999, 99, -1): for j in range(999, 99, -1): num = i * j if is_palindrome(num) and num > large: large = num combination = (i, j) print(combination) return large def main(): print(solve()) if __name__ == '__main__': main()
true
230f3b9c7735deadb877274b1dfc9c6203f407c7
umahato/pythonDemos
/4_MethodAndFunctions/7_argsAndKwargs.py
1,279
4.1875
4
''' def myfunc(a,b): #Return 5% of the sum of a and b return sum((a,b)) * 0.05 print(myfunc(40,60)) def myfunc(*args): return sum(args) * 0.05 print(myfunc(34,53,53)) def myfunc (**kwargs): print(kwargs) if 'fruit' in kwargs: print('My fruit of choise is {}'.format(kwargs['fruit'])) else: print('I did not find any fruit here') print(myfunc(fruit='apple')) # Define a function called myfunc that takes in an arbitrary number of arguments, and return a list containing # only those arguments that are even def myfunc(*args): return [x for x in args if x %2 ==0] print(myfunc(23,33,24,35,66)) ''' # Define a function called myfunc that takes in a string and returns a matching string where every even letter # is uppercase and every odd letter is lowercase. Assume that the incoming string only contains letters # and don't worry about numbers , spaces or punctuations. The output string can start with either an # uppercase letter , so long as letter alternate throughout the string. def myfunc(val): st = '' count = 1 for i in val: if count%2 ==0: st = st + i.upper() else: st = st + i.lower() count = count + 1 return st print(myfunc('hello'))
true
cf4bf78e08205d21f77080dc552247a94a3283e4
umahato/pythonDemos
/3_PythonStatements/3_whileLoops.py
909
4.375
4
# While loops will continue to execute a block of code while some condition remain true. # For example , while my pool is not full , keep filling my pool with water. # Or While my dogs are still hungry, keep feeding my dogs. ''' x = 0 while x < 5: print(f'The current value of x is {x}') #x = x +1 x += 1 else: print('X is not less than 5') ''' # Break , Continue and Pass # We can use break, continue and pass statements in our loops to add additional functionality for various cases. # The three statements are defined by: # break: Breaks out of the current closest enclosing loop. # continue: Goes to the top of the closest enclosing loop. # pass: Does nothing at all. ''' x = [1,2,3] for item in x: pass print('end of my script') ''' mystring = 'Sammy' for letter in mystring: if letter == 'a': break # can be use break or continue print(letter)
true
b7f0c53ae0215250ecf91d5f59489c8fd1f8793c
SilviaVazSua/Python
/Basics/coding_life.py
376
4.15625
4
# a program about something in real life :D number_of_stairs_1_2 = int(input("Tell me how many stairs from floor 1 to floor 2, please: ")) floor = int(input("In which floor you live? ")) total_stairs = number_of_stairs_1_2 * floor print("Then, if the elevator doesn\'t work, you will have ", total_stairs, "until your home! Maybe you want to stay at a friend's home! :D")
true
247b7c1a9aba17644415a90f117b4d327e3f332d
SilviaVazSua/Python
/Basics/leap_years.py
719
4.25
4
# This program asks for a starting year and an ending year and then puts all the leap years between them (and including them, if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). start_date = int(input("Tell me a start date, please: ")) end_date = int(input("Tell me a end date, please: ")) end_date2 = end_date + 1 print("The leap years between these two dates (including them) are:") for dates in range (start_date, end_date2): if dates % 4 == 0: print (dates) print("Yes, I know, I'm pretty smart! :D")
true
43c40e8eb46f891023aea282aa8fff1e081581fc
razvanalex30/Exercitiul3
/test_input_old.py
1,138
4.21875
4
print("Hi! Please choose 1 of these 3 inputs") print("1 - Random joke, 2 - 10 Random jokes, 3 - Random jokes by type") while True: try: inputus = int(input("Enter your choice: ")) if inputus == 1: print("You have chosen a random joke!") break elif inputus == 2: print("You have chosen 10 Random Jokes!") break elif inputus == 3: types = ["general","programming","knock-knock"] numbers = [1, 10] typee = None number = None while typee not in types: typee = str(input("Please choose a type: ")) if typee in types: break else: print("Try again!") print("Your type chosen was {}".format(typee)) while number not in numbers: number = int(input("Please choose the number of jokes: ")) if number in numbers: break else: print("Try again!") print("Here are your jokes!") break print("Please enter a valid number!\n") except Exception: print("Please choose a valid input\n")
true
a70be84406ab8fdf4944f6030533fbda0297b11e
ashishp0894/CS50
/Test folder/Classes.py
910
4.125
4
"""class point(): #Create a new class of type point def __init__(self,x_coord,y_coord): #initialize values of class self.x = x_coord self.y = y_coord p = point(10,20) q = point (30,22) print(f"{p.x},{p.y} ") """ class flight(): def __init__(self,capacity): self.capacity = capacity self.passengers = [] def add_passenger (self,Passenger_name): #New function created inside class if not self.open_seats(): return False else: self.passengers.append(Passenger_name) return True def open_seats(self): return self.capacity - len(self.passengers) f90 = flight(3) people = ["Harry","Ron","Hermoine","Ginnie"] for person in people: success = f90.add_passenger("person") if success: print(f"Added {person} successfully") else: print(f"Unable to add {person} successfully")
true
23f6a8643e06ed18a73c9bf1519b9719e0a3283c
christophe12/RaspberryPython
/codeSamples/fileManipulation/functions.py
933
4.25
4
#----handy functions---- #The os() function #os.chdir('directory_name') -> changes your present working directory to directory_name #os.getcwd() -> provides the present working directory's absolute directory reference #os.listdir('directory_name') -> provides the files and subdirectories located in directory_name. if no directory_name is provided, it returns the files and subdirectories located in the present working directory. #os.mkdir('directory_name') -> creates a new directory #os.remove('file_name') -> deletes file_name from your present working directory. it will not remove directories or subdirectories. There are no "Are you sure?" questions provided. #os.rename('from_file', 'to_file') -> renames a file from the name from_file to the name to_file in your present working directory. #os.rmdir('directory_name') -> deletes the directory directory_name. it will not delete the directory if it contains any files.
true
ff0e7cbbf0cff9dd00e60a14d1382e52aac4331f
SuryakantKumar/Data-Structures-Algorithms
/Functions/Check_Prime.py
554
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 24 05:36:47 2019 @author: suryakantkumar """ ''' Problem : Write a function to check whether the number N is prime or not. Sample Input 1 : 5 Sample output 1 : prime Sample input 2 : 4 Sample output 2: Not Prime ''' def IsPrime(n): if n < 2: return False d = 2 while d < n: if n % d == 0: return False d += 1 return True n = int(input()) result = IsPrime(n) if result: print('prime') else: print('Not Prime')
true
1c4ccd633778efae1e6d402385ff2eb10a509c91
SuryakantKumar/Data-Structures-Algorithms
/Exception Handling/Else-And-Finally-Block.py
1,101
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 7 14:42:20 2020 @author: suryakantkumar """ while True: try: numerator = int(input('Enter numerator : ')) denominator = int(input('Enter denominator : ')) division = numerator / denominator except ValueError: # handling ValueError exception explicitly print('Numerator and denominator should be integers') except ZeroDivisionError: # handling ZeroDivisionError exception explicitly print('Denominator should not bee zero') except (ValueError, ZeroDivisionError): # Handling multiple exceptions at a time print('Numerator and denominator should be integers and Denominator should not bee zero') except: print('Another exception has been raised') else: # Else will execute when no any exception will be raised print(division) break finally: # Finally block will execute whether exception will be raised or not print('Exception raised or not')
true
b895e3cd708cd102baaf7f4126f4d1a13c32e889
SuryakantKumar/Data-Structures-Algorithms
/Object Oriented Programming/Class-Method.py
1,374
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 6 06:20:20 2020 @author: suryakantkumar """ from datetime import date class Student: def __init__(self, name, age, percentage = 80): # Init method self.name = name self.age = age self.percentage = percentage @classmethod # Class method are factory methods which returns object of the class specified def FromBirthYear(cls, name, year, percentage): return cls(name, date.today().year - year, percentage) # class method returns object of the class def StudentDetails(self): print('name :', self.name) print('age :', self.age) print('percentage :', self.percentage) def IsPassed(self): if self.percentage > 40: print(self.name, 'is passed') else: print(self.name, 'is not passed') @staticmethod def WelcomeToSchool(): print('Welcome to School') @staticmethod def IsTeen(age): # Static methods are used as utility functions, used to check some functionalities return age >= 16 s = Student('Suryakant', 21, 90) s.StudentDetails() print() s1 = Student.FromBirthYear('shashikant', 2000, 70) # Object creation from class method s1.StudentDetails()
true
0beb688b4af8803550204cf01f8879b8f327050e
SuryakantKumar/Data-Structures-Algorithms
/Functions/Fahrenheit_To_Celcius.py
878
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 24 07:44:35 2019 @author: suryakantkumar """ ''' Problem : Given three values - Start Fahrenheit Value (S), End Fahrenheit value (E) and Step Size (W), you need to convert all Fahrenheit values from Start to End at the gap of W, into their corresponding Celsius values and print the table. Input Format : 3 integers - S, E and W respectively Output Format : Fahrenheit to Celsius conversion table. One line for every Fahrenheit and Celsius Fahrenheit value. Fahrenheit value and its corresponding Celsius value should be separate by tab ("\t") Sample Input : 0 100 20 Sample Output : 0 -17 20 -6 40 4 60 15 80 26 100 37 ''' s = int(input()) e = int(input()) w = int(input()) def f2c(s, e, w): for s in range(s, e+1, w): c = int((s-32)*5/9) print(s, '\t', c) f2c(s, e, w)
true
2450c7cccafa7d66157ef16b35ced3b903ee0b60
SuryakantKumar/Data-Structures-Algorithms
/Searching & Sorting/Insertion-Sort.py
1,120
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 1 08:42:58 2020 @author: suryakantkumar """ ''' Problem : Given a random integer array. Sort this array using insertion sort. Change in the input array itself. You don't need to return or print elements. Input format : Line 1 : Integer N, Array Size Line 2 : Array elements (separated by space) Constraints : 1 <= N <= 10^3 Sample Input 1: 7 2 13 4 1 3 6 28 Sample Output 1: 1 2 3 4 6 13 28 Sample Input 2: 5 9 3 6 2 0 Sample Output 2: 0 2 3 6 9 ''' def InsertionSort(n, li): for i in range(1, n): consider = li[i] # Choose one element j = i - 1 # Last index of sorted lements while j >= 0 and li[j] > consider: # Compare considered element with sorted elements in reverse li[j+1] = li[j] # Shift element one index right j = j - 1 li[j+1] = consider # Put considered element on right position n = int(input()) li = [int(x) for x in input().strip().split()] InsertionSort(n, li) print(*li)
true