blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
e72216a516cffe0cd78432f118de9d5fb6441a47
|
kai-ca/Kai-Python-works
|
/LAB09/datastructlab/stackmodule.py
| 1,658
| 4.21875
| 4
|
"""We implement a Stack data structure.
Stack is a LIFO = Last In First Out data
structure, like a atack of plates. The last
plate you put on the stack is the first plate
that will be removed.
Tip: Print out all the test files in the tests
directory and then get to work on the metods,
one by one.
Use your Stack class to create an instance
named mystack.
>>> mystack = Stack()
>>> isinstance(mystack, Stack)
True
The Stack has a push method. Push a bunch of
numbers onto the stack.
>>> for item in [90, 30, 50, 60, 20, 50]:
... mystack.push(item)
Remove an item from the stack using the pop
method you definfed for Stack. Notice that
it's LIFO !
>>> mystack.pop()
50
>>> mystack.pop()
20
>>> mystack.is_empty()
False
"""
class Stack:
"""Stack data structure.
>>> mystack = Stack()
"""
def __init__(self):
"""Creates an instance of Stack with no items in it."""
self.data = []
def push(self, item):
"Push item onto the stack."
self.data.append(item)
def pop(self):
"""Remove the item we put in last ( remember it's LIFO). """
return self.data.pop()
def is_empty(self):
"""Returns True if the stack is empty."""
return self.data == []
def peek(self):
"""Returns the top item of the stack but does not remove that item. Just peeking."""
return self.data[-1]
def __str__(self):
"""Method for casting Stack objects as str object. Used by print."""
return "<Stack: {} items>".format(len(self.data))
if __name__ == '__main__':
import doctest
doctest.testmod()
| true
|
0da353feebc2597c645b088385db28f6f023235e
|
ramakrishna1994/SEM2
|
/NS/Assg1/d_5_Decryption_Procedure_code.py
| 2,803
| 4.28125
| 4
|
'''
Author : Saradhi Ramakrishna
Roll No : 2017H1030081H
M.E Computer Science , BITS PILANI HYDERABAD CAMPUS
Description : Takes Cipher text as input and gives the Plain text as output
Input - 1.Key
2.Cipher Text
Output - Decrypted Plain Text
Steps : 1. Shifts the cipher in the length of key by 0,1,2,3,.... (SUBTRACTION)
2. Applies Vignere Cipher Decryption Procedure by repeating the key until it satisfies
the cipher text length.
3. Finally prints the decrypted plain text onto the console.
'''
file1 = open("h20171030081_decrypted.txt","r")
originalcipher = file1.read().strip()
key = "edgarcodd"
cipheraftershifting = ""
currentlength = 0;
currentshift = -1;
'''
Function which returns the decrypted character in vignere cipher by taking
a single encrypted character and single key character.
'''
def getDecryptedCharInVignere(enc,key):
e = ord(enc)
k = ord(key)
d = ((e - k + 26) % 26) + 65 # d = ((e - k + 26) mod 26) + 65
return chr(d)
'''
Shifting Original Cipher by 0,1,2,3.... in the length of key repetitively
'''
for c in originalcipher:
if ord(c) >=65 and ord(c) <=90:
if ((currentlength % len(key)) == 0):
currentlength = 0;
currentshift += 1;
res = ord(c) - (currentshift % 26)
if res < 65:
res += 26
cipheraftershifting += str(chr(res))
currentlength = currentlength + 1
elif ord(c) >=97 and ord(c) <= 122:
if ((currentlength % len(key)) == 0):
currentlength = 0;
currentshift += 1;
res = ord(c.upper()) - (currentshift % 26) # Shifting by 0,1,2,3,... (Subtraction)
if res < 65:
res += 26
cipheraftershifting += str(chr(res).lower())
currentlength = currentlength + 1
else:
cipheraftershifting += str(c)
currentlength = 0;
plaintextafterdecryption = ""
'''
Applying Vignere Cipher breaking procedure and getting the plain text.
Key is repeated in lengths of its size until it satisfies the plain text length.
'''
for c in cipheraftershifting:
if ord(c) >= 65 and ord(c) <= 90:
if ((currentlength % len(key)) == 0):
currentlength = 0;
plaintextafterdecryption += getDecryptedCharInVignere(c.upper(),key[currentlength].upper())
currentlength = currentlength + 1
elif ord(c) >= 97 and ord(c) <= 122:
if ((currentlength % len(key)) == 0):
currentlength = 0;
plaintextafterdecryption += getDecryptedCharInVignere(c.upper(),key[currentlength].upper()).lower()
currentlength = currentlength + 1
else:
plaintextafterdecryption += str(c)
print plaintextafterdecryption
| true
|
acebf175ac269144ba81c7aa9db35a84ae3dcb91
|
Nuria788/Aso_Python
|
/for.py
| 615
| 4.3125
| 4
|
#Ciclo repetitivo FOR
#Siempre hace uso de una varible para determinar
# las veces que debe de repetirse el ciclo.
#A veces esta variable aumenta dentro del mimo
# ciclo para llegar al final.
# RANGE es una función predeterminada de Python.
#Siempre lleva : al final.
#Siempre comienza a contar desde el 0 cero.
#for x in range(6):
# print(x)
for x in range(2,6):
print(x)
| false
|
761cfb3ca383146a744b8919598e46cfe7216cba
|
Gongzi-Zhang/Code
|
/Python/iterator.py
| 850
| 4.625
| 5
|
'''
Iterable is a sequence of data, one can iterate over using a loop.
An iterator is an object adhering to the iterator portocol.
Basically this means that it has a "next" method, which, when called
returns the next item in the sequence, and when there's nothing to
return, raise the StopIteration exception.
'''
'''
Why is iterator useful. When an iterator is used to power a loop, the loop
becomes very simple. The code to initialise the state, to decide if the loop
is finished, and t ofind the next value is extracted into a separate place,
therefore highlighting the body of the loop.
'''
'''
Calling the __iter__ method on a container to create an iterator
object is the most straightforward way to get hold of an iterator.
The iter function does that for us. Similarly, the next function
will call the __next__ method of the iterator.
'''
| true
|
7fcf3dc50b38d8c01e7c3fc6760d650328578114
|
Gongzi-Zhang/Code
|
/Python/dict.py
| 923
| 4.34375
| 4
|
#!/usr/bin/python
'''
Dictionaries are indexed by a key, which can be any 'immutable' value
'''
phone_nos = {"home" : "988988988",
"office" : "0803332222",
"integer": 25}
print phone_nos[0]
# KeyError: 0
print phone_nos['home']
# 988988988
# Dictionaries can also be created from lists of tuples.
myinfo = [("name","ershaad"), ("phone","98989898")]
mydict = dict(myinfo)
print mydict
# {'phone': '98989898', 'name': 'ershaad'}
print mydict["name"]
# ershaad
# dict comprehensions
{x: x**2 for x in (2, 4, 6)}
# {2: 4, 4: 16, 6: 36}
# keywords arguments
dict(sape=4139, guido=4127, jack=4092)
# {'sape': 4139, 'guido': 4127, 'jack': 4092}
# unpack
for key in (**phone_nos):
print (key, phone_nos[key])
# looping techniques: tiems
for k, v in phone_nos.items():
print(k, v)
# enumerate()
for i, v in enumerate(['tic', 'tac', 'toe'])
print(i, v)
# 0 tic
# 1 tac
# 2 toe
| false
|
0aaa40fdb013ee3cc2b10000709f9fcc7241c476
|
vrrohan/Topcoder
|
/easy/day11/srm740/getaccepted.py
| 2,810
| 4.4375
| 4
|
"""
Problem Statement for GetAccepted
Problem Statement
For this task we have created a simple automated system. It was supposed to ask you a question by giving you a String question.
You would have returned a String with the answer, and that would be all. Here is the entire conversation the way we planned it:
"Do you want to get accepted?"
"True."
Unluckily for you, a hacker got into our system and modified it by inserting negations into the sentence.
Each negation completely changes the meaning of the question to the opposite one, which means that you need to give us the opposite answer.
Write a program that will read the question and answer accordingly. More precisely, your program must return either the string "True." if the question you are given has the same meaning as the one shown above or the string "False." if the question has the opposite meaning.
Definition
Class: GetAccepted
Method: answer
Parameters: String
Returns: String
Method signature: String answer(String question)
(be sure your method is public)
Notes
- All strings in this problem are case-sensitive. In particular, make sure the strings your program returns have correct uppercase and lowercase letters, as shown in the statement and examples.
Constraints
- question will always have the following form: "Do you " + X + "want to " + Y + "get " + Z + "accepted?", where each of X, Y and Z is the concatenation of zero or more copies of the string "not ".
- question will have at most 1000 characters.
Examples
0) "Do you want to get accepted?"
Returns: "True."
This is the original question, you should give the original answer.
1) "Do you not want to get accepted?"
Returns: "False."
This question has the opposite meaning from the original, you should give the opposite answer.
2) "Do you want to not get accepted?"
Returns: "False."
This is another possible negation of the original question.
3) "Do you want to get not not accepted?"
Returns: "True."
Two negations cancel each other out. The meaning of this question is the same as the meaning of the original question, so you should answer "True.".
4) "Do you not want to not get not not not accepted?"
Returns: "False."
"""
import re
def answer(question) :
allWords = re.split('\\s', question)
totalNots = 0
for nots in allWords :
if nots == 'not' :
totalNots = totalNots + 1
if totalNots%2 == 0 :
return "True."
else :
return "False."
print(answer("Do you want to get accepted?"))
print(answer("Do you not not not not not not not not not not not not want to not not not get not not not accepted?"))
print(answer("Do you not not not not not not not not not not not not not not not not not not not not not want to not not not not not not not not not get not not not not not not not accepted?"))
| true
|
e26ca389a503da8b04371fbbff9c187cd809b81d
|
cleiveliu/code-archive
|
/code-20190223/1plus1is2/runoob_c_100/11.py
| 585
| 4.21875
| 4
|
"""
题目:古典问题(兔子生崽):有一对兔子,从出生后第3个月起每个月都生一对兔子,
小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?(输出前40个月即可)
"""
def print_fib_nums(n):
if n == 1:
print([1])
return [1]
elif n == 2:
print([1, 1])
return [1, 1]
else:
res = [1, 1]
for i in range(2, n):
res.append(res[i - 2] + res[i - 1])
print(res)
return res
print_fib_nums(40)
| false
|
2fe7c4f1acffb9dbd5a1e8b005adbdb871bace1f
|
MoisesSanchez2020/CS-101-PYTHON
|
/cs-python/w02/team02_2.py
| 1,352
| 4.40625
| 4
|
"""
File: teach02_stretch_sample.py
Author: Brother Burton
Purpose: Practice formatting strings.
This program also contains a way to implement the stretch challenges.
"""
print("Please enter the following information:")
print()
# Ask for the basic information
first = input("First name: ")
last = input("Last name: ")
email = input("Email address: ")
phone = input("Phone number: ")
job_title = input("Job title: ")
id_number = input("ID Number: ")
# Ask for the additional information
hair_color = input("Hair color: ")
eye_color = input("Eye color: ")
month = input("Starting Month: ")
training = input("Completed additional training? ")
# Now print out the ID Card
print("\nThe ID Card is:")
print("----------------------------------------")
print(f"{last.upper()}, {first.capitalize()}")
print(job_title.title())
print(f"ID: {id_number}")
print()
print(email.lower())
print(phone)
print()
# There are various ways to accomplish the spacing
# In this approach, I told it that hair_color will take exactly 15
# spaces, and month will take 14. That way, the next columns will
# line up. I had to do month 14 (instead of 15) because the word
# 'Month' that came before my value was one letter longer.
print(f"Hair: {hair_color:15} Eyes: {eye_color}")
print(f"Month: {month:14} Training: {training}")
print("----------------------------------------")
| true
|
34abc2ab48a1065cb7f0055b1b0489654a406ed0
|
MoisesSanchez2020/CS-101-PYTHON
|
/w04/team04.py
| 2,862
| 4.28125
| 4
|
"""
File: teach04_sample.py
Author: Brother Burton
Purpose: Calculate the speed of a falling object using the formula:
v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
"""
import math
# while you don't _have to_, it's considered good practice to import libraries
# at the top of your program, so that others know exactly which libraries
# you are using.
print("Welcome to the velocity calculator. Please enter the following:\n")
# Note: In this example, I chose to use single letter variable names, because they
# map directly to variables in the physics equation, so it seemed like it would
# actually be more clear in this case to use the single letter variables than to
# try to use the more descriptive names of "mass" or "gravity".
m = float(input("Mass (in kg): "))
g = float(input("Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): "))
t = float(input("Time (in seconds): "))
p = float(input("Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): "))
A = float(input("Cross sectional area (in m^2): "))
C = float(input("Drag constant (0.5 for sphere, 1.1 for cylinder): "))
# First calculate c = 1/2 p A C
c = (1 / 2) * p * A * C
# Now calculate the velocity v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
v = math.sqrt(m * g / c) * (1 - math.exp((-math.sqrt(m * g * c) / m) * t))
print() # display a blank line
print(f"The inner value of c is: {c:.3f}")
print(f"The velocity after {t} seconds is: {v:.3f} m/s")
"""
File: teach04_sample.py
Author: Brother Burton
Purpose: Calculate the speed of a falling object using the formula:
v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
"""
import math
# while you don't _have to_, it's considered good practice to import libraries
# at the top of your program, so that others know exactly which libraries
# you are using.
print("Welcome to the velocity calculator. Please enter the following:\n")
# Note: In this example, I chose to use single letter variable names, because they
# map directly to variables in the physics equation, so it seemed like it would
# actually be more clear in this case to use the single letter variables than to
# try to use the more descriptive names of "mass" or "gravity".
m = float(input("Mass (in kg): "))
g = float(input("Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): "))
t = float(input("Time (in seconds): "))
p = float(input("Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): "))
A = float(input("Cross sectional area (in m^2): "))
C = float(input("Drag constant (0.5 for sphere, 1.1 for cylinder): "))
# First calculate c = 1/2 p A C
c = (1 / 2) * p * A * C
# Now calculate the velocity v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
v = math.sqrt(m * g / c) * (1 - math.exp((-math.sqrt(m * g * c) / m) * t))
print() # display a blank line
print(f"The inner value of c is: {c:.3f}")
print(f"The velocity after {t} seconds is: {v:.3f} m/s")
| true
|
b0bcfd87202ae144fbf263229c4fe94efebb6072
|
MoisesSanchez2020/CS-101-PYTHON
|
/w10/checkpoint.py
| 917
| 4.3125
| 4
|
# Create line break between the terminal and the program.
print()
# Explain use of program to user.
print('Please enter the items of the shopping list (type: quit to finish):')
print()
# Create empty shopping list.
shop_list = []
# Define empty variable for loop.
item = None
# Populate shop_list with user input:
while item != 'Quit':
item = input('Item: ').capitalize()
if item != 'Quit':
shop_list.append(item)
print('The shopping list is:')
for item in shop_list:
print(item)
print('The shopping list with indexes is:')
for i in range(len(shop_list)):
item = shop_list[i]
print(f'{i}. {item}')
print()
index = int(input('Which item would you like to change? '))
new_item = input('What is the new item? ').capitalize()
shop_list[index] = new_item
print('The shopping list with indexes is:')
for i in range(len(shop_list)):
item = shop_list[i]
print(f'{i}. {item}')
| true
|
e2a8d0f69d84f49228e816676adc8c6506905696
|
vpdeepak/PirpleAssignments
|
/AdvancedLoops/main.py
| 1,104
| 4.28125
| 4
|
"""
This is the solution for the Homework #6: Advanced Loops
"""
print("Assignment on Advanced Loops")
def DrawBoard(rows, columns):
result = False
if(rows < 70 and columns < 235):
result = True
for row in range(rows):
if(row % 2 == 0):
for column in range(columns):
if(column % 2 == 0):
if(column != columns - 1):
print(" ", end="")
else:
print(" ")
else:
if(column != columns - 1):
print("|", end="")
else:
print("|")
else:
for column in range(columns):
if(column != columns - 1):
print("-", end="")
else:
print("-")
return result
result = DrawBoard(69, 234)
if(result is False):
print("Playing Board doesn't fit the screen !! Please re-consider rows and column values")
| true
|
6948f7fae7e5042b299b5953d967a2159c9ed999
|
damani-14/supplementary-materials
|
/Python_Exercises/Chapter03/CH03_05.py
| 543
| 4.15625
| 4
|
# program to calculate the order costs for the "Konditorei Coffee Shop"
# cost = 10.50/lb + shipping
# shipping = 0.86/lb + 1.50 fixed overhead cost
import math
def main():
print("")
print("This program will calculate the total cost (10.50/lb) for your coffee plus shipping (0.86/lb + 1.50 fixed).")
print("")
wt = eval(input("Enter the quantity of coffee you would like to order in pounds: "))
print("")
cost = wt * 11.36 + 1.5
print("The total cost of your order + shipping is $", cost)
print("")
main()
| true
|
2bd6df777921168b3b76c52becaad87f6fe7ab70
|
damani-14/supplementary-materials
|
/Python_Exercises/Chapter03/CH03_17.py
| 958
| 4.3125
| 4
|
# bespoke algorithm for calculating the square root of n using the "guess-and-check" approach
# Newton's method of estimating the square root, where:
# sqrt = (guess + (x/guess))/2
# guess(init) = x/2
import math
def main():
print("")
print("This program will estimate the square root of a value 'x' using 'n'",end="\n")
print("attempts to improve accuracy.",end="\n\n")
x = eval(input("Please select a value to estimate the square root: "))
n = eval(input("Please confirm the number of times to iterate: "))
guess = x/2
sr = 0
print("")
for i in range(1,n+1):
sr = (guess + (x / guess)) / 2
guess = sr
print("Attempt ",i,":",sep="",end="\n")
print("Guess = ",guess, sep="", end="\n")
print("Square Root = ", math.sqrt(x), sep="", end="\n")
print("Accuracy = ", (math.sqrt(x) - guess), sep="", end="\n\n")
print("...",end="\n\n")
print("END",end="\n\n")
main()
| true
|
c8ce4ca5959e673f92c28944bb53d3058329f4c5
|
damani-14/supplementary-materials
|
/Python_Exercises/Chapter03/CH03_06.py
| 555
| 4.21875
| 4
|
# program which calculates the slope of a line given x,y coordinates of two user provided points
import math
def main():
print("")
print("This program will calculate ths slope of a non-vertical line between two points.")
print("")
x1,y1 = eval(input("Enter the coordinates of POINT 1 separated by a comma: "))
print("")
x2,y2 = eval(input("Enter the coordinates of POINT 2 separated by a comma: "))
print("")
m = (y2 - y1)/(x2 - x1)
print("The slope between the selected coordinates is: ", m)
print("")
main()
| true
|
ec940e4973e310100d24207050f870e66b0543b1
|
damani-14/supplementary-materials
|
/Python_Exercises/Chapter05/CH05_01.py
| 800
| 4.53125
| 5
|
# CH05_01: Use the built in string formatting methods to re-write the provided date converting program p. 147
#-----------------------------------------------------------------------------------------------------------------------
# dateconvert2.py
# Converts day month and year numbers into two date formats
def main():
# get the day month and year
day, month, year = eval(input("Enter the day, month, and year numbers: "))
date1 = "/".join([str(month), str(day), str(year)])
print(date1)
months = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
monthStr = months[month-1]
date2 = monthStr+" "+str(day)+", "+str(year)
print("The date is {0} or {1}.".format(date1, date2))
main()
| true
|
22a1797bf0d139c56371968d6ba26eb7f176ed81
|
damani-14/supplementary-materials
|
/Python_Exercises/Chapter08/CH08_01.py
| 400
| 4.25
| 4
|
# CH08_01: Wite a program that computes and outputs the nth Fibonacci number where n is a user defined value
#----------------------------------------------------------------------------------------------------------------------
def main():
a, b = 1,1
n = eval(input("Enter the length of the Fibonacci sequence: "))
for i in range(n-1):
a, b = b, (a+b)
print(a)
main()
| true
|
37c43ced0891ada8ca9d7b2d01df59b9ba96113c
|
JacksonJ01/List-Operations
|
/Operations.py
| 2,338
| 4.28125
| 4
|
# Jackson J.
# 2/10/20
# List Operations with numbers
from ListMethodsFile import *
print("Hello user, today we're going to do some tricks with Lists"
"\nFor that I'm going to need your help"
"\nOne number at a time please")
# This loop will get all five values needed for the methods in the other file to run properly.
# It also calls the adding function which appends the lists
inc = 1
dec = 5
while inc <= 5:
print(f"\n{dec} more numbers required")
adding()
inc += 1
dec -= 1
# Calls the sort method
sort()
# calls the method to sum the List
print("\nThe sum of all the numbers is:", s_m())
time_()
# This will call the multiply the 5 values
print("\nThe product of numbers in this list is:", product())
time_()
# Call the the average function
print("\nThe mean, or average of these numbers is:", mean())
time_()
# The calls the median function
print("\nThe median is:", median())
time_()
# Calls the mode function to check if the list contains a mode
print("\nNow lettuce check if this list has any modes:")
if mode() == "Yes":
print("")
else:
print("No, this list doesn't have a mode.")
time_()
# Call the function to check what the largest number is
print("\nThe largest number in this list is:", large())
time_()
# Call the function to check what the smallest number is
print("\nThe smallest number in the list is:", smallest())
time_()
# If there is a mode, then this deletes it
print("\n")
if mode() == "Yes":
print("*As we stated earlier*."
"\nSo, let's remove any extra numbers:")
else:
print("There are no reoccurring numbers, so nothing will be removed from the list.")
time_()
# Calls the function to display odd numbers
print("\nTime to take out the even numbers:"
"\nODD:")
only_odd()
time_()
# Calls the function to display even numbers
print("\nAnd now to take out the odd numbers"
"\nEVEN:")
only_even()
time_()
# Checks if the user input equals one of the numbers in the list
print(f"\nType a number and we'll see if it's in the list of numbers you gave me:")
included()
time_()
# Shows the second largest number in the list
print("\nHey hey hey, bonus time")
print(f"\nThe second largest number in this list is:", sec_large(), "\b.")
time_()
print("Well, that wasn't much of a crazy ending, but thanks for participating.")
| true
|
2a54f5959a20c597b8250b63a2e3852066193204
|
tstennett/Year9DesignCS4-PythonTS
|
/StringExample.py
| 984
| 4.5
| 4
|
#This file will go through the basics of string manipulation
#Strings are collections of characters
#Strings are enclosed in "" or ''
#"Paul"
#"Paul is cool"
#"Paul is cool!"
#Two things we need to talk about when we think of strings
#index - always starts at 0
#length
#example
# 0123 012345
#"Paul" "Monkey"
#len("Paul") = 4
#len("Monkey") = 6
name = "Paul"
print(name) #I can print strings
sentence = name + " is cool!" #concatination is adding strings
print(sentence)
print(sentence + "!")
#I can access specific letters
fLetter = name[0] #name at 0 (first character)
print(fLetter)
letters1 = name[0:2] #inclusive:exclusive (up to 2)
print(letters1)
letters2 = name[2:1]
print(letters2)
letters2a = name[2:len(name)] #forma way of writing letters 2a
print(letters2a)
letters3 = name[:2]
print(letters3)
lname = len(name) #length of string
print(lname)
#if I want to print out all letters
for i in range(len(name)):
print(name[i])
| true
|
cae88fdf277cf60c97b82bac80aea1729728ffdd
|
juanchuletas/Python_dev
|
/objects.py
| 825
| 4.21875
| 4
|
#!/usr/bin/python
# In python everything is an object
# a variable is a reference to an object
# each object has an identity or an ID
x = 1
print(type(x))
print(id(x))
#####################
# class 'int'
# 139113568
####################
# number, string, tuple -> inmutable
# list, dictionary -> mutable
x = 1
y = 1
print(type(x))
print(id(x))
print(type(y))
print(id(y))
if x==y:
print("True")
else:
print("False")
if x is y:
print("True")
else:
print("False")
##################
# see the last two lines, both are true # class 'int'
# 139113568
# class 'int'
# 139113568
# True
# True
##################
a = dict(x = 1, y = 1)
print(type(a))
print(id(a))
b = dict(x = 1, y = 1)
print(id(b))
if a == b:
print("True")
else:
print("False")
if a is b:
print("True")
else:
print("False")
| true
|
a4f2833e1539560e32481e855419cce224d5a0b4
|
CameronOBrien95/cp1404practicals
|
/prac_05/emails.py
| 474
| 4.25
| 4
|
"""
CP1404/CP5632 Practical
Email to name dictionary
"""
email_name = {}
email = input("Email: ")
valid = False
while email != "":
name = email.split("@")[0]
name = name.replace(".", " ").title()
choice = input("Is your name {}? (Y/n)".format(name)).upper()
if choice != 'Y':
name = input("What is your name ?")
email_name[email] = name
email = input("Email: ")
for email in email_name:
print("{} ({})".format(email_name[email], email))
| false
|
005f3298cad9d70f22201532a895541eee04f730
|
smohorzhevskyi/Python
|
/Second_homework_4.py
| 991
| 4.21875
| 4
|
"""
Напишите функцию, которая принимает список строк в качестве аргумента и возвращает отфильтрованный список,
который содержит только строки, которые являются палиндромами.
Например: Аргументы: words = ["radar", "device", "level", "program", "kayak", "river", "racecar"]
Функция должна вернуть : ['radar', 'level', 'kayak', 'racecar']
"""
words = input().split()
filtered_list = filter(lambda i: i == i[::-1], words)
print(list(filtered_list))
"Ниже вариант без использования лямбда-функции"
# words = input().split()
#
#
# def palindrom_search(words, palindrom_list=[]):
# for i in words:
# if i == i[::-1]:
# palindrom_list.append(i)
# print(palindrom_list)
#
#
# palindrom_search(words)
| false
|
6e0dc99e9239f6ecc6e2cfb18c2aa899277aff3a
|
smohorzhevskyi/Python
|
/Second_homework_3.py
| 856
| 4.1875
| 4
|
"""
Напишите функцию, которая принимает 2 списка в качестве аргументов и возвращает список кортежей,
отсортированный по значению второго элемента в кортеже. Например:
Аргументы:
weekdays = ['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wednesday','Tuesday', 'Monday']
days = [7, 6, 5, 4, 3, 2, 1].
Функция должна вернуть:
[('Monday', 1), ('Tuesday', 2), ('Wednesday', 3), ('Thursday', 4),('Friday', 5), ('Saturday', 6),
('Sunday', 7)]
"""
weekdays = ['Sunday', 'Saturday', 'Friday', 'Monday', 'Thursday', 'Wednesday', 'Tuesday']
days = [7, 6, 5, 4, 3, 2, 1]
days_of_week = sorted(list(zip(weekdays, days)), key=lambda x: x[1])
print(days_of_week)
| false
|
056aa02e58696d83b7e75f8cadad3339e09096ed
|
goodGopher/HWforTensorPython
|
/DZ4to11032021/prog4_deliting_elements.py
| 823
| 4.125
| 4
|
"""Removing duplicate elements in list.
Functions:
list_reading(my_list):
Allows to read list from keyboard.
remove_copies(m_list):
Removing duplicate elements in list.
main():
Organize entering and clearing of list.
"""
import checks
def remove_copies(m_list):
"""Removing duplicate elements in list."""
rand_list = list(set(m_list))
m_list.reverse()
for i in rand_list:
while m_list.count(i) > 1:
m_list.remove(i)
m_list.reverse()
def main():
"""Organize entering and clearing of list."""
print("Введите список через Enter:")
main_list = []
checks.list_reading(main_list)
remove_copies(main_list)
print(f"обработанный список {main_list}")
if __name__ == "__main__":
main()
| true
|
64b15b4ed5ed67df6e7f912891491dbc6576230c
|
adiiitiii/IF-else
|
/alphabet digit or special char???.py
| 233
| 4.125
| 4
|
ch=input("enter any character")
if ch>"a" and ch<"z" or ch>"A" and ch<"Z" :
print("the character is an alphabet")
elif ch[0].isdigit():
print("the character is a digit")
else:
print("the character is a special character")
| true
|
a84e87ca3ec6379c4c7582862ed4ff48f4cbee24
|
121710308016/asignment4
|
/10_balanced_brackets.py
| 2,396
| 4.15625
| 4
|
"""
You're given a string s consisting solely of "(" and ")".
Return whether the parentheses are balanced.
Constraints
Example 1
Input
s = "()"
Output
True
Example 2
Input
s = "()()"
Output
True
Example 3
Input
s = ")("
Output
False
Example 4
Input
s = ""
Output
True
Example 5
Input
s = "((()))"
Output
True
"""
import unittest
# Implement the below function and run this file
# Return the output, No need read input or print the ouput
# Workout the solution or the logic before you start coding
def balanced_brackets(sentence):
def is_match(ch1, ch2):
match_dict = {')':'(', ']':'[', '}':'{'}
return match_dict[ch1] == ch2
lst = []
close = [']', ')', '}']
open = ['{', '(', '[']
for i in sentence:
if i in open:
lst.append(i)
if i in close:
if len(lst)==0:
return False
if not is_match(i,lst.pop()):
return False
return (len(lst)==0)
# DO NOT TOUCH THE BELOW CODE
class TestBalancedBrackets(unittest.TestCase):
def test_01(self):
self.assertEqual(balanced_brackets("()"), True)
def test_02(self):
self.assertEqual(balanced_brackets("()()"), True)
def test_03(self):
self.assertEqual(balanced_brackets(")("), False)
def test_04(self):
self.assertEqual(balanced_brackets(""), True)
def test_05(self):
self.assertEqual(balanced_brackets("((()))"), True)
def test_06(self):
self.assertEqual(balanced_brackets("((((())))(()))"), True)
def test_07(self):
self.assertEqual(balanced_brackets(
"(((((((((())))))))))()((((()))))"), True)
def test_08(self):
self.assertEqual(balanced_brackets(")))))((((("), False)
def test_09(self):
self.assertEqual(balanced_brackets(
"()()(((((((((()()))))))))))((((()))))"), False)
def test_10(self):
self.assertEqual(balanced_brackets(
"()()()(((())))((()))()()(()())(((((())()()()()()))))"), True)
def test_11(self):
self.assertEqual(balanced_brackets(
"()((((((()()()()()((((((())))))))))(())))()))))))()()(((((()))))))))))))))))))())()))"), False)
if __name__ == '__main__':
unittest.main(verbosity=2)
| true
|
746a47a541ca0da03832a24b02ef340be66659ec
|
src053/PythonComputerScience
|
/chap3/ladderAngle.py
| 891
| 4.5
| 4
|
# This program will determine the length of the ladder required to
# reach a height on a house when you have that height and the angle of the ladder
import math
def main():
# Program description
print("This program will find the height a ladder will need to be when given two inputs")
print("1) The height of the house 2) the angle (in degrees) of the ladder")
height = eval(input("Please provide the height of the house: ")) # The var that contains the height of the house
degrees = eval(input("Please provide the angle of the ladder against the house: ")) # The var that contains the degree angle of the ladder
radians = (math.pi / 180) * degrees # The equation to find the radian
length = round(height / math.sin(radians), 2) # The equation to find the needed length of the ladder
# Print the length of the ladder
print("length the ladder will need to be: ", length)
main()
| true
|
326c7997a605b2a681185f98f76b309ae2548e58
|
src053/PythonComputerScience
|
/chap5/avFile.py
| 602
| 4.28125
| 4
|
#program that will count the number of words in a sentence from within a file
def main():
#get the name of file
fname = input("Please enter the name of the file: ")
#open the file
infile = open(fname, "r")
#read in file
read = infile.read()
#split the sentence into a list
split = read.split()
#count the length of the split list
length = len(split)
count = 0
#loop through each word and count the len
for w in split:
for i in w:
count = count + 1
#calculate average
av = count / length
#print the average
print("The average word length is: {0:0.2f}".format(av))
main()
| true
|
e200b43b7d728635cf1581cf5eb4fcde4729bff6
|
src053/PythonComputerScience
|
/chap3/slope.py
| 985
| 4.3125
| 4
|
# This program will calculate the slope of to points on a graph
# User will be required to input for var's x1, x2, y1, y2
import math
def slope(x1, x2, y1, y2):
return round((y2 - y1)/(x2 - x1)) #Calculate and return the slope
def distance(x1, x2, y1, y2):
return round(math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)), 2)
def main():
print("This program takes to points on a graph and finds the slope")
print()
x1 = eval(input("Enter the x1 location: ")) #prompt for x1 location
y1 = eval(input("Enter the y1 location: ")) #prompt for y1 location
x2 = eval(input("Enter the x2 location: ")) #prompt for x2 location
y2 = eval(input("Enter the y2 location: ")) #prompt for y2 location
choice = eval(input("If you want the slope type 1 type anything else for the distance: ")) #prompt user for what equation they want done
if choice == 1:
s = slope(x1, x2, y1, y2)
print("The slope is: ", s)
else:
d = distance(x1, x2, y1, y2)
print("The distance is: ", d)
main()
| true
|
90873ee519d41e877adbe3037d7fcd9b5e0b7e96
|
src053/PythonComputerScience
|
/chap3/easter.py
| 467
| 4.125
| 4
|
# This program will take the year a user inputs and output the value of easter
def main():
print("This program will figure out the epact for any given year")
year = eval(input("Input the year you would like to know the epact of: "))
#Equation to figure out integer division of C
C = year//100
#Equation to figure out epact
epact = (8 + (C // 4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30
#Display the epact
print("The epact is: ", epact)
main()
| true
|
26870cc55f6e78c2d25cc09b9119491abdef8434
|
src053/PythonComputerScience
|
/chap2/convert.py
| 331
| 4.28125
| 4
|
#A program to convert Celsius temps to Fahrenheit
def main():
print("This program will convert celsius to farenheit")
count = 0
while(count < 5):
celsius = eval(input("What is the Celsuis temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degree Fahrenheit.")
count += 1
main()
| true
|
f40123af7ffca03d3d4184aa3fcf131f7f8f2ce4
|
Kdk22/PythonLearning
|
/PythonApplication3/exception_handling.py
| 2,688
| 4.21875
| 4
|
# ref: https://docs.python.org/3/tutorial/errors.html
while True:
try:
x = int(input('Please enter a number: '))
break
except ValueError:
print('Ooops ! THat was no valid number. Try agian..')
''' If the error type matches then only in displays message.
If the error type is not matched then it is passed to outer
try statements, if no handler is found to handle that
statement then it is unhandled exception and execution
stops
'''
''' Therefore you can add more than one except clause in try statement
except (RuntimeError , TypeError, NameError):
pass
'''
# I didn't understood this
class B(Exception):
print('It\'s B')
pass
class C(B):
print('It\'s C that extracts B')
pass
class D(C):
print('It\'s D that extracts C')
pass
for cls in [B,C,D]:
try:
raise cls()
except B:
print('B')
except D:
print('D')
except C:
print('C')
'''
THis is the real way of doing exception handling
if name of the error is not given then it works as
wildcard(means it handles all the exception.).
'''
import sys
try:
with open('D:\Visual Studio 2017\Repos\PythonApplication3\PythonApplication3\exception_test.txt') as f:
s= f.readline()
i= int(s.strip()) # strip() returns the copy of string in which the defined characters are stripped from beginning and end.
except OSError as err:
print('OS Error: {0}'. format(err))
except ValueError:
print('Could not convert data to integer.')
except:
print('Unexcepted Error: ', sys.exc_info()[0])
raise
'''
sys.exc_info gives information about the exception that is
currently being handled in the format (type, value, traceback)
'raise' displays the class object of error along with value
'''
#Check
import sys
try:
a= 1/0
c= '!!!cat!!!'
b= int(c.strip('!'))
except:
print('Unexceptied Error ', sys.exc_info()[0])
# raise
try:
raise Exception('spam','eggs') # associated value or exception's argument
except Exception as inst: # inst is variable that represents exception instance
print(type(inst)) # and the exception instance is bound to instance.args , type() returns the type of variable
print(inst.args) #__str__ allows args to be printed as we know that print executes __str__()
print(inst) # but may be overwrritten
x, y = inst.args #unpack args
print('x =', x)
print('y =', y)
# even functions can be called indirectly
def this_fails():
x =1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err)
| true
|
bb52036b8bf49eb4af098c7f2025fce8080316d8
|
Kdk22/PythonLearning
|
/PythonApplication3/class_var_and_instance_var.py
| 1,005
| 4.5625
| 5
|
class foo:
x='orginal class'
c1,c2 = foo(), foo()
''' THis is creating the multiple objects of
same as
c1 = foo()
c2 = foo()
and these objects can access class variable (or name)
'''
print('Output of c1.x: ', c1.x)
print('Output of c2.x: ', c2.x)
'''
Here if you change the c1 instance, and it will
not affect the c2 instance
'''
c1.x = 'changed instance'
print('Output of c1.x: ',c1.x)
print('Output of c2.x: ',c2.x)
'''
But if I change the foo class, all instances of that
class will be changed
'''
foo.x = 'Changed class'
print('Output of c1.x: ',c1.x)
print('Output of c2.x: ', c2.x)
'''
Now using 'self'
Here Changing the class does not affect the instances
'''
class foo:
def __init__(self):
self.x = 'Orginal self'
c1 = foo
foo.x ='changed class'
print('Output of instance attributes: ', foo.x)
print('Output of self: ',c1.x)
# ref: https://stackoverflow.com/questions/1537202/variables-inside-and-outside-of-a-class-init-function
| true
|
b6417cda68e6efe3792e317980cbbdb923a5cb63
|
vohrakunal/python-problems
|
/level2prob4.py
| 806
| 4.375
| 4
|
'''
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out .
You are given a string . Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character '' with in the string.
For a better understanding of the problem, check the explanation.
Input Format
A single line of input consisting of the string .
Output Format
A single line of output consisting of the modified string.
Constraints
All the characters of denote integers between and .
Sample Input
''''
########## Solution ################
from itertools import groupby
S = str(raw_input())
T = [list(g) for k, g in groupby(S)]
for i in T:
print (len(i), int(i[0])),
| true
|
61d217ee89bf72920f370c96b6554d675a4c035e
|
steveiaco/COMP354-Team-E
|
/Functions/pi.py
| 1,320
| 4.125
| 4
|
# Goal: Calculate pi to the power of a given variable x
# Author: Ali
from Functions.constants import get_pi
# Pie Function
# Using Table Method
# I have basically created a global variable for PIE and its power
PIE = get_pi()
# the index (n) of the dictionary represent PIE**(10**n)
PIE_Dictionary = {
-5: 1.000011447364379,
-4: 1.0001144795408674,
-3: 1.001145385339187,
-2: 1.0115130699114478,
-1: 1.1212823532318632,
0: 1,
1: PIE,
2: 93648.04747608298,
3: 5.187848314319592e+49
}
def pi_function(args):
x = 0
# check if
if len(args) == 1:
x = args[0]
else:
raise Exception(
f"Invalid number of arguments, pie expected 1 argument but got "
f"{len(args)} arguments.")
negative_exponent = False
if float(x) < 0:
negative_exponent = True
x = float(x) * -1
exponent = list(str(float(x)))
decimal = list(str(float(x))).index('.')
n = 1.0
for i in range(len(exponent)):
power_level = decimal - int(
i) # power_level give us the index of PIE_Dictionary
if power_level != 0:
j = int(exponent[i])
for k in range(j):
n = n * PIE_Dictionary[power_level]
if negative_exponent:
return 1 / n
return n
| true
|
2dd449e8b85f1814e6c857a1e411936f21ea6c09
|
verjavec/guessing_game
|
/game.py
| 1,217
| 4.25
| 4
|
"""A number-guessing game."""
import random
# Put your code here
# Greet the player
name = input("Please enter your name: ")
print (f'Hello {name}!')
#choose a random number
numbertoguess = random.randrange(1,100)
print(numbertoguess)
keep_guessing = True
num_guesses = 0
#repeat this part until random number equals the guess
#ask player to input a number from 1-100
#check if input number is equal to random number
while keep_guessing:
str_guess = input("Please choose a number between 1 and 100: ")
guess = int(str_guess)
if guess == numbertoguess:
num_guesses += 1
print(f'Congratulations {name}! You guessed the number in {num_guesses} tries!!!')
#increase number of guesses
keep_guessing = False
#if random number is not equal to input number, is it higher?
elif guess > numbertoguess:
print(f'Too high! Try a lower number, {name}.')
num_guesses += 1
elif guess < numbertoguess:
print(f'Too low! Try a higher number, {name}.')
num_guesses += 1
#if random number is not equal to or higher, it must be lower
#give user a hint
#once random number equals the guess, congratulate the user.
| true
|
946d079c682179d1e5b09bfeed6ae36a23045eae
|
inwk6312winter2019/week4labsubmissions-deepakkumarseku
|
/lab5/task4.py
| 762
| 4.34375
| 4
|
import turtle
class rectangle():
"""Represents a rectangle.
attributes: width, height.
"""
class circle():
"""Represents a circle.
attributes: radius.
"""
radius=50
def draw_rect(r):
""" Draws a rectangle with given width and height using turtle"""
for i in range(2):
turtle.fd(r.width)
turtle.lt(90)
turtle.fd(r.height)
turtle.lt(90)
def draw_circle(c):
"""Draws a circle with given radius using turtle"""
turtle.circle(c.radius)
def main():
r = rectangle()
r.width=50
r.height=200
c = circle()
c.radius=50
print(draw_rect(r))
turtle.reset()
print(draw_circle(c))
turtle.mainloop()
if __name__ == '__main__':
main()
| true
|
8f2e39d178be9670253ca98d275cc549226b6971
|
williamstein/480_HW2
|
/simple_alg.py
| 1,050
| 4.15625
| 4
|
print "Hello"
import math
#computes the probability of the binomial function in the specified range inclusive
#min, max are the values for the range
#n is the total population
#p is the success probability
def binom_range(min, max, n, p):
if(min > max):
raise Exception("Please pass a valid range")
if(min < 0):
raise Exception("The minimum must be positive")
if(max >n):
raise Exception("The maximum cannot exceed the total population")
current = min
total = 0
while(current <= max): #go through and add up all the probabilities
total+= binom(current, n,p)
current = current+1
return total
def binom(x, n, p):
coeff = math.factorial(n) / (math.factorial(x)*math.factorial(n-x))
return coeff*(p**x)*((1-p)**(n-x))
#examples
# We want the probability that a binomial with population of 2 and success probability of .5
#for 0<= x <= 1
x = binom_range(0,1,2,.5)
print x # should print .75
x = binom_range(10,15,20, .7)
print x
| true
|
5bc42f93d4da19adc21bc675f5cfa6aec78411a7
|
tianxiongWang/codewars
|
/sum.py
| 484
| 4.15625
| 4
|
# >Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.
# 其实就是把a到b之间的数求和,太简单了
def get_sum(a,b):
if a == b:
return a
if a < b:
sum = 0
for num in range(a, b+1):
sum += num
else:
sum = 0
for num in range(b, a+1):
sum += num
return sum
| true
|
32699826b747b0009a4313fb427fda5a4ac7ef79
|
Kallol-A/python-scripting-edureka
|
/Module 3/Case1/commavalues.py
| 641
| 4.1875
| 4
|
#Write a program that calculates and prints the value according to the given formula:
#Q = Square root of [(2 * C * D)/H]
#Following are the fixed values of C and H: C is 50. H is 30.
#D is the variable whose values should be input to your program in a comma- separated sequence.
#Let us assume the following comma separated input sequence is given to the program:
#100,150,180
#The output of the program should be:
#18,22,24
import math
from math import sqrt
values=input("Enter Comma seprated values").split(",")
print(values)
Q=[]
for i in values:
Q.append((int(math.sqrt((100 * int(i) )/30))))
print (*Q,sep=",")
| true
|
8c89eb33be9a01050fd6f4929d8ed287ed5dd2aa
|
sdn0303/algorithm-training
|
/Palindrome.py
| 259
| 4.25
| 4
|
# -*- coding:utf-8 -*-
# 回文かどうかを判定する
def palindrome(string):
if string == string[::-1]:
print('True')
else:
print('False')
string1 = 'abcdefgfedcba'
string2 = 'asifjvbh'
palindrome(string1)
palindrome(string2)
| false
|
126d10961d3e699b353863fa96ea055c43fa46d2
|
Elvis2597/Sorting_Algorithms
|
/MergeSort.py
| 692
| 4.1875
| 4
|
#Time Complexity = O(nlogn)
#Function to merge to array
def merge(a,l,r):
nl=len(l)
nr=len(r)
i=0
j=0
k=0
while (i<nl and j<nr):
if l[i]<=r[j]:
a[k]=l[i]
i+=1
else:
a[k]=r[j]
j+=1
k+=1
while (i<nl):
a[k]=l[i]
i+=1
k+=1
while (j<nr):
a[k]=r[j]
j+=1
k+=1
#main Function which calls the merge function to perform mergesort
def mergesort(a):
n=len(a)
if n<2:
return
mid=n//2
l= a[:mid]
r= a[mid:]
mergesort(l)
mergesort(r)
merge(a,l,r)
return a
l=list(map(int,input().split()))
print(mergesort(l))
| false
|
58a0e3ca5ac367b7b994450b49fc7fc3a6c664ad
|
Alainfou/python_tools
|
/prime_list.py
| 2,134
| 4.1875
| 4
|
#!/usr/bin/python
import math
import sys
import getopt
print "\n\tHey, that's personal! That's my very, very personal tool for listing prime numbers! Please get out of here! =(\n"
dat_prime_list = [2,3]
def its_prime (p):
s = int(math.sqrt(p))+1
for i in dat_prime_list :
if (p%i) == 0:
return False
return True
def yeah (argv):
try:
opts, args = getopt.getopt(argv,"n:l:")
except getopt.GetoptError:
print 'prim.py -n <number_until_which_primes_shall_be_listed>'
sys.exit(2)
until_there = 42
based_on_prime_limit = False
list_length = 42
based_on_list_length = False
p = 5
for opt, arg in opts:
if opt == '-n':
based_on_prime_limit = True
try:
until_there = int(arg)
except ValueError:
print 'Invalid argument. Limit will be set to 42, which is a totally arbitrary and random number.'
elif opt == '-l':
based_on_list_length = True
try:
list_length = int(arg)
except ValueError:
print 'Invalid argument. Length will be set to 42, which is a totally arbitrary and random number.'
if based_on_prime_limit :
while (p < until_there):
if its_prime (p):
dat_prime_list.append(p)
p+=2
print 'Fine... Here are your prime numbers until ',until_there
elif based_on_list_length :
while (len(dat_prime_list)<list_length):
if its_prime (p):
dat_prime_list.append(p)
p+=2
print 'Fine... Here are your ',list_length,' prime numbers.'
print dat_prime_list
if __name__ == "__main__":
yeah(sys.argv[1:])
| true
|
2a378d9c0099652c3f74f22fa67311636d6d477a
|
geraldo1993/CodeAcademyPython
|
/Strings & Console Output/String methods.py
| 614
| 4.4375
| 4
|
'''Great work! Now that we know how to store strings, let's see how we can change them using string methods.
String methods let you perform specific tasks for strings.
We'll focus on four string methods:
len()
lower()
upper()
str()
Let's start with len(), which gets the length (the number of characters) of a string!
Instructions
On line 1, create a variable named parrot and set it to the string "Norwegian Blue". On line 2, type len(parrot) after the word print, like so: print len(parrot). The output will be the number of letters in "Norwegian Blue"! '''
parrot="Norwegian Blue"
print len(parrot)
| true
|
d3b8a54fca1ec8f724ec1a2de1a81f952c0368d7
|
ohwowitsjit/WK_1
|
/2.py
| 201
| 4.125
| 4
|
num_1 = int(input("Enter the first number: "));
num_2= int(input("Enter the first number: "));
product=0;
for i in range(0, num_2):
product=product+num_1;
print("Product is:", str(product));
| true
|
2db6a8ca529a72823ce4e7ba45cfcb050ff830bd
|
puneet672003/SchoolWork
|
/PracticalQuestions/06_question.py
| 358
| 4.28125
| 4
|
# Write a Python program to pass a string to a function and count how many vowels present in the string.
def count_vowels(string):
vowels = ["a" ,"e", "i", "o", "u"]
count = 0
for char in string:
if char.lower() in vowels:
count += 1
return count
print(f"Total vowels : ", count_vowels(input("Enter string : ")))
| true
|
6647ec2418ab875585ed562ceeea49a6bd1c9746
|
puneet672003/SchoolWork
|
/PracticalQuestions/03_question.py
| 411
| 4.40625
| 4
|
# Write a python program to pass list to a function and double the odd values and half
# even values of a list and display list element after changing.
def halfEven_doubleOdd(arr):
for i in range(len(arr)):
if arr[i] % 2 == 0:
arr[i] = arr[i]/2
else :
arr[i] = arr[i]*2
lst = eval(input("Enter list : "))
halfEven_doubleOdd(lst)
print(f"Final list : {lst}")
| true
|
d1fff6ff6f5f6c089029a521907eb1fe14a9680c
|
erin-koen/Whiteboard-Pairing
|
/CountingVotes/model_solution/solution.py
| 1,377
| 4.28125
| 4
|
# input => array of strings
# output => one string
# conditions => The string that's returned is the one that shows up most frequently in the array. If there's a tie, it's the one that shows up most frequently in the array and comes last alphabetically
# sample input => input: ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael'];
# expected output: 'michael'
# strategy: loop through array and add names to a dictionary. If name not in dictionary, dictionary[name]: 1, else dictionary[name]+=1
#this'll provide a count
# loop through dictionary, declare two variables - count and winner. If dictionary[key]:value >= count, value = count and winner = key
def counting_votes(arr):
vote_dict = {}
for name in arr:
if name not in vote_dict:
vote_dict[name] = 1
else:
vote_dict[name] = vote_dict[name] + 1
count = 0
winners = []
# figure out the largest number of votes
for value in vote_dict.values():
if value > count:
count = value
# find the name(s) of the people who got that many votes
for key in vote_dict.keys():
if vote_dict[key] == count:
winners.append(key)
return sorted(winners, reverse=True)[0]
print(counting_votes(['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael']))
| true
|
4c051300bade9b496dcb31f81376b704a82f84eb
|
fionnmcguire1/LanguageLearning
|
/PythonTraining/Python27/BattleShip_medium.py
| 1,815
| 4.1875
| 4
|
'''
Author: Fionn Mcguire
Date: 26-11-2017
Description:
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
'''
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
numBattleships = 0
for line in xrange(len(board)):
for element in xrange(len(board[line])):
if board[line][element] == 'X':
if line != 0:
if board[line-1][element] != 'X':
if element != 0:
if board[line][element-1] != 'X':
numBattleships+=1
else:
numBattleships+=1
else:
if element != 0:
if board[line][element-1] != 'X':
numBattleships+=1
else:
numBattleships+=1
return numBattleships
| true
|
1e20b0f6ffd29554ce2e1fe5551abf3b9c839f01
|
boerz-coding/cs107_Boer_Zhang
|
/pair_programming/PP7/exercise_2.py
| 858
| 4.25
| 4
|
"""
Pair Programming Assignment #7
Collaborators: Ryan Liu, Blake Bullwinkel, Zhufeng Kang, Boer Zhang
Forward mode on f(x) = x**r
"""
# Define a simple function
def my_pow(x, r):
f = x**r
f_prime = (r)*x**(r-1)
output = (f, f_prime)
return output
# Implement a closure
def outer(r):
def inner(x, seed):
f = x**r
f_prime = seed*(r)*x**(r-1)
output = (f, f_prime)
return output
return inner
# Using a class
class my_pow_class:
def __init__(self, r):
self.r = r
def get_tuple(self, x, seed):
f = x**self.r
f_prime = seed*(self.r)*x**(self.r-1)
output = (f, f_prime)
return output
if __name__ == "__main__":
print(my_pow(3, 4))
closure_test = outer(4)
print(closure_test(3,1))
class_test = my_pow_class(4)
print(class_test.get_tuple(3,1))
| false
|
a6d0f86a9c77d54bec821e91a665522357466cf5
|
Dallas-Marshall/CP1404
|
/prac_01/electricity_bill_estimator.py
| 719
| 4.15625
| 4
|
# Electricity Costs
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
electricity_cost = 0
# Define Menu:
MENU = """Please select tariff;
Tariff(11)
Tariff(31)"""
# Display Menu
print(MENU)
# Ask user to select menu option
user_choice = int(input(">>> "))
# Define relevant electricity cost
if user_choice == 31:
electricity_cost = TARIFF_31
else:
electricity_cost = TARIFF_11
# Daily use in kWh
daily_use = float(input("What is your daily usage in KWh: "))
# Number of days in the billing period
billing_period = int(input("How many days are in the billing period? "))
# Calculate bill total
bill_total = electricity_cost * daily_use * billing_period
print("Your estimated bill is: ${:.2f}".format(bill_total))
| true
|
306684db850ddb2a45b4b554a8a4f940b9322151
|
EtienneBauscher/Classes
|
/student.py
| 1,970
| 4.1875
| 4
|
"""'student.py' is a program that computes the following:
1. The average score of a student's grades.
2. It tests whether a student is a male or a female.
The program utilises a class called Student
The class hosts various fucntions for the computation of the needed outcomes.
"""
class Student(object):
"""class 'Student' hosts the following variables:
a. age - for the student's age
b. name - for the name of the student.
c. gender - for the gender of the student
d. grades - for the grades of the student
"""
# initialise the class through the constructor
def __init__(self, age, name, gender, grades):
self.age = age
self.name = name
self.gender = gender
self.grades = grades
def compute_average(self):
"""this function calculates the average of the student's scores"""
# utilise the class variables in the list to compute
average = sum(
self.grades)/len(self.grades)
print("The average for student " +
str(self.name) + " is " + str(average)) # print the results
def check_if_male(self):
"""'check_if_male()' checks whether a student is male or not and
prints "True" if yes and "False" if no"""
# use a conditional to check if the gender is male
if self.gender == "Male":
print("True")
else:
print("False")
# three students
MIKE = Student(20, "Philani Sithole", "Male", [64, 65])
SARAH = Student(19, "Sarah Jones", "Female", [82, 58])
ETIENNE = Student(43, "Etienne Bauscher", "Male", [99, 99])
# run a couple of checks on the newly added check_if_male() method
ETIENNE.check_if_male()
ETIENNE.compute_average()
SARAH.check_if_male()
MIKE.check_if_male()
# create a new list
# run a for loop through the list calling the functions
NEWLIST = [ETIENNE, SARAH, MIKE]
for i in NEWLIST:
Student.check_if_male(i)
Student.compute_average(i)
| true
|
2d327cbc6d7edc81198880b6a5663e0166ef54d2
|
crazy-bruce/algorithm
|
/data_structure/queue.py
| 1,078
| 4.1875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time: 2021/1/12 下午2:10
# @Author: Bruce Chen
# @Site:
# @File: queue.py
# @Software: PyCharm
class Queue(object):
def __init__(self, size):
self.queue = [0 for i in range(size)]
self.rear = 0
self.front = 0
self.size = size
def append(self, element):
if not self.is_filled():
self.queue[self.rear] = element
self.rear = (self.rear + 1) % self.size
else:
raise IndexError("Queue is filled")
def pop(self):
if not self.is_empty():
data = self.queue[self.front]
self.front = (self.front + 1) % self.size
return data
else:
raise IndexError("Queue is empty")
def is_empty(self):
return self.front == self.rear
def is_filled(self):
return (self.rear + 1) % self.size == self.front
if __name__ == "__main__":
q = Queue(6)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
#q.append(6)
#print(q.pop())
| false
|
532d90e13e03f6af7ef54e45544688a5ef934009
|
ghostassault/AutomateTheBoringWithPython
|
/Ch7/RegEx.gyp
| 2,277
| 4.375
| 4
|
#The search() method will return a match object of the first matched text in a searched string
#1 Matching Multiple groups with the pipe
import re
heroR = re.compile(r'Batman|Tina Fey')
mo1 = heroR.search('Batman and Tina Fey.')
print(mo1.group())
#2 Optional Matching with the Question Mark
batRe = re.compile(r'Bat(wo)?man')
mo1 = batRe.search('The adventures of Batman')
print(mo1.group())
# The (wo)? part of the regular expression means the pattern wo is an optional group
batRe = re.compile(r'Bat(wo)?man')
# The regex will match text that has "zero" ie one instance of wo in it.
mo1 = batRe.search('The adventures of Batwoman, and Batman')
print(mo1.group())
# Using Regex to look for phone numbers that do or do not have an area code
phoneRe = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo1 = phoneRe.search('My number is 415-555-4242')
print(mo1.group())
#Match 0 or 1 of the group preceding this question mark. Questions (?) marks can be escaped with \?
mo2 = phoneRe.search('My number is 412-4565')
print(mo2.group())
#3 Matching zero or more with the Star. * means to match zero or more
batRe = re.compile(r'Bat(wo)*man')
mo1 = batRe.search('The adventures of Batman Batgirl')
print(mo1.group())
batRe = re.compile(r'Bat(wo)*man')
mo4 = batRe.search('The adventures of Batwowowowowowowoman')
print(mo4.group())
#4 Matching one or more with the plus
batRe = re.compile(r'Bat(wo)+man')
mo1 = batRe.search('The adventures of Batwowowoman')
print(mo1.group())
# The group preceding the plus must appear at least once
batRe = re.compile(r'Bat(wo)+man')
mo2 = batRe.search('The adventures of Batman')
print(mo2 == None )
# Matching specific repetitions with Curly Brackets
#If you have a group that you want to repeat a specific number of times, follow the group in your regex wit h number in curly brackets.
haRe = re.compile(r'(Ha){3}')
mo1 = haRe.search('HaHaHa')
print(mo1.group())
#Here, (Ha){3} matchers 'HaHaHa' but not 'Ha'. Since it doesnt match 'Ha 3', serach() returns None
mo2 = haRe.search('Ha')
mo2 == None
print(mo2)
#Greedy and Nongreedy matching
greedyHaRe = re.compile(r'(Ha){3,5}')
mo1 = greedyHaRe.search('HaHaHaHaHa')
print(mo1.group())
nonegreedyHaRe = re.compile(r'(Ha){3,5}?')
mo2 = nonegreedyHaRe.search('HaHaHaHaHa')
print(mo2.group())
| true
|
db7cd6a5237bdfca4a0622c10b1cdd3ddb430bf8
|
jinshanpu/lx
|
/python/func.py
| 280
| 4.125
| 4
|
print "the prog knows which number is bigger"
a=int(raw_input("Number a:"))
b=int(raw_input("Number b:"))
def theMax(a, b=0):
'''Prints the maximun of two numbers.
the two values must be integers'''
if a>b:
return a
else:
return b
print theMax(a, b)
print theMax.__doc__
| true
|
9f96445ed9e96509427feb05dfc2ba262c5171d8
|
javirodriguezzz/als-labs
|
/tribonacci.py
| 1,455
| 4.21875
| 4
|
"""
En la sucesión de Tribonacci, cada elemento
es la suma de los tres anteriores, y se empieza
por 0, 1, 1.
In the Tribonacci succesion, each element is the sum
of the three previous instances, and it always
starts with 0, 1, 1.
"""
def tribonacci_iter(n):
def tribonacci(n):
"""
Calcular la sucesión de tribonacci hasta n elementos de forma iterativa.
:param n: número de elementos.
:return: Una lista de n elementos con la sucesión.
"""
if n == 0:
toret = []
if n == 1:
toret = [0]
elif n == 2:
toret = [0, 1]
elif n == 3:
toret = [0, 1, 1]
else:
toret = [0, 1, 1]
for i in range(3, n):
toret.append(toret[i - 1] + toret[i - 2] + toret[i - 3])
return toret
def tribonacci_rec(n):
"""
Calcular la sucesión de tribonacci hasta n elementos de forma recursiva.
:param n: número de elementos.
:return: Una lista de n elementos con la sucesión.
"""
if n <= 0:
toret = []
if n == 1:
toret = [0]
elif n == 2:
toret = [0, 1]
elif n == 3:
toret = [0, 1, 1]
else:
toret = tribonacci_rec(n - 1)
toret.append(toret[-1] + toret[-2] + toret[-3])
return toret
def tribonacci(n):
return tribonacci_rec(n)
if __name__ == "__main__":
print("Tribonacci(10):", tribonacci(10))
| false
|
dc8668bc96298bb2172e39038df5ffcfeacd568c
|
botnaysard/askPython
|
/forLoops.py
| 614
| 4.28125
| 4
|
# LESSON
city = ['Tokyo', 'NYC', 'Toronto', 'Philadelphia', 'Ottawa', 'London', 'Shanghai']
print("List of cities:\n")
for x in city:
print("City" + x)
print("\n")
num = [1,2,3,4,5,6,7,8,9,10]
print("Multiplications:")
for x in num:
y = x * (x - 1)
print(str(x) + " x " + str(x - 1) + " = " +str(y))
# EXERCISES
print("\n")
# create a loop that prints every city in the provided list
cities = ['Barcelona','Madrid','Bilbao','Paris']
for x in cities:
print(x)
# create a loop that prints the numbers from 1 to 10
print("\n")
count = 1
for i in range(10):
print(count)
count += 1
| false
|
15c7e77fbbb4a9dd3b253db741681ccb25e6657c
|
botnaysard/askPython
|
/nestedLoops.py
| 576
| 4.25
| 4
|
# LESSON
persons = ["John", "Marissa", "Pete", "Dayton"]
restaurants = ["Mucho Burrito", "McDonald's", "Dominos", "Poop Station"]
for p in persons:
for r in restaurants:
print(p + " eats at " + r)
# EXERCISES
# print every tic tac toe position
vert = ["a", "b", "c"]
hori = ["1", "2", "3"]
for v in vert:
for h in hori:
print("position: " + v + h)
# make each person meet each other person in "persons"
for person1 in persons:
for person2 in persons:
if person1 is not person2:
print(person1 + " please meet " + person2)
| false
|
e2e6f661dece58eb23e84de878e866878d54d295
|
franklinharvey/CU-CSCI-1300-Fall-2015
|
/Assignment 3/Problem1.py
| 251
| 4.125
| 4
|
#Franklin Harvey
#Assignment 3
#Problem 1
#TA: Amber
fullName = raw_input("What is your name in the format Last, First Middle? ")
comma = fullName.find(",")
lastName = fullName[0:comma]
#print lastName
print fullName [comma + 2:len(fullName)] + " " + lastName
| true
|
1398a66b86aca613a6dbb7ba5c534615e14348cc
|
ShreyasAmbre/python_practice
|
/PythonPracticeQuestion2.0/PythonProgram_2.3.py
| 432
| 4.1875
| 4
|
# WAP to add 'ing' at the end of a given string (length should be at least 3). If the given
# string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3,
# leave it unchanged.
s = "playing"
ls = list(s)
if len(s) > 3:
estr = "ing"
ostr = s[-3:]
if estr == ostr:
nstr = "ly"
newls = s.replace(ostr, nstr)
print(newls)
else:
print(s)
| true
|
305d22b7d4094bfe69f613bc6a11cac088cd51f0
|
ShreyasAmbre/python_practice
|
/IntroToPython/Numpy/Basic Numpy.py
| 773
| 4.375
| 4
|
# Basic of Numpy, creating array using numpy
# numpy is faster then list because it store data in continous manner
# array() method is built-in in numpy yo create the numpy object, we can pass any array like object such as
# list & tuple
import numpy
# Basic Numpy Array
arr = numpy.array([12, "12", False, "Shreyas", 1.2])
for i in arr:
print(i)
print(type(arr))
# 2-D & 3-D Array using Array
# Note:- 1-D as an element called 2-D
# Note:- 2-D as an element called 3-D
# arr2 = numpy.array([ [1-D Element], [1-D Element] ])
arr2 = numpy.array([[2, 3, 5], [4, 6, 5]])
arr3 = numpy.array([[[12, 23, 15], [13, 16, 15]], [[1, 2, 3], [1, 2, 3]]])
print("2-D Array :- ")
print(arr2)
print("3-D Array :- ")
print(arr3)
print(arr.ndim)
print(arr2.ndim)
print(arr3.ndim)
| true
|
2421994d28a7d4df0684dfcc759c7e14f098b1c5
|
worldbo/Effective_Python
|
/chapter2/19.py
| 1,305
| 4.125
| 4
|
# page44 第十九条
def remainder(number, divisor):
return number % divisor
assert remainder(20, 7) == 6
assert remainder(20, 7) == remainder(20, divisor=7) == remainder(number=20, divisor=7) == remainder(divisor=7,
number=20)
# remainder(number=20, 7) #位置参数在关键字参数之后,出错!!!
# remainder(20, number=7) #每个参数只能指定一次
# page45
def flow_rate(weight_diff, time_diff):
return weight_diff / time_diff
weight_diff = 0.5
time_diff = 3
flow = flow_rate(weight_diff, time_diff)
print('%.3f kg per second' % flow)
# 增加估算流率
def flow_rate(weight_diff, time_diff, period=1):
return (weight_diff / time_diff) * period
flow_per_second = flow_rate(weight_diff, time_diff)
flow_per_hour = flow_rate(weight_diff, time_diff, period=3600)
print('%.3f kg per second' % flow_per_second)
print('%.3f kg per hour' % flow_per_hour)
#可以扩充函数参数
def flow_rate(weight_diff, time_diff, period=1,units_per_kg=1):
return ((weight_diff * units_per_kg) / time_diff) * period
pounds_per_hour = flow_rate(weight_diff, time_diff,
period=3600,units_per_kg=2.2)
print('%.3f kg per second' % pounds_per_hour)
| false
|
2a473790322470554dc4e9abcd1a0ed09f77ec89
|
VAMSIPYLA/python-practice
|
/if_elif.py
| 437
| 4.21875
| 4
|
#If n is odd, print Weird
#If n is even and in the inclusive range of 2 to 5, print Not Weird
#If n is even and in the inclusive range of 6 to 20, print Weird
#If n is even and greater than 20 , print Not Weird
N = int(input())
if N % 2 == 1:
print("Weird")
elif N % 2 == 0 and N in range(1, 6):
print("Not Weird")
elif N % 2 == 0 and N in range(5, 21):
print("Weird")
elif N % 2 == 0 and N >= 20:
print("Not Weird")
| false
|
db2d38e26b8302c89dc54311773c5d38bdfd35d4
|
N8Brooks/schrute_farms_algos
|
/pseudorandom.py
| 1,064
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 09:35:06 2020
@author: nathan
"""
from random import randrange
from math import isqrt
def is_prime(n):
# return if it is 2 or 3
if n < 4:
return n > 1
# cut down on iteration checking 2s and 3s
if n % 2 == 0 or n % 3 == 0:
return False
# check other cases
return all(n % i and n % (i + 2) for i in range(5, isqrt(n) + 1, 6))
def get_prime(n):
a, b = 10 ** (n - 1), 10 ** n
while True:
x = randrange(a, b)
if is_prime(x):
return x
def linear_recurrence(seed, a, c, n):
while True:
yield (seed := (a * seed + c) % n)
def square_last_term(seed, n=get_prime(8) * get_prime(8)):
while True:
yield (seed := pow(seed, 2, n))
def square_the_middle(seed, n=4):
half = 10 ** (n // 2)
max_digit = 10 ** n
min_digit = 10 ** (2 * n - 1)
while True:
seed **= 2
while 0 < seed < min_digit:
seed *= 10
yield (seed := seed // half % max_digit)
| false
|
0ac484f4a9ab8dd8b0b3de4a0fb6da2a095b1471
|
sizips0418/memorizing_gittest
|
/math_python.py
| 2,960
| 4.34375
| 4
|
# # # # # # factorial in math package
# # # # # from math import factorial
# # # # # fact = factorial(5)
# # # # # print(fact)
# # # # # # use recursive function when solving factorial
# # # # # def factorial(n):
# # # # # if n == 1:
# # # # # return 1
# # # # # return n * factorial(n-1)
# # # # # print(factorial(6))
# # # # # 재귀함수로 그림을 그리는 프로그램
# # # # # import turtle as t
# # # # # def spiral(sp_len):
# # # # # if sp_len <= 5:
# # # # # return
# # # # # t.forward(sp_len)
# # # # # t.right(90)
# # # # # spiral(sp_len - 5)
# # # # # t.speed(0)
# # # # # spiral(200)
# # # # # t.hideturtle()
# # # # # t.done()
# # # # # 시에르핀스키의 삼각형을 그리는 프로그램
# # # # import turtle as t
# # # # def tri(tri_len):
# # # # if tri_len <= 10:
# # # # for i in range(0, 3):
# # # # t.forward(tri_len)
# # # # t.left(120)
# # # # return
# # # # new_len = tri_len / 2
# # # # tri(new_len)
# # # # t.forward(new_len)
# # # # tri(new_len)
# # # # t.backward(new_len)
# # # # t.left(60)
# # # # t.forward(new_len)
# # # # t.right(60)
# # # # tri(new_len)
# # # # t.left(60)
# # # # t.backward(new_len)
# # # # t.right(60)
# # # # t.speed(-1000)
# # # # tri(160)
# # # # t.hideturtle()
# # # # t.done()
# # # # 나무를 그리는 프로그램
# # # import turtle as t
# # # def tree(br_len):
# # # if br_len <= 5:
# # # return
# # # new_len = br_len * 0.7
# # # t.forward(br_len)
# # # t.right(20)
# # # tree(new_len)
# # # t.left(40)
# # # tree(new_len)
# # # t.right(20)
# # # t.backward(br_len)
# # # t.speed(-1000)
# # # t.left(90)
# # # tree(70)
# # # t.hideturtle()
# # # t.done()
# # # 눈꽃을 그리는 프로그램
# # import turtle as t
# # def snow_line(snow_len):
# # if snow_len <= 10:
# # t.forward(snow_len)
# # return
# # new_len = snow_len / 3
# # snow_line(new_len)
# # t.left(60)
# # snow_line(new_len)
# # t.right(120)
# # snow_line(new_len)
# # t.left(60)
# # snow_line(new_len)
# # t.speed(-1000)
# # snow_line(150)
# # t.right(120)
# # snow_line(150)
# # t.right(120)
# # snow_line(150)
# # t.hideturtle()
# # t.done()
# from math import sin,cos,exp,log
# functions = {'sine':sin,
# 'cosine': cos,
# 'exponential': exp,
# 'logarithm': log}
# print(functions)
# print(functions['exponential'])
# print(functions.keys())
# print(functions.values())
# for name in functions:
# print('The result of {} (1) is {}'.format(name, functions[name](1.0)))
def test_sequence(N):
limit = 1.0
partial_sum = 1.0
for n in range(1 , N+1):
partial_sum = partial_sum + limit
limit = limit / 2.0
return limit, partial_sum
if __name__ == '__main__':
print(test_sequence(50))
| false
|
290f44cf617673bc0203df18a99141e36e701a9d
|
rudrashishbose/PythonBible
|
/emailSlicer.py
| 346
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 19:24:24 2020
@author: Desktop
"""
email_id = input("enter your email id: ")
username = email_id[0:email_id.index("@"):1]
domain_name = email_id[email_id.index("@")+1:]
output = "Your username is {} and your domain name is {}"
print(output.format(username,domain_name))
| true
|
9eae76c78fdce03ce5285d1ad9bc32f87acd6da4
|
rudrashishbose/PythonBible
|
/BabyTalkSimulator.py
| 391
| 4.25
| 4
|
#import random as rand
from random import choice
questions = ["Why is the sky blue?: ","Why is water wet?: ", "Why is the earth round?: "]
#answer = input(questions[rand.randint(0,2)]).strip().capitalize() #this is one way
answer = input(choice(questions)).strip().capitalize()
while (answer != "Just because!"):
answer = input("Why?: ").strip().capitalize()
print("Oh..Okay")
| false
|
4a43883591df60bf17aaa26b91aa6fdadf470f6e
|
safin777/ddad-internship-Safin777
|
/factorial.py
| 391
| 4.21875
| 4
|
def factorial(n):
factorial=1
if n<0 :
print("Factorial does not exits for value less than 0")
elif n == 0 :
print("The factorial of 0 is 1")
elif 0<n<10 :
for i in range(1,n+1):
factorial=factorial*i
print("The factorial of",n,"is",factorial)
else:
print("The input number is greater than 10")
if __name__ == '__main__':
number = int(input())
factorial(number)
| true
|
48f7a90dfc5a7e933d00ad2b69806418992baf48
|
jillianhou8/CS61A
|
/labs/lab01/lab01.py
| 1,192
| 4.15625
| 4
|
""
"Lab 1: Expressions and Control Structures"""
# Coding Practice
def repeated(f, n, x):
"""Returns the result of composing f n times on x.
>>> def square(x):
... return x * x
...
>>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4
81
>>> repeated(square, 1, 4) # square(4)
16
>>> repeated(square, 6, 2) # big number
18446744073709551616
>>> def opposite(b):
... return not b
...
>>> repeated(opposite, 4, True)
True
>>> repeated(opposite, 5, True)
False
>>> repeated(opposite, 631, 1)
False
>>> repeated(opposite, 3, 0)
True
"""
while n>0:
x = f(x)
n -= 1
return x
def sum_digits(n):
"""Sum all the digits of n.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
"""
total = 0
while n > 0:
total += n % 10
n = n // 10
return total
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
while n > 0:
if n % 10 == 8 and (n // 10) % 10 == 8:
return True
n = n // 10
return False
| true
|
2ae557b4da917c5273c5a79b86618bd97805134e
|
antGulati/number_patterns
|
/narssistic numbers/narcissistic_number_list_python.py
| 887
| 4.28125
| 4
|
# program to take a long integer N from the user and print all the narcissistic number between one and the given number
# narcissistic numbers are those whose sum of individual digits each raised to the power of the number of digits gives the orignal number
import math
def digitcount(num):
return int(math.log(num,10)) + 1
def isNstc(a):
if a <= 9 and a >= 0:
return True
q = 0
num_digits = digitcount(a)
for i in range(num_digits):
digit = int(a/(10 ** i))
digit = digit % 10
q += (digit ** num_digits)
if q == a:
return True
return False
if __name__ == "__main__":
print("to find all narcissistic number between one and a given upper bound number")
upper_bound = int(input("enter the upperbound: "))
print("the narcissistic numbers in the given range are:")
for i in range(1,upper_bound+1):
if isNstc(i):
print(i)
| true
|
488db0e00a310b5c45987ccbdf3171ccb6d875fb
|
clickykeyboard/SEM-2-OOP
|
/OOP/Week 08/assignment/employee.py
| 2,941
| 4.34375
| 4
|
class Employee:
def __init__(self, name, id, department, job_title):
self.name = name
self.id = id
self.department = department
self.job_title = job_title
employee_1 = Employee("Ahmed", "12345", "Management", "Manager")
employee_2 = Employee("Abbas", "54321", "Creative Team", "Designer")
employee_3 = Employee("Ahsan", "67891", "Management", "Senior Manager")
employees = {
employee_1.id: employee_1,
employee_2.id: employee_2,
employee_3.id: employee_3
}
while True:
print("""
Welcome to our system\n
Press 1 to look up an employee\n
Press 2 to add a new employee\n
Press 3 to change an existing employees name, department, or job title in the dictionary\n
Press 4 to delete an employee from the dictionary\n
Press 5 to exit\n
""")
print(employees)
choices = [1, 2, 3, 4, 5]
choice = int(input("> "))
if choice not in choices:
print("Please enter a valid choice")
elif choice == 1:
employee_id = input("Which employee do you want to look up?\n> ")
query = employees.get(employee_id)
if query is None:
print("Could not find employee!")
else:
print(query.id, query.name, query.department, query.job_title)
elif choice == 2:
print("Add a new employee: ")
employee_name = input("Enter employee name: ")
employee_id = input("Enter employee id: ")
employee_department = input("Enter employee department: ")
employee_job_title = input("Enter employee job title: ")
new_employee = Employee(employee_name, employee_id, employee_department, employee_job_title)
employees[new_employee.id] = new_employee
elif choice == 3:
print("Which employee information do you want to change?")
employee_choice = input("> ")
query = employees.get(employee_choice)
if query is None:
print("Could not find employee!")
else:
employee_name = input("Enter employee name: ")
employee_id = input("Enter employee id: ")
employee_department = input("Enter employee department: ")
employee_job_title = input("Enter employee job title: ")
query.name = employee_name
query.id = employee_id
query.department = employee_department
query.job_title = employee_job_title
employees.pop(query.id)
employees[query.id] = query
elif choice == 4:
print("Which employee information do you want to delete?")
employee_choice = input("> ")
query = employees.get(employee_choice)
if query is None:
print("Could not find employee!")
else:
employees.pop(query.id)
print("Deleted employee!")
elif choice == 5:
print("Exiting...")
exit()
| true
|
48a341c581e8b042d226bfc9016ba6a752bdde77
|
ARPIT443/Python
|
/8Jun-problem5.py
| 328
| 4.125
| 4
|
import datetime
now = datetime.datetime.now().hour
name=input('Enter your name')
if now in range(0,12):
print('Hello'+name+',Good Morning..!')
elif now in range(12,18):
print('Hello'+name+',Good Afternoon..!')
elif now in range(18,22):
print('Hello'+name+',Good Evening..!')
else:
print('Hello'+name+',Good Night..!')
| false
|
ef24c44d58052f1cba4008a7449b61fc123da0f1
|
ARPIT443/Python
|
/problem6.py
| 881
| 4.125
| 4
|
option = '''
Select operation you want to perform--->>
1.Show contents of single file :
2.Show contents of multiple file :
3.cat -n command :
4.cat -E command :
'''
print(option)
choice=input()
if choice == '1':
fname=input('Name of file :')
f=open(fname,'r')
print(f.read())
f.close()
elif choice == '2':
num=int(input('Enter no. of files :'))
fnames=[]
print('Enter name of files seperated by enter :')
for i in range(1,num+1):
name=input()
fnames.append(name)
for i in fnames:
f=open(i,'r')
print(f.read())
f.close()
elif choice == '3':
fname=input('Name of file :')
f=open(fname,'r')
data=f.read()
a=data.split('\n')
n=1
for i in a:
print(str(n)+' ' +i)
n=n+1
elif choice == '4':
fname=input('Name of file :')
f=open(fname,'r')
data=f.read()
a=data.split('\n')
for i in a:
print(i+'$')
else:
print('wrong input')
| true
|
9a6cd9211feb8dc010e44af0e55eeecc592bbc1d
|
Benjamin1118/cs-module-project-recursive-sorting
|
/src/searching/searching.py
| 1,160
| 4.3125
| 4
|
# TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
#find a midpoint start search there
#check if start < end first
if start > end:
return -1
mid = (start + end) // 2
if arr[mid] == target:
return mid
# check if mid is < target
#if yes call binary search on new area
else:
if arr[mid] < target:
start = mid + 1
end = len(arr)
return binary_search(arr[start:end], target, start, end)
# check if mid is > target
#if yes call binary search on new area
if arr[mid] > target:
start = 0
end = mid
return binary_search(arr[start:end], target, start, end)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
# Your code here
pass
| true
|
5a58d0e43b93f4ea82b39b3fb181f89458b5369b
|
nabepa/coding-test
|
/Searching/bisect_library.py
| 549
| 4.125
| 4
|
# Count the number of frequencies of elements whose value is between [left, right] in a sorted array
from bisect import bisect_left, bisect_right
def count_by_range(array, left_val, right_val):
right_idx = bisect_right(array, right_val)
left_idx = bisect_left(array, left_val)
return right_idx - left_idx
if __name__ == '__main__':
array = list(map(int, input().split()))
left, right = map(int, input().split())
cnt = count_by_range(array, left, right)
print(cnt) if cnt > 0 else print(-1)
'''
1 2 3 3 4 5
3 4
'''
| true
|
1bb30d2a451e8f528b364789d3b07537f364f4f5
|
Hallessandro/GeradorScriptPython
|
/gerarTagCustom.py
| 719
| 4.21875
| 4
|
instituicao = input("Digite a sigla da instituicao: ")
numTarefa = input('Digite o número da tarefa: ')
print("""/* INICIO CUSTOMIZACAO ESPECIFICA '{instituicao}' - TAREFA '{numTarefa}' */""".format(instituicao=instituicao, numTarefa=numTarefa))
print("""/* FIM CUSTOMIZACAO ESPECIFICA '{instituicao}' - TAREFA '{numTarefa}' */""".format(instituicao=instituicao, numTarefa=numTarefa))
print("\n")
print("""<%-- INICIO CUSTOMIZACAO ESPECIFICA '{instituicao}' - TAREFA '{numTarefa}' --%>""".format(instituicao=instituicao, numTarefa=numTarefa))
print("""<%-- FIM CUSTOMIZACAO ESPECIFICA '{instituicao}' - TAREFA '{numTarefa}' --%>""".format(instituicao=instituicao, numTarefa=numTarefa))
input("Aperte ENTER para sair")
| false
|
3a12122d4e65fd58d473244fe50a9de3a1339b27
|
austinjhunt/dailycodingproblem
|
/dcp2.py
| 1,924
| 4.125
| 4
|
#This problem was asked by Uber.
#Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
#For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
#Follow-up: what if you can't use division?
# First use division approach
def dcp2_wDiv(num_array):
product = 1
for num in num_array:
product = product * num
for i in range(len(num_array)):
num_array[i] = product / num_array[i]
return num_array
#print(dcp2_wDiv([1,2,3,4,5]))
# Now, if you cant divide?
def dcp2_woDiv(num_array):
# exclusively multiply everything
count = 0
new_num_array = []
for i in range(len(num_array)):
product = 1
print "\n\ni = " + str(i)
for j in range(0,i): #nums before current num
print "product =" + str(product) + "*" + str(num_array[j])
product = product * num_array[j]
count += 1
for k in range(i+1, len(num_array)):
print "product =" + str(product) + "*" + str(num_array[k])
product = product * num_array[k]
count += 1
print "product = " + str(product)
new_num_array.append(product)
print("Count =", count)
return new_num_array
#print(dcp2_woDiv([1,2,3,4,5]))
def newdcp2(num_array):
temp = 1
products = [None] * len(num_array)
for j in range(0, len(num_array)):
products[j] = 1;
for i in range(0,len(num_array)):
products[i] = temp
temp = temp * num_array[i]
# init temp to one for product on right side
for i in range(len(num_array) - 1, -1,-1):
products[i] = products[i] * temp
temp = temp * num_array[i]
return products
#print(newdcp2([1,2,3,4,5])
| true
|
18e5a15a489628f3c1a1e8d2a6e5b99ce66ddeeb
|
DrDavxr/email-text-finder
|
/mainPackage/extension_detector.py
| 320
| 4.40625
| 4
|
'''
This module finds the extension of the file selected by the user.
'''
def find_extension(filename):
'''
Finds the extension of a given file.
input: filename
output: file extension
'''
filename_list = filename.split('/')
extension = filename_list[-1].split('.')[-1]
return extension
| true
|
e009fa6b516388eb7018d208ee2325196c7909ba
|
sonisidhant/CST8333-Python-Project
|
/calc.py
| 2,170
| 4.1875
| 4
|
######################
# calc.py
# By Sidhant Soni
# October 24, 2018
######################
# Declaring variables and assigning user input
a = input('Enter First Number: ');
b = input('Enter Second Number: ');
print('\n')
# Converting user input string to integer
firstN = int(a);
secondN = int(b);
# Making the list of two numbers using user input
numbers = [firstN,secondN];
# Defining a test case
def arthDivide(c,d):
return c / d;
def add(c,d):
return c + d;
# Function for operating arithmetic operation
def arithmetic():
Sub = numbers[0] - numbers[1];
Add = numbers[0] + numbers[1];
modulus = numbers[0] % numbers[1];
multiply = numbers[0] * numbers[1];
print('Result of a-b = ', Sub);
print('Result of a+b = ', Add);
print('Result of a%b = ', modulus);
print('Result of a/b = ', multiply, '\n');
# Function for operating comparison operation
def comparison():
if numbers[0] == numbers[1]:
print('number a and b are equal');
else:
print('Number a and b are not equal');
if numbers[0] > numbers[1]:
print('Number a is greater than b');
else:
print('Number a is smaller than b');
# Function for operating logic operation
def logic():
if numbers[0] >= 10 and numbers[1] >=5:
print('True')
else:
print('False')
if numbers[0] > 10 or numbers[1] >= 5:
print('True')
else:
print('False')
# Function for operating decision structure operation
def decisionStructure():
age = int(input('Enter your age: '))
if age >= 18:
print('You are eligible for driving');
else:
print('Your age is less than 18. So, you are not eligible for driving.');
# Function for operating repetition structure operation
def repetitionStructure():
firstNumber = int(input('Enter the number to start printing: '));
secondNumber = int(input('Enter the number to finish printing: '))
while(firstNumber<secondNumber):
print('The number is: ', firstNumber);
firstNumber += 1;
# Running all the functions
repetitionStructure();
arithmetic();
comparison();
logic();
decisionStructure();
| true
|
702f5ca9c7b730ac315b0fc6072e4bee0216824f
|
decadevs/use-cases-python-oluwasayo01
|
/instance_methods.py
| 1,277
| 4.3125
| 4
|
# Document at least 3 use cases of instance methods
class User():
def __init__(self, username = None):
self.__username = username
def setUsername(self, x):
self.__username = x
def getUsername(self):
return(self.__username)
Steve = User('steve1')
print('Before setting:', Steve.getUsername())
Steve.setUsername('steve2')
print('After setting:', Steve.getUsername())
class BankAccount:
def __init__(self):
self.balance = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
class Shape:
def __init__(self, length, width):
self.length = length
self.width = width
self.area = 0
self.perimeter = 0
def calc_area(self):
pass
def calc_perimeter(self):
pass
class Rectangle(Shape):
def calc_area(self):
self.area = self.length * self.width
def calc_perimeter(self):
self.perimeter = 2(self.length + self.width)
def get_area(self):
return self.area
def get_perimeter(self):
return self.perimeter
shape = Rectangle(23, 12)
print(shape.get_area())
print(shape.calc_area())
print(shape.get_area())
| true
|
abad3a169e74dd4e19cbc6877567eb39a0bdb683
|
AthenaTsai/Python
|
/python_notes/OOP/class.py
| 904
| 4.5625
| 5
|
# Class: object-oriented programming, inheritance
class Parent: # parent class, class is a structure, start with uppercase
def __init__(self, name, age, ht=168): # self tells the function is for which class
self.name = name
self.age = age
self.ht = ht
print('this is the parent class')
def parent_func(self):
print('your name is:' + self.name)
def test(self):
print('parent_before')
p = Parent('athena', 18) # now creating an object
p.parent_func()
#
class Child(Parent): # inherit contents from Parent class
def child_func(self):
print('this is the child func')
def test(self): # will overwrite parent methods
print('child_after')
c = Child('Kev', 23) # inherit this from Parent class
c.child_func()
c.parent_func() # inherit this from Parent class
c.test() # overwrite Parent class version
print(c.ht)
| true
|
0750e02ab7a6e963ea1a1191d1def0e52a60f856
|
sourcery-ai-bot/Estudos
|
/PYTHON/Python-Estudos/motorcycles.py
| 1,814
| 4.28125
| 4
|
# ALTERANDO, ACRESCENTANDO E REMOVENDO ITENS DE UMA LISTA
motorcycles = ['honda', 'yamaha', 'suzuki']
# ALTERANDO UM ITEM DE UMA LISTA
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# ACRESCENTANDO ELEMENTOS EM UMA LISTA
# CONCATENANDO ELEMENTOS NO FINAL DE UMA LISTA
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
# ADICIONANDO ITENS A PARTIR DE UMA LISTA VAZIA
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
# INSERINDO ELEMENTOS EM UMA LISTA
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
# REMOVENDO ELEMENTOS DE UMA LISTA
# instrução (del)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[1]
print(motorcycles)
# método (pop)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
# utilizando em uma frase
motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")
# REMOVENDO ITENS DE QUALQUER POSIÇÃO EM UMA LISTA
motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop(0)
print("The first motorcycle I owned was a " + last_owned.title() + ".")
# REMOVENDO UM ITEM DE ACORDO COM O VALOR
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
# utilizando em uma frase
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'yamaha'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
| false
|
1383c2f21b5c3d55f153a21394baf6805a9c308f
|
max180643/Pre-Programming-61
|
/Onsite/Week-3/Monday/Custom Sign 2.0.py
| 1,153
| 4.15625
| 4
|
"""Custom Sign"""
def main():
"""Main Function"""
size = int(input())
text = input()
text1 = text[:size - 2]
align = input()
if align == "Left":
print("*" * size)
print("*%s*" % (" " * (size - 2)))
print("*%s*" % (text1.ljust(size - 2)))
print("*%s*" % (" " * (size - 2)))
print("*" * size)
elif align == "Center":
if (size - 2 - len(text)) % 2 == 0: # เลขคู่
print("*" * size)
print("*%s*" % (" " * (size - 2)))
print("*%s*" % (text1.center(size - 2)))
print("*%s*" % (" " * (size - 2)))
print("*" * size)
else: # เลขคี่
print("*" * size)
print("*%s*" % (" " * (size - 2)))
print("* %s*" % (text1.center(size - 3)))
print("*%s*" % (" " * (size - 2)))
print("*" * size)
elif align == "Right":
print("*" * size)
print("*%s*" % (" " * (size - 2)))
print("*%s*" % (text1.rjust(size - 2)))
print("*%s*" % (" " * (size - 2)))
print("*" * size)
main()
| false
|
a48f0730061352526c030c3ac66845e48fd213a8
|
thelmuth/ProfessorProjectPrograms110
|
/calculations/pizza.py
| 1,003
| 4.25
| 4
|
"""
*****************************************************************************
FILE: pizza.py
AUTHOR: Professors
ASSIGNMENT: Calculations
DESCRIPTION: Professors' program for Pizza problem.
*****************************************************************************
"""
import math
def main():
standard_diameter = int(input('What is the diameter of a "standard" size pie? '))
slice_count = int(input("How many slices are in a standard size pie? "))
slices = int(input("How many standard slices do you want? "))
diameter = int(input("What is the diameter of the pies you will buy? "))
# Calculate number of pies
pies = slices * (standard_diameter ** 2.0) / ((diameter ** 2) * slice_count)
pies_ceiling = int(math.ceil(pies))
print("You will need to buy", pies_ceiling, str(diameter) + "-inch diameter pies.")
# this invokes the main function. It is always included in our
# python programs
if __name__ == "__main__":
main()
| true
|
ba433e81b15fbe40ae03d9f2425ebc0de5ba6ba1
|
tamalesimon/CS1101----uni
|
/Unit 3_conditionals/nested_made_easy.py
| 379
| 4.375
| 4
|
number_of_days_worked = 30
if number_of_days_worked != 30:
print("HOW MANY DAYS DID YOU WORK?")
else:
if number_of_days_worked <30:
print("YOU WORKED LESS DAYS")
else:
print("YOU WORKED A MONTH")
number_of_days_worked = 30
if number_of_days_worked != 30 and number_of_days_worked <30:
print("YOU WORKED LESS DAYS")
else:
print("YOU WORKED")
| false
|
350c2b4dc2d213524d7d35754e8d1d908d2dc118
|
tamalesimon/CS1101----uni
|
/unit 7/discussion.py
| 461
| 4.46875
| 4
|
country = 'Uganda', 'Kenya', 'Norway', 'South Africa', #defining a tuple
capital = ['Kampala', 'Nairobi', 'Oslo', 'Joburg'] #defining a list
#using zip
country_capital = list(zip(country, capital))
print(country_capital) #printing out a list of tuples
for index in enumerate(country_capital):
print(index)
my_capital_country = {'Uganda':'Kampala', 'Kenya':'Nairobi', 'Norway':'Oslo', 'South Africa':'Joburg'}
print(my_capital_country.items()) #printing
| false
|
9dd0b3f60eb6ed3e167b001035da7cb07630a480
|
Jaffacakeee/Python
|
/Python_Bible/Section 5 - The ABCs/hello_you.py
| 437
| 4.125
| 4
|
# Ask user for name
name = input("What is your name? ")
# Ask user for age
age = input("What is your age? ")
# Ask user for city
city = input ("What city do you live in? ")
# Ask user for what they love
love = input("What do you love? ")
# Build the structure of the sentence
string = "Your name is {} and you are {} old. You live in {} and love {}."
output = string.format(name, age, city, love)
# Print out sentence
print(output)
| true
|
df6b0634ce5825b8369d78f7f0c75ba6b6c19e17
|
FrMiMoAl/tareas
|
/calificaciones.py
| 804
| 4.1875
| 4
|
nota = input("nota: ")
nota = int(nota)
if nota >= 1 and nota <= 10 :
print("La nota es correcta")
if nota >= 9 and nota <= 10 :
print("La nota es A")
print ("Exelente sigue asi")
if nota >= 7 and nota <= 8 :
print("La nota es B")
print("Estuviste muy cerca puedes mejorar")
if nota <= 6 and nota > 5 :
print("La nota es C")
print("puedes mejorar")
if nota <= 5 :
print("La nota es D")
print("Estas en el promedio")
if nota <= 4 :
print("La nota es E")
print("!!!Estudia!!!!")
if nota >= 1 and nota <= 3 :
print("La nota es F")
print("Mejor no digo nada por que estas aplasado")
| false
|
d3906ba829aecd6d2d665ba33306ebcafcb39f26
|
Virtual-Uni/Discover-Python
|
/Exams/15.11.2020/Solutions/Mueem/Exam1/Task6.py
| 549
| 4.25
| 4
|
"""
6. Task
Your code should calculate the average mark of students in a dictionary as key/value pairs.
Key represents the name of the student, whereas value represents marks_list from last few exams.
"""
marks_dictionary = {
'Hasan': [10, 5, 20],
'Sakir': [10, 10, 14],
'Hanif': [20, 15, 10],
'Saiful': [20, 20, 20]
}
empty_list = []
for x in marks_dictionary.keys():
empty_list.append(x)
for y in empty_list:
marks_list = marks_dictionary[y]
average = sum(marks_list) / len(marks_list)
print('Average of {} : {}'.format(y,average))
| true
|
119b1ca27fc2a33b201c4f635e37fa8c7d77d4e6
|
Virtual-Uni/Discover-Python
|
/Exams/15.11.2020/Solutions/Mueem/Exam1/Task4.py
| 422
| 4.3125
| 4
|
"""
4. Task
Your provided code section should find a meaning of a word from a dictionary containing
key/value pairs of word: value.
line.
"""
input_word = input('Enter a word(Passed/Failed/Other) = ')
dictionary = {'Passed':'You have practiced at home.', 'Failed': 'You was not serious.',
'Other': 'Write your own meaning.'}
if input_word.isalpha():
print(dictionary[input_word])
else:
print('Enter a string')
| true
|
58d38c4e908813e76d824039e7921e3dbfe91bb2
|
marvin939/projecteuler-python
|
/problem 9 - special pythagorean triplet/problem9.py
| 1,347
| 4.34375
| 4
|
'''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
from math import sqrt, floor, ceil
a = 1
b = None
c = None
P = 1000 # Perimeter of right-angled triangle. eg. a + b + c = 1000
# Must be a valid right-angle triangle perimeter since I'm only
# allowing natural numbers for a, b and c!!!
satisfied = False
aThirdOfP = floor(P / 3)
while a <= aThirdOfP:
# ^ condition is narrowed to 1/3 of P because we expect a < b < c
# and a + b + c = P; a cannot be larger than b and c, but can get somewhat
# close.
b = floor((P - 2 * a) * P / (2 * (P - a)))
c = floor(sqrt(a**2 + b**2))
if a + b + c == P and (a < b < c):
satisfied = True
break
a += 1
if satisfied:
print('pythagorean triplet satisfying a + b + c = {}'
' and a < b < c found:'.format(P))
print('a = {}, b = {}, c = {}'.format(a, b, c))
print('a * b * c =', a * b * c)
print('CONDITION SATISFIED!!!')
else:
print('a = {}, b = {}, c = {}'.format(a, b, c))
print('a^2 + b^2 = {}, and c^2 = {}'.format(a**2 + b**2, c**2))
print('a * b * c =', a * b * c)
print('NOT SATISFIED')
| true
|
b068813edb18ee50949c41b70ba6047a906ea794
|
marvin939/projecteuler-python
|
/problem 1 - multiples of 3 and 5/problem1.py
| 402
| 4.25
| 4
|
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
x = 1
sum35 = 0
while x < 1000: # below 10
addToSum = False
if x % 3 == 0 or x % 5 == 0:
sum35 += x
x += 1
print(sum35)
# sum of multiples of 3 and 5's below 1000 is 233168
| true
|
1855ba6951647a66912cde9b70e1574cef006706
|
ZryletTC/CMPTGCS-20
|
/labs/lab02/lab02Funcs.py
| 2,281
| 4.1875
| 4
|
# lab02Funcs.py Define a few sample functions in Python
# T. Pennebaker for CMPTGCS 20, Spring 2016
def perimRect(length,width):
"""
Compute perimiter of rectangle
>>> perimRect(2,3)
10
>>> perimRect(4, 2.5)
13.0
>>> perimRect(3, 3)
12
>>>
"""
return 2*(length+width)
def areaRect(length,width):
"""
compute area of rectangle
>>> areaRect(2,3)
6
>>> areaRect(4, 2.5)
10.0
>>> areaRect(3,3)
9
>>>
"""
return length*width
def isList(x):
"""
returns True if argument is of type list, otherwise False
>>> isList(3)
False
>>> isList([5,10,15,20])
True
"""
return ( type(x) == list ) # True if the type of x is a list
def isString(x):
""""
return True if x is a string, otherwise False
"""
return (type(x)==str)
# The following function is provided for you as an example
# of how to write a Python function involving "or"
# This contains HINTS as to how to do the next function definition.
def isAdditivePrimaryColor(color):
"""
return True if color is a string equal to "red", "green" or "blue", otherwise False
>>> isAdditivePrimaryColor("blue")
True
>>> isAdditivePrimaryColor("black")
False
>>> isAdditivePrimaryColor(42)
False
>>>
"""
return ( (color == "red" ) or (color == "green" ) or (color == "blue") )
# NOTE: the following will NOT work for isAdditivePrimaryColor:
#
# def isAdditivePrimaryColor(color):
# return ( color == "red" or "green" or "blue" )
#
# Try it, and convince yourself that it doesn't work.
# Does it fail to compile, fail to run (python vomit), or just give the
# wrong answer? You may be surprised!
# Try it, then try to understand _why_ this doesn't do what you want
# Hints: 'or' is an operator, and it must take operands that are
# either True or False
# (color == "red") is either True or False. What about the other operands?
def isSimpleNumeric(x):
"""
returns True if x is has type int or float; anything else, False
>>> isSimpleNumeric(5)
True
>>> isSimpleNumeric(3.5)
True
>>> isSimpleNumeric("5")
False
>>> isSimpleNumeric([5])
False
>>> isSimpleNumeric(6.0221415E23)
True
>>>
"""
return ((type(x)==int) or (type(x)==float))
| true
|
86a7139693f7997f4b0b0018f298bb45fbbd4126
|
shivapk/Programming-Leetcode
|
/Python/Trees/checkGraphisaTreecolorsGraphds[n,n].py
| 2,218
| 4.21875
| 4
|
#say given graph is a valid tree or not.An undirected graph is tree if it has following properties.
#1) There is no cycle.
#2) The graph is connected.
#Time: O(n) where n is the number of vertices..as number of edges will be n-1.
#space: O(n) where n is number of vertices
# keep track of parent in case of undirected graph, although directed graph is not tree but if you want to find cycle for directed graph then p is not required
'''
cycle:For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v,
then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle.
'''
from collections import defaultdict
class Graph:
def __init__(self,n):
self.vcount=n
self.adjlist=defaultdict(list)
def insert(self,v1,v2):
self.adjlist[v1].append(v2)
self.adjlist[v2].append(v1)
class Solution:
def isgraph_tree(self,g):
color=['w']*(g.vcount)
#for v in range(g.vcount):#as we need to show graph is connected so need to do for every vertex
if self.dfs(0,color,g,-1): #choose any random vertex- 0 and -1 is assumed parent of 0 #parent is not required to check cycle in directed graph
return False
for i in range(g.vcount): #check after dfs anything is left still not visited
if color[i]=='w':
return False
return True
def dfs(self,v,color,g,p): # returns True if there is any cycle in the graph, p is for parent
color[v]='g' # grey means in process not yet backtracked to this vertex
for w in g.adjlist[v]:
if color[w]=='w' and self.dfs(w,color,g,v): # for directed graph p is not required
return True
elif color[w]=='g' and w!=p : # for directed graph p is not required
return True # cycle found
color[v]='b' #time to backtrack
return False # no cycle found
g=Graph(5)# number of vertices so nodes are labels from 0 to n-1
g.insert(1, 0)
g.insert(0, 2)
#g.insert(2,1)
g.insert(0, 3)
g.insert(3, 4)
s=Solution()
print (s.isgraph_tree(g))
| true
|
f95f64cfdb3c2aa61700e311d79610d79262d1e8
|
TheDiegoFrade/python_crash_course_2nd_ed
|
/input_while_loops.py
| 1,515
| 4.125
| 4
|
#number = input("Enter a number, and I'll tell you if it's even or odd: ")
#number = int(number)
#if number % 2 == 0:
# print(f"\nThe number {number} is even.")
#else:
# print(f"\nThe number {number} is odd.")
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
#prompt = "\nTell me something, and I will repeat it back to you:"
#prompt += "\nEnter 'quit' to end the program. "
#message = ""
#while message != 'quit':
# message = input(prompt)
# if message != 'quit':
# print(message)
# prompt = "\nPlease enter the name of a city you have visited:"
# prompt += "\n(Enter 'quit' when you are finished.) "
#Using break
# ➊ while True:
# city = input(prompt)
# if city == 'quit':
# break
# else:
# print(f"I'd love to go to {city.title()}!")
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(f'\n{pets}')
while 'cat' in pets:
pets.remove('cat')
print(pets)
| true
|
d34f14cf5ffa70b9d4bacf51ef4a41e8c41d533c
|
TheDiegoFrade/python_crash_course_2nd_ed
|
/python_poll.py
| 1,020
| 4.15625
| 4
|
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which are your favorite tacos? ")
# Store the response in the dictionary.
responses['name'] = name
responses['flavor'] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to tell me something else about you?(yes/no)")
if repeat.lower() == 'no':
polling_active = False
comment = ""
print(comment)
print("Goodbye!")
else:
comment = input("Write your comment please: ")
polling_active = False
print(comment)
print("Goodbye!")
responses['comment'] = comment
print(responses.items())
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for value in responses.values():
print(value)
print(f'Poll Dictionary: {responses}')
print("\n--- Poll Results ---")
for item in responses.items():
print(item)
| true
|
f740acd2ff5d494434ef64d91baed730e754f779
|
Izydorczak/learn_python
|
/gdi_buffalo_2015/class2/functions_continued.py
| 1,899
| 4.78125
| 5
|
"""
filename: functions_continued.py
author: wendyjan
This file shows more about functions.
"""
def say_hi():
print "Hello World!"
def say_hi_personally(person):
print "Hello " + person + "!"
def add_together(a, b):
return a + b
def calculate_y(m, x, b):
return m * x + b
def add_together_many(a, *args):
result = a
for n in args:
result += n
return result
def scale_list(my_list):
# TODO please implement this!
pass
if __name__ == "__main__":
# Call a function.
say_hi()
# Call a function with a parameter (also called an argument).
say_hi_personally("Elena")
# Print a value returned from a function.
result = add_together(2, 3)
print "The first result is:", result
# See the scope of a variable.
# Comment out the following three lines unless you want an error!
# result = add_together(5, 6)
# print "Done adding together", a, "and", b
# print "The result of add_together(5, 6) is", result
# Another scope example. What's different about this one?
# Why did it work, when the previous one in comments did not?
a = 7
b = 11
result = add_together(a, b)
print "Done adding together", a, "and", b
print "The result of add_together(a, b) is", result
# Now what if we want to give three parameters?
print "Given the formula y = 3x + 5, what is y when x is 8?"
print "Don't forget that old formula, y = mx + b."
print "y =", calculate_y(3, 8, 5)
# What about an arbitrary number of parameters?
result = add_together_many(1, 2, 3, 4, 5, 6)
print "All of those together equal:", result
# Now what if we have a list, and want to multiply each element?
my_list = range(5)
print my_list, "scaled by 3 is", my_list * 5
print "Oops!!! No!!! I meant to say it's", scale_list(my_list)
# Hmm... looks like this needs work!
| true
|
0f8919198cf24d822e3a6324042480f5f4ba34fb
|
Izydorczak/learn_python
|
/gdi_buffalo_2015/class2/sample_library.py
| 1,468
| 4.3125
| 4
|
"""
filename: sample_library.py
author: wendyjan
Small start to our own library to write letters in Turtle.
"""
import turtle
def print_w(t, start_x, start_y):
"""Draws an uppercase 'W' in Turtle.
Args:
t (turtle.Turtle): used to draw letter.
start_x (int): starting x coordinate at lower left of letter.
start_y (int): starting y coordinate at lower left of letter.
"""
t.penup()
t.goto(start_x, start_y + 30) # Assume total letter size is 20x30
t.pendown()
t.goto(start_x + 7, start_y)
t.goto(start_x + 15, start_y + 10)
t.goto(start_x + 23, start_y)
t.goto(start_x + 30, start_y + 30)
t.penup()
def print_j(t, start_x, start_y):
"""Draws an uppercase 'W' in Turtle.
Args:
t (turtle.Turtle): used to draw letter.
start_x (int): starting x coordinate at lower left of letter.
start_y (int): starting y coordinate at lower left of letter.
"""
t.penup()
t.goto(start_x, start_y + 30)
t.pendown()
t.goto(start_x + 20, start_y + 30)
t.penup()
t.goto(start_x, start_y + 30)
t.pendown()
t.goto(start_x, start_y)
t.goto(start_x + 20, start_y)
t.penup()
t.goto(start_x, start_y + 15)
t.pendown()
t.goto(start_x + 15, start_y + 15)
t.penup()
if __name__ == "__main__":
my_turtle = turtle.Turtle()
wn = turtle.Screen()
print_w(my_turtle, 0, 0)
print_j(my_turtle, 35, 0)
wn.exitonclick()
| false
|
c2f2744f17073e94b26f0c01f33dfd4750a65007
|
shaneapen/LeetCode-Search
|
/src/utils.py
| 1,643
| 4.34375
| 4
|
def parse_args(argv):
"""Parse Alfred Arguments
Args:
argv: A list of arguments, in which there are only two
items, i.e., [mode, {query}].
The 1st item determines the search mode, there are
two options:
1) search by `topic`
2) search by `problem content/name/index`
The 2nd item is a string which is the user entered
from Alfred, which as known as {query}.
Return:
A argument dictionary, which contains following fields:
- mode: topic/problem
- difficulty: easy/medium/hard
- query: <query content>
"""
args = {}
# determine search mode
if(argv[0].lower() == "--topic"):
args["mode"] = "topic"
else:
args["mode"] = "problem"
# parsing query arguments
query_args = argv[1].split(' ')
# get difficulty (only take the highest level if
# multi-level are selected)
args["difficulty"] = None
if ("-e" in query_args) or ("--easy" in query_args):
args["difficulty"] = "Easy"
if ("-m" in query_args) or ("--medium" in query_args):
args["difficulty"] = "Medium"
if ("-h" in query_args) or ("--hard" in query_args):
args["difficulty"] = "Hard"
# get query content, any word start with '-' will be ignored
query_content = ""
for arg in query_args:
if arg and arg[0] != '-':
query_content += arg + " "
args["query"] = query_content[:-1]
return args
def is_match(dst, src):
if dst in src:
return True
else:
return False
| true
|
70c91c40394ae59ca2973541bd8a4d73da98b0c3
|
skilstak/code-dot-org-python
|
/mymod.py
| 1,758
| 4.25
| 4
|
"""Example module to contain methods, functions and variables for reuse.
This file gets loaded as a module (sometimes also called a library) when
you call `import mymod` in your scripts.
"""
import codestudio
class Zombie(codestudio.Artist):
"""An Artist with a propensity for brains and drawing squares.
While class definitions look like function definitions they are different.
The parameter inside the parenthesis () is the parent class. This means
all Zombies are Artists and can do everything an Artist can do.
The `start_direction` and `speed` are special variables that goes with
all Zombies. These are called class or static attributes. An attribute
is a variable that goes with a class or the objects created from a class.
"""
start_direction = 90 # facing the east, or right of screen
speed = 'slow' # it is a zombie after all
color = 'green' # it is a zombie after all
def draw_square(self,length):
for count in range(4):
self.move_forward(length)
self.turn_right(90)
def draw_circle(self):
saved_speed = zombie.speed
zombie.speed = 'fastest'
for count in range(360):
zombie.move_forward(1)
zombie.turn_right(1)
zombie.speed = saved_speed
def draw_snowman(self,length):
self.left()
distances = [length * 0.5, length * 0.3, length * 0.2]
for counter in range(6):
distance = distances[counter if counter < 3 else 5 - counter] / 57.5
for degree in range(90):
self.move(distance)
self.right(2)
if counter != 2:
self.left(180)
self.left()
| true
|
9fe708eb8f839f215dc21fdc2296253970e02055
|
lamida/algorithms-drills
|
/others/array_mountain.py
| 930
| 4.25
| 4
|
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
from typing import List
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
i = 1
j = 0
stage = "start" # up then down
while i < len(arr):
j = i- 1
c = arr[i]
b = arr[j]
if b == c:
return False
if c > b and (stage == "start" or stage == "up"):
stage = "up"
i+=1
continue
elif c < b and (stage == "up" or stage=="down"):
stage = "down"
i+=1
continue
else:
return False
return True
if __name__ == "__main__":
s = Solution()
x = s.validMountainArray([0,3,2,1])
print(x)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.