blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
24b03adda55bc74c4365e93ecf529f3cc1c4453d | ravisjoshi/python_snippets | /Permutation-Combination/PermutationAndCombination.py | 879 | 4.3125 | 4 | """
"My fruit salad is a combination of apples, grapes and bananas" We don't care what order the fruits are in, they could also be "bananas, grapes and apples" or "grapes, apples and bananas", its the same fruit salad.
"The combination to the safe is 472". Now we do care about the order. "724" won't work, nor will "247". It has to be exactly 4-7-2.
So, in Mathematics we use more precise language:
When the order doesn't matter, it is a Combination.
When the order does matter it is a Permutation.
"""
from itertools import permutations, combinations
text = 'ravi'
perm_list = ["".join(p) for p in permutations(text)]
print(perm_list)
# distinct Combination of 2 letter words
comb_list = ["".join(c) for c in combinations(text, 2)]
print(comb_list)
# distinct Combination of 3 letter words
comb_list = ["".join(c) for c in combinations(text, 3)]
print(comb_list)
| true |
c90e7d6f56a990f373775438722f91d821f1ff1f | ravisjoshi/python_snippets | /Basics-2/NumberOfDaysBetweenTwoDates.py | 815 | 4.21875 | 4 | """
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Input: date1 = "2019-06-29", date2 = "2019-06-30" / Output: 1
Input: date1 = "2020-01-15", date2 = "2019-12-31" / Output: 15
Constraints: The given dates are valid dates between the years 1971 and 2100.
"""
from datetime import date
class Solution:
def daysBetweenDates(self, date1, date2):
if date1 == date2:
return 0
y1, m1, d1 = map(int, date1.split('-'))
y2, m2, d2 = map(int, date2.split('-'))
d1 = date(y1, m1, d1)
d2 = date(y2, m2, d2)
delta = d2 - d1
return abs(delta.days)
s = Solution()
date1 = "2019-06-29"
date2 = "2019-06-30"
print(s.daysBetweenDates(date1, date2))
| true |
228e9868f9142aec935642cae53376452d296029 | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/319-StringMethods-Part2/string-methods2.py | 404 | 4.3125 | 4 | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC'))
#print(a.upper()) # another way to convert if all is need to upper case (or a.lower if all needed to be in lower case)
# Sub-Strings
# starting index is inclusive
# Ending index is exclusive
sub = a[0:6]
step = a[1:6:2]
print("****************")
print(sub)
print(step)
| true |
902b77933c6d369a13fa8963737cde0a22c0d01b | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/314-Numbers-ExponentiationAndModulo/numbers_operations.py | 427 | 4.28125 | 4 | # This is a one line comment
# Exponentiation
exponents = 10**2
print(exponents)
"""
this is a multi line comment
modulo - returns the remainder
"""
a=100
b=3
remainder = a % b
print("Getting the modulo of " + str(a)+ " % "+ str(b) + " is just like getting the remainder integer when " + str(a) +" is being divided by " + str(b))
print("The modulo of ("+str(a) +" % "+str(b) +") is " + str(remainder))
| true |
ddb4a47288b73951542d6c1aa3854b7c3846cf9c | DysphoricUnicorn/CodingChallenges | /extra_char_finder.py | 1,630 | 4.3125 | 4 | """
This is my solution to the interview question at https://www.careercup.com/question?id=5101712088498176
The exercise was to write a script that, when given two strings that are the same except that one string has an extra
character, prints out that character.
"""
import sys
def find_extra_char(longer_string, shorter_string):
"""
Returns the extra char that longer_string has but shorter_string hasn't got
:param str longer_string:
:param str shorter_string:
:return char:
"""
i = 0
for char in longer_string:
try:
if not char == shorter_string[i]:
# if the char is not the same as the one in the same position in the shorter string, it is the extra one
return char
except IndexError:
# if an IndexError occurs, we can assume that the extra char is at the end of the longer string
return char
i += 1
def main():
"""
Gets two strings from sys.argv and prints out the extra character
:return void:
"""
try:
string_one = sys.argv[1]
string_two = sys.argv[2]
except IndexError:
print("Could not find strings. Please call this script like this:")
print("python3 extra_char_finder <string1> <string2>")
sys.exit(1)
if len(string_one) > len(string_two):
# check which string is the longer one to iterate through it inside the find_extra_char function
char = find_extra_char(string_one, string_two)
else:
char = find_extra_char(string_two, string_one)
print(char)
if __name__ == '__main__':
main()
| true |
6a563dbae7b8cf7a46621ba9013275c2856ffc95 | pratikmallya/interview_questions | /sorting/insertion_sort.py | 1,011 | 4.34375 | 4 | """
Insertion Sort
Pick lowest element, push it to the front of the list
This will be an in-place sort. Why? Because that's a little
more complicated.
"""
import unittest
from random import sample
from copy import deepcopy
class TestAlg(unittest.TestCase):
def test_case_1(self):
v = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
insertion_sort(v)
self.assertEqual(v, list(range(1,11)))
maxlen = 10000
v1 = sample(range(maxlen), maxlen)
v2 = deepcopy(v1)
self.assertEqual(
v1.sort(), insertion_sort(v2))
def insertion_sort(v):
for i in range(1, len(v)):
ind = find_ind(v[:i], v[i])
insert_elem(v, i, ind)
def find_ind(v, elem):
for i,item in enumerate(v):
if elem < item:
return i
return i
def insert_elem(v, from_ind, to_ind):
elem = v[from_ind]
for i in reversed(range(to_ind+1, from_ind+1)):
v[i] = v[i-1]
v[to_ind] = elem
if __name__ == "__main__":
unittest.main()
| true |
4206e176b23841534c80170b24ca94ee87170c1a | navnathsatre/Python-pyCharm | /BasicOprations.py | 580 | 4.25 | 4 | num1=int(input("Enter the value for num1 "))
num2=int(input("Enter the value for num2 "))
#num1=568
#num2=64
add=num1+num2
multi=num1*num2
sub=num1-num2
div=num1/num2
pow=num1**num2
"""print("addition of num1 and num2 is:-",add)
print("multiplication of num1 and num2 is:-",multi)
print("substraction of num1 and num2 is:-",sub)
print("power of num1 and num2 is:-",pow)
print("division of num1 and num2 is:-%.5f"%(div))"""
print(f"addition of two no. is {add} multiplication of two no. is {multi} substraction of two no. is {sub} division is {div} power is{pow}")
| true |
147560dd844918b281b381aedec10aac292711e6 | navnathsatre/Python-pyCharm | /pyFunc_3.py | 301 | 4.1875 | 4 | # Factorial of number
# 5! = 5*4*3*2*1
#1! = 0
#0! = 0
def iterFactorial(num):
result = 1
for item in range(1, num+1):
result = result*item
return result
n = int(input("Enter the number: "))
out = iterFactorial(n)
print("Factorial of {} is {} ".format(n, out)) | true |
dc8d1e68476d077ab36ca4aece654e6ac5ef63bb | RyanLongRoad/Records | /Test scores.py | 745 | 4.15625 | 4 | #Ryan Cox
#29/01/15
#Store and display students test scores
#Blue print
class studentMarks:
def __init__(self):
self.testScore = "-"
self.studentName = "-"
#main program
def create_record():
new_studentMarks = studentMarks
def enter_enformation():
studentMarks.studentName = input("Enter the student's name: ")
studentMarks.testScore = int(input("Enter the test score: "))
scores = []
scores.append(studentMarks)
return scores
def disply(scores):
for each in scores:
print("The student {0} got the test score of {1}".format(studentMarks.studentName,studentMarks.testScore))
create_record()
scores = enter_enformation()
disply(scores)
| true |
3cdcc8c5f51e8b0813fad7ad93b09331af801b9a | tamkevindo97/Runestone-Academy-Exercises | /longest_word_dict.py | 456 | 4.28125 | 4 | import string
def longest_word(text):
text.translate(str.maketrans('', '', string.punctuation))
list_text = list(text.split())
dictionary = {}
for aChar in list_text:
dictionary.update({aChar: len(aChar)})
max_key = max(dictionary, key=dictionary.get)
print(dictionary)
return max_key
def main():
text = input("Enter a sentence to see which word is longest: ")
print(longest_word(text))
main() | true |
08f8761330af9c9dccb0ed64557e1b45516b2bc4 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter01/ch1/scopes3.py | 450 | 4.21875 | 4 | # Local, Enclosing and Global
def enclosing_func():
m = 13
def local():
# m doesn't belong to the scope defined by the local
# function so Python will keep looking into the next
# enclosing scope. This time m is found in the enclosing
# scope
print(m, 'printing from the local scope')
# calling the function local
local()
m = 5
print(m, 'printing from the global scope')
enclosing_func()
| true |
d19cb3e849ab5d6e7d43843a000d24992e0a3b22 | llewyn-jh/codingdojang | /calculate_trigonometric_function.py | 1,046 | 4.28125 | 4 | """Calculate cosine and sine funtions in person"""
import math
def calculate_trigonometric_function(radian_x: float) -> float:
"""This function refer to Taylor's theorm.
A remainder for cos or sin at radian_x follows Cauchy's remainder.
The function has 2 steps. Step1 get a degree of
Taylor polynomial function at radian_x. Step 2 calculates sin and cos at radian_x
and return two values
"""
# Step1: get a degree of Taylor polynomial function at radian_x
degree = 0
error = 5 * 1e-6
upper_limit = radian_x ** degree / math.factorial(degree)
while upper_limit >= error:
# Upper limit of Cauchy's remainder for sin or cos at radian_x
degree += 1
upper_limit = radian_x ** degree / math.factorial(degree)
# Step2: Calculate sin, cos at radian_x
sin = 0
cos = 0
for i in range(degree):
sin += (-1) ** i * radian_x ** ((2 * i) + 1) / math.factorial(2 * i + 1)
cos += (-1) ** i * radian_x ** (2 * i) / math.factorial(2 * i)
return sin + cos
| true |
e78bb6f14e5aa6a3fc8e765ac206b458bcaa2fb3 | sirobhushanamsreenath/DataStructures | /Stacks/stack.py | 1,026 | 4.21875 | 4 | # Implementation of stack data structure using linkedlist
class Node:
def __init__(self, data=None, next=None):
self.next = next
self.data = data
def has_next(self):
return self.next != None
class Stack:
def __init__(self, top=None):
self.top = top
def print_stack(self):
current = self.top
while current:
print(current.data)
current = current.next
def push(self, data):
current = self.top
if self.top == None:
new_node = Node(data, None)
self.top = new_node
else:
new_node = Node(data, current)
self.top = new_node
def pop(self):
current = self.top
if self.top == None:
print('The stack is empty')
else:
self.top = current.next
def peek(self):
print(self.top.data)
mystack = Stack()
mystack.push(2)
mystack.push(1)
mystack.push(3)
# mystack.pop()
# mystack.print_stack()
mystack.peek()
| true |
c33c1e6d9251779cf6f7f8484d8e431575e8d1fa | ronshuvy/IntroToCS-Course-Projects | /Ex2 - Math/shapes.py | 1,529 | 4.46875 | 4 | # FILE : shapes.py
# WRITER : Ron Shuvy , ronshuvy , 206330193
# EXERCISE : intro2cs1 2019
import math
def shape_area():
""" Calculates the area of a circle/rectangle/triangle (Input from user)
:return: the area of a shape
:rtype: float
"""
def circle_area(r):
""" Calculates the area of a circle
:param r: circle radius
:return: the area of the shape
:rtype: float
"""
return math.pi * (r**2)
def rectangle_area(side_a, side_b):
""" Calculates the area of a rectangle
:param side_a: rectangle first side
:param side_b: rectangle second side
:return: the area of the shape
:rtype: float
"""
return side_a * side_b
def triangle_area(side_a):
""" Calculates the area of an equilateral triangle
:param side_a: triangle side
:return: the area of the shape
:rtype: float
"""
return (side_a**2) * (math.sqrt(3)/4)
print('Choose shape (1=circle, 2=rectangle, 3=triangle):', end = " ")
shape_type = float(input())
if shape_type == 1: # Circle
radius = float(input())
return circle_area(radius)
elif shape_type == 2: # Rectangle
side1 = float(input())
side2 = float(input())
return rectangle_area(side1, side2)
elif shape_type == 3: # Triangle
side = float(input())
return triangle_area(side)
else:
return None
| true |
e3a613de2b32756b5a6bad7846b1db69cd134bab | SonnyTosco/HTML-Assignments | /Python/sonnytosco_pythonoop_bike.py | 1,603 | 4.3125 | 4 | class Bike(object):
def __init__(self, price,max_speed):
self.price=price
self.max_speed=max_speed
self.miles=0
print "Created a new bike"
def displayInfo(self):
print "Bike's price:"+ str(self.price)
print "Bike's max speed:"+str(self.max_speed)+'mph'
print "Bike's mileage:"+str(self.miles)+'miles'
def ride(self):
print 'Riding'
self.miles+=10
def reverse(self):
print 'Reversing'
if self.miles>=5:
self.miles-=5
bike1 = Bike(99.99, 12)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(139.99, 20)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
# Answer:
# class Bike(object):
# def __init__(self, price, max_speed):
# self.price = price
# self.max_speed = max_speed
# self.miles = 0
#
# def displayInfo(self):
# print 'Price is: $' + str(self.price)
# print 'Max speed: ' + str(self.max_speed) + 'mph'
# print 'Total miles: ' + str(self.miles) + ' miles'
#
# def drive(self):
# print 'Driving'
# self.miles += 10
#
# def reverse(self):
# print 'Reversing'
# # prevent negative miles
# if self.miles >= 5:
# self.miles -= 5
#
# # create instances and run methods
# bike1 = Bike(99.99, 12)
# bike1.drive()
# bike1.drive()
# bike1.drive()
# bike1.reverse()
# bike1.displayInfo()
#
# bike2 = Bike(139.99, 20)
# bike2.drive()
# bike2.drive()
# bike2.reverse()
# bike2.reverse()
# bik2.displayInfo()
| true |
13ff32648e515107376972672ac74737c6670379 | HanaAuana/PyWorld | /DNA.py | 2,807 | 4.21875 | 4 | #Michael Lim CS431 Fall 2013
import random
# A class to hold a binary string representing the DNA of an organism
class DNA():
#Takes an int representing the number of genes, and possibly an existing genotype to use
def __init__(self, numGenes, existingGenes):
self.numGenes = numGenes
#If a genotype is given, use this
if existingGenes is not None:
self.dna = existingGenes
#Else, create a random genotype
else:
self.dna = ""
#Randomly pick 1 or 0 for the required number of genes
for i in range(0, numGenes):
value = random.randint(0, 1)
if value == 0:
self.dna += "0"
else:
self.dna += "1"
#Given a number, return the corresponding bit
def getGene(self, num):
return self.dna[num]
#Return a string containing the genotype of this instance. Bits are grouped as they are expressed in an Organism
def getGeneotype(self):
#Get a string for each gene that an Organism will express
gene0to4 = self.getGene(0) + self.getGene(1) + self.getGene(2) + self.getGene(3) + self.getGene(4)
gene5to8 = self.getGene(5) + self.getGene(6) + self.getGene(7) + self.getGene(8)
gene9to12 = self.getGene(9) + self.getGene(10) + self.getGene(11) + self.getGene(12)
gene13to17 = self.getGene(13) + self.getGene(14) + self.getGene(15) + self.getGene(16) + self.getGene(17)
gene18to23 = self.getGene(17) + self.getGene(18) + self.getGene(19) + self.getGene(20) + self.getGene(21) + self.getGene(22)
gene24to30 = self.getGene(24) + self.getGene(25) + self.getGene(26) + self.getGene(27) + self.getGene(28) + self.getGene(29) + self.getGene(30)
gene31to33 = self.getGene(31) + self.getGene(32) + self.getGene(33)
gene34to36 = self.getGene(34) + self.getGene(35) + self.getGene(36)
gene37to39 = self.getGene(37) + self.getGene(38) + self.getGene(39)
#Prints out each chunk
genes = ""
genes += str(gene0to4)+" "
genes += str(gene5to8)+" "
genes += str(gene9to12)+" "
genes += str(gene13to17)+" "
genes += str(gene18to23)+" "
genes += str(gene24to30)+" "
genes += str(gene31to33)+" "
genes += str(gene34to36)+" "
genes += str(gene37to39)+" "
genes += " "
#Genes past 40 are also unused, group these together too
for i in range(40, self.numGenes):
genes += self.dna[i]
return genes
#Returns the genotype as a single contiguous string
def getGeneotypeString(self):
genes = ""
for i in range(0, len(self.dna)):
genes += self.dna[i]
return genes | true |
697f05adc3fd045a5d8b4757ba1ceae1a92de41c | DrewStanger/pset7-houses | /import.py | 1,595 | 4.375 | 4 | from sys import argv, exit
from cs50 import SQL
import csv
# gives access to the db.
db = SQL("sqlite:///students.db")
# Import CSV file as a command line arg
if len(argv) != 2:
# incorrect number print error and exit
print(f"Error there should be 1 argv, you have {argv}")
exit(1)
# assume CSV file exists and columns name, house and birth present
# open the CSV file
with open(argv[1], "r") as inputfile:
reader = list(csv.reader(inputfile))
char_list = []
# add each entry to the list name , house, birth
for row in reader:
char_list.append(row)
# for each entry in char_list row[0] is the two or three names, split splits these into individual strings. [1] is the house [2] is the birth year.
for row in char_list:
name = row[0].split(' ')
house = row[1]
birth = row[2]
# now to if to figure out if len = 2 first and last names only, if len = 3 first midddle last. The following then adds the names to the db
if len(name) == 2:
#No middle name
firstName = name[0]
middleName = None
lastName = name[1]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?,?,?,?,?)", firstName, middleName, lastName, house, birth)
elif len(name) == 3:
#Middle name
firstName = name[0]
middleName = name[1]
lastName = name[2]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?,?,?,?,?)", firstName, middleName, lastName, house, birth)
| true |
0606a46baee937e230d7ae503a69c4724957c3d0 | elaineli/ElaineHomework | /Justin/hw2.py | 834 | 4.125 | 4 | ages = { "Peter": 10, "Isabel": 11, "Anna": 9, "Thomas": 10, "Bob": 10, "Joseph": 11, "Maria": 12, "Gabriel": 10, }
# 1 find the number of students
numstudents = len(ages)
print(numstudents)
# 2 receives ages and returns average
def averageAge(ages):
sum = 0
for i in ages.values():
sum += i
length = len(ages)
average = sum/length
return average
print('average age is ' + str(averageAge(ages)))
#3 find oldest student
def oldest(ages):
max = 0
name = ''
for k, i in ages.items():
if i > max:
max = i
name = k
return name
print('The oldest student is ' + str(oldest(ages)))
#4 how old in time
def new_ages(ages, n):
for key, value in ages.items():
value += n
ages[key] = value
return ages
print(new_ages(ages, 10))
| true |
8e472f11b1d5e9c6d3cec5500c8fb2229f3a6641 | Kakadiyaraj/Leetcode-Solutions | /singalString.py | 539 | 4.21875 | 4 | #Write a program that reads names of two python files and strips the extension. The filenames are then concatenated to form a single string. The program then prints 'True' if the newly generated string is a palindrome, or prints 'False' otherwise.
name1 = input('Enter a first file name : ')
name2 = input('Enter a second file name : ')
name1 = name1.replace('.py','')
name2 = name2.replace('.py','')
name = name1+name2
print('Newly generated string : ',name)
if name==name[::-1]:
print('Output : True')
else:
print('Output : False')
| true |
55a870349405f243b9a7b6fad1a4a27c82d9017a | rohitgit7/Ethans_Python | /Class4_[13-10-2018]/dictionary.py | 2,117 | 4.40625 | 4 | #Dictionary is a collection which is unordered, changeable and indexed
data = { 'name' : 'Rohit',
'roll_no' : 20, #will be overriden by last key value
'city' : 'Pune',
'roll_no' : 34,
2 : 234}
#dict() is a constructor too
print data
print "type(data)", type(data)
data['name'] = 'India'
data['call'] = 12345
print data
my_dict = dict(apple="green",banana="yellow",cherry='red') #using dict constructor to make a dictionary or convert to dictionary
print 'my_dict',my_dict
del(my_dict['apple']) #Delete key from dictionary
print "Delete apple", my_dict
print"----------------------------------------------------------------------------------"
print "keys in data:", data.keys()
print "Values in data:", data.values()
print "items in data:", data.items() #returns list of tuples of each key value pair
print "has_key \'cherry\': ", data.has_key('city')
print "get value of key \'name\': ", data.get('name')
print "get value of key \'n\': ", data.get('n') #data['n'] returns error if key doesnot exists, but get() will return none if key doesn't exists
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print "squares.pop(4):",squares.pop(4) #delete deletes the key/value pair silently where pop returns value while deleting
print "squares", squares
squares[4]=16
print "squares[4]=16",squares
print "squares.popitem()", squares.popitem() #popitem() does not require key like pop(). it pops single key/value pair from start
print squares
print "squares.popitem()", squares.popitem()
print squares
print "squares:",squares.clear() #clears the dictionary
sq = squares #creates reference/alias to squares. Change in sq will reflect in squares.
sq[6] = 36
print "squares",squares
squares.copy() #copy() will create a new copy unlike aliases sq=squares
print 23 in squares
print 6 in squares
print squares.has_key(6)
print len(sq)
sq[7] = ''
print squares
dict1 = {'Name':'Zara','Age':20}
dict2 = {'sex':'female'}
dict1.update(dict2) #update is like extend in lists unlike append() it extends the dictionary
print "dict1",dict1
print "-------------------------------------------------------------------------"
| true |
afe039a8f713e6a13372d2de91ec8c0d972a3d6d | gwlilabmit/Ram_Y_complex | /msa/msas_with_bad_scores/daca/base_complement.py | 1,870 | 4.3125 | 4 | #sequence = raw_input("Enter the sequence you'd like the complement of: \n")
#seqtype = raw_input("Is this DNA or RNA? \n")
sequence = ''
seqtype = 'DNA'
def seqcomplement(sequence, seqtype):
complement = ''
for i in range(len(sequence)):
char = sequence[i]
if char == 'A' or char == 'a':
if 'R' in seqtype or 'r' in seqtype:
complement += 'U'
else:
complement += 'T'
elif char == 'T' or char == 't':
if 'R' in seqtype or 'r' in seqtype:
answer = raw_input("Just letting you know, this sequence has T's despite you saying it's RNA. Do you want me to treat it as DNA? [Answer yes/no]\n")
if 'y' in answer or 'Y' in answer:
seqtype = 'DNA'
for j in range(len(complement)):
if complement[j] == 'U':
complementlist = list(complement)
complementlist[j] = 'T'
complement = "".join(complementlist)
complement += 'A'
else:
complement += 'A'
elif char == 'U' or char == 'u':
if 'D' in seqtype or 'd' in seqtype:
answer = raw_input("Just letting you know, this sequence has U's despite you saying it's DNA. Do you want me to treat it as RNA? [Answer yes/no]\n")
if 'y' in answer or 'Y' in answer:
seqtype = 'RNA'
for j in range(len(complement)):
if complement[j]== 'T':
complementlist = list(complement)
complementlist[j] = 'U'
complement = "".join(complementlist)
complement += 'A'
elif char == 'C' or char == 'c':
complement += 'G'
elif char == 'G' or char == 'g':
complement += 'C'
elif char == '\n' or char == ' ':
continue
else:
print "There's some non-A/U/T/C/G base here. Check index", i, "for the problem. There may be more issues later on in the string but this is the first issue I'm detecting."
complement = ""
break
i+=1
return complement
seqcomplement(sequence, seqtype)
| true |
5eead0bd31ab85a27925a22a450abc5eeff8f689 | gayathrib17/pythonpractice | /IdentifyNumber.py | 1,356 | 4.40625 | 4 | # Program to input from user and validate
while True:
try: # try is used to catch any errors for the input validation into float
num = int(input("Please input a integer between -9999 and 9999: "))
except ValueError: # ValueError is raised when we are attempting to convert a non numeric string into float.
print("This is not a valid number, please try again.")
continue
else: # should be a number, but check for within range
if -9999 < num < 9999:
print("Congrats! You have given a valid number!")
break
else:
print("Enter an integer between -9999 and 9999")
continue
def valid(n):
if n >= 0:
print(n, "is a positive number.")
else:
print(n, "is a negative number.")
if n%2 == 0:
print(n," is also an even number")
else:
print(n, " is also an odd number.")
def prime(n):
if n > 1:
# check for factors
for i in range(2, n):
if (n % i) == 0:
print(n, "is not a prime number")
print(i, "times", n // i, "is", n)
break
else:
print("and",n, " is also a prime number!")
# if input number is less than or equal to 1, it is not prime
else:
print(n, "is not a prime number.")
valid(num)
prime(num) | true |
1110b8b86c71d30e8e220e005cc60ac2c3ce546a | oscarhuang1212/Leecode | /LeetCode#073_Set_Matrix_Zeroes.py | 2,350 | 4.15625 | 4 | # File name: LeetCode#73_Set_Matrix_Zeroes.py
# Author: Oscar Huang
# Description: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
# Example 2:
# Input:
# [
# [0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]
# ]
# Output:
# [
# [0,0,0,0],
# [0,4,5,0],
# [0,3,1,0]
# ]
#
# Follow up:
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Could you devise a constant space solution?
# KeyPoints: Array
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
#Do not return anything, modify matrix in-place instead.
firstColumnZero = False
firstRowZero = False
R = len(matrix)
C = len(matrix[0])
if matrix[0][0] == 0:
firstColumnZero = True
firstRowZero = True
for r in range(0,R):
for c in range(0,C):
if r==0 and c ==0:
continue
if(matrix[r][c]==0):
if r == 0:
firstRowZero = True
if c == 0 :
firstColumnZero = True
matrix[r][0] = 0
matrix[0][c] = 0
for r in range(1,R):
for c in range(1,C):
if matrix[r][0] == 0 or matrix [0][c] ==0:
matrix[r][c]=0
if firstColumnZero ==True:
for r in range(0,R):
matrix[r][0] = 0
if firstRowZero ==True:
for c in range(0,C):
matrix[0][c] = 0
print(matrix)
print(firstRowZero)
print(firstColumnZero)
return None
input = [
[1,1,1],
[1,0,1],
[1,1,1]
]
input2 = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
input3 = [[0,1]]
Solution.setZeroes(None, input3) | true |
2392192820c230c919b684c3d2d9ba92b8ca4d59 | Gt-gih/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 594 | 4.25 | 4 | #!/usr/bin/python3
"""
Module with function that add two integers
"""
def add_integer(a, b=98):
"""Function that add two numbers
Raises:
TypeError: a parameter must be integer type
TypeError: b parameter must be integer type
Args:
a (int): The first parameter.
b (int): The second parameter.
Returns:
int -- a+b
"""
if type(a) not in [int, float]:
raise TypeError('a must be an integer')
if type(b) not in [int, float]:
raise TypeError('b must be an integer')
else:
return(int(a) + int(b))
| true |
3b5f8c3e6f1bd65ba15d4af55840ef50afae0ffe | Gt-gih/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 362 | 4.1875 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
# new list
new_list = []
for element in my_list:
# checking element not exist in list 🔄
if element not in new_list:
new_list.append(element)
result = 0
# adding each element in list into result 🔴
for item in new_list:
result += item
return result
| true |
e047b0eeda1e934eebcef822d70a9403f30f7eec | ngchrbn/DS-Roadmap | /DS Code/1. Programming/Python/Projects/banking_system.py | 1,217 | 4.28125 | 4 | """
Banking System using OOP:
==> Holds details about a user
==> Has a function to show user details
==> Child class : Bank
==> Stores details about the account balance
==> Stores details about the amount
==> Allows for deposits, withdrawals, and view balance
"""
class User:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def show_details(self):
print("Personal Details\n")
print("Name ", self.name)
print("Age", self.age)
print("Gender", self.gender)
# Child class
class Bank(User):
def __init__(self, name, age, gender):
super().__init__(name, age, gender)
self.balance = 0
def deposit(self, amount):
self.balance += amount
print("Account balance has been updated: $", self.balance)
def withdrawal(self, amount):
if amount > self.balance:
print("Insufficient Funds | Balance Available: $", self.balance)
else:
self.balance -= amount
print("Account balance has been updated: $", self.balance)
def view_balance(self):
self.show_details()
print("Balance available: $", self.balance) | true |
cb217a8a547a07eb1c02e065e9a0db8416ffd117 | shaniajain/hello-world | /ShaniaJainLab3.py | 2,792 | 4.15625 | 4 | ###############################################################################
# CS 21A Python Programming: Lab #3
# Name: Shania Jain
# Description: Password Verification Program
# Filename: ShaniaJainLab3.py
# Date: 07/25/17
###############################################################################
def main():
str1 = input("Enter password: ")
str2 = input("Re-enter password: ")
while str1!=str2:
print("Passwords do not match. Try again.")
str1 = input("Enter password: ")
str2 = input("Re-enter password: ")
check_length(str1, str2)
check_uppercase(str1, str2)
check_digits(str1, str2)
check_lowercase(str1, str2)
def check_length(str1, str2):
#check if password is atleast 8 characters long
chars = len(str1)
MIN_LENGTH = 8
if chars >= MIN_LENGTH:
return
else:
print("That password didn't have the required properties.")
main()
return
def check_uppercase(str1, str2):
#check if password has atleast one uppercase letter
while str1 == str2:
for char in str1:
if char >= "A" and char <= "Z":
return
else:
print("That password didn't have the required properties.")
main()
return
def check_digits(str1, str2):
#check if password has atleast one digit
while str1 == str2:
for char in str1:
if char >= "0" and char <= "9":
return
else:
print("That password didn't have the required properties.")
main()
return
def check_lowercase(str1, str2):
#check if password has atleast one lowercase letter
while str1 == str2:
for char in str1:
if char >= "a" and char <= "z":
print("That pair of passwords will work.")
return
else:
print("That password didn't have the required properties.")
main()
return
main()
'''
Enter password: Abc12
Re-enter password: Abc12
That password didn't have the required properties.
Enter password: abcd12345
Re-enter password: abcd12345
That password didn't have the required properties.
Enter password: ABCDabcd
Re-enter password: ABCDabcd
That password didn't have the required properties.
Enter password: ABCD12345
Re-enter password: ABCD12345
That password didn't have the required properties.
Enter password: Hello1234
Re-enter password: Ello12345
Passwords do not match. Try again.
Enter password: 123ABCabc
Re-enter password: 456ABCabc
Passwords do not match. Try again.
Enter password: ABCabc123
Re-enter password: ABCabc123
That pair of passwords will work.
'''
| true |
ce0198d5caa2eb033fb1b4c40198232063d0de38 | asiftandel96/Python-Implementation | /LambdaFunctions.py | 2,580 | 4.40625 | 4 | """ Python Lambda Functions/Anonymous Functions.Anonymous function are those function which are without name."""
# Defining a Normal functions.
def addition_num(a, b):
c = a * b
print(c)
addition_num(2, 42)
# Using A Lambda
# Syntax lambda arguments:expression
# Note-(Lambda Function can take single expression one at a time) (x+y-This is a expression)
s = lambda x, y: x + y
print(s(2, 3))
# Now Using lambda function with Filter() method
# Filter method filter out the list and give the output
List_li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
g = list(filter(lambda x: (x % 2 == 0), List_li))
print(g)
# Now Using Lambda function with map() method
c_2 = list(map(lambda x1, x2: x1 * 2 + x2 * 2, [2, 4, 6, 8, 10], [4, 2, 5, 7, 8]))
# Using Lambda Functions with reduce() method
from functools import reduce
c_3 = reduce(lambda x3, x4: x3 + x4, [1, 2, 4, 6, 7] + [1, 6, 7, 8, 9])
print(c_3)
# This is very Important Code
full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
print(full_name('guido', 'van rossum'))
# Python Program to find Linear Equation using Lambda Functions
Linear_eq = lambda a, b: 3 * a + 4 * b
print(Linear_eq(3, 4))
# Python Program to find Quadratic Equations
Quadratic_eq = lambda a, b: (a + b) ** 2
print((Quadratic_eq(3, 4)))
Unknown_number = lambda x: x * x
print(Unknown_number(5))
# Write a Python program to sort a list of tuples using Lambda.
subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
print("Original list of tuples:")
print(subject_marks)
subject_marks.sort(key=lambda x: x[1])
print("\nSorting the List of Tuples:")
print(subject_marks)
# Python Program to sort List Of Dictionaries using lambda
models = [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': '2', 'color': 'Gold'},
{'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
print("Original list of dictionaries :")
print(models)
sorted_models = sorted(models, key=lambda x: x['color'])
print("\nSorting the List of dictionaries :")
print(sorted_models)
# Write a Python program to filter a list of integers using Lambda
List_Integers = [1, 2, 3, 4, 5, -1, -2, -3, -4, -5]
g_e = list(filter(lambda x: (x > 0), List_Integers))
print(g_e)
# Write a Python program to find if a given string starts with a given character using Lambda.
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Python'))
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Java'))
| true |
413f32f1367a8cbf5183add9771d598e630f9534 | amarinas/algo | /chapter_1_fundamentals/leapyear.py | 484 | 4.21875 | 4 | # write a function that determines whether a given year is a leap year
# if the year is divisible by four, its a leap year
# unless its divisible by 100
# if it is divisible by 400 than it is
def leapyear(year):
if year % 4 == 0:
print "it is a leap year"
elif year % 100 ==0:
print "not a leap year buddy!"
elif year % 400 == 0:
print "it is a leap year"
else:
print "not a leap year"
print(leapyear(1901))
print(leapyear(2000))
| true |
ef06ee1de6b838599b98c1bab5883c595086f514 | amarinas/algo | /Hack_rank_algo/writefunction.py | 304 | 4.1875 | 4 | #Determine if a year is a leap yesar
def is_leap(year):
leap = False
#condition for a leap year
if year % 4 == 0 and year % 400 == 0 or year % 100 != 0:
return True
#return leap if the above condition is false
return leap
year = int(raw_input())
print is_leap(year)
| true |
9554a30f82c858f0aacab04102ba43a7f7057f02 | amarinas/algo | /random_algo_exercise/strings_integers.py | 208 | 4.15625 | 4 | # Read a string,S , and print its integer value; if S cannot be converted to an integer, print Bad String
import sys
S = raw_input().strip()
try:
print(int(S))
except ValueError:
print("Bad String")
| true |
096abdbc6c7a049bbfbc7c8afc516bad0ec5d022 | amarinas/algo | /PlatformAlgo/reversing.py | 474 | 4.65625 | 5 | #Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), write a program that reverses the values in the array. Once your program is done X should be in the reserved order. Do this without creating a temporary array. Also, do NOT use the reverse method but find a way to reverse the values in the array (HINT: swap the first value with the last; second with the second to last and so forth).
def reverse(arr):
return arr[::-1]
print(reverse([-3,5,1,3,2,10]))
| true |
f9bd0cca25a8e163eb84c490e44fc305f3e1dc85 | amarinas/algo | /PlatformAlgo/square_value.py | 477 | 4.21875 | 4 | #Given an array x (e.g. [1,5, 10, -2]), create an algorithm (sets of instructions) that squares each value in the array. When the program is done x should have values that have been squared (e.g. [1, 25, 100, 4]). You're not to use any of the pre-built function in Javascript. You could for example square the value by saying x[i] = x[i] * x[i];
def square(arr):
for i in range(len(arr)):
arr[i] = arr[i] * arr[i]
return arr
print(square([1,5, 10, -2]))
| true |
7f90da219ab5807749f17964bdd7b1ff78b3c1eb | amarinas/algo | /random_algo_exercise/arrays_day7.py | 302 | 4.125 | 4 | # Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers.
from __future__ import print_function
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
for num in arr:
print(num + " ", end='')
| true |
113abd3f4d90aa0b95d135b2b7928b6400738fa1 | amarinas/algo | /PlatformAlgo/iterate_array.py | 394 | 4.3125 | 4 | #Given an array X say [1,3,5,7,9,13], write a program that would iterate through each member of the array and print each value on the screen. Being able to loop through each member of the array is extremely important. Do this over and over (under 2 minutes) before moving on to the next algorithm challenge.
def Iterate_a(arr):
for i in arr:
print i
Iterate_a([1,3,5,7,9,13])
| true |
a06208c839a3331629c2116f667e73a693dc62a9 | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/sort_selection_array_implement.py | 1,878 | 4.34375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sort_selection_array_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status quo.
# You can quote them, disagree with them, glority or vilify
# them. About the only thing you can't do is ignore them.
# Because they change things. They push the human race forward.
# And while some may see them as the creazy ones, we see genius.
# Because the poeple who are crazy enough to think thay can change
# the world, are the ones who do."
#
# Created by Chyi Yaqing on 02/18/19 16:16.
# Copyright © 2019. Chyi Yaqing.
# All rights reserved.
#
# Distributed under terms of the
# MIT
"""
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum
element(considering ascending order)from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
1) The Subarray which is already sorted
2) Remaining subarray which is unsorted
In every iteration of selection sort, the minimum element (considering ascendin
order) from the unsorted subarray is picked and moved to the sorted subarray
"""
# Python program for implementation of Selection Sort
def selectionSort(arr):
for i in range(len(arr)):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Driver code to test above
arr = [64, 25, 12, 22, 11]
print("Original array is : {}".format(arr))
selectionSort(arr)
print("Sorted array is : {}".format(arr))
| true |
3b2d4f6855512f17e98d393348cdf39f855ab739 | lstobie/CP1404_practicals | /prac_03/ASCII.py | 612 | 4.125 | 4 | def main():
LOWER_LIMIT = 33
UPPER_LIMIT = 127
char = input("Enter a character: ")
print("The ASCII code for {} is {}".format(char, ord(char)))
cord = int(input("Enter a number between {} and {}: ".format(LOWER_LIMIT, UPPER_LIMIT)))
if LOWER_LIMIT <= cord <= UPPER_LIMIT:
print("The character for {} is {}".format(cord, chr(cord)))
else:
print("invalid")
for i in range(LOWER_LIMIT, UPPER_LIMIT + 1):
print("{0:>3}{1:>10}".format(i, chr(i)))
# I only know data frames can edit column numbers unless we want an if/elif/elif... code with limits
main()
| true |
967bb21482280ffe1eff1b09ee403dcaac27858d | alexpsimone/other-practice | /repls/anagram_finder.py | 2,072 | 4.1875 | 4 | # anagram finder
# write a function that takes two strings and returns whether or not they are anagrams
# abc cab -> true
# abc abc -> true
# abc abd -> False
# '' '' -> True
# abc1 1abc -> True
# abcd abc -> False
# numbers and letters, no spaces, any length strings
def anagram(x, y):
# if the strings are equal, return True
if x == y:
return True
# if one of the strings is empty, return False
if x == '' or y == '':
return False
# if len(x) != len(y), return False
if len(x) != len(y):
return False
list_x = sorted(x)
list_y = sorted(y)
# loop through each index in x
for idx in range(len(list_x)):
if list_x[idx] != list_y[idx]:
return False
# see if list_x[idx] = list_y[idx]
# if not equal, return False
# return True
return True
def anagram2(x, y):
# if the strings are equal, return True
if x == y:
return True
# if one of the strings is empty, return False
if x == '' or y == '':
return False
# if len(x) != len(y), return False
if len(x) != len(y):
return False
# initialize a dict for x
x_dict = {}
# initialize a dict for y
y_dict = {}
# loop through x
for char in x:
# if char in dict, increment value at char
if char in x_dict:
x_dict[char] += 1
else:
x_dict[char] = 1
# otherwise, initialize a value dict[char]: 1
# do the same things for y
for char in y:
if char in y_dict:
y_dict[char] += 1
else:
y_dict[char] = 1
# loop through each key in x dict
for x_key in x_dict:
# if key not in y_dict, return False
if x_key not in y_dict:
return False
# elif dict[key] != dict[key] return False
elif x_dict[x_key] != y_dict[x_key]:
return False
# else return True
return True
if __name__ == '__main__':
pass | true |
bb40fb86a454d0617480ae24c842a1cd91ca9c7c | erijones/phs | /python/intro/prime_finder.py | 1,815 | 4.40625 | 4 | #!/usr/bin/python3
# This program runs as ./prime_finder (with correct permissions), but
# incorrectly! The program's goal is to list the prime numbers below a certain
# number using the Sieve of Eratosthenes, discovered around 200 BC.
# Run the file, and mess around with the testing area below. Debug and
# troubleshoot with print() messages
# you can import this file into the shell with "import prime_finder" and then
# test individual functions
# end goal:
# ---------
# prime_list(30) returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
import math # so we can use the floor function! called with math.floor(2.33)
# check if 'num' is prime
def is_prime(num):
# to check, we divide num by all numbers less than it. If num is divisible
# by any number, we set flag to False
flag = True
# use is_integer to tell what sort of data type a number is (useful for
# divisibility)
print("ints? ", (4.0).is_integer(), (4.3).is_integer(), '\n')
# can you implement this same line using modulus (%) instead?
for elem in range(1,num):
if elem == 4:
print("elem is 4")
print(elem)
# [print(elem) for elem in range(num)]
# note this is the same as directly above!
return flag # let's say flag = True means prime, flag = False means composite
# return a list of prime numbers less than 'bound'
def prime_list(bound):
# return a list of all of the prime numbers up to
return [elem for elem in range(bound) if elem > 10]
# example test commands
# ------------
print("Is 15 prime?")
print(is_prime(15))
print("All primes under 30:")
print(prime_list(30))
# food for thought:
# -----------------
# how fast does this algorithm run?
# could you improve the speed? do you need to check whether n is divisible by
# every number from 1 to n?
| true |
4885d8d60b7b2245f2bc4c8d398a66e26a5620e9 | noehoro/Python-Data-Structures-and-Algorithms | /Recursion/recursiveMultiply.py | 349 | 4.15625 | 4 | def iterative_multiply(x, y):
results = 0
for i in range(y):
results += x
return results
def recursive_multiply(x, y):
# This cuts down on the total number of
# recursive calls:
if y == 0:
return 0
return x + recursive_multiply(x, y - 1)
x = 500
y = 2000
print(x * y)
print(recursive_multiply(x, y))
| true |
9ea9de95112cbcf5d0c6dc1e87833c67b9602bf1 | prince6635/expert-python-programming | /syntax_best_practices/coroutines.py | 2,417 | 4.1875 | 4 | """
Coroutines:
A coroutine is a function that can be suspended and resumed, and can have multiple entry points.
For example, each coroutine consumes or produces data, then pauses until other data are passed along.
PEP 342 that initiated the new behavior of generators also
provides a full example on how to create a coroutine scheduler.
The pattern is called Trampoline, and can be seen as a mediator between coroutines that produce and consume data.
It works with a queue where coroutines are wired together.
Threading:
Threading is an alternative to coroutines in Python.
It can be used to run an interaction between pieces of code.
But they need to take care of resource locking since they behave in a pre-emptive manner,
whereas coroutines don't.
"""
from __future__ import with_statement
from contextlib import closing
import socket
import multitask
# simple coroutine test
# The multitask module available at PyPI (install it with easy_install multitask)
# if it doesn't work, download .gz, unzip and then install
# $ tar -xzf multitask-0.2.0.tar.gz
# $ cd multitask-0.2.0
# $ python setup.py install
import time
def coroutine1():
for i in range(3):
print 'coroutine1'
yield i
def coroutine2():
for i in range(3):
print 'coroutine2'
yield i
def test_simple_coroutine():
multitask.add(coroutine1())
multitask.add(coroutine2())
multitask.run()
# complicated coroutine test for sockets and server
def client_handler(sock):
with closing(sock):
while True:
data = (yield multitask.recv(sock, 1024))
if not data:
break
yield multitask.send(sock, data)
def echo_server(hostname, port):
addrinfo = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
(family, socktype, proto, canonname, sockaddr) = addrinfo[0]
with closing(socket.socket(family, socktype, proto)) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(sockaddr)
sock.listen(5)
while True:
multitask.add(client_handler((yield multitask.accept(sock))[0]))
def test_complicated_coroutine():
hostname = 'localhost'
port = 1111
multitask.add(echo_server(hostname, port))
multitask.run()
if __name__ == '__main__':
test_simple_coroutine()
test_complicated_coroutine()
| true |
98aefb8c8ae08939ef877e268bfc10a54a0be896 | alancyao/fun-times | /Algorithms/reverse_contiguous_subset_to_sort.py | 794 | 4.21875 | 4 | #!/usr/bin/env python3
""" Problem description:
You have an array of n distinct integers. Determine whether it is possible to sort the array by reversing exactly one contiguous segment of the array. For example, 1 [4 3 2] 5 => 1 [2 3 4] 5.
"""
""" Some variables for testing """
possible = [1, 2, 6, 5, 4, 3, 7, 8]
impossible = [1, 2, 6, 3, 4, 5, 7, 8]
def can_sort_by_reversing_subsegment(arr):
s = sorted(arr)
oop = [x for x in enumerate(arr) if (x[1] != s[x[0]])]
return [x[1] for x in oop[::-1]] == s[oop[0][0]:oop[-1][0]+1]
def main():
print("Array: {}\n Possible: {}".format(possible,
can_sort_by_reversing_subsegment(possible)))
print("Array: {}\n Possible: {}".format(impossible,
can_sort_by_reversing_subsegment(impossible)))
if __name__ == '__main__':
main()
| true |
0e0bbc7c9d542fe1967d7b1fdd36cda4548bf5f7 | nicklambson/pcap | /class/subclass2.py | 460 | 4.28125 | 4 | class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
# super().__init__()
A.__init__(self)
# self.a = 2
self.b = 3
# use super() to access the methods of the parent class
# or A.__init__(self)
# use super().__init__() to initialize from the parent class
# If it's not initialized, b.a will not unless called explicitly from B's __init__()
a = A()
b = B()
print(a.a)
print(b.a)
print(b.b) | true |
3123e526b96d7aa2d5eaaa3e22bc676e127f9307 | nicklambson/pcap | /exceptions/which_exception.py | 419 | 4.125 | 4 | '''
try:
raise Exception
except:
print("c")
except BaseException:
print("a")
except Exception:
print("b")
'''
# error: default except: must be last
try:
raise Exception
except BaseException:
print("a")
except Exception:
print("b")
except:
print("c")
# a
try:
raise Exception
except BaseException:
print("a", end='')
else:
print("b", end='')
finally:
print("c")
# ac
| true |
e616966a28dbd8bbd905ecba525b13c87ce2980d | deelm7478/CTI110 | /P4T2_BugCollector_MathewDeel.py | 602 | 4.3125 | 4 | # Collects and displays the number of bugs collected.
# 10/15/18
# CTI-110 P4T2 - Bug Collector
# Mathew Deel
#
def main():
#Initialize the accumulator
total = 0
#Get the bugs collected for each day.
for day in range(1, 6):
#Prompt user for amount of bugs that day
print('Enter the bugs collected on day', day)
#User must input number of bugs
bugs = int(input())
#Gets the total for the week
total += bugs
#Display the total bugs.
print('You collected a total of', total, 'bugs.')
main()
| true |
9583849c3077e5aeefc86c503f69043286d0edf9 | amit70/Python-Interview-Examples | /isPower2.py | 481 | 4.28125 | 4 | #Given an integer, write a function to determine if it is a power of two.
def isPower(n):
# Base case
if (n <= 1):
return True
# Try all numbers from 2 to sqrt(n)
# as base
for x in range(2, (int)(math.sqrt(n)) + 1):
p = x
# Keep multiplying p with x while
# is smaller than or equal to x
while (p <= n):
p = p * x
if (p == n):
return True
return False
print isPower(8)
| true |
134d690ef5727cce192900151ddb83c8d67b73b8 | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReverseString.py | 1,183 | 4.6875 | 5 | # Implement a program to reverse a string.
# Follow up: Write a function to reverse an array of characters in place. "In place" means "without creating a new string in memory."
def reverseString(inputStr):
reversed = ""
for i in range(len(inputStr)-1,-1,-1):
reversed = reversed + inputStr[i]
return reversed
def reverseStringInPlace(inputStr):
# python strings are immutable. i.e. once we create a string, we cannot change it.
# To solve the problem, convert the string in to a list of characters and reverse the list in place.
# Then join all the characters in the list to get the reversed string
listOfChar = [] # create a list of characters from the inputStr.
listOfChar.extend(inputStr)
temp = ''
i=0
j=len(listOfChar)-1
while(i<j):
temp = listOfChar[i]
listOfChar[i] = listOfChar[j]
listOfChar[j] = temp
i = i+1
j = j-1
inputStr = ''.join(listOfChar)
return inputStr
def main():
user_input = input("Enter a string: ")
print "You entered: ",user_input
result1 = reverseString(user_input)
print "Reversed string: ",result1
result2 = reverseStringInPlace(user_input)
print "Reversed string: ",result2
if __name__ == "__main__":
main() | true |
d8c39538141f5d4065f9a6c89a0b438d66648a9e | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReplaceAllSpaces.py | 749 | 4.4375 | 4 | # Write a method to replace all spaces in a string with '%20'. Assume that the string has sufficient space at the end of the string to hold the additional characters
# and that you are given the true length of the string.
# E.g. Input: "Mr John Smith ", 13
# Output: "Mr%20John%20Smith"
def replaceAllSpaces(input):
newString = ""
# Find each space in the input string. Replace it with '%20'.
for i in range(0,len(input)):
if(input[i] == " "):
newString = newString + "%20"
else:
newString = newString + input[i]
return newString
def main():
user_input = input("Enter a string: " )
print "You entered: ", user_input
result = replaceAllSpaces(user_input)
print "Result is: ",result
if __name__ == "__main__":
main()
| true |
f90911ff384b918a697fd987bf4e12b814bbc92c | jananee009/DataStructures_And_Algorithms | /Miscellaneous/Parentheticals.py | 1,984 | 4.125 | 4 | # Write a function that, given a sentence, , finds the position of an opening parenthesis and the corresponding closing parenthesis.
# Source: https://www.interviewcake.com/question/python/matching-parens?utm_source=weekly_email&__s=ibuidbvzaa2i67rfb2mc
# Approach: 1. Process the string character by character.
# We can solve the problem using a dictionary and a stack (list).
# 2. As you encounter a parentheses, check if it is opening or closing one:
# 3. If it is opening one, find its position in the string and store it as a key in the dictionary.
# Push the position of the last found open parentheses in to a stack.
# At any point in time, the position of the most recently found open parentheses can be obtained by popping the stack.
# 4. else if parentheses is a closing one:
# pop the stack. i.e. get the position of the open parentheses that was most recently found and for which the corresponding closing parentheses was not found.
# store the position of the closing parentheses as value for the key whose value is same as the popped value.
# this method uses a dictionary and a list to find the positions of opening and corresponding closing parentheses.
def findParentheses(inputString):
last_found_open_parentheses = [] # this will be used like a stack.
parentheses_dict = {}
for index, character in enumerate(inputString):
if character == "(":
parentheses_dict[index] = -1
last_found_open_parentheses.append(index)
elif character == ")":
if last_found_open_parentheses: # if last_found_open_parentheses is not empty
parentheses_dict[last_found_open_parentheses[-1]] = index
del last_found_open_parentheses[-1]
else:
print "String with invalid parentheses"
return
return parentheses_dict
def main():
sentence = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
print findParentheses(sentence)
if __name__ == "__main__":
main()
| true |
89167fe59613bc1eba62d18d09deea19c0bad38f | jananee009/DataStructures_And_Algorithms | /Stacks_And_Queues/Stack.py | 1,046 | 4.25 | 4 | # Write a program to implement a stack (LIFO). Implement the operations : push, pop, peek.
class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
if(len(self.stack)==0):
return True
else:
return False
def push(self,element):
self.stack.append(element)
def pop(self):
if(len(self.stack)==0):
print "Empty!! Nothing to pop."
return
tmp = self.stack[len(self.stack)-1]
del self.stack[len(self.stack)-1]
return tmp
def peek(self):
if(len(self.stack)==0):
return "Empty stack."
return self.stack[len(self.stack)-1]
def getSize(self):
return len(self.stack)
def printStack(self):
print "printing elements:"
for i in range(len(self.stack)-1,-1,-1):
print self.stack[i]
return
def main():
myStack = Stack()
myStack.push(10)
myStack.push(20)
myStack.isEmpty()
myStack.getSize()
myStack.push(30)
myStack.peek()
myStack.pop()
myStack.peek()
myStack.pop()
myStack.pop()
myStack.pop()
myStack.isEmpty()
myStack.getSize()
if __name__ == "__main__":
main()
| true |
95c1d47ade4d105851b29eb1bbacf6231d188fbd | GuND0Wn151/Python_OOP | /13_MagicMethods_1.py | 1,670 | 4.4375 | 4 | #C0d3 n0=13
#made By GuND0Wn151
"""
there are some methods in python class
Magic methods in Python are the special methods which add "magic"
to your class. Magic methods are not
meant to be invoked directly by you, but the invocation happens
internally from the class on a certain action.
"""
"""
The below is example of overloading the arthematic methods like addition subtraction etc
whihc also returns a object of that class
"""
class Point:
x=0
y=0
def __init__(self,a,b):
self.x=a
self.y=b
def __add__(self,a):
return Point(self.x+a.x ,self.y+a.y)
def __sub__(self,a):
return Point(self.x-a.x ,self.y-a.y)
def __mul__(self,a):
return Point(self.x*a.x ,self.y*a.y)
def __floordiv__(self,a):
return Point(self.x/a.x ,self.y/a.y)
def displayDetails(self):
print("X:",self.x,', Y:',self.y)
a=Point(2,3)
b=Point(4,6)
# here + will invoke the overloaded __add__ method in the class and return a object of type Point
f=a+b
# here - will invoke the overloaded __sub__ method in the class and return a object of type Point
g=a-b
# here * will invoke the overloaded __mul__ method in the class and return a object of type Point
h=a*b
# here // will invoke the overloaded __floordiv__ method in the class and return a object of type Point
i=a//b
"""
the return type of the overloaded arthematic options are Point
so we acces them with the method displayDetails
"""
print(type(f))
f.displayDetails()
print(type(g))
g.displayDetails()
print(type(h))
h.displayDetails()
print(type(i))
i.displayDetails()
| true |
53f18b79d98cfc5fb94bc561d54248cb33c62165 | GuND0Wn151/Python_OOP | /10_Getter.py | 609 | 4.28125 | 4 | #C0d3 n0=10
#made By GuND0Wn151
'''
The getattr() method retu
the value of the named attribute of an object.
If not found, it returns the default value provided to the function.
'''
class person:
legs=2
hands=2
hair_color='black'
def __init__(self,a):
self.name=a
person1=person("kevin")
#usual syntax of accesing elements
print(person1.legs)
print(person1.hands)
print(person1.hair_color)
#using getter method
print(getattr(person1,"legs"))
print(getattr(person1,"hands","legs"))
#if used for a unknown attributes throws AttributeError
print(getattr(person1,"age")) | true |
28719c5fed80810c43c3376758b82f851f56a05b | DAVIDMIGWI/python | /lesson 3b.py | 399 | 4.15625 | 4 |
a = 40
b = 50
c = 500
if a > b:
print("A is greater than B")
if a > c:
print("A is also greater than C")
else:
print("A is not greater than C")
if c > b:
print("C is the largest")
else:
print("A is the largest")
else:
if b > c:
print("B is greater")
else:
print("its C")
| true |
369d0f3e749c5419d5e40d9e41f3db3a43c946b7 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/05_lists.py | 1,707 | 4.625 | 5 | # For the exercise,
# look up the methods and functions that are available for use with Python lists.
# An array can only have one data type, list can have multiple data types.
# If you want to add to an array you have to create a new array twice the size of
# the one you have, taking up more space.
# You need to use numpy to use arrays or it will just be a list in python.
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] ## #
x.append(4)
print(x)
# ## Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] ## #
x.extend(y) # Best practice
# print(x + y) # Throws error with `pop` function below
# x = x + y # |
# print(x) # --> These 2 lines are another way to do the same
# ## Change x so that it is [1, 2, 3, 4, 9, 10] ## #
x.pop(4) # pop(index #) <-- Best practices if you know the index location
# x.pop(-3) # Counting backwards from the end of the index
# x.pop(x.index(8)) # gets the index if unknown, then "pops" it off
# x.remove(8) # computationally more expense but works if index unknown
print(x)
# ## Change x so that it is [1, 2, 3, 4, 9, 99, 10] ## #
x.insert(5, 99) # insert(<index place where to insert>, <value>)
print(x)
# ## Print the length of list x ## #
print(len(x))
# ## Print all the values in x multiplied by 1000 ## #
# Using a for loop will print each number individually
# for num in x:
# print(num * 1000)
# Same thing as above but in List Comprehension which will
# print it as a list - similar to .map in JavaScript
x = [num * 1000 for num in x]
print(x)
# Can also do it as a list of strings instead of integers:
# x = [str(num * 1000) for num in x]
# print (x)
| true |
2589aa703538ead00de18c0b828a84f27aeb16c1 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/14_cal.py | 2,934 | 4.59375 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
# ## My Code ## #
import sys
import calendar as cal
from datetime import datetime as dt
# Create variable to hold today's date
today = dt.today()
# Get the user's input from the command line and check edge cases
# If user enters all required inputs in the command line
if len(sys.argv) == 3:
# Convert user input to ints and return the calender month and year
print(cal.TextCalendar().formatmonth(int(sys.argv[2]), int(sys.argv[1])))
sys.exit(0) # Exits the program
# If the user only enters one argument, such as month but not year or vise versa
elif len(sys.argv) == 2:
# Return current in place of missing value from user input
if int(sys.argv[1]) in range(12):
print(cal.TextCalendar().formatmonth(today.year, int(sys.argv[1])))
sys.exit(0) # Exits the program
elif int(sys.argv[1]) in range(1000, 2021):
print('Year', int(sys.argv[1]))
print(cal.TextCalendar().formatmonth(int(sys.argv[1]), today.month))
sys.exit(0) # Exits the program
# If the user does not enter and arguments in the command line
if len(sys.argv) == 1:
# Return current month and year
print(cal.TextCalendar().formatmonth(today.year, today.month))
sys.exit(0) # Exits the program
# If user enters an invalid format
else:
print('Usage: 14_cal.py [month number] [year]') # Return usage statement
sys.exit(1) # Exit the program
# # ## Ava's Code ## #
# import sys
# import calendar
# from datetime import datetime
#
#
#
#
# # ## Fatima's code: ## #
# # import sys
# # import calendar
# # from datetime import datetime
# #
# # date = datetime.now() | true |
d86a00d4050862b4e14da77ed994e90595b5e40a | Paahn/practice_python | /reverse_word_order.py | 265 | 4.34375 | 4 | # Write a program that asks the user
# for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
a = input("Gimme a string containing multiple words:\n")
b = a.split(' ')
print(b[::-1])
| true |
7588d9c2400c665eb0be8ca319c3dc17f03ec568 | Paahn/practice_python | /guessing_game.py | 997 | 4.375 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low,
# too high, or exactly right.
# Keep the game going until the user types “exit”
# Keep track of how many guesses the user has taken, and when the game ends, print this out.
from random import randint
a = randint(1, 9)
ans = int(input("Guess a number between 1 and 9: "))
guesses = 0
while True:
try:
if ans == a and guesses == 0:
print("Wow! You got it right the first time!")
break
elif ans < a:
guesses += 1
ans = int(input("Too low. Guess again."))
elif ans > a:
guesses += 1
ans = int(input("Too high. Guess again."))
else:
guesses += 1
print("You guessed right! It only took you {} times.".format(guesses))
break
except ValueError:
print("Try again")
| true |
47717a3918ae9d4522508d3125763b31c3298a4d | elenaozdemir/Python_bootcamp | /Week 1/Day Two/Practicing with lists & functions.py | 747 | 4.53125 | 5 | # practicing with lists and functions
# EXAMPLE: Define a function that returns a list of even numbers
# between A and B (inclusive)
def find_events(A,B):
# make an empty list to return to something
evens = []
for nums in range (A,B+1): #inclusive
if (nums % 2 == 0):
evens.append(nums)
return evens
print(find_events(2,20))
# TODO: Define a function that returns a list of numbers between A and B (inclusive) that are multiples of 3
def list_num(A,B):
numlist = []
for numbers in range (A,B+1):
if (numbers % 2 == 0) and (numbers % 3 == 0): # or you can just do (numbers % 6 == 0), even multiples of 2 and 3
numlist.append(numbers)
return numlist
print(list_num(3,20))
| true |
4c5a3b9f23c9910631860938ce17e86c87a31939 | SBenkhelfaSparta/eng89_python_basics | /string_casting_concatenation.py | 1,567 | 4.34375 | 4 | # using and managing strings
# strings casting
# string concatenation
# Casting methods
# Single and double quotes
single_quotes = 'These are single quotes and working perfectly fine!'
double_quotes = "These are double quotes also working fine"
# print(single_quotes)
# print(double_quotes)
# concatenation
# first_name = "James"
# last_name = "Bond"
# age = 22
# print(type(age))
# print(type(str(age)))
# create a variable called ge with int val and display age on the same line as james bond
# print(first_name + ' ' + last_name + ' ' + str(age))
# 01234567891011
# greetings = "Hello World"
#-1
# in python indexing start with 0
# print(greetings)
# to confrirm the length of the string as a method is len()
# print(len(greetings))
# print(greetings[0:5]) # slicing# the string from index 0 - 4 upto but not including 5
# print(greetings[-1]) # slicing string from the last index position
# print(greetings[6:])
# print(greetings[-5:])
# white_spaces = "Lots of white spaces "
# we have strip() tgat removes all the whire spaces
#print(str(len(white_spaces)) + 'including white spaces')
# some more built in methods that we can use with strings
example_text = " here's some text with lots of text"
print(example_text.count('text')) #count() method count the word in string
print(example_text.lower()) # brings everything to lower case
print(example_text.upper()) #brings everything to upper case
print(example_text.capitalize()) #capatilsises the first letter
print(example_text.replace('with', ',')) | true |
95a2ee3b58d7fdf3e0bcc499b37b7bfa59a286b6 | Ms-Noxolo/Predict-Team-7 | /EskomFunctions/function3.py | 591 | 4.375 | 4 | def date_parser(dates):
""" This function returns a list of strings where each element in the returned list contains only the date
Example
-------
Input: ['2019-11-29 12:50:54',
'2019-11-29 12:46:53',
'2019-11-29 12:46:10']
Output: ['2019-11-29', '2019-11-29', '2019-11-29']
"""
c = [] # initialize an empty list
for i in dates:
i = i[:10] # the date from the datetime string is only made up of 9 characters
c.append(i) # Adds items to the list c
return c #return list c
| true |
813a5288fc26121aee0081f4b9ab131a2190e321 | aprabhu84/PythonBasics | /Methods and Functions/Level 1/03_Makes_Twenty.py | 473 | 4.15625 | 4 | #MAKES TWENTY:
# -- Given two integers,
# -- return True if the sum of the integers is 20
# -- or if one of the integers is 20.
# -- If not, return False
#makes_twenty(20,10) --> True
#makes_twenty(12,8) --> True
#makes_twenty(2,3) --> False
def makes_twenty(number1, number2):
int_num1 = int(number1)
int_num2 = int(number2)
if (int_num1 == 20) or (int_num2 == 20) or (int_num1+int_num2 == 20):
return True
else:
return False
| true |
f751e02345f05a8f287ff20671542153c6e88cac | aprabhu84/PythonBasics | /Methods and Functions/Level 2/02_Paper_Doll.py | 394 | 4.15625 | 4 | # PAPER DOLL: Given a string, return a string where for every character in the original there are three characters
# paper_doll('Hello') --> 'HHHeeellllllooo'
# paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
def paper_doll(someString):
resultString = ""
for pos in range(0,len(someString)):
resultString = resultString + someString[pos]*3
return resultString
| true |
46be0a96d81cb8c48dc94ab9a2883c6ffdbaddd8 | Aleksandraboy/basics | /nesting.py | 2,894 | 4.5 | 4 | # 03/20/21
# 1. A List of Lists
# 2. A List of Dictionary
# 3. A List in a Dictionary
# 4. A Dictionary in a Dictionary
print('*** 1. A List of Lists***')
countries = ['usa', 'russia', 'spain', 'france']
cities = ['new york', 'moscow', 'barcelona', 'paris']
companies = ['level up', 'abc company', 'ola company']
customers = [countries, cities, companies]
print(customers)
print(customers[0]) # printing all countries. since countries has index '0'
print(customers[0][0]) # printing 'usa', since countries index [0] and index of 'usa' also [0]
print(customers[1][2]) # printing the 'Barcelona'
multi_dim_nums = [
[3, 9, 0],
[2, 7, 10],
[0, 1, 0]
] # multidimensional (многомерный)
print(multi_dim_nums[1][1]) # printing the number '7'
print("***Nested Loops: Looping through multidimensional list(array)***")
for column in customers: #
print(column)
for value in column:
print(value)
print('******')
# for customer in customers[0][1]:
# print(customer, end='\t')
print(customers[0][1].upper())
print('***** 2. List of dictionaries')
user_0 = {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'}
user_1 = {'name': 'jane', 'age' : 20, 'city' : 'paris'}
user_2 = {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
users = [user_1, user_0, user_2]
print(users[0])
print(users[0]['name'])
print(users[0]['age'])
print(users[0]['city'])
print(users[2]['name'])
print("******** Looping****")
for user in users:
print(user['name'], end='||')
print(user['age'], end='||' )
print(user['city'])
print('***** 3. A List in a Dictionary ***** ')
countries = ['usa', 'russia', 'spain', 'france']
cities = ['new york', 'moscow', 'barcelona', 'paris']
companies = ['level up', 'abc company', 'ola company']
customers = {
"countries" : ['usa', 'russia', 'spain', 'france'],
"cities" : ['new york', 'moscow', 'barcelona', 'paris'],
"companies" : ['level up', 'abc company', 'ola company']
}
print(customers['cities'])
print(customers['cities'][1]) # second element from cities
print('***** 4. A Dictionary in a Dictionary *****')
user_0 = {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'}
user_1 = {'name': 'jane', 'age' : 20, 'city' : 'paris'}
user_2 = {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
users = {
'user_0' : {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'},
'user_1' : {'name': 'jane', 'age' : 20, 'city' : 'paris'},
'user_2' : {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
}
print(users)
print(users['user_0'])
print(users['user_0']['name'])
print("***keys***")
for user in users.keys():
print(user)
print(users[user])
print("**items***")
for username, details in users.items():
print(username)
print(details['name'])
print("***items(key, value)***")
for username, details in users.items():
print(username)
for key, value in details.items():
print(key)
print(value)
| true |
20127e1855c3307e7b25812eccb46818d7db4609 | JoseVteEsteve/Lists | /LI_03.py | 289 | 4.1875 | 4 | #given a list of numbers, find and print all the elements that are greater than the previous element.
list = [1,3,7,9,2,4,11,10,8,5,14,16]
n = len(list)
max = 0
for i in range(n):
if list[i] > list[i - 1]:
print(str(list[i]) + " is greater than " + str(list[i - 1]))
| true |
a3d204581bd24365e6ebb3ce7fb1d750e795237f | tieje/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 240 | 4.1875 | 4 | #!/usr/bin/python3
"""This module reads a text file"""
def read_file(filename=""):
"""This method reads a file."""
with open(filename, mode="r", encoding="utf_8") as file:
for line in file:
print(line, end='')
| true |
32040098ac2f626214124dab1cc919b8aebd8eb9 | GaryGonzenbach/python-exercises | /control_structures_examples.py | 1,991 | 4.3125 | 4 | print('Good Morning Ada!')
i_like_coffee = True # switch to False to test else
if i_like_coffee:
print('I like coffee!')
else:
print('Ok - lets have some tea')
# ---
pizza_reference = input('What kind of pizza do you like?')
if pizza_reference == 'pineapple and hot sauce':
print('Wow - what a coincidence!')
# spicy_level = int(input('How spicy would you like it? (1-5)'))
elif pizza_reference == 'pepperoni and chocolate':
print('hmmm... ok')
elif pizza_reference == 'cheese':
print('Plain cheese, ok!')
else:
print('Not my favorite, but lets order some!')
# -
print('Ok - Done ordering pizza')
# -----------------------------------
# 1. prompt the user for a day of the week, print out whether the day is Monday or not
day_of_the_week = input('What day of the week is it?')
if day_of_the_week.lower() == 'monday' or day_of_the_week == 'mon':
print('Happy Monday!')
else:
print('At least its not Monday')
# 2. prompt the user for a day of the week, print out whether the day is a weekday or a weekend
weekend_list = ['saturday', 'sat', 'sunday', 'sun']
if day_of_the_week.lower() in weekend_list:
print('Great, its the weekend! ')
else:
print('another workday')
# 3. create variables for
# - the number of hour worked in one week
# - the hourly rate
number_of_hours_per_week = -1
hourly_rate = -1
while number_of_hours_per_week < 1 or number_of_hours_per_week > 150:
number_of_hours_per_week = int(input('How many hours did you work this week (1-150)?'))
while hourly_rate < 1 or hourly_rate > 2000:
hourly_rate = int(input('How much do you make an hour?'))
# - how much the week's paycheck will be
# write the python code that calculates the weekly paycheck. You get paid time
# and a half if you work more than 40 hours
if number_of_hours_per_week > 40:
paycheck = ((number_of_hours_per_week - 40) * (1.5 * hourly_rate)) + (40 * hourly_rate)
else:
paycheck = (40 * hourly_rate)
print('You paycheck will be ', paycheck)
| true |
b27acfbc54aeae4b5741ed27fa849e09d9c8a46a | skyrydberg/LPTHW | /ex3/ex3.py | 1,251 | 4.25 | 4 | # Exercise 3: Numbers and Math
# I addressed Exercises 1 & 2 in the same post because they
# are trivial. This one gets its own post.
print "I will now count my chickens:"
# Note the order of operations holds here, a kind programmer
# would type this 25 + (30 / 6) for clarity, we divide 30 by 6
# and then add the result to 25
print "Hens", 25 + 30 / 6
# Similarly 100 - ((25 * 3) % 4), we multiply 25 by 3 and then
# divide by 4 and take the remainder, which we then subtract
# from 100
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
# And again 3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6 or more
# realistically you'd split this across a couple lines...
# Regardless, we divide 1 by 4 and divide 4 by 2 and keep the
# remainder then we sum across. Note per Study Drill 3 I've
# replaced 1 with 1.0 to force python to evaluate the values
# as floating point numbers instead of integers
print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
618535ad2c3d769521c1a60f73b2e37f26ee5cc3 | GaddamMS/PythonMoshYT | /own_program_weather_notify_0.py | 1,481 | 4.4375 | 4 | '''Feature: Intimate user with precautions based on weather when going outside
Problem Statement: We should identify the weather and tell the user of necessary precautions
Solution:
1. We will ask the user for temperature
2. Based on the given temperature, we will intimate user with self - defined precautions
'''
temperature = int(input('What is the temperature (in centigrade) outside now?'))
# if type(temperature) is int or type(temperature) is float:
# else :
# print('I am expecting the temperature and nothing else')
if temperature < 0:
print('It is freezing outside. Prefer staying indoor unless it is an emergency.')
elif temperature in range (1,14):
print('Use a thick, furry coat and shoes to go outside. Carry an umbrella if possible')
elif temperature in range (15,24):
print('Use a furry coat and shoes to go outside. You should be loving the weather today.')
elif temperature in range (24,30):
print('Damn! Your lucky day')
elif temperature in range (30,45):
print('Cotton clothes are the best for this weather. Avoid black colour. '
'Wear as lite as possible. Carry an umbrella')
elif temperature in range (45,60):
print('You must stay indoors. Possibilities of heat stroke and going to an ER')
elif temperature in range (60,75):
print('rush! Switch ON your air conditioner right away')
elif temperature > 75:
print('You are Kentucky Fried Chicken!')
else:
print('Nasty You! Enter the temperature correctly') | true |
7b28907cfd5737677e3d0380f631272847cfe936 | monsybr11/FirstCodingAttempts | /textrealiser.py | 535 | 4.21875 | 4 | abc = input("Type any text in.\n")
abc = str(abc) # converting the input to a string in case of text and digits being used.
if abc.islower() is True:
print("the text is lowercase!")
if abc.isupper() is True:
print("the text is Uppercase!")
if abc.isupper() is False and abc.islower() is False and abc.isnumeric() is False and abc.isdigit() is False:
print("The text is mixed!!!") # so many "and" uses to make sure that one output is chosen.
if abc.isnumeric() is True:
print("these are numbers!")
| true |
095c16d2e25fe3e5d076ea09bad8b18c0e0e140a | SastreSergio/Datacademy | /paper_scissors.py | 2,815 | 4.1875 | 4 | #A game of Scissors, paper and stone against the machine
import random
def choice_player2(): #Function with random for the other player, in this case: the machine
options = ['Scissors', 'Paper', 'Stone']
random_choice = random.choice(options)
return random_choice
def play(choice_player1, choice_player2):
print('One two three scissors, paper and stone!')
if choice_player1 == 'Scissors' and choice_player2 == 'Paper':
print(f'{choice_player1} against {choice_player2}')
print('Player 1 wins')
elif choice_player1 == 'Scissors' and choice_player2 == 'Stone':
print(f'{choice_player1} against {choice_player2}')
print('The machine wins')
elif choice_player1 == 'Scissors' and choice_player2 == 'Scissors':
print(f'{choice_player1} against {choice_player2}')
print('It is a draw!')
elif choice_player1 == 'Paper' and choice_player2 == 'Stone':
print(f'{choice_player1} against {choice_player2}')
print('Player 1 wins')
elif choice_player1 == 'Paper' and choice_player2 == 'Scissors':
print(f'{choice_player1} against {choice_player2}')
print('The machine wins')
elif choice_player1 == 'Paper' and choice_player2 == 'Paper':
print(f'{choice_player1} against {choice_player2}')
print('It is a draw!')
elif choice_player1 == 'Stone' and choice_player2 == 'Scissors':
print(f'{choice_player1} against {choice_player2}')
print('Player 1 wins')
elif choice_player1 == 'Stone' and choice_player2 == 'Paper':
print(f'{choice_player1} against {choice_player2}')
print('The machine wins')
elif choice_player1 == 'Stone' and choice_player2 == 'Stone':
print(f'{choice_player1} against {choice_player2}')
print('It is a draw!')
def run():
## Initialization
print('Welcome to Scissors, Paper and Stone!')
choice_player1 = input('What do you choose? Scissors, Paper or Stone? -> ')
##Verification process
if choice_player1 == "Scissors" or choice_player1 == "scissors":
choice_player1 = choice_player1.capitalize()
print(f'You have chosen {choice_player1}')
elif choice_player1 == "Paper" or choice_player1 == "paper":
choice_player1 = choice_player1.capitalize()
print(f'You have chosen {choice_player1}')
elif choice_player1 == "Stone" or choice_player1 == "stone":
choice_player1 = choice_player1.capitalize() #Capitalize first letter
print(f'You have chosen {choice_player1}')
else:
print('Please, write a valid option')
run()
## Player 2 choice ( The machine chooses randomly)
player2 = choice_player2()
## Playing the game
play(choice_player1, player2)
if __name__ == '__main__':
run() | true |
27804af36166140fc6655be1c6fd1f60096f34ef | vickiedge/cp1404practicals | /prac_04/quick_picks.py | 584 | 4.125 | 4 | #relied heavily on solution for this exercise. Still not printing all quick picks
import random
MIN_NUMBER = 1
MAX_NUMBER = 45
NUMBER_PER_LINE = 6
number_of_quick_picks = int(input("How many quick picks? "))
for i in range(number_of_quick_picks):
quick_pick = []
for j in range(NUMBER_PER_LINE):
number = random.randint(MIN_NUMBER, MAX_NUMBER)
while number in quick_pick:
number = random.randint(MIN_NUMBER, MAX_NUMBER)
quick_pick.append(number)
quick_pick.sort()
print("".join("{:3}".format(number) for number in quick_pick))
| true |
11ed3a0ab634d3fc1568dbfb38c9d9aff5aced21 | introprogramming/exercises | /exercises/fibonacci/fibonacci-iterative.py | 735 | 4.25 | 4 | '''An iterative version, perhaps more intuitive for beginners.'''
input = int(input("Enter a number: "))
def fibonacci_n(stop_after):
"""Iteratively searches for the N-th fibonacci number"""
if stop_after <= 0:
return 0
if stop_after <= 2:
return 1
prev = 1
curr = 1
count = 2
while count <= stop_after:
curr = curr + prev
prev = curr - prev
count = count + 1
return prev
def next_fibonacci(stop_after):
"""Iteratively searches for the fibonacci number that
comes after the stop_after value"""
prev = 0
curr = 1
while prev <= stop_after:
curr += prev
prev = curr - prev
return prev
print(next_fibonacci(input))
| true |
e435dd76259d6ad09b57f30f5b8b3647f565b086 | shea7073/Algorithm_Practice | /phone_number.py | 495 | 4.28125 | 4 | # Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string
# of those numbers in the form of a phone number.
def create_phone_number(arr):
if len(arr) != 10:
return ValueError('Array Must be 10 digits long!')
for i in arr:
if i > 9 or i < 0:
return ValueError('Phone numbers only except 0-9')
return '({}{}{}) {}{}{}-{}{}{}{}'.format(*arr)
print(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
| true |
dd7aa50d126ddab75b24da79f3b0ac1b0d61bcf3 | gy09/python-learning-repo | /PythonLearning/FunctionLearning/forLoop.py | 290 | 4.15625 | 4 | def upperConversion():
sentence = input("Enter the sentence to loop on:")
for word in sentence:
print(word.upper())
def listLoop():
friends = ["test1","test2","test3","test4"]
for friend in friends:
print(friend.upper())
upperConversion()
listLoop()
| true |
c2853f4bd7682ed91b22dd8040e727299bff2b52 | vharmers/Kn0ckKn0ck | /Parsing/Readers/Reader.py | 1,416 | 4.1875 | 4 | import abc
class Reader:
"""
Abstract class which defines the minimal functionality of Readers. You will need to extend from tis class
if you want to create your own reader.
"""
def __init__(self):
pass
@abc.abstractmethod
def get_count(self):
"""
Gets the amount of items in this Reader.
:return: amount of items (int)
"""
return
@abc.abstractmethod
def get_value(self, value_name, index):
"""
Get a value from the reader.
:param value_name: The name of the value
:param index: The index of the value
:return: The value with the given value name at the given index. Example get_value('Age', 0) -> 25
"""
return
@abc.abstractmethod
def value_exists(self, value_name):
"""
Checks if the given value name exists.
:param value_name: The value name to check
:return: True if the given value name exists in the Reader and False otherwise
"""
return
@abc.abstractmethod
def get_item(self, index):
"""
Get a dictionary with values and their names at a given index.
:param index: Index of the values you want
:return: A list with values. Example: ['Name': 'John', 'Surname': 'Doe', 'Age': 25]
"""
return
| true |
f2e3ddcbfedf9b3860590b28dbfd032e106e9390 | aayush2906/learning_curve | /for.py | 559 | 4.34375 | 4 | '''
You are given a number N, you need to print its multiplication table.
'''
{
#Initial Template for Python 3
//Position this line where user code will be pasted.
def main():
testcases=int(input()) #testcases
while(testcases>0):
numbah=int(input())
multiplicationTable(numbah)
print()
testcases-=1
if __name__=='__main__':
main()
}
def multiplicationTable(N):
for i in range(1,11): ## i in range(x,y,z) means i goes from x to y-1 and increments z steps in each iteration
print(i*N, end=" ")
| true |
a4e7ded1eac764352cb65888ba36ef4289bd6c4b | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/lecture09/python/stack.py | 1,661 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.prev = None
class StackLinkedList:
"""
linked list implementation of stack
- similar to singly linked list
"""
def __init__(self):
self.top = None
def push(self, data):
"""
add element to top of stack, O(1)
"""
if not self.top:
self.top = Node(data)
else:
node = Node(data)
node.prev = self.top
self.top = node
def pop(self):
"""
pop element from top of stack, O(1)
"""
if not self.top:
raise Exception("Cannot pop from empty stack")
data = self.top.data
self.top = self.top.prev
return data
def __str__(self):
"""
string representation of stack
"""
s = ""
node = self.top
while node is not None:
s += str(node.data) + " "
node = node.prev
return s
class StackArrayList:
"""
array list implementation of stack
"""
def __init__(self):
self.arr = []
def push(self, data):
self.arr.insert(0, data)
def pop(self):
return self.arr.pop(0)
def __str__(self):
return str(self.arr)
if __name__ == "__main__":
stack = StackLinkedList()
stack.push(5)
stack.push(3)
stack.push(7)
print(str(stack)) # 7, 3, 5
stack.pop()
print(str(stack)) # 3, 5
stack = StackArrayList()
stack.push(5)
stack.push(3)
stack.push(7)
print(str(stack)) # 7, 3, 5
stack.pop()
print(str(stack)) # 3, 5
| true |
9a044231cb1d922651e6b3463e5f3696cf7b18af | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/question6.py | 892 | 4.1875 | 4 | """
write an algorithm that gets a tree and computes its
depth using iterative implementation.
"""
"""
write an algorithm that gets a tree and computes its size
using iterative implementation.
"""
from binary_tree import build_tree1, build_tree2, build_tree3
def get_depth(bt):
"""
use level-order iterative algorithm
"""
max_depth = 0
q = [(bt.root, 1)]
while q:
node, depth = q.pop(0)
max_depth = max(depth, max_depth)
if node.left is not None:
q.append((node.left, depth + 1))
if node.right is not None:
q.append((node.right, depth + 1))
return max_depth
if __name__ == "__main__":
# test tree1
tree1 = build_tree1()
print(get_depth(tree1))
# test tree2
tree2 = build_tree2()
print(get_depth(tree2))
# test tree3
tree3 = build_tree3()
print(get_depth(tree3))
| true |
3875d9590a0a90962b5680329c571b9e300d4540 | Pranav2507/My-caption-project | /project 2.py | 398 | 4.125 | 4 | filename=input('Enter a filename: ')
index=0
for i in range(len(filename)):
if filename[i]=='.':
index=i
print(filename[index+1: ])
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
fn= input("Enter Filename: ")
f = fn.split(".")
print ("Extension of the file is : " + f[-1])
| true |
aba6611d825897b03b9d9c4a7adca8f2e6b66c69 | uniite/anagram_finder | /modules/util.py | 449 | 4.125 | 4 | import string
def remove_punctuation(word):
"""
Return the given word without any punctuation:
>>> remove_punctuation("that's cool")
'thatscool'
"""
return "".join([c for c in word if c in string.ascii_letters])
def save_anagram_sets(sets, output_file):
"""
Save the given list of anagram_sets to the specified file or file-like object.
"""
for s in sets:
output_file.write(",".join(s) + "\n")
| true |
5d8b5f6d8436b68596e79fd29672031d4e0fbd03 | kwstu/Algorithms-and-Data-Structures | /BubbleSort.py | 443 | 4.15625 | 4 | def bubble_sort(arr):
# Go over every element (arranged backwards)
for n in range(len(arr)-1,0,-1):
# For -1 each time beacuse each loop an elemnt will be set in position.
for k in range(n):
# Check with the rest of the unset elements if they are greater than one another if so, switch
if arr[k]>arr[k+1]:
temp = arr[k]
arr[k] = arr[k+1]
arr[k+1] = temp | true |
c608d17aeb079332cf51be22647352ce2abc5085 | titanlien/workshop | /task04/convert.py | 1,167 | 4.15625 | 4 | #!/usr/bin/env python3
import argparse
"""https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html"""
ROMAN_NUMERALS = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I'),
]
def int_to_roman_num(_int: int) -> str:
"""Convert a integer to a Roman numerals
:param _int: the digital number
"""
if (not isinstance(_int, int)):
raise TypeError("input int must be of type int")
return_list = []
keeper = _int
for integer, numeral in ROMAN_NUMERALS:
quotient, keeper = divmod(keeper, integer)
return_list.append(quotient * numeral)
return ''.join(return_list)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="converts integer numbers into Roman numbers")
parser.add_argument(
"integer",
metavar="N",
type=int,
choices=range(1, 999999),
help="an natural number for webapp size, [1-9999]",
)
args = parser.parse_args()
print (int_to_roman_num(args.integer))
| true |
06b8339073dff3c0e3207154c9a1277f63202956 | davidygp/Project_Euler | /python/prob4.py | 893 | 4.34375 | 4 | """
Problem 4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def find_max_palin_product() -> int:
"""
Find the largest palindrome made from the product of two 3-digit numbers
"""
max_palin_product = 0
for _, val1 in enumerate(range(100, 1000), 1):
for _, val2 in enumerate(range(100, 1000), 1):
if val1 > val2:
product = str(val1 * val2)
reverse_product = "".join(list(product)[::-1])
if product == reverse_product and int(product) > max_palin_product:
max_palin_product = int(product)
return max_palin_product
if __name__ == "__main__":
print("Ans is %s" % ( find_max_palin_product() ) )
# 9066909
| true |
dd37b3f9e28b6c26000a9c94f1883c647708b3ae | razvitesting/Automation-Testing | /mylist.py | 206 | 4.125 | 4 | mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist:
print(x) | true |
044be8776e8a959acbac43836290556e632b3e99 | milindukey/Python | /Beginners/control loop.py | 1,022 | 4.375 | 4 | largestNumber = -99999999
counter = 0
number = int(input("Enter a number or type -1 to end program: "))
while number != -1:
if number == -1:
continue
counter += 1
if number > largestNumber:
largestNumber = number
number = int(input("Enter a number or type -1 to end program: "))
if counter:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")
#Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters "chupacabra" as the secret exit word,
#in which case the message "You've successfully left the loop." should be printed to the screen, and the loop should terminate.
#Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.
while True :
word = input("You're stuck in an infinite loop. Enter secret word to exit the loop ")
if word == "chupacabra" :
break
print("You've successfully left the loop.")
| true |
4b41f7f1a744e6820d77049da3443faadacaa9a6 | Abinaya3198/shivanya | /f4.py | 211 | 4.34375 | 4 | al = input("enter the character : ")
if((al >= 'a' and al <= 'z') or (al >= 'A' and al <= 'Z')):
print("The Given Character ", ch, "is an Alphabet")
elif(al == '?'):
print("no")
else:
print("not an alphabet")
| true |
5fbc21600fc9ea53a5e16fa3a00389efecc8be91 | nitin-cherian/LifeLongLearning | /Web_Development_Python/RealPython/flask-blog/sql.py | 684 | 4.125 | 4 | # sql.py - Create a sqlite3 table and populate it with data
# import sqlite3 library
import sqlite3
# create a new database if the database already does not exist
with sqlite3.connect("blog.db") as connection:
# get a cursor object to execute sql commands
c = connection.cursor()
# create the table
c.execute("CREATE TABLE posts(title TEXT, post TEXT)")
# insert dummy data into the table
c.execute('INSERT INTO posts VALUES("Good", "I\'am good")')
c.execute('INSERT INTO posts VALUES("Well", "I\'am well")')
c.execute('INSERT INTO posts VALUES("Excellent", "I\'am excellent")')
c.execute('INSERT INTO posts VALUES("Okay", "I\'am good")')
| true |
b70018a393d272324b542a0d6bc40ce0e1a5a23e | nitin-cherian/LifeLongLearning | /Python/Experiments/ITERATORS/Polyglot.Ninja/why_iterables.py | 494 | 4.75 | 5 | # why_iterables.py
print("""
Iterator behaves like an iterable in that it implements the __iter__ method. Then why do we need iterables?
When StopIteration is raised from an iterator, there is no way to iterator over the iterator again, because
iterator maintains the state and return self when iter is invoked on it. If we iterate over iterables, a fresh instance
of iterator is returned which can be used to iterate again. This is what happens in the case of iterables like 'list'
""")
| true |
83b8306a533237034ce55d980ee49b44d9ba0f78 | nitin-cherian/LifeLongLearning | /Python/Experiments/ITERATORS/Polyglot.Ninja/iterators_should_be_iterable.py | 2,400 | 4.40625 | 4 | # iterators_should_be_iterable
print('''
According to the official doc:
*********
Iterators should implement the __iter__ method that returns the iterator object itself,
so every iterator is also iterable and may be used in most places where other iterables
are accepted.
*********
{code}
class HundredIterator:
def __init__(self):
self.__int = 0
def __next__(self):
self.__int += 1
if self.__int > 100:
raise StopIteration
return self.__int
class HundredIterable:
def __iter__(self):
return HundredIterator()
hundred = HundredIterable()
for i in hundred:
print(i)
hundredIter = HundredIterator()
print()
for i in hundredIter:
print(i)
{code}
''')
class HundredIterator:
def __init__(self):
self.__int = 0
def __next__(self):
self.__int += 1
if self.__int > 100:
raise StopIteration
return self.__int
class HundredIterable:
def __iter__(self):
return HundredIterator()
hundred = HundredIterable()
for i in hundred:
print(i)
hundredIter = HundredIterator()
print()
# for i in hundredIter:
# print(i)
print("""Since the iterator has not implemented an __iter__ method, the iterator above is not
iterable and a for loop cannot be used on the iterator.
To fix this issue, implement a __iter__ method on the iterator object, returning itself like so:.
{code}
class HundredIterator:
def __init__(self):
self.__int = 0
def __iter__(self):
return self
def __next__(self):
self.__int += 1
if self.__int > 100:
raise StopIteration
return self.__int
class HundredIterable:
def __iter__(self):
return HundredIterator()
hundred = HundredIterable()
for i in hundred:
print(i)
print()
hundredIter = HundredIterator()
for i in hundredIter:
print(i)
{code}
""")
class HundredIterator:
def __init__(self):
self.__int = 0
def __iter__(self):
return self
def __next__(self):
self.__int += 1
if self.__int > 100:
raise StopIteration
return self.__int
class HundredIterable:
def __iter__(self):
return HundredIterator()
hundred = HundredIterable()
for i in hundred:
print(i)
print()
hundredIter = HundredIterator()
for i in hundredIter:
print(i)
| true |
d0c3eee3504d0e0fb919e97c9396080bb70719b9 | indra-singh/Python | /prime_number.py | 350 | 4.125 | 4 | #Write a program to print if a number is a prime number *
n=int(input("Enter lower number :"))
m=int(input("Enter upper number :"))
print("Prime numbers between",n,"and",m,"are:")
for num in range(n,m+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
| true |
4c7173d644078932261cf2f33aa568baf85671f1 | imaaduddin/TreeHouse-Data-Structures-And-Algorithms | /recursion.py | 297 | 4.125 | 4 | # def sum(numbers):
# total = 0
# for number in numbers:
# total+= number
# return total
# print(sum([1, 2, 3, 4, 5]))
# Recursive Function
def sum(numbers):
if not numbers:
return 0
remaining_sum = sum(numbers[1:])
return numbers[0] + remaining_sum
print(sum([1, 2, 7, 9]))
| true |
88891cba26521787b2d7eeecd1f2e558baf8f0fd | orhanyagizer/Python-Code-Challange | /count_of_wovels_constants.py | 549 | 4.3125 | 4 | #Write a Python code that counts how many vowels and constants a string has that a user entered.
vowel_list = []
constant_list = []
word = input("Please enter a word: ").lower()
for i in word:
if i in set("aeiou"):
vowel_list.append(i)
count_vowel = len(vowel_list)
else:
constant_list.append(i)
count_constant = len(constant_list)
print(f"'{word}'\nVowels: {vowel_list}. The number of vowels is {count_vowel}.\nConstants: {constant_list}. The number of constants is {count_constant}.")
| true |
541d39fe2f6ef9cc7f86284554fc10a7fe0d7678 | JamesMcPeek/Python-100-Days | /Day 2.py | 342 | 4.125 | 4 | print("Welcome to the tip calculator!")
billTotal = float(input("What is the total bill? "))
percTip = int(input("What percentage tip would you like to give? "))
people = int(input("How many people will split the bill? "))
results = round((billTotal * (1 + (percTip / 100))) / people,2)
print("Each person should pay: " + "$" + str(results))
| true |
7419e55dcfacf0eab400524d1fd3cc1cbe5f48c6 | srajamohan1989/aquaman | /StringSlicer.py | 392 | 4.59375 | 5 | #Given a string of odd length greater 7, return a string made of the
# middle three chars of a given String
def strslicer(str):
if(len(str)<=7):
print("Enter string with length greater than 7")
else:
middleindex= int(len(str)/2)
print(text[middleindex-1:middleindex+2])
text=input("Enter a string of lenght odd and greater than 7: ")
strslicer(text) | true |
2d2c2f7ea670a516a2716d73a92d986b8498325e | joshl26/tstcs_challenge_solutions | /chapter14_ex1.py | 1,456 | 4.34375 | 4 | # This question actually does not make much sense
# because it is impossible to make a binary tree with no
# leaf nodes! My mistake!
class BinaryTree():
def __init__(self, value):
self.key = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = BinaryTree(value)
else:
bin_tree = BinaryTree(value)
bin_tree.left_child = self.left_child
self.left_child = bin_tree
def insert_right(self, value):
if self.right_child == None:
self.right_child = BinaryTree(value)
else:
bin_tree = BinaryTree(value)
bin_tree.lef_child = self.right_child
self.right_child = bin_tree
def has_leaf_nodes(self, root):
current = [root]
next = []
while current:
leaf = True
for node in current:
if node.left_child:
next.append(node.left_child)
leaf = True
if node.right_child:
next.append(node.right_child)
leaf = True
if leaf:
return True
current = next
next = []
return False
tree = BinaryTree(0)
tree.insert_left(10)
tree.insert_right(4)
tree.insert_left(3)
tree.insert_right(5)
print(tree.has_leaf_nodes(tree)) | true |
8053fdd5fed3a656f5e52ae6e66af9a62976500d | jnyryan/rsa-encryption | /p8_is_prime.py | 965 | 4.375 | 4 | #!/usr/bin/env python
"""
Implement the following routine:
Boolean fermat(Integer, Integer)
such that fermat(x,t) will use Fermat's algorithm to determine if x is prime.
REMEMBER
Fermat's theorm asserts that if n is prime and 1<=a<=n, then a**n-1 is congruent to 1(mod n)
"""
import p5_expm
import random
def is_prime(n, t):
for i in xrange(1, t):
a = random.randint(2, n-1)
#r = (a**n-1) % n
r = p5_expm.expm(a, n-1, n)
#print a , r
if r != 1:
return False
return True
#####################################################################
# Tests
if __name__ == "__main__":
print "Practical 8 - Verify a number is prime using Fermats Theorem"
t = 30
print is_prime(3, t)
print is_prime(4, t)
print is_prime(5, t)
print is_prime(6, t)
print is_prime(7, t)
print is_prime(11, t)
print is_prime(13, t)
print is_prime(101, t)
print is_prime(294000, t)
print is_prime(294001, t)
print "Done." | true |
efa2dcde8d6fddbcbea0ce5b0defa790986396ef | martinpeck/broken-python | /mathsquiz/mathsquiz-step3.py | 1,822 | 4.15625 | 4 | import random
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, second_number):
print("What is", first_number, "x", second_number)
answer = input("Answer: ")
correct_answer = first_number * second_number
if int(answer) == correct_answer:
print("Correct!")
points_awarded = 1
else:
print("Wrong! The correct answer was", correct_answer)
points_awarded = 0
print("")
return points_awarded
# this function will look at the final scores and print the results
def print_final_scores(final_score, max_possible_score):
print("That's all the questions done. So...what was your score...?")
print("You scored", score, "points out of a possible", max_possible_score)
percentage = (score/max_possible_score)*100
if percentage < 50:
print("You need to practice your maths!")
elif percentage < 80:
print("That's pretty good!")
elif percentage < 100:
print("You did really well! Try and get 10 out of 10 next time!")
elif percentage == 100:
print("Wow! What a maths star you are!! I'm impressed!")
# display welcome message
welcome_message()
# set the score to zero and the number of questions to 10
score = 0
number_of_questions = 10
# ask questions
for x in range(1,number_of_questions + 1):
print("Question", x)
first_number = random.randint(2,12)
second_number = random.randint(2,12)
score = score + ask_question(first_number,second_number)
# print the final scores
print_final_scores(score, number_of_questions)
| true |
b66bf8a200e19fe87eb82eaf0667bca53f7fc8c3 | sumitsrv121/parctice2 | /Excercise3.py | 227 | 4.1875 | 4 | def reverse_string(arr):
new_list = []
for x in arr:
new_list.append(x[::-1])
return new_list
fruits = ['apple','mango','orange','pears','guava','pomegranate','raspberry pie']
print(reverse_string(fruits)) | true |
12dda19350218d4ad3b9a4bbae13a72101bd44a5 | Chithra-Lekha/pythonprogramming | /co5/co5-1.py | 346 | 4.40625 | 4 | # Write a python program to read a file line by line and store it into a list.
l = list()
f = open("program1.txt", "w")
n = int(input("Enter the number of lines:"))
for i in range(n):
f.write(input("Enter some text:")+"\n")
f.close()
f = open("program1.txt", "r")
for i in f:
print(i)
l.append(i[:-1])
f.close()
print(l) | true |
04aea542b7903d07b756e8a7287b720f8938a414 | Chithra-Lekha/pythonprogramming | /co2-8.py | 335 | 4.28125 | 4 | list=[]
n=int(input("enter the number of words in the list:"))
for i in range(n):
x=input("enter the word:")
list.append(x)
print(list)
length=len(list[0])
temp=list[0]
for i in list:
if len(i) > length:
length=len(i)
temp=i
print("the longest word is of length",length)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.