blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
91b435e4c6afda99270bec91eae519bcb8a09cf8
amolsmarathe/python_programs_and_solutions
/2-Basic_NextConceptsAndNumpy/4-LocalGlobalVariables.py
1,522
4.40625
4
# Local- defined inside the function # Global- defined outside the function # Global can always be accessed inside function, given that same variable is not defined inside function, however, # local variable cannot be accessed outside the function # Local and global variables are different # 'global'-Global variable can be recalled inside a function using 'global' function - BUT with such usage, BOTH local & # GLOBAL variables cannot exist inside a function at the same time. Changes are directly reflected on global # variable from within the function # 'globals' - function can be used when we need BOTH local as well as global variables to be accessed in function # Local and global variables are different a = 10 def fun(): a = 15 print('\n a inside function= ', a, 'with address= ', id(a)) fun() print(' a outside function= ', a, 'with address= ', id(a)) # 'global'- Global variable can be recalled inside a function using global function: a = 10 def fun(): global a a = 15 print('\n a inside function= ', a, 'with address= ', id(a)) fun() print(' a outside function= ', a, 'with address= ', id(a)) # 'globals'- Global as well as local variable can be accessed inside a function using globals function: a = 10 def fun(): x = globals()['a'] a = 15 print('\n a inside function= ', a, 'with address= ', id(a)) print(' Value of global variable \'a\' accessed inside function is = ', x) fun() print(' a outside function= ', a, 'with address= ', id(a))
true
30a9464d99def27837a31aa58c3dc01a4e494ce6
amolsmarathe/python_programs_and_solutions
/3-ObjectOriented/5-Polymorphism-3&4-MethodOverload&Override.py
1,439
4.71875
5
# Method Overload (within same class): 2 methods exist with same name but different number of args # - NOT supported as it is in python,we CANNOT have 2methods with same name in python. But there is a similar concept # - In python,we define method with arg=None &while creating an object,it will get default value None if arg is absent # - This itself can be called as a similar concept to Method overload # Method Override (within 2 diff. classes): 2 methods exist with same name and same no. of args but in different classes # - When we inherit the classes i.e. class B(A) and both A and B have same methods, preference is given to # - the method from class B over class A. This is called method override # Method Overload Example: class Addition: def add(self, a=None, b=None, c=None): sum = 0 if a != None and b != None and c != None: sum = a + b + c elif a != None and b != None: sum = a + b else: sum = a return sum a1 = Addition() print(a1.add(5, 6, 7)) # In this way, we have overloaded same method 'add' by passing different no. of args print(a1.add(5, 6)) print(a1.add(5)) # Method Override Example: class A: def printfun(self): print('Fun in Class A') class B(A): def printfun(self): # this method overrides the method in class A print('Fun in Class B') b1 = B() b1.printfun()
true
d90b0446da8f2201d5bc0ac0bed1b15dca86eefd
qikuta/python_programs
/text_to_ascii.py
760
4.5
4
# Quentin Ikuta # August 7, 2022 # This program takes input from user, anything from a-z, A-Z, or 0-9 -- # converts the input into ASCII code, then finally prints the original input and ASCII code. # ask user for input user_string = input("please enter anything a-z, A-Z, and/or 0-9:") # iterate through each character and/or number, compare to dictionary of ASCII, pull the appropriate ASCII letter. asciiDict = {i: chr(i) for i in range(128)} keyList = list(asciiDict.keys()) valList = list(asciiDict.values()) def letter_to_ascii(user_string): indexlist = [] for letter in user_string: letterindex = valList.index(letter) indexlist.append(letterindex) return indexlist print(letter_to_ascii(user_string)) print(user_string)
true
2b3cb34f4d91c43bd4713619e0adbd53dbd6f17e
ICANDIGITAL/crash_course_python
/chapter_7/restaurant_seating.py
230
4.1875
4
seating = input("How many people are in your dinner group? ") seating = int(seating) if seating >= 8: print("You'll have to wait for a table of " + str(seating) + ".") else: print("There is currently a table available.")
true
d415802c81d337356a85c4c0f94ca993fbcb1d7d
ICANDIGITAL/crash_course_python
/chapter_8/unchanged_magicians.py
421
4.125
4
def show_magicians(magicians): """Displays the name of each magicians in a list.""" for magician in magicians: print(magician.title()) magical = ['aalto simo', 'al baker', 'alessandro cagliostro', 'paul daniels'] def make_great(tricks): """Modifies the original function by adding a message.""" for great in range(len(tricks)): tricks[great] += " the great".title() make_great(magical[:]) show_magicians(magical)
true
be760a2488631c90a135637a524a857ee1bfc7d3
Divyansh-coder/python_challenge_1
/area_of_circle.py
244
4.5625
5
#import math to use pi value import math #take radius as (real number)input from user radius = float(input("Enter the radius of the circle: ")) #print area of circle print("The area of the circle with radius",radius,"is :",math.pi*radius**2)
true
7a287ab16b4fa019dc5190951f5f6268ae9d6d0b
Mannuel25/Mini-Store-Project
/items_in_file.py
657
4.34375
4
def no_of_items_in_file(): """ Displays the total number of items in the file :return: None """ filename = 'myStore.txt' # open original file to read its contents open_file = open(filename,'r') description = open_file.readline() # make a variable to count the number of items TOTAL = 0 while description != '': TOTAL += 1 description = open_file.readline() open_file.close() # since each record consists of three fields # divide the total number of items by 3 # in the file and round it to the nearest whole number print(f'Total number of items in file: {round(TOTAL / 3)}')
true
2e93d1859265eb0f7f53a7a34c2458c8201acc20
xiaofeixiawang/cs101
/lesson5/problem-set2.py
1,744
4.1875
4
1. # Write a procedure, shift, which takes as its input a lowercase letter, # a-z and returns the next letter in the alphabet after it, with 'a' # following 'z'. def shift(letter): if letter=='z': return 'a' return chr(ord(letter)+1) print shift('a') #>>> b print shift('n') #>>> o print shift('z') #>>> a 2. # Write a procedure, shift_n_letters which takes as its input a lowercase # letter, a-z, and an integer n, and returns the letter n steps in the # alphabet after it. Note that 'a' follows 'z', and that n can be positive, #negative or zero. def shift_n_letters(letter, n): return chr((ord(letter)-ord('a')+n)%26+ord('a')) print shift_n_letters('s', 1) #>>> t print shift_n_letters('s', 2) #>>> u print shift_n_letters('s', 10) #>>> c print shift_n_letters('s', -10) #>>> i 3. # Write a procedure, rotate which takes as its input a string of lower case # letters, a-z, and spaces, and an integer n, and returns the string constructed # by shifting each of the letters n steps, and leaving the spaces unchanged. # Note that 'a' follows 'z'. You can use an additional procedure if you # choose to as long as rotate returns the correct string. # Note that n can be positive, negative or zero. def shift_n_letters(letter, n): return chr((ord(letter)-ord('a')+n)%26+ord('a')) def rotate(word,n): res='' for letter in word: if letter==' ': res+=' ' else: res+=shift_n_letters(letter,n) return res print rotate ('sarah', 13) #>>> 'fnenu' print rotate('fnenu',13) #>>> 'sarah' print rotate('dave',5) #>>>'ifaj' print rotate('ifaj',-5) #>>>'dave' print rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu " "sv rscv kf ivru kyzj"),-17) #>>> ???
true
e424eb0df975b287825768065921bdac8473c72d
RaisuFire/ExProject
/leetCode/Medium/Rotate Image.py
758
4.125
4
from copy import deepcopy class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ c = deepcopy(matrix) for i in range(len(matrix)): matrix[i] = [c[j][i] for j in range(len(c[i]))][::-1] """ matrix.reverse() r = len(matrix) for i in range(r): for j in range(i+1, r): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return """ if __name__ == "__main__": nums1 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] so = Solution() c = so.rotate(nums1) print(c)
true
aeca2a9b20564854381cba2a7478f5cfbb266201
sumitdba10/learnpython3thehardway
/ex11.py
1,108
4.25
4
print("How old are you?", end=' ') age = input() print("How tall are you in inches?",end=' ') height = input() print("How much do you weigh in lbs?",end=' ') weight = input() # end=' ' at the end of each print line. This tells print to not end the line with a newline character and go to the next line. print(f"So, you're {age} old, {height} inches tall, and {weight} pounds heavy.") print("#"*50) ################################################################################ #ex12.py age = input("How old are you? ") height = input("How tall are you? ") weight = input("How much you weigh? ") print(f"So, you're {age} old, {height} inches tall, and {weight} pounds heavy.") print("#"*50) ############################################################################### #ex13.py # importing a feature from Python feature statement #argv is argument variable, it holds arguments as value from sys import argv script, first, second, third = argv print("The script is called:",script) print("The first variable is:",first) print("The second variable is:",third) print("The third variable is:",third)
true
f1169d8cfd40df1dcf07287ffaab636bb51f28db
sumitdba10/learnpython3thehardway
/ex20.py
1,856
4.5625
5
# from sys package, we are importing argument variables module from sys import argv import os # asigning two variables to argv module script,input_file = argv # defining a function to read all content of a file def print_all(f): print(f.read()) # defining a function to reset pointer to 0 position def rewind(f): f.seek(0) # defining a function to read one line from file def print_a_line(line_count, f): print(line_count,f.readline()) # defining a function to append the existing file with new entries, and save it using close() method of file class def write_to_file(f): f.write(input()) f.write("\n") f.close() # opening file and saving contents to variable current_file = open(input_file) print(f"First let's print the content of whole file {input_file}: ") print("\n") # while using f formatting method, how can we use \n formatter in string # calling print_all function to print all the content of file print_all(current_file) print("Now, Let's rewind, kind of like a tape \n") rewind(current_file) print("Let's print three lines.\n") current_line =1 print_a_line(current_line,current_file) current_line += 1 print_a_line(current_line,current_file) current_line+=1 print_a_line(current_line,current_file) # opening file in append mode current_file = open(input_file,"a") print(f"Add a new line to {input_file} file.") # now as file is append mode, we can write new contents to it write_to_file(current_file) print("\n") # As file was in write mode, we would not be able to read it directly, So opening same file in read mode current_file = open(input_file,"r") # printing all contents print_all(current_file) ####################################################################### # Questions for future: # How can I delete specific line from a input_fileself. # How can I edit the content of exisiting file.
true
6ff3500c81ed429be175c5610a853c2e0f98a728
sumitdba10/learnpython3thehardway
/ex23.py
1,738
4.5625
5
# importing sys package import sys #assigning three variables to argv (argument variable) module # script : this whole program as .py # encoding : variable to define encoding e.g. unicode - utf8/utf16/utf32 or ASCII etcself. #error : to store errors script,encoding, errors = sys.argv # defining a function with 3 arguments , the input file, encoding and errors def main(language_file,encoding, errors): # reading lines from file and assigning to a Variable line = language_file.readline() # if condition, if we have a line in file then if line: #execute the print_line function which is defined below print_line(line,encoding,errors) # also, return main function again to continue with readline return main(language_file,encoding,errors) def print_line(line,encoding,errors): # we are using line variable from main function above, using .strip() function of a string we strip both trailing and leading whiespaces are removed from string next_lang = line.strip() # raw bytes is a sequence of bytes that python uses to store utf-8 encoded string # next_lang is a variable which has stripped line from language input input_file # we are encoding each line in raw bytes using encode method raw_bytes = next_lang.encode(encoding,errors=errors) # we are decoding raw bytes to utf-8 string using decode method cooked_string = raw_bytes.decode(encoding,errors=errors) # Now printing bytes encoding and utf-8 character equivalent to each other print(raw_bytes, '<====>',cooked_string) # opening input file in utf-8 unicode encoding languages = open("languages.txt",encoding ="utf-8") # Now finally calling main function main(languages,encoding,errors)
true
c640eccb766d3be16d513516ca9b3bb7499df39e
Sophorth/mypython_exercise
/ex11.py
569
4.4375
4
print " " print " ------Start Exercise 11, Asking Question ------" print " " print "What is your name: ", name = raw_input() print "How tall are you: ", height = raw_input() print "How old are you: ", age = raw_input() print "You name is %s and your are %s inches tall and you are %s" % (name, height, age) # We can do it in another way as bellow: name = raw_input("What is your name? :") height = raw_input("How tall are you? :") age = raw_input("How old are you? :") print "Again, Your name is %s and your are %s inches tall and you are %s" % (name, height, age)
true
9fb33802cd8348fc3fa37be0c0bc61e81bfb683c
nojronatron/PythonPlayarea
/PycharmProjects/Chapter4Explorations/Heros_Inventory.py
1,366
4.25
4
__author__ = 'Blue' # Hero's Inventory # Demonstrates tuple creation # Create an empty Tuple inventory = () # Treat the tuple as a condition if not inventory: print("You are empty-handed.") # create a tuple with some items inventory = ("sword", "armor", "shield", "healing potion") # print the tuple print("\nYou have:", (len(inventory)), "items in your inventory.") # print each element in the tuple print("\nYour items:") for item in inventory: print(item) # Test for membership with 'in' if "healing potion" in inventory: print("\nYou will live to fight another day.") # Display one item through an index index = int(input("\nEnter the index number for an item in inventory: ")) if index < 1: index = 1 print("\nThat number is too low, so I'll assume you meant the first item in inventory.") if index > len(inventory): index = len(inventory) print("\nThat number is too high, so I'll assume you meant the last item in inventory.") print("At index", index, "is", inventory[index - 1]) # Concatenate two tuples (since they are immutable) chest = ("gold", "gems") print("\nYou find a chest. It contains:") print(chest) print("You add the contents of the chest to your inventory.") inventory += chest print("Your inventory is now:") print(inventory) input("\nPress the Enter key to exit.")
true
aca33cc8e9e6394ba986c45caf8d3eb96f8e367c
nojronatron/PythonPlayarea
/PycharmProjects/Chapter 4 Exercizes/Word_Jumble_Game.py
1,319
4.25
4
# -------------------------------------------------# # Title: Chapter 4: Word Jumble Game # Author: Jon Rumsey # Date: 3-May-2015 # Desc: Computer picks a random word from a list and jumbles it # User is asked to guess the word. # 1. Create sequence of words # 2. Pick one word randomly from the sequence # 3. Create a new word sequence and re-arrange the letters to form the jumble # 4. Loop the player through guesses # 5. Congratulate player, ask if done/play again # ChangeLog: Initial #-------------------------------------------------# #-- Data --# import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") jumble = "" #-- Processing --# word = random.choice(WORDS) correct = word while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] #-- Presentation (I/O) --# print("\tWelcome to Word Jumble!") print("\nUnscramble the letters to make a word.") print("\n\nThe jumble is:", jumble) guess = input("\nYour guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") guess = input("Your guess: ") if guess == correct: print("\nThat's it! You guessed it!\n") print("Thanks for playing.") input("\n\nPress the Enter key to exit.")
true
56321bc2ea255b211551506b56bc2e255cdcd34d
rahuldevyadav/Portfolio-PYTHON
/gui/program2.py
436
4.375
4
#In this program we will create frame #size of widget #and putting button on it from tkinter import * root= Tk() frame = Frame(root, width=300,height =200) # ONCE WE DEFINE BUTTON WIDTH AND HEIGHT IS DEFAULT button = Button(frame,text='Button1') button.pack() frame.pack() # # frame2 = Frame(root,width=300,height =200) # button2 = Button(frame2,text="default") # button2.pack(side=LEFT) # frame2.pack(side=BOTTOM) root.mainloop()
true
8a80887a2d41386d9f9097abc97c08298076757d
learnPythonGit/pythonGitRepo
/Assignments/20200413_Control_Flow/secondLargeNumSaurav.py
998
4.40625
4
# .................................... # Python Assignment : # Date : 15/04/2020 : # Developer : Saurav Kumar : # Topic : Find Second Largest Num : # Git Branch: D15042020saurav : # ................................... # Compare two number and find out the greater number (using if else) print("Assignment : Find second largest of the given numbers in list - Method 1") lst = [3, 2, 7, 4, 6, 6, 5, 8] # sorting of list newList = [] for i in lst: if i not in newList: newList.append(i) newList.sort(reverse=True) print("Second Largest number is {0}".format(newList[1])) # FInd the second Largest number from the list of Number- Ashish print("Assignment : Find second largest of the given numbers in list - Method 2") number_list = [1,2,3,4,2,1,5,6,8,4,1,5,1,5,4,8] number_list = list(set(number_list)) number_list.sort(reverse=True) print("Second Largest number is {0}".format(number_list[1])) print("\n" + "-"*80)
true
636a447d89387773056d4e81c6a7519cea3675dd
TCIrose/watchlist
/app/models/movie.py
1,124
4.125
4
class Movie: ''' Movie class to define Movie Objects ''' def __init__(self, id, title, overview, poster, vote_average, vote_count): ''' Args: 1. Title - The name of the movie 2. Overview - A short description on the movie 3. image- The poster image for the movie 4. vote_average - Average rating of the movie 5. vote_count - How many people have rated the movie 6. id - The movie id ''' self.id = id self.title = title self.overview = overview self.poster = 'https://image.tmdb.org/t/p/w500/'+ poster self.vote_average = vote_average self.vote_count = vote_count ''' def __repr__(self):#, id, title, overview, poster, vote_average, vote_count): self.id = "%s" % (self.id) self.title = "%s" % (self.title) self.overview = "%s" % (self.overview) self.poster = "%s" % (self.poster) self.vote_average = "%s" % (self.vote_average) self.vote_count = "%s" % (self.vote_count) '''
true
4b11b5f80610aa514338426c0b0262b20c81aa3c
Cretis/Triangle567
/TestTriangle.py
2,667
4.15625
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testRightTriangleA(self): self.assertEqual(classifyTriangle(3, 4, 5), 'Right', '3,4,5 is a Right triangle') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5, 3, 4), 'Right', '5,3,4 is a Right triangle') def testRightTriangleC(self): self.assertEqual(classifyTriangle(3, 5, 4), 'Right', '3,5,4 is a Right triangle') def testEquilateralTrianglesA(self): self.assertEqual(classifyTriangle(1, 1, 1), 'Equilateral', '1,1,1 should be equilateral') def testEquilateralTrianglesB(self): self.assertEqual(classifyTriangle(200, 200, 200), 'Equilateral', '200,200,200 should be equilateral') def testNotATriangleA(self): self.assertEqual(classifyTriangle(1, 2, 10), 'NotATriangle', '1,2,10 is not a Triangle') def testNotATriangleB(self): self.assertEqual(classifyTriangle(10, 1, 2), 'NotATriangle', '10,1,2 is not a Triangle') def testNotATriangleC(self): self.assertEqual(classifyTriangle(2, 10, 1), 'NotATriangle', '2,10,1 is not a Triangle') def testNotATriangleD(self): self.assertEqual(classifyTriangle(1, 2, 3), 'NotATriangle', '1,2,3 is not a Triangle') def testInvalidIputA(self): self.assertEqual(classifyTriangle(201, 201, 201), 'InvalidInput', '201,201,201 is invalid input') def testInvalidIputB(self): self.assertEqual(classifyTriangle(0, 1, 2), 'InvalidInput', '0,1,2 is invalid input') def testInvalidIputC(self): self.assertEqual(classifyTriangle(1, 5, 300), 'InvalidInput', '1,5,300 is invalid input') def testInvalidIputD(self): self.assertEqual(classifyTriangle(0, 0, 0), 'InvalidInput', '0,0,0 is invalid input') def testInvalidIputE(self): self.assertEqual(classifyTriangle(0.1, 0.1, 0.1), 'InvalidInput', '0.1,0.1,0.1 is invalid input') def testIsocelesTriangle(self): self.assertEqual(classifyTriangle(2, 2, 3), 'Isoceles', '2,2,3 is a Isoceles Triangle') def testScaleneTriangle(self): self.assertEqual(classifyTriangle(5, 6, 7), 'Scalene', '5,6,7 is a Scalene Triangle') if __name__ == '__main__': print('Running unit tests') unittest.main()
true
7cbea7f0bd0645048484806489ed71c2c6e580b7
wonpyo/Python
/Basic/VariableScope.py
1,207
4.3125
4
# Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. # Python supports global variables (usable in the entire program) and local variables. # By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’. print("[Local Variable]\n") def sum(x,y): sum = x + y return sum print(sum(8,6)) # print(x) # Local variables cannot be used outside of their scope, this line will not work print() def f(x,y): print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)) print('x * y = ' + str(x*y)) z = 4 # local variable print('Local variable z = ' + str(z)) z = 3 # global variable f(3,2) print('Global variable z = ' + str(z)) print() print("[Global Variable]\n") z = 10 def afunction(): global z z = 9 afunction() print("z = " + str(z)) print('') z = 10 print("z = " + str(z)) def func1(): global z z = 3 def func2(x,y): global z return x+y+z func1() print("z = " + str(z)) total = func2(4,5) print("total = ", total)
true
25209b004ddb4eae65d34e63235622fa9fa44a3d
wonpyo/Python
/Basic/MethodOverloading.py
1,019
4.4375
4
# Several ways to call a method (method overloading) # In Python you can define a method in such a way that there are multiple ways to call it. # Given a single method or function, we can specify the number of parameters ourself. # Depending on the function definition, it can be called with zero, one, two or more parameters. # This is known as method overloading. # Not all programming languages support method overloading, but Python does. # We create a class with one method sayHello(). The first parameter of this method is set to None, # this gives us the option to call it with or without a parameter. # An object is created based on the class, and we call its method using zero and one parameter. class Human: def sayHello(self, name=None): if name is not None: print('Hello ' + name) else: print('Hello ') # Create an instance (object) obj = Human() # Call the method without parameter obj.sayHello() # Call the method with a parameter obj.sayHello("Wonpyo")
true
a2cfdf0723538af644a2eee5372069785bdc048e
wonpyo/Python
/Basic/Threading.py
1,526
4.53125
5
""" A thread is an operating system process with different features than a normal process: 1. Threads exist as a subset of a process 2. Threads share memory and resources 3. Processes have a different address space in memory When would you use threading? Usually when you want a function to occur at the same time as your program. If you want the server not only listens to one connection but to many connections. In short, threads enable programs to execute multiple tasks at once. """ from threading import * import time print("Example #1: Create and start 10 threads") class MyThread(threading.Thread): def __init__(self, x): # constructor self.__x = x threading.Thread.__init__(self) def run(self): print(str(self.__x)) # Start 10 threads: Threads do not have to stop if run once for x in range(10): MyThread(x).start() print() print("Example #2: Timed threads") def hello(): print("Hello Python!") # Create timed thread by instantiating Timer class t = Timer(10.0, hello()) # Start the thread after 10 seconds t.start() print() print("Example #3: Repeat functionality using threads") def handleClient1(): while(True): print("Waiting for client 1...") time.sleep(5) # Wait for 5 seconds def handleClient2(): while(True): print("Waiting for client 2...") time.sleep(5) # Wait for 5 seconds # Create timed threads t1 = Timer(5.0, handleClient1()) t2 = Timer(3.0, handleClient2()) # Start threads t1.start() t2.start()
true
50a126e7540a343ff18cbe16262324bf091cc0a4
cameron-teed/ICS3U-3-08-PY
/leap-year.py
548
4.34375
4
#!/usr/bin/env python3 # Created by: Cameron Teed # Created on: Oct 2019 # This is program finds out if it's a leap year def main(): # calculates if it is a leap year # variables leap_year = " is not" # input year = int(input("What is the year: ")) # process # output if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap_year = " is" else: leap_year = " is" print(str(year) + leap_year + " a leap year.") if __name__ == "__main__": main()
true
50cdfe6dd5d6826a19477bbd440f7b1af507619e
ElleDennis/build-a-blog
/crypto/helpers.py
1,276
4.4375
4
def alphabet_position(letter): """alphabet_position receives single letter string & returns 0-based numerical position in alphabet of that letter.""" alphabetL = "abcdefghijklmnopqrstuvwxyz" alphabetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" letter = letter.lower() if letter in alphabetL: return alphabetL.find(letter) if letter in alphabetU: return alphabetU.find(letter) def rotate_character(char, rot): """rotate_character receives single string character & an integer for rotation (rot) to places right in alphabet.""" alphabetL = "abcdefghijklmnopqrstuvwxyz" alphabetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if char.isalpha() == False: #to ignore all non-alpha chars return char if char.isupper(): rotated_let_num = alphabet_position(char) """Calling the above function""" rotated_let_num = (rotated_let_num + int(rot)) % 26 encrypted_letter_upper = alphabetU[rotated_let_num] return encrypted_letter_upper else: rotated_let_num = alphabet_position(char) """Calling the above function""" rotated_let_num = (rotated_let_num + int(rot)) % 26 encrypted_letter = alphabetL[rotated_let_num] return encrypted_letter
true
e1a296cfe2eb437daad088ff4070a689872bb03e
ishaik0714/MyPythonCode
/Strings_Prog.py
1,232
4.375
4
mult_str = """This is a multi line string, this can have data in multiple lines and can be printed in multiple lines !""" print(mult_str) # The Multi-line string can be in either in three single quotes or three double quotes. st1 = "Hello" st2 = "World!" print (st1+st2) # String Concatenation str1 = "Hello World!" # Character position in a String start from 0 print("Character at position - 0 of the string: ",str1[0]) # First Character is 0 print("Sub-string from position 3 to 5: ", str1[2:5]) # 2:5 means characters at position 3rd, 4th and 5th print("Sub-string from position -6 to -3 from end: ",str1[-6:-3]) # Negative number means, start counting from the end of string starting with 0 print("String length: ",len(str1)) # Get the string length print("String remove whitespace: ",str1.strip()) # Remove white spaces in string print("String to lower case: ",str1.lower()) # change the string to lower case print("String to upper case: ",str1.upper()) # change the string to upper case print("String to upper case: ",str1.replace('H','M')) # Replace H with M print("String to upper case: ",str1.split(',')) # change the string to upper case 987654321 HELLOWORD 012345678 [3:6] = [-4:-1] =
true
8698aa545749d13a550704ba005888e0fbb0001f
syedsouban/PyEditor
/PyEditor.py
1,690
4.15625
4
import sys print("Welcome to Python 2 Text Editor") condition = True while condition == True: print("""What do you want to do: 1. Creating a new file 2. Writing to a saved file 3. Viewing a saved file 4. Exit """) choice=eval(input("Enter your choice: ")) if choice==4: sys.exit() elif choice==3: mode="r" file_name=input("Enter your filename: ") File=open(file_name,mode) print(File.read()) elif choice==2: mode="a+" file_name=input("Enter your filename: ") File=open(file_name,mode) print(File.read()) File.close() File=open(file_name,mode) while True: new_text=input() File.write((new_text)+'\n') elif choice==1: mode="w+" file_name=input("Enter your filename: ") File=open(file_name,mode) File.truncate() print("Start writing your text from here(Press Ctrl+Z and then Press Enter for stop writing): ") while True: new_text=input() File.write((new_text)+'\n') else: print("Invalid choice entered") char=input("Press C/c to continue and Q/q to quit: ") if char=='C' or char == 'c': condition=True elif char=='q' or char=='Q': condition=False else: print("Invalid choice entered") File.close() #addong a commit, bruuuh.
true
d44ab2f4b12fbeb112faceddf889d477f0c796b2
sunil830/PracticePerfect
/ListOverlap.py
1,315
4.25
4
""" Author: Sunil Krishnan Date: 17-Apr-2016 Name: ListOverlap.py Reference: http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html Problem Statement: Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Extras: Randomly generate two lists to test this Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon) """ import random def findlistoverlap(a, b): print([x for elem in a for x in b if elem == x]) def randomlist(): v_num = int(input('Enter the number of elements you want in the generated list: ')) a = random.sample(range(100), v_num) b = random.sample(range(100), v_num) findlistoverlap(a, b) def staticlist(): a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] findlistoverlap(a, b) if __name__ == '__main__': v_yes_no = str(input('Enter Y for Random List and N for Static List: ')) if v_yes_no == 'Y': randomlist() else: staticlist()
true
b2c0f4d56af52930fb94356d565dc2a7822acd3b
KennethTBarrett/cs-module-project-iterative-sorting
/src/iterative_sorting/iterative_sorting.py
2,050
4.40625
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # For loop, in range of untouched indexes. for index in range(i + 1, len(arr)): # Check if the current smallest is still the smallest. if arr[smallest_index] > arr[index]: # If so... smallest_index = index # Update the smallest index. #Swap the values around. arr[i], arr[smallest_index] = arr[smallest_index], arr[i] return arr # Quadratic runtime. - O(n^2) # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): # We're going to need to iterate over the entire array. for i in range(len(arr)): for index in range(0, len(arr)-i-1): # Last elements already in place # If the current index is greater than the next... if arr[index] > arr[index + 1]: # Swap the values around. arr[index], arr[index+1] = arr[index+1], arr[index] return arr # Quadratic runtime. - O(n^2) ''' STRETCH: implement the Counting Sort function below Counting sort is a sorting algorithm that works on a set of data where we specifically know the maximum value that can exist in that set of data. The idea behind this algorithm then is that we can create "buckets" from 0 up to the max value. This is most easily done by initializing an array of 0s whose length is the max value + 1 (why do we need this "+ 1"?). Each buckets[i] then is responsible for keeping track of how many times we've seen `i` in the input set of data as we iterate through it. Once we know exactly how many times each piece of data in the input set showed up, we can construct a sorted set of the input data from the buckets. What is the time and space complexity of the counting sort algorithm? ''' def counting_sort(arr, maximum=None): # Your code here return arr
true
e8ca51cc2ec589c50b304d5e8b25d04fc9670cc8
Cbkhare/Challenges
/Fb_beautiful_strings.py
2,140
4.15625
4
#In case data is passed as a parameter from sys import argv import string from operator import itemgetter file_name = argv[1] fp = open(file_name,'r+') contents = [line.strip('\n') for line in fp] #print (contents) alphas = list(string.ascii_lowercase) #Else use this list(map(chr, range(97, 123))) #print (alphas) for item in contents: zapak = [ ltr.lower() for ltr in list(item) if ltr.lower() in alphas] zapak_dict = {} for zap in zapak: if zap not in zapak_dict: zapak_dict[zap]=zapak.count(zap) summ = 0 count = 26 l = len(zapak_dict) for z in range(l): k,v = (max(zapak_dict.items(), key=itemgetter(1))[0],max(zapak_dict.items(), key=itemgetter(1))[1]) summ += count* v del zapak_dict[k] count -=1 print (summ) ''' Credits: This problem appeared in the Facebook Hacker Cup 2013 Hackathon. When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world. Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it. The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.) You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string? Input sample: Your program should accept as its first argument a path to a filename. Each line in this file has a sentence. E.g. ABbCcc Good luck in the Facebook Hacker Cup this year! Ignore punctuation, please :) Sometimes test cases are hard to make up. So I just go consult Professor Dalves Output sample: Print out the maximum beauty for the string. E.g. 152 754 491 729 646 '''
true
fd331cd98a5383c06c45605f4a736462cfd78502
Cbkhare/Challenges
/remove_char_crct.py
1,073
4.21875
4
#In case data is passed as a parameter from sys import argv, getsizeof #from operator import itemgetter #import re #import math #from itertools import permutations #from string import ascii_uppercase file_name = argv[1] fp = open(file_name,'r+') contents = [line.strip('\n').split(', ') for line in fp] for item in contents: p1 = list(item[0]) p2 = list(item[1]) for w in p2: if w in p1: while w in p1: p1.remove(w) else: continue print (''.join(p1)) ''' Write a program which removes specific characters from a string. Input sample: The first argument is a path to a file. The file contains the source strings and the characters that need to be scrubbed. Each source string and characters you need to scrub are delimited by comma. For example: how are you, abc hello world, def malbororo roro, or Output sample: Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing empty spaces on each line you print. For example: how re you hllo worl malb '''
true
8a4d50a0c008157298bfbd1c818f8192a48b9d5f
Cbkhare/Challenges
/swap_case.py
878
4.15625
4
#In case data is passed as a parameter from sys import argv, getsizeof #from operator import itemgetter #import re #import math #from itertools import permutations #from string import ascii_uppercase file_name = argv[1] fp = open(file_name,'r+') contents = [line.strip('\n') for line in fp] for item in contents: stack = [] for it in item: if it.lower()==it: stack.append(it.upper()) else: stack.append(it.lower()) print (''.join(stack)) ''' Write a program which swaps letters' case in a sentence. All non-letter characters should remain the same. Input sample: Your program should accept as its first argument a path to a filename. Input example is the following Hello world! JavaScript language 1.8 A letter Output sample: Print results in the following way. hELLO WORLD! jAVAsCRIPT LANGUAGE 1.8 a LETTER '''
true
920d2ff4b74ff86352851e8435f0a9761c649392
Cbkhare/Challenges
/multiply_list.py
1,233
4.15625
4
#In case data is passed as a parameter from sys import argv #from string import ascii_uppercase file_name = argv[1] fp = open(file_name,'r+') contents = [ line.strip('\n').split('|') for line in fp] #print (contents) for item in contents: part1 = list(item[0].split(' ')) part1.remove('') part2 = list(item[1].split(' ')) part2.remove('') stack = [] for i in range(len(part1)): #assumed length of both list are equal stack.append(int(part1[i])*int(part2[i])) print (str(stack).replace('[','').replace(']','').replace(', ',' ')) ''' Multiply Lists Challenge Description: You have 2 lists of positive integers. Write a program which multiplies corresponding elements in these lists. Input sample: Your program should accept as its first argument a path to a filename. Input example is the following 9 0 6 | 15 14 9 5 | 8 13 4 15 1 15 5 | 1 4 15 14 8 2 The lists are separated with a pipe char, numbers are separated with a space char. The number of elements in lists are in range [1, 10]. The number of elements is the same in both lists. Each element is a number in range [0, 99]. Output sample: Print the result in the following way. 135 0 54 40 13 16 225 14 120 10 '''
true
0ea75af0aeb9c2bea86f5c8e95f9ca942344e8a9
Cbkhare/Challenges
/HackerRank_Numpy_Transpose_Flatten.py
1,424
4.125
4
from sys import stdin as Si, maxsize as m import numpy as np class Solution: pass if __name__=='__main__': n,m = map(int,Si.readline().split()) N = np.array([],int) for i in range(n): N = np.append(N,list(map(int,Si.readline().split())),axis=0) N.shape = (n,m) #Note:- #To append vertically, Ex:- N = np.append(N,[[9],[10]],axis=1) print(np.transpose(N)) print(N.flatten()) ''' Transpose We can generate the transposition of an array using the tool numpy.transpose. It will not affect the original array, but it will create a new array. import numpy my_array = numpy.array([[1,2,3], [4,5,6]]) print numpy.transpose(my_array) #Output [[1 4] [2 5] [3 6]] Flatten The tool flatten creates a copy of the input array flattened to one dimension. import numpy my_array = numpy.array([[1,2,3], [4,5,6]]) print my_array.flatten() #Output [1 2 3 4 5 6] Task You are given a NNXMM integer array matrix with space separated elements (NN = rows and MM = columns). Your task is to print the transpose and flatten results. Input Format The first line contains the space separated values of NN and MM. The next NN lines contains the space separated elements of MM columns. Output Format First, print the transpose array and then print the flatten. Sample Input 2 2 1 2 3 4 Sample Output [[1 3] [2 4]] [1 2 3 4] '''
true
0c747667e925a98008c91f87dedbd34c2ab10e83
Cbkhare/Challenges
/str_permutations.py
1,087
4.3125
4
#In case data is passed as a parameter from sys import argv from itertools import permutations #from string import ascii_uppercase file_name = argv[1] fp = open(file_name,'r+') contents = [line.strip('\n') for line in fp] #print (contents) for item in contents: #print (item) p_tups= sorted(permutations(item,len(item))) stack = [] for tups in p_tups: stack.append(''.join(tups)) print (','.join(stack)) ''' String Permutations Sponsoring Company: Challenge Description: Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper case letters < lower case letters. The sorting should be performed in ascending order. Input sample: Your program should accept a file as its first argument. The file contains input strings, one per line. For example: hat abc Zu6 Output sample: Print to stdout the permutations of the string separated by comma, in alphabetical order. For example: aht,ath,hat,hta,tah,tha abc,acb,bac,bca,cab,cba 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6 '''
true
ac2ffaa848aee4feacc96c124fa6ca0e6f4480e6
PutkisDude/Developing-Python-Applications
/week3/3_2_nameDay.py
490
4.25
4
#Author Lauri Putkonen #User enters a weekday number and the program tells the name of the day. import calendar day = int(input("Number of the day: ")) -1 print(calendar.day_name[day]) # Could also make a list and print from it but there is inbuilt module in python to do same thing # weekdays = ["Monday", "Tuedsday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # day = int(input("Number of the day ")) -1 # print(weekdays[day]) #OUTPUT EXAMLE: #Number of the day: 3 #Wednesday
true
7a32efcdfaf7edef3e3ffaffabbeed9bed255bd3
mkgmels73/Bertelsmann-Scholarship-Data-Track
/Python challenge/39_random_password.py
1,389
4.40625
4
#While generating a password by selecting random characters usually creates one that is relatively secure, it also generally gives a password that is difficult to memorize. As an alternative, some systems construct a password by taking two English words and concatenating them. While this password may not be as secure, it is normally much easier to memorize.Write a program that reads a file containing a list of words, randomly selects two of them, and concatenates them to produce a new password. When producing the password ensure that the total length is between 8 and 10 characters, and that each word used is at least three letters long. Capitalize each word in the password so that the user can easily see where one word ends and the next one begins. Finally, your program should display the password for the user. #Run: 39_random_password.py names.txt from sys import argv import random try: name_file = argv[1] lines = open(name_file).read().splitlines() while 1: # choosing 2 words w1 = random.choice(lines) w2 = random.choice(lines) password = w1 + w2 # total length is between 8 and 10 characters, at least three letters by word if(8 < len(password) < 10 and len(w1) >= 3 and len(w2) >= 3): print('Password is:',w1.capitalize()+ w2.capitalize()) break except: print('Error in file')
true
12b45b29d942aec593b21161d8f6c4c6409722f2
kimfucious/pythonic_algocasts
/solutions/matrix.py
1,501
4.53125
5
# --- Directions # Write a function that accepts an integer, n, and returns a n x n spiral matrix. # --- Examples # matrix(2) # [[1, 2], # [4, 3]] # matrix(3) # [[1, 2, 3], # [8, 9, 4], # [7, 6, 5]] # matrix(4) # [[1, 2, 3, 4], # [12, 13, 14, 5], # [11, 16, 15, 6], # [10, 9, 8, 7]] def matrix(n): """ Need to create a list of n x n filled with None to avoid 'IndexError: list index out of range' issues when using this technique Also note the +1s and -1s on the ranges, as the second argument in a range is non-inclusive. There are other ways to do this, but they make my head explode: https://rosettacode.org/wiki/Spiral_matrix#Python """ spiral = [[None] * n for j in range(n)] start_col, start_row = 0, 0 end_col, end_row = n-1, n-1 counter = 1 while start_col <= end_col and start_row <= end_row: for index in range(start_row, end_col+1): spiral[start_row][index] = counter counter += 1 start_row += 1 for index in range(start_row, end_row+1): spiral[index][end_col] = counter counter += 1 end_col -= 1 for index in range(end_col, start_col-1, -1): spiral[end_row][index] = counter counter += 1 end_row -= 1 for index in range(end_row, start_row-1, -1): spiral[index][start_col] = counter counter += 1 start_col += 1 return spiral
true
dca708d0b43e4adea6e69b7ec9611e919310a472
kimfucious/pythonic_algocasts
/exercises/reversestring.py
273
4.375
4
# --- Directions # Given a string, return a new string with the reversed order of characters # --- Examples # reverse('apple') # returns 'leppa' # reverse('hello') # returns 'olleh' # reverse('Greetings!') # returns '!sgniteerG' def reverse(string): pass
true
b93be8d587df03aa1ef86361067b3ae45c42e861
kimfucious/pythonic_algocasts
/solutions/levelwidth.py
510
4.15625
4
# --- Directions # Given the root node of a tree, return a list where each element is the width # of the tree at each level. # --- Example # Given: # 0 # / | \ # 1 2 3 # | | # 4 5 # Answer: [1, 3, 2] def level_width(root): widths = [0] l = [root, "end"] while len(l) > 1: node = l.pop(0) if node == "end": l.append("end") widths.append(0) else: l = l + node.children widths[-1] += 1 return widths
true
fdc8646c69a3c4eb44cd016b4d1708ca77acef07
kimfucious/pythonic_algocasts
/solutions/palindrome.py
410
4.40625
4
# --- Directions # Given a string, return True if the string is a palindrome or False if it is # not. Palindromes are strings that form the same word if it is reversed. *Do* # include spaces and punctuation in determining if the string is a palindrome. # --- Examples: # palindrome("abba") # returns True # palindrome("abcdefg") # returns False def palindrome(string): return string == string[::-1]
true
7484096aff7b568bf17f4bc683de3a538807ce52
kimfucious/pythonic_algocasts
/solutions/capitalize.py
1,010
4.4375
4
# --- Directions # Write a function that accepts a string. The function should capitalize the # first letter of each word in the string then return the capitalized string. # --- Examples # capitalize('a short sentence') --> 'A Short Sentence' # capitalize('a lazy fox') --> 'A Lazy Fox' # capitalize('look, it is working!') --> 'Look, It Is Working!' def capitalize(string): """ Using the Python str.title() method """ return string.title() # def capitalize(string): # """ # Using a loop on the string # """ # result = string[0].upper() # for index in range(1, len(string)): # if string[index-1] == " ": # result += string[index].upper() # else: # result += string[index] # return result # def capitalize(string): # """ # Using a loop on a list split from the string # """ # words = [] # for word in string.split(" "): # words.append(word[0].upper() + word[1:]) # return " ".join(words)
true
6744b752c094cf71d347868859037e6256cdb4e8
didomadresma/ebay_web_crawler
/ServiceTools/Switcher.py
978
4.28125
4
#!/usr/bin/env python3 __author__ = 'papermakkusu' class Switch(object): """ Simple imitation of Switch case tool in Python. Used for visual simplification """ value = None def __new__(class_, value): """ Assigns given value to class variable on class creation :return: Returns True if the assignment was a success :rtype: Boolean """ class_.value = value return True def case(*args): """ Matches given value with class value Possible utilization: #while Switch('b'): # if case('a'): # print("Sad face (T__T)") # if case('b'): # print("Eurica!") #>>> Eurica! :return: returns True if given argument is in .value field of Switch class :rtype: Boolean Doctest: >>> swi = Switch('Caramba!') >>> case('Pirates!') False >>> case('Caramba!') True """ return any(arg == Switch.value for arg in args)
true
e7d5d7e1c7a2d766c49de8e0009482ad488a3a63
Priktopic/python-dsa
/str_manipualtion/replace_string_"FOO"_"OOF".py
1,052
4.3125
4
""" If a string has "FOO", it will get replaced with "OOF". However, this might create new instances of "FOO". Write a program that goes through a string as many times as required to replace each instances of "FOO" with "OOF". Eg - In "FOOOOOOPLE", 1st time it will become "OOFOOOOPLE". Again we have "FOO", so the 2nd iteration it will become "OOOOFOOPLE". In the next iteration it will become "OOOOOOFPLE" since we have another "FOO". """ def string_manipulation(new_string, available_string, replace_string_with): s1="" for i in new_string: s1 += i # stores each chracter "i" in new string "s1" if available_string in s1: # checks if s1 contains "FOO" s1 = s1.replace(available_string,replace_string_with) # if condition satisfies, it replaces "FOO" with "OOF" and stores it in same "s1". # In the next iteration it adds, the new character "i" of "new_string" with "s1" that already contains replaced string. return s1 OUTPUT = string_manipulation ("FOOOOOOOPLE", "FOO", "OOF") print(OUTPUT)
true
57899dbcf24323514b453e3b1a9de5bc01379c8c
Priktopic/python-dsa
/linkedlist/largest_sum_of_ele.py
1,149
4.4375
4
''' You have been given an array containg numbers. Find and return the largest sum in a contiguous subarray within the input array. Example 1: arr= [1, 2, 3, -4, 6] The largest sum is 8, which is the sum of all elements of the array. Example 2: arr = [1, 2, -5, -4, 1, 6] The largest sum is 7, which is the sum of the last two elements of the array. ''' def max_sum_subarray(arr): current_sum = arr[0] # `current_sum` denotes the sum of a subarray max_sum = arr[0] # `max_sum` denotes the maximum value of `current_sum` ever # Loop from VALUE at index position 1 till the end of the array for element in arr[1:]: ''' # Compare (current_sum + element) vs (element) # If (current_sum + element) is higher, it denotes the addition of the element to the current subarray # If (element) alone is higher, it denotes the starting of a new subarray ''' current_sum = max(current_sum + element, element) # Update (overwrite) `max_sum`, if it is lower than the updated `current_sum` max_sum = max(current_sum, max_sum) return max_sum
true
17e30a414fdf6bf310fa229ddede6b7dd23551bc
Priktopic/python-dsa
/str_manipualtion/rmv_digits_replace_others_with_#.py
350
4.25
4
""" consider a string that will have digits in that, we need to remove all the not digits and replace the digits with # """ def replace_digits(s): s1 = "" for i in s: if i.isdigit(): s1 += i return(re.sub('[0-9]','#',s1)) # modified string which is after replacing the # with digits replace_digits("#2a$#b%c%561#")
true
153687f5a58296d127d14789c96ce8843eb236a0
dylanly/Python-Practice
/best_friends.py
386
4.25
4
list_friends = ['Ken', 'Mikey', 'Mitchell', 'Micow'] print("Below you can see all my best friends!\n") for friend in list_friends: print(friend) if 'Drew' not in list_friends: print("\n:O \nDrew is not in my friends list!!\n") list_friends.append('Drew') for friend in list_friends: print(friend) print("\nI fixed my best friend's list hehe xD")
true
7014390c7d7031113d04ac773ee1dec33950aeea
KKobuszewski/pwzn
/tasks/zaj2/zadanie1.py
1,623
4.15625
4
# -*- coding: utf-8 -*- def xrange(start=0, stop=None, step=None): """ Funkcja która działa jak funkcja range (wbudowana i z poprzednich zajęć) która działa dla liczb całkowitych. """ #print(args,stop,step) x = start if step is None: step = 1 if stop is None: stop = start x = 0 while x < stop: yield x x = x + step #print(list(xrange(2,15,2)))#przez print nie tworzy sie referencja; print(list(xrange(5))) """ range(n) creates a list containing all the integers 0..n-1. This is a problem if you do range(1000000), because you'll end up with a >4Mb list. xrange deals with this by returning an object that pretends to be a list, but just works out the number needed from the index asked for, and returns that. For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range(): In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange(). range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however) xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods. """
true
91023ff23cf97b09c25c2fe53f787aa764c8ca69
clark-ethan9595/CS108
/lab05/song.py
1,076
4.375
4
''' A program to specify verses, container, and desired food/beverage. Fall 2014 Lab 05 @author Ethan Clark (elc3) ''' #Prompt user for their own version of the song lyrics verses = int(input('Please give number of verses for song:')) container = input('Please give a container for your food/beverage:') substance = input('Please give a desired food/beverage:') #Fix the number of verses to a variable to use in the last verse of the song. number = verses #Use a loop to write the song with the user-desired verses, container, and substance. for count in range(verses, -1, -1): if verses != 0: print(verses, container + '(s) of', substance, 'on the wall,', verses, container + '(s) of', substance + '. Take one down, pass it around,', (verses - 1), container + '(s) of', substance, 'on the wall.') verses = verses - 1 else: print(verses, container + '(s) of', substance, 'on the wall,', verses, container + '(s) of', substance + '. Go to the store and buy some more.', number, container + '(s) of', substance, 'on the wall.') print('Finish')
true
8bcb5e719f1148779689d7d80422c468257a9f0f
clark-ethan9595/CS108
/lab02/einstein.py
729
4.21875
4
''' Variables and Expessions September 11, 2014 Lab 02 @author Ethan and Mollie (elc3 and mfh6) ''' #Ask user for a three digit number. number = int(input('Give a three digit number where the first and last digits are more than 2 apart : ')) #Get the reverse of the user entered number. rev_number = (number//1)%10 * 100 + (number//10)%10 * 10 + (number//100)%10 #Find the difference of the number and the reverse of the number. difference = abs(number - rev_number) #Find the reverse of the difference. rev_difference = (difference//1)%10 * 100 + (difference//10)%10 * 10 + (difference//100)%10 #Print the difference of the difference and the reverse of the difference. print(difference + rev_difference) print(rev_number)
true
2ab3022ae0ea51d58964fffd5887dbd5f1812974
huajianmao/pyleet
/solutions/a0056mergeintervals.py
1,085
4.21875
4
# -*- coding: utf-8 -*- ################################################ # # URL: # ===== # https://leetcode.com/problems/merge-intervals/ # # DESC: # ===== # Given a collection of intervals, merge all overlapping intervals. # # Example 1: # Input: [[1,3],[2,6],[8,10],[15,18]] # Output: [[1,6],[8,10],[15,18]] # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. # # Example 2: # Input: [[1,4],[4,5]] # Output: [[1,5]] # Explanation: Intervals [1,4] and [4,5] are considered overlapping. # ################################################ from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if len(intervals) <= 1: return intervals else: result = [] intervals.sort(key=lambda x: x[0]) current = intervals[0] for interval in intervals: if interval[0] <= current[1]: current = [current[0], max(interval[1], current[1])] else: result.append(current) current = interval result.append(current) return result
true
cd72d43f6a973cf8d0bb3b522e9226dc7f8eef76
ACES-DYPCOE/Data-Structure
/Searching and Sorting/Python/merge_sort.py
1,939
4.125
4
''' Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one''' '''////ALGORITHM//// #MergeSort(arr[], l, r) If r > l 1. Find the middle point to divide the array into two halves: middle m = (l+r)/2 2. Call mergeSort for first half: Call mergeSort(arr, l, m) 3. Call mergeSort for second half: Call mergeSort(arr, m+1, r) 4. Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r)''' '''Python program for implementation of MergeSort''' def mergeSort(arr): if len(arr) > 1: mid = len(arr) // 2 # Finding the mid of the array left = arr[:mid] # Dividing the array elements right = arr[mid:] # into 2 halves mergeSort(left) # Sorting the first half mergeSort(right) # Sorting the second half i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 # Checking if any element was left while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 # printing the list def printList(arr): for i in range(len(arr)): print(arr[i], end=" ") print() arr = [12, 11, 13, 5, 6, 7] print("Given array is: ") printList(arr) mergeSort(arr) print("Sorted array is: ") printList(arr)
true
aad803d232b8bb4e205cd3b0cac8233f228b44d3
ACES-DYPCOE/Data-Structure
/Searching and Sorting/Python/shell_sort.py
1,254
4.15625
4
#Shell sort algorithm using python #Shell sort algorithm is an improved form of insertion sort algorithm as it compares elements separated by a gap of several position. #In Shell sort algorithm, the elements in an array are sorted in multiple passes and in each pass, data are taken with smaller and smaller gap sizes. # However, the finale of shell sort algorithm is a plain insertion sort algorithm. def shellsort(a): #initialize the function definition gap=len(a)//2 #Return the number of items in a container while gap>0: for i in range(gap,len(a)): j=a[i] ##initialize j to a[i] pos=i #initialize pos to i while pos>=gap and j<a[pos-gap]: #inner while loop a[pos]=a[pos-gap] pos=pos-gap a[pos]=j gap=gap//2 n=int(input("Enter length of array: ")) print("Enter values in array: ") #taking input from user arr=[int(input()) for i in range(n)] shellsort(arr) #calling of function definition print("sorted array: ",arr) #Time complexity : O(n*log n) #space complexity : O(1)
true
f5cf5e85ffd22f6a59d4d1c1f183b2b668f82e29
faizanzafar40/Intro-to-Programming-in-Python
/2. Practice Programs/6. if_statement.py
298
4.1875
4
""" here I am using 'if' statement to make decisions based on user age """ age = int(input("Enter your age:")) if(age >= 18): print("You can watch R-Rated movies!") elif(age > 13 and age <= 17): print("You can watch PG-13 movies!") else: print("You should only watch Cartoon Network")
true
c56354bd9e49655c5f7f4a4c8f009ee7c13b7272
razi-rais/toy-crypto
/rsa.py
1,457
4.1875
4
# Toy RSA algo from rsaKeyGen import gen_keypair # Pick two primes, i.e. 13, 7. Try substituting different small primes prime1 = 13 prime2 = 7 # Their product is your modulus number modulus = prime1 * prime2 print "Take prime numbers %d, %d make composite number to use as modulus: %d" % (prime1, prime2, modulus) print "RSA security depends on the difficulty of determining the prime factors of a composite number." # Key generation is the most complicated part of RSA. See rsaKeyGen.py for algorithms print "\n*~*~*~ Key Generation *~*~*~" keys = gen_keypair(prime1, prime2) print "All possible keys:", keys # We'll go with the first keypair: pub 5, priv 29 pubkey = keys[0]['pub'] privkey = keys[0]['priv'] print "\nYour pubkey is %d, your privkey is %d\n" % (pubkey, privkey) def encrypt_char(num): # multiply num by itself, pubkey times r = num ** pubkey return r % modulus def decrypt_char(num): # multiply encrypted num by itself, modulus times r = num ** privkey return r % modulus def encrypt_word(word): encwd = '' for char in word: n = ord(char) enc = encrypt_char(n) encwd += chr(enc) return encwd def decrypt_word(word): decwd = '' for char in word: n = ord(char) dec = decrypt_char(n) decwd += chr(dec) return decwd encwd = encrypt_word('CLOUD') print "Encrypted word: ", encwd decwd = decrypt_word(encwd) print "Decrypted word: ", decwd
true
bc60a2c690b7f7e51f086f92258a7e9bc14ff466
raoliver/Self-Taught-Python
/Part II/Chapter 14.py
997
4.21875
4
##More OOP class Rectangle(): recs = []#class variable def __init__(self, w, l): self.width = w#Instance variable self.len = l self.recs.append((self.width, self.len))#Appends the object to the list recs def print_size(self): print("""{} by {}""".format(self.width, self.len)) r1 = Rectangle(10, 24) r2 = Rectangle(20, 40) r3 = Rectangle(100, 200) print(Rectangle.recs) ##Magic Methods class Lion: def __init__(self, name): self.name = name #Overrides inherited __repr__ method and prints name def __repr__(self): return self.name lion = Lion('Dilbert') print(lion) #Another Magic Method Example class AlwaysPositive: def __init__(self, number) : self.n = number ##overrides the add function to return the absolute value of 2 numbers added together def __add__(self, other): return abs(self.n + other.n) x = AlwaysPositive(-20) y = AlwaysPositive(10) print(x + y)
true
7633a1fedf0957e1577ffcae5d1b35fc894a3b34
knmarvel/backend-katas-functions-loops
/main.py
2,253
4.25
4
#!/usr/bin/env python import sys import math """Implements math functions without using operators except for '+' and '-' """ __author__ = "github.com/knmavel" def add(x, y): added = x + y return added def multiply(x, y): multiplied = 0 if x >= 0 and y >= 0: for counter in range(y): multiplied = add(multiplied, x) return multiplied if x <= 0 and y <= 0: for counter in range(-y): multiplied = add(multiplied, -x) return multiplied if x < 0 and y >= 0: for counter in range(y): multiplied = add(multiplied, x) return multiplied if x >= 0 and y < 0: for counter in range(x): multiplied = add(multiplied, y) return multiplied def power(x, n): print(x**n) powered = 1 for counter in range(n): powered = multiply(powered, x) return powered def factorial(x): if x == 0: return 1 for counter in range(x-1, 0, -1): x = multiply(x, counter) return x def fibonacci(n): fib = [0, 1] for index in range(0, n): fib.append(fib[index]+fib[index+1]) return fib[n] def main(): if len(sys.argv) < 3: print ('usage: python main.py {--add | --multiply | --power | --factorial | fibonacci } {[x ,y] | [x, y] | [x, n] | [x] | [n] ') sys.exit(1) if sys.argv[0] == "--add" or sys.argv[0] == "--multiply" or sys.argv[0] == "--power": if len(sys.argv) != 5: print("need two integer arguments for that function") else: if len(sys.argv) != 4: print("need one integer parameter for that function") option = sys.argv[1] numbers = sys.argv[2:] if option == '--add': print(add(int(numbers[0]), int(numbers[1]))) elif option == '--multiply': print(multiply(int(numbers[0]), int(numbers[1]))) elif option == '--power': print(power(int(numbers[0]), int(numbers[1]))) elif option == '--factorial': print(factorial(int(numbers[0]))) elif option == '--fibonacci': print(fibonacci(int(numbers[0]))) else: print ('unknown option: ' + option) sys.exit(1) if __name__ == '__main__': main()
true
e2755d36a518efc21f5c479c4c3f32a54408eade
behind-the-data/ccp
/chap2/name.py
534
4.3125
4
name = "ada lovelace" print(name.title()) # the title() method returns titlecased STRING. # All below are optional # Only Capital letters print(name.upper()) # Only Lower letters print(name.lower()) ## Concatenation ## first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_name) ## Pass a string variable within a string ## print("Hello, " + full_name.title() + "!") ## Store the above in a varialbe, then print said variable ## message = "Hello, " + full_name.title() + "!" print(message)
true
2d29f47c7b91c33feac52f38bf0168ac6918d821
jcol27/project-euler
/41.py
1,674
4.3125
4
import math import itertools ''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? Can use itertools similar to previous problem. We can use the rule than a number is divisible by three if and only if the sum of the digits of the number is divisible by three to see that for pandigital numbers, only those with 4 or 7 digits can be prime. ''' ''' Function to find if a number is prime, simply checks if a number is divisible by values other than one and itself. ''' def is_prime(num): if (num == 0 or num == 1): return 0 for i in range(2, math.floor(num/2) + 1): if (num % i == 0): return False return True # Create initial iterable and variables num = 0 count = 1 best = 0 # Since we only care about the largest, start at largest possible # and stop at first solution while best == 0: # Iterable for 7 digit pandigital numbers iterables = itertools.permutations(list(range(7,0,-1)),7) for num in iterables: num = int("".join(str(s) for s in num)) # Check if prime if (is_prime(num) and num > best): best = num break # Iterable for 4 digit pandigital numbers if best != 0: iterables = itertools.permutations(list(range(4,0,-1)),4) for num in iterables: num = int("".join(str(s) for s in num)) # Check if prime if (is_prime(num) and num > best): best = num break print(f"Solution = {best}")
true
5c4fc548e88cada634ce1e2c84bf0fa494d6b6a8
mparkash22/learning
/pythonfordatascience/raise.py
538
4.1875
4
#raise the value1 to value2 def raise_both(value1, value2): #function header """Raise value1 to the power of value 2 and vice versa""" #docstring new_value1= value1 ** value2 #function body new_value2= value2 ** value1 new_tuple = (new_value1, new_value2) return new_tuple #we can print the tuple value using index powr = raise_both(2,5) #function call print(powr[0]) print(powr[1]) #we can unpack the tuple and print the value power1,power2 = raise_both(2,5) print(power1) print(power2)
true
aec15d1708777d5cccc103aa309fab48491fb53c
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/04_tree_based_models_in_python/classification_and_regression_tree/02_entropy.py
1,607
4.125
4
#Using entropy as a criterion # #In this exercise, you'll train a classification tree on the Wisconsin Breast Cancer dataset using entropy as an information criterion. #You'll do so using all the 30 features in the dataset, which is split into 80% train and 20% test. ## ##X_train as well as the array of labels y_train are available in your workspace. # Import DecisionTreeClassifier from sklearn.tree from sklearn.tree import DecisionTreeClassifier # Instantiate dt_entropy, set 'entropy' as the information criterion dt_entropy = DecisionTreeClassifier(max_depth=8, criterion='entropy', random_state=1) # Fit dt_entropy to the training set dt_entropy.fit(X_train, y_train) #Entropy vs Gini index # #In this exercise you'll compare the test set accuracy of dt_entropy to the accuracy of another tree named dt_gini. The tree dt_gini was trained on the same dataset using the same parameters except for the information criterion which was set to the gini index using the keyword 'gini'. # #X_test, y_test, dt_entropy, as well as accuracy_gini which corresponds to the test set accuracy achieved by dt_gini are available in your workspace. # Import accuracy_score from sklearn.metrics from sklearn.metrics import accuracy_score # Use dt_entropy to predict test set labels y_pred= dt_entropy.predict(X_test) # Evaluate accuracy_entropy accuracy_entropy = accuracy_score(y_pred, y_test) # Print accuracy_entropy print('Accuracy achieved by using entropy: ', accuracy_entropy) # Print accuracy_gini print('Accuracy achieved by using the gini index: ', accuracy_gini)
true
a5b6035fb3d38ef3459cfd842e230bbfb2148583
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/06_clustering_analysis_in_python/03_kmeans_clustering/01_example_kmeans.py
1,881
4.1875
4
#K-means clustering: first exercise # #This exercise will familiarize you with the usage of k-means clustering on a dataset. Let us use the Comic Con dataset and check how k-means clustering works on it. # #Recall the two steps of k-means clustering: # # Define cluster centers through kmeans() function. It has two required arguments: observations and number of clusters. # Assign cluster labels through the vq() function. It has two required arguments: observations and cluster centers. # #The data is stored in a Pandas data frame, comic_con. x_scaled and y_scaled are the column names of the standardized X and Y coordinates of people at a given point in time. # Import the kmeans and vq functions from scipy.cluster.vq import kmeans, vq # Generate cluster centers cluster_centers, distortion = kmeans(comic_con[['x_scaled', 'y_scaled']], 2) # Assign cluster labels comic_con['cluster_labels'], distortion_list =vq(comic_con[['x_scaled', 'y_scaled']], cluster_centers, check_finite=True) # Plot clusters sns.scatterplot(x='x_scaled', y='y_scaled', hue='cluster_labels', data = comic_con) plt.show() #Runtime of k-means clustering # #Recall that it took a significantly long time to run hierarchical clustering. How long does it take to run the kmeans() function on the FIFA dataset? # #The data is stored in a Pandas data frame, fifa. scaled_sliding_tackle and scaled_aggression are the relevant scaled columns. timeit and kmeans have been imported. # #Cluster centers are defined through the kmeans() function. It has two required arguments: observations and number of clusters. You can use %timeit before a piece of code to check how long it takes to run. You can time the kmeans() function for three clusters on the fifa dataset. %timeit kmeans(fifa[['scaled_sliding_tackle', 'scaled_aggression']], 3)
true
5ca2cf2b0365dd45d8f5ff5dc17b8e21d6ab751f
remichartier/002_CodingPractice
/001_Python/20210829_1659_UdacityBSTPractice/BinarySearchTreePractice_v00.py
1,210
4.25
4
"""BST Practice Now try implementing a BST on your own. You'll use the same Node class as before: class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None This time, you'll implement search() and insert(). You should rewrite search() and not use your code from the last exercise so it takes advantage of BST properties. Feel free to make any helper functions you feel like you need, including the print_tree() function from earlier for debugging. You can assume that two nodes with the same value won't be inserted into the tree. Beware of all the complications discussed in the videos! Start Quiz Provided : """ class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): pass def search(self, find_val): return False # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print tree.search(4) # Should be False print tree.search(6)
true
c7f1a592ba1dc81f24bc3097fbde5f0784eecd35
remichartier/002_CodingPractice
/001_Python/20210818_2350_UdacityQuickSortAlgo/QuickSorAlgoPivotLast_v01.py
1,305
4.1875
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" # Note : method always starting with last element as pivot def quicksort(array): # quick sort with pivot # Then quick sort left_side of pivot and quick_sort right side of pivot # Then combine left_array + Pivot + Right Array # but reminder : it is an "in place" Algorithm #left = 0 #right = len(array) -1 def sort(left,right): pivot = right #for pos in range(left,right + 1): pos = left while pos != pivot and pos < right : # compare value at pos and value at pivot # if array(pivot) < array(pos), need to move pivot... if array[pivot] < array[pos]: tmp = array[pos] array[pos] = array[pivot-1] array[pivot-1] = array[pivot] array[pivot] = tmp pivot -= 1 pos = left else: pos +=1 # end loop # Now sort right array, since left array already sorted if left < pivot -1: sort(left,pivot-1) if pivot+1 < right: sort(pivot+1,right) sort(0,len(array)-1) return array test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] print(quicksort(test))
true
d975dee37afc80c487f6ff0b1723697f340b2448
ZeroDestru/aula-1-semestre
/aulas/oitavo3.py
1,764
4.125
4
import turtle myPen = turtle.Turtle() myPen.tracer(5) myPen.speed(5) myPen.color("blue") # This function draws a box by drawing each side of the square and using the fill function def box(intDim): myPen.begin_fill() # 0 deg. myPen.forward(intDim) myPen.left(90) # 90 deg. myPen.forward(intDim) myPen.left(90) # 180 deg. myPen.forward(intDim) myPen.left(90) # 270 deg. myPen.forward(intDim) myPen.end_fill() myPen.setheading(0) boxSize = 25 #Position myPen in top left area of the screen myPen.penup() myPen.forward(-100) myPen.setheading(90) myPen.forward(100) myPen.setheading(0) ##Here is an example of how to draw a box #box(boxSize) ##Here are some instructions on how to move "myPen" around before drawing a box. #myPen.setheading(0) #point to the right, 90 to go up, 180 to go to the left 270 to go down #myPen.penup() #myPen.forward(boxSize) #myPen.pendown() #Here is how your PixelArt is stored (using a "list of lists") pixels = [[0,0,1,0,0,0,0,0,1,0,0]] pixels.append([0,0,0,1,0,0,0,1,0,0,0]) pixels.append([0,0,1,1,1,1,1,1,1,0,0]) pixels.append([0,1,1,1,0,1,0,1,1,1,0]) pixels.append([1,1,1,1,1,1,1,1,1,1,1]) pixels.append([1,0,1,1,1,1,1,1,1,0,1]) pixels.append([1,0,1,0,0,0,0,0,1,0,1]) pixels.append([0,0,0,1,1,0,1,1,0,0,0]) for i in range (0,len(pixels)): for j in range (0,len(pixels[i])): if pixels[i][j]==1: box(boxSize) myPen.penup() myPen.forward(boxSize) myPen.pendown() myPen.setheading(270) myPen.penup() myPen.forward(boxSize) myPen.setheading(180) myPen.forward(boxSize*len(pixels[i])) myPen.setheading(0) myPen.pendown() myPen.getscreen().update()
true
92f0837d2b94b72d013e7cb41d72ef7f5c78fdf8
HYnam/MyPyTutor
/W2_Input.py
1,110
4.375
4
""" Input and Output Variables are used to store data for later use in a program. For example, the statement word = 'cats' assigns the string 'cats' to the variable word. We can then use the value stored in the variable in an expression. For example, sentence = 'I like ' + word + '!' will assign the string 'I like cats!' to the variable sentence. When creating a variable, we can use any name we like, but it’s better to choose a name which makes clear the meaning of the value in the variable. The first two lines of the provided code will ask the user to input two words, and will store them in variables word1 and word2. Below that is a call to the print function which outputs the value in a variable combined. Write an assignment statement in the space between that adds the strings word1 and word2, and stores the result in the variable combined. For example, if the words reap and pear are input, the output should be reappear. """ word1 = input("Enter the first word: ") word2 = input("Enter the second word: ") # Write your code in the space here: combined = word1 + word2 print(combined)
true
c21a9037c094373b18800d86a8a5c64ea1beb0f7
HYnam/MyPyTutor
/W6_range.py
711
4.53125
5
""" Using Range The built-in function range returns an iterable sequence of numbers. Write a function sum_range(start, end) which uses range to return the sum of the numbers from start up to, but not including, end. (Including start but excluding end is the default behaviour of range.) Write a function sum_evens(start, end) which does the same thing, but which only includes even numbers. You should also use range. """ def sum_range(start, end): x = range(start, end) count = 0 for n in x: count += n return count def sum_evens(start, end): count = 0 for i in range(start, end, 1): if(i % 2 == 0): count += i return count
true
0fbe09ab6841a44123707d905ee14be14e03fc53
HYnam/MyPyTutor
/W12_recursive_base2dec.py
354
4.125
4
""" Recursively Converting a List of Digits to a Number Write a recursive function base2dec(digits, base) that takes the list of digits in the given base and returns the corresponding base 10 number. """ def base2dec(digits, base): if len(digits) == 1: return digits[0] else: return digits[-1] + base * base2dec(digits[:-1], base)
true
8dc081fad4227c0456266c0eab5ae3fcf5ed4d36
HYnam/MyPyTutor
/W7_except_raise.py
1,736
4.5625
5
""" Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function validate_input(string) which takes a command string in the format 'command arg1 arg2' and returns the pair ('command', [arg1, arg2]), where arg1 and arg2 have been converted to floats. If the command is not one of 'add', 'sub', 'mul', or 'div', it must raise InvalidCommand. If the arguments cannot be converted to floats, it must raise InvalidCommand. """ class InvalidCommand(Exception): pass def validate_input(string): """ If string is a valid command, return its name and arguments. If string is not a valid command, raise InvalidCommand Valid commands: add x y sub x y mul x y div x y Parameters: string(str): a valid command (see above) Return: tuple<str, list<float>>: the command and its corresponding arguements Precondition: Arguments x and y must be convertable to float. """ # your code here lst = string.split(' ') commands = ['add', 'sub', 'mul', 'div'] if lst[0] not in commands: raise InvalidCommand() if len(lst) != 3: raise InvalidCommand() try: arg1 = float(lst[1]) arg2 = float(lst[2]) return(lst[0], [arg1, arg2]) except ValueError: raise InvalidCommand()
true
dc68b3a0f41f752b188744d0e1b0cdb547682b11
HYnam/MyPyTutor
/W3_if_vowels.py
1,070
4.5
4
""" If Statements Using Else In the previous question, we used an if statement to run code when a condition was True. Often, we want to do something if the condition is False as well. We can achieve this using else: if condition: code_if_true [code_if_true...] else: code_if_false [code_if_false...] Here, if condition evaluates to False, then Python will run the block of code under the else statement. For example, this code will print 'Python': x = 0 if x > 1: print('Monty') else: print('Python') Prompt the user to enter a character, and then print either 'vowel' or 'consonant' as appropriate. You may use the is_vowel function we’ve provided. You can call this with is_vowel(argument) e.g. vowel_or_not = is_vowel(a_variable). Alternatively you can just perform the logical test in the if condition. """ l = input("Enter the character: ") if l.lower() in ('a', 'e', 'i', 'o', 'u'): print("vowel") elif l.upper() in ('A', 'E', 'I', 'O', 'U'): print("vowel") else: print("consonant")
true
edb7cb3c4ee6562817d60924828836e66eed9011
PraveshKunwar/python-calculator
/Volumes/rcc.py
410
4.125
4
import math def rccCalc(): print(""" Please give me radius and height! Example: 9 10 9 would be radius and 10 would be height! """) takeSplitInput = input().split() if len(takeSplitInput) > 2 or len(takeSplitInput) < 2: print("Please give me two numbers only to work with!") value = (1/3)*(int(takeSplitInput[0]) ** 2)*(math.pi)*(int(takeSplitInput[1])) print(value)
true
32321cdb22a57d52a55354adc67bdf020828a8e1
nitinaggarwal1986/learnpythonthehardway
/ex20a.py
1,317
4.375
4
# import the argv to call arguments at the script call from sys module. from sys import argv # Asking user to pass the file name as an argument. script, input_file = argv # To define a function to print the whole file passed into function as # a parameter f. def print_all(f): print f.read() # To define a rewind function to bring the current location on file back to # starting position. def rewind(f): f.seek(0) # To define a function that will print the line at the position given bytearray # line_count in the file f. def print_a_line(line_count, f): print line_count, f.readline() # To open the input_file in the variable name current_file. current_file = open(input_file) print "First let's print the whole file: \n" # To print the whole of the file using print_all function. print_all(current_file) print "Now let's rewind, kind of like a tape." # To rewind the file to the original location so that it can be read from the # start again. rewind(current_file) print "Let's print three lines:" # To print the first three lines of the file by a consecutive calls of # print_a_line function. current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
true
8872d33049899b976831cea4e01e8fc73f88ebef
bvsbrk/Learn-Python
/Basics/using_super_keyword.py
684
4.46875
4
class Animal: name = "animal" """ Here animal class have variable name with value animal Child class that is dog have variable name with value dog So usually child class overrides super class so from child class If we see the value of name is dog To get the value of super class we use 'super' :keyword """ def __init__(self): print("Super class constructor was called") class Dog(Animal): name = "dog" def __init__(self): print(self.name) # Prints dog print(super().name) # Prints animal super(Dog, self).__init__() # Super class constructor was called here def main(): dog = Dog() main()
true
7ae4858f192bbbc1540e1fb3d8a3831e6a04f6e9
CodeItISR/Python
/Youtube/data_types.py
979
4.59375
5
# KEY : VALUE - to get a value need to access it like a list with the key # key can be string or int or float, but it need to be uniqe # Creating an dictionary dictionary = {1: 2 ,"B": "hello" , "C" : 5.2} # Adding a Key "D" with value awesome dictionary["D"] = "awesome" print(dictionary["D"]) # Print the dictionary as list of tuples print(list(dictionary.items())) #==================== # tuple is like a list except its static, cant change the values # 1 item tuple need to be with comma (50, ) # Create a tuple variable tup = (1,2,3) # Print the second item print(tup[1]) #==================== # multi dimensional list # contain list that have items that can be list # set the variable to be a list with list item list_of_lists = [[1,2,3], ["hello", "1"], 5] print(list_of_lists[0]) # print the first item - [1,2,3] print(list_of_lists[1][0]) # print the first item in the second item of the all list - hello print(list_of_lists[2]) # print the third item - 5
true
a1c2a407f9e3c3bac070a84390674c519ca8ed63
scidam/algos
/algorithms/sorting/bubble.py
1,446
4.21875
4
__author__ = "Dmitry E. Kislov" __created__ = "29.06.2018" __email__ = "kislov@easydan.com" def bubble_sort(array, order='asc'): """Bubble sorting algorithm. This is a bit smart implementation of the bubble sorting algoritm. It stops if obtained sequence is already ordered. **Parameters** :param array: an iterable to be sorted :param order: a string, defines ordering, default value is `asc` (that is ascending order) :type array: list, tuple :type order: string :returns: sorted list of input values :rtype: list """ from operator import lt, gt n = len(array) sorted_array = list(array) comparison = lt if order == 'desc' else gt for j in range(n): done = True for i in range(n - j - 1): if comparison(sorted_array[i], sorted_array[i + 1]): sorted_array[i + 1], sorted_array[i] = \ sorted_array[i], sorted_array[i + 1] done = False if done: break return sorted_array if __name__ == '__main__': array = range(10) print("Source array: {}".format(array)) sorted_array = bubble_sort(array) print("Sorted array: {}".format(sorted_array)) array_reversed = range(10)[::-1] print("Reversed array: {}".format(array_reversed)) sorted_array = bubble_sort(array_reversed) print("Sorted array: {}".format(sorted_array))
true
30cf241927d7fb24f62b6ec3afd4952e05d01032
KrisztianS/pallida-basic-exam-trial
/namefromemail/name_from_email.py
512
4.40625
4
# Create a function that takes email address as input in the following format: # firstName.lastName@exam.com # and returns a string that represents the user name in the following format: # last_name first_name # example: "elek.viz@exam.com" for this input the output should be: "Viz Elek" # accents does not matter email = input("Give me your email adress: ") def name_from_email(email): name = email.split("@") split_name = name[0].split(".") split_name.reverse() return (' '.join(split_name)) print(name_from_email(email))
true
b3561a5180fc2c219f1b7fa97a663de9ea0be793
Whitatt/Python-Projects
/Database1.py
1,057
4.25
4
import sqlite3 conn = sqlite3.connect('database1.db') with conn: cur = conn.cursor() #Below I have created a table of file list cur.execute("CREATE TABLE IF NOT EXISTS tbl_filelist(ID INTEGER PRIMARY KEY AUTOINCREMENT, \ col_items TEXT)") # in the file list, i have created a column of items. conn.commit() conn = sqlite3.connect('database1.db') #tuple of items items_tuple = ('information.docx', 'Hello.txt', 'myImage.png', 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg') # loop through each object in the tuple to find the filelist that ends in .txt for x in items_tuple: if x.endswith('.txt'): with conn: cur = conn.cursor() #the value for each row will be one filelist out of the tuple therefore (x,) # will denote a one element tuple for each filelist ending with .txt cur.execute("INSERT INTO tbl_filelist (col_items) VALUES (?)", (x,)) print(x) conn.close() #the output should be #Hello.txt #World.txt
true
7d32b260a8251dfe0bd111e615f8c84975d7102c
zarkle/code_challenges
/codility/interviewing_io/prechallenge2.py
2,097
4.1875
4
""" Mary has N candies. The i-th candy is of a type represented by an interger T[i]. Mary's parents told her to share the candies with her brother. She must give him exactly half the candies. Fortunately, the number of candies N is even. After giving away half the candies, Mary will eat the remaining ones. She loves variety, so she wants to have candies of various types. Can you find the maximum number of different types of candy that Mary can eat? Write a function: [Java] class Solution { puiblic int solution(int[] T); } [Python] def solution(T) that, given an array T of N integers, representing all the types of candies, returns the maximum possible number of different types of candy that Mary can eat after she has given N/2 candies to her brother. For example, given: T = [3, 4, 7, 7, 6, 6] the function should return 3. One optimal strategy for Mary is to give away one candy of type 4, one of type 7 and one of type 6. The remaining candies would be [3, 7, 6]: three candies of different types. Given: T = [80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789] the function should also return 3. Here, Mary starts with ten candies. She can give away five candies of type 80 and the remaining candies would be [1000000000, 123456789, 80, 80, 80]. There are only three different types in total, i.e. 80, 1000000000 and 123456789. Write an efficient algorithm for the following assumptions: - N is an integer within the range [2 .. 100,000]; - N is even; - each element of array T is an integer with the range """ def candy(candies): diff = set(candies) if len(diff) > len(candies) // 2: return len(candies) // 2 else: return len(diff) def solution(T): diff_candies = set(T) if len(diff_candies) < len(T) // 2: return len(diff_candies) return len(T) // 2 print(candy([3, 4, 7, 7, 6, 6])) # returns 3 print(candy([80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789])) # returns 3 print(candy([1, 1, 7, 7, 6, 6])) # returns 3 print(candy([1, 7, 7, 7])) # returns 2 print(candy([7, 7, 7, 7])) # returns 1
true
ba81db6eb0340d66bc8151f3616069d4d6a994a0
zarkle/code_challenges
/dsa/recursion/homework_solution.py
2,026
4.3125
4
def fact(n): """ Returns factorial of n (n!). Note use of recursion """ # BASE CASE! if n == 0: return 1 # Recursion! else: return n * fact(n-1) def rec_sum(n): """ Problem 1 Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer For example, if n=4 , return 4+3+2+1+0, which is 10. This problem is very similar to the factorial problem presented during the introduction to recursion. Remember, always think of what the base case will look like. In this case, we have a base case of n =0 (Note, you could have also designed the cut off to be 1). In this case, we have: n + (n-1) + (n-2) + .... + 0 """ if n == 0: return 0 else: return n + rec_sum(n - 1) # using helper function def helper(n, sum): if n == 0: return sum sum += n return helper(n-1, sum) return helper(n, 0) def sum_func(n): """Given an integer, create a function which returns the sum of all the individual digits in that integer. For example: if n = 4321, return 4+3+2+1""" if len(str(n)) == 1: return n else: return n % 10 + sum_func(n // 10) # using helper function def helper(n, sum): if len(str(n)) == 1: sum += n return sum sum += n % 10 return helper(n // 10, sum) return helper(n, 0) def word_split(phrase,list_of_words, output = None): """ Note, this is a more advanced problem than the previous two! It aso has a lot of variation possibilities and we're ignoring strict requirements here. Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is completely splittable. """ pass
true
84ba5a4f2a1b9761148d8ec7c803bb7732f3e75a
zarkle/code_challenges
/fcc_pyalgo/07_minesweeper.py
1,491
4.5
4
""" Write a function that wil take 3 arguments: - bombs = list of bomb locations - rows - columns mine_sweeper([[0,0], [1,2]], 3, 4) translates to: - bomb at row index 0, column index 0 - bomb at row index 1, column index 2 - 3 rows (0, 1, 2) - 4 columns (0, 1, 2, 3) [2 bomb location coordinates in a 3x4 matrix] we should return a 3 x 4 array (-1) = bomb (ends up deleting this stuff because he changed the original bomb location from [0,1] to [1,2]) [[-1, -1, 1, 0], [2, 2, 1, 0], the 2 bombs means 2 bombs in surrounding cells [1,0] knows [0,0] and [0,1] have ...?... 0,0,0,0]] Visualization: https://goo.gl/h4h4ax similar: https://leetcode.com/problems/minesweeper/ """ def minesweeper(bombs, rows, cols): # build field using 2 for loops in one line, place 0 in each cell field = [[0 for i in range(cols)] for j in range(rows)] # bomb locations change from 0 to -1 for location in bombs: (bomb_row, bomb_col) = location field[bomb_row][bomb_col] = -1 # go through rows and columns to find bombs (check numerical value of cell); can put these directly in for loop, it's separate just for visualization row_range = range(bomb_row - 1, bomb_row + 2) col_range = range(bomb_col - 1, bomb_col + 2) for i in row_range: for j in col_range: if 0 <= i < rows and 0 <= j < cols and field[i][j] != -1: field[i][j] += 1 return field print(minesweeper([[0, 0], [1, 2]], 3, 4))
true
c2a5429480d3c26fefd305b728e27c8fe7824ebf
zarkle/code_challenges
/hackerrank/16_tree_postorder_trav.py
783
4.21875
4
# https://www.hackerrank.com/challenges/tree-postorder-traversal/problem """ Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ def postOrder(root): #Write your code here traverse = '' def _walk(node=None): nonlocal traverse if node is None: return if node.left: _walk(node.left) if node.right: _walk(node.right) traverse += str(node.info) + ' ' _walk(root) return print(traverse[:-1]) # simpler def postOrder(root): #Write your code here if root: postOrder(root.left) postOrder(root.right) print(root.info, end=' ')
true
7624dfe6435e1575121da552c169df512f974c24
rxu17/physics_simulations
/monte_carlo/toy_monte_carlo/GluonAngle.py
1,025
4.1875
4
# Rixing Xu # # This program displays the accept and reject method - generate a value x with a pdf(x) as the gaussian distribution. # Then generate a y value where if it is greater than the pdf(x), we reject that x, otherwise we accept it # Physically, the gluon is emitted from the quark at an angle # Assumptions: the gluon is emitted between 0 and pi/2 radians, and its angle has a gaussian distribution import math import random import matplotlib.pyplot as plt angles = [] mean = math.pi/2 # sets the mean and std for the gaussian function std = 2 while len(angles) != 1000: x = random.random()*(math.pi/2.00) # our generated angle to accept or reject y = random.random() g = math.exp((-(x-mean)**2)/(2*std))/(2*math.sqrt(std*math.pi)) # gaussian density distribution personalized for gluon angle if g >= y: angles.append(x) plt.hist(angles, bins = 20, normed = True) plt.title("Distribution of Gluon Angle") plt.xlabel("Angle of emitted gluon") plt.ylabel("Density") plt.show()
true
c6be4757dcfe28f09cee4360444ede6068058a8b
omarMahmood05/python_giraffe_yt
/Python Basics/13 Dictionaries.py
786
4.40625
4
# Dict. in python is just like dicts in real life. You give a word and then assign a meaning to it. Like key -> An instrument used to open someting speciftc. # In python we do almost the same give a key and then a value to it. For eg Jan -> January monthConversions = { "Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April", "May": "May", "Jun": "June", "Jul": "July", "Aug": "August", "Sept": "September", "Oct": "October", "Nov": "November", "Dec": "December", } print(monthConversions["Sept"]) print(monthConversions.get("Mar")) #Using get is much better than using [] because you can add a default value incase the key is not found for eg -> print(monthConversions.get("Afr", "Key Not Found"))
true
2935d9e5617f497d5eb145bc473650ab021d996a
huangqiank/Algorithm
/leetcode/sorting/sort_color.py
1,112
4.21875
4
# Given an array with n objects colored red, # white or blue, sort them in-place  # so that objects of the same color are adjacent, # with the colors in the order red, white and blue. # Here, we will use the integers # 0, 1, and 2 to represent the color red, white, and blue respectively. # Note: You are not suppose to use the library's sort function for this problem. # Example: # Input: [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] class Solution: def sortColors(self, nums): if not nums: return nums p=0 q = len(nums)-1 self.quick_sort(nums,p,q) def quick_sort(self,nums,p,q): if p<q: d = self.quick_sort_help(nums,p,q) self.quick_sort(nums,d+1,q) self.quick_sort(nums,p,d-1) def quick_sort_help(self,nums,p,q): j = p-1 for i in range(p,q): if nums[i] < nums[q]: j+=1 nums[i],nums[j] = nums[j],nums[i] j+=1 nums[j],nums[q] = nums[q],nums[j] return j a= "abcdef" print(a[:3]) print(a[:3] + "e" + a[3:]) print(a[6:]) print(a[0])
true
317f0783b9e840b41f9d422896475d5d76949889
huangqiank/Algorithm
/leetcode/tree/binary_tree_level_order_traversal2.py
1,205
4.15625
4
##Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). ##For example: ##Given binary tree [3,9,20,null,null,15,7], ## 3 ## / \ ## 9 20 ## / \ ## 15 7 ##return its bottom-up level order traversal as: ##[ ## [15,7], ## [9,20], ## [3] ##] # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root): if not root: return res = [] queue = [[root]] self.levelOrderBottom_help(queue, res) def levelOrderBottom_help(self, queue, res): while queue: this_Level = [] cur = queue.pop(0) tmp =[] for node in cur: this_Level.append(node.val) if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) if len(tmp) > 0: queue.append(tmp) res.append(this_Level) res.reverse() return res
true
f07911a813545ba8213b8500356406cd1a3fb8af
Hyeongseock/EulerProject
/Problem004.py
1,832
4.15625
4
''' Largest palindrome product Problem 4 ''' ''' English version 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. ''' #Make empty list to add number number_list = [] #the first number is 100 because of 3-digit number for i in range(100, 999) : for j in range(100, 999) : number = i * j number = str(number) #transforming from integer to string for checking each digit number if len(number) == 6 : #check number's lenth if number[0]==number[5] and number[1]==number[4] and number[2]==number[3] : #check whether the number is palindrome number_list.append(int(number)) print(max(number_list)) #time spent : 0.312 seconds ''' Korean version 앞에서부터 읽을 때나 뒤에서부터 읽을 때나 모양이 같은 수를 대칭수(palindrome)라고 부릅니다. 두 자리 수를 곱해 만들 수 있는 대칭수 중 가장 큰 수는 9009 (= 91 × 99) 입니다. 세 자리 수를 곱해 만들 수 있는 가장 큰 대칭수는 얼마입니까? ''' #숫자를 넣어줄 리스트를 생성 number_list = [] #세 자리 수 두개를 곱해야 하므로 최초의 값은 100 for i in range(100, 999) : for j in range(100, 999) : number = i * j number = str(number) #각각의 자리수에 어떤 숫자가 있는지 체크하기 위해 integer에서 string으로 타입 변환 if len(number) == 6 : #6자리인지 체크 if number[0]==number[5] and number[1]==number[4] and number[2]==number[3] : #대칭수인지 체크 number_list.append(int(number)) print(max(number_list)) #걸린 시간 : 0.312 seconds
true
88021e789e0602fff3527af5edd82e2db4e5376c
omolea/BYUI_CS101
/week_02/team_activity.py
2,155
4.15625
4
""" Jacob Padgett W02 Team Activity: Bro Brian Wilson """ First_name = input("What is you first name: ") Last_name = input("What is you last name: ") Email_Address = input("What is you email: ") Phone_Number = input("What is you number: ") Job_Title = input("What is you job: ") ID_Number = input("What is you id: ") Hair_Color = input("What is your hair color: ") Eye_Color = input("What is your eye color: ") Month_Started = input("What is the month you started: ") In_Training = input("Are you in training (Yes/No): ") d = "----------------------------------------" print("The ID Card is:") print(d) print(f"{Last_name.upper()}, {First_name.capitalize()}") print(Job_Title.title()) print(ID_Number, "\n") print(Email_Address.lower()) print(Phone_Number, "\n") print(f"Hair: {Hair_Color.capitalize()}\t\tEyes: {Eye_Color.capitalize()}") print( f"Month Started: {Month_Started.capitalize()}\tTraining: {In_Training.capitalize()}" ) print(d) """ Below is my personal code for the assignment """ # d = "----------------------------------------" # First_Name = input("What is your first name: ") # Last_Name = input("What is your last name: ") # Email_Address = input("What is your email address: ") # Phone_Number = input("What is your phone number: ") # Job_Title = input("What is your job title: ") # ID_Number = input("What is your ID number: ") # Hair_Color = input("What is your hair color: ") # Eye_Color = input("What is your eye color: ") # Month_Started = input("What is the month you started: ") # In_Training = input("Are you in training (Yes/No): ") # lst = [ # First_Name, # index 0 # Last_Name, # index 1 # Email_Address, # index 2 # Phone_Number, # index 3 # Job_Title, # index 4 # ID_Number, # index 5 # Hair_Color, # index 6 # Eye_Color, # index 7 # Month_Started, # index 8 # In_Training, # index 9 # ] # badge = f""" # {d} # {lst[1].upper()}, {lst[0].capitalize()} # {lst[4].title()} # ID: {lst[5]} # {lst[2].lower()} # {lst[3]} # Hair: {lst[6].capitalize()}\tEyes: {lst[7].capitalize()} # Month: {lst[8].capitalize()}\tTraining: {lst[9].capitalize()} # {d} # """ # print(badge)
true
c3f197930c850ca43bc7c7339d1ab7482ea218bc
shoel-uddin/Digital-Crafts-Classes
/programming102/exercises/list_exercises.py
1,555
4.375
4
#Exercise 1 # Create a program that has a list of at least 3 of your favorite # foods in order and assign that list to a variable named "favorite_foods". # print out the value of your favorite food by accessing by it's index. # print out the last item on the list as well. favorite_foods = ["Pizza", "Pasta", "Byriani"] print (favorite_foods[2]) print (favorite_foods[-1]) # #Exercise 2 # #Create a program that contains a list of 4 different "things" around you. # # Print out the each item on a new line with the number of it's # # index in front of the item. # # 0. Coffee Cup # # 1. Speaker # # 2. Monitor # # 3. Keyboard random_things = ["Mug", "Lamp", "Fan", "Boxes"] index = 0 while index < len(random_things): things = random_things[index] print("%d: %s" % (index + 1, things)) #things [index] index += 1 # #Using the code from exercise 2, prompt the user for # # which item the user thinks is the most interesting. # # Tell the user to use numbers to pick. (IE 0-3). # # When the user has entered the value print out the # # selection that the user chose with some sort of pithy message # # associated with the choice. # # "You chose Coffee Cup, You must like coffee!" interests = int(input("Which do you thing is most interresting? (Pick 1-4)\n")) if interests == 0: print (f"You chose {random_things[0]}. You must be thursty") elif interests == 1: print ("You must need some light") elif interests == 2: print ("It must be hot lets get some air flowing") else: print ("would you like some to use")
true
28c51e037e37d5567b59afb6abb3cbdf40f9e64b
Eccie-K/pycharm-projects
/looping.py
445
4.28125
4
#looping - repeating a task a number of times # types of loops: For loop and while loop # modcom.co.ke/datascience counter = 1 # beginning of the loop while counter <= 10: # you can count from any value print("hello", counter) counter = counter +1 # incrementing z = 9 while z >= -9: print("you", z) z = z-3 y = 1960 while y<=2060: print("hey", y) y = y +1 for q in range(2020, 1961, -1): print("see", q)
true
d1bbfae6e3467c8557852939faf5cdd1daa1f2ca
Robock/problem_solving
/interview_code_14.py
1,127
4.125
4
#Given a non-finite stream of characters, output an "A" if the characters "xxx" are found in exactly that sequence. #If the characters "xyx" are found instead, output a "B". #Do not re-process characters so as to output both an “A” and a “B” when processing the same input. For example: #1. The following input xxyxyxxxyxxx would produce the following output: BAA #2. The following input xxxyxyxxxxyyxyxyx would produce the following output: ABAB def abba(sample_string): three = '' new_string = '' for ch in sample_string: if len(three) == 0: if ch == 'x': three += ch else: three = '' elif len(three) == 1: if ch == 'x' or ch == 'y': three += ch else: three = '' elif len(three) == 2: if three == 'xx': if ch == 'x': new_string += 'A' three = '' elif ch == 'y': three = 'xy' else: three = '' elif three == 'xy': if ch == 'x': new_string += 'B' three = '' else: three = '' return new_string print(abba('xxyxyxxxyxxx')) print(abba('xxxyxyxxxxyyxyxyx'))
true
c7b7a3f789e1481bdd819b815820bebefddb6582
ashwin-pajankar/Python-Bootcamp
/Section09/08fact.py
225
4.3125
4
num = int(input("Please enter an integer: ")) fact = 1 if num == 0: print("Factorial of 0 is 1.") else: for i in range (1, num+1): fact = fact * i print("The factorial of {0} is {1}.".format(num, fact))
true
718ebb2daf0753bcaeeef1bfc6c226f320000859
zenvin/ImpraticalPythonProjects
/chapter_1/pig_latin_ch1.py
926
4.125
4
## This program will take a word and turn it into pig latin. import sys import random ##get input VOWELS = 'aeiouy' while True: word = input("Type a word and get its pig Latin translation: ") if word[0] in VOWELS: pig_Latin = word + 'way' else: pig_Latin = word[1:] + word[0] + 'ay' print() print("{}".format(pig_Latin), file=sys.stderr) try_again = input("\n\nTry again? (Press Enter else n to stop)\n ") if try_again.lower() == "n": sys.exit() ## if input start with a vowel do the following: ## add "way" to the end of the word ## else (input starts with a consonant) do the following: ## remove the constant (cut?) ## add it to the end of the input (append?) ## add "ay" after the constant ## perhaps we can add consonant and "ay" in one line ## elseif (if the input is a number or begins with a symbol) ## print("We need a leter")
true
d436073bd316bd56c8c9958785e0bb18476944a7
Soundaryachinnu/python_script
/classobj.py
1,360
4.125
4
#!/usr/bin/python class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method' # c = Child() # instance of child # c.childMethod() # child calls its method # c.parentMethod() # calls parent's method # c.setAttr(130) # again call parent's method # c.getAttr() # again call parent's method class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vecdddtor (%d, %d)' % (self.a, self.b) def __sub__(self,other): return Vector(self.a - other.a, self.b - other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 - v2 class chkgreater: def __init__(self,a,b): self.a = a; self.b = b; def __str__(self): return 'greater (%d)' % (self) def _gt__(self,a,b): if(self.a > self.b): return chkgreater(self.a); else: return chkgreater(self.b); print chkgreater(10,4);
true
f60b812a06af2b1a20d6f8c609c5c06492fe3f8c
Arsal-Sheikh/Dungeon-Escape---CS-30-Final
/gamemap.py
2,604
4.25
4
class Dungeon: def __init__(self, name, riddle, answer): """Creates a dungeon Args: name (string): The name of the dungeon riddle (string): The riddle to solve the dungeon answer (string): The answer to the riddle """ self.name = name self.riddle = riddle self.answer = answer def __str__(self): """Returns the name of the dungeon Returns: string: The name of the dungeon """ return self.name def __len__(self): """Returns the length of the name of the dungeon Returns: int: Length of the dungeon name """ return len(self.name) class GameMap: def __init__(self, gamemap): """Creates a gamemap Args: gamemap (list[Dungeon]): A list of the dungeons in order """ self.gamemap = gamemap def display(self, position): """Prints the dungeons out Args: position (int): The dungeon the player is in """ size = max(map(len, self.gamemap)) print(f"|{'-'*(size+2)}|") print(f"| {'Start'.ljust(size)} |") for i, line in enumerate(self.gamemap): if i == position: print(f"|{'='*(size+2)}|") print(f"| {str(line).ljust(size)} |") print(f"|{'='*(size+2)}|") else: print(f"| {str(line).ljust(size)} |") print(f"| {'Finish'.ljust(size)} |") print(f"|{'-'*(size+2)}|") gamemap = GameMap( [ Dungeon( "Dungeon 1", "What has to be broken before you can use it? (Hint: It's food)", "egg", ), Dungeon( "Dungeon 2", "I’m tall when I’m young, and I’m short when I’m old. What am I?", "candle", ), Dungeon( "Dungeon 3", "What month of the year has 28 days?", "all", ), Dungeon( "Dungeon 4", "What is full of holes but still holds water?", "sponge", ), Dungeon( "Dungeon 5", "What question can you never answer yes to?", "asleep", ), Dungeon( "Dungeon 6", "What is always in front of you but can’t be seen?", "future", ), Dungeon( "Dungeon 7", "What can you break, even if you never pick it up or touch it?", "promise", ), ] )
true
d9736075107c9ca1f288291a0109789e658d00c1
1ekrem/python
/CrashCourse/chapter10/tiy103.py
1,962
4.375
4
''' 10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt. 10-4. Guest Book: Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file. 10-5. Programming Poll: Write a while loop that asks people why they like programming. Each time someone enters a reason, add their reason to a file that stores all the responses. ''' filename = "C://PythonClass//CrashCourse//chapter10//sampleFiles//guests.txt" name = str(input("Can you please enter your name?: \n")) name2 = ('{}\n').format(name) try: with open(filename) as read_object: cont = read_object.readlines() cont2 = [] for i in cont: cont2.append(i.rstrip()) if name not in cont2: with open(filename, 'a') as file_object: file_object.write(name2) print(name + " is added to the guests list. Thank you!") else: print(name + " is in the guest list") print("Current Names in the file: ", cont2) except FileNotFoundError: print("File not found.") print("--- NEW LINE ---") """ 10-5. Programming Poll: Write a while loop that asks people why they like programming. Each time someone enters a reason, add their reason to a file that stores all the responses. """ filename105 = 'C://PythonClass//CrashCourse//chapter10//sampleFiles//filename105.txt' responses = [] while True: response = input("Why do you like programming?:\n") responses.append(response) continue_poll = input("Would you like to let someone else respond? (y/n) ") if continue_poll != 'y': break with open(filename105, 'w') as f: for i in responses: f.write(i + "\n")
true
9a6a512989a683662cb0947cc5b7ad2d3ba903e7
1ekrem/python
/CrashCourse/chapter8/tiy86.py
2,533
4.75
5
""" 8-6. City Names: Write a function called city_country() that takes in the name of a city and its country. The function should return a string formatted like this: "Santiago, Chile" Call your function with at least three city-country pairs, and print the value that’s returned. """ def city_country(cityName, countryName): return (cityName + ", "+ countryName) city_1 = city_country("Santiago", "Chile") print(city_1) city_2 = city_country("New York City", "NY") print(city_2) city_3 = city_country("Barcelona", "Spain") print(city_3) print("------- NEW LINE --------") """8-7. Album: Write a function called make_album() that builds a dictionary describing a music album. The function should take in an artist name and an album title, and it should return a dictionary containing these two pieces of information. Use the function to make three dictionaries representing different albums. Print each return value to show that the dictionaries are storing the album information correctly. Add an optional parameter to make_album() that allows you to store the number of tracks on an album. If the calling line includes a value for the number of tracks, add that value to the album’s dictionary. Make at least one new function call that includes the number of tracks on an album.""" def make_album(artistName, albumTitle, numberofTracks=''): album = { 'Artist Name': artistName, 'Album Title': albumTitle } if numberofTracks: album['Number of Tracks'] = numberofTracks return album artist1 = make_album("Ekrem", "Hello1") artist2 = make_album("Daria", "Sensitive2") artist3 = make_album("Pupsik", "Always Hungry", 3) print(artist1) print(artist2) print(artist3) """8-8. User Albums: Start with your program from Exercise 8-7. Write a while loop that allows users to enter an album’s artist and title. Once you have that information, call make_album() with the user’s input and print the dictionary that’s created. Be sure to include a quit value in the while loop.""" user_question = input("\nWould you like me to ask you some questions?: ") if user_question.title() == 'Yes': while True: print("If you would like me to stop, please type 'stop' below") artist_name = input("Enter Artist's name: ") if artist_name == 'stop': break album_title = input("Enter Artist's album title: ") artist_generation = make_album(artist_name,album_title) print(artist_generation)
true
38f7a26fd5f45b93c1d1ed6669bd362a55e2f641
1ekrem/python
/CrashCourse/chapter8/tiy89.py
1,670
4.46875
4
"""8-9. Magicians: Make a list of magician’s names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.""" def show_magicians(magicians): for name in magicians: print(name) names = ['Ekrem', 'Daria', 'Pupsik'] show_magicians(names) """8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a function called make_great() that modifies the list of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to see that the list has actually been modified.""" print("--- New line ---") def show_magicians2(magicians): for magician in magicians: print(magician) def make_great(magicians): #Building a new list to hold great magicians great_magicians = [] #Make each magician great, and add it to great_magician while magicians: magician = magicians.pop() great_magician = magician + " the Great" great_magicians.append (great_magician) for great_magician in great_magicians: magicians.append(great_magician) m_names = ['Tapar', 'Sencer', 'Hasan Sabbah'] show_magicians2(m_names) print("--- New line ---") make_great(m_names) """8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the function make_great() with a copy of the list of magicians’ names. Because the original list will be unchanged, return the new list and store it in a separate list. Call show_magicians() with each list to show that you have one list of the original names and one list with the Great added to each magician’s name. """ print("8-11")
true
8b816e4924d13dad093ea03f4967cae78eb494d5
Lyonidas/python_practice
/Challenge-4.py
1,759
4.1875
4
# Preston Hudson 11/21/19 Challenge 4 Written in Python #1. Write a function that takes a number as input and returns that number squared. def f(x): """ returns x squared :param x: int. :return: int sum of x squared """ return x ** 2 z = f(4) print(z) #2. Create a function that accepts a string as a parameter and prints it. def string(x): """ prints string :param x: string. :return: None """ print(x) string("Hello.") #3. Write a function that takes three required parameters and two optional parameters. def five_letters(a, b, c, d = 4, e = 5): """ return the addition of a, b, c, d, and e. :param a: int. :param b: int. :param c: int. :optparam d: int. :optparam e: int. :return: sum of params """ print(a + b + c + d + e) return a + b + c + d + e five_letters(1, 2, 3) #4. Write a program with 2 functions. The first function takes a integer then divides it by two. The second function takes the first functions output then multiplies it by 4. def divided_by_two(x): """ returns x divided by two :param x: int. :return: x / 2 """ return x / 2 def multiply_by_four(y): """ returns y times 4 :param y: int. :return: y * 4 """ return y * 4 y = divided_by_two(10) result = multiply_by_four(y) print(result) #5. Write a function that converts a string into a float def string_float(string): """ returns a float converted from a string :param string: string. :returns number: """ try: number = float(string) print(number) return number except ValueError: print("Input has to me string number.") string_float("21") string_float("Hundo.") #Complete
true
ceb3a00d884b1ee19687364f03d1755e7932c43d
Lyonidas/python_practice
/Challenge-6.py
1,652
4.1875
4
# Preston Hudson 11/25/19 Challenge 6 Written in Python #1. Print every character in the string "Camus". author = "Camus" print(author[0]) print(author[1]) print(author[2]) print(author[3]) print(author[4]) #2. Write a program that collects two strings from the user, inserts them into a string and prints a new string. response_one = input("Enter a noun: ") response_two = input("Enter a place: ") print("Yesterday I wrote a "+response_one+". I sent it to "+response_two+"!") #3. Use a method to capitalize a string. capital_string = "aldous Huxley was born in 1894.".capitalize() print(capital_string) #4. Call a method on a string that splits it into a list. "Where now?. Who now?. When now?.".split(".") #5. Take the list ... and turn it into a grammer correct string. words = ["The", "Fox", "jumped", "over", "the", "fence", "."] sentence = " ".join(words) print(sentence) #6. Replace all s's in a sentence with a $ sky = "A screaming comes across the sky." sky = sky.replace("s", "$") print(sky) #7. Use a method to find the first index of the character "m" in the string "Hemingway". print("Hemingway".index("m")) #8. Find dialogue from your favorite book and turn it into a string. socrates = """True knowledge, is the wisdom to admit that you know nothing.""" print(socrates[:]) #9. Create a string ... using concatination then multiplication. print("Three "+"Three "+"Three") print("Three " * 3) #10. Slice the string ... to only include characters before the comma. slice = """It was a bright cold day in April, and the clocks were striking thirteen.""" print(slice[0:34]) #Complete
true
76178534554fa030e42e9f7a2d23db151b282b09
jcalahan/ilikepy
/004-functions.py
311
4.15625
4
# This module explores the definition and invocation of a Python function. PI = 3.1459 def volume(h, r): value = PI * h * (r * r) return value height = 42 radius = 2.0 vol = volume(height, radius) print "Volume of a cylinder with height of %s and radius of %s is %s" \ % (height, radius, vol)
true
2b409cfeb923e07db625a46cf4a357cc627d5a20
niranjan2822/Interview1
/count Even and Odd numbers in a List.py
1,827
4.53125
5
# count Even and Odd numbers in a List ''' Given a list of numbers, write a Python program to count Even and Odd numbers in a List. Example: Input: list1 = [2, 7, 5, 64, 14] Output: Even = 3, odd = 2 Input: list2 = [12, 14, 95, 3] Output: Even = 2, odd = 2 ''' # Example 1: count Even and Odd numbers from given list using for loop # # Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. # If the condition satisfies, then increase even count else increase odd count. # Python program to count Even # and Odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 1] even_count, odd_count = 0, 0 # iterating each number in list for num in list1: # checking condition if num % 2 == 0: even_count += 1 else: odd_count += 1 print("Even numbers in the list: ", even_count) print("Odd numbers in the list: ", odd_count) # output : Even numbers in the list: 3 # Odd numbers in the list: 4 # Example 2: Using while loop # Python program to count Even and Odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] even_count, odd_count = 0, 0 num = 0 # using while loop while (num < len(list1)): # checking condition if list1[num] % 2 == 0: even_count += 1 else: odd_count += 1 # increment num num += 1 print("Even numbers in the list: ", even_count) print("Odd numbers in the list: ", odd_count) # Example 3 : Using Python Lambda Expressions # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] odd_count = len(list(filter(lambda x: (x%2 != 0) , list1))) # we can also do len(list1) - odd_count even_count = len(list(filter(lambda x: (x%2 == 0) , list1))) print("Even numbers in the list: ", even_count) print("Odd numbers in the list: ", odd_count)
true