blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8026ce987b2ed319dee7faf702c82772be01e708 | dzhonapp/python_programs | /Loops/averageRainfall.py | 1,003 | 4.375 | 4 | '''Write a program that uses nested loops to collect data and calculate the average rainfall
over a period of years. The program should first ask for the number of years. The outer loop
will iterate once for each year. The inner loop will iterate twelve times, once for each month.
Each iteration of the inner loop will ask the user for the inches of rainfall for that month.
After all iterations, the program should display the number of months, the total inches of
rainfall, and the average rainfall per month for the entire period.'''
yearsToCalculate = int(input('How many years would you like to calculate rainfall? '))
monthlyRainfall = 0.0
for i in range(yearsToCalculate):
for month in range(1, 13):
print('Month #', month, end=" ")
monthlyRainfall += float(input('Please input the rainfall! '))
print('For year ', i+1, 'the total rainfall was: ', monthlyRainfall, 'inches')
print('The average rainfall was: ', format(monthlyRainfall/(yearsToCalculate*12, ',.2f')))
| true |
94b675bb81acbb2d07829c4180920a36bb601b8b | dzhonapp/python_programs | /Basics/Celsius to Fahreneit Temperature Converter.py | 429 | 4.25 | 4 | '''9. Celsius to Fahrenheit Temperature Converter
Write a program that converts Celsius temperatures to Fahrenheit temperatures. The formula
is as follows:
F =9/5C+32
The program should ask the user to enter a temperature in Celsius, and then display the
temperature converted to Fahrenheit.
'''
fahreneit= int(input('What is todays Temperature in Fahrenheit? '))
print('Todays temperature in Celcius: ', (fahreneit-32)/(9/5))
| true |
8d0ae7668e921e6e0047c1143cfbcdbf56f701a6 | dzhonapp/python_programs | /functions/milesPerGallon.py | 507 | 4.34375 | 4 | '''Miles-per-Gallon
A car’s miles-per-gallon (MPG) can be calculated with the following formula:
MPG = Miles driven / Gallons of gas used
Write a program that asks the user for the number of miles driven and the gallons of gas
used. It should calculate the car’s MPG and display the result.
'''
def mpgCalculate():
miles = float(input('How many miles you drove?'))
gallons= float(input('How many gallons of gas you filled? '))
return miles/gallons
print('Your MPG is: ', mpgCalculate()) | true |
ebec474eb20cfa6f338595a9bccf23b95a541dfd | dzhonapp/python_programs | /Loops/oceanLevels.py | 382 | 4.3125 | 4 | '''
Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an
application that displays the number of millimeters that the ocean will have risen each year
for the next 25 years.
'''
millimeters=1.6
for years in range(25):
print("Year #", years+1)
print('Millimeters risen so far: ', format(millimeters, ',.2f'))
millimeters+=1.6
| true |
7780f37587dc6bc07109b72911dc720f332268ad | garimadawar/LearnPython | /DynamicAvg.py | 262 | 4.1875 | 4 | print("Calculate the sum and average of two numbers")
number1 = float(input("Enter the first number"))
number2 = float(input("Enter the second number"))
print("the sum equals to " , number1 + number2)
print("average equals to " , (number1 + number2) / 2)
| true |
c1fa73caced9e5aeafe0e282ae88e6cb5c58a7fd | justinhinckfoot/Galvanize | /github/Unit 1 Exercise.py | 1,662 | 4.34375 | 4 | # Unit 1 Checkpoint
# Challenge 1
# Write a script that takes two user inputted numbers
# and prints "The first number is larger." or
# "The second number is larger." depending on which is larger.
# If the numbers are equal print "The two numbers are equal."
first = int(input('Enter first test value: '))
second = int(input('Enter second test value: '))
if first > second:
print('The first number is larger.')
elif first < second:
print('The second number is larger.')
else:
print('The two numbers are equal.')
# Challenge 2
# Write a script that computes the factorial
# of a user inputted positive numbers
# and prints the result.
user_input = int(input('Enter a value to compute its factorial: '))
total = 1
while user_input > 0:
total *= user_input
user_input -= 1
print(total)
# Challenge 3
# Write a script that computes and prints
# all of the positive divisors of a user inputted
# positive number from lowest to highest.
user_input = int(input('Enter a value to view all positive divisors: '))
x = 1
while user_input >= x:
if user_input % x == 0:
print(x)
x += 1
else:
x += 1
# Challenge 4
# Write a script that copmutes the greatest common divisor
# between two user inputted positive numbers and prints the result.
user_input = int(input('Please enter the first test value: '))
second_user_input = int(input('Please enter the second test value: '))
divisor = 1
gcd = 1
while divisor <= user_input or divisor <= second_user_input:
if user_input % divisor == 0 and second_user_input % divisor == 0:
gcd = divisor
divisor += 1
else:
divisor += 1
print(gcd)
| true |
95350d0995ec53e75601c3db0010b9da7ce90ebe | ricek/lpthw | /ex11/ex11-1.py | 265 | 4.40625 | 4 | # Prompt the user to enter their name
# end='' arg tells print function to not end the line
print("First Name:", end=' ')
first = input()
print("Last Name:", end=' ')
last = input()
# Prints out formatted string with the given input
print(f"Hello {first} {last}")
| true |
9013585a902e8aa2384f162b4a8c25e730429778 | arossholm/Py_Prep | /egg_problem.py | 1,347 | 4.125 | 4 | # A Dynamic Programming based Python Program for the Egg Dropping Puzzle
# http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
INT_MAX = 32767
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]
print("eggFloor")
print(eggFloor)
# We need one trial for one floor and 0 trials for 0 floors
for i in range(1, n + 1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
print("eggFloor2")
print(eggFloor)
# We always need j trials for one egg and j floors.
for j in range(1, k + 1):
eggFloor[1][j] = j
print("eggFloor3")
print(eggFloor)
# Fill rest of the entries in table using optimal substructure
# property
# eggFloor[egg(i)][floor(j)]
for i in range(2, n + 1):
for j in range(2, k + 1):
eggFloor[i][j] = INT_MAX
for x in range(1, j + 1):
res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x])
if res < eggFloor[i][j]:
eggFloor[i][j] = res
print (eggFloor)
# eggFloor[n][k] holds the result
print("eggFloor Resultat")
print (eggFloor)
return eggFloor[n][k]
print(eggDrop(2,10)) | true |
b073e30fb0c7b43e61845de6a0cb50ea6fe1d4f0 | Benature/Computational-Physics-Course-Code | /chp9/随机数/布朗运动1d.py | 1,082 | 4.25 | 4 | # 参考答案
# random walk,随机行走
import matplotlib.pyplot as plt
import random as rd
# %matplotlib inline
nsteps = 100 # input('number of steps in walk -> ')
nwalks = 100 # input('number of random walks -> ') 粒子数
seed = 10 # input('random number seed -> ')
rd.seed(seed)
steps = range(nsteps)
xrms = [0.0] * nsteps # mean squared distance
# loop over the number of walks being done
for i in range(nwalks):
x = [0] * nsteps # position at each step in walk
# loop over steps in this walk
for n in steps[1:]:
if rd.random() < 0.5:
x[n] = x[n-1] - 1
else:
x[n] = x[n-1] + 1
xrms[n] += (x[n]**2 - xrms[n]) / (i+1)
plt.plot(steps, x, 'o-')
for n in steps:
xrms[n] = xrms[n]**0.5
plt.title('random walk')
plt.xlabel('step number')
plt.ylabel('x')
plt.grid()
plt.figure()
plt.title('root-mean-squared distance for %d walks' % nwalks)
plt.plot(steps, xrms, '.')
plt.plot(steps, [n**0.5 for n in steps], '-')
plt.xlabel('step number')
plt.ylabel('root-mean-squared distance')
plt.grid()
plt.show()
| true |
0bb48e09dcbde0d8d604075bf650e9f2c42e9570 | jezzicrux/Python-Alumni-Course | /Excercises/inclass9_16.py | 508 | 4.28125 | 4 | #Making a function the adds three number and divdes by 3. (Pretty much average)
#This the function to get the average of the three numbers
avg = 0
def average(x,y,z):
avg=(x+y+z)/3
print(f"The average the three numbers is {avg}.")
def getting_numbs():
print ("Please enter your first number")
x = int(input(">>"))
print ("Please enter your second number")
y = int(input(">>"))
print ("Please enter your third number")
z = int(input(">>"))
average(x,y,z)
getting_numbs()
| true |
ef1b85d6df36bc6b251b94edd51c27c019bc63ec | jezzicrux/Python-Alumni-Course | /Excercises/triangle.py | 992 | 4.25 | 4 | def main():
print(f"Welcome to the triangle finder program")
print(f"Please enter 3 values for each side.")
print(f"Enter in value for side 1")
side1 = int(input(">> "))
print(f"Enter in value for side 2")
side2 = int(input(">> "))
print(f"Enter in value for side 3")
side3 = int(input(">> "))
triangle_check(side1,side2,side3)
def triangle_check(a,b,c):
if (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) == (c**2)):
print(f"All your sides can make a triangle! ALRIGHT!!!! Get it?")
elif (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) > (c**2)):
print(f"Look at your triangle. It's a cutie")
elif (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) < (c**2)):
print(f"Your triangle is so obtuse")
elif (a+b == c) or (a+c == b) or (c+b == a):
print("YOUR TRIANGLE IS OUT OF CONTROL. IT'S A REAL DEGENERATE!!")
else:
print("You aint got nutin' son!")
main()
| true |
17a546db017b9abc0b1853b1df5137167e6fb795 | jezzicrux/Python-Alumni-Course | /Excercises/HW1.py | 837 | 4.34375 | 4 | #a message stating it going to count the number on chickens
print("I will now count my chickens:")
#number of hens
print("Hens", 25 + 30 / 6)
#number of roosters
print("Roosters", 100 - 25 * 3 % 4)
#a message counting the number of eggs
print("Now I will count the eggs:")
#The math for calculating the number of eggs
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
#A message
print("Is it true that 3 + 2 < 5 - 7?")
#the answer
print(3 + 2 < 5 - 7)
#A question and then the answer. Answer is found with a math equation
print("What is 3 + 2?", 3 + 2)
#A question and then the answer. Answer is found with a math equation
print("What is 5 - 7?", 5 - 7)
#a message
print("Oh, that's why it's False.")
#
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
| true |
fb8125f73e2825f92d99ac10951cf857e8be7239 | jaredmckay17/DataStructuresAlgorithmsPractice | /binary_search.py | 1,120 | 4.125 | 4 | # Non-recrusive implementation
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
while first <= last:
midpoint = (first + last) // 2
if input_array[midpoint] == value:
return midpoint
else:
if value < input_array[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 19
test_val2 = 2
print binary_search(test_list, test_val1) # 5
print binary_search(test_list, test_val2) # -1
# Recursive implementation
def binary_search(input_array, value):
if len(input_array) == 0:
return False
else:
midpoint = len(input_array) // 2
if input_array[midpoint] == value:
return midpoint
else:
if value < input_array[midpoint]:
return binary_search(input_array[:midpoint], value)
else:
return binary_search(input_array[midpoint + 1:], value)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))
| true |
f791702e716e22da1327780cbc9e272648b5c2b8 | justinmyersdata/ProjectEuler | /7_Project_Euler.py | 607 | 4.25 | 4 |
def isprime(x):
'''Returns True if x is prime and false if x is composite'''
if x == 1:
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
else:
for y in range(3,int(x**(1/2))+1,2):
if x % y == 0:
return False
return True
def prime(n):
'''Returns the nth prime number'''
count = 0
num = 1
while count < n:
num +=1
if isprime(num):
count+=1
return(num)
prime(10001) | true |
ab65d41474186820587e216e5c91617621b599c2 | amitshipra/PyExercism | /recursion/examples.py | 743 | 4.28125 | 4 | __author__ = 'agupt15'
# Source: http://www.python-course.eu/python3_recursive_functions.php
#
#
#
#
# ## Example 1
#
# Write a recursive Python function that returns the sum of the first n integers.
###
def rec_add(num):
if num == 1:
return 1
return num + rec_add(num - 1)
print(rec_add(10))
### Exmple 1.1: Add numbers in a list using recursion.
def add_list(lst, total = 0):
return None
### Example 2
#
# Write a function which implements the Pascal's triangle:
#
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# 1 5 10 10 5 1
def pascal_triangle(row_count):
return None
| true |
5bea9d32a0f174543c3d734002f8e856d6ac6279 | gurkiratsandhu/Assignment_Daily | /assignment7 (1).py | 1,521 | 4.15625 | 4 | #(Q.1)- Create a function to calculate the area of a circle by taking radius from user.
def area():
pi = 3.14
radius = float(input("enter radius: "))
area = pi*radius**2
print("Area of a circle = ",area)
area()
#(Q.2)- Write a function “perfect()” that determines if parameter number is a perfect number.
#Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
#[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself),
#sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
def perfect(n):
sum=0
for x in range(1,n):
if n % x == 0:
sum = sum + x
if sum == n:
print("perfect Number:",n)
for i in range(1,1001):
#(Q.3)- Print multiplication table of 12 using recursion.
def table():
number=int(input("enetr value"))
for i in range(1,11):
result=number*i
print("%d * %d = %d"%(number,i,result))
table()
#(Q.4)- Write a function to calculate power of a number raised to other ( a^b ) using recursion.
def power():
i = int(input("enter any no.: "))
n = int(input("enter power of : "))
result = i**n
print("power of %d: %d"%(i,result))
power()
#(Q.5)- Write a function to find factorial of a number but also store the factorials calculated in a dictionary.
def factorial(number):
if number==1 or number==0:
return 1
else:
f = number*factorial(number-1)
return f
call = int(input("enter any no."))
fact=factorial(call)
print("factorial of %d: %d"%(call,fact))
| true |
8263b10b5c958eb40ebc8c67a4aafecf5b18a6f8 | rhysJD/CC1404_Practicals | /Prac 2/exceptions_demo.py | 785 | 4.21875 | 4 | """
CP1404 - Practical 2
Rhys Donaldson
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
denominator = int(input("Denominator cannot be zero. PLease enter a new number: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.")
#Q1: ValueError occurs when the input is not an integer. Putting in symbols, letter, or decimals will get this number
#Q2: This occurs when the denominator is zero and the program attempts to divide by it. Fixed by checking that it doesnt contain a zero, and asking for a new input if it does. | true |
685f5b4ead65493c2689d479df91bbc9af93aa0c | kiwi-33/Programming_1_practicals | /p12-13/p12p3(+pseudo).py | 639 | 4.28125 | 4 | '''define function for getting approx square root
prompt for input and convert to float
check if greater than 0
call function with (input, self selected tolerance)
else print message'''
def sq(number, epsilon):
root = 0.0
step = epsilon**2
while abs(number-root**2) >= epsilon and root <= number:
root += step
if abs(number-root**2) < epsilon:
print('Approx. square root of ', number, 'is', root)
else:
print('Failed to find the square root of ',number)
number = float(input('Enter a floating point number: '))
if number >= 0:
sq(number, .01)
else:
('An appropriate error message') | true |
ddb2f13ed4d056934a51cdc65a58aa3c7eabe411 | kiwi-33/Programming_1_practicals | /p14-15/p15p3.py | 568 | 4.1875 | 4 | '''define the function
prompt for input
enter while loop:
enter for loop, limit = input:
print statement that shows progression towards the base case and calls function
prompt for input'''
def series(x):
if x == 0:
return 13
elif x == 1:
return 8
else:
return((series(x-2)) + ((13)*(series(x-1))))
number = int(input("Enter a number: "))
while number >= 0:
for i in range(0, number):
print("Term number", i, "in series of length", number, "is:", series(i))
number = int(input("Enter a number: "))
| true |
68390cc2272a00e24b578960ba52c76c1a3265e4 | Kadus90/CS50 | /pset6/mario/less/mario.py | 899 | 4.21875 | 4 | from cs50 import get_int
def main():
# Get an integer between 1 - 8
height = get_positive_int("Height: ")
# Print bricks
print_bricks(height)
def get_positive_int(prompt):
# Use get_int to get an integer from the user
n = get_int(prompt)
# While not in the proper range
while n < 1 or n > 8:
n = get_int(prompt)
return n
def print_bricks(height):
# Initialize spaces to height
spaces = height
for i in range(height):
# Set spaces to the current row
spaces -= 1
for j in range(spaces):
# Print the spaces while omitting the new line
print(" ", end="")
# Set the bricks
bricks = height - spaces
for k in range(bricks):
# Print the bricks
print("#", end="")
# Create a new line
print("")
if __name__ == "__main__":
main()
| true |
ccb9824ec5d7ffeeb123b86914383d174eb63e03 | alcoccoque/Homeworks | /hw5/ylwrbxsn-python_online_task_5_exercise_2/task_5_ex_2.py | 692 | 4.5625 | 5 | """
Task05_2
Create function arithm_progression_product, which outputs the product of multiplying elements of arithmetic progression sequence.
The function requires 3 parameters:
1. initial element of progression - a1
2. progression step - t
3. number of elements in arithmetic progression sequence - n
Example,
For a1 = 5, t = 3, n = 4 multiplication equals to 5*8*11*14 = 6160
Note:
The output of your program should contain only the multiplication product
Usage of loops is obligatory
"""
from math import prod
def arithm_progression_product(a1, t, n):
res = []
tmp = a1
for i in range(n):
res.append(tmp)
tmp += t
return prod(res)
| true |
a0716844aecf22b76731ae339ea52037ba170bb9 | alcoccoque/Homeworks | /hw10/ylwrbxsn-python_online_task_10_exercise_3/task_10_ex_3.py | 2,102 | 4.375 | 4 | """
File `data/students.csv` stores information about students in CSV format.
This file contains the student’s names, age and average mark.
1. Implement a function get_top_performers which receives file path and
returns names of top performer students.
Example:
def get_top_performers(file_path, number_of_top_students=5):
pass
print(get_top_performers("students.csv"))
Result:
['Teresa Jones', 'Richard Snider', 'Jessica Dubose', 'Heather Garcia',
'Joseph Head']
2. Implement a function write_students_age_desc which receives the file path
with students info and writes CSV student information to the new file in
descending order of age.
Example:
def write_students_age_desc(file_path, output_file):
pass
Content of the resulting file:
student name,age,average mark
Verdell Crawford,30,8.86
Brenda Silva,30,7.53
...
Lindsey Cummings,18,6.88
Raymond Soileau,18,7.27
"""
import csv
from operator import itemgetter
def get_top_performers(file_path: str, number_of_top_students: int = 5) -> list:
with open(file_path, newline='') as file:
csv_data = list(csv.reader(file, quoting = csv.QUOTE_ALL))
csv_data = csv_data[1:]
csv_data = [[i[0], int(i[1]), float(i[2])] for i in csv_data]
csv_data = sorted(csv_data, key=itemgetter(2), reverse=True)
return [x[0] for x in csv_data[:number_of_top_students] if x]
def write_students_age_desc(file_path: str, output_file: str) -> None:
with open(file_path, newline='') as file:
csv_data = list(csv.reader(file, quoting=csv.QUOTE_ALL))
info = csv_data[0]
csv_data = csv_data[1:]
csv_data = [[i[0], int(i[1]), float(i[2])] for i in csv_data]
csv_data = sorted(csv_data, key=itemgetter(1), reverse=True)
with open(f'{output_file}', 'w', newline='') as wfile:
writer = csv.writer(wfile, delimiter=',')
writer.writerow(info)
for row in csv_data:
if row:
writer.writerow(row)
else:
continue
# print(get_top_performers('students.csv', 3))
# write_students_age_desc('students.csv', 'out.csv') | true |
28c998e30f41f350345d22934294b93fda8f3dc2 | alcoccoque/Homeworks | /hw9/ylwrbxsn-python_online_task_9_exercise_4/task_9_ex_4.py | 2,094 | 4.28125 | 4 | """
Implement a bunch of functions which receive a changeable number of strings and return next
parameters:
1) characters that appear in all strings
2) characters that appear in at least one string
3) characters that appear at least in two strings
Note: raise ValueError if there are less than two strings
4) characters of alphabet, that were not used in any string
Note: use `string.ascii_lowercase` for list of alphabet letters
Note: raise TypeError in case of wrong data type
Examples,
```python
test_strings = ["hello", "world", "python", ]
print(chars_in_all(*test_strings))
>>> {'o'}
print(chars_in_one(*test_strings))
>>> {'d', 'e', 'h', 'l', 'n', 'o', 'p', 'r', 't', 'w', 'y'}
print(chars_in_two(*test_strings))
>>> {'h', 'l', 'o'}
print(not_used_chars(*test_strings))
>>> {'q', 'k', 'g', 'f', 'j', 'u', 'a', 'c', 'x', 'm', 'v', 's', 'b', 'z', 'i'}
"""
import string
def chars_in_all(*strings):
if len(strings) >= 2:
chars_inall = set()
uniquechars = set(''.join(strings))
for i in uniquechars:
if all(i if i in x else False for x in strings):
chars_inall.add(i)
return chars_inall
raise ValueError
def chars_in_one(*strings):
return set(''.join(strings))
def chars_in_two(*strings):
if len(strings) >= 2:
chars_inall = set()
uniquechars = set(''.join(strings))
for i in uniquechars:
if len([i for x in strings if i in x]) >= 2:
chars_inall.add(i)
return chars_inall
raise ValueError
def not_used_chars(*strings):
strings = set(''.join([x.lower() for x in strings if x.isalpha()]))
list_of_str = set()
for i in string.ascii_lowercase:
if i not in strings:
list_of_str.add(i)
else:
continue
return list_of_str
#
# print(chars_in_all('asd', 'asas','asd'))
# print(chars_in_one('asd', 'asdasdd','asdddd'))
# print(chars_in_two('asd', 'asas','bbbbbb'))
# print(not_used_chars('asd', 'asas','bbbbbb'))
# print() | true |
d5b3eb35448994bbe027230cf715f633e3bbef90 | alcoccoque/Homeworks | /hw4/ylwrbxsn-python_online_task_4_exercise_8/task_4_ex_8.py | 638 | 4.1875 | 4 | """
Task 04-Task 1.8
Implement a function which takes a list of elements and returns a list of tuples containing pairs of this elements.
Pairs should be formed as in the example. If there is only one element in the list return `None`
instead.
Using zip() is prohibited.
Examples:
>>> get_pairs([1, 2, 3, 8, 9])
[(1, 2), (2, 3), (3, 8), (8, 9)]
>>> get_pairs(['need', 'to', 'sleep', 'more'])
[('need', 'to'), ('to', 'sleep'), ('sleep', 'more')]
>>> get_pairs([1])
None
"""
def get_pairs(lst: list) -> list:
if len(lst) > 1:
return [(lst[i], lst[i + 1]) for i in range(len(lst) - 1)]
return None
| true |
0039bfc1dae3f74a8116973fade7541d37435561 | mandypepe/py_data | /spark_querin_dataset.py | 1,071 | 4.1875 | 4 | # First we need to import the following Row class
from pyspark.sql import SQLContext, Row
# Create a RDD peopleAge,
# when this is done the RDD will
# be partitioned into three partitions
peopleAge = sc.textFile("examples/src/main/resources/people.txt")
# Since name and age are separated by a comma let's split them
parts = peopleAge.map(lambda l: l.split(","))
# Every line in the file will represent a row
# with 2 columns name and age.
# After this line will have a table called people
people = parts.map(lambda p: Row(name=p[0], age=int(p[1])))
# Using the RDD create a DataFrame
schemaPeople = sqlContext.createDataFrame(people)
# In order to do sql query on a dataframe,
# you need to register it as a table
schemaPeople.registerTempTable("people")
# Finally we are ready to use the DataFrame.
# Let's query the adults that are aged between 21 and 50
adults = sqlContext.sql("SELECT name FROM people \
WHERE age >= 21 AND age <= 50")
# loop through names and ages
adults = adults.map(lambda p: "Name: " + p.name)
for Adult in adults.collect():
print Adult | true |
2a51577b5291d2667e285d799a1cb47d0dec5c88 | lunawarrior/python_book | /Exercises/6/1_turn_clockwise.py | 721 | 4.28125 | 4 |
'''
This is the first exercise in chapter 6:
The four compass points can be abbreviated by single-letter strings as “N”, “E”, “S”, and “W”.
Write a function turn_clockwise that takes one of these four compass points as its parameter,
and returns the next compass point in the clockwise direction. Here are some tests that should pass:
'''
from test import test
# Define your turn_clockiwse function here
# Here are the tests
test(turn_clockwise("N") == "E")
test(turn_clockwise("W") == "N")
test(turn_clockwise("E") == "S")
''' When you have those working, other values should return None. Uncomment the below tests '''
# test(turn_clockwise(42) == None)
# test(turn_clockwise("rubbish") == None) | true |
b735e871863e7f2fe735293b21f01ea0158bb9d5 | quydau35/quydau35.github.io | /ds/chunk_6/python_modules.py | 2,618 | 4.53125 | 5 | """
# Python Modules\n
What is a Module?\n
Consider a module to be the same as a code library.\n
A file containing a set of functions you want to include in your application.\n
# Create a Module\n
To create a module just save the code you want in a file with the file extension ```.py```:\n
```
# Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
```
# Use a Module\n
Now we can use the module we just created, by using the ```import``` statement:\n
```
# Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
```
Note: When using a function from a module, use the syntax: ```module_name.function_name```.\n
# Variables in Module\n
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):\n
```
# Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
```
```
# Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
```
# Naming a Module\n
You can name the module file whatever you like, but it must have the file extension ```.py```\n
# Re-naming a Module\n
You can create an ```alias``` when you import a module, by using the ```as``` keyword:\n
```
# Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
```
# Built-in Modules\n
There are several built-in modules in Python, which you can import whenever you like.\n
```
# Import and use the platform module:
import platform
x = platform.system()
print(x)
```
# Using the ```dir()``` Function\n
There is a built-in function to list all the function names (or variable names) in a module. The ```dir()``` function:\n
```
# List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
```
Note: The ```dir()``` function can be used on all modules, also the ones you create yourself.\n
# Import From Module\n
You can choose to import only parts from a module, by using the from keyword.\n
```
# The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
```
```
# Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
```
Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: ```person1["age"]```, not ```mymodule.person1["age"]```\n
""" | true |
fa096dffbef3c9578b693c3b2c07014a53b94ec6 | sandycamilo/SPD1.4 | /Complexity_Analysis/merge_lists.py | 1,027 | 4.125 | 4 | # Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
# Input: 1->2->4, 1->3->4
#Create a new linked list:
# Output: 1->1->2->3->4->4
# O(1)
class Solution(object):
def mergeTwoLists(self, l1, l2):
head = ListNode(0)
ptr = head #reference to the head
while True:
if l1 is None and l2 is None:
break #nothing to merge
elif l1 is None:
ptr.next = l2
break
elif l2 is None:
ptr.next = l1
else:
smallerVal = 0
if l1.val < l2.va:
smallerVal = l1.val
l1 = l1.next
else:
smallerVal = l2.val
l2 = l2.next
newNode = ListNode(smallerVal)
ptr.next = newNode
ptr = prt.next
return head.next
| true |
e85c5ae1101d7e3e25ccd570231e3e04e5e32d74 | JLtheking/cpy5python | /practical03/q1_display_reverse.py | 899 | 4.3125 | 4 | # Filename: q1_display_reverse.py
# Author: Justin Leow
# Created: 19/2/2013
# Modified: 22/2/2013
# Description: Displays an integer in reverse order
##Input a positive integer: 5627631
##1367265
##Input a positive integer: nope
##Input is not an integer. Utilizing default value of 6593
##3956
##Input a positive integer: quit
def newString(inputString):
tempInput = input(inputString)
if(tempInput=="quit"):
quit()
try:
int(tempInput)
except:
print("Input is not an integer. Utilizing default value of 6593")
return 6593
tempInput = int(tempInput)
if(tempInput < 0):
print("Input is not positive. Utilizing default value of 6593")
return 6593
else:
return tempInput
# main
while(True):
#get user input
myNumber = str(newString("Input a positive integer: "))
print (int(myNumber[::-1]))
| true |
bf920db934db1952d9c741ce8e8335a47dae2d0f | JLtheking/cpy5python | /08_OOP/bankaccount.py | 2,339 | 4.3125 | 4 | #bankaccount.py
class Account():
'''Bank account class'''
def __init__(self,account_no,balance):
'''constructor method'''
#double underscore makes it a hidden private attribute
self.__account_no = account_no
self.__balance = balance
def get_account_no(self):
'''accessor method to retrieve account no'''
return self.__account_no
def get_balance(self):
return self.__balance
def deposit(self,amount):
'''modifier/mutator method to update balance'''
self.__balance += amount
print("")
def withdraw(self,amount):
self.__balance -= amount
print("")
#no public method to change account number, for safety because usually you do not change account number after creation
def display(self):
'''helper/support method to show account info'''
print("Account No:",self.__account_no)
print("Balance:",self.__balance)
class Savings_Account(Account):
def __init__(self,account_no,balance,interest):
super().__init__(account_no,balance)
self.__interest = interest
def withdraw(self,amount):
if amount > self.get_balance():
print("Your account does not have sufficient funds")
else:
super().withdraw(amount)
def calc_interest(self):
self.deposit(self.get_balance() * self.__interest)
def display(self):
print("Account type: Savings Account")
super().display()
print("")
class Current_Account(Account):
def __init__(self,account_no,balance,overdraft_limit):
super().__init__(account_no,balance)
self.__overdraft_limit = overdraft_limit
def withdraw(self,amount):
if (self.get_balance() - amount) < (self.__overdraft_limit * -1):
print("The amount you have intended to withdraw, ",amount,"has exceeded the overdraft limit for your account, ",self.__overdraft_limit,".")
else:
super().withdraw(amount)
def display(self):
print("Account type: Current Account")
super().display()
print("Overdraft limit:",self.__overdraft_limit)
print("")
#main
acct1 = Savings_Account("S01",5000,.1)
acct1.display()
acct1.calc_interest()
acct1.display()
acct1.calc_interest()
acct1.display()
acct1.withdraw(3000)
acct1.display()
acct1.withdraw(3000)
acct1.display()
print("")
acct2 = Current_Account("C01",5000,3000)
acct2.display()
acct2.withdraw(3000)
acct2.display()
acct2.withdraw(3000)
acct2.display()
acct2.withdraw(3000)
acct2.display() | true |
73b2fa58628caf0682ba2fbcca4d44c25662c460 | JLtheking/cpy5python | /practical01/q1_fahrenheit_to_celsius.py | 634 | 4.25 | 4 | # Filename: q1_fahrenheit_to_celsius.py
# Author: Justin Leow
# Created: 22/1/2013
# Modified: 22/1/2013
# Description: Program which converts an input of temperature in farenheit to an
# output in celcius
# main
while(True):
#get user input farenheit
fInput = input(["Input temperature in farenheit, or 'quit' to quit"])
if(fInput=="quit"):
quit()
try:
float(fInput)
except:
print("please input a number")
else:
fInput=float(fInput)
#calculate celcius
cOutput=(5/9)*(fInput-32)
#display result
print("{0:.2f}".format(cOutput)+"\n")
| true |
af47a62770895f3239b6a0505b1cce9509a903ad | mmutiso/digital-factory | /darts.py | 773 | 4.28125 | 4 | import math
def square(val):
return math.pow(val,2)
def score(x, y):
'''
Give a score given X and Y co-ordinates
Rules
X range -10,10
Y range -10, 10
The problem is finding the radius of the circle created by a given point x,y
then compare if the point is inside the circle using pythagoras theorem
where a^2 + b^2 = c^2
'''
if (square(x) + square(y)) <= square(1):
return 10
elif ((square(x) + square(y)) <= square(5)) and ((square(x) + square(y)) > square(1)):
return 5
elif ((square(x) + square(y)) <= square(10)) and ((square(x) + square(y)) > square(5)):
return 1
else:
return 0
if __name__ == "__main__":
result = score(0,10)
print(result)
assert result == 1 | true |
d239595956f2ebdd76d628be8aae6892ba43e352 | Andeleisha/dicts-restaurant-ratings | /ratings.py | 1,534 | 4.15625 | 4 | """Restaurant rating lister."""
# put your code here
def build_dict_restaurants(filename, dictionary):
"""Takes a file and creates a dictionary of restaurants as keys and ratings as values"""
with open(filename) as restaurant_ratings:
for line in restaurant_ratings:
line = line.strip()
line = line.split(":")
dictionary[line[0]] = line[1]
return dictionary
def print_restuarant_ratings(dictionary):
"""Given a dictionary it alphebatizes the keys"""
alpha_list = sorted(dictionary.keys())
for restaurant in alpha_list:
print("{} is rated at {}".format(restaurant, dictionary[restaurant]))
def add_rating(dictionary):
"""add new entry into dictionary"""
new_restaurant_name = input("What's your new restaurant? ")
new_restaurant_score = input("What rating would you give it? ")
dictionary[new_restaurant_name] = dictionary.get(new_restaurant_name, new_restaurant_score)
return dictionary
#print("Thank you for your rating!")
# dict_restaurants = {}
def ratings_loop(fname):
dict_restaurants = {}
dict_restaurants = build_dict_restaurants(fname, dict_restaurants)
print_restuarant_ratings(build_dict_restaurants(fname, dict_restaurants))
add_rating(dict_restaurants)
print("Here is the new list of restaurant ratings.")
print_restuarant_ratings(dict_restaurants)
ratings_loop('scores.txt')
# dict[upper_version] = [rating, "string_user_input"]
# dict[upper][0] == rating
# dict[upper][1] == input
# sort(dict) => keys in actual sorted order
# dict[key][1] => printed version | true |
f12370d769339351a1e01eb6189c6e45914fbd67 | sukritishah15/DS-Algo-Point | /Python/armstrong_number.py | 585 | 4.1875 | 4 | n = int(input())
l = len(str(n))
s = 0
temp = n
while temp > 0:
s += (temp%10) ** l
temp //= 10
if n == s:
print("Armstrong number")
else:
print("Not an armstrong number")
'''
Check whether a number entered by the user is Armstrong or not.
A positive integer of n digits is called an Armstrong Number (of order n) if:
abcd.. = a^n + b^n + c^n + d^n + ...
Sample Input:
n = 153
Sample Output:
Armstrong number
Explanation: 153 is an armstrong number because, 153= 1x1x1 + 5x5x5 + 3x3x3 i.e. 1^3+5^3+3^3 = 153.
Time complexity : O(log N)
Space complexity: O(1)
''' | true |
ec34d801bf68c970a600d37ae6cc5a6e04fee1f6 | sukritishah15/DS-Algo-Point | /Python/majority_element.py | 733 | 4.375 | 4 | # Python problem to find majority element in an array.
def majorityElement(nums, n):
nums.sort()
for i in range(0, n):
if(i+int(n/2)) < n and nums[i] == nums[i+int(n/2)]:
return nums[i]
return None
n = int(input("Enter the total number of elements\n"))
print('Enter a list of '+str(n) + ' number in a single line')
arr = list(map(int, input().split()))
result = majorityElement(arr, n)
if (result == None):
print("No majority element")
else:
print("Majority element is", result)
'''
Time complexity ==> O(nlogn)
Space complexity=> O(1)
I/O -->
Enter the total number of elements
10
Enter a list of 10 number in a single line
1 1 3 1 2 1 1 6 5 1
O/P -->
Majority element is 1
'''
| true |
c1d8ba9a81d785d6a77de20d075150f371825ba7 | sukritishah15/DS-Algo-Point | /Python/automorphic.py | 423 | 4.125 | 4 | # Automorphic Number: The last digits of thr square of the number is equal to the digit itself
n=int(input("Enter the number: "))
sq= n**2
l=len(str(n))
ld=sq%pow(10,l)
if (ld==n):
print("Automorphic Number")
else:
print("Not a automorphic number")
"""
I/O
Enter the number: 25
Automorphic Number
Enter the number: 12
Not a automorphic number
Time complexity- O(1)
Space Complexity- O(1)
""" | true |
ccfe5912c428bbaf377448c3b4961ce2d3c4e838 | sukritishah15/DS-Algo-Point | /Python/inordder.py | 608 | 4.28125 | 4 | class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "\nInorder traversal of binary tree is"
printInorder(root)
'''
Time Complexity - O(N)
Space Complexity - O(N)
Input - Taken in the Code .
Output -Inorder traversal of binary tree is
4 2 5 1 3
'''
| true |
00d927ab9488e3d8954720d71ee8272394f99739 | sukritishah15/DS-Algo-Point | /Python/harmonic.py | 372 | 4.3125 | 4 | # Sum of harmonic series
def sumHarmonic(n):
i = 1
sum = 0.0
for i in range(1, n+1):
sum = sum + 1/i;
return sum;
n = int(input("First term :"))
print("Sum of the Harmonic Series :", sumHarmonic(n))
""""
Example:
First term :
6
Sum of the Harmonic Series : 2.4499999999999997
.........
Time Complexity :- O(logn)
Space Complexity :- O(n)
""" | true |
aabf2577bd44425c702d6a670ba21dcef79c4aa0 | dboldt7/PRG105 | /Banana revised.py | 1,207 | 4.21875 | 4 | """"
Banana Bread Recipe:
2 cups of flour
1 teaspoon of baking soda
0.25 teaspoons of salt
0.5 cups of butter
0.75 cups of brown sugar
2 eggs
2.33 bananas
Recipe produces 12 servings of bread
Write a program that asks the user how many servings they want
Program displays the ingredients needed to make the desired amount
"""
Servings = 12
Flour = 2
bakingSoda = 1
salt = 0.25
butter = 0.5
sugar = 0.75
egg = 2
banana = 2.33
desiredServings = int(input("How many servings do you want? "))
percentChange = (desiredServings - Servings) / Servings
if percentChange == 0:
percentChange = 1
elif percentChange > 0:
percentChange = 1 + percentChange
else:
percentChange = percentChange * -1
print("")
print("Ingredients Needed:\n")
print((Flour * percentChange), " cups of flour")
print(format(bakingSoda * percentChange, ".1f"), "teaspoons of baking soda")
print(format(salt * percentChange, ".1f"), " teaspoons of salt")
print(format(butter * percentChange, ".1f"), " cups of butter")
print(format(sugar * percentChange, ".1f"), " cups of sugar")
print(format(egg * percentChange, ".1f"), " eggs")
print(format(banana * percentChange, ".1f"), " bananas")
| true |
c3920afa242227c20a26747c5903249ca2fb2687 | AliMazhar110/Python-Projects | /Guess-a-number/main.py | 1,575 | 4.1875 | 4 | #Number Guessing Game Objectives:
from art import logo
import random
from os import system
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player.
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).
while 1==1:
system('cls')
print(logo)
number = random.randint(1,100)
print("\nGuess a number between 1 - 100");
level = input("\nSelect a level 'EASY' or 'HARD' = ").lower()
if level == "easy":
attempts = 10
else:
attempts = 5
finish = False
print(f"\nYou have {attempts} attempts.")
while not finish:
if attempts==0:
print("\nNo Attempts Left. You Lost.")
print(f"The number was {number}")
finish = True
continue
guess = int(input("\nGuess a number = "))
if guess == number:
print(f"\nCorrect. You got it. Number was {number}")
finish = True
elif guess > number:
print("Too high.")
elif guess < number:
print("Too low")
attempts-=1
print(f"attempts Left: {attempts}")
again = input("\nDo you want to play again(yes/no)? = ")
if(again!="yes"):
break
else:
continue
| true |
233d0067b828c7d7a12c6fd0d7c8e5f2f3d5476a | Elyseum/python-crash-course | /ch9/car.py | 1,512 | 4.25 | 4 | """ Modifying class state """
class Car():
""" Simple car """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
""" Formatting a descriptive name """
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
""" print mileage """
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
""" Set odometer to given mileage, don't allow roll back! """
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
""" Add given amount to odometer """
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
MY_NEW_CAR = Car('audi', 'a4', 2016)
print(MY_NEW_CAR.get_descriptive_name())
MY_NEW_CAR.read_odometer()
MY_NEW_CAR.odometer_reading = 23
MY_NEW_CAR.read_odometer()
MY_NEW_CAR.update_odometer(46)
MY_NEW_CAR.read_odometer()
MY_NEW_CAR.update_odometer(23)
MY_USED_CAR = Car('subaru', 'outback', 2013)
print(MY_USED_CAR.get_descriptive_name())
MY_USED_CAR.update_odometer(23500)
MY_USED_CAR.read_odometer()
MY_USED_CAR.increment_odometer(100)
MY_USED_CAR.read_odometer()
| true |
f21caae41042f33a4a60ea9ebcc8211b85d62bd2 | jormao/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 939 | 4.4375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
This module have a function that prints My name is <first name> <last name>
prototype: def say_my_name(first_name, last_name=""):
"""
def say_my_name(first_name, last_name=""):
""" function that prints My name is <first name> <last name>
first_name and last_name must be strings otherwise,
raise a TypeError exception with the message first_name must be a string
or last_name must be a string
Do not allowed to import any module
Args:
first name: first parameter
lasta name: second parameter
Raises:
TypeError: first_name must be a string
TypeError: last_name must be a string
"""
if type(first_name) is not str:
raise TypeError('first_name must be a string')
if type(last_name) is not str:
raise TypeError('last_name must be a string')
print("My name is {} {}".format(first_name, last_name))
| true |
48af3a3a7920e8b0fc67cca325cc3d1305db77d1 | PureWater100/DATA-690-WANG | /ass_2/ass2.py | 1,413 | 4.21875 | 4 | # python file for assignment 2
# code from the jupyter notebook
user_inputs = []
MAX_TRY = 11
for i in range(1, MAX_TRY):
while True:
try:
user_input = input("Please enter an integer:")
in_input = int(user_input)
break
except:
print("Please retry (only integer accepted)")
user_inputs.append(user_input)
print(f"You have entered integer #{i}:", user_input)
ints = [int(item) for item in user_inputs] #cast each element into an integer
print("Overall, you have entered:", ints) #display looks cleaner after casting
ints.sort(reverse = True)
print("The minimum is:", ints[9])
print("The maximum is:", ints[0])
the_max = ints[0]
the_min = ints[9]
print("The range is:", the_max - the_min)
# Python program to find sum of elements in list
sum = 0
# Iterate each element in list
# and add them in variale sum
for ele in range(0, len(ints)):
sum += ints[ele]
mean = sum / 10
print("The mean is:", mean)
sum_diff = 0
for ele in range(0, len(ints)):
sum_diff += (ints[ele] - mean) ** 2
var = sum_diff / 9
# Format variance to display only 2 decimals
variance = "The variance is: {:.2f}"
print(variance.format(var))
# Get standard deviation by raising variance to .5 power
stan_dev = var ** .5
# Format standard deviation to 2 decimals
stand_dev = "The standard deviation is: {:.2f}"
print(stand_dev.format(stan_dev)) | true |
5c3e03c9ec8a0c41e68d542f959098169adf612f | selvendiranj-zz/python-tutorial | /hello-world/exceptions.py | 2,018 | 4.3125 | 4 | """
Python provides two very important features to handle any unexpected error in your Python programs
and to add debugging capabilities in them
Exception Handling
Assertions
"""
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0), "Colder than absolute zero!"
return ((Temperature - 273) * 1.8) + 32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
# print KelvinToFahrenheit(-5)
# Handling an exception
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
# finally block
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
# Argument of an Exception
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz")
# Raising an Exceptions.
def functionName(level):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
try:
# Business Logic here...
print("Business Logic here...")
except "Invalid level!":
# Exception handling here...
print("Exception handling here...")
else:
# Rest of the code here...
print("Rest of the code here...")
# User - Defined Exceptions
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Networkerror("Bad hostname")
except Networkerror, e:
print e.args
| true |
c16a4d2cb51863a144f5a9e33c46467620b8abd9 | LogSigma/unipy | /docstring.py | 916 | 4.5 | 4 | def func(*args, **kwargs):
"""
Summary
This function splits an Iterable into the given size of multiple chunks.
The items of An iterable should be the same type.
Parameters
----------
iterable: Iterable
An Iterable to split.
how: {'equal', 'remaining'}
The method to split.
'equal' is to split chunks with the approximate length
within the given size.
'remaining' is to split chunks with the given size,
and the remains are bound as the last chunk.
size: int
The number of chunks.
Returns
-------
list
A list of chunks.
See Also
--------
Examples
--------
>>> up.splitter(list(range(10)), how='equal', size=3)
[(0, 1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> up.splitter(list(range(10)), how='remaining', size=3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]
"""
pass
| true |
9d07ce046e2c46a928da07c2d6578f7e91d1df9b | kristinamb15/cracking-the-coding-interview | /1_ArraysStrings/1.4.py | 1,286 | 4.15625 | 4 | # 1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
# The palindrome does not need to be limited to just dictionary words.
# You can ignore casing and non-letter characters.
import unittest
# Solution 1
# O(N)
def palindrome_perm(mystring):
mystring = mystring.lower()
char_dict = {char:0 for char in mystring if char.isalpha()}
for char in mystring:
if char.isalpha():
char_dict[char] += 1
evens = 0
odds = 0
for key in char_dict:
if char_dict[key] % 2 == 0:
evens += 1
else:
odds += 1
result = (odds == 1 or odds == 0)
return result
# Testing
class Tests(unittest.TestCase):
def test_with_space_true(self):
self.assertTrue(palindrome_perm('taco cat'))
def test_with_space_false(self):
self.assertFalse(palindrome_perm('I am not a palindrome'))
def test_no_space_true(self):
self.assertTrue(palindrome_perm('racecar'))
def test_no_space_false(self):
self.assertFalse(palindrome_perm('nope'))
def test_with_punc_true(self):
self.assertTrue(palindrome_perm('Was it a cat I saw?'))
if __name__ == '__main__':
unittest.main()
| true |
616067b46918e0940fcf1805d8e3ae12ab0bbf2f | ShehabAhmedSayem/Rosalind-Chapterwise | /Chapter 1/ba1a.py | 691 | 4.15625 | 4 | # Problem Name: Compute the Number of Times a Pattern Appears in a Text
def read_input_from_file(file_name):
with open(file_name, 'r') as file:
string = file.readline().strip()
pattern = file.readline().strip()
return string, pattern
def occurrence(string, pattern):
"""
string: input string
pattern: pattern to search
"""
count = 0
l = len(string)
p = len(pattern)
for start in range(l-p+1):
if(string[start:start+p] == pattern):
count += 1
return count
if __name__ == "__main__":
string, pattern = read_input_from_file("in.txt")
print(occurrence(string, pattern)) | true |
864401be5d0d0ba69503da811f67cebe37edbaa4 | Mustafa-Filiz/HackerRank--Edabit--CodeWars | /Codewars_12_ROT13.py | 1,234 | 4.65625 | 5 | # ROT13
"""
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
Please note that using encode is considered cheating.
"""
def rot13(message):
import string
cipher = ""
for i in message:
if i in string.ascii_uppercase:
if string.ascii_uppercase.index(i) < 13:
cipher += string.ascii_uppercase[string.ascii_uppercase.index(i) + 13]
else:
cipher += string.ascii_uppercase[string.ascii_uppercase.index(i) - 13]
elif i in string.ascii_lowercase:
if string.ascii_lowercase.index(i) < 13:
cipher += string.ascii_lowercase[string.ascii_lowercase.index(i) + 13]
else:
cipher += string.ascii_lowercase[string.ascii_lowercase.index(i) - 13]
else:
cipher += i
return cipher | true |
d8ad0945acb41da09f474325b940b6b289bd91ad | newemailjdm/intro_python | /121515/conditional.py | 337 | 4.21875 | 4 |
first_name = input("What's your first name")
name_length = len(first_name)
if name_length > 10:
print("That's a long name!")
elif name_length > 3:
print("Nice, that's a name of medium length.")
elif name_length == 3:
print("That's a short name.")
else:
print("Are you sure those aren't your initials?")
| true |
83a1611d3673951ca106228ea3b28e55c97a85b1 | AnkurPokhrel8/LinkedList | /LinkedList.py | 2,012 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Ankur Pokhrel
"""
class Node: # Node class
def __init__(self, data):
self.data = data
self.next = None
class LinkedList: # Linkedlist class
def __init__(self):
self.head = None
def addNode(self, data):
if not self.head: # if linked list is empty, set first element as head
self.head = Node(data)
else:
top = self.head # if not, add element at last of linked list
while top.next:
top = top.next
top.next = Node(data)
def deleteNodefromFirst(self):
print(self.head.data, " is deleted")
self.head = self.head.next # set second element as head of linkedlist, hence deleting first element
def deleteNodefromLast(self):
top = self.head
while top.next.next:
top = top.next
print(top.next.data, " is deleted")
top.next = None # set next value of second last element as None, hence deleting last element
def showAll(self):
top = self.head
if self.head:
top = self.head
while top.next: # Iterating through the linkedlist printing all elements
print(top.data)
top = top.next
else:
print(top.data)
else:
print("The Linked List is empty")
ll = LinkedList()
ll.addNode(25)
ll.addNode(36)
ll.addNode(5)
ll.addNode(15)
ll.addNode(250)
ll.addNode(360)
ll.addNode(50)
ll.addNode(100)
ll.showAll()
ll.deleteNodefromFirst()
ll.deleteNodefromLast()
ll.showAll()
'''
Output:
25
36
5
15
250
360
50
100
25 is deleted
100 is deleted
36
5
15
250
360
50
'''
| true |
6243bfacd386b76e0bf1fb38183e40bba96c48d9 | jmason86/python_convenience_functions | /lat_lon_to_position_angle.py | 982 | 4.1875 | 4 | import numpy as np
def lat_lon_to_position_angle(latitude, longitude):
"""Function to translate heliocentric coordinates (latitude, longitude) into position angle
Written by Alysha Reinard and James Paul Mason.
Inputs:
longitude [float]: The east/west coordinate
latitude [float]: The north/south coordinate
Optional Inputs:
None
Outputs:
position_angle [float]: The converted position angle measured in degrees from solar north, counter clockwise
Optional Outputs:
None
Example:
position_angle = lat_lon_to_position_angle(35, -40)
"""
x = longitude * 1.0
y = latitude * 1.0
if y != 0:
pa = np.arctan(-np.sin(x) / np.tan(y))
else:
pa = 3.1415926 / 2. # limit of arctan(infinity)
pa = pa * 180.0 / 3.1415926
if y < 0:
pa += 180
if x == 90 and y == 0:
pa += 180
if pa < 0:
pa += 360
if x == 0 and y == 0:
pa = -1
return pa
| true |
94418a9660befad407049a9b6b6c3e3708c3e394 | LogicPenguins/BeginnerPython | /Udemy Course/HW Funcs & Methods/exer3.py | 444 | 4.375 | 4 | # Write a Python function that accepts a string and calculates the number of upper case
# and lowercase letters.
def case_info(string):
num_upper = 0
num_lower = 0
for char in string:
if char.islower():
num_lower += 1
elif char.isupper():
num_upper += 1
print(f'Upper Case Chars: {num_upper}\nLower Case Chars: {num_lower}')
case_info('Hello Mr. Rogers, how are you this fine Tuesday?') | true |
d79574835a4f1924c0d5fc4160cb3e31788aba42 | madhuri-bh/DSC-assignmentsML-AI | /Python1.py | 572 | 4.25 | 4 | movieEntered = input("Enter a movie")
thriller=["Dark","Mindhunter","Parasite","Inception","Insidious","Interstellar","Prison Break","MoneyHeist","War","Jack Ryan"]
comedy=["Friends","3 Idiots","Brooklyn 99","How I Met Your Mother","Rick And Morty","The Big Bang Theory","TheOffice","Space Force"]
movieEntered = movieEntered.lower()
thriller = map(str.lower,thriller)
comedy = map(str.lower,comedy)
if movieEntered in thriller:
print("It is a thriller")
elif movieEntered in comedy:
print("It is a comedy")
else:
print("It's neither thriller nor comedy") | true |
6c8326308e4df9e5a607376b8ccf1c68a1ba6478 | sushtend/100-days-of-ml-code | /code/basic python/13.5 guessing game.py | 361 | 4.1875 | 4 | Guess_count=1
guess=9
print("+++++ This program lets you guess the secret number +++++")
while Guess_count<=3:
num = int(input("Gues the number: "))
if guess==num:
print("Correct")
#exit()
break
Guess_count+=1
# Else for while loop evaluates after completion of all loops without brteak
else :
print("Sorry you failed") | true |
a957102ba9b196c13b102ecdf02e81ed94796a8b | sushtend/100-days-of-ml-code | /code/basic python in depth/21 sets.py | 1,367 | 4.5 | 4 | # https://realpython.com/python-sets/
#
numbers = [1, 2, 3, 4]
first = set(numbers)
second = {1, 5}
print(first | second) # Uniion
print(first & second) # Intersection
print(first - second) # Differece
print(first ^ second) # semantic difference. Items in either a or b but not both
# ----------------------------------------
print("+++++++++++++Strings++++++++++++++")
x = set(["foo", "bar", "baz", "foo", "qux"])
print(x)
x = set(("foo", "bar", "baz", "foo", "qux"))
print(x)
x = {"foo", "bar", "baz", "foo", "qux"}
print(x)
# Strings are also iterable, so a string can be passed to set() as well.
s = "quux"
print(list(s))
print(set(s))
# 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.
# An empty set is falsy in Boolean context
y: set = set()
print(bool(y))
print(len(x))
print("----------------")
x1 = {"foo", "bar", "baz"}
x2 = {"baz", "qux", "quux"}
print(x1.union(x2))
print(x1.intersection(x2))
print(x1.difference(x2))
print(x1.symmetric_difference(x2))
# Determines whether or not two sets have any elements in common.
print(x1.isdisjoint(x2))
# Determine whether one set is a subset of the other.
print(x1.issubset(x2))
# Modify a set by union.
x1.update(["corge", "garply"])
x1.add("corge")
x1.remove("baz")
| true |
635a67a18e9542866a68fc362ecc2941069da6e1 | jinm808/Python_Crash_Course | /chapter_4_working_w_lists/pracs.py | 1,661 | 4.5625 | 5 | '''
4-1: Pizzas
Think of at least three kinds of your favorite pizza.
Store these pizza names in a list, and then use a for loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza.
For each pizza you should have one line of output containing a simple statement like I like pepperoni pizza.
Add a line at the end of your program, outside the for loop, that states how much you like pizza.
The output should consist of three or more lines about the kinds of pizza you like and then an additional sentence, such as I really love pizza!
'''
favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie']
# Print the names of all the pizzas.
for pizza in favorite_pizzas:
print(pizza)
print("\n")
# Print a sentence about each pizza.
for pizza in favorite_pizzas:
print("I really love " + pizza + " pizza!")
print("\nI really love pizza!")
'''
4-3: Counting to Twenty
Use a for loop to print the numbers from 1 to 20, inclusive.
'''
numbers = list(range(1, 21))
for number in numbers:
print(number)
'''
4-5: Summing a Million
Make a list of the numbers from one to one million,
and then use min() and max() to make sure your list actually starts at one and ends at one million.
Also, use the sum() function to see how quickly Python can add a million numbers.
'''
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
'''
4-7: Threes
Make a list of the multiples of 3 from 3 to 0. Use a for loop to print the numbers in your list.
'''
threes = list(range(3, 31, 3))
for number in threes:
print(number) | true |
cab02298ed5b609d152d734f11416bf9442792f8 | jinm808/Python_Crash_Course | /chapter_8_functions/user_album.py | 712 | 4.21875 | 4 | def make_album(artist_name, album_title, tracks = 0):
"""Build a dictionary describing a music album."""
album_dict = {
'artist' : artist_name.title(),
'album' : album_title.title()
}
if tracks:
album_dict['tracks'] = tracks
return album_dict
print("Enter 'q' at any time to stop.")
while True:
title = input('\nWhat album are you thinking of? ').lower()
if title == 'q':
break
artist = input('Who\'s the artist? ').lower()
if artist == 'q':
break
tracks = input('Enter number of tracks if you know them: ')
if artist == 'q':
break
album = make_album(artist, title, tracks)
print(album)
print("\nThanks for responding!")
| true |
2fc1a9a57b5e8713e1fd8b231289656d1838e32c | wandingz/daily-coding-problem | /daily_coding_problem61.py | 1,695 | 4.28125 | 4 | '''
This problem was asked by Google.
Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
Do this faster than the naive method of repeated multiplication.
For example, pow(2, 10) should return 1024.
'''
class Solution:
def powNaive(self, a, b):
# naive method of repeated multiplication
result = 1
for _ in range(b):
result *= a
return result
def powNaive2(self, a, b):
# naive method of repeated multiplication
if not b:
return 1
return a * self.powNaive2(a, b-1)
def powSquaring(self, a, b):
# exponentiation by squaring
if b == 1:
return a
elif b % 2 == 1:
return a * self.powSquaring(a, b-1)
else:
p = self.powSquaring(a, b/2)
return p*p
def powSquaring2(self, a, b):
# exponentiation by squaring
result = 1
while True:
if b % 2 == 1:
result *= a
b -= 1
if b == 0:
break
b /= 2
a *= a
return result
def powBinary(self, a, b):
# left-to-right binary exponentiation
def _traversal(n):
bits = []
while n:
bits.append(n % 2)
if n % 2 == 1:
n -= 1
n /= 2
return bits
result = 1
for x in reversed(_traversal(b)):
result *= result
if x == 1:
result *= a
return result
a, b = 2, 5
a, b = 3, 4
Solution().powBinary(a, b)
| true |
5503d10bbcf8a15a7e6e4d4e1becb769f87839d1 | glemvik/Knowit_julekalender2017 | /Luke11.py | 2,087 | 4.375 | 4 | # -*- coding: utf-8 -*-
from time import time
from math import sqrt
def mirptall(primes):
"""
Returns all positive 'mirptall' smaller than 'number', where 'mirptall' are
primes which are also primes when the digits are reversed without being
palindromes.
"""
# INITIALIZE
primes = set(primes)
mirptall = []
# WORK THROUGH SET OF PRIMES
while primes:
prime = primes.pop()
reverse_prime = int(str(prime)[::-1])
# IF NOT PALINDROME AND REVERSE OF PRIME IS PRIME
if prime != reverse_prime and reverse_prime in primes:
# ADD BOTH 'MIRPTALL' AND REMOVE FROM SET OF PRIMES
mirptall.append(prime)
mirptall.append(reverse_prime)
primes.remove(reverse_prime)
return mirptall
def primes(number):
"""
Returns an array of all primes smaller than 'number'.
"""
# INITIALIZE
primes = [2]
# WORK THROUGH LIST
for number in range(3, number):
index = 0
is_prime = True
# CHECK DIVISIBILITY BY PRIME NUMBERS
while index < len(primes) and primes[index] < sqrt(number) + 1:
# DIVISIBLE BY OTHER PRIME -> NOT PRIME
if number % primes[index] == 0:
is_prime = False
break
index += 1
# IF NOT DIVISIBLE BY OTHER PRIMES -> APPEND TO PRIMES
if is_prime:
primes.append(number)
return primes
#-----------------------------------------------------------------------------#
#---------------------------------- M A I N ----------------------------------#
#-----------------------------------------------------------------------------#
start_time = time()
number = 1000
# FIND PRIMES BELOW 'number'
primes = primes(number)
# FIND 'MIRPTALL' AMONG PRIMES
mirptall = mirptall(primes)
print('Result:', len(mirptall))
print('Time:', time() - start_time) | true |
db545519dc14cf85b7b0a0b7c146974958756205 | pipa0979/barbell-squats | /Singly Linked List/Insertion/LL-Insertion-end.py | 1,746 | 4.28125 | 4 | # Purpose - to add node to the end of the list.
class Node(object):
def __init__(self, val):
self.data = val
self.next = None
class LinkedList(object):
# Head, Tail in a new LL will point to None
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
if self.head==None:
return True
else:
return False
def status(self):
if self.isEmpty():
print "Empty!! No Status!"
return
else:
print "Head --> {}".format(self.head.data)
print "Tail --> {}".format(self.tail.data)
# Print the LL
def traverse(self):
node = self.head
if node == None:
print "Empty Linked List"
else:
while node.next != None:
print "{} -->".format(node.data),
node = node.next
print "{} --> |".format(node.data)
# Adding the new node to the end of the list.
# the head pointer will stay constant
# the tail pointer will move to the new node.
def addEnd(self, val):
new_node = Node(val)
if self.head == None:
self.head = new_node
self.tail = new_node
self.head.next = None
return True
else:
self.tail.next = new_node # ask why
self.tail = new_node
new_node.next = None
return True
LL = LinkedList()
LL.status()
LL.traverse()
for each in xrange(6):
if LL.addEnd(each):
print "{} added at the end!".format(each)
else:
print "{} not added :(".format(each)
LL.status()
LL.traverse()
| true |
8d90eb725e1b93cafb1f814f531052d52f7db673 | emcguirk/atbs | /Chapter 7/strongPass.py | 573 | 4.1875 | 4 | import re
import pyperclip
# Regexes for each requirement:
hasLower = re.compile(r'[a-z]')
hasUpper = re.compile(r'[A-Z]')
hasNumber = re.compile(r'[0-9]')
def isStrong(pwd):
assert type(pwd) == str
lower = hasLower.findall(pwd)
upper = hasUpper.findall(pwd)
number = hasNumber.findall(pwd)
if len(lower) < 1 or len(upper) < 1 or len(number) < 1:
print('Password is not strong enough. Make sure to include all required characters')
if len(pwd) < 8:
print('Password is not strong enough. Please enter at least 8 characters')
else:
print('Password is strong')
| true |
f242ca44b241f49b69bd857d106747af2bcf5e2c | mattdrake/pdxcodeguild | /python/fizz_buzz.py | 757 | 4.1875 | 4 | __author__ = 'drake'
#reques input from user for any number
question = input("Enter a number. ")
#created variable for incrementing input from user
num = -1
#create loop to count from zero to user input number
while question > num:
#incrementing by one
num += 1
#test if number is a multiple of both 3 and 4 not including zero
if num % 3 ==0 and num % 4 == 0 and num != 0:
print('\033[1;32mfizzbuzz\033[1;m')
#test if number is a multiple of 3 not including zero
elif num % 3 == 0 and num != 0:
print('\033[1;31mfizz\033[1;m')
#test if number is a multiple of 4 not including zero
elif num % 4 == 0 and num != 0:
print('\033[1;34mbuzz\033[1;m')
#otherwise print number incremented
else:
print(num)
| true |
742e5d7916310d6be17299e6d47c40c901498635 | kebron88/essential_libraries_assignment | /question11.py | 941 | 4.21875 | 4 | import numpy as np
import pandas as pd
#Do not import any other libraries
"""
Suppose you have created a regression model to predict some quantity. Write a function that takes 2 numpy arrays that both have the same length, y and y_pred.
The function should return the loss between the predicted and the actual values where the losss function is defined here to be
loss = 1/N * Sum from i=1 to N (y[i] - y_pred[i])**2 (See sklearn part 1 video for explanation of this loss function)
Where N is the number of datapoints. For example if y = array([0.5,1,2,4,8]) and y_pred = array([1,2,3,4,5]), then f(y, y_pred) should return 2.25
"""
y = np.array([4,11.5,6,3,8])
y_pred = np.array([7.1,12,5,6.5,5])
def f(y,y_pred):
N=len(y)
return np.sum((y-y_pred)**2)/N
print(f(y,y_pred))
###########END CODE###############
if __name__=='__main__':
######CREATE TEST CASES HERE######
pass
##################################
| true |
69ba98a8c14e62037d3016662fc7d6e571187c67 | LukeG-dev/CIS-2348 | /homework1/3.18.py | 888 | 4.21875 | 4 | # Luke Gilin
import math
wall_H = float(input("Enter wall height (feet):\n"))
wall_W = float(input("Enter wall width (feet):\n"))
wall_A = wall_H * wall_W # Calculate wall area
print("Wall area:", '{:.0f}'.format(wall_A), "square feet")
paintNeeded = wall_A / 350 # Calculate Paint needed for wall
print("Paint needed:", '{:.2f}'.format(paintNeeded), "gallons")
cansNeeded = math.ceil(paintNeeded) # Rounds up the paint gallons needed to the nearest integer
print("Cans needed:", cansNeeded, "can(s)\n")
paintColor = input("Choose a color to paint the wall:\n")
paintColors = {'red': 35, 'blue': 25, 'green': 23} # create dic of paint colors and prices
colorPrice = paintColors[paintColor] * cansNeeded # multiply number of cans by the price of that color
print('Cost of purchasing {color} paint: ${price}'.format(color=paintColor, price=colorPrice))
| true |
5226c99becd7721dcced90cd85b26526fa8880c8 | ashish-dalal-bitspilani/python_recipes | /python_cookbook/edition_one/Chapter_One/recipe_two.py | 597 | 4.625 | 5 | # Chapter 1
# Section 1.2
# Swapping values without using a temporary variable
# Python's automatic tuple packing (happens on the right side)
# and unpacking are used to achieve swap readily
a,b,c = 1,2,3
print("pre swap values")
print('a : {}, b : {}, c : {}'.format(a,b,c))
a,b,c = b,c,a
print("post swap values")
print('a : {}, b : {}, c : {}'.format(a,b,c))
# Tuple packing, done using commas, on the right hand side and
# sequence (tuple) unpacking, done by placing several comma-separated
# targets on the lefthand side of a statement, are both useful, simple
# and general mechanisms
| true |
43ab394f43b06ace4fffb0b09c18d01c04c0b962 | CruzAmbrocio/python-factorial | /application.py | 1,161 | 4.28125 | 4 | """This program calculates a Fibonacci number"""
import os
def fib(number):
"""Generates a Fibonacci number."""
if number == 0:
return 0
if number == 1:
return 1
total = fib(number-1) + fib(number-2)
return total
def typenum():
"""Function that allows the user to enter a number."""
while True:
try:
num = int(raw_input(" >*Enter a number: "))
print ""
print "Fibonacci in position", str(num), ":"
print fib(num)
new()
break
except ValueError:
print " Please enter a valid number!"
def new():
"""It allows entering a new number."""
question = raw_input("Do you want to type another number? y/n ")
questlow = question.lower()
if questlow == "y" or questlow == "yes":
typenum()
elif questlow == "n" or questlow == "not":
os.system("exit")
else:
print "Type 'y' or 'n'"
new()
print ""
print " ----> *Fibonacci number* <----"
print ""
print "/*Enter a number, and the fibonacci number in the given position is displayed."
print ""
typenum()
| true |
29322f2c5a750b532c5faccb5549d29841bd5b14 | miku/khwarizmi | /sorting/median.py | 645 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
Swap the median element with the middle element. Create two smaller
problems, solve these.
Subproblems: Find the median of an unsorted list efficiently.
"""
def sort(A):
medianSort(A, 0, len(A))
def medianSort(A, left, right):
if left > right:
# find median A[me] in A[left:right]
mid = math.floor((right + left) / 2)
A[mid], A[me] = A[me], A[mid]
for i in range(mid):
if A[i] > A[mid]:
# find A[k] <= A[mid], where k > mid
A[i], A[k] = A[k], A[i]
medianSort(A, left, mid)
medianSort(A, mid, right)
| true |
1771618b573a48c8f0c19fbce9d50bf705fd481e | joedo29/Self-Taught-Python | /NestedStatementsAndScope.py | 1,367 | 4.46875 | 4 | # Author Joe Do
# Nested Statement and Scope in Python
'''
It is important to understand how Python deals with the variable names you assign.
When you create a variable name in Python the name is stored in a *name-space*.
Variable names also have a *scope*, the scope determines the visibility of that variable name to other parts of your code.
'''
# Example:
x = 25
def printer():
x = 50
return x
print(x) # print 25
print(printer()) # print 50
#Enclosing function locals.
# This occurs when we have a function inside a function (nested functions)
name = 'This is a global name'
def greet():
# Enclosing function
name = 'Sammy'
def hello():
print ('Hello ' + name)
hello()
greet()
# #Local Variables When you declare variables inside a function definition,
# they are not related in any way to other variables with the same names used outside the function
x = 50
def func(x):
print ('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
# Global statement is used to declare that y if global var
y = 50
def func():
global y
print('This function is now using the global y!')
print('Because of global y is: ', y)
y = 2
print('Ran func(), changed global y to', y)
print('Before calling func(), y is: ', y)
print(func())
print('Value of y (outside of func()) is: ', y) | true |
072ad3929e779ef840bc40875ff1eccaf7e55c1a | joedo29/Self-Taught-Python | /Files.py | 1,452 | 4.65625 | 5 | # Joe Do
# Python uses file objects to interact with external files on your computer.
# These file objects can be any sort of file you have on your computer,
# whether it be an audio file, a text file, emails, Excel documents, etc.
# Note: You will probably need to install certain libraries or modules to interact with those various file types,
# but they are easily available.
# Python has a built-in open function that allows us to open and play with basic file types.
# We're going to use some iPython magic to create a text file!
# Open the phonebook.txt file
my_file = open('phonebook.txt')
# Read a file using read() function
# after you read, the cursor is now at the end of the file
# meaning you can't read the file again unless you seek
print(my_file.read())
# Seek to the start of file (index 0) so you can read the file again
my_file.seek(0)
print(my_file.read())
# readlines() returns a list of the lines in the file
# readlines() avoid having to reset cursor every time
my_file.seek(0)
print()
print('The first line of the file is {p}'.format(p=my_file.readline()))
# ITERATING THROUGH A FILE
for line in open('phonebook.txt'):
print(line)
# WRITING TO A FILE
# By default, using the open() function will only allow us to read the file,
# we need to pass the argument 'w' to write over the file. For example:
my_file = open('phonebook.txt', 'w+')
# now write to my_file
my_file.write('JOE DO 123456')
print(my_file.read())
| true |
0230151c53ea3f13baa6b353e2c9108452b1edff | shilpa5g/Python-Program- | /python_coding_practice/sum_of_series.py | 276 | 4.25 | 4 | # program to find Sum of natural numbers up to given range
terms = int(input("Enter the last term of the series: "))
if terms < 0:
print("please enter a positive number.")
else:
sum = 0
for i in range(1, terms+1):
sum +=i
print('sum of series = ',sum) | true |
55084a7529445303cf7dc531022ee39ab52613d2 | shilpa5g/Python-Program- | /python_coding_practice/palindrome.py | 246 | 4.5625 | 5 | # Program to check if a string is palindrome or not
string = str(input("enter a string: "))
rev_str = reversed(string)
if list(string) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.") | true |
7d7ac0d51758458af03015b2b016c7608d266232 | fminor5/TonyGaddisCh13 | /p13-7button_demo.py | 849 | 4.28125 | 4 | import tkinter
import tkinter.messagebox
class MyGUI:
def __init__(self):
self.main_window = tkinter.Tk()
# Create a Button widget. The text 'Click Me!' should appear on the
# face of the Button. The do_something method should be executed when
# the user clicks the Button.
self.my_button = tkinter.Button(self.main_window, text='Click Me!',
command=self.do_something)
# Pack button
self.my_button.pack()
# Enter the tkinter main loop
tkinter.mainloop()
# The do_something method is a callback function for the Button widget.
def do_something(self):
# Display an info dialog box.
tkinter.messagebox.showinfo('Response',
'Thanks for clicking the button.')
MyGUI()
| true |
7cdf5ba9b7c9cf90abcc0f0592cff859ecde851a | thangln1003/python-practice | /python/trie/208-implementTrie_I.py | 2,294 | 4.125 | 4 | """ 208. Implement Trie (Prefix Tree) (Medium)
https://leetcode.com/problems/implement-trie-prefix-tree/
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
!Note:
!You may assume that all inputs are consist of lowercase letters a-z.
!All inputs are guaranteed to be non-empty strings.
"""
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEnd = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = self._getNode()
def _getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def _searchPrefix(self, prefix: str) -> TrieNode:
node = self.root
for level in range(len(word)):
index = self._charToIndex(word[level])
if not node.children[index]:
return None
node = node.children[index]
return node
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for level in range(len(word)):
index = self._charToIndex(word[level])
if not node.children[index]:
node.children[index] = self._getNode()
node = node.children[index]
node.isEnd = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self._searchPrefix(word)
return node != None and node.isEnd
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self._searchPrefix(prefix)
return node != None
if __name__ == "__main__":
word = "a"
prefix = "app"
obj = Trie()
# obj.insert(word)
param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
print("Search result is {}".format(param_2))
# print("StartsWith result is {}".format(param_3))
| true |
a670acd7b46c33e6c19dbd4130be7b20860bc89e | thangln1003/python-practice | /python/1-string/438-findAllAnagrams.py | 2,175 | 4.125 | 4 | """ 438. Find All Anagrams in a String (Medium)
https://leetcode.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
*Input: s: "cbaebabacd" p: "abc"
*Output: [0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
*Input: s: "abab" p: "ab"
*Output: [0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
"""
from collections import Counter
from typing import List
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
lengthP, lengthS = len(p), len(s)
if not s or not p or lengthS < lengthP:
return []
def checkAnagrams(arrS: [], arrP: []) -> bool:
for i in range(len(arrP)):
if arrP[i] != arrS[i]:
return False
return True
arrS = [0]*26 # "cbaebabacd"
arrP = [0]*26 # "abc"
startWindow = 0
result = []
for i in range(lengthP):
arrS[ord(s[i]) - ord('a')] += 1
for j in range(lengthP):
arrP[ord(p[j]) - ord('a')] += 1
for endWindow in range(len(s)-1):
if endWindow >= lengthP - 1:
if checkAnagrams(arrS, arrP):
result.append(startWindow)
arrS[ord(s[startWindow]) - ord('a')] -= 1
arrS[ord(s[endWindow+1]) - ord('a')] += 1
startWindow += 1
if checkAnagrams(arrS, arrP):
result.append(lengthS - lengthP)
return result
if __name__ == "__main__":
# s, p = "cbaebabacd", "abc"
s, p = "abab", "ab"
solution = Solution()
result = solution.findAnagrams(s, p)
print(result)
| true |
3c5bc82862d3f05da5ce7d0807de1e5d0e735e7d | rasmiranjanrath/PythonBasics | /Set.py | 521 | 4.25 | 4 | #A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
set_of_link={'google.com','facebook.com','yahoo.com','jio.com'}
#loop through set
def loop_through_set():
for links in set_of_link:
print(links)
loop_through_set()
#check if item exists or not
if 'google.com' in set_of_link:
print('yes')
#add an element to set
set_of_link.add('example.com')
loop_through_set()
#add multiple items to set
set_of_link.update(['random.com','gooje.com'])
loop_through_set()
| true |
5b7543e3b0fc8cf24b22afb680da2e4f28a1b9ac | LeenaKH123/python3 | /02_classes-objects-methods/02_04_classy_shapes.py | 1,078 | 4.4375 | 4 | # Create two classes that model a rectangle and a circle.
# The rectangle class should be constructed by length and width
# while the circle class should be constructed by radius.
#
# Write methods in the appropriate class so that you can calculate
# the area of both the rectangle and the circle, the perimeter
# of the rectangle, and the circumference of the circle.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def __str__(self):
return f"{self.length},{self.width}"
def RectanglePerimeter(self):
perimeter = 2 * (self.length + self.width)
print(perimeter)
class Circle:
def __init__(self, circleradius):
self.circleradius = circleradius
def circumference(self):
perimter = 2* 3.14 * self.circleradius
print(perimter)
def __str__(self):
return f"{self.circleradius}"
rectangle1 = Rectangle(3,4)
print(rectangle1)
rectangle1.RectanglePerimeter()
circle1 = Circle(2)
print(circle1)
circle1.circumference()
| true |
f7fe24777d99688ce0f67c7f16ee4788d4c694d4 | LeenaKH123/python3 | /02_classes-objects-methods/02_06_freeform.py | 695 | 4.125 | 4 | # Write a script with three classes that model everyday objects.
# - Each class should have an `__init__()` method that sets at least 3 attributes
# - Include a `__str__()` method in each class that prints out the attributes
# in a nicely formatted string.
# - Overload the `__add__()` method in one of the classes so that it's possible
# to add attributes of two instances of that class using the `+` operator.
# - Create at least two instances of each class.
# - Once the objects are created, change some of their attribute values.
#
# Be creative. Have some fun. :)
# Using objects you can model anything you want:
# Animals, paintings, card games, sports teams, trees, people etc...
| true |
d9dcd1205b58e9f5502d6b2fb183b95ff6e24deb | arkoghoshdastidar/python-3.10 | /14_for_loop.py | 524 | 4.5 | 4 | # for loop can be used to traverse through indexed as well as un-indexed collections.
fruits = ["apple", "mango", "banana", "cherry"]
for x in fruits:
if x == "cherry":
continue
print(x)
else:
print("fruits list completely traverse!!")
# range function range(starting_index, last_index, step)
for x in range(1, 11, 2):
print(x)
else: # NOTE: The else block will not be executed if the loop is broken by break statement
print("for loop traversed successfully!!")
| true |
4ded74124b0a8a72d4f3ef553470bc01609be6b9 | shireeny1/Python | /python_basics_104_lists.py | 2,208 | 4.4375 | 4 | # Lists in Python
# Lists are ordered by index
## AKA --> Arrays or (confusingly) as objects in JavaScript
# Syntax
# Declare lists using []
# Separate objects using ,
# var_list_name = [0 , 1, 2, 3,..] --> index numbers
crazy_x_landlords = ['Sr. Julio', 'Jane', 'Alfred', 'Marksons']
print(crazy_x_landlords)
print(type(crazy_x_landlords))
# How to access record number 3 in the list: --> record number - 1
print(crazy_x_landlords[2])
# Accessing other location
print(crazy_x_landlords[0])
print(crazy_x_landlords[-1])
# New list of places to live
places_to_live = ['California', 'Rio de Janeiro', 'Melbourne', 'Manchester', 'Singapore']
# Re-assign an index
places_to_live[3] = 'Hawaii'
print(places_to_live[3])
# Method .append(object)
print(len(places_to_live))
places_to_live.append('LA')
print(len(places_to_live))
print(places_to_live)
# .insert(index,,object)
places_to_live.insert(0, 'Lisboa')
print(places_to_live)
# .pop(index) --> removes from list at specific index
places_to_live.pop(3)
print(places_to_live)
# List slicing
# This is used to manage lists
# Prints from index to end of the list
print(places_to_live[3:])
# Prints from index to the start of the list (not inclusive the index '3')
print(places_to_live[:3])
# Print from specified index to second specified index (not inclusive of the index)
print(places_to_live[0:3])
print(places_to_live[1:3])
# Skip slicing
list_exp = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list_exp)
print(list_exp[2:10:3])
print(list_exp[::-1])
# Tuples --> Immutable lists
# Syntax
# Defined using (object, object)
mortal_enemies = ('Mario', 'Sailormoon', 'MOON CAKE', 'Jerry', 'Berry')
print(type(mortal_enemies))
# If you try re-assign it will break
# print(mortal_enemies[0]) = 'Goku'
# print(mortal_enemies)
# Example of creating amazing list for end of the world survival
list_of_kit = []
item_1 = input('What is your first item to keep? ')
list_of_kit.append(item_1)
item_2 = input('What is your second item to keep? ')
list_of_kit.append(item_2)
item_3 = input('What is your third item to keep? ')
list_of_kit.append(item_3)
print('Hey there, You have a lot of stuff!' + ' ' + str(list_of_kit))
| true |
5e7dbf191a2b1396cb23f1bdc870d8b1dbcbff7e | nirzaf/python_excersize_files | /section9/lecture_043.py | 289 | 4.125 | 4 |
### Tony Staunton
### Working with empty lists
# Empty shopping cart
shopping_cart = ['pens']
if shopping_cart:
for item in shopping_cart:
print("Adding " + item + " to your cart.")
print("Your order is complete.")
else:
print("You must select an item before proceeding.")
| true |
edb115e5a043e70668684de5ac215346c59df01b | nirzaf/python_excersize_files | /section9/9. Branching and Conditions/8.1 lecture_040.py.py | 324 | 4.21875 | 4 | ### 28 / 10 / 2016
### Tony Staunton
### Checking if a value is not in a list
# Admin users
admin_users = ['tony', 'frank']
# Ask for username
username = input("Please enter your username?")
# Check if user is an admin user
if username not in admin_users:
print("You do not have access.")
else:
print("Access granted.")
| true |
d4d7ddf9bac3658959f888dda9c75d49491fdfad | AnetaEva/NetPay | /NetPay.py | 837 | 4.25 | 4 | employee_name = input('Name of employee: ')
weekly_work_hours = float(input('How many hours did you work this week?: '))
pay_rate = float(input('What is your hourly rate?: $'))
#Net Pay without seeing the breakdown from gross pay and tax using the pay rate * work hours * (1 - 0.05)
net_pay = pay_rate * weekly_work_hours * (1 - 0.05)
print('Net Pay without breakdown.')
print('- Net Pay: $', format(net_pay, '.2f'), sep='')
#Net Pay with breakdown of gross pay, tax, and Net Pay using tax rate 0.05
tax_rate = 0.05
gross_pay = weekly_work_hours * pay_rate
tax = gross_pay * tax_rate
alternate_net_pay = gross_pay - tax
print('Net Pay with breakdown.')
print('- Gross Pay: $', format(gross_pay, '.2f'), sep='')
print('- Tax: $', format(tax, '.2f'), sep='')
print('- Alternate net pay: $', format(alternate_net_pay, '.2f'), sep='')
| true |
43b8107a49178ce617fa90e55b0b3d612be117bb | cornielleandres/Intro-Python | /src/day-1-toy/fileio.py | 403 | 4.1875 | 4 | # Use open to open file "foo.txt" for reading
foo = open('foo.txt')
# Print all the lines in the file
for line in foo:
print(line)
# Close the file
foo.close()
# Use open to open file "bar.txt" for writing
bar = open('bar.txt', 'w')
# Use the write() method to write three lines to the file
lines = ['first line\n', 'second line\n', 'third line']
bar.writelines(lines)
# Close the file
bar.close()
| true |
08138bc7d63a9cc15ec13c8cf33e60cce825d6da | VinidiktovEvgenijj/PY111-april | /Tasks/a0_my_stack.py | 980 | 4.3125 | 4 | """
My little Stack
"""
my_stack = []
def push(elem) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
global my_stack
my_stack.append(elem)
return None
def pop():
"""
Pop element from the top of the stack
:return: popped element
"""
global my_stack
if my_stack == []:
return None
else:
pop_elem = my_stack[-1]
del my_stack[-1]
return pop_elem
def peek(ind=0):
"""
Allow you to see at the element in the stack without popping it
:param ind: index of element (count from the top)
:return: peeked element
"""
global my_stack
if ind > len(my_stack) - 1:
return None
else:
return my_stack[ind - 1]
def clear() -> None:
"""
Clear my stack
:return: None
"""
global my_stack
my_stack = []
return None
| true |
40b0eab57ae17cdb77045d0156e53e0ba073abd2 | Viiic98/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 352 | 4.15625 | 4 | #!/usr/bin/python3
def inherits_from(obj, a_class):
""" inherits_from
Check if obj is a sub class of a_class
Return:
True if it is a subclass
False if it is not a subclass
"""
if type(obj) is not a_class and issubclass(type(obj), a_class):
return True
else:
return False
| true |
d15a5aa268e7d312cef56fdd19be4efe2a0b9fdc | dscottboggs/practice | /HackerRank/diagonalDifference/difference.py | 1,391 | 4.5 | 4 | from typing import List
"""The absolute value of the difference between the diagonals of a 2D array.
input should be:
Width/Height of the array on the first input line
any subsequent line should contain the space-separated values.
"""
def right_diagonal_sum(arrays: List[List[int]]) -> int:
"""Sum the right diagonal of the given 2d array."""
outsum = 0
for index in range(len(arrays)):
outsum += arrays[index][index]
return outsum
def left_diagonal_sum(arrays: List[List[int]]) -> int:
"""Sum the left diagonal of the given 2d array."""
outsum = 0
row = 0
column = len(arrays) - 1
while row < len(arrays):
outsum += arrays[row][column]
column -= 1
row += 1
return outsum
def diagonal_difference(arrays: List[List[int]]) -> int:
"""Get the absolute value of the difference between the diagonals.
@param arrays: must be a sqare matrix - i.e. an array of arrays where the
number of arrays is the same as the number of values in
each array.
"""
return abs(right_diagonal_sum(arrays) - left_diagonal_sum(arrays))
def main():
rows = int(input("Number of arrays to be specified."))
a = [
int(element) for element in [
input(f"Array #{row}: ").split(' ') for row in range(rows)
]
]
print(diagonal_difference(a))
| true |
b4729ac8cb9c4d7ba23b8fb98149a734ef517a93 | yawitzd/dsp | /python/q8_parsing.py | 1,343 | 4.375 | 4 | #The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
import csv
def read_data(data):
'''Returns 'fbd', a list of lists'''
fb = open('football.csv')
csv_fb = csv.reader(fb)
fbd = []
for row in csv_fb:
fbd.append(row)
fb.close()
return fbd
def add_score_difference(parsed_data):
'''Adds a column to the data for score difference'''
d = parsed_data
for i in range(len(d)):
if i == 0:
d[i].append('Score Difference')
else:
d[i].append(int(d[i][5]) - int(d[i][6]))
return d
def get_min_team(parsed_data):
d = add_score_difference(parsed_data)
diffs = []
teams = []
for row in d:
if d.index(row) > 0:
diffs.append(row[8])
teams.append(row[0])
i = diffs.index(min(diffs))
return teams[i]
| true |
b12125bfd87a14b9fba134333f933e0adf308bb6 | talhahome/codewars | /Oldi2/Write_Number_in_Expanded_Form.py | 612 | 4.3125 | 4 | # You will be given a number and you will need to return it as a string in Expanded Form. For example:
#
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
# NOTE: All numbers will be whole numbers greater than 0.
def expanded_form(num):
z = ''
while len(str(num)) > 1:
x = num % 10**(len(str(num))-1)
z = z + str(num - x) + ' + '
num = x
if num != 0:
z = z + str(num)
else:
z = z[:-3]
print(z)
return z
expanded_form(70304)
# Ans: '70000 + 300 + 4'
| true |
ea28dc883c613ace6f42e05c4bcd733df3482635 | talhahome/codewars | /Number of trailing zeros of N!.py | 580 | 4.3125 | 4 | # Write a program that will calculate the number of trailing zeros in a factorial of a given number.
# N! = 1 * 2 * 3 * ... * N
#
# Examples
# zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero
#
# zeros(12) = 2
# # 12! = 479001600 --> 2 trailing zeros
# Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.
def zeros(n):
a = int(n/5)
if a < 5:
print(int(a))
return int(a)
z = a
while int(a/5) >= 1:
z = z + int(a/5)
a = int(a/5)
print(z)
return z
zeros(10000)
| true |
3e27494fa5776ac2a3f8190bd688e6aacb5539c3 | imayush15/python-practice-projects | /Learn/ListEnd.py | 260 | 4.15625 | 4 | print("Program to Print First and last Element of a list in a Seperate List :=\n")
list1=['i',]
x = int(input("Enter the Range of list : "))
for i in range(x):
y = int(input("Enter the Value : "))
list1.append(y)
print(list1[1], list1[-1])
| true |
78d0f11ae198c5115cee65f7646a1cc00472b497 | piotrbelda/PythonAlgorithms | /SpiralTraverse.py | 1,280 | 4.1875 | 4 | # Write a function that takes in an n x m two-dimensional array
# (that can be square-shaped when n==m) and returns a one-dimensional array of all the array's
# elements in spiral order; Spiral order starts at the top left corner of the two-dimensional array, goes
# to the right, and proceeds in a spiral pattern all the way until every element has been visited
mat=[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
# 1st, "pythonic" version
def spiralTraverse(matrix):
arr_to_sort=[]
for element in matrix:
arr_to_sort.extend(element)
arr_to_sort.sort()
return arr_to_sort
print(spiralTraverse(mat))
# 2nd, with algorithmic approach
def spiralTraverse(matrix):
sC,eC,sR,eR=0,len(matrix[0])-1,0,len(matrix)-1
spiral_list=[]
while len(matrix)*len(matrix[0]) != len(spiral_list):
for x in range(sC,eC+1):
spiral_list.append(matrix[sC][x])
for y in range(sR+1,eR+1):
spiral_list.append(matrix[y][eC])
for z in range(eC-1,sC-1,-1):
if sR==eR:break
spiral_list.append(matrix[eR][z])
for k in range(eR-1,sR,-1):
if sC==eC:break
spiral_list.append(matrix[k][sC])
sC+=1
eC-=1
sR+=1
eR-=1
return spiral_list
| true |
209019237804db02fcb51e4001df53aaff1e45b0 | kleutzinger/dotfiles | /scripts/magic.py | 2,524 | 4.25 | 4 | #!/usr/bin/env python3
"""invoke magic spells from magic words inside a file
magic words are defined thusly: (must be all caps)
#__MAGICWORD__# echo 'followed by a shell command'
put something of that format inside a file to set up running that command
additionally, #__file__# will be substituted with the path of the file this is called on
#__dir__# is the file's containing directory
you can also call the script with a spell_idx argument
`magic.py magic.py 0`
TODO:
if no args:
look for other executables inside folder
look for .MAGIC or MAGIC.txt inside folder?
`magic.py % 0` is <leader>0
examples:
#__PUSH__# gist -u ed85631bcb75846d950258eb19cb6b2a #__file__#
#__RUN__# python ~/scripts/magic.py
"""
import os
import re
import sys
import subprocess
MAGIC_REGEX = re.compile(r"\s*#\s*__([A-Z0-9_]+)__#\s*(\S.*)")
CAST_EMOJI = "(๑•ᴗ•)⊃━☆.*・。゚"
def main():
if len(sys.argv) == 1:
print(__doc__)
exit()
if len(sys.argv) >= 2:
filename = sys.argv[1]
if os.path.isfile(filename):
with_arg(filename)
else:
print(f"no file {filename}")
sys.exit(1)
def with_arg(filename):
spells = []
spell_counter = 0
with open(filename, "r") as fileobj:
for line in fileobj:
matches = MAGIC_REGEX.search(line)
if matches:
name, command = matches.group(1), matches.group(2)
command = sub_magic(command, filename)
spells.append((name, command))
spell_counter += 1
if spell_counter == 0:
print(f"no spells found in {filename}")
sys.exit(1)
if len(sys.argv) >= 3:
spell_idx = int(sys.argv[2])
else:
spell_idx = choose_spell_idx(spells)
name, command = spells[spell_idx]
print(f"{CAST_EMOJI}{name}")
process = subprocess.call(command, shell=True)
def sub_magic(command, argfile):
file_abs = os.path.abspath(argfile)
file_dir = os.path.dirname(file_abs)
command = command.replace("#__file__#", file_abs)
command = command.replace("#__dir__#", file_dir)
return command
def choose_spell_idx(spells):
idx = 0
for name, command in spells:
print(f"{idx}.\t{CAST_EMOJI}{name}")
print(f"{command}")
print("-" * 5)
idx += 1
inp = input("idx: ")
if not inp:
spell_idx = 0
else:
spell_idx = int(inp)
return spell_idx
if __name__ == "__main__":
main()
| true |
6369192c8d069bc4fd9f3b49e1e0cc94b1cc124a | nihaal-gill/Example-Coding-Projects | /Egyption Fractions/EgyptianFractions.py | 1,000 | 4.28125 | 4 | #Language: Python
#Description: This program is a function that uses the greedy strategy to determine a set of distinct (i.e. all different) Egyptian
#fractions that sum to numerator/denominator. The assumptions in this program are that the numerator and denominator are positive integers
#as well as the numerator is less than or equal to denominator. The function 1) prints a readable "equation" showing the result and
#2) returns a list of Egyptian fraction denominators.
def egypt1(numerator,denominator):
x = 2
result = []
print("{}/{} = ".format(numerator,denominator), end = " ")
while(numerator != 0):
if((numerator * x) >= denominator):
result.append(x)
numerator = (numerator * x) - denominator
denominator = denominator * x
x += 1
print("1/{} ".format(result[0]),end="")
i = 1
while i < len(result):
print("+ 1/{}".format(result[i]), end=" ")
i += 1
print ()
return result
| true |
57060973638e77b4247be650fc3f065b3a06070c | BloodyInspirations/VSA2018 | /proj01.py | 2,321 | 4.375 | 4 | # Name:
# Date:
# proj01: A Simple Program
# Part I:
# This program asks the user for his/her name and grade.
#Then, it prints out a sentence that says the number of years until they graduate.
# Part II:
# This program asks the user for his/her name and birth month.
# Then, it prints a sentence that says the number of days and months until their birthday
# If you complete extensions, describe your extensions here!
print "Hello there!"
your_name = raw_input("What is your name?")
date_of_grad = raw_input("What grade are you in?")
print your_name + ", you will graduate in" + str(12 - int(date_of_grad)) + "years."
print "Hi!"
your_name = raw_input("What is your name?")
your_name = your_name[0].upper() + your_name[1:100].lower()
print your_name
print "Hello!"
your_name = raw_input("What is your name?")
your_name = your_name[0:2].lower() + your_name[2].upper() + your_name[3:].lower()
print your_name
print "Hey there!"
birth_month = int(raw_input("What is your birth month in a number?"))
birth_day = int(raw_input("What is the date of when you were born?[Number]"))
date_current = 11
month_current = 6
if birth_month >= month_current:
print "Your birthday is in" + str(birth_month - month_current)
elif month_current >= birth_month:
print "Your birthday is in" + str(12-(month_current - birth_month))
print "months"
print '/'
if birth_day >= date_current:
print str(birth_day - date_current)
elif date_current >= birth_day:
print str(30-(date_current - birth_day))
print "days."
print "Hello"
your_name = raw_input("What is your name?")
print your_name + ", you are probably wondering what the highest ranking movie you are allowed to see is."
age_limitation = int(raw_input("First of all how old are you?"))
if age_limitation == 17 or age_limitation > 17:
print "The highest ranking movie you can see would be R-rated."
elif age_limitation == 13:
print "The highest ranking movie you can see would be rated PG-13."
if age_limitation == 14 or age_limitation == 16:
print "The highest ranking movie you can see would be rated PG-13."
elif age_limitation == 15:
print "The highest ranking movie you can see would be rated PG-13."
if age_limitation == 12 or age_limitation < 12:
print "The highest ranking movie you can see would be rated PG or G."
| true |
65fb4afd1c43749106c02ed065d530e8bf3782b3 | KeerthanaPravallika/DSA | /Patterns/Xpattern.py | 558 | 4.28125 | 4 | '''
Write a program to take String if the length of String is odd print X pattern otherwise print INVALID.
Input Format:
Take a String as input from stdin.
Output Format:
print the desired Pattern or INVALID.
Example Input:
edyst
Output:
e t
d s
y
d s
e t
'''
word = input()
if len(word) % 2 == 0:
print("INVALID")
else:
n = len(word)
for i in range(n):
for j in range(n):
if(i == j) or (j == n-i-1):
print(word[j],end='')
else:
print(' ',end='')
print()
| true |
488adf142b4eea5c71f5f3381b80935a33e47ebb | kayodeomotoye/Code_Snippets | /import csv.py | 848 | 4.1875 | 4 | import csv
from io import StringIO
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 elements only"'
the resulting list would be:
['Should', 'give', '3 elements only']
"""
data = StringIO(text)
reader = csv.reader(data, delimiter=' ')
for row in reader:
return row
from shlex import split
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 words only"'
the resulting list would be:
['Should', 'give', '3 words only']
"""
return split(text) | true |
a29a74255df46a2d0944a8389558cc294ed2eacb | kayodeomotoye/Code_Snippets | /running_mean.py | 1,227 | 4.3125 | 4 | from itertools import islice
import statistics
def running_mean(sequence):
"""Calculate the running mean of the sequence passed in,
returns a sequence of same length with the averages.
You can assume all items in sequence are numeric."""
avg_list=[]
new_list = []
for num in sequence:
new_list.append(num)
avg = round(statistics.mean(new_list), 2)
avg_list.append(avg)
return avg_list
#pybites
from itertools import accumulate
def running_mean_old(sequence):
"""Calculate the running mean of the sequence passed in,
returns a sequence of same length with the averages.
You can assume all items in sequence are numeric."""
if not sequence:
return []
total = 0
running_mean = []
for i, num in enumerate(sequence, 1):
total += num
mean = round(total/i, 2)
running_mean.append(mean)
return running_mean
def running_mean(sequence):
"""Same functionality as above but using itertools.accumulate
and turning it into a generator"""
for i, num in enumerate(accumulate(sequence), 1):
yield round(num/i, 2)
[3, 4, 6, 2, 1, 9, 0, 7, 5, 8] | true |
e12ec0d529f890f1f46ead8feb24ce5ba1bef83a | rinoSantoso/Python-thingy | /Sorting.py | 1,256 | 4.21875 | 4 | def sort(unsorted):
sorted = []
sorted.append(unsorted[0])
i = 1
while i < len(unsorted):
for j in range(len(sorted)):
if unsorted[i] < sorted[j]:
sorted.insert(j, unsorted[i])
break
elif j == len(sorted) - 1:
sorted.insert(j + 1, unsorted[i])
i += 1
return sorted
while True: # Status loop if the user wants to use the program
status = str(input("Would you like to use the sorting program? (Y/N) "))
if status.upper() == "Y":
numList = []
type = input("Would you like to do an ascending or descending sort? ")
while True: # Input loop
num = int(input("Please input the numbers you wish to sort (input '-1' to end input) "))
if num >= 0:
numList.append(num)
elif num == -1:
break
print ("The sorted list of numbers in ascending order is")
if type.lower() == "ascending":
print (sort(numList))
elif type.lower() == "descending":
print(sort(numList)[::-1])
elif status.upper() == "N":
print("Thank you for using this sorting program!")
break | true |
c0842c0917df268ba89c1d1fac5c46154ce24960 | twhorley/twho | /matplotlib_tests.py | 1,540 | 4.34375 | 4 | """
Script to play around with how to make a variety of plots using matplotlib and
numpy. I'll be using object-oriented interface instead of the pyplot interface to
make plots because these are far more customizable.
"""
import matplotlib.pyplot as plt
import numpy as np
# Create a figure with 2 axes, both same scale, and plot a line
fig, ax = plt.subplots() # creates a figure containing a single axes scale
ax.plot([1,2,3,4], [4,1,3,2])
# plt.plot([1,2,3,4], [4,1,3,2]) <-- another way to make the same plot, but simpler
# Easiest to make a new figure and axes with pyplot
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes, defaults scale 0 to 1
fig, axs = plt.subplots(2,2) # a figure with a 2x2 grid of plots, default scale 0-1
# Plot different equations on one figure
x = np.linspace(0,2,100) # make array from 0 to 2 with 100 intervals between
fig, ax = plt.subplots() # create a figure iwth an axes
ax.plot(x, x, label='linear') # plot line x=y and name it 'linear'
ax.plot(x, x**2, label='quadratic') # plot line x^2 and name it 'quadratic'
ax.plot(x, x**3, label='cubic') # plot line x^3 and name it 'cubic'
ax.set_xlabel('x label') # add an x-label to the axes
ax.set_ylabel('y label') # add a y-label to teh axes
ax.set_title("Simple Plot") # add a title to the axes
ax.legend() # add a legend; I think this adds the 'label's made in the ax.plot() lines
# Show all the plots (made with 'plt') made up to this point
plt.show()
| true |
a98813061b478d0d7be602d6ba503f33ed228863 | LaKeshiaJohnson/python-fizz-buzz | /challenge.py | 664 | 4.3125 | 4 | number = int(raw_input("Please enter a number: "))
# values should be stored in booleans
# If the number is divisible by 3, print "is a Fizz number"
# If the number is divisible by 5, print "is a Buzz number"
# If the number is divisible by both 3 and 5, print is a FizzBuzz number"
# Otherwise, print "is neither a fizzy or buzzy number"
is_fizz = number % 3 == 0
is_buzz = number % 5 == 0
if (is_fizz and is_buzz):
print("{} is a FizzBuzz number.".format(number))
elif (is_fizz):
print("{} is a Fizz number.".format(number))
elif (is_buzz):
print("{} is a Buzz number.".format(number))
else:
print("{} is neither a fizzy or buzzy number.".format(number))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.