blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
36a3e44f366e2bcf8bbab61ce3cee2f551acd80b | itsfarooqui/Python-Programs | /Program15.py | 275 | 4.125 | 4 | #15. Write a method to find number of even number and odd numbers in an array.
arr = [8, 4, 3, 6, 9, 2]
i = 0
for i in range(0, len(arr)):
if arr[i]%2 == 0:
print("Even Number: ", arr[i])
else:
print("Odd Number: ", arr[i])
i = i +1 | true |
960bc02fa729a588f9220769365fd4194fc7e0a3 | thinkphp/rabin-miller | /rabin-miller.py | 2,613 | 4.21875 | 4 | # Miller-Rabin Probabilistic Primality Test.
#
# It's a primality test, an algorithm which determines whether a given number is prime.
#
# Theory
#
# 1. Fermat's little theorem states that if p is a prime and 1<=a<p then a^p-1 = 1(mod p)
#
# 2. If p is a prime x^2 = 1(mod p) or(x-1)(x+1) = 0 (mod p), then x = 1 (mod p) or x = -1 (mod p)
#
# 3. If n is an add prime then n-1 is an even number and can be written as 2^s*d. By Fermat's Little Theorem
# either a^d = 1 (mod n) or a^2^r*d = -1 (mod n) for some 0<=r<=s-1
#
# 4. The Rabin-Miller primality test is base on contrapositive of the above claim. That is, if we can find an
# a(witness) such that a^d != 1 (mod n) and a^2^r*d != -1 (mod p) for all 0<=r<=s-1 then a is witness of compositeness
# of n and we can say n is not prime, otherwise n may be prime.
#
# 5. We test our number P for some numbers random a and either declare that p is definitely a composite or probably
# a prime.
#
# The probably that a composite number is returned as prime after k iterations is 1/4^k.
#
# The Running Time: O(k log 3 n)
#
import random
def modexp(x, y, mod):
sol = 1
i = 0
while (1<<i) <= y:
if (1<<i)&y:
sol = (sol * x) % mod
x = (x * x) % mod
i = i + 1
return sol
#
# @param n, n > 3, an odd integer to be tested for primality
# @param accuracy, a parameter that determines the accuracy of the test
# @return false, if n is composite, otherwise probably prime
#
def isPrime(n, accuracy):
# If the number is 2 or 3, then return True
if n == 2 or n == 3:
return True
# if the number is negative or oven then I have to return False
if n<=1 or n&1 == 0:
return False
# next step we write n-1 as 2^s*d
s = 0
m = n - 1
while m&1 == 0:
s += 1
m >>= 1
# now we have and s and d as well
d = (n-1) / (1<<s)
for i in range(1, accuracy + 1):
# next step we pick a random number between 2 and n-2
# we call a a witness for compositeness of n, or is called
# strong liar when is n is probably prime to a base a.
witness = random.randint(2,n-2)
q = modexp(witness, d, n)
if q == 1 or q == n - 1:
continue
for i in range(0, s):
q = modexp(q, 2, n)
if q == 1:
return False
if q == n-1:
break
return False
# return n is probably prime
return True
print isPrime(21, 3)
| true |
15b439cc89bae13fbfd7a981ce68aa5c23ecaf0f | randcyp/FIT2085 | /Practical 1/Exercise 1 - task_1.py | 1,633 | 4.21875 | 4 | # Non-assessed practical
"""
This module demonstrates a way to interface basic list
operations.
"""
__author__ = "Chia Yong Peng"
from typing import List, TypeVar
T = TypeVar('T')
list_of_items = []
def print_menu() -> None:
"""
Prints the menu.
"""
menu_items = ["append", "reverse", "print", "pop", "count", "quit"]
print("Menu: ")
for i in range(0, len(menu_items)):
print(str(i+1) + ". " + menu_items[i])
print()
def reverse(ls: List[T]) -> List[T]:
"""
Reverses a list.
:param ls: The list to be reversed
:return: The reversed list
"""
for i in range(len(ls) // 2):
ls[i], ls[len(ls) - 1 - i] = ls[len(ls) - 1 - i], ls[i]
return ls
def count(ls: List[T], obj: T) -> int:
"""
Returns the number of times an element appears in a list
:param ls: The list to iterate through
:param obj: The element to be counted
:return: The number of times an element appears in a list
"""
return len([x for x in ls if x is obj])
# Displays the menu and prompts for an option
while True:
print_menu()
option = int(input("Enter an option: "))
if option == 1:
item = input("Enter an item: ")
list_of_items.append(item)
elif option == 2:
reverse(list_of_items)
elif option == 3:
print(list_of_items)
elif option == 4:
print(list_of_items.pop())
elif option == 5:
item = input("Enter an item: ")
print(count(list_of_items, item))
elif option == 6:
exit()
else:
print("You've entered an invalid option, please try again.")
print()
| true |
583f9a7bf7f1aa39295f404f8ad42ba4c529abb3 | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 040 - Sound Levels.py | 845 | 4.4375 | 4 | # Exercise 40: Sound Levels
# Jackhammer 130 dB
# Gas Lawnmower 106 dB
# Alarm Clock 70 dB
# Quiet Room 40 dB
Sound=float(input("Enter a number to define a sound level in decibels: "))
if Sound > 130:
Sound="The sound level is louder than a Jackhammer"
elif Sound == 130:
Sound="The sound level is Jackhammer"
elif Sound > 106 :
Sound="The sound level is between Gas Lawnmower and Jackhammer"
elif Sound == 106:
Sound="The sound level is Gas Lawnmower"
elif Sound > 70 :
Sound="The sound level is between Alarm Clock and Gas Lawnmower"
elif Sound == 70:
Sound="The sound level is Alarm Clock"
elif Sound >40 :
Sound="The sound level is between Quiet Room and Alarm Clock"
elif Sound == 40:
Sound="The sound level is Quiet Room"
else:
Sound="The sound leve is between silence and Quiet Room"
print(Sound)
| true |
93153b09c6c76b9e8b7daf4643d507e2a4bbacde | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 051 - Roots of a Quadratic Function.py | 547 | 4.1875 | 4 | # Exercise 51: Roots of a Quadratic Function
import math
a=float(input("Enter the value a: "))
b=float(input("Enter the value b: "))
c=float(input("Enter the value c: "))
discriminant = (b**2) - (4 * a * c)
print(discriminant)
if discriminant < 0:
print("has no real roots")
elif discriminant == 0:
result = (-b / (2 * a))
print(result)
else:
root1 = (- b - math.sqrt(discriminant)) / (2 * a)
root2 = (- b + math.sqrt(discriminant)) / (2 * a)
print("the first root is:", root1)
print("the second root is:", root2)
| true |
22c14c12f08fcc25ab970493f8ef05cb5b73982b | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 035 - Even or Odd.py | 208 | 4.125 | 4 | # Exercise 35: Even or Odd?
number=int(input("Enter a valid integer number: "))
number1=number % 2
if number1 == 0:
number1="the number is even."
else:
number1="the number is odd: "
print(number1)
| true |
b971b310ae02ec049a32d1bebca9ea41a6ac5fb1 | taoyuc3/SERIUS_NUS | /5.28.py | 1,699 | 4.125 | 4 | # https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# Load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.data.csv", delimiter=",")
# split into input (X) and output (Y) variables
# the dataset has 9 cols, 0:8 will select 0 to 7, stopping before index 8
# *Numpy Arrays for ML in Python
X = dataset[:, 0:8]
Y = dataset[:, 8]
# Define a sequential model and add layers one at a time
model = Sequential()
# first layer has 12 neurons and expects 8 inputs with rectifier activation function
model.add(Dense(12, input_dim=8, activation='relu'))
# the hidden layer has 8 neurons
model.add(Dense(8, activation='relu'))
# finally the output layer has 1 neuron to predict the class (onset of diabetes or not)
model.add(Dense(1, activation='sigmoid'))
# Compile modelsurface-defect-detection
# binary_crossentropy refer to logarithmic loss
# adam refers to gradient descent
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit/Train model
# 150 iterations with the batch size 10
# these can be chosen experimentally by trial and error
model.fit(X, Y, epochs=150, batch_size=10, verbose=2)
# # Evaluate
# # we have trained our nn on the entire dataset, but only know train accuracy
# # don't know how well the algorithm might perform on new data
# scores = model.evaluate(X, Y)
# print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
# calculate predictions
predictions = model.predict(X)
# round predictions
rounded = [round(x[0]) for x in predictions]
print(rounded)
| true |
9d44df3ad84744af06d02d53553f0049c382f2d2 | Nana-Antwi/UVM-CS-21 | /distance.py | 799 | 4.125 | 4 | #Nana Antwi
#cs 21
#assignment 4
#distance.py
#write a program that calculates distance
#distance is equal to speed muliple by time
#variables
speed = 0.0
time = 0.0
distance = 0.0
var_cons = 1.0
#user input variable
speed = float(input('Enter speed: ')) #user prompts
#condition loop statements
while speed <= 0:
print('Speed must always be greater than zero')
speed = int(input('Enter speed: '))
time = int(input('Enter time: '))
while time <= 0:
print('Time must always be greater than zero')
time = int(input('Enter time: '))
#results output
print('Hour of distance treavelled')
print('---------------------------')
for var_cons in range(1, (time + 1)):
distance = var_cons * speed
print(var_cons, "\t", format(distance, ',.1f'))
| true |
0c2bc2ff035678d3f8d947124c05d6293a0c7da0 | rynoV/andrew_ng-ml | /mongo-lin-reg/src/computeCost.py | 790 | 4.3125 | 4 | import numpy as np
def computeCost(X, y, theta):
"""
Compute cost for linear regression with multiple variables.
Computes the cost of using theta as the parameter for linear regression to fit the data points in X and y.
Parameters
----------
X : array_like
The dataset of shape (m x n+1).
y : array_like
A vector of shape (m, ) for the values at a given data point.
theta : array_like
The linear regression parameters. A vector of shape (n+1, )
Returns
-------
J : float
The value of the cost function.
"""
m = y.shape[0] # number of training examples
predictions = X @ theta
differences = predictions - y
J = (1/(2*m)) * np.sum(differences**2)
return J
| true |
7a2aba24cf92a368bdeef9eae3951420627c2830 | nazomeku/miscellaneous | /fizzbuzz.py | 489 | 4.375 | 4 | def fizzbuzz(x):
"""Take integer and check if it is divisable by:
3: return 'fizz',
5: return 'buzz',
3 and 5: return 'fizzbuzz',
otherwise: return input as string.
Args:
x: The integer for which the condition is checked.
Returns:
Corresponding string value.
"""
if x % 3 == 0 and x % 5 == 0:
return "fizzbuzz"
elif x % 3 == 0:
return "fizz"
elif x % 5 == 0:
return "buzz"
else:
return str(x)
| true |
cc79f38420b39113f7d988a6171bdf3fd6f27e2d | UmmadisettyRamsai/ramsai | /labprogramme2.py | 1,140 | 4.46875 | 4 |
# basic operations on single array
#A PYTHON PROGRAM TO PERFORM UNIARY OPERATIONS
import numpy as np
a = np.array([1, 2, 5, 3])
# add 2 to every element
print ("Adding 2 to every element:", a+2)
# subtract 3 from each element
print ("Subtracting 3 from each element:", a-3)
# multiply each element by 10
print ("Multiplying each element by 10:", a*10)
# square each element
print ("Squaring each element:", a**2)
# modify existing array
a *= 2
print ("Doubled each element of original array:", a)
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())
| true |
ab7ef4dd24c0e21a857cd1a8c28c9fdb36739169 | Psycadelik/sifu | /general/is_integer_palindrome.py | 486 | 4.15625 | 4 | """
Check Whether a Number is Palindrome or Not
Time complexity : O(log 10(n)).
We divided the input by 10 for every iteration,
so the time complexity is O(log10(n))
Space complexity : O(1)
"""
def is_palindrome(num):
original_num = num
reversed_num = 0
while (num != 0):
num, rem = divmod(num, 10)
reversed_num = (reversed_num * 10) + rem
return original_num == reversed_num
assert is_palindrome(121) == True
assert is_palindrome(1212) == False
| true |
1f3533dc0dd324766f4e7d39681dbdf434ad0d4d | MPeteva/HackBulgariaProgramming101 | /Week0/1-PythonSimpleProblemsSet/T11_CountSubstrings.py | 330 | 4.25 | 4 | def count_substrings(haystack, needle):
count_of_occurrences = haystack.count(needle)
return count_of_occurrences
def main():
String = input("Input a string: ")
Word = input("Input a word to count occurrences of it in string: ")
print (count_substrings(String, Word))
if __name__ == '__main__':
main()
| true |
15836a7c158c46605a536ab7b889119eed45fe7b | SaudiWebDev2020/Sumiyah_Fallatah | /Weekly_Challenges/python/week5/wee5day3.py | 2,632 | 4.3125 | 4 | # Create a queue using 2 stacks. A hint: stack1 will hold the contents of the actual queue, stack2 will be used in the enQueueing
# Efficiency is not the goal!
# Efficiency is not the goal!
# Efficiency is not the goal!
# The goal is to practice using one data structure to implement another one, in our case Queue from 2 Stacks
# Queue is FIFO --> First In First out
# Stack is LIFO --> Last In First Out
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
class QueueOfStacks:
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
# def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def front(self):
if self.head == None:
return None
else:
print('top is :')
print (self.head.value)
def isEmpty(self):
if self.head == None:
print ("this stack is empty")
else:
print ("this stack is not empty")
def size(self):
temp = self.head
count = 0
while(temp):
count+=1
# print('value', temp.value)
temp = temp.next
print('size is :', count)
return count
def deQueue(self):
temp = 0
if self.head == self.tail:
self.head = None
self.tail = None
else:
temp = self.head
self.head = self.head.next
return temp.value
def enQueue(self, value):
if self.head == None:
new_node = StackNode(value)
self.head = new_node
self.tail = new_node
else:
new_node = StackNode(value)
self.tail.next = new_node
self.tail = new_node
# Optional
# def showQS(self):
# pass
# head = self.head
# while(head):
# print(head.value)
# head = head.next
stack1 = QueueOfStacks.Stack()
stack2 = QueueOfStacks.Stack()
stack1.isEmpty()
print('*'*70)
stack2.isEmpty()
stack1.enQueue(7)
# stack1.showQS()
print(stack1.front())
stack1.isEmpty()
print('*'*70)
print(stack1.deQueue())
stack1.isEmpty() | true |
c059e02dfe1f9c556b82de12ee26cd89a810db93 | ton4phy/hello-world | /Python/55. Logic.py | 253 | 4.28125 | 4 | # Exercise
# Implement the flip_flop function, which accepts a string as input and, if that string is 'flip',
# returns the string 'flop'. Otherwise, the function should return 'flip'.
def flip_flop(arg):
return 'flop' if arg == 'flip' else 'flip'
| true |
ca71548c786da72de4c83531cdba7a5d8e6f3519 | ton4phy/hello-world | /Python/57. Cycles.py | 379 | 4.3125 | 4 | # Exercise
# Modify the print_numbers function so that it prints the numbers in reverse order. To do this,
# go from the top to the bottom. That is,
# the counter should be initialized with the maximum value,
# and in the body of the loop it should be reduced to the lower limit.
def print_numbers(n):
while n > 0:
print(n)
n = n - 1
print('finished!')
| true |
af32739412f82b395268bf8a13e89b42184a8bb8 | ton4phy/hello-world | /Python/59. Cycles.py | 817 | 4.125 | 4 | # Exercise
# Implement the is_arguments_for_substr_correct predicate function, which takes three arguments:
# the string
# index from which to start extraction
# extractable substring length
# The function returns False if at least one of the conditions is true:
# Negative length of the extracted substring
# Negative given index
# The specified index extends beyond the entire line.
# The length of the substring in the amount with the specified index extends beyond the boundary of the entire line.
# Otherwise, the function returns True.
def is_arguments_for_substr_correct(string, index, length):
if index < 0:
return False
elif length < 0:
return False
elif index > len(string) - 1:
return False
elif index + length > len(string):
return False
return True
| true |
bd152a5e10c36bfc628bcd88b405966b3741c0c2 | Chriskoka/Kokanour_Story | /Tutorials/mathFunctions.py | 557 | 4.28125 | 4 | """
Math Functions
"""
#Variables
a = 3
b = -6
c = 9
#Addition & Subtraction
print(a+b)
print(a-b)
#Multiplication & Division
print(a * b)
print(a / b)
#exponents
print(a ** b) # Notice ** means to the power of
print(b ** a)
#Square Root & Cube Root
print(c ** (1/3))
print(c ** (1/2))
#Modulus (% symbol is used) -- Only returns the remainder after division
print(c % a) #Said as c mod a
print(c%4)
"""In order to do advanced math like sine, cosine, etc, you have to inport math and add .math to the function"""
import math
print(math.sin(a)) | true |
20ffa4780a571b56cd17304dde237f4a4fb7eed5 | Chriskoka/Kokanour_Story | /Tutorials/addSix.py | 233 | 4.3125 | 4 | """
This program will take the input of the user and return that number plus 6 in a print statement
"""
numb = int(input ('Choose an integer from 1 to 10. Input: '))
print ('The number ' + str(numb) + ' plus six = ' + str(numb + 6)) | true |
0838e7bca4295999e847c41b218bd1b5b928e6c1 | josandotavalo/OSSU | /001-Python-for-Everyone/Exercise-9.5.py | 814 | 4.15625 | 4 | # Exercise 5: Write a program to read through the mail box data and when you find line that starts
# with “From”, you will split the line into words using the split function. We are interested in who
# sent the message, which is the second word on the From line.
# You will parse the From line and print out the second word for each From line, then you will also
# count the number of From (not From:) lines and print out a count at the end.
file_name = input("Enter file name: ")
if len(file_name) < 1 : file_name = "mbox-short.txt"
file_hand = open(file_name)
count = 0
for line in file_hand :
if line.startswith("From:") :
aux = line.split()
email = aux[1]
print(email)
count = count + 1
print("There were", count, "lines in the file with From as the first word") | true |
ce6840467ee5ec0a8cb7748bd7441527b6fad2da | mohit-singh4180/python | /string operations/StringLogical operation.py | 645 | 4.3125 | 4 | stra=''
strb='Singh'
print(repr(stra and strb))
print(repr(stra or strb))
stra='Mohit'
print(repr(stra and strb))
print(repr(strb and stra))
print(repr(stra or strb))
print(repr(not stra))
stra=''
print(repr(not stra))
# A Python program to demonstrate the
# working of the string template
from string import Template
# List Student stores the name and marks of three students
Student = [('Ram',90), ('Ankit',78), ('Bob',92)]
# We are creating a basic structure to print the name and
# marks of the students.
t = Template('Hi $name, you have got $marks marks')
for i in Student:
print (t.substitute(name = i[0], marks = i[1])) | true |
ea291fcdc704b8133b4b0ef66f3883c251776399 | gonegitdone/MITx-6.00.2x | /Week 5 - Knapsack and optimization/L9_Problem_2.py | 1,897 | 4.15625 | 4 | # ==============L9 Problem 2 =================
'''
L9 PROBLEM 2 (10 points possible)
Consider our representation of permutations of students in a line from Problem 1. In this case, we will consider a
line of three students, Alice, Bob, and Carol (denoted A, B, and C). Using the Graph class created in the lecture,
we can create a graph with the design chosen in Problem 1. To recap, vertices represent permutations of the students
in line; edges connect two permutations if one can be made into the other by swapping two adjacent students.
We construct our graph by first adding the following nodes:
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
nodes.append(Node("BAC")) # nodes[2]
nodes.append(Node("BCA")) # nodes[3]
nodes.append(Node("CAB")) # nodes[4]
nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
Add the appropriate edges to the graph.
Hint: How to get started?
Write your code in terms of the nodes list from the code above. For each node, think about what permutation is
allowed. A permutation of a set is a rearrangement of the elements in that set. In this problem, you are only
adding edges between nodes whose permutations are between elements in the set beside each other .
For example, an acceptable permutation (edge) is between "ABC" and "ACB" but not between "ABC" and "CAB".
'''
from graph import *
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
nodes.append(Node("BAC")) # nodes[2]
nodes.append(Node("BCA")) # nodes[3]
nodes.append(Node("CAB")) # nodes[4]
nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
g.addEdge(Edge(nodes[0], nodes[1]))
g.addEdge(Edge(nodes[0], nodes[2]))
g.addEdge(Edge(nodes[1], nodes[4]))
g.addEdge(Edge(nodes[2], nodes[3]))
g.addEdge(Edge(nodes[3], nodes[5]))
g.addEdge(Edge(nodes[4], nodes[5]))
| true |
a05b26542169a4cb883d87c62baee613856ece9d | CallieCoder/TechDegree_Project-1 | /01_GuessGame.py | 938 | 4.125 | 4 | CORRECT_GUESS = 34
attempts = [1]
print("Hello, welcome to the Guessing Game! \nThe current high score is 250 points.")
while True:
try:
guess = int(input("Guess a number from 1 - 100: "))
except ValueError:
print("Invalid entry. Please enter numbers as integers only.")
else:
if guess < 1 or guess > 100:
print("This number is outside of the specified range. Stay between 1 - 100.")
elif guess < CORRECT_GUESS:
print("Sorry, {} is too low. Try a higher number.".format(guess))
attempts.append(guess)
elif guess > CORRECT_GUESS:
print("Sorry, {} is too high. Try a lower number.".format(guess))
attempts.append(guess)
elif guess == CORRECT_GUESS:
print("That's the correct guess!!")
print("You guessed {} times.".format(len(attempts)))
play_again = input("would you like to play again? (yes/no): ")
if play_again == "no":
break
print("Thanks for playing today. Goodbye!")
| true |
28b749e2ea944bcd4e56112453fd2b9836da0cca | amrfekryy/daysBetweenDates | /daysBetweenDates.py | 1,800 | 4.375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
def isLeapYear(year):
"""returns True if year is leap. otherwise, False"""
# a leap year is a multiple of 4 (EXCEPT all hundreds BUT including multiples of 400)
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
else:
return False
def daysInMonth(year,month):
"""returns the number of days in a given month, taking leap years into account"""
if isLeapYear(year) and month == 2:
return 29
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return daysOfMonths[month - 1]
def nextDay(year,month,day):
"""returns the date of the day next to year-month-day"""
day += 1
if day > daysInMonth(year,month):
day = 1
month += 1
if month > 12:
month = 1
year += 1
return year, month, day
def dateIsBefore(year1,month1,day1,year2,month2,day2):
"""returns True if year1-month1-day1 is before year2-month2-day2. otherwise, False"""
if (year1 < year2) or (year1 == year2 and month1 < month2) or (year1 == year2 and month1 == month2 and day1 < day2):
return True
return False
def daysBetweenDates(year1,month1,day1,year2,month2,day2):
"""returns number of days between two dates"""
# assert date1 is before date2
assert not dateIsBefore(year2,month2,day2,year1,month1,day1)
# assert date1 is valid in the Gregorian calendar
assert not dateIsBefore(year1,month1,day1,1582,10,15)
days = 0
while dateIsBefore(year1,month1,day1,year2,month2,day2):
days += 1
year1,month1,day1 = nextDay(year1,month1,day1)
return days
| true |
b1545d03a2ae61fa8c7858f14183f60ff9ff4493 | joshp123/Project-Euler | /4.py | 460 | 4.21875 | 4 | def isPalindrome(string):
if string == string[::-1]:
return 1 # string reversed = string
else:
return 0 # not a palindrome
palindromes = []
for num1 in xrange(999, 100, -1):
for num2 in xrange(999, 100, -1):
product = num1 * num2
if isPalindrome(str(product)) == 1:
palindromes.append(product)
print 'The largest palindrome from the product of 2 three digit numbers is: ' + repr(max(palindromes))
| true |
e805d017fb69438e5cf968288dfd77488a00246f | zjuKeLiu/PythonLearning | /GUI.py | 1,306 | 4.21875 | 4 | import tkinter
import tkinter.messagebox
def main():
flag = True
#change the words on label
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world')
label.conflg(text = msg, fg = color)
#quit
def confirm_to_quit():
if tkinter.massageboc.askokcancel('notice', 'are you sure to quit?'):
top.quit()
#create the top window
top = tkinter.Tk()
#set the size of window
top.geometry('240*160')
#set the title of window
top.title('Game')
#create the label and add it to the top window
label = tkinter.Label(top, text = 'Hello, world!', font = 'Arial -32', fg = 'red')
label.pack(expand=1)
#create a container to contain the button
panel = tkinter.Frame(top)
#create a button , attach it to the container, use the parameter of command to attach it to the function
button1 = tkinter.Button(panel, text='change', command=change_label_text)
button1.pack(side='left')
button2 = tkinter.button(panel, text='quit', command=confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
#start the main loop of issue
tkinter.mainloop()
if __name__ == '__main__':
main()
| true |
1603adb378d36caaba42ea862482e4810f3591b2 | igusia/python-algorithms | /binary_search.py | 452 | 4.125 | 4 | import random
#searching for an item inside a search structure
def binary_search(search, item):
low = 0
high = len(search)-1
while low <= high:
mid = (low + high)//2 #if odd -> returns a lower number
guess = search[mid]
if guess < item:
low = mid+1 #it's not mid, so we don't take it
elif guess > item:
high = mid-1 #as with low
else:
return mid
return None
| true |
cd70df45ab8f7635e3e4d4ae38fed02e8bab4e51 | oluyalireuben/python_workout | /session_one.py | 1,398 | 4.25 | 4 | # getting started
print("Hello, World!")
# syntax
if 5 > 2:
print("Five is greater than two")
# Variables
x = 23
y = 45
print(x + y)
a = "python "
b = "is "
c = "awesome"
print(a + b + c)
u = "I like "
j = "Codding "
k = "with python language"
print(u + j + k)
# python numbers and strings
h = "Welcome to eMobilis College"
s = 2
d = 2.8
y = 3j
print(type(s))
print(type(d))
print(type(y))
# Counting of the characters in a statement
print(len(h))
# To print all the characters on lower case and upper case
print(h.lower())
print(h.upper())
# Working with Operators
peter = 23 + 23
jack = 46
print(jack is peter)
o = ["Ian", "Dylan","Andrew", "Kevin"]
print("Paul" in o)
thistuple = tuple(("apple", "banana", "cherry" ))
print(len(thistuple))
# Conditional statements
zulu = 45
south = 45
if zulu < south:print("zulu is less than south")
elif zulu == south:
print("zulu and south are equal")
else:print("south is greater than zulu")
# While loops (While loops and for loops)
peter = 1
while peter < 23:
print(peter)
peter +=1
jack < 5
while jack < 5:
jack +=1
print(jack)
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
# for loop
noise_makers = ["Ian","Zeff" , "Paul" , "Peter" , "Reuben" , "Kevin" , "Chairman" , "Temmy"]
for n in noise_makers:
print(n)
# done to print a lis tof decimal numbers
for s in range(4):
print(s)
| true |
090435b9cf27a02233288045250d90f4181f4b9b | Maciejklos71/PythonLearn | /Practice_python/palidrom.py | 635 | 4.4375 | 4 | #Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
def palidrom(string):
string = string.lower().replace(" ","")
for i in range(0,len(string)):
if string[i]==string[-i-1]:
if i == len(string)-1:
print("This string is palidrom!")
continue
if string[i]!=string[-i-1]:
print("This string isn't palidrom")
exit()
print("This string is palidrom!")
palidro = "a tu mam mamuta".lower().replace(" ","")
palidrom(palidro)
| true |
692d14e3fea32a798eb19731e5d2b214fa40dcdc | robado/automate-the-boring-stuff-with-python | /2. Flow Control/5. If, Else, and Elif Statements.py | 1,216 | 4.1875 | 4 | # if statement
name = 'Alice'
if name == 'Alice':
print('Hi Alice')
print('Done')
# Hi Alice
# Done
# if name is other than Alice than the output will beDone
# else statement
password = 'swordfish'
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
# If password is swordfish then output is Access granted but if not then the output is Wrong password
name = 'Bob'
age = 3000
if name == 'Alice':
print('Hi Alice')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
# Unlike you, Alice is not an undead, immortal vampire.
# Truthy and Falsey Values
print('Enter a name.')
name = input()
if name: # better option would be to use name != ''
print('Thank you for entering a name.')
else:
print('You did not enter a name')
# Blank string is falsey all others are truthy
# for int 0 and 0.0 are falsey, all others are truthy
print(bool(0)) # False
print(bool(42)) # True
print(bool('Hello')) # True
print(bool('')) # False
# Resources
# https://automatetheboringstuff.com/chapter2/
# http://pythontutor.com/
| true |
dd109d0231382f4680d93159ac106fe0f9d2e0b0 | scarletgrant/python-programming1 | /p9p1_cumulative_numbers.py | 593 | 4.375 | 4 | '''
PROGRAM
Write a program that prompts the user for a positive integer and uses a
while loop to calculate the sum of the integers up to and including that number.
PSEUDO-CODE
Set and initialize number to zero
Set and initialize total to zero
Prompt user for first positive integer
While number => 0:
total += number
print total
Prompt user for a new positive integer
'''
number = 0
total = 0
number = int(input("Please enter a positive number: "))
while number >= 0:
total += number
print("Total is:", total)
number = int(input("Please enter a positive number: "))
| true |
340b1481b39b4ed272b3bd09ad648f933570e7de | scarletgrant/python-programming1 | /p8p3_multiplication_table_simple.py | 415 | 4.3125 | 4 | '''
PROGRAM p8p3
Write a program that uses a while loop to generate a simple multiplication
table from 0 to 20.
PSEUDO-CODE
initialize i to zero
prompt user for number j that set the table size
while i <= 20:
print(i, " ", i*j)
increment i+=1
print a new line with print()
'''
i = 0
j = int(input("Please enter a number: "))
while i <= 20:
print(i, " ", i*j)
i+=1
print()
| true |
3bfb8410e8a4e2b498ed3387833a74ed905088e3 | scarletgrant/python-programming1 | /p10p1_square_root_exhaustive_enumeration.py | 1,305 | 4.25 | 4 | '''
PROGRAM
Write a program that prompts the user for an integer and performs exhaustive
enumeration to find the integer square root of the number. By “exhaustive enumeration”,
we mean that we start at 0 and succcessively go through the integers, checking whether
the square of the integer is equal to the number entered.
If the number is not a perfect square, the program should print out a
message to that effect. The program should exit when a negative number
is entered.
PSEUDO-CODE
# Prompt user for a positive integer (number) to calculate the square root for
number = int(input("Please enter a (whole) number that you like to calculate the square root for: "))
If number >= 0
Initialize square_root to zero
While square_root ** 2 < number:
square_root += 1
if square_root ** 2 == number:
print("Square root of", number, "is", square_root)
else:
print(number, "is not a perfect square.")
'''
number = int(input("Please enter a (whole) number that you like to calculate the square root for: "))
if number >= 0:
square_root = 0
while square_root ** 2 < number:
square_root += 1
if square_root ** 2 == number:
print("Square root of", number, "is", square_root)
else:
print(number, "is not a perfect square.")
| true |
707e0ea61e1f821b44b7225c5e287a6645a04815 | LucaDev13/hashing_tool | /hashing/hash_text.py | 1,252 | 4.1875 | 4 | from algoritms import sha1_encryption, sha224_encryption, sha256_encryption, sha512_encryption, md5_encryption, \
sha3_224_encryption
print("This program works with hashlib library. It support the following algorithms: \n"
"sha1, sha224, sha256, sha512, md5, sha3_224\n")
print("In order to use this program choose an algorithm from the above list \n"
"and then insert the string to be hashed with the chosen algorithm. \n")
print('When done press q + Enter to stop the program. \n')
while True:
chosen_algorithm = input("Choose the encryption algorithm to be used: \n")
print('\n' + f'Enter string to hash in {chosen_algorithm} algorithm: ' + '\n')
string = input()
if string == "q":
print('See you next time!')
break
else:
if chosen_algorithm == 'sha1':
sha1_encryption(string)
if chosen_algorithm == 'sha224':
sha224_encryption(string)
if chosen_algorithm == 'sha256':
sha256_encryption(string)
if chosen_algorithm == 'sha512':
sha512_encryption(string)
if chosen_algorithm == 'sha3_224':
sha3_224_encryption(string)
if chosen_algorithm == 'md5':
md5_encryption(string)
| true |
47208a23d4ea29f0ad4cf605d0ded3aa4c4ca495 | tripaak/python | /Practice_Files/cube_finder.py | 638 | 4.1875 | 4 | # Execercise
# Define a Function that takes a number
# return a dictionary containing cubes of number from 1 to n
# example
# cube_finder(3)
# {1:1, 2:8, 3:27}
####### First approach
# def cube_finder(input_number):
# dNumb = {}
# for j in range(1,input_number + 1):
# vCube = 1
# for i in range(1,4):
# vCube = vCube * j
# dNumb[j] = vCube
# return dNumb #print(vCube, end=" ")
####### Second approach
def cube_finder(n):
cubes = {}
for i in range(1,n+1):
cubes[i] = i**3 # Without using FOR loop
return cubes
print(cube_finder(10)) | true |
e8f93243c5fdb8b236abf3defd638a338884ca14 | vibhor-shri/Python-Basics | /controlflow/Loops.py | 400 | 4.34375 | 4 | separator = "============================"
print("Loops in python")
print("There are 2 types of loops in python, for loops and while loop")
print(separator)
print()
print()
print("A for loop, is used to iterate over an iterable. An iterable is an object which returns one of it's elements "
"at a time")
cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"]
for city in cities:
print(city)
| true |
3817df8619e45824b2a425b5e2768bd6d8989b40 | curtisjm/python | /personal/basics/functions.py | 1,210 | 4.46875 | 4 | # declare a function
def my_function():
print("Hello from a function")
# call a function
my_function()
# arbitrary arguments
# if you do not know how many arguments that will be passed into your function,
# add a * before the parameter name in the function definition
# this way the function will receive a tuple of arguments
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# keyword arguments with key = value syntax
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
# arbitrary keyword arguments
# if you do not know how many keyword arguments that will be passed into your function,
# add two asterisk: ** before the parameter name in the function definition.
# this way the function will receive a dictionary of arguments
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
# default parameter value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function()
# return values
def my_function(x):
return 5 * x
print(my_function(5))
| true |
7de2665bd9b5d91fab286fd7b09c4172d85363ad | curtisjm/python | /personal/basics/inheritance.py | 1,890 | 4.5625 | 5 | # create a parent class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
# to create a class that inherits the functionality from another class,
# send the parent class as a parameter when creating the child class
class Student(Person):
pass
# use the Student class to create an object,
# and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
# the child's __init__() function overrides the inheritance of the parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
x = 1
# add properties etc
# to keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
# super() function will make the child class inherit all the methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
# add a property called graduationyear to the Student class:
self.graduationyear = 2019
# add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
# add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
# if you add a method in the child class with the same name as a function in the parent class,
# the inheritance of the parent method will be overridden. | true |
f0c27da11efe0dfda2bc81b296bedfdc64303b2b | chettayyuvanika/Questions | /Easy/Pascals_Triangle_Problem.py | 1,236 | 4.28125 | 4 | # Problem Name is Pascals Triangle PLEASE DO NOT REMOVE THIS LINE.
"""
/*
** The below pattern of numbers are called Pascals Triangle.
**
** Pascals Triangle exhibits the following behaviour:
**
** The first and last numbers of each row in the triangle are 1
** Each number in the triangle is the sum of the two numbers above it.
**
** Example:
** 1
** 1 1
** 1 2 1
** 1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
**
** Please Complete the 'pascal' function below so that given a
** col and a row it will return the value in that positon.
**
** Example, pascal(1,2) should return 2
**
*/
"""
def pascal(col, row):
if col==0 or row==0 or row==col:
return 1
else:
return pascal(col-1,row-1)+pascal(col,row-1)
def doTestPass():
""" Returns 1 if all tests pass. Otherwise returns 0. """
doPass = True
pascalColRowValues={(0,0):1,(1,2):2,(5,6):6,(5,5):1}
for key, val in pascalColRowValues.items():
if pascal(key[0],key[1]) != val:
doPass = False
print("Failed for {} and {} \n", format(key, val))
if doPass:
print("All tests pass\n")
return doPass
if __name__ == "__main__":
doTestPass() | true |
0311c673ba64df27b3acf07c4ade56ebbc823a87 | chettayyuvanika/Questions | /Medium/Best_Average_grade_Problem.py | 1,820 | 4.1875 | 4 | # Problem Name is &&& Best Average Grade &&& PLEASE DO NOT REMOVE THIS LINE.
"""
Instructions:
Given a list of student test scores, find the best average grade. Each student may have more than one test score in the list.
Complete the bestAverageGrade function in the editor below. It has one parameter, scores, which is an array of student test scores. Each element in the array is a two-element array of the form [student name, test score] e.g. [ "Bobby", "87" ]. Test scores may be positive or negative integers.
If you end up with an average grade that is not an integer, you should use a floor function to return the largest integer less than or equal to the average. Return 0 for an empty input.
Example:
Input:
[ [ "Bobby", "87" ],
[ "Charles", "100" ],
[ "Eric", "64" ],
[ "Charles", "22" ] ].
Expected output: 87
Explanation: The average scores are 87, 61, and 64 for Bobby, Charles, and Eric, respectively. 87 is the highest.
"""
""" Find the best average grade. """
def bestAverageGrade(scores):
""" Returns true if the tests pass. Otherwise, returns false """
# TODO: implement more test cases
d=dict()
for i in scores:
if i[0] in d:
d[i[0]].append(int(i[1]))
else:
d[i[0]]=[int(i[1])]
avg=0
for i in d:
avg1=sum(d[i])//len(d[i])
if avg1>avg:
avg=avg1
return avg
def doTestsPass():
""" Returns true if the tests pass. Otherwise, returns false """
# TODO: implement more test cases
tc1 = [ [ "Bobby", "87" ], [ "Charles", "100" ], [ "Eric", "64" ], [ "Charles", "22" ] ];
return bestAverageGrade(tc1)==87
if __name__ == "__main__":
result = doTestsPass()
if result:
print("All tests pass\n");
else:
print("Tests fail\n");
| true |
ec304864d363af08d7245df034c786523674b85d | kornel45/basic_algorithms | /quick_sort.py | 533 | 4.15625 | 4 | #!/usr/bin/python
import random
def quick_sort(lst):
"""Quick sort algorithm implementation"""
if len(lst) < 2:
return lst
pivot = lst[random.randint(0, len(lst) - 1)]
left_list = []
right_list = []
for val in lst:
if val < pivot:
left_list.append(val)
elif val > pivot:
right_list.append(val)
return quick_sort(left_list) + [pivot] + quick_sort(right_list)
if __name__ == '__main__':
ar = [1, 5, 2, 0, 3, 7]
assert sorted(ar) == quick_sort(ar)
| true |
a7faa8c5043ecf8405c113f3ef1b7e21bc690dc9 | TarSen99/python3 | /lab7_3.py | 1,163 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def UI_input_string() -> str:
'''Function input string'''
checkString = input("Enter some string ")
return checkString
def UI_print_result(result: bool):
'''Print result'''
if result:
print("String is correct")
else:
print("String is NOT correct")
def remove_characters(checkString: str) -> str:
'''Remove all characters except brackets'''
brackets = ['(', ')', '{', '}', '[', ']', '<', '>']
for _ in checkString:
if _ not in brackets:
checkString = checkString.replace(_, "")
return checkString
def check_brackets(checkString: str) -> str:
'''check if correct couples of brackets exist'''
print(checkString)
brackets = ['()', '{}', '[]', '<>']
while len(checkString) > 0:
startLen = len(checkString)
for _ in brackets:
if _ in checkString:
checkString = checkString.replace(_, "")
if len(checkString) == 0:
return True
if startLen == len(checkString):
break
return False
UI_print_result(check_brackets(remove_characters(UI_input_string()))) | true |
875bb31378cf1de15998763dc39d985c906bd6d3 | TarSen99/python3 | /lab8_2.py | 758 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def set_size() -> int:
'''inputs size'''
size = int(input("Enter size of list "))
return size
def print_sorted(currList: list):
'''print sorted list'''
print(currList)
def generate_list(size: int) -> list:
'''generate list'''
currList = [random.randint(1,30) for currList in range(size)]
return currList
def sort_list(currList: list) -> list:
'''sort list'''
for _ in range(len(currList)-1,0,-1):
for i in range(_):
if currList[i]>currList[i+1]:
temp = currList[i]
currList[i] = currList[i+1]
currList[i+1] = temp
return currList
print_sorted(sort_list(generate_list(set_size()))) | true |
a51cbcf803b13929c0737ba36c30c2a189ec650b | TarSen99/python3 | /lab52.py | 552 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('Enter 2 dimensions of the door')
width = int(input())
height = int(input())
print('Enter 3 dimensions of the box')
a = int(input())
b = int(input())
c = int(input())
exist = False
if (width > a and height > b) or (width > b and height > a):
exist = True
elif (width > a and height > c) or (width > c and height > a):
exist = True
elif (width > b and height > c) or (width > c and height > b):
exist = True
else:
print('box doesnt exist')
if exist:
print('box exist')
| true |
9a1ddd72238f9b770e0e6754f82a6d1348ab757a | SakiFu/sea-c28-students | /Students/SakiFu/session03/pseudocode.py | 991 | 4.3125 | 4 |
#!/usr/bin/env python
This is the list of donors
donor_dict = {'Andy': [10, 20, 30, 20], 'Brian': [20, 40, 30],
'Daniel': [30, 40,10, 10, 30]}
prompt the user to choose from a menu of 2 actions: 'Send a Thank You' or 'Create a Report'.
If the user chose 'Send a Thank You'
Prompt for a Full Name.
name = raw_input("What is the donor's full name?")
if name is 'list', show the list of the donor names and re-prompt
if name in the list, move on.
if name in the list, add that name to the list.
Prompt for the amount of donation.
amount = raw_input("How much is the donation?")
if amount is not digit, re-prompt.
if amount is digit, add the amount to the list.
Compose an email thanking the donor for their generous donation.
If the user chose 'Create a Report'
Create a report, including Donor Name, total donated, number of donations and average donation amount as values in each row
Print the report and return to the original report.
| true |
ad43d34ca563c60c7987d0a02de482407b558d99 | liberdamj/Cookbook | /python/ShapesProject/shape/circle.py | 948 | 4.1875 | 4 | # Circle Class
import math
class Circle:
# Radius is passed in when constructor called else default is 5
def __init__(self, radius=5):
self.radius = radius
self.circumference = (2 * (math.pi * self.radius))
self.diameter = (radius * 2)
self.area = (math.pi * (radius * radius))
def getRadius(self):
return self.radius
def getDiameter(self):
return self.diameter
def getCircumference(self):
return self.circumference
def getArea(self):
return self.area
if __name__ == '__main__':
print()
print("This is the Circle Class within the shape package.")
print("##################################################")
print("Authored by Malachi Liberda")
print("E-Mail: liberdamj@gmail.com")
print()
print("Creation syntax:")
print("circle.Circle(radius)")
print("Available methods:")
print("getRadius, getDiameter, getCircumference, getArea")
| true |
ff46a43fbb377a07fc38ecf781220c6cf1cad33d | klbinns/project-euler-solutions | /Solutions/Problem09.py | 546 | 4.25 | 4 | from math import floor
'''
Problem 9:
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a**2 + b**2 = c**2
For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
s = 1000
a = 3
for a in range(3, floor((s-3)/3)):
for b in range(a+1, floor((s-1-a)/2)):
c = s-a-b
if c*c == a*a + b*b:
print(a, b, c)
print ('Product: ' + str(a*b*c)) # 31875000
| true |
00069652dcb1d3adab681230ee43147a97f8b831 | nmasamba/learningPython | /23_list_comprehension.py | 819 | 4.5 | 4 |
"""
Author: Nyasha Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of Python's expressiveness. Less is more when it
comes to true Pythonic code, and list comprehensions prove that. A list comprehension
is an easy way of automatically creating a list in one line of code. In this example,
we use a list comprehension to create a list, cubes_by_four. The comprehension
should consist of the cubes of the numbers 1 through 10 only if the cube is evenly
divisible by four. Finally, we print that list to the console. Note that in this
case, the cubed number should be evenly divisible by 4, not the original number.
Example output:
[8, 64, 216, 512, 1000]
"""
cubes_by_four = [n**3 for n in range(1,11) if (n**3)%4 == 0]
print cubes_by_four | true |
2c0d1241ef7354776f28dbf02587b1c3ef705942 | nmasamba/learningPython | /22_iteration.py | 1,121 | 4.5 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program shows a way to iterate over tuples, dictionaries and strings.
Python includes a special keyword: in. You can use in very intuitively, like below.
In the example, first we create and iterate through a range, printing out 0 1 2 3 4.
Next, we create a dictionary and iterate through, printing out age 26 name Eric.
Dictionaries have no specific order. Finally, we iterate through the letters of a
string, printing out E r i c.
Example output:
0 1 2 3 4 age 26 name Eric E r i c
"""
for number in range(5):
print number,
d = { "name": "Eric", "age": 26 }
for key in d:
print key, d[key],
for letter in "Eric":
print letter, # note the comma!
#Note that the trailing comma ensures that we keep printing on the same line.
| true |
e88c2d3097b8f1eda62acb39223f4c5e2848a96b | nmasamba/learningPython | /14_anti_vowel.py | 849 | 4.25 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of modularity, encapsulation and algorithmic thinking.
It is simply a function that takes a string text as input. It will then return that string
without any vowels. Note that it does not count Y as a vowel.
Example input and output:
anti_vowel("Hey You!") should return "Hy Y!"
"""
def anti_vowel(text):
no_vowels = []
for l in text:
if l not in "aeiouAEIOU":
no_vowels.append(l)
return "".join(no_vowels) | true |
c1e5a23c822dc77349e3ffd91817d59e71dd62f8 | nmasamba/learningPython | /20_remove_duplicates.py | 589 | 4.25 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of modularity, encapsulation and algorithmic thinking.
It is simply a function that takes in a list of integers. It will then remove elements
of the list that are the same.
Example input and output:
remove_duplicates([1,1,2,2]) should return [1,2].
"""
def remove_duplicates(numbers):
unduplicated = []
for num in numbers:
if num not in unduplicated:
unduplicated.append(num)
return unduplicated
| true |
248a46e01c23a9a818ca88afc3e78b0f9e85269b | amitagrahari2512/PythonBasics | /Numpy_Array_ShallowAndDeepCopy.py | 1,376 | 4.21875 | 4 | from numpy import *
print("Copy of array")
arr1 = array([1,2,3,4,5])
arr2 = arr1
print(arr1)
print(arr2)
print("Both address is same")
print(id(arr1))
print(id(arr2))
print("------------------------------Shallow Copy------------------------------------------------")
print("So we can use view() method , so it will gives new address, But this is shallow Copy")
arr1 = array([1,2,3,4,5])
arr2 = arr1.view()
print(arr1)
print(arr2)
print("Both address is different")
print(id(arr1))
print(id(arr2))
print("But this is a shallow copy, means if I change any value in arr1 it will reflect to arr2 as well")
arr1[1] = 100
print(arr1)
print(arr2)
print("------------------------------------------------------------------------------")
print("------------------------------Deep Copy------------------------------------------------")
print("So if we don't want this , we need to use copy() function, so it will create deep copy of array")
print("so in this time actual array and copy Array are not interlinked")
arr1 = array([1,2,3,4,5])
arr2 = arr1.copy()
print(arr1)
print(arr2)
print("Both address is different")
print(id(arr1))
print(id(arr2))
print("But this is a deep copy, means if I change any value in arr1 it will not reflect to arr2")
arr1[1] = 100
print(arr1)
print(arr2)
print("------------------------------------------------------------------------------")
| true |
c388cc4fb91fd3b4e4d568f9b8dcfebdffc9319e | ryanhake/python_fundamentals | /02_basic_datatypes/2_strings/02_09_vowel.py | 533 | 4.3125 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
def isvowel(c):
return (c == "a") or (c == "e") or (c == "i") or (c == "o") or (c == "u")
input_string = input("Enter sentence: ")
vowel_count = 0
for ch in input_string:
if isvowel(ch):
vowel_count +=1
print("Total vowel count : {}".format(vowel_count)) | true |
16d8884b52f368d613c1c75b7965f116678001ae | ryanhake/python_fundamentals | /10_testing/10_02_tdd.py | 1,171 | 4.375 | 4 | '''
Write a script that demonstrates TDD. Using pseudocode, plan out a couple simple functions. They could be
as simple as add and subtract or more complex such as functions that read and write to files.
Instead of writing out the functions, only provide the tests. Think about how the functions might
fail and write tests that will check and prevent failure.
You do not need to implement the actual functions after writing the tests but you may.
'''
import unittest
class TDDExample(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_calc_add_method(self):
calc = Calculator()
result = calc.add(2, 2)
self.assertEqual(result, 4)
def test_calculator_returns_error_message_if_both_args_not_numbers(self):
self.assertRaises(ValueError, self.calc.add, 'two', 'three')
def test_calculator_returns_error_message_if_x_arg_not_number(self):
self.assertRaises(ValueError, self.calc.add, 'two', 3)
def test_calculator_returns_error_message_if_y_arg_not_number(self):
self.assertRaises(ValueError, self.calc.add, 2, 'three')
if __name__ == '__main__':
unittest.main()
| true |
4c0960015e4ebfe69e5e06a30c0c0c0223f7979d | DesireeMcElroy/hacker_rank_challenges | /python_exercises.py | 2,383 | 4.21875 | 4 | # Python exercises
# If-Else
# Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
# A single line containing a positive integer, .
# Constraints
# Output Format
# Print Weird if the number is weird. Otherwise, print Not Weird.
def check_number(n):
if n > 0 and n < 101:
if n % 2 == 1:
print('Weird')
elif n % 2 == 0 and n in range(2, 6):
print('Not Weird')
elif n % 2 == 0 and n in range(6, 21):
print('Weird')
elif n % 2 == 0 and n > 20:
print('Not Weird')
else:
print("Invalid")
check_number(4)
# Loops
# Task
# The provided code stub reads and integer, , from STDIN. For all non-negative integers , print .
# Constraints
# 0 <= n <= 20
n = int(input())
for i in range(0, n):
if i > -1 and i < 21:
print(i**2)
# Division
# Task
# The provided code stub reads two integers, and , from STDIN.
# Add logic to print two lines. The first line should contain the
# result of integer division, // . The second line should contain
# the result of float division, / .
a = int(input())
b = int(input())
print(a//b)
print(a/b)
# outputs
# 0
# 0.6
# Arithmetic Operators
# Task
# The provided code stub reads two integers from STDIN, and . Add code to print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
# Constraints
# 1 <= a <= 10**10
# 1 <= b <= 10**10
a = int(input("Enter a number between 1 and 10**10: "))
b = int(input("Enter a number between 1 and 10**10: "))
if 1 <= a <= 10**10 and 1 <= b <= 10**10:
print(a+b)
print(a-b)
print(a*b)
# Print Function
# The included code stub will read an integer, , from STDIN.
# Without using any string methods, try to print the following:
# 123.....n
# Note that "" represents the consecutive values in between.
# Constraints
# 1 <= n <= 150
n = int(input("Please enter a number between 1 and 150: "))
if 1 <= n <= 150:
number = range(1,n+1)
print(*number)
| true |
f8cd504dd44ff54de0c85010baced9f3b202c051 | prathameshkurunkar7/common-algos-and-problems | /Math and Logic/Prime Number/Prime.py | 378 | 4.21875 | 4 | def isPrime(number):
if number == 1 or number == 0:
return False
limit = (number // 2) + 1
for i in range(2, limit):
if number % i == 0:
return False
return True
if __name__ == "__main__":
number = int(input("Enter a number: "))
print("Entered number is", "a prime." if isPrime(number) == True else "not a prime.") | true |
5f3def601254e9e873f48b1ec47153f6d1abc00e | seige13/SSW-567 | /HW-01/hw_01_chris_boffa.py | 1,044 | 4.3125 | 4 | """
# equilateral triangles have all three sides with the same length
# isosceles triangles have two sides with the same length
# scalene triangles have three sides with different lengths
# right triangles have three sides with lengths, a, b, and c where a2 + b2 = c2
"""
def classify_triangle(side_a, side_b, side_c):
"""
Classifies the triangle based on the sides given
"""
intersection = {side_a, side_b, side_c} & {side_a, side_b, side_c}
is_right_triangle = side_a ** 2 + side_b ** 2 == side_c ** 2
triangle_classification = 'Invalid Triangle'
if side_a <= 0 or side_b <= 0 or side_c <= 0:
return triangle_classification
if is_right_triangle:
triangle_classification = 'right'
elif len(intersection) == 1:
triangle_classification = 'equilateral'
elif len(intersection) == 2:
triangle_classification = 'isosceles'
else:
triangle_classification = 'scalene'
return triangle_classification
if __name__ == '__main__':
classify_triangle(3, 3, 1)
| true |
308e92c4dc6f53a773e2e8320463fdb7eb0925b4 | manpreet1994/topgear_python_level2 | /q5.py | 2,347 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:16:54 2020
@author: manpreet
python assignment level 2
Level 2 assignment:
-------------------
program 1:
write a python program using regex or by any other method to check
if the credit card number given is valid or invalid. your python program should read the credit card number from input
A valid credit card number from xyz Bank has the following rules
It must start with 3,4,5
It must contain exactly 16 digits
It must only consist of digits (0-9)
It may have digits in groups of , separated by one hyphen "-"
It must NOT use any other separator like ' ' , '_', etc
It must NOT have 4 or more consecutive repeated digits
Examples:
input:
4253625879615786
output:
valid
input:
5122-2368-7954-3214
output:
valid
input:
42536258796157867
output:
invalid - #17 digits in card number is not allowed
input:
4424444424442444
output:
invalid #Consecutive digits are repeating 4 or more times not allowed
input:
5122-2368-7954 - 3214
output:
invalid: #Separators other than '-' not allowed
program 2:
write a python program to output the following
look and say sequence of numbers. It should print
up to 10 numbers
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
program 3
convert the given roman number in to decimal number.
The syntax of roman number is given below
write the python program using functools
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
example:
input: XL
output: 40
program 4
write a python proram to count the occurences of string two in
string one. your python program should read the strings from input
example:
input:
stringone = "KSCDCDC"
stringtwo = "CDC"
output: 2
program 5
write a python program to reverse the words in a given sentence as given below. your python program should read the sentence from input
example:
input: "python programming is awesome"
output: "awesome is programming python"
"""
def program5(inputstring):
temp_list = inputstring.split(" ")
temp_list = list(reversed(temp_list))
return temp_list
print("write a python program to reverse the words in a given sentence as given below. your python program should read the sentence from input")
print("Enter your string :")
inputstr = input()
print("output = ",program5(inputstr))
| true |
191d92772eb8464c5fa2a9e37298ae1911b2c2f2 | cnastoski/Data-Structures | /Hybrid Sort/HybridSort.py | 2,482 | 4.65625 | 5 | def merge_sort(unsorted, threshold, reverse):
"""
Splits a list in half until it cant anymore, then merges them back together in order
:param unsorted: the unsorted list
:param threshold: if the list size is at or below the threshold, switch to insertion sort
:param reverse: sorts the list in descending order if True
:return: A sorted list
"""
size = len(unsorted)
if size < 2:
return unsorted
mid = size // 2
first = unsorted[:mid]
second = unsorted[mid:]
if mid <= threshold:
first = insertion_sort(first, reverse)
second = insertion_sort(second, reverse)
merged = merge(first, second, reverse)
return merged
else:
first = merge_sort(first, threshold, reverse)
second = merge_sort(second, threshold, reverse)
merged = merge(first, second, reverse)
return merged
def merge(first, second, reverse):
"""
non-recursive part of merge_sort. takes two lists and merges them together in the right order
:param first: first part of list
:param second: second part of list
:param reverse: sorts the list in descending order if True
:return: the correctly merged list
"""
temp = [0] * len(first + second)
i = j = 0
if reverse is False:
while i + j < len(temp):
if j == len(second) or (i < len(first) and first[i] < second[j]):
temp[i + j] = first[i]
i += 1
else:
temp[i + j] = second[j]
j += 1
else:
while i + j < len(temp):
if j == len(second) or (i < len(first) and first[i] > second[j]):
temp[i + j] = first[i]
i += 1
else:
temp[i + j] = second[j]
j += 1
return temp
def insertion_sort(unsorted, reverse):
"""
Sorts a list using insertion sort
:param unsorted: the list to sort
:param reverse: true if list is to be sorted backwards
:return: the sorted list
"""
for i in range(1, len(unsorted)):
j = i
if not reverse:
while j > 0 and unsorted[j] <= unsorted[j - 1]:
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
j -= 1
else:
while j > 0 and unsorted[j] >= unsorted[j - 1]:
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
j -= 1
return unsorted
| true |
a83cb5b5cab2973aa697cab221e20aaf3bea570e | ksemele/coffee_machine | /coffee_machine.py | 2,235 | 4.125 | 4 | class CoffeeMachine:
def __init__(self):
self.water = 400
self.milk = 540
self.beans = 120
self.cups = 9
self.money = 550
def status(self):
print("\nThe coffee machine has:")
print(str(self.water) + " of water")
print(str(self.milk) + " of milk")
print(str(self.beans) + " of coffee beans")
print(str(self.cups) + " of disposable cups")
print("$"+str(self.money) + " of money")
def reduce_resources(self, water_, milk_, beans_, cost):
if self.water - water_ < 0:
print("Sorry, not enough water!")
return False
elif self.milk - milk_ < 0:
print("Sorry, not enough milk!")
return False
elif self.beans - beans_ < 0:
print("Sorry, not enough beans!")
return False
elif self.cups - 1 < 0:
print("Sorry, not enough cups!")
return False
else:
self.water -= water_
self.milk -= milk_
self.beans -= beans_
self.cups -= 1
self.money += cost
return True
def buy(self):
order = input("\nWhat do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: \n")
res = False
if order == '1':
res = self.reduce_resources(250, 0, 16, 4)
elif order == '2':
res = self.reduce_resources(350, 75, 20, 7)
elif order == '3':
res = self.reduce_resources(200, 100, 12, 6)
elif order == 'back':
return
if res:
print("I have enough resources, making you a coffee!")
def fill(self):
self.water += int(input("Write how many ml of water do you want to add: \n"))
self.milk += int(input("Write how many ml of milk do you want to add: \n"))
self.beans += int(input("Write how many grams of coffee beans do you want to add: \n"))
self.cups += int(input("Write how many cups do you want to add: \n"))
def take(self):
print("I gave you $" + str(self.money) + '\n')
self.money = 0
def ft_user_input(machine):
while True:
command = input("\nWrite action (buy, fill, take, remaining, exit): \n")
if command == "buy":
machine.buy()
elif command == "fill":
machine.fill()
elif command == "take":
machine.take()
elif command == "remaining":
machine.status()
elif command == "exit":
exit(0)
if __name__ == '__main__': # something like main() in C
machine = CoffeeMachine()
ft_user_input(machine)
| true |
2ca25165a87b7a7360d35e86b519469f9606da1f | Mahiuha/RSA-Factoring-Challenge | /factors | 1,887 | 4.34375 | 4 | #!/usr/bin/python3
"""
Factorize as many numbers as possible into a product of two smaller numbers.
Usage: factors <file>
where <file> is a file containing natural numbers to factor.
One number per line
You can assume that all lines will be valid natural numbers\
greater than 1
You can assume that there will be no empy line, and no space\
before and after the valid number
The file will always end with a new line
Output format: n=p*q
one factorization per line
p and q don’t have to be prime numbers
See example
You can work on the numbers of the file in the order of your choice
Your program should run without any dependency: You will not be ablei\
to install anything on the machine we will run your program on
Time limit: Your program will be killed after 5 seconds\
if it hasn’t finish
Push all your scripts, source code, etc… to your repository
"""
# library to get arguments
import sys
# fn unpack number factorial
def fc():
"""
function fc to search file to convert number and format n=p*q
"""
try:
revfile = sys.argv[1]
with open(revfile) as f:
for revnumber in f:
revnumber = int(revnumber)
if revnumber % 2 == 0:
print("{}={}*{}".format(revnumber, revnumber // 2, 2))
continue
i = 3
while i < revnumber // 2:
if revnumber % i == 0:
print("{}={}*{}".format(revnumber, revnumber // i, i))
break
i = i + 2
if i == (revnumber // 2) + 1:
print("{}={}*{}".format(revnumber, revnumber, 1))
except (IndexError):
pass
# autostart
fc()
| true |
1a7ef6b488b6ce7e7a592d8dbeac6625547ea0fc | rdasxy/programming-autograder | /problems/CS101/0035/solution.py | 350 | 4.21875 | 4 | # Prompt the use to "Enter some numbers: "
# The user should enter a few numbers, separated by spaces, all on one line
# Sort the resulting sequence, then print all the numbers but the first two and the last two,
# one to a line.
seq = raw_input("Enter some numbers: ")
seq = [int(s) for s in seq.split()]
seq.sort()
for s in seq[2:-2]:
print s | true |
f3213933c26dc79928dfb3be5323cec7977b2884 | dasdachs/smart | /08/python/to_lower.py | 384 | 4.28125 | 4 | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
"""Return the input text in lower case."""
import argparse
parser = argparse.ArgumentParser(description='Transforms text to lower case.')
parser.add_argument('text', type=str, nargs="+", help='Text that will be transformed to lower case.')
args = parser.parse_args()
if __name__ == "__main__":
print " ".join(args.text).lower()
| true |
715df80224d4637c68ccf079bf8903df7c50206e | dasdachs/smart | /10/python/game.py | 867 | 4.125 | 4 | def main():
country_capital_dict = {"Slovenia": "Ljubljana", "Croatia": "Zagreb", "Austria": "Vienna"}
while True:
selected_country = country_capital_dict.keys()[0]
guess = raw_input("What is the capital of %s? " % selected_country)
check_guess(guess, selected_country, country_capital_dict)
again = raw_input("Would you like to continue this game? (yes/no) ")
if again == "no":
break
print "END"
print "_________________________"
def check_guess(user_guess, country, cc_dict):
capital = cc_dict[country]
if user_guess == capital:
print "Correct! The capital of %s is indeed %s." % (country, capital)
return True
else:
print "Sorry, you are wrong. The capital of %s is %s." % (country, capital)
return False
if __name__ == "__main__":
main()
| true |
f1337838af3d2dafe14302b84ac07870d7409029 | magnuskonrad98/max_int | /FORRIT/timaverkefni/27.08.19/prime_number.py | 341 | 4.15625 | 4 | n = int(input("Input a natural number: ")) # Do not change this line
# Fill in the missing code below
divisor = 2
while divisor < n:
if n % divisor == 0:
prime = False
break
else:
divisor += 1
else:
prime = True
# Do not changes the lines below
if prime:
print("Prime")
else:
print("Not prime") | true |
8fa2839f5c02e9c272f21e437caa8e2ab7f4f2c9 | TedYav/CodingChallenges | /Pramp/python/flatten_dict.py | 1,137 | 4.125 | 4 | """
Time Complexity: O(n) based on number of elements in dictionary
1. allocate empty dictionary to store result = {}
2. for each key in dictionary:
call add_to_output(key,value,result)
add_to_output(prefix,value,result)
- if value is dict:
for each key in dict, call add_to_output(prefix + '.' + key, value[key])
- else:
result[prefix + '.' + key] = value
3. return result
{} ==> {}
{'a': 1} ==> {'a': 1}
Example:
{
'Key1': '1',
'Key2': {
'a' : '2',
'b' : '3',
'c' : {
'd' : '3',
'e' : '1'
}
}
}
Result:
{
'Key1': '1',
'Key2.a': // it works
}
"""
def flatten_dict(input):
if input is None or len(input) == 0: return {}
else:
result = {}
stack = [('',input)]
while stack:
prefix,target = stack.pop()
if isinstance(target, dict): # check this
for key in target:
stack.append((prefix + '.' + key, target[key]))
else:
result[prefix] = target
return result | true |
b600abf744c3dbb8abbaa694f1df0516847b1cab | lucianopereira86/Python-Examples | /examples/error_handling.py | 661 | 4.15625 | 4 | # Division by zero
x = 1
y = 0
try:
print(x/y)
except ZeroDivisionError as e:
print('You must NOT divide by zero!!!')
finally:
print('This is a ZeroDivisionError test')
# Wrong type for parsing
a = 'abc'
try:
print(int(a))
except ValueError as e:
print('Your string cannot to be parsed to int')
finally:
print('This is a ValueError test')
# Validation with Input
try:
b = int(input("Enter a positive integer: "))
if b <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
else:
print('Your number is positive!')
finally:
print('This is an Input ValueError test')
| true |
b85fd57a82d8cd32671f1f7c6cfe05659d182cf0 | mydopico/HackerRank-Python | /Introduction/division.py | 539 | 4.1875 | 4 | # Task
# Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
# You don't need to perform any rounding or formatting operations.
# Input Format
# The first line contains the first integer, aa. The second line contains the second integer, bb.
# Output Format
# Print the two lines as described above.
# Sample Input
# 4
# 3
# sample Output
# 1
# 1.3333333333333333
a = int(raw_input())
b = int(raw_input())
print a/b
print (float(a)/b)
| true |
57ba583649fdb78dfd5afdad714e2b9bd72ea363 | nini564413689/day-3-2-exercise | /main.py | 546 | 4.34375 | 4 | # 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
BMI = round (weight / height ** 2,1)
if BMI < 18.5:
result = "You are underweight."
elif BMI < 25:
result = "You have a normal weight."
elif BMI < 30:
result = "You are slightly overweight."
elif BMI < 35:
result = "You are obese."
else:
result = "You are clinically obese."
print (f" Your BMI is {BMI}, {result}")
| true |
9cd8f10f326504cf9a46d47048fcf3c25d2df827 | chaithra-yenikapati/python-code | /question_08.py | 1,356 | 4.21875 | 4 | __author__ = 'Chaithra'
notes = """
This is to make you familiar with linked list structures usage in python
see the listutils.py module for some helper functions
"""
from listutils import *
#Given sorted list with one sublist reversed,
#find the reversed sublist and correct it
#Ex: 1->2->5->4->6->7
# sort the list as: 1->2->4->5->6->7
def sort_reversed_sublist(head):
if(head==None):
return []
count=0
temp=head
temp1=temp
while temp.next!=None:
if temp.value<temp.next.value:
count=1
temp1=temp
temp=temp.next
else:
temp2=temp
temp=temp.next
temp3=temp.next
temp.next=temp2
temp1.next=temp
temp2.next=temp3
break
if(count==1):
return from_linked_list(head)
else:
return from_linked_list(temp)
#write test cases covering all cases for your solution
def test_sort_reversed_sublist():
assert [1,2,4,5,6,7]==sort_reversed_sublist(to_linked_list([1,2,5,4,6,7]))
assert [1,2,3]==sort_reversed_sublist(to_linked_list([2,1,3]))
assert [2,3]==sort_reversed_sublist(to_linked_list([3,2]))
assert [2]==sort_reversed_sublist(to_linked_list([2]))
assert []==sort_reversed_sublist(to_linked_list([])) | true |
c18b622285056b2305b06fa34624e566826b2f19 | asbabiy/programming-2021-19fpl | /shapes/reuleaux_triangle.py | 1,435 | 4.1875 | 4 | """
Programming for linguists
Implementation of the class ReuleauxTriangle
"""
import math
from shapes.shape import Shape
class ReuleauxTriangle(Shape):
"""
A class for Reuleaux triangles
"""
def __init__(self, uid: int, width: int):
super().__init__(uid)
self.width = width
def get_area(self):
"""
Returns the area of an Reuleaux triangle
:return int: the area of an Reuleaux triangle
"""
area = 0.5 * (math.pi - math.sqrt(3)) * (self.width ** 2)
return area
def get_perimeter(self):
"""
Returns the perimeter of an Reuleaux triangle
:return float: the perimeter of an Reuleaux triangle
"""
perimeter = math.pi * self.width
return perimeter
def get_inscribed_circle_radius(self):
"""
Returns the inscribed circle radius of an Reuleaux triangle
:return float: the inscribed circle radius of an Reuleaux triangle
"""
inscribed_circle_radius = (1 - 1 / math.sqrt(3)) * self.width
return inscribed_circle_radius
def get_circumscribed_circle_radius(self):
"""
Returns the circumscribed circle radius of an Reuleaux triangle
:return float: the circumscribed circle radius of an Reuleaux triangle
"""
circumscribed_circle_radius = self.width / math.sqrt(3)
return circumscribed_circle_radius
| true |
95058a6355a18b7a0ce81c9671e8e102ce194ac0 | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH6_ConditionalExpression_PositiveIntegerCheck.py | 229 | 4.28125 | 4 | userInput = int(input("Enter Number: "))
if userInput > 0:
print(userInput, "is a positive integer")
elif userInput < 0:
print(userInput, "is a negative integer")
else:
print("Nor Positive and Nor Negative Integer, it's Zero") | true |
f4eb7877a49cca45074124096ace75dd5e89b72f | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH5_DictionaryAndSets_DeclarationAndInitialization.py | 499 | 4.15625 | 4 | student = {
"name" : "bhanu",
"marks" : 99,
"subject" : "CS",
# "marks" : 98 # always print last updated value
}
print(student) # print whole dictionary
print(student["name"]) # print value of key "name"
print(len(student)) # print dictionary length
print(type(student)) # data types
# Access Dictionary
x = student.get("marks") # get by key
print(x)
y = student.keys() # get all keys
print(y)
val = student.values() # print all values
print(val) | true |
a528a47e1d7c6c1c861e9128c43db7a6645ff453 | bhanugudheniya/Python-Program-Directory | /PythonHome/Input/UserInput_JTP.py | 705 | 4.25 | 4 | name = input("Enter name of student : ")
print("Student name is : ", name)
# 'name' is variable which store value are stored by user
# 'input()' is function which is helps to take user input and string are written in this which is as it is show on screen
# ---------------------------------------------------------------------------------------------------------------------------- #
# --> By default the 'input()' function takes the string input but what if we want to take other data types as an input
# --> If we want to take input as an integer number, we need to typecast the input() function an integer
a = int(input("Enter First Number = "))
b = int(input("Enter Second Number = "))
print(a+b) | true |
141b1eafcfbdbd8324b7f5004774ea9c3a2986e8 | gmaldona/Turtles | /runGame.py | 2,561 | 4.21875 | 4 | import turtle
import random
from tkinter import *
import time
### Class for each player object
class Player:
## Starting y coordinate
y = -250
## Initialing variables
def __init__(self, vMin, vMax, color):
self.player = turtle.Turtle()
self.player.showturtle()
self.player.shape('turtle')
self.color = color
self.player.color(self.color)
self.velocity = random.randint(vMin, vMax)
self.player.penup()
self.player.setheading(90)
self.player.sety(self.y)
## Function that starts moving the turtle
def start(self):
self.player.pendown()
self.player.forward(self.velocity)
## Class that holds all of the player objects
class Race:
turtle.Screen().bgcolor('#498000')
## Array that holds all of the player objects
turtles = []
## Color for each turtle
colors = ['blue', 'red', 'orange', 'pink', 'black', 'purple', 'cyan', 'yellow']
## Function that adds turtles to the array
def addTurtle(self, amount):
## Initializes players for each turtle given in the parameters
for x in range(0, amount):
## Creates a player with a given velocity
t = Player(0, 10, self.colors[x])
## Appends the turtle to the array
self.turtles.append(t)
## Sets up the race
def setup(self):
currentX = -350
maxX = 350
## Spacing between each of the turtles
spacing = 700 / (len(self.turtles) - 1)
## Each turtle gets their x coordinate set to the current x position and the spacing
for t in self.turtles:
t.player.setx(currentX)
currentX = currentX + spacing
## Function that starts the race
def start(self):
## Variable that is responsible for stopping the race
won = False
## color of the turtle that won
color = ''
## Moves the turtle until a color won
while won != True:
## Loops through each turtle
for t in self.turtles:
## Moves the turtle
t.start()
## If a turtle crossed the finish line
if t.player.ycor() >= 250:
## There is a winnter
won = True
color = t.color
time.sleep(2)
def run(numberOfTurtles):
race = Race()
race.addTurtle(numberOfTurtles)
race.setup()
race.start()
run(8) | true |
0aa3a7fddbe66a9fb10a00f251c5bc0519267e19 | Code-Law/Ex | /BYFassess.py | 2,097 | 4.15625 | 4 | def Student():
Student_num = int(input("please input your student number:"))
while Student_num < 4990 or Student_num > 5200:
Student_num = int(input("your student number is out of range, please input again!"))
while Student_num in Student_Numbers:
Student_num = int(input("this student number has already been inputted, please input again!"))
Student_Numbers.append(Student_num)
Subject_Choice()
def Subject_Choice():
global Fundamentals
Fundamentals = 3
Subject_choices = []
subject_1 = input("what's your first subject choice?")
while subject_1 not in Subjects:
subject_1 = input("this is not a choice, please input again:")
Subject_choices.append(subject_1)
subject_2 = input("what's your second subject choice?")
while subject_2 not in Subjects:
subject_2 = input("this is not a choice, please input again:")
while subject_2 == subject_1:
subject_2 = input("this subject has already been inputted, please input again:")
Subject_choices.append(subject_2)
subject_3 = input("what's your third subject choice?")
while subject_3 not in Subjects:
subject_3 = input("this is not a choice, please input again:")
while subject_3 == subject_1 or subject_3 == subject_2:
subject_3 = input("this subject has already been inputted, please input again:")
Subject_choices.append(subject_3)
if "Geography" in Subject_choices:
Fundamentals = Fundamentals - 1
if "History" in Subject_choices:
Fundamentals = Fundamentals - 1
if "Economics" in Subject_choices:
Fundamentals = Fundamentals - 1
Foundamental_num = Fundamentals
Subject_choice = Subject_choices
print(Foundamental_num + 1)
print("you have chosen %0d fundamental subjects" % (Foundamental_num+1))
print(Subject_choice)
Student_Numbers = []
Subject_choice = []
Subjects = ["Math", "English", "Geography", "Physics", "Chemistry", "History", "Economics"]
for i in range(210):
Student()
# print("your subject choices are:")
# print(Subject_choices)
| true |
43624ddb794cc122bf493cbb055169b042824d1b | michaelmnicholl/reimagined-train | /module_grade_program.py | 555 | 4.21875 | 4 | marks = [0,55,47,67]
lowest = marks[0]
mean = 0
if len(marks) < 3:
print("Fail")
print("Your score is below the threshold and you have failed the course")
exit()
for item in marks:
if item < lowest:
lowest = item
for item in marks:
mean = mean + item
mean = mean - lowest
mean = mean / 3
print(mean)
if mean >=40:
print("You have passed the course")
elif mean >=30 and mean <=39:
print("Resit required")
else:
print("Your score is below the threshold and you have failed the course")
| true |
1b5f0832809513821db10e2be39737d60209ea5f | braxtonphillips/SDEV140 | /PhillipsBraxtonM02_Ch3Ex12.py | 2,041 | 4.46875 | 4 | #Braxton Phillips
#SDEV 140
#M02 Chapter 3 Exercise 12
#This purpuse of this program is to calculate the amount a discount,
# if any, based on quantity of packages being purchased.
print('Hello, this progam will read user input to determine if a discount is applicable based on order quantity.')
packageQuantity = int(input('Please enter the amount of packages you will be purchasing. \n'))
#I read ahead some in the book. This while loop is used as defensive programming to stop the user from entering
#Non-positive integers.
while packageQuantity <= 0:
print('Error. Please enter a valid number.')
packageQuantity = int(input('Please enter the amount of packages you will be purchasing. \n'))
#Selection strucure used to determine which paclage is approriate based on used input
if packageQuantity < 10:
totalAmount = float(format(packageQuantity * 99, '.2f'))
print('Your total for this order will be $',totalAmount, sep='')
elif packageQuantity < 20:
totalAmount = float(format((packageQuantity * 99)*.9, '.2f')) #chose to multiply by .9 rather than the diff of totalAm from 10% of totalAm
print('For ordering ',packageQuantity,' packages, you have recieved a 10% discount! This brings your total for this order to $', totalAmount, sep='')
elif packageQuantity < 50:
totalAmount = float(format((packageQuantity * 99)*.8, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 20% discount! This brings your total for this order to $', totalAmount, sep='')
elif packageQuantity < 100:
totalAmount = float(format((packageQuantity * 99)*.7, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 30% discount! This brings your total for this order to $', totalAmount, sep='')
else:
packageQuantity >= 100
totalAmount = float(format((packageQuantity * 99)*.6, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 40% discount! This brings your total for this order to $', totalAmount, sep='') | true |
4e31d151c7d8d2246a42e286263ae5af2cd87cb4 | nanihari/regular-expressions | /lower with __.py | 394 | 4.40625 | 4 | #program to find sequences of lowercase letters joined with a underscore.
import re
def lower_with__(text):
patterns="^[a-z]+_[a-z]+$"
if re.search(patterns,text):
return ("found match")
else:
return ("no match")
print(lower_with__("aab_hari"))
print(lower_with__("hari_krishna"))
print(lower_with__("harI_kriShna"))
print(lower_with__("HARI_Kri###na"))
| true |
e15765c217cc41d624aa18e1fb54d7490fde49ff | nanihari/regular-expressions | /replace_space_capital.py | 270 | 4.1875 | 4 | #program to insert spaces between words starting with capital letters.
import re
def replace_spaceC(text):
return re.sub(r"(\w)([A-Z])", r"\1 \2", text)
print(replace_spaceC("HariKrishna"))
print(replace_spaceC("AnAimInTheLifeIsTheOnlyFortuneWorthFinding"))
| true |
809214d38526ab39fa2026b0c05525ae34aaebde | nanihari/regular-expressions | /remove numbers.py | 278 | 4.375 | 4 | ##program to check for a number at the end of a string.
import re
def check_number(string):
search=re.compile(r".*[0-9]$")
if search.match(string):
return True
else:
return False
print(check_number("haari00"))
print(check_number("hari"))
| true |
50929ea4cbf1a0ca13d4a9054c577055e71bb196 | ar1ndamg/algo_practice | /3.sorting_algos.py | 1,533 | 4.5 | 4 | def insertion_sort(arr: list):
""" Takes an list and sorts it using insertion sort algorithm """
l = len(arr)
#print(f"length: {l}")
for i in range(1, l):
key = arr[i]
j = i-1
while j >= 0:
if key < arr[j]:
# slide the elements what are greater than the key to the right in the sorted array
swap(arr, j, j+1)
j -= 1
return arr
def swap(arr, i, j):
#print(f"swapping: {arr[i]},{arr[j]}")
arr[i], arr[j] = arr[j], arr[i]
def merge_sort(arr: list, start: int, end: int):
""" Takes an list and sorts it using merge sort algorithm """
if end == start:
return [arr[start]]
else:
mid = start + (end - start)//2
left = merge_sort(arr, start, mid)
right = merge_sort(arr, mid+1, end)
sorted_arr = merge(left, right)
return sorted_arr
def merge(left: list, right: list):
i = j = k = 0
l1 = len(left)
l2 = len(right)
arr = [0]*(l1+l2)
while k < l1+l2 and i < l1 and j < l2:
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while(i < l1):
arr[k] = left[i]
i += 1
k += 1
while(j < l2):
arr[k] = right[j]
j += 1
k += 1
return arr
if __name__ == '__main__':
arr = [5, 3, 4, 1, 6, 8, 11, 25, 54, 32, 21, 12]
print(merge_sort(arr, 0, len(arr)-1))
print(insertion_sort(arr))
| true |
0c6e89d23d913a1234d8bcd95de548b6a5bd6a62 | hariprasadraja/python-workspace | /MoshTutorial/basics.py | 2,268 | 4.28125 | 4 | import math
"""
Tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=7729s
"""
course = 'Python learning tutorial'
print(course[0:-3])
print("Another variable: ")
another = course[:]
print(another)
# works only on python > 3.6
# formated_string = (f'this is an another course')
# print(formated_string)
print(len(another))
print(another.upper())
# find and return the location of 'P'
print(another.find('P'))
# replaces 'P' to J
print(another.replace('P', 'J'))
# Math
x = 2.9
print(round(2.9))
print(abs(-2.9)) # always retrun positive value
print(math.ceil(2.9))
is_hot = False
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It is cold day")
print("wear warm clothes")
else:
print("It is a lovely day")
print("enjoy your day")
price = 1000000
has_good_credit = True
if has_good_credit:
downpayemnt = 0.1 * price
else:
downpayemnt = 0.2 * price
print("the downpayment is $" + str(downpayemnt))
# Logical Operators
has_high_income = False
has_good_credit = True
if has_good_credit and not has_high_income:
print("eligilble for loan")
else:
print("not eligible for loan")
# while loop
secret_number = 9
guest_count = 0
guess_limit = 3
while guest_count < guess_limit:
guess = int(input("Guess:"))
guest_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("You Lost!")
# Data Types
x = 10.0001
y = 2
quo, reminder = divmod(x, y)
print("Quotient", quo)
print("Reminder", reminder)
# Execptin handline
try:
age = int(input('Age:'))
income = 20000
risk = income/age
print(age)
except ValueError:
print("Invalid value")
except ZeroDivisionError:
print("Age cannot be 0")
# Class
class Point:
# constructor
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
# Initialize with constructor
point1 = Point(10, 20)
print(point1.x)
print(point1.y)
point1.x = 10
point1.y = 20
print(point1.x)
print(point1.y)
# Inherritance
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal):
pass
class Cat(Mammal):
def walk(self):
print("walk")
| true |
ba785abefc90c1d15878514b9d93be99c7383f4f | Ankush-Chander/euler-project | /9SpecialPythagoreanTriplet.py | 539 | 4.28125 | 4 | '''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import sys
import os
if len(sys.argv) != 2:
print("Usage: python " + sys.argv[0] + " number")
else:
number = int(sys.argv[1])
# print(number)
for i in range(1,number):
for j in range(1,number-i):
k = number-(i+j)
if i**2 + j**2 == k**2:
print(i,j,k)
print(i*j*k)
break | true |
1df7dca01c15594555d5b19f63c50049229a4b05 | rudrasingh21/Python---Using-Examples | /27. Dict - Given Key Exists in a Dictionary or Not.py | 247 | 4.125 | 4 | # Given Key Exist in a Dictionary or Not
d={'A':1,'B':2,'C':3}
k = input("Enter Key which you want to search:- ")
if k in d.keys():
print("Value is present and value for the Key is:- ", d[k])
else:
print("Key is not present")
| true |
6958f52980d417abfb01324cebe6f4b6cf452eb3 | rudrasingh21/Python---Using-Examples | /11.Count the Number of Digits in a Number.py | 271 | 4.125 | 4 | #Count the Number of Digits in a Number
'''
n=int(input("Enter number: "))
s = len(str(n))
print(s)
'''
n=int(input("Enter number: "))
count = 0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are: ",count)
| true |
26ecc9df30d13fbeabe16387bfcf5dd79b3ee02d | rudrasingh21/Python---Using-Examples | /25. Dict - Add a Key-Value Pair to the Dictionary.py | 278 | 4.25 | 4 | #Add a Key-Value Pair to the Dictionary
n = int(input("Enter number of Element you want in Dictionary:- "))
d = {}
for i in range(1,n+1):
Key = input("Enter Key : ")
Value = input("Enter Value : ")
d.update({Key:Value})
print("Updated Dictonary is: ",d) | true |
d063654808224d54d7ee8c41d6019dab24b458ac | arjun-krishna1/leetcode-grind | /mergeIntervals.py | 2,766 | 4.34375 | 4 | '''
GIVEN
INPUT
intervals: intervals[i] = [start of i'th interval, end of i'th interval]
merge all overlapping intervals
OUTPUT
return an array of the non-overlapping intervals that cover all the intervals in the input
EXAMPLE
1:
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
already sorted
the end of intervals[0] is after the start of intervals[1] and before the end of intervals[1], these two can be merged
the lowest start time is 1, the highest end time is 6
so [1, 3] and [2, 6] can be merged to [1, 6]
intervals = [[1, 6], [8, 10], [15, 18]]
all of the end times of the rest intervals are before the start times of the next interval
6 < 8, 10 < 15
it is done
return [[1, 6], [8, 10], [15, 18]]
2:
already sorted
[[1, 4], [4, 5]] -> [1, 5]
intervals[0][1] >= intervals[1][0]: they are overlapping
erge them -> [[1, 5]]
BRUTE FORCE
while we haven't considered all of the intervals left
find each other interval whose start time is before this ones end time
and its end time is after this end time
i.e. they are overlapping
find the smallest start time out of all of these overlapping interval
find the largest end time out of all of these overlapping intervals
replace all of these overlapping interval with the smallest start time and the largest end time
move to the next interval
return intervals
SORTING O(n**2) time (single iteration, popping non-end element from list) O(1) space
sort intervals
while we have intervals left to consider
if the next intervals start time is before this ones end time
merge these two
else
move to the next one
return intervals
OPTIMIZATION
push result into another list -> O(n) time, O(n) space
'''
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
# sort intervals
intervals.sort()
result = []
start_time = intervals[0][0]
end_time = intervals[0][1]
# iterate through each interval
for i in range(len(intervals)):
# this interval is overlapping with the previous interval
if end_time >= intervals[i][0]:
end_time = max(end_time, intervals[i][1])
# not merged
else:
# add the previous merged interval to result
result.append([start_time, end_time])
# update start and end time of this interval
start_time = intervals[i][0]
end_time = intervals[i][1]
# add the last interval
result.append([start_time, end_time])
return result
| true |
826a3993e35aece4c19e88969dd44439fc86b969 | ericdasse28/graph-algorithms-implementation | /depth-first-search.py | 1,334 | 4.3125 | 4 | """
Python3 program to print DFS traversal
from a given graph
"""
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
def add_edge(self, u, v):
"""Function to add an edge"""
self.graph[u].append(v)
def dfs_util(self, v, visited):
"""A function used by DFS"""
# Mark the current node as visited
# and print it
visited.add(v)
print(v, end=" ")
# Recur for all the vertices
# adjacent to this vertex
for neighbor in self.graph[v]:
if neighbor not in visited:
self.dfs_util(neighbor, visited)
def dfs(self, v):
"""The function to do DFS traversal. It uses
recursive dfs_util()"""
# Create a set to store visited vertices
visited = set()
# Call the recursive helper function
# to print DFS traversal
self.dfs_util(v, visited)
# Driver code
# Create a graph given
# in the above diagram
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.dfs(2)
| true |
d86d291ac0a1a21683cd70d4a23bed601a90262a | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/appBirthday.py | 705 | 4.25 | 4 | dictionary = {}
while True:
print("--- APP BIRTHDAY ---")
print(">>(1) Show birthdays")
print(">>(2) Add to Birthday list")
print(">>(3) Exit")
choice = int(input("Enter the choice: "))
if choice == 1:
if(len(dictionary.keys()))==0:
print("Nothing to show..")
else:
name = str(input("Enter name to look for birthday: "))
birthday= dictionary.get(name,"Not data found")
print("> Birthday: ",birthday)
elif choice ==2:
name = str(input("# Enter name:"))
date = str(input("# Enter birthdate: "))
dictionary[name]=date
print("#> Birthday Added")
elif choice == 3:
break | true |
29c5eaa6897dbbbb6d3cbfe9d868c5110992366b | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio24.py | 2,464 | 4.34375 | 4 | ## PYTHON JSON ##
# - JSON is a syntax for storing and exchanging data.
# - JSON is text, written with Javascript object notation.
# JSON IN PYTHON:
#Python has built-in package called json, which can be use
#to work with JSON data.
#Example:
# Import the json module:
import json
#Parse JSON - Convert from JSON to Python:
#If you have a JSON string, you can parse it by using the
# json.loads() method.(The result will be a Python Dictionary)
#Example:
# Conert from JSON to Python:
"""
x = '{"name":"Joseph","age":17,"city":"New York"}' #some JSON
y = json.loads(x) #convert x string to y json
print(y["name"])#The result is a dictionary, and print value 'name' key
"""
#Convert from Python to JSON:
#If you have a Python object, you can convert it into a JSON string by
#using the json.dumps() method.
""""
x = {"name":"Joseph","age":17,"city":"New York"}
y = json.dumps(x)
print(y)
"""
#You can convert Python objects of the following types, into JSON strings:
"""
dict
list
tuple
string
int
float
True
False
None
#----------------------------------------#
#Example:
# Convert Python object into JSON string, and print the values.
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
"""
#Example:
# Convert a Python object containing all the legal data types:
legal_data = {
"name":"Joseph",
"age": 18,
"married": False,
"divorcied": False,
"children": None,
"pets": ('Cone', 'Candy'),
"cars": [
{"model":"BMW 230", "mpg": 27.5},
{"model":"Ford Edge", "mpg": 24.1}
]
}
# Whitout format the result
"""print(json.dumps(legal_data))"""
#Format the result:
# - The example above prints a JSON string, but it is not very easy to
# read, with no indentations and line breaks.
# - The json.dumps() method has parameters to make it easier to read the
# result.
#Example:
# Use the indet parameter to define the numbers of indents:
"""
legalData_json = json.dumps(legal_data,indent=4)
print(legalData_json)
"""
#Order the result:
#The json.dumps() method has parameters to order the keys in the result:
#Example:
# Use the sort_key parameters to specify if the result should be
# sorted or not:
print(json.dumps(legal_data,indent=3,sort_keys=True)) | true |
39773f7d4aa077701cbb9b8bd826f63c5b6169a4 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 3 - File Handling/writeFiles.py | 1,040 | 4.65625 | 5 | # PYTHON FILE WRITE #
#Create a new File:
# To create a new file in Python, use the open() method, with one of the
# following parameter:
# "x" - Create - will create a file, returns an error if the file exist
# "a" - Append - will create a file if the specified file does not exist
#Example:
# Create a file called "demofile.txt"
"""
myFile = open("demofile.txt","x")
"""
#or
#Example: Create a new file if it does not exist:
"""
myFile = open("demofile.txt","w")
"""
#Write to an Existing File:
# To write toan existing file, you must add parameter to the open() function:
# "a" - Append - will append to the end of the file
# "w" - Write - will overwrite any existing content
#Example: 'Open the file "demofile.txt" and append content to the file'
f = open("\PYTHON - DE - 0 - 10000\Modulo 3 - File Handling\demofile.txt","x") #create file
f.write("Now the file has one more line!")#write file
f = open("\PYTHON - DE - 0 - 10000\Modulo 3 - File Handling\demofile.txt","r") #read file
print(f.read())
| true |
429f9f55f17d32174ab5c856728622926b38c861 | juanmunoz00/python_classes | /ej_validate_user_input.py | 829 | 4.40625 | 4 | ##This code validates if the user's input is a number, it's type or it's a string
##So far no library's needed
##Method that performs the validation
def ValidateInput(user_input):
try:
# Verify input is an integer by direct casting
is_int = int(user_input)
print("Input is an integer: ", is_int)
except ValueError:
try:
# Verify input is a float by direct casting
if_float = float(user_input)
print("Input is a float: ", if_float)
except ValueError:
print("It's a string or NaN (Not a Number)")
user_input = 'i' ##Initilize
##User input will be solicited and validated until user types an enter
while( user_input.strip() != '' ):
user_input = raw_input("Please type a number. Enter to exit: ")
ValidateInput(user_input) | true |
626dc70789de6e61963051996357f3ba6aae42e6 | noisebridge/PythonClass | /instructors/course-2015/errors_and_introspection/project/primetester4.py | 1,242 | 4.46875 | 4 | """
For any given number, we only need to test the primes below it.
e.g. 9 -- we need only test 1,2,3,5,7
e.g. 8 -- we need only test 1,2,3,5,7
for example, the number 12 has factors 1,2,3,6,12.
We could find the six factor but we will find the two factor first.
The definition of a composite number is that it is composed of primes, therefore it will always have a prime as a factor.
This prime test should have an index of all primes below i.
"""
total_range = 1000
primes = list()
def prime_test(i):
"""
Cases:
Return False if i is not prime
Return True if i is prime
Caveat: cannot test 1.
Caveat 2: Cannot test 2.
It is fortuitous that these tests both return true.
"""
for possible_factor in primes:
if i % possible_factor == 0:
return False
return True
for prime in range(2,total_range):
import timeit
# This isn't good enough, we'll have to use a context
# manager or something to set up and tear down the right
# prime list and current integer to test.
setup = "from __main__ import prime_test"
print(timeit.timeit("is_prime = prime_test(prime)", number=1, setup=setup))
if is_prime:
primes.append(prime)
print len(primes)
| true |
9c81264446ef2fd968208b79fd0d696409bb5f83 | noisebridge/PythonClass | /instructors/lessons/higher_order_functions/examples/closure1.py | 1,509 | 4.15625 | 4 | """
This example intentionally doesn't work.
Go through this code and predict what will happen, then run
the code.
The below function fixes i in the parent scope, which means
that the function 'f' 'gets updates' as i progresses through
the loop.
Clearly we need to somehow fix i to be contained in the local
scope for 'f'.
Original code at: http://eev.ee/blog/2011/04/24/gotcha-python-scoping-closures/
"""
if __name__ == "__main__":
"""
Only read the code the first time through.
Then read the comments after you see the results.
"""
# We'll append a bunch of functions into this list.
myfunctions = list()
for i in range(4):
"""
We'll use the namespace f repeatedly in this scope, but
the functions will actually be bound as indexed items in
our list. The 'f' name will be fresh in each loop.
"""
def f():
"""
Each time we build this function, we are fixing the
value i into the function from the parent scope.
Here we try and fail to fix a new value of i into the
function f each time through the loop. Why does it fail?
Note: in Python, child scopes have access to all parent
scopes up to the global scope, so be wary of this and
use it to your advantage where possible.
"""
print i
myfunctions.append(f)
i=7
for my_function in myfunctions:
my_function()
| true |
f412f50e278ad7ba058891a8e463625155bffdfb | noisebridge/PythonClass | /instructors/projects-2015/workshop_100515/quick_sort.py | 1,124 | 4.1875 | 4 | """ Quick Sort
Implement a simple quick sort in Python.
"""
# we'll use a random pivot.
import random
def my_sorter(mylist):
""" The atomic component of recursive quick sort
"""
# we are missing a base case
if len(mylist) == 1:
return mylist
# do we need this?
if len(mylist) == 0:
return mylist
pivot_index = random.choice(range(len(mylist)))
pivot = mylist[pivot_index]
left_side = mylist[0:pivot_index]
right_side = mylist[pivot_index+1:]
#print left_side, pivot, right_side
# can swap left and right once we find one in each, then append
# once we run out on one side.
right_side_2 = list()
left_side_2 = list()
for item in left_side+right_side:
if item > pivot:
right_side_2.append(item)
if item <= pivot:
left_side_2.append(item)
print "l:", left_side_2
print "p:", pivot
print "l+p:", left_side_2 + [pivot]
print "r:", right_side_2
return my_sorter(left_side_2) + [pivot] + my_sorter(right_side_2)
mylist = [4,6,5,9,2,3,1,8]
print mylist
print my_sorter(mylist)
| true |
9db3cd6f2fbadcfa1e558ac85e38bb1129f163b2 | noisebridge/PythonClass | /instructors/lessons/functions_and_gens/examples/example0.py | 618 | 4.1875 | 4 | #Return the absolute value of the number x. Floats as well as ints are accepted values.
abs(-100)
abs(-77.312304986)
abs(10)
#Return True if any element of the iterable is true. If the iterable is empty, return False.
any([0,1,2,3])
any([0, False, "", {}, []])
#enumerate() returns an iterator which yields a tuple that keeps count of the elements in the sequence passed.
#Since the return value is an iterator, directly accessing it isn't particularly useful.
from string import ascii_letters as ltrs
for index, letter in enumerate(ltrs):
print index, letter
print enumerate(ltrs)
print list(enumerate(ltrs)) | true |
3d7581fb9378298bd491df6a5f54063a659ae965 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter6/strings.py | 720 | 4.125 | 4 | word = "Ishini"
def backward(word):
index = len(word) - 1
while index >= 0:
print(word[index])
index -= 1
backward(word)
fruit = "apple"
def count(fruit, count):
count = 0
for letter in fruit:
if letter == "p":
count = count + 1
print("Amount of p:", count)
count(fruit,"p")
q4_word = "tennakoon"
print("Amount of n: ", q4_word.count("n"), "Amount of o: ", q4_word.count("o"))
str = "X-DSPAM-Confidence:0.8475"
colon = str.find(":")
print("Find the index of (:)", colon)
last_num = str.find("5")
print("Find the index of 5: ", last_num)
slice_str = str[colon+1:last_num] #start from colon + 1 to get number 0
print("Convert str to float", float(slice_str))
| true |
b1d766d3d8a6a7635f7c928e085844594e0eb329 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter5/iteration.py | 1,479 | 4.3125 | 4 | import math
n = 5
while n > 0:
print(n)
n =- 1
print("Launched!")
while True:
line = input('> ')
if line == 'done':
break #this means if input is "done" -> break the while loop
print(line)
print('Done!')
while True:
usr_line = input('> ')
if usr_line[0] == '#':
continue #finish the current # iteration input, then jump to the next iteration which is the next input without the #
if usr_line == 'done':
break
print(usr_line)
print('Done!')
friends = ['John', 'Barnaby', 'Thien']
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
#questions
total = 0
count = 0
average = 0
while True:
number = input("Enter a number: ")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print("bad data")
print ("Total: ", total, "Count: ", count, "Average: ", average)
numbers = []
while True:
num = input("Enter a number: ")
try:
if num == "done":
break
else:
numbers.append(int(num))
except:
print("bad data")
print("Max: ", max(numbers))
print("Min: ", min(numbers))
#Important:
"""
We call the while statement
an indefinite loop because it simply loops until some condition becomes False,
whereas the for loop is looping through a known set of items so it runs through
as many iterations as there are items in the set.
"""
| true |
ad1894bc97e870b14a06d8dd46bcc6ff9875cdb5 | rakshithvasudev/Datacamp-Solutions | /Recommendation Engines in Pyspark/How ALS works/ex16.py | 606 | 4.28125 | 4 | """
Get RMSE
Now that you know how to build a model and generate predictions, and have an evaluator to tell us how well it predicts ratings, we can calculate the RMSE to see how well an ALS model performed. We'll use the evaluator that we built in the previous exercise to calculate and print the rmse.
Instructions
100 XP
Call the .evaluate() method on our evaluator to calculate our RMSE on the test_predictions dataframe. Call the result RMSE.
Print the RMSE
Take Hint (-30 XP)
"""
# Evaluate the "test_predictions" dataframe
RMSE = evaluator.evaluate(test_predictions)
# Print the RMSE
print (RMSE) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.