blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c914ff467f6028b7a7e9d6f7c3b710a1445d15e4 | Safirah/Advent-of-Code-2020 | /day-2/part2.py | 975 | 4.125 | 4 | #!/usr/bin/env python
"""part2.py: Finds the number of passwords in input.txt that don't follow the rules. Format:
position_1-position_2 letter: password
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
"""
import re
valid_passwords_count = 0
lines = [line.rstrip('\n') for line in open("input.txt")]
for line in lines:
match = re.search("(?P<pos_1>\d+)-(?P<pos_2>\d+) (?P<letter>.): (?P<password>.+)", line)
pos_1 = int(match.group('pos_1'))
pos_2 = int(match.group('pos_2'))
letter = match.group('letter')
password = match.group('password')
password_pos_1 = password[pos_1 - 1]
password_pos_2 = password[pos_2 - 1]
if (bool(password_pos_1 == letter) is not bool(password_pos_2 == letter)):
valid_passwords_count = valid_passwords_count + 1
print (f"Valid passwords: {valid_passwords_count}") | true |
17bca95271d269cf806decd0f1efafa05367146c | ycechungAI/yureka | /yureka/learn/data/bresenham.py | 1,424 | 4.125 | 4 | def get_line(start, end):
"""Modified Bresenham's Line Algorithm
Generates a list of tuples from start and end
>>> points1 = get_line((0, 0), (3, 4))
>>> points2 = get_line((3, 4), (0, 0))
>>> assert(set(points1) == set(points2))
>>> print points1
[(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
>>> print points2
[(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
# Determine how steep the line is
is_steep = abs(dy) > abs(dx)
# Rotate line
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
# Swap start and end points if necessary
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
# Recalculate differentials
dx = x2 - x1
dy = y2 - y1
# Calculate error
error = int(dx / 2.0)
ystep = 1 if y1 < y2 else -1
# Iterate over bounding box generating points between start and end
prev_x = None
prev_y = None
y = y1
for x in range(x1, x2 + 1):
coord = (y, x) if is_steep else (x, y)
if prev_x is None or prev_x != coord[0]:
yield (0, coord[0])
prev_x = coord[0]
if prev_y is None or prev_y != coord[1]:
yield (1, coord[1])
prev_y = coord[1]
error -= abs(dy)
if error < 0:
y += ystep
error += dx
| true |
f712fa962c06854c9706919f63b52e6a6a6002ab | vasetousa/Python-basics | /Animal type.py | 263 | 4.21875 | 4 | animal = input()
# check and print what type animal is wit, also if it is a neither one (unknown)
if animal == "crocodile" or animal == "tortoise" or animal == "snake":
print("reptile")
elif animal == "dog":
print("mammal")
else:
print("unknown")
| true |
bc25ffa52620a3fd26e1b687452a60cb18dbf75e | Paulokens/CTI110 | /P2HW2_MealTip_PaulPierre.py | 968 | 4.375 | 4 | # Meal and Tip calculator
# 06/23/2019
# CTI-110 P2HW2 - Meal Tip calculator
# Pierre Paul
#
# Get the charge for the food.
food_charge = float(input('Enter the charge for the food: '))
# Create three variables for the tip amounts.
tip_amount1 = food_charge * 0.15
tip_amount2 = food_charge * 0.18
tip_amount3 = food_charge * 0.20
# Create three variables for the meal's total cost.
meal_total_cost1 = food_charge + tip_amount1
meal_total_cost2 = food_charge + tip_amount2
meal_total_cost3 = food_charge + tip_amount3
# Display the result.
print("For a 15% tip, the tip amount is",format(tip_amount1,',.2f'), "and the meal's total cost is",format (meal_total_cost1,",.2f"))
print("For an 18% tip, the tip amount is", format(tip_amount2,',.2f'), "and the meal's total cost is",format (meal_total_cost2,",.2f"))
print("For a 20% tip, the tip amount is", format(tip_amount3, ',.2f'), "and the meal's total cost is",format (meal_total_cost3,",.2f"))
| true |
f27015948ad6042d42f278c8cbd287d46b502e93 | GaryLocke91/52167_programming_and_scripting | /bmi.py | 392 | 4.46875 | 4 | #This program calculates a person's Body Mass Index (BMI)
#Asks the user to input the weight and height values
weight = float(input("Enter weight in kilograms: "))
height = float(input("Enter hegiht in centimetres: "))
#Divides the weight by the height in metres squared
bmi = weight/((height/100)**2)
#Outputs the calculation rounded to one decimal place
print("BMI is: ", round(bmi, 1))
| true |
92bc95604d982256a602ef749f090b63b4f47555 | knightscode94/python-testing | /programs/cotdclass.py | 433 | 4.28125 | 4 |
"""
Define a class named Rectangle, which can be constructed by a length and width.
The Rectangle class needs to have a method that can compute area.
Finally, write a unit test to test this method.
"""
import random
class rectangle():
def __int__(self, width, length):
self.width=width
self.length=length
def area():
return length*width
length=random.randint(1,100)
width=random.randint(1,100)
| true |
499cccb2e57239465a929e0a2dc0db0e9d4602b7 | ivankatliarchuk/pythondatasc | /python/academy/sqlite.py | 872 | 4.1875 | 4 | import sqlite3
# create if does not exists and connect to a database
conn = sqlite3.connect('demo.db')
# create the cursor
c = conn.cursor()
# run an sql
c.execute('''CREATE TABLE users (username text, email text)''')
c.execute("INSERT INTO users VALUES ('me', 'me@mydomain.com')")
# commit at the connection level and not the cursor
conn.commit()
# passing in variables
username, email = 'me', 'me@mydomain.com'
c.execute("INSERT INTO users VALUES (?, ?)", (username, email) )
# passing in multiple records
userlist = [
('paul', 'paul@gmail.com'),
('donny', 'donny@gmail.com'),
]
c.executemany("INSERT INTO users VALUES (?, ?)", userlist )
conn.commit()
# passed in variables are tuples
username = 'me'
c.execute('SELECT email FROM users WHERE username = ?', (username,))
print c.fetchone()
lookup = ('me',)
c.execute('SELECT email FROM users WHERE username = ?', lookup )
print c.fetchone()
| true |
0aeaa34a11aef996450483d8026fe6bdc4da6535 | ivankatliarchuk/pythondatasc | /python/main/datastructures/set/symetricdifference.py | 820 | 4.4375 | 4 | """
TASK
Given 2 sets of integers, M and N, print their difference in ascending order. The term symmetric
difference indicates values that exist in eirhter M or N but do not exist in both.
INPUT
The first line of input contains integer M.
The second line containts M space separeted integers.
The third line contains an integer N
The fourth line contains N space separated integers.
CONSTANTS
-----
OUTPUT
Output the symmetric difference integers an ascending order, one per line
SAMPLE INPUT
4
2 4 5 9
4
2 4 11 12
SAMPLE OUTPUT
5
9
11
12
EXPLANATION
-----
"""
M = int(input())
MM = set([int(x) for x in input().split()])
N = int(input())
NN = set([int(x) for x in input().split()])
difference = MM.symmetric_difference(NN)
data = list(difference)
data.sort()
# sorted(list)
for x in data:
print(x)
| true |
b64c41f1627f672833c1998c0230d300d6790763 | OMR5221/MyPython | /Analysis/Anagram Detection Problem/anagramDetect_Sorting-LogLinear.py | 626 | 4.125 | 4 | # We can also sort each of the strings and then compare their values
# to test if the strings are anagrams
def anagramDetect_Sorting(stringA, stringB):
#Convert both immutable strings to lists
listA = list(stringA)
listB = list(stringB)
# Sort using Pythons function
listA.sort()
listB.sort()
continueSearch = True
index = 0
# Compare the two lists
while index < len(listA) and continueSearch:
if listA[index] != listB[index]:
continueSearch = False
else:
index += 1
return continueSearch
print(anagramDetect_Sorting('abcd', 'dcba')) | true |
79a96ea2bf66f92ab3df995e2a330fd51cbae567 | OMR5221/MyPython | /Trees/BinarySearchTree.py | 2,308 | 4.125 | 4 | # BinarySearchTree: Way to map a key to a value
# Provides efficient searching by
# categorizing values as larger or smaller without
# knowing where the value is precisely placed
# Build Time: O(n)
# Search Time: O(log n)
# BST Methods:
'''
Map(): Create a new, empty map
put(key,val): Add a new key, value pair to the map.
If already in place then replace old values
get(key): Find the key in search tree and return value
del: remove key-value in map using del map[key]
len():Return the number of key-value pairs in the map
in: return True/False if key found in map
'''
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.size
def __iter__(self):
return self.root.__iter__()
class TreeNode:
# Python optional parameters: Use these values if none passed on initialization
def __init__(self,key,val,left=None,right=None,
parent=None):
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
# Is this Node a left or right child to its parent?
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
# Rott Node only node without a parent Node
def isRoot(self):
return not self.parent
# Leaf Nodes: No children Nodes
def isLeaf(self):
return not (self.rightChild or self.leftChild)
def hasAnyChildren(self):
return self.rightChild or self.leftChild
def hasBothChildren(self):
return self.rightChild and self.leftChild
def replaceNodeData(self,key,value,lc,rc):
self.key = key
self.payload = value
self.leftChild = lc
self.rightChild = rc
# Update parent reference of this node's children
if self.hasLeftChild():
self.leftChild.parent = self
if self.hasRightChild():
self.rightChild.parent = self | true |
4143917f483f11fde2e83a52a829d73c62fc2fcd | OMR5221/MyPython | /Data Structures/Deque/palindrome_checker.py | 1,264 | 4.25 | 4 | # Palindrome: Word that is the same forward as it is backwards
# Examples: radar, madam, toot
# We can use a deque to get a string from the rear and from the front
# and compare to see if the strings ae the same
# If they are the same then the word is a palindrome
class Deque:
def __init__(self):
self.items = []
# O(1) Operation
def addFront(self, item):
self.items.append(item)
# O(n) operation to shift other elements to the right
def addRear(self, item):
self.items.insert(0, item)
# O(1) Operation
def removeFront(self):
return self.items.pop()
# O(n) operation to shift other elements to the left
def removeRear(self):
return self.items.pop(0)
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def PalindromeChecker(checkWord):
rearDeque = Deque()
for letter in checkWord:
rearDeque.addRear(letter)
stillEqual = True
while rearDeque.size() > 1 and stillEqual:
if rearDeque.removeRear() == rearDeque.removeFront():
stillEqual = True
else:
stillEqual = False
return stillEqual
print(PalindromeChecker("radar"))
print(PalindromeChecker("cook")) | true |
bb8c26d9f183f83582717e8fadc247b21f3c174d | freddieaviator/my_python_excercises | /ex043/my_throw.py | 982 | 4.28125 | 4 | import math
angle = float(input("Input angle in degrees: "))
velocity = float(input("Input velocity in km/h: "))
throw_height = float(input("Input throw height in meter: "))
angle_radian = math.radians(angle)
throw_velocity = velocity/3.6
horizontal_velocity = throw_velocity * math.cos(angle_radian)
vertical_velocity = throw_velocity * math.sin(angle_radian)
ball_airtime = (vertical_velocity + math.sqrt(vertical_velocity**2 + 2*9.81*throw_height))/9.81
throw_distance = horizontal_velocity * ball_airtime
print(f"The throw angle in radians is: {angle_radian:.2f}")
print(f"The throw velocity in m/s is: {throw_velocity:.2f}")
print(f"The throw velocity in the horizontal direction in m/s is: {horizontal_velocity:.2f}")
print(f"The throw velocity in the vertical direction in m/s is: {vertical_velocity:.2f}")
print(f"The ball airtime is: {ball_airtime:.2f}")
print(f"The throw distance is: {throw_distance:.2f}")
#f) a little bit less than 45 degrees for the longest throw. | true |
aad041babf64d755db4dad331ef0f7446a1f7527 | s-ruby/pod5_repo | /gary_brown_folder/temperture.py | 710 | 4.15625 | 4 | '''----Primitive Data Types Challenge 1: Converting temperatures----'''
# 1) coverting 100deg fahrenheit and celsius
# The resulting temperature us an integer not a float..how i know is because floats have decimal points
celsius_100 = (100-32)*5/9
print(celsius_100)
# 2)coverting 0deg fahrenheit and celsius
celsius_0 = (0-32)*5/9
print(celsius_0)
# 3) coverting 34.2deg fahrenheit and celsius
# making a statement without saving any variables
print((34.2-32)*5/9)
# 4) Convert a temperature of 5deg celsius to fahrenheit?
fahrenheit_5 = (9*5)/5+32
print(fahrenheit_5)
# 5) Going to see if 30.2deg celsius or 85.1deg fahrenheit is hotter
whichIsHotterCelsius = (9*30.2)/5+32
print(whichIsHotterCelsius) | true |
8407a85c075e4a560de9a9fbc2f637c79f813c1e | scottbing/SB_5410_Hwk111 | /Hwk111/python_types/venv/SB_5410_Hwk4.2.py | 2,605 | 4.15625 | 4 | import random
# finds shortest path between 2 nodes of a graph using BFS
def bfs_shortest_path(graph: dict, start: str, goal: str):
# keep track of explored nodes
explored = []
# keep track of all the paths to be checked
queue = [[start]]
# return path if start is goal
if start == goal:
# return "That was easy! Start = goal"
return [start]
# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
if node not in explored:
neighbours = graph[node]
# go through all neighbour nodes, construct a new path and
# push it into the queue
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
# return path if neighbour is goal
if neighbour == goal:
return new_path
# mark node as explored
explored.append(node)
# in case there's no path between the 2 nodes
return "A path doesn't exist "
# end def bfs_shortest_path(graph, start, goal):
def main():
graph = {"Omaha" : ["Dallas", "Houston", "Chicago"],
"Louisville" : ["Dallas", "Houston", "Baltimore", "Chicago"],
"Baltimore" : ["Jacksonville", "Louisville", "Houston", "Dallas", "Portland", "Chicago"],
"Portland" : ["Baltimore"],
"Jacksonville" : ["Dallas", "Houston", "Baltimore", "Chicago"],
"Belize City" : [],
"Dallas" : ["Houston", "Baltimore", "Jacksonville", "Louisville", "Chicago", "Omaha"],
"Houston" : ["Dallas" , "Baltimore", "Jacksonville", "Louisville", "Chicago", "Omaha"],
"Chicago" : ["Dallas", "Baltimore", "Jacksonville", "Louisville", "Omaha", "Houston"]
}
path=bfs_shortest_path(graph, 'Omaha', 'Louisville')
print("From Omaha to Louisville: " + str(path))
path1 = bfs_shortest_path(graph, 'Baltimore', 'Jacksonville')
#print("From Baltimore to Jacksonville: " + str(path1))
path2 = bfs_shortest_path(graph, 'Jacksonville', 'Portland')
print("From Baltimore to Jacksonville: " + str(path1) + " to Portland, Maine: " + str(path2))
path = bfs_shortest_path(graph, 'Belize City', 'Portland')
print("From Belize City to Portland, Maine: " + str(path))
# end def main():
if __name__ == "__main__":
main()
| true |
db8e97cdc0ae8faa35700bfb83502a1d8b0c4712 | Catarina607/Python-Lessons | /new_salary.py | 464 | 4.21875 | 4 |
print('----------------------------------')
print(' N E W S A L A R Y ')
print('----------------------------------')
salary = float(input('write the actual salary of the stuff: '))
n_salary = (26*salary)/100
new_salary = salary + n_salary
print(new_salary, 'is the actual salary')
print('the old salary is ', salary)
print(f'the new salary with + 26% is {new_salary}')
print(f'so the equation is like {salary} + 26% = {new_salary}')
| true |
e1c6c077d75f28f7e5a93cfbafce19b01586a26d | michaelvincerra/pdx_codex | /wk1/dice.py | 419 | 4.6875 | 5 | """
Program should ask the user for the number of dice they want to roll
as well as the number of sides per die.
1. Open Atom
1. Create a new file and save it as `dice.py`
1. Follow along with your instructor
"""
import random
dice = input('How many dice?')
sides = input('How may sides?')
roll = random.randint(1, 6)
def dice():
for i in range(int(dice)):
print('Rolling dice.')
print('Roll', roll)
| true |
9faf1d8c84bdf3be3c8c47c8dd6d34832f4a2b1e | vmueller71/code-challenges | /question_marks/solution.py | 1,395 | 4.53125 | 5 | """
Write the function question_marks(testString) that accepts a string parameter,
which will contain single digit numbers, letters, and question marks,
and check if there are exactly 3 question marks between every pair of two
numbers that add up to 10.
If so, then your program should return the string true, otherwise it should
return the string false.
If there aren't any two numbers that add up to 10 in the string, then your
program should return false as well.
For example: if str is "arrb6???4xxbl5???eee5" then your program should
return true because there are exactly 3 question marks between 6 and 4, and
3 question marks between 5 and 5 at the end of the string.
Sample Test Cases
Input:"arrb6???4xxbl5???eee5"
Output:"true"
Input:"aa6?9"
Output:"false"
Input:"acc?7??sss?3rr1??????5ff"
Output:"true"
"""
def question_marks(testString):
# Your code goes here
has_3_question_marks = False
qm_found = 0
start_int = None
for c in testString:
if c.isdigit():
if start_int:
if start_int + int(c) == 10:
if qm_found == 3:
has_3_question_marks = True
else:
return False
start_int = int(c)
qm_found = 0
else:
if c == '?':
qm_found += 1
return has_3_question_marks
| true |
844abbd605677d52a785a796f70d3290c9754cd6 | Aishwaryasaid/BasicPython | /dict.py | 901 | 4.53125 | 5 | # Dictionaries are key and value pairs
# key and value can be of any datatype
# Dictionaries are represented in {} brackets
# "key":"value"
# access the dict using dict_name["Key"]
student = {"name":"Jacob", "age":25,"course":["compsci","maths"]}
print(student["course"])
# use get method to inform user if a key doesn't exist in the dictionary
print(student.get("phone","Not Found!"))
# add the dictionary with new key value pair
student["phone"]:["555-000"]
# update as well as add the key value
student.update({'name':'jane', 'age':'18','address':'New Avenue Park,US'})
# delete the key
del student["name"]
print(student)
# In dictionary unlike list, pop takes the key as an argument to delete that specific key-value pair
student.pop("age")
# Access the key of dictionary
print(student.keys())
# Access the value of dictionary
print(student.values())
| true |
cc0bbc28266bb25aa4822ac443fa8d371bb12399 | Akrog/project-euler | /001.py | 1,384 | 4.1875 | 4 | #!/usr/bin/env python
"""Multiples of 3 and 5
Problem 1
Published on 05 October 2001 at 06:00 pm [Server Time]
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
import sys
if (2,7) > sys.version_info or (3,0) <= sys.version_info:
import warnings
warnings.warn("Code intended for Python 2.7.x")
print "\n",__doc__
ceiling = 1000
#----------------
#Trivial solution: O(n)
#----------------
#result = sum([x for x in xrange(ceiling) if (0 == x%3) or (0 == x%5)])
#---------------
#Better solution: O(1)
#---------------
# The idea of this approach is that the sum of the numbers below N multiple of M
# is: M+2M+3M+4M+...+(N/M-1)*M = M * (1+2+3+4+...+(N-1))
# And we know that the addition of 1 to N-1 = (N-1)*N/2
# So we have that the sum of the numbers is: M * (((N-1) * N) / 2)
# For the complete solution we only have to add the sum of multipliers of 3 to
# the sum of multipliers of 5 and take out those of 15 as they were added twice.
def addMults(number, ceiling):
ceil = (ceiling-1)/number
addUpTo = (ceil * (ceil+1)) / 2
return number * addUpTo
result = addMults(3,ceiling) + addMults(5,ceiling) - addMults(15,ceiling)
print "The sum of all the multiples of 3 or 5 below {0} is {1}".format(ceiling,result)
| true |
7d3428fd768e5bf71b26f6e6472cf9efa8c79e8b | khyati-ghatalia/Python | /play_with_strings.py | 387 | 4.15625 | 4 | #This is my second python program
# I am playing around with string operations
#Defing a string variable
string_hello = "This is Khyatis program"
#Printing the string
print("%s" %string_hello)
#Printing the length of the string
print(len(string_hello))
#Finding the first instance of a string in a string
print(string_hello.index("K"))
#Reverse of a string
print(string_hello[::-1]) | true |
962c2ccc73adc8e1a973249d4e92e8286d307bf1 | nihalgaurav/Python | /Python_Assignments/Quiz assignment/Ques4.py | 385 | 4.125 | 4 | # Ques 4. Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
s=raw_input()
d={ "UPPER_CASE" :0, "LOWER_CASE" :0}
for c in s:
if c.isupper():
d[ "UPPER_CASE" ]+=1
elif c.islower():
d[ "LOWER_CASE" ]+=1
else:
pass
print("UPPER CASE: ",d[ "UPPER_CASE" ])
print("LOWER CASE: ",d[ "LOWER_CASE" ]) | true |
b44cd8d204f25444d6b5ae9467ad90e539ace8b3 | nihalgaurav/Python | /Python_Assignments/Assignment_7/Ques1.py | 219 | 4.375 | 4 | # Ques 1. Create a function to calculate the area of a circle by taking radius from user.
r = int(input("Enter the radius of circle: "))
def area():
a = r * r * 3.14
print("\nArea of circle is : ",a)
area() | true |
ef4f49af3cb27908f9721e59222418ee63c99022 | antoshkaplus/CompetitiveProgramming | /ProjectEuler/001-050/23.py | 2,599 | 4.21875 | 4 | """
A number n is called deficient if the sum of its proper divisors
is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
the smallest number that can be written as the sum of two abundant
numbers is 24. By mathematical analysis, it can be shown that all
integers greater than 28123 can be written as the sum of two abundant
numbers. However, this upper limit cannot be reduced any further
by analysis even though it is known that the greatest number that
cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum
of two abundant numbers.
Every integer greater than 20161 can be written as the sum of two abundant numbers.
"""
bound = 20161
# begin finding abundant numbers
from math import sqrt
# returns list of primes in segment [1:n]
def find_primes(n):
primes = []
table = n*[True]
table[0] = False
for i, el in enumerate(table):
if el:
primes.append(i+1)
table[2*i+1:n:i+1] = len(table[2*i+1:n:i+1])*[False]
return primes
# add divisor to set
def add_divisor(res,key,val):
if key in res: res[key]+=val
else: res[key] = val
# add divisors from divs {prime:quantity} dictionary to res
def add_divisors(res,divs):
for key,val in divs.items(): add_divisor(res,key,val)
# returns list dictionary of {prime:quantity}
def find_prime_divisors(bound,primes):
table = [{} for i in range(bound)]
for i in range(bound):
b = int(sqrt(i+1))
div = 0
for p in primes:
if b < p: break
if (i+1)%p == 0:
div = p
break
if div:
add_divisor(table[i],div,1)
if len(table[(i+1)/div-1]) == 0: add_divisor(table[i],(i+1)/div,1)
else: add_divisors(table[i],table[(i+1)/div-1])
return table
primes = find_primes(int(sqrt(bound)))
table = find_prime_divisors(bound,primes)
def sum_of_divisors(divs):
sum = 1
for div,quantity in divs.items():
sum *= (1-div**(quantity+1))/(1-div)
return sum
sums = bound*[0]
for i in range(bound):
sums[i] = sum_of_divisors(table[i])
if table[i] != {}: sums[i] -= i+1
abundants = [i+1 for i in range(bound) if sums[i] > i+1]
# end abundant numbers
print "here"
is_sum_of_two_abundants = bound*[False]
for i,a in enumerate(abundants):
for b in abundants[i:]:
if a+b <= bound:
is_sum_of_two_abundants[a+b-1] = True
else: break
print "here"
print sum([i+1 for i,val in enumerate(is_sum_of_two_abundants) if not val])
| true |
cf1c83c8cabc0620b1cdd1bc8ecf971e0902806f | pgavriluk/python_problems | /reverse_string.py | 406 | 4.21875 | 4 | def reverse(string):
str_list=list(string)
length = len(string)
half = int(length/2)
for i, char in enumerate(str_list):
last_char = str_list[length-1]
str_list[length-1] = char
str_list[i] = last_char
length = length-1
if i >= half-1:
break;
return ''.join(str_list)
print(reverse('Hi, my name is Pavel!'))
| true |
c963de87cbf668a579a6de35ed4873c07b64ee90 | ramsayleung/leetcode | /600/palindromic_substring.py | 1,302 | 4.25 | 4 | '''
source: https://leetcode.com/problems/palindromic-substrings/
author: Ramsay Leung
date: 2020-03-08
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
'''
# time complexity: O(N**2), N is the length of `s`
# space complexity: O(1)
class Solution:
def countSubstrings(self, s: str) -> int:
strLen = len(s)
result = 0
for i in range(strLen):
# when len of palidrome is odd, i means the middle number
result += self.countPalindromic(s, i, i)
# when len of palidrome is event, i means the middle left number, i+1 means the middle right number
result += self.countPalindromic(s, i, i + 1)
return result
def countPalindromic(self, s: str, left: int, right: int) -> int:
result = 0
while (left >= 0 and right < len(s) and s[left] == s[right]):
left -= 1
right += 1
result += 1
return result | true |
350ff920efd20882b4b138110612d4a6ad08b378 | RobertEne1989/python-hackerrank-submissions | /nested_lists_hackerrank.py | 1,312 | 4.40625 | 4 | '''
Given the names and grades for each student in a class of N students, store them in a nested list and
print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and
print each name on a new line.
Example
records = [["chi", 20.0], ["beta", 50.0], ["alpha", 50.0]]
The ordered list of scores is [20.0, 50.0], so the second lowest score is 50.0.
There are two students with that score: ["beta", "alpha"].
Ordered alphabetically, the names are printed as:
alpha
beta
Input Format
The first line contains an integer,N, the number of students.
The 2N subsequent lines describe each student over 2 lines.
- The first line contains a student's name.
- The second line contains their grade.
Constraints
2 <= N <= 5
There will always be one or more students having the second lowest grade.
'''
students = []
students_f = []
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
students.append([score, name])
scores.add(score)
second_lowest = sorted(scores)[1]
for score, name in students:
if score == second_lowest:
students_f.append(name)
for name in sorted(students_f):
print(name)
| true |
a89e546c4a3f3cd6027c3a46e362b23549eee2d0 | RobertEne1989/python-hackerrank-submissions | /validating_phone_numbers_hackerrank.py | 1,136 | 4.4375 | 4 | '''
Let's dive into the interesting topic of regular expressions! You are given some input, and you are required
to check whether they are valid mobile numbers.
A valid mobile number is a ten digit number starting with a 7, 8 or 9.
Concept
A valid mobile number is a ten digit number starting with a 7, 8 or 9.
Regular expressions are a key concept in any programming language. A quick explanation with Python examples
is available here. You could also go through the link below to read more about regular expressions in Python.
https://developers.google.com/edu/python/regular-expressions
Input Format
The first line contains an integer N, the number of inputs.
N lines follow, each containing some string.
Constraints
1 <= N <= 10
2 <= len(Number) <= 15
Output Format
For every string listed, print "YES" if it is a valid mobile number and "NO" if it is not on separate lines.
Do not print the quotes.
'''
N = int(input())
a = ""
for i in range(N):
a = input()
if len(a) == 10 and a[0] in ['7', '8', '9'] and a.isnumeric():
print('YES')
else:
print('NO') | true |
8d3e58e5049ef80e24a22ea00340999334358eb2 | RobertEne1989/python-hackerrank-submissions | /viral_advertising_hackerrank.py | 1,709 | 4.1875 | 4 | '''
HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product,
they advertise it to exactly 5 people on social media.
On the first day, half of those 5 people (i.e.,floor(5/2)=2) like the advertisement and each shares it with 3 of
their friends. At the beginning of the second day, floor(5/2) x 3 = 2 x 3 = 6 people receive the advertisement.
Each day, floor(recipients/2) of the recipients like the advertisement and will share it with 3 friends
on the following day.
Assuming nobody receives the advertisement twice, determine how many people have liked the ad by the end
of a given day, beginning with launch day as day 1.
Example
n = 5
Day Shared Liked Cumulative
1 5 2 2
2 6 3 5
3 9 4 9
4 12 6 15
5 18 9 24
The progression is shown above. The cumulative number of likes on the 5'th day is 24.
Function Description
Complete the viralAdvertising function in the editor below.
viralAdvertising has the following parameter(s):
int n: the day number to report
Returns
int: the cumulative likes at that day
Input Format
A single integer,n, the day number.
Constraints
1 <= n <= 50
'''
import math
import os
import random
import re
import sys
def viralAdvertising(n):
shared=5
cumulative=0
for d in range(1,n+1):
liked=shared//2
shared=liked*3
cumulative=cumulative+liked
return cumulative
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = viralAdvertising(n)
fptr.write(str(result) + '\n')
fptr.close()
| true |
dfaea68c6693f63cce8638bb978077536a7dcecc | medetkhanzhaniya/Python | /w3/set.py | 2,461 | 4.71875 | 5 | """
#CREATE A SET:
thisset={"a","b","c"}
print(thisset)
ONCE A SET CREATED
YOU CANNOT CHANGE ITS ITEMS
BUT YOU CAN ADD NEW ITEMS
#SETS CANNOT HAVE 2 ITEMS WITH SAME VALUE
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
#out:true
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
#add new item to set
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
#add elements from one set to another
#you can also add elements of a list to at set
#REMOVE ITEMS
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
#out:{'apple', 'cherry'}
#REMOVE LAST ITEM
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
#cherry
#{'banana', 'apple'}
#EMPTIES THE SET
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
#out:set()
#DELETE THE SET COMPLETELY
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
#returns a new set with all items from both sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
#out:{1, 2, 3, 'a', 'b', 'c'}
#inserts the items in set2 into set1
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
#union()и update()исключают повторяющиеся элементы.
#ВЫВОДИТ ЭЛЕМЕНТЫ КОТОРЫЕ ЕСТЬ И В СЕТ1 И В СЕТ2
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
#out:{'apple'}
#ДОБАВЛЯЕТ ОБЩИЙ ЭЛЕМЕНТ В НОВЫЙ СЕТ
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
#выводит все элементы кроме общих элементы
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
#out:{'microsoft', 'google', 'cherry', 'banana'}
#добавляет все необщие элементы в новый сет
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
#out:{'google', 'microsoft', 'banana', 'cherry'}
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
""" | true |
b17cb584cf6c78c34f6e1c7b78670fb90a9b58dd | manumuc/python | /rock-paper-scissors-lizard-spock.py | 1,905 | 4.28125 | 4 | <pre>[cc escaped="true" lang="python"]
# source: https://www.unixmen.com/rock-paper-scissors-lizard-spock-python/
#Include 'randrange' function (instead of the whole 'random' module
from random import randrange
# Setup a dictionary data structure (working with pairs efficientlyconverter = ['rock':0,'Spock':1,'paper':2,'lizard':3,'scissors':4]
# retrieve the names (aka key) of the given number (aka value)
def number_to_name(number):
If (number in converter.values()):
Return converter.keys()[number]
else:
print ('Error: There is no "' + str(number) + '" in ' + str(converter.values()) + '\n')
# retrieve the number (aka value) of the given names (aka key)
def name_to_number(name):
If (name in converter.keys()):
Return converter[name]
else:
print ('Error: There is no "' + name + '" in ' + str(converter.keys()) + '\n')
def rpsls(name):
player_number = name_to_number(name)
# converts name to player_number using name_to_number
comp_number = randrange(0,5)
# compute random guess for comp_number using random.randrange()
result = (player_number - comp_number) % 5
# compute difference of player_number and comp_number modulo five
# Announce the opponents to each other
print 'Player chooses ' + name
print 'Computer chooses ' + number_to_name(comp_number)
# Setup the game's rules
win = result == 1 or result == 2
lose = result == 3 or result == 4
# Determine and print the results
if win:
print 'Player wins!\n'
elif lose:
print 'Computer wins!\n'
else:
print 'Player and computer tie!\n'
# Main Program -- Test my code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# Check my Helper Function reliability in case of wrong input
#number_to_name(6)
# Error in case of wrong number
#name_to_number('Rock')
# Error in case of wrong name
[/cc]</pre>
| true |
fb8a10f89fc38052190a480da6eeeacf88d6dd22 | govind-mukundan/playground | /python/class.py | 2,379 | 4.28125 | 4 | # Demo class to illustrate the syntax of a python class
# Illustrates inheritance, getters/setters, private and public properties
class MyParent1:
def __init__(self):
print ("Hello from " + str(self.__class__.__name__))
class MyParent2:
pass
# Inheriting from object is necessary for @property etc to work OK
# This is called "new style" classes
class MyClass(object, MyParent1, MyParent2): # Multiple inheritance is OK
"======== My Doc String ==========="
def __init__(self, param1=None): # __init__ is like a constructor, it is called after creating an object. By convention it's the first method of a class
MyParent1.__init__(self) # Initialize our parent(s), MUST be done explicitly
self.__private_prop1 = "I'm Private" # Declare and initialize our object (private) properties
self.public_prop1 = "I'm Public" # Declare and initialize our object (public) properties
self.__public_prop2__ = "I'm also Public" # Declare and initialize our object (public) properties
## self["name"] = param1 # To use this syntax you need to define the __setitem__() function
# Property1 is exposed using getters and setters. Similarly a "deleter" can also be declared using @prop_name.deleter
@property
def public_prop1(self):
print("Getting value")
return self.__public_prop1
@public_prop1.setter
def public_prop1(self, value):
print("Setting value")
self.__public_prop1 = value + "++setter++"
# Destructor
def __del__(self):
print("Don't delete me!")
# Context manager used along with the WITH keyword
# https://docs.python.org/2/reference/compound_stmts.html#with
# https://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/
if __name__ == "__main__":
o1 = MyClass("Govind")
o2 = MyParent1()
print(o1.public_prop1)
## print(o1.__private_prop1) --> Won't run
print(o1._MyClass__private_prop1) # However this works
# More about introspection -> https://docs.python.org/3/library/inspect.html
print(o1.__dict__) # because the interpreter mangles names prefixed with __name to _class__name
print(o1.__public_prop2__)
# Equivalence of Objects
ox = o1
if ox is o1:
print("ox and o1 point to the same memory location = " + str(id(ox)))
| true |
d3b3a2f39945050d6dd423146c794965069ead21 | jdipietro235/DailyProgramming | /GameOfThrees-239.py | 1,521 | 4.34375 | 4 |
# 2017-05-17
# Task #1
# Challenge #239, published 2015-11-02
# Game of Threes
"""
https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/?utm_content=title&utm_medium=browse&utm_source=reddit&utm_name=dailyprogrammer
Back in middle school, I had a peculiar way of dealing with super boring classes. I would take my handy pocket calculator and play a "Game of Threes". Here's how you play it:
First, you mash in a random large number to start with. Then, repeatedly do the following:
If the number is divisible by 3, divide it by 3.
If it's not, either add 1 or subtract 1 (to make it divisible by 3), then divide it by 3.
The game stops when you reach "1".
While the game was originally a race against myself in order to hone quick math reflexes, it also poses an opportunity for some interesting programming challenges. Today, the challenge is to create a program that "plays" the Game of Threes.
"""
def start():
print("start")
print("this program will take a number\nand will reduce it to 0 by")
print("subtracting and dividing by 3")
kickoff()
def kickoff():
var = int(input("Submit a number greater than 1:\n"))
runner(var)
def runner(var):
if(var == 1):
print("Done!")
kickoff()
elif(var % 3 == 0):
varX = var / 3
print(str(varX) + " = " + str(var) + " / 3")
runner(varX)
else:
varX = var - 1
print(str(varX) + " = " + str(var) + " - 1")
runner(varX)
start()
| true |
330ba20a83c20ecb7df2e616379023f74631ee2c | olutoni/pythonclass | /control_exercises/km_to_miles_control.py | 351 | 4.40625 | 4 | distance_km = input("Enter distance in kilometers: ")
if distance_km.isnumeric():
distance_km = int(distance_km)
if distance_km < 1:
print("enter a positive distance")
else:
distance_miles = distance_km/0.6214
print(f"{distance_km}km is {distance_miles} miles")
else:
print("You have not entered an integer")
| true |
924d7324d970925b0f26804bc135ffd318128745 | olutoni/pythonclass | /recursion_exercise/recursion_prime_check.py | 332 | 4.21875 | 4 | # program to check if a number is a prime number using recursion
number = int(input("enter number: "))
def is_prime(num, i=2):
if num <= 2:
return True if number == 2 else False
if num % i == 0:
return False
if i * i > num:
return True
return is_prime(num, i+1)
print(is_prime(number))
| true |
10c70c24825c0b8ce1e9d6ceb03bd152f3d2d0c1 | slohmes/sp16-wit-python-workshops | /session 3/2d_arrays.py | 1,149 | 4.21875 | 4 | '''
Sarah Lohmeier, 3/7/16
SESSION 3: Graphics and Animation
2D ARRAYS
'''
# helper function
def matrix_print(matrix):
print '['
for i in range(len(matrix)):
line = '['
for j in range(len(matrix[i])):
line = line + str(matrix[i][j]) + ', '
line += '],'
print line
print ']'
# A regular array holds a single line of information:
array = [0, 0, 0, 0,]
# Which is a problem if we want to store a grid.
# We can solve this by storing arrays inside arrays-- essentially creating a matrix:
example_matrix = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
matrix_print(example_matrix)
# We can access an entire row in a matrix:
print example_matrix[0]
example_matrix[0] = [2, 0, 0, 0]
#matrix_print(example_matrix)
# We can also access single elements by specifying what row and column they're in:
example_matrix[1][2] = 4
matrix_print(example_matrix)
# This is the basis for manipulating pixels on a screen.
# With the right GUI (http://www.codeskulptor.org/#poc_2048_gui.py), it's also the basis for 2048!
# http://www.codeskulptor.org/#user34_cHRBjzx8rx_114.py
| true |
8aa48619ba0e0741d001f061041aa944c7ee6d05 | amysimmons/CFG-Python-Spring-2018 | /01/formatting.py | 471 | 4.28125 | 4 | # STRING FORMATTING
age = 22
like = "taylor swift".title()
name = "Amy"
print "My age is {} and I like {}".format(age, like)
print "My age is 22 and I like Taylor Swift"
print "My age is {1} and I like {0}".format(age, like)
print "My age is Taylor Swift and I like 22"
print "My name is {}, my age is {} and I like {}".format(name, age, like)
# # What would we expect?
# print "testing"
# print "xxx {name}, xxx{age}, xxx{like}".format(name=name, age=age, like=like)
| true |
297a5886f75bde1bb4e8d1923401512848dcc53f | abhinashjain/codes | /codechef/Snakproc.py | 2,698 | 4.25 | 4 | #!/usr/bin/python
# coding: utf-8
r=int(raw_input())
for i in xrange(r):
l=int(raw_input())
str=raw_input()
ch=invalid=0
for j in str:
if((j=='T' and ch!=1) or (j=='H' and ch!=0)):
invalid=1
break
if(j=='H' and ch==0):
ch=1
if(j=='T' and ch==1):
ch=0
if(invalid or ch):
print "Invalid\n"
else:
print "Valid\n"
'''
The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for
this he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark a 'H'. The snakes are long, and when he sees the snake
finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with
'.'s.
Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T...HTH....T.", or "...", or "HT", whereas "T...H..H.T", "H..T..H", "H..H..T..T"
would be invalid reports (See explanations at the bottom).
Formally, a snake is represented by a 'H' followed by some (possibly zero) '.'s, and then a 'T'. A valid report is one such that it begins with a (possibly zero length) string of '.
's, and then some (possibly zero) snakes between which there can be some '.'s, and then finally ends with some (possibly zero) '.'s.
Chef had binged on the festival food and had been very drowsy. So his report might be invalid. You need to help him find out if his report is valid or not.
Input
The first line contains a single integer, R, which denotes the number of reports to be checked. The description of each report follows after this.
The first line of each report contains a single integer, L, the length of that report.
The second line of each report contains a string of length L. The string contains only the characters '.', 'H', and 'T'.
Output
For each report, output the string "Valid" or "Invalid" in a new line, depending on whether it was a valid report or not.
Constraints
1 ≤ R ≤ 500
1 ≤ length of each report ≤ 500
Example
Input:
6
18
..H..T...HTH....T.
3
...
10
H..H..T..T
2
HT
11
.T...H..H.T
7
H..T..H
Output:
Valid
Valid
Invalid
Valid
Invalid
Invalid
Explanation
"H..H..T..T" is invalid because the second snake starts before the first snake ends, which is not allowed.
".T...H..H.T" is invalid because it has a 'T' before a 'H'. A tail can come only after its head.
"H..T..H" is invalid because the last 'H' does not have a corresponding 'T'.
'''
| true |
8f97da7c54be77e69733bb92efae07666c0ab421 | Didden91/PythonCourse1 | /Week 13/P4_XMLinPython.py | 1,689 | 4.25 | 4 | #To use XML in Python we have to import a library called ElementTree
import xml.etree.ElementTree as ET #The as ET is a shortcut, very useful, makes calling it a lot simpler
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes" />
</person>'''
tree = ET.fromstring(data) #create a object called tree, put the xml string information from 'data' in there
print('Name:', tree.find('name').text) #in the tree find the tag name, and return the whole text content (.text)
print('Attr:', tree.find('email').get('hide')) #in the tree find the tag email and get (.get) only the data in the attribute 'hide'
#Second example:
import xml.etree.ElementTree as ET
input = '''
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
<user x="29">
<id>1991</id>
<name>Ivo</name>
</user>
</users>
</stuff>'''
stuff = ET.fromstring(input)
lst = stuff.findall('users/user') # Creates a LIST called lst, and puts in there, every item it finds in the path users/user
#In other words, in the users 'directory' return every item 'user' and put in the list
print('User count:', len(lst))
for item in lst:
print(item)
print('Name', item.find('name').text) #in the tree find the tag name, and return the whole text content (.text)
print('Id', item.find('id').text) #in the tree find the tag id, and return the whole text content (.text)
print('Attribute', item.get('x')) #in the tree find the attribute x and get (.get) only the data in the attribute
| true |
69940b6c1626270cf73c0fe36c2819bbba1523bd | Didden91/PythonCourse1 | /Week 11/P5_GreedyMatching.py | 929 | 4.28125 | 4 | #WARNING: GREEDY MATCHING
#Repeat characters like * and + push OUTWARD in BOTH directions (referred to as greedy) to match THE LARGEST POSSIBLE STRING
#This can make your results different to what you want.
#Example:
import re
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print (y)
#So you want to find 'From:', so you say, starts with (^) F (F), followed by any character (.) one or more times (+) upto the colon (:)
#This finds 'From:' but it also finds 'From: Using the :'
#If this occurs, it always chooses the LARGEST ONE to return, so be careful with that.
#You can SUPRESS this behaviour (of course) by using adding another character, the questionmark '?'
import re
x = 'From: Using the : character'
y = re.findall('^F.+?:', x) #Adding the ? to the + means one or more characters, BUT NOT GREEDY
print (y)
#NOT GREEDY just means it prefers the SHORTEST string rather than the largest one
| true |
9c74e24deb16d11cc0194504b4be55ea81bd1115 | Didden91/PythonCourse1 | /Week 6/6_3.py | 645 | 4.125 | 4 | def count(letter, word):
counter = 0
for search in word:
if search == letter:
counter = counter + 1
return counter
letterinput = input("Enter a letter: ")
wordinput = input("Enter a word: ")
wordinput = wordinput.strip('b ')
counter = count(letterinput, wordinput)
print(counter)
lowercasewordinput = wordinput.lower()
if lowercasewordinput < 'banana':
print("Your word:",wordinput,"comes before banana")
elif lowercasewordinput > 'banana':
print("Your word:",wordinput,"comes after banana")
else:
print("Well everything is just bananas")
print("What I actually checked was",lowercasewordinput)
| true |
1b8b5732eeb4b7c9c767c815e5c0f2ec0676a99a | Didden91/PythonCourse1 | /Week 12/P7_HTMLParsing.py | 2,523 | 4.375 | 4 | #So now, what do we do with a webpage once we've retrieved it into our program
# We call this WEB SCRAPING, or WEB SPIDERING
# Not all website are happy to be scraped, quite a few don't want a 'robot' scraping their content
# They can ban you (account or IP) if they detect you scraping, so be careful when playing around with this.
#now onto PARSING HTML. It is difficult! You can search string manually but the internet is FULL of BAD HTML
#Errors everywhere
#FORTUNATELY, there is some software called Beautiful Soup which basically says, 'give me the HTML link and I'll return you the tags'
#I already have Beautful Soup 4 (BS4) installed.
# To call it we need to import it
import urllib.request, urllib.parse, urllib.error # First the same stuff we did earlier:
from bs4 import BeautifulSoup # and then BS4
# Now to write a simple program with BS4. NOTE: Beautiful Soup is a COMPLEX library. I'll do something simple here, but I might need to
# read up on the documentation if I want to use it more in depth.
url = input('Enter - ')
html = urllib.request.urlopen(url).read() #read() here means read the WHOLE thing, which is ok if you know the file is not so large
#This return a BYTES object and places it in HTML. BS4 knows how to deal with BYTES
soup = BeautifulSoup(html, 'html.parser') #Here we call BS4 and say, hey use the stuff in the variable html, and use your html.parser on it,
# place the results in soup
# Retrieve all of the anchor tags
tags = soup('a') #Here we call the soup object we just made (or BS4 made for us), and sort of call it like a function,
#The 'a' instruction says, hey give me the anchor tags in soup, and then place them in 'tags'
#Anchor tags are HYPERLINKS, by the way, this wasn't explained, you're basically extracting a LINK
# from the HTML.
for tag in tags:
print(tag.get('href', None)) #href is the tag used in HTML to indicate a hyperlink, so in the HTML code it is
# <a href="http://www.dr-chuck.com/page2.htm"> Second Page</a>
#That's why we're 'getting' the href part, so it prints the actual URL and nothing else
# Although I'm not sure exactly how that works
| true |
0196fbecdcaae1f917c8d17e505e2d6ca5cb8b4f | Didden91/PythonCourse1 | /Week 14/P4_Inheritance.py | 1,400 | 4.5 | 4 | # When we make a new class - we can reuse an existing class and inherit all the capabilities of an existing class
# and then add our own little bit to make our new class
#
# Another form of store and reuse
#
# Write once - reuse many times
#
# The new class (child) has all the capabilities of the old class (parent) - and then some more
#
# Again, for now this is just about learning TERMINOLOGY!
# I don't have to understand when to use this, why to use this etc. This is just to get a better grasp of the bigger picture
#
# With inheritance there is once again a hierarchical system!
# The original class is called the PARENT
# and the new class derived from it is called the CHILD
# SUBCLASSES are another word for this
#
# example:
class PartyAnimal:
x = 0
name = ""
def __init__(self, nam):
self.name = nam
print(self.name,"constructed")
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
#Now FootballFan is a class which EXTENDS PartyAnimal. It has all the capabilities of PartyAnimal and MORE
#So FootballFan is an amalgamation of all this. It includes everything we see here.
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
self.points = self.points + 7
self.party()
print(self.name,"points",self.points)
s = PartyAnimal("Sally")
j = FootballFan("Jim")
s.party()
j.party()
j.touchdown()
| true |
47e3ee0aa65599b23394a1b494508e0e6e1e753b | d-robert-buckley3/FSND | /Programming_Fundamentals/Use_Classes/turtle_poly.py | 402 | 4.125 | 4 | import turtle
def draw_poly(sides, size):
window = turtle.Screen()
window.bgcolor("white")
myturtle = turtle.Turtle()
myturtle.shape("classic")
myturtle.color("black")
myturtle.speed(2)
for side in range(sides):
myturtle.forward(size)
myturtle.right(360/sides)
window.exitonclick()
if __name__ == "__main__":
draw_poly(3, 80)
| true |
7186b0324e96780924078e1d1e07058c1ddc1545 | SummerLyn/devcamp_2016 | /python/Nov_29_Tue/File_Reader/file_reader.py | 1,482 | 4.3125 | 4 | # This is an example on how to open a file as a read only text document
def open_file():
'''
Input: no input variables
Usage: open and read a text file
Output: return a list of words in the text file
'''
words = []
with open('constitution.html','r') as file:
#text = file.read()
#return text.split(" ")
for line in file:
line = line.rstrip().replace('\\n','\n')
line_words = line.split()
for w in line_words:
words.append(w)
return words
def create_frenquency_dict(word_list):
'''
Input:
Usage: puts the words into a dictionary so it has a
Output: returns how many times a word is used
'''
frenquency = {}
# 1) Loop through word_list
# a) check if word is in the dictionary and add if it isn't
# and increment count by one if it is
for word in word_list:
frenquency[word] = frenquency.get(word , 0) + 1
return frenquency
def get_max_word_in_file(frenquency_dict):
'''
Input: A dictionary of word frenquencies
Usage: Finds the max word user_word
Output: None just print the max used word
'''
frenquency = {}
for word in word_list:
frenquency[word] = frenquency.get(word , 0) + 1
return max(frenquency)
def main():
word_list = open_file()
#print(word_list)
print(create_frenquency_dict(word_list))
print(get_max_word_in_file(frenquency_dict))
main()
| true |
549d05dd07db0861e05d1a748cd34ce3cc5ed303 | SummerLyn/devcamp_2016 | /python/day3/string_problem_day3.py | 395 | 4.1875 | 4 | # Take the first and last letter of the string and replace the middle part of
# the word with the lenght of every other letter.
user_input_fun = input(" Give me a fun word. >>")
#user_input_shorter = input("Enter in a shorter word. >>")
if len(user_input_fun) < 3:
print("Error!")
else:
print(user_input_fun[0] + str(len(user_input_fun)- 2) + user_input_fun[len(user_input_fun)- 1])
| true |
1219597ac11a07ca8bbce48b6f18b61ca058052f | SummerLyn/devcamp_2016 | /python/day7/more_for_loops.py | 495 | 4.15625 | 4 | #use for range loop and then for each loop to print
word_list = ["a","b","c","d","e","f","g"]
# for each loop
for i in word_list:
print(i)
# for loop using range
for i in range(0,len(word_list)):
print(word_list[i])
#get user input
#loop through string and print value
#if value is a vowel break out of loop
user_input = input("Give me a word. >> ")
vowels = ("aeiou")
#can also cast as a list - list("aeiou")
for i in user_input:
if i in vowels:
break
print(i)
| true |
2d3d01facdd8cf1951f31bd1705391b1ccb53b68 | cafeduke/learn | /Python/Advanced/maga/call_on_object.py | 1,009 | 4.28125 | 4 | ##
# The __call__() method of a class is internally invoked when an object is called, just like a function.
#
# obj(param1, param2, param3, ..., paramN)
#
# The parameters are passed to the __call__ method!
#
# Connecting calls
# ----------------
# Like anyother method __call__ can take any number of arguments and return an object of any type.
# If the object returned by __call__, is of a class that has __call__ as well, then the next set of parameters will be passed to this __call__ method and so on.
##
class A:
def __call__(self, x):
return B(x)
class B:
def __init__(self, x):
self.x = x
def __call__(self):
return C()
class C:
pass
##
# Main
# -----------------------------------------------------------------------------
##
def main():
a = A()
b = a('Object arg to create instance of B')
c = b()
print("Type :", type(c))
# Short cut for the same thing above
print("Type :", A()('Arg')())
if __name__ == '__main__':
main()
| true |
fc1d3ba12a5e13e8e002d503e2a5e1f9e16e4736 | RLuckom/python-graph-visualizer | /abstract_graph/Edge.py | 1,026 | 4.15625 | 4 | #!/usr/bin/env python
class Edge(object):
"""Class representing a graph edge"""
def __init__(self, from_vertex, to_vertex, weight=None):
"""Constructor
@type from_vertex: object
@param from_vertex: conventionally a string; something unambiguously
representing the vertex at which the edge originates
@type to_vertex: object
@param to_vertex: conventionally a string; something unabiguously
representing the vertex at which the edge terminates
@type weight: number
@param weight: weight of the edge, defaults to None.
"""
self.from_vertex = from_vertex
self.to_vertex = to_vertex
self.weight = weight
def __str__(self):
"""printstring
@rtype: str
@return: printstring
"""
return "Edge {0}{1}, weight {2}.".format(self.from_vertex, self.to_vertex, self.weight)
if __name__ == '__main__':
x = Edge('A', 'B', 5)
print x
| true |
7ccb83743060b18258178b414afdd1ba418acd3c | lyndsiWilliams/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 901 | 4.28125 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# TBC
# Set a base case for recursion to stop (if the word is down to 1 or 0 letters)
if len(word) == 1 or len(word) == 0:
return 0
# Set the counting variable
count = 0
# Check if the word has 't' followed by 'h' in the first two positions
if word[0] == 't' and word[1] == 'h':
# If it does, increase the word count by 1
count += 1
# Recursively run through the input word and check the first two positions
# If the first two positions don't have 't' followed by 'h',
# Take the first letter off and check again
return count + count_th(word[1:])
| true |
64742533ee6dd3747a8e1945a0ae3d74dd00bee7 | rhenderson2/python1-class | /Chapter03/hw_3-5.py | 627 | 4.25 | 4 | # homework assignment section 3-5
guest_list = ["Abraham Lincoln", "President Trump", "C.S.Lewis"]
print(f"Hello {guest_list[0]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[1]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[-1]},\nYou are invited to dinner at my house.")
print(f"\n{guest_list[1]} said he can't make it.\n")
guest_list[1] = "Andrew Wommack"
print(f"Hello {guest_list[0]},\nYou are still invited to dinner at my house.\n")
print(f"Hello {guest_list[1]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[-1]},\nYou are still invited to dinner at my house.") | true |
2f84d347adabaa3c9788c2b550307e366998fc6f | RobertElias/AlgoProblemSet | /Easy/threelargestnum.py | 1,169 | 4.4375 | 4 | #Write a function that takes in an array of at least three integers
# and without sorting the input array, returns a sorted array
# of the three largest integers in the input array.
# The function should return duplicate integers if necessary; for example,
# it should return [10,10,12]for inquiry of [10,5,9,10,12].
#Solution 1
# O(n) time | O(1) space
def findThreeLargestNumbers(array):
# Write your code here.
threeLargest = [None, None, None]
for num in array:
updateLargest(threeLargest, num)
return threeLargest
# method helper function checks
# if the numbers are largets in stored array
def updateLargest(threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
shiftAndUpdate(threeLargest, num, 2)
elif threeLargest[1] is None or num > threeLargest[1]:
shiftAndUpdate(threeLargest, num, 1)
elif threeLargest[0] is None or num > threeLargest[0]:
shiftAndUpdate(threeLargest, num, 0)
# method helper function
def shiftAndUpdate(array, num, idx):
for i in range(idx + 1):
if i == idx:
array[i] = num
else:
arrya[i] = array[i + 1]
pass | true |
060b043e11b67ad11e5ecc8dc2076dacd6efa1cf | WebSofter/lessnor | /python/1. objects and data types/types.py | 695 | 4.21875 | 4 | """
int - integer type
"""
result = 1 + 2
print(result, type(result))
"""
float - float type
"""
result = 1 + 2.0
print(result, type(result))
"""
string - string type
"""
result = '1' * 3
print(result, type(result))
"""
list - list type
"""
result = ['1','hello', 'world', 5, True]
print(result, type(result))
"""
tuple - tuple type
"""
result = ('1','hello', 'world', 5, True)
print(result, type(result))
"""
seat - seat type (all values in seat must by or autoconverting as unical)
"""
result = {'1','hello', 'world', 5, True, 5}
print(result, type(result))
"""
dict- seat type (it simillar as array with custom keys)
"""
result = {'a': 'hello', 'b': 'world'}
print(result, type(result)) | true |
e2f04c145a4836d14f933ae04557dd6598561af2 | blfortier/cs50 | /pset6/cash.py | 1,657 | 4.1875 | 4 | from cs50 import get_float
def main():
# Prompt the user for the amount
# of change owed until a positive
# number is entered
while True:
change = get_float("Change owed: ")
if (change >= 0):
break
# Call the function that will
# print the amount of coins that
# will be given to the user
changeReturned(change)
# A function that will convert the
# amount of change entered into cents
# and will calculate the number of
# coins needed to make change
def changeReturned(change):
# Convert change into cents
cents = round(change * 100)
# Set the counter to 0
count = 0;
# Calculate how many quarters can be used
if cents >= 25:
quarters = cents // 25;
# Keep track of amount of coins
count += quarters
# Keep track of amount of change
cents %= 25
# Calculate how many dimes can be used
if cents >= 10:
dimes = cents // 10
# Keep track of amount of coins and change
count += dimes
# Keep track of amount of change
cents %= 10
# Calculate how many nickels can be used
if cents >= 5:
nickels = cents // 5
# Keep track of amount of coins and change
count += nickels
# Keep track of amount of change
cents %= 5
# Calculate how many pennies can be used
if cents >= 1:
pennies = cents // 1
# Keep track of amount of coins and change
count += pennies
# Keep track of amount of change
cents %= 1
# Print total coins used
print(count)
if __name__ == "__main__":
main() | true |
4164c5ecc2da48210cb32028b01493a06b111873 | amymou/Python- | /masterticket.py | 2,298 | 4.34375 | 4 | SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
# Outpout how many tickets are remaining using the ticket_remaining variable
# Gather the user's name and assign it to a new variable
names = input("Please provide your name: ")
# Prompt the user by name and ask how many tickets they would like
print("Hi {}.".format(names))
tickets_asked = int()
# Create the calculate_price function. It takes number of tickets and returns
# num_tickets*TICKET_PRICE
def calculate_price(number_of_tickets):
return(number_of_tickets*TICKET_PRICE)+SERVICE_CHARGE
# Run this code continuously until we run of tickets
while tickets_remaining-tickets_asked>0:
# Expect a ValueError to happen and handle it appropriately...remember to test it out!
try:
tickets_asked = int(input("How many tickets would you like? "))
#Raise a ValueError if the request is for more tickets than are available
if tickets_asked > tickets_remaining:
raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
#Include the error text in the output
print("Oh no, we ran into an issue {}. Please try again!".format(err))
else:
# Calculate the price (number of tickets multiplied by the price) and assign it to variable
total_price = calculate_price(tickets_asked)
# Output the price to the screen
print("Okay, the total price is ${}".format(total_price))
# Prompt user if they want to proceed. Y/N?
proceed =input("Would you like to proceed? Yes/No ")
# If they want to proceed
if proceed == 'Yes':
# print out to the screen "SOLD!" to confirm purchase
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= tickets_asked
print("There are {} tickets remaining.".format(tickets_remaining))
# Otherwise...
print("Thank you, {}!".format(names))
user_keep_buying =input("Would you like more tickets? Yes/No ")
if user_keep_buying == 'No':
# Thank them by name
print("Thank you for visiting {}!".format(names))
break
# Nofify user that the tickets are sold out
else:
print("There are no more tickets for this event")
| true |
265462e6a06f4b50a87aecb72e05645d2a62d5e1 | danriti/project-euler | /problem019.py | 1,498 | 4.15625 | 4 | """ problem019.py
You are given the following information, but you may prefer to do some research
for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September, April, June and November. All the rest have
thirty-one, Saving February alone, Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century
unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
DAYS_IN_MONTH = {
1: 31, # jan
2: 28, # feb
3: 31, # mar
4: 30, # april
5: 31, # may
6: 30, # june
7: 31, # july
8: 31, # aug
9: 30, # sept
10: 31, # oct
11: 30, # nov
12: 31 # dec
}
DAYS_OF_WEEK = [
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday'
]
def main():
start = 1900
end = 2000
day_offset = 0 # 1 Jan 1900 was a Monday, so start there
any_given_sundays = []
for year in xrange(start, end + 1):
for month, days in DAYS_IN_MONTH.iteritems():
for day in xrange(1, days+1):
index = (day - 1 + day_offset) % 7
if DAYS_OF_WEEK[index] == 'sunday' and day == 1 and \
year >= 1901:
any_given_sundays.append((year, month, day,))
day_offset = index + 1
print len(any_given_sundays)
if __name__ == '__main__':
main()
| true |
ae99ba05dfed268a96cf36014ece74a6dc8ad58c | yash1th/hackerrank | /python/strings/Capitalize!.py | 418 | 4.125 | 4 | def capitalize(string):
return ' '.join([i.capitalize() for i in string.split(' ')])
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string)
# s = input().split(" ") #if i use default .split() it will strip the whitespace otherwise it will only consider single space
# for i in range(len(s)):
# s[i] = s[i].capitalize()
# print(" ".join(s))
| true |
23b10c277a1632f5a41c15ea55f8ca3598cf43c5 | FredericoIsaac/Case-Studies | /Data_Structure_Algorithms/code-exercicies/queue/queue_linked_list.py | 1,696 | 4.28125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
# Attribute to keep track of the first node in the linked list
self.head = None
# Attribute to keep track of the last node in the linked list
self.tail = None
# Attribute to keep track of how many items are in the stack
self.num_elements = 0
def enqueue(self, value):
# Create a new node with the value to introduce
new_node = Node(value)
# Checks is queue is empty
if self.head is None:
# If queue empty point both head and tail to the new node
self.head = new_node
self.tail = self.head
else:
# Add data to the next attribute of the tail (i.e. the end of the queue)
self.tail.next = new_node
# Shift the tail (i.e., the back of the queue)
self.tail = self.tail.next
# Increment number of elements in the queue
self.num_elements += 1
def dequeue(self):
""" Eliminate first element of the queue and return that value """
# Checks if queue empty, if empty nothing to dequeue
if self.is_empty:
return None
# Save value of the element
value = self.head.value
# Shift head over to point to the next node
self.head = self.head.next
# Update number of elements
self.num_elements -= 1
# Return value that eliminate
return value
def size(self):
return self.num_elements
def is_empty(self):
return self.num_elements == 0 | true |
19d88c04da25f392e92c55469f8ebac6cdb5ba1b | frostickflakes/isat252s20_03 | /python/fizzbuzz/fizzbuzz.py | 1,291 | 4.15625 | 4 | """A FizzBuzz program"""
# import necessary supporting libraries or packages
from numbers import Number
def fizz(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 3.
If it is both, return 'Fizz'.
Otherwise, return the input.
"""
return 'Fizz' if isinstance(x, Number) and x % 3 == 0 else x
def buzz(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 5.
If it is both, return 'Buzz'.
Otherwise, return the input.
"""
return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x
def fibu(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 15.
If it is both, return 'FizzBuzz'.
Otherwise, return the input.
"""
return 'FizzBuzz' if isinstance(x, Number) and x % 15 == 0 else x
def play(start, end):
"""
Given a start number and an end number, produce
all of the output expected for a game of FizzBuzz
as an array.
"""
# initialize an empty list (array) to hold our output
output = []
# loop from the start number to the end number
for x in range(start, end + 1):
# append the tranformed input to the output array
output.append(buzz(fizz(fibu(x))))
return output
| true |
c062d016b88b589ffdccaa0175269439778a8ae3 | sahil-athia/python-data-types | /strings.py | 979 | 4.5625 | 5 | # strings can be indexed and sliced, indexing starts at 0
# example: "hello", regular index: 0, 1, 2, 3, 4, reverse index: 0, -4, -3, -2, -1
greeting = "hello"
print "hello \nworld \n", "hello \t world" # n for newline t for tab
print greeting # will say hello
print greeting[1] # will say 'e'
print greeting[-1] # will say '0'
print len(greeting) # length function
# slicing lets us grab a subsection of characters, syntax: [start:stop:step]
# start is the index of where we start
# stop is where we go up to (but not include)
# step is the size of the jump
my_string = "abcdefghijk"
print my_string
print my_string[2:] # from 2 all the way to the end
print my_string[:3] # will give back abc [0:3]
print my_string[3:6] # will give back def
print "setting the step size"
print my_string[::] # from 0 to end with a step size of 1
print my_string[::2] # from 0 to end with a step size of 2
print my_string[::-1] # this can be used to reverse a string since the step size is -1 | true |
5eea12122a9ff7e636d3e6e6d7c81eff21adaa5a | RachelKolk/Intro-Python-I | /src/lists.py | 808 | 4.3125 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print(x)
# Print the length of list x
# YOUR CODE HERE
print(len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
def mult_by_thousand(num):
return num * 1000
multiplied = map(mult_by_thousand, x)
multiplied_list = list(multiplied)
print(multiplied_list) | true |
0f65a069cd882e3aac41649d09c1adbfe901a479 | vskemp/2019-11-function-demo | /list_intro.py | 2,910 | 4.65625 | 5 | # *******How do I define a list?
grocery_list = ["eggs", "milk", "bread"]
# *******How do I get the length of a list?
len(grocery_list)
# ******How do I access a single item in a list?
grocery_list[1]
# 'milk'
grocery_list[0]
# 'eggs'
#Python indexes start at 0
# ******How do I add stuff to a list?
grocery_list.append("beer")
# ['eggs', 'milk', 'bread', 'beer']
grocery_list.append("cat food")
# ['eggs', 'milk', 'bread', 'beer', 'cat food']
# ******How do I access the last item in a list?
grocery_list[-1]
# *******How do I access multiple items in a list?
grocery_list[0:3] # known as a slice (Starts at index[0] and goes up to but not including index[3])
# *******What is "iteration" and how do I do that with a list?
# To iterate a list, use a FOR LOOP
# You need to buy: eggs
# You need to buy: milk
# You need to buy: bread
# ...
for item in grocery_list:
print(f"You need to buy {item}")
# Item is an automatic variable
# *******How do I replace stuff in a list?
grocery_list[1] = "almond milk"
# replaces "milk" with "almond milk"
# *******How do I replace multiple items in a list?
# grocery_list[0:3] = "chocolate"
# grocery_list["c", "h", "o", "c", "o", "l", "a", "t", "e", "beer", "cat food"]
# Don't do that
an_item = "awesome" + an_item
for item in grocery_list:
grocery_list[???] = "awesome " + item
# replaces everything with cheese
index = 0
while index < len(grocery_list):
# print(grocery_list[index])
grocery_list[index] = "cheese"
index += 1
# adds awesome before every list entry
index = 0
while index < len(grocery_list):
# print(grocery_list[index])
grocery_list[index] = "awesome" + grocery_list[index]
index += 1
# ******How do I remove stuff from a list?
grocery_list.pop() #---->gives/removes last item of the list until list is empty \
#H******How to combine lists?
grocery_list = ["eggs", "milk", "bread"]
snacks = ["gummy bears", "pringles", "more beer"]
for snakcs in snacks:
grocery_list.append(snacks)
grocery_list.extend(snacks)
# list can be concatinated!
grocery_list + snacks
new_grocery_list = grocery_list + snacks
#******How do I create a list of lists
chris_dirs = ["Jonathan", "Tedge"]
seans_dirs = ["Evan", "Eric"]
all_dirs = [chris_dir, seans_dir]
all_dirs
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
#******How do I access items in a list... that's inside another list?
# NESTED LISTS
all_dirs = [chris_dir, seans_dir]
all_dirs
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
all_dirs[0]
['Jonathan', 'Tedge']
all_dirs[0][1]
'Tedge'
all_dirs[0][1] = ["Liz", "Tasha"]
all_dirs
[["Jonathan", ["Liz", "Tasha"]] ["Evan", "Eric"]]
all_dirs[0][1][1]
"Tasha"
all_dirs[0][1] = "Tedge"
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
count = 0
for dir_list in all_dirs:
print(dir_list)
["Jonathan", "Tedge"]
["Evan", "Eric"]
for name in dir_list:
print(name)
count += 1
count?
Jonathan
Tedge
Evan
Eric
4 | true |
81e42c23911fce65155e1da44ca35666e507bd6e | helaahma/python | /loops_task.py | 1,296 | 4.125 | 4 | #define an empty list which will hold our dictionary
list_items= []
#While loop, and the condition is True
while True:
#User 1st input
item= input ("Please enter \"done\" when finished or another item below: \n")
# Define a conditional statement to break at "Done" input
if item == "done" or item=="Done":
break
#return to the loop
#User input
price= input ("Please enter the price of the item below: \n")
quant= input ("Please enter quantity of the item below: \n")
#Required by the example
price_items= int(price)*int(quant)
#Add a dictionary to enter multiple variables
dict={}
#Add 1st key
dict["item"]=item
#Add 2nd key
dict["price"]=price
#Add 3rd key
dict["quantity"]=quant
#And the last key
dict["all"]=price_items
#Append our dictionary to the list_items
list_items.append(dict)
#Define new variable that shall be used later to calculate the sum of "all" key in the dictionary
total = 0
#Use for loop as required in the task but also to iterate over the values where i is now the dict
for i in list_items:
#print reciept
print (i["quantity"], i["item"], i["price"], i["all"])
#Now we use total which will iterate over "all" key and add the values up (Note to self: I used i)
total += i["all"]
#print the total price
print ("total: ", total, " K.D")
| true |
b55dfd6fe18a15149ff4befa6199165655c60011 | mspang/sprockets | /stl/levenshtein.py | 1,949 | 4.40625 | 4 | """Module for calculating the Levenshtein distance bewtween two strings."""
def closest_candidate(target, candidates):
"""Returns the candidate that most closely matches |target|."""
return min(candidates, key=lambda candidate: distance(target, candidate))
def distance(a, b):
"""Returns the case-insensitive Levenshtein edit distance between |a| and |b|.
The Levenshtein distance is a metric for measuring the difference between
two strings. If |a| == |b|, the distance is 0. It is roughly the number
of insertions, deletions, and substitutions needed to convert |a| -> |b|.
This distance is at most the length of the longer string.
This distance is 0 iff the strings are equal.
Examples:
levenshtein_distance("cow", "bow") == 1
levenshtein_distance("cow", "bowl") == 2
levenshtein_distance("cow", "blrp") == 4
See https://en.wikipedia.org/wiki/Levenshtein_distance for more background.
Args:
a: A string
b: A string
Returns:
The Levenshtein distance between the inputs.
"""
a = a.lower()
b = b.lower()
if len(a) == 0:
return len(b)
if len(b) == 0:
return len(a)
# Create 2D array[len(a)+1][len(b)+1]
# | 0 b1 b2 b3 .. bN
# ---+-------------------
# 0 | 0 1 2 3 .. N
# a1 | 1 0 0 0 .. 0
# a2 | 2 0 0 0 .. 0
# a3 | 3 0 0 0 .. 0
# .. | . . . . .. .
# aM | M 0 0 0 .. 0
dist = [[0 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
for i in range(len(a)+1):
dist[i][0] = i
for j in range(len(b)+1):
dist[0][j] = j
# Build up the dist[][] table dynamically. At the end, the Levenshtein
# distance between |a| and |b| will be in the bottom right cell.
for i in range(1, len(a)+1):
for j in range(1, len(b)+1):
cost = 0 if a[i-1] == b[j-1] else 1
dist[i][j] = min(dist[i-1][j] + 1,
dist[i][j-1] + 1,
dist[i-1][j-1] + cost)
return dist[-1][-1]
| true |
e2064d9111bc5b9d73aeaf79eb3b248c25552b54 | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qa.py | 506 | 4.3125 | 4 | """This module received three numbers from the user, computes their sum and prints the sum to the screen"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("First number: "))
y = float(input("Second number: "))
z = float(input("Third number: "))
except ValueError:
# If cast fails print error message and exit with error code
print("Invalid input.")
exit(1)
# If nothing went wrong with input casting, sum and print
print("Sum is", x + y + z)
| true |
1ea7e928f266a8d63ec7735333632901954a1dea | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qf.py | 763 | 4.15625 | 4 | """This module receives a single number input from the user for a GPA and prints a message depending on the value"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("GPA: "))
except ValueError:
# If cast fails print error message and exit with error code
print("Invalid input")
exit(1)
"""Print the proper message depending on the range, if value isn't in the range print an error message
and exit with error code"""
if 0 <= x < 1:
print("No comment!")
elif 1 <= x < 2:
print("Hmm!")
elif 2 <= x < 3:
print("Good!")
elif 3 <= x <= 4:
print("Superb!")
else:
print("Invalid input, must be in range [0,4]")
# The exit is needles, it is merely here to indicate an error code
exit(1)
| true |
179d5d73c249b74a4056eaf0a6c1f9de6f4fc892 | AmandaMoen/StartingOutWPython-Chapter5 | /bug_collector.py | 1,141 | 4.1875 | 4 | # June 8th, 2010
# CS110
# Amanda L. Moen
# 1. Bug Collector
# A bug collector collects bugs every day for seven days. Write
# a program that keeps a running total of the number of bugs
# collected during the seven days. The loop should ask for the
# number of bugs collected for each day, and when the loop is
# finished, the program should display the total number of bugs
# collected.
def main():
# Call an intro function so the user doesn't have to
# press Enter to start the function.
intro()
# Initialize an accumulator variable.
bugs_collected = 0.0
# Ask the user to enter the number of bugs collected for each
# of the 7 days.
for counter in range(7):
daily = input('Enter the number of bugs collected daily: ')
bugs_collected = bugs_collected + daily
# Display the total bugs collected.
print 'The total number of bugs collected over 7 days was', bugs_collected
def intro():
# Explain what we are doing.
print 'This program calculates the sum of'
print 'the number of bugs collected over'
print 'a 7 day period.'
# Call the main function.
main()
| true |
2ebb6abe09a57a9ba5b4acdd4cf91b1a59b52545 | mkioga/17_python_Binary | /17_Binary.py | 637 | 4.375 | 4 |
# ==================
# 17_Binary.py
# ==================
# How to display binary in python
# Note that {0:>2} is for spacing. >2 means two spaces
# and on 0:>08b means 8 spaces with zeros filling the left side
# Note that adding b means to display in binary
for i in range(17):
print("{0:>2} in binary is {0:>08b}".format(i))
print()
# Here we have (0:>02} which has 0 filling the left side.
for i in range(17):
print("{0:>02} in binary is {0:>08b}".format(i))
# This is experimenting with high numbers to see how they display in binary
print()
for i in range(1000):
print("{0:>3} in binary is {0:>016b}".format(i))
| true |
32bdfbc9a0a8a1c6dac00220d7cd5a5f6932062b | zenithude/Python-Leetcode | /h-index.py | 1,936 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index
h if h of his/her N papers have at least h citations each, and the other N −
h papers have no more than h citations each."
Example:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each
of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the
remaining two with no more than 3 citations each, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken
as the h-index.
"""
from bisect import bisect_right
class Solution_1:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
citations.sort(reverse=True)
ans = 0
for i, c in enumerate(citations, 1):
if c >= i: ans = i
return ans
class Solution_2:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
return next(
(len(citations) - i for i, x in enumerate(sorted(citations)) if
len(citations) - i <= x), 0)
class Solution:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
return bisect_right([i - c for i, c in
enumerate(sorted(citations, reverse=True), 1)], 0)
citations = [3, 0, 6, 1, 5]
obj_1 = Solution_1()
obj_2 = Solution_2()
obj = Solution()
print(obj_1.hIndex(citations))
print(obj_2.hIndex(citations))
print(obj.hIndex(citations))
| true |
0cbefae29e6cf212a779c7da538661df56063fa5 | zenithude/Python-Leetcode | /removeAllGivenElement.py | 2,245 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenithude
Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
"""
class ListNode(object):
"""List of Nodes Linked."""
def __init__(self, val=0, nextval=None):
"""
Initialize the list.
Parameters
----------
val : TYPE int
nextval : Type int
Returns
-------
None.
"""
self.val = val
self.nextval = None
def constructListNode(arr):
"""
Construct ListNode with a List
:param arr: List()
:return: ListNode()
"""
NewListNode = ListNode(arr[0])
arr.pop(0)
if len(arr) > 0:
NewListNode.nextval = constructListNode(arr)
return NewListNode
def headLength(head):
"""
Function return number of Nodes in ListNode().
:param head: ListNode()
:return: int
"""
numberNode = 0
while head is not None:
head = head.next
numberNode += 1
return numberNode
def listPrint(node):
print("None", end='<-->')
while node is not None:
print(node.val, end='<-->')
last = node
node = node.nextval
print(node)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head, val):
"""
:param head : ListNode
:param val: int
:return : ListNode
"""
if not head:
return
factice = ListNode(float('-inf'))
factice.nextval = head
previous, current = factice, factice.nextval
while current:
if current.val == val:
previous.nextval = current.nextval
else:
previous = current
current = current.nextval
return factice.nextval
arr = [1, 2, 6, 3, 4, 5, 6]
head = constructListNode(arr)
obj = Solution()
listPrint(obj.removeElements(head, 6)) | true |
661959a1cace03d1be96a892ed6d8115c734a40f | zenithude/Python-Leetcode | /reorderList.py | 2,071 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be
changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
"""
class ListNode():
"""List of Nodes."""
def __init__(self, x):
"""
Initialize the list.
Parameters
----------
x : TYPE int
Returns
-------
None.
"""
self.val = x
self.next = None
def __str__(self):
"""Print the List."""
return '<ListNode {}>'.format(self.val)
def listPrint(head):
"""
Print the ListNode passed in params.
:param head : type ListNode
:return: nothing just print the Listnode
"""
while head:
print(head, end='->')
head = head.next
print(head)
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# step 1: find middle
if not head:
return []
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# step 2: reverse second half
prev, curr = None, slow.next
while curr:
after = curr.next
curr.next = prev
prev = curr
curr = after
slow.next = None
# step 3: merge lists
head1, head2 = head, prev
while head2:
after = head1.next
head1.next = head2
head1 = head2
head2 = after
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
listPrint(s.reorderList(a)) | true |
463fa32db7284ea1088d0193b26aa64f220da509 | prasant73/python | /programs/shapes/higher_order_functions.py | 2,063 | 4.4375 | 4 | '''4. Map, Filter and Reduce
These are three functions which facilitate a functional approach to programming. We will discuss them one by one and understand their use cases.
4.1. Map
Map applies a function to all the items in an input_list. Here is the blueprint:
Blueprint
map(function_to_apply, list_of_inputs)
Most of the times we want to pass all the list elements to a function one-by-one and then collect the output. For instance:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map allows us to implement this in a much simpler and nicer way. Here you go:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Most of the times we use lambdas with map so I did the same. Instead of a list of inputs we can even have a list of functions!
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
4.2. Filter
As the name suggests, filter creates a list of elements for which a function returns true. Here is a short and concise example:
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
The filter resembles a for loop but it is a builtin function and faster.
Note: If map & filter do not appear beautiful to you then you can read about list/dict/tuple comprehensions.
4.3. Reduce
Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. For example, if you wanted to compute the product of a list of integers.
So the normal way you might go about doing this task in python is using a basic for loop:
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
# product = 24
Now let’s try it with reduce:
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24''' | true |
c1cd86da9cab336059a84e6401ac97232302036c | TurbidRobin/Python | /30Days/Day 10/open_file.py | 323 | 4.15625 | 4 | #fname = "hello-world.txt"
#file_object = open(fname, "w")
#file_object.write("Hello World")
#file_object.close()
# creates a .txt file that has hello world in it
#with open(fname, "w") as file_object:
# file_object.write("Hello World Again")
fname = 'hello-world.txt'
with open (fname, 'r') as f:
print(f.read()) | true |
32851ca38461cdc284e106dc600c104ac3b025d7 | bioright/Digital-Coin-Flip | /coin_flip.py | 1,231 | 4.25 | 4 | # This is a digital coin flip of Heads or Tails
import random, sys #Importing the random and sys modules that we will use
random_number = random.randint(1, 2)
choice = "" # stores user's input
result = "" # stores random output
def play_game(): # the main function that calls other function
instructions()
decision()
flip_result()
quit()
def decision(): # getting player input
global choice # calling a global variable in a local scope
choice = input(" Heads or Tails? ")
if choice == "1":
choice = "Heads"
else:
choice = "Tails"
def flip_result(): # getting random output
global result
if random_number == 1:
result = "Heads"
else:
result = "Tails"
if result == choice: # comparing random output and player input
print(result, ", You win!")
else:
print(result, ", You lose!")
def instructions():
print("The system will generate a random number, either '1- for Heads' or '2- for Tails'.\n Choose '1' or '2' for this digital coin flip")
def quit():
sys.exit("The game has ended! Restart to flip the coin again")
play_game()
| true |
83aeea4934c224bb313c05e567c398a5e00da6d6 | monicaihli/python_course | /misc/booleans_numbers_fractions.py | 1,091 | 4.21875 | 4 | # **********************************************************************************************************************
#
# File: booleans_numbers_fractions.py
#
# Author: Monica Ihli
#
# Date: Feb 03, 2020
#
# Description: Numbers and fractions in Python. Best results: use debugging to go through each line
# **********************************************************************************************************************
# Combine comparison operations that return boolean objects with boolean logic: and or
print("Boolean Logic: OR") # Either value has to pass the test to return True
print(True or True) # Returns True
print(True or False) # Returns True
print(False or True) # Returns True
print(False or False) # Returns False
print("Boolean Logic: AND") # Both values must pass the test to return True
print(True and True) # Returns True
print(True and False) # Returns False
print(False and True) # Returns False
print(False and False) # Returns False
print('/n/n')
print('Fractions')
from fractions import Fraction
print(Fraction(1/2)) | true |
7dda75c52ab735158c9daa38fb3661284c19c98c | dillon-DL/PolynomialReggression | /PolynomialRegression/poly.py | 1,592 | 4.1875 | 4 | # Firstly the program will be using polynomial regression to pefrom prediction based on the inputs
# The inputs or variables we will be anlysing to study is the relation between the price and the size of the pizza
# Lastly the data will displayed via a graph which indicates the "non-linear" relationship between the 2 features; in a user friednly manner
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
x_train = [[8], [18], [13], [17], [30]]
y_train = [[13], [22], [28], [30], [40]]
x_test = [[8], [18], [11], [16]]
y_test = [[13], [22], [15], [18]]
regresor = LinearRegression()
regresor.fit(x_train, y_train)
xx = np.linspace(0, 26, 100)
yy = regresor.predict(xx.reshape(xx.shape[0], 1))
plt.plot(xx, yy)
quadratic_featurizer = PolynomialFeatures(degree=2)
x_train_quadratic = quadratic_featurizer.fit_transform(x_train)
x_test_quadratic = quadratic_featurizer.transform(x_test)
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y_train)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))
plt.plot(xx, regressor_quadratic.predict(xx_quadratic), c='y', linestyle='--')
plt.title('Pizza price regressed on the diameter')
plt.xlabel('Diameter in Cm')
plt.ylabel('Price in Rands')
plt.axis([0, 30, 0, 30])
plt.grid(True)
plt.scatter(x_train, y_train)
plt.show()
print (x_train)
print ()
print (x_train_quadratic)
print ()
print (x_test)
print ()
print (x_test_quadratic)
| true |
a28381495e08d45a75e21c512d06f688b9ab5dff | iwantroca/PythonNotes | /zeta.py | 2,427 | 4.46875 | 4 | ########LISTS########
# assigning the list
courses = ['History', 'Math', 'Physics', 'CompSci']
# finding length of list
print(len(courses))
# using index in list
print(courses[0])
# adding item to list
courses.append('Art')
print(courses)
# using insert to add in specific location
courses.insert(2, 'Art')
print(courses)
# using extend method to add lists
courses_2 = ['Humanities', 'Education']
courses.extend(courses_2)
print(courses)
# removing items from the list
courses.remove('Art')
print(courses)
# using pop to remove item from the list
popped = courses.pop()
print(popped)
print(courses)
# to find the index in the list
print(courses.index('Physics'))
# using del to remove specified item
del courses[2] # should delete physics
print(courses)
# to check if item is in list
print('Physics' in courses)
# to reverse the list
courses.reverse()
print(courses)
# to sort the list
sorted_courses = sorted(courses)
print(sorted_courses)
# list operations on the number
nums = [1, 5, 2, 4, 3]
sorted_nums = sorted(nums)
print(sorted_nums)
print(sum(nums))
print(min(nums))
print("")
# using loop in list
for index,item in enumerate(courses, start=1):
print(index, item)
# joining the courses with symbol
courses_str = ' - '.join(courses)
print(courses_str)
# spliting the list
courses_split = courses_str.split(' - ')
print(courses_split)
# tuples are immutable; can't be modified
tuple_1 = ('Art', 'Math', 'Physics')
print(tuple_1[2])
# tuple don't support list assignment
# tuple_1[0] = 'Chemistry'
####
######SETS######
####
# to make a empty set
# empty_set = set()
# in sets, order of the items do not matter
cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math'}
art_courses = {'History', 'Math', 'Art', 'Design', 'Math'}
print('Math' in cs_courses)
print(cs_courses.intersection(art_courses))
#####
######Dictionaries######
#####
student = {1: 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student[1])
# adding new key to the dictionary
student['phone'] = '555-5555'
# using get helps us to change the error for defualt
print(student.get('phone', 'Not exist'))
print(student)
# updating student dict
student.update({1: 'Jane', 'age': 26})
print(student)
print(student.items())
# deleting key in dictionaries
# del student[1]
student.pop(1)
print(student)
# looping through dictionaries
for key, value in student.items():
print(key, value) | true |
f461e4886e514f6497cbe1f87d648efe3a7cf1cf | RaimbekNusi/Prime-number | /Project_prime.py | 1,146 | 4.25 | 4 | def is_prime(N):
"""
Determines whether a given positive integer is prime or not
input: N, any positive integer.
returns: True if N is prime, False otherwise.
"""
# special cases:
if N == 1:
return False
# the biggest divisor we're going to try
divisor = N // 2
while divisor > 1:
if N % divisor == 0:
# we found a number that is a factor of N
return False
divisor = divisor - 1
return True
out = {}
def numbers(x):
"""
Opens a numbers.txt file, reads all the numbers in the file,
calls a is_prime function, caches the numbers (keys) and values True or False to dictionary "out"
:param x: is a txt file, in this case numbers.txt
returns: The dictionary "out" containing numbers from the file and values True or False,
depending if the number is prime or non-prime respectively
"""
f = open(x,"r")
for line in f:
out[int(line)] = is_prime(int(line))
f.close()
return out
x = input("Write the name of the .txt file")
print(numbers(x))
| true |
0188c28e0485e2a0ff7efe15b89e7c5286723de9 | rajesh95cs/wordgame | /wordgameplayer.py | 2,158 | 4.15625 | 4 | class Player(object):
"""
General class describing a player.
Stores the player's ID number, hand, and score.
"""
def __init__(self, idNum, hand):
"""
Initialize a player instance.
idNum: integer: 1 for player 1, 2 for player 2. Used in informational
displays in the GUI.
hand: An object of type Hand.
postcondition: This player object is initialized
"""
self.points = 0.
self.idNum = idNum
self.hand = hand
def getHand(self):
"""
Return this player's hand.
returns: the Hand object associated with this player.
"""
return self.hand
# TODO
def addPoints(self, points):
"""
Add points to this player's total score.
points: the number of points to add to this player's score
postcondition: this player's total score is increased by points
"""
self.points += points
# TODO
def getPoints(self):
"""
Return this player's total score.
returns: A float specifying this player's score
"""
return self.points
# TODO
def getIdNum(self):
"""
Return this player's ID number (either 1 for player 1 or
2 for player 2).
returns: An integer specifying this player's ID number.
"""
return self.idNum
# TODO
def __cmp__(self, other):
"""
Compare players by their scores.
returns: 1 if this player's score is greater than other player's score,
-1 if this player's score is less than other player's score, and 0 if
they're equal.
"""
if self.points > other.getPoints() :
return 1
if self.points = other.getpoints() :
return 0
if self.points < other.getpoints() :
return -1
# TODO
def __str__(self):
"""
Represent this player as a string
returns: a string representation of this player
"""
return 'Player %d\n\nScore: %.2f\n' % \
(self.getIdNum(), self.getPoints())
| true |
1d76bf2cead6e296b7e7c37893a59a66cede9957 | Samk208/Udacity-Data-Analyst-Python | /Lesson_4_files_modules/flying_circus.py | 1,209 | 4.21875 | 4 | # You're going to create a list of the actors who appeared in the television programme Monty Python's Flying Circus.
# Write a function called create_cast_list that takes a filename as input and returns a list of actors' names. It
# will be run on the file flying_circus_cast.txt (this information was collected from imdb.com). Each line of that
# file consists of an actor's name, a comma, and then some (messy) information about roles they played in the
# programme. You'll need to extract only the name and add it to a list. You might use the .split() method to process
# each line.
import re
def create_cast_list(filename):
cast_list = []
# use with to open the file filename
# use the for loop syntax to process each line
# and add the actor name to cast_list
with open(filename) as f:
# p = re.compile('^[a-z ]+', re.IGNORECASE) tried regex for fun, but line split is much easier
for line in f:
# matched = p.match(line)
# if matched:
line_data = line.split(',')
cast_list.append(line_data[0])
# cast_list.append(matched.group())
return cast_list
print(create_cast_list('flying_circus_cast.txt'))
| true |
87a54bf9f8875f2f578c0ed361b8adb924ff866c | Samk208/Udacity-Data-Analyst-Python | /Lesson_3_data_structures_loops/flying_circus_records.py | 1,018 | 4.1875 | 4 | # A regular flying circus happens twice or three times a month. For each month, information about the amount of money
# taken at each event is saved in a list, so that the amounts appear in the order in which they happened. The
# months' data is all collected in a dictionary called monthly_takings.
# For this quiz, write a function total_takings that calculates the sum of takings from every circus in the year.
# Here's a sample input for this function:
monthly_takings = {'January': [54, 63], 'February': [64, 60], 'March': [63, 49],
'April': [57, 42], 'May': [55, 37], 'June': [34, 32],
'July': [69, 41, 32], 'August': [40, 61, 40], 'September': [51, 62],
'October': [34, 58, 45], 'November': [67, 44], 'December': [41, 58]}
def total_takings(monthly_takings):
pass # TODO: Implement this function
total = []
for i in monthly_takings:
total.append(sum(monthly_takings[i]))
return sum(total)
print(total_takings(monthly_takings)) | true |
cb2a90a4869b762145f3e48160d7448ad0fda3a4 | CODE-Lab-IASTATE/MDO_course | /03_programming_with_numpy/arrays.py | 889 | 4.40625 | 4 | #Numpy tutorials
#Arrays
#Import the numpy library
import numpy as np
a = np.array([1, 2, 3])
#print the values of 'a'
print(a)
#returns the type of 'a'
print(type(a))
#returns the shape of 'a'
print(a.shape)
#prints the value of 'a'
print(a[0], a[1], a[2])
# Change an element of the array
a[0] = 5
#print the values of 'a'
print(a)
#reshape a
a = a.reshape(-1,1)
#returns the shape of 'a'
print(a.shape)
#Note (3,) means it is a 1d matrix
#(3,1) means it is a 2d matrix
#In python this matters
a = a.reshape(1,-1)
#returns the shape of 'a'
print(a.shape)
#.reshape(1,-1) refers to the following
#the first index refers to number of columns, in this case 1
#second index is number of rows, -1 tells numpy to fiugre the length out
#Array of zeros
b = np.zeros(3)
print(b)
#Array of ones
c = np.ones(3)
print(c) | true |
cb3c16cae8164f495dd73644ec16ea267f8c0814 | NickosLeondaridisMena/nleondar | /shortest.py | 1,560 | 4.375 | 4 |
# Create a program, shortest.py, that has a function
# that takes in a string argument and prints a sentence
# indicating the shortest word in that string.
# If there is more than one word print only the first.
# Your print statement should read:
# “The shortest word is x”
# Where x = the shortest word.
# The word should be all uppercase.
def print_shortest_word(input_sentence):
# we need to split the sentence into separate words
temp = input_sentence.split()
# I'm going to initialize a very, very large number
initial_counter = 10000000000000000000000000000000
# returned word is just a placeholder. our answer will end up here
returned_word = ""
# for every word we come across in this sentence
for word in temp:
# if the length of the word is less than our current huge number
# note by making it strictly LESS, it will return the first occuring shortest
# letter. If I made it less than or equal to, then it wouldn't work as asked
if len(word) < initial_counter:
# you need to replace that large number with the shortest word
# length so far
initial_counter = len(word)
# and update our placeholder variable with our new shortest word
returned_word = word
# they asked to return this sentece with it capitalized
return print("The shortest word is " + returned_word.upper())
# see how I added another 1 letter word afterwards and our output still works?
print_shortest_word("The shortest word is x P")
| true |
7e13a6736cdae035792dec2400a1ec76e63289ce | SebasJ4679/CTI-110 | /P5T1_KilometerConverter_SebastianJohnson.py | 670 | 4.625 | 5 | # Todday i will create a program that converts kilometers to miles
# 10/27/19
# CTI-110 P5T1_KilometerConverter
# Sebastian Johnson
#
#Pseudocode
#1. Prompt the user to enter a distance in kilometers
#2. display the formula so the user knows what calculation is about to occur
#3 write a function that carries out the formula
#4. display the end result to the user
def main():
kilometers= float(input('Enter the kilometers you would like converted to miles: '))
print('The formula being used is miles = kilometers * 0.6214.')
miles = (kilometers) * 0.6214
print('The conversion of', kilometers,'kilometers','to miles is', miles)
main()
| true |
d0de9f4a94d395499f87c7c304a70cc4e6055de2 | AkshatTodi/Machine-Learning-Algorithms | /Supervised Learning/Regression/Simple Linear Regression/simple_linear_regression.py | 1,693 | 4.46875 | 4 | # Simple Linear Regression
# Formula
# y = b0 + b1*X1
# y -> dependent variable
# X1 -> independent variable
# b0 -> Constent
# b1 -> Coefficient
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
# When we build a machine learning model and specially regression model thgen we have to make our matix of feature to be considered all the
# time as a matrix means X should be in the form of (i,j) not as a vector (i,).
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
# Training the Simple Linear Regression model on the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
slr = regressor.fit(X_train, y_train) # fit(Training data, Target data)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
# model accuracy
accuracy = slr.score(X_test, y_test)
print(accuracy)
print("\n\n")
# Visualising the Training set results
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
# Visualising the Test set results
plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() | true |
81d28f7e974c142d2792a4983342723fb8e7a712 | SarahMcQ/CodeWarsChallenges | /sortedDivisorsList.py | 618 | 4.1875 | 4 | def divisors(integer):
'''inputs an integer greater than 1
returns a list of all of the integer's divisor's from smallest to largest
if integer is a prime number returns '()is prime' '''
divs = []
if integer == 2:
print(integer,'is prime')
else:
for num in range(2,integer):
if integer%num == 0:
divs.append(num)
# print(sorted(divs))
if len(divs) == 0:
print(integer, 'is prime')
else:
return sorted(divs)
| true |
ef7cb3ec31fe915692c68d0d61da36bdb8004576 | jfonseca4/FonsecaCSC201-program03 | /program03-Part1.py | 1,129 | 4.375 | 4 | #Jordan Fonseca
#2.1
DNA = input(str("Enter the DNA sequence")) #asks user to input a string
DNA2 = []
for i in DNA:
if i == "A": #if DNA is A, replaces it with a T
DNA2.append("T")
if i == 'G': #if DNA is G, replaces it with a C
DNA2.append("C")
if i == "C": #if DNA is C, replaces it with a G
DNA2.append("G")
if i == "T": #if DNA is T, replaces it with a A
DNA2.append("A")
MirrorDNA = "".join(DNA2) #brings string together
print(MirrorDNA) #prints list mirrored DNA sequence
#2.2
DNA = input(str("Enter the DNA sequence")) #Asks user to enter DNA string
ReverseDNA = DNA[::-1] #reverses the entered DNA string
print(ReverseDNA) #prints reverse DNA string
#2.3
validDNA = "TGCA" #set valid DNA
DNA = input(str("Enter DNA sequence"))
if all(i in validDNA for i in DNA) == True : #If what the user enters for DNA is true
print("valid") #prints valid
else:
print("invalid") #If not true, prints invalid
#2.4
#I was not able to figure out how to put it all together, it would not work.
| true |
b5eb87686608cd0fc8e4215db1479bfc2e9a379b | mlm-distrib/py-practice-app | /00 - basics/08-sets.py | 515 | 4.25 | 4 |
# Set is a collection which is unordered and unindexed. No duplicate members.
myset = {"apple", "banana", "mango"}
print(myset)
for x in myset:
print(x)
print('')
print('Is banana in myset?', "banana" in myset)
myset.add('orange')
print(myset)
myset.update(["pineapple", "orange", "grapes"])
print(myset)
print('length is', len(myset))
myset.remove("orange")
print(myset)
myset.discard("mango")
print(myset)
myset.pop()
print(myset)
myset.clear()
print(myset)
myset = set(("AAA", "BBB", "CCC"))
print(myset)
| true |
4cc99b2d1de0595bc2d0b6f335e7f8d1b80b906d | kannanmavila/coding-interview-questions | /quick_sort.py | 714 | 4.28125 | 4 | def r_quick_sort(array, start, end):
# Utility for swapping two elements of the array
def swap(pos1, pos2):
array[pos1], array[pos2] = array[pos2], array[pos1]
if start >= end:
return
pivot = array[start]
left = start+1
right = end
# Divide
while left - right < 1:
if array[left] > pivot:
swap(left, right)
right -= 1
if array[left] <= pivot:
left += 1
# Insert pivot in its position
swap(start, right)
# Recurse
r_quick_sort(array, start, right-1)
r_quick_sort(array, left, end)
def quick_sort(array):
r_quick_sort(array, 0, len(array)-1)
#################### DRIVERS ####################
l = [10, 1, 7, 3, 8, 9, 2, 6]
quick_sort(l)
print l
| true |
e177b1f2ba2fb3baaef810214a9325e1e9207342 | kannanmavila/coding-interview-questions | /reverse_string.py | 235 | 4.21875 | 4 | def reverse(string):
string = list(string)
length = len(string)
for i in xrange((length - 1) / 2 + 1):
string[i], string[length-i-1] = string[length-i-1],string[i]
return "".join(string)
print reverse("Madam, I'm Adam")
| true |
070d388659df628d00116c127f2b212c0e6033cf | kannanmavila/coding-interview-questions | /tree_from_inorder_postorder.py | 1,470 | 4.125 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def binary_tree(inorder, postorder):
"""Return the root node to the BST represented by the
inorder and postorder traversals.
"""
# Utility for recursively creating BST for
# a subset of the traversals.
def _construct(left, right, head_pos):
if left > right:
return None
# Split the inorder array, using head
# as pivot. `head_pos` is the position
# of the head in `postorder`.
pivot = inorder.index(postorder[head_pos])
head = Node(inorder[pivot])
# Recursively create subtrees, and connect
# them to the head.
head.left = _construct(left, pivot-1,
head_pos - (right-pivot) - 1)
head.right = _construct(pivot+1, right,
head_pos-1)
return head
n = len(inorder)
return _construct(0, n-1, n-1)
def inorder(node):
if node is None:
return ""
return inorder(node.left) + " " + str(node.value) \
+ inorder(node.right)
def postorder(node):
if node is None:
return ""
return postorder(node.left) + postorder(node.right) \
+ " " + str(node.value)
if __name__ == "__main__":
ino = [4, 8, 2, 5, 1, 6, 3, 7]
post = [8, 4, 5, 2, 6, 7, 3, 1]
root = binary_tree(ino, post)
print inorder(root)
print postorder(root)
ino = [1, 2, 3]
post = [3, 2, 1]
root = binary_tree(ino, post)
print inorder(root)
print postorder(root)
| true |
668f846583dadfcd5270c9e674b3271ee7381235 | kannanmavila/coding-interview-questions | /interview_cake/16_cake_knapsack.py | 1,136 | 4.25 | 4 | def max_duffel_bag_value(cakes, capacity):
"""Return the maximum value of cakes that can be
fit into a bag. There are infinitely many number
of each type of cake.
Caveats:
1. Capacity can be zero (naturally handled)
2. Weights can be zero (checked at the start)
3. A zero-weight cake can give infinite value
iff its value is non-zero
Attributes:
cakes - list of cakes represented by a
(weight, value) tuple
capacity - the maximum weight the bag can carry
"""
# If there is a cake with zero weight and non-zero
# value, the result is infinity.
if [c for c in cakes if c[0] == 0 and c[1] > 0]:
return float('inf')
max_value = [0] * (capacity+1)
for i in xrange(1, capacity+1):
# For every cake that weighs not more
# than i, see if including it will
# give better results for capacity 'i'
choices = [max_value[i-cake[0]] + cake[1]
for cake in cakes
if cake[0] <= i] + [0]
max_value[i] = max(choices)
return max_value[capacity]
if __name__ == "__main__":
cakes = [(7, 160), (3, 90), (2, 15)]
print max_duffel_bag_value(cakes, 20) # 555 (6*90 + 1*15)
| true |
4a46b2a0a5c8455746758351e85cbf52eaee7e72 | engineeredcurlz/Sprint-Challenge--Intro-Python | /src/oop/oop2.py | 1,535 | 4.15625 | 4 | # To the GroundVehicle class, add method drive() that returns "vroooom".
#
# Also change it so the num_wheels defaults to 4 if not specified when the
# object is constructed.
class GroundVehicle():
def __init__(self, num_wheels = 4): # only works for immutable (cant change) variables otherwise use []
self.num_wheels = num_wheels
# TODO
def drive(self):
return "vroooom"
# Subclass Motorcycle from GroundVehicle. (motorcycle in groundvehicle)
#
# Make it so when you instantiate a Motorcycle, it automatically sets the number
# of wheels to 2 by passing that to the constructor of its superclass.
#
# Override the drive() method in Motorcycle so that it returns "BRAAAP!!"
class Motorcycle(GroundVehicle):
def __init__(self, num_wheels = 2): # set number, doesn't change for now (why do we need __ instead of _?)
self.num_wheels = num_wheels # because it is a special defined method in python. it is used when an object is created from a class
# TODO # and used to initialize the attributes of said class
def drive(self):
return "BRAAAP!!"
vehicles = [
GroundVehicle(),
GroundVehicle(),
Motorcycle(),
GroundVehicle(),
Motorcycle(),
]
# Go through the vehicles list and print the result of calling drive() on each.
# through the vehicles list = for loop
# vehicle = groundvehicle = car
# vehicles = list
# call drive on each , attach drive to vehicle on the end
# TODO
for vehicle in vehicles:
print (vehicle.drive())
| true |
57170eafa6f1197f2032a809dbb0981f49b507ff | a100kpm/daily_training | /problem 0029.py | 983 | 4.1875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding.
You can assume the string to be encoded have no digits and consists solely of
alphabetic characters. You can assume the string to be decoded is valid.
'''
string = "AAAABBBCCDAA"
def encodeur(string):
retour = []
lenn=len(string)
retour.append([string[0],1])
j=0
for i in range(1,lenn):
if string[i]==retour[j][0]:
retour[j][1]+=1
else:
j+=1
retour.append([string[i],1])
lenn2=len(retour)
encodage=''
for i in range(lenn2):
encodage=encodage+str(retour[i][1])+retour[i][0]
return encodage | true |
003bc82579dfd89b4d1d001ee16d40d6a726da67 | a100kpm/daily_training | /problem 0207.py | 1,301 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Dropbox.
Given an undirected graph G, check whether it is bipartite.
Recall that a graph is bipartite if its vertices can be divided into two independent sets,
U and V, such that no edge connects vertices of the same set.
'''
import numpy as np
graph = np.array([[0,1,1,1,0,0,0],
[1,0,0,0,0,0,0],
[1,0,1,1,0,0,0],
[1,0,1,1,0,0,0],
[0,0,0,0,0,1,1],
[0,0,0,0,1,0,1],
[0,0,0,0,1,1,0]
])
def bipartite(graph):
lenn=np.shape(graph)[0]
list_=set()
compteur=0
while len(list_)<lenn:
compteur+=1
for i in range(lenn):
if i not in list_:
break
current_list=[i]
while len(current_list):
for j in range(lenn):
val = graph[current_list[0]][j]
if val==1 and j not in list_ and j not in current_list:
list_.add(j)
current_list.append(j)
current_list=current_list[1:]
if compteur==2:
return True
return False
| true |
0dc1cf2fcc01b34b4cf943a17ba24475df7e768a | a100kpm/daily_training | /problem 0034.py | 958 | 4.21875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Quora.
Given a string, find the palindrome that can be made by inserting the fewest
number of characters as possible anywhere in the word. If there is more than
one palindrome of minimum length that can be made, return the lexicographically
earliest one (the first one alphabetically).
For example, given the string "race", you should return "ecarace",
since we can add three letters to it (which is the smallest amount to make a palindrome).
There are seven other palindromes that can be made from "race" by adding three letters,
but "ecarace" comes first alphabetically.
As another example, given the string "google", you should return "elgoogle".
'''
string1 = "race"
string2="google"
def palindr(string):
lenn=len(string)
bout=""
A=True
j=1
for i in range(1,lenn+1):
bout+=string[-i]
new_str=bout+string | true |
211d0303800ef36e5c658498aa5c8ed99b3a91e8 | a100kpm/daily_training | /problem 0202.py | 671 | 4.28125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write a program that checks whether an integer is a palindrome.
For example, 121 is a palindrome, as well as 888. 678 is not a palindrome.
Do not convert the integer into a string.
'''
nbr1=121
nbr2=123454321
nbr3=678
nbr4=1234
def nbr_palindrome(nbr):
if nbr<10:
return True
taille=0
while nbr//10**taille>0:
taille+=1
taille-=1
while nbr>9:
if nbr%10!=nbr//10**taille:
return False
nbr=int((nbr-(nbr//10**taille*10**taille)-nbr%10)/10)
taille-=2
return True
| true |
2d3369c67839346d1e81cc29eda6163e1bf27080 | a100kpm/daily_training | /problem 0063.py | 1,824 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Given a 2D matrix of characters and a target word, write a function that returns
whether the word can be found in the matrix by going left-to-right, or up-to-down.
For example, given the following matrix:
[['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']]
and the target word 'FOAM', you should return true, since it's the leftmost column.
Similarly, given the target word 'MASS', you should return true, since it's the last row.
'''
import numpy as np
word= 'FOAM'
word2= 'MASS'
word3 = 'AAAAA'
word4= 'MASSS'
matrix = np.array([['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']])
def word_finder(matrix,word):
first_letter = word[0]
size=len(word)
lenn=np.shape(matrix)[0]
lenn2=np.shape(matrix)[1]
for i in range(lenn):
for j in range(lenn2):
if matrix[j][i]==first_letter:
# print('i={} and j={}'.format(i,j))
horizontal=i
vertical=j
ok=True
n=1
while horizontal < lenn2-1 and ok ==True:
horizontal+=1
n+=1
if word[n-1]!=matrix[j][horizontal]:
ok=False
if n==size and ok==True:
return True
ok=True
n=1
while vertical < lenn-1 and ok ==True:
vertical+=1
n+=1
if word[n-1]!=matrix[vertical][i]:
ok=False
if n==size and ok==True:
return True
return False
| true |
f34bef76194d77d6a5e5f5891c334c33c8d7ca10 | a100kpm/daily_training | /problem 0065.py | 1,407 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following:
1
2
3
4
5
10
15
20
19
18
17
16
11
6
7
8
9
14
13
12
'''
import numpy as np
matrice = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])
def asticot_printer(matrix):
base1=0
base2=1
coorX=0
coorY=0
base1_max=np.shape(matrix)[1]-1
base2_max=np.shape(matrix)[0]-1
taille_=np.shape(matrix)[0]*np.shape(matrix)[1]-1
direction=0
for _ in range(taille_):
print(matrix[coorY][coorX])
if direction==0:
coorX+=1
if coorX==base1_max:
direction=1
base1_max-=1
elif direction==1:
coorY+=1
if coorY==base2_max:
direction=2
base2_max-=1
elif direction==2:
coorX-=1
if coorX==base1:
direction=3
base1+=1
else:
coorY-=1
if coorY==base2:
direction=0
base2+=1
print(matrix[coorY][coorX])
| true |
4be59ab979de011b3761d0744013c0ff1ff5d9d2 | a100kpm/daily_training | /problem 0241.py | 949 | 4.3125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
In academia, the h-index is a metric used to calculate the impact of a researcher's papers. It is calculated as follows:
A researcher has index h if at least h of her N papers have h citations each.
If there are multiple h satisfying this formula, the maximum is chosen.
For example, suppose N = 5, and the respective citations of each paper are
[4, 3, 0, 1, 5]. Then the h-index would be 3, since the researcher has 3 papers with at least 3 citations.
Given a list of paper citations of a researcher, calculate their h-index.
'''
citation= [4, 3, 0, 1, 5]
def h_value(citation):
lenn=len(citation)
for i in range(lenn,-1,-1):
compteur=0
for j in range(lenn):
if citation[j]>=i:
compteur+=1
if compteur==i:
return i
return 0 | true |
625c3d016087f104ed463b41872b3510d000a04c | Abhishek4uh/Hacktoberfest2021_beginner | /Python3-Learn/Decorators_dsrathore1.py | 1,775 | 4.625 | 5 | #AUTHOR: DS Rathore
#Python3 Concept: Decorators in Python
#GITHUB: https://github.com/dsrathore1
# Any callable python object that is used to modify a function or a class is known as Decorators
# There are two types of decorators
# 1.) Fuction Decorators
# 2.) Class Decorators
# 1.) Nested function
# 2.) Function return function
# 3.) reference
# 4.) Function as parameter
''' Note: Need to take a function as parameter
Add functionality to the function
Function need to return another function'''
def outer ():
a = 3
def inner ():
b = 4
result = a +b
return result
return inner # Refrences to the inner funtion
# retun inner() # Returning the value of the function
a = outer ()
print (a)
def function1():
print ("Hi, I am function 1")
def function2():
print ("Hi, I am function 2")
function1()
function2()
def function1():
print("Hi, I am function 1")
def function2(func):
print ("Hi, I am function 2, and now I am calling function 1")
func()
function2(function1)
def str_lower(func):
def inner():
str1 = func()
return str1.lower
return inner()
@str_lower
def print_str():
return ("GOOD MORNING")
print(print_str())
d = str_lower(print_str)
print(d())
def add(func):
def sum():
result = func() + 5
return result
return sum
@add
def function1():
x = 3
y = 5
return x + y
print(function1())
print (add(function1()))
# Parameteric Decorator
def d(func):
def inner(x, y):
result = f'Answer of divide and the value of the a : {x} b : {y} \nResult is {func(x, y)}'
return result
return inner
@d
def div(a, b):
divide = a // b
return divide
print (div(4, 2)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.