blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
85d969c057da158c9b16bd1143b78e7f1be1a990 | vkagwiria/thecodevillage | /Python Week 2/Day 1/02_else_statements.py | 1,073 | 4.5625 | 5 | """
Else statements
The final part of a good decision is what to do by default. Else statements are used to cater for this.
How They Work
Else conditional statements are the end all be all of the if statement. Sometimes you’re
not able to create a condition for every decision you want to make, so that’s where the
else statement is useful. The else statement will cover all other possibilities not covered
and will always run the code if the program gets to it. This means that if an elif or if
statement were to return True, then it would never run the else; however, if they all
return False, then the else clause would run no matter what every time.
Writing An Else Statement
Like an elif statement, the else clause needs to always be associated with an original
if statement. The else clause covers all other possibilities, so you don’t need to write a
condition at all; you just need to provide the keyword “else” followed by an ending
colon. Remember that an else clause will run the code inside of it if t reaches the statement.
"""
| true |
54ebed866e5e015a47b3e2a23ff660dab7adf0af | vkagwiria/thecodevillage | /Python Week 2/Day 1/exercise2.py | 381 | 4.28125 | 4 | # ask the user to input a number
# check whether the number is higher or lower than 100
# print "Higher than 100" if the number is greater than 100
# print "Loweer than 100" if the number is lower than 100
num=int(input("Please insert your number here: "))
if(num>100):
print("The number is greater than 100.")
elif(num<100):
print("The number is less than 100.") | true |
fcc5b1cf3dc24a7f146f66147223bc577a753eef | vkagwiria/thecodevillage | /Python Week 5/Day 2/Day 3/Object Oriented Programming/classes.py | 810 | 4.1875 | 4 | # attributes (variables within a class)
# class Car():
# capacity = 2000
# colour = 'white'
# mazda = Car()
# print(mazda.capacity,mazda.colour)
# # methods (functions within a class)
# class Dog():
# def bark():
# return bark
# german_shepherd = Dog()
# # access methods
# german_shepherd.bark()
# using init method
class Car():
# initialization function or constructor method
# self keyword refers to the current instance of the class
def __init__(self,color,capacity):
self.color = color
self.capacity = capacity
# create an instance - an instance of a class is an object
toyota = Car("red",2000)
toyota1 = Car("white",1500)
mazda = Car("grey",1800)
print(toyota.color)
print(toyota1.capacity)
print(mazda.color)
| true |
5ddd60d5209a8d63bb1517ca403b4bfe4ad0d9f6 | vkagwiria/thecodevillage | /Python week 1/Python Day 1/if_statements.py | 924 | 4.5 | 4 | if statements give us the ability to have our programs decide what lines of code to run,
depending on the user inputs, calculations, etc
Checks to see if a given condition is True or False
if statements will execute only if the condition is True
# syntax:
if some condition:
do something
"""
number1 = 5
number2 = 7
# Equality ==
if number2 == number1:
print("Equal")
# Inequality !=
if number2 != number1:
print("Not equal")
# Greater than >
if number2 > number1:
print("Number is greater")
# Less than <
if number2 < number1:
print("Number is less")
# Greater than or equal >=
if number2 >= number1:
print("Number is greater than or equal to")
# Less or equal <=
if number1 <= number2:
print("Number is less than or equal to")
# test for even numbers
# user inputs a number
# check whether the number is even
# output to the user "Number is even"
| true |
28d1ddc682cd7054814d9598f7a7f938140cf5e5 | samdarshihawk/python_code | /sum_array.py | 1,169 | 4.5 | 4 | '''
Given a 2D Array
We define an hourglass in to be a subset of values with indices falling.
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in,
then print the maximum hourglass sum.
Function Description
Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.
hourglassSum has the following parameter(s):
arr: an array of integers
Output Format
Print the largest (maximum) hourglass sum found in arr.
'''
import numpy as np
# this function only work on 6X6 2d array
def sum_2darray(arr):
if(type(arr)!='numpy.ndarray'):
a=np.asarray(arr)
else:
a=arr
end_row = 3
l = []
for i in range(6):
end_column = 3
for j in range(6): # the nested for loop creates only 3X3 2D array
d=np.array(a[i:end_row,j:end_column])
end_column += 1
if(d.shape == (3L,3L)):
d[1,0] = 0
d[1,2] = 0
l.append(np.sum(d))
else:
continue
end_row += 1
return(max(l))
| true |
0a4aa3128121334cb84eb728b4316dde61f2f6a1 | zuoshifan/sdmapper | /sdmapper/cg.py | 2,471 | 4.15625 | 4 | """
Implementation of the Conjugate Gradients algorithm.
Solve x for a linear equation Ax = b.
Inputs:
A function which describes Ax <-- Modify this vector -in place-.
An array which describes b <-- Returns a column vector.
An initial guess for x.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
def cg_solver(x0, Ax_func, b_func, args=(), max_iter=200, tol=1.0e-6, verbose=False):
"""
Returns x for a linear system Ax = b where A is a symmetric, positive-definite matrix.
Parameters
----------
x0 : np.ndarray
Initial guess of the solution `x`.
Ax_func : function
Function returns the product of `A` and `x`, has form Ax_func(x, Ax, *args),
the result is returned via the inplace modification of `Ax`.
b_func : function
Function returns the right hand side vector `b`, has form b_func(x, *args),
args : tuple, optional
Arguments that will be pass to `Ax_func` and `b_func`.
max_iter : interger, optional
Maximum number of iteration.
tol : float, optional
Tolerance of the solution error.
verbose : boolean, optional
Output verbose information.
Returns
-------
x : np.ndarray
The solution `x`.
"""
# get value of b
b = b_func(x0, *args)
# initial guess of Ax
Ax = np.zeros_like(b)
# Ad = np.zeros_like(b)
Ax_func(x0, Ax, *args)
x = x0 # re-use x0
r = b - Ax
d = r.copy()
delta_new = np.dot(r, r)
delta0 = delta_new
it = 0
while it < max_iter and delta_new > tol**2 * delta0:
Ax_func(d, Ax, *args) # re-use Ax for Ad
alpha = delta_new / np.dot(d, Ax) # re-use Ax for Ad
x += alpha * d
if (it + 1) % max(50, np.int(it**0.5)) == 0:
Ax_func(x, Ax, *args)
r[:] = b - Ax # re-use the existing r
else:
r -= alpha * Ax # re-use Ax for Ad
delta_old = delta_new
delta_new = np.dot(r, r)
beta = delta_new / delta_old
# d[:] = r + beta * d
d *= beta
d += r
it += 1
if verbose:
sgn = '>' if delta_new > tol**2 * delta0 else '<'
print 'Iteration %d of %d, %g %s %g...' % (it, max_iter, (delta_new/delta0)**0.5, sgn, tol)
if delta_new > tol**2 * delta0:
print 'Iteration %d of %d, %g > %g...' % (it, max_iter, (delta_new/delta0)**0.5, tol)
return x
| true |
98d1f01500ee4038a2acba3d39b3e820b0af7f21 | bjday655/CS110H | /901815697-Q1.py | 1,651 | 4.5 | 4 | '''
Benjamin Day
9/18/2017
Quiz 1
'''
'''
Q1
'''
#input 3 values and assign them to 'A','B', and 'C'
A=float(input('First Number: '))
B=float(input('Second Number: '))
C=float(input('Third Number: '))
#check if the numbers are in increasing order and if so print 'the numbers are in increasing order'
if A<B<C:
print('the numbers are in increasing order')
#check if the numbers are in decreasing order and if so print 'the numbers are in decreasing order'
elif A>B>C:
print('the numbers are in decreasing order')
#otherwise print that the numbers are random
else:
print('the numbers are in a random order')
'''
Q2
'''
#assign a desired value to 'A'
A=int(input('Give me a number between 1 and 12: '))
if A>=1 and A<=12: #check to see if the input value is between 1 and 12
if A==1:
print('That is January')
elif A==2:
print('That is February')
elif A==3:
print('That is March')
elif A==4:
print('That is April')
elif A==5:
print('That is May')
elif A==6: #checks the value of 'A' and prints corresponding month
print('That is June')
elif A==7:
print('That is July')
elif A==8:
print('That is August')
elif A==9:
print('That is September')
elif A==10:
print('That is October')
elif A==11:
print('That is November')
elif A==12:
print('That is December')
else: #if the number is outtside the range between 1 nad 12 then prints a response to the user
print('I said BETWEEN 1 and 12!') | true |
83e91333dcc783026f7383020e919ff7cb29432b | gracewanggw/PrimeFactorization | /primefactors.py | 972 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
PrimeFactors
@Grace Wang
"""
def prime_factorization(num):
## Finding all factors of the given number
factors_list = []
factor = 2
while(factor <= num):
if(num % factor == 0):
factors_list.append(factor)
factor = factor + 1
print(factors_list)
## Finding which of the factors are prime
prime_factors = []
for i in factors_list:
for j in range(2,i):
if(i % j == 0):
break
else:
prime_factors.append(i)
## Prints results
num = str(num)
prime_factors = str(prime_factors)
print("The prime factors of " + num + " are " + prime_factors)
## Takes user input and calls on the prime factorization function
while True:
a = int(input('give me a number greater than 1 or enter 0 to quit: '))
if (a == 0):
break
prime_factorization(a)
| true |
28a302e680fecebd3acfc1f4f8c0aa183b5efa0b | dstrube1/playground_python | /codeChallenges/challenge9.py | 1,375 | 4.125 | 4 | #challenge9
#https://www.linkedin.com/learning/python-code-challenges/simulate-dice?u=2163426
#Simulate dice
#function to determine the probability of certain outcomes when rolling dice
#assume d6
#Using Monte Carlo Method: Trial 1 - 1,000,000
#Roll dice over and over, see how many times each occurs, calculate probability from that
import random
#input: variable number of arguments for sides of dice
#output: table of probability for each outcome
def diceRoll(numSides):
counts = []
for x in range(1, numSides+1):
counts.append(0)
#print("x: " + str(x))
maxRolls = 1_000_000 #neat trick to make big numbers more human readable
for x in range(maxRolls):
dice = random.randint(1, numSides)
counts[dice-1] += 1
print("results:")
for x in range(numSides):
print(str(x+1) + " probability: {:0.2f}% chance ".format((counts[x] / maxRolls) * 100) )
#instructor's solution- I underestimated what he meant by the input & output
from collections import Counter
def roll_dice(*dice, num_trials=1_000_000):
counts = Counter()
for roll in range(num_trials):
counts[sum((random.randint(1, sides) for sides in dice))] += 1
print("\nOutcome\tProbability")
for outcome in range(len(dice), sum(dice)+1):
print("{}\t{:0.2f}%".format(outcome, counts[outcome]*100/num_trials))
#main
diceRoll(10)
roll_dice(4,6,6)
#ok, compactified logic aside, that is pretty cool | true |
479f2b2aa2fe422659aa9a7667bdc135d4117ac7 | jkalmar/language_vs | /strings/strings.py | 1,751 | 4.4375 | 4 | #!/usr/bin/python3
""" Python strings """
def main():
""" Main func """
hello = "Hello"
world = "World"
print(hello)
print(world)
# strings can be merged using + operator
print(hello + world)
# also creating a new var using + operator
concat = hello + world
print(concat)
# space can be added easily
print(hello + " " + world)
# or a little differently
# but this first creates a list from the two strings and then
# join the list into a string using space
print(" ".join([hello, world]))
# this do the same but without the middle man
helloworld = hello + " " + world
print(helloworld)
# string slicing is nice
print("substring from 0 to 5th char: " + helloworld[:5])
print("substring from 5 to the rest of var: " + helloworld[5:])
# indexing is natural(at least for C developers :) )
print(hello[4] + world[0] + hello[2])
# nice feature is that the operator * repeates the whole string
print("*" * 80)
print("*" + " " * 78 + "*")
print(("*" + " " * 78 + "*\n") * 2, end='')
print("*" + " "* int(78 / 2 - len(helloworld) / 2) + helloworld + " " * int(78 / 2 - len(helloworld) / 2 + 1) + "*")
print(("*" + " " * 78 + "*\n") * 3, end='')
print("*" * 80)
# strings can draw in the terminal
base = 30
for row in range(1, base, 2):
print(" " * int(base / 2 - row / 2) + "+" * row)
# searching string in another string is very natural
print("Is hello in Hello World?")
print("hello" in helloworld)
# but please note that seach is case-sensitive
# so ones more
print("Is hello in Hello World?")
print("hello" in helloworld.lower())
if __name__ == '__main__':
main()
| true |
225877fca1af5d782e1fb5ac0f694b4dfa703014 | samandeveloper/Object-Oriented-Programming | /Object Oriented Programming.py | 672 | 4.4375 | 4 | #Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
cat1=Cat('Loosy',1)
cat2=Cat('Tom',5)
cat3=Cat('Johnny',10)
print(cat1.name)
print(cat1.age)
print(cat2.name)
print(cat2.age)
print(cat3.name)
print(cat3.age)
# 2 Create a function that finds the oldest cat
def oldest_cat(*args):
return max(args)
print(oldest_cat(cat1.age,cat2.age,cat3.age))
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
print(f'The oldest cat is {oldest_cat(cat1.age,cat2.age,cat3.age)} years old.')
| true |
b5a0c7b1e3d99afef07497fc70019ee271ff3aa7 | FabianForsman/Chalmers | /TDA548/Exercises/week6/src/samples/types/CollectionsSubtyping.py | 2,098 | 4.125 | 4 | # package samples.types
# Using super/sub types with collections
from typing import List
from abc import *
def super_sub_list_program():
d = Dog("Fido", 3)
c = Cat("Missan", 4, False)
pets: List[Pet] = []
pets.append(d) # Ok, Dog is a Pet
pets.append(c) # Ok, Cat is a Pet
pets[0].get_name()
speakers: List[CanSpeak] = []
speakers.append(d) # Ok, Dog can speak
speakers.append(c) # Ok, Cat can speak
speakers[0].say()
speakers[0].get_name() # No guarantee there is such a method!
speakers = pets # Whoa, dangerous! (Why?)
pets = speakers # This is even worse, but at least here we get a warning.
pets.append(speakers[0]) # A speaker might not be a Pet!
speakers.append(pets[0]) # But any pet can speak
speakers.extend(pets) # We can add all pets to a list of speakers
pets.extend(speakers) # ... but not all speakers to a list of pets
for speaker in speakers:
if isinstance(speaker, Pet): # Check if object is Pet or subclass to
pets.append(speaker) # then we know we can add it safely
# --------------- Types -----------------
class CanSpeak(ABC):
@abstractmethod
def say(self):
pass
class Pet(CanSpeak, ABC):
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class Dog(Pet):
def __init__(self, name, age): # Redundant code gone
super().__init__(name, age)
def say(self): # Dog is subtype to Pet and CanSpeak, must implement method!
return f"{self.name} says Arf"
class Cat(Pet):
def __init__(self, name, age, is_evil):
super().__init__(name, age)
self.is_evil = is_evil
def is_evil(self):
return self.is_evil()
def say(self):
return f"{self.name} says Meow"
if __name__ == "__main__":
super_sub_list_program()
| true |
c4df0605b50f9bff5df32e5bcb89bb1ab6f51305 | FabianForsman/Chalmers | /TDA548/Exercises/week4/src/samples/Stack.py | 1,900 | 4.46875 | 4 | # package samples
# Python program to demonstrate stack implementation using a linked list.
# Class representing one position in the stack; only used internally
class Stack:
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Initializing a stack.
def __init__(self):
self.head = None # Node("head")
self.size = 0
# String representation of the stack, for printouts
def __str__(self):
cur = self.head
out = ""
while cur is not None:
out += str(cur.value) + "->"
cur = cur.next
return "[ " + out[:-2] + " ]"
# Get the current size of the stack
def get_size(self):
return self.size
# Check if the stack is empty
def is_empty(self):
return self.size == 0
# Get the top item of the stack, without removing it
def peek(self):
if self.is_empty():
raise ValueError("Peeking from an empty stack")
return self.head.next.value
# Push a value onto the stack
def push(self, value):
new_node = Stack.Node(value)
new_node.next = self.head
self.head = new_node
self.size += 1
# Remove a value from the stack and return it
def pop(self):
if self.is_empty():
raise ValueError("Popping from an empty stack")
node_to_pop = self.head
self.head = self.head.next
self.size -= 1
return node_to_pop.value
# Remove all elements from the stack
def clear(self):
self.head = None
self.size = 0
def test():
stack = Stack()
for i in range(1, 11):
stack.push(i)
print(f"Stack: {stack}")
for _ in range(1, 6):
remove = stack.pop()
print(f"Pop: {remove}")
print(f"Stack: {stack}")
# Driver Code
if __name__ == "__main__":
test()
| true |
5d696e7556db84b16e050e5d4f7263e13f937423 | bz866/Data-Structures-and-Algorithms | /bubblesort.py | 668 | 4.25 | 4 | # Bubble Sort
# - Assume the sequence contains n values
# - iterate the sequence multiple times
# - swap values if back > front (bubble)
# - Time: O(n^2)
# - [(n -1) + 1] * [(n - 1 + 1) / 1 + 1] / 2
# - 0.5 * n^2 + 0.5 * n
# - Spac: O(1)
# - sorting done by swapping
import warnings
# implementation of the bubble sort algorithm
def bubbleSort(theValues):
if len(theValues) == 0:
warnings.warn("User is sorting empty sequence.")
n = len(theValues)
for i in range(0, n - 1):
for j in range(0, n - i - 1):
if theValues[j] > theValues[j+1]:
# Swap
temp = theValues[j]
theValues[j] = theValues[j+1]
theValues[j+1] = temp
return theValues
| true |
4cc05e77f7d7fabc3f2498c8d93426425cfabcc9 | bz866/Data-Structures-and-Algorithms | /radixSort.py | 637 | 4.15625 | 4 | # Implementation of the radix sort using an array of queues
# Sorts a sequence of positive integers using the radix sort algorithm
from array import array
from queueByLinkedList import Queue
def radixSort(intList, numDigits):
# Create an array of queues to represent the bins
binArray = Array(10)
for k in range(10):
binArray[k] = Queue()
# The value of the current column
column = 1
# Iterate over the number of digits in the largest value
for d in range(numDigits):
digit = (key // column) % 10
binArray[digit].enqueue(key)
# Gather the keys from the bins and place them back intList
i = 0
for bin in binArray:
| true |
c9a567f4bcd0536dd1f3933c081d35d59ccad7a7 | bz866/Data-Structures-and-Algorithms | /linkedListMergeSort.py | 2,267 | 4.40625 | 4 | # The merge sort algorithm for linked lists
# Sorts a linked list using merge sort. A new head reference is returned
def linkedListMergeSort(theList):
# If the list is empty, return None
if not theList:
return None
# Split the linked list into two sublists of equal size
rightList = _splitLinkedList(theList)
leftList = theList
# Perform the same operation on the left half & right half
leftList = linkedListMergeSort(leftList)
rightList = linkedListMergeSort(rightList)
# merge the two ordered sublists
theList = _mergeLinkedLists(leftList, rightList)
# Return the head pointer of the ordered sublist
return theList
# Splits a linked list at the midpoint to create two sublists. The head reference of the right sublist is
# returned. The left sublist is still referenced by the original head reference
def _splitLinkedList(subList):
# Assign a reference to the first and second nodes in the list
midPoint = subList
curNode = midPoint.next
# Iterate through the list until curNode falls off the end
while curNode is not None:
# Advance curNode to the next Node
curNode = curNode.next
# if there are more nodes, advance curNode again and midPoint once
if curNode is not None:
midPoint = midPoint.next
curNode = curNode.next
# Set rightList as the head pointer to the right subList
rightList = midPoint.next
# Unlink the right subList from the left subList
midPoint.next = None
# Return the right subList head reference
return rightList
# Merges two sorted linked list; returns head reference for the new list
def _mergeLinkedLists(subListA, subListB):
# Create a dummy node and insert it at the front of the list
newList = ListNode(None)
newTail = newList
# Append nodes to the newList until one list is empty
while subListA is not None and subListB is not None:
if subListA.data <= subListB.data:
newTail.next = subListA
subListA - subListA.next
else:
newTail.next = subListB
subListB = subListB.next
newTail = newTail.next
newTail.next = None
# if self list contains more terms, append them
if subListA is not None:
newTail.next = subListA
else:
newTail.next = subListB
# Return the new merged list, which begins with the first node after the dummy node
return newList.next
| true |
752c7275e39eb3b4ce0e30cd99d738d8406733dd | cBarnaby/helloPerson | /sine.py | 420 | 4.125 | 4 | import math
def sin(x):
if x > 360:
x = x%360
print(x)
x = x/180*math.pi
term = x
sum = x
eps = 1E-8
n = 2
while abs(term/sum) > eps:
term = -(term*x*x)/(((2*n)-1)*((2*n)-2))
sum = sum + term
n += 1
return sum
print(sin(3000))
x = (float(input("Enter an angle in degrees: ")))
result = math.sin(x/180*math.pi)
print("sin(x) = ", result)
| true |
8e6c241216f935be862425a1b8854c4876757e75 | cyinwei/crsa-rg-algs-1_cyinwei | /bin/divide_and_conquer/mergesort.py | 1,015 | 4.21875 | 4 | def merge(left, right):
combined = [None] * (len(left) + len(right))
i = 0 #left iterator
j = 0 #right iterator
for elem in combined:
#first do cases where one arr is fully used
#note that we won't have out bounds, since the length
# of combined is the the two smaller blocks' length
if i == len(left):
elem = right[j]
j += 1
elif j == len(right):
elem = left[i]
i += 1
#then do cases with both arrs aren't used yet
elif left[i] <= right[j]:
elem = left[i]
i += 1
else:
elem = right[j]
j += 1
return combined
def mergesort(arr):
#base case
if len(arr) <= 1:
return arr
#recursive case
left = mergesort(arr[:len(arr)//2])
right = mergesort(arr[len(arr)//2:])
return merge(left, right)
#example
test = [10, 8, 6, 4, 2, 9, 7, 5, 3, 1]
sorted_arr = mergesort(test)
| true |
176f3cede6656a83f21adf57e69af59538c1cc61 | vlad-belogrudov/jumping_frogs | /jumping_frogs.py | 1,307 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Jumping frogs and lamps - we have a number of either.
All lamps are off at the beginning and have buttons in a row.
Frogs jump one after another. The first frog jumps on each button
starting with the first button, the second frog on button number 2,
4, 6... the third on button number 3, 6, 9...
This program emulates state of lamps (on, off)
"""
class Lamps:
"""This class represents state of lamps"""
def __init__(self, num) -> None:
"""Initialize state of all lamps - all off"""
self.state = [False for _ in range(0, num)]
def __str__(self) -> str:
"""To string"""
return "".join((str(int(s)) for s in self.state))
def __int__(self) -> int:
"""To int"""
return int(str(self), 2)
def press(self, num) -> None:
"""Press button"""
self.state[num] = not self.state[num]
if __name__ == "__main__":
NUM_LAMPS = 10
NUM_FROGS = 10
lamps_state = Lamps(NUM_LAMPS)
for iteration in range(1, NUM_LAMPS + 1):
for frog in range(1, NUM_LAMPS + 1):
lamp_num = frog * iteration -1
if lamp_num < NUM_LAMPS:
lamps_state.press(lamp_num)
else:
break
print(lamps_state)
print(hex(int(lamps_state)))
| true |
9bc9a24e5de1f990442b9c544c04bb56121e3a9e | Soham2020/Python-basic | /General-Utility-Programs/LCM..py | 258 | 4.15625 | 4 | # Calculate LCM of Two Numbers
a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
if(a>b):
min = a
else:
min = b
while(1):
if(min%a == 0 and min%b == 0):
print("LCM is",min)
break
min = min + 1 | true |
92764bc93100ff1c7472e93608a96d88c4936ebd | Soham2020/Python-basic | /Numpy/Arrays.py | 576 | 4.15625 | 4 | """
The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data.
To use the NumPy module, we need to import it using:
import numpy
A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the same type.
Task
You are given a space separated list of numbers.
Your task is to print a reversed NumPy array with the element type float.
"""
import numpy
def arrays(arr):
a = numpy.array(arr[::-1],float)
return(a)
arr = input().strip().split(' ')
result = arrays(arr)
print(result) | true |
e5c118e589dc2e47944ef452cb70660c7f854c88 | Soham2020/Python-basic | /General-Utility-Programs/GCD_HCF.py | 247 | 4.125 | 4 | # Calculate The GCD/HCF of Two Numbers
def gcd(a, b):
if(b==0):
return a
else:
return gcd(b, a%b)
a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
ans = gcd(a, b)
print("The GCD is",ans) | true |
ec160ee9cf8ba837fd261d5e922cf29f73ca6af0 | Bharti20/python_if-else | /age_sex.py | 546 | 4.15625 | 4 | age=int(input("enter the age"))
sex=(input("enter the sex"))
maretial_status=input("enter the status")
if sex=="female":
if maretial_status=="yes" or maretial_status=="no":
print("she will work only urban area")
elif sex=="male":
if age>=20 and age<=40:
if maretial_status=="yes" or maretial_status=="no":
print("he can work anywhere")
elif age>=40 and age<=60:
if maretial_status=="yes" or maretial_status=="no":
print("he will work in urban areas")
else:
print("error")
| true |
ca79f69bcb7096b0e6d13c61bcef7785c0de1e35 | phattarin-kitbumrung/basic-python | /datetime.py | 411 | 4.28125 | 4 | import datetime
#A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
#To create a date, we can use the datetime() class (constructor) of the datetime module.
x = datetime.datetime(2020, 5, 17)
print(x)
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B")) | true |
3b15fff39e3e4cc1ecbf5ed0e7d95fdcd15f662d | tj1234567890hub/pycharmed | /i.py | 514 | 4.25 | 4 | def findPrime(num):
prime = True
if num < 1:
print("This logic to identify Negative prime number is not yet developed.. please wait")
else:
for i in range(2, num - 1, 1):
if num % i == 0:
prime = False
break
print (prime)
return prime
if __name__ == '__main__':
num = input ("Enter the number to check if it is prime:")
try:
num = int(num)
findPrime(num)
except:
print("Correct your entry") | true |
0faccfc350ba25e81ae58256cfa90186a7310d12 | tchitchikov/data_structures_and_algorithms | /sorting/insertion_sort.py | 1,258 | 4.375 | 4 | __author__ = 'tchitchikov'
"""
An insert sort will allow you to compare a single element to multiple at once
The first value is inserted into the sorted portion, all others remain in
the unsorted portion. The next value is selected from the unsorted array and
compared against each value in the sorted array and inserted in its proper
ascending or descending order depending on how you code this.
Run so all values are in the sorted array.
"""
from base_class import Sort
class InsertSort(Sort):
def sorting_process(self, input_array):
"""
Uses only a single list and compares the two indexed values
"""
unsorted = input_array
for index in range(1, len(unsorted)):
value = unsorted[index]
index_2 = index - 1
while(index_2 >= 0 and unsorted[index_2] > value):
unsorted[index_2+1] = unsorted[index_2] # shift number in slot i to slot i + 1
unsorted[index_2] = value # shift value left into slot i
index_2 = index_2-1
return unsorted
if __name__ == '__main__':
sorting = InsertSort()
sorting.main()
print('Subclass: ', issubclass(InsertSort, Sort))
print('Instance: ', isinstance(InsertSort(), Sort))
| true |
a47002a92364beda833760095fdb204a48b68c29 | Serge-N/python-lessons | /Basics/strings/exercise2.py | 305 | 4.125 | 4 | user = input('Would you like to continue? ')
if(user=='no' or user =='No' or user == 'NO' or user=='n'):
print('Exiting')
elif (user=='yes' or user =='Yes' or user == 'YES' or user=='y'):
print('Continuing...')
print('Complete!')
else:
print('Please try again and respond with yes or no') | true |
d279c333259192f4c397269c8dde2fdb605527c4 | Serge-N/python-lessons | /Basics/Numeric/calculator.py | 1,484 | 4.375 | 4 | print ('Simple Calculator!')
first_number = input ('First number ?')
operation = input ('Operation ?')
second_number = input ('Second number ?')
if not first_number.isnumeric() or not second_number.isnumeric():
print('One of the inputs is not a number.')
operation = operation.strip()
if operation == '+' :
first_number = int(first_number)
second_number = int (second_number)
print(f'Sum of {first_number} + {second_number} = {first_number+second_number}')
elif operation =='-':
first_number = int(first_number)
second_number = int (second_number)
print(f'Difference of {first_number} - {second_number} = {first_number-second_number}')
elif operation =='*':
first_number = int(first_number)
second_number = int (second_number)
print(f'Product of {first_number} * {second_number} = {first_number*second_number}')
elif operation =='/':
first_number = int(first_number)
second_number = int (second_number)
print(f'Dividend of {first_number} / {second_number} = {first_number/second_number}')
elif operation =='**':
first_number = int(first_number)
second_number = int (second_number)
print(f'{first_number} power {second_number} = {first_number**second_number}')
elif operation =='%':
first_number = int(first_number)
second_number = int (second_number)
print(f'Modulus of {first_number} % {second_number} = {first_number%second_number}')
elif operation:
print('Operation not recognized.') | true |
ce7678a04a4faf67239c8131b7db9f42bfcaf579 | mikelhomeless/CS490-0004-python-and-deep-learning- | /module-1/python_lesson_1.py | 1,345 | 4.375 | 4 | # QUESTION 1: What is the difference between python 2 and 3?
# Answer: Some of the differences are as follows
# Print Statement
# - Python 2 allowed for a print statement to be called without using parentheses
# _ Python 3 Forces parentheses to be used on the print statement
#
# Division Operations
# 2/3 in python 2 will result in integer division => 1
# 2/3 in python 3 will result in a floating point division => 1.5
#
# Input Function
# The input method in python 2 is raw_input()
# The input method in python 3 is simply input()
# QUESTION 2
user_string = input('Please type "python": ')
print(user_string[::2][::-1])
num1 = int(input('Please enter a number: '))
num2 = int(input('Please enter another number: '))
print('The sum of the numbers you entered is %s' % (num1 + num2))
print('The power of the first number by the second number is %s' % num1 ** num2)
print('The remainder of the first number divided by the second number is %s' % (num1 % num2))
# QUESTION 3
string_of_pythons = input('Please enter a string containing at least one "python": ')
# split the string on the word python and rejoin with pythons in the split locations
new_string = 'pythons'.join(string_of_pythons.split('python'))
print(new_string) | true |
cdddf8d99ef523049380a7a9d659f6c02a77572a | tsholmes/leetcode-go | /02/84-peeking-iterator/main.py | 1,846 | 4.34375 | 4 | # Below is the interface for Iterator, which is already defined for you.
#
class Iterator(object):
def __init__(self, nums):
"""
Initializes an iterator object to the beginning of a list.
:type nums: List[int]
"""
self.nums = nums
def hasNext(self):
"""
Returns true if the iteration has more elements.
:rtype: bool
"""
return len(self.nums) > 0
def next(self):
"""
Returns the next element in the iteration.
:rtype: int
"""
v = self.nums[0]
self.nums = self.nums[1:]
return v
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.it = iterator
self.p = None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if self.p is None:
self.p = self.it.next()
return self.p
def next(self):
"""
:rtype: int
"""
if self.p is not None:
v = self.p
self.p = None
return v
return self.it.next()
def hasNext(self):
"""
:rtype: bool
"""
return self.p is not None or self.it.hasNext()
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].
if __name__ == '__main__':
it = Iterator([1,2,3,4,5])
pit = PeekingIterator(it)
while pit.hasNext():
print(pit.peek())
print(pit.next())
| true |
c9d1bf857bd0a38c69c14069dc6801e8a034b143 | icarlosmendez/dpw | /wk1/day1.py | 2,249 | 4.15625 | 4 | # print 'hello'
# # if, if/else
# grade = 60
# message = 'you really effed it up!'
# if grade > 89:
# message = "A"
# elif grade > 79:
# message = 'B'
# elif grade > 69:
# message = 'C'
#
# print message
# # if, if/else
#
# name = 'bob'
#
# if(name == 'bob'):
# print 'your name is bob'
# elif(name == 'joe'):
# print 'your name is bob'
# else:
# print "you're a nobody"
# # simple iterative loop
#
# for i in range(10):
# print i
# # iterative loop with a starting point, end point and a metric
#
# for i in range(2,11,2):
# print i
# # iterate over a list (array)
#
# grades = [70, 80, 90]
# grades.append(100)
# grades.splice(1,1) javaScript for removing an index
# grades.pop() - get rid of the last element
# grades.pop(0) - get rid of an element at a specific index
# print grades
# # functions
#
# an empty function
# def greetings():
# pass
#
# def add(a, b):
# total = a + b
# return total
#
# print add(2, 2)
# calculate avg function
#
# test = [70, 80, 90, 90] # test is our variable
# def avg(n): # n is a generic variable representing a numerical value
# total = 0
# for i in n:
# total += i
# average = total/len(n)
# return average
# pass in the variable test which will be represented in the function by n
# print avg(test)
# sum of all odd numbers in a list
#
# nums = [1,2,3,4,5,6,7,8,9]
# def odd_sum(n):
# odd_total = 0
# for i in n:
# if i %2 != 0:
# odd_total += i
# return odd_total
# print odd_sum(nums)
# verify vowels in a string
#
print 'This program will output a list of vowels contained in any word you enter.'
word = raw_input("Type a word: ")
def vowels(w):
vowel_container = []
for i in w:
if i == 'a':
vowel_container.append(i)
elif i == 'e':
vowel_container.append(i)
elif i == 'i':
vowel_container.append(i)
elif i == 'o':
vowel_container.append(i)
elif i == 'u':
vowel_container.append(i)
if len(vowel_container) == 0:
return 'There are no vowels in this word'
else:
return sorted(vowel_container)
print vowels(word)
# extra credit:
# no duplicate values
| true |
09405c197f8fdd64081dda2c24197c37ad5da468 | kfactora/coding-dojo-python | /python_oop/bankAccount.py | 1,319 | 4.5 | 4 | # Assignment: BankAccount
# Objectives
# Practice writing classes
# The class should also have the following methods:
# deposit(self, amount) - increases the account balance by the given amount
# withdraw(self, amount) - decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5
# display_account_info(self) - print to the console: eg. "Balance: $100"
# yield_interest(self) - increases the account balance by the current balance * the interest rate (as long as the balance is positive)
class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print("Balance:", "$",self.balance)
def yield_interest(self):
self.balance *= self.int_rate
return self
bank1 = BankAccount(1.01,0)
bank1.deposit(100).deposit(100).deposit(100).withdraw(50).yield_interest().display_account_info()
bank2 = BankAccount(1.01,0)
bank2.deposit(100).deposit(100).withdraw(25).withdraw(25).withdraw(25).withdraw(25).yield_interest().display_account_info()
| true |
1e99ffac6aebd8568435cd24162c5c20cd20185b | airportyh/begin-to-code | /lessons/javascript/guess_number_bonus.py | 948 | 4.125 | 4 |
while True:
import random
secret_number = random.randint(1, 10)
counter = 0
guess = int(input("I'm thinking of a number from 1-10. Pick one!"))
while counter <= 3:
if guess > secret_number:
print("Nope. Too high! Keep guessing!")
if guess < secret_number:
print("Nope. Too low! Keep guessing!")
if guess == secret_number:
print("You got it!")
guess = int(input("Go again? y or n"))
counter = counter + 1
if guess != "y":
break
print("Bye bye!")
'''
Stage 4
Make it so that the player can only guess 5 times at most. If they guessed 5 times and still miss, print "You used up all your guesses!".
Hint: you'll need to introduce the loop counter pattern into your code by adding a loop counter, and repeating condition, and a incrementer statement.
''' | true |
91cbeb7914b033c2983011c6e270a5efa10a8f31 | Success2014/AlgorithmStanford | /QuickSort.py | 2,141 | 4.125 | 4 | __author__ = 'Neo'
def QuickSort(array, n):
"""
:param array: list
:param n: length of the array
:return: sorted array and number of comparison
"""
if n <= 1:
return array, 0
pivot = ChoosePivot2(array, n)
pivot_idx = array.index(pivot)
array = Partition(array, pivot_idx)
pivot_idx = array.index(pivot)
first_array = array[0: pivot_idx]
second_array = array[pivot_idx + 1:]
first_array_new, facNum = QuickSort(first_array, len(first_array))
second_array_new, secNum = QuickSort(second_array, len(second_array))
return first_array_new + [pivot] + second_array_new, (n - 1) + facNum + secNum
def Partition(array, index):
"""
:param array:
:param index: index of the pivot
:return: partitioned array
"""
if len(array) <= 1:
return array
i = 1
array[0], array[index] = array[index], array[0]
for j in range(1,len(array)):
if array[j] < array[0]:
array[i], array[j] = array[j], array[i]
i += 1
array[0], array[i - 1] = array[i - 1], array[0]
return array
def ChoosePivot1(array, n):
"""
choose the first item as the pivot
:param array:
:param n: length of the array
:return: pivot
"""
return array[0]
def ChoosePivot2(array, n):
"""
:param array:
:param n: length of the array
:return: pivot
"""
return array[-1]
def ChoosePivot3(array, n):
"""
use the median-of-three
:param array:
:param n: length of the array
:return: pivot
"""
if n % 2 == 0:
median = array[n / 2 - 1]
else:
median = array[n / 2]
comArray = [array[0], median, array[-1]]
max = -100000000
maxSec = -200000000
for value in comArray:
if value > max:
maxSec = max
max = value
elif value > maxSec:
maxSec = value
return maxSec
fhand = open('QuickSort.txt')
testarray = []
count = 0
for line in fhand:
line = int(line)
testarray.append(line)
count += 1
#print testarray
print type(testarray)
x,y = QuickSort(testarray, count)
print y
| true |
864fb4584710cd28db4f0f9cec58ab1e60068662 | FakeEmpire/Learning-Python | /inheritance vs composition.py | 1,819 | 4.5 | 4 | # Most of the uses of inheritance can be simplified or replaced with composition
# and multiple inheritance should be avoided at all costs.
# here we create a parent class and a child class that inherits from it
class Parent(object):
def override(self):
print("PARENT override()")
def implicit(self):
print("PARENT implicit()")
def altered(self):
print("PARENT altered()")
class Child(Parent):
# note here that override is going to override the inheritance from the Parent
# class
def override(self):
print("CHILD override()")
# in this case, super (Child, self) looks for the parent class of Child
# and then returns Parent.altered()
def altered(self):
print("CHILD, BEFORE PARENT altered()")
super(Child, self).altered()
print("CHILD, AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
# Using composition instead of inheritance
# good for has-a rather than is-a relationships
class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, BEFORE OTHER altered()")
self.other.altered()
print("CHILD, AFTER OTHER altered()")
son = Child()
son.implicit()
son.override()
son.altered()
# In this case the child class takes what it needs from other, not everthing
| true |
f38e472b66609a02b34c26746d4280f6fb869157 | FakeEmpire/Learning-Python | /lists.py | 1,192 | 4.46875 | 4 | # They are simply ordered lists of facts you want to store and access randomly or linearly by an index.
# use lists for
# If you need to maintain order. Remember, this is listed order, not sorted order. Lists do not sort for you.
# If you need to access the contents randomly by a number. Remember, this is using cardinal numbers starting at 0.
# If you need to go through the contents linearly (first to last). Remember, that's what for-loops are for.
# you can ONLY use numbers to get things out of lists
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(' '.join(stuff)) # what? cool!
print('#'.join(stuff[3:5])) # super stellar!
| true |
328645b0543f27cc5b2bb471fb71bc33f6adf9ca | momentum-cohort-2019-02/w2d1--house-hunting-lrnavarro | /house-hunting.py | 1,143 | 4.40625 | 4 | print("How many months will it take to buy a house? ")
annual_salary = int(input("Enter your annual salary: ") )
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ") )
total_cost = int(input("Enter the cost of your dream home: ") )
down_payment_percent = input("Enter the percent of your home's cost to save as down payment [0.25]: ")
if down_payment_percent == "":
down_payment_percent = 0.25
annual_rate_of_return = input("Enter the expected annual rate of return [0.04]: ")
if annual_rate_of_return == "":
annual_rate_of_return = 0.04
current_savings = 0
portion_down_payment = (total_cost) * float(down_payment_percent)
# r = 0.04 # current_savings*r/12
total_months = 0
monthly_savings = (annual_salary/12)*portion_saved
# At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your monthly salary (annual salary / 12)
while current_savings < portion_down_payment:
current_savings += monthly_savings + current_savings * float(annual_rate_of_return)/12
total_months += 1
print("Number of months: " + str(total_months) )
| true |
ac1558fae111c31f0d18e714807f93178e6ec275 | eflipe/python-exercises | /codewars/string_end_with.py | 682 | 4.28125 | 4 | '''
Link: https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d/train/python
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
'''
def solution(string, ending):
end_value = len(string)
print('end', end_value)
ends_with = string.endswith(ending, 0, end_value)
return ends_with
if __name__ == '__main__':
string_test_1 = 'abc'
end_test_1 = 'bc'
string_test_2 = 'abc'
end_test_2 = 'd'
string_test_3 = 'abc'
end_test_3 = 'abc'
print(solution(string_test_3, end_test_3))
| true |
9dd2f246428cf6227a0f110cc2cf4efb468ad292 | eflipe/python-exercises | /apunte-teorico/gg/reverse_string.py | 249 | 4.28125 | 4 | # https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/
def reverse(s):
str = ""
for i in s:
str = i + str
return str
# otra
# Function to reverse a string
def reverse(string):
string = string[::-1]
return string
| true |
9c8fd4d8675080e4551348d61e1846d2a9b14f62 | eflipe/python-exercises | /automateStuff/strings_manipulation_pyperclip.py | 748 | 4.3125 | 4 | '''
Paste text from the clipboard
Do something to it
Copy the new text to the clipboard
#! python3
# Adds something to the start
# of each line of text on the clipboard.
'''
import pyperclip
text = pyperclip.paste()
print('Texto original :')
print(text)
print(type(text))
# split() return a list of strings, one for each line in the original string
lines = text.split('\n')
print(type(lines))
for i in range(len(lines)):
# print(i)
lines[i] = '- ' + lines[i].lower() # agregamos '- ' y lowercase
# print(lines[i])
# join(): to make a single string value from the list Lines
text = '\n'.join(lines)
print('Texto modificado :\n')
print(text)
print(type(text))
print('\n El texto ha sido modificado con éxito')
pyperclip.copy(text)
| true |
a854977aeab48172b818526ab814c99b2846fc72 | julianikulski/cs50 | /sentimental_vigenere/vigenere.py | 1,911 | 4.21875 | 4 | import sys
from cs50 import get_float, get_string, get_int
# get keyword
if len(sys.argv) == 2:
l = sys.argv[1]
else:
print("Usage: python vigenere.py keyword")
sys.exit("1")
# if keyword contains a non-alphabetical character
for m in range(len(l)):
if str.isalpha(l[m]) is False:
print("Please enter a keyword with letters and no numbers")
sys.exit("1")
# request plaintext
s = get_string("plaintext: ")
# declaring j to ensure that enciphering is only done is character in l isalpha
j = 0
# encipher the plaintext using the keyword
print("ciphertext: ", end="")
for i in range(len(s)):
# keeping j independent of i and only moving forward if char in l isalpha
j = j % len(l)
# for all alphabetic values
if str.isalpha(s[i]):
# preserve case
if str.isupper(s[i]):
# shift upper case plaintext character by key
if str.isupper(l[j]):
# ensure that characters in l will be treated irrespective of case
o = (((ord(s[i])) - 65) + (ord(l[j]) - 65)) % 26
print(f"{chr(o + 65)}", end="")
else:
o = (((ord(s[i])) - 65) + (ord(l[j]) - 97)) % 26
print(f"{chr(o + 65)}", end="")
else:
# shift lower case plaintext character by key
if str.isupper(l[j]):
# ensure that characters in l will be treated irrespective of case
o = (((ord(s[i])) - 97) + (ord(l[j]) - 65)) % 26
print(f"{chr(o + 97)}", end="")
else:
o = (((ord(s[i])) - 97) + (ord(l[j]) - 97)) % 26
print(f"{chr(o + 97)}", end="")
# increasing j if ith character in l islpha is True
j += 1
else:
# anything non-alphabetic will be printed without changes
print(f"{s[i]}", end="")
# skip to next row at the end
print("") | true |
4a35f649b74b1103a6520c8d04551038636613ba | JRMfer/dataprocessing | /Homework/Week_3/convertCSV2JSON.py | 695 | 4.34375 | 4 | #!/usr/bin/env python
# Name: Julien Fer
# Student number: 10649441
#
# This program reads a csv file and convert it to a JSON file.
import csv
import pandas as pd
import json
# global variable for CSV file
INPUT_CSV = "unemployment.csv"
def csv_reader(filename, columns):
"""
Loads csv file as dataframe and select columns
to analyze
"""
data = pd.read_csv(filename)
data = data[columns]
return data
def make_json(data):
"""
Coverts dataframe to JSON file with date as index
"""
data.set_index("DATE").to_json("data.json", orient="index")
if __name__ == "__main__":
data = csv_reader(INPUT_CSV, ["DATE", "UNEMPLOYMENT"])
make_json(data)
| true |
3152f88c91ac47190be22d71cc04623d4b8029ce | MarioAP/saturday | /sabadu/three.py | 390 | 4.15625 | 4 | # Create a variable containing a list
my_list = ['ano', 'mario', 'nando', 'niko']
# print that list
print my_list
# print the length of that list
print len(my_list)
# add an element to that list
my_variable = "hello world"
my_list.append(my_variable)
# print that list
print my_list
# print the length of that list
print len(my_list)
# print the first element in that list
print my_list[0]
| true |
efccc9931fcb7b9594a54e383449557fa7a38ea7 | PalakSaxena/PythonAssigment | /Python Program that displays which letters are in two strings but not in both.py | 549 | 4.15625 | 4 | List1 = []
List2 = []
def uncommon(List1, List2):
for member in List1:
if member not in List2:
print(member)
for member in List2:
if member not in List1:
print(member)
num1 = int(input(" Enter Number of Elements in List 1 : "))
for i in range(0, num1):
ele = int(input(" Enter Element : "))
List1.append(ele)
num2 = int(input(" Enter Number of Elements in List 2 : "))
for i in range(0, num2):
ele = int(input(" Enter Elements : "))
List2.append(ele)
uncommon(List1, List2)
| true |
409615f7a9e1c85e8402fcde1e1ee1e3a20dcc78 | spartus00/PythonTutorial | /lists.py | 2,324 | 4.46875 | 4 | #Showing items in the list
food = ['fruit', 'vegetables', 'grains', 'legumes', 'snacks']
print(food)
print(food[-2])
print(food[0:-2])
#Add an item to a list
food.append('carbs')
print(food)
#Insert a new thing to a certain area in the list
food.insert(-1, 'beverages')
print(food)
#Extend method - add the items from another list
specific_food = ['lettuce', 'tomates']
food.extend(specific_food)
print(food)
#Remove items in the list
food.remove('lettuce')
print(food)
popped = food.pop()
print(popped)
#Reverse a list
food.reverse()
print(food)
#Sort a list in alphabetical order
food.sort()
print(food)
num_sort = [4, 3, 6, 7, 2, 1 ]
num_sort.sort()
print(num_sort)
#Sort values in descending order
num_sort.sort(reverse=True)
print(num_sort)
#Get a sorted version of a list without changing the actual list
sorted_food = sorted(food) #sorted is a function
print(sorted_food)
#Built in functions
numbers = [7, 4, 2, 7, 1, 0, 9]
print(min(numbers)) #min number of the list
print(max(numbers))
print(sum(numbers))
#Find values in the list
print(food)
print(food.index('fruit'))
#See if a value is in a list. The "in" operator is very important.
print('cat' in food)
print('grains' in food)
#Looping through values using a for loop
for item in food:
print(item)
#Index value we are on using enumerate
for index, item in enumerate(food, start=1):
print(index, item)
#Turning lists into strings
food_str = ', '.join(food)
print(food_str)
food_str = ' - '.join(food)
print(food_str)
new_food = food_str.split(' - ')
print(new_food)
#Tuples (cannot modify tuples)
tuple_1 = ('fruit', 'vegetables', 'grains', 'legumes', 'snacks')
tuple_2 = tuple_1
# tuple_1[0] = 'Cat food'
print(tuple_1)
#Sets (order can change) - Sets don't care about order. Throw away duplicates
set_food = {'fruit', 'vegetables', 'grains', 'legumes', 'snacks'}
print(set_food)
print('fruit' in set_food)
#Sets - compare
set_food_2 = {'fruit', 'vegetables', 'grains', 'legumes', 'cat food'}
print(set_food.intersection(set_food_2))
print(set_food.difference(set_food_2))
print(set_food.union(set_food_2))
#Create empty lists, tuples, and sets
# Empty Lists
empty_list = []
empty_list = list()
# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()
# Empty Sets
empty_set = {} # This isn't right! It's a dict
empty_set = set() | true |
11fdf182212f1cabf7d32f2e741890f7d18923f1 | muyie77/Rock-Paper-Scissors | /RPS.py | 2,528 | 4.1875 | 4 | from random import randint
from sys import exit
# Function Declarations
# Player
def player():
while True:
choice = int(input("> "))
if choice == 1:
print("You have chosen Rock.")
break
elif choice == 2:
print("You have chosen Paper.")
break
elif choice == 3:
print("You have chosen Scissors.")
break
else:
print("Invalid choice! Choose again.")
return choice
# Computer
def computer():
choice = randint(1, 3)
if choice == 1:
print("Computer have chosen Rock.\n")
elif choice == 2:
print("Computer have chosen Paper.\n")
else:
print("Computer have chosen Scissors.\n")
return choice
# Comparing choice
def compare():
win = 0
lose = 0
draw = 0
while True:
print("--------------")
print("| 1. Rock |\n| 2. Paper |\n| 3. Scissors|")
print("--------------")
user = player()
ai = computer()
if user == 1: # User chose Rock
if ai == 1: # Computer chose Rock
print("Draw!\n")
draw += 1
elif ai == 2: # Computer chose Paper
print("You lose!\n")
lose += 1
else: # Computer chose Scissors
print("You win!\n")
win += 1
elif user == 2: # User chose Paper
if ai == 1: # Computer chose Rock
print("You win!\n")
win += 1
elif ai == 2: # Computer chose Paper
print("Draw!\n")
draw += 1
else: # Computer chose Scissors
print("You lose!\n")
lose += 1
else: # User chose Scissors
if ai == 1: # Computer chose Rock
print("You lose!\n")
lose += 1
elif ai == 2: # Computer chose Paper
print("You win!\n")
win += 1
else: # Computer chose Scissors
print("Draw!\n")
draw += 1
print(f"Win: {win}\tLose: {lose}\tDraw: {draw}")
print("Do you want to play again? y/n")
while True:
ch = input("> ")
if ch == 'y' or ch == 'Y':
print("")
"""Play again"""
break
elif ch == 'n' or ch == 'N':
exit(0)
else:
print("Invalid choice!\n")
compare()
| true |
3fd9efdb51612106ecb7284f02490157906a7aaf | jitesh-cloud/password-guesser | /passGuesser.py | 1,082 | 4.375 | 4 | # importing random lib for checking out random pass
from random import *
# Taking a sample password from user to guess
give_pass = input("Enter your password: ")
# storing alphabet letter to use thm to crack password
randomPass = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v',
'w', 'x', 'y', 'z']
# initializing an empty string
actualguess = ""
count = 0
# using loop to catch the give_pass by random guesses
# it is also showing count of the passes
while (actualguess != give_pass.lower()):
actualguess = ""
# generating random passwords using for loop
for letter in range(len(give_pass)):
guess_letter = randomPass[randint(0, 25)]
actualguess = str(guess_letter) + str(actualguess)
# printing guessed passwords
print(actualguess,"-",count+1)
count+=1
# printing the matched password
print("--------------------------------------------------------")
print("Your input is", give_pass,"-->","Your password is",actualguess)
| true |
5da4f6ff26a580665ead28ed30b01cfc93cdf29a | devtony168/python-100-days-of-code | /day_09/main.py | 861 | 4.15625 | 4 | from replit import clear
from art import logo
#HINT: You can call clear() to clear the output in the console.
print(logo)
print("Welcome to the secret auction program!")
bidders = {}
def add_bid():
name = input("What is your name? ") # Key
bid = int(input("What is your bid? $")) # Value
bidders[name] = bid
add_bidders = True
add_bid()
while add_bidders:
result = input("Are there any other bidders? Enter 'yes' or 'no': ")
if result == "no":
add_bidders = False
clear()
elif result == "yes":
add_bidders = True
clear()
add_bid()
else:
input("Invalid input. Press enter to continue. ")
clear()
highest_bid = 0
winner_name = ""
for name in bidders:
if bidders[name] > highest_bid:
highest_bid = bidders[name]
winner_name = name
print(f"The winner is {winner_name} with a bid of ${highest_bid}!") | true |
1888175e01d6c4548fdd943699435df2d6d8ab44 | TravisMWeaver/Programming-Languages | /ProblemSet5/SideEffects2.py | 391 | 4.125 | 4 | #!/usr/bin/python
# Note that as arr1 is passed to changeList(), the values are being changed
# within the function, not from the return of the function. As a result, this
# behavior is indicative of a side effect.
def changeList(arr):
arr[0] = 9
arr[1] = 8
arr[2] = 7
arr[3] = 6
arr[4] = 5
return arr
arr1 = [1, 2, 3, 4 , 5]
arr2 = changeList(list(arr1))
print(arr1)
print(arr2) | true |
cffe973b153db29bc9b58010da4c7a0204a02169 | bhanukirant99/AlgoExpert-1 | /Arrays/TwoNumberSum.py | 465 | 4.125 | 4 | # time complexity = o(n)
# space complexity = o(n)
def twoNumberSum(array, targetSum):
# Write your code here.
dicti = {}
for i in range(len(array)):
diff = targetSum - array[i] # calculate diff between target and every other item in the array
if diff in dicti:
return ([diff, array[i]])
else:
dicti[array[i]] = diff
return [] # if the array has no element or just one element or if there was no pair then return the empty list
| true |
b0545ce4169a0b4f176f128cc990001be3068ebe | QiuFeng54321/python_playground | /while/Q5.py | 424 | 4.125 | 4 | # Quest: 5. Input 5 numbers,
# output the number of positive numbers and
# negative number you have input
i: int = 0
positives: int = 0
negatives: int = 0
while i < 5:
num: float = float(input(f"Number {i + 1}: "))
if num >= 0:
positives += 1
else:
negatives += 1
i += 1
print(f"There are {positives} positive numbers and "
f"{negatives} negative numbers")
| true |
25116ccdfd3d7e7663d1764544bbd3bc4de4a664 | QiuFeng54321/python_playground | /loop_structure/edited_Q2.py | 323 | 4.1875 | 4 | # Quest: 2. Input integer x,
# if it is an odd number,
# output 'it is an odd number',
# if it is an even number,
# output 'it is an even number'.
print(
[
f"it is an {'odd' if x % 2 == 1 else 'even'} number"
for x in [int(input("Input a number: "))]
][0]
)
| true |
6ed9d9b9a39a91941c3c9ce522a9b2427b922be5 | koushikbhushan/python_space | /Arrays/replce_next_greatest.py | 562 | 4.28125 | 4 | """Replace every element with the greatest element on right side
Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2, -1}.
"""
arr = [16, 17, 4, 3, 5, 2]
arr_length = len(arr)
i = arr_length - 1
max = -1
print(i)
while i >= 0:
temp = arr[i]
arr[i] = max
if temp > max:
max = temp
i = i-1
print(arr) | true |
2d157098f1f22a0940dd413d5459cd8e6027fc0b | mikaylakonst/ExampleCode | /loops.py | 1,222 | 4.375 | 4 | # This is a for loop.
# x takes on the values 0, 1, 2, 3, and 4.
# The left end of the range is inclusive.
# The right end of the range is exclusive.
# In other words, the range is [0, 5).
for x in range(0, 5):
print(x)
# This is another for loop.
# x takes on the values 0, 1, 2, 3, and 4. In other words,
# x takes on all values between 0 (inclusive) and 5 (exclusive).
# This loop is equivalent to the for loop above
# and prints the exact same thing.
for x in range(5):
print(x)
# This for loop does the same thing as the other ones.
# x goes from 0 to 5 by steps of size +1.
# As before, the 0 is inclusive and the 5 is exclusive,
# so x takes on the values 0, 1, 2, 3, and 4.
for x in range(0, 5, 1):
print(x)
# This is a while loop.
# Every time the loop executes,
# x is printed, and then x is increased by 1.
# x takes on the values 0, 1, 2, 3, and 4.
# This loop does the same thing as the for loop above.
x = 0
while x < 5:
print(x)
x = x + 1
# This is also a while loop.
# A loop that starts with while True
# will run forever unless it is broken
# by a break statement.
# This loop does the same thing as the loops above.
x = 0
while True:
print(x)
x = x + 1
if x >= 5:
break
| true |
b4b3197fdd4fbea2e6b219e55e4bd87653123005 | Nishith/Katas | /prime_factors.py | 879 | 4.21875 | 4 | import sys
"""List of primes that we have seen"""
primes = [2]
def generate(num):
"""Returns the list of prime factors for the given argument
Arguments:
- `num`: Integer
Returns:
List of prime factors of num
"""
factors = []
if num < 2:
return factors
loop = 2
while loop < num:
if num % loop == 0 and is_prime(loop):
while(num % loop == 0):
num /= loop
factors.append(loop)
loop = loop + 1
factors.sort()
return factors
def is_prime(n):
"""
Checks whether the given number is a prime
"""
if n in primes:
return 1
if n % 2 == 0:
return 0
for i in range(3, n//2 + 1, 2):
if n % i == 0:
return 0
primes.append(n)
return 1
if __name__ == '__main__':
print(generate(sys.maxsize))
| true |
c355a311ae7d97d282cf9c5788d05d77e6a9de83 | pruty20/100daysofcode-with-python-course | /days/01-03-datetimes/code/Challenges/challenges_3_yo.py | 1,743 | 4.28125 | 4 | # https://codechalleng.es/bites/128/
from datetime import datetime
from time import strptime, strftime
THIS_YEAR = 2018
"""
In this Bite you get some more practice with datetime's useful
strptime and stftime.
Complete the two functions: years_ago and convert_eu_to_us_date
following the instructions in their docstrings.
This is the defintion and difference between the two:
- strptime: parse (convert) string to datetime object.
- strftime: create formatted string for given time/date/datetime object
according to specified format.
Reference: 8.1.8. strftime() and strptime() Behavior.
Link: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
Good luck and keep calm and code in Python!
"""
def years_ago(date):
"""Receives a date string of 'DD MMM, YYYY', for example: 8 Aug, 2015
Convert this date str to a datetime object (use strptime).
Then extract the year from the obtained datetime object and subtract
it from the THIS_YEAR constant above, returning the int difference.
So in this example you would get: 2018 - 2015 = 3"""
date_parsed = strptime(date, '%d %b, %Y')
year = date_parsed.tm_year
return THIS_YEAR - year
def convert_eu_to_us_date(date="08/12/2015"):
"""Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002
Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002).
To enforce the use of datetime's strptime / strftime (over slicing)
the tests check if a ValueError is raised for invalid day/month/year
ranges (no need to code this, datetime does this out of the box)"""
dt = datetime.strptime(date, "%d/%m/%Y")
return dt.strftime("%m/%d/%Y")
convert_eu_to_us_date() | true |
c7f351833cc35883cbc542a76d6659a112607a93 | kiddlu/kdstack | /python/programiz-examples/flow-control/if-else.py | 1,415 | 4.53125 | 5 | #!/usr/bin/env python
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = 1
if not num <= 0:
print(num, "is a positive number.")
print("This is also always printed.")
num = 3
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
#num = int(input("\nEnter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
year = int(input("\nEnter one year: "))
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
| true |
b5ca219951a291a323d3e93c8b2c46369de54ba9 | alex99q/python3-lab-exercises | /Lab2/Exercise5.py | 676 | 4.15625 | 4 | range_start = int(input("Beginning of interval: "))
range_end = int(input("End of interval: "))
if range_start < range_end:
for num in range(range_start, range_end + 1):
if 0 < num < 10:
print(num)
continue
elif 10 <= num < 100:
continue
else:
power_of_armstrong_num = len(str(num))
armstrong_num = 0
for digit in str(num):
armstrong_num += pow(int(digit), int(power_of_armstrong_num))
if num == armstrong_num:
print(armstrong_num)
else:
print("End of interval can't be higher than beginning of interval") | true |
3a5ac90e5105ef1d1be19c786f79f553dfc5b7db | honda0306/Intro-Python | /src/dicts.py | 382 | 4.21875 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{'hometown': 'Rescue, CA'},
{'age': 42},
{'hobbies': 'smiling'}
]
# Write a loop that prints out all the field values for all the waypoints
for i in waypoints:
print(i) | true |
7c1667f2c28599a74f27953fa8752f8162e05987 | krishia2bello/N.B-Mi-Ma-Sorting-Algorithm | /NB_MiMa_Sorting_Algorithm.py | 2,046 | 4.34375 | 4 | def sort_list(list_of_integers):
list_input = list_of_integers # copying the input list for execution
sorted_list = [] # defining the new(sorted) list
min_index = 0 # defining the index of the minimum value to be inserted in the new list
max_index = 1 # defining the index of the maximum value to be inserted in the new list
while len(list_input) != 0: # while there is still an integer in the input list
sorted_list.insert(min_index, min(list_input)) # inserting the least value of the input list to the new list
list_input.remove(min(list_input)) # removing what was inserted from the previous line
min_index = min_index + 1 # setting the next index of the least value to be inserted in the new list
if len(list_input) != 0: # if there are still integers in the list remaining
sorted_list.insert(max_index, max(list_input)) # insert the greatest value of the input list to the new list
list_input.remove(max(list_input)) # removing what was inserted from the previous line
max_index = max_index + 1 # setting the next index of the greatest value to be inserted in the new list
return sorted_list # returning the new list as output
print(Test Cases!)
# empty list,
sort_list([]) # expect []
# even length,
sort_list([4, 3, 2, 1]) # expect 1 2 3 4
# odd length,
sort_list([2, 3, 4, 5, 1]) # expect 1 2 3 4 5
# consist of positive and negative integer values,
sort_list([3, -3, 2, -2, 1, 0, -1 ]) # expect -3 -2 -1 0 1 2 3
# consist of integers having the same value in the list,
sort_list([10, -3, 0, 6, 4, 5, 2, 7, 3, 1, -1, 8, 7, 9, -2, -3, 10, 2]) # expect -3 -3 -2 -1 0 1 2 2 3 4 5 6 7 7 8 9 10 10
| true |
a333e519c0b53b1649c07102417a38ae4f13c8a5 | Ler4onok/ZAL | /3-Calculator/calculator.py | 2,010 | 4.21875 | 4 |
import math
def addition(x, y):
addition_result = x + y
return addition_result
def subtraction(x, y):
subtraction_result = x - y
return subtraction_result
def multiplication(x, y):
# multiplication_result = args[0]*args[1]
multiplication_result = x * y
return multiplication_result
def division(x, y):
if y != 0:
division_result = x/y
return division_result
else:
raise ValueError('This operation is not supported for given input parameters')
def modulo(x, y):
if 0 < y <= x:
modulo_result = x % y
return modulo_result
else:
raise ValueError('This operation is not supported for given input parameters')
def secondPower(x):
secondPower_result = x * x
return secondPower_result
def power(x, y):
if y >= 0:
power_result = x ** y
return float(power_result)
else:
raise ValueError('This operation is not supported for given input parameters')
def secondRadix(x):
if x > 0:
secondRadix_result = math.sqrt(x)
return secondRadix_result
else:
raise ValueError('This operation is not supported for given input parameters')
def magic(x, y, z, k):
l = x + k
m = y + z
if m == 0:
raise ValueError('This operation is not supported for given input parameters')
z = ((l/m) + 1)
return z
def control(a, x, y, z, k):
if a == 'ADDITION':
return addition(x, y)
elif a == 'SUBTRACTION':
return subtraction(x, y)
elif a == 'MULTIPLICATION':
return multiplication(x, y)
elif a == 'DIVISION':
return division(x, y)
elif a == 'MOD':
return modulo(x, y)
elif a == 'POWER':
return power(x, y)
elif a == 'SECONDRADIX':
return secondRadix(x)
elif a == 'MAGIC':
return magic(x, y, z, k)
else:
raise ValueError('This operation is not supported for given input parameters')
#print (control('SECONDRADIX', -3, 1, 1, 1))
| true |
55873f77d5e19e886a182236b4658eee94b21ec2 | clairepeng0808/Python-100 | /07_mortgage:-calculator.py | 2,756 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 18:04:17 2020
@author: clairepeng
Mortgage Calculator - Calculate the monthly payments of a f
ixed term mortgage over given Nth terms at a given interest rate.
Also figure out how long it will take the user to pay back the loan.
For added complexity, add an option for users to select the
compounding interval (Monthly, Weekly, Daily, Continually).
"""
print('Welcome to mortgage Calculator!')
def enter_terms():
while True:
try:
terms = int(input('Enter the morgage term(in years): '))
if terms >= 50:
print('Sorry, the term should be under 50 years.')
elif terms <= 0:
print('The term should be a positive integer.')
continue
else:
return terms
break
except ValueError:
print('Please enter an integer.')
def enter_rate():
while True:
try:
rate = float(input('Enter the interest rate(%): '))
if rate > 100:
print('Sorry, the rate should be under 100.')
continue
elif rate < 0:
print('Sorry, the rate should be a positive number.')
continue
else:
return rate
break
except ValueError:
print('Please enter a valid number.')
def enter_loan():
while True:
try:
loan = float(input('Enter the loan(in dollars): '))
if loan < 10000:
print('Sorry, the minimum loan is 10000 dollars.')
continue
elif loan < 0:
print('Sorry, the loan should be a positive number.')
continue
else:
return loan
break
except ValueError:
print('Please enter a valid number.')
if __name__ == '__main__':
terms = enter_terms()
rate = enter_rate()
loan = enter_loan()
monthly_rate = rate / 12 /100
months = terms * 12
monthly_payback_rate = (((1 + monthly_rate) ** months) * monthly_rate) / ((( 1 + monthly_rate) ** months) -1)
monthly_payment = loan * monthly_payback_rate
# 每月應付本息金額之平均攤還率=
# {[(1+月利率)^月數]×月利率}÷{[(1+月利率)^月數]-1}
# 平均每月應攤付本息金額=貸款本金×每月應付本息金額之平均攤還率
print(f'Your monthly payment is {monthly_payment:.2f} dollars.') | true |
4f483712e0265702305407df328a349d9ad00b84 | clairepeng0808/Python-100 | /08_change_return_program.py | 2,610 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 18:53:27 2020
@author: clairepeng
Change Return Program -
The user enters a cost and then the amount of money given.
The program will figure out the change and the number of
quarters, dimes, nickels, pennies needed for the change.
"""
def enter_cost():
while True:
try:
cost = round(float(input('Please enter the cost.')),2)
if cost <= 0:
print('The cost must be a positive number!')
continue
else:
return cost
break
except ValueError:
print('Please enter a number.')
continue
def enter_paid():
while True:
try:
paid = round(float(input('Please enter the money you paid.')),2)
if paid < cost:
print('\nYour paid amount must exceed the cost.')
continue
else:
return paid
break
except ValueError:
print('Please enter a number.')
continue
if __name__ == '__main__':
print('Welcome to the change return program!')
while True:
cost = enter_cost()
paid = enter_paid()
change = paid - cost
if change >= 1:
print('Error! The change must be under 1 dollar.')
continue
elif change < 0:
print('Error! Your paid amount must exceed your cost.')
elif change == 0:
print("There's no change.")
break
else:
# Tony's solution
coins = [0.25, 0.1, 0.05, 0.01]
used = []
left = change
for c in coins:
c_used = left // c
left -= ((c_used) * c)
used.append(c_used)
# Claire's solution
quarters = change // 0.25
# left = (change % 0.25)
dimes = (change % 0.25) // 0.1
# left = (change % 0.25) % 0.1
nickles = ((change % 0.25) % 0.1) // 0.05
# left = (left % 0.05) % 0.1
pennies = (round((((change % 0.25) % 0.1) % 0.05),2) // 0.01)
print(f'You will receive {change:.2f} dollars in change.')
print(f'You will get {quarters:.0f} quarters, {dimes:.0f} dimes, {nickles:.0f} nickles, and {pennies:.0f} pennies.')
break | true |
0932555326668cc6127d1d4b3adfe644e6da19f8 | clairepeng0808/Python-100 | /37_check_if_palindrome.py | 753 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 15:52:44 2020
@author: clairepeng
**Check if Palindrome** - Checks if the string entered by the user
is a palindrome. That is that it reads the same forwards as backwards
like “racecar”
"""
from utility import utility as util
def enter_string():
string = input('Enter a string: ').lower()
return string
def check_palindrome(string):
return string[:] == string[::-1]
while True:
string = enter_string()
if check_palindrome(string):
print(f'Congrats! The string \'{string}\' is a palindrome.')
else:
print(f'Sorry, the string \'{string}\' is not a palindrome.')
if not util.replay():
break | true |
2413e3107fbf48938c305f595a678c8ab1b5dbaa | thuytran100401/HW-Python | /multiply.py | 549 | 4.28125 | 4 | """
Python program to take in a list as input and multiply all of the
elements in the list and return the result as output.
Parameter
inputList: list[]
the integer list as input
result: int
the result of multiplying all of the element
"""
def multiply_list(inputList):
result = 1;
for i in range(0, len(inputList)):
try:
int(inputList[i])
except:
return False
for number in inputList:
result = result * int(number)
return result
| true |
871e54ac66b3349a0e66a0117f4a800177f18a2b | SamCadet/PythonScratchWork | /Birthdays.py | 494 | 4.21875 | 4 | birthdays = {'Rebecca': 'July 1', 'Michael': 'July 22', 'Mom': 'August 22'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is ' + str(name) + '\'s birthday.')
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
| true |
c72c90e0c2dfe865eab1d40b99073a8e757cca95 | taharBakir/code_cademy-python | /string_stuff.py | 1,121 | 4.375 | 4 | #Print a
s="Hella"[4]
print s
#Print the length of the string
parrot = "Norwegian Blue"
print len(parrot)
#Print the string in lower case
parrot = "Norwegian Blue"
print parrot.lower()
#Print the string in upper case
parrot = "norwegian blue"
print parrot.upper()
#toString
pi = 3.14
print str(pi)
#Methods that use dot notation only work with strings.
#On the other hand, len() and str() can work on other data types.
ministry = "The Ministry of Silly Walks"
print len(ministry)
print ministry.upper()
print "Spam\n" + "and\n" + "eggs"
print "The value of pi is around " + str(3.14)
'''The % operator after a string is used to combine a string with variables.
The % operator will replace a %s in the string with the string variable that comes after it.
'''
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
name = raw_input("What is your name? ")
quest = raw_input("What is your quest? ")
color = raw_input("What is your favorite color? ")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
| true |
ccebdf820de15e6ff5c5e06b20fa75bbd06448f9 | mitchell-hardy/CP1404-Practicals | /Week 3/asciiTable.py | 1,280 | 4.125 | 4 | __author__ = 'Mitch Hardy'
def main():
NUMBER_MINIMUM = 33
NUMBER_MAXIMUM = 127
# get a number from the user (ASCII) and print the corresponding character.
user_number = get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM)
# get a character from the user and print the corresponding ASCII key
print("The character for {} is {}".format(user_number, chr(user_number)))
user_character = str(input("Enter a character: "))
print("The ASCII code for {} is {}".format(user_character,ord(user_character)))
for i in range(NUMBER_MINIMUM, NUMBER_MAXIMUM):
print("{:^10d}{:^10s}".format(i, chr(i)))
# Get a number from the user, error check and return to main.
def get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM):
number = int(input("Enter a number between {} and {}: ".format(NUMBER_MINIMUM, NUMBER_MAXIMUM)))
while number < NUMBER_MINIMUM or number > NUMBER_MAXIMUM:
try:
print("Invalid number, please choose from between {} and {}:".format(NUMBER_MINIMUM, NUMBER_MAXIMUM))
number = int(input("Enter a number between {} and {}: ".format(NUMBER_MINIMUM, NUMBER_MAXIMUM)))
except:
number = ValueError
number = 0
print("Please only enter numbers!")
return number
main()
| true |
a48c5ea84c3d9d6a8af8517150977ae2c99b8ad7 | abhisheknm99/APS-2020 | /52-Cartesian_product.py | 245 | 4.3125 | 4 | from itertools import product
#only with one list
arr=[1,2,3]
#repeat=2 i.e arr*,repeat=3 i.e arr*arr*arr
l=list(product(arr,repeat=3))
#different arrays
arr1=[1,2,3]
arr2=[2,3]
arr3=[3]
cartesian=list(product(arr1,arr2,arr3))
print(cartesian) | true |
3e05e88a61f112f293f4efb6a0a81f63e0909410 | abdullahw1/CMPE131_hw2 | /calculator.py | 1,529 | 4.46875 | 4 | def calculator(number1, number2, operator):
"""
This function will allow to make simple calculations with 2 numbers
parameters
----------
number1 : float
number2 : float
operator : string
Returns
-------
float
"""
# "+" operator will perform addition
if operator == "+":
print(number1 + number2)
# else if "-" operator used, then subtraction performed
elif operator == "-":
print(number1 - number2)
# else if "*" operator used, multiplication will be performed
elif operator == "*":
print(number1 * number2)
# else if "/" operator is used, division performed
elif operator == "/":
# return false if num2 is 0 as result wont exist
print(number1 / number2)
# perform integral division with "//" operator
elif operator == "//":
print(number1 // number2)
# else perform power operation with "**" operator
elif operator == "**":
print(number1 ** number2)
def parse_input():
"""
gets user input and splits.
This function splits user input into number1, number2, and operator.
passes variables to calculator() function.
"""
EquatOutout = input("Enter Equation: ")
equat = EquatOutout.split()
number1, operator, number2 = equat
number1 = float(number1)
number2 = float(number2)
# pass user input to calculator() function
return(calculator(number1, number2, operator))
#parse_input()
| true |
872fe63e47975aaf586df582e37aced46ed5f8c2 | ZY1N/Pythonforinfomatics | /ch9/9_4.py | 940 | 4.28125 | 4 | #Exercise 9.4 Write a program to read through a mail log, and figure out who had
#the most messages in the file. The program looks for From lines and takes the
#second parameter on those lines as the person who sent the mail.
#The program creates a Python dictionary that maps the senders address to the total
#number of messages for that person.
#After all the data has been read the program looks through the dictionary using
#a maximum loop (see Section 5.7.2) to find who has the most messages and how
#many messages the person has.
fname = raw_input("Enter a file name : ")
handle = open(fname)
dictionary = dict()
for line in handle:
words = line.split()
if "From" in words:
dictionary[words[1]] = dictionary.get(words[1], 0) + 1
largest = None
for element in dictionary:
if largest == None or element > largest:
largest = element
print largest
print 'Largest :', largest, dictionary [largest]
| true |
d33211f78829e397346809c11dd08ea732d61363 | ZY1N/Pythonforinfomatics | /ch11/11_1.py | 491 | 4.15625 | 4 | #Exercise 11.1 Write a simple program to simulate the operation of the the grep
#command on UNIX. Ask the user to enter a regular expression and count the number of lines that matched the regular expression:
import re
fname = open('mbox.txt')
rexp = raw_input("Enter a regular expression : ")
count = 0
for line in fname:
line = line.rstrip()
x = re.findall(rexp, line)
if len(x) > 0:
count = count + 1
print "mbox.txt had %d lines that matched %s" % (count, rexp)
| true |
bf4fb0bb615781cd26ea4c7fde9ee78f21c5dff0 | archana-nagaraj/experiments | /Udacity_Python/Excercises/testingConcepts.py | 890 | 4.21875 | 4 | def vehicle(number_of_tyres, name, color):
print(number_of_tyres)
print(name)
print(color)
vehicle(4, "Mazda", "blue")
# Trying Lists
courses = ['Math', 'Science', 'CompSci']
print(courses)
print(len(courses))
print(courses[1])
print(courses[-1])
#Lists slicing
print(courses[0:2])
print(courses[:2])
print(courses[2:])
print(courses[1:-1])
# Lists methods
#courses.append('Art')
print(courses)
#courses.insert(0,'Art')
print(courses)
#Lists within a list
courses_2 = ['Zoology', 'Writing']
#courses.insert(0,courses_2)
print(courses)
print(courses[0])
# extend a list
courses_3 = ['Education', 'Photography']
#courses.extend(courses_3)
print(courses)
#remove some items from list
courses.remove('Math')
print(courses)
#popped = courses.pop()
print(courses)
#print(popped)
#reverse a list
courses.reverse()
print(courses)
#sorting a list
courses.sort()
print(courses) | true |
9a2a1d2058cc7a2b6345d837173e109f20b39ed5 | jeb26/Python-Scripts | /highestScore.py | 622 | 4.21875 | 4 | ##Write a prog that prompts for a number of students. then each name and score and
##then displays the name of student with highest score.
scoreAcc = 0
nameAcc = None
currentScore = 0
currentName = None
numRuns = int(input("Please enter the number of students: "))
for i in range(numRuns):
currentName = str(input("Please enter the name of the current student: "))
currentScore = int(input("Pleae enter the score the current student: "))
if currentScore > scoreAcc:
scoreAcc = currentScore
nameAcc = currentName
print("The highest scoring student is: ",nameAcc)
| true |
fdb5d39c2ed2c61416aeffb1e4dbc491241ce316 | sonht113/PythonExercise | /HoTrongSon_50150_chapter5/Chapter5/Exercise_page_145/Exercise_04_page_145.py | 338 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 18/08/2021
Program: Exercise_04_page_145.py
Problem:
4. What is a mutator method? Explain why mutator methods usually return the value None.
Solution:
Display result:
58
"""
#code here:
data = [2, 5, 24, 2, 15, 10]
sum = 0
for value in data:
sum += value
print(sum)
| true |
25a467d72816cf35cf0b5ef9b94503dd40376c2a | sonht113/PythonExercise | /HoTrongSon_50150_chapter2/Chapter2/exercise_page_46/exercise_04_page_46.py | 624 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 11/07/2021
Program: exercise_04_page_46.py
PROBLEM:
4) What happens when the print function prints a string literal with embedded
newline characters?
SOLUTION:
4)
=> The print function denoted print() in a computer programming language such as Python is a function that prints values assigned to its parameter.
When assigned a string literal("I'm not going" for example) and break line statements/new line characters(\n),
it prints the value such as "I'm not going\n" and starts a new line where a break line is indicated in the instruction(after "going" in the example)
""" | true |
7d4ed044ec86306dff4cb4752b0d6d9202fad492 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_12_page_133.py | 1,421 | 4.15625 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Project_12_page_133.py
Problem:
12. The Payroll Department keeps a list of employee information for each pay period in a text file.
The format of each line of the file is the following:
<last name> <hourly wage> <hours worked>
Write a program that inputs a filename from the user and prints to the terminal a report of the
wages paid to the employees for the given period. The report should be in tabular format with
the appropriate header. Each line should contain an employee�s name, the hours worked, and the
wages paid for that period.
Solution:
Display result
Enter the file name: ../textFile/project12.txt
Name Hours Work Total Pay
Ho 10 135.0
Dang 15 123.75
Tran 7 86.8
"""
fileName = input("Enter the file name: ")
inputFileName = open(fileName, 'r')
print("%-20s%10s%20s" % ("Name", "Hours Work", "Total Pay"))
for line in inputFileName:
dataList = line.split()
name = dataList[0]
hoursWork = int(dataList[1])
moneyPriceOneHour = float(dataList[2])
totalPay = hoursWork * moneyPriceOneHour
print("%-20s%10s%20s" % (name, hoursWork, totalPay))
| true |
805f1755caf35c97cf3c31dfe3436ffc407ccb01 | sonht113/PythonExercise | /HoTrongSon_50150_chapter5/Chapter5/Exercise_page_149/Exercise_04_page_149.py | 522 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 18/08/2021
Program: Exercise_04_page_149.py
Problem:
4. Define a function named summation. This function expects two numbers, named low and high, as arguments.
The function computes and returns the sum of the numbers between low and high, inclusive.
Solution:
Display result:
5
"""
def summation(low, high):
result = 0
for index in range(low, high):
result += index
return result
low = 2
high = 4
print(summation(low, high))
| true |
ca59990c60f302bcb8521710ad34a14d493224f4 | sonht113/PythonExercise | /HoTrongSon_50150_chapter3/Chapter3/Exercise_page_70/exercise_02_page_70.py | 364 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 23/07/2021
Program: exercise_02_page_70.py
PROBLEM:
2. Write a loop that prints your name 100 times. Each output should begin on a new line.
SOLUTION:
"""
# Code here:
name = "Ho Trong Son"
for i in range(100):
print(name, "(" + str(i+1) + ")")
# Result:
# Ho Trong Son (1)
# ...
# ...
# ...
# Ho Trong Son (100) | true |
e8e4d0c2a84f2bf905a9a4c3721e132249cfd403 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Project_page_132-133/project_05_page_132.py | 1,139 | 4.5625 | 5 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Project_05_page_132.py
Problem:
5. A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right.
For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110.
Note that the leftmost two bits are wrapped around to the right side of the string in this operation.
Define two scripts, shiftLeft.py and shiftRight.py, that expect a bit string as an input. The script
shiftLeft shifts the bits in its input one place to the left, wrapping the leftmost bit to the rightmost
position. The script shiftRight performs the inverse operation. Each script prints the resulting string
Solution:
Display result
Enter a string of bits: 1101
1011
1110
"""
def left(bit):
if len(bit) > 1:
bit = bit[1:] + bit[0]
return bit
def right(bit):
if len(bit) > 1:
bit = bit[-1] + bit[:-1]
return bit
# main
bitInput = input("Enter a string of bits: ")
print(left(bitInput))
print(right(bitInput))
| true |
1e23187a25a230abed4a21b60cdda3e90ae27930 | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_118/Exercise_01_page_118.py | 805 | 4.25 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Exercise_01_page_118.py
Problem:
1. Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2
to perform the following tasks:
a. Obtain a list of the words in the string.
b. Convert the string to uppercase.
c. Locate the position of the string "rules".
d. Replace the exclamation point with a question mark.
Solution:
Display result:
a) ['P', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'u', 'l', 'e', 's', '!']
b) PYTHON RULES!
c) 7
d) Python rules?
"""
string = 'Python rules!'
print('a)', list(string))
print('b)', string.upper())
print('c)', string.index('rules'))
print('d)', string.replace('!', '?'))
| true |
a6971bf97f895b2eafc8af4aba0a631b0bc3dfbe | sonht113/PythonExercise | /HoTrongSon_50150_Chapter4/Chapter4/Exercise_page_125/Exercise_03_page_125.py | 682 | 4.3125 | 4 | """
Author: Ho Trong Son
Date: 5/08/2021
Program: Exercise_03_page_125.py
Problem:
3. Assume that a file contains integers separated by newlines. Write a code segment that opens the
file and prints the average value of the integers.
Solution:
Display result:
Average: 5.0
"""
#Code here:
textFile = open("../textFile/myfile.txt", 'w', encoding='utf-8')
for index in range(1, 50):
textFile.write(str(index) + '\n')
textFile = open("../textFile/myfile.txt", 'r', encoding='utf-8')
sum = 0
count = 0
for line in textFile:
sum += int(line.strip())
count += 1
print(sum)
average = sum/count
print("Average =>", average)
| true |
8fe5c46bdf8a1c42a910d3135d1a8f0dde4fee4f | sonht113/PythonExercise | /HoTrongSon_50150_chapter6/Chapter6/Exercise_page_182/Exercise_04_page_182.py | 522 | 4.125 | 4 | """
Author: Ho Trong Son
Date: 01/09/2021
Program: Exercise_04_page_182.py
Problem:
4. Explain what happens when the following recursive function is called with the value 4 as an argument:
def example(n):
if n > 0:
print(n)
example(n - 1)
Solution:
Result:
- Print to the screen the numbers from 10 to 1
"""
def example(n):
if n > 0:
print(n)
example(n - 1)
def main():
example(10)
main() | true |
4ba7d4715f7716794594ae54630d63a3ad3e3745 | sonht113/PythonExercise | /HoTrongSon_50150_chapter3/Chapter3/Project_page_99-101/project_07_page_100.py | 1,986 | 4.1875 | 4 | """
Author: Ho Trong Son
Date: 24/07/2021
Program: project_07_page_100.py
Problem:
7. Teachers in most school districts are paid on a schedule that provides a salary based on their number of years
of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000
the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2%
increase over the preceding value. Write a program that displays a salary schedule, in tabular format, for
teachers in a school district. The inputs are the starting salary, the percentage increase, and the number of
years in the schedule. Each row in the schedule should contain the year number and the salary for that year.
Solution:
"""
# Code here:
def checkYear(year):
while not 0 < year < 11:
year = float(input("Enter years of service: "))
# input
salary = float(input("Enter starting salary: $ "))
rate = float(input("Enter salary increase rate: "))
year = int(input("Enter years of service: "))
checkYear(year)
print("\n%10s %20s %25s %18s" % ("Year", "Starting salary", "Salary increase rate", "Ending salary"))
for i in range(1, year+1):
endSalary = salary + (salary * rate/100)
print("%9s %18s %17s %26s" % (i, "$ " + str(round(salary, 1)), str(round(rate))+"%", "$ " + str(round(endSalary, 1))))
salary = endSalary
# Result here:
# Enter starting salary: $ 2000
# Enter salary increase rate: 3
# Enter years of service: 5
#
# Year Starting salary Salary increase rate Ending salary
# 1 $ 2000.0 3% $ 2060.0
# 2 $ 2060.0 3% $ 2121.8
# 3 $ 2121.8 3% $ 2185.5
# 4 $ 2185.5 3% $ 2251.0
# 5 $ 2251.0 3% $ 2318.5 | true |
9ddbfa493304a945a607310e245ba8265ebd8a26 | AAM77/Daily_Code_Challenges | /codewars/6_kyu/python3/who_likes_it.py | 2,339 | 4.28125 | 4 | # Name: Who Likes It
# Source: CodeWars
# Difficulty: 6 kyu
#
# URL: https://www.codewars.com/kata/who-likes-it/train/ruby
#
#
# Attempted by:
# 1. Adeel - 03/06/2019
#
#
##################
# #
# Instructions #
# #
##################
#
#
# You probably know the "like" system from Facebook and other pages. People can
# "like" blog posts, pictures or other items. We want to create the text that
# should be displayed next to such an item.
#
# Implement a function likes :: [String] -> String, which must take in input
# array, containing the names of people who like an item. It must return the
# display text as shown in the examples:
#
# likes [] // must be "no one likes this"
# likes ["Peter"] // must be "Peter likes this"
# likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
# likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
# likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
# For 4 or more names, the number in and 2 others simply increases.
#################
# PseudoCode: #
#################
# Five scenarios:
# (1) Empty => no one likes this
# (2) One => 1 likes this
# (3) Two => 0 & 1 like this
# (4) Three => 0, 1 & 2 like this
# (5) Four => 0, 1, & # others like this
# if empty:
# return 'no one likes this'
# elsif length == 1:
# return 'name1 likes this'
# elsif length == 2:
# return 'name1 and name2 like this'
# elsif length == 3:
# return 'name1, name2, and name3 like this'
# else:
# return 'name1, name2, & remaining # others like this'
# end
####################
# PYTHON SOLUTIONS #
####################
#*******************#
# Adeel’s Attempt 1 #
#*******************#
# This is the attempt I made after the session
def likes(names):
if len(names) == 0:
return 'no one likes this'
elif len(names) == 1:
return "{names[0]} likes this".format(names=names)
elif len(names) == 2:
return "{names[0]} and {names[1]} like this".format(names=names)
elif len(names) == 3:
return "{names[0]}, {names[1]} and {names[2]} like this".format(names=names)
else:
return "{names[0]}, {names[1]} and {remaining} others like this".format(names=names, remaining = len(names)-2)
| true |
fca476b8dd0f39eacd82ee137010acc742dfb1c3 | keshopan-uoit/CSCI2072U | /Assignment One/steffensen.py | 1,470 | 4.28125 | 4 | # Keshopan Arunthavachelvan
# 100694939
# January 21, 2020
# Assignment One Part Two
def steffensen(f, df, x, epsilon, iterations):
'''
Description: Calculates solution of iterations using Newton's method with using recursion
Parameters
f: function that is being used for iteration (residual)
df: derivative of the function f
x: initial point
epsilon: lower bound for when the iteration should terminate (estimated error)
iterations: maximum number of iterations
'''
# Iterates through the Steffensen's iteration
for i in range(0, iterations):
# Variable Instantiation
y1 = x
# Performs Newton's step and stores values
y2 = x - float(f(y1))/float(df(y1))
y3 = x - float(f(y2))/float(df(y2))
# Using the previously saves values from Newton's Steps, perform an iteration with Steffensen's iterations
x = y1 - ((y2 - y1) ** 2 / (y3 - (2 * y2) + y1))
# If current solution is less than the estimated error or residual, then print converged and break the loop
print('The solution at the ' + str(i) + 'th iteration is ' + str(f(x)) + '.')
if (f(x) < epsilon):
print "Converged"
return x
# If current iteration exceeds maximum number of iterations, print the current solution and return null
print('Next iteration exceeds maximum number of iterations. Current solution is ' + str(f(x)) + ". \nDoes not Converge.")
return None
| true |
eae0607b690abe39fd59214c1d018ac0ddc24d13 | fhorrobin/CSCA20 | /triangle.py | 290 | 4.125 | 4 | def triangle_area(base, height):
"""(number, number) -> float
This function takes in two numbers for the base and height of a
triangle and returns the area.
REQ: base, height >= 0
>>> triangle_area(10, 2)
10.0
"""
return float(base * height * 0.5)
| true |
42467a9b02e36935f5c34815dc53081841a156fb | tsung0116/modenPython | /program02-input.py | 479 | 4.125 | 4 | user_name = input("Enter your name:")
print("Hello, {name}".format(name=user_name))
principal = input("Enter Loan Amount:")
principal = float(principal)
interest = 12.99
periods = 4
n_years = 2
final_cost = principal * (1+interest/100.0/periods)**n_years
print(final_cost)
print("{cost:0.02f}".format(cost=final_cost))
print("Total Interest Paid: {interest:0.02f}".format(interest=final_cost-principal))
print("Monthly Payments: {payment:0.02f}".format(payment=final_cost/24)) | true |
0e034002296b0cf3d7c0486907d571802341606d | DanaAbbadi/data-structures-and-algorithms-python | /data_structures_and_algorithms/stacks_and_queues_challenges/stacks.py | 1,922 | 4.28125 | 4 | from data_structures_and_algorithms.stacks_and_queues_challenges.node import Node
# from node import Node
class Stack(Node):
def __init__(self):
self.top = None
def push(self, *args):
"""
Takes a single or multiple values as an argument and adds the new nodes with that value to the front of the stack.
Arguments:
*args -- list of values with variable length
"""
for i in args:
new_node = Node(i)
temp = self.top
self.top = new_node
new_node.next = temp
def pop(self):
"""
* Removes the node from the front of the queue, and returns the node’s value.
* Will raise an exception if the queue is empty.
"""
try:
value = self.top.value
self.top = self.top.next
return value
except AttributeError as error:
return 'Stack is empty'
def peek(self):
"""
* Returns the value of the node located in the front of the queue, without removing it from the queue.
* Will raise an exception if the queue is empty
"""
try:
return self.top.value
except AttributeError as error:
return 'Stack is empty'
def isEmpty(self):
"""
Checks whether or not the Queue is empty.
"""
return False if self.top else True
def __str__(self):
current = self.top
output = 'top->'
while current:
output += f"{current.value}->"
current = current.next
output+=" NULL"
return output
if __name__ == "__main__":
adjectives = Stack()
adjectives.push('smart','unique')
adjectives.push('fluffy')
print(adjectives)
print(adjectives.pop())
print(adjectives.peek())
print(adjectives.isEmpty())
| true |
ddb6bb1bc35904275e44ba87e46cf1efe7983c0f | DanaAbbadi/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/binary_tree/breadth_first.py | 1,541 | 4.1875 | 4 | class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
"""
This class is responsible of creating and traversing the Binary Search Tree.
"""
def __init__(self):
self.root = None
def breadth_first(self, root):
"""
Traverse the tree using Breadth First approach where the Node Values at each level
of the Tree are traversed before going to next level.
"""
try:
queue = []
breadth = []
if not root:
return 'Tree is empty'
else:
if root:
queue.append(root)
while queue:
current = queue.pop(0)
breadth.append(current.value)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return breadth
except Exception as e:
return f'An error occured, {e}'
if __name__ == "__main__":
bt = BinaryTree()
bt.root = Node(2)
bt.root.left = Node(7)
bt.root.right = Node(5)
bt.root.left.left = Node(2)
bt.root.left.right = Node(6)
bt.root.left.right.left = Node(5)
bt.root.left.right.right = Node(11)
bt.root.right.right = Node(9)
bt.root.right.right.left = Node(4)
# 2 7 5 2 6 9 5 11 4
print(bt.breadth_first(bt.root))
| true |
30b58144b16e936bea70ff6d1bb79c56db04947c | avikchandra/python | /Python Assignment/centredAverage.py | 574 | 4.28125 | 4 | #!/usr/bin/env python3
'''
"centered" average of an array of integers
'''
# Declare the list
num_list=[-10, -4, -2, -4, -2, 0]
# Find length
list_len=len(num_list)
# Check if length is odd or even
if list_len%2 == 0:
# For even length, find average of two centred numbers
mean_result=(num_list[list_len//2 -1] + num_list[list_len//2]) // 2
else:
# For odd length, find the centred number
mean_result=num_list[list_len//2]
# Print value
print("The given list is: \n", num_list)
print("Centered mean value is: ", mean_result)
| true |
8d812c5251edda45c2a531b9bf28ed4b138e233c | avikchandra/python | /Python Assignment/wordOccurence.py | 1,459 | 4.125 | 4 | #!/usr/bin/env python3
'''
highest occurences of words in file "sample.txt"
'''
def main():
# Declare dict
word_dict={}
punct_list=[',','.','\'',':','?','-'] # list of punctuations
# Create file object from file
file_obj=open("sample.txt", 'r')
word_list=[]
# Read line from file object
for line in file_obj:
# Strip the punctuations from line
for punct in punct_list:
line=line.replace(punct,'')
# Get words from line
for word in line.split():
# Append to list
word_list.append(word.lower())
word_dict=updateDict(word_list, word_dict)
print("Top five word occurences: ")
for num in range(5):
print(findHighest(word_dict))
# Close the file
file_obj.close()
def updateDict(word_list, word_dict):
# Update dictionary with word count
for word in word_list: word_dict[word]=word_list.count(word)
return word_dict
def findHighest(word_dict):
# Check for occurences from dictionary
highest_num=0
for entry in word_dict:
curr_count=int(word_dict[entry])
if curr_count > highest_num:
highest_num=curr_count
highest_word=entry
# Remove the word from dict
word_dict.pop(highest_word)
# Return the highest occurence
return (highest_word, highest_num)
if __name__ == '__main__': main()
| true |
fbb14a7e554803b8d3e42998a545bd399ab9c795 | avikchandra/python | /Python Advanced/sentenceReverse.py | 303 | 4.4375 | 4 | #!/usr/bin/env python3
'''
Reverse words in sentence
'''
# Take input from user
orig_string=input("Enter the string: ")
str_list=orig_string.split()
# Option1
#str_list.reverse()
#print(' '.join(str_list))
# Option2
reversed_list=list(str_list[::-1])
print(' '.join(reversed_list))
| true |
ee1aeab37fc4b91f7f8f65b50aba287b8e9c1801 | Joldiazch/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 460 | 4.375 | 4 | #!/usr/bin/python3
class Square:
"""class Square that defines a square by: (based on 0-square.py)
Attributes:
size_of_square (int): Description of `attr1`.
"""
def __init__(self, size_of_square=0):
if type(size_of_square) is not int:
raise TypeError('size must be an integer')
elif size_of_square < 0:
raise ValueError('size must be >= 0')
else:
self.__size = size_of_square
| true |
54c574df0d191bcd3e68f076859588c74827b1ef | beckam25/ComputerScience1 | /selectionsort.py | 2,652 | 4.375 | 4 | """
file: selectionsort.py
language: python3
author: bre5933@rit.edu Brian R Eckam
description:
This program takes a list of numbers from a file and
sorts the list without creating a new list.
Answers to questions:
1) Insertion sort works better than selection sort in a case where you have
a very long list that you wish to be sorted.
2)Selection sort is worse in this case because it would search the list for
the lowest(or highest) index remaining in the list THEN put it at the end of
the sorted list.
Insertion sort would take the next unsorted index and insert it where it belonged in
the sorted part of the list.
"""
def swap(lst, x, y):
"""
Swap two indexes in a list
:param lst: The list to be swapped in
:param x: first index to swap
:param y: second index to swap
:return: list with x and y swapped
"""
temporary = lst[x]
lst[x] = lst[y]
lst[y] = temporary
def find_min(lst):
"""
Find the minimum index in a list
:param lst: THe list to look in
:return: the minimum in the list
"""
if len(lst) > 0:
minimum = lst[0]
for index in range(1, len(lst)):
if lst[index] < minimum:
minimum = lst[index]
return minimum
def search_in_list(lst, number):
"""
Finding the index of a number. In this case the minimum.
:param lst: The list to look in.
:param number: The number to look for.
:return: The index where the number is located in the list
"""
for index in range(len(lst)):
if number == lst[index]:
return index
return None
def selection_sort(lst):
"""
Sorting function that will sort integers in a list
from lowest to highest
:param lst: The list to be sorted
:return: A sorted version of the list from low to high
"""
x = 0
while x < len(lst):
minimum = find_min(lst[x:])
found = search_in_list(lst[x:], minimum) + x # add x to account for all indexes before the slice
swap(lst, found, x)
x = x + 1
print("The sorted list:")
print(lst)
def main():
"""
The main function which imports a user input list
and sends that list to the sorting function.
:return: The sorted list
"""
filename = input("filename: ")
text = open(filename)
lst = []
count = 0
for line in text:
lst = lst + line.split()
new_lst = []
for char in lst:
new_lst.append(char)
print("The original list:")
print(new_lst)
selection_sort(new_lst)
main()
| true |
079ac76649cfff4b61345dd077e68178de0ffc52 | joseluismendozal10/test | /DATA ANALYTICS BOOTCAMP/June 19/Python/2/quick check up .py | 266 | 4.125 | 4 | print("Hello user")
name = input("what is your name?")
print ("Hello" + name)
age = int(input("whats your age?"))
if age >= 21:
print("Ah, a well traveled soul you are ye")
else:
print("aww.. you're just a baby!")
| true |
25f5ba74734da7afb773999499cca4c79685c717 | r0hansharma/pYth0n | /prime number.py | 319 | 4.125 | 4 | no=int(input('enter the no to check\n'))
if(no>1):
for i in range(2 , no):
if(no%i==0): print(no,'is not a prime number')
else:
print( no,"is a prime number")
elif(no==1):
print("1 is neither a prime nor a compposite number")
else:
print("enter a number greater than 1") | true |
27908d6450779964609a859a83c29decd4e67d3e | bnsh/coursera-IoT | /class5/week4/leddimmer.py | 605 | 4.25 | 4 | #! /usr/bin/env python3
"""This is week 4 of the Coursera Interfacing with the Raspberry Pi class.
It simply dims/brightens the LED that I've attached at pin 12 back and forth."""
import math
import time
import RPi.GPIO as GPIO
def main():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
pwm = GPIO.PWM(12, 50)
pwm.start(0)
# So, let's make a sine wave.
try:
while True:
for theta in range(0, 360):
rate = 100.0 * (1.0 + math.sin(theta * math.pi / 180.0)) / 2.0
pwm.ChangeDutyCycle(rate)
time.sleep(2.0/360.0)
finally:
GPIO.cleanup()
if __name__ == "__main__":
main()
| true |
e2fda25298068dda88406226945b707a7514a200 | JesNatTer/python_fibonacci | /fibonacci.py | 464 | 4.1875 | 4 | numbers = 20 # amount of numbers to be displayed
def fibonacci(n): # function for fibonacci sequence
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) # function formula for fibonacci
if numbers <= 0:
print("Please enter positive value") # amount of numbers cannot be less than 1
else:
for i in range(numbers): # amount of numbers is 1 or more, so sequence is printed
print(fibonacci(i), end= " ")
| true |
15cfa3ed4506417d5eb879b43e1ac0a6f3d9b5bc | Moiseser/pythontutorial | /ex15.py | 719 | 4.375 | 4 | #This allows your script to ask you on the terminal for an input
from sys import argv
#this command asks you what the name of your text file you want to read is
script,filename = argv
#this opens the file and then assigns the opened file to a variable
txt = open(filename)
#here we print the name of the file
print 'Heres your file %s' % filename
#here the contents of the file are printed onto the terminal
print txt.read()
#text is printed on the terminal
print 'Type the filename again'
#here we again manually input into script whht the name of the of the file is
file_again = raw_input('>')
#the opened file again is assigned to this variable
txt_again = open(file_again)
#contents printed
print txt_again.read()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.