blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4efffd09c623ecf7c64ef4c4e1bac18dc2ec8af5
harris44/PythonMaterial
/02_Advanced/algorithms_and_data_structures/01_Guessing_Game_with_Stupid_search.py
1,272
4.25
4
#!/usr/bin/python # -*- coding: utf-8 -*- from random import randrange """ Purpose: Stupid Search. In a list of numbers, user guesses a number. if it is correct, all is good. Else, next time, he/she will guess among the unguessed numbers. """ __author__ = "Udhay Prakash Pethakamsetty" list_of_numbers = range(10, 20) winning_number = randrange(10, 20) # place this statement in while loop, to increase probability of failure # attempts = len(list_of_numbers) while True: try: # attempts -= 1 guess_number = int(raw_input('Guess a number between 10 and 20:')) if guess_number == winning_number: print 'You Guessed correctly' break else: list_of_numbers.remove(guess_number) # print 'Your guess is closer by ', abs(guess_number - winning_number) print 'You guessed larger number' if guess_number > winning_number else 'You guessed lower number' if len(list_of_numbers) == 1: # attempts <= 1: print 'You are STUPID. Use your brain.' print 'Max. attempts completed. The winning number is', list_of_numbers[0] except Exception: print 'You STUPID! Guess properly' # all exceptions are catched here, as user should not know the problem
true
854b44a67d155c0c901d010a3e7ed5fc3735761a
liboyue/BOOM
/examples/BioASQ/extra_modules/bioasq/Tiler.py
671
4.3125
4
import abc from abc import abstractmethod ''' @Author: Khyathi Raghavi Chandu @Date: October 17 2017 This code contains the abstract class for Tiler. ''' ''' This is an Abstract class that serves as a template for implementations for tiling sentences. Currently there is only one technique implemented which is simple concatenation. ''' class Tiler(object): __metaclass__ = abc.ABCMeta @classmethod def __init__(self): pass #abstract method that should be implemented by the subclass that extends this abstract class @abstractmethod def tileSentences(self, sentences, pred_length): pass ''' instance = Tiler(["John"," has cancer"]) print instance.sentenceTiling() '''
true
9c86c21e8546fd8bde9a8b41187fd54e6c25b538
BumShubham/assignments-AcadView
/assignment8.py
1,591
4.46875
4
#Q1 #What is time tuple ''' Many of Python's time functions handle time as a tuple of 9 numbers, as shown below − Index Field Domain of Values 0 Year (4 digits) Ex.- 1995 1 Month 1 to 12 2 Day 1 to 31 3 Hour 0 to 23 4 Minute 0 to 59 5 Second 0 to 61 (60/61 are leap seconds) 6 Day of Week 0 to 6 (Monday to Sunday) 7 Day of Year 1 to 366 (Julian day) 8 DST -1,0,1 ''' #Q2 Write a program to get formatted time. import time import math import os print(time.strftime("%H:%M:%S")) #Q3 Extract month from the time. '''The function strftime takes '2' arguments one format and another time strftime(format,t = time) ''' print(time.strftime("%B,%m")) #Q4 Extract day from the time print(time.strftime("%d, %j")) #Q5 Extract date (ex : 11 in 11/01/2021) from the time. print(time.strftime("%d in %d/%m/%Y")) #Q6 Write a program to print time using localtime method. localtime = time.localtime(time.time()) print("Local current time :", localtime) #Q7 Find the factorial of a number input by user using math package functions. ''' Used to calculate factorial of a Number, using Math package function Math.factorial(number) is used ''' no=int(input('enter a no:')) print(math.factorial(no)) #Q8 Find the GCD of a number input by user using math package functions. ''' Used to calculate GCD of a number, using Math package function Math.gcd(no1,no2) is used ''' a=int(input('enter 1st no:')) b=int(input('enter 2nd no:')) print(math.gcd(a,b)) #Q9 Use OS package and do the following tasks: Get current working directory.Get the user environment. print(os.getcwd()) print(os.getenv('TEMP'))
true
8dfe63e954810cead138b81ef4c5fdf813cf224e
ShahrukhSharif/Applied_AI_Course
/Fundamental of Programming/python Intro/Prime_Number_Prg.py
364
4.125
4
# Wap to find Prime Number ''' num = 10 10/2,3,4,5 ---> Number is not pN OW PN ''' num = int(input("Input the Number")) is_devisible = False for i in range(2,num): if(num%i==0): is_devisible = True break if is_devisible is True: print("Number is Not Prime {}".format(num)) else: print("Number is Prime Number {}".format(num))
true
612ace04b4af232ecc5408a2c92f06620e75a17b
kitsuyui/dict_zip
/dict_zip/__init__.py
2,086
4.375
4
"""dict_zip This module provides a function that concatenates dictionaries. Like the zip function for lists, it concatenates dictionaries. Example: >>> from dict_zip import dict_zip >>> dict_zip({'a': 1, 'b': 2}, {'a': 3, 'b': 4}) {'a': (1, 3), 'b': (2, 4)} >>> from dict_zip import dict_zip_longest >>> dict_zip_longest({'a': 1, 'b': 2, 'c': 4}, {'a': 3, 'b': 4}) {'a': (1, 3), 'b': (2, 4), 'c': (4, None)} """ import functools def dict_zip(*dictionaries): """Returns a new dictionary \ concatenated with the dictionaries specified in the argument. The key is a common key that each dictionary has. The value is a tuple of the values of the dictionaries. >>> dict_zip({'a': 1, 'b': 2}, {'a': 3, 'b': 4}) {'a': (1, 3), 'b': (2, 4)} """ common_keys = functools.reduce( lambda x, y: x & y, (set(d.keys()) for d in dictionaries) ) return_dic = {} for dic in dictionaries: for key, val in dic.items(): if key in common_keys: return_dic.setdefault(key, []).append(val) return {key: tuple(val) for key, val in return_dic.items()} def dict_zip_longest(*dictionaries, fillvalue=None): """Returns a new dictionary \ concatenated with the dictionaries specified in the argument. The keys are the union set of the dictionaries. The value is a tuple of the values of the dictionaries. If the specified dictionary does not have the key, \ it is filled with fillvalue (default: None). >>> dict_zip_longest({'a': 1, 'b': 2, 'c': 4}, {'a': 3, 'b': 4}) {'a': (1, 3), 'b': (2, 4), 'c': (4, None)} """ all_keys = __all_keys(d.keys() for d in dictionaries) return_dic = {key: tuple() for key in all_keys} for dic in dictionaries: for key in all_keys: return_dic[key] += (dic.get(key, fillvalue),) return return_dic def __all_keys(iterables): keys = [] for iterable in iterables: for key in iterable: if key in keys: continue keys.append(key) return keys
true
5afd548624578e174b04bec5374c778e1bbed79f
dbwebb-se/python-slides
/oopython/example_code/vt23/kmom04/a_module.py
1,048
4.15625
4
""" How to mock function in a module. In a unit test we dont want to actually read a file so we will mock the read_file_content() function. But still test get_number_of_line_in_file(). """ def get_number_of_line_in_file(): """ Return how many lines exist in a file """ content = read_file_content() nr_lines = 0 for _ in content: nr_lines += 1 return nr_lines def read_file_content(): """ This function will be mocked """ with open("a file.txt", encoding="utf-8") as fd: return fd.readlines() def get_number_of_line_in_file_with_arg(filename): """ Return how many lines exist in a file. The filename is sent as argument """ content = read_file_content_with_arg(filename) nr_lines = 0 for _ in content: nr_lines += 1 return nr_lines def read_file_content_with_arg(filename): """ This function will be mocked and has an argument with can be asserted """ with open(filename, encoding="utf-8") as fd: return fd.readlines()
true
7bc58f3621d6e04206543d4b556929e56b1c3b0f
dbwebb-se/python-slides
/oopython/example_code/vt23/kmom03/get_post_ok/src/guess_game.py
1,766
4.21875
4
#!/usr/bin/env python3 """ Main class for the guessing game """ import random from src.guess import Guess class GuessGame: """ Holds info for playing a guessing game """ def __init__(self, correct_value=None, guesses=None): if correct_value is not None: self._correct_value = correct_value else: self._correct_value = random.randint(1, 15) self.guesses = [] if guesses: for value, attempt, is_correct in guesses: self.guesses.append(Guess(value, attempt, is_correct)) # self.guesses = [Guess(v, a, c) for v, a, c in guesses] if guesses is not None else [] # denna raden gör samma sak som de fyra raderna ovanför self.guess_attempts = len(self.guesses) def make_guess(self, guess_value): """ Makes a new guess and adds to list """ self.guess_attempts += 1 if guess_value == self._correct_value: self.guesses.append(Guess(guess_value, self.guess_attempts, True)) return True self.guesses.append(Guess(guess_value, self.guess_attempts)) return False def get_correct_value(self): """ Return private attribute """ return self._correct_value def get_if_guessed_correct(self): """ return if last guess was correct or not """ return self.guesses[-1].correct if self.guesses else False def to_list(self): """ Turn old guesses to a list """ # new_list = [] # for g in self.guesses: # new_list.append((g.value, g.attempt, g.correct)) # return new_list return [(g.value, g.attempt, g.correct) for g in self.guesses] # denna raden gör samma sak som de fyra raderna ovanför.
true
9902a96d8649184b27bafe7835742d13bcec0f07
yyyuaaaan/python7th
/crk/8.4subsets.py
1,655
4.25
4
"""__author__ = 'anyu' 9.4 Write a method to return all subsets of a set. gives us 2" subsets.We will therefore not be able to do better than 0(2") in time or space complexity. The subsets of {a^ a2, ..., an} are also called the powerset, P({aj, a2, ..., an}),or just P(n). This solution will be 0(2n) in time and space, which is the best we can do. For a slight optimization, we could also implement this algorithm iteratively. Generating P(n) for the general case is just a simple generalization of the above steps. We compute P(n-l), clone the results,and then add an to each of these cloned sets. How can we use P ( 2 ) to create P( 3 ) ? We can simply clone the subsets in P ( 2 ) and add a3 to them: P(2) ={} , {aj, {aj, {9lJ a2} P(2) + a3 = {a3}, {at, aj, {a2, a3}, {aaJ a2, a3} When merged together, the lines above make P(3). """ def powerset2(myset): """ recursion, powerset is subsets!, don't be consused of the name """ if not myset: #l is [] wrong, but (not l) is ok return [[]] else: # + and append() is very different return powerset2(myset[:-1]) + [ subset+[myset[-1]] for subset in powerset2(myset[:-1])] def powerset(myset): result = [[]] for element in myset: result += [subset+[element] for subset in result] # result.extend() also ok subset.append is wrong c #coz [] somehow become Nonetype # result will not change when do list operations return result print powerset([]) print powerset(['a','b','c']) print powerset2(['a','b','c'])
true
c2ffda55f905b9d0bc11dd1cff64761490722eb0
yyyuaaaan/python7th
/crk/4.4.py
1,547
4.125
4
"""__author__ = 'anyu' Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any # this is so called AVL-tree node never differ by more than one. """ class Node(object): def __init__(self): self.data=None self.left=None self.right=None def __str__(self): return "data:"+str(self.data)+"("+str(self.left)+"|"+str(self.right)+")"+"depth:"+str(self.depth) #O(n^2) naive algorithm def heightoftree(t): if not t: return 0 else: return max(heightoftree(t.left)+1, heightoftree(t.right)+1) def checkavl(t): if not t: return True elif abs(heightoftree(t.left)-heightoftree(t.right))<=1: return checkavl(t.left) and checkavl(t.right) else: return False #On each node, we recurse through its entire subtree. # This means that getHeight is called repeatedly on the same nodes. # The algorithm is therefore O(N2). #effcient algorithm, get heights of subtrees and check subtrees if balanced at the same time O(V+E)= O() def heightandavl(t): """ o(n) time and O(logn) space, space is the height """ if not t: return 0 else: h1= heightandavl(t.left) h2= heightandavl(t.right) if abs(h1 - h2)>1 or h1<0 or h2<0: #must include h1<0 and h2<0 return -1 # one num to denote False # wrong! return abs(h1-h2)<=1 return max(h1, h2)+1 #if height>=0 then True
true
b5e756f9eec761edbd58127e9ad66d9d0ec3dae5
tnguyenswe/CS20-Assignments
/Variables And Calculations (2)/Nguyen_Thomas_daylight.py
1,071
4.28125
4
''' Name: Thomas Nguyen Date: 1/6/20 Professor: Henry Estrada Assignment: Variables and Calculations (2) This program takes the latitude and day of the year and calculates the minutes of sunshine for the day. ''' #Import math module import math #Gets input from user latitude = float(input("Enter latitude in degrees: ")) day = float(input("Enter day of year (1-365): ")) #Calculates the latitude in radians instead of degrees. latitudeinradians = math.radians(latitude) #Calculates p - I broke it up into different variables for easier readability. insideoftan = math.tan(.00860*(day-186)) insideofarctan = math.atan(0.9671396*insideoftan) insideofcos = math.cos(0.2163108+ (2*insideofarctan)) p = math.asin(0.39795*insideofcos) #Calculates d numerator = math.sin(.01454)+math.sin(latitudeinradians)*math.sin(p) denominator = math.cos(latitudeinradians)*math.cos(p) d = 24 - (7.63944*math.acos(numerator/denominator)) #Prints the amount of minutes in daylight. Multiply d by 60 because d is in hours, not minutes. print("There are about %.3f" % (d*60) + " minutes of daylight." )
true
722b1e1ca439affec2aed8d27f674f281ebc36bb
gg/integer_encoding
/src/integer_encoding.py
1,339
4.34375
4
#!/usr/bin/env python # coding: utf-8 from collections import deque def encoder(alphabet): """ Returns an encoder that encodes a positive integer into a base-`len(alphabet)` sequence of alphabet elements. `alphabet`: a list of hashable elements used to encode an integer; i.e. `'0123456789'` is an alphabet consisting of digit character elements. """ base = len(alphabet) def encode(num): if num == 0: return [alphabet[0]] deq = deque() while num > 0: num, rem = divmod(num, base) deq.appendleft(alphabet[rem]) return list(deq) return encode def decoder(alphabet): """ Returns a decoder that decodes a base-`len(alphabet)` encoded sequence of alphabet elements into a positive integer. `alphabet`: a list of hashable elements used to encode an integer; i.e. `'0123456789'` is an alphabet consisting of digit characters. """ base = len(alphabet) index = dict((v, k) for k, v in enumerate(alphabet)) def decode(xs): try: result = 0 for i, x in enumerate(xs[::-1]): result += (base ** i) * index[x] return result except KeyError: raise ValueError("%r is not in the alphabet %r" % (x, alphabet)) return decode
true
273d638b3c2b9ea9bc8e8b32e59f8c45e61e7ef5
sassy27/DAY1
/OOP/Class instance.py
781
4.125
4
class employees: raised_amount = 1.04 num_emp = 0 def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay employees.num_emp += 1 # prints number of employees by adding after each emp created def fullname(self): return "{} {}". format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raised_amount) emp_1 = employees("sassy","siyan", 50000) emp_2 = employees("santi","cazzorla",5050) employees.raised_amount = 1.10 # can change the raised amount after print(emp_1.__dict__) print(emp_1.fullname()) print(emp_1.raised_amount) print(emp_1.pay) emp_1.apply_raise() # have to use apply raise to get new figure print(emp_1.pay) print(employees.num_emp)
true
4589928fdb9ae81e9d9d23b509b30a61539ebd8e
rohitx/Zelle-Python-Solutions
/Chapter2/question1.py
289
4.125
4
print "This program takes Celsius temperature as user \ input and outputs temperature in Fahrenheit" def main(): celsius = input("What is the Celsius temperature?") fahrenheit = (9/5.) * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit." main()
true
7bcdb4a3550071c4ff668aa0f7977a1aad65ad16
rohitx/Zelle-Python-Solutions
/Chapter3/question1.py
349
4.25
4
import math print "This program computes the Volume and Surface of a sphere\ for a user-specified radius." def main(): radius = float(raw_input("Please enter a radius: ")) volume = (4/3.) * (math.pi * radius**3) surface = 4 * math.pi * radius**2 print "The Volume is: ", volume print "The Surface is: ", surface main()
true
ca20faf4e6b8365bcbffe5f3fe94ce0c1d07c239
PeterParkSW/User-Logins
/UserLogins.py
1,525
4.4375
4
#dictionary containing paired usernames and passwords that have been created #keys are usernames, values are passwords credentials = {} #asks user for a new username and password to sign up and put into credentials dictionary def signup(): new_user = input('Please enter a username you would like to use: ') while new_user in credentials: print('That username already exists.') new_user = input('Please enter a different username you would like to use: ') if new_user not in credentials: new_pw = input('Please enter a password you would like to use: ') credentials[new_user] = new_pw #adds the key-value pair to the credentials dictionary print('You have successfully chosen a username and password!') signup() #asks the user to choose a username and password user = input('Please enter your username: ') pw = input('Please enter your password: ') #checks if username and password match to an account # if username == 'robert' and password == 'password123': # return 'Nice, you\'re in!' # else: # return 'Get outta here!' def is_valid_credentials(username, password): if username in credentials and password == credentials.get(username): print('Your credentials have been verified.') return True else: print('Your username and password do not match.') return False is_valid_credentials('peter', 'park') #example to check if there is a matching username & password in credentials dictionary
true
d5441ca9d8a467482c1341852a04c893850c10b5
KhoobBabe/math-expression-calculator
/mathmatical expression calculator.py
1,629
4.1875
4
import warnings print('Enter a mathematical expression to view its result') #we put a while to cotinously prompt the yser to input expressions cond = True while cond is True: #this ignores other warnings warnings.simplefilter('ignore') #input is taken here a = input("\nEnter a mathematical expression: ") #this shows history of the entered expressions if a == "history": file = open("history.txt", mode="r") data = file.read() print(data) file.close() #this clears the history elif a == "clear": file = open("history.txt", mode="w") file.close() print("Your History has been cleared :) ") #this exits the program elif a == "exit": cond = False print("program closed, Adios master :-)") #the expression is solved here else: try: b = eval(a) print(f'The result of the entered expression is {b}.') #the expression is stored in the file history file = open("history.txt", mode="a") file.write(f"{a}\n") file.close() print() #if an operator i.e. +, -, *, / is missing except TypeError: print("Operator is missing") continue #if the value is divided by zero except ZeroDivisionError: print("Division with 0 is infinity") continue #this handles other errors except Exception as e: print(e.__class__, "has occoured") continue
true
0a0e377ff207f57bafb2cd622c772080d4559fe4
AvyanshKatiyar/megapython
/app4/app4_code/backend.py
2,190
4.3125
4
import sqlite3 def connect(): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") conn.commit() conn.close() #id checks how many entries def insert(title, author, year,isbn): conn=sqlite3.connect("books.db") cur=conn.cursor() # id is created automatically by NULL matching somehow conn.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title, author, year, isbn )) conn.commit() conn.close() def view(): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("SELECT * FROM book") rows=cur.fetchall() conn.close return rows #initializing the strings as empty values as we wont need all of them at once like can query only for auhtor as well at the starting # basically since lets say we are looking for author name # then as title is "" empty therefore it will return an empty value as no entry with null value yes def search(title="", author="", year="",isbn=""): #if year then all entries for that year conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("SELECT * FROM book WHERE title=? OR Author=? OR year=? OR isbn=?", (title, author, year, isbn)) rows=cur.fetchall() conn.close return rows #use id to delete def delete(id): conn=sqlite3.connect("books.db") cur=conn.cursor() # id is created automatically by NULL matching somehow conn.execute("DELETE FROM book WHERE id=?", (id,)) conn.commit() conn.close() def update(id,title, author, year, isbn): conn=sqlite3.connect("books.db") cur=conn.cursor() # id is created automatically by NULL matching somehow conn.execute("UPDATE book SET title=?,author=?, year=?, isbn=? WHERE id=?", (title, author,year,isbn,id))#order matters here conn.commit() conn.close() connect() #insert("My name jef","jef",2015, 6060) #insert("Moshi Moshi Max","Alpino",2013, 9393939) #insert("How to how to books","Haus",1888, 939393) #update(3,'How to how to books', 'Haus Himmelmaker', 1888, 939393) #print(view()) #print(search(title="Moshi Moshi Max")) #note id does not change
true
eb740ea5b08d9f8b1cec289512d993ec5093ea42
AvyanshKatiyar/megapython
/Not_app_code/the_basics/forloops.py
889
4.1875
4
monday_temperatures=[9.1, 9.7, 7.6] #rounding print(round(monday_temperatures[0])) for temperature in monday_temperatures: print(round(temperature)) #loop goes through all the variables #looping through a dictionary student_grades={"Marry": 9.1, "Sim": 8.8, "John": 7.5} #chose what you want to iterate over items keys values for grades in student_grades.items(): print(grades) for grades in student_grades.values(): print(grades) for grades in student_grades.keys(): print(grades) phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"} for a, b in phone_numbers.items(): print("%s: %s"%(a,b)) #while loops username = '' while username != "pypy": username=input("Enter username: ") #break and other stuff while True: username=input("Enter yo name: ") if username== "pypy": break else: continue
true
cecf188d0a3425dbc83dac4b9caf56f1f428b4d2
meetashwin/python-play
/basic/countsetbits.py
392
4.5
4
# Program to count the set bits in an integer # Examples: # n=6, binary=110 => Set bits = 2 (number of 1's) # n=12, binary=1100 => Set bits = 2 # n=7, binary=111 => Set bits = 3 def countsetbits(n): count = 0 while(n): count += n & 1 n >>= 1 return count print("Enter the number to find set bits for:") n = int(input()) print("Set bits for {0} is {1}".format(n, countsetbits(n)))
true
6b674887d7d590d12016e60aed03cce67d284b9d
remcous/Python-Crash-Course
/Ch04/squares.py
452
4.5625
5
#initialize an empty list to hold squared numbers squares = [] for value in range(1,11): # ** acts as exponent operator in python square = value**2 # appends the square into the list of squares squares.append(square) print(squares) # more concise approach squares = [] for value in range(1,11): squares.append(value**2) print(squares) # List Comprehension method to initialize list squares = [value**2 for value in range(1,11)] print(squares)
true
b9854e8781e6261b6919999f85e782205aab07d1
BD20171998/holbertonschool-higher_level_programming
/0x0A-python-inheritance/2-is_same_class.py
686
4.46875
4
#!/usr/bin/python3 """ This is an example of the is_same_class function >>> a = 1 >>> if is_same_class(a, int): ... print("{} is an instance of the class {}".format(a, int.__name__)) >>> if is_same_class(a, float): ... print("{} is an instance of the class {}".format(a, float.__name__)) >>> if is_same_class(a, object): ... print("{} is an instance of the class {}".format(a, object.__name__)) 1 is an instance of the class int """ def is_same_class(obj, a_class): """ This function that returns True if the object is exactly an instance of the specified class ; otherwise False """ if type(obj) is a_class: return True else: return False
true
36bcd1fc0ec00f9ca1da87c053a7813973b4d23d
BD20171998/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
624
4.25
4
#!/usr/bin/python3 """This is an example of the append_write function >>> append_write = __import__('4-append_write').append_write >>> nb_characters_added = append_write("file_append.txt", "Holberton School \ ... is so cool!\n") >>> print(nb_characters_added) 29 """ def append_write(filename="", text=""): """ Function that appends a string at the end of a text file (UTF8) and returns the number of characters written """ count = 0 with open(filename, mode='a+', encoding='utf-8') as f: for i in text: f.write(i) count += 1 f.close() return count
true
b024737c383e9990ea898a749ec09a2ef3a42320
samaroo/PythonForBeginners
/Ch7_Exercise.py
1,064
4.3125
4
# Notes # Functions in "Math" Library # use "import math" to import math library # abs(x) will return the absolutw calue of x # "math.ceil(x)" will round x up to the nearest integer greater than it # "math.floor(x)" will round x down to the nearest integer less than it # "pow(x, y)" will return x^y # # Functions in "Random" Library # "random.choice(x)" where x is a list or tuple will return a random element of x # "random.randrange(x, y)" will return a random elements between x and y # "random.shuffle(x)" where x is a list or tuple, will shuffle x import math import random # Find the hypotnuse of a triangle with sides 15 and 17 print(math.hypot(15, 17)) # convert degrees to radians and radians to degrees print(math.radians(180)) print(math.degrees(2)) print(math.radians(270)) print(math.degrees(5)) # generate 100 random numbers between 1 and 10 sum = 0; x = 100 for i in range(x): num = random.randrange(1,10) sum += num print(num) print("The sum is: ", sum) print("The average is: ", sum / x)
true
a3b988261743a290910d8c3110733d393ef01512
wolverinez/T_Mud
/dice.py
1,099
4.15625
4
"""this module contains functions for rolling dice from a cointoss to a one hundred sided dice the funtions are named with the letter 'd' and then a number forinstance the function to simulate a d20 is simply named d20(pluss=0) where the pluss argument makes it possible to modify the roll """ import random as R def d2(pluss=0): """Simulates a coin toss""" return R.randint(1, 2) + pluss def d3(pluss=0): """Simulates a threesided dice""" return R.randint(1, 3) + pluss def d4(pluss=0): """Simulates a four sided dice""" return R.randint(1, 4) + pluss def d6(pluss=0): """Simulates a six sided dice""" return R.randint(1, 6) + pluss def d8(pluss=0): """Simulates a eight sided dice""" return R.randint(1, 8) + pluss def d10(pluss=0): """Simulates a ten sided dice""" return R.randint(1, 10) + pluss def d12(pluss=0): """Simulates a twelve sided dice""" return R.randint(1, 12) + pluss def d20(pluss=0): """Simulates a twenty sided dice""" return R.randint(1, 20) + pluss def d100(pluss=0): """Simulates a hundred sided dice""" return R.randint(1, 100) + pluss
true
2b953aeab24e60b0a44915565b05b7cb3f1a4dd6
kosskiev/University-of-Michigan
/turtle_and_color_figure.py
873
4.46875
4
#Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. #The program should draw the polygon and then fill it in. import turtle number_side = int(input('How many sides would you like?(Сколько сторон у вашей фигуры?) ')) angle = 360 / number_side length_side = int(input('How long length side?(Какая будет длина стороны?) ')) color = input('Which color line do you want?(Каким цветом рисовать линии?) ') fill_color = input('What color to sketch your figure?(Каким цветом закрасить вашу фигуру?) ') wm = turtle.Screen() turtle.color(color, fill_color) turtle.begin_fill() for i in range(number_side): turtle.fd(length_side) turtle.lt(angle) turtle.end_fill() turtle.exitonclick()
true
429a1d0562b5385edfa9a443c0732272e82bef4d
hutor04/UiO
/in1000/oblig_3/ordbok.py
1,197
4.34375
4
# The program initiates a dictionary with product names as keys and their prices as values. It then prints out the list # Then the program asks the user to input a new product and its price two times. # It ads new products to the dictionary and then prints a new dictionary. # We create a dictionary that holds product names as keys and their prices as values. products = {'melk': 14.90, 'brød': 24.90, 'yoghurt': 12.90, 'pizza': 39.90} # We print the dictionary print(products) # We enter the for-loop with two repetitions. for i in range(2): # We ask for a product name product = input('Please, provide the name of a product: ') # We are going to handle the exception that rises if the user inputs not a number on the next step try: # We ask the user to enter the price price = float(input('Provide the price of the product (digits , please): ')) # We then ad a new product to the dictionary products[product] = price except ValueError: # We print this if the user enters price with alphabetic characters. And we don't add this value to the list. print('We expected a digit here.') # We print the list again print(products)
true
215b78a3a4ae410b55ea532938f4d337b338ee1f
hutor04/UiO
/in1000/oblig_1/hei_student.py
361
4.21875
4
# The following program prints salutation, asks the user to input its name. # Then it prints out salutation and the name that was provided by the # user. # Prints to screen the first salutation print('Hei Student!') # Asks to input the name of the user navn = input('Scriv navnet ditt nå: ') # Prints to screen new salutation with the name print('Hei', navn)
true
e4279841462864909d41865df0c27e91b156831d
CharlieHuang95/Algorithms
/Sorting/quick_sort.py
1,188
4.25
4
# Quicksort works by randomly selecting an element to be its pivot, and shifting # smaller elements to its left side, and larger elements to its right side. # At the end of all the shifting, the pivot should ultimately be in the correct # location. import random def quick_sort_helper(array, left, right): if left >= right: return pivot = array[left] l = left + 1 r = right while l < r: while l < r and array[l] < pivot: l += 1 while l < r and array[r] > pivot: r -= 1 if l < r: array[l], array[r] = array[r], array[l] if array[l] <= pivot: array[left], array[l] = array[l], array[left] boundary = l else: array[left], array[l-1] = array[l-1], array[left] boundary = l - 1 quick_sort_helper(array, left, boundary - 1) quick_sort_helper(array, boundary + 1, right) def quick_sort(array): quick_sort_helper(array, 0, len(array) - 1) if __name__=="__main__": for _ in xrange(10): array = [] for _ in xrange(10): array.append(random.randrange(0, 100)) quick_sort(array) assert sorted(array) == array
true
fd2a94cec38175d7ff35a93814bc5815df69dcd0
MeenaRepo/augustH2K
/DictionaryTest.py
1,285
4.1875
4
sampleDictionary = { "Warm":"Red", "Cold":"Baige", "Nuetral":"Grey", "Common":"Black", } print(sampleDictionary) print(sampleDictionary["Cold"]) print(sampleDictionary.get("Warm")) # Add - replaces the old value sampleDictionary["Warm"] = "Blue" print(sampleDictionary) # Membership if "Nuetral" in sampleDictionary: print(" Nuetral color is : ", sampleDictionary.get("Nuetral")) if "Black" in sampleDictionary.values(): print(" Black exists in the Dictionary : ", sampleDictionary.get("Common")) # pop sampleDictionary.pop("Common") print(sampleDictionary) # popitem - Remove the last item in the list sampleDictionary.popitem() print(sampleDictionary) #iterate with Keys for eachkey in sampleDictionary: print(eachkey, sampleDictionary.get(eachkey)) #iterate with Key-Value pairs for eachkey, eachvalue in sampleDictionary.items(): print(eachkey, eachvalue) # iterate with only values for eachvalue in sampleDictionary.values(): print(eachvalue) # you can even add a list as one of the key value pair in dictionary sampleDictionary["List_item"] = ["apple", "pineapple", "grapes","lotus"] sampleDictionary["Cold"]="Yellow" sampleDictionary["Common"] = "White" print(sampleDictionary)
true
10cd5c0f8f3bf6fae6e03e1e740a115f505a1aba
duthaho/python-design-patterns
/creational/builder.py
2,288
4.15625
4
from abc import abstractmethod from typing import Optional class Car: def __init__(self): self.seat = 0 self.engine = "" self.trip_computer = False self.gps = False def info(self): print(f"Car: {self.seat} - {self.engine} - {self.trip_computer} - {self.gps}") class Builder: def __init__(self): self._car = None self.reset() @abstractmethod def reset(self) -> "Builder": pass @abstractmethod def set_seat(self, seat: int) -> "Builder": pass @abstractmethod def set_engine(self, engine: str) -> "Builder": pass @abstractmethod def set_trip_computer(self) -> "Builder": pass @abstractmethod def set_gps(self) -> "Builder": pass @abstractmethod def get(self) -> Car: pass class CarBuilder(Builder): def reset(self) -> "Builder": self._car = Car() return self def set_seat(self, seat: int) -> "Builder": self._car.seat = seat return self def set_engine(self, engine: str) -> "Builder": self._car.engine = engine return self def set_trip_computer(self) -> "Builder": self._car.trip_computer = True return self def set_gps(self) -> "Builder": self._car.gps = True return self def get(self) -> Car: return self._car class Director: def __init__(self): self._builder: Optional[Builder] = None @property def builder(self) -> Builder: return self._builder @builder.setter def builder(self, builder: Builder): self._builder = builder def build_sport_car(self) -> Car: self._builder.reset().set_seat(2).set_engine("sport").set_trip_computer().set_gps() return self._builder.get() def build_suv(self) -> Car: self._builder.reset().set_seat(4).set_gps() return self._builder.get() class Application: def make_car(self): director = Director() car_builder = CarBuilder() director.builder = car_builder car = director.build_suv() car.info() car = director.build_sport_car() car.info() if __name__ == "__main__": app = Application() app.make_car()
true
259d53c7b2581e146cc8b1c5c9d75da5f04ee845
joelbd/CSC110
/convertmiles.py
244
4.3125
4
# File: convertmiles.py # This program converts distance in miles to distance in kilometers # Day def main(): miles = eval(input("Enter the distance in miles:")) kilometers = miles * 1.60934 print("The distance is:",kilometers,"km") main()
true
a80ddf31a4e28b238ebd83d30c80ef432bd25a16
Raktacharitra/TrueCaller-search
/truecaller.py
1,022
4.125
4
from sys import argv choice = input("Tell us if you want to 'search' a particular contact or 'add' a contact (s / a): ") if choice.lower() == "s" or choice.lower() == "search": with open(argv[1], "r") as phone_book: search_type = input("search by name or number: ") try: a = int(search_type) for line in phone_book: bucket = line.split(":") if int(bucket[1]) == a: print(bucket[0]) except ValueError: for line in phone_book: bucket = line.split(":") if bucket[0].lower() == search_type.lower(): print(bucket[1]) elif choice.lower() == "a" or choice.lower() == "add": with open(argv[1], "a") as phone_book: name = input("enter person's name: ") number = int(input("enter person's number: ")) phone_book.writelines(f"\n{name}:{number}") else: print("You need to type 'search' or 'add' to perform the desired operation!" )
true
1f527d83890651daeebb1874a70225fa013d07e4
louisbranch/hello-py
/ProblemSet3/ps3_newton.py
1,757
4.21875
4
# 6.00x Problem Set 3 # # Successive Approximation: Newton's Method # # Problem 1: Polynomials def evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' s = 0.0 for i in range(len(poly)): s += poly[i] * x ** i return s # Problem 2: Derivatives def computeDeriv(poly): ''' Computes and returns the derivative of a polynomial function as a list of floats. If the derivative is 0, returns [0.0]. poly: list of numbers, length &gt; 0 returns: list of numbers (floats) ''' list = [] if len(poly) <= 1: list = [0.0] for i in range(len(poly)): if i == 0: continue if abs(poly[i]) == 0: list.append(0.0) else: list.append(poly[i] * i) return list counter = 0 # Problem 3: Newton's Method def computeRoot(poly, x_0, epsilon): ''' Uses Newton's method to find and return a root of a polynomial function. Returns a list containing the root and the number of iterations required to get to the root. poly: list of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: list [float, int] ''' # FILL IN YOUR CODE HERE... global counter rootX = evaluatePoly(poly, x_0) if abs(rootX) > epsilon: x_1 = x_0 - (rootX / evaluatePoly(computeDeriv(poly), x_0)) counter += 1 return computeRoot(poly, x_1, epsilon) else: old = counter + 0 counter = 0 return [x_0, old]
true
ae069876ea6409ad4a9ff29f1fb23a915d707e01
priyankagoma/learningpython
/src/python_scripts/print_examples/printexamples.py
290
4.15625
4
#below are few examples that how we can print numbers. print(2 + 8) print(3 * 5) print(6 - 3) #Example of a string. print("The end", "it should be nice", "we will able to make it") #Exapme of integers. print(1, 2, 3, 4, 5) #Example of words. print("one two three four five cat dog")
true
df53ec293bedda6a6954334daca394536dc0e02b
Junhee-Kim1/RandomNumber
/RandomNumberGuesser.py
442
4.15625
4
import random print("number Guessing Game!") number=random.randint(1,9) chance=0 print("guess number") while chance<5: guess=int(input("enter your guess!: ")) if guess == number: print("you win!") break elif guess<number: print("your number is too low") else: print("your number is too High") chance=chance+1 if not chance<5: print("you lose the number was" , number)
true
2c4da32e1420daae3f9401ca78d4be75b6af5f9d
prathmesh2606/DSA_LU
/a1q1.py
344
4.4375
4
# Assignment 1 - Q1 # Write a python program that takes two numbers as the input such as X and Y and print the result # of X^Y(X to the power of Y). # Taking input x,y = [int(i) for i in input("Enter base value and then power value by giving space between them (eg: 2 3 ans: 8): ").split()] print(f"{x} to the power of {y} is: {x**y}")
true
b1b7f0de711f5d40447d83553dc3e8c4bbe3209f
charliettaylor/CSA231
/Projects/4/project4.py
2,286
4.28125
4
# Turtle Project by Charlie Taylor from turtle import * import random as rand SCALE = "Enter the size of the spiral (recommend 1-10): " LOW = "Enter low bound of shake (rec. negative or 0): " HIGH = "Enter high bound of shake (rec. positive or 0): " def draw_c(t) -> None: ''' draws letter C ''' t.down() for i in range(2): t.fd(100) t.left(90) t.fd(100) t.up() def draw_t(t) -> None: ''' draws letter T ''' t.down() t.fd(100) t.left(90) t.fd(75) t.back(150) t.up() def initials(t: Turtle) -> None: ''' draws initials from any starting position ''' t.setheading(180) draw_c(t) t.fd(100) t.left(90) draw_t(t) def shake(low, high) -> int: ''' returns an int to modify the degrees in spiral should be a negative number for low and positive for high to make effect look good ''' return rand.randint(low, high) def spiral(t, degrees, n, scale, low=0, high=0) -> None: ''' Draws a spiral based on degrees and number of iterations entered t : Turtle object degrees : should be 1 less than interior angle of regular polygon n : number of iterations Keyword arguments low : lower bound of shake that varies degrees high : upper bound of shake that varies degrees ''' size = 2 t.down() for i in range(n): t.fd(size) t.left(degrees + shake(low, high)) size += scale t.up() def main(): print("Welcome to the spiral maker by Charlie Taylor") done = False while not done: try: scale = float(input(SCALE)) low = int(input(LOW)) high = int(input(HIGH)) done = True except ValueError: print("Enter a positive non zero integer") wn = Screen() wn.bgcolor("black") wn.title("Turtle") t = Turtle() t.speed(0) t.setposition(0, 0) t.pencolor("green") spiral(t, 119, 300, scale, low, high) t.pencolor("salmon") t.setposition(0, 0) spiral(t, 89, 300, scale, low, high) t.pencolor("orange") t.setposition(0, 0) spiral(t, 71, 300, scale, low, high) t.pencolor('white') t.setposition(0, 0) initials(t) if __name__ == "__main__": main()
true
101cedb9b67c9004b1a4a5af955197ed7b71a4b9
yingl910/MongoDB
/Basics/mdb_update.py
1,899
4.25
4
'''These are examples of MongoDB example codes of save and update, two methods for updating''' '''update method one: save''' # a method on collection objects # find_one just returns the first document it finds city = db.cities.find_one({'name':"munchen",'country':'Germany'}) city['isoCountryCode'] = 'DEU' db.cities.save(city) # a method on collection objcects #if the object we pass already have a _id and a document with that id already in the collection ->replacement #if there is no document with _id or the object we're passing does not have _id -> create '''update method two: update''' #update : a method on collection objects; a query document as 1st parameter #2nd parameter: an update document: specify what operations mongodb should perform on the document matching this query #by default, update operates on just one document(first found) #if the field is not exsit -> create; exist -> update city = db.cities.update({'name':"munchen",'country':'Germany'}, {'$set':{ 'isoCountryCode':'DEU' }}) '''inverse of $set: $unset''' # if the field is not exsit -> no effect; exist -> remove city = db.cities.update({'name':"munchen",'country':'Germany'}, {'$unset':{ 'isoCountryCode':'' }}) '''PAY ATTENTION: IT'S REALLY EASY TO FORGET $SET AND $UNSET OPERATOR''' # what happens here is the document matching this query will be replaced so that it contains the _id and #'iscountrycode' field ONLY city = db.cities.update({'name':"munchen",'country':'Germany'}, {'isoCountryCode':'DEU'}) '''update multiple documents at once''' db.cities.update({'country': 'Germany'}, {'$set': { 'isoCountryCode': "DEU" } }, multi = True)
true
cd890912e0574154ac18385ac92f43fdd68f430d
PrabhudevMishra/PRO-97
/numberGuessingGame.py
497
4.15625
4
import random number = random.randint(0,10) chances = 0 while chances < 5 : guess = int(input("Enter your guess")) chances = chances + 1 if guess < number: print('Your guess is too low') if guess > number: print('Your guess is too high') if guess == number: break if guess == number: print('CONGRATULATIONS!! You guessed the number correct.') else: print("You lost!! Please try again.")
true
c43c7f51aff65b851a591bf7d00c96a0d8a160be
shivesh01/Python-Basics
/Project&problems/Example_30.py
425
4.28125
4
# Shuffle Deck of cards import random # In the program, we used the product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequences. from itertools import product deck = list(product(range(1, 14), ["Spade", "Heart", "Club", "Diamond"])) random.shuffle(deck) print(" Your picked card is: ") for i in range(5): print(deck[i][0], "of", deck[i][1])
true
65e62f4761054c0cf0ac8911e1715c5537608c7c
shivesh01/Python-Basics
/Project&problems/Example_10.py
233
4.375
4
# check number +,- or 0 num = float(input("Enter number")) if num == 0: print("your entered number is zero") elif num > 0: print("You have entered a positive number") else: print("You have entered a negative number")
true
dd701404bbf09b357bdd5faec5512de7093ca871
lmjim/year1
/cs210/p61_testfunc_key.py
1,584
4.21875
4
""" CIS210 Project 6-1 Fall 2017 Author: [Solution] Credits: N/A Implement a function to test the string reverse functions from project 5 (iterative and recursive). Practice: -- user-defined test functions -- functions as parameters """ import p52_stringreverse_key as p5 def test_reverse(f): '''(function) -> None Test function f (one of the string reverse functions). Report results for each test. > test_reverse(p5.strReverseR) <report results> > test_reverse(p5.strReverseI) <report results> ''' test_cases = ( ('', ''), ('a', 'b'), ('xyz', 'zyx'), ('testing123', '321gnitset'), ('hello, world', 'dlrow ,olleh') ) for test in test_cases: # parse the arguments arg1 = test[0] expected_result = test[1] # report test case print('Checking {}({}) ...'.format( f.__name__, str(arg1)), end='') # execute the test actual_result = f(arg1) # report result if (actual_result == expected_result): print('its value {} is correct!'.format(actual_result)) else: print('Error: has wrong value {}, expected {}.'.format(actual_result, expected_result)) return None def main(): '''calls string reverse test func 2x''' test_reverse(p5.strReverseR) test_reverse(p5.strReverseI) return None if __name__ == '__main__': #print(doctest.testmod()) main()
true
826fb885f233ea03edffde38cb2342bda0236dea
dudulydesign/python_web_pratice
/webserver/py_though/bubble sort.py
747
4.15625
4
#Bubble Sort sampleList = [6,5,4,3,2,1] def bubbleSort(sourceBubbleSortList): #how long the list listLength = len(sourceBubbleSortList) i = 0 # the i here to count how many value not in while i < listLength-1: j = listLength - 1 # here to compare two value while j > i: print(" sourceBubbleSortList = " + str(sourceBubbleSortList)) #compare two value, replace it if here are diffrent big, and continute to compare until finish all of it if sourceBubbleSortList[j] < sourceBubbleSortList[j-1]: tempNum = sourceBubbleSortList[j] sourceBubbleSortList[j] = sourceBubbleSortList[j-1] sourceBubbleSortList[j-1] = tempNum j = j - 1 i = i + 1 return sourceBubbleSortList
true
62f8410ff45e2352f7ac48cf8327c35a62371895
geraldfan/Automate-The-Boring-Stuff
/Chapter_9_Organizing_Files/selectiveCopy.py
699
4.25
4
#! python3 # selectiveCopy.py - Walks through a folder tree, then searches and copies for files with a particular extension (i.e. .jpg) import shutil, os folder = input('Enter the absolute filepath of' ' the directory you wish to copy from: ') extension = input("Enter the extension you'd like to copy: ") destination = input("Enter destination folder's absolute filepath: ") for foldername, subfolders, filenames in os.walk(folder): for filename in filenames: if filename.endswith(extension): shutil.copy(os.path.join(foldername, filename), destination) print("Selective copy of %s extension from %s to %s is complete" %(extension, folder, destination))
true
578494d75a99a79091946b96a93a13fc485c6c50
Szkeller/TDD_lab
/FizzBuzz.py
867
4.125
4
class FizzBuzz: ''' This is for TDD sample Author: Keller Zhang create date: 04/27 description: FizzBuzz Quiz When given number just can be divided by 3, then return 'Fizz'; When given number just can be divided by 5, then return 'Buzz'; When given number just can be divided by 3 and 5, then return 'FizzBuzz'; otherwise return given number itself. ''' def fizz_buzz(self, number): result = '' if number % 15 == 0: result = 'FizzBuzz' elif number % 5 == 0: result = 'Buzz' elif number % 3 == 0: result = 'Fizz' else: result = str(number) return result if __name__ == '__main__': fizzbuzz = FizzBuzz() for i in range (1,101): print(fizzbuzz.fizz_buzz(i))
true
383c7b66d2e6c025f09270cf1e547d64556954aa
Shilinana/LearnPythonTheHardWayPractices
/ex18.py
633
4.3125
4
""" @Author:ShiLiNa @Brief:The exercise18 for Learn python the hard way @CreatedTime:28/7/2016 """ # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1:%r, arg2:%r" % (arg1, arg2) # ok, that *arg is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1:%r, arg2:%r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1:%r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." print print_two("Zed", "Shaw") print print_two_again("Zed", "Shaw") print_one("First!") print_none()
true
89768748cf4abc99b56f383e025fe37a851579f8
justinelai/Sorting
/src/iterative_sorting/iterative_sorting.py
2,598
4.5625
5
def insertion_sort(list): for i in range(1, len(list)): # copy item at that index into a temp variable temp = list[i] # iterate to the left until reaching correct . # shift items to the right j = i while j > 0 and temp < list[j-1]: list[j] = list[j-1] j -= 1 list[j] = temp return list # TO-DO: Complete the selection_sort() function below # How many loops will be needed to complete this algorithm? # How do we know how many items should be shifted over to the right? # What do we need to do so that we don't overwrite the value we are `inserting`? # What, if anything needs to be returned? """ For every index in the collection from 0 to length-2: Compare the element at the current index, i, with everything on its right to identify the position of the smallest element Swap the element at i with the smallest element i++ Algorithm Start with current index = 0 For all indices EXCEPT the last index: a. Loop through elements on right-hand-side of current index and find the smallest element b. Swap the element at current index with the smallest element found in above loop """ """ test = [ 4, 3, 1, 2, 5, 6 ] def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index for j in range(i + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index] print(arr) selection_sort(test) """ # TO-DO: implement the Bubble Sort function below # If `elements` is a collection, remember it will be passed by reference, not value # We only need to loop through `elements` until we make a pass that leads to 0 swaps. How do we keep track of whether or not any swaps have occurred? # Do we always need to loop through all elements? # Depending on how our loop was set up, which neighbors should be compared? # Can we do swaps in Python without a `temp` variable? # What, if anything needs to be returned? test1 = [ 4, 3, 1, 2, 5, 6 ] def bubble_sort(arr): swapped = True while swapped: swapped = False for i in range(0, len(arr)-1): if(arr[i+1] < arr[i]): arr[i+1], arr[i] = arr[i], arr[i+1] swapped = True print(arr) return arr bubble_sort(test1) """ # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): return arr """
true
2851a656bd9f2bdc1b7877c587dd09a17e0fe219
Tech-Amol5278/Python_Basics
/c5 - list/c5_more_methods_to_add_data.py
626
4.15625
4
# count # sort method # sorted function # reverse # clear # copy # Count: Counts the string available in list fruits = ['apple','orange','banana','grapes','apple','apple','guava'] print(fruits.count('apple')) # Sort: sort the list contains in alphabetical/numeric order fruits.sort() print(fruits) numbers = [3,51,8,4,67,12] numbers.sort() print(numbers) # Sorted function: sort the return from list instead sorting the actual list num = [10,2,5,7,4] print(sorted(num)) print(num) # Clear: clears the list num1 = [5,6,2,19,25] num1.clear() print(num1) # Copy: Copying of list num_copy=num.copy() print(num_copy)
true
43bce6c540aa4ad249c33ab9650e4e1b739a73cb
Tech-Amol5278/Python_Basics
/c5 - list/c5e4.py
522
4.4375
4
# define a function which returns a lists inside list, inner lists are odd and even numbers # for example # input : [1,2,3,4,5,6,7,8] # returns : [[1,3,5,7],[2,4,6,8]] ####### Sol ############################################### num1 = [1,2,3,4,5,6,7,8] def separate_odd_even(list1): sep_list = [] odd = [] even = [] for i in list1: if i%2==0 : even.append(i) else: odd.append(i) sep_list = [odd,even] return(sep_list) print(separate_odd_even(num1))
true
f383537b4da9f340610aaa7e4ee2e1fbf5b73147
Tech-Amol5278/Python_Basics
/c2 - strings methods/c2e2.py
218
4.21875
4
# ask username and print back username in reverse order # note: try to maje your program in 2 lines using string formatting #### Sol ##########################3 u_name = input("Enter your name: ") print(u_name[::-1])
true
4e09df38fd41bfaa63801dffa2f1a822878deab4
Tech-Amol5278/Python_Basics
/c17 - debugging and exceptions/else and finally.py
675
4.28125
4
# Else and fianlly while True: ## Loop to accept input til true comes try: age = int(input("Enter a number: ")) except ValueError: # valueerror : optional only if we know the error which can come print("Please enter age only in integer ") except: # when error is unpredictable print("Unexpected error") else: # executes when there is no exception print(f"You entered {age}") break finally: # this executes in both the cases, errors and no errors print("finally blocks......") if age > 18: print("Welcome to play game") else: print("You cant play this game")
true
e3a71a4f1447e3fc0e6bf03654df9c63e1af56f2
Tech-Amol5278/Python_Basics
/c16 - oops/property and setter decorator.py
2,526
4.21875
4
# property and setter decorator # the below code from last slide it has below problems # 1. this accepts the negative amount for price # sol: write a validation not to accept negative numbers # using getter(),setter() # 2. After changing the price , complete specification shows the old price. # sol: write those specification in seprate function # OR using property decorator # class Phone: # def __init__(self,brand,model_name,price): # self.brand = brand # self.model = model_name # self._price = price # self.complete_spefic = f" {self.brand} {self.model_name} and price {_price}" # def make_a_call(self,phone_num): # print(f"Calling {phone_num} .....") # def full_name(self): # print(f"{self.brand} {self.model}") # phone1 = Phone('nokia','1100',5600) # print(phone1._price) ################################################################################################### class Phone: def __init__(self,brand,model_name,price): self.brand = brand self.model = model_name if price >= 0: self._price = price else: self._price = 0 ### or use below line # self._price = max(price,0) ## this checks for the maximum number between given number and 0 and returns the max number either given number or 0 # self.complete_spefic = f" {self.brand} {self.model} and price {self._price}" def make_a_call(self,phone_num): print(f"Calling {phone_num} .....") def full_name(self): print(f"{self.brand} {self.model}") def specs(self): return f" {self.brand} {self.model} and price {self._price}" # @Property- using this decorator we can use this function as method and we can call this method as attribute @property def property_spec(self): return f" {self.brand} {self.model} and price {self._price}" # getter(), setter() for price validation @property def price(self): return self._price @price.setter def price(self,new_price): self._price = max(new_price,0) phone1 = Phone('nokia','1100',-5600) phone1._price = 2200 print(phone1._price) print(phone1.specs()) print(phone1.property_spec) ## see here we are not given parenthesis() ### to set the new price from getter and setter phone1.price = 3400 print(phone1.price) # used price instead of _price print(phone1.property_spec) ## see here we are not given parenthesis()
true
1990af0b8f76c76eaa907f985d091f44a32cad62
Tech-Amol5278/Python_Basics
/c5 - list/c5_list_intro.py
649
4.5
4
# Data Structures # List # List is ordered collection of items # We can store anything in lits like int, float, string numbers = [1,2,3,4] print(numbers) ## to print 2 from list print(numbers[1]) ## to access only and 1 and 2 print(numbers[:2]) ## to reverse the elements in list print(numbers[::-1]) ## to access only last element i.e 4 print(numbers[-1]) words = ["word1",'word2','word3'] print(words) mixed = [1,2,3,4,"five","six",None] print(mixed) ## to update the elements in list such as 2 > "two" mixed[1] = "two" print(mixed) mixed[1:] = "two" ## considered new list t , w, o print(mixed) mixed[1:] = ["three","four"] print(mixed)
true
9fe26472b3e65060b858040cdacc132387283fbd
mansi135/mansi_prep
/practice/new_problems.py
2,850
4.1875
4
# Given two sorted lists, return the interesection (ie the common elements b/w the two sorted lists) # For example given l1 = [1, 2, 3] and l2 = [2, 3, 5, 10] (they can be different sizes) # return [2, 3] # LINEAR TIME # 4 def get_intersection(l1, l2): pass # given two sorted lists l1 and l2, merge them such that the result is also sorted # use no helper methods # For example given l1 = [1, 2, 3] and l2 = [2, 3, 5, 10] (they can be different sizes) # return [1, 2, 2, 3, 3, 5, 10] # return [1, 2, 3, 5, 10] # LINEAR TIME # 5 def merge(l1, l2): pass # return true iff the string has a repeated substring. # for example: "I ate not so late today" has a repeated substring ate. So it would return true for that # but if I gave "Have not eaten", it would return false. # 3 def has_repeated_substring(s): pass # Given a string s, and an index i, return the index of the # space, or end of string, that terminates the word starting at s[i]. For example given # s = "monkey ate my banana", i = 0, returns 6. And i = 14 (returns 20) # 1 def find_word_boundary(s, i): pass # Given a string s that has single-space separated words like "I am a fool" # Print the words in order, with their characters reversed # Try not to use any helper methods like split # For example, the result for "I am a fool" would be "I ma a loof" # You may consider using the above helper method find_word_boundary # 2 def reverse_words_in_list(s): pass # Given a 2D array board, that represents a square board of size n # find if its a winning combination # ie, that there is either a horizontal, vertical or any of the two diagnols are streams of 1 or 0 # example: # board[0] = [1, 0, 0], board[1] = [0, 1, 0], board[2] = [0, 0, 1] # and you call this method with board and n = 3, then it would return true (because there is a diagnol streak of 1) # 0 def is_winning(board, n): pass # Find two indices i, j in the list (that may be the same) such that l[i] + l[j] == n # Return that as a tuple def find_two_nums_summing(l, n): pass # Print the first n fibonacci numbers. # The numbers are defined as: # a_1 = 1 # a_2 = 1 # a_n = a_{n-1} + a_{n-2} def fibonacci(n): pass # a is a 2D matrix (array of arrays). Return true iff n exists in a def find_element_in_matrix(a, n): pass # Check if the substring sub exists in s. For example, find_substring("hello buffalo", "o b") == True def find_substring(s, sub): pass # is a string containing just '(' or ')'. For example it could be ((())) or (()()()) or ((() or )(() # Check if the string contains 'matched' paranthesis (matched as in it would be mathematically correct use of paranthesis). For example the last two examples aren't matched # Hint: Use the list methods append and pop. You can also read about "Stack datastructure" online def is_paranthesis_matched(s): pass
true
bf5541aff5d60357f0a736f7689cfeb3aa8b46e7
snidarian/Algorithms
/factorial_recursion.py
429
4.46875
4
#! /usr/bin/python3 # Factorial recursive algorithm import argparse parser = argparse.ArgumentParser(description="Returns factorial of given integer argument") args = parser.add_argument("intarg", help="Int to be factored", type=int) args = parser.parse_args() def factorial_recursive(n): if n == 1: return 1 else: return n * factorial_recursive(n - 1) print(factorial_recursive(args.intarg))
true
aa952649de3e87a99472f6cc2b92e7b2b8bf57ea
Factumpro/HackerRank
/Python/Practice/Sets/intersection.py
535
4.15625
4
''' Set .intersection() Operation https://www.hackerrank.com/challenges/py-set-intersection-operation/problem ''' ''' The .intersection() operator returns the intersection of a set and the set of elements in an iterable. Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set. The set is immutable to the .intersection() operation (or & operation). ''' _, x = input(), set( input().split()) _, y = input(), set( input().split()) print(len(x.intersection(y)))
true
9cd9cb9efd74fd3e3ff798b3865ace2590249fa4
Factumpro/HackerRank
/Python/Practice/Sets/union.py
481
4.1875
4
''' Set .union() Operation https://www.hackerrank.com/challenges/py-set-union/problem ''' ''' The .union() operator returns the union of a set and the set of elements in an iterable. Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set. Set is immutable to the .union() operation (or | operation). ''' not_need1 =input() a = set(input().split()) not_need2 = input() b = set(input().split()) print(len(a.union(b)))
true
42d6fba978a62e664aad1dbb1aa10fe161d51fab
Epic-R-R/Round-robin-tournament
/main.py
1,536
4.125
4
from pprint import pprint as pp def make_day(num_teams, day): # using circle algorithm, https://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm assert not num_teams % 2, "Number of teams must be even!" # generate list of teams lst = list(range(1, num_teams + 1)) # rotate day %= (num_teams - 1) # clip to 0 .. num_teams - 2 if day: # if day == 0, no rotation is needed (and using -0 as list index will cause problems) lst = lst[:1] + lst[-day:] + lst[1:-day] # pair off - zip the first half against the second half reversed half = num_teams // 2 return list(zip(lst[:half], lst[half:][::-1])) def PrintTable(schedule): days = [f"Day {i+1}" for i in range(len(schedule))] for i in range(len(schedule)): print(f"|Day {i+1}: ", end="") for j in schedule[i]: print("{} - {}| ".format(j[0], j[1]), end="") if len(schedule) == 5: print(f"\n{'-'*28}") else: print(f"\n{'-'*71}") def make_schedule(num_teams): """ Produce a one round schedule """ # number of teams must be even if num_teams % 2: num_teams += 1 # add a dummy team for padding # build round-robin schedule = [make_day(num_teams, day) for day in range(num_teams - 1)] return schedule def main(): num_teams = int(input("How many teams? ")) schedule = make_schedule(num_teams) PrintTable(schedule) # pp(schedule) if __name__ == "__main__": main()
true
9f815235eb7c74e01c17cd19ef5622bd843c8f1d
Elsie0312/pycharm_code
/two_truths-lie.py
584
4.15625
4
print('Welcome to Two Truths and a Lie! /n One of the following statements is a lie...you need to identify which one!') print('1. I have a donkey living in my backyard.') print('2. I have three fur babies') print('3. I speak 4 languages') truth_or_lie = input('Now put in the number of the statement you think is the lie!') conv_truth_or_lie = int(truth_or_lie) if conv_truth_or_lie == 1: print('Congrats, you have identified the lie correctly!') elif conv_truth_or_lie == 2: print('That is not the one!') elif conv_truth_or_lie == 3: print('Sorry, you have to try again')
true
2492520b1fc91cf095c964e1b178c483046766b6
besslwalker/algo-coding-practice
/4.1 Quicksort/quicksort.py
1,534
4.125
4
# Quicksort # Bess L. Walker # 2-21-12 import random def quicksort(unsorted): real_quicksort(unsorted, 0, len(unsorted)) def real_quicksort(unsorted, low, high): if high - low <= 1: return pivot_index = partition(unsorted, low, high) real_quicksort(unsorted, low, pivot_index) real_quicksort(unsorted, pivot_index + 1, high) def partition(unsorted, low, high): pivot_index = random.randint(low, high - 1) # inclusive of high bound pivot_value = unsorted[pivot_index] # Put pivot value at the end of the partition to keep it out of the way unsorted[pivot_index] = unsorted[high - 1] unsorted[high - 1] = pivot_value lowest_high_index = low # the lowest index of the higher-than-pivot values for index in range(low, high - 1): # don't go through the pivot if unsorted[index] < pivot_value: # then put it at the end of the lower-than-pivot section # unless it is already there if not index == lowest_high_index: temp = unsorted[lowest_high_index] unsorted[lowest_high_index] = unsorted[index] unsorted[index] = temp lowest_high_index += 1 # The low index of the higher-than-pivot section is where the pivot goes unsorted[high - 1] = unsorted[lowest_high_index] unsorted[lowest_high_index] = pivot_value return lowest_high_index permut_1 = [0, 1, 2, 3, 4 ,5] print permut_1 quicksort(permut_1) print permut_1 print permut_2 = [5, 4, 3, 2, 1, 0] print permut_2 quicksort(permut_2) print permut_2 print permut_3 = [3, 2, 21, 8, 4, 4] print permut_3 quicksort(permut_3) print permut_3
true
c7c008011e3694dae55fa8a676721bd8e9f5e78b
jaypsingh/PyRecipes
/String_n_Text/Str_n_Txt_07.py
710
4.4375
4
''' This program demonstrates how can we specify a regular expression to search shortest possible match. By Default regular expression gives the longest possible match. ''' import re myStr = 'My heart says "no." but mind says "yes."' # Problem demonstration ''' Here we ar etrying to match a text inside a quote. So i expect an answer as 'yes.' and 'no.' Lets see what it returns. ''' myProblemPat = re.compile(r'\"(.*)\"') print (myProblemPat.findall(myStr)) # Python returns ['no." but mind says "yes.'] # Solution ''' To fix this, we just need to add a ? after the * This will force python to search in a non gready way. ''' mySolutionPat = re.compile(r'\"(.*?)\"') print (mySolutionPat.findall(myStr))
true
f8d563e8c1ce87996fe1f0df6ebe05e65ff8a543
jaypsingh/PyRecipes
/String_n_Text/Str_n_Txt_05.py
445
4.1875
4
''' This function demonstrates how can we search and replace strings ''' import re myStr = "Today is 03/09/2016. Game of Thrones starts 21/07/2017" # Simple replace using str.replace() print (myStr.replace('Today', 'Tomorrow')) # Replace using re.sub() - Approach 1 print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3\-2\-1', myStr)) # Replace using re.sub() - Approach 2 newStr = re.compile(r'(\d+)/(\d+)/(\d+)') print(newStr.sub(r'\3\-2\-1', myStr))
true
c8913860b13c4619cd5119cacdce93fce0e6bcb7
DHSZ/programming-challenge-2
/seven-seg-words.py
300
4.40625
4
def longest_word(): longest_word = "" ## Write your Python3 code inside this function. ## Remember to find words that only use the following letters: ## A, B, C, E, F, H, I, J, L, N, O, P, S, U, Y ## Good luck!! return longest_word print(longest_word())
true
5f4313bc5806a145daf721c578f7120dd2755c01
HarrisonPierce/Python-Class
/pierce-assignment2.py
1,258
4.28125
4
##Harrison Pierce ##This program calculates the factorial of a user defined number ##Set factorial variable to 1 factorial = 1 k = int(input('Enter a postitive integer: ')) ##Ask user for an integer and set equal to the variable k for k in range(1,k + 1): ##start for loop for k. while between 1 and the number entered continue to stay in loop factorial = factorial * k ##multiply the number entered by k and each time add 1 to k ##until the numbner entered by the user is reached. print("The factorial of the number entered is ", factorial) ##Print the product of the factorial. ##------------------------------------------------------------------------------ ##Question 2 ##Create variable i and set equal to user input for number of rows desired i = int(input('Enter the number of rows: ')) ##create for loop that stays in loop until i is reached for row in range(i): ##print a pound sign for the column on the left print('#', end='', sep='') ##this loop prints the appropriate number of spaces for the current iteration in the ##outter for loop. for spacenum in range(row): ##print a space print(' ', end='', sep="") ##print the pound sign after reaching the appropriate number of spaces for the row print('#', sep='')
true
a9f0b22836ca6ae81e7d60383386fffdc7ef8011
Rayansh14/Term-1-Project
/rock paper scissors.py
2,289
4.25
4
import random score = 0 def generate_random(): return random.choice(["rock", "paper", "scissors"]) def is_valid(user_move): if user_move in ["rock", "paper", "scissors", "r", "p", "s"]: return True return False def result(comp_move, user_move): if comp_move == user_move: return "tie" if comp_move == "rock": if user_move == "paper": return "user" else: return "comp" elif comp_move == "paper": if user_move == "rock": return "comp" else: return "user" elif comp_move == "scissors": if user_move == "rock": return "user" else: return "comp" def scorekeeper(comp_choice, user_input): global score my_result = result(comp_choice, user_input) if my_result == "user": print(f"You chose {user_input} and the computer chose {comp_choice}, so you won.") score += 1 print(f"Score: {score}") elif my_result == "comp": print(f"You chose {user_input} and the computer chose {comp_choice}, so you lost.") score -= 1 print(f"Score: {score}") elif my_result == "tie": print(f"You chose {user_input} and the computer chose {comp_choice}, so it was a tie.") print(f"Score: {score}") print("This is a game of Rock-Paper-Scissors") print("Your possible moves are: rock, paper, scissors, r, p or s") print("Write 'quit' to terminate") print("Score: 0\n") while True: user_input = input("What's your move: ").lower() if user_input == "quit": if score < 0: print(f"The Computer won by {score} points!") elif score > 0: print(f"Congratulations! You won by {score} points!") else: print("The game was a tie!") break if not is_valid(user_input): print("Invalid Move") print("Your possible moves are: rock, paper, scissors, r, p or s\n") continue if user_input == "r": user_input = "rock" elif user_input == "s": user_input = "scissors" elif user_input == "p": user_input = "paper" comp_choice = generate_random() scorekeeper(comp_choice, user_input) print()
true
1bd93d500350c63fca4ba7e6a8ed3e1fb80bd1fe
UnKn0wn27/PyhonLearning-2.7.13
/ex11.py
505
4.21875
4
#raw_input() presents a prompt to the user(the optional arg of raw_intput([arg]) #gets input from the user and returns the data input by the user in a string. #Exemple: # name = raw_input("What is your name?") # print "Hello, %s." % name #raw_input was renamed input() in Python 3 print "How old are you?", age = raw_input() print "How tall are you", height = raw_input() print "How much do you weight?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." %( age, height, weight)
true
4d7eb9d814d4cd5db77400c7a96e1c18900eb00f
cantayma/web-caesar
/caesar.py
1,197
4.21875
4
import string def alphabet_position(letter): """ receives a letter, returns 0-based numerical position in the alphabet; case-sensitive; assumes letters only input """ if letter in string.ascii_uppercase: position = string.ascii_uppercase.find(letter) elif letter in string.ascii_lowercase: position = string.ascii_lowercase.find(letter) return position def rotate_character(char, rot): """ recieves a string, char, and an integer, rot, and returns a new string that is the character after it is rotated through the alphabet by rot """ if char in string.ascii_uppercase: newChar = string.ascii_uppercase[(alphabet_position(char) + rot) % 26] elif char in string.ascii_lowercase: newChar = string.ascii_lowercase[(alphabet_position(char) + rot) % 26] else: newChar = char return newChar def encrypt(text, rot): """ receives a string, text and an int, rot, and returns the encrypted text by rotating each character in text by rot positions """ encryptedText = "" for aLetter in text: encryptedText += rotate_character(aLetter, rot) return encryptedText
true
36d1432db82c986858bf650aa2c8281d494e01ac
tlananthu/python-learning
/00_simple_examples/06_maths.py
336
4.1875
4
number1=int(input('Please input a number')) number2=int(input('Please input another number')) operation=input('Please input an operation. +-/*') if operation=='+': print(number1+number2) elif operation=='-': print(number2-number2) elif operation=='/': print(number2/number2) elif operation=='*': print(number2*number2)
true
90094aafd436e093d00d2300a8278938caa788c1
Shwebs/Python-practice
/BasicConcepts/3.strings/string-multiplication.py
567
4.15625
4
#Strings can also be multiplied by integers. This produces a repeated version of the original string. # The order of the string and the integer doesn't matter, but the string usually comes first. print("spam" * 3) #O/p:spamspamspam print (4 * '2') #O/p: 2222 #Strings can't be multiplied by other strings. #Strings also can't be multiplied by floats, even if the floats are whole numbers. print ('17' * '87') #TypeError: can't multiply sequence by non-int of type 'str' print ( 'pythonisfun' * 7.0) #TypeError: can't multiply sequence by non-int of type 'float'
true
28b923b625a0d8e716f3a85b98cfea1ac81d285b
Shwebs/Python-practice
/ControlStructure/List/List-method-count.py
305
4.125
4
#list.count(obj): Returns a count of how many times an item occurs in a list letters = ['p', 'q', 'r', 's', 'p', 'u'] print(letters.count('r')) #O/P:-1 print(letters.count('p')) #O/P:-2 # index method finds the "first occurrence" of a list item and returns its index print(letters.count('z')) #O/P:-0
true
2fd82e086ef9fd6b383c2055f70ced123c94963d
Shwebs/Python-practice
/BasicConcepts/3.strings/string-methods/split.py
489
4.21875
4
#Splits string according to delimiter string, returns list of substrings. #Default delimiter is ' ' . str='Test My Skill' output=str.split() print(output) #o/p:- ['Test', 'My', 'Skill'] for x in output: print(x) #o/p:-Test # My # Skill #Delimiter can be changed in the split() argument str="02-May-2018" output=str.split('-') for x in output: print(x) time="12:00:05" output=time.split(':') for x in output: print(x)
true
e21cba589f4928a7ad09bd7ad84d786b5a4fb73c
Shwebs/Python-practice
/ControlStructure/range/basic-range.py
727
4.75
5
#The range function creates a sequential list of numbers. #The call to list is necessary because range by itself creates a range object, # and this must be converted to a list if you want to use it as one. #If range is called with one argument, it produces an object with values from 0 to that argument. numbers = list(range(5)) print(numbers) #If it is called with two arguments, it produces values from the first to the second. num = list(range(3, 8)) print(num) print(range(20) == range(0, 20)) nums1 = list(range(5, 8)) print(len(nums1)) #range can have a third argument, which determines the interval of the sequence produced. This third argument must be an integer. numbers = list(range(5, 20, 2)) print(numbers)
true
909325fdb03654071ecb54104d622e35e96a3497
Shwebs/Python-practice
/python-fundamentals-by-pluralsight/Object_Reference.py
1,065
4.25
4
#Pass by Object Reference #The value of the reference is copied , not the value of the object # Helpful Link https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ m = [9, 15, 24] def modify(k): """Appending a value to function. Args: A any literal can be added. Returns: If you want to modify a copy of a object it the responsiblity of the function to do the coping it. The literal will be appended at the end of the list. """ k.append(41) print("Value of k =", k) print("Value of m before function call=", m) modify(m) print("Value of m after function call=", m) # # f = [9, 15, 24] def replace(g): """Creating a new list. Args: A any literal can be added. Returns: If you want to modify a copy of a object it the responsiblity of the function to do the coping it. The literal will be appended at the end of the """ g = [17, 22, 35] print("Value of g =", g) print("Value of f before function call=", f) replace(f) print("Value of f after function call=", f)
true
79699f6e7d3ab0c9ad08ad75dcf510fae492166d
Shwebs/Python-practice
/ControlStructure/List/List-operation.py
1,186
4.53125
5
#The item at a certain index in a list can be reassigned. #In the below example , we are re-assigned List[2] to "Bull" nums = [7, 8, 9, 10, "spring"] nums[2] = "Bull" print(nums) print("===================================") #What is the result of this code? nums = [1, 2, 3, 4, 5] nums[3] = nums[1] # We are re-assigning nums[3] = 2 print(nums[3]) print(nums + [4, 5, 6]) print(nums * 3) print("===================================") ##Lists can be added and multiplied in the same way as strings. nums = [1, 2, 3] nums2 = [11,22,33] #print("nums * nums2", nums * nums2) #TypeError:can't multiply sequence by non-int of type 'list' print(nums[1] * nums2[1]) # We have multiplied 2 numbers. char = ["a","b","c"] char2 = ["x","y","z"] print ("char + char2", char + char2) #print ("char * char2", char * char2) #TypeError:can't multiply sequence by non-int of type 'list' print("Multiplying Number with Character list",nums[2]*char) # O/p:-2 * [a,b,c]=[a,b,c,a,b,c] print("Multiplying indexed Number with Character index list",nums[2]*char[2]) #O/P:- ccc #Lists and strings are similar in many ways - strings can be thought of as lists of characters that can't be changed.
true
18f795a10eb2da066a1599fd909069e2d00216fc
Shwebs/Python-practice
/ControlStructure/List/List-method-insert.py
797
4.25
4
#The insert method is similar to append, #except that it allows you to insert a new item at any position in the list, #as opposed to just at the end. words = ["Python", "fun"] index = 1 words.insert(index, "is") print (words) print("================================") nums = [1,2,3,5,6,7] index = 3 nums.insert(index,4) # it allows you to insert a new item at any position print("We have added 4 to the list ", nums) nums.append(8) print("We have added 8 (at the end) to the list ", nums) #it allows you to insert a new item only at end of the list. print("================================") #What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) #O/P:- [9, 8, 7, 6, 5, 4] print(nums) nums.insert(2, 11) #O/P:-[9, 8, 11, 7, 6, 5, 4] print(nums) print(len(nums)) #O/P:-7
true
fba81294a158815848dded2ca40206fb46b6ccd5
Shwebs/Python-practice
/BasicConcepts/3.strings/string-methods/string-is-check.py
1,386
4.21875
4
str=input("Enter a String: ") #isalnum() #Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. print('Checking If it is an alphanumeric :-',str.isalnum()) #isalpha() #Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. print('Checking If it is analphabestic :-',str.isalpha()) #isdigit() #Returns true if string contains only digits and false otherwise. print('Checking If it is numeric :-',str.isdigit()) #islower() #Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. print('Checking If string has character in lowercase :-',str.islower()) #isnumeric() #Returns true if a unicode string contains only numeric characters and false otherwise. print('Checking If string has numeric :-',str.isnumeric()) #isspace() #Returns true if string contains only whitespace characters and false otherwise. print('Checking If it is string has white space :-',str.isspace()) #istitle() #Returns true if string is properly "titlecased" and false otherwise. print('Checking If it is character in numeric :-',str.istitle()) #isupper() #Returns true if string has at least one cased character and all cased characters #are in uppercase and false otherwise. print('Checking If string has character in uppercase :-',str.isupper())
true
9539c945b6063ffdcd398710f03d371056ec52f7
IlyaTroshchynskyi/python_education_troshchynskyi
/algoritms/algoritms.py
2,512
4.125
4
# -*- coding: utf-8 -*- """calc Implements algorithms: - Binary search - Quick sort (iterative) - Recursive factorial """ def factorial(number): """ Define factorial certain number. """ if number <= 0: return 1 return number * factorial(number-1) print(factorial(50)) test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] def binary_search(input_list, number): """ Look for index of certain number by using algorithms binary search. Return None if number out of list. """ start = 0 stop = len(input_list) - 1 while start <= stop: middle = (stop + start) // 2 guess = input_list[middle] if guess == number: return middle if guess > number: stop = middle - 1 else: start = middle + 1 return None print(binary_search(test_list, 10)) def partition(my_list, start_index, end_index): """ Elements less than the last will go to the left of array and elements more than the last will go to the right of array """ start_index_1 = (start_index - 1) last_element = my_list[end_index] for j in range(start_index, end_index): if my_list[j] <= last_element: start_index_1 = start_index_1 + 1 my_list[start_index_1], my_list[j] = my_list[j], my_list[start_index_1] my_list[start_index_1 + 1], my_list[end_index] = my_list[end_index], my_list[start_index_1 + 1] return start_index_1 + 1 def quick_sort(my_list, start_index, end_index): """ Sort array in ascending order by using algorithms quick sort. """ size = end_index - start_index + 1 stack = [0] * size top = -1 top = top + 1 stack[top] = start_index top = top + 1 stack[top] = end_index while top >= 0: end_index = stack[top] top = top - 1 start_index = stack[top] top = top - 1 res_partition = partition(my_list, start_index, end_index) if res_partition - 1 > start_index: top = top + 1 stack[top] = start_index top = top + 1 stack[top] = res_partition - 1 if res_partition + 1 < end_index: top = top + 1 stack[top] = res_partition + 1 top = top + 1 stack[top] = end_index test_list = [4, 3, 5, 2, 1, 3, 2, 3] quick_sort(test_list, 0, len(test_list) - 1) for i, value in enumerate(test_list): print(f"Index: {i} Element:{value}")
true
e4b018aa44483d0eeed003818634cd3d785c2714
Zahidsqldba07/python_exercises-1
/exercise_7.py
348
4.4375
4
''' Write a Python program to accept a filename from the user and print the extension of that. Go to the editor Sample filename : abc.java Output: java ''' file_name = input('Enter file name with extension, example: abc.java') if file_name == '': file_name = 'abc.java' name = file_name.split('.')[0] ext = file_name.split('.')[-1] print(ext)
true
31e0794ad9981a270497e4cd91c2b9dbe52ea0f3
tohungsze/Python
/other_python/palindrome.py
869
4.1875
4
''' check if a given word is a palindrome ''' def main(): input = ['abcba', 'abc1cba', 'abcba ', 'abc1cba1'] for word in input: if is_palindrome(word): print('\'%s\' is a palindrome'%word) else: print('\'%s\' is a NOT palindrome'%word) def is_palindrome(input): # takes a string as input (cannot take list) input_list = list(input) input_reverselist = input_list # input_list and input_reverselist both points to same object input_reverselist.reverse() input_list = list(input) # now input_list and input_reverselist point to different object result = True for i in range(len(input_list)): if input_list[i] == input_reverselist[i]: continue else: result = False break return result if __name__ == '__main__': main()
true
9ce0cec8b92e20b92a39e6e5d1af707c3db4fb27
tohungsze/Python
/other_python/fibonacci.py
1,139
4.28125
4
# demonstrate fibonacci with and without caching ''' # this is really slow, can't handle more than 30 ish numbers def fibonacci_n(n): if n == 0 or n ==1: return 1 else: return fibonacci_n(n-1) + fibonacci_n(n-2) for i in range(1, 11): print("fibonacci(", i, ") is:", fibonacci_n(i)) ''' ''' cache_dict = {} # manual caching def fibonacci_mc(n): # mc = manual cache global cache_dict if n in cache_dict: return cache_dict[n] if n == 1 or n == 2: #cache_dict[n]=1 result = 1 else: result = fibonacci_mc(n-1) + fibonacci_mc(n-2) cache_dict[n] = result return result for i in range(1, 1001): print("fibonacci(", i, ") is:", fibonacci_mc(i)) ''' # using functools lru # with lru, originally slow simple calculation is fast! # each function will have own cache from functools import lru_cache @lru_cache(maxsize = 1000) #default is 128 def fibonacci_lru(n): if n == 0 or n == 1: return 1 else: return fibonacci_lru(n - 1) + fibonacci_lru(n - 2) for i in range(1, 10001): print("fibonacci(", i, ") is:", fibonacci_lru(i))
true
ff7c0a83280f5080fcef88e288d96fbeda29289e
prashantkgajjar/Machine-Learning-Essentials
/16. Hierarchical Clustering.py
2,929
4.15625
4
# Hierarchical Clustering ''' 1. Agglomerative Hierarchical Clustering (Many single clusters to one single cluster) 1. Make each data point as a single point Cluster. 2. Take the two closest datapoints, and make them one cluster. 3. Take to closest clusters, and make them one cluster. 4. Repeat STEP 3 unitll there is only one cluster. ''' ''' ******** Distance between two clusters:******* Option 1: Measure Distance between two closest points Option 2: Measure Distance between two farthest points Option 3: Take the average of the all points of clusters Option 4: Measure the distance between two centroids of clusters. ''' ''' ******** Dendograpms *********** It is a diagram that shows the Hierarchical relationship between two clusters or data points To optimize the clustering, selecting the Dendograms with the Highest Distance is considered as a optimal limit of number of cluster. ''' # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # Using the dendrogram to find the optimal number of clusters import scipy.cluster.hierarchy as sch dendrogram = sch.dendrogram(sch.linkage(X, method = 'ward')) plt.title('Dendrogram') plt.xlabel('Customers') plt.ylabel('Euclidean distances') plt.show() ''' From the above plot, it can be understood that the length(line) with highest gap between the clusters is the first line orangge one. From that line, 5 others such line are passsing, so we can conclude that there are 5 such clusters. ''' # Training the Hierarchical Clustering model on the dataset from sklearn.cluster import AgglomerativeClustering hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward') y_hc = hc.fit_predict(X) # Visualising the clusters plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Cluster 1') plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Cluster 2') plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Cluster 3') plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4') plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5') plt.title('Clusters of customers') plt.xlabel('Annual Income (k$)') plt.ylabel('Spending Score (1-100)') plt.legend() plt.show() ''' From the cluster, it can be concluded that::: Cluster 1: Red Color -- They spend less, despite earning high Cluster 2: Blue Color -- Average customer, those who has average income & average spends Cluster 3: Green Color -- They earn more, spend more. Perfect to target for advertisements Cluster 4: Light Blue Colo -- They earn less, but mostly spends high at the mall. cLUSTER 5: Pink Color -- Thay ean less & spends less '''
true
5f4d01e512104db3e264784891663d304937ed96
HsiaoT/Python-Tutorial
/data_structure/Sorting/Selection_sort.py
802
4.28125
4
# The selection sort algorithm sorts an array by repeatedly finding the # minimum element (considering ascending order) from unsorted part and # putting it at the beginning. The algorithm maintains two subarrays in a given array. # Time complexity (average): O(n^2) # Time complexit (best): O(n^2) (list already sorted) # Space complexity: O(1) import random init_random_Data = random.sample(range(100), 10) print("Init list:") print(init_random_Data) def selection_sort(nums): for i in range(len(nums)): min_index = i for j in range(i+1, len(nums)): # Find the minimum if nums[min_index] > nums[j]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums sorted_Data = selection_sort(init_random_Data) print("\nsorted list:") print(sorted_Data)
true
d9bc14d8ae35cb2475bb92bcc8d99446694bc590
sunDalik/Information-Security-Labs
/lab1/frequency_analysis.py
2,879
4.3125
4
import argparse # Relative letter frequencies in the English language texts # Data taken from https://en.wikipedia.org/wiki/Letter_frequency theory_frequencies = {'A': 8.2, 'B': 1.5, 'C': 2.8, 'D': 4.3, 'E': 13.0, 'F': 2.2, 'G': 2.0, 'H': 6.1, 'I': 7.0, 'J': 0.15, 'K': 0.77, 'L': 4.0, 'M': 2.4, 'N': 6.7, 'O': 7.5, 'P': 1.9, 'Q': 0.095, 'R': 6.0, 'S': 6.3, 'T': 9.1, 'U': 2.8, 'V': 0.98, 'W': 2.4, 'X': 0.15, 'Y': 2.0, 'Z': 0.074} def main(): # Reads encrypted text from file by name [filename] and outputs result to stdout usage = 'frequency_analysis.py filename' parser = argparse.ArgumentParser(usage=usage) parser.add_argument('filename', action='store') args = parser.parse_args() # Data to Theory letters mapping dtt = {letter: 0 for letter in theory_frequencies} # Number of english alphabet characters encountered data_len = 0 # File contents data = "" # Step 1. Read file and count how many of each letters there are with open(args.filename) as message: while True: # Process text file char by char c = message.read(1) # Stop reading file when it ends if not c: break data += c if c in dtt: data_len += 1 dtt[c] += 1 continue # Step 2. Get letter frequencies by dividing the amount of each letter by data length and multiplying it by 100 for k in dtt: dtt[k] = dtt[k] / data_len * 100 # Step 3. Create mapping between encrypted letters and real letters for k in dtt: best_letter = "" best_diff = 999 # Compare every encrypted letter to every real letter to find the best correlation for m in theory_frequencies: # Calculate frequency difference between current encrypted letter and real letter diff = abs(theory_frequencies[m] - dtt[k]) # If this is the lowest difference and this real letter was not yet assigned to any encrypted letter # then we found a mapping if diff <= best_diff and m not in dtt.values(): best_diff = diff best_letter = m # Map our best real letter candidate to the current encrypted letter dtt[k] = best_letter # Debug # print(dtt) # Output decrypted message by mapping every encrypted alphabet character to the real counterpart decrypted_message = "" for char in data: if char in dtt: decrypted_message += dtt[char] else: # If a character is not present in the alphabet then output it without any changes decrypted_message += char print(decrypted_message) main()
true
50d5314cda34ce36b4af6d37acdc81b3a87a17f8
luckychummy/practice
/queueUsingStack.py
1,222
4.28125
4
from queue import LifoQueue class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.q1=LifoQueue() self.q2=LifoQueue() def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ while(not self.q2.empty()): self.q1.put(self.q2.get()) self.q2.put(x) while(not self.q1.empty()): self.q2.put(self.q1.get()) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ return self.q2.get() def peek(self): """ Get the front element. :rtype: int """ item=self.q2.get() self.q2.put(item) return item def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return self.q2.empty() #Your MyQueue object will be instantiated and called as such: obj = MyQueue() obj.push(5) obj.push(6) obj.push(7) obj.push(8) param_2 = obj.pop() param_3 = obj.peek() param_4 = obj.empty()
true
34f84a9883b3d57911b30aea2ab4470efa57e482
AsharGit/Python-ICP
/Source/ICP-3/Employee.py
1,137
4.28125
4
class Employee: num_employees = 0 total_salary = 0 def __init__(self, name, family, salary, department): self.emp_name = name self.emp_family = family self.emp_salary = salary self.emp_dept = department self.increment(salary) # Increment num_employees and total_salary def increment(self, salary): self.__class__.num_employees += 1 self.__class__.total_salary += salary # Return the average salary of employees def avg_salary(self): return self.total_salary / self.num_employees class FulltimeEmployee(Employee): # Increment num_employees and total_salary in parent class def increment(self, salary): Employee.num_employees += 1 Employee.total_salary += salary # Initialize an employee and a full time employee emp1 = Employee('Bob', 'Smith', 40000, 'health') emp2 = FulltimeEmployee('Linda', 'Smith', 80000, 'health') print(emp1.emp_name) print(emp1.emp_salary) print(emp2.emp_name) print(emp2.emp_salary) print(emp1.num_employees) print(emp2.num_employees) print(emp1.avg_salary()) print(emp2.avg_salary())
true
e50d45dda524f0471a01371f202cb2f7384ca07f
stompingBubble/Asteroids
/shape.py
2,492
4.15625
4
# -*- coding: utf-8 -*- """ Gruppuppgift: Asteroids - Objektorienterad Programmering Nackademin IOT 17 Medverkande: Isa Sand Felix Edenborgh Christopher Bryant Stomme källkod: Mark Dixon """ from abc import ABC, abstractmethod import math from point import Point class Shape(ABC): def __init__( self, x=0, y=0, rotation=0 ): self.position = Point(x,y) self.rotation = rotation self.pull = Point(0,0) self.angular_velocity = 0.0 @abstractmethod def draw(self, screen): pass def update(self, width, height): """ Update the position and orientation of the shape :param width: screen width to confine the shape to :param height: screen height to confine the shape to :return: """ # Update the position and orientation of the shape # position is modified by "pull" - how much it should move each frame # rotation is modified by "angular_velocity" - how much it should rotate each frame self.position += self.pull self.rotation += self.angular_velocity # Use modulus to ensure that the object never vanishes from the screen # Position is wrapped to always be between (0,0) and (width,height) # Rotation is wrapped to always be between 0 and 360 degrees self.position.x %= width self.position.y %= height self.rotation %= 360 def accelerate(self, acceleration): """ Cause the object to start moving by giving it a little push :param acceleration: ammount to accelerate the shape by, if 0 then the shape is slowed down instead """ # if acceleration==0: self.pull.x *=0.9 self.pull.y *=0.9 else: self.pull.x += (acceleration * math.cos(math.radians(self.rotation))) self.pull.y += (acceleration * math.sin(math.radians(self.rotation))) def rotate(self, degrees): """ Rotation the shape by a specific amount :param degrees: angle in degrees for the shape to be rotated by """ self.rotation = ( self.rotation + degrees ) % 360; @abstractmethod def contains(self, point): if point: return True """ Abstract base class to perform collission detection - should return true if a point is inside the shape :param point: Point to test for collission :return: True or False """ return False
true
ffd1c6706c107f8fa4ca74bf33d36650046d0608
thechemist54/PYth0n-and-JaVa
/Area calculation.py
1,663
4.4375
4
#printing the options print("Options:") print("-"*8) print("1. Area of Rectangle") print("2. Area of Triangle") print("3. Area of Circle") print("4. Quit") #assigning a value to flag flag = False #analyzing responses and displaying the respective information #looping statement while flag == False: #asking to make a choice from the option choice = int(input("\nMake a selection from the option menu: ")) if choice == 1: #asking for height and width height = float(input ("\nEnter height: ")) width = float(input ("Enter width: ")) area_rectangle = (height * width) #calculating area print ("Area of rectangle is","{0:,.2f}".format(area_rectangle)) elif choice == 2: #asking for the base and height base = float(input("\nEnter base: ")) height_triangle = float(input ("Enter height of triangle: ")) area_triangle = ((1/2) * base * height_triangle) #calculating area print ("Area of triangle is","{0:,.2f}".format(area_triangle)) elif choice == 3: #asking for the radius of a circle radius = float(input("\nEnter the radius of a circle: ")) area_circle = (3.141592)*(radius**2)#calculating area of circle print ("Area of circle is","{0:,.2f}".format(area_circle)) elif choice == 4: #assigning flag as true flag = True else: #displaying the error message print("\nYou did not enter a proper number.")
true
a948e2106b7150b3a41ae7486415a8dc17842292
AndrejLehmann/my_pfn_2019
/Vorlesung/src/Basic/example4_2.py
769
4.65625
5
#!/usr/bin/env python3 # Example 4-2 Concatenating DNA # store two DNA sequences into two variables called dna1 and dna2 dna1 = 'ACGGGAGGACGGGAAAATTACTACGGCATTAGC' dna2 = 'ATAGTGCCGTGAGAGTGATGTAGTA' # print the DNA onto the screen print('Here are the original two DNA sequences:') print(dna1) print(dna2) # concatenate DNA sequences into a 3rd var with format dna3 = '{}{}'.format(dna1, dna2) print('concatenation of the first two sequences (version 1):') print(dna3) # alternative way using the concatenation operator +: dna3 = dna1 + dna2 print('Concatenation of the first two sequences (version 2):') print(dna3) # print the same thing without using the variable dna3 print('Concatenation of the first two sequences (version 3):') print(dna1 + dna2) exit(0)
true
e2802f46eeb773f497cab112e4a74fe96b763f8f
pravalikavis/Python-Mrnd-Exercises
/finaltest_problem3.py
2,052
4.34375
4
__author__ = 'Kalyan' max_marks = 25 problem_notes = ''' For this problem you have to implement a staircase jumble as described below. 1. You have n stairs numbered 1 to n. You are given some text to jumble. 2. You repeatedly climb down and up the stairs and on each step k you add/append starting k chars from the text you have (and remove them from the text). 3. You repeat this process till you finish the whole text. 4. Finally you climb up from step 1 and collect all chars to get the jumbled text. E.g. if the text is "Ashokan" and n = 2. You have the following text on the steps. First you drop "As" on step 2, then "h" on step 1, then you get to the ground and you climb back again droping "o" on step 1 and "ka" on step2 and finally "n" on step2 (since you have run out of chars and you dont have 2 chars). So sequence of steps is 2, 1 then 1, 2 then 2, 1 and so on... (step2)As;ka;n ---- (step 1)|h;o ---- Final jumbled text is hoAskan (all text on step1 followed by all text on step2, the ; is shown above only to visually distinguish the segments of text dropped on the stair at different times) Notes: 1. Raise ValueError if n <= 0 2. Raise TypeError if text is not a str 3. Note that spaces, punctuation or any other chars are all treated like regular chars and they will be jumbled in same way. ''' def jumble(text, n): if type(text).__name__ != 'str': raise TypeError if n <= 0: raise ValueError c = n l = [] o = 0 while text != "": l.append((text[:c], c)) text = text[c:] if o == 0: c = c - 1 if c == 0: c = 0 o = 1 if o == 1: if c == n: o = 0 continue c = c + 1 l.sort(key=lambda x: x[1]) res = "" for a in l: res = res + a[0] return res def test_jumble(): assert "hoAskan" == jumble("Ashokan", 2)
true
2873efc5e996028da3dbe1d1a3a70e8046511c65
pankajdahilkar/python_codes
/prime.py
268
4.1875
4
def isPrime(a=0): i=2 if a==0 : return 0 while(i<a): if a%i==0: return 0 i=i+1 return 1 x=int(input("Enter The number : ")) if(isPrime(x)): print(x, "is Prime number ") else : print(x," is not Prime number")
true
44894e050247f38dc88e2184ed65b8e7fc3e868e
pravishbajpai06/Projects
/6.py
1,483
4.1875
4
#6-Change Return Program - The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. import math cent=0.01 penny=0.01 nickel=0.05 dime=0.1 quarter=0.25 do=1 cost=float(input("Enter the costt")) amount=float(input("Enter amount paid")) if cost>amount: change=cost-amount s=round((change/cent),2) p=round((change/cent),2) n=round((change/nickel),2) d=round((change/dime),2) q=round((change/quarter),2) de=round((change/do),2) print("U can pay ur left amount by paying",s,"cents OR ",p,"pennies OR ", n,"nickels OR", d,"dimes OR",q,"quarters OR", de,"dollars" ) elif amount>cost: change=amount-cost if change>0: s=round((change/cent),2) p=round((change/cent),2) n=round((change/nickel),2) d=round((change/dime),2) q=round((change/quarter),2) de=round((change/do),2) print("How would you like to have your change",(s),"cents \n OR \n",p,'pennies \n OR \n"',n,"nickels \n OR \n",d,"dimes \n OR \n",q,"quarters \n OR \n",de,"dollars") elif cost==amount: print("Thanks for your purchase \n change left=0")''' #-Print hex oct...... '''number=int(input()) width = len('{:b}'.format(number)) for i in range(1,number+1): print(str.rjust(str(i),width),str.rjust(str(oct(i)[2:]),width),str.rjust(str(hex(i).upper()[2:]),width),str.rjust(str(bin(i)[2:]),width))
true
b2b10777497bf79f6353bd04ac19ddb0d69fc281
0x0all/coding-challenge-practices
/python-good-questions/reverse_vowels.py
542
4.28125
4
""" The Problem: Write a function to reverse the vowels in a given string Example: input -> output "hello elephant" -> "halle elophent" "abcde" -> "ebcda" "abc" -> "abc" """ def reverse_vowels(s): vowels = 'aeiou' res = list(s) pos = [index for index, char in enumerate(s) if char in vowels] reversed_pos = pos[::-1] for index in range(len(pos)): res[pos[index]] = list(s)[reversed_pos[index]] return ''.join(res) if __name__ == '__main__': print reverse_vowels("hello elephant")
true
6736443ed68910ee2e4d2d665da47667024e19c3
vasanth9/10weeksofcp
/basics/classesandobjects.py
1,491
4.21875
4
#classes and objects """ Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ class myclass: x=5 p1=myclass() print(p1.x) """ All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: """ class Person: def __init__(self,name,age): self.name=name self.age=age def printname(self): print("my name is",self.name) p1=Person("vasanth",19) print(p1.name," ",p1.age) p1.printname() #change values p1.age=40 print(p1.age) #del del p1.age print(p1) print(p1.name) """ print(p1.age) gives error age was deleted Traceback (most recent call last): File "classesandobjects.py", line 32, in <module> print(p1.age) AttributeError: 'Person' object has no attribute 'age' """ del p1 #object deletion """ 5 vasanth 19 my name is vasanth 40 <__main__.Person object at 0x7f3d8d87d8e0> vasanth """ #inheritance class Student(Person): def __init__(self, name, age, year): super().__init__(name, age) self.graduationyear = year def welcome(self): print("Welcome", self.name, "to the class of", self.graduationyear) s1=Student("Amulya",18,2038) s1.welcome() #Welcome Amulya to the class of 2038
true
6bc780d508f837ca9c0428fa160e72932b2060c8
futurice/PythonInBrowser
/examples/session1/square.py
837
4.5625
5
# Let's draw a square on the canvas import turtle ##### INFO ##### # Your goal is to make the turtle to walk a square on the # screen. Let's go through again turtle commands. # this line creates a turtle to screen t = turtle.Turtle() # this line tells that we want to see a turtle shape t.shape("turtle") # this line moves turtle 100 steps forward t.forward(100) # here the turtle turns 90 degrees to the left t.left(90) # And again turtle moves forward t.forward(50) ##### EXERCISE ##### # What do you need to add to have the turtle walk a square # and return where he started? # TIP: you can always hit 'Run' to check what you're about to draw. # add code here: ##### Additional exercise ##### # how would you need to change the commands to have the # turtle draw a diamond (square with tip towards the top) instead?
true
14207390dc1852453b97d8922b1f8b3607f26e64
futurice/PythonInBrowser
/examples/session1/wall.py
998
4.46875
4
# Goal: help the turtle to find a hole in the wall # We need to remember to import a turtle every time we want # to use it. import turtle ##### INFO ##### # The following code draws the wall and the target. You can # look at the code but to get to the actual exercise, scroll # down. # Here we create a wall to the middle of the screen wall = turtle.Turtle() wall.hideturtle() wall.speed("fastest") wall.width(4) wall.penup() wall.setx(100) wall.sety(110) wall.pendown() wall.sety(-500) wall.penup() wall.sety(140) wall.pendown() wall.sety(500) wall.penup() wall.right(90) wall.forward(420) wall.setx(200) # create a red dot wall.dot(20, "red") # here we create new turtle, with name Joe joe = turtle.Turtle() joe.shape("turtle") # joe is taking a stroll here joe.right(120) joe.forward(100) joe.right(90) joe.forward(50) ##### EXERCISE ##### # Hit 'Run' and see where Joe is about to go. # What do you need to add to have Joe walk to the red dot? # Don't touch the wall! # add code here:
true
5f66bea9207f8a7149844204245dc09345a636aa
futurice/PythonInBrowser
/examples/session3/function.py
2,912
4.8125
5
# Computing with functions import turtle t = turtle.Turtle() ##### INFO ##### # Fucntions can be used for computing things. # # As an example, let's consider computing an area of a # circle. You may remember form a math class that the area # of a circle is computed by multiplying the radius of the # circle by itself and by the number pi. # # Pi is a mathematical constant. It's approximate value is # below: pi = 3.14159265359 # We can compute the area of a circle with radius of 15 as # follows: area15 = pi * 15 * 15 t.circle(15) print 'Area of circle with radius 15 is ' + str(area15) # Area of a bit larger circle that has radius 22 is: area22 = pi * 22 * 22 t.circle(22) print 'Area of circle with radius 22 is ' + str(area22) ##### EXERCISES ##### ##### EXERCISE 1 ##### # What is the area of a circle that has radius of 30? ##### EXERCISE 2 ##### # Let's define a function for computing the area of a # circle: def circle_area(radius): return pi * radius * radius # "return" means that the function finishes execution and # the value of the expression after the "return" is computed # and passed out of the function back to the program that # called the function. # # The circle_area function, which we just defined above, # takes one parameter called radius. We need to specify a # value for the parameter by writing the value in # parenthesis after the function name like this: # circle_area(15). In this example, the radius variable in # the function will be 15 when the function is executed. # # We can use the function to compute the area of circle with # radius 15 (again) and assign the returned value to a # variable called area15_with_function, and the print its # value: area15_with_function = circle_area(15) print 'Area of circle with radius 15 computed by a function is ' + str(area15_with_function) # 1. Check that the value you got here is the same as the # first value we computed in this exercise. They should be # the same because they both are the area of a circle with # radius 15. # 2. Compute the area of circle with radius 22 using the # function. # 3. Compute the area of circle with radius 30 using the # function. ##### ADDITIONAL EXERCISE ##### # Functions can also manipulate strings. This function # counts the number of vowels in a text string. def count_vowels(text): count = 0 for letter in text: if letter.lower() in u"aeiouyöä": count = count + 1 return count # For example, the following code will count the number of # vowels in the word "Python". Remove the comment mark from # the line below. # # print 'Number of vowels in the word "Python": ' + str(count_vowels("Python")) # 1. Can you come up the words that contain 5 vowels? What # about 6 or even more? # 2. Write a function that counts the number of consonants # (letters that are not vowels). Try to come up with words # that contain as many consonants as possible.
true
35c92a9c66af8bcf6ee2eeec1eb9f3743e375091
ShaneKoNaung/Python-practice
/stack-and-queue/linked_list_queue.py
1,222
4.25
4
''' implementing queue using linked-list''' class LinkedListQueue(object): class Node(object): def __init__(self, data, next=None): self._data = data self._next = next def __init__(self): self._head = None self._tail = None self._size = 0 def __len__(self): ''' return the number of element in the queue''' return self._size def is_empty(self): ''' return True if the queue is emtpy''' return self._size == 0 def first(self): ''' return the first element in the queue ''' return self._head._data def dequeue(self): ''' remove the first element in the queue ''' if self.is_empty(): raise IndexError("queue is empty") answer = self._head._data self._head = self._head._next self._size -= 1 if self.is_empty(): self._tail = None return answer def enqueue(self, e): ''' add an element at the end of the queue''' node = self.Node(e) if self.is_empty(): self._head = node else: self._tail._next = node self._tail = node self._size += 1
true
2f9976e9ae634c5d370e0a45e4484a9c63e7d363
ShaneKoNaung/Python-practice
/stack-and-queue/linked_list_stack.py
1,171
4.125
4
''' Implementation of stack using singly linked list ''' class LinkedListStack(object): class Node(object): def __init__(self, data, next=None): self._data = data self._next = next def __init__(self): ''' create an empty stack ''' self._head = None self._size = 0 def __len__(self): ''' return Number of elements in the list ''' return self._size def is_empty(self): ''' return True if the list is empty''' return self._size == 0 def push(self, e): ''' add element at the top of the stack ''' self._head = self.Node(e, self._head) self._size += 1 def top(self): ''' return the element at the top of the stack''' if self.is_empty(): raise IndexError("Stack is empty") else: return self._head._data def pop(self): ''' remove and return the element at teh top of the stack''' if self.is_empty(): raise IndexError("stack is empty") answer = self._head._data self._head = self._head._next self._size -= 1 return answer
true
5151cfe22c6ba893660c49ba006b512c77a74e6b
Suryashish14/Suryashish-Programs
/SpecialCalculator 1.py
2,115
4.25
4
print('::::::::::::::::::::::::::: MENU ::::::::::::::::::::::::::::::::::') print('Press 1 To Check For Armstrong Number') print('Press 2 To Check For Duck Number') print('Press 3 To Check For Perfect Number') print('\t\t\t\t Instructions') print('''1.Provide Only Positive Numbers 2.For Using The Menu Use Only 1,2,3''') a=int(input('Enter Your Choice From The Above Menu:')) if a==1 or a==2 or a==3: print(':::::::::::: WELCOME ::::::::::::::::::::') if a==1: b=int(input('Enter A Number:')) numcopy1=b add=0 if b>0: while numcopy1>0: part=int(numcopy1%10) add+=part**3 numcopy1//=10 if add==b: print('Its an Armstrong Number') else: print('Its Not An Armstrong Number') else: print('Invalid Input!Provide Any Positive Integer') if a==2: c=int(input('Enter Any Positive Number:')) numcopy2=c flag=0 if c>0: while numcopy2>0: rem=int(numcopy2%10) numcopy2//=10 if rem==0: flag+=1 break if flag>0: print(c,'is a Duck Number') else: print(c,'is Not a Duck Number') else: print('Invalid Input!Please Provide Any Positive Integer') if a==3: d=int(input('Enter Any Positive Integer:')) numcopy3=d factors=0 if d>0: for i in range(1,numcopy3): if numcopy3%i==0: factors+=i if factors==d: print('It is a Perfect Number') else: print('It is Not A a Perfect Number') else: print('invalid Input!Please Enter A Positive Number') else: print('Invalid Input!Please Follow The Instructions') print('\n') print('''Thank You For Using This Program.. It Has Developed By Suryashish Guha ''')
true
034c084055637a5c567c8c6b25e6ccd6c25a302e
u101022119/NTHU10220PHYS290000
/student/100021216/myclass.py
734
4.125
4
import copy import math class point(object): '''Represents a point in 2-D space.''' class rectangle(object): """ Represents a rectangle. attributes: width, height, corner. """ a=point() a.x=0.0 a.y=0.0 b=point() b.x=3.0 b.y=4.0 box=rectangle() box.width=100.0 box.height=200.0 box.corner=point() box.corner.x=0.0 box.corner.y=0.0 def print_point(p): print '(%g,%g)' % (p.x,p.y) def distance_between_points(a,b): distance=math.sqrt((a.x-b.x)**2+(a.y-b.y)**2) return distance def move_rectangle(rect,dx,dy): rect.corner.x += dx rect.corner.y += dy def move_rectangle_1(rect,dx,dy): global newbox newbox=copy.deepcopy(rect) newbox.corner.x += dx newbox.corner.y += dy
true