blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fbc4ac57f264a917f6b57f50991be8360191af16 | euggrie/w3resources_python_exercises | /Strings/exercise14.py | 822 | 4.25 | 4 | ###############################
# #
# Exercise 14 #
# www.w3resource.com #
###############################
# Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in
# sorted form (alphanumerically). Go to the editor
# Sample Words : red, white, black, red, green, black
# Expected Result : black, green, red, white,red
######################################################################################
secuence = input("Enter comma separated words: ")
words = [word for word in secuence.split(",")]
print(",".join(sorted(list(set(words))))) | true |
e0d3ed27dd48792145a724db61e2ecb9ab9c66a6 | euggrie/w3resources_python_exercises | /Basic/exercise12.py | 794 | 4.25 | 4 | ###############################
# #
# Exercise 12 #
# www.w3resource.com #
###############################
# Write a Python program to print the calendar of a given month and year.
# Note : Use 'calendar' module.
###################################################################################################
import calendar
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
cal2 = calendar.TextCalendar()
print(cal2.formatmonth(year,month))
#Another option to print it in HTML:
#cal = calendar.HTMLCalendar()
#print(cal.formatmonth(2015,11,True)) | true |
7e0c0e825e7db2e8d1f4d6690d5def4791b288b5 | euggrie/w3resources_python_exercises | /Strings/exercise10.py | 816 | 4.25 | 4 | ###############################
# #
# Exercise 10 #
# www.w3resource.com #
###############################
# Write a Python program to change a given string to a new string where the first and last chars have been exchanged.
######################################################################################################################
def prog(string):
new_string = ""
char1 = string[0]
char2 = string[-1]
rest = string[1:-1]
new_string = char2 + rest + char1
# return str1[-1:] + str1[1:-1] + str1[:1] another option
return new_string
print(prog("banana"))
| true |
0962e1e56e5f9eb01a86f2fdf8d34dac129c65f2 | euggrie/w3resources_python_exercises | /Strings/exercise11.py | 685 | 4.34375 | 4 | ###############################
# #
# Exercise 11 #
# www.w3resource.com #
###############################
# Write a Python program to remove the characters which have odd index values of a given string.
#################################################################################################
def prog(string):
word = ""
for i in range(len(string)):
if i % 2 == 0:
word = word + string[i]
return word
print(prog('python'))
| true |
608e1f2ebe4482e6bffbd075df0b6f6725fd361c | nedssoft/Graphs | /projects/ancestor/ancestor.py | 1,823 | 4.125 | 4 |
from queue import Queue
from graph import Graph
def earliest_ancestor(ancestors, starting_node):
# Initialize a graph
graph = Graph()
# build a graph of the parents and children
# Iterate over ancestors' tuple (parent, child)
for parent, child in ancestors:
# check if the parent is not in the vertices
if parent not in graph.vertices:
# Add parent to the graph vertices
graph.add_vertex(parent)
# check if the child is not in the vertices
if child not in graph.vertices:
# Add parent to the graph vertices
graph.add_vertex(child)
# Create an edge of child and parent
graph.add_edge(child,parent)
# Apply BFS
# Initialize a queue
q = Queue()
# enqueue the starting_node
q.enqueue(starting_node)
# Initialize a visited set
visited = set()
# Set the earliest_ancestor to None
earliest_ancestor = None
# While the queue is not empty
while q.size() > 0:
# Assign the head to the earliest_ancestor
earliest_ancestor = q.dequeue()
# Check if the earliest_ancestor has not been visited
if earliest_ancestor not in visited:
# If not visited,get the neighbors
neighbors = graph.get_neighbors(earliest_ancestor)
# Iterate the neighbors and enqueue
for neighbor in neighbors:
q.enqueue(neighbor)
# Add the earliest_ancestor to the visited
visited.add(earliest_ancestor)
# If the earliest_ancestor at this point is still the starting_node, yeye dey smell
if earliest_ancestor == starting_node:
# Return -1
return -1
else:
# Return the earliest_ancestor
return earliest_ancestor | true |
7094a2cb97ee65161af28d73c8610185cd91c752 | avin82/Python_foundation_with_data_structures | /swap_alternate.py | 1,095 | 4.59375 | 5 | # PROGRAM swap_alternate:
'''
Given an array of length N, swap every pair of alternate elements in the array.
You don't need to print or return anything, just change in the input array itself.
Input Format:
Line 1 : An Integer N i.e. size of array
Line 2 : N integers which are elements of the array, separated by spaces
Output Format:
Elements after swapping, separated by space
Sample Input 1:
6
9 3 6 12 4 32
Sample Output 1:
3 9 12 6 32 4
Sample Input 2:
9
9 3 6 12 4 32 5 11 19
Sample Output 2:
3 9 12 6 32 4 11 5 19
'''
#########################
# Swap Alternate Module #
#########################
def swap_alternate(li):
i = 0
while i + 1 <= len(li) - 1:
# DO
li[i], li[i + 1] = li[i + 1], li[i]
i = i + 2
# ENDWHILE;
for element in li:
# DO
print(element, end=" ")
# ENDFOR;
# END swap_alternate.
################
# Main Program #
################
n = int(input("Input the size of the array (or list, separated by space): \n"))
li = [int(x) for x in input("Input the elements of the array (or list, separated by space): \n").split()]
swap_alternate(li)
# END.
| true |
f3950dd5cf075f54278cd721781cceec557ac1fc | avin82/Python_foundation_with_data_structures | /bubble_sort.py | 1,020 | 4.5625 | 5 | # PROGRAM bubble_sort:
'''
Given a random integer array. Sort this array using bubble sort.
Change in the input array itself. You don't need to return or print elements.
Input format:
Line 1 : Integer N, Array Size
Line 2 : Array elements (separated by space)
Constraints :
1 <= N <= 10^3
Sample Input 1:
7
2 13 4 1 3 6 28
Sample Output 1:
1 2 3 4 6 13 28
Sample Input 2:
5
9 3 6 2 0
Sample Output 2:
0 2 3 6 9
'''
######################
# Bubble Sort Module #
######################
def bubble_sort(li):
for i in range(len(li)):
# DO
for j in range(len(li) - i - 1):
# DO
if li[j] > li[j + 1]:
# THEN
li[j], li[j + 1] = li[j + 1], li[j]
# ENDIF;
# ENDFOR;
# ENDFOR;
return li
# END bubble_sort.
################
# Main Program #
################
n = int(input("Input the size of array (or list): \n"))
li = [int(x) for x in input("Input the elements of array (or list, separated by space): \n").split()]
for element in bubble_sort(li):
# DO
print(element, end=" ")
# ENDFOR;
# END.
| true |
edfee79b2601268c1de74fbfbd9e40a7260451b4 | avin82/Python_foundation_with_data_structures | /array_intersection.py | 1,456 | 4.28125 | 4 | # PROGRAM array_intersection:
'''
Given two random integer arrays of size m and n, print their intersection. That is, print all the elements that are present in both the given arrays.
Input arrays can contain duplicate elements.
Note : Order of elements are not important
Input format:
Line 1 : Array 1 Size
Line 2 : Array 1 elements (separated by space)
Line 3 : Array 2 Size
Line 4 : Array 2 elements (separated by space)
Output format:
Print intersection elements in different lines
Constraints :
1 <= m, n <= 10^3
Sample Input 1:
6
2 6 8 5 4 3
4
2 3 4 7
Sample Output 1:
2
4
3
Sample Input 2:
4
2 6 1 2
5
1 2 3 4 2
Sample Output 2:
2
2
1
'''
##################################
# Find Array Intersection Module #
##################################
def find_array_intersection(li_m, li_n):
i = 0
while i < len(li_m) and len(li_n) > 0:
# DO
if li_m[i] in li_n:
# THEN
print(li_m[i])
li_n.remove(li_m[i])
# ENDIF;
i = i + 1
# ENDWHILE;
# END find_array_intersection.
################
# Main Program #
################
m = int(input("Input the size of the first array (or list): \n"))
li_m = [int(x) for x in input("Input the elements of the first array (or list, separated by space): \n").split()]
n = int(input("Input the size of the second array (or list): \n"))
li_n = [int(x) for x in input("Input the elements of the second array (or list, separated by space): \n").split()]
find_array_intersection(li_m, li_n)
# END.
| true |
9e7978f32832e2912c2136be6adb0de6c81f2ad3 | avin82/Python_foundation_with_data_structures | /find_reverse_of_num.py | 754 | 4.5 | 4 | # PROGRAM find_reverse_of_num:
'''
Write a program to generate the reverse of a given number N. Print the corresponding reverse number.
Input format:
Integer N
Constraints:
Time Limit: 1 second
Output format:
Corresponding reverse number
Sample Input 1:
1234
Sample Output 1:
4321
Sample Input 2:
1980
Sample Output 2:
891
'''
#################################
# Find Reverse Of Number Module #
#################################
def find_reverse_of_num():
num = int(input("Input the number to calculate its reverse: \n"))
rev = 0
while num != 0:
# DO
rev = rev * 10 + num % 10
num = num // 10
# ENDWHILE;
return rev
# END find_reverse_of_num.
################
# Main Program #
################
print(find_reverse_of_num())
# END.
| true |
4611752ec19471a7bb892b4c32c689e2ae4f8977 | avin82/Python_foundation_with_data_structures | /check_num_in_array_recursive.py | 1,183 | 4.15625 | 4 | # PROGRAM check_num_in_array_recursive:
'''
Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false.
Do this recursively.
Input Format:
Line 1 : An Integer N i.e. size of array
Line 2 : N integers which are elements of the array, separated by spaces
Line 3 : Integer x
Output Format:
true or false
Constraints:
1 <= N <= 10^3
Sample Input:
3
9 8 10
8
Sample Output:
true
'''
#######################################
# Check Num In Array Recursive Module #
#######################################
def check_num_in_array_recursive(arr, num):
if len(arr) == 1:
# THEN
return arr[0] == num
# ENDIF;
return (arr[0] == num) or check_num_in_array_recursive(arr[1:], num)
# END check_num_in_array_recursive.
################
# Main Program #
################
n = int(input("Input the size of array (or list): \n"))
arr = [int(x) for x in input("Input the elements of array (or list, separated by space): \n").split()]
num = int(input("Input the number to be searched for in the array provided above: \n"))
if check_num_in_array_recursive(arr, num):
# THEN
print('true')
else:
print('false')
# ENDIF;
# END.
| true |
ec10db1087d697597551771bc74c157018212c46 | avin82/Python_foundation_with_data_structures | /largest_column_sum_2d_array.py | 1,204 | 4.125 | 4 | # PROGRAM largest_column_sum_2d_array:
'''
Find the column id of the column in a 2D array with largest sum of elements.
Note: Assume that all columns are of equal length.
Input Format:
Line 1: Two integers m and n (separated by space)
Line 2: Matrix elements of each row (separated by space)
Output Format:
Column id of the column with largest sum of elements
Sample Input:
3 4
1 2 3 4 8 7 6 5 9 10 11 12
Sample Output:
3
'''
##########################################
# Find Column Id With Largest Sum Module #
##########################################
def find_largest_column_sum_2d_array(li):
max_sum, col_id_with_max_sum = - float("inf"), - float("inf")
for j in range(len(li[0])):
# DO
sum = 0
for element in li:
# DO
sum = sum + element[j]
# ENDFOR;
if sum > max_sum:
# THEN
max_sum, col_id_with_max_sum = sum, j
# ENDIF;
# ENDFOR;
return col_id_with_max_sum
# END find_largest_column_sum_2d_array.
################
# Main Program #
################
m, n = (int(i) for i in input().strip().split(' '))
l = [int(i) for i in input().strip().split(' ')]
arr = [[l[(j*n)+i] for i in range(n)] for j in range(m)]
print(find_largest_column_sum_2d_array(arr))
# END.
| true |
2bd0589eef540f182bc9e1018e0d2294a2aba576 | avin82/Python_foundation_with_data_structures | /row_wise_sum_2d_array.py | 971 | 4.21875 | 4 | # PROGRAM row_wise_sum_2d_array:
'''
Given a 2D integer array of size M*N, find and print the sum of ith row elements separated by space.
Input Format:
Line 1 : Two integers M and N (separated by space)
Line 2 : Matrix elements of each row (separated by space)
Output Format:
Sum of every ith row elements (separated by space)
Constraints:
1 <= M, N <= 10^3
Sample Input:
4 2
1 2 3 4 5 6 7 8
Sample Output:
3 7 11 15
'''
########################################
# Find Row Wise Sum Of 2d Array Module #
########################################
def rowWiseSum(arr):
res = []
for row in arr:
# DO
sum = 0
for element in row:
# DO
sum = sum + element
# ENDFOR;
res.append(sum)
# ENDFOR;
return res
################
# Main Program #
################
m, n = (int(i) for i in input().strip().split(' '))
l = [int(i) for i in input().strip().split(' ')]
arr = [[l[(j*n)+i] for i in range(n)] for j in range(m)]
l = rowWiseSum(arr)
print(*l)
# END.
| true |
a8b5f7ee0be1f8e6e198857a2951b86d4eb20a19 | avin82/Python_foundation_with_data_structures | /rotate_array.py | 1,129 | 4.53125 | 5 | # PROGRAM rotate_array:
'''
Given a random integer array of size n, write a function that rotates the given array by d elements (towards left).
Change in the input array itself. You don't need to return or print elements.
Input format:
Line 1 : Integer n (Array Size)
Line 2 : Array elements (separated by space)
Line 3 : Integer d
Output Format:
Updated array elements (separated by space)
Constraints :
1 <= N <= 1000
1 <= d <= N
Sample Input:
7
1 2 3 4 5 6 7
2
Sample Output:
3 4 5 6 7 1 2
'''
#######################
# Rotate Array Module #
#######################
def rotate_array(arr, d):
new_tail = arr[:d]
for i in range(d, len(arr)):
# DO
arr[i - d] = arr[i]
# ENDFOR;
for i in range(d):
# DO
arr[i - d] = new_tail[i]
# ENDFOR;
# END rotate_array(arr, d).
n = int(input("Input the size of array (or list): \n"))
arr = [int(x) for x in input("Input the elements of array (or list, separated by space): \n").split()]
d = int(input("Input the number of elements (positive integer value) by which the array (or list) needs to be rotated towards the left: \n"))
rotate_array(arr, d)
print(*arr)
# END.
| true |
6848e1f8170f7c654e3c39b3abc276a8b13d0cde | avin82/Python_foundation_with_data_structures | /print_1_to_n.py | 381 | 4.1875 | 4 | # PROGRAM print_1_to_n:
################
# Print Module #
################
def print_till_num():
num = int(input("Input number till which you want to print all numbers starting from 1: \n"))
count = 1
while count <= num:
# DO
print(count)
count = count + 1
# ENDWHILE;
# END print_till_num.
################
# Main Program #
################
print_till_num()
# END.
| true |
4ff603e25d455dd4a034739c41b4e11bcc982449 | avin82/Python_foundation_with_data_structures | /print_even_between_1_to_n.py | 517 | 4.375 | 4 | # PROGRAM print_even_between_1_to_n:
#####################
# Print Even Module #
#####################
def print_even_till_num_inclusive():
num = int(input("Input number to print all the even numbers between 1 and the entered number both inclusive: \n"))
start = 1
while start <= num:
# DO
if start % 2 == 0:
# THEN
print(start)
# ENDIF;
start = start + 1
# ENDWHILE;
# END print_even_till_num_inclusive.
################
# Main Program #
################
print_even_till_num_inclusive()
# END.
| true |
55b84355e66a06f831fc6d7b251f9d41aea28824 | avin82/Python_foundation_with_data_structures | /num_pattern_four.py | 738 | 4.34375 | 4 | # PROGRAM num_pattern_four:
'''
Print the following pattern for the given N number of rows.
Pattern for N = 4
1234
123
12
1
Input format:
Integer N (Total no. of rows)
Output format:
Pattern in N lines
Sample Input:
5
Sample Output:
12345
1234
123
12
1
'''
###############################
# Print Number Pattern Module #
###############################
def print_num_pattern():
n = int(input("Input the number of rows to print the desired number pattern: \n"))
p = n
i = 1
while i <= n:
# DO
j = 1
while j <= p:
# DO
print(j, end="")
j = j + 1
# ENDWHILE;
p = p - 1
print()
i = i + 1
# ENDWHILE;
# END print_num_pattern.
################
# Main Program #
################
print_num_pattern()
# END.
| true |
5ae50bd68d0f3bb83b1d800afd6985f79c7a5ca3 | evanlamberson/Get-Programming-Python | /Unit 2/Lesson10Q1.py | 1,148 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 11:49:04 2020
@author: evanlamberson
"""
### Lesson 10 Q10.1
# Write a program that initializes the string word = "echo", the empty tuple
# t = (), and the integer count = 3. Then, write a sequence of commands by
# using the commands you learned in this lesson to make t = ("echo", "echo",
# "echo", "cho", "cho", "cho", "ho", "ho", "ho", "o", "o", "o") and print it.
# The original word is added to the end of the tuple, and then the original
# word without the first letter is added to the tuple, and so on. Each
# substring of the original word gets repeated count number of times.
## Method 1
# initialize vars
word = "echo"
t = ()
count = 3
#add word to tuple, then shorten word
t += (word,) * count
word = word[1:]
t += (word,) * count
word = word[1:]
t += (word,) * count
word = word[1:]
t += (word,) * count
print("Method 1:", t)
## Method 2
# initialize vars
word = "echo"
t = ()
count = 3
# while loop to clean up Method 1
i = 1
length = len(word)
while i <= length:
t += ((word,) * count)
word = word[1:]
i += 1
print("Method 2:", t)
| true |
23275c80bbc961da2e0a3ae055aef01dfd8aa970 | KitsuneNoctus/test_cases_apr15 | /problem_one.py | 1,508 | 4.28125 | 4 | '''
Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a
repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
lumberjacks
background
downstream
six-year-old
The word isograms, however, is not an isogram, because the s repeats.
Pseudo:
- function takes in a string
- Create a new list
- Loop through the string
-- if character is in the new list
--- return False
-- else:
--- append character to the new list
- return True
'''
def is_isogram(text):
''' Check if a string is an isogram (no letters repeat)'''
# for edges Cases --- if letters repeat, but have different casing, without .lower(), it returns True
# text = text.lower()
# Edge case of no text at all
# if text == "":
# return False
#-
list = []
for char in text:
if char in list:
return False
else:
list.append(char)
return True
#Good Test cases
print("Good Tests")
print(is_isogram("lumberjacks"))
print(is_isogram("background"))
print(is_isogram("isograms"))
#
# #Bad Test Cases
# print("Bad Test")
# print(is_isogram(12456)) int isnt iterable
# print(is_isogram(124-5+6))
#Edge Cases
# list = ["a",7,"c"]
# print(is_isogram(list))
# print(is_isogram("iSograms"))
# print(is_isogram("")) #return true
# print(is_isogram("1234567890qwertyuiopasdfghjklzxcvbnm,./;[]{}")) - Impossible to go too long with normal characters
| true |
21a26951cef5a26ec8a74a8ab0c5a639b1c835a0 | ChiragPatelGit/PythonLearningProjects | /Numbers_Processor.py | 416 | 4.1875 | 4 | # Numbers Processor
line = input("Enter a line of numbers - separate them with spaces:")
strings = line.split()
total = 0
substr =''
# print("strings is: ", strings)
try:
for substr in strings:
total += float(substr)
if len(strings) <= 0:
print("There was nothing to total")
else:
print(f"The total is: {total}")
except:
print(f"{substr} is not a number") | true |
893a41c7e43a09215a51fd1e2f5e62b55d402d89 | sanatanghosh/python-programs | /basic/nestedifelse.py | 208 | 4.28125 | 4 | x =int(input("enter a number"))
if x>=0:
if x == 0:
print("the number is neither positive nor negative")
else:
print("the number is positive")
else:
print("the number is negative") | true |
75b4368dce79e4beebd0fd3771ac7bcaa1aadfbf | albertogeniola/Corso-Python-2019 | /Lecture 6/0. Simple adder.py | 365 | 4.125 | 4 | print("I am a nice adder. Please input two numbers and I will sum them")
addend_1 = input("First number:")
addend_2 = input("Second number:")
if not addend_1.isdigit() or not addend_2.isdigit():
print("Sorry: one of the inputs does not seem to be a valid integer number.")
else:
result = int(addend_1) + int(addend_2)
print("Result: {}".format(result))
| true |
a874557ed91313e3f4737e4c268e57053c771675 | AyanUpadhaya/Basic-Maths | /primenumber.py | 426 | 4.15625 | 4 | #Python Program to Find Prime Number using For Loop
#Any natural number that is not divisible by any other number except 1 and itself
#called Prime Number.
user_num=int(input("Enter a number:"))
def is_prime(num):
count=0
for i in range(2,(num//2+1)):
if num%i==0:
count+=1
break
if count==0 and num!=1:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
is_prime(user_num)
| true |
0418a7679705377379b20f6364f66a708b530126 | Kireetinayak/Python_programs | /Programs/Map/Find length.py | 404 | 4.25 | 4 | #The map() function applies a given function to each item of an iterable
def myfunc(n):
return len(n)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print((list(x)))
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
print(list(x))
def myfunc(n):
return n.count("k")
x = map(myfunc, "aabcdefghijklmnopqrstuvwxyz")
print(list(x)) | true |
ec1a3f80df71a70088ab4833f709f0d842d43e8a | lalit97/DSA | /graph/topological-practice.py | 993 | 4.1875 | 4 | '''
https://www.youtube.com/watch?v=n_yl2a6n7nM
https://www.geeksforgeeks.org/topological-sorting/
https://practice.geeksforgeeks.org/problems/topological-sort/1
https://medium.com/@yasufumy/algorithm-depth-first-search-76928c065692
'''
def topoSort(n, graph):
visited = set()
stack = []
# given that node are between 0 and n-1
for node in range(n): # now works for disconnected graphs
if node not in visited:
dfs_topolo(graph, node, visited, stack)
return stack[::-1]
def dfs_topolo(graph, node, visited, stack):
if node not in visited:
visited.add(node)
for neighbour in graph[node]:
dfs_topolo(graph, neighbour, visited, stack)
stack.append(node)
if __name__ == '__main__':
graph = {
'A' : ['B','G'],
'B' : ['C'],
'C' : ['A','D'],
'D' : ['E', 'F'],
'E' : [],
'F' : [],
'G' : ['C']
}
n = 7
ans = topoSort(n, graph)
print(ans) | true |
c6f22a8617bdb7a869f72691c2b2902cb3daf719 | lgomezm/daily-coding-problem | /python/problem02.py | 640 | 4.15625 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element
# at index i of the new array is the product of all the numbers in the
# original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output
# would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected
# output would be [2, 3, 6]
def evaluate(numbers):
p = 1
for n in numbers:
p = p * n
l = []
for n in numbers:
l.append(p / n)
return l
line = input()
numbers = []
for s in line.split(' '):
numbers.append(int(s))
print(evaluate(numbers)) | true |
2d5b885fd31a1e2761d76751b70ce097a49c59f7 | lgomezm/daily-coding-problem | /python/problem08.py | 1,412 | 4.28125 | 4 | # This problem was asked by Google.
# A unival tree (which stands for "universal value") is a tree where
# all nodes under it have the same value.
# Given the root to a binary tree, count the number of unival subtrees.
# For example, the following tree has 5 unival subtrees:
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1 1
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def count_unival_trees(node):
if not node:
return False, 0, -1
elif not node.left and not node.right:
return True, 1, node.value
else:
is_unival_l, count_l, value_l = count_unival_trees(node.left)
is_unival_r, count_r, value_r = count_unival_trees(node.right)
if is_unival_l and is_unival_r and node.value == value_l and node.value == value_r:
return True, 1+count_l+count_r, node.value
elif is_unival_l and not node.right and node.value == value_l:
return True, 1+count_l, node.value
elif is_unival_r and not node.left and node.value == value_r:
return True, 1+count_r, node.value
else:
return False, count_l+count_r, -1
print(count_unival_trees(Node(1)))
print(count_unival_trees(Node(1).left))
print(count_unival_trees(Node(0, left=Node(1), right=Node(0, left=Node(1, Node(1), Node(1)), right=Node(0))))) | true |
e53d9addeb038d020ce876f0cf59e0c2aa8fe5df | vishalpatil0/Python-cwh- | /class in python.py | 845 | 4.21875 | 4 | #class is nothing but a template to store data
#object is the instance of the class by using object we can acces the elemnt of the class
class student:
no_of_leaves=9
pass #pass means nothing
vishal=student() #this is the way to create object in python
namrata=student()
print(f"memory location of object = {vishal}\n memory location of object = {namrata}")
vishal.name='Vishal Gajanan Patil'
vishal.age=20
vishal.addr='Kurha'
namrata.name="Namrata Laxman Badge"
namrata.age=20
namrata.addr="pune"
list1=[vishal,namrata]
vishal.no_of_leaves=10
for i in list1:
print(i.name)
print(i.age)
print(i.addr)
print(i.no_of_leaves)
print(vishal.__dict__) #__dict__ this function helps to see all the atributes which are presents in object
print(namrata.__dict__) #__dict__ this function helps to see all the atributes which are presents in object
| true |
0c052658817903571506e47e54de3ee109626501 | noelleirvin/PythonProblems | /Self-taught Programmer/Ch7/Ch7_challenges.py | 1,121 | 4.28125 | 4 | #CHAPTER 7
# 1. Print each item in the following list
listOfItems = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]
for show in listOfItems:
print(show)
# 2. Print all numbers from 25 to 50
# for i in range(25, 51):
# print(i)
# 3. Print each item in the list from the first challenge and their indexes
for i, show in enumerate(listOfItems):
print(show + ' ' + str(i))
# 4. Write a program with an infinite loop (with the option to type q to quit) and a list
# of numbers. Each time through the loop ask the user to guess a number on the list and tell them
# whether or not they guessed correctly
while True:
print("type q to quit")
x = input("Number:")
list = [ "1", "2", "3"]
if x in list:
print("You got it")
elif x == "q":
break;
else:
print("wrong")
# 5. Mulitply all the numbers in the list [ 8, 19, 148, 4] with all the numbers
# in the list [9, 1, 33, 83] and append each result to a third list
thirdList = []
for x in [8, 19, 148, 4]:
for y in [9, 1, 33, 83]:
thirdList.append(x * y)
print(thirdList)
| true |
f1468cee8de26ee04f98e0d0678ed42f69ce97a3 | dabideee13/exercises-python | /mod3_act3.py | 851 | 4.46875 | 4 | # mod3_act3.py
"""
Tasks
1. Write a word bank program.
2. The program will ask to enter a word.
3. The program will store the word in a list.
4. The program will ask if the user wants to try again. The user will
input Y/y if Yes and N/n if No.
5. If Yes, refer to step 2.
6. If No, display the total number of words and all the words that
user entered.
"""
yes_list = ['Yes', 'yes', 'Y', 'y']
no_list = ['No', 'no', 'N', 'n']
word_list = []
while True:
word = input("Enter a word: ")
word_list.append(word)
add_word = input("Try again? (Yes or No): ")
while add_word not in (yes_list + no_list):
print("\nInvalid input.")
add_word = input("Try again? (Yes or No): ")
if add_word in yes_list:
continue
elif add_word in no_list:
print(f"\nTotal words: {word_list}")
break
| true |
c42892dd50b96c6463b899870b52fd9ffb868bc0 | sagar412/Python-Crah-Course | /Chapter_8/greet.py | 533 | 4.1875 | 4 | # Program for greeter example using while loop, Chapter 8
def greet(first_name,last_name):
person = f"{first_name} {last_name}"
return person
while True:
print("Please enter your name and enter quit when you are done.")
f_name = input("\n Please enter your first name.")
if f_name == 'quit':
break
l_name = input("\n Please enter your last name")
if l_name == 'quit':
break
formated_name = greet(f_name,l_name)
print(f" Hello {formated_name.title()} welcome to the world of python")
| true |
6e94da1bcafeb70de4cdaab83ae5f5281cdd3182 | rahulbhatia023/python | /08_Operators.py | 1,090 | 4.375 | 4 | # Arithmetic Operators
print(2 + 3)
# 5
print(9 - 8)
# 1
print(4 * 6)
# 24
print(8 / 4)
# 2.0
print(5 // 2)
# Floor Division (also called Integer Division) : Quotient when a is divided by b, rounded to the next smallest whole
# number
# 2
print(2 ** 3) # Exponentiation : a raised to the power of b
# 8
print(10 % 3)
# 1
#######################################################################
# Assignment Operators
x = 2
x += 2
print(x)
# 4
a, b = 5, 6
print(a)
# 5
print(b)
# 6
#######################################################################
# Unary Operators
x = 2
y = -x
print(y)
# -2
#######################################################################
# Relational Operators
a = 5
b = 6
print(a < b)
# True
print(a > b)
# False
print(a == b)
# False
print(a <= b)
# True
print(a >= b)
# False
print(a != b)
# True
#######################################################################
# Logical Operator
a = 5
b = 4
print(a < 8 and b < 5)
# True
print(a < 8 and b < 2)
# False
print(a < 8 or b < 2)
# True
x = True
print(not x)
# False
| true |
2cab37f6a7ea4fab967566286837d961b28a5a1a | MattAllen92/Data-Science-Basics | /Practice and Notes/The Self-Taught Programmer/Second Script.py | 2,479 | 4.21875 | 4 | # 1) Basic Functions
#def square(x, y=5):
# """
# Returns the square of the input
# :param x: int
# """
# return (x ** 2) + y
#
#print square(3)
#print square(4,2)
#print square.__doc__
#def str_to_float(x):
# try:
# return float(x)
# except:
# print("Cannot convert input to float.")
#
#str_to_float("Hello")
#str_to_float("5.32")
#str_to_float(32)
## 2) Containers
## a) Lists (mutable, indexed, ordered)
#test = list()
#test = []
#test.append("green")
#test.append("blue")
#test.append("yellow")
#print test[1]
#test[2] = "red"
#test2 = ["white", "black", "purple"]
#test3 = test + test2
#item = test.pop
#print item
#if "white" in test3:
# print "True"
#if "black" not in test:
# print "False"
#
## b) Tuples (immutable, good for things that never change, can be used as dict keys)
#test_tup = tuple()
#test_tup = ()
#test_tup = ("hello",1,True)
#test_tup = ("hello",) # comma afer ensures it's a tuple and not sth like (9)
#print test_tup[0]
#test_tup[0] = "hello again" # raises exception, tuples are immutable
#if "hello" in test_tup:
# print True
#
## c) Dictionaries
#my_dict = dict()
#my_dict = {}
#my_dict = {"test":1,"test2":2}
#print my_dict["test"]
#my_dict["test2"] = 3
#my_dict["new_test"] = 4
#del my_dict["test"]
#if "test8" in my_dict:
# print True
#else:
# print "not found"
#
## d) Containers within Containers
#tup_of_lists = ([1,2,3],[4,5,6])
#list_of_tups = [(1,"abc",True),(2,"def",False)]
#tup_of_dicts = ({1:"hello",2:"goodbye"}, {3:"ok",4:"not"})
#list_of_dicts = [{1:"hi",2:"bye"}, {3:"hey",4:"see ya"}]
#dict_of_tups = {1:(1,"abc"),2:(2,"def")}
#dict_of_lists = {1:[1,2,3],2:[4,5,6]}
#dict_of_dicts = {1:{1:"hi",2:"bye"}, 2:{3:"ok",4:"not"}}
#
## e) Sets (no order, unique items only, fixed search time [hashable])
#set1 = set([1,2,3])
#set2 = set([2,4,6])
#set3 = set([1,2])
#print len(set1)
#if 1 in set1:
# print True
#if 1 not in set2:
# print True
#if set3.issubset(set1):
# print True
#if set1.issuperset(set3):
# print True
#set4 = set1.union(set2) # combo of both, unique items only
#set5 = set1.intersection(set2) # items common to both only
#set6 = set1.difference(set2) # items unique to set1 only
#set7 = set1.symmetric_difference(set2) # items unique to each, not shared
#print set4, set5, set6, set7
| true |
6066100934e59f803128f3415a1e9a25db9889cd | arahaanarya/PythonCrashCourse2ndEdition.6-1.Person.py | /Main.py | 472 | 4.40625 | 4 | # Use a dictionary to store information about a person
# you know. Store their first name, last name, age, and
# the city in which they live. You should have keys
# such as first_name, last_name, age, and city. Print
# each piece of information stored in your dictionary.
parents = {
"first_name": "Bruce",
"last_name": "Morse",
"age": 74,
"city": "San Diego",
}
for key, value in parents.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
| true |
ad58c95139fd4a8c5da75c239dcbc5d38290312e | ShaneyMantri/Algorithms | /Binary Search/Minimum_Number_of_Days_to_Make_m_Bouquets.py | 2,421 | 4.15625 | 4 | """
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
"""
import sys
class Solution:
def minDays(self, A, m, k):
if m * k > len(A): return -1
left, right = 1, max(A)
while left < right:
mid = (left + right) // 2
flow = bouq = 0
for a in A:
flow = 0 if a > mid else flow + 1
if flow >= k:
flow = 0
bouq += 1
if bouq == m: break
if bouq == m:
right = mid
else:
left = mid + 1
return left
| true |
7be9816c8fdb2e9c859b119dc729eb525b2e861f | danielbrenden/Learning-Python | /RemoveDuplicatesFromList.py | 290 | 4.34375 | 4 | # This program removes duplicates from a list of numbers via the append method and prints the result.
numbers = [2, 4, 5, 6, 5, 7, 8, 9, 9]
unique_numbers = []
for number in numbers:
if number not in unique_numbers:
unique_numbers.append(number)
print (unique_numbers)
| true |
f9b1a50f006459852fb2bc4314a8f23ba191b37b | bhavik89/CourseraPython | /CourseEra_Python/Rock_Paper_Scissors.py | 2,301 | 4.1875 | 4 | #Mini Project 2:
# Rock-paper-scissors-lizard-Spock program
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# library function random is imported to generate random numbers
import random
# helper functions
# This Function converts a number (0-4) to corresponding name
def number_to_name(number):
if number == 0:
name = 'rock'
elif number == 1:
name = 'Spock'
elif number == 2:
name = 'paper'
elif number == 3:
name = 'lizard'
elif number == 4:
name = 'scissors'
else:
name = 'Invalid'
return name
# This function converts a name to the corresponding number
def name_to_number(name):
if name == 'rock':
number = 0
elif name == 'Spock':
number = 1
elif name == 'paper':
number = 2
elif name == 'lizard':
number = 3
elif name == 'scissors':
number = 4
else:
number = 9
return number
# determines winner
def winner(diff_mod5):
if diff_mod5 == 0:
print "Player and computer tie! \n"
elif diff_mod5 <= 2:
print "Player Wins! \n"
else:
print "Computer Wins! \n"
# Main function:
# This function takes the player's choice and
# generates a random guess for computer
# and computes the winner\Tie between two
def rpsls(name):
# converts name to player_number using name_to_number
print "Player chooses %s" %name
player_number = name_to_number(name)
if player_number > 4:
print "ERROR: Incorrect user input!! \n"
return None
# computes random guess for comp_number using random.randrange()
comp_number = random.randrange(0, 5)
print "Computer chooses %s" % number_to_name(comp_number)
# computes difference of player_number and comp_number modulo five
diff_mod5 = (player_number - comp_number) % 5
winner(diff_mod5)
# tests for the program
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
| true |
001932fff07cf23900f82da599f858f4045951f1 | Shubhamrawat5/Python | /iterator-generator.py | 643 | 4.1875 | 4 | #ITERATOR : gives values one by one by next(iterator_object)
l=[6,4,7,9,0]
it = iter(l) #creating iterator object of list
print(next(it)) #next is function to go to next element
print(next(it))
for i in it: #loop with iterator object
print(i)
'''output:- (6 and 4 printed only once)
6
4
7
9
0
[Program finished]'''
#GENERATOR : by yield keyword
#yield generators a iterator and stores the values in the iterator object
def gen(n): #square of 10 natural number
i=1
while i<11:
yield i*i
i+=1
val=gen(10)
print(next(val))
print(next(val))
for i in val:
print(i)
'''output:-
1
4
9
16
25
36
49
64
81
100
[Program finished]''' | true |
f64f2cb09a7d6381ec1eb735d210f686d02eccb7 | decolnz/HS_higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 581 | 4.34375 | 4 | #!/usr/bin/python3
"""
print_square - prints a square with #
size: size of the square
"""
def print_square(size):
"""
Method to print a square
"""
error1 = "size must be an integer"
error2 = "size must be >= 0"
if not (isinstance(size, int)):
raise TypeError(error1)
if size < 0:
raise ValueError(error2)
if not (isinstance(size, float)) and size < 0:
raise TypeError(error1)
for count1 in range(size):
for count2 in range(size):
print("#", end='')
print()
if size == 0:
print()
| true |
eb2b3310bf51435dd8120f3d878bea9f1ac588e2 | vishal-1codes/python | /PYTHON LISTS_AND_DICTIONARIES/Maintaining_Order.py | 392 | 4.40625 | 4 | #In this code we find out index of any element
#using .index("name")
#also we insert element using index and value
#eg - animals.insert(2,"cobra")
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")# Use index() to find "duck"
# Your code here!
animals.insert(duck_index,"cobra")
print(animals) # Observe what prints after the insert operation | true |
1aadd3ce06ed65bb043a63c94fde435c90cd98e5 | vishal-1codes/python | /PRACTICE_MAKES_PERFECT/digit_sum.py | 436 | 4.1875 | 4 | #In below example we first get input as a string then we apply for loop for each element in that can be join with + and also convert string element to int then return total.
def digit_sum(n):
total = 0
string_n = str(n)
for char in string_n:
total += int(char)
return total
#Alternate Solution:
#def digit_sum(n):
# total = 0
# while n > 0:
# total += n % 10
# n = n // 10
# return total
print(digit_sum(1234)) | true |
d829d4b8c7a6f701ce066d40df1ad2f870b78e88 | sachins0023/tarzanskills | /day-2.py | 1,929 | 4.5 | 4 | print("I will now count my chickens: ") #I will now count my chickens:
print("Hens", 25+30/6) #Hens 30.0
print("Roosters",100-25*3%4) #Roosters 97
print("Now I will count the eggs: ") #Now I will count the eggs:
print(3+2+1-5+4%2-1/4+6) #6.75
print("Is it true that 3+2<5-7?") #Is it true that 3+2<5-7?
print(3+2<5-7) #False
print("What is 3+2?",3+2) #What is 3+2? 5
print("What is 5-7?",5-7) #What is 5-7? -2
print("Oh, that's why it's False.") #Oh,that's why it's False
print("How about some more.") #How about some more.
print("Is it greater?",5>-2) #Is it greater? True
print("Is it greater or equal?",5>=-2) #Is it greater or equal? True
print("Is it less or equal?",5<=-2) #Is it less or equal? False
print((25+3)*75.3) #2108.4
print((35/3)*(25+4.9)) #348.833333333333333
from decimal import Decimal
print((Decimal('42.2')+Decimal('37.403'))*(Decimal('7')%Decimal('4')+Decimal('3')-Decimal('2')*Decimal('7'))) #-636.824
print(Decimal('-636.8240000000001')+Decimal('636.824'))
first_name="Sachin"
print(first_name)
first_name=23
print(first_name)
from decimal import Decimal
from fractions import Fraction
string='Happy Birthday'
int=23
float=92.8
decimal_value=99.9
fraction_value=Fraction(475,500)
decimal_value=Decimal(99.9)
bool_value= decimal_value>40
print(string,"Age",int,"Marks",float,"top",Decimal(decimal_value),"percentile","marks fraction",fraction_value,"passed",bool_value)
first_mile=1
second_mile=3
third_mile=1
first_inverse_speed=8*60+15
second_inverse_speed=7*60+12
third_inverse_speed=8*60+15
total_time= first_mile*first_inverse_speed + second_mile*second_inverse_speed + third_mile*third_inverse_speed
time_minutes=total_time/60
time_seconds=total_time%60
print(time_minutes-time_seconds/60,"mins",time_seconds,"seconds")
| true |
1a28f0d4d473cf62088c578f425f40619ecf838c | wtakang/class_2 | /projects/alarm_clock/alarm_clock.py | 973 | 4.1875 | 4 | #!/home/tanyi/development/pythonclass/class_2/projects/alarm_clock/bin/python3
from time import sleep
from datetime import datetime
import winsound
def set_alarm():
print('your current time is:',datetime.now().strftime('%H:%M')) # print the current time to the user before the alarm
min = int(input("Enter number of minutes to set the alarm: "))# get the users alarm time in minutes
sec = min * 60 # convert the minutes to seconds
if min >= 0:
if min == 1:
print("Alarm will ring in " + str(min) + ' minute')
sleep(sec) #make the script to wait for the number of serconds
print("Get up!")
winsound.Beep(1500, 5000)# beep to wake up the user as alarm
else:
print("Alarm will ring in " + str(min) + ' minutes')
sleep(sec)
print("Get up!")
winsound.Beep(1500, 5000)
else:
print("Please enter valid value!")
set_alarm() | true |
eba00dc827e5fdf4bd5098872802f18decbbdf7d | kennyestrellaworks/100-days-of-code-the-complete-python-pro-bootcamp-for-2021 | /Day 3/Day-3-4-Exercise- Pizza Order/day-3-4-exercise-pizza-order.py | 1,308 | 4.25 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L\n")
add_pepperoni = input("Do you want pepperoni? Y or N\n")
extra_cheese = input("Do you want extra cheese? Y or N\n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
small_pizza = 15
medium_pizza = 20
large_pizza = 25
small_pizza_pepperoni = 2
medium_to_large_pizza_pepperoni = 3
if size == "S" or size == "s":
if add_pepperoni == "Y" or add_pepperoni == "y":
final_bill = small_pizza + small_pizza_pepperoni
elif add_pepperoni == "N" or add_pepperoni == "n":
final_bill += small_pizza
print(f"Your final bill is: {final_bill}")
if size == "M" or size == "m":
if add_pepperoni == "Y" or add_pepperoni == "y":
final_bill = medium_pizza + medium_to_large_pizza_pepperoni
elif add_pepperoni == "N" or add_pepperoni == "n":
final_bill += medium_pizza
print(f"Your final bill is: {final_bill}")
if size == "L" or size == "l":
if add_pepperoni == "Y" or add_pepperoni == "y":
final_bill = large_pizza + medium_to_large_pizza_pepperoni
elif add_pepperoni == "N" or add_pepperoni == "n":
final_bill += large_pizza
print(f"Your final bill is: ${final_bill}") | true |
a5f6ff9d546893c2b6552aaaddb324a1bf33b7d9 | kennyestrellaworks/100-days-of-code-the-complete-python-pro-bootcamp-for-2021 | /Day 4/Day-4-3-Exercise- Treasure Map/day-4-3-exercise-treasure-map.py | 781 | 4.28125 | 4 | # 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure?\n")
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
empty = []
for x in position:
empty.append(x)
empty_len = len(empty)
if empty_len <= 2:
row_item = int(empty[0])
column_item = int(empty[1])
if row_item <= 3 and column_item <= 3:
map[column_item - 1][row_item - 1] = "x"
print(f"{row1}\n{row2}\n{row3}")
else:
print("Position not covered.")
else:
print("Position not covered.")
#Write your code above this row 👆
# 🚨 Don't change the code below 👇 | true |
7d92cd6287d39e641878f860c4b17b0b6d6c3048 | GarciaCS2/CSE | /GABRIELLA - GAMES/Beginner Programs/Gabriella - Hangperson, Shorter program (Beginner).py | 2,452 | 4.21875 | 4 | import random
setup = [0, 1, 2, 3]
counted_letters = [] # 0 = right_letter_count, 1 = guesses, 2 = doubles, 3 = letters_required
word_bank = ["cat", "edison", "donut", "zebra", "travel", "humor", "python", "computer", "number", "aerobic",
"math", "cow", "dog", "snow", "cake", "cough", "list", "binary", "code", "person", "nice", "amazing",
"word", "time", "space", "github", "mouse", "dig", "dug", "string", "four", "cookies", "america", "moo",
"goofy", "biology", "program", "update", "bee", "cake", "charm", "turkey", "thanksgiving", "halloween",
"talk", "cast", "friday", "shop", "ballpark", "lines", "true", "false"]
word = random.choice(word_bank) # Choosing the word
setup[1] = int(len(word)*2.5)
for i in range(len(word)): # Figuring out how to detect doubles
count = word.count(word[i])
if word[i] in counted_letters:
setup[1] = setup[1] - 1
elif count > 1:
count = count - 1
setup[2] = setup[2] + count
list.append(counted_letters, word[i])
setup[3] = len(word) - setup[2]
print("This word has %d letters. You have %s tries to find all the letters." % (len(word), setup[1])) # Introduce Game
letter_pos = 0
wrong_letters = [] # Storing the letters
right_letters = []
right_letter_list = []
for i in range(len(word)): # making the display list
list.append(right_letter_list, "*")
while setup[1] > 0 and setup[0] < setup[3]: # Playing the Game
print()
guess_letter = input("Give me a letter")
if guess_letter.lower() in right_letters:
print("Correct, but you already said that letter.")
elif guess_letter == "":
print("What? I can't hear you.")
elif guess_letter in word:
print("Yes, '%s' is in the word." % guess_letter)
setup[1] = setup[1] - 1
right_letter_count = setup[0] + 1
right_letters.insert(0, guess_letter)
elif guess_letter in wrong_letters:
print("You already tried that letter.")
else:
print("No, sorry.")
list.append(wrong_letters, guess_letter)
setup[1] = setup[1] - 1
print("%s tries left." % setup[1])
for i in range(len(word)):
if (word[i]) in right_letters:
right_letter_list[i] = word[i]
print(right_letter_list)
if setup[0] == setup[3]:
print("Game end. You won! You had %s guesses left." % setup[1])
else:
print("Game end. The word was %s. Try again next time." % word)
| true |
f4433e3e99a94d3843f29b63463c1368bd85db17 | clash402/turtle-race | /main.py | 1,161 | 4.25 | 4 | from turtle import Turtle, Screen
import random
# PROPERTIES
screen = Screen()
screen.setup(width=500, height=400)
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
random.shuffle(colors)
turtles = []
pos_y = -145
for color in colors:
turtle = Turtle("turtle")
turtle.shapesize(2)
turtle.color(color)
turtle.penup()
turtle.goto(-210, pos_y)
turtles.append(turtle)
pos_y += 60
# METHODS
def turtle_crossed_finish_line(current_turtle):
if current_turtle.xcor() > 210:
return True
def determine_winner():
if winning_color == user_color:
print(f"You won! The {winning_color} turtle won.")
else:
print(f"You lost. The {winning_color} turtle won.")
# MAIN
user_color = screen.textinput("Make your bet", "Which turtle will win the race? Enter a color: ").lower()
race_is_in_progress = True
while race_is_in_progress:
for turtle in turtles:
turtle.forward(random.randint(0, 10))
if turtle_crossed_finish_line(turtle):
race_is_in_progress = False
winning_color = turtle.pencolor()
determine_winner()
screen.exitonclick()
| true |
53a5767fd1c27c87a91f94bfb7a42ae802ec4136 | Jacquelinediaznieto/PythonCourse | /final-project/final-project.py | 1,531 | 4.15625 | 4 | #Ask tJhe player name and store
player_name = input('What is your name? ')
#This is a list made up of questions and answers dictionaries
questions = [
{"question": "What is the capital of Germany? ",
"answer": "berlin"},
{"question": "What is the capital of Spain? ",
"answer": "madrid"},
{"question": "What is the capital of Colombia? ",
"answer": "bogota"},
{"question": "What is the capital of England,UK? ",
"answer": "london"},
{"question": "What is the capital of Portugal? ",
"answer": "lisbon"}
]
#Welcome the player
print(f"Hello {player_name}, let's start. There are five questions. Good luck!")
def runquiz():
#Start with a scoor of 0
score = 0
#Loop through all the questions - a dictionary in a list
for question in questions:
player_ans = input(question["question"])
player_ans_lower = player_ans.lower()
if player_ans_lower == question["answer"]:
print("Correct!")
score += 1
else:
print("Incorrect")
print(f"Your score is {score}")
#Print the final score
print(f"{player_name} Your final score was {score} out of 5")
while True:
runquiz()
#Ask user if they want to play again?
play_again = input("Would you like to play again? y/n ")
if play_again == "y":
print("runs the function to play again")
else:
print("Thanks for playing, see you again soon")
break | true |
eaa246a72872b0f43a823f09db327c69202a9ad6 | sarkarChanchal105/Coding | /Leetcode/python/Medium/minimum-lines-to-represent-a-line-chart.py | 2,995 | 4.3125 | 4 | """
https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/
2280. Minimum Lines to Represent a Line Chart
Medium
185
368
Add to List
Share
You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:
Return the minimum number of lines needed to represent the line chart.
Example 1:
Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
Output: 3
Explanation:
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.
Example 2:
Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]
Output: 1
Explanation:
As shown in the diagram above, the line chart can be represented with a single line.
Constraints:
1 <= stockPrices.length <= 105
stockPrices[i].length == 2
1 <= dayi, pricei <= 109
All dayi are distinct.
"""
from typing import List
import decimal
class Solution:
def minimumLines(self, stockPrices: List[List[int]]) -> int:
## Step 1: calculete the lenght of the array
n = len(stockPrices)
if n <= 1:
return 0
## Step 2 : sort the array based on X since we have atleast two points
stockPrices = sorted(stockPrices, key=lambda x: x[0])
## Calculate the slope of the first two points
x0, y0 = stockPrices[0][0], stockPrices[0][1]
x1, y1 = stockPrices[1][0], stockPrices[1][1]
prevSlope = (decimal.Decimal(y1 - y0) / decimal.Decimal(x1 - x0)) ## Slope of first two points
i = 1
countoflines = 1 ## So far we have one line
while i < n - 1:
## for each i, calculate the slope between xi, yi and xi+1 , yi+1
x0, y0 = stockPrices[i][0], stockPrices[i][1]
x1, y1 = stockPrices[i + 1][0], stockPrices[i + 1][1]
currentSlope = (decimal.Decimal(y1 - y0) / decimal.Decimal(x1 - x0)) ## slope of the current two points
if currentSlope != prevSlope: ## of the slopes are not matching then we need new line
countoflines += 1
prevSlope = currentSlope ## current slope becomes the previous slope for the next iteration
i += 1 ## increment i for considering the next points
return countoflines
object=Solution()
array=[[1,1],[500000000,499999999],[1000000000,999999998]]
print(object.minimumLines(array)) | true |
7475f1052d034bb82d231b1bc45659bf391b9cc5 | sarkarChanchal105/Coding | /Leetcode/python/Easy/matrix-diagonal-sum.py | 1,521 | 4.40625 | 4 | """
https://leetcode.com/problems/matrix-diagonal-sum/submissions/
1572. Matrix Diagonal Sum
Easy
1204
22
Add to List
Share
Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
"""
from typing import List
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
## Diagonal 1
summary = 0
for i in range(n):
summary += mat[i][i]
## Diagonal 2
for i in range(n - 1, -1, -1):
summary += mat[i][n-i-1]
## if the number of columns is odd. then we have counted the middle element at the cross section
## of both diagonals. Sutract that element from the entire sume
if n % 2 != 0:
idx = n // 2
summary -= mat[idx][idx]
return summary
object=Solution()
array=[[7,3,1,9],[3,4,6,9],[6,9,6,6],[9,5,8,5]]
print(object.diagonalSum(array))
| true |
09cf7d97cc71fa4aba589b07f418609f2a3cd354 | sarkarChanchal105/Coding | /Leetcode/python/Medium/validate-binary-search-tree.py | 1,552 | 4.1875 | 4 | """
https://leetcode.com/problems/validate-binary-search-tree/
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode, lower=float("-inf"), upper=float("inf")) -> bool:
## if reached end of the tree or tree is empty its a valid Binary Tree
if not root:
return True
if root.val <= lower or root.val >= upper: ## if the value at the root is out side the valid limits then return False
return False
check_left = self.isValidBST(root.left, lower, root.val) ## check the. validity of the left sub tree
check_right = self.isValidBST(root.right, root.val, upper) ## check the validity of the right sub tree
return check_left and check_right ## return True or False based on the values returned
| true |
50a0a350fb3aa861a4227044e5ac5e498847875a | Jokers01/Code_Wars | /8kyu/Beginner - Lost Without a Map.py | 391 | 4.1875 | 4 | """
Given and array of integers (x), return the array with each value doubled.
For example:
[1, 2, 3] --> [2, 4, 6]
For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
"""
#answer
def maps(a):
return [ x * 2 for x in a ]
#or
def maps(a):
new_list = []
for x in a:
new_list.append(x*2)
return new_list
| true |
c59add8de30bcc385145236694d7ec330cf386d3 | KristofferFJ/PE | /problems/unsolved_problems/test_196_prime_triplets.py | 1,058 | 4.125 | 4 | import unittest
"""
Prime triplets
Build a triangle from all positive integers in the following way:
1
2 3
4 5 6
7 8 9 1011 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 2829 30 31 32 33 34 35 3637 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
. . .
Each positive integer has up to eight neighbours in the triangle.
A set of three primes is called a prime triplet if one of the three primes has the other two as neighbours in the triangle.
For example, in the second row, the prime numbers 2 and 3 are elements of some prime triplet.
If row 8 is considered, it contains two primes which are elements of some prime triplet, i.e. 29 and 31.
If row 9 is considered, it contains only one prime which is an element of some prime triplet: 37.
Define S(n) as the sum of the primes in row n which are elements of any prime triplet.
Then S(8)=60 and S(9)=37.
You are given that S(10000)=950007619.
Find S(5678027) + S(7208785).
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
e3b20e979229a6f595e54a66003687e9e9de1ea3 | KristofferFJ/PE | /problems/unsolved_problems/test_309_integer_ladders.py | 873 | 4.1875 | 4 | import unittest
"""
Integer Ladders
In the classic "Crossing Ladders" problem, we are given the lengths x and y of two ladders resting on the opposite walls of a narrow, level street. We are also given the height h above the street where the two ladders cross and we are asked to find the width of the street (w).
Here, we are only concerned with instances where all four variables are positive integers.
For example, if x = 70, y = 119 and h = 30, we can calculate that w = 56.
In fact, for integer values x, y, h and 0 < x < y < 200, there are only five triplets (x,y,h) producing integer solutions for w:
(70, 119, 30), (74, 182, 21), (87, 105, 35), (100, 116, 35) and (119, 175, 40).
For integer values x, y, h and 0 < x < y < 1 000 000, how many triplets (x,y,h) produce integer solutions for w?
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
9058eb2ad8a06f152b4e292796b776bc132594af | KristofferFJ/PE | /problems/unsolved_problems/test_152_writing_1slash2_as_a_sum_of_inverse_squares.py | 854 | 4.3125 | 4 | import unittest
"""
Writing 1/2 as a sum of inverse squares
There are several ways to write the number 1/2 as a sum of inverse squares using distinct integers.
For instance, the numbers {2,3,4,5,7,12,15,20,28,35} can be used:
$$\begin{align}\dfrac{1}{2} &= \dfrac{1}{2^2} + \dfrac{1}{3^2} + \dfrac{1}{4^2} + \dfrac{1}{5^2} +\\
&\quad \dfrac{1}{7^2} + \dfrac{1}{12^2} + \dfrac{1}{15^2} + \dfrac{1}{20^2} +\\
&\quad \dfrac{1}{28^2} + \dfrac{1}{35^2}\end{align}$$
In fact, only using integers between 2 and 45 inclusive, there are exactly three ways to do it, the remaining two being: {2,3,4,6,7,9,10,20,28,35,36,45} and {2,3,4,6,7,9,12,15,28,30,35,36,45}.
How many ways are there to write the number 1/2 as a sum of inverse squares using distinct integers between 2 and 80 inclusive?
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
0ff6187cf73b4e3ce59cea63123d4d5e5941bbac | KristofferFJ/PE | /problems/unsolved_problems/test_797_cyclogenic_polynomials.py | 928 | 4.15625 | 4 | import unittest
"""
Cyclogenic Polynomials
A monic polynomial is a single-variable polynomial in which the coefficient of highest degree is equal to 1.
Define $\mathcal{F}$ to be the set of all monic polynomials with integer coefficients (including the constant polynomial $p(x)=1$). A polynomial $p(x)\in\mathcal{F}$ is cyclogenic if there exists $q(x)\in\mathcal{F}$ and a positive integer $n$ such that $p(x)q(x)=x^n-1$. If $n$ is the smallest such positive integer then $p(x)$ is $n$-cyclogenic.
Define $P_n(x)$ to be the sum of all $n$-cyclogenic polynomials. For example, there exist ten 6-cyclogenic polynomials (which divide $x^6-1$ and no smaller $x^k-1$):
giving
Also define
It's given that
$Q_{10}(x)=x^{10}+3x^9+3x^8+7x^7+8x^6+14x^5+11x^4+18x^3+12x^2+23x$ and $Q_{10}(2) = 5598$.
Find $Q_{10^7}(2)$. Give your answer modulo $1\,000\,000\,007$.
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
ae296ed1c5ef3b45bc2997780d61aae7376ab3ee | KristofferFJ/PE | /problems/unsolved_problems/test_726_falling_bottles.py | 1,191 | 4.15625 | 4 | import unittest
"""
Falling bottles
Consider a stack of bottles of wine. There are $n$ layers in the stack with the top layer containing only one bottle and the bottom layer containing $n$ bottles. For $n=4$ the stack looks like the picture below.
The collapsing process happens every time a bottle is taken. A space is created in the stack and that space is filled according to the following recursive steps:
This process happens recursively; for example, taking bottle $A$ in the diagram above. Its place can be filled with either $B$ or $C$. If it is filled with $C$ then the space that $C$ creates can be filled with $D$ or $E$. So there are 3 different collapsing processes that can happen if $A$ is taken, although the final shape (in this case) is the same.
Define $f(n)$ to be the number of ways that we can take all the bottles from a stack with $n$ layers.
Two ways are considered different if at any step we took a different bottle or the collapsing process went differently.
You are given $f(1) = 1$, $f(2) = 6$ and $f(3) = 1008$.
Find $S(10^4)$ and give your answer modulo $1\,000\,000\,033$.
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
75942c440659f556135d1b93074f464bd88cdc1b | KristofferFJ/PE | /problems/unsolved_problems/test_155_counting_capacitor_circuits.py | 1,148 | 4.21875 | 4 | import unittest
"""
Counting Capacitor Circuits
An electric circuit uses exclusively identical capacitors of the same value C.
The capacitors can be connected in series or in parallel to form sub-units, which can then be connected in series or in parallel with other capacitors or other sub-units to form larger sub-units, and so on up to a final circuit.
Using this simple procedure and up to n identical capacitors, we can make circuits having a range of different total capacitances. For example, using up to n=3 capacitors of 60 $\mu$ F each, we can obtain the following 7 distinct total capacitance values:
If we denote by D(n) the number of distinct total capacitance values we can obtain when using up to n equal-valued capacitors and the simple procedure described above, we have: D(1)=1, D(2)=3, D(3)=7 ...
Find D(18).
Reminder : When connecting capacitors C1, C2 etc in parallel, the total capacitance is CT = C1 + C2 +...,
whereas when connecting them in series, the overall capacitance is given by: $\dfrac{1}{C_T} = \dfrac{1}{C_1} + \dfrac{1}{C_2} + ...$
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
60ade4195efa8fbd6cce3ea80f0c9f512b711906 | KristofferFJ/PE | /problems/unsolved_problems/test_796_a_grand_shuffle.py | 790 | 4.125 | 4 | import unittest
"""
A Grand Shuffle
A standard $52$ card deck comprises thirteen ranks in four suits. However, modern decks have two additional Jokers, which neither have a suit nor a rank, for a total of $54$ cards. If we shuffle such a deck and draw cards without replacement, then we would need, on average, approximately $29.05361725$ cards so that we have at least one card for each rank.
Now, assume you have $10$ such decks, each with a different back design. We shuffle all $10 \times 54$ cards together and draw cards without replacement. What is the expected number of cards needed so every suit, rank and deck design have at least one card?
Give your answer rounded to eight places after the decimal point.
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
fd5834f002062fe02f75d86178696cd7886491c6 | KristofferFJ/PE | /problems/unsolved_problems/test_750_optimal_card_stacking.py | 930 | 4.1875 | 4 | import unittest
"""
Optimal Card Stacking
Card Stacking is a game on a computer starting with an array of $N$ cards labelled $1,2,\ldots,N$.
A stack of cards can be moved by dragging horizontally with the mouse to another stack but only when the resulting stack is in sequence. The goal of the game is to combine the cards into a single stack using minimal total drag distance.
For the given arrangement of 6 cards the minimum total distance is $1 + 3 + 1 + 1 + 2 = 8$.
For $N$ cards, the cards are arranged so that the card at position $n$ is $3^n\bmod(N+1), 1\le n\le N$.
We define $G(N)$ to be the minimal total drag distance to arrange these cards into a single sequence.
For example, when $N = 6$ we get the sequence $3,2,6,4,5,1$ and $G(6) = 8$.
You are given $G(16) = 47$.
Find $G(976)$.
Note: $G(N)$ is not defined for all values of $N$.
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
3a6bc780036eba832c5c0d23bf007f45aaf47a57 | KristofferFJ/PE | /problems/archived_old_tries/test_059_xor_decryption.py | 2,606 | 4.28125 | 4 | # Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
# A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
# For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
# Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
# Your task has been made easy, as the encryption key consists of three lower case characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
numbers = open("../../resources/59.txt", "r")
grid = []
for line in numbers:
grid = line.split(",")
alphabet = 'abcdefghijklmnopqrstuvxyz'
potential_keys = []
for letter1 in alphabet:
for letter2 in alphabet:
for letter3 in alphabet:
potential_keys.append(letter1 + letter2 + letter3)
numbers = [int(a) for a in grid]
stuff = [chr(97 ^ a) for a in numbers]
def validate(number):
if (number < 65):
return False
if (number > 90 and number < 97):
return False
if (number > 122):
return False
return True
def decrypt(numbers, key):
result = ''
index = 0
for number in numbers:
this_key = key[index]
decrypted_number = number ^ ord(this_key)
result += chr(decrypted_number)
index = (index + 1) % 3
return result
for character in alphabet:
result = ''
index = 0
for number in numbers:
if index % 3 == 0:
decrypted_number = number ^ ord(character)
result += chr(decrypted_number)
index = index + 1
print(result)
| true |
7598bda86f1d88a5b10fb952862ccbe35f1336db | KristofferFJ/PE | /problems/unsolved_problems/test_066_diophantine_equation.py | 706 | 4.125 | 4 | import unittest
"""
Diophantine equation
Consider quadratic Diophantine equations of the form:
x2 – Dy2 = 1
For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
It can be assumed that there are no solutions in positive integers when D is square.
By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:
32 – 2×22 = 1
22 – 3×12 = 192 – 5×42 = 1
52 – 6×22 = 1
82 – 7×32 = 1
Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.
Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
"""
class Test(unittest.TestCase):
def test(self):
pass
| true |
1fa8ba3ddfd53d736b9699fce9c7e0ad2be30e7c | GeneKao/ita19-assignment | /02/task1.py | 767 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Task 1: Given two vectors, use the cross product to create a set of three orthonormal vectors.
"""
__author__ = "Gene Ting-Chun Kao"
__email__ = "kao@arch.ethz.ch"
__date__ = "29.10.2019"
def orthonormal_bases(u, v):
"""
Generate three base vectors from two vectors
Args:
u: compas.geometry.Vector, first vector
v: compas.geometry.Vector, second vector
Returns:
tuple of compas.geometry.Vector: three normalised vectors as list
"""
return u.unitized(), u.cross(v).cross(u).unitized(), u.cross(v).unitized()
if __name__ == '__main__':
from compas.geometry import Vector
a = Vector(10, 10, 0)
b = Vector(0, 10, 0)
vectors = orthonormal_bases(a, b)
print(vectors)
| true |
7b419d44fa9686983dc3ebf2a9003b764d25e228 | nikadam/HangmanGamePython | /pythonGame.py | 1,938 | 4.15625 | 4 | import random
class HangmanGame(object):
words = ["guessing","apple","television","earphones",'mobile',
"apple","macbook","python","sunset",'sunrise','winter',
"opensource",'rainbow','computer','programming','science',
'python','datascience','mathematics','player','condition',
'reverse','water','river','boardmember']
def start(self):
name = input("Enter your name = ")
print(f"Hello {name}! Welcome to the guessing game!")
self.play()
def play(self):
chances = 10
guesses = ""
index = random.randint(0, len(self.words)-1)
word = self.words[index]
indexes = random.sample(range(0, len(word)), 3)
for i in indexes:
guesses += word[i]
while chances > 0:
won = True
for ch in word:
if ch in guesses:
print(ch, end=" ")
else:
print("_", end=" ")
won = False
if won:
print("\nYou won!")
print(f"Your score is {chances * 10})")
self.playagain() #ask user want to play again
break
# take a guess from the user
guess = input("\nGuess a character: ")
guesses += guess
if guess not in word:
chances -= 1
print("\nWrong Answer!!")
print(f"\nYou have {chances} chances left!")
if chances == 0:
print("You lose!!")
self.playagain() #ask user want to play again
break
def playagain(self):
play = input("Do you want to play again? (Yes/No): ")
if play == "Yes":
self.play()
if __name__ == '__main__':
HangmanGame().start() | true |
4b263f6d53b6a0a58611c8ef8765f309144b2454 | cami20/calculator-2 | /calculator.py | 2,907 | 4.28125 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# Your code goes here
# No setup
# repeat forever:
while True:
# read input
input = raw_input("> ")
# tokenize input
input_string = input.split(" ")
# if the first token is "q":
if input_string[0] == "q":
# quit
break
# else:
else:
try:
# decide which math function to call based on first token
if input_string[0] == "+":
if len(input_string) < 3:
print "I don't understand"
else:
print add_list(input_string[1:])
elif input_string[0] == "-":
if len(input_string) < 3:
print "I don't understand"
else:
print subtract_list(input_string[1:])
elif input_string[0] == "*":
if len(input_string) < 3:
print "I don't understand"
else:
print multiply_list(input_string[1:])
elif input_string[0] == "/":
if len(input_string) > 3:
print "Too many inputs :("
else:
print divide(int(input_string[1]), int(input_string[2]))
elif input_string[0] == "square":
if len(input_string) > 2:
print "Too many inputs :("
else:
print square(int(input_string[1]))
elif input_string[0] == "cube":
if len(input_string) > 2:
print "Too many inputs"
else:
print cube(int(input_string[1]))
elif input_string[0] == "pow":
if len(input_string) > 3:
print "Too many inputs"
else:
print power(int(input_string[1]), int(input_string[2]))
elif input_string[0] == "mod":
if len(input_string) > 3:
print "Too many inputs"
else:
print mod(int(input_string[1]), int(input_string[2]))
elif input_string[0] == "x+":
if len(input_string) > 4:
print "Too many inputs"
else:
print add_mult(int(input_string[1]), int(input_string[2]), int(input_string[3]))
elif input_string[0] == "cubes+":
if len(input_string) > 3:
print "Too many inputs"
else:
print add_cubes(int(input_string[1]), int(input_string[2]))
else:
print "I do not understand."
except:
print "I do not understand"
| true |
f3f4eca9cee37f6e1906840c088e1576421a0911 | fatimaalheeh/python_stack | /_python/assignments/users_with_bank_account.py | 2,858 | 4.28125 | 4 | class BankAccount:
interest=1
rate=1
balance=0
def __init__(self, int_rate=1, balance=0):
self.rate=int_rate
self.balance=balance
def deposit(self, amount):
self.balance+=amount
def withdraw(self, amount):
self.balance-=amount
def display_account_info(self):
print("Account info:","--interest:",self.interest,"--rate:",self.rate,"--balance:",self.balance) #\n new line
def yield_interest(self):
self.balance*=self.rate
class User:
def __init__(self, name, email_address):# now our method has 2 parameters!
self.name = name # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.BankAccount = BankAccount() # added association
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
#change .deposit to .balance :.balance is an attribute of the current child and .deposit is an attribute of the associated class, what ed do is exchange the method of the current class with a similar method from the class it is associated with, that it should iherti that specific method from
self.balance.deposit += amount # the specific user's account decreases by the amount of the value withdrawn, balance is an attribute
def make_withdrwal(self, amount): # takes an argument that is the amount of the deposit
if self.balance.withdraw-amount>=0: #as long as there is some money, withdraw money
self.balance -= amount # the specific user's account decreases by the amount of the value withdrawn
else:
print("Dear Mr.",self.name," ,you tried to withdraw: ",amount, "but you have insufficient balance so your withdrawal has failed. Your current balance is: ",self.account_balance)
def display_user_balance(self): # takes an argument that is the amount of the deposit
pass # the specific user's account decreases by the amount of the value withdrawn
def transfer_money_to_other_user(self,other,amount): # takes an arguments self, other relates to other user and the amount to be transferred
if self.balance - amount >=0: #this is to check if the user got enough money
self.balance-=amount
other.balance+=amount
print("success. Dear",self.name,", you have transferred an amount of: ",amount," to ",other.name,". Your current Balancec is",self.account_balance)
else:
print("Failed. Dear",self.name,", you have tried to transfer an amount of: ",amount," to ",other.name,"but your balance is insufficient.Your current Balancec is",self.account_balance)
me = User("fatima","mail@gmail.com")
me.BankAccount.deposit(34343)
me.BankAccount.withdraw(34343)
me.BankAccount.display_account_info() | true |
4690cd9ff624a71728980ad40c60d686da8fd5c0 | shrenik77130/Repo5Batch22PythonWeb | /#3_Python_Complex_Programs/Program15.py | 241 | 4.25 | 4 | #WAP to input three digit number and print its reverse
no = int(input("Enter 3 Digit Number :")) #276 -> 27 -> 2
rem=no%10 #6
rev=rem
no=no//10
rem=no%10 #7
rev=rev*10+rem
no=no//10
rem=no%10 #2
rev=rev*10+rem
print("Reverse = ",rev)
| true |
3833d1646b0470f64f8258265681cb1d098d9e39 | shrenik77130/Repo5Batch22PythonWeb | /#3_Python_Complex_Programs/Program10.py | 256 | 4.125 | 4 | #WAP to input two numbers and perform Swapping
a=int(input("Enter value of a :"))
b=int(input("Enter value of b :"))
print(f"value of a = {a} and value of b = {b}")
t=a
a=b
b=t
print("After interchange")
print(f"value of a = {a} and value of b = {b}")
| true |
2b44364a2d8bac7c9ac95bafe580d55e2e209613 | paris3200/AdventOfCode | /code/Y2015/D05.py | 2,562 | 4.15625 | 4 | import re
import string
if __name__ != "__main__":
from Y2015 import utils
else:
import utils
def check_three_vowels(text: str) -> bool:
"""Checks if the input text has 3 or more vowels [aeiou]."""
result = re.search("^(.*[aeuio].*){3,}$", text)
if result:
return True
else:
return False
def check_repeat_characters(text: str) -> bool:
"""Checks if two characters repeat one after another in the text."""
chars = list(string.ascii_lowercase)
for char in chars:
regex_str = char + "{2}"
result = re.search(regex_str, text)
if result:
return True
return False
def check_forbidden_characters(text: str) -> bool:
"""Checks if the forbidden characters are found in the text."""
forbidden_characters = ["ab", "cd", "pq", "xy"]
for chars in forbidden_characters:
result = re.search(chars, text)
if result:
return True
return False
def check_letter_pairs(text: str) -> bool:
"""Checks if a pair of letters occurs twice in the text without overlapping."""
result = re.search("(\\w{2}).*?(\\1)", text)
if result:
return True
else:
return False
def check_single_letter_repeat_with_single_char_between(text: str) -> bool:
"""Returns true if a single letter is repeated in the string with exactly one character between the repeats."""
result = re.search("(\\w)\\w{1}?(\\1)", text)
if result:
return True
else:
return False
def check_nice_words(text: str, version="1.0") -> bool:
"""Returns True for nice words, False for naughty words."""
if version == "1.0":
if (
check_repeat_characters(text) is True
and check_three_vowels(text) is True
and check_forbidden_characters(text) is False
):
return True
elif version == "2.0":
if (
check_letter_pairs(text) is True
and check_single_letter_repeat_with_single_char_between(text) is True
):
return True
return False
def part_one():
data = utils.read_lines("data/05.data")
sum = 0
for word in data:
if check_nice_words(word):
sum += 1
return sum
def part_two():
data = utils.read_lines("data/05.data")
sum = 0
for word in data:
if check_nice_words(word, version="2.0"):
sum += 1
return sum
if __name__ == "__main__":
print("Part One")
print(part_one())
print("Part Two")
print(part_two())
| true |
5ad40813a589481b8afa46844746a3eb6e4c9da6 | jessicagamio/calculator | /calculator.py | 2,605 | 4.15625 | 4 | """Calculator
>>> calc("+ 1 2") # 1 + 2
3
>>> calc("* 2 + 1 2") # 2 * (1 + 2)
6
>>> calc("+ 9 * 2 3") # 9 + (2 * 3)
15
Let's make sure we have non-commutative operators working:
>>> calc("- 1 2") # 1 - 2
-1
>>> calc("- 9 * 2 3") # 9 - (2 * 3)
3
>>> calc("/ 6 - 4 2") # 6 / (4 - 2)
3
"""
def calc(s):
"""Evaluate expression."""
# create symbols string
symbol = '*/+-'
# convert s to list
s_list = s.split(' ')
# set current as a empty list
current = []
# while s_list has a value keep looping
while s_list:
# pop the last item in the list
num = s_list.pop()
# if not an operator append number as an int to current list
if num not in symbol:
current.append(int(num))
# if operator is + add each element in current list
elif num == '+':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc += curr
if len(s_list) == 0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '-':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc - curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '*':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc * curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '/':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc // curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED; WELL-CALCULATED! ***\n")
| true |
2e655cc1d809c964b90f44f24d76126547ca0bba | Seabagel/Python-References | /3-working-with-strings/6-counting-all-the-votes-function.py | 1,110 | 4.28125 | 4 | # Create an empty dictionary for associating radish names
# with vote counts
counts = {}
# Create an empty list with the names of everyone who voted
voted = []
# Clean up (munge) a string so it's easy to match against other strings
def clean_string(s):
return s.strip().capitalize().replace(" "," ")
# Check if someone has voted already and return True or False
def has_already_voted(name):
if name in voted:
print(name + " has already voted! Fraud!")
return True
return False
# Count a vote for the radish variety named 'radish'
def count_vote(radish):
if not radish in counts:
# First vote for this variety
counts[radish] = 1
else:
# Increment the radish count
counts[radish] = counts[radish] + 1
for line in open("radishsurvey.txt"):
line = line.strip()
name, vote = line.split(" - ")
name = clean_string(name)
vote = clean_string(vote)
if not has_already_voted(name):
count_vote(vote)
voted.append(name)
print()
print("Results:")
for name in counts:
print(name + ": " + str(counts[name]))
| true |
69b8ecf656173add61531024d7d8ed636e7f6f2b | maiwen/LeetCode | /Python/739. Daily Temperatures.py | 1,904 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2018/7/16 15:22
@author: vincent
Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
"""
class Solution:
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
stack = []
result = [0] * len(temperatures)
stack.append(0)
for i, v in enumerate(temperatures):
while len(stack) !=0 and v > temperatures[stack[-1]]:
pre = stack.pop()
result[pre] = i-pre
stack.append(i)
return result
def dailyTemperatures1(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
# clever solution
# start backwards from the array
# first element is 0
# supporse we have found the correct days from position j+1 to the last
# consider j. two possibilities appear:
# temp[j] < temp[j+1] -> days[j] = 1
# temp[j] >= temp[j+1] -> we can skip to j+1 + days[j+1], since previous days are colder anyway
n = len(temperatures)
days = [0] * n
for i in range(n - 2, -1, -1):
j = i + 1
while True:
if temperatures[i] < temperatures[j]:
days[i] = j - i
break
elif days[j] == 0:
break
j += days[j]
return days | true |
a8141241380818f22c3f8a0f6285a247e01d11ce | NRJ-Python/Learning_Python | /Ch3/dates_start.py | 923 | 4.5 | 4 | #
# Example file for working with date information
# (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
from datetime import date
from datetime import time
from datetime import datetime
def main():
#Date Objects
#Get today's date from today() method from date class
today=date.today()
print("Today's date is :",today)
#Print out date's individual components
print("Date Components :",today.day,today.month,today.year)
#Retrieve today's weekday (0=Monday , 6=Sunday)
print("Today's weekday is",today.weekday())
#Get today's date and time from datetime class
today=datetime.now()
print("The date and time is :",today)
#Get the current time
t=datetime.time(datetime.now())
print("The current time is :",t)
#Getting day number and day
wd=date.weekday(today)
print("Today's day number is %d" % wd)
day=["Mon", "Tue" ,"Wed"]
print("And the days is ",day[wd])
if __name__ == "__main__":
main();
| true |
ff407d313085cd40426d61ffc481ffc44acb0f71 | srczhou/ProficientPython | /palindrome_linked_list.py | 2,355 | 4.21875 | 4 | #!/usr/bin/env python3
import sys
class ListNode:
def __init__(self, data=0, next_node=None):
self.data = data
self.next = next_node
#from reverse_linked_list_iterative import reverse_linked_list
def reverse_singly_list(L):
if not L:
return None
dummy_head = ListNode(0, L)
while L.next:
temp = L.next
dummy_head.next, L.next, temp.next = (temp, temp.next, dummy_head.next)
return dummy_head.next
def is_linked_list_a_palindrome(L):
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# Compares the first half and the reversed second half lists.
# if n is odd, the first half will go one step more step, but same result.
first_half_iter, second_half_iter = L, reverse_singly_list(slow)
while second_half_iter and first_half_iter:
if second_half_iter.data != first_half_iter.data:
return False
second_half_iter, first_half_iter = (second_half_iter.next,
first_half_iter.next)
return True
def main():
head = None
if len(sys.argv) > 2:
# Input the node's value in reverse order.
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
print('Yes' if is_linked_list_a_palindrome(head) else 'No')
assert is_linked_list_a_palindrome(None)
assert is_linked_list_a_palindrome(ListNode(1))
assert is_linked_list_a_palindrome(ListNode(1, ListNode(1)))
assert is_linked_list_a_palindrome(ListNode(1, ListNode(2))) == False
assert is_linked_list_a_palindrome(
ListNode(1, ListNode(3, ListNode(2, ListNode(1))))) == False
head = None
# A link list is a palindrome.
for _ in range(6):
curr = ListNode(1, head)
head = curr
assert is_linked_list_a_palindrome(head)
# Still a palindrome linked list.
head = None
for _ in range(5):
curr = ListNode(1, head)
head = curr
head.next.next.data = 3
assert is_linked_list_a_palindrome(head)
# Not a palindrome linked list.
head = None
for i in reversed(range(1, 5)):
curr = ListNode(i, head)
head = curr
assert is_linked_list_a_palindrome(head) == False
if __name__ == '__main__':
main()
| true |
4d3751389ef8147c17e6bb43da20015a41761864 | narnat/leetcode | /sort_list/sort_list.py | 2,728 | 4.15625 | 4 | #!/usr/bin/env python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
""" Regular recursive solution"""
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
mid = self.middleNode(head)
middle = mid.next
mid.next = None
left = self.sortList(head)
right = self.sortList(middle)
return self.mergeTwoLists(left, right)
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
cur = head
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return head.next
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = prev = head
while fast and fast.next:
fast = fast.next.next
prev = slow
slow = slow.next
return prev
class Solution_2:
""" Bottom up, no recursion solution"""
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
def length(head):
count = 0
while head:
count += 1
head = head.next
return count
def split(head, step):
i = 1
while i < step and head:
head = head.next
i += 1
if not head: return None
middle, head.next = head.next, None
return middle
def mergeTwoLists(l1: ListNode, l2: ListNode, root: ListNode) -> ListNode:
head = root
cur = head
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
while cur.next: cur = cur.next
return cur # Returns the last node
size = length(head)
step = 1
dummy = ListNode()
dummy.next = head
tail = l = r = None
while step < size:
cur = dummy.next
print(cur.val)
tail = dummy
while cur:
l = cur
r = split(l, step)
cur = split(r, step)
tail = mergeTwoLists(l, r, tail)
step *= 2
return dummy.next
| true |
a7198cf7640343771137bec333d57f8b777301b1 | Lyubov-smile/SEP | /Data/task24.py | 499 | 4.4375 | 4 | # 24. Write a Python program to print the elements of a given array.
Sample array : ["Ruby", 2.3, Time.now]
import sys
sv = (sys.version)
sv1 = sv[0:6]
print(sv)
print(sv1,"\n")
import datetime
import array
now = datetime.datetime.now()
dt = datetime.datetime.now().strftime("%H.%M")
print(dt, type(dt))
dt1 = float(dt)
a1 = "Ruby"
a2 = 2.3
a3 = dt1
print(a1, a2, a3)
ar = [a1, a2, a3]
print(ar)
#ar = ar + [dt]
#a = ["Ruby", 2.3, % now.hour, % now.minute"]
#print(a[0],a[1],a[2])
| true |
48f6dc47d99b3f3e679c12a02c44af0edc9885c7 | Lyubov-smile/SEP | /Statements_syntax/task23.py | 696 | 4.25 | 4 | # 23. Write a Python program to check whether a given value appears everywhere in a given array.
# A value is "everywhere" in an array if it presents for every pair of adjacent elements in the array.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
#arr = [1, 3, 5, 2, 7, 5]
value = int(input('Input value which you want to check:'))
for i in range(len(arr)):
if arr[i] == value:
i += 1
inf = 'Every element in array = '
else:
inf = 'Not every element in array = '
break
print(inf, value)
| true |
0ea8922947d6f6b578adf79034feb4af42f49620 | Lyubov-smile/SEP | /Statements_syntax/task14.py | 474 | 4.28125 | 4 | # 14. Write a Python program to check if a given array of integers contains 3 twice, or 5 twice.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
if arr.count(3) == 2 or arr.count(5) == 2:
print('Array of integers contains 3 or 5 twice')
else:
print('Array of integers doesn\'t contains 3 or 5 twice')
| true |
29a7e843519581a67df4ac8a22a3c24512b17662 | Lyubov-smile/SEP | /Data/task04.py | 267 | 4.46875 | 4 | # 4. Write a Python program which accepts the radius of a circle from the user and compute the parameter and area.
r = float(input('Input the radius of a circle: '))
import math
p = 2 * r * math.pi
s = r ** 2 * math.pi
print('P=', p, sep='')
print('S=', s, sep='')
| true |
787360a936fa50633e29dac47347e9c49fb8a520 | Lyubov-smile/SEP | /Statements and syntax/task22.py | 360 | 4.375 | 4 | # 22. Write a Python program to check whether every element is a 3 or a 5 in a given array of integers.
arr = [3, 5, 3, 5, 3]
#[1, 3, 5, 2, 7, 5]
for i in range(len(arr)):
if arr[i] == 3 or arr[i] == 5:
i += 1
inf = 'Every element in array = 3 or 5'
else:
inf = 'Not every element in array = 3 or 5'
break
print(inf) | true |
26100f9023f28861bcb35b8a5fbc20f26bcd15c4 | Lyubov-smile/SEP | /Statements_syntax/task17.py | 427 | 4.375 | 4 | # 17. Write a Python program to get the number of even integers in a given array.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
n = 0
for i in range(len(arr)):
if arr[i] %2 == 0:
n += 1
print('The number of even integers in a given array is', n)
| true |
a45b7b1ea7b5f9ab8d48c6507cd1d9c2f1d57f34 | Lyubov-smile/SEP | /Statements and syntax/task23.py | 425 | 4.21875 | 4 | # 23. Write a Python program to check whether a given value appears everywhere in a given array.
# A value is "everywhere" in an array if it presents for every pair of adjacent elements in the array.
arr = [1, 3, 5, 2, 7, 5]
value = 3
for i in range(len(arr)):
if arr[i] == 3:
i += 1
inf = 'Every element in array = 3'
else:
inf = 'Not every element in array = 3'
break
print(inf)
| true |
62683c96cca30403c196eaf641b2e3e712cb1a1b | Max-Rider/basic-number-guessing-game | /number_guesser.py | 952 | 4.25 | 4 | # Maxwell Rider
# September 23 2020
# A very simple number guessing game where you guess a number between 1 and 100
# and the computer tells you if its too high or too low
# This is simply to help boost my python knowledge as I am very much a beginner as of writting this
from __future__ import print_function
import random
def higherOrLower():
numToGuess = random.randint(1, 100)
userNum = None
while userNum != numToGuess:
userNum = int(input("Guess my number (between 1 and 100): "))
if userNum > numToGuess:
print("To high!")
elif userNum < numToGuess:
print("To low")
else:
break
print("You got my number!")
if __name__ == "__main__":
higherOrLower()
playAgain = input("Want to play again? Y/N: ")
if playAgain == "Y" or playAgain == "y":
higherOrLower()
else:
print("Thanks for playing!") | true |
be28e73a27607679fa8b6a87bc7c8f7c44279367 | avielz/self.py_course_files | /self.py-unit6 lists/6.1.2.py | 579 | 4.28125 | 4 |
def shift_left(my_list):
"""Shift items in the list to the left.
:param my_list: the list with the items
:param last_item: will get the last item from my list
:type my_list: list
:type last_item: string
:return: The list with the items shifted to the left
:rtype: list
"""
last_item = my_list.pop()
my_list.insert(0,last_item)
return(my_list)
the_list = input("Enter items to place in a list: ")
the_list = the_list.split()
print(the_list)
shifted_list = shift_left(the_list)
print("I shifted all the items to the lfet: ",shifted_list)
| true |
2cf335bf134fe8301e05aa9c60ef03d154be10ab | nicholasji/IS211_Assignment1 | /assignment1_part1.py | 1,098 | 4.21875 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 1 Part 1"""
class ListDivideException(Exception):
"""Exception"""
def listDivide(numbers, divide=2):
"""Divisible by divide.
Args:
numbers(list): a list of numbers
divide(integer): a divisor integer default set to 2
Return:
Int: Number of elements divisible by divide.
"""
counter = 0
for number in numbers:
if number % divide == 0:
counter += 1
return counter
def testListDivide():
"""Test of listDivide."""
test1 = listDivide([1, 2, 3, 4, 5])
test2 = listDivide([2, 4, 6, 8, 10])
test3 = listDivide([30, 54, 63, 98, 100], divide=10)
test4 = listDivide([])
test5 = listDivide([1, 2, 3, 4, 5], 1)
bigtest = (test1, test2, test3, test4, test5)
while test1 == int(2):
while test2 == int(5):
while test3 == int(2):
while test4 == int(0):
while test5 == int(5):
return bigtest
else:
raise ListDivideException('List Divide Exception')
| true |
2e88aa71a50bec39e0c64b8466c2f5bc888b7340 | delacruzfranklyn93/Python--Challenge | /PyBank/Bank.py | 2,486 | 4.1875 | 4 | # import libraries
import os
import csv
# Declare the variable that you think you might be using
months = 0
net_total = 0
avg_change = []
greatest_increase = 0
greatest_decrease = 0
current = 0
past = 0
month_increase = ""
month_decrease = ""
# Read in the data into a list
csv_path = os.path.join( "Resources", "budget_data.csv")
txt_outpath = os.path.join("Analysis", "bank.txt")
with open(csv_path) as csv_file:
budget_data = csv.reader(csv_file, delimiter = ",")
header = next(budget_data)
# Create a for statements that will go thorugh each row in the dataset that was read in
for i, row in enumerate(budget_data):
# Increase the month counter for to receive the total number of months
months += 1
# Start adding the profit losses to net_total to get the final net_total
net_total += int(row[1])
# Create the list of profit/losses changes month to month for the entire data set
if i > 0:
current = int(row[1])
avg_change.append(current - past)
monthly_change = current - past
# Check to see if the monthly_change is greater than the greatest_increase thus far and if so update.
if monthly_change > greatest_increase:
month_increase = row[0]
greatest_increase = monthly_change
# Check to see if the monthly_change is less than the greatest_decrease thus far and if so update.
elif monthly_change < greatest_decrease:
month_decrease = row[0]
greatest_decrease = monthly_change
past = int(row[1])
else:
past = int(row[1])
# Calculate the avg_change using sum and len
avg_change = round(sum(avg_change)/len(avg_change), 2)
# Open a new file where we will write our Analysis to and start writing
with open(txt_outpath, "w") as outfile:
outfile.write("Financial analysis\n")
outfile.write("-----------------------------\n")
outfile.write(f"Total Months: {months}\n")
outfile.write(f"Total: ${net_total}\n")
outfile.write(f"Average Change: ${avg_change}\n")
outfile.write(f"Greatest Increase in Profits: {month_increase} (${greatest_increase})\n")
outfile.write(f"Greatest Decrease in Profits: {month_decrease} (${greatest_decrease})\n")
# Open the new file you just created and also print the results on the terminal
with open(txt_outpath) as print_file:
print(print_file.read())
| true |
9fac2d1b600b43bb2e9842ca5028532f5b6feb1b | icimidemirag/GlobalAIHubPythonCourse | /Homeworks/HW1.py | 542 | 4.4375 | 4 | #Create two lists. The first list should consist of odd numbers. The second list is also of even numbers.
#Merge two lists. Multiply all values in the newlist by 2.
#Use the loop to print the data type of the all values in the new list.
#Question 1
oddList = [1,3,5,7,9]
evenList = [0,2,4,6,8]
oddList.extend(evenList)
newList = [x*2 for x in oddList]
for i in newList: #newList elemanlarını yazdırır.
print(i, end=" ")
print("\n")
for i in newList: #newlist elemanlarının typelarını yazdırır.
print(type(i), end=" ")
| true |
c17b1ed61bb9753fcae4633bb059af8f5ffba1e1 | BhargavKadali39/Python_Data_Structure_Cheat_Sheet | /anti_duplicator_mk9000.py | 474 | 4.125 | 4 | List_1 = [1,1,1,2,3,4,4,4,5,5,6,6]
'''
# The old method
List_2 = []
for i in List_1:
if i not in List_2:
List_2.append(i)
print(List_2)
# Still this old method is faster than the other.
# Execution time is: 0.008489199999999975
# That much doesn't matter much,not in the case while working with big amount of data.
'''
# Removing Duplicates using set() and List() methods.
List_3 = list(set(List_1))
print(List_3)
# Execution time is: 0.011315100000000022
| true |
9e10430c18dbdc82851fa9e58dacfb435b749b5e | Dillonso/bio-django | /ReverseComplement/process.py | 547 | 4.25 | 4 | # reverseComplement() function returns the revurse complement of a DNA sequence
def reverseComplement(stringInput):
# Reverse the input
string = stringInput[::-1].upper()
# define pairs dict
pairs = {
'A':'T', 'T':'A',
'G':'C', 'C':'G'
}
# Turn string into list
_list = list(string)
# Define a new empty list
new = []
# Iterate through the sequence list and append corresponding chars from pairs dict to new list
for char in _list:
new.append(pairs[char])
# Join and return the new list as a string
return ''.join(new)
| true |
0f89dafea5460e09641fde03a3bba3f8571e4641 | arjunreddy-001/DSA_Python | /Algorithms/CountdownUsingRecursion.py | 294 | 4.25 | 4 | # use recursion to implement a countdown timer
def countdown(x):
if x == 0:
print("Done!")
return
else:
print(x, "...")
countdown(x - 1)
print("foo") # this code will execute after we reach the top of call stack
countdown(5)
| true |
ffbcd78e46dbb32c172ee980f837c5c32d3a118f | jkorstia/Intro2python | /population.py | 1,284 | 4.125 | 4 | # a program to calculate population size after a user specified time (in years)
# demographic rates are fixed, initial population size is 307357870 selfie taking quokkas
# This script is designed to model quokka populations! Use with other species at your own risk.
# ask user for number of years (inputs as string)
yr_str=input("How many years into the future would you like to predict the population size?")
# convert year string to integer
yr_int=int(yr_str)
# define demographic statistics in seconds
birth_s=7
death_s=13
imm_s=35
# starting population size in quokkas
pop=307357870
# convert demographic statistics to years. 31536000 seconds are in a year (60s*60m*24hrs*365days).
birth_y=birth_s*31536000
death_y=death_s*31536000
imm_y=imm_s*31536000
#since the population changes every year, this must be re-evaluated after each year
#sets up the initial population for the loop
initial_population=pop
count=0
while(count < yr_int):
#counter for number of years
count = count + 1
#figures out the final population after i years
final_population=initial_population+birth_y+imm_y-death_y
#prints out results
print("After", count, "years the population is", final_population)
# readjusts the initial population for subsequent years
initial_population=final_population
| true |
673d177a709a5c019892d42b8579b12e6d13c790 | alexwolf22/Python-Code | /Cities QuickSort/quicksort.py | 1,203 | 4.34375 | 4 | #Alex Wolf
#Quicksort Lab
#functions that swaps two elements in a list based off indexs
def swap(the_list,x,y):
temp=the_list[x]
the_list[x]=the_list[y]
the_list[y]=temp
#partition function that partitions a list
def partition(the_list, p, r, compare_func):
pivot =the_list[r] #sets pivot to last element of list
i=p-1
j=p
while j<r:
if compare_func(the_list[j],pivot):
i+=1
swap(the_list, j,i) #swaps elements at index i and j if j is less than pivot
j+=1
#swaps pivot with index i+1, and returns that index
swap(the_list,r,i+1)
return i+1
#recursive quicksort function
def quicksort(the_list, p, r, compare_func):
if r>p:
#q= index of the list which list was partitioned
q= partition(the_list, p, r, compare_func)
#recursively call quicksort on the two sublist left and right of q
quicksort(the_list, p, q-1, compare_func)
quicksort(the_list, q+1, r, compare_func)
#function that sorts a list based off a specific comparison
def sort(the_list, compare_func):
quicksort(the_list,0,len(the_list)-1, compare_func)
| true |
60fab78905611616e336ccd8a320332099302905 | jjinho/rosalind | /merge_sort_two_arrays/main.py | 1,755 | 4.15625 | 4 | #!/usr/bin/python3
"""
Merge Sort Two Arrays
Given: A positive integer n <= 10^5 and a sorted array A[1..n] of integers
from -10^5 to 10^5, a positive integer m <= 10^5 and a sorted array B[1..m] of
integers from -10^5 to 10^5.
Return: A sorted array C[1..n+m] containing all the elements of A and B.
"""
def main():
n = 0 # number of elements in array A
m = 0 # number of elements in array B
array_a = []
array_b = []
# Parse in.txt
with open('./in.txt') as f:
for i, line in enumerate(f):
if i == 0:
n = int(line.strip())
if i == 1:
array_a = [int(x) for x in line.split()]
if i == 2:
m = int(line.strip())
if i == 3:
array_b = [int(x) for x in line.split()]
# Non-recursive way to solve
array_c = []
while array_a and array_b:
if array_a[0] < array_b[0]:
array_c += [array_a.pop(0)]
else:
array_c += [array_b.pop(0)]
# Can do this because array_a and array_b are already sorted
if array_a:
array_c += array_a
if array_b:
array_c += array_b
for x in array_c:
print(x, end=" ")
print()
# This works but is too
def merge_arrays(array_a, array_b):
if array_a and array_b:
if array_a[0] < array_b[0]:
return [array_a.pop(0)] + merge_arrays(array_a, array_b)
else:
return [array_b.pop(0)] + merge_arrays(array_a, array_b)
else:
if array_a:
return array_a
if array_b:
return array_b
return array_c
if __name__ == '__main__':
main()
| true |
d239f0a21759c9cc3275d87c740fca7a525a094c | jjinho/rosalind | /insertion_sort/main.py | 1,028 | 4.4375 | 4 | #!/usr/bin/python3
"""
Insertion Sort
Given: A positive ingeter n <= 10^3 and an array A[1..n] of integers.
Return: The number of swaps performed by insertion sort algorithm on A[1..n].
"""
def main():
n = 0 # number of integers in array A
array = []
# Parse in.txt
with open('./in.txt') as f:
for i, line in enumerate(f):
if i == 0:
n = int(line)
else:
array = [int(x) for x in line.split()]
print(insertion_sort_swaps(array))
def insertion_sort_swaps(array):
"""Number of times insertion sort performs a swap
Args:
array: An unsorted list that will undergo insertion sort.
Returns:
The number of swaps that insertion sort performed.
"""
swap = 0
for i, x in enumerate(array):
k = i
while k > 0 and array[k] < array[k-1]:
array[k], array[k-1] = array[k-1], array[k]
swap += 1
k -= 1
return swap
if __name__ == '__main__':
main()
| true |
1df31164bee68d1f7a3d824d820f9be602797b3f | ziyang-zh/pythonds | /01_Introduction/01_03_input_and_output.py | 741 | 4.15625 | 4 | #input and output
#aName=input('Please enter your name: ')
aName="David"
print("Your name in all capitals is",aName.upper(),"and has length",len(aName))
#sradius=input("Please enter the radius of the circle ")
radius=2
radius=float(radius)
diameter=2*radius
print(diameter)
#format string
print("Hello")
print("Hello","world")
print("Hello","world",sep="***")
print("Hello","world",end="***\n")
age=18
print(aName,"is",age,"years old.")
print("%s is %d years old."%(aName,age))
price=24
item="banana"
print("The %s costs %d cents"%(item,price))
print("The %+10s costs %5.2f cents"%(item,price))
print("The %+10s costs %10.2f cents"%(item,price))
itemdict={"item":"banana","cost":24}
print("The %(item)s costs %(cost)7.1f cents"%itemdict) | true |
5cf1d1d96e8ea34205a206273b8e8eb7e1a466ca | prohodilmimo/turf | /packages/turf_helpers/index.py | 2,552 | 4.34375 | 4 | from numbers import Number
factors = {
"miles": 3960,
"nauticalmiles": 3441.145,
"degrees": 57.2957795,
"radians": 1,
"inches": 250905600,
"yards": 6969600,
"meters": 6373000,
"metres": 6373000,
"kilometers": 6373,
"kilometres": 6373
}
def radians_to_distance(radians, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from radians to a more friendly unit
:type radians: Number
:param radians: distance in radians across the sphere
:type units: str
:param units: units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: distance
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError('Invalid unit')
return radians * factor
def distance_to_radians(distance, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from a real-world unit into radians
:type distance: Number
:param distance: distance in real units
:type units: str
:param units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: radians
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError("Invalid unit")
return distance / factor
def distance_to_degrees(distance, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from a real-world unit into degrees
:type distance: Number
:param distance: distance in real units
:type units: str
:param units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: degrees
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError("Invalid unit")
return (distance / factor) * 57.2958
__all__ = [
"factors",
"radians_to_distance",
"distance_to_radians",
"distance_to_degrees"
]
| true |
7efe282d6ded5d17da05d420c71f7963be4dc419 | alexacanaan23/COSC101 | /hw03_starter/hw03_turtleword.py | 1,619 | 4.34375 | 4 | # ----------------------------------------------------------
# -------- HW 3: Part 3.1 ---------
# ----------------------------------------------------------
# ----------------------------------------------------------
# Please answer these questions after you have completed this
# program
# ----------------------------------------------------------
# Name: Alexa Canaan
# Time spent on part 3.1: 1.5 hours
# Collaborators and sources: https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.getshapes
# (List any collaborators or sources here.)
# ----------------------------------------------------------
# Write your python program for part 3.1 below:
#set up turtle
import turtle
wn = turtle.Screen()
bob = turtle.Turtle
#set attributes
wn.bgcolor("black")
turtle.pencolor("white")
#get the word to be used
word = input("Word to be spaced in a circular, clockwise position: ")
num = len(word)
angle = 360 / num
#turns turtle to appropriate starting position facing north
turtle.left(90)
#for words with even amount of letters or for words with odd amount
if num % 2 == 0:
for i in word:
turtle.right(angle)
turtle.penup()
turtle.forward(200)
turtle.write(i, True, align="right", font=("Arial", 16, "normal"))
turtle.backward(200)
else:
turtle.right(angle/2)
for i in word:
turtle.penup()
turtle.forward(200)
turtle.write(i, True, align="right", font=("Arial", 16, "normal"))
turtle.backward(200)
turtle.right(angle)
#ending
turtle.hideturtle()
wn.exitonclick()
| true |
83c64368ab1d5b532f42d8a792f6e60c8b195f3c | AndriiSotnikov/py_fcsv | /fcsv.py | 462 | 4.28125 | 4 | """There is a CSV file containing data in this format: Product name, price, quantity
Calculate total cost for all products."""
import csv
def calc_price(filename: str, open_=open) -> float:
"""Multiply every second and third element in the row, and return the sum"""
with open_(filename, 'rt') as file:
reader = csv.reader(file, delimiter=',')
total_cost = sum([float(row[1])*float(row[2]) for row in reader])
return total_cost
| true |
22815c71694d907bb322a2ef02f73bd2d617856d | newbieeashish/LeetCode_Algo | /3rd_30_questions/ConstructTheRectangle.py | 1,202 | 4.34375 | 4 | '''
For a web developer, it is very important to know how to design a
web page's size. So, given a specific rectangular web page’s area,
your job by now is to design a rectangular web page, whose length
L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal to
given target area.
2. The width W should not be larger than the length L, which means
L >= W.
3. The difference between length L and width W should be as small
as possible.
You need to output the length L and the width W of the web page
you designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to
construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to
requirement 3, [4,1] is not optimal compared to [2,2]. So the
length L is 2, and the width W is 2.
'''
import math
def constructRectangle(area):
sqrt_val = int(math.sqrt(area))
l = w = sqrt_val
while (l * w) != area and l > 0 and w > 0:
l += 1
w = area // l
return [l, w] if w > 1 else (area, 1)
print(constructRectangle(4)) | true |
e0e976dd9ec32a240382544cb36bf2f42a59a0df | newbieeashish/LeetCode_Algo | /1st_100_questions/TransposeMatrix.py | 456 | 4.46875 | 4 | '''
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal,
switching the row and column indices of the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
'''
import numpy as np
def TransposeMatrix(A):
return np.transpose(A)
print(TransposeMatrix([[1,2,3],[4,5,6]])) | true |
884106b89d0e1bf8b34f22c55e53894f8b587191 | newbieeashish/LeetCode_Algo | /1st_100_questions/ShortestCompletingWord.py | 1,714 | 4.40625 | 4 | '''
Find the minimum length word from a given dictionary words, which has all the
letters from the string licensePlate. Such a word is said to complete the
given string licensePlate
Here, for letters we ignore case. For example, "P" on the licensePlate still
matches "p" on the word.
It is guaranteed an answer exists. If there are multiple answers, return the
one that occurs first in the array.
The license plate might have the same letter occurring multiple times. For
example, given a licensePlate of "PP", the word "pair" does not complete the
licensePlate, but the word "supper" does.
Example 1:
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters
"S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the
word twice.
Also note that we ignored case for the purposes of comparing whether a
letter exists in the word.
Example 2:
Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.
'''
def ShortestCompletingWord(licensePlate, words):
words.sort(key=len)
licensePlate = licensePlate.lower()
for w in words:
flag = True
for char in licensePlate:
if char.isalpha():
if char not in w or licensePlate.count(char) > w.count(char):
flag = False
if flag == True:
return w
print(ShortestCompletingWord("1s3 456",["looks", "pest", "stew", "show"])) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.