blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eb3fb66e3983c8ea0d131c308cd32b0ed8c30b0c | UnderGrounder96/mastering-python | /02. Built-in Data Structures/4.sets.py | 963 | 4.625 | 5 | # EXAMPLE 1
myset = set();
myset.add(1)
myset.add(2)
myset.add(3)
mylist = [1,2,3,4,5]
myset2 = set(mylist)
# EXAMPLE 2
numbers = [1, 1, 2, 2, 4, 3]
print(numbers)
# converting the list into a set
set_uniques = set(numbers)
print(set_uniques)
# defining a new set
set_new = { 1, 4}
set_new.add(5)
set_new.remove(5)
len(set_new)
print(set_new)
# Sets shine in the Powerful Mathematical Operations that are supported by them
first = set(numbers)
second = {1, 2, 5, 6}
#union
print(first | second)
# intersection - the numbers that exist in both set
print(first & second)
# difference
print(first - second) # the elements that exist in the "first set" and don't exist in the "second set"
print(second - first) # the elements that exist in the "second set" and don't exist in the "first set"
print(first ^ second) # the elements that exist either in the first or second set but not both
# checking for the existance of 1
if 1 in first:
print("yes") | true |
c30c0b73aa515d1541962322d6b33079008d2a66 | Efun/CyberPatriotTutoring | /practice/Archive_8-9_2020/practice_9_27_2020.py | 1,624 | 4.1875 | 4 | from classes.BankAccount import BankAccount
# test = BankAccount('a', 'a', 100)
# print(test.balance)
# write a list of 5 elements containing tennis player names
tennisPlayers = ["serena williams", "roger federer", "rafael nadal", "novak djokovic", "rod laver"]
#print the second element of this list
#print (tennisPlayers[1])
#loops
#for loop will loop through an list like this:
#for varName in listName:
#for each tennis player in the list named tennisPlayers
idx = 0
for tennisPlayer in tennisPlayers:
#print(str(idx) + ".) " + tennisPlayer)
idx += 1
#for loop through numbers
#for varName in range(number)
#i will start at 0
# for x in range(5):
# print(str(x) + ".) " + "hi")
#range(initial_val, max_val, step_size)
#x is set to the initial_val, and then increases by step size until it exceeds the max_val
# for x in range(5, 10, 2):
# print(str(x) + ".) " + "hi")
#print out all tennis players using range instead of in tennisPlayers
#set the variable to be the place in the list where the tennis player is
#how do we get all of the numbers we need?
#x = 0, 1, 2, 3, 4
#tennisPlayers[x]
for x in range(0, 5, 1):
#print(tennisPlayers[x])
#print out every other tennis player starting at serena williams
for x in range(0, 5, 2):
#print(tennisPlayers[x])
#for x in range(5) == for x in range(0, 5, 1)
tennisPlayerA = "Lina"
tennisPlayers.append(tennisPlayerA)
#print(tennisPlayers[5])
userName = input("Type in your username.")
password = input("Type in your passwrord.")
balance = 100
bankAccounts = []
newBankAccount = BankAccount(userName, password, balance)
bankAccounts.append(newBankAccount)
| true |
155359354b2395e4c1b887ad8cb8c9312cb3f0fc | FisicaComputacionalPrimavera2018/ArraysAndVectorOperations | /vectoroperationsUpdated.py | 1,620 | 4.28125 | 4 | import math
#### FUNCTIONS
# The name of the function is "norm"
# Input: array x
# Output: the norm of x
def norm(x):
tmp = 0
for v in x:
tmp += v*v
norm_x = math.sqrt(tmp)
return norm_x
def vectorSum(x, y):
#z = x + y This doesn't work for arrays!
# First we check if the dimensions of x and y
# are the same
if len(x) != len(y):
return "ERROR"
# Now, we know the dimensions are the same
# We create an empty (zeros) vector z, which as the
# same dimensions as x and y
z = [0]*len(x)
# Next step, calculate the components of z
for i in range(0, len(z)):
z[i] = x[i] + y[i]
#z = [ x[0]+y[0], x[1]+y[1], x[2]+y[2] ]
return z # return the sum
def scalarProduct(x, y):
if len(x) != len(y):
return "ERROR"
r = 0
for i in range(0, len(x)):
r = x[i]*y[i]
return r
def angle(x, y):
return math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# Define some three-dimensional vectors
x = [5, 3, 5]
y = [5.5, 6, 8]
z = [2, 0, 6.6]
# norm
print norm(x)
# sum
print vectorSum(x, y)
# scalar product
print scalarProduct(x, y)
# angle (homework)
norm_x = norm(x)
norm_y = norm(y)
n = scalarProduct(x,y)
#print math.acos(n/(norm_x*norm_y))
# shorter way:
#print math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# even shorter
angle1 = angle(x, y)
print angle1
#print angle(x, y)
# convert to degrees
#print math.degrees(angle(x, y))
# angle of vector A between x,y,z axis
A = [5, 6, 11]
alpha_1 = angle(A, [1, 0, 0])
alpha_2 = angle(A, [0, 1, 0])
alpha_3 = angle(A, [0, 0, 1])
print alpha_1, alpha_2, alpha_3
# vector product (homework)
| true |
77d3c7c625dc887ddc8aaa848f0d199fbfa1a06b | JinalShah2002/MLAlgorithms | /LinearRegression/Prof.py | 2,211 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author Jinal Shah
Suppose you are the CEO of a restaurant franchise and are
considering different cities for opening a new outlet.
The chain already has trucks in various cities and you have data for
profits and populations from the cities.You would like to use this data to
help you select which city to expand to next.
This is the Gradient Descent tester. Since I am only looking to test
Gradient Descent and make sure it works, the given problem has already
been determined to be a Linear Regression problem. For future problems,
the user will have to go through the Machine Learning project development
steps!
"""
# Importing the Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from GradientDescent import LinearRegression
from sklearn.model_selection import train_test_split
# Getting the data
PATH = '/Users/jinalshah/SpiderProjects/ML Algorithm Implementations/Data/Profits.csv'
raw_data = pd.read_csv(PATH)
# Splitting the data into X and y
X = raw_data.copy().drop('Profits',axis=1).values
y = raw_data.copy().drop('Population',axis=1).values
"""
Note: Since this class is only for the sole purpose
of testing the Gradient Descent implementation, the
data has already been preprocessed so no preprocessing
is needed
However, for future data sets, you will need to
preprocess the data. If needed, you will need to
apply feature scaling because gradient descent
doesn't do it for you!
"""
# Plotting the data for insights
plt.scatter(X,y,c='Red')
plt.xlabel('Population')
plt.ylabel('Profits')
plt.title('Profits v.s Population')
plt.show()
# Splitting the Data into training and testing
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)
# Building the Linear Regression model
regressor = LinearRegression()
regressor.fit(X_train,y_train)
# Predicting the testing set
y_pred = regressor.predict(X_test)
# Plotting the final hypothesis
plt.scatter(X_train,y_train,c='red')
plt.plot(X_train,regressor.predict(X_train),c='blue')
plt.title('Profits v.s Population')
plt.xlabel('Population')
plt.ylabel('Profits')
plt.show()
# Plotting the Cost Function
regressor.plot()
| true |
751f1777faad91870b7079238aa8d840848021b7 | prabhatpal77/Complete-core-python- | /typeconversion.py | 390 | 4.125 | 4 | #Type conversion function converse the data in the form of required format in the data is possible to convert..
a=input("enter int value")
print(type(a))
b=int(a)
print(type(b))
c=input("enter float value")
print(type(c))
d=float(c)
print(type(d))
i=input("enter complex value")
print(type(i))
j=complex(i)
print(type(j))
p=input("enter bool value")
print(type(p))
q=bool(p)
print(type(q))
| true |
0f5463149ed49570c867f233e6dbc145da9104d6 | prabhatpal77/Complete-core-python- | /identityope.py | 470 | 4.125 | 4 | #Identity operators are used to compare the addresses of the objects which are pointed by the operators ..
#there are 2 identity operators.
# 1. is 2. is not
a=1000
b=2000
c=3000
d=3000
p=[10, 20, 30]
q=[40, 50, 60]
x=[70, 80, 90]
y=[70, 80, 90]
print(a==b)
print(a!=b)
print(a is b)
print(a is not b)
print(c==d)
print(c!=d)
print(c is d)
print(c is not d)
print(p==q)
print(p!=q)
print(p is q)
print(p is not q)
print(x==y)
print(x!=y)
print(x is y)
print(x is not y)
| true |
94492c43f4f858d9e46e6484a4faf4cb1585d487 | prabhatpal77/Complete-core-python- | /filehandl.py | 323 | 4.4375 | 4 | # Through the python program we can open the file, perform the operations on the file and we can close the file..
# 'r', 'w', 'a', 't', 'b', '+' for operations on file
# Open function opens the given file into the specified mode and crete file object..
# reading from file...
x=open("myfile.txt")
print(x.read())
x.close()
| true |
cf89d81fa5fa2fc86a2770f9cf42954ffa049599 | suzibrix/lpthw | /ex4.py | 1,660 | 4.21875 | 4 | # This line assigns 100 to the variable "cars"
cars = 100
# This statement assigns the number "4.0" to the variable "space_in_car"
space_in_a_car = 4.0
# Assigns the number 30 to the variable "drivers"
drivers = 30
# Assigns the number 90 to the variable "passengers"
passengers = 90
# Assigns the difference of variable "cars" and "drivers" to "cars_not_driven"
cars_not_driven = cars - drivers
# Assigns the number stored in "drivers" to the variable "cars_driven"
cars_driven = drivers
# Assigns the multiple of "cars_driven" and "space_in_car" to "carpool_capacity"
carpool_capacity = cars_driven * space_in_a_car
# Assigns the dividend of the total of "passengers" and "cars_driven"
average_passengers_per_car = passengers / cars_driven
#
# Let's show our work
#
# Insert variable $cars into printable string revealing # of cars
print("There are", cars, "cars available.")
# Insert the variable $drivers into printable string displaying number of drivers
print("There are only", drivers, "drivers available.")
# Insert $cars_not_driven into printable string demonstrating number of unused vehicles
print("There will be", cars_not_driven, "empty cars today.")
# Insert variable $carpool_capacity into the number of people that can be driven today
print("We can transport", carpool_capacity, "people today.")
# Insert variable $passengers into the string printing how many passengers are in need of transportation
print("We have", passengers, "to carpool today.")
# Insert the variable of $average_passengers_per_car into a string printing the number of people per car
print("We need to put about", average_passengers_per_car, "in each car.")
| true |
8d33594f74c58174b463aba1f3b365e4ef01fd5e | micgainey/Towers-of-Hanoi | /towers_of_hanoi_count.py | 1,979 | 4.15625 | 4 | """
Towers of Hanoi rules
1. You can't place a larger disk onto a smaller disk.
2. Only 1 disk can be moved at a time.
Towers of Hanoi moves is:
2^n - 1
OR
2 * previous + 1
example with 3 disks
3 towers: A. B. C.
Starting point:
1
2
3
A B C
Move1
2
3 1
A B C
Move2
3 2 1
A B C
Move3
1
3 2
A B C
Move4
1
2 3
A B C
Move5
1 2 3
A B C
Move6
2
1 3
A B C
Move7
1
2
3
A B C
"""
"""
Iterative approach:
for one disk it will take 1 move
for two disks minimum number of moves is 3
...
n - 1 disks = p
2p + 1 = minimum number of moves for n disks
number of disks minimum number of moves
1 1
2 3
3 (2 * 3) + 1 = 7
4 (2 * 7) + 1 = 15
5 (2 * 15) + 1 = 31
6 (2 * 31) + 1 = 63
7 (2 * 63) + 1 = 127
8 (2 * 127) + 1 = 255
9 (2 * 255) + 1 = 511
n - 1 p
n 2p + 1
"""
# This function will return the minimum number of moves it will take to solve TOH with n disks
def towers_of_hanoi_moves(disks):
if disks <= 0:
print('Number of disks must be greater than 0')
return
num_of_moves = 0
for i in range(0, disks):
num_of_moves = (2 * num_of_moves) + 1
# Uncomment below to see the number of moves for each disk
# print(num_of_moves)
return num_of_moves
# print(towers_of_hanoi_moves(9))
num_of_moves = int(input("Enter the number of disks: "))
print(towers_of_hanoi_moves(num_of_moves))
| true |
a5305f23d0038814f95207a3dba6199913518cbd | thewchan/impractical_python | /ch4/storing_route_cipher_key.py | 1,387 | 4.25 | 4 | """
Pseudo-code:
ask for number of length of key
initiate defaultdict
for count in length of key
ask for column number store as temp1
ask for direction store as temp2
defaultdict[temp1] = temp2
"""
from collections import defaultdict
while True:
key_len = input("Enter length of key: ")
try:
key_len = int(key_len)
except ValueError:
print("Please enter a number.")
continue
break
key_stored = defaultdict(int)
for column in range(key_len):
while True:
column_num = input(f"Enter column number for position {column + 1}: ")
try:
column_num = int(column_num)
except ValueError:
print("Please enter a number.")
continue
if (column_num > 0 and column_num <= key_len):
break
else:
print("Please enter a valid column number.")
continue
while True:
direction = input(
f"Enter direction of position {column + 1} (up/down): "
)
if direction.lower() == 'up':
direction = -1
break
elif direction.lower() == 'down':
direction = 1
break
else:
print("Please enter a valid direction (up/down).")
continue
key_stored[column_num] = direction
print("The key you have entered is:\n ", key_stored)
| true |
6a1716818b21e765ba02e275553467a060c21269 | Kids-Hack-Labs/Fall2020 | /Activities/Week02/Code/activity1_suggested_solution.py | 737 | 4.125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 02: Python Review
Activity 1
"""
#Step 1: Function that takes 2 arguments and displays greater
def greater(num_a, num_b):
if num_a > num_b:
print(num_a, "is greater than", num_b)
else:
print(num_b, "is greater than", num_a)
#step 2: Inputs from user (cast to integer) stored in variables
first = int(input("First number, please: "))
second = int(input("Second number, please: "))
#step 3: Calling function defined in step 1
greater(first, second)
"""
Obs.: Inputs were cast to integers for comparison.
The implementation does not account for
equal numbers. The student is free to improve
the code in that regard.
"""
| true |
1c7b497ffce28f0a1f2faa790eca25693b2814c1 | Kids-Hack-Labs/Fall2020 | /Activities/Week04/Code/act2.py | 1,116 | 4.3125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 04: Introduction to Classes
Activity 2
"""
#Suggested answer:
class Animal():
def __init__(self, _type, _name, _legs, _sound):
self.type = _type
self.name = _name
self.legs = int(_legs)
self.sound = _sound
def walk(self):
for i in range(self.legs):
print("step", end= " ")
def make_sound(self):
print(self.sound)
def get_name(self):
print("The "+self.type+"'s name is: "+self.name+".")
"""
The following twelve lines should be input in the shell,
once the current module is run. The names and data in the
animals are simply suggestions, and serve to test the
class's functions under different initial parameters
puppy = Animal("dog", "Hacky", 4, "woof!")
puppy.walk()
puppy.make_sound()
puppy.get_name()
kitty = Animal("cat", "Nimbus", 4, "meow!")
kitty.walk()
kitty.make_sound()
kitty.get_name()
flappy = Animal("duck", "Chamille", 2, "Quack!")
flappy.walk()
flappy.make_sound()
flappy.get_name()
"""
| true |
c58359a746beaaa275045aafa9d1509b028a2760 | Kids-Hack-Labs/Fall2020 | /Homework/W02/Code/w02_hw_suggested_solution.py | 1,213 | 4.125 | 4 | """
Kids Hack Labs
Fall 2020 - Senior
Week 02: Python Review
Homework: Number guessing game
"""
#Step 1: random module import
import random
#Step 2: application main entry point
def main():
#setup (steps 2.1 through 2.5)
random.seed()
tries = 5 #total tries granted
guesses = 0 #total guesses made
player_won = False
target = random.randint(1, 63)
#game loop(step 2.6 and sub-steps)
while guesses < tries and not player_won:
player_guess = int(input("Guess a number: "))
guesses += 1
if player_guess == target:
player_won = True
else:
if player_guess < target:
print("You guessed lower than the secret number.")
else:
print("you guessed higher than the secret number.")
#Game end: Steps 2.7 and 2.8
if player_won:
print("You won the game in",guesses,"tries!")
else:
print("You lost the game... The secret number was",target)
if __name__ == "__main__":
main()
"""
Obs.: Students are encouraged to experiment with the code and try
other techniques to generate the numbers or streamline the outputs
to the user.
"""
| true |
5eb8e0b24c3f32f17ec1d13c07aee382aeef9a39 | himajasricherukuri/python | /src/listfunctions.py | 1,949 | 4.21875 | 4 | lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.extend(lucky_numbers)
print(friends)
# extend function allows you take a list and append it on another list
#append- adding individual elements
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.append("creed")
print(friends)
#insert - inserts the element at the given index, shifting elements to the right.
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.insert(1,"kelly")
print(friends)
#remove - searches for the first instance of the given element and removes it
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.remove("jim")
print(friends)
#clear - gives an empty list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.clear()
print(friends)
#pop- pops /remobves last element in the list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.pop()
print(friends)
#index- searches for the given element from the start of the list and returns its index.
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
print(friends.index("kevin"))
#count the number of similar elements
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby","kevin"]
print(friends.count("kevin"))
#sort - sort the list in ascending order
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.sort()
lucky_numbers.sort()
print(lucky_numbers)
print(friends)
# reverse a list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends.reverse()
print(friends)
# copy -used to copy attributes from another list
lucky_numbers = [4,8,15,16,23,42]
friends = ["kevin","karen","jim","oscar","toby"]
friends2 = friends.copy()
print(friends2)
| true |
b33bd9fe0dffcc22d3f657b10d11d1aff016b5b1 | yourpalfranc/tstp | /14challenge-2.py | 671 | 4.21875 | 4 | ##Change the Square class so that when you print a square object, a message prints telling you the
##len of each of the four sides of the shape. For example, if you ceate a square with Square(29)
##and print it, Python should print 29 by 29 by 29 by 29.
class Square():
square_list = []
def __init__(self, sides):
self.side_length = sides
self.square_list.append(self.side_length)
def print_sides(self):
print(self.side_length, " by ", self.side_length, " by ", self.side_length, " by ", self.side_length)
s1 = Square(29)
s2 = Square(30)
s3 = Square(40)
s4 = Square(50)
##print(s1.side_length)
s1.print_sides() | true |
e489a9c6d7e662cd125a74b2f014614bdc861a9f | yourpalfranc/tstp | /13challenge-2.py | 937 | 4.1875 | 4 | ##Define a method in your Square class called change_size that allows you to pass in a number
##that increases or decreases (if the number is negative) each side of a Square object by that
##number.
class Rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
print("Object Created")
def calculate_perimeter(self):
return (self.width + self.length)*2
class Square(Rectangle):
def change_size(self, newnum):
if newnum >= 0:
print("New Square perimeter: ", my_square.calculate_perimeter() + (newnum * 4))
else:
print("New Square perimeter: ", my_square.calculate_perimeter() + (newnum * 4))
my_rectangle = Rectangle(24, 30)
my_square = Square(10, 10)
print("Rectangle perimeter: ", my_rectangle.calculate_perimeter())
print("Square perimeter: ", my_square.calculate_perimeter())
my_square.change_size(2)
| true |
1cdbf36cf05b93addd8e5797b82747e5448462f8 | druv022/Disease-Normalization-with-Graph-Embeddings | /nerds/util/file.py | 1,216 | 4.21875 | 4 | import shutil
from pathlib import Path
def mkdir(directory, parents=True):
""" Makes a directory after checking whether it already exists.
Parameters:
directory (str | Path): The name of the directory to be created.
parents (boolean): If True, then parent directories are created as well
"""
path_dir = Path(directory)
if not path_dir.exists():
path_dir.mkdir(parents=parents)
def rmdir(directory, recursive=False):
""" Removes an empty directory after checking whether it already exists.
Parameters:
directory (str | Path): The name of the directory to be removed.
recursive (boolean): If True, then the contents are removed (including subdirectories and files),
otherwise, the directory is removed only if it is empty
"""
path_dir = Path(directory)
if not path_dir.exists():
return
if recursive:
shutil.rmtree(path_dir)
else:
if len(list(path_dir.iterdir())) == 0:
path_dir.rmdir()
else:
raise ValueError(
"Cannot remove directory '{}' as it is not empty: consider removing it recursively".format(path_dir))
| true |
e5b94f0ba5cadbd496e8bf15318db7ae8f4d31cf | Abhiram-Agina/PythonProjects_Algebra | /CHAPTER10_ExponentsProperties.py | 1,776 | 4.25 | 4 | # Type in an Expression that includes exponents and I will give you an Answer
# Negative Exponents: Work in progress
SEEquations = input(" Type in a simple expression using exponents, 1 operator, and the same constant (i.e. 3^2 * 3^6) \n ")
terms2 = SEEquations.split(" ")
ExponentTerms = []
for item in terms2:
if '^' in item:
ExponentTerms.append(item)
print(ExponentTerms)
lhs1, rhs1 = ExponentTerms[0].split('^')
lhs2, rhs2 = ExponentTerms[1].split('^')
ExpoNum = int(int(rhs1) + int(rhs2))
counter = 1
sumNum = (int(lhs1) * int(lhs1))
print(" your answer is: ... \n")
if('*' in str(SEEquations)):
print(str(lhs1) + "^" + str(ExpoNum))
while(counter < ExpoNum-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
print("= " + str(sumNum))
if('/' in str(SEEquations)):
print(str(lhs1) + "^" + str(int(int(rhs1) - int(rhs2))))
while((counter < int(int(rhs1) - int(rhs2)))-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
print("= " + str(sumNum))
Ans1 = 0
Ans2 = 0
if('+' in str(SEEquations)):
while(counter < int(rhs1)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans1 = sumNum
sumNum = (int(lhs1) * int(lhs1))
counter = 1
while(counter < int(rhs2)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans2 = sumNum
print("= " + str(int(Ans1 + Ans2)))
if('-' in str(SEEquations)):
while(counter < int(rhs1)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans1 = sumNum
sumNum = (int(lhs1) * int(lhs1))
counter = 1
while(counter < int(rhs2)-1):
sumNum = sumNum * int(lhs1)
counter = counter + 1
Ans2 = sumNum
print("= " + str(int(Ans1 - Ans2))) | true |
9e25339de670199da3cab9de8a98cc88c58cb5ca | jansenhillis/Python | /A004-python-functionsBasic2/functionsBasic2.py | 2,414 | 4.40625 | 4 | # 1. Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one,
# from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(seed):
seedList = []
for i in range(seed, -1, -1):
seedList.append(i)
return seedList
# print(downList(10))
# 2. Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
def print_and_return(lst):
print(lst[0])
return(lst[1])
# print(print_and_return([1,2]))
# 3. First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(lst):
return lst[0] + len(lst)
# print(first_plus_length([1,2,3,4,5]))
# 4. Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values
# from the original list that are greater than its 2nd value. Print how many values this is and then return the new list.
# If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
def values_greater_than_second(lst):
if len(lst) < 2:
return False
shortList = []
secondVal = lst[1]
for item in lst:
if item > secondVal:
shortList.append(item)
print(len(shortList))
return shortList
# print (values_greater_than_second([5, 2, 3, 2, 1, 4]))
# print (values_greater_than_second([5]))
# print (values_greater_than_second([5, 2]))
# 5. This Length, That Value - Write a function that accepts two integers as parameters: size and value.
# The function should create and return a list whose length is equal to the given size, and
# whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def length_and_value(size, value):
newList = []
for i in range(size):
newList.append(value)
return newList
# print(length_and_value(4, 7))
# print(length_and_value(6, 2)) | true |
2e129574ad41492e099ab2181717ed8aeb79fb1f | simoonsaiyed/CS303 | /Payroll.py | 1,620 | 4.15625 | 4 | # Assignment 3: Payroll.py
# A program that prints out the Payroll dependent on inputs.
def calculate(worked, pay, fedtax, statetax):
worked = float(worked)
gross = worked * pay
fedwitholding = fedtax * gross
statewitholding = statetax * gross
total = statewitholding + fedwitholding
return worked, gross, fedwitholding, statewitholding, total
def main():
# enter inputs
name = input("Enter employee ’s name : ")
hours_worked = int(input("Enter number of hours worked in a week : "))
hourly_pay = float(input("Enter hourly pay rate : "))
federal_tax = float(input("Enter federal tax withholding rate : "))
fedtax = str(float(federal_tax * 100)) + '%'
state_tax = float(input("Enter state tax withholding rate : "))
sttax = str(float(state_tax * 100)) + '%'
worked, gross, fedwitholding, statewitholding, total = calculate(hours_worked, hourly_pay, federal_tax, state_tax)
# print the final statements
print("Employee Name :", name)
print("Hours Worked :", worked)
print("Pay Rate : $" + str(hourly_pay))
print("Gross Pay : $" + str(gross))
print("Deductions:")
fedwitholding = "{:.2f}".format(fedwitholding)
print(" Federal Withholding " + '(' + fedtax + ')' + ': $' + str(fedwitholding))
statewitholding = "{:.2f}".format(statewitholding)
print(" State Withholding " + '(' + sttax + ')' + ': $' + str(statewitholding))
totall = "{:.2f}".format(total)
print(" Total Deductions: $" + str(totall))
netpay = gross - total
netpay = "{:.2f}".format(netpay)
print("Net Pay: $" + str(netpay))
main()
| true |
7b683b972accd14c161f79cb23a585863a9ab556 | rubayetalamnse/Basic-Python-Codes | /string-finction.py | 1,224 | 4.5625 | 5 | print(len("rubayet"))
#string functions------->>>>
passage = "nuclear energy provide zero carbon electricity, most reliable and cheap one. This energy is better than renewable energy! If we talk about wind power or solar or hydro, nuclear takes lowest place and produces maximum energy. And obviously we should come out of oil/gas/coal powered energy sources and their applications"
#len is used to count all the string characters
print(len(passage))
#endswith is used to verify the last word or last character in a string/passage/word/line
print(passage.endswith("applications"))
print(passage.endswith("rubayet"))
print(passage.endswith("e"))
#lets find out how many e or any other characters/words are there in the passage
print(passage.count("e"))
print(passage.count("energy"))
#lets captialize energy in the passage
print(passage.capitalize())
#lets find any word from the given passage, we will find the word "carbon"
print(passage.find("carbon")) # 4 will come as answer
#here indexing starts from 0, so nuclear-->0, energy-->1,provides-->2,zero-->3, carbon-->4
#lets replace the word "provide" with "produce"
print(passage.replace("provide", "produce"))
print("Nuclear is good.\n it \tis best for \\ all.") | true |
eeb24838ff1e76e6e73c80e79741e364e5716782 | rubayetalamnse/Basic-Python-Codes | /geeks-1.py | 353 | 4.15625 | 4 | #printing sum of two numbers
num1 = 10
num2 = 45
sum = num1+num2
print("Sum of {0} and {1} is : {2}".format(num1,num2,sum))
#printing sum of two decimal or float numbers
no1 = input("enter any decimal Number: ")
no2 = input("enter another decimal number: ")
sum2 = float(no1)+float(no2)
print("The sum of {0} and {1} is: {2} ".format(no1,no2,sum2)) | true |
8467ad15dcfeb454383e1ef26143328ccca9ec7d | rubayetalamnse/Basic-Python-Codes | /functions11.py | 2,640 | 4.40625 | 4 | """You're planning a vacation, and you need to decide which city you want to visit. You have shortlisted four cities and identified the return flight cost, daily hotel cost, and weekly car rental cost. While renting a car, you need to pay for entire weeks, even if you return the car sooner.
City Return Flight ($) Hotel per day ($) Weekly Car Rental ($)
Paris 200 20 200
London 250 30 120
Dubai 370 15 80
Mumbai 450 10 70
Answer the following questions using the data above:
1.If you're planning a 1-week long trip, which city should you visit to spend the least amount of money?
2.How does the answer to the previous question change if you change the trip's duration to four days, ten days or two weeks?
3.If your total budget for the trip is $1000, which city should you visit to maximize the duration of your trip? Which city should you visit if you want to minimize the duration?
4.How does the answer to the previous question change if your budget is $600, $2000, or $1500?
Hint: To answer these questions, it will help to define a function cost_of_trip with relevant inputs like flight cost, hotel rate, car rental rate, and duration of the trip. You may find the math.ceil function useful for calculating the total cost of car rental."""
#solve-3----
import math
paris_f,paris_h,paris_c = 200,20,200
london_f,london_h,london_c =250,30,120
dubai_f,dubai_h,dubai_c =370,15,80
mumbai_f,mumbai_h,mumbai_c = 450,10,70
def vacation_cost_trip(flight_cost, hotel_rate,car_rental):
total_cost = flight_cost + hotel_rate + car_rental
return math.ceil(total_cost)
#for 16 days----------------------------------------------------------------
paris_trip = vacation_cost_trip(paris_f,paris_h*16,paris_c*(16/7))
print("to make a 16 days vacation plan in paris, you need to have",paris_trip,"dollars!")
london_trip_expensive = vacation_cost_trip(london_f,london_h*15,london_c*(15/7))
print("to make a 15 days vacation plan in London, you need to have",london_trip_expensive,"dollars!")
dubai_trip = vacation_cost_trip(dubai_f,dubai_h*16,dubai_c*(16/7))
print("to make a 16 days vacation plan in DUBAI, you need to have",dubai_trip,"dollars!")
mumbai_trip = vacation_cost_trip(mumbai_f,mumbai_h*16,mumbai_c*(16/7))
print("to make a 16 days vacation plan in mumbai, you need to have",mumbai_trip,"dollars!")
mumbai_trip_cheap = vacation_cost_trip(mumbai_f,mumbai_h*27,mumbai_c*(27/7))
print("to make 27days vacation plan in mumbai, you need to have",mumbai_trip_cheap,"dollars!")
| true |
933857731a1e75f757c5f57ef7913ca5585b0f7e | rubayetalamnse/Basic-Python-Codes | /celsius-farenheit.py | 598 | 4.3125 | 4 | #Write a Python program to convert temperatures to and from celsius, fahrenheit.
temperature = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temperature[0:-1])
temp = temperature[-1]
if temp.upper() == "F":
celsius_temp = float((degree - 32) * 5/9 )
print("The temperature -", temperature, "in celsius is", celsius_temp, "degrees.")
elif temp.upper() == "C":
farenheit_temp = float((9 * degree) / 5 + 32)
print("The temperature -", temperature, "in celsius is", farenheit_temp, "degrees.")
else:
print("Input proper temperature.") | true |
94529887c259ec0c647cf90102487626a0b36fd5 | rubayetalamnse/Basic-Python-Codes | /for-break.py | 241 | 4.1875 | 4 | for i in range(5,20):
print(i)
if i==10:
break
#when i ==10, the loop ends. We see values from 5 to 10 in the terminal.
else:
print("as we used break at 10, 5 to 10 is printed. after that this else loop won't be printed") | true |
622019a68abba6e0c1d31bdec0ad3c2d7778809a | rubayetalamnse/Basic-Python-Codes | /functions6.py | 1,310 | 4.15625 | 4 | #If you borrow $100,000 using a 10-year loan with an interest rate of 9% per annum, what is the total amount you end up paying as interest?
import math
#for loan emi------------------------
loan = 100000
loan_duration = 10*12 #10 years
interest_rate = .09/12 #compounded monthly
#reusing our previous function to calculate emi---------
def loan_emi_interest(amount,duration,interest,down_payment):
loan_amount = amount-down_payment
try:
emi_interest = (loan_amount * interest * ((1+interest) ** duration)) /(((1+interest) **duration)-1)
except ZeroDivisionError:
emi_interest = loan_amount/duration
return math.ceil(emi_interest)
#calling our function to calculate emi with interest------------
emi_with_interest =loan_emi_interest(amount = loan, duration =loan_duration, interest=interest_rate, down_payment=0)
print("EMI WITH Interest:",emi_with_interest)
#calling our function to calculate emi without interest------------
emi_without_interest =loan_emi_interest(amount = loan, duration =loan_duration, interest=0, down_payment=0)
print("EMI without Interest:",emi_without_interest)
#total interest-------
total_interest = emi_with_interest - emi_without_interest
print("total interest per month:",total_interest)
print("total interest for 10 year:",total_interest*120) | true |
c81b693f9dcca328b6d547ed885ed5403a266cbf | rubayetalamnse/Basic-Python-Codes | /q4b.py | 845 | 4.125 | 4 | #Use a for loop to display the type of each value stored against each key in person
person = {
"Name":"Rubayet",
"Age": 21,
"HasAndroidPhone": True
}
for i in range(len(person)):
print(type(person.keys()))
print(type(person.values()))
for value in person:
print(type(value))
for key in person:
print(type(key))
#worked----------------------------------------------------------------
for j in person.values():
print(type(j))
my_list = ["blue","yellow","green","white",1,True]
my_list.append(30)
print(my_list)
print('My favorite color is', my_list[1])
print('I have {} pet(s).'.format(my_list[4]))
if my_list[5]==True:
print("I have previous programming experience")
else:
print("I do not have previous programming experience")
my_list.pop(0)
print("The list has {} elements.".format(len(my_list)))
| true |
59a8c9b981bb0203fae5aabe709451ef4706a7c5 | edpretend/learn_python | /defs/def_txt.py | 1,264 | 4.34375 | 4 | """文本处理函数库"""
def watch_txt(filename):
"""watch txt and read"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
print(contents)
def word_time(filename):
"""read one word of all time"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about" + str(num_words) +
" words.")
def one_word_time(filename, word):
"""read one word of all time"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
word_time = contents.lower().count(str(word))
print("The word '" + str(word) + "' in the file '" + filename + "' has about " +
str(word_time) + " time.") | true |
86e7af0c89f72ae192f7c2e6936f7cbb28c47068 | Joyce-w/Python-practice | /09_is_palindrome/is_palindrome.py | 752 | 4.1875 | 4 | def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capitalization/spaces when deciding:
>>> is_palindrome('taco cat')
True
>>> is_palindrome('Noon')
True
"""
lowercase = phrase.lower().replace(' ', '')
lowercase_lst = list(lowercase)
reverse = list(lowercase)
reverse.reverse()
for idx in range(len(lowercase_lst)):
if lowercase[idx] != reverse[idx]:
return False
else:
return True
| true |
a53af1d873b2238aa568577ae9ebd48bd7d8a846 | rgederin/python-sandbox | /python-code/src/collections/set.py | 2,859 | 4.46875 | 4 | x = {'foo', 'bar', 'baz', 'foo', 'qux', 'bar'}
print(type(x))
print(x)
x = set(['foo', 'bar', 'baz', 'foo', 'qux'])
print(type(x))
print(x)
x = set(('foo', 'bar', 'baz', 'foo', 'qux'))
print(type(x))
print(x)
_str = "quux"
print(list(_str))
print(set(_str))
# A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty dictionary,
# so the only way to define an empty set is with the set() function
x = set()
print(type(x))
print(x)
x = {}
print(type(x))
print(x)
# You might think the most intuitive sets would contain similar objects—for example, even numbers or surnames:
s1 = {2, 4, 6, 8, 10}
s2 = {'Smith', 'McArthur', 'Wilson', 'Johansson'}
# Python does not require this, though. The elements in a set can be objects of different types:
x = {42, 'foo', 3.14159, None}
print(x)
# Don’t forget that set elements must be immutable. For example, a tuple may be included in a set:
x = {42, 'foo', (1, 2, 3), 3.14159}
print(x)
# The len() function returns the number of elements in a set, and the in and not in operators can be used to test for
# membership:
x = {'foo', 'bar', 'baz'}
print(len(x))
print('bar' in x)
print('qux' in x)
## Operating on a Set
# Given two sets, x1 and x2, the union of x1 and x2 is a set consisting of all elements in either set.
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print(x1 | x2)
# Set union can also be obtained with the .union() method. The method is invoked on one of the sets, and the other is
# passed as an argument:
print(x1.union(x2))
# The way they are used in the examples above, the operator and method behave identically. But there is a subtle
# difference between them. When you use the | operator, both operands must be sets. The .union() method, on the other
# hand, will take any iterable as an argument, convert it to a set, and then perform the union.
y = x1.union(('baz', 'qux', 'quux'))
print(y)
# Below is a list of the set operations available in Python. Some are performed by operator, some by method,
# and some by both. The principle outlined above generally applies: where a set is expected, methods will typically
# accept any iterable as an argument, but operators require actual sets as operands.
# x1.intersection(x2[, x3 ...])
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print(x1.intersection(x2))
print(x1 & x2)
# x1.difference(x2[, x3 ...])
print(x1.difference(x2))
print(x1 - x2)
# Modifying a Set
# Although the elements contained in a set must be of immutable type, sets themselves can be modified. Like the
# operations above, there are a mix of operators and methods that can be used to change the contents of a set.
x1 = {'foo', 'bar', 'baz'}
x2 = {'foo', 'baz', 'qux'}
x1 |= x2
print(x1)
x1.update(['corge', 'garply'])
print(x1)
x = {'foo', 'bar', 'baz'}
x.add('qux')
print(x) | true |
113acba3954da223bf206b2f3c61df537db7f878 | syedareehaquasar/Python_Interview_prepration | /Hashing_Questions/is_disjoint.py | 982 | 4.21875 | 4 | Problem Statement
You have to implement the bool isDisjoint(int* arr1, int* arr2, int size1, int size2) function, which checks whether two given arrays are disjoint or not.
Two arrays are disjoint if there are no common elements between them. The assumption is that there are no duplicate elements in each array.
Input
Two arrays of integers and their lengths.
Output
It returns true if the two arrays are disjoint. Otherwise, it returns false.
arr_one = [4,5,6,9,8]
arr_two = [0,3]
def is_subset(arr_one, arr_two):
len_one = len(arr_one)
len_two = len(arr_two)
arr_one_hash = {}
for value in arr_one:
arr_one_hash[ value ] = 1
#print( arr_one, arr_two, arr_one_hash)
'''for value in arr_two:
if not arr_one_hash.get(value):
return True'''
if not any( arr_one_hash.get( value) for value in arr_two ): return True
else: return False
print ( is_subset(arr_one, arr_two))
| true |
f4b23e71cb3395d3f90a8f823407ddea41724000 | shreyasandal05/HelloWorld | /utils.py | 203 | 4.1875 | 4 | def find_max(numbers):
"""This prints maximum number within a list"""
maximum = numbers[0]
for number in numbers:
if maximum < number:
maximum = number
print(maximum)
| true |
21334ff4ca556f71bdba054c54693575d5d94bfc | Yesid4Code/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,921 | 4.5625 | 5 | #!/usr/bin/python3
""" A Square class definition """
class Square:
""" Initialization of the class """
def __init__(self, size=0, position=(0, 0)):
""" Initialization of the class """
self.size = size
self.position = position
def area(self):
""" Calculate the square's area """
return self.__size ** 2
@property
def size(self):
""" The size of the square """
return self.__size
@size.setter
def size(self, value):
""" Set the size of the square and check if it's >= 0 """
if type(value) is not int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
@property
def position(self):
""" The position of the Square """
return self.__position
@position.setter
def position(self, value):
"""setter of __position
Args:
value (tuple): position of the square in 2D space
Returns:
None
"""
if type(value) is not tuple:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif len(value) != 2:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif type(value[0]) is not int or type(value[1]) is not int:
raise TypeError("position must be a\
tuple of 2 positive integers")
elif value[0] < 0 or value[1] < 0:
raise TypeError("position must be a\
tuple of 2 positive integers")
else:
raise TypeError("position must be a\
tuple of 2 positive integers")
# if type(value) != tuple or len(value) != 2 or \
# type(value[0]) != int or value[0] < 0 or \
# type(value[1]) != int or value[1] < 0:
# raise TypeError("position must be a\
# tuple of 2 positive integers")
# else:
# self.__position = value
def my_print(self):
""" prints in stdout the square with the character # """
if self.__size > 0:
print("\n" * self.__position[1], end="")
for i in range(self.__size):
print(" " * self.__position[0], end="")
print("#" * self.__size)
else:
print()
| true |
168d8066d57bbf9e622187a32f93bd123531092d | AJKemps/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,320 | 4.3125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(left, right):
# elements = len(left) + len(right)
# merged_arr = [0] * elements
merged_arr = []
# Your code here
left_point = right_point = 0
while left_point < len(left) and right_point < len(right):
if left[left_point] < right[right_point]:
merged_arr.append(left[left_point])
left_point += 1
else:
merged_arr.append(right[right_point])
right_point += 1
merged_arr.extend(left[left_point:])
merged_arr.extend(right[right_point:])
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
if len(arr) <= 1:
return arr
midpoint = len(arr) // 2
left, right = merge_sort(arr[:midpoint]), merge_sort(arr[midpoint:])
return merge(left, right)
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
pass
def merge_sort_in_place(arr, l, r):
# Your code here
pass
| true |
5e653857300e785e7c2755977af5951cbd0bc909 | HeyMikeMarshall/GWARL-Data | /03-Python/2/Activities/01-Stu_QuickCheckup/Solved/quick_check_up.py | 483 | 4.15625 | 4 | # Print Hello User!
print("Hello User!")
# Take in User Input
hru = input("How are you doing today?")
# Respond Back with User Input
print(f"I am glad to hear you are {hru}.")
# Take in the User Age
age = int(input("If you don't mind my asking, how old are you?"))
# Respond Back with a statement based on age
if (age > 50):
print("dang, you're old!")
elif (age < 5):
print("are you allowed to be using the computer?")
else: print(f"Ah, {age}, a good age to be.")
| true |
d8e26246147eeb15860e2946038dea1519814e13 | truongpt/warm_up | /practice/python/study/linked_list.py | 1,004 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, pre_node, data):
if not pre_node:
print("Previous node is not existence")
return
new_node = Node(data)
new_node.next = pre_node.next
pre_node.next = new_node
def print(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
| true |
837417ff10a136800d60313bca2657459e48b71b | sailskisurf23/sidepeices | /prime.py | 556 | 4.28125 | 4 | #Ask user for Inputs
userinput1 = int(input("This program determines primality. Enter an integer greater than 0: "))
#Define function that returns divisors of a number
def divisor(number):
divisors = []
for x in range(1, (number+1)):
if number % x == 0:
divisors.append(x)
return divisors
#apply divisor function to userinput1
divlist = divisor(userinput1)
#Print primality of userinput1
if len(divlist) <= 2 :
print(str(userinput1) + " is a prime number")
else:
print(str(userinput1) + " is NOT a prime number")
| true |
bf34ef2231cd514deb40a267976b5b7ede184893 | sailskisurf23/sidepeices | /factorial.py | 337 | 4.21875 | 4 | uservar = int(input("Enter an integer you would like to factorialize: "))
def factorialize(var1):
"""Returns the factorial of var1"""
counter = 1
result = 1
while counter <= var1:
result = result * counter
counter = counter + 1
return result
print(str(uservar) +"! = " + str(factorialize(uservar)))
| true |
5e30f36955b95279a0e0c9cded56c35cf7d67184 | sailskisurf23/sidepeices | /dice.py | 2,879 | 4.34375 | 4 | #1. Write a function that rolls two sets of dice to model players playing a game with dice.
#It will accept two arguments, the number of dice to roll for the first player, and the number of dice to roll
#for the second player. Then, the function will do the following:
#* Model rolling the appropriate number of dice for each player.
#* Sum the total values of the corresponding dice rolls.
#* Print which player rolled the higher total.
#* Return the total sum of each players rolls in a tuple.
#Add functionality to Game
#Adjust game for any number of players
#Ask user how many players there are
#For each player ask how many rolls they get and then print each roll along with their sum
#After last player, print winner(s)
#Ask user if they want to play again
import random
import sys
def rolls_result(numrolls):
'''Roll a 6 sided die 'numrolls' times, returns sum of rolls and list of results'''
sumrolls = 0
result_list = []
for i in range(numrolls):
result = random.randint(1,6)
sumrolls += result
result_list.append(result)
return sumrolls, result_list
def dice(playerscores):
'''Input the score for each player, return list of winner(s)'''
maxscore = max(playerscores)
winnerlist = []
for i in range(len(playerscores)):
if playerscores[i] == maxscore:
winnerlist.append(f"Player{i+1}")
return winnerlist
def winnerstring(winnerlist):
'''Input the list of winners, return a string exclaiming the winner1(s)'''
if len(winnerlist) == 1:
return f"{winnerlist[0]} is the winner!!!"
elif len(winnerlist) > 1:
winstring = " are winners!!!"
for i in winnerlist:
winstring = i + ", " + winstring
return winstring
else:
return "Something's wrong, there are no winners..."
if __name__ == '__main__':
#Ask user if they want to play ()
playagain = 'y'
while playagain == 'y':
playagain = input("Would you like to play a game of dice? (y/n): ")
if playagain == 'n':
print("Goodbye!")
sys.exit()
#Ask user for number of players
num_of_players = int(input("Input number of players: "))
print("Thanks!")
#Ask user how many times each player rolls;
#Show them their score
numrollslist = []
playerscores = []
for x in range(1,num_of_players+1):
numrolls = int(input(f"Input number of times Player{x} rolls: "))
numrollslist.append(numrolls)
score = rolls_result(numrolls)
playerscores.append(score[0])
print(score)
#Determine winners
winnerlist = dice(playerscores)
#Print list of winners
print("The scores are: " + str(playerscores))
print(winnerstring(winnerlist))
print("")
| true |
9fa447c3fae1328014bd7775bd7688bb16b2a180 | KSVarun/Coding-Challanges | /remove_consonents.py | 825 | 4.1875 | 4 | # Given a string s, remove all consonants and prints the string s that contains vowels only.
# Input: The first line of input contains integer T denoting the number of test cases. For each test case, we input a string.
# Output: For each test case, we get a string containing only vowels. If the string doesn't contain any vowels, then print "No Vowel"
# Constraints:
# 1<=T<=100
# The string should consist of only alphabets.
# Examples:
# Input: geEks
# Output: eE
# Input: what are you doing
# Output: a ae ou oi
def removecons(st):
vowels = ["a", "i", "u", "o", "e"]
for x in st:
if x.lower() not in vowels and x != " ":
st = st.replace(x, "")
if st:
return(st)
else:
return("No Vowel")
for _ in range(int(input())):
st = input()
print(removecons(st))
| true |
847252b2b65da4adf71fedb141400e8f74d97e5e | remon/pythonCodes | /python_bacics_101/Arithemtic_operators_en.py | 2,020 | 4.21875 | 4 | # Examples on how to uses Python Arithmetic Operators
'''
What is the operator in Python?
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
for example: 2 + 3 = 5
Here, + is the operator that performs addition.
2 and 3 are the operands and 5 is the output of the operation.
what is Arithmetic Operators means ?
Operator | Description
-----------------------------------------------
+ Addition | Adds values on either side of the operator.
- Subtraction | Subtracts right hand operand from left hand operand.
* Multiplication | Multiplies values on either side of the operator
/ Division | Divides left hand operand by right hand operand
% Modulus | Divides left hand operand by right hand operand and returns remainder
** Exponent | Performs exponential (power) calculation on operators
// Floor Division | he division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero
when do we use it ?
we use this kind of every where form basic math operation to loops or condition statements
'''
from __future__ import print_function
a = 20 ; b = 10
# Addition operator
c = a + b
print("Addition value =" , c)
# Subtraction operator
c = a - b
print("Subtraction value = " , c)
# Multipliction operator
c = a * b
print("Multipliction value = " , c)
# Division operator
c = a / b
print("Division value = " , c)
# Mod operator
c = a % b
print("Mod value = " , c)
# Exponent or power operator
a = 2 ; b = 3
c = a ** b
print("Exponent value = " , c)
# floor Division or integer division operator
'''
Note :
In Python 3 the division of 5 / 2 will return 2.5 this is floating point division
the floor Division or integer divisio will return 2 mean return only the integer value
'''
a = 9 ; b = 4
c = a // b
print("Integer Division value = " , c)
| true |
fb6b67ad09585fe97647f5fc40bf1934a4e7dfd7 | remon/pythonCodes | /Lists/List_Methods/append_en.py | 1,291 | 4.75 | 5 | #added by @Azharoo
#Python 3
"""
The append() method adds an item to the end of the list.
The item can be numbers, strings, another list, dictionary etc.
the append() method only modifies the original list. It doesn't return any value.
"""
#Example 1: Adding Element to a List
my_list = ['python', 'codes', 1, 2, 3]
my_list.append('Azharo')
print (my_list) #['python', 'codes', 1, 2, 3, 'Azharo']
#Example 2: Adding List to a List
aList = [123, 'xyz', 'abc', 78];
bList = [2018, 'Lolo'];
aList.append(bList)
print ("Updated List : ", aList ) #Updated List : [123, 'xyz', 'abc', 78, [2018, 'Lolo']]
""" Notes
1) The difference between append and extend
append:
Appends any Python object as-is to the end of the list (i.e. as a last element in the list).
The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)
extend:
Accepts any iterable as its argument and makes the list larger.
The resulting list is always one dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying list(iterable).
2) Similarity between append and extend
Both takes exactly one argument.
Both modify the list in-place.
As a result, both returns None
""" | true |
0a78a10b44750efbf098df50ab885e38eb12058e | remon/pythonCodes | /Functions/python_exmple_fibonacci_en.py | 641 | 4.375 | 4 | #this file print out the fibonacci of the function input
#importing numpy for execute math with lists
import numpy as np
#define the function that takes one input
def fibonacci_cube(num):
#define a list that contains 0 and 1 , because the fibonacci always starts with 0 and 1
lis = [0,1]
#this for loop takes the range of the parameter and 2
for i in range(2,num):
#appending the sum of the previuos two numbers to the list
lis.append(lis[i-2] + lis[i-1])
#finally returning the cube of the fibonacci content
return np.array(lis)**3
#calling the function with 8 as an example
print fibonacci_cube(8)
| true |
591ce87b8211499434dc4f19086d6a8eb042f843 | remon/pythonCodes | /Functions/strip_en.py | 618 | 4.25 | 4 | #strip() returns a copy of the string
#in which all chars have been stripped
#from the beginning and the end of the string
#lstrip() removes leading characters (Left-strip)
#rstrip() removes trailing characters (Right-strip)
#Syntax
#str.strip([chars]);
#Example 1
#print Python a high level
str = "Python a high level language";
print str.strip( 'language' )
#Examlpe 2
str = "Python a high level language , Python")
#print a high level language ,
print str.strip("Python")
#print a high level language , Python
print str.lstrip("Python")
#print Python a high level language ,
print str.rstrip("Python")
| true |
57e7fdb1ff3591f58ec76cf85638980d3f5a6171 | remon/pythonCodes | /Lists/comprehensions_en.py | 1,012 | 4.5625 | 5 |
# Added by @ammarasmro
# Comprehensions are very convenient one-liners that allow a user to from a
# whole list or a dictionary easily
# One of the biggest benefits for comprehensions is that they are faster than
# a for-loop. As they allocate the necessary memory instead of appending an
# element with each cycle and reallocate more resources in case it needs them
sample_list = [x for x in range(5)]
print(sample_list)
# >>> [0,1,2,3,4]
# Or to perform a task while iterating through items
original_list = ['1', '2', '3'] # string representations of numbers
new_integer_list = [int(x) for x in original_list]
# A similar concept can be applied to the dictionaries
sample_dictionary = {x: str(x) + '!' for x in range(3) }
print(sample_dictionary)
# >>> {0: '0!', 1: '1!', 2: '2!'}
# Conditional statements can be used to preprocess data before including them
# in a list
list_of_even_numbers = [x for x in range(20) if x % 2 == 0 ]
print(list_of_even_numbers)
# >>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
| true |
aa3f18d2d26c103253f0df89c11c30c5bd9a754e | vdn-projects/omnilytics-challenge | /read_print_data.py | 998 | 4.125 | 4 | import os
def is_float(obj):
"""
Check if object is float datatype or not
Args:
obj: input object in string
Returns:
True if it is float, else False
"""
try:
float(obj)
except ValueError:
return False
return True
if __name__=="__main__":
base_path = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(base_path, "output.txt")
with open(file_path, "r") as f:
content = f.read()
objs = [obj.strip() for obj in content.split(",")]
for obj in objs:
if obj.isnumeric():
result = f"{obj} - integer"
elif obj.isalpha():
result = f"{obj} - alphabetical strings"
elif obj.isalnum():
result = f"{obj} - alphanumeric"
elif is_float(obj):
result = f"{obj} - real number"
else:
raise ValueError(f"Unknown object type: '{result}', please check your code.")
print(result) | true |
0858e00dbefe600268bf106ce92459396828b6f8 | laineyr19/MAGIC | /Week 3/text_based_adventure_game-2/game_02.py | 317 | 4.15625 | 4 | def main():
'''Getting your name'''
play_name=(raw_input("What's your name? > "))
play_age=(raw_input("enter your age? >"))
print ("hi"+" "+play_name)
result="my name is {name} and my age is {age}".format (name=play_name, age=play_age)
print(result)
if __name__ == '__main__':
main() | true |
7264c06c4327d762d4f072a4c903cc6fd79cf3c4 | krishnachouhan/calculator | /calculator/sum.py | 1,200 | 4.25 | 4 | # Sum Module
def sum(a, b, verbose=0):
'''
Writing this Sample doc. This is useful as when you type __doc(sum)__, this text is printed.
hence its a good practice to use this.
Here,
- parameters are to be explained.
- return values are to be explained.
- finally, dependencies are to explained
'''
try:
return a+b
except:
if verbose==1:
print("a+b Couldn't be done simply, Trying other alternaives.")
temp=None
try:
if verbose==2:
print("""Second level of Verbose here we are explaining the simply preformed operations.
a+b Couldn't be done simply, Trying other alternaives, as this mmight be a list.""")
if type(a[0])==type(''):
temp=''
if type(a[0])==type(0):
temp=0
for i in a:
if type(i)==type(0):
temp = temp + i
elif type(i)==type(''):
temp = str(temp)+i
except:
if verbose==1:
print("""Possible Unsupported operation, please check the variable-type.""")
return a+b | true |
ee26f9872314401c7e376ac3018ef80dd5f23e58 | agandhasiri/Python-OOP | /program 4 Contest problems/everywhere.py | 996 | 4.15625 | 4 | Tests = int(input()) # no of test cases
len_list=[] # for length of each test case list with distinct names
for v in range(Tests): # a loop for every test case
n = int(input()) # no of work trips for each test case
list = [] # a list for distinct names
i=0
while True:
name = input() # name of the place
if name not in list: # checking for the name in the list
list.append(name) # adding that name to the list, if it is not in the list.
i+=1 # counting every trip
if n==i: # if the count is equal to n(no of trips)
break # it stops taking trip name
len_list.append(len(list)) # add length of every test case list to a new list
for j in len_list: # print length of every distinct names list
print(j)
| true |
218275d05a30d062ce99d9dd2f4cb2dea08523ca | xhemilefr/ventureup-python | /exercis5.1.py | 314 | 4.21875 | 4 | def reverse_string(string):
reversed_string = ""
for x in string:
reversed_string = x + reversed_string
return reversed_string
def check_palindrome(string):
temp = string.lower()
if temp == reverse_string(temp):
return True
return False
print(check_palindrome("Pasddsap")) | true |
0b8a3bfb2f1514d77b83bf94c59fefb20f1b5bd8 | mabbott2011/PythonCrash | /conditionals.py | 536 | 4.125 | 4 | # Conditionals
x = 4
#basic if
if x < 6:
print('This is true')
#basic If Else
y = 1
if y > 6:
print("This is true")
else:
print("This is false")
# Elif
color = 'red'
#color = 'blue'
#color = 'purple'
if color == 'red':
print('Color is red')
elif color == 'blue':
print('Color is blue')
else:
print('Color is neither red or blue')
#Nested if
if color == 'red':
if x < 10:
print('This is true')
#But lets write this better
if color == 'red' and x < 10:
print('This is a true statement')
| true |
63b4bdc7b80b17cd676b6c404c15a9ccb27f6d7e | ADcadia/py-calc | /coin-toss-calculator.py | 474 | 4.125 | 4 | # Enter the number of times you will toss the coin.
import random
def tossCoin():
num = random.randint(0, 1)
if num == 0:
return "Heads"
else:
return "Tails"
timesToToss = int(input("How many times will you toss the coin? \n"))
headsCounter = 0
tailsCounter = 0
for i in range(timesToToss):
if tossCoin() == "Heads":
headsCounter = headsCounter+1
else:
tailsCounter = tailsCounter+1
print("Heads: ", headsCounter, "\nTails: ", tailsCounter)
| true |
8c396abb6742f4e88cd68d47c057420fb5f3f253 | stoneboyindc/udacity | /P1/problem_2.py | 1,862 | 4.4375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
result = []
try:
listDirs = os.listdir(path)
for i in listDirs:
item = os.path.join(path, i)
if os.path.isdir(item):
result += find_files(suffix, item)
if os.path.isfile(item):
if item.endswith(suffix):
result.append(item)
except FileNotFoundError:
print (path, "does not exist.")
except NotADirectoryError:
if path.endswith(suffix):
result.append(path)
return result
## Locally save and call this file ex.py ##
# Code to demonstrate the use of some of the OS modules in python
# Test code below
# Test Case 1 - Normal case - Use provided `testdir.zip` file
print (find_files(".c", "C:\\Temp\\testdir\\testdir")) # ['C:\\Temp\\testdir\\testdir\\subdir1\\a.c', 'C:\\Temp\\testdir\\testdir\\subdir3\\subsubdir1\\b.c', 'C:\\Temp\\testdir\\testdir\\subdir5\\a.c', 'C:\\Temp\\testdir\\testdir\\t1.c']
# Test Case 2 - Edge case - Use a file as an input argument for path
print (find_files(".c", "C:\\Temp\\testdir\\testdir\\subdir1\\a.c")) # ['C:\\Temp\\testdir\\testdir\\subdir1\\a.c']
# Test Case 3 - Edge case - Use provided `testdir.zip` file but the wrong input
print (find_files(".cpp", "C:\\Temp\\testdir\\testdirX")) # [] with an error message printed out C:\\Temp\\testdir\\testdirX does not exist.
| true |
b9d3484d14d0a0148a32d94715c1a30009ce3b3f | Rohitthapliyal/Python | /Python_basics/14.py | 280 | 4.15625 | 4 | import math
class Power:
x=int(input("enter any number:\n"))
y=int(input("enter base:\n"))
def show(ob):
ob.power=math.pow(ob.x*ob.y)
def output(ob):
print("power of the number is=",ob.power)
obj=Power()
obj.show()
obj.output()
| true |
c2c4f82acaa1cfa7cc082ddcdf5819a21d64f3fd | BadrChoujai/hacker-rank-solutions | /Python/13_Regex and Parsing/Re.findall() & Re.finditer().py | 1,211 | 4.125 | 4 | # Problem Link: https://www.hackerrank.com/challenges/re-findall-re-finditer/problem
# ----------------------------------------------------------------------------------
import re
m = re.findall(r'(?i)(?<=[^aeiou])[aeiou]{2,}(?=[^aeiou])', input())
if len(m) > 0:
print(*m, sep = '\n')
else:
print('-1')
# (?i) is for making case insensitive
# Lookbehind:
# (?<=[expression])[pattern] #positive lookbehind
# (?<![expression])[pattern] #negative lookbehind
# (?=...) -> It is called lookahead assertion
# eg.
# Matches if ... matches next, but doesn’t consume any of the string.
# This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
# (?<=...) -> It is called Positive Lookbehind
# eg.
# Matches if the current position in the string is preceded by a match for ... that ends at the current position.
# This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef,
# since the lookbehind will back up 3 characters and check if the contained pattern matches.
# References:
# https://www.hackerrank.com/challenges/re-findall-re-finditer/forum/comments/88272 | true |
2ecded57167e4ff843aea14dcc97e141de899a38 | Sunil-Archive-Projects/Python-Experiments | /Python_Basics/classes.py | 370 | 4.1875 | 4 | #defining classes
class myClass():
def firstMethod(self):
#self refers to itself
print("First Method")
def secondMethod(self,str):
#self refers to itself
print "Second Method",str
#defining subclasses
# subClass inherits superClass myClass
class subClass(myClass):
x=0
def main():
obj=subClass()
obj.firstMethod()
obj.secondMethod("Arg1")
main()
| true |
063d16a81a5348f33bc809d857d7ad71d16ee58c | elmasria/mini-flow | /src/linear.py | 689 | 4.25 | 4 | from neuron import Neuron
class Linear(Neuron):
def __init__(self, inputs, weights, bias):
Neuron.__init__(self, inputs)
# NOTE: The weights and bias properties here are not
# numbers, but rather references to other neurons.
# The weight and bias values are stored within the
# respective neurons.
self.weights = weights
self.bias = bias
def forward(self):
"""
Set self.value to the value of the linear function output.
Your code goes here!
"""
self.value = self.bias.value
for w, x in zip(self.weights, self.inbound_neurons):
self.value += w.value * x.value
| true |
bac53da6089ab51d4d094411fdcbc2a9741a50c4 | schnitzlMan/ProjectEuler | /Problem19/Problem19.py | 1,400 | 4.125 | 4 | # strategy -
#count all the days - approximately 100 * 365.25 - not too large.
#keep track of the month to add correctly
#devide the day by %7 - if no rest, sunday if you counted correctly
#count the numbers of sundays
#months = {"jan": 31, "feb": 28, "mar":31, "apr":30, "may":31, "jun":30,
# "jul": 31, "aug": 31, "sep":30, "oct":31, "nov":30, "dec":31}
daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]
monthchar = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
dayschar = ["sun", "mon", "tue", "wed", "thu", "fri", "sat", "sun"]
days = 1 #1.1.1900 was a Monday -count Mon=1 Sun = 7
sundays = 0
for year in range(1900,2001):
#print("year ", year)
for mon in range(len(daysInMonth)):
print("year", year, "mon ", monthchar[mon], "firstDay ", dayschar[days%7])
if (days%7 == 0 and year > 1900):
sundays += 1
days += daysInMonth[mon] # next first of month
if mon == 1:
if year%4 ==0:
if year%100 != 0:
if year % 400 != 0:
days +=1
print("Schaltjahr - add 1")
# print(mon, daysInMonth[mon], days, sundays)
#print(mon, months[mon])
#days += 365
#if (i%4 == 0 ):
# days+1
# if (i%400 == 0):
# print(i)
# days += 1
print(sundays)
| true |
62f40aec64258193e15abedd7a346425bbc877b3 | pranakum/Python-Basics | /week 2/course_1_assessment_6/q8.py | 426 | 4.34375 | 4 | '''
Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list. (You should use the len function).
'''
original_str = "The quick brown rhino jumped over the extremely lazy fox"
#code
str = original_str.split()
print (str)
num_words_list = []
for word in str:
num_words_list.append(len(word))
print (num_words_list)
| true |
7e31942b56635ec1122e4ee36ae7127759ff1d29 | H-B-P/WISHK | /Resources/PYTHON/repeater.py | 593 | 4.28125 | 4 | import sys #Imports sys, the library containing the argv function
the_string=str(sys.argv[1]) #The string to repeat is the first argument given.
target_number_of_repeats=int(sys.argv[2]) #The number of repeats is the second argument given.
number_of_repeats=0 #Set this variable to zero, as there are no repeats at the start of program.
while (number_of_repeats<target_number_of_repeats):#Until the statement in the brackets is false.
print (the_string) #Output the string, again. (This section must be indented!)
number_of_repeats=number_of_repeats+1 #Add 1 to the number of repeats.
| true |
56a6965014a8d529400257f90556692bb619861d | platinum2015/python2015 | /cas/python_module/v07_nested_functions_2.py | 440 | 4.1875 | 4 | def derivative(my_function):
'''Returns a function that computes the numerical derivative of the given
function my_function'''
def df(x, h=0.0001):
return ((my_function(x+h) - my_function(x-h)) / (2*h))
return df
def f(x):
'''The mathematical function f(x) = x^3'''
return x*x*x
df = derivative(f) #f'
ddf = derivative(df) #f''
for x in range(-10, 10):
print x, f(x), df(x), ddf(x)
| true |
0b7360bdf8002a8b0c5542ea2cfa08784855be7b | platinum2015/python2015 | /cas/python_module/Day1_SampleSolutions/p02_braking_distance_SOLUTION.py | 1,095 | 4.375 | 4 | # Compute the distance it takes to stop a car
#
# A car driver, driving at velocity v0, suddenly puts on the brake. What
# braking distance d is needed to stop the car? One can derive, from basic
# physics, that
# d=0.5*v_0^2 / mu * g
#
# Develop a program for computing d using the above formula when the initial
# car velocity v0 and the friction coefficient mu are provided via the
# raw_input function.
#
# Run the program for two cases: v0 = 120 and v0 = 50 km/h, both with mu = 0.3
# (mu is dimensionless).
#
# Hint: Remember to convert the velocity from km/h to m/s before inserting the
# value in the formula!
g = 9.81 # Assigns g value
# Inputs become floats
v0_in_kmh = float(raw_input("Please enter the initial velocity(v0) in km/h "))
mu = float(raw_input("Please, enter the friction coefficient (mu) "))
# Conversion from km/h to m/s
v0 = (v0_in_kmh*1000.)/3600.
# Computes braking distance
distance = (0.5*v0**2)/(mu*g)
# Prints the result
print "The braking distance of a car traveling at %.2f km/h is %.2f m" % (v0_in_kmh, distance)
| true |
2ff4e164e15623a045036ad189bfab2280086e68 | kpatel1293/CodingDojo | /DojoAssignments/Python/PythonFundamentals/Assignments/12_ScoresAndGrades.py | 907 | 4.375 | 4 | # Assignment: Scores and Grades
# Write a function that generates ten scores between 60 and 100.
# Each time a score is generated, your function should display what the grade
# is for a particular score.
# Here is the grade table:
# Score: 60 - 69; Grade - D
# Score: 70 - 79; Grade - C
# Score: 80 - 89; Grade - B
# Score: 90 - 100; Grade - A
import random
def scoreAndGrade():
grade = ''
print 'Scores and Grades'
for num in range(0,10):
score = random.randint(60,101)
if score <= 69 and score >= 60:
grade = 'D'
elif score <= 79 and score >= 70:
grade = 'C'
elif score <= 89 and score >= 80:
grade = 'B'
elif score <= 100 and score >= 90:
grade = 'A'
print 'Score: {}; Your grade is {}'.format(score,grade)
print 'End of the program. Bye!'
scoreAndGrade() | true |
fac7cceb04d13dc68e238e969a306522b51c73e9 | kpatel1293/CodingDojo | /DojoAssignments/Python/PythonFundamentals/Assignments/9_FooBar.py | 1,623 | 4.1875 | 4 | # Optional Assignment: Foo and Bar
# Write a program that prints all the prime numbers and all the perfect
# squares for all numbers between 100 and 100000.
# For all numbers between 100 and 100000 test that number for whether
# it is prime or a perfect square. If it is a prime number, print "Foo".
# If it is a perfect square, print "Bar". If it is neither, print "FooBar".
# Do not use the python math library for this exercise. For example, if the
# number you are evaluating is 25, you will have to figure out if it is a
# perfect square. It is, so print "Bar".
# prime numbers : 1 2 3 5 7 11 13 17 19 23 29...
# def primeNum(num):
# count = 0
# for i in range(1,12):
# if(num % i == 0 and num != i):
# count += 1
# if count == 1:
# return 'Foo'
def FooAndBar():
count = 0
num = 1
# for e in range(100,100000):
while(num <= 100):
for i in range(1,12):
if(num % i == 0 and num != i):
count += 1
print num
num += 1
# num += 1
FooAndBar()
FooAndBar()
# def primeNum(num):
# count = 0
# #check if prime
# for e in range(1,100):
# if(num % e == 0 and num != e):
# count += 1
# if count == 1:
# print 'Foo'
# # check if square
# for e in range(1,100):
# if(e * e == num):
# print 'Bar'
# break
# if(count > 1 and e * e != num):
# print 'FooBar'
# # primeNum(2)
# primeNum(3)
# primeNum(4)
# # primeNum(25)
# primeNum(6)
# # primeNum(7)
# primeNum(8) | true |
a3b664d4fa3abcccc3cd93690ffe40b053ccf044 | prkhrv/mean-day-problem | /meanday.py | 1,050 | 4.53125 | 5 | """
Mean days
Problem: You are given a list with dates find thee mean day of the given list
Explanation: Given that the range of day values are 1-7 while Monday = 1 and Sunday = 7
Find the "Meanest Day" of the list .
"Meanest Day" is the sum of values of all the days divided by total number of days
For Example:- Consider a list with dates ['04041996','09091999','26091996']
Meanest Day == Thursday
Explanation:-
Day on '04041996 is Thursday(4),
Day on '09091999' is Thursday(4),
Day on '26091996' is Thursday(4),
hence Meanest day = 4+4+4 // 3 ---> 4 (Thursday)
Input:- A list with dates in string format. ie. '01011997'
Output:- Name of the Mean Day
"""
import calendar
import datetime
date_list = ['04041996','09091999','26091996']
def mean_day(date_list):
value_sum = 0
for date in date_list:
day_value = datetime.datetime.strptime(date, '%d%m%Y').weekday()+1
value_sum = value_sum + day_value
mean_day = value_sum // len(date_list)
return calendar.day_name[mean_day-1]
print(mean_day(date_list)) | true |
61895160c36dbfbaafb426cfdbdecc280d6475c9 | lisu1222/towards_datascience | /jumpingOnClouds.py | 1,833 | 4.28125 | 4 | """ Emma is playing a new mobile game that starts with consecutively numbered
clouds. Some of the clouds are thunderheads and others are cumulus. She can jump
on any cumulus cloud having a number that is equal to the number of the current
cloud plus or . She must avoid the thunderheads. Determine the minimum number
of jumps it will take Emma to jump from her starting postion to the last cloud.
It is always possible to win the game.
For each game, Emma will get an array of clouds numbered if they are safe or
if they must be avoided. For example, indexed from . The number on each cloud
is its index in the list so she must avoid the clouds at indexes and . She
could follow the following two paths: or . The first path takes jumps while
the second takes .
Function Description
Complete the jumpingOnClouds function in the editor below. It should return the
minimum number of jumps required, as an integer.
jumpingOnClouds has the following parameter(s):
c: an array of binary integers Input Format
The first line contains an integer , the total number of clouds. The second line
contains space-separated binary integers describing clouds where .
Constraints
Output Format
Print the minimum number of jumps needed to win the game.
Sample Input 0
7 0 0 1 0 0 1 0 Sample Output 0
4 """
def jumpingOnClouds(c):
step = 0
i = 0
while i < len(c)-2:
if c[i+2] == 0:
i += 1
step += 1
i += 1
#if i hasn't reached the last cloud:
if i != len(c)-1:
step += 1
return step
#improved solution:
def jumpingOnClouds(c):
step = -1
i = 0
while i < len(c):
if i < len(c)-2, and c[i+2]==0:
i+=1
i += 1
step += 1
return step
if __name__ =='__main__': n = int(input()) c = list(map(int,
input().rstrip().split())) result = jumpingOnClouds(c)
| true |
01c591c32142f0cb206fbee55375e77ee798121e | momentum-cohort-2019-02/w2d3-word-frequency-rob-taylor543 | /word_frequency.py | 1,769 | 4.125 | 4 | STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
import string
def clean(file):
"""Read in a string and remove special characters and stop words (keep spaces). Return the result as a string."""
file = file.casefold()
valid_chars = string.ascii_letters + string.whitespace + string.digits
new_file = ""
for char in file:
if char in valid_chars:
new_file += char
file = new_file
file = file.replace("\n", " ")
return file
def print_word_freq(file):
"""Read in `file` and print out the frequency of words in that file."""
with open(file, "r") as open_file:
file_string = open_file.read()
clean_file = clean(file_string)
word_freq = {}
words = []
for word in clean_file.split(" "):
if word and word not in STOP_WORDS:
words.append(word)
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
sorted_keys = sorted(word_freq, key = word_freq.__getitem__, reverse = True)
for word in sorted_keys:
freq = word_freq[word]
asterisk = "*" * freq
print (f"{word:>20} | {freq:<3} {asterisk}")
if __name__ == "__main__":
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(
description='Get the word frequency in a text file.')
parser.add_argument('file', help='file to read')
args = parser.parse_args()
file = Path(args.file)
if file.is_file():
print_word_freq(file)
else:
print(f"{file} does not exist!")
exit(1)
| true |
cec4b8438e743ddce8a680a2d4791b3e75dcbb93 | Nas-Islam/qa-python-exercises | /programs/gradecalc.py | 687 | 4.21875 | 4 | def gradeCalc():
print("Welcome to the Grade Calculator!")
mathsmark = int(input("Please enter your maths mark: "))
chemmark = int(input("Please enter your chemistry mark: "))
physicsmark = int(input("Please enter your physics mark: "))
percentage = (mathsmark + chemmark + physicsmark) / 3
if percentage >= 70:
grade = 'You scored a grade of: A'
elif percentage >= 60:
grade = 'You scored a grade of: B'
elif percentage >= 50:
grade = 'You scored a grade of: C'
elif percentage >= 40:
grade = 'You scored a grade of: D'
else:
grade = 'You failed.'
print(percentage,"%")
print(grade)
gradeCalc()
| true |
f68a1c9afe8a230e2b9e5ef79982be601a9b97bb | meahow/adventofcode | /2017/06/solution1_test.py | 1,348 | 4.28125 | 4 | import solution1
"""
For example, imagine a scenario with only four memory banks:
The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution.
Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2.
Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3.
Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4.
The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1.
The third bank is chosen, and the same thing happens: 2 4 1 2.
At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5.
"""
def test_solve():
data = [0, 2, 7, 0]
assert solution1.solve(data) == 5
| true |
24cab64adff4d0da92ad5b941b501e355dacfd98 | Iliyakarimi020304/darkT-Tshadow | /term 2/dark shadow51.py | 320 | 4.125 | 4 | number = input("Enter Number: ")
counter = 0
numbers = []
sums = 0
while number != '0':
if number.isdigit():
numbers.append(number)
counter += 1
number = input("Enter Number: ")
for n in numbers:
sums += int(n)
print(f"Your numbers{numbers}")
print(f"Average of your numbers {sums/counter}")
| true |
5c64470d7d305603eb43654528cb7fd6ea78c1cb | MerchenCB2232/backup | /todolist.py | 814 | 4.125 | 4 | import pickle
print ("Welcome to the To Do List :))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))")
todoList = []
while True:
print("Enter a to add an item")
print("Enter r to remove an item")
print("Enter l to load list")
print("Enter p to print the list")
print("Enter q to quit")
choice = input("Make your choice: ")
if choice == "q":
pickle.dump(todoList,open("save.p", "wb"))
break
elif choice == "a":
addition = input("What would you like to add to the list? ")
todoList.append(addition)
elif choice == "r":
subtraction = input("What would you like to remove? ")
todoList.remove(subtraction)
elif choice == "p":
print(todoList)
elif choice == "l":
todoList = pickle.load(open("save.p", "rb"))
else:
print("That is not an option. :(") | true |
c0d1f2201c3dc6a715ba9994214db7c1d535b453 | cpvp20/bubblesort | /del.py | 378 | 4.21875 | 4 | def sortit(numbers):
for i in range(len(numbers)):
if i[1]>i[2]:
i[1],i[2]=i[2],i[1]
return(numbers)
#ACTIAL CODE
x=list(input("type some integers randomly, separating them with spaces "))
#creates a list with the numbers the user gives
y=[int(i) for i in range(len(x))]#turns list of str into list of int
sortit(y) #sort the list of int
| true |
622f93ea01a437ead0616c01901d593092a26927 | rwaidaAlmehanni/python_course | /get_started/Comprehensions/problem28.py | 218 | 4.21875 | 4 | #Write a function enumerate that takes a list and returns a list of tuples containing (index,item) for each item in the list.
def enumerate(array):
print [(array.index(y),y) for y in array]
enumerate(["a", "b", "c"]) | true |
28a6f77cddab8da561601b8f743f57d2e1da03bf | Nzembi123/function.py | /functions.py | 2,647 | 4.3125 | 4 | #Function is a block of code that runs only when called
def adding(num1, num2):
x = num1+num2
print(x)
adding(2,4)
#Multiplication
def multiplication():
num1 =15
num2 =30
sum = num2*num1
print(sum)
multiplication()
##arguments
def courses(*args):
for subject in args:
print(subject)
courses('IT', 'Nutririon', 'Math')
def courses(*args):
for subject in args:
return subject
print(courses('IT', 'Nutririon', 'Math'))
#keyword arguments
def cars(**kwargs):
for key, value in kwargs.items():
print("{}:{} ". format(key,value))
cars( car1='Subaru\n', car2='Bentley\n', car3='jeep')
#Default parameter value - used when we call the fn without an argument
def shoes(shoe_type = 'Airmax'): ##Airmax is set to be the default argument
print('\nMy shoe type is ' + shoe_type )
shoes() ##this will print 'My shoetype is Airmax since it is the default parameter'
shoes('fila')
shoes('puma')
#passing a list as arguments
def muFunction (devices):
for x in devices:
print(x)
input_devices = ['Keyboard', 'touchscreen', 'mouse']
muFunction(input_devices)
#passing a dictionary as arguments
def muFunction (student):
for x in student:
print(x)
student = {
'Fname' : 'James', #string
'Sname' : 'Bond', #string
'Tel' : 8508447, #integer
'Shoes' : ['Fila', 'Airmax' , 'Dior'], #list
'Male' : True
}
muFunction(student)
#The pass statement
#area of a circle
def area_of_circle():
print('\nAREA OF A CIRCLE')
pi = 3.142
r = float(input('\nEnter the radius: '))
area = (pi*r*r)
print('\nThe area is ' + str(area))
area_of_circle()
#volume of a cylinder
def volume_of_cylinder():
print('\nVOLUME OF A CYLINDER')
pi = 3.142
r = float(input('\nEnter the radius: '))
h = float(input('\nEnter the height: '))
v = (pi*r*h)
print('\nThe volume is ' + str(v))
volume_of_cylinder()
#GRADING SYSTEM
def grading():
mat = float(input('Enter marks for Math: '))
sci = float(input('Enter marks for Science: '))
eng = float(input('Enter marks for English: '))
sum = mat+sci+eng
avr = sum/3
if avr >=0 and avr<=49:
print('Average = ' + str(avr) + 'GRADE : E')
elif avr >=50 and avr<=59:
print('Average = ' + str(avr) + 'GRADE : D')
elif avr >=60 and avr<=69:
print('Average = ' + str(avr) + 'GRADE : C')
elif avr >=70 and avr<=79:
print('Average = ' + str(avr) + 'GRADE : B')
elif avr >=80 and avr<=100:
print('Average = ' + str(avr) + 'GRADE : A')
else:
print('Marks out of range! ')
grading() | true |
e214ac661d060b1ce887b15ad66ff44caac1947c | jubic/RP-Misc | /System Scripting/Problem15/6P/t50_xml1.py | 1,763 | 4.21875 | 4 | """
h2. XML from List of Dictionary
Create a function @xmlFromList@ that takes a list of dictionaries. The XML must have the root tag @<storage>@.
Each item in the dictionary should be put inside the @<container>@ tag. The dictionary can contain any keys (just make sure the keys are the same for all of the dictionaries in the list). and different values. See the example below.
bc. {- python -}
print xmlFromList([
{'title':'Introduction to Algoritms', 'author':'Ronald Rivest'},
{'title':'Learning Python', 'author':'Mark Lutz'},
{'title':'The Ruby Programming Language', 'author':'David Flanagan'}
])
bc. {- xml -}
<?xml version='1.0' encoding='UTF-8'?>
<storage>
<container>
<author>Ronald Rivest</author>
<title>Introduction to Algoritms</title>
</container>
<container>
<author>Mark Lutz</author>
<title>Learning Python</title>
</container>
<container>
<author>David Flanagan</author>
<title>The Ruby Programming Language</title>
</container>
</library>
*{color:red;}Notes:* Don't hardcode @<author>@ and @<title>@ as they can change according to keys and values in the dictionary. Only @<storage>@ and @<container>@ are fix.
"""
def xmlFromList(l):
# your code here
s = "<?xml version='1.0' encoding='UTF-8'?>\r\n"
s += "<storage>\r\n"
for dict in l:
s += "\t<container>\r\n"
for (k,v) in dict.items():
s += "\t\t<%s>%s</%s>\r\n" % (k, v, k)
s += "\t</container>\r\n"
s += "</storage>\r\n"
return s
if __name__ == "__main__":
print xmlFromList([ {'title':'Introduction to Algoritms', 'author':'Ronald Rivest'}, {'title':'Learning Python', 'author':'Mark Lutz'}, {'title':'The Ruby Programming Language', 'author':'David Flanagan'}])
| true |
4a2ce6635442bfaf8555a1958b6dd06b1389d52d | jubic/RP-Misc | /System Scripting/Problem15/t40_db1.py | 1,533 | 4.53125 | 5 | """
h2. Putting Data into SQLite Database
Write a function @putData@ that takes 4 arguments as specified below:
# @dbname@ - a string that specifies the location of the database name
# @fnames@ - the list of first names
# @lnames@ - the list of last names corresponding to the first names list
# @ages@ - the list of the age corresponding to each name in the first name and last name lists
Insert those lists into a table named @people@ in a database with name that is in the first argument. The function needs not return anything. See the example below:
bc. {- python -}
putData("tmp/test.db", ["Bob", "John"], ["Lim", "Tan"], [45, 32])
@testall.pyc@ will check the database that's created by @putData@ directly.
"""
import sqlite3
# Complete the function below
def putData(dbname, fnames, lnames, ages):
conn = sqlite3.connect(dbname)
#conn.execute("drop table people")
conn.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, fnames TEXT, lnames TEXT, ages INTEGER)")
for x in range(len(fnames)):
#age = ", "+ str(ages[x])
conn.execute("INSERT INTO people (fnames, lnames, ages) VALUES ('"+fnames[x]+"', '"+lnames[x]+"', "+str(ages[x])+")")
#print "INSERT INTO people (firstname, lastname, age) VALUES ('"+fnames[x]+"', '"+lnames[x]+"', "+str(ages[x])+")"
conn.commit()
if __name__ == '__main__':
putData("tmp/names.db", ["John", "Paul", "George", "Ringo"], ["Lennon", "McCartney", "Harrison", "Star"], [25, 26, 27, 28])
| true |
8ac8ef9b63495ec2678dbad87faa668c9d4d9924 | jubic/RP-Misc | /System Scripting/Problem15/t02_list3.py | 665 | 4.21875 | 4 | """
h2. Zip Two Lists into One
Write a function @zipper@ that takes 2 arguments.
Both arguments are lists of integers. The function must then create a new list to put the first item of the first list, followed by the first item of the second list. Then second item of the first list, followed by the second item in the second list.
Check the example below:
bc. {- python -}
"""
a = [1,2,3]
b = [4,5,6]
# After running zipper(a, b), you'll get [1,4,2,5,3,6]
def zipper(l1, l2):
result = []
i=0
for item in l1:
result.append(item)
result.append(l2[i])
i = i+1
return result
if __name__ == "__main__":
print zipper(a, b)
| true |
4c4bb3ad3c2b0a45b1b044891d10805fccabb614 | Montanaz0r/Skychallenge-Chapter_II | /I_write_my_programs_in_JSON/I_write_my_programs_in_JSON.py | 629 | 4.25 | 4 | import re
def sum_the_numbers(filename):
"""
A function that sum up all the numbers encountered in the file
:param filename: name of the file (str)
:return: sum of all numbers (int)
"""
with open(f'{filename}.txt', 'r') as file:
data = file.read()
results = re.findall(r'(-?\d+)', data) # using REGEX pattern to detect numbers
sum_of_all_numbers = sum([int(number) for number in results])
print(f'Sum of all numbers in the document is equal to: {sum_of_all_numbers}')
return sum_of_all_numbers
if __name__ == '__main__':
sum_the_numbers('json_data')
| true |
beaaff1569c17464bb006805d7f2f20ae0b7457a | SpikyClip/rosalind-solutions | /bioinformatics_stronghold/FIB_rabbits_and_recurrence_relations.py | 2,483 | 4.40625 | 4 | # url: http://rosalind.info/problems/fib/
# Problem
# A sequence is an ordered collection of objects (usually numbers), which
# are allowed to repeat. Sequences can be finite or infinite. Two examples
# are the finite sequence (π,−2–√,0,π) and the infinite sequence of odd
# numbers (1,3,5,7,9,…). We use the notation an to represent the n-th
# term of a sequence.
# A recurrence relation is a way of defining the terms of a sequence with
# respect to the values of previous terms. In the case of Fibonacci's
# rabbits from the introduction, any given month will contain the rabbits
# that were alive the previous month, plus any new offspring. A key
# observation is that the number of offspring in any month is equal to
# the number of rabbits that were alive two months prior. As a result,
# if Fn represents the number of rabbit pairs alive after the n-th month,
# then we obtain the Fibonacci sequence having terms Fn that are defined
# by the recurrence relation Fn=Fn−1+Fn−2 (with F1=F2=1 to initiate the
# sequence). Although the sequence bears Fibonacci's name, it was known
# to Indian mathematicians over two millennia ago.
# When finding the n-th term of a sequence defined by a recurrence
# relation, we can simply use the recurrence relation to generate terms
# for progressively larger values of n. This problem introduces us to the
# computational technique of dynamic programming, which successively
# builds up solutions by using the answers to smaller cases.
# Given: Positive integers n≤40 and k≤5.
# Return: The total number of rabbit pairs that will be present after n
# months, if we begin with 1 pair and in each generation, every pair of
# reproduction-age rabbits produces a litter of k rabbit pairs
# (instead of only 1 pair).
def rabbit_recursive(months, litter_size):
"""
return no. of adult pairs after n months given adult pairs
produce a litter of size k each month
"""
adults, newborns = 0, 1
for _ in range(months):
adults, newborns = adults + newborns, adults * litter_size
return adults
if __name__ == "__main__":
file1, file2 = "inputs/FIB_input.txt", "outputs/FIB_output.txt"
with open(file1, "r") as f1, open(file2, "w") as f2:
# splits string into list, converts to int, then tuple
months, litter_size = tuple(map(int, f1.read().split()))
# convert int result to str before writing
f2.write(str(rabbit_recursive(months, litter_size))) | true |
e8bcb65bd9bb11fd4a11c030c0885dda1669c43b | SpikyClip/rosalind-solutions | /bioinformatics_stronghold/MRNA_inferring_mRNA_from_protein.py | 2,808 | 4.28125 | 4 | # url: http://rosalind.info/problems/mrna/
# Problem
# For positive integers a and n, a modulo n (written amodn in shorthand)
# is the remainder when a is divided by n. For example, 29mod11=7
# because 29=11×2+7.
# Modular arithmetic is the study of addition, subtraction, multiplication,
# and division with respect to the modulo operation. We say that a and b
# are congruent modulo n if amodn=bmodn; in this case, we use the
# notation a≡bmodn.
# Two useful facts in modular arithmetic are that if a≡bmodn and c≡dmodn,
# then a+c≡b+dmodn and a×c≡b×dmodn. To check your understanding of these
# rules, you may wish to verify these relationships for a=29, b=73, c=10,
# d=32, and n=11.
# As you will see in this exercise, some Rosalind problems will ask for
# a (very large) integer solution modulo a smaller number to avoid the
# computational pitfalls that arise with storing such large numbers.
# Given: A protein string of length at most 1000 aa.
# Return: The total number of different RNA strings from which the
# protein could have been translated, modulo 1,000,000. (Don't neglect
# the importance of the stop codon in protein translation.)
import numpy as np
def prot_to_mrna_no(protein):
"""
Counts the number of each type of amino acid in protein, appending the
number of permutations possible for each amino acid type to the power of
the count to a list. The product of this list is returned as a modulo of
1_000_000.
"""
# dict containing the number of possible codons for each amino acid
aa_permutations = {
"F": 2,
"L": 6,
"I": 3,
"V": 4,
"M": 1,
"S": 6,
"P": 4,
"T": 4,
"A": 4,
"Y": 2,
"H": 2,
"N": 2,
"D": 2,
"Q": 2,
"K": 2,
"E": 2,
"C": 2,
"R": 6,
"G": 4,
"W": 1,
}
# 3 ** 1 is the initial value in the list, as proteins must have 1
# stop codon and there are only 3 permutations to a stop codon
total_no = [3]
# Loops through all amino acids and counts its frequency in
# protein. The possible mRNA combinations for that amino acid are
# appended as permutations to the power of its count, modulus
# 1_000_000 which saves some computational power
for amino_acid, permute in aa_permutations.items():
aa_count = protein.count(amino_acid)
total_no.append(pow(permute, aa_count, 1_000_000))
result = np.prod(total_no) % 1_000_000
return result
if __name__ == "__main__":
file1, file2 = "inputs/MRNA_input.txt", "outputs/MRNA_output.txt"
with open(file1, "r") as f1, open(file2, "w") as f2:
protein = f1.read().strip()
total_no = prot_to_mrna_no(protein)
f2.write(str(total_no))
| true |
1e0382442c4c5c2c87899e2084d88182bf589c11 | VIncentTetteh/Python-programming-basics | /my_math.py | 868 | 4.125 | 4 | import math
def calculate(enter, number1, number2):
print("choose from the list.")
print(" 1. ADD \n 2. SUBTRACT \n 3. MULTIPLY")
if enter == "add" or enter == "ADD":
#number1 = input("enter first number ")
#number2 = int(input(" enter second number "))
answer = number1 + number2
return answer
elif enter == "subtract" or enter == "SUBTRACT":
#number1 = int(input("enter first number "))
#number2 = int(input(" enter second number "))
answer = number1 - number2
return answer
elif enter == "multiply" or enter == "MULTIPLY":
#number1 = int(input("enter first number "))
#number2 = int(input(" enter second number "))
answer = number1 * number2
return answer
else:
print("wrong input !!")
print("your answer is ", calculate("ADD",10,2)) | true |
95a29801463084c4374fa418b437e2b79719c702 | Aparna9876/cptask | /task9.py | 201 | 4.28125 | 4 | odd = 0
even = 0
for i in (5,6,8,9,2,3,7,1):
if i % 2 == 0:
even = even+1
else:
odd = odd+1
print("Number of even numbers: ",even)
print("Number of odd numbers: ",odd)
| true |
661875f584581198453a3ba706a8dd24f2c71430 | erchiragkhurana/Automation1 | /Python_Practice/Loops/WhileLoop.py | 362 | 4.15625 | 4 | #Initialization, condition then increment
#while loop with increment, while loop is also called indefinte loop
number = input("Write your number")
i=1
while(i<=10):
print(int(number)*i)
i = i + 1
#while loop with decrement
number = input ("your num")
i=10
while(i>=1):
print(int(number)*i)
i=i-2
#another
i=10
while(i>=1):
print(i)
i=i-3
| true |
61d72a38fbeda9f07c9e3847e50dd85737c94f53 | erchiragkhurana/Automation1 | /Python_Practice/Handling/Condition_Handling.py | 1,511 | 4.46875 | 4 | # take a number from user to check condition handling using if and else
x = input("Hey User type your number")
if(int(x)==100):
print("Number is Greater")
else:
print("Number is smaller")
if(int(x)>100):
print("Number is Greater")
else:
print("Number is smaller")
#check multiple condition handling elif statements
inputnum = input("type your number")
inputnum = int(inputnum) # typecasting to change the string to integer
if(inputnum<0):
print("Number is less than zero")
elif(inputnum==0):
print("Number is equal to zero")
elif(inputnum%2==0): #if number remainder is 0
print("This is even number")
else:
print("This is odd number")
#check nested condition handling examples
inputnum = input("Give your num input")
inputnum = int(inputnum)
if (inputnum>=0):
if(inputnum%2==0):
print("This is even number")
else:
print("This is odd number")
else:
print("This is negative number")
#check condition handling with logical or operator and this should be in lower case as it is case sensitive
inputnum = input("Give your num input")
inputnum = int(inputnum)
if (inputnum> 100 or inputnum <0):
print(" This is invalid number")
else:
print("This is valid number")
#check condition handling with logical and operator and same goes with not operator which is !
inputnum = input("Give your num input")
inputnum = int(inputnum)
if (inputnum> 0 and inputnum >10):
print(" This is valid number")
else:
print("This is invalid number")
| true |
4aba95f8d59bec6b7be786522f62bcc98b8ca04f | tranhd95/euler | /1.py | 367 | 4.28125 | 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.
"""
multiplies_of_three = set(range(0, 1000, 3))
multiplies_of_five = set(range(0, 1000, 5))
multiplies = multiplies_of_three.union(multiplies_of_five)
print(sum(multiplies)) | true |
e4a0c67027e213cf03f165c2ccd6b1ccc6c05ba6 | snirsh/intro2cs | /ex2/largest_and_smallest.py | 1,261 | 4.4375 | 4 | ######################################################################
# FILE : largest_and_smallest.py #
# WRITER : Snir Sharristh , snirsh , 305500001 #
# EXERCISE : intro2cs ex2 2015-2016 #
# DESCRIPTION: The code below calculates the maximum number and the #
# minimum number using three numbers given to it #
######################################################################
# function receives three numbers and returns the biggest and the smallest one
def largest_and_smallest(n1, n2, n3):
n1 = int(n1)
n2 = int(n2)
n3 = int(n3)
# defines which one is the biggest considering that it may be equal to the
# rest and mx is the biggest number
if n1 >= n2 and n1 >= n3:
mx = n1
elif n2 >= n1 and n2 >= n3:
mx = n2
elif n3 >= n1 and n3 >= n2:
mx = n3
# defines which one is the smallest considering that it may be equal to the
# rest and mn is the smallest number
if n1 <= n2 and n1 <= n3:
mn = n1
elif n2 <= n1 and n2 <= n3:
mn = n2
elif n3 <= n1 and n3 <= n2:
mn = n3
# returns the biggest number, and the smallest number
return mx, mn
| true |
4078dfbb0fa06a2375d323e747edf7bd4aae9d4a | danschae/Python-Tutorial | /introduction/basics.py | 757 | 4.1875 | 4 | """
This section is more just about very basic programming, i'm not putting too much effort into it. This type of information is universal to most programming languages.
"""
print("hello world") # simple console log
print (5 * 7)
print("hello" + " world") # can concatante strings just like in javascript
# greetings = "Hello"
# name = input("please enter your name?")
# print(greetings + " " + name)
print("1\n2\n3\n4\n5") # escaping
"""
the good thing with python is that variables can have multiple types implied. It's more that the value has a data type. Python is a strongly typed languaged meaning the data types should match with each other, so you can't concatante a string with a number. Javascript for example is a weakly typed language.
""" | true |
b3299f6e5d300404892111647477ef82d30dfb1b | Rohit102497/Command_Line_Utility | /web_crawler/links_from_html.py | 1,657 | 4.15625 | 4 | '''
This script prompts a user to pass website url and the html code in string format
and output all the links present in the html in a set.
'''
import re
HREF_REGEX = r"""
href # Matches href command
\s* # Matches 0 or more white spaces
=
\s* # Matches 0 or more white spaces
[\'\"](?P<link_url>.+?)[\"\'] # Matches the url
"""
SRC_REGEX = r"""
src
\s*
=
\s*
[\'\"](?P<src_url>.+?)[\'\"]
"""
href_pattern = re.compile(HREF_REGEX, re.VERBOSE)
src_pattern = re.compile(SRC_REGEX, re.VERBOSE)
def links_from_html(html_crawled: str, url: str) -> set:
'''
Returns a set of links extracted from the html passed.
It contains internal links by removing the url (from
the starting of the string) passed to it.
All internal links begins with '/'.
Example Usage:
--------------
>>> url = "https://python.org/"
>>> links_from_html('src = "https://python.org/sitemap/"', url)
{'/sitemap/'}
>>> links_from_html("""src = '#sitemap/'""", url)
{'/#sitemap/'}
>>> links_from_html('href = "https://git.corp.adobe.com/"', url)
{'https://git.corp.adobe.com/'}
'''
links = href_pattern.findall(html_crawled)
links.extend(src_pattern.findall(html_crawled))
links = set(links)
links = {link.replace(url, "/") if link.startswith(url) else link for link in links}
links = {f"/{link}" if link.startswith('#') else link for link in links}
if "/" in links:
links.remove("/")
return links
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
491fefbcbebbbe83f59f94b792b123bd2d0a5e0a | Madhu13d/GITDemo | /PythonBasics1/List.py | 1,217 | 4.5 | 4 | values = [1, 2, "Sai", 4, 5]
print(values[0]) # prints 1
print(values[3]) # prints 4
print(values[-1]) # -1 refers to the last element in the list, prints 5
print(values[1:3])#[1:3] is used to get substring.it will fetch 2 values leaving the 3rd index, prints 2, Sai
values.insert(3, "Ramana") # will insert Ramana at 3rd index
print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5]
values.append("End") # append will insert value at last
print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5, 'End']
values[2] ="SAI" # will Update the old value with new one
print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5, 'End']
del values[0] # will delete the 0th index value
print(values) # prints [2, 'SAI', 'Ramana', 4, 5, 'End']
#Tuple
val= (1, 2, "Sai")
print(val) # prints (1, 2, 'Sai')
#val[2] ="SAI" #TypeError: 'tuple' object does not support item assignment
# Dictionary
dic = {"a":2, 4:"bcd","c":"Hello World"}
print(dic[4]) # prints bcd
print(dic["c"]) # prints Hello World
print(dic["a"]) # prints 2
#
dict = {}
dict["firstname"] = "Madhavi"
dict["lastname"] = "Latha"
dict["gender"] = "Male"
print(dict)# prints {'firstname': 'Madhavi', 'lastname': 'Latha', 'gender': 'Male'}
print(dict["lastname"]) # prints Latha
| true |
f88a428b294348655fba37c81c51cce6976e75aa | RumorsHackerSchool/PythonChallengesSolutions | /Guy/hackerrank.com/Python_Division.py | 596 | 4.15625 | 4 | '''
Task
Read two integers and print two lines. The first line should contain integer division, // . The second line should contain float division, / .
You don't need to perform any rounding or formatting operations.
Input Format
The first line contains the first integer, . The second line contains the second integer, .
Output Format
Print the two lines as described above.
'''
from __future__ import division
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
if a > b:
print int(a/b)
print float(a/b)
else:
print int(b/a)
print float(b/a)
| true |
995a1bbf95d98be9fd0ad66d4ffdbef299e9b78d | sudharkj/ml_scripts | /regression/regression_template.py | 1,426 | 4.125 | 4 | # From the course: Machine Learning A-Z™: Hands-On Python & R In Data Science
# https://www.udemy.com/machinelearning/
# dataset: https://www.superdatascience.com/machine-learning/
# Import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import the dataset
dataset = pd.read_csv('data/Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Split the dataset
# from sklearn.model_selection import train_test_split
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Scale the dataset
# from sklearn.preprocessing import StandardScaler
# sc_X = StandardScaler()
# X_train = sc_X.fit_transform(X_train)
# X_test = sc_X.transform(X_test)
# Fit the regression model
# Predict with regression model
# y_pred = regressor.predict(6.5)
# Visualize regression model
plt.scatter(X, y, color='red')
# plt.plot(X, regressor.predict(X), color='blue')
plt.title("Truth or bluff (Regressor Model)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
# Visualize regression model (for higher resolution and smoother curve)
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape(len(X_grid), 1)
plt.scatter(X, y, color='red')
# plt.plot(X_grid, regressor.predict(X_grid), color='blue')
plt.title("Truth or bluff (Smoother Regressor Model)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
| true |
d73be7748c66e2a6d3a50c8d884b4e713dc1b92d | sudharkj/ml_scripts | /regression/simple_linear_regression.py | 1,252 | 4.34375 | 4 | # From the course: Machine Learning A-Z™: Hands-On Python & R In Data Science
# https://www.udemy.com/machinelearning/
# dataset: https://www.superdatascience.com/machine-learning/
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('data/Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Split the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)
# fit the data
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the test set
y_pred = regressor.predict(X_test)
# Visualising the Train set
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title("Salary vs Experience (Train Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
# Visualising the Test set
plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title("Salary vs Experience (Test Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
| true |
c5cc75fe885f14f205e2b0db8255ef3c580f0684 | Vaild/python-learn | /teacher_cade/day19/7.对象可迭代的.py | 533 | 4.3125 | 4 | #!/usr/bin/python3
# coding=utf-8
class MyList(object):
def __init__(self):
self.container = []
def add(self, item):
self.container.append(item)
# 对象就是可迭代的
def __iter__(self):
return iter(self.container)
mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
for num in mylist:
print(num)
from collections import Iterable
print(isinstance(mylist, Iterable))
from collections import Iterator
print(isinstance(mylist, Iterator))
print(isinstance([], Iterator))
| true |
1e252b0287dd1146885882d9443fa506a41cdfc6 | chris-miklas/Python | /Lab01/reverse.py | 269 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Print out arguments in reverse order.
"""
import sys
def reverse():
"""
Printing arguments in reverse order.
"""
for i in range(len(sys.argv)-1, 0, -1):
print(sys.argv[i])
if __name__ == "__main__":
reverse()
| true |
86ffb3138d8eb92b4fb9d7834b8411a9e77e1b57 | leoswaldo/acm.tju | /2968_Find-the-Diagonal/find_the_diagonal.py | 1,969 | 4.4375 | 4 | #!/python3/bin/python3
# A square matrix contains equal number of rows and columns. If the order of
# the matrix is known it can be calculated as in the following format:
# Order: 3
# 1 2 3
# 4 5 6
# 7 8 9
# Order: 5
# 1 2 3 4 5
# 6 7 8 9 10
# 11 12 13 14 15
# 16 17 18 19 20
# 21 22 23 24 25
#
# and so on..
#
# Now look at the diagonals of the matrices. In the second matrix - the
# elements of a diagonal are marked with circles but this is not the only one
# in this matrix but there are some other minor diagonals like <6, 12, 18, 24>
# as well as <2, 8, 14, 20> and many others.
# Input
#
# Each input line consists of two values. The first value is the order of the
# matrix and the later is an arbitrary element of that matrix. The maximum
# element of the matrix will fit as a 32-bit integer.
# Output
#
# Each output line will display the diagonal elements of the matrix containing
# the given input element.
# Sample Input
#
# 4 5
# 5 11
# 10 81
#
# Sample Output
#
# 5 10 15
# 11 17 23
# 81 92
def find_diagonals(diagonal_questions):
# Need to know how many questions are, to iterate for each one and get its
# answer
questions = len(diagonal_questions)
# Iterate for each question
for current_question in range(0, questions):
# Get order and number to look for
order = diagonal_questions[current_question][0]
number = diagonal_questions[current_question][1]
numbers = ''
# Iterate throug the virtual matrix to find all the diagonal members,
# avoid breaking the limits using the order * order
while(number < (order * order)):
numbers += str(number) + " "
# Add order to break line in diagonal, add 1 to make it diagonal
# to the right
number += order + 1
print(numbers)
# Test scenarios
find_diagonals([[4, 5], [5, 11], [10, 81]])
| true |
24d17e612bfc874dc12d9e3c03d8eb020bf9158a | RanjaniMK/Python-DataScience_Essentials | /creating_a_set_from_a_list.py | 250 | 4.34375 | 4 | # Trying to create a set from a list
# 1. create a list
# 2. create a set
my_list = [1,2,3,4,5]
my_set = set(my_list)
print(my_set)
#Note: The list has square brackets
# The output of a set has curly braces. Like below:
# {1, 2, 3, 4, 5}
| true |
0d55e9a32e80e3bf70ef0534f9f8bda1cec61684 | gjwlsdnr0115/Computer_Programming_Homework | /lab5_2015198005/lab5_p1.py | 431 | 4.28125 | 4 | # initialize largest number variable
largest_num = 0
# variable to stop while loop
more = True
while(more):
num = float(input('Enter a number: '))
if(num > largest_num) :
largest_num = num
if(num == 0):
more = False
if(largest_num > 0): # if there was a positive number input
print('The largest number entered was', format(largest_num, '.2f') )
else:
print('No positive number was entered') | true |
069739315c2e7c0c2a2f8e62fb2f4338cb767650 | grahamh21/Python-Crash-Course | /Chapter 4/Try_it_yourself_chapter_4_2.py | 1,560 | 4.34375 | 4 | #Try_it_yourself 4-7
print('Try it yourself 4-7')
threes = list(range(3,31,3))
for three in threes:
print(three)
#Try_it_yourself 4-8
print('Try it yourself 4-8\n')
cubes = []
for cube in range(1,11):
cubes.append(cube**3)
print(cubes)
#Try_it_yourself 4-9
print('Try it yourself 4-9')
#list comprehension
cubed = [quark**3 for quark in range(1,11)]
print(cubed)
#range() function generates a series of numbers
#from there, you can manipulate it in a list comprehension or other ways
#Try_it_yourself 4-10
print('Try it yourself 4-10: Slices')
colors = ['red', 'blue', 'orange', 'green', 'yellow', 'black', 'white']
print('The first three items in the list are:')
print(colors[0:3])
print('The middle three items in the list are:')
print(colors[2:5])
print('The last three items in the list are:')
print(colors[-3:])
#Try_it_yourself 4-11
print('Try it yourself 4-11: pizzas')
my_pizzas = ['cheese', 'pepperoni', 'mushroom', 'meat', 'veggie', 'cream']
friend_pizza = my_pizzas[:]
print(my_pizzas)
print(friend_pizza)
my_pizzas.append('frank')
friend_pizza.append('charlie')
print('My favorite pizzas are:')
for pizzas in my_pizzas:
print(pizzas)
print('\n')
for pizzas2 in friend_pizza:
print(pizzas2)
#Try_it_yourself 4-12
print('Try it yourself 4-12: tuples')
buffet = ( 'chicken', 'beef', 'cheese', 'meat', 'pork' )
for food in buffet:
print(food)
#buffet[1] = 'cow'
print('\n')
buffet = ( 'beer', 'water', 'cheese', 'meat', 'pork' )
for food in buffet:
print(food)
| true |
d758a3f7db1391f62de60fafdb8396d8977f1e70 | sudheer-sanagala/edx-python-course | /WEEK-01/square_of_numbers.py | 522 | 4.125 | 4 | """
Square of a given number
ex: 3^2 = 3*3 = 9; 5^2 = 5*5 = 25
"""
# using while-loop
x = 4
ans = 0
itersLeft = x # no of iterations remaining
while(itersLeft != 0): # while no of iterations not equal to 0
ans = ans + x # add the same number by itself for thje total no of loops
itersLeft = itersLeft - 1 # reduce the iteration loop by 1
print(str(x) + '*' + str(x) + ' = ' + str(ans))
# using for-loop
x = 4
ans = 0
for i in range(x):
ans = ans + x
print(str(x) + '*' + str(x) + ' = ' + str(ans))
| true |
1c6a01ffad2fabee405191e2e4d6e5a6f094d55f | meltedfork/Python-1 | /Python Assignments/Bike_Assignment/bike.py | 890 | 4.21875 | 4 | class bike(object):
def __init__(self,price, max_speed,miles = 0):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print self.price,self.max_speed,self.miles
return self
def ride(self):
print "Riding..."
self.miles+=10
print "Total miles on bike is",self.miles
return self
def reverse(self):
if self.miles < 5:
print "Cannot reverse below zero, you moron."
return self
print "Reversing..."
self.miles-=5
print "Total miles on bike is",self.miles
return self
Blue = bike(450,"25mph")
Red = bike(300, "15mph")
Yellow = bike(375, "22mph")
Blue.ride().ride().ride().reverse().displayInfo()
Red.ride().ride().reverse().reverse().displayInfo()
Yellow.reverse().reverse().reverse().displayInfo()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.