blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4e1822d57930a2cad40f1dd08c99569233bbcd69 | dfeusse/2018_practice | /dailyPython/06_june/17_reverseWords.py | 911 | 4.5 | 4 | '''
Reverse words
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
'''
def reverse_words(text):
# break up each word to preserve order into list
words = text.split()
# reverse the word
wordsReversed = [ i[::-1] for i in words ]
# list to sentence
finalSentence = ""
for i in wordsReversed:
finalSentence += i + " "
return " ".join(wordsReversed)
return finalSentence
print reverse_words('The quick brown fox jumps over the lazy dog.')#, 'ehT kciuq nworb xof spmuj revo eht yzal .god')
print reverse_words('apple')#, 'elppa')
print reverse_words('a b c d')#, 'a b c d')
print reverse_words('double spaced words')#, 'elbuod decaps sdrow')
'''
return ' '.join([ i[::-1] for i in str.split(' ') ])
''' | false |
cdc560c33d0d9ef2dd9c210dca683d35c0b27004 | dfeusse/2018_practice | /dailyPython/07_july/05_vowelCount.py | 442 | 4.1875 | 4 | '''
Vowel Count
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.
'''
def getCount(inputStr):
vowels = list('aeiou')
num_vowels = 0
for i in inputStr:
if i in vowels:
num_vowels+=1
#return num_vowels
return sum([1 for i in inputStr if i in list('aeiou')])
print getCount("abracadabra")#, 5) | true |
67ec226662c56c93fe5f0176cfb1380003385afc | amruth153/Python-projects | /K means/Assignment_2.py | 2,943 | 4.1875 | 4 | #Name: Amruth Kanakaraj
#Student ID: 201547293
""" Implement a simplified version of k-means algorithm using Python to
cluster a toy dataset comprising five data points into two clusters.
More specifically, consider the following dataset comprising five data points (2-dimensional)
{(0; 0); (1; 0); (1; 1); (0; 1); (-1; 0)} """
#Importing math library to use sqrt for ease of programming.
from math import sqrt
#defining mean separately to keep one common loop for both centroids.
def mean(clusterpoints):
#defining size variable to find length of the list so average can be found.
size = len(clusterpoints)
xsum = 0
ysum = 0
for point in clusterpoints:
xsum += point[0]
ysum += point[1]
#average or finding mean
xmean = xsum/size
ymean = ysum/size
return [xmean,ymean]
#main fucntion program
def main():
#Given data points as input. Note that I used lists despite fixed data as lists are mutable.
dataPoints= [[0,0],[1,0],[1,1],[0,1],[-1,0]]
print("Given datapoints are:", dataPoints,"\n")
#Defined centroid one as c1 & centroid two as c2.
c1 = [1,0]
c2 = [1,1]
print("Initial position of the centroid c1:", c1,"\n")
print("Initial position of the centroid c2:", c2,"\n")
#set up an iteration lable to show the number of iterations
#a for loop for the 2 iterations
for i in range(0,2):
#empty lists to be filled or appended later by the program.
c1DistanceList = []
c2DistanceList = []
#for loop to compute the distance "d" from c1 and c2,.
for point in dataPoints:
#setting values for x1,y1 & x2,y2
x1,y1 = point
x2,y2 = c1
#computing the distance with the below formula
c1topointdist = sqrt(((x2-x1)**2)+((y2-y1)**2))
#appending the distance calculated
c1DistanceList.append(c1topointdist)
x2,y2 = c2
c2topointdist = sqrt(((x2-x1)**2)+((y2-y1)**2))
c2DistanceList.append(c2topointdist)
#creating a list to store the cluster points close to the nearest centroids
c1Cluster = []
c2Cluster = []
#for loop to append points to the list
for j , d1 , d2 in zip(range(len(dataPoints)),c1DistanceList,c2DistanceList):
if d1 <= d2:
c1Cluster.append(dataPoints[j])
else:
c2Cluster.append(dataPoints[j])
#taking the mean of both centroids and checking if the value is same after each iteration.
c1 = mean(c1Cluster)
c2 = mean(c2Cluster)
#printing the iterations
print("Iteration : ", i+1,"\n")
print("The updated centroid c1 is : ", c1, "\n")
print("The updated centroid c2 is : ", c2 ,"\n")
print("\n")
#calling main function
main() | true |
be4cc1e7a6f9843f2da95734093f510fa6d7ee67 | Samuel-Trujillo/rock_paper_scissors | /index.py | 1,063 | 4.3125 | 4 | import random
comp_options= ["rock", "paper", "scissors"]
your_score=0
cpu_score=0
while your_score or cpu_score < 3:
choice= input(" BEST OF FIVE! rock, paper, scissors: ")
comp_choice= random.choice(comp_options)
print(f"CPU CHOSE {comp_choice}")
if choice == comp_choice:
print("TIE!!!")
elif choice == "rock":
if comp_choice== "scissors":
your_score += 1
print("WINNER!!")
else:
cpu_score += 1
print("LOSER!!")
elif choice == "paper":
if comp_choice== "rock":
your_score += 1
print("WINNER!!")
else:
cpu_score += 1
print("LOSER!!")
elif choice == "scissors":
if comp_choice== "paper":
print("WINNER!!")
your_score += 1
else:
cpu_score +=1
print("LOSER!!")
print(cpu_score)
print(your_score)
if cpu_score == 3:
print("YOU LOSE")
break
if your_score == 3:
print("YOU WIN")
break
| false |
6a71e7762b77de162b2a868178c2b003c459529c | bhuvan21/C2Renderer | /Vector3.py | 2,825 | 4.25 | 4 | '''Contains the Vector3 Class, a helper class for working with vectors with 3 components'''
from math import sqrt
# the Vector3 class can be initialised with 3 separate values, or an array of 3 values
class Vector3():
def __init__(self, a=0, b=0, c=0, full=[0, 0, 0]):
if full == [0, 0, 0]:
self.values = [a, b, c]
else:
self.values = full
# the syntax for dot product with this class is (a*b).product, simply because the syntax read aloud is 'dot product'
self.product = self.values[0]+self.values[1]+self.values[2]
self.length = sqrt((self.values[0]**2) + (self.values[1]**2) + (self.values[2]**2))
# returns a normalized version of the vector
def normalized(self):
scale_factor = 1.0/self.length
return scale_factor*self
# returns the cross product of this vector with another
def cross(self, other):
cx = (self.values[1]*other.values[2]) - (self.values[2]*other.values[1])
cy = (self.values[2]*other.values[0]) - (self.values[0]*other.values[2])
cz = (self.values[0]*other.values[1]) - (self.values[1]*other.values[0])
return Vector3(cx, cy, cz)
# implementing basic addition and subtraction of instances of the Vector3 class
def __add__(self, other):
r = []
for i in range(3):
r.append(self.values[i]+other.values[i])
return Vector3(full=r)
def __sub__(self, other):
r = []
for i in range(3):
r.append(self.values[i]-other.values[i])
return Vector3(full=r)
# implements indexing of the Vector3 class
def __getitem__(self, key):
return self.values[key]
# makes Vector3 classes iterable
def __iter__(self):
return iter(self.values)
def __mul__(self, other):
# this is technically not a proper operation, but in conjunction with '.product' it has the desired effect
if type(other) == Vector3:
r = []
for i in range(3):
r.append(self.values[i]*other.values[i])
return Vector3(full=r)
else:
# vector3 multiplication by a scalar
return Vector3(full=[other*y for y in self.values])
# same as __mul__ but reversed in order
def __rmul__(self, other):
if type(other) == Vector3:
r = []
for i in range(3):
r.append(self.values[i]*other.values[i])
return Vector3(full=r)
else:
return Vector3(full=[other*y for y in self.values])
# raising Vector3 instances to a power is now defined (this way)
def __pow__(self, other):
return Vector3(full=[other**y for y in self.values])
def __repr__(self):
return str(self.values) | true |
6ad069ca0e91a74bd5469a5b396594fa5e780944 | NRKEngineering/PythonScripts | /oddOrEven.py | 485 | 4.34375 | 4 | # Odd or Even
# This program asks the user for a number and
# determines if that number is odd or even
# get a number from the user
number = input("Please enter a number: ")
# See if even
if int(number) % 2 is 0:
print ("Number is even")
# If even is it divisable by four
if int(number) % 4 is 0:
print ("and is divsible by 4")
# See if odd
elif int(number) % 2 is not 0:
print ("Number is odd")
# Error check
else:
print ("Error")
| true |
b6824bdeb579a4eddf70f10033645ba89f83d0fb | MayKeziah/CSC110 | /inclasswk3.py | 747 | 4.53125 | 5 | #Keziah May
#04/17/18
#In class activity: Week 3
#Goal: prove understanding of splitting strings
def main():
#Explain the goal of the program
print("This program demonstrates splitting strings.\n")
#Assign string to variable "mystring".
mystring = 'This is a line.\n This is a separate line.'
print("Before: ")
print(mystring)
#Split variable mystring into two strings
mysplit = mystring.split(".\n ")
print("After: ")
print(mysplit)
#Assign new string to variable "mystring"
mystring = 'this_is_a_line.'
print("Before: ")
print(mystring)
#Split variable "mystring" into separate strings of words
mysplit = mystring.split("_")
print("After: ")
print(mysplit)
main()
| true |
ffad27d374046a8be3bb17f146ce3ec28b1049d3 | omrawal/Studbud-Prep | /Week 4/Stack Intermediate/q11.py | 1,639 | 4.15625 | 4 | # reverse a stack without using loops
# idea is store values in function calls untill stack is empty
# insert at bottom of stack
class Stack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
if(len(self.stack) == 0):
return None
else:
return self.stack.pop(-1)
def peek(self):
if(len(self.stack) == 0):
return None
else:
return self.stack[-1]
def isEmpty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
def __str__(self) -> str:
ans = '->'
for i in self.stack:
ans += ' '+str(i)
return ans
def addBotttom(self, val):
new_stack = []
while(len(self.stack) > 0):
new_stack.append(self.stack.pop(-1))
new_stack.append(val)
while(len(new_stack) > 0):
self.stack.append(new_stack.pop(-1))
return True
def insert(stack, ele):
if(stack.isEmpty()):
stack.push(ele)
# return stack
else:
temp = stack.peek()
stack.pop()
# stack = insert(stack, ele)
insert(stack, ele)
stack.push(temp)
# return stack
def reverse(stack):
if(stack.size() == 1):
# return stack
return
else:
temp = stack.peek()
stack.pop()
# stack = reverse(stack)
reverse(stack)
insert(stack, temp)
# return stack
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
print(s)
reverse(s)
print(s)
| true |
64dbc0adf1fcac24acf522c310bf119f158a5ffa | pm0n3s/Python | /python1/python/multiples_sum_average.py | 738 | 4.40625 | 4 | '''Multiples
Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for
loop and don't use a list to do this exercise.'''
for i in range (1, 1001):
if i % 2 == 1:
print i
'''Part II - Create another program that prints all the multiples of 5 from 5 to
1,000,000.'''
for i in range(5, 1000001):
if i % 5 == 0:
print i
'''Sum List
Create a program that prints the sum of all the values in the list:
a = [1, 2, 5, 10, 255, 3]'''
a = [1, 2, 5, 10, 255, 3]
x = 0
for i in a:
x += i
print x
'''Average List
Create a program that prints the average of the values in the list:
a = [1, 2, 5, 10, 255, 3]'''
a = [1, 2, 5, 10, 255, 3]
x = 0
for i in a:
x += i
x = float(x) / len(a)
print x | true |
7cfed039b88b8749a7b2cf8d2f9cdfa524cba6ae | D-e-v-i-k-a/python | /Conditionals 1.py | 450 | 4.25 | 4 | name = 'John Doe'
len_name= len (name)
print(len_name)
if len_name > 20:
print("Name {} is more than 20 chars long".format(name))
elif len_name > 15:
print("Name {} is more than 15 chars long".format(name))
elif len_name > 10:
print("Name {} is more than 10 chars long".format(name))
elif 8<=len_name <=10:
print("Name {} is 8, 9 or 10 chars long".format(name))
else:
print("Name {} is a short name".format(name)) | false |
39f69c37098906a7ac2697d666e6a908ef2b564d | adrianaroxana/hello-world | /hello_world.py | 399 | 4.125 | 4 |
def hello_world():
return "Hello, World!"
def hello(name):
if not name:
return "Hello, World!"
else:
return "Hello" + ", " + name + "!"
def print_hello(name):
if not name:
print(hello(""))
else:
print(hello(name))
name = input("What is your name?")
print(hello_world())
print(hello(name))
print(hello(""))
print_hello(name)
print_hello("")
| false |
afc303dcdc9540aa39bc4a81c8baa8759258a080 | rinaBorisova/GBHomework | /HW4.py | 969 | 4.25 | 4 | # Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
print('Программа ищет самую большую цифру в введенном числе')
n = int(input('Введите целое положительное число: '))
m = n % 10
n = n // 10
# Пока число n не будет меньше 10, будем делить это число.
# Остаток от деления записывать в переменные.
# Затем сравнить полученные значения
while n > 0:
if n % 10 > m:
m = n % 10
n = n // 10
print ('Самая большая цифра: ', m)
# Тут пришлось искать в интернете :( Но в решении разобралась | false |
6cdb0f55518aecfeb0834848796b14bcb7d1d49e | kajkap/Day_of_the_squirrel | /remember_number_game.py | 1,564 | 4.15625 | 4 | import random
import time
import os
def initial_print():
"""Function prints the game instruction."""
os.system('clear')
print("""
*** Remember telephone number!
Write it down in the same format (divided into 3-digits blocks)***
""")
def generate_number():
"""Function generates 9 random digits.
Return:
number (int): 9-digit number
"""
number = []
for i in range(3):
for i in range(3):
number.append(str(random.randint(0, 9)))
number.append(' ')
number = (''.join(number)).strip(' ')
print('telephone: ', number)
return number
def guessing():
"""Function asks user for typing remembered number.
Return:
guess (int): user's answer
"""
guess = input()
return guess
def check_answer(number, guess):
"""Function checks if the user's answer is correct.
Args:
number (int): generated number
guess (int): user's guess
Return:
won (bool): True if the user's answer is correct, False otherwise
"""
win = False
if guess != number:
print('Wrong answer. Try again')
time.sleep(2)
else:
print('Well done!')
time.sleep(2)
win = True
return win
def main():
guess = ''
number = '0'
while guess != number:
initial_print()
number = generate_number()
time.sleep(5)
initial_print()
guess = guessing()
win = check_answer(number, guess)
return win
if __name__ == '__main__':
main()
| true |
592993959bec9722c6273a79ed0bb989102e55b4 | vineetwani/PythonDevelopment | /ListAndSetBasics.py | 1,056 | 4.15625 | 4 | #Define a list, set
#Output of Function listBasics:
# <class 'list'>
# [['Punit', 79], ['Vineet', 66]]
# ['Punit', 'Vineet']
# [79, 66]
def listBasics():
#l1=list() Can define like this as well
l1=[]
print(type(l1))
l1.insert(0,["Vineet",66])
l1.insert(0,["Punit",79])
#l1=[["Vineet",66],["Punit",79]]
print(l1)
print([name for name,marks in l1])
print([marks for name,marks in l1])
#Output of Function setBasics:
# <class 'dict'>
# <class 'set'>
# <class 'set'>
# {44, 22}
def setBasics():
#Empty curly braces {} will make an empty dictionary in Python.
s={}
print(type(s))
s1={ 13 , 12 }
print(type(s1))
#To make a set without any elements, we use the set() function without any argument.
s2=set()
print(type(s2))
#Sets are mutable. However, since they are unordered, indexing has no meaning.
s2.add(22)
s2.add(44)
s2.add(22)
print(s2)
if __name__ == "__main__":
#listBasics()
setBasics() | true |
04dd3dd769902ca514f1685e0ef057776098dc44 | shyamdalsaniya/Python | /generator.py | 960 | 4.125 | 4 | def main():
for i in inclusive_range(0,25,3):
print(i,end=" ")
print(end="\n\n")
for i in inclusive_range1(25):
print(i,end=" ")
print(end="\n\n")
for i in inclusive_range1(5,25):
print(i,end=" ")
print(end="\n\n")
for i in inclusive_range1(5,25,2):
print(i,end=" ")
#yield is return value at between execution of program at calling function
def inclusive_range(start,stop,step):
i=start
while i <= stop:
yield i
i+=step
def inclusive_range1(*args):
num=len(args)
if num < 1:
raise TypeError("atleast on argument is required")
elif num == 1:
start=0;
stop=args[0];
step=1
elif num == 2:
start,stop=args
step=1
elif num == 3:
start,stop,step=args
else: raise TypeError("argument can't exceed 3.you gave {} ".format(num))
i=start
while i <= start:
yield i
i+=step
main() | false |
55b51dae6e3344553d0aa227a2d20710c00b49b4 | frontsidebus/automating-the-boring-stuff | /exercise2-13.py | 202 | 4.1875 | 4 | print('This is a for loop: ')
for number in range(1, 11):
print(int(number))
print('This is a while loop: ')
number = 1
while number <= 10:
print(int(number))
number = (number + 1) | true |
bb5af9c8070b4b6c3a97ae26e56ce7bb5a0a9e40 | jacindaz/data_structures | /other_practice/doubly_linked_list.py | 373 | 4.40625 | 4 | def reverse_doubly_linked_list(linked_list):
print('hi!')
# Traverse a linked list
# Remove duplicates from a linked list
# Get the kth to last element from a linked list
# Delete a node from a linked list
# Add two linked lists from left to right
# e.g. 1->2->3 + 8->7 => 321+78 = 399
# Add two linked lists from right to left
# e.g. 1->2->3 + 8->7 => 123+87 = 210
| true |
08609793a8c7c3b33c76f72e1899bce2fd0fd217 | arstepanyan/Notes | /programming/elements_prog_interview/10_heaps/1_merge_sorted_files.py | 1,138 | 4.3125 | 4 | '''
Write a program that takes as input a set of sorted sequences and computes the union of these sequences as a sorted sequence.
For example, if the input is [3, 5, 7], [0, 6], and [0, 6, 28], then the output is [0, 0, 3, 5, 6, 6, 7, 28].
'''
import heapq
def merge_sorted_arrays(sorted_lists):
min_heap = []
iters = [iter(x) for x in sorted_lists]
for i, el in enumerate(iters):
next_el = next(el, None)
if next_el is not None:
heapq.heappush(min_heap, [next_el, i])
result = []
while min_heap:
min_element, min_element_i = heapq.heappop(min_heap)
result.append(min_element)
next_el = next(iters[min_element_i], None)
if next_el is not None:
heapq.heappush(min_heap, [next_el, min_element_i])
return result
if __name__ == '__main__':
list1 = [1, 4, 5]
list2 = [2, 3, 6, 20]
list3 = [1, 2]
print(f'list1 ....... {list1}')
print(f'list1 ....... {list2}')
print(f'list1 ....... {list3}')
merged_lists = merge_sorted_arrays(sorted_lists = [list1, list2, list3])
print(f'merged .......... {merged_lists}') | true |
5d7eb4e1f78d56817c6fcbf896731e6b3989030d | arstepanyan/Notes | /programming/elements_prog_interview/5_arrays/9_enumerate_all_primes_to_n.py | 980 | 4.375 | 4 | """
Write a program that takes an integer argument and returns all the primes between 1 and that integer.
For example, if the input is 18, you should return [2,3,5,7,11,13,17].
A natural number is called a prime if it is bigger than 1 and has no divisors other than 1 and itself.
"""
# Time = O(n log log n) Explanation: The time to shift out the multiples of num is proportional to n/num,
# so the overall time complexity is O(n/2 + n/3 + n/5 + n/7 + n/11 + ...).
# It is not obvious but this sum asymptotically tends to (n log log n)
# Space = O(n)
def find_primes(n):
primes = []
is_prime = [False, False] + [True] * (n - 1)
for num in range(2, n + 1):
if is_prime[num]:
primes.append(num)
for i in range(num, n + 1, num):
is_prime[i] = False
return primes
if __name__ == "__main__":
print(find_primes(18))
print(find_primes(30))
| true |
632ce36a32bd89143ba0e061706eacecde9c980a | arstepanyan/Notes | /programming/elements_prog_interview/13_sorting/1_intersection_of_two_sorted_arrays.py | 1,767 | 4.1875 | 4 | # write a program which takes as input two sorted arrays, and returns a new array containing elements that are present
# in both of the input array. The input arrays may have duplicate entries, but the returned array should be free of duplicates.
# O(m + n) time complexity, as adding an element to a set is O(1)
def intersection(l1, l2):
"""
computes the intersection of l1 and l2
:param l1: List[int]
:param l2: List[int]
:return: set, intersection of l1 and l2
"""
p1, p2 = 0, 0
res = set()
while p1 < len(l1) and p2 < len(l2):
if l1[p1] < l2[p2]:
p1 += 1
elif l1[p1] == l2[p2]:
res.add(l1[p1])
p1 += 1
p2 += 1
else:
p2 += 1
return res
# O(m + n), from the book, faster than above
def intersect_two_sorted_arrays(A, B):
"""
Computes the intersection of A and B
:param A: List[int]
:param B: List[int]
:return: List[int], intersection of A and B
"""
i, j, intersection_A_B = 0, 0, []
while i < len(A) and j < len(B):
if A[i] == B[j]:
if i == 0 or A[i] != A[i - 1]:
intersection_A_B.append(A[i])
i, j = i + 1, j + 1
elif A[i] < B[j]:
i += 1
else:
j += 1
return intersection_A_B
if __name__ == "__main__":
import time
l1 = [2, 3, 3, 5, 5, 6, 7, 7, 8, 12, 100, 300, 301, 301, 400, 400, 410, 412, 423, 425]
l2 = [5, 5, 6, 8, 8, 9, 10, 10]
t0 = time.time()
print(intersection(l1, l2))
print(f'Intersection(l1, l2) ......... {time.time() - t0}')
t0 = time.time()
print(intersect_two_sorted_arrays(l1, l2))
print(f'Intersect_two_sorted_arrays(t1, t2) ...... {time.time() - t0}')
| true |
dd57df565e7e828a4aa7aa8c6b3d859830323b8c | nroovers/data-analysis-python-course | /hy-data-analysis-with-python-2020/part01-e13_reverse_dictionary/src/reverse_dictionary.py | 476 | 4.28125 | 4 | #!/usr/bin/env python3
def reverse_dictionary(d):
rev={}
for eng, finL in d.items():
for fin in finL:
if fin in rev:
rev[fin].append(eng)
else:
rev[fin]=[eng]
return rev
def main():
d = {'move': ['liikuttaa'], 'hide': ['piilottaa',
'salata'], 'six': ['kuusi'], 'fir': ['kuusi']}
print(reverse_dictionary(d))
if __name__ == "__main__":
main()
| false |
3f9b3c14560dea0a0e929c0886e3541896148abc | lyk2018-python/django-notlar | /DERSLER/GUN 1/reversed_dictionary.py | 218 | 4.28125 | 4 | #!usr/bin/env python
sozluk ={'elma': 'apple', 'muz': 'banana', 'uzum': 'grapes', 'havuc': 'carrot'}
print(sozluk)
reverse_sozluk = {i:j for j,i in sozluk.items()}
print(reverse_sozluk)
print(reverse_sozluk["apple"])
| false |
4209130d1740cdf09c074e03c825874767ed5b33 | Camski1/DPWP | /Intro to Python/main.py/main.py | 1,217 | 4.21875 | 4 | #comment
'''
doc string
'''
first_name = "Cameron"
last_name = "Kozinski"
#response = raw_input("Please enter your name. ")
#print response
birth_year = 1988
current_year = 2014
age = current_year - birth_year
#print "You are " + str(age) + " years old."
# int(var) to read as a number str(var) to read as string
'''
if age > 100:
print "You are doing great for your age!"
elif age > 30:
print "How old are you? 20?"
else:
print "You look like a teenager!"
'''
# pass will skip the line
characters = ["Bob", "Tom", "Jen"]
characters.append("Ray")
#print characters[0]
films = dict() #to create an "object"
films = {"Midnight in Paris":"Dali", "Waking Ned Devine":"Ireland"}
#print films["Midnight in Paris"]
'''
#while loop
i = 0
while i<=9:
#print "count is", i
#i = i + 1
#for loop
for i in range(0,10):
print "count is", i
i = i + 1
'''
#for each
for c in characters:
#print c
pass
#Function in py = def
def calc_area(h, w):
area = h * w
return area
a = calc_area(20, 40);
print a
weight = 200
height = 63
message = '''
<!DOCTYPE HTML>
<head>
</head>
<body>
{height}
</body>
</html>
'''
message = message.format(**locals())
print message
| false |
ae53c9325b923096e981af98f3a76c17dd9f9439 | mdolmen/daily_coding_problem | /029-rain-between-walls/solution.py | 1,129 | 4.34375 | 4 | #!/usr/bin/env python3
# You are given an array of non-negative integers that represents a
# two-dimensional elevation map where each element is unit-width wall and the
# integer is the height. Suppose it will rain and all spots between two walls get
# filled up.
#
# Compute how many units of water remain trapped on the map in O(N) time and O(1)
# space.
#
# For example, given the input [2, 1, 2], we can hold 1 unit of water in the
# middle.
#
# Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in
# the second, and 3 in the fourth index (we cannot hold 5 since it would run off
# to the left), so we can trap 8 units of water.
def count_water_units(walls):
units = 0
for i in range(1, len(walls)):
w1 = walls[i-1]
w2 = walls[i]
diff = w1 - w2
if diff > 0:
units += diff
walls[i] += diff
return units
walls = [2, 1, 2]
assert count_water_units(walls) == 1
walls = [3, 0, 1, 3, 0, 5]
assert count_water_units(walls) == 8
walls = [10, 3, 15, 2, 4, 9]
assert count_water_units(walls) == 37
print("[+] All tests done.")
| true |
3c5debecd8059514f58c29eda2a2778718f60b3b | fanying2015/code_learning_python | /Battleship.py | 1,862 | 4.3125 | 4 | # Battle Ship Game
""" In this project a simplified, one-player version of the classic board game Battleship will be built! In this version of the game, there will be a single ship hidden in a random location on a 5x5 grid. The player will have 4 guesses to try to sink the ship."""
# generate an empty board
from random import randint
board = []
for x in range(5):
row = []
for y in range(5):
row.append("X")
board.append(row)
# make the board look nice by removing quotation marks and linking 'X's with spaces
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
# let the machine generate the random location of the ship
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Let the gamer try four times to guess the location of the ship
for turn in range(4):
guess_row = int(raw_input("Enter a row number:")) #int changes String into Integer
guess_col = int(raw_input("Enter a column number:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
break # no need to continue the game; break from the for loop
else:
if guess_row not in range(5) or guess_col not in range(5): # situation: input the location outside the board
print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col] == "X": # situation: already guess that one
print "You guessed that one already."
else:
print "You missed my battleship!" # lose the game. Make an X mark on the guessed place
board[guess_row][guess_col] = "X"
print_board(board)
if turn == 3:
print "Game Over"
# print turn + 1 here
print "Turn", turn+1
| true |
afd166b6ab62403e018c4e5617026d531c1eeb74 | chao813/Leetcode-Practice | /345ReverseVowels.py | 603 | 4.25 | 4 | """Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y"."""
def reverseVowels(s):
vowel = ['a','e','i','o','u']
vowel_lst = []
index_lst = []
s = list(s)
for i in range(len(s)):
if s[i].lower() in vowel:
vowel_lst.append(s[i])
index_lst.append(i)
vowel_lst = vowel_lst[::-1]
for i,v in zip(index_lst,vowel_lst):
s[i] = v
return ''.join(s)
| true |
78b7a4a6051540ab5695902c76637180e7363859 | Wellington-Silva/Python | /Python-Exercicios-Basicos/PythonExercicios/Desafio033.py | 599 | 4.15625 | 4 | # Maior e Menor
# Faça um programa que leia 3 nº e mostre qual nº é maior e menor
n1 = int(input("Digite um número:"))
n2 = int(input("Digite um número:"))
n3 = int(input("Digite um número:"))
#Verificando quem é MENOR
if n1 < n2 and n1 < n3:
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
#Verificando quem é MAIOR
if n1 > n2 and n1 > n3:
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n1:
maior = n3
print("O menor valor digitado foi", menor)
print("O maior valor digitado foi", maior)
| false |
0d7db3a2a83a9cec8a3407b98b99f9b953778589 | prdmkumar7/PythonProjects | /rolling_dice.py | 656 | 4.53125 | 5 | #importing module for random number generation
import random
#range of the values of a dice
min_val = 1
max_val = 6
#to loop the rolling through user input
roll_again = "yes"
#loop
while roll_again == "yes" or roll_again == "y":
print("Rolling The Dices...")
print("The Value is :")
#generating and printing random integer from 1 to 6
number = random.randint(min_val, max_val)
print(number)
if number==6:
roll_again="yes"
continue
#asking user to roll the dice again. Any input other than yes or y will terminate the loop
roll_again = input("Roll the Dices Again? :") | true |
64b5c8a44c92b0c3ec02fa688a09c4c183438723 | nuwa0422/p2pu-python-101 | /02. Expressions/exercise-2.3.py | 285 | 4.1875 | 4 | # Exercise 2.3
#
# Write a program to prompt the user for hours and rate per hour to compute
# gross pay
#
# Enter Hours: 35
# Enter Rate: 2.75
# Pay: 96.25
#
hours = int(raw_input('Enter Hours: '))
rate = float(raw_input('Enter Rate: '))
pay = hours * rate
print 'Pay: ' + str(pay)
| true |
351e16b3026c0248060a8e98f5fb3c93a42cb777 | jcehowell1/learn_python | /ms_challenge_01.py | 994 | 4.40625 | 4 | # This program is to complete the first challenge for Create your first Python program
# the output will be similar to the following sample output:
# Today's date?
# Thursday
# Breakfast calories?
# 100
# Lunch calories?
# 200
# Dinner calories?
# 300
# Snack calories?
# 400
# Calorie content for Thursday: 1000
#Start
# this will ask the user what is today's date
print("What is today's date? ")
date_today = input()
# this will ask the user for the number of calories consumed for breakfast
print("Number of calories for breakfast? ")
breakfast_cal = int(input())
# this will ask the user for the number of calories consumed for breakfast
print("Number of calories for lunch? ")
lunch_cal = int(input())
# this will ask the user for the number of calories consumed for breakfast
print("Number of calories for dinner? ")
dinner_cal = int(input())
# sum the total calories
total_day = breakfast_cal + lunch_cal + dinner_cal
print("Calorie to total for " + date_today + ": " + str(total_day))
| true |
32683e32d25edcbf2eb5d559857dca9b8060e6cb | gouravkmar/codeWith-hacktoberfest | /python/Bunny_Prisoners_plates.py | 2,354 | 4.4375 | 4 | '''You need to pass a message to the bunny prisoners, but to avoid detection, the
code you agreed to use is... obscure, to say the least. The bunnies are given food on
standard-issue prison plates that are stamped with the numbers 0-9 for easier sorting,
and you need to combine sets of plates to create the numbers in the code. The signal
that a number is part of the code is that it is divisible by 3. You can do smaller
numbers like 15 and 45 easily, but bigger numbers like 144 and 414 are a little trickier.
Write a program to help yourself quickly create large numbers for use in the code,
given a limited number of plates to work with.
You have L, a list containing some digits (0 to 9). Write a function solution(L) which
finds the largest number that can be made from some or all of these digits and is
divisible by 3. If it is not possible to make such a number, return 0 as the solution.
L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times
in the list, but each element in the list may only be used once.
-- Test cases --
Input :
solution.solution([3, 1, 4, 1])
Output:
4311
Input:
solution.solution([3, 1, 4, 1, 5, 9])
Output:
94311
'''
l =[3,1,4,1]
def solution(l):
number=''
ans=''
l = sorted(l,reverse=True)
for i in l:
number +=str(i)
lis0= [x for x in l if x%3==0]
lis1= [x for x in l if x%3==1]
lis2= [x for x in l if x%3==2]
if int(number)%3==0:
return int(number)
elif int(number)%3!=0 and len(lis0)==0 and (len(lis1)==0 or len(lis2)==0):
return 0
elif int(number)%3==1:
if len(lis1)==0 and len(lis2)>=2:
lis2.pop()
lis2.pop()
else :
lis1.pop()
final_lis= lis0+lis1+lis1
# if len(final_lis==0):return 0
final_lis = sorted(final_lis,reverse=True)
for i in final_lis:
ans +=str(i)
return int(ans)
elif int(number)%3==2:
if len(lis2)==0 and len(lis1)>=2:
lis1.pop()
lis1.pop()
else:
lis2.pop()
final_lis= lis0+lis1+lis1
# if len(final_lis==0):return 0
final_lis = sorted(final_lis,reverse=True)
for i in final_lis:
ans +=str(i)
return int(ans)
print(solution(l))
| true |
430f471a548fc1f66baf3c99102b4df4395fdd41 | naveenkonam/my_projects | /areaofcircle.py | 333 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 10:38:26 2020
@author: konam
"""
import math
def area_cir(r):
return (math.pi*(r**2))
n = eval(input('Please enter the radius to claculate the area of circle: '))
A = area_cir(n)
print("The area of the cirle with radius {0} is {1}".format(n, A))
| true |
5b6241f28bec3bfa8407bb0770939d2348cf0227 | akniels/Data_Structures | /Project_2/Problem_4.py | 1,666 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 11:15:19 2020
@author: akniels1
"""
from time import time
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def get_users(self):
return self.users
def get_name(self):
return self.name
def is_user_in_group(user, group):
"""
Return True if user is in the group, False otherwise.
Args:
user(str): user name/id
group(class:Group): group to check user membership against
"""
# if group is not Group:
# return False
people = sorted(group.get_users())
if len(people) == 0:
return False
center = (len(people)-1)//2
if people[center] == user:
return True
elif people[center] < user:
return is_user_in_group(user, group[center+1:])
else:
return is_user_in_group(user, group[:center])
#Test Case 1 #
parent = Group("parent")
child = Group("child")
sub_child = Group("subchild")
sub_child_user = "sub_child_user"
sub_child.add_user(sub_child_user)
child.add_group(sub_child)
parent.add_group(child)
print(is_user_in_group("sub_child_user", sub_child))
# Test Case 2 #
computer = Group("subchild")
computer_1_user = "computer1_user"
print(is_user_in_group("computer1_user", computer))
# Test Case 3 #
print(is_user_in_group("", computer))
| true |
3be7933c6114435c0357da694ddade72663cd26f | akniels/Data_Structures | /Project_1/P0/Task1.py | 1,052 | 4.125 | 4 | #!/usr/bin/env python3
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
tele_number = set()
for item in calls:
tele_number.add(item[0])
tele_number.add(item[1])
for item in texts:
tele_number.add(item[0])
tele_number.add(item[1])
#print(len(calls))
#print(len(texts))
print(f"There are {len(tele_number)} different telephone numbers in the records.")
"""
Big O Notation Worst Case Scenario
O(1 + 2n + 2x)
2 is for the set created tele_number
2n and 2x is for the for loops based on the length of calls and texts
I could make this more efficient by reading each
row once instead of twice and then checking if it is in the list.
""" | true |
a45f4b26afa16e28eb158b79b763290fd17636f2 | akniels/Data_Structures | /Project_1/P0/Task4.py | 2,089 | 4.25 | 4 | #!/usr/bin/env python3
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
incoming_text = []
outgoing_text = []
incoming_call = []
for text in texts:
if text[0] not in incoming_text:
incoming_text.append(text[0])
if text[1] not in outgoing_text:
outgoing_text.append(text[1])
for call in calls:
if call[1] not in incoming_call:
incoming_call.append(call[1])
master_list = set(incoming_text + outgoing_text + incoming_call)
spammers = set()
for call in calls:
if (call[0] not in master_list):
spammers.add(call[0])
print(f"These numbers could be telemarketers:",*sorted(spammers),sep='\n')
"""
Big O Notation Worst Case Scenario
O(5 + 1n^3 + 1x^2 + 1y^2+ x(log(x)))
5 represents the 5 valiables created in the algorithm (3 lists, two sets)
1n^3 represents the first for loop iterating over texts. This item is cubed because
one must check if the item is not in incoming text or outgoing text and the worse case is the item
as long as the CSV
the 1x^2 variables represent the loop iteration over calls. This item is squared because
the worst case scenario is the incoming call is just as long as the call csv
the 1y^2 variables represent the second loop iteration over calls. This item is squared because
the worst case scenario is the master list is just as long as the call csv
xlog(x) is for the sorting function in the print statement
""" | true |
ff3e08a2ef01b158bf2756cfa03d3c179e5686c2 | arshmohd/daily_coding_problem | /problems/49/problem_49.py | 624 | 4.15625 | 4 | def coding_problem_49(arr):
"""
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements
42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any
elements. Do this in O(N) time.
Examples:
>>> coding_problem_49([34, -50, 42, 14, -5, 86])
137
>>> coding_problem_49([-5, -1, -8, -9])
0
"""
pass
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| true |
db439e7a13dbee158a48e5534ee536afe79e2c9d | arshmohd/daily_coding_problem | /problems/44/solution_44.py | 1,137 | 4.15625 | 4 | def coding_problem_44(arr):
"""
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i]
and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
You may assume each element in the array is distinct.
Examples:
>>> coding_problem_44([1, 2, 3, 4, 5])
0
>>> coding_problem_44([2, 4, 1, 3, 5]) # inversions: (2, 1), (4, 1), (4, 3)
3
>>> coding_problem_44([5, 4, 3, 2, 1]) # every distinct pair forms an inversion
10
Note: complexity is that of sorting O(n log(n)) plus a linear pass O(n), therefore bounded by O(n log(n))
"""
sorted_indexes = sorted(range(len(arr)), key=lambda x: arr[x])
inversions = 0
while sorted_indexes:
inversions += sorted_indexes[0]
sorted_indexes = [si - 1 if si > sorted_indexes[0] else si for si in sorted_indexes[1:]]
return inversions
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| true |
2860771bdcd835f9a2f5ac7994cea2fa2413b030 | ronnynijimbere/python_basic_crashcourse | /loops.py | 695 | 4.21875 | 4 | # A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
people = ['simon', 'thomas', 'mike', 'suzan']
#simple loop
#for person in people:
# print(f'current person: {person}')
#break
#for person in people:
# if person == 'mike':
# break
# print(f'current person: {person}')
#continue
#for person in people:
# if person == 'mike':
# continue
# print(f'current person: {person}')
#range
#for i in range(len(people)):
# print(people[i])
#for i in range(0, 11):
# print(f'Number: {i}')
# While loops execute a set of statements as long as a condition is true.
count = 0
while count < 24:
print(f'Count: {count}')
count += 1 | false |
59a9f50b583e7381ead51af49389a6e9c43aa706 | alexmaclean23/Python-Learning-Track | /04-Floats/Floats.py | 611 | 4.15625 | 4 | # Declaration of a few floats
x = 7.0
y = 21.0
z = 45.0
# Basic math operations using floats
addInt = x + z
subtractInt = z - y
multiplyInt = x * y
divideInt = y / x
modInt = z % x
powerInt = y ** z
everythingInt = (y ** 7) / ((z + y) - (-(y * x)))
# Printing of the math calculations
print(addInt)
print(subtractInt)
print(multiplyInt)
print(divideInt)
print(modInt)
print(powerInt)
print(everythingInt)
print()
# Demonstration of decimal accuracy
result = 444 / 777
print(result)
# Formats variable with width of 1 and accuracy of 3 decimal places
print("The rounded result is{r: 1.3f}".format(r = result)) | true |
700acbeebbdeb5bf8961a1f2cfc6d928ec14a341 | alexmaclean23/Python-Learning-Track | /16-ForLoops/ForLoops.py | 478 | 4.25 | 4 | # Declaration of various data types
myList = [1, 2, 3, 4, 5]
myString = "Hello"
# For loop to print integers in list
for integers in myList:
print(integers)
print()
# For loop to print letters in String
for letters in myString:
print(letters)
print()
# For loop to print dash for each integer in list
for integers in myList:
print("-")
print()
# For loop to tally letters in String
numLetters = 0
for letters in myString:
numLetters += 1
print(numLetters) | true |
ba031a215ffc6315bfe9b79f81827a3269b9f7d3 | alexmaclean23/Python-Learning-Track | /17-WhileLoops/WhileLoops.py | 225 | 4.15625 | 4 | # Declaration if an integer variable
myNum = 0
# While loops that increment and prints nyNum up to 5
while (myNum <= 5):
print(f"myNum is currently {myNum}")
myNum += 1
else:
print("myNum is no longer in range.") | true |
04ab40e25129d568f6a2e322a18a8705d555d406 | alexmaclean23/Python-Learning-Track | /33-AdvancedModules/AdvancedModules.py | 1,673 | 4.125 | 4 | print()
print("####################################################")
print()
# Example of the counter module
from collections import Counter
myList = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4]
print(Counter(myList))
sentence = "this this sentence is is is iterable iterable"
words = sentence.split()
print(Counter(words))
myList = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4]
data = Counter(myList)
print(data.most_common(2))
print(sum(data.values()))
print()
print("####################################################")
print()
# Example of the defaultdict module
from collections import defaultdict
myDictionary = defaultdict(lambda: "NO VALUE")
myDictionary[0] = "zero"
myDictionary[2] = "two"
myDictionary[3] = "three"
print(myDictionary[0])
print(myDictionary[1])
print(myDictionary[2])
print(myDictionary[3])
print(myDictionary[4])
print()
print("####################################################")
print()
# Example of the ordereddict module
from collections import OrderedDict
myDictionary = OrderedDict()
myDictionary["a"] = 1
myDictionary["b"] = 2
myDictionary["c"] = 3
myDictionary["d"] = 4
myDictionary["e"] = 5
for k, v in myDictionary.items():
print(k, v)
d1 = OrderedDict()
d1["a"] = 1
d1["b"] = 2
d2 = OrderedDict()
d2["b"] = 2
d2["a"] = 1
print(d1 == d2)
print()
print("####################################################")
print()
# Example of the namedtuple module
from collections import namedtuple
Cat = namedtuple("Cat", "name age weight")
myCat = Cat(name = "Harley", age = 14, weight = 10)
print(myCat.name)
print(myCat.age)
print(myCat.weight)
print()
print("####################################################")
print() | true |
56afd756823502a2da59ae4442f64742a283b893 | cdelprato0/Long-Beach | /CECS 424 - Programming Lauguages/main.py | 1,109 | 4.25 | 4 | # sorts the numbers list with built in sort
numbers = [645.32, 37.40, 76.30, 5.40, -34.23, 1.11, -34.94, 23.37, 635.46, -876.22, 467.73, 62.26]
numbers.sort()
print(*numbers, "\n")
#creates a person class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return str(self.name) + "\t" + str(self.age) + "\n"
# creates a list of people
people = [Person("Hal", 20), Person("Susann", 31),
Person("Dwight", 19), Person("Kassandra", 21),
Person("Lawrence", 25), Person("Cindy", 22),
Person("Cory", 27), Person("Mac", 19),
Person("Romana", 27), Person("Doretha", 32),
Person("Danna", 20), Person("Zara", 23),
Person("Rosalyn", 26), Person("Risa", 24),
Person("Benny", 28), Person("Juan", 33),
Person ("Natalie", 25)]
# sorts the people by their name
people.sort(key = lambda Person: Person.name)
print(*people, "\n")
# sorts the people by their age and reverses the order to show decending
people.sort(key = lambda Person: Person.age, reverse=True)
print(*people, "\n") | false |
6454417ab910b4d68c4f237607f227c027284126 | gfomichev/Coffee-Machine | /Problems/Calculator/task.py | 555 | 4.15625 | 4 | # put your python code here
first = float(input())
second = float(input())
operation = input()
if operation == "+":
print(first + second)
elif operation == "-":
print(first - second)
elif operation == "/":
print(first / second if second != 0 else "Division by 0!")
elif operation == "*":
print(first * second)
elif operation == "mod":
print(first % second if second != 0 else "Division by 0!")
elif operation == "pow":
print(first ** second)
elif operation == "div":
print(first // second if second != 0 else "Division by 0!")
| false |
f84b3855120007e952476bb535e16921c9ff2104 | abulho/Python_Coding_Practice | /max_profit.py | 1,323 | 4.25 | 4 | '''
Suppose we could access yesterday's stock prices as a list, where:
The indices are the time in minutes past trade opening time, which was 9:30am local time.
The values are the price in dollars of Apple stock at that time.
So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500.
Write an efficient function that takes stock_prices_yesterday and returns the best profit
I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
get_max_profit(stock_prices_yesterday)
# Returns 6 (buying for $5 and selling for $11)
'''
def max_profit(stock_prices):
'''
function that takes stock_prices_yesterday and returns the best profit
I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.
Parameters
----------
stock_prices : list of stock stock_prices
Returns
-------
Best profit that could have been for the given day
'''
min_price = stock_prices[0]
final_profit = 0
for price in stock_prices:
min_price = min(min_price, price)
profit = price - min_price
final_profit = max(final_profit, profit)
return final_profit
if __name__ == '__main__':
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
print(max_profit(stock_prices_yesterday))
| true |
d68757f8517c27a7fa0bd9bb03c68517a251c63c | zarim/Caesar-Cipher | /P1216.py | 2,614 | 4.125 | 4 | #Zari McFadden = 1/27/17
#P1216 - Caesar Cipher
#Write a program that prompts a user for a string and an encryption key.
#The encryption key is the cipher shift amount. Your program will function as
#both an Caesar Cipher encrypter and decrypter.
def main(): #define main
A = [] #create an empty list for A
A1 = [] #create an empty list for A1
S = []
for letter in range(65, 91): #append the letters to A
A.append(chr(letter))
e = int(input("Enter an encryption key: ")) #user enters encryption key
s = input("Enter a string: ") #user enters a string
s1 = s.upper() #uppercase letters in string
if e < 0: #if encryption key is neg
for i in range(e, len(A)+e): #shift alphabet down
A1.append(A[i])
print(A1) #print shifted alphabet
A = ''.join(A) #turn A into a string
for char in s1: #search char in string
if char in A: #if char in A
y = A.find(char) #find index of char in A
S.append(A1[y]) #append new letter to S
else:
S.append(char) #append spaces/ other char
s2 = ''.join(S) #turn S into a string
else:
for i in range(e, len(A)): #if encrytion key is positive
A1.append(A[i]) #shift alphabet up
for x in range(e):
A1.append(A[x])
print(A1)
A = ''.join(A) #turn A into a string
for char in s1: #search char in string
if char in A: #if char in A
y = A.find(char) #find index of char in A
S.append(A1[y]) #append new letter to S
else:
S.append(char) #append spaces/ other char
s2 = ''.join(S) #turn S into a string
print(s2) #print new string
main() #call main
| true |
532e2c325f68a7701e16b091f4814f2ee4ab2819 | kongmingpuzi/python_classes_homework | /第二次上机作业/problem_2.py | 512 | 4.125 | 4 | name=input('Please input the account name')
passwprd='8'*8
for i in range(3):
if i==0:
input_passwprd=input('Please input the account passwprd')
else:
input_passwprd=input('The wrong password!\nPlease input the account passwprd again.')
if input_passwprd==passwprd:
print('You have successfully logined in and have a good time in Python world.')
break
if i==2:
print("You have inputted the wrong password three times and you can't input.") | true |
6fbbc3fae2250d7f1b64058da14f1776fe24c881 | SridharPy/MyPython | /SQL/SQLLite.py | 889 | 4.28125 | 4 | import sqlite3
# The connection sqlite3.connect : lite.db db file is created if it doesn't exist else will connect if exists
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Store (Item text, Quantity integer, Price real )")
conn.commit()
conn.close()
def insert_table(itm,qty,prc):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO Store VALUES (?,?,?)",(itm,qty,prc))
conn.commit()
conn.close()
def view_table():
con = sqlite3.connect("lite.db")
cur1 = con.cursor()
cur1.execute("Select * FROM store")
rows = cur1.fetchall()
con.close
return rows
print("Enter Item Name : ")
i = str(input())
print("\nEnter Quantity : ")
q = int(input())
print("\nEnter Price : ")
p = float(input())
insert_table(i,q,p)
print(view_table())
| true |
9fe89bc4d058c9c152ecd46e86b3dde08b9c7c85 | thecodesanctuary/python-study-group | /assessment/assessment_1/princess/4.py | 238 | 4.25 | 4 | #This program converts inputed weight from KG to Pounds
print("Conversion from Kilograms to Pounds\n \n")
KG=float(input("Enter the Weight in Kilograms: "))
Pound = round(float(KG*2.2),2)
print(f"\nThe Weight in Pounds is {Pound} lb") | true |
c0d161a5c277d6f68fdd118fa8a00a3ec9da19b2 | thecodesanctuary/python-study-group | /assessment/assessment_1/princess/1A.py | 258 | 4.25 | 4 | #This program converts temperature from Fahrehnheit to Celsius
print('Conversion from Fahrenheit to Celsius \n')
Fahrehn=int(input('Enter the temperature in Fahrehnheit: '))
Cel=round((Fahrehn-32)* 5/9, 2)
print('\n The temperature in Celsius is ', Cel) | true |
80c5b9239794b18991a07413cccdd52b069236d0 | SZTankWang/dataStructure_2020Spring | /recitation3/Recitation3 Python Files/binary_search.py | 2,288 | 4.15625 | 4 | import random
def binary_search_rec(x, sorted_list):
# this function uses binary search to determine whether an ordered array
# contains a specified value.
# return True if value x is in the list
# return False if value x is not in the list
# If you need, you can use a helper function.
# TO DO
low = 0
high = len(sorted_list)-1
if low == high:
if sorted_list[low] == x:
return True
else:
return False
if len(sorted_list) == 0:
return False
else:
mid_value = len(sorted_list) // 2
if sorted_list[mid_value] == x:
return True
elif sorted_list[mid_value] > x:
sorted_list = sorted_list[:mid_value]
return binary_search_rec(x,sorted_list)
elif sorted_list[mid_value] < x:
sorted_list = sorted_list[mid_value+1:]
return binary_search_rec(x,sorted_list)
def binary_search_iter(x, sorted_list):
# TO DO
# return True if value x is in the list
# return False if value x is not in the list
low = 0
high = len(sorted_list)-1
find = False
while low <= high and find == False:
mid_value = (low+high)//2
if sorted_list[mid_value] == x:
find = True
elif sorted_list[mid_value] > x:
high = mid_value-1
elif sorted_list[mid_value] < x:
low = mid_value +1
return find
def main():
sorted_list = []
for i in range(100):
sorted_list.append(random.randint(0, 100))
sorted_list.sort()
print("Testing recursive binary search ...")
for i in range(5):
value = random.randint(0, 100)
answer = binary_search_rec(value, sorted_list)
if (answer == True):
print("List contains value", value)
else:
print("List does not contain value", value)
print("Testing iterative binary search ...")
for i in range(5):
value = random.randint(0, 100)
answer = binary_search_iter(value, sorted_list)
if (answer == True):
print("List contains value", value)
else:
print("List does not contain value", value)
main()
| true |
f0286e3a80e564b81998480c8b2461d04ccde93c | SZTankWang/dataStructure_2020Spring | /recitation12/python files/union_intersection.py | 1,553 | 4.21875 | 4 | def union(l1, l2):
"""
:param l1: List[Int] -- the first python list
:param l2: List[Int] -- the second python list
Return a new python list of the union of l1 and l2.
Order of elements in the output list doesn’t matter.
Use python built in dictionary for this question.
return: union of l1 and l2, as a SingleLinkedList.
"""
# To do
dic = dict()
union = []
for i in l1:
if i not in dic:
dic[i] = 0
union.append(i)
for j in l2:
if dic.get(j) == None:
dic[j] = 0
union.append(j)
return union
def intersection(l1, l2):
"""
:param l1: List[Int] -- the first python list
:param l2: List[Int] -- the second python list
Return a new python list of the intersection of l1 and l2.
Order of elements in the output list doesn’t matter.
Use python built in dictionary for this question.
return: intersection of l1 and l2, as a SingleLinkedList.
"""
# To do
dic = dict()
inter = []
for i in l1:
if i not in dic:
dic[i] = 0
for j in l2:
if dic.get(j) != None:
inter.append(j)
return inter
def main():
l1 = [10, 15, 4, 20]
l2 = [8, 4, 2, 10]
print(union(l1, l2), "||||should contain [10,15,4,20,8,2], order doesn't matter.")
print(intersection(l1, l2), "||||should contain [4, 10], order doesn't matter.")
main()
| true |
648bc1fef43834198aa01b1c84e83120ac56d303 | raghukrishnamoorthy/Python-Cookbook | /02_Strings and Text/04_matching_and_searching_for_text_patterns.py | 662 | 4.28125 | 4 | text = 'yeah, but no, but yeah, but no, but yeah'
print(text == 'yeah')
print(text.startswith('yeah'))
print(text.endswith('no'))
print(text.find('no'))
# For complicated matching use regex
text1 = '11/27/2012'
text2 = 'Nov 27, 2012'
import re
if re.match(r'\d+/\d+/\d+', text1):
print('yes', text1)
else:
print('no')
# If you are going to perform a lot of matches then precompile
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(text):
print('yes', text)
else:
print('no', text)
# match always finds only start of string. use findall for all occurences
text = 'Today is 11/27/2012. PyCon starts 3/13/2013'
datepat.findall(text)
| true |
13f9b86121d4ed355faba46d67e885ac2ad811ce | cmullis-it/KatakanaPractice | /kataGUI.py | 1,473 | 4.125 | 4 | # GUI Practice for the application
import tkinter as tk
import kataPairs
#messing with Fonts
import tkinter.font as font
# Create the master window, and name "Kat.Pract."
master = tk.Tk()
master.title("Katakana Practice")
######
# Messing with Font Size
myFont = font.Font(size=30)
# Placeholders for the prompt/ correct answer that user
# input is being compared against.
promptKana = "マ"
promptQuestion = "Enter Romanji for this Kana"
answer = "ma"
# Answers for romanji the user is inputing
rightAns = "Correct!"
wrongAns = "Sorry, that was wrong"
# The Kana Label that will shift through the various Kana
lbl_KanaPrompt = tk.Label(
text=promptKana,
height=2,
)
lbl_KanaPrompt['font'] = myFont
lbl_KanaPrompt.pack()
# Constant prompt explaining instructions from App
lbl_QuestionPrompt = tk.Label(
text=promptQuestion
)
lbl_QuestionPrompt.pack()
# Entry box grabbing the input from the user.
inputFromUser = tk.Entry(master)
inputFromUser.pack()
################################################
def checkAnswer():
userInput = inputFromUser.get()
if userInput == answer:
lbl_FeedBack.config(text=rightAns)
else:
lbl_FeedBack.config(text=wrongAns)
################################################
# Creates button used to check answer
button = tk.Button(
text='Check Answer',
command=checkAnswer
)
button.pack()
# Creates label used to provide Right/Wrong Feedback
lbl_FeedBack = tk.Label(
)
lbl_FeedBack.pack()
master.mainloop()
| true |
e7a51b4c84405c51d0bc7799213b6ec912036c3d | afrokoder/skywaywok | /order_entry.py | 1,170 | 4.15625 | 4 | import time
import datetime
from menu import menu
from datetime import date
#Welcome Screen
print("Hello and welcome to SkyWay Wok!")
time.sleep(1)
print("\n\n")
print("Today's date and time: ", datetime.datetime.now())
time.sleep(1)
#Display list of available items
#menus = ["bread","toast","eggs","muffins"]
print ("Todays Menu: ", *menu.keys(), sep = "\n")
#List that holds the items being ordered by the customer
ordered = []
#defining the order entry process
def entree():
for item in range(0,3): #allows up to x amount of orders to be placed
item = input('enter your item: press q to quit: ') #takes in the customers order or Q to quit
item = item.lower()
#while item != 'q':
if item == "q":
break
if item in menu:
print(f"your order of {item} has been placed")
ordered.append(item)
elif item == '':
print("please enter a valid item")
else:
print("please try again")
break
return(ordered)
entree()
print('your order of', ordered, 'has been placed')
| true |
015a1da9b88778d9302acb4fbf69b60531d2d2c5 | mycodestiny/100-days-of-code | /Day 3/Projects/even or odd.py | 236 | 4.46875 | 4 | #the purpose of this project states determine whether or not a number is odd or even.
#while True
number = int(input("What is your number?\n"))
if number % 2 == 0:
print("This number is even")
else:
print("This number is odd")
| true |
23044c15636580b54c2ed945b49fa9d010baa4d7 | justincruz97/DataStructures-and-Algos | /LinkedLists/reverse_LL.py | 811 | 4.5 | 4 | from LinkedList import *
## reversing a linked list
def reverse_linked_list(L):
prev = None # this will be assigned as the new next
curr = L # this is the node we are reassigning next
next = None # this is the next node we wil work on
while (curr != None):
# store the next value
next = curr.next
# reassign current.next to previous (reverses)
curr.next = prev
# set previous to current to work on the next one
prev = curr
# assign curr to next to work on the next node
curr = next
return prev
LL = Node(1)
LL.next = Node(2)
LL.next.next = Node(3)
LL.next.next.next = Node(4)
reversedLL = reverse_linked_list(LL)
print(reversedLL)
print(reversedLL.next)
print(reversedLL.next.next)
print(reversedLL.next.next.next)
print(reversedLL.next.next.next.next)
| true |
9b1fe89b45bfb105171c935e6f60d42d70fe8b67 | justincruz97/DataStructures-and-Algos | /Sorting/selection_sort.py | 440 | 4.125 | 4 | # Selection sort, continuing finding small elements and adding it in order
def selection_sort(arr):
length = len(arr)
for index in range(0, length):
current_min = index
for index2 in range(index, length):
if (arr[index2] < arr[current_min]):
current_min = index2
temp = arr[current_min]
arr[current_min] = arr[index]
arr[index] = temp
return arr
print(selection_sort([10, 7, 1, 200, 30, 130])) | true |
f6dee9b41cdfd5557ce8720910d59e0ecc95b671 | osamafrougi/test | /scratch.py | 786 | 4.125 | 4 | mylist=["osama","ahmed","khlid"]
while True:
print("hi my name is travis ")
name=input("what is you name ?:")
if name in mylist:
print("hi {}".format(name))
remove=input("would you like to be removed from the sysytem (y/n)?:").strip().lower()
if remove =="y":
mylist.remove(name)
print("sorry to c you go")
print(mylist)
elif remove =="n":
print("thank you for syting with us ")
print(mylist)
else:
print("hummm id ont think i know you {}".format(name))
addme=input("would you like to be added to the sysyme (y/n)?:").strip().lower()
if addme =="y":
mylist.append(name)
elif addme =="n":
print("ok cy later ") | false |
9776b7314351aad593af7a8385d466a009d3484a | Madhav2108/udemy-python-as | /basic/ifgrater.py | 201 | 4.15625 | 4 | N=int(input("Enter Value of N: "))
if N%2==0 and N%5==0:
print("Yes")
else:
print("No")
N=int(input("Enter Value of N: "))
if N%2==0 or N%5==0:
print("Yes")
else:
print("No")
| false |
4cbfa3c511fd5f73407251373c9ab9d241e73379 | annamalo/py4e | /Exercises/ex_05_01/smallest.py | 422 | 4.1875 | 4 | smallest = None
print('Before:', smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest:
smallest = itervar
print('Loop:', itervar, smallest)
print('Smallest:', smallest)
def min(values):
smallest = None
for value in values:
if smallest is None or value < smallest:
smallest = value
return smallest
print (min([3, 41, 12, 9, 74, 15]))
| true |
09c3a9cdc222b71a69ba60ebbe6a0e6e50133579 | Anaisdg/Class_Resources | /UT_Work/Week_3_Python/Comprehensions.py | 570 | 4.5 | 4 | # -*- coding: UTF-8 -*-
#create name input
names = input("List 5 people that you know")
splitnames = names.split()
#create comprehension so that all items in list are lowercased
lowernames = [names.lower() for names in splitnames]
#create comprehension so that all items in list are capitalized
capitalizednames = [names.title() for names in lowernames]
#create comprehension so that list is created with different letters
letters = [f"Dear {names}, please come to the wedding this Saturday!" for names in capitalizednames]
for letters in letters:
print(letters)
| true |
43bd7130931ef987c6e0568d54444c15d9beb1cc | sudharsanansr/randomProblems | /secondLargest.py | 245 | 4.15625 | 4 | #find the second largest number in the given array
arr = [12,4,2,51,34,54,345]
largest = 0;
second_largest = 0;
for i in range(len(arr)):
if arr[i] > largest:
second_largest = largest
largest = arr[i]
print(second_largest) | true |
9ece4acb90fc64465ef6a37fc7ad27fb17071a80 | victenna/Math | /Quadratic_equation.py | 1,022 | 4.34375 | 4 | # quadratic equation
# A program that computes the real roots of a quadratic equation.
# Illustrates use of the math library.
# Note: this program crashes if the equation has no real roots.
import math # Makes the math library available.
import turtle
t=turtle.Turtle()
wn=turtle.Screen()
wn.bgcolor('gold')
Text_font=('Arial', 30,'bold')
t.up()
t.color('blue')
t.hideturtle()
t.goto(-300,0)
t.write('Quadratic Equation: Ax^2+Bx+C=0',font=Text_font)
def main():
print("This program finds the real solutions to a quadratic")
print()
a = float(input("Enter coefficient A: "))
b = float(input("Enter coefficient B: "))
c = float(input("Enter coefficient C: "))
q=b * b - 4 * a * c
if q>=0:
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("The solutions are:", root1, root2 )
else:
print('No solution')
#print()
main()
| true |
ef4f72eceea4450dfb0ce77e3dcd39841433c536 | nicholask98/CS-Dojo---Python-Tutotial--5-For-loop-Challenge | /main.py | 235 | 4.1875 | 4 | # Can you compute all multiples of 3, and 5
# That are less than 100?
list_100 = list(range(1, 100))
list_multiples = []
for i in list_100:
if i % 3 == 0 or i % 5 == 0:
list_multiples.append(i)
print(list_multiples)
| true |
a1a34376a29d5d5361a352eef1f2a1b0f31687ee | blip-lorist/python-the-hard-way | /ex6.py | 1,259 | 4.28125 | 4 | # Sets 'x' variable to a string with a format character that
# takes an integer
x = "There are %d types of people." % 10
# Sets 'binary' variable to a string
binary = "binary"
# Sets 'do_not' variable to a string
do_not = "don't"
# Sets 'y' variable to a string containing two string format characters
y = "Those who know %s and those who %s." % (binary, do_not)
# Prints the string and integer contained in x
print x
# Prints the strings contained in y
print y
# Prints any format passed in through this formatter (in this case,
# a string and an integer)
print "I said: %r." % x
# Prints strings
print "I also said: '%s'." % y
# Sets 'hilarous' variable to the boolean value of false
hilarious = False
# Sets 'joke_evaluation' variable to a string that will take any
# format at the end
joke_evaluation = "Isn't that joke so funny?! %r"
# Prints a string followed by the boolean value contained
# in hilarious
print joke_evaluation % hilarious
# Sets 'w' variable to a string
w = "This is the left side of ..."
# Sets 'e' variable to a string
e = "a string with a right side."
# Prints the combined string of concatinating w and e
print w + e
# There are four places where strings are in strings
# Twice on 9, then on lines 14 and 19
# Concatination
| true |
35f952e031ba36520064dda00037eb434687427b | saligramdalchand/python_code_practice | /chapter3/cube_root using binary method.py | 1,128 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 19:03:41 2018
@author: dc
"""
'''this program is for finding the cube root of integer either negative or positive'''
'''this program is telling me things that i done wrong in the program of getting square root of the
negative integer.. very useful but pretty basic program for someone who is a good coder '''
number = float(input("please provide the number you want to get the cube root\n"))
low = min(0,number)
high = max(0,number)
steps = 0
temp_var =0.0 #for swap purpose
ans = (low+high)/2
new_number = 0.0 #for negative integer purpose
epsilon = 0.01 # to check the accuracy
#if number<0:
## temp_var = low
## low = high
## high = temp_var
# while(abs(ans**3-number)>=epsilon):
# steps += 1
# if ans**3 < number:
# low = ans
# else:
# high = ans
# ans = (low+high)/2.0
#else:
while abs(ans**3-number)>=epsilon:
steps += 1
# print (ans)
if ans**3 > number:
high = ans
else:
low = ans
ans = (high+low)/2.0
print(steps)
print(ans)
| true |
ba2760fd6c61f1047e2c4a2abf577a1fa81c0e2e | saligramdalchand/python_code_practice | /chapter3/square root of negative integer.py | 1,730 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 18:10:38 2018
@author: dc
"""
#this is the finding of the square root of the number which is a negative integer
number = float(input('please provide the interger number of which you want to get square root\n'))
low = min(0,number) #these are just new trick of using min and max
high =max(0,number)
new_number = 0.0 #for stroing the positive number of the negative number
temp_var = 0.0 #for swaping value of low and high when number is negative
steps = 0
ans = (low + high)/2.0
epsilon = 0.01
# i am un necessarly writing this piece of code
#we can do this buy getting abs of number in starting
#and checking the result in last whether the number is negative or not
#by the way i am learning the hard coding
#smile please
if number < 0: #this will run if number is negative
new_number = abs(number) #to get the positive value of number
temp_var= low #swap
low =high
high = temp_var
while abs(ans**2 - new_number) >= epsilon: #very similar loop as was expected for square root
steps +=1
if ans**2 > new_number:
high = ans
else:
low = ans
ans = (low+high)/2.0#i am not using abs in this place and its making result awesome
else:# this will run if number is positive
while abs(ans**2 - number) >= epsilon: #this is also the same thing
steps +=1
if ans**2 > number:
high = ans
else:
low = ans
ans = abs(high + low)/2.0
#this piece of code is very awesome as i learnt the thing of swaping the result in the middle code
#
print('the number of steps followed in the whole calculations are',steps)
print (ans) | true |
6a8a53bb241aebe4018784e262aeb259d6eb49c2 | saligramdalchand/python_code_practice | /chapter3/magical program.py | 1,514 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 6 09:48:06 2018
@author: dc
"""
#import time
#this is a megical program that is going to print the value same as the user
low = 0
high = 100
magical_number = (low+high)/2
character = ' '
checker = ' '
print ('Please think of a number between 0 and 100!')
#time.sleep(5)
#print("there are some rule that you have to follow while going through it.")
#time.sleep(5)
#print("first and last rule")
#time.sleep(3)
#print("you have to enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
#time.sleep(6)
#print ("Is your secret number",magical_number,"?")
#print ("Enter 'h' to indicate the guess is too high.")
#print("Enter 'l' to indicate the guess is too low.")
#print("Enter 'c' to indicate I guessed correctly.")
while (checker != 'c'):
print("Is your secret number",magical_number,"?")
character = str(input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. "))
checker = character
if character == 'h':
high = magical_number
elif character == 'l':
low = magical_number
elif (checker == 'c'):
break
else:
print("Sorry, I did not understand your input.")
magical_number = int((low+high)/2)
if (checker == 'c'):
print("Game over. Your secret number was:",magical_number)
else:
print("tough choice\n") | true |
ae88663c89ed61c663ebe7d19edb439d82b54a91 | zola-jane/MyCP1404Workshops | /Workshop5/lottery_generator.py | 814 | 4.1875 | 4 | """
This program asks the user how many quick picks they wish to generate.
The program then generates that many lines of output.
Each line consists of siz random numbers between 1 and 45
Each line should not contain any repeated number.
Each line of numbers should be displayed in ascending order.
"""
def main():
# lottery_numbers = []
quick_pick = int(input("How many quick picks?"))
for pick in range(quick_pick):
lottery_numbers = get_random_numbers()
print("{}".format(" ".join(str(i) for i in lottery_numbers)))
def get_random_numbers():
import random
numbers = []
for number in range(6):
number = random.randint(1, 45)
while number in numbers:
number = random.randint(1, 45)
numbers.append(number)
return numbers
main()
| true |
4b0667fbce2322865c6bb6a590fad10680fb5179 | SakshiKhandare/Leetcode | /sqrt.py | 730 | 4.28125 | 4 | '''
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
'''
class Solution:
def mySqrt(self, x: int) -> int:
if x==0:
return 0
start=1
end=x
ans = 0
while(start<=end):
mid = start + (end-start)//2
if mid<=x/mid:
ans = mid
start = mid+1
else:
end = mid-1
return int(ans)
| true |
93149ead3fab3596c0c3185126c7404252776a1d | SakshiKhandare/Leetcode | /divide_int.py | 720 | 4.125 | 4 | '''
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
Example:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
'''
import math
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
sign = 1
if dividend*divisor < 0:
sign = -1
dividend = abs(dividend)
divisor = abs(divisor)
val=0
while (dividend >= divisor):
dividend -= divisor
val += 1
if val == 2**31:
return 2**31-1
return int(math.trunc(sign*val)) | true |
95218d56ab350cb642398be49d5c77e90440ab65 | ihatetoast/lpthw | /python-class/class1_ifelif_cont.py | 805 | 4.21875 | 4 | health = 49
strHealth = str(health)
print "A vicious warg is chasing you."
print "Options:"
print "1 - hide in the cave"
print "2 - Climb a tree"
input_value = raw_input("Enter choice: ")
if input_value == "1":
print "You hide in a cave."
print "The warg finds you and injures your leg with his claws."
health = health - 7
strHealth = str(health)
elif input_value == "2":
print "You climb a tree"
print "The warg eventually loses interest and wanders off"
health = health * 1.5
strHealth = str(health)
else:
print "You can't follow directions."
health = health / health
strHealth = str(health)
if health == 1:
print "Your health is " + strHealth + "."
print "You should just stop."
elif health > 50:
print "You are smokin' with a health of " + strHealth + "."
else:
print "Keep playing." | true |
c7fd41df703caa35150d0495fd483bdb27be17c1 | ihatetoast/lpthw | /python-class/class1_range.py | 225 | 4.3125 | 4 | print "range(5)"
print range(5)
print "range(5,10)"
print range(5,10)
print "range(5,20,2)"
print range(5,20,2)
print "range(50,20,-2)"
print range(50,20,-2)
for number in range(5):
print "the number is : " + str(number) | false |
6e0d8d2efca6586150389aaab19f9098c304e111 | belushkin/Guess-the-number | /game.py | 1,856 | 4.1875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
# initialize global variables used in your code
secret_number = 0
num_range = 100
guess_left = 7
def init():
global secret_number
global guess_left
print "New game. Range is from 0 to", num_range
print "Number of remaining guesses is", guess_left
print ""
secret_number = random.randrange(0, num_range)
# define event handlers for control panel
def range100():
global num_range
global guess_left
num_range = 100
guess_left = 7
init()
def range1000():
global num_range
global guess_left
num_range = 1000
guess_left = 10
init()
def get_input(guess):
global guess_left
guess_left -= 1
print "Guess was", guess
print "Number of remaining guesses is", guess_left
if guess_left == 0:
print "You loose";
print ""
if num_range == 100:
range100()
return False
else:
range1000()
return False
if int(guess) > secret_number:
print "Lower!"
elif int(guess) == secret_number:
print "Correct!"
print ""
if num_range == 100:
range100()
else:
range1000()
return False
else:
print "Higher!"
print ""
# create frame
frame = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
frame.add_input("Enter a guess", get_input, 200)
init()
# start frame
frame.start()
# always remember to check your completed program against the grading rubric
| true |
1977b8be6cb866b5a38c942df6913c361a65dd05 | DU-ds/Misc-Python-Scripts | /firstUnitTest.py | 1,162 | 4.1875 | 4 | """
following tutorials:
https://www.jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/
https://diveinto.org/python3/unit-testing.html
https://docs.pytest.org/en/latest/getting-started.html#install-pytest
see unittest docs for more ideas about tests:
https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug
to run tests:
pytest R:/Git/Misc-Python-Scripts/firstUnitTest.py
"""
# import os
# os.chdir("R:/Git/Misc-Python-Scripts")
# don't think I need them?
import unittest
from primes import is_prime
class PrimesTestCase(unittest.TestCase):
"""Tests for `primes.py`."""
def test_is_eleven_prime(self):
""" does it recognize that 11 is prime """
self.assertTrue(is_prime(11))
def test_zero_is_not_prime(self):
self.assertFalse(is_prime(0))
def test_negative(self):
self.assertFalse(is_prime(-1))
def test(self):
pass
def func(x):
return x + 2
def test_one():
assert func(3) == 5
def test_two():
x = "hello"
assert not hasattr(x, "check")
if __name__ == '__main__':
unittest.main()
#pytest.main()
| false |
5039fdabafb4517156c15150c5c69395647cb6bf | sherly75/python1 | /intro3.py | 1,904 | 4.3125 | 4 | values =['a','b','c']
#values.append(1)
#values.append(2)
#values.append(3)
values.extend([1,2,3])
print(values)
print(values[2])
#deleting a value : del array_name[index]
del values[1]
print(values)
#values.append(['d','e','f'])
values.extend(['d','e','f'])
print(values) #['d','e','f'] is one single element in case of values.append
#looping through a list
#for singular in plural:
#for one instance in a list
count=0
for value in values: #the word value here is arbitary, u can use any world
#print(value)
print(f'value{count}:{value}')
#count=count+1 ...................
# for count+=1 can be used for *-/, count*=5
count+=1
for index, value in enumerate(values):
print(f'{index}:{value}')
numbers=[1,2,3,4,5,6,7,8,9]
sum=0
for number in numbers:
sum+=number
print(f'Sum:{sum}')
print(f'avg:{sum/len(values)}')
print(len(values)) #length of the list
#print(list(range(5)))......... NOT IMP RN
for index in range(5):
print (index)
for index in range(5,10): #range(start,stop) [5,10) 10th index is not included
print(index)
for index in range(0,21,2):#step or the "2" here is every 2nd number
print(index)
#alternative loop
#while boolean condition, boolean means some true or false statement has to be executed
index=0
while index<5: #while index is less than 5
print(index)
index+=1
else:
print('done with loop')
while True:
print('hi')
break #break exits the loop
message="Hello Marymount"
for letter in message:
print(letter)
print(message[-1])
#splice
#list_name[start:end]
print(message[0:3])
print(message[6:]) #leaving blank it goes till the end
print(message[:6]) #leaving blank starts at the beginning
food_trucks=['Karnage Asada', ' Killer Tomato', 'Kraving Kabob']
print(food_trucks[1:])
print(food_trucks[-2:])
print(food_trucks[:2])
print('end')
| true |
a8f36cd8a7117f94b63b9d7d6da61fef3b946f8e | taxioo/study_python | /01.python/ch09/ex08.py | 257 | 4.25 | 4 | # .append(값) - 리스트의 끝에 값을 추가
# .insert(위치, 값) - 지정한 위치에 값을 삽입
nums = [1, 2, 3, 4]
nums.append(5)
print(nums)
nums.insert(2, 99)
print(nums)
nums.insert(0, 100)
print(nums)
nums.insert(-1, 1000)
print(nums) | false |
31c6fcfb0a72d845d31506606f08802d3e6d0a28 | taxioo/study_python | /01.python/ch03/ex02.py | 274 | 4.125 | 4 | a = 10.1 #float
print(a)
print(type(a))
b = 10.0
print(type(b))
a = '10'
a = int(a) #int - 숫자로 치환
print(type(a))
b = '10.1'
print(type(b))
b = float(b) #float - 실수로 치환
s= str(b) # str - 문자열로 치환
print(s, type(s)) | false |
c42e5ac88690d81c74df3072228203f34405f397 | Armanchik74/practicum-1 | /36.py | 1,082 | 4.15625 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: Задание 36.py
Автор: 2020 © А.С. Манукян, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 17/12/2020
Дата последней модификации: 17/12/2020
Описание: Решение задачи № 36
#версия Python:3.9
"""
Дан одномерный массив числовых значений, насчитывающий N элементов. Вставить группу из M новых элементов, начиная с позиции K.
""
import array
import random
N = int(input("Введите количество элементов массива "))
M = int(input("Количесвто элементов в группе"))
K = int(input("Позиция K"))
A = [random.randint(0, 100) for i in range(0, N)]
B = [random.randint(0, 100) for b in range(0, M)]
print(A)
print(B)
A.insert(K, B)
print(A)
| false |
792b8b7eb6ef0ad9fcc14b3e8abcbcb1eba7a076 | Armanchik74/practicum-1 | /22.py | 1,215 | 4.21875 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: Задание 22.py
Автор: 2020 © А.С. Манукян, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 12/12/2020
Дата последней модификации: 12/12/2020
Описание: Решение задачи № 22
#версия Python:3.9
"""
Даны вещественные числа A,B,C. Определить, выполняются ли неравенства A < B < C или A>B>C, и какое именно неравенство выполняется.
""
A=float(input("Введите первое вещественное число"))
B=float(input("Введите второе вещественное число"))
C=float(input("Введите третье вещественное число"))
if A<B and B>C:
print("Оба неравенства выполняются")
if A<B:
print("Выполняется только первое неравенство")
if B>C:
print("Выполняется только второе неравенство")
| false |
678819346fc645b0cf0326ba95be403e491e9c01 | buglenka/python-exercises | /FindReplace.py | 2,555 | 4.46875 | 4 | #!/usr/local/bin/python3.7
"""Find And Replace in String
To some string S, we will perform some replacement operations that
replace groups of letters with new ones (not necessarily the same size).
Each replacement operation has 3 parameters: a starting index i, a source
word x and a target word y. The rule is that if x starts at position i in
the original string S, then we will replace that occurrence of x with y.
If not, we do nothing.
For example, if we have S = "abcd" and we have some replacement operation
i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the
original string S, we will replace it with "ffff".
Using another example on S = "abcd", if we have both the replacement
operation i = 0, x = "ab", y = "eee", as well as another replacement
operation i = 2, x = "ec", y = "ffff", this second operation does nothing
because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.
All these operations occur simultaneously. It's guaranteed that there won't
be any overlap in replacement: for example, S = "abc", indexes = [0, 1],
sources = ["ab","bc"] is not a valid test case.
Example 1:
Input: S = "abcd", indexes = [0,2], sources = ["a","cd"],
targets = ["eee","ffff"]
Output: "eeebffff"
Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
"cd" starts at index 2 in S, so it's replaced by "ffff".
Example 2:
Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"],
targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.
Notes:
0 <= indexes.length = sources.length = targets.length <= 100
0 < indexes[i] < S.length <= 1000
All characters in given inputs are lowercase letters.
"""
from typing import List
def findReplaceString(S: str, indexes: List[int],
sources: List[str], targets: List[str]) -> str:
l = len(indexes)
Slist = list(S); replacements = []
for i in range(l):
replacements.append((indexes[i], list(sources[i]), list(targets[i])))
replacements.sort(key=lambda x: x[0])
shift = 0
for i, s, t in replacements:
lssub = len(s)
ltsub = len(t)
index = i + shift
if (Slist[index:index+lssub] == s):
Slist[index:index+lssub] = t
shift += (ltsub - lssub)
return ''.join(Slist)
S = "abcd"
indexes = [0,2]
sources = ["a","cd"]
targets = ["eee","ffff"]
print(findReplaceString(S, indexes, sources, targets))
| true |
0a38e961cddf6582e569c10475027e9573f8c1f4 | buglenka/python-exercises | /TrappingWater.py | 1,149 | 4.125 | 4 | #!/usr/local/bin/python3.7
"""Trapping Rain Water
Given n non-negative integers representing an elevation
map where the width of each bar is 1, compute how much
water it is able to trap after raining.
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
"""
from typing import List
def trap(height: List[int]) -> int:
"""Using dynamic programming
3 Steps:
- Find max height upto the point from the left
- Find max height upto the point from the right
- Choose the minimum of 2 heights and substract initial height
"""
if not height:
return 0
l = len(height)
max_right = [0] * l
max_left = [0] * l
max_right[0] = height[0]
for i in range(1, len(height)):
max_right[i] = max(height[i], max_right[i - 1])
max_left[len(height) - 1] = height[len(height) - 1]
for i in range(len(height) - 2, -1, -1):
max_left[i] = max(height[i], max_left[i + 1])
res = 0
for i in range(l):
res += min(max_right[i], max_left[i]) - height[i]
return res
hs = [0,1,0,2,1,0,1,3,2,1,2,1]
print(trap(hs)) | true |
9bce4d77b4e1ff65794552c1d282240b4bffde78 | buglenka/python-exercises | /ValidPalindrome.py | 791 | 4.375 | 4 | #!/usr/local/bin/python3.7
"""Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
"""
import string
def isPalindrome(s: str) -> bool:
alphabet = string.ascii_lowercase + string.digits
alphanumeric_s = list(filter(lambda x: x in alphabet, s.lower()))
if len(alphanumeric_s) < 2:
return True
tail_len = len(alphanumeric_s) // 2
left = alphanumeric_s[:tail_len]
right = alphanumeric_s[-tail_len:]
return left == right[::-1]
s = "race a car"
print(isPalindrome(s)) | true |
ce54f35f9200d9c664bc1488d4bff5e62edba522 | davidjb90/bicycle-project | /bicycle.py | 2,281 | 4.34375 | 4 | ##This is the final 'model the bicycle industry' project in unit 1
### Create the Bicycle Class
import random
class Bicycle:
def __init__(self, manufacturer, model, weight, cost):
self.manufacturer = manufacturer
self.model = model
self.weight = weight
self.cost = cost
class Bike_Shop:
def __init__(self, name, margin, inventory={}, bikecost={}):
self.name = name
self.margin = margin + 1
self.inventory = inventory
self.bikecost = bikecost
for bike, price in self.bikecost.items(): #### moved logic into the bike shop; where pricing of bike occurs
self.bikecost[bike] = price * self.margin #### updates the bikecost dictionary (shop_inventory2 in main.py) within Bike_Shop object
#### easier than updating it manually each time we want the price of a given bike
def get_price(self, bike):
return self.bikecost[bike]
def shop_profit(self, profit):
x = 0
for i in profit:
x += self.bikecost[i] - (self.bikecost[i] / self.margin)
return x
class Customer:
def __init__(self, Name, budget):
self.Name = Name
self.budget = budget
self.bikes_afforded = []
def purchase_decision(self, bikes_afforded):
self.purchase = "" ### empty string to which we add the single random bike we pick in the next line
self.purchase += random.choice(self.bikes_afforded) #picks a random bike among a list of bikes each customer can afford
return self.purchase
def bike_purchased(self):
return self.purchase
class Wheel:
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
class Frame:
def __init__(self, material, weight, cost):
self.material = material
self.weight = weight
self.cost = cost
class Manufacturer:
def __init__(self, name, sell_margin, models=[]):
self.name = name
self.models = models
self.sell_margin = sell_margin + 1
#def wholesale_price(self, bike):
| true |
e96b588092e27565c1bbf0ed760148a48abe97b6 | radhika2303/PPL_assignments | /assignment5/exception.py | 1,948 | 4.3125 | 4 | #1.NORMAL TRY-EXCEPT BLOCK IS IMPLEMENTED HERE
print("Exception 1: (try-except block)\n")
i = int(input("Enter 1st number :\n"))
j = int(input("Enter 2nd number :\n"))
try:
k = i/j
print(k)
except:
print("You divided by 0")
print("No error shown because the exception was handled")
#2.EXCEPTION FOR ZeroDivision Error
print("\nException 2: (ZeroDivision Error)\n")
a = int(input("Enter 1st value for division\n"))
b = int(input("Enter 1st value for division\n"))
try:
print(a/b)
except ZeroDivisionError:
print("A number cannot be divided by zero")
#3.EXCEPTION FOR HANDLING TYE-ERROR
print("\nException 3: (Type-Error)\n")
a = input("Enter 1st value for division\n")
b = int(input("Enter 1st value for division\n"))
try:
print(a/b)
except TypeError:
print("A string cannot be divided by integer. Convert string to integer in code while taking input")
#4.TRY WITH MULTIPLE EXCEPT
print("\nException 4: (Multiple Excepts)\n")
i = int(input("Enter 1st number :\n"))
j = int(input("Enter 2nd number :\n"))
try:
print(i/j)
print("Inside try --- printed")
except TypeError:
print("You added values of incompatible types")
except ZeroDivisionError:
print("You divided by 0")
#5.If you don't know which type of exception to raise, then don't specify the exception name
print("\nException 5: (Using finally)\n")
print("Enter a filename you want to read\n")
a = input()
try:
f = open(a, "r")
m = f.read()
print("This is the content of your file:")
print(m)
except:
print("Error : File not found.")
finally:
print("Finally executes like a common print statement.It is executed always.\n")
#6.Deliberately raising an error using raise keyword
print("\nException 6: (Using raise)\n")
i = int(input("Enter 1st number :\n"))
j = int(input("Enter 2nd number :\n"))
try:
if b==0:
raise ZeroDivisionError
except:
print("You divided by 0")
print("This is printed if no error found\n")
print("\n----*----\n")
| true |
34801085f50cd1dd516bc64b8bffb544878932cf | saurav1066/python_assignment2 | /10.py | 812 | 4.46875 | 4 | """
Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case
(i.e. this_is_camel_cased). Modify the function by adding an argument, separator, so it will also convert to
the kebab case (i.e.this-is-camel-case) as well.
"""
import re
def snake_cased_separator(string_value, separator):
result_list = []
result_string = ''
lis = re.findall('[A-Z][^A-Z]*', string_value)
for i in lis:
result_list.append(i.lower())
result = list(map(lambda x: separator + x, result_list[1:]))
result_list = [result_list[0]]
result = result_list + result
for i in result:
result_string += i
print(result_string)
string = input("Enter camel cased string:")
sep = input("Enter a separator:")
snake_cased_separator(string, sep)
| true |
bc97b5f762b360688f9f0bf662baf9965b3e67ea | marisha-g/INF200-2019 | /src/marisha_gnanaseelan_ex/ex02/file_stats.py | 1,002 | 4.3125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Marisha Gnanaseelan'
__email__ = 'magn@nmbu.no'
def char_counts(textfilename):
"""
This function opens and reads a given file with utf-8 encoding.
It also counts how often each character code (0–255) occurs in the string
and return the result as a list or tuple.
:return: list
"""
with open(textfilename, 'r', encoding='utf-8') as read_file:
read_file = read_file.read()
result = [0] * 256 # empty list with zeros
for char in read_file:
result[ord(char)] += 1 # converting the characters to integers
return result
if __name__ == '__main__':
filename = 'file_stats.py'
frequencies = char_counts(filename)
for code in range(256):
if frequencies[code] > 0:
character = ''
if code >= 32:
character = chr(code)
print(
'{:3}{:>4}{:6}'.format(
code, character, frequencies[code]
)
)
| true |
c8f22e2c0385bf7a4ff0c8344f24a995a92988e7 | nachiket8188/Python-practice | /CSV Module.py | 693 | 4.1875 | 4 | import csv
# with open('new_names.csv','r') as f:
# csv_reader = csv.reader(f)
# print(csv_reader) # this is an iterable object. Hence, the loop below.
# next(csv_reader)
# # for line in csv_reader:
# # print(line)
# with open('new_names.csv', 'w') as new_file:
# csv_writer = csv.writer(new_file, delimiter='\t')
# for line in csv_reader:
# csv_writer.writerow(line)
# for line in csv_reader: # no delimiter specified for new file.
# print(line)
# using dictionary reader & writer to operate on CSvs.
with open('names.csv','r') as f:
csv_reader = csv.DictReader(f)
for line in csv_reader:
print(line)
| true |
f0654b773eebb8c9455020b77937b2e0018f2a00 | JishnuSaseendran/Recursive_Lab | /task 21_22_Anand-Python Practice Book/3. Modules/9.py | 299 | 4.28125 | 4 | '''
Problem 9: Write a regular expression to validate a phone number.
'''
import re
def val_mob_no(num):
list=re.findall('\d{1,10}',num)
print list
if len(list[0])==10:
print 'Your mobile number is valid'
else:
print 'sorry! Your mobile number is not valid'
val_mob_no('9846131311')
| true |
63b856b7578497ba92e1f29eaa0e41f049e21899 | Ron-Chang/MyNotebook | /Coding/Python/PyMoondra/Threading/demo_5_lock.py | 1,355 | 4.21875 | 4 | # lock 變數上鎖, lock variabl
# 應用在多線程執行時有機會存取同一變數
# apply to multi-thread which might access or share the same variable
# we can lock it until the processing tread has finished
import threading
# def adding_2():
# global x
# lock.acquire()
# for i in range(COUNT):
# x += 2
# lock.release()
# # equivalent the following function
def adding_2(COUNT):
global x
# with lock:
for i in range(COUNT):
x += 2
def adding_3(COUNT):
global x
# with lock:
for i in range(COUNT):
x += 3
def subtracting_4(COUNT):
global x
# with lock:
for i in range(COUNT):
x -= 4
def subtracting_1(COUNT):
global x
# with lock:
for i in range(COUNT):
x -= 1
if __name__ == '__main__':
x = 0
COUNT = 100000
# lock = threading.Lock()
t1 = threading.Thread(target=adding_2, name='thread_add_2', args=(COUNT,))
t2 = threading.Thread(target=subtracting_4, name='thread_sub_4', args=(COUNT,))
t3 = threading.Thread(target=adding_3, name='thread_add_3', args=(COUNT,))
t4 = threading.Thread(target=subtracting_1, name='thread_sub_1', args=(COUNT,))
# x = 0+2-4+3-1 = 0
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print(x)
| true |
78e4f68240f7e24c6d7c3e78507ed927be5edef4 | Ron-Chang/MyNotebook | /Coding/Python/Ron/Trials_and_Materials/Hello_world->elloHay_orldway.py | 1,071 | 4.25 | 4 | """
Move the first letter of each word to the end of it, then "ay" to the end of the word.
Leave punctuation marks untouched.
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !"""
from string import punctuation
def pig_it(text):
sentence = text.split(" ")
result =""
for word in sentence:
if len(word) == 1 and word[0] in punctuation:
result += word+" "
elif word[0] not in punctuation and word[-1] not in punctuation:
word = word[1:]+word[0]+"ay"
result += word+" "
elif word[0] not in punctuation and word[-1] in punctuation:
word = word[1:-1]+word[0]+"ay"+word[-1]
result += word+" "
else:
word+="ay"
result += word+" "
return result.strip()
# # clever one
# import re
# def pig_it(text):
# return re.sub(r'([a-z])([a-z]*)', r'\2\1ay', text, flags=re.I)
x = pig_it("! Pig, latin is cool")
y = pig_it("Hello world!")
print(f"!, Pig, latin is cool\n{x}\nHello world !\n{y}")
| true |
12352ca917158947b2505906ee626be64da9c340 | andrade-marco/python_masterclass | /basic/Recursive.py | 1,093 | 4.125 | 4 | def fact(n):
# Calculate n! iteratively
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result
def fact_recursive(n):
# n! can also be defined as n * (n - 1)!
if n <= 1:
return 1
else:
return n * fact_recursive(n - 1)
def fib(n):
if n == 0:
result = 0
elif n == 1:
result = 1
else:
n_minus_one = 1
n_minus_two = 0
for i in range(1, n):
result = n_minus_two + n_minus_one
n_minus_two = n_minus_one
n_minus_one = result
return result
def fib_recursive(n):
# Calculate Fibonacci sequence
if n < 2:
return n
else:
return fib_recursive(n - 1) + fib_recursive(n - 2)
print('Factorial')
for i in range(30):
fact_reg = fact(i)
fact_rec = fact_recursive(i)
print('{}: {:5} | {:5}'.format(i, fact_reg, fact_rec))
print('-' * 50)
print('Fibonacci')
for i in range(30):
fib_reg = fib(i)
fib_rec = fib_recursive(i)
print('{:2}: {:9} | {:9}'.format(i, fib_reg, fib_rec))
| false |
409b11e470d507ef3320c5788e4a46a5dae2639e | joe-bethke/daily-coding-problems | /DCP-6-20190220.py | 2,912 | 4.25 | 4 | """
This problem was asked by Google.
An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields,
it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list;
it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.
If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and
dereference_pointer functions that converts between nodes and memory addresses.
"""
class XOR:
def __init__(self, value, both=tuple()):
self.value = value
self.both = both
def __repr__(self):
return str(self.value)
def link(self, steps):
i = 0 if steps < 0 else 1
link = self
for _ in range(abs(steps)):
if not link.both:
raise ValueError("The links ended before the given number of steps could be completed.")
link = link.both[i]
return link
class LinkedList:
def __init__(self, lis):
xors = [XOR(value) for value in lis]
pushed_forw = [xors[-1]] + xors[0:-1]
pushed_back = xors[1:] + [xors[0]]
self._linked_list = list()
for both, xor in zip(zip(pushed_forw, pushed_back), xors):
xor.both = both
self._linked_list.append(xor)
def __str__(self):
fstr = "{idx}: {val}"
return "\n".join([" --> ".join([fstr.format(idx=(idx - 1) if idx != 0 else (len(self._linked_list) - 1),
val=xor.both[0]),
fstr.format(idx=idx,
val=xor.value),
fstr.format(idx=(idx + 1) if idx < len(self._linked_list) - 1 else 0,
val=xor.both[-1])])
for idx, xor in enumerate(self._linked_list)])
def __iter__(self):
return iter(self._linked_list)
def __getitem__(self, idx):
return self._linked_list[idx]
def add(self, element):
new_xor = XOR(element, both=(self._linked_list[-1], self._linked_list[0])) # create the new xor
self._linked_list[-1].both = (self._linked_list[-2], new_xor) # change current last xor
self._linked_list.append(new_xor) # add the new xor to the list
self._linked_list[0].both = (self._linked_list[-1], self._linked_list[1]) # update the first xor
def get(self, idx):
return self.__getitem__(idx) # same as __getitem__
test = [x**2 for x in range(10)]
ll = LinkedList(test)
ll.add(100)
ll.add(121)
print(ll)
xor_4 = ll.get(4)
print(xor_4)
print(xor_4.link(-4))
print(ll[0:2])
print(ll.get(slice(0, 2))) | true |
dfa59e95e4430f99377a20191dacb99b50f22be3 | joe-bethke/daily-coding-problems | /DCP-27-20190313.py | 1,009 | 4.1875 | 4 | """
This problem was asked by Facebook.
Given a string of round, curly, and square open and closing brackets,
return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
openers = ("(", "[", "{")
closers = (")", "]", "}")
opener_to_closer = dict(zip(openers, closers))
def is_valid(s):
closer_order = list()
for char in s:
if char in openers:
closer_order.append(opener_to_closer[char])
if char in closers:
if closer_order and char == closer_order[-1]:
closer_order.pop(-1)
else:
return False
return not closer_order # If the closer order is empty, return True
print(is_valid("([])[]({})"))
print(is_valid("([)]"))
print(is_valid("((()"))
print(is_valid("]]]"))
print(is_valid("ab[]ad[]d{fasdf(fasdf)fa}"))
print(is_valid("ab[]ad[]d{fasdf(fasdf)fa")) | true |
8a0aea7768a2f4dd29d14dfd3d5eec634778ff2c | jbregli/edward_tuto | /gp_classification.py | 2,903 | 4.3125 | 4 | """
EDWARD TUTORIAL: Gaussian process classification
------------------------------------------------
In supervised learning, the task is to infer hidden structure from labeled data,
comprised of training examples $\{(x_n, y_n)\}$.
Classification means the output y takes discrete values.
A Gaussian process is a powerful object for modeling nonlinear relationships between
pairs of random variables. It defines a distribution over (possibly nonlinear) functions,
which can be applied for representing our uncertainty around the true functional
relationship. Here we define a Gaussian process model for classification
(Rasumussen & Williams, 2006).
Formally, a distribution over functions f:\mathbb{R}^{D}→\mathbb{R} can be specified by a
Gaussian process,
p(f)=GP(f∣0,k(x,x′)),
whose mean function is the zero function,
and whose covariance function is some kernel which describes dependence between any set of
inputs to the function.
Given a set of input-output pairs {x_{n} \in \mathbb{R}^{D}, y_{n} \in \mathbb{R}}, the
likelihood can be written as a multivariate normal,
p(y)=Normal(y∣0,K)
where K is a covariance matrix given by evaluating k(x_{n},x_{m}) for each pair of inputs
in the data set.
The above applies directly for regression where y is a real-valued response, but not for
(binary) classification, where y is a label in {0,1}. To deal with classification, we
interpret the response as latent variables which is squashed into [0,1]. We then draw from
a Bernoulli to determine the label, with probability given by the squashed value.
Define the likelihood of an observation (x_{n},y_{n}) as,
p(y_{n}∣z,x_{n})=Bernoulli(y_{n}∣logit−1(x_{n}^{⊤}z)).
Define the prior to be a multivariate normal
p(z)=Normal(z∣0,K),
with covariance matrix given as previously stated
NOTE:
Uses crabs data set:
https://github.com/blei-lab/edward/tree/master/examples/data
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import edward as ed
from edward.models import Bernoulli, MultivariateNormalCholesky, Normal
from edward.util import rbf
plt.style.use('ggplot')
ed.set_seed(42)
# ===== Data =====
data = np.loadtxt('data/crabs_train.txt', delimiter=',')
data[data[:, 0] == -1, 0] = 0 # replace -1 label with 0 label
N = data.shape[0] # number of data points
D = data.shape[1] - 1 # number of features
X_train = data[:, 1:]
y_train = data[:, 0]
print("Number of data points: {}".format(N))
print("Number of features: {}".format(D))
# ===== Model =====
X = tf.placeholder(tf.float32, [N, D])
f = MultivariateNormalCholesky(mu=tf.zeros(N), chol=tf.cholesky(rbf(X)))
y = Bernoulli(logits=f)
# ==== Inference =====
qf = Normal(mu=tf.Variable(tf.random_normal([N])),
sigma=tf.nn.softplus(tf.Variable(tf.random_normal([N]))))
inference = ed.KLqp({f: qf}, data={X: X_train, y: y_train})
inference.run(n_iter=5000)
| true |
4199ce2ac053cc5c42e02c8672ac350f5e90d553 | PlumpMath/designPatterns-431 | /prototype/app.py | 1,031 | 4.125 | 4 | #!/usr/bin/python
'''
Prototype pattern.
This creational pattern is similar to an Abstract Factory. The difference is that we do not subclass the Factory,
instead initialize the factorty with objects (the prototypes), and then the factory will clone these objects whenever we ask for a new instance.
The magic 'cloning' must be implemented by each of the prototypes themselves. The factory simply calls the clone method.
Our example will use a single type of PrototypeFactory to make a whole breakfast.
'''
from prototypeFactory import PrototypeFactory
from prototypes import Bacon, Eggs, Toast
def main():
print 'making bacon...'
protoFac = PrototypeFactory(Bacon())
prototype = protoFac.make()
print prototype.describe()
print 'making eggs...'
protoFac = PrototypeFactory(Eggs())
prototype = protoFac.make()
print prototype.describe()
print 'making toast...'
protoFac = PrototypeFactory(Toast())
prototype = protoFac.make()
print prototype.describe()
return
if __name__ == '__main__':
main()
| true |
8842d653ca5dfb7fe9d557773e11de745c429b2d | margonjo/variables | /assignment_improvement_exercise.py | 420 | 4.1875 | 4 | #john bain
#variable improvement exercise
#05-09-12
import math
circle_radius = int (input("please enter the radius of the circle: "))
circumfrence = 2* math.pi * circle_radius
final_circumfrence = round(circumfrence,2)
area = math.pi * circle_radius**2
final_area = round(area,2)
print("The circumference of this circle is {0}.".format(final_circumfrence))
print("The area of this circle is {0}.".format(final_area))
| true |
c0f96908a518fdaddc400049452d16e2b51aa579 | Ilhamw/practicals | /prac_02/ascii_table.py | 453 | 4.25 | 4 | LOWER_BOUND = 33
UPPER_BOUND = 127
character = str(input("Enter a character: "))
print("The ASCII code for {} is {}".format(character, ord(character)))
order = int(input("Enter a number between {} and {}: ".format(LOWER_BOUND, UPPER_BOUND)))
while order < LOWER_BOUND or order > UPPER_BOUND:
order = int(input("Enter a number between {} and {}: ".format(LOWER_BOUND, UPPER_BOUND)))
print("The character for {} is {}".format(order, chr(order)))
| true |
3d1e63a67ad7986dd7e4be78e7c83f2f18af401a | SharanyaMarathe/Birthday_Reminder | /Birthday_reminder_test.py | 957 | 4.1875 | 4 | import datetime
def Current_Date():
Today=datetime.date.today() #To get current date and day
Today_day=Today.strftime("%A")
return Today,Today_day
def Birthday(date):
date_l=date.split("-")
d1=datetime.date(int(2020),int(date_l[1]),int(date_l[0]))
p= "On "+d1.strftime("%A") +", "+date_l[0]+"th "+d1.strftime("%B") #To notify the user birthday details of year 2020
return d1,p
def Notification(c,b):
if(c.month == b.month):
return ( "In same month")
elif((b.month - c.month) > 0):
return (str(b.month - c.month)+"Months from now")
else:
return (str(c.month - b.month) +"Months Ago")
def Display_Notifications(date):
Current_Info=Current_Date()
Birthday_info=Birthday(date)
notes=Notification(Current_Info[0],Birthday_info[0])
return str(notes)
if (__name__ == "__main__") :
date=input("Input Your Birth date in dd-mm-yy format: ")
dsn=Display_Notifications(date)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.