blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2f69b2620798d10de0b6eb730ee28e82cb032a67 | vikky1993/Mytest | /test3.py | 1,997 | 4.34375 | 4 | # Difference between regular methods, class methods and static methods
# regular methods in a class automatically takes in instance as the first argument and by convention we wer
# calling this self
# So how can we make it to take class as the first argument, to do that we gonna use class methods
#just add a decorator called @classmethod to make a class method
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
# common convention for class variable is cls
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
# you may hear people say they use class methods as alternative constructors
# what do they mean by this is we can use these class methods in order to provide multiple ways of creating or objects
# this new method as an alternative constructor, usually these start with from - and that's convention also
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay) #this line is going to create the new employee, so we will return it too
# now lets see what is a static method, static method dont pass as argument automatically
# usually they behave just like regular functions, except we include them in our classes because they have some
# logically connection with the class
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
#usually a method should be made static if you dont access instance(self) or class(cls) anywhere within function
emp1 = Employee('Vickranth', 'Kalloli', 70000)
emp2 = Employee('User', 'Test', 50000)
import datetime
my_date = datetime.date(2018, 2, 21)
print(Employee.is_workday(my_date)) | true |
6b66cbbdb06804c86c757ca97397895a314ecfeb | RamaryUp/hackerrank | /Python/sets/symmetric_difference.py | 1,060 | 4.28125 | 4 | '''
HackerRank Challenge
Name : Symmetric Difference
Category : Sets
Difficulty : easy
URL : https://www.hackerrank.com/challenges/symmetric-difference/problem
Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
Input Format
The first line of input contains an integer, .
The second line contains space-separated integers.
The third line contains an integer, .
The fourth line contains space-separated integers.
Output Format
Output the symmetric difference integers in ascending order, one per line.
Sample Input
4
2 4 5 9
4
2 4 11 12
Sample Output
5
9
11
12
'''
# let's play with set collections !
m, set1 = int(input()), set(map(int,input().split()))
n, set2 = int(input()), set(map(int,input().split()))
syms_diff = list(set1 ^ set2) # list(set1.difference(set2)) - list(set2.difference(set1)) could be used; or list(set1-set2) + list(set2-set1)
syms_diff.sort()
for item in syms_diff:
print(item) | true |
ef64e4a52c2f1f0d14755358ba29b6f945a86336 | SinghTejveer/stepic_python_in_action_eng | /solutions/s217.py | 713 | 4.25 | 4 | """Given a real positive number a and an integer number n.
Find a**n. You need to write the whole program with a recursive function
power(a, n).
Sample Input 1:
2
1
Sample Output 1:
2
Sample Input 2:
2
2
Sample Output 2:
4
"""
def solve(num: float, exp: int) -> float:
"""Calculate num**exp."""
if exp < 0:
return solve(1 / num, -exp)
elif exp == 0:
return 1
elif exp == 1:
return num
elif exp % 2 == 0:
return solve(num * num, exp // 2)
else:
return num * solve(num * num, (exp - 1) // 2)
def main():
num = float(input())
exp = int(input())
print(solve(num, exp))
if __name__ == '__main__':
main()
| true |
99f3382c8b97ce2f4195f6ac93d9712d662cace5 | SinghTejveer/stepic_python_in_action_eng | /solutions/s005.py | 1,065 | 4.15625 | 4 | # pylint: disable=invalid-name
"""Difference of times
Given the values of the two moments in time in the same day: hours, minutes
and seconds for each of the time moments. It is known that the second moment
in time happened not earlier than the first one. Find how many seconds passed
between these two moments of time.
Input data format
The program gets the input of the three integers: hours, minutes, seconds,
defining the first moment of time and three integers that define the second
moment time.
Output data format
Output the number of seconds between these two moments of time.
Sample Input 1:
1
1
1
2
2
2
Sample Output 1:
3661
Sample Input 2:
1
2
30
1
3
20
Sample Output 2:
50
"""
def main():
h1 = int(input().rstrip())
m1 = int(input().rstrip())
s1 = int(input().rstrip())
h2 = int(input().rstrip())
m2 = int(input().rstrip())
s2 = int(input().rstrip())
print(h2*60*60 + m2*60 + s2 - h1*60*60 - m1*60 - s1)
if __name__ == '__main__':
main()
| true |
85288d85c45185c3505ac16f9fc76d02459e83a3 | SinghTejveer/stepic_python_in_action_eng | /solutions/s080.py | 423 | 4.1875 | 4 | """
Write a program, which reads the line from a standard input, using the input()
function, and outputs the same line to the standard output, using the print()
function.
Please pay attention that you need to use the input function without any
parameters, and that you need to output only that, what was transferred
to the input of this program.
"""
def main():
print(input())
if __name__ == '__main__':
main()
| true |
8c3ed77439371b18c45e60d0c1623efa5e2570c7 | bthuynh/python-challenge | /PyPoll/main.py | 2,879 | 4.125 | 4 | # You will be give a set of poll data called election_data.csv.
# The dataset is composed of three columns: Voter ID, County, and Candidate.
# Your task is to create a Python script that analyzes the votes and calculates each of the following:
# The total number of votes cast
# A complete list of candidates who received votes
# The percentage of votes each candidate won
# The total number of votes each candidate won
# The winner of the election based on popular vote.
# As an example, your analysis should look similar to the one below:
# Election Results
# -------------------------
# Total Votes: 3521001
# -------------------------
# Khan: 63.000% (2218231)
# Correy: 20.000% (704200)
# Li: 14.000% (492940)
# O'Tooley: 3.000% (105630)
# -------------------------
# Winner: Khan
# -------------------------
import os
import csv
votes = []
candidate = []
kvote = 0
cvote = 0
lvote = 0
ovote = 0
name1 = "Khan"
name2 = "Correy"
name3 = "Li"
name4 = "O'Tooley"
csvpath = os.path.join("Resources", "election_data.csv")
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
for row in csvreader:
votes.append(row[0])
candidate.append(row[2])
for name in candidate:
if name == name1:
kvote = kvote + 1
elif name == name2:
cvote = cvote + 1
elif name == name3:
lvote = lvote + 1
elif name == name4:
ovote = ovote + 1
def most_frequent(candidate):
return max(set(candidate), key = candidate.count)
total_votes = len(votes)
winner = most_frequent(candidate)
knumber = round(int(kvote) / int(total_votes),2)
cnumber = round(int(cvote) / int(total_votes),2)
lnumber = round(int(lvote) / int(total_votes),2)
onumber = round(int(ovote) / int(total_votes),2)
kpercent = "{:.0%}".format(knumber)
cpercent = "{:.0%}".format(cnumber)
lpercent = "{:.0%}".format(lnumber)
opercent = "{:.0%}".format(onumber)
print("Election Results")
print("--------------------------")
print(f"Total Votes: {total_votes}")
print(f"Khan: {kpercent} ({kvote})")
print(f"Correy: {cpercent} ({cvote})")
print(f"Li: {lpercent} ({lvote})")
print(f"O'Tooley: {opercent} ({ovote})")
print("--------------------------")
print(f"Winner: {winner}")
print("--------------------------")
analysis = os.path.join("analysis","Pypoll.txt")
file = open(analysis, 'w')
file.writelines("Election Results"+'\n')
file.writelines("--------------------------"+'\n')
file.writelines(f"Total Votes: {total_votes}"+'\n')
file.writelines(f"Khan: {kpercent} ({kvote})"+'\n')
file.writelines(f"Correy: {cpercent} ({cvote})"+'\n')
file.writelines(f"Li: {lpercent} ({lvote})"+'\n')
file.writelines(f"O'Tooley: {opercent} ({ovote})"+'\n')
file.writelines("--------------------------"+'\n')
file.writelines(f"Winner: {winner}"+'\n')
file.writelines("--------------------------"+'\n') | true |
8a4876cd4aae26f15d9673aac9fdf90aa58b573c | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_17.py | 787 | 4.1875 | 4 | ##
#Compute the amount of energy to achieve the desired temperature change
H_C_WATER=4.186
J_TO_KWH=2.777e-7
C_PER_KWH=8.9
#Read the volume of the water and the temperature change from the user
volume=float(input("Enter the amount of water in milliliters:\n"))
temp_change=float(input("Enter the value of the temperature change in degrees Celsius:\n"))
#Compute the amount of energy
energy_J=volume*H_C_WATER*temp_change
#Display the result
print("This is the amount of energy to achieve the desired temperature change: %.3f J\n"%energy_J)
#Compute the conversion from joule to kilowatt hours and the cost of boiling the water
energy_KWH=energy_J*J_TO_KWH
cost_electricity=C_PER_KWH*energy_KWH
#Display the result
print("The cost of boiling the water is: %.2f cents"%cost_electricity)
| true |
1e0ed285d5f8797eab8da2e8bd076f1c7078185a | peltierchip/the_python_workbook_exercises | /chapter_2/exercise_49.py | 894 | 4.40625 | 4 | ##
#Determine the animal associated with the inserted year
#Read the year from the user
year=int(input("Enter the year:\n"))
#Check if the year is valid
if year>=0:
#Determine the corresponding animal and display the result
if year%12==8:
animal="Dragon"
elif year%12==9:
animal="Snake"
elif year%12==10:
animal="Horse"
elif year%12==11:
animal="Sheep"
elif year%12==0:
animal="Monkey"
elif year%12==1:
animal="Rooster"
elif year%12==2:
animal="Dog"
elif year%12==3:
animal="Pig"
elif year%12==4:
animal="Rat"
elif year%12==5:
animal="Ox"
elif year%12==6:
animal="Tiger"
elif year%12==7:
animal="Hare"
print("The animal associated to the year",year,"is:",animal)
else:
print("The year isn't valid")
| true |
4878ceeb7108bd2885a2fccdce8abb5312be586d | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_184.py | 1,378 | 4.59375 | 5 | ##
# Perform the flattening of a list, which is convert
# a list that contains multiple layers of nested lists into a list that contains all the same elements without any nesting
## Flatten the list
# @param data the list to flatten
# @return the flattened list
def flattenList(data):
if not(data):
return data
if type(data[0]) == list:
l1 = flattenList(data[0])
l2 = flattenList(data[1:])
return l1 + l2
if type(data[0]) != list:
l1 = [data[0]]
l2 = flattenList(data[1:])
return l1 + l2
# Demonstrate the flattenList function
def main():
print("The result of the flattening of the list [1, [2, 3], [4, [5, [6, 7]]], [[[8], 9], [10]]] is:",flattenList([1, [2, 3], [4, [5, [6, 7]]], [[[8], 9], [10]]]))
print("The result of the flattening of the list [] is:",flattenList([]))
print("The result of the flattening of the list [1, 3, 7, 8, 10, 20, 77, 6] is:",flattenList([1, 3, 7, 8, 10, 20, 77, 6]))
print("The result of the flattening of the list [[1, 2], [[[3], 4, [5, 6]], [7]], [8], 9, [10, 11], 12, [[[13, 14], [15]]]] is:",flattenList([[1, 2], [[[3], 4, [5, 6]], [7]], [8], 9, [10, 11], 12, [[[13, 14], [15]]]]))
print("The result of the flattening of the list [[1, [2]], [[3, 4], [5]], [6]] is:",flattenList([[1, [2]], [[3, 4], [5]], [6]]))
# Call the main function
main() | true |
5d8a7606ac90a78fb1303d7f7e93c1be4e9aa563 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_115.py | 995 | 4.5 | 4 | ##
#Determine the list of proper divisors of a positive integer entered from the user
##Create the list of proper divisors
# @param n the positive integer
# @return the list of proper divisors
def properDivisors(n):
p_d=[]
i=1
#Keep looping while i is less or equal than about half of n
while i<=(n//2):
if n%i==0:
p_d.append(i)
i=i+1
return p_d
#Demonstrate the properDivisors function
def main():
p_integer=int(input("Enter a positive integer:\n"))
#Keep looping while the user enters a number less or equal than 0 or a number greater than 1
while p_integer<=0:
print("You must enter an integer greater than 0!")
p_integer=int(input("Enter a positive integer:\n"))
pro_divisors=properDivisors(p_integer)
print("Here the proper divisors of %d:\n"%p_integer)
print(pro_divisors)
#Only call the main function when this file has not been imported
if __name__=="__main__":
main()
| true |
8312a957ec2cc7de0eacaa4fda57e20f04689b70 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_120.py | 785 | 4.1875 | 4 | ##
#Display a list of items formatted
##Formatting items in a list
# @param l the list
# @return a string containing the formatted elements
def formattingList(l):
i=0
n_l=l
if len(l)==0:
return "No items have been entered."
if len(l)==1:
return str(l[i])
delimeter=" "
n_s=""
while i<len(l)-2:
n_l.insert(i,(l[i]+","))
n_l.pop(i+1)
i=i+1
n_l.insert(len(l)-1,"and")
n_s=delimeter.join(n_l)
return n_s
#Demonstrate the formattingList function
def main():
items=[]
item=input("Enter the first item:\n")
while item!="":
items.append(item)
item=input("Enter the item:\n")
s_items=formattingList(items)
print("\n%s"%s_items)
#Call the main function
main()
| true |
1d460dae11b9cf1493fa428c3d32e07fcf3910d8 | peltierchip/the_python_workbook_exercises | /chapter_4/exercise_95.py | 1,319 | 4.3125 | 4 | ##
#Capitalize a string entered from the user
##Capitalize the string
# @param string the string to capitalize
# @return the string for which the capitalization has been realized
def capitalize_it(string):
c_string=string
i=0
while i<len(string) and c_string[i]==" ":
i=i+1
if i<len(string):
c_string=c_string[0:i]+c_string[i].upper()+string[i+1:len(c_string)]
i=0
while i<len(string):
if c_string[i]=="." or c_string[i]=="?" or c_string[i]=="!":
i=i+1
while i<len(string) and c_string[i]==" ":
i=i+1
if i<len(string):
c_string=c_string[0:i]+c_string[i].upper()+c_string[i+1:len(c_string)]
i=i+1
i=1
while i<len(string)-1 :
if c_string[i]=="i" and c_string[i-1]==" " and (c_string[i-1]==" " or c_string[i+1]=="." or \
c_string[i]=="?" or c_string[i]=="!" or c_string[i]=="'"):
c_string=c_string[0:i]+c_string[i].upper()+c_string[i+1:len(c_string)]
i=i+1
return c_string
#Read the string from the user and demonstrate the capitalize_it function
def main():
s=input("Enter the string:\n")
c_s=capitalize_it(s)
print("Here the correct string:\n%s"%c_s)
#Call the main function
main()
| true |
029562d3c3a05977df813e73fbda14bf86927683 | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_181.py | 1,233 | 4.125 | 4 | ##
# Determine whether it is possible to form the dollar amount entered by
# the user with a precise number of coins, always entered by the user
from itertools import combinations_with_replacement
## Determine whether or not it is possible to construct a particular total using a
# specific number of coins
# @param d_a the dollar amount
# @param n_c the number of coins
# @return True if d_a can be formed with n_c coins
def possibleChange(d_a, n_c, i = 0):
c_l = [0.25, 0.10, 0.05, 0.01]
p_c_l = list(combinations_with_replacement(c_l, n_c))
# Base case
if i < len(p_c_l) and d_a == round(sum(p_c_l[i]), 4):
return True
# Recursive case
if i < len(p_c_l):
i = i + 1
return possibleChange(d_a, n_c, i)
# Demonstrate the possibleChange function
def main():
dollar_amount = float(input("Enter the dollar amount:\n"))
number_coins = int(input("Enter the number of coins:\n"))
if possibleChange(dollar_amount, number_coins):
print("The entered dollar amount can be formed using the number of coins indicated.")
else:
print("The entered dollar amount can't be formed using the number of coins indicated.")
# Call the main function
main()
| true |
ab065da1c97d276ae71cff4985aa8b33314cf6ee | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_7.py | 247 | 4.1875 | 4 | ##
#Calculation of the sum of the first n positive integers
#Read positive integer
n=int(input("Enter a positive integer\n"))
#Calculation of the sum
s=(n)*(n+1)/2
#Display the sum
print("The sum of the first %d positive integers is: %d" %(n,s))
| true |
b6f80becd1d1f37802a427950c059b41788d2b0d | peltierchip/the_python_workbook_exercises | /chapter_6/exercise_136.py | 921 | 4.71875 | 5 | ##
# Perform a reverse lookup on a dictionary, finding keys that
# map to a specific value
## Find keys that map to the value
# @param d the dictionary
# @param v the value
# @return the list of keys that map to the value
def reverseLookup(d,v):
# Create a list to store the keys that map to v
k_a_v=[]
# Check each key of d
for k in d:
# If the current value is equal to v, store the key in k_a_v
if d[k]==v:
k_a_v.append(k)
return k_a_v
#Demonstrate the reverseLookup function
def main():
dctnry={"a": 3, "b": 1, "c": 3, "d": 3, "e": 0, "f": 5}
print("The keys that map to 3 are:",reverseLookup(dctnry,3))
print("The keys that map to 7 are:",reverseLookup(dctnry,7))
print("The keys that map to 0 are:",reverseLookup(dctnry,0))
#Only call the main function when this file has not been imported
if __name__=="__main__":
main() | true |
c22deedf7d33043df0d14f90d3068ea1776b5f54 | peltierchip/the_python_workbook_exercises | /chapter_7/exercise_172.py | 1,981 | 4.15625 | 4 | ##
# Search a file containing a list of words and display all of the words that
# contain each of the vowels A, E, I, O, U and Y exactly once and in order
# Create a list to store vowels
vowels_list = ["a", "e", "i", "o", "u", "y"]
# Read the name of the file to read from the user
f_n_r = input("Enter the name of the file to read:\n")
try:
# Open the file for reading
inf = open(f_n_r, "r")
# Create a list to store the words that meet this constraint
s_v_o_ws = []
# Read the first line from the file
line = inf.readline()
# Keep looping until we have reached the end of the file
while line != "":
line = line.rstrip()
o_line = line
line = line.lower()
l_c = 0
t = True
v_c = 0
# Keep looping while l_c is less than the length of line and t is True
while l_c < len(line) and t:
# Check if the character is a consonant
if not(line[l_c] in vowels_list):
l_c = l_c + 1
else:
# Check if the character matches the current vowel
if line[l_c] == vowels_list[v_c]:
# Check if the character matches the last vowel
if v_c == len(vowels_list) - 1:
s_v_o_ws.append(o_line)
t = False
else:
v_c = v_c + 1
l_c = l_c + 1
else:
t = False
# Read the next line from the file
line = inf.readline()
# Close the file
inf.close()
# Check if s_v_o_ws is empty
if s_v_o_ws:
# Display the result
print("The words that contain each of the vowels A, E, I, O, U and Y exactly once and in order are:\n")
for w in s_v_o_ws:
print(w)
else:
print("No word satisfies the constraint")
except FileNotFoundError:
# Display an error message if the file to read was not opened successfully
print("'%s' wasn't found."%f_n_r)
| true |
b9a6cb431b02ff057c8ce4aff5a20ae724f78b30 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_111.py | 718 | 4.4375 | 4 | ##
#Display in reverse order the integers entered from the user, after being stored in a list
#Read the first integer from the user
n=int(input("Enter the first integer:\n"))
#Initialize integers to an empty list
integers=[]
#Keep looping while n is different from zero
while n!=0:
#Add n to integers
integers.append(n)
#Read the integer from the user
n=int(input("Enter the integer(0 to quit):\n"))
#Check if integers is empty
if integers==[]:
print("No integers have been entered.")
else:
#Sort the integers into revers order
integers.reverse()
#Display the elements of the list
print("Here are the integers in sorted order:\n")
for integer in integers:
print(integer) | true |
84e1d58ad16f91825fcfb06eac1c1226b61f5e6a | Lycurgus1/python | /day_1/Dictionaries.py | 1,220 | 4.53125 | 5 | # Dictionary
student_records = {
"Name": "Sam" # Name is key, sam is value
, "Stream": "DevOps"
, "Topics_covered": 5
, "Completed_lessons": ["Tuples", "Lists", "Variables"]
} # Can have a list in a tuple
student_records["Name"] = "Jeff"
print(student_records["Completed_lessons"][2]) # fetching index of list in dictionary
print(student_records["Name"]) # Fetching the value of name
print(sorted(student_records)) # Sorts according to keys
print(student_records.keys()) # Gets keys of dictionary
print(student_records.values()) # Gets values of dictionaries
print(student_records["Name"]) # Gets value from key in dictionary
print(student_records.get("Name")) # Different method of same thing
# Adding two items to completed lessons then displaying it
student_records["Completed_lessons"].append("Lists")
student_records["Completed_lessons"].append("Built in methods")
print(student_records["Completed_lessons"]) # Checking work
# Removing items
student_records.pop("Topics covered") # Removes item associated with key
student_records.popitem() # Removes last item added to list
del student_records["Name"] # Removes item with specific key name
# Can also clear copy and nest dictionaries.
| true |
1467bd581d54b3244d0ed003f2e5a47d0d6e77a7 | Lycurgus1/python | /day_1/String slicing.py | 567 | 4.21875 | 4 | # String slicing
greeting_welcome = "Cheese world" # H is the 0th character. Indexing starts at 0.
print(greeting_welcome[3]) # Gets 4th character from string
print(greeting_welcome[-1]) # Gets last character from string
print(greeting_welcome[-5:]) # Gets 1st character to last
x = greeting_welcome[-5:]
print(x)
# Strip - remove spaces
remove_white_space = "remove spaces at end of string "
print(len(remove_white_space))
print(remove_white_space.strip()) # Removes spaces at end of string
print(len(remove_white_space.strip())) # Length can bee seen to go down
| true |
2ecaa40da83339322abdb4f2377cbe44fad0b3b6 | Lycurgus1/python | /OOP/Object Orientated Python.py | 1,496 | 4.25 | 4 | # Object orientated python
# Inheritance, polymorhpism, encapsulation, abstraction
class Dog:
amimal_kind = "Canine" # Class variable
# Init intalizes class
# Give/find name and color for dog
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
return "woof, woof"
# create a methods inside for sleep, breath, run, eat
# Encapsulation. This creates a private method. Abstraction is a expansion on this
def __sleep(self):
return "zzzzz"
# Pas enables this function without error
def breath(self):
pass
# Inheritance. This refers to creating sub classes, but run is using is a
# previously define attribute
def run(self):
return "Come back, {}".format(self.name)
# Polymorphism. Here the sub class method overrides the methods in the
# parent class when appropriate. It first searches it its own class, then
# in its inherited class
def eat(self):
print("{} is eating fast".format(self.__class__.__name__))
class Retriever(Dog):
def eat(self):
print("Retriever is eating slowly")
class Labrador(Dog):
pass
# Creating object of our class
jim = Dog("Canine", "White")
peter = Dog("peter", "Brown")
print(jim.name)
# Testing encapsulation
print(peter.__sleep())
# Testing inheritance
print(peter.run())
# Testing polymorphism
jack = Labrador("Bill", "Black")
jill = Retriever("Ben", "Brown")
jack.eat()
jill.eat()
| true |
d9df4158b15accfba5c36e113f383140409ab02a | Lycurgus1/python | /More_exercises/More_Methods.py | 2,013 | 4.21875 | 4 | # From the Calculator file importing everything
from Calculator import *
# Inheriting the python calculator from the previous page
class More_Methods(Python_Calculator):
# As per first command self not needed
def remainder_test():
# Input commands get the numbers to be used, and they are converted to integers with int
print("This tests whether there will be a remainder to a divison, returning true and false")
num1 = int(input("Please enter your first number\n"))
num2 = int(input("Please enter your second number\n"))
outcome = num1 % num2
# Using the outcome we test if it is 0(False in boolean) or not zero(True in boolean).
# This determines what the user is told with a further message elaborating.
if bool(outcome) == True:
print("True")
return ("This returns a remainder of {}".format(outcome))
elif bool(outcome) == False:
print("False")
return ("This divison has no remainder")
# As per first command self not needed
def triangle_area():
# Input commands get the numbers to be used, and they are converted to integers with int
height = int(input("Enter triangle height in cm\n"))
width = int(input("Enter triangle width in cm\n"))
# This calculates the area of a triangle and returns it in a user friendly string
area = (width * height) / 2
return ("The triangle's area is {} cm".format(area))
# As per first command self not needed
def inches_to_cm():
# Input commands get the numbers to be used, and they are converted to integers with int
inches = int(input("Enter amount of inches to convert here, please \n"))
# This calculates the conversion and returns it in a user friendly string
cm = math.ceil(inches * 2.54)
return("That converts to {} Centimetres".format(cm))
# To test functions
print(More_Methods.remainder_test())
print(More_Methods.inches_to_cm())
| true |
80a11ffa961d83208461d324062f37d9f7b1d830 | yesusmigag/Python-Projects | /Functions/two_numberInput_store.py | 444 | 4.46875 | 4 | #This program multiplies two numbers and stores them into a variable named product.
#Complete the missing code to display the expected output.
# multiply two integers and display the result in a function
def main():
val_1 = int(input('Enter an integer: '))
val_2 = int(input('Enter another integer: '))
multiply(val_1, val_2)
def multiply(num_1, num_2):
product = num_1*num_2
print ('The result is', product)
main() | true |
a5643896a36f24aab394372e73d18e052deb624c | yesusmigag/Python-Projects | /List and Tuples/10 find_list_example.py | 710 | 4.34375 | 4 | """This program aks the user to enter a grocery item and checks it against a grocery code list. Fill in the missing if statement to display the expected output.
Expected Output
Enter an item: ice cream
The item ice cream was not found in the list."""
def main():
# Create a list of grocery items.
grocery_list = ['apples', 'peanut butter', 'eggs', 'spinach', 'coffee', 'avocado']
# Search for a grocery item.
search = input('Enter an item: ')
# Determine whether the item is in the list.
if search in grocery_list:
print('The item', search, 'was found in the list.')
else:
print('The item', search, 'was not found in the list.')
# Call the main function.
main() | true |
8c4a55fa444dc233b0f11291147c224b0ed1bdb5 | yesusmigag/Python-Projects | /List and Tuples/18 Min_and_Max_functions.py | 500 | 4.40625 | 4 | """Python has two built-in functions named min and max that work with sequences.
The min function accepts a sequence, such as a list, as an argument and returns
the item that has the lowest value in the sequence."""
# MIN Item
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The lowest value is', min(my_list))
#display The lowest value is 2
print('--------------------------')
#MAX Item
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The highest value is', max(my_list))
#display The highest value is 50 | true |
73037324693d0170667f036a2e61fcd1e586895f | yesusmigag/Python-Projects | /File and Files/Chapter6_Project3.py | 639 | 4.125 | 4 | '''Write a program that reads the records from the golf.txt file written in the
previous exercise and prints them in the following format:
Name: Emily
Score: 30
Name: Mike
Score: 20
Name: Jonathan
Score: 23'''
#Solution 1
file = open("golf.txt", "r")
name = True
for line in file:
if name:
print("Name:" + line, end="")
else:
print("Score:" + line)
name = not name
file.close()
#SOLUTION 2
golf_file = open('golf.txt','r')
line=golf_file.readlines()
#score=''
for i in range(0,len(line),2):
print('Name:'+line[i].strip('\n'))
print('Score:'+line[i+1].strip('\n'))
print()
golf_file.close() | true |
f735a64f0aa2132efd6a12b57cc812bc87a29444 | JaimeFanjul/Algorithms-for-data-problems | /Sorting_Algorithms/ascii_encrypter.py | 1,301 | 4.40625 | 4 | # ASCII Text Encrypter.
#--------
# Given a text with several words, encrypt the message in the following way:
# The first letter of each word must be replaced by its ASCII code.
# The second letter and the last letter of each word must be interchanged.
#--------
# Author: Jaime Fanjul García
# Date: 16/10/2020
def text_encrypter(text):
"""Return a string encrypted.
Parameters
----------
text: str
String of characters. It can contain any type of characters
This script generate a new string encripted which:
The first letter of each word must be replaced by its ASCII code.
The second letter and the last letter of each word must be interchanged..
"""
if not isinstance(text, str):
raise TypeError(f" {text} is not a string type")
words = text.split(" ")
for i , word in enumerate(words):
ch = list(word)
if len(ch) == 1:
ch[0] = str(ord(word[0]))
else:
ch[0] = str(ord(word[0]))
ch[1] = word[-1]
ch[-1]= word[1]
words[i] = ''.join(ch)
text = ' '.join(words)
return text
if __name__ == "__main__":
encrypted_text = text_encrypter("To be or not to be that is the question")
print(encrypted_text)
| true |
bc0c2d7871b4263c62e43cd04d7370fc4657468e | gitsana/Python_Tutorial | /M5-Collections/words.py | 1,607 | 4.5 | 4 | #!/usr/bin/env python3
#shebang
# indent with 4 spaces
# save with UTF-8 encoding
""" Retrieve and print words from a URL.
Usage: python3 words.py <URL>
"""
from urllib.request import urlopen
def fetch_words():
"""Fetch a list of words from a URL.
Args:
url: The URL of a UTF-8 text document
Returns:
A list of strings containing the words from the document
"""
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('UTF-8').split()
for word in line_words:
story_words.append(word)
def print_words(story_words):
""" print items one per line
Args: an iterable series of printable items
Returns: Nothing
"""
paragraph = ""
for word in story_words:
paragraph = paragraph + word + " "
print("--------------PRINT WORDS FUNCTION--------------",paragraph)
def main():
words = fetch_words()
print_words(words)
print(__name__)
if __name__ == '__main__':
main()
# to execute from REPL:
# >> python3 words.py
# import "words.py" to REPL:
# >> python3
# >> import words
# >> words.fetch_words()
# import function "fetch_words()" from "words.py" to REPL and execute:
# >> python3
# >> from words import fetch_words
# >> fetch_words()
# >> from words import(fetch_words,print_words)
####### docstrings
# >>> from words import *
# words
# >>> help(fetch_words)
####### docstrings for whole program
# $ python3
# >>> import words
# words
# >>> help(words)
# python module: convenient import with API
# python script: convenient execution from cmd line
# python program: composed of many modules
| true |
a90012c851cad115f6f75549b331cfa959de532b | JasleenUT/Python | /ShapeAndReshape.py | 587 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 22:47:26 2019
@author: jasleenarora
"""
#You are given a space separated list of nine integers.
#Your task is to convert this list into a 3X3 NumPy array.
#Input Format
#A single line of input containing space separated integers.
#Output Format
#Print the 3X3 NumPy array.
#Sample Input
#1 2 3 4 5 6 7 8 9
#Sample Output
#[[1 2 3]
# [4 5 6]
# [7 8 9]]
import numpy
arr = input()
arr = arr.split()
for i in range(0,len(arr)):
arr[i] = int(arr[i])
arr1 = numpy.array(arr)
arr1.shape = (3,3)
print(arr1)
| true |
a685dfed0946a9c01454d98f65abab97d25f6ce2 | StarPony3/403IT-CW2 | /Rabbits and recurrence.py | 645 | 4.3125 | 4 | # program to calculate total number of rabbit pairs present after n months,
# if each generation, every pair of reproduction-age rabbits produces k rabbit pairs, instead of only one.
# variation of fibonacci sequence
# n = number of months
# k = number of rabbit pairs
# recursive function for calculating growth in rabbit population
def rabbits(n, k):
if n <= 1:
return n
else:
return rabbits(n - 1, k) + k * rabbits(n - 2, k)
# prints the total number of rabbit pairs each month.
for x in range(1, 8):
print (f"Total number of rabbit pairs after {x} months: ", (rabbits(x, 3)))
| true |
d9f32b00f9bcaec443b3fc22b1f239333bfb26a3 | peterpfand/aufschrieb | /higher lower.py | 413 | 4.65625 | 5 | string_name.lower() #to lower a string
.higher() #to higher a string
#example:
email = input("What is your email address?")
print(email)
final_email = email.lower()
print(final_email)
string_name.isLower() #to check if a string id written in lowercase letters
.ishigher() #to check if a string id written in highercase letters
#returns true or false
| true |
ad26db5b5d0e3e5b8c73c190b88db85b16c8fa3c | sawaseemgit/AppsUsingDictionaries | /PollingApp.py | 1,596 | 4.21875 | 4 | print('Welcome to Yes/No polling App')
poll = {
'passwd': 'acc',
}
yes = 0
no = 0
issue = input('What is the Yes/No issue you will be voting on today: ').strip()
no_voters = int(input('What is number of voters you want to allow: '))
repeat = True
while repeat:
for i in range(no_voters):
fname = input('What is your full name: ').title().strip()
if fname in poll.keys():
print('Sorry, you seem to have already voted.')
else:
print(f"Hii {fname}, Today's issue is: {issue}")
choice = input('What is your vote (yes/no): ').lower().strip()
if choice.startswith('y'):
yes += 1
elif choice.startswith('n'):
no += 1
else:
print('Thats an invalid answer.')
poll[fname] = choice
print(f'Thank you {fname}. Your vote {poll[fname]} has been recorded.')
if i == (no_voters - 1):
repeat = False
total = len(poll.keys())
print(f'The following {total} people voted: ')
for key in poll.keys():
print(key)
print(f'On the following issue: {issue}')
if yes > no:
print(f'Yes wins. {yes} votes to {no}.')
elif yes < no:
print(f'No wins. {no} votes to {yes}.')
else:
print(f'It was a tie. {yes} votes to {no}.')
passwd = str(input('To see all of the voting results, enter admin password: '))\
.strip()
if passwd == poll['passwd']:
for k, v in poll.items():
print(f'Voter:{k} Vote:{v}')
else:
print('Incorrect password. Good bye.. ')
print("Thank you for using the Yes/no App.")
| true |
99a2a83c7059b61e14c054e650e4bb1c221047cd | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/09 Guessing Game One.py | 699 | 4.25 | 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.
import random
numGuess= 0
a = random.randint(1,9)
end= 1
while (end != 0) or (end != 0):
guess = input('Guess a number : ')
guess = int(guess)
numGuess +=1
if guess < a:
print('You guessed too low')
elif guess > a:
print('You guessed too high')
else:
print('You got it Genuis!!!')
ended = input('"Enter exit" to quit : ')
if (str(ended) == 'exit') or (str(ended) == 'Exit') or (str(ended) == 'EXIT'):
end= 0
print(f"You took {numGuess} guesse(s).") | true |
f033cc8e82f2692f55b1531159229168fdb638b9 | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/12 List Ends.py | 293 | 4.125 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.
def rand():
import random
return random.sample(range(5, 25), 5)
a= rand()
print(a)
newList = [a[0],a[-1]]
print(newList) | true |
cfa6497baa42d0662b46188a4460d47c28e878aa | LemonTre/python_work | /Chap09/eat_numbers.py | 1,166 | 4.15625 | 4 | class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The name of restaurant is: " + self.restaurant_name.title() + ".")
print("The type of restaurant is " + self.cuisine_type + ".")
def open_restaurant(self):
print("The restaurant is working.")
def set_number_served(self, numbers):
"""修改吃饭的人数"""
self.number_served = numbers
def increment_number_served(self, increments):
"""增加的人数值"""
self.number_served += increments
restaurant = Restaurant('KFC', 'fast food')
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.number_served = 12
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.set_number_served(15)
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.increment_number_served(100)
print("The numbers that you think the restaurant can hold: "
+ str(restaurant.number_served) + " guys.")
| true |
a787c4e2a01b88818289586d13c7332a12d8868f | omkar1117/pythonpractice | /file_write.py | 993 | 4.3125 | 4 | fname = input("Enter your First name:")
lname = input("Enter your Last name:")
email = input("Enter your Email:")
if not fname and not lname and not email:
print("Please enter all the details:")
elif fname and lname and not email:
print("Please enter a valid email")
elif email and fname and not lname:
print("First Name and Last name both are mandatory")
elif email and lname and not fname:
print("First Name and Last name both are mandatory")
if email and not '@' in email:
print("Not a valid Email, Please have a valid email")
elif fname.strip() and lname.strip() and email.strip():
fw = open("details.txt", "a")
fw.write("-------------------------------------------\n")
fw.write("First Name is :: %s \n"%fname.capitalize())
fw.write("Last Name is :: %s \n"%lname.capitalize())
fw.write("Email is :: %s \n"%email.lower())
fw.write("-------------------------------------------\n")
fw.close()
print("End of Script completed")
| true |
dddb2bfd290929643eb202396aecd88df6d51e0f | Catering-Company/Capstone-project-2 | /Part2/sub_set_min_coin_value.py | 1,889 | 4.75 | 5 | # CODE FOR SETTING THE MINIMUM COIN INPUT VALUE ( CHOICE 2 OF THE SUB-MENU )
# --------------------------------------------------
# Gets the user to input a new minimum amount of coins that the user can enter
# into the Coin Calulator and Mutiple Coin Calculator.
# There are restrictions in place to prevent the user from entering:
# - Any non-integer.
# - A min value less than 0.
# - A min value greater than or equal to 10000.
# - A min value greater than the current max value.
# If any of the above happens then min_coin_value returns a negative integer.
# A while-loop in main(config) will then rerun min_coin_value.
def min_coin_value(config):
try:
min_coin = input("What is the minimum amount of coins you want the machine to accept? ")
min_coin = int(min_coin)
if int(min_coin) < 0:
print("Request denied.")
print("The minimum must be at least 0.")
print()
return -1
if int(min_coin) >= 10000:
print("Request denied.")
print("You cannot set the minimum coin value to 10000 or larger.")
print()
return -2
if int(min_coin) > config["max_coin_value"]:
print("Request denied.")
print("That is larger than the maximum coin amount!")
print()
return -3
except:
print("Please enter a minimum amount of coins.")
print()
return -3
return int(min_coin)
# --------------------------------------------------
# Returns the number that the user has inputted, provided that the number is greater than 0.
# If the number is 0 or less then the user is re-prompted.
def main(config):
min_coin = min_coin_value(config)
while min_coin < 0:
min_coin = min_coin_value(config)
return min_coin
# --------------------------------------------------
| true |
f2725f5d5f4b12d7904d271873c421c99ff2fe9f | MagRok/Python_tasks | /regex/Python_tasks/Text_stats.py | 1,627 | 4.15625 | 4 | # Create a class that:
#• When creating an instance, it required entering the text for which it will count statistics.
# The first conversion occurred when the instance was initialized.
#Each instance had attributes: - lower_letters_num - which stores the number of all lowercase letters in the text
#- upper_letters_num - holds the number of all uppercase letters in the text
#- punctuation_num - storing the number of punctuation characters in the text.
#- digits_num - the number of digits present in the text.
# stats - a dictionary that stores the statistics of letters, numbers and punctuation in the text.
# Calculate statistics using the calculate_stats method.
import re
class LetterStats():
def __init__(self, text):
self.lower_l_num = None
self.upper_l_num = None
self.punct_l_num = None
self.digits_l_num = None
self.stats = {}
self.text = text
self._calculate_stats()
def _calculate_stats(self):
self.lower_l_num = len(re.findall(r'[a-ząćęłóżź]', self.text))
self.upper_l_num = len(re.findall(r'[A-ZĄĆĘŁÓŻŹ]', self.text))
self.punct_l_num = len(re.findall(r'[.?\-",:;!]', self.text))
self.digits_l_num = len(re.findall(r'[0-9]', self.text))
self.stats = {'lower_letters': self.lower_l_num,
'upper_letters': self.upper_l_num,
'punctuation': self.punct_l_num,
'digits': self.digits_l_num}
return self.stats
def add_text(self, text):
self.text = text
self._calculate_stats()
return self.stats | true |
ad88d60e5b4b5ab7c77df24182ec07525e213411 | hulaba/geekInsideYou | /trie/trieSearch.py | 2,112 | 4.125 | 4 | class TrieNode:
def __init__(self):
"""
initializing a node of trie
isEOW is isEndOfWord flag used for the leaf nodes
"""
self.children = [None] * 26
self.isEOW = False
class Trie:
def __init__(self):
"""
initializing the trie data structure with a root node
"""
self.root = self.getNode()
def getNode(self):
"""
Create a node in the memory
:return: a new node with children and isEOW flag
"""
return TrieNode()
def charToIndex(self, ch):
"""
converts characters to index starting from 0
:param ch: any english albhabet
:return: ascii value
"""
return ord(ch) - ord('a')
def insert(self, value):
"""
function for inserting words into prefix tree (trie)
:param value: word string to be inserted
"""
rootNode = self.root
length = len(value)
for step_size in range(length):
index = self.charToIndex(value[step_size])
if not rootNode.children[index]:
rootNode.children[index] = self.getNode()
rootNode = rootNode.children[index]
rootNode.isEOW = True
def search(self, word):
"""
utility function that searches for a word in trie
:param word: search word
:return: boolean, if true, word is present otherwise not
"""
rootNode = self.root
length = len(word)
for _ in range(length):
index = self.charToIndex(word[_])
if not rootNode.children[index]:
return False
rootNode = rootNode.children[index]
return rootNode is not None and rootNode.isEOW
if __name__ == '__main__':
keys = ["the", "a", "there", "anaswe", "any",
"by", "their"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
if t.search('the'):
print('present')
else:
print('not present')
| true |
0d877b43c404c588ef0dbacd8c93c94b17534359 | hulaba/geekInsideYou | /tree/levelOrderSpiralForm.py | 1,421 | 4.1875 | 4 | """
Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
spiral_order
"""
class Node:
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def spiralOrder(root):
h = heightOfTree(root)
ltr = False
for i in range(1, h + 1):
spiralPrintLevel(root, i, ltr)
ltr = not ltr
def spiralPrintLevel(root, level, ltr):
if root is None:
return
if level == 1:
print(root.val, end=" ")
if level > 1:
if ltr:
spiralPrintLevel(root.left, level - 1, ltr)
spiralPrintLevel(root.right, level - 1, ltr)
else:
spiralPrintLevel(root.right, level - 1, ltr)
spiralPrintLevel(root.left, level - 1, ltr)
def heightOfTree(node):
if node is None:
return 0
else:
l_height = heightOfTree(node.left)
r_height = heightOfTree(node.right)
if l_height > r_height:
return l_height + 1
else:
return r_height + 1
def main():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("--The spiral order traversal of the tree is")
spiralOrder(root)
if __name__ == '__main__':
main()
| true |
8bbd84f22d9af1917de39200a00c0a8edeb81a34 | hulaba/geekInsideYou | /linked list/deleteListPosition.py | 1,403 | 4.15625 | 4 | class Node:
def __init__(self, data):
"""initialising the data and next pointer of a node"""
self.data = data
self.next = None
class linkedList:
def __init__(self):
"""initialising the head node"""
self.head = None
def push(self, new_data):
"""inserting the data in the linked list"""
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def deleteAt(self, position):
"""delete data at a given index in linked list"""
if self.head is None:
return
temp = self.head
if position == 0:
self.head = temp.next
temp = None
return
for i in range(position - 1):
temp = temp.next
if temp is None:
break
if temp is None:
return
if temp.next is None:
return
next = temp.next.next
temp.next = None
temp.next = next
def printList(self):
"""traversing the elements"""
temp = self.head
while (temp):
print(temp.data)
temp = temp.next
if __name__ == '__main__':
llist = linkedList()
llist.push(1)
llist.push(2)
llist.push(7)
llist.push(4)
llist.printList()
print("after deletion")
llist.deleteAt(2)
llist.printList()
| true |
1ebf124d42d510c2e60c3c7585c03e0efd6dad18 | gnsisec/learn-python-with-the-the-hard-way | /exercise/ex14Drill.py | 871 | 4.21875 | 4 | # This is Python version 2.7
# Exercise 14: Prompting and Passing
# to run this use:
# python ex14.py matthew
# 2. Change the prompt variable to something else entirely.
# 3. Drill: Add another argument and use it in your script,
# the same way you did in the previous exercise with first, second = ARGV.
from sys import argv
script, user_name, status = argv
prompt = 'answer: '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you few questions."
print "Do you like me %s ?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r compter. Nice.
Your status %r.
""" % (likes, lives, computer, status)
| true |
1804f578c7ff417744edc804043b2016d8bcde4a | paulocuambe/hello-python | /exercises/lists-execises.py | 554 | 4.21875 | 4 | my_list = ["apple", "banana", "cherry", "mango"]
print(my_list[-2]) # Second last item of the list
my_list.append("lemon")
if "lemon" in my_list:
print("Yes, that fruit is in the list.")
else:
print("That fruit is not in the list.")
my_list.insert(2, "orange")
print(my_list)
new_list = my_list[1:]
print(new_list)
new_list.sort()
print(new_list)
print(sorted(my_list))
nums = [1, 3, 6, 7, 9]
sqr_list = [x * x for x in nums]
nums.extend([10, 12, 13])
print(nums)
print(sqr_list)
sqr_list.pop()
del nums[1:2]
print(nums)
print(sqr_list)
| true |
45ab566c204a9a593871d670c1c0e206fa3949fd | paulocuambe/hello-python | /exercises/dictionaries/count_letter.py | 367 | 4.125 | 4 | """
Count how many times each letter appears in a string.
"""
word = "lollipop"
# Traditional way
trad_count = dict()
for l in word:
if l not in trad_count:
trad_count[l] = 1
else:
trad_count[l] += 1
print(trad_count)
# An elegant way
elegant_count = dict()
for l in word:
elegant_count[l] = elegant_count.get(l, 0) + 1
print(trad_count) | true |
fccfaac6346eaf23b345cd2117cda259fd83ff80 | MrinaliniTh/Algorithms | /link_list/bring_last_to_fast.py | 1,663 | 4.15625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def create_link_list(self, val):
if not self.head:
self.head = Node(val)
else:
temp = self.head
while temp.next:
temp = temp.next
new_node = Node(val)
temp.next = new_node
def print_link_list(self): # O(n) time complexity
temp = self.head
data = ""
while temp is not None:
if temp.next is None:
data += str(temp.val)
temp = temp.next
else:
data += str(temp.val) + '->'
temp = temp.next
return data
def end_to_first(self):
# import pdb;pdb.set_trace()
current = self.head
while current.next.next:
current = current.next
temp = current.next
current.next = None
temp.next = self.head
self.head = temp
def end_to_first_and_remove_first_node(self):
current = self.head
while current.next.next:
current = current.next
temp = current.next
current.next = None
temp.next = self.head.next
self.head = temp
node = LinkedList()
# creation of link list
node.create_link_list(1)
node.create_link_list(2)
node.create_link_list(3)
node.create_link_list(4)
node.create_link_list(5)
node.create_link_list(6)
print(node.print_link_list())
# node.end_to_first()
# print(node.print_link_list())
node.end_to_first_and_remove_first_node()
print(node.print_link_list()) | true |
b3f14159120e16453abdbd43687885956393e811 | TaylorWhitlatch/Python | /tuple.py | 967 | 4.3125 | 4 | # # Tuple is a list that:
# # 1. values cannot be changed
# # 2. it uses () instead of []
#
# a_tuple = (1,2,3)
# print a_tuple
#
# # Dictionaries are lists that have alpha indicies not mumerical
#
# name = "Rob"
# gender = "Male"
# height = "Tall"
#
# # A list makes no sense to tie together.
#
# person = {
# "name": "Rob",
# "gender": "Male",
# "heigt": "Tall"
# }
#
# print person
zombie = {}
zombie["weapon"] = "axe"
zombie["health"] = 100
zombie["speed"] = 10
print zombie
for key,value in zombie.items():
print "Zombie has a key of %s with a value of %s" % (key, value)
del zombie["speed"]
print zombie
is_nighttime = True
zombies = []
if(is_nighttime):
zombie["health"] +50
zombies.append({
'speed':15,
'weapon':'fist',
'name: peter'
})
zombies.append({
'speed':25,
'weapon':'knee',
'name: will',
'victims': [
'jane',
'bill',
'harry'
]
})
print zombies[1]['victims'[1]
| true |
79004d747935ebfc19599a9df859400c47120c7e | PavanMJ/python-training | /2 Variables/variables.py | 832 | 4.1875 | 4 | #!/usr/bin/python3
## All the variables in python are objects and every object has type, id and value.
def main():
print('## checking simple variables and their attributes')
n = 12
print(type(n), n)
f = 34.23
print(type(f), f)
print(f / 4)
print(f // 4)
print(round(f / 4), end = '\n\n')
print('## type casting ##')
a = int(23.33)
print(type(a), a)
b = float(324)
print(type(b), b, end = '\n\n')
print('## check immutability of objects ##')
num = 3
print('id of object {} is - '.format(num), id(num))
num = 4
print('after changing value of object to {}, id changed to {}'.format(num, id(num)))
num = 3
print('restored value of object to original value {}, now id is {}'.format(num, id(num)), end = '\n\n')
if __name__ == '__main__' : main()
| true |
fe789098e54d1a7a59573d36fc03a4da0159b552 | vuminhph/randomCodes | /reverse_linkedList.py | 969 | 4.1875 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
def add_node(self, value):
ptr = self.head
while ptr.next != None:
ptr = ptr.next
ptr.next = Node(value)
def print_list(self):
ptr = self.head
while ptr != None:
print(ptr.value)
ptr = ptr.next
def ll_reversed(linked_list):
ptr = linked_list.head
next_ptr = ptr.next
linked_list.head.next = None
while next_ptr != None:
ptr1 = ptr
ptr2 = next_ptr
next_ptr = next_ptr.next
ptr2.next = ptr1
ptr = ptr2
linked_list.head = ptr
linked_list = LinkedList(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.add_node(4)
linked_list.add_node(5)
linked_list.add_node(6)
linked_list.print_list()
ll_reversed(linked_list) | true |
a83a1d0e35bed07b1959086aff1ef4f7a872520e | rpayal/PyTestApp | /days-to-unit/helper.py | 1,232 | 4.40625 | 4 | USER_INPUT_MESSAGE = "Hey !! Enter number of days as a comma separated list:unit of measurement (e.g 20, 30:hours) " \
"and I'll convert it for you.\n "
def days_to_hours(num_of_days, conversion_unit):
calculation_factor = 0
if conversion_unit == "hours":
calculation_factor = 24
elif conversion_unit == "minutes":
calculation_factor = 24 * 60
elif conversion_unit == "seconds":
calculation_factor = 24 * 60 * 60
else:
return "Unsupported unit of measurement. Pls. pass either (hours/minutes/seconds)."
return f"{num_of_days} days are {num_of_days * calculation_factor} {conversion_unit}"
def validate_and_execute(num_of_days, conversion_unit):
try:
user_input_number = int(num_of_days)
if user_input_number > 0:
calculated_value = days_to_hours(user_input_number, conversion_unit)
print(calculated_value)
elif user_input_number == 0:
print("You entered a 0, please provide a valid positive number.")
else:
print("You entered a negative number, no conversion for you.")
except ValueError:
print("Your input is not a valid number. Don't ruin my program.")
| true |
05564cfff12bdf3b73b32f3f4c8b484046ff3d91 | PatDaoust/6.0002 | /6.0002 ps1/ps1b adapt from teacher.py | 2,717 | 4.125 | 4 | ###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
def dp_make_weight(egg_weights, target_weight, memo = {}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
#highly analogous to knapsack problem of fastMaxVal
#return smallest #eggs to make target weight = len(list of eggs)
avail_weight = target_weight
egg_weights.sort()
#TODO: figure out how to make this happen once
possible_eggs_list = [((str(egg)+" ") * int((target_weight/int(egg)))).split() for egg in egg_weights]
possible_eggs_list = [egg for egg_sublist in possible_eggs_list for egg in egg_sublist]
if avail_weight in memo:
eggs_list = memo[avail_weight]
elif avail_weight == 0 or len(egg_weights)==0:
eggs_list = [0]
elif int(possible_eggs_list [0]) > avail_weight:
eggs_list = dp_make_weight(possible_eggs_list [1:], avail_weight, memo)
else:
next_egg = int(possible_eggs_list [0])
#take next item, recursive call for next step
withVal = dp_make_weight(possible_eggs_list [1:], (avail_weight-next_egg), memo)
withVal += [next_egg]
#not take next item, recursive call for next step
withoutVal = dp_make_weight(possible_eggs_list [1:], avail_weight, memo)
#pick if take
if withVal > withoutVal:
eggs_list = [withVal] + [next_egg]
print("with")
print(possible_eggs_list)
else:
eggs_list = withoutVal
print("without")
print(possible_eggs_list)
memo[avail_weight] = eggs_list
return eggs_list
dp_make_weight([1, 5, 10, 25], 99, memo = {})
"""
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print("Egg weights = (1, 5, 10, 25)")
print("n = 99")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()
""" | true |
6df61f24bfe1e9943ac01de9eec80caad342c8a9 | rootid23/fft-py | /arrays/move-zeroes.py | 851 | 4.125 | 4 | #Move Zeroes
#Given an array nums, write a function to move all 0's to the end of it while
#maintaining the relative order of the non-zero elements.
#For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
#should be [1, 3, 12, 0, 0].
#Note:
#You must do this in-place without making a copy of the array.
#Minimize the total number of operations.
# TC : O(n)
class Solution(object):
#Iteration with trick
def moveZeroes(self, nums):
strt = 0
for i in range(len(nums)):
if (nums[i] != 0): #It moves all zeros to end and reverse condition move them to front
nums[i], nums[strt] = nums[strt], nums[i]
strt += 1
#W/ exception
def moveZeroesWithXcept(self, nums):
c = 0
while True:
try:
nums.remove(0)
c += 1
except:
nums += [0] * c
break
| true |
85b9bec9a1ceea4ee661b59c7efc82595e30f871 | Anand8317/food-ordering-console-app | /admin.py | 2,127 | 4.15625 | 4 | admin = {"admin":"admin"}
food = dict()
def createAdmin():
newAdmin = dict()
username = input("Enter username ")
password = input("Enter password ")
newAdmin[username] = password
if username in admin:
print("\nAdmin already exist\n")
else:
admin.update(newAdmin)
print("\nNew Admin has been created\n")
def adminLogin(username, password):
if not username in admin:
print("Account doesn't exist")
print("\n")
return False
if admin[username] == password:
print("\n")
print("Successful login")
print("\n")
return True
else:
print("\n")
print("Wrong password")
print("\n")
return False
def addFood():
newFood = dict()
foodId = id(newFood)
newFood[foodId] = ["","",0,0,0]
newFood[foodId][0] = input("Enter food name: ")
newFood[foodId][1] = input("Enter food quantity: ")
newFood[foodId][2] = int(input("Enter food price: "))
newFood[foodId][3] = int(input("Enter food discount: "))
newFood[foodId][4] = int(input("Enter the stock: "))
food.update(newFood)
print("\nFood item has been added")
print("\nFood item Id is ",foodId)
print("\n")
def editFood(foodId):
if foodId not in food:
print("\nFood id not found\n")
return
food[foodId][0] = input("Enter food name: ")
food[foodId][1] = input("Enter food quantity: ")
food[foodId][2] = int(input("Enter food price: "))
food[foodId][3] = int(input("Enter food discount: "))
food[foodId][4] = int(input("Enter the stock: "))
print("\n Food item has been edited\n")
def viewFoodItems():
i = 1
for foodId in food:
print("\n")
print(str(i) + ". " + food[foodId][0] + " (" + food[foodId][1] + ") [INR " + str(food[foodId][2]) + "]" )
i += 1
print("\n")
def delFood(foodId):
if foodId not in food:
print("\nFood id not found\n")
return
del food[foodId]
print("\nFood Item has been deleted\n") | true |
c9033580121ba38277facb1729565d15a994b8b6 | Ani-Stark/Python-Projects | /reverse_words_and_swap_cases.py | 419 | 4.15625 | 4 | def reverse_words_order_and_swap_cases(sentence):
arrSen = sentence.split()
arrSen = list(reversed(arrSen))
result = list(" ".join(arrSen))
for i in range(len(result)):
if result[i].isupper():
result[i] = result[i].lower()
else:
result[i] = result[i].upper()
return "".join(result)
res = reverse_words_order_and_swap_cases("aWESOME is cODING")
print(res)
| true |
e0857fdba34db0f114bcf7843f844aea775303e7 | Villanity/Python-Practice | /Reverse Array/Reverse_Array_while.py | 343 | 4.59375 | 5 | #Python program to reverse the array using iterations
def reverse_array (array1, start, end):
while (start<=end):
array1[start], array1[end] = array1[end], array1[start]
start += 1
end -= 1
A = [1, 2, 2 , 3, 4]
start=0
end= len(A) -1
print(A)
print("The reversed Array is: ")
reverse_array(A, start, end)
print(A)
| true |
fb67e1eff16e1804ecf9c2e4ff0010962bb930c3 | guyitti2000/int_python_nanodegree_udacity | /lessons_month_one/lesson_3_FUNCTIONS/test.py | 263 | 4.21875 | 4 | def times_list(x):
x **= 2
return x
output = []
numbers = [2, 3, 4, 3, 25]
for num in numbers:
val = times_list(numbers)
print(output.append(val))
# this is supposed to iterate through a list of numbers then print out the squares
| true |
093d56467f6309b099b8e2210efe8ecaca8397eb | shanahanben/myappsample | /Portfolio/week6/article_four_word_grabber.py | 564 | 4.15625 | 4 | #!/usr/bin/python3
import random
import string
guessAttempts = 0
myPassword = input("Enter a password for the computer to try and guess: ")
passwordLength = len(myPassword)
while True:
guessAttempts = guessAttempts + 1
passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in range(passwordLength)])
print(passwordGuess)
if passwordGuess == myPassword:
print("Password guessed successfully!")
print("It took the computer %s guesses to guess your password." % (guessAttempts))
break
| true |
106ddf889cd1ac1fb1b4e6fe1beef995982c4c31 | tajrian-munsha/Python-Basics | /python2 (displaying text and string).py | 2,391 | 4.53125 | 5 | # displaying text
#to make multiple line we can- 1.add \n in the string or, 2.use print command again and again.\n means newline.
print ("I am Shawki\n")
#we can use \t in the string for big space.\t means TAB.
print ("I am a\t student")
#we can use triple quotes outside the string for newline.For doing that,we can just press enter after ending a line into three quotes' string.
print ("""I read in class 9.
which class do you read in?""")
#we can use + between two strings under same command for displaying them jointly.
# this is called string concatenation.
print ("I am a coder."+"I am learning python.")
# we can also use comma between two string or a strind and integer/float value.
# comma give spaces automatically after each of its part.
print("I read in class",9)
#if we use single quotes in the string ,we should use double quotes outside of the string.
#if we use double quotes in the string ,we should use single quotes outside of the string.
#if we want to use extra quote in string and we want to display that quote, we need to put an \ before that quote.
print ("I love programming \" do you?")
#if we want to display \, just put it in its place.
#but some string may have words like \news, \talk,This time we have to put another \ before \.
print("I want to print\\news")
# string repetition
# we can multiply string with integer. it is called repetition.
print("Boo! "*4)
# all the work that we have done before using back-slash are called "escape sequence"
# there are lots more escape sequence.
# sequence intro
# \\ single back-slash
# \' single quote
# \" double quote
# \a ASCII Bell (BEL)
# \b ASCII Backspace (BS)
# \f ASCII Formfeed (FF)
# \n ASCII Linefeed (LF)
# \r ASCII Carriage Return (CR)
# \t ASCII Horizontal Tab (TAB)
# \v ASCII Vertical Tab (VT)
# \ooo Character with octal value ooo
# \xhh Character with hex value hh
# \N{name} Character named name in the Unicode database
# \uxxxx Character with 16-bit hex value xxxx. Exactly four hexadecimal digits are required.
# \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx. Exactly eight hexadecimal digits are required.
# to learn more, we can go to
"http://python-ds.com/python-3-escape-sequences" | true |
0812e177cd0f9b5e766f6f981b4bc1947946fa22 | akhilreddy89853/programs | /python/Natural.py | 288 | 4.125 | 4 | Number1 = int(input("How many natural numbers you want to print?"))
Count = 0
Counter = 1
print("The first " + str(Number1) + " natural numbers are", end = '')
while(Count < Number1):
print(" "+str(Counter), end = '')
Counter = Counter + 1
Count = Count + 1
print(".")
| true |
7a9ed1b59eca36822827d20359aa1b1eb9292d52 | JeRusakow/epam_python_course | /homework7/task2/hw2.py | 1,861 | 4.4375 | 4 | """
Given two strings. Return if they are equal when both are typed into
empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Examples:
Input: s = "ab#c", t = "ad#c"
Output: True
# Both s and t become "ac".
Input: s = "a##c", t = "#a#c"
Output: True
Explanation: Both s and t become "c".
Input: a = "a#c", t = "b"
Output: False
Explanation: s becomes "c" while t becomes "b".
"""
from itertools import zip_longest
from typing import Generator
def backspace_compare(first: str, second: str) -> bool: # noqa: CCR001
"""
Compares two strings as if they were printed into text editor.
Args:
first: A string which should rather be understood as a command flow.
Each letter means a key pressed, "#" means backspace.
second: The same as first
Returns:
True, if both command flow cause the same text to appear on the editor,
false otherwise
"""
def simulate_text_editor(commands: str) -> Generator[str, None, None]:
"""
Simulates text editor behaviour
Args:
commands: A flow of keys pressed. Consisits of letters and '#' signs.
'#' sign means 'Backspace' pressed.
Returns:
A generator yielding chars in text editor window in reversed order
"""
chars_to_skip = 0
for char in reversed(commands):
if char == "#":
chars_to_skip += 1
continue
if chars_to_skip > 0:
chars_to_skip -= 1
continue
yield char
for char1, char2 in zip_longest(
simulate_text_editor(first), simulate_text_editor(second)
):
if char1 != char2:
return False
return True
| true |
f226cabe15ea1b978dcb8015c040575394d90fbf | JeRusakow/epam_python_course | /tests/test_homework1/test_fibonacci.py | 1,083 | 4.125 | 4 | from homework1.task2.fibonacci.task02 import check_fibonacci
def test_complete_sequence():
"""Tests if true sequence starting from [0, 1, 1, ... ] passes the check"""
test_data = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
assert check_fibonacci(test_data)
def test_sequence_fragment():
"""Tests if true sequence not starting from [0, 1, 1, ... ] also passes the check"""
test_data = [5, 8, 13, 21, 34, 55, 89]
assert check_fibonacci(test_data)
def test_wrong_sequence():
"""Tests if a wrong sequence does not pass the test"""
test_data = [1, 1, 5, 8, 6, 3]
assert not check_fibonacci(test_data)
def test_rightful_sequence_with_wrong_beginning():
"""Tests if a sequence built with correct rules but with wrong initial values fails the check"""
test_data = [5, 6, 11, 17, 28, 45, 73]
assert not check_fibonacci(test_data)
def test_reversed_fibonacci_sequence():
"""Tests if a reversed descending sequence fails the tests"""
test_data = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
assert not check_fibonacci(test_data)
| true |
95bdedbc353d1b86f536777b28f8fca63990d8bc | kevindurr/MOOCs | /Georgia Tech - CS1301/Test/6.py | 1,693 | 4.21875 | 4 | #Write a function called are_anagrams. The function should
#have two parameters, a pair of strings. The function should
#return True if the strings are anagrams of one another,
#False if they are not.
#
#Two strings are considered anagrams if they have only the
#same letters, as well as the same count of each letter. For
#this problem, you should ignore spaces and capitalization.
#
#So, for us: "Elvis" and "Lives" would be considered
#anagrams. So would "Eleven plus two" and "Twelve plus one".
#
#Note that if one string can be made only out of the letters
#of another, but with duplicates, we do NOT consider them
#anagrams. For example, "Elvis" and "Live Viles" would not
#be anagrams.
#Write your function here!
def are_anagrams(s1, s2):
s1, s2 = s1.lower(), s2.lower()
charArray = {}
for char in s1:
if not char.isalpha():
continue
if char not in charArray:
charArray[char] = 0
charArray[char] += 1
for char in s2:
if not char.isalpha():
continue
if char not in charArray:
return False
charArray[char] -= 1
for v in charArray.values():
if v != 0:
return False
return True
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: True, False, True, False, each on their own line.
print(are_anagrams("Elvis", "Lives"))
print(are_anagrams("Elvis", "Live Viles"))
print(are_anagrams("Eleven plus two", "Twelve plus one"))
print(are_anagrams("Nine minus seven", "Five minus three"))
| true |
622b856988a7621b09fca280ba2564a593df37e1 | kevindurr/MOOCs | /Georgia Tech - CS1301/Objects & Algos/Algos_5_2/Problem_Set/5.py | 1,403 | 4.375 | 4 | #Write a function called search_for_string() that takes two
#parameters, a list of strings, and a string. This function
#should return a list of all the indices at which the
#string is found within the list.
#
#You may assume that you do not need to search inside the
#items in the list; for examples:
#
# search_for_string(["bob", "burgers", "tina", "bob"], "bob")
# -> [0,3]
# search_for_string(["bob", "burgers", "tina", "bob"], "bae")
# -> []
# search_for_string(["bob", "bobby", "bob"])
# -> [0, 2]
#
#Use a linear search algorithm to achieve this. Do not
#use the list method index.
#
#Recall also that one benefit of Python's general leniency
#with types is that algorithms written for integers easily
#work for strings. In writing search_for_string(), make sure
#it will work on integers as well -- we'll test it on
#both.
#Write your code here!
def search_for_string(lst, target):
indexes = []
for i in range(len(lst)):
if target == lst[i]:
indexes.append(i)
return indexes
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: [1, 4, 5]
sample_list = ["artichoke", "turnip", "tomato", "potato", "turnip", "turnip", "artichoke"]
print(search_for_string(sample_list, "turnip"))
| true |
a7b544425be8d629667975fc19983028bbe51136 | Ebi-aftahi/Files_rw | /word_freq.py | 735 | 4.125 | 4 | import csv
import sys
import os
file_name = input();
if not os.path.exists(file_name): # Make sure file exists
print('File does not exist!')
sys.exit(1) # 1 indicates error
items_set = []
with open(file_name, 'r') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',') # Returns lines in a list
for row in csv_reader:
[items_set.append(item) for item in row if item not in items_set]
# print(row)
# print(items_set)
for item in items_set:
print('{} {}'.format(item, row.count(item)))
# better method:
# for row in csv_reader:
# items_set = set(row)
# or
## for row in csv_reader:
# items_list = list(set(row))
| true |
7bb3dc041d323337163fab2cf5a19ef6e97c94c2 | DharaniMuli/PythonAndDeepLearning | /ICPs/ICP-3/Program1_e.py | 1,627 | 4.21875 | 4 | class Employee:
data_counter = 0
total_avg_salary = 0
total_salary = 0
# List is a class so I am creating an object for class
mylist = list()
def __init__(self, name, family, salary, department):
self.empname = name
self.empfamily = family
self.empsalary = salary
self.empdepartment = department
self.datamemberdefination()
# Append is a method in the list class so calling using list object
# Storing all the salaries into list
self.mylist.append(self.empsalary)
Employee.total_salary = Employee.total_salary + self.empsalary
def datamemberdefination(self):
Employee.data_counter = Employee.data_counter + 1
def avg_salary(self):
Employee.total_avg_salary = Employee.total_salary / Employee.data_counter
# This is a derived class 'FulltimeEmployee' inheriting base class 'employee'
class FulltimeEmployee(Employee):
maxsalary =0
def __init__(self, name, family, salary, department):
Employee.__init__(self, name, family, salary, department)
def highestsalary(self):
#Access base class list object
list1= Employee.mylist
# Finding Max salary
maxsalary = max(list1)
return maxsalary
if __name__ == '__main__':
e = Employee("Rani", "M", 2, "Developer")
f1 = FulltimeEmployee("Nani", "K", 3, "DataScientist")
#Access base class method
f1.avg_salary()
print("Average of Salary:",Employee.total_avg_salary)
f1.highestsalary()
#Access Derived class method
print("Highest Salary:",f1.highestsalary()) | true |
df79f1a4a72a30fe40de567859db42fbb44e8f5d | echedgy/prg105fall | /3.3 Nested Ifs.py | 1,247 | 4.21875 | 4 | package = input("Which package do you have? (A, B, C): ")
print("You entered Package " + package)
minutes_used = int(input("How many minutes did you use this month? "))
package_price = 0.0
if package == "A" or package == "a":
package_price = 39.99
if minutes_used > 450:
additional_minutes = minutes_used - 450
minutes_cost = additional_minutes * .45
total_cost = package_price + minutes_cost
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(total_cost, ',.2f'))
else:
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(package_price, '.2f'))
elif package == "B" or package == "b":
package_price = 59.99
additional_minutes = minutes_used - 900
minutes_cost = additional_minutes + .40
total_cost = package_price + minutes_cost
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(total_cost, '2.f'))
elif package == "C" or package == "c":
package_price = 69.99
print("With package " + package + " you owe: $" + format(package_price, ' .2f'))
else:
print("That is not a valid package.")
| true |
93746c4f02729852c13d04b1de64a729a6a07dd8 | echedgy/prg105fall | /11.2 Production Worker.py | 816 | 4.28125 | 4 | # Once you have written the classes, write a program that creates an object of the ProductionWorker class and prompts
# the user to enter data for each of the object’s data attributes.
# Store the data in the object and then use the object’s accessor methods to retrieve it and display it on the screen.
import employee
def main():
name = input("Employee's name: ")
number = input("Employees's number: ")
shift = input("Employees's Shift: ")
pay = input("Employee's pay rate: ")
new_employee = employee.ProductionWorker(name, number, shift, pay)
print("\nEmployee name: " + new_employee.get_employee_name() + "\nEmployee Number: " + new_employee.get_employee_number() + "\nShift: " + new_employee.get_shift() + "\nPay Rate: " + new_employee.get_pay_rate())
main()
| true |
112a19946aef220606d17f2f547e67a58da7da03 | echedgy/prg105fall | /2.3 Ingredient Adjuster.py | 1,089 | 4.46875 | 4 | # A cookie recipe calls for the following ingredients:
# 1.5 cups of sugar
# 1 cup of butter
# 2.75 cups of flour
# The recipe produces 48 cookies with this amount of ingredients. Write a program that asks the user
# how many cookies they want to make, and then displays the number of cups
# (to two decimal places) of each ingredient needed for the specified number of cookies.
COOKIE_NUMBER = 48
cupsOfSugar_cookie_num = 1.5/COOKIE_NUMBER
cupsOfButter_cookie_num = 1/COOKIE_NUMBER
cupsOfFlour_cookie_num = 2.75/COOKIE_NUMBER
userNumber_of_cookies = int(input('How many cookies do you want to make? '))
print("For " + str(userNumber_of_cookies) + " cookies, you will need")
expectedCupsOfSugar = userNumber_of_cookies * cupsOfSugar_cookie_num
expectedCupsOfButter = userNumber_of_cookies * cupsOfButter_cookie_num
expectedCupsOfFlour = userNumber_of_cookies * cupsOfFlour_cookie_num
print(format(expectedCupsOfSugar, ".2f") + " cups of sugar, " + format(expectedCupsOfButter, ".2f") + " cups of butter and " + format(expectedCupsOfFlour, ".2f") + " cups of flour")
| true |
08e291f0d7343d98f559e10755ac64ebf74d652c | varaste/Practice | /Python/PL/Python Basic-Exercise-6.py | 1,064 | 4.375 | 4 | '''
Python Basic: Exercise-6 with Solution
Write a Python program which accepts a sequence of comma-separated numbers
from user and generate a list and a tuple with those numbers.
Python list:
A list is a container which holds comma separated values (items or elements)
between square brackets where items or elements need not all have the same type.
In general, we can define a list as an object that contains multiple data items
(elements). The contents of a list can be changed during program execution.
The size of a list can also change during execution, as elements are added or
removed from it.
Python tuple:
A tuple is container which holds a series of comma separated values
(items or elements) between parentheses such as an (x, y) co-ordinate.
Tuples are like lists, except they are immutable (i.e. you cannot change its
content once created) and can hold mix data types.
'''
vals = input("Enter values comma seprated: ")
v_list = vals.split(",")
v_tuple = tuple(v_list)
print("List: ", v_list)
print("Tuple ", v_tuple) | true |
6fdf3e5c757f7de27c6afb54d6728116d9f3ae55 | varaste/Practice | /Python/PL/Python Basic-Exercise-4.py | 553 | 4.3125 | 4 | '''
Write a Python program which accepts the radius of a circle from the user and
compute the area.
Python: Area of a Circle
In geometry, the area enclosed by a circle of radius r is πr2.
Here the Greek letter π represents a constant, approximately equal to 3.14159,
which is equal to the ratio of the circumference of any circle to its diameter.
'''
from math import pi
rad = float(input("Input the radius of the circle: "))
a_circle = (rad**2) * pi
print("The area of the cirvle with radius" + str(rad) + " is: " + str(a_circle)) | true |
0173ae9e82213f4f01ccc6239a152b7ad0c5f8ad | varaste/Practice | /Python/PL/Python tkinter widgets-Exercise-8.py | 756 | 4.21875 | 4 | '''
Python tkinter widgets: Exercise-8 with Solution
Write a Python GUI program to create three single line text-box to accept a
value from the user using tkinter module.
'''
import tkinter as tk
parent = tk.Tk()
parent.geometry("400x250")
name = tk.Label(parent, text = "Name").place(x = 30, y = 50)
email = tk.Label(parent, text = "User ID").place(x = 30, y = 90)
password = tk.Label(parent, text = "Password").place(x = 30, y = 130)
sbmitbtn = tk.Button(parent, text = "Submit", activebackground = "green", activeforeground = "blue").place(x = 120, y = 170)
entry1 = tk.Entry(parent).place(x = 85, y = 50)
entry2 = tk.Entry(parent).place(x = 85, y = 90)
entry3 = tk.Entry(parent).place(x = 90, y = 130)
parent.mainloop()
| true |
285451e05017f8598ff68eb73ae537ca2e0922a5 | varaste/Practice | /Python/PL/Python Basic-Exercise-27-28-29.py | 1,554 | 4.1875 | 4 | '''
Python Basic: Exercise-27 with Solution
Write a Python program to concatenate all elements in a list into a string and return it.
'''
def concat(list):
output = ""
for element in list:
output = output + str(element)
return output
print(concat([1, 4, 0, 0,"/" , 0, 7,"/" ,2, 0]))
'''
Python Basic: Exercise-28 with Solution
Write a Python program to print out all even numbers from a given numbers list
in the same order and stop the printing if any numbers that come after 237 in
the sequence.
'''
numbers_list = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
for n in numbers_list:
if n == 237:
print (n)
break;
elif n % 2 == 0:
print(n)
'''
Python Basic: Exercise-29 with Solution
Write a Python program to print out a set containing all the colors from
color_list_1 which are not present in color_list_2.
Test Data:
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
Expected Output :
{'Black', 'White'}
'''
list1 = set(["White", "Black", "Red"])
list2 = set(["Red", "Green"])
def is_in_color_list(list1, list2):
output_list = list1.difference(list2)
return output_list
print(is_in_color_list(list1, list2))
print(is_in_color_list(list2, list1))
| true |
0ed76e4bb935107504ffed0f3b77804d7f42cdc2 | varaste/Practice | /Python/PL/Python tkinter widgets-Exercise-7.py | 688 | 4.21875 | 4 | '''
Python tkinter widgets: Exercise-7 with Solution
Write a Python GUI program to create a Text widget using tkinter module.
Insert a string at the beginning then insert a string into the current text.
Delete the first and last character of the text.
'''
import tkinter as tk
parent = tk.Tk()
# create the widget.
mytext = tk.Text(parent)
# insert a string at the beginning
mytext.insert('1.0', "- Python exercises, solution -")
# insert a string into the current text
mytext.insert('1.19', ' Practice,')
# delete the first and last character (including a newline character)
mytext.delete('1.0')
mytext.delete('end - 2 chars')
mytext.pack()
parent.mainloop() | true |
897a1b3f11bc3f0352e61ed6802094bd6c341729 | michalkasiarz/automate-the-boring-stuff-with-python | /regular-expressions/usingQuestionMark.py | 499 | 4.125 | 4 | import re
# using question mark -> for something that appears 1 or 0 times (preceding pattern)
batRegex = re.compile(r"Bat(wo)?man")
mo = batRegex.search("The Adventures of Batman")
print(mo.group()) # Batman
mo = batRegex.search("The Adventures of Batwoman")
print((mo.group())) # Batwoman
# another example with ? inside pattern
dinRegex = re.compile(r"dinner\?") # we are looking for dinner?
mo = dinRegex.search("Do you fancy a dinner? Because he does not. So sad.")
print(mo.group())
| true |
9393e65692d8820d71fdda043da48ec33658b467 | michalkasiarz/automate-the-boring-stuff-with-python | /dictionaries/dataStructures.py | 686 | 4.125 | 4 | # Introduction to data structure
def printCats(cats):
for item in cats:
print("Cat info: \n")
print("Name: " + str(item.get("name")) +
"\nAge: " + str(item.get("age")) +
"\nColor: " + str(item.get("color")))
print()
cat = {"name": "Parys", "age": 7, "color": "gray"}
allCats = [] # this is going to be a list of dictionaries
allCats.append({"name": "Parys", "age": 7, "color": "gray"})
allCats.append({"name": "Burek", "age": 5, "color": "white"})
allCats.append({"name": "Mruczek", "age": 12, "color": "black"})
allCats.append({"name": "Fajter", "age": 2, "color": "black-white"})
printCats(allCats)
| true |
c795f6ac170f96b398121ddbbc9a22cf13835061 | AshwinBalaji52/Artificial-Intelligence | /N-Queen using Backtracking/N-Queen_comments.py | 2,940 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 00:42:23 2021
@author: Ashwin Balaji
"""
class chessBoard:
def __init__(self, dimension):
# board has dimensions dimension x dimension
self.dimension = dimension
# columns[r] is a number c if a queen is placed at row r and column c.
# columns[r] is out of range if no queen is place in row r.
# Thus after all queens are placed, they will be at positions
# (columns[0], 0), (columns[1], 1), ... (columns[dimension - 1], dimension - 1)
self.columns = []
def matrixdimension(self):
return self.dimension
def evaluateQueens(self):
return len(self.columns)
def backtrackNextRow(self, column):
self.columns.append(column)
def popQueen(self):
return self.columns.pop()
def isSafe(self, column):
# index of next row
row = len(self.columns)
# check column
for queeninColumn in self.columns:
if column == queeninColumn:
return False
# check diagonal
for queeninRow, queeninColumn in enumerate(self.columns):
if queeninColumn - queeninRow == column - row:
return False
# check other diagonal
for queeninRow, queeninColumn in enumerate(self.columns):
if ((self.dimension - queeninColumn) - queeninRow
== (self.dimension - column) - row):
return False
return True
def display(self):
for row in range(self.dimension):
for column in range(self.dimension):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()
def displaySolutions(dimension):
"""Display a chessboard for each possible configuration of placing n queens
on an n x n chessboard where n = dimension and print the number of such
configurations."""
board = chessBoard(dimension)
possibleSolutions = solutionBacktracker(board)
print('Number of solutions:', possibleSolutions)
def solutionBacktracker(board):
"""Display a chessboard for each possible configuration of filling the given
board with queens and return the number of such configurations."""
dimension = board.matrixdimension()
# if board is full, display solution
if dimension == board.evaluateQueens():
board.display()
print()
return 1
possibleSolutions = 0
for column in range(dimension):
if board.isSafe(column):
board.backtrackNextRow(column)
possibleSolutions += solutionBacktracker(board)
board.popQueen()
return possibleSolutions
size = int(input('Dimensions : '))
displaySolutions(size) | true |
dee277547fa6e80610a419c7285ff2074e0078cf | tejadeep/Python_files | /tej_python/basics/add.py | 287 | 4.28125 | 4 | #program by adding two numbers
a=10
b=20
print"%d+%d=%d"%(a,b,a+b) #this is one method to print using format specifiers
print"{0}+{1}={2}".format(a,b,a+b) #this is one method using braces
#0 1 2
print"{1}+{0}={2}".format(a,b,a+b) # here output is 20+10=30
| true |
0ddac05ddceaa96fc1a31d35d43e91bedd70dc8e | dannikaaa/100-Days-of-Code | /Beginner Section/Day2-BMI-Calulator.py | 418 | 4.3125 | 4 | #Create a BMI Calculator
#BMI forumula
#bmi = weight/height**2
height = input("Enter your height in m: ")
weight = input("Enter your weight in kg: ")
#find out the type of height & weight
#print(type(height))
#print(type(weight))
#change the types into int & float
int_weight = int(weight)
float_height = float(height)
#change bmi type as well
bmi = int_weight/float_height**2
int_bmi = int(bmi)
print(int_bmi)
| true |
3fd9c30f76f11696abac88e60cc1ce28c212b729 | akashbhalotia/College | /Python/Assignment1/012.py | 554 | 4.25 | 4 | # WAP to sort a list of tuples by second item.
# list1.sort() modifies list1
# sorted(list1) would have not modified it, but returned a sorted list.
def second(ele):
return ele[1]
def sortTuples(list1):
list1.sort(key=second)
inputList = [(1, 2), (1, 3), (3, 3), (0, 3), (3, 5), (7, 2), (5, 5)]
print('Input List:', inputList)
sortTuples(inputList)
print('\nSorted:', inputList)
###########################################################################
# Another way to do it:
def sortTuples(list1):
list1.sort(key=lambda x: x[1])
| true |
c52de657a3ae4643f627703138e86bc03d8383dc | momentum-cohort-2019-02/w3d3-oo-pig-yyapuncich | /pig.py | 2,594 | 4.15625 | 4 | import random
class ComputerPerson:
"""
Computer player that will play against the user.
"""
def __init__(self, name, current_score=0):
"""
Computer player will roll die, and automatically select to roll again or hold for each turn. They will display their turn totals after each turn.
"""
self.name = name
self.current_score = current_score
def roll_die(self):
"""
Roll dice for random result range 1-6. Return the number.
"""
return random.randint(1, 6)
def current_score(game, turn_total):
"""
Keep track of the player's total score by adding all the turn_total values as the game progresses
"""
pass
def choose():
"""
Returns value of hold or roll depending on random choice.
"""
choices = ['HOLD', 'ROLL']
return random.choice(choices)
class PersonPerson:
"""
Human player that will play against computer. They will choose by user input each turn to roll, or hold. Score totals will display after each turn.
"""
def __init__(self, name, current_score=0):
self.name = name
self.current_score = current_score
def roll_die(self):
"""
Roll dice for random result range 1-6. Return the number.
"""
return random.randint(1, 6)
def current_score(game, turn_total):
"""
Keep track of the player's total score by adding all the turn_total values as the game progresses
"""
pass
def choose():
"""
Returns value of hold or roll depending on user input.
"""
pass
class Game:
"""
Controls the flow of the game: keeps track of scores, who's turn it is, who wins, and if you want to play again. The goal is to reach 100 points.
"""
def __init__(self, comp_player, pers_player, current_winner):
# self.current_player = None
self.current_winner = None
# self.choose = None
self.comp_player = comp_player
self.pers_player = pers_player
def begin_game(self):
"""
Allow PersonPerson and CompterPerson to roll die. The largest number gets to go first and roll!
"""
pass
def turn_total(dice_roll):
"""
For each turn the player will roll dice. If they don't roll a 1 they will add all the numbers for a turn_total. Otherwise add 0 to the turn_total
"""
pass
if __name__ == "__main__":
print(Game.roll_die())
print(ComputerPerson.choose()) | true |
b6d518a4d5c829045cc4b19c1a0630422cf38050 | SwethaVijayaraju/Python_lesson | /Assignments/Loops/Biggest number divisible.py | 522 | 4.25 | 4 | #write a function that returns the biggest number divisible by a divisor within some range.
def biggest(num1,num2,divisor):
bignum=None
while num1<=num2:
if (num1%divisor)==0:
bignum=num1
num1=num1+1
return bignum
print(biggest(1,10,2)) #answer should be 10
#write a function that returns the biggest number divisible by a divisor within some range.
def biggest(num1,num2,divisor):
while num2>=num1:
if (num2%divisor)==0:
return num2
num2=num2-1
print(biggest(1,10,2)) #answer should be 10
| true |
db73a48731ed073e252d56eedc05c98588ba1675 | jayednahain/python-Function | /function_mix_calculation.py | 386 | 4.15625 | 4 |
def addition(x,y):
z=x+y
return print("the addtion is: ",z)
def substruction(x,y):
z=x-y
return print("the substruction is : ",z)
def multiplication(x,y):
z=x*y
return print("the multiplication is :",z)
a = int(input("enter a number one : "))
b = int(input("enter second number: "))
addition(a,b)
multiplication(a,b)
substruction(a,b) | true |
7a3c29e08029bdbfd42dbda0b6cc6c22144d01c8 | Nate-17/LetsUpgrade-Python | /primenumber.py | 444 | 4.28125 | 4 | '''
This is a module to check weather the given number is even or odd.''
'''
def prime(num):
'''
This is the main function which check out the given number is even or odd.
'''
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
return print("It is a Prime Number")
return print("It is not a Prime Number")
n = int(input("enter the number :"))
prime(n)
| true |
686c1f0c8ebec7caade9bd99e8c45b5581e421e1 | SweetLejo/DATA110 | /past_exercises_leo/yig012_t2.py | 1,562 | 4.28125 | 4 | #Oppgave 1
from math import pi #imports pi from the math library, since its the only thing I'll use in this exercise it felt redundant to import the whole library
radius = float(input('Radius: ')) #promts the user to enter a radius
area = round((radius**2)*pi, 3) #defines a variable as the area, and rounds it to 3 decimals
print(area)
#oppgave 2
sentance = input('sentance: ') #prompts user to enter a sentance
guess = int(input('Guess: ')) #prompts the user to guess the length of his sentance, and converts it to the data-type int
sentance = sentance.replace(' ', '') #removes whitespace (' ') so that the length does not include it (len('hej jeg er glad') -> 12 (not 15), could also be done with commas etc
#Line 12 is not a part of the exercise but I felt it made sense so why not :D
print(f"That's {len(sentance) == guess}!!") #prints a f-string with a bool, hence True or False
#Personally I would've solved this using conditional execution btw
#oppgave 3
from random import randint #Same logic as in 1
number = input('Give me a number: ') #Prompts user to enter a number (this is already a string)
rnumber= str(randint(1, 10)) #new variable is a random number between 1-10 (has to be a string so that 1+2 = 12 (see line 20))
answer = int(number+rnumber)/int(number) #finds the answer of the sum of the two strings given above divided by the old number (convertet to ints (answer is float))
print(number+rnumber, '/', number,' = ', answer, sep='') #print, removed whitespace beacuase that's what it looked like in the exercise | true |
fac04373d57b33f9dd8298e01aaf36f0ebb3fb75 | wonderme88/python-projects | /src/revstring.py | 285 | 4.40625 | 4 |
# This program is to reverse the string
def revStr(value):
return value[::-1]
str1 = "my name is chanchal"
str2 = "birender"
str3 = "chanchal"
#print revStr(str1)
list = []
list.append(str1)
list.append(str2)
list.append(str3)
print (list)
for x in list:
print revStr(x)
| true |
e10a0af7adca68109ebeb211ad994b2877c5a52d | EugenieFontugne/my-first-blog | /test/python_intro.py | 835 | 4.125 | 4 | volume = 18
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the details")
elif 60 <= volume < 80:
print("Nice for parties")
elif 80 <= volume < 100:
print("A bit loud!")
else:
print("My hears are hurting!")
# Change the volume if it's too loud or too quiet
if volume < 20 or volume > 80:
volume = 50
print("That's better!")
def hi():
print("Hi there!")
print("How are you?")
hi()
def hi(name):
if name == "Ola":
print("Hi Ola!")
elif name == "Sonja":
print("Hi Sonja")
else:
print("Hi anonymous")
hi("Ola")
hi("Eugenie")
def hi(name):
print("Hi" + name + "!")
girls = ["Rachel", "Monica", "Phoebe", "Ola", "You"]
for name in girls:
hi(name)
print("next girl")
for i in range(1, 6):
print(i)
| true |
3eb6198afa9481a86e43c80b29b1156c64108dc0 | JI007/birthdays | /birthday search.py | 2,316 | 4.3125 | 4 | def birthday():
birthdays = {'Jan': ' ','Feb': ' ', 'Mar': ' ', 'Apr': ' ', 'May': 'Tiana (10), Tajmara (11) ', 'June': ' ', 'July': 'Jamal (7)', 'Aug': 'Richard (7) ', 'Sept': 'Nazira (16) ', 'Oct': ' ', 'Nov': ' ', 'Dec': ' '}
birthday()
# Welcomes the user to the program
print("\n\n\t\tWelcome to the Birthday Finder!\n\t\t-------------------------------")
# Create a list consisting of a calendar
Calendar = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
# Display available search types
print("\nSearch Type:\n\n 1. Month\n 2. Person")
# Ask the user for the search type
searchType = input("\nEnter '1' or '2' as Search Type: ")
# Create conditions based on users search type
if searchType == "1": #(Month)
print("\nMonth:\n--------\n1.Jan.\t2.Feb.\t3.Mar.\t4.April\t5.May\t6.June\n7.July\t8.Aug.\t9.Sept.\t10.Oct.\t11.Nov.\t12.Dec.")
month = input("\nEnter the number of the desired month: ")
if month == "1":
print(Calendar[0])
print(birthdays['Jan'])
elif month == "2":
print(Calendar[1])
print(birthdays['Feb'])
elif month == "3":
print(Calendar[2])
print(birthdays['Mar'])
elif month == "4":
print(Calendar[3])
print(birthdays['Apr'])
elif month == "5":
print(Calendar[4])
print(birthdays['May'])
elif month == "6":
print(Calendar[5])
print(birthdays['June'])
elif month == "7":
print(Calendar[6])
print(birthdays['July'])
elif month == "8":
print(Calendar[7])
print(birthdays['Aug'])
elif month == "9":
print(Calendar[8])
print(birthdays['Sept'])
elif month == "10":
print(Calendar[9])
print(birthdays['Oct'])
elif month == "11":
print(Calendar[10])
print(birthdays['Nov'])
elif month == "12":
print(Calendar[11])
print(birthdays['Dec'])
else:
print("Invalid Entry!")
elif searchType == "2": #(Person)
person = input("\nEnter the first name of person: ")
print("\nThe birthday of", person, "is", )
else:
print("Invalid Type!")
input("\nPress the enter key to exit.")
| true |
df97a2008ef5f6576c0d100699bef3a4ce706400 | Shamita29/266581dailypractice | /set/minmax.py | 455 | 4.21875 | 4 | #program to find minimum and maximum value in set
def Maximum(sets):
return max(sets)
def Minimum(sets):
return min(sets)
"""
setlist=set([2,3,5,6,8,28])
print(setlist)
print("Max in set is: ",Maximum(setlist))
print("Min in set is: ",Minimum(setlist))
"""
print("Enter elements to be added in set")
sets = set(map(int, input().split()))
#print(sets)
print("Maximum value in set is: ",Maximum(sets))
print("Minimum value in set is: ", Minimum(sets)) | true |
3165bc53048b76a1fc5c7bc58bef2663c595f69e | zmatteson/epi-python | /chapter_4/4_7.py | 335 | 4.28125 | 4 | """
Write a program that takes a double x and an integer y and returns x**y
You can ignore overflow and overflow
"""
#Brute force
def find_power(x,y):
if y == 0:
return 1.0
result = 1.0
while y:
result = x * result
y = y - 1
return result
if __name__ == "__main__":
print(find_power(3,1)) | true |
7bfff88b28253ec0f69e3c93dc01c29be200e71b | zmatteson/epi-python | /chapter_13/13_1.py | 1,092 | 4.1875 | 4 | """
Compute the intersection of two sorted arrays
One way: take the set of both, and compute the intersection (Time O(n + m) )
Other way: search in the larger for values of the smaller (Time O(n log m ) )
Other way: start at both and walk through each, skipping where appropriate (Time O(n + n) , space O(intersection m & n) )
#Assume A is always larger than B
"""
def compute_intersection(A, B):
intersection = []
i, j = 0, 0
while i < len(B) and j < len(A):
while i < len(B) and (B[i] < A[j]): #skip duplicates and fast forward
i += 1
while (j < len(A) and i < len(B)) and (A[j] < B[i]):
j += 1
b, a = B[i], A[j]
print(b,a)
if b == a:
intersection.append(b)
i += 1
j += 1
while i < len(B) and B[i] == b: #skip duplicates
i += 1
while j < len(A) and A[j] == a:
j += 1
return intersection
if __name__ == '__main__':
B = [1, 2, 3, 3, 4, 5, 6, 7, 8]
A = [1, 1, 5, 7]
print(compute_intersection(A,B)) | true |
af77d80d6b95b5dc847f33ba0783b5fcc7c872d6 | zmatteson/epi-python | /chapter_5/5_1.py | 1,620 | 4.21875 | 4 | """
The Dutch National Flag Problem
The quicksort algorith for sorting arrays proceeds recursively--it selects an element
("the pivot"), reorders the array to make all the elements less than or equal to the
pivot appear first, followed by all the elements greater than the pivot. The two
subarrays are then sorted recursively.
Implemented naively, quicksort has large run times and deep functioncall stacks on
arrays with many dupicates because the subarrays may differ greatly in size. One
solution is to reorder the array so that all elements less than the pivot appear first,
followed by elements equal to the pivot, followed by elements greater than the pivot.
This is known as the Dutch National Flag partitioning because the Dutch national flag
consists of 3 horizontal bands of different colors.
Write a program that takes an array A and an index i into A, and rearrange the elements
such that all elements less than A[i] appear first, followed by elements equal to the
pivot, followed by elements greater than the pivot
EXAMPLE:
A = [1,2,0] i = 2, A[i] = 0
Return [0,1,2]
"""
#Brute force/Brute space
def partition_array(A, i):
L = []
M = []
R = []
for x in A:
if x < A[i]:
L.append(x)
elif x == A[i]:
M.append(x)
else:
R.append(x)
return L + M + R
if __name__ == "__main__":
A = [1,2,0]
print("A is ", A)
print("A partioned with pivot at index 2 is ", partition_array(A, 2))
A = [1,2,3,1,1,10,0,1,5,1,0]
print("A is ", A)
print("A partioned with pivot at index 2 is ", partition_array(A, 2))
| true |
d3e57c2ec3133003e2d8d5f67c2aee403e3ab0e8 | zmatteson/epi-python | /chapter_14/14_1.py | 959 | 4.15625 | 4 | """
test if a tree satisfies the BST property
What is a BST?
"""
class TreeNode:
def __init__(self, left = None, right = None, key = None):
self.left = left
self.right = right
self.key = key
def check_bst(root):
max_num = float('inf')
min_num = float('-inf')
return check_bst_helper(root, max_num, min_num)
def check_bst_helper(root, max_num, min_num):
if not root:
return True
elif root.key > max_num or root.key < min_num:
print(root.key, max_num, min_num)
return False
return (check_bst_helper(root.left, root.key, min_num) and check_bst_helper(root.right, max_num, root.key))
if __name__ == '__main__':
nodeE = TreeNode(None,None, 9)
nodeD = TreeNode(None,nodeE,7)
left = TreeNode(None,nodeD,5)
right = TreeNode(None,None,15)
root = TreeNode(left, right, 10)
print(check_bst(root))
# 10
# 5 15
# 7
# 2 | true |
cad9a59e7ed85cd5f9c7cea130d6589ee7a70bd9 | Pyae-Sone-Nyo-Hmine/Ciphers | /Caesar cipher.py | 1,362 | 4.46875 | 4 | def encode_caesar(string, shift_amt):
''' Encodes the specified `string` using a Caesar cipher with shift `shift_amt`
Parameters
----------
string : str
The string to encode.
shift_amt : int
How much to shift the alphabet by.
'''
answer = ""
for i in range(len(string)):
letter = string[i]
if (letter.isupper()):
if (ord(letter) + shift_amt) <= 90:
answer += chr((ord(letter) + shift_amt ))
elif (ord(letter) + shift_amt) > 90 and (ord(letter) + shift_amt + 6) <= 122:
answer += chr((ord(letter) + shift_amt + 6))
elif (ord(letter) + shift_amt + 6) > 122:
answer += chr((ord(letter) + shift_amt -52))
if (letter.islower()):
if (ord(letter) + shift_amt) <= 122:
answer += chr((ord(letter) + shift_amt ))
elif (ord(letter) + shift_amt) > 122 and (ord(letter) + shift_amt) <=148 :
answer += chr((ord(letter) + shift_amt - 52-6))
elif (ord(letter) + shift_amt) > 148:
answer += chr((ord(letter) + shift_amt - 52))
if (letter.isspace()):
answer += string[i]
if (letter.isnumeric()):
answer += string[i]
return answer
| true |
de6be7734a7996f5bbea60637be01ed928b7ddb4 | v4vishalchauhan/Python | /emirp_number.py | 669 | 4.28125 | 4 | """Code to find given number is a emirp number or not"""
"""Emirp numbers:prime nubers whose reverse is also a prime number for example:17 is a
prime number as well as its reverse 71 is also a prime number hence its a emirp number.."""
def prime_check(k):
n=int(k)
if n<=1:
return False
for i in range(2,n):
if n%int(i)==0:
return False
else:
return True
print("Enter the number: ")
l=int(input())
for num in range(l+1):
if prime_check(num)==True:
d=str(num)[::-1]
if prime_check(d)==True:
print("$$$We got it....."+str(num)+" is a Emirp number$$$")
else:
print(str(num)+ " is not a emirp number..") | true |
112da86c726bd8f3334258910eae937aff2f8db5 | ms99996/integration | /Main.py | 1,664 | 4.1875 | 4 | """__Author__= Miguel salinas"""
"""This is my attempt to create a mad lib """
ask = input("welcome to my mad lib, would you like to give it a try? enter "
"yes or no, the answer is case sensitive: ")
while ask not in ("yes", "no"):
ask = input("please type a valid input: ")
def get_answers(color, animal, body_parts, verb, verb2, verb3):
"""Creates a mad lib using inputs for variables inside argument. """
print("there once was a", color, animal, "that had 3", body_parts,
"it uses one part for", verb, "the next for", verb2,
"and the last for", verb3)
def main():
"""Asks user age, and many questions to create a mad lib,"""
if ask == "yes":
age = int(input("wonderful, please enter your age: "))
if age >= 16:
print("your age is", age, "you are old enough to continue")
color = input("please enter a color: ")
animal = input("please enter an animal: ")
body_parts = input("please enter a body part(plural): ")
verb = input("please enter a verb that ends with 'ing': ")
verb2 = input("please enter another verb that ends with 'ing': ")
verb3 = input("please enter one more verb that end with 'ing': ")
mad_libs = get_answers(color, animal, body_parts, verb, verb2, verb3)
# I have get_answers to print the mad lib
# I don't like how return outputs the mad lib
print(mad_libs)
else:
print("sorry but you are not old enough to continue")
else:
print("thank you and have a nice day")
main()
| true |
d6baa2d4320f15ece2bd9d628911145a1b471105 | ErenBtrk/PythonSetExercises | /Exercise7.py | 237 | 4.375 | 4 | '''
7. Write a Python program to create a union of sets.
'''
set1 = set([1,2,3,4,5])
set2 = set([6,7,8])
set3 = set1 | set2
print(set3)
#Union
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
seta = setx | sety
print(seta)
| true |
546cd33519cea7f759d09ccd11203d44fed2fc4d | sivaprasadkonduru/Python-Programs | /Sooryen_python/question3.py | 608 | 4.125 | 4 | '''
Write a function that takes an array of strings and string length (L) as input. Filter out all the string string in the array which has length ‘L’
eg.
wordsWithoutList({"a", "bb", "b", "ccc"}, 1) → {"bb", "ccc"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 3) → {"a", "bb", "b"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 4) → {"a", "bb", "b", "ccc”}
'''
def words_without_list(words, target):
return {i for i in words if not len(i) == target}
words_without_list({"a", "bb", "b", "ccc"}, 1)
words_without_list({"a", "bb", "b", "ccc"}, 3)
words_without_list({"a", "bb", "b", "ccc"}, 4)
| true |
c80c00855a308016585a2620659b44a93b218a07 | kauboy26/PyEvaluator | /miscell.py | 569 | 4.15625 | 4 | def print_help():
print 'Type in any expressions or assignment statements you want.'
print 'For example:'
print '>> a = 1 + 1'
print '2'
print '>> a = a + pow(2, 2)'
print '6'
print '\nYou can also define your own functions, in the form'
print 'def <function name>([zero or more comma separated args]) = <expression>'
print '\nFor example,'
print '>> def f(x, y) = x * y + 3'
print '>> f(2, 3)'
print '9\n'
print 'Type "print" to see all values and defined functions.'
print 'Type "help" to see this message.' | true |
76972fcaadbc52294e7e06871d1f7115e8eb6285 | jabarszcz/randompasswd | /randompasswd.py | 1,496 | 4.125 | 4 | #!/usr/bin/env python3
import argparse
import string
import random
# Create parser object with program description
parser = argparse.ArgumentParser(
description="simple script that generates a random password")
# Define program arguments
parser.add_argument("-a", "--lower", action='store_true',
help="add lowercase characters to alphabet")
parser.add_argument("-A", "--upper", action='store_true',
help="add uppercase characters to alphabet")
parser.add_argument("-1", "--num", action='store_true',
help="add digits to alphabet")
parser.add_argument("-s", "--special", action='store_true',
help="add punctuation characters to alphabet")
parser.add_argument("-c", "--characters", action='append', metavar="string",
help="add the characters from the given string")
parser.add_argument("-l", "--length", default=10, type=int, metavar ="N",
help="length of the password generated")
args = parser.parse_args()
# Create the alphabet
alphabet = ''.join(args.characters) if args.characters else []
if args.lower:
alphabet += string.ascii_lowercase
if args.upper:
alphabet += string.ascii_uppercase
if args.num:
alphabet += string.digits
if args.special:
alphabet += string.punctuation
if not alphabet:
print("Alphabet is empty!")
parser.print_help()
exit()
passwd = ''.join(random.choice(alphabet) for i in range(args.length))
print(passwd)
| true |
7fbee6b902a11525f9d8afd0f20a343126dd51b1 | isaolmez/core_python_programming | /com/isa/python/chapter6/Tuples.py | 530 | 4.4375 | 4 | ## Tuples are very similar to lists; but they are immutable
tuple1 = (1,2,3)
print tuple1
# For tuples, parantheses are redundant and this expression craetes a tuple.
# For lists we must use brackets
tuple2 = "a", "b", "c"
print tuple2
# tuple1[1] = 99 # ERROR: We cannot mutate tuple or assign new values to its elements
print tuple
tuple1 = (0, 0, 0) # But we can assign a completely new tuple
print tuple1
# Cannot delete individual elements; but can delete tuple itself
# del tuple1[1] # ERROR: We cannot mutate
del tuple1
| true |
916b10dc06df2fece2e1af6afe15b80696ea11cc | isaolmez/core_python_programming | /com/isa/python/chapter5/Exercise_5_11.py | 468 | 4.1875 | 4 | for item in range(0,21,2):
print item,
print
for item in range(0, 21):
if item % 2 == 0:
print item,
print
for item in range(1,21,2):
print item,
print
for item in range(0, 21):
if item % 2 == 1:
print item,
print
## If you omit return type, it does not give warning but returns None
def isDivisible(num1, num2):
if num1 % num2 == 0:
return True
return False
print isDivisible(10, 2)
print isDivisible(10, 20)
| true |
b433ed328d118c05a67b42d8085391af87955ba7 | isaolmez/core_python_programming | /com/isa/python/chapter7/SetOperators.py | 899 | 4.21875 | 4 | ## 1. Standard Type Operators
set1 = set([1, 2, 3, 3]) # Removes duplicates
print set1
set2 = set("isa123")
print set2
print 1 in set1
print "i" in set2
print "---- Equality test"
set1Copy = set(set1)
print "set1 == set1Copy", set1 == set1Copy
print "set1 < set1Copy", set1 < set1Copy # Strictly must be smaller. Equal sets return False with < (smaller than)
print "set1 <= set1Copy", set1 <= set1Copy # Less Strict. Equal sets return True with <=
set3 = set([1, 2, 3, 4, 5, 6])
print set1 < set3 # All of the == < > could return False. Interesting
print set1 == set3
## Set Type Operators
# union, instersection, difference, symmetric difference: | & - ^
# No + operator
print "---- Set type operators"
set1 = set([1, 2, 3, 4])
set2 = set([4, 5, 6])
print set1 | set2 # union
print set1 & set2 # intersection
print set1 - set2 # difference
print set1 ^ set2 # symmetric difference, XOR
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.