blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
0f4d4cb8f7f45575b5ba4d04757db25a09d0c79e
|
DrFeederino/python_scripts
|
/password_randomizer.py
| 2,820
| 4.28125
| 4
|
"""
This module to randomize passwords for your own or user's usages.
Supports for custom or default (8-16) lengths of passwords. Can be used
both as a standalone program or imported to your project.
Example:
For default length:
$ python3 password_randomizer.py
For a variable length:
$ python3 password_randomizer.py 20
Note: if a variable length is not an integer, it would fallback
to either default length (if used as a standalone program) or
0 if imported.
"""
import random, string, sys
list_of_symbols = list(string.ascii_letters + string.digits)
def check_int(num):
"""Check if arguement is integer.
Arg:
num (int): The only arguement.
Returns:
bool: The return value. True if num is indeed an integer, False otherwise.
"""
if num is not None:
try:
int(num)
return True
except ValueError:
return False
else:
return False
def randomize_password():
"""Randomizes password for default length, which is a
random range from 8 to 16.
Returns:
pswd (str): the string of password.
"""
pswd = ""
pswd_length = random.randrange(8, 17)
for random_char in range(pswd_length):
rnd = random.randrange(len(list_of_symbols))
pswd += list_of_symbols[rnd]
return pswd
def randomize_password_custom(length=0):
"""Randomizes password for variable length, which is by default 0.
Returns:
pswd (str): the string of password.
"""
pswd = ""
if check_int(length):
for random_char in range(length):
rnd = random.randrange(len(list_of_symbols))
pswd += list_of_symbols[rnd]
return pswd
else:
print("Length is not an int.")
raise TypeError
def write_to_file(password="", txt="password.txt"):
"""Writes a string to the file. Passowrd and txt arguements,
by default, are set to empty string and password.txt. Can be modified
during call.
Args:
password (str): the string arguement.
txt (str): the string arguement;
"""
with open(txt, 'w') as f:
f.write(password + "\n")
def main (length=None):
"""Main function to tie every part of module if it is used a standalone
program. It checks the length if it was set, otherwise it is None. Then
it randomizes the password and writes it to a file accordingly.
"""
if check_int(length) and int(length) > 0:
pswd = randomize_password_custom(int(length))
else:
print("Length wasn't recognized as a positive int, fallback to default randomizing.")
pswd = randomize_password()
write_to_file(pswd)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
main()
| true
|
8a4dcdb0d69d1c5ef779637dab859e3c68bde45f
|
Ameliarate16/python-programming
|
/unit-2/homework/highest.py
| 220
| 4.28125
| 4
|
#Given a list of numbers, find the largest number in the list
num_list = [1, 2, 3, 17, 5, 9, 13, 12, 11, 4]
highest = num_list[0]
for number in num_list:
if number > highest:
highest = number
print(highest)
| true
|
180727f1c1ed8730bcf31e95b5b36409fe7da25d
|
Ameliarate16/python-programming
|
/unit-2/functions.py
| 905
| 4.15625
| 4
|
'''
def add_two():
result = 5 + 5
print(result)
#passing arguments
def add_two(a, b):
result = a + b
print(result)
#returning the value
def add_two(a, b):
result = a + b
return result
print(add_two(3, 10))
'''
#write a function that returns the sum of the integers in a list
def sum_list(a_list):
running_sum = 0
for num in a_list:
running_sum += num
return running_sum
#print(sum_list([1,-2,3,4,5]))
# write a function that reverses a string
def rev_string(my_string):
reverse = ""
for char in my_string:
reverse = char + reverse
return reverse
#write a function that finds the intersection of two lists
def intersect_list(list_1, list_2):
intersection = []
for item in list_1:
if item in list_2:
intersection.append(item)
return intersection
print(intersect_list([1,2,3,4,5,"c"],[12,4,1,"c",180,3]))
| true
|
3a4c0903706acf84bb11dbea0ee1fa1b4074c2d1
|
MNikov/Python-Advanced-September-2020
|
/Lists_as_Stacks_and_Queues/06E_balanced_parentheses.py
| 849
| 4.15625
| 4
|
def check_balanced_parentheses(expression):
stack = []
is_valid = True
opening_parentheses = ['(', '[', '{']
closing_parentheses = [')', ']', '}']
for char in expression:
if char in opening_parentheses:
stack.append(char)
elif char in closing_parentheses:
if len(stack) == 0:
is_valid = False
else:
last = stack.pop()
if last == '(' and char == ')':
continue
elif last == '[' and char == ']':
continue
elif last == '{' and char == '}':
continue
else:
is_valid = False
break
if is_valid:
print('YES')
else:
print('NO')
check_balanced_parentheses(input())
| false
|
72e333744b418ea8cb9202e32544bcea68db4c0e
|
MNikov/Python-Advanced-September-2020
|
/Old/Python-Advanced-Preliminary-Homeworks/Exams/Python Advanced Exam Preparation - 18 February 2020/03. Magic Triangle.py
| 460
| 4.125
| 4
|
# ВЗЕТ КОД ОТ СТАРО УПРАЖНЕНИЕ, В STACKOVERFLOW ИМА РАЗЛИЧНИ РЕШЕНИЯ(PASCAL/BINOMIAL TRIANGLE), НО СА С ПО-СЛОЖЕН ПОДХОД
def get_magic_triangle(rows):
triangle = [[1] * i for i in range(1, rows + 1)]
for row in range(2, rows):
for col in range(1, row):
triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col]
return triangle
get_magic_triangle(5)
| false
|
7c5f074599d8e75323b73f52097d1fdc3ef90c18
|
nathanaelchun/code-is-awesome
|
/2020-07-30/Calculator_V1.py
| 430
| 4.1875
| 4
|
number1 = input("Enter a random number:")
operation = input("Enter a operation:")
number2 = input("Enter a random number:")
number1a = int(number1)
number2a = int(number2)
if operation == "+":
answer = number1a+number2a
elif operation == "-":
answer = number1a-number2a
elif operation == "*":
answer = number1a*number2a
elif operation == "/":
answer = number1a/number2a
print(number1,operation,number2,"=",answer)
| false
|
bd947bf7410ca64c210a42e5a278aada8b949131
|
HEroKuma/leetcode
|
/1005-univalued-binary-tree/univalued-binary-tree.py
| 1,029
| 4.21875
| 4
|
# A binary tree is univalued if every node in the tree has the same value.
#
# Return true if and only if the given tree is univalued.
#
#
#
# Example 1:
#
#
# Input: [1,1,1,1,1,null,1]
# Output: true
#
#
#
# Example 2:
#
#
# Input: [2,2,2,5,2]
# Output: false
#
#
#
#
#
# Note:
#
#
# The number of nodes in the given tree will be in the range [1, 100].
# Each node's value will be an integer in the range [0, 99].
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
set_ = set()
def unique(root, set_):
if root is None:
return set_
set_.add(root.val)
set_ = unique(root.left, set_)
set_ = unique(root.right, set_)
return set_
set_ = unique(root, set_)
print(set_)
return True if len(set_) is 1 else False
| true
|
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
|
620d32a561fcd99b33134b584c98fe048b986389
|
avin82/Python_foundation_with_data_structures
|
/find_nth_fibonacci_recursive.py
| 683
| 4.65625
| 5
|
# PROGRAM find_nth_fibonacci_recursive:
'''
Given a number n, find the nth fibonacci number.
Input Format:
A natural number n
Output Format:
nth fibonacci number
Sample Input:
4
Sample Output:
3
'''
#######################################
# Find nth Fibonacci Recursive Module #
#######################################
def find_nth_fib_recursive(n):
if n == 1 or n == 2:
# THEN
return 1
# ENDIF;
return find_nth_fib_recursive(n - 2) + find_nth_fib_recursive(n - 1)
# END find_nth_fib_recursive.
################
# Main Program #
################
n = int(input("Input a natural number n to find the nth fibonacci number: \n"))
print(find_nth_fib_recursive(n))
# END.
| false
|
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
|
2e1812fbdb754cded3d1fb2ac9d6f99abb692947
|
miaviles/Python-Fundamentals
|
/demo/e2.py
| 490
| 4.125
| 4
|
#1st SOLUTION
MIN_CRITERIA = 1
MAX_CRITERIA = 100
while True: # Infinite while loop
number = float(input("Please enter a number between 1 and 100: "))
if MIN_CRITERIA <= number <= MAX_CRITERIA:
break
print(f'The number {number} is between 1 and 100')
#SECOND SOLUTION
# MIN_CRITERIA = 1
# MAX_CRITERIA = 100
# number = float(input())
#
# while not MIN_CRITERIA <= number <= MAX_CRITERIA:
# number = float(input())
#
# print(f'The number {number} is between 1 and 100')
| false
|
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
|
a2f3c7b051cf59c45e4cbe607bcd6b36738d29e4
|
djrgit/coursework
|
/talkpython/100-days-of-code-in-python/my_progress/day_001_datetime_module_nye_countdown.py
| 794
| 4.4375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
from datetime import datetime
from datetime import timedelta
# datetime
today = datetime.today()
print()
print("Today: ", today)
print()
# date
todaydate = date.today()
year = todaydate.year
month = todaydate.month
day = todaydate.day
print("Today's Date: ", todaydate)
print('Current Year: ', year)
print('Current Month: ', month)
print('Current Day: ', day)
print()
# timedelta objects
nye = date(year, 12, 31)
days_til_nye = nye - todaydate
add_a_day = timedelta(days=1)
ny = nye + add_a_day
print("New Year's Day: ", ny)
print()
if nye is not todaydate:
print("There are still " + str(days_til_nye.days) + " days until New Year's Eve...")
else:
print("It's New Year's Eve - Time to party!")
print()
| false
|
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
|
13299a205c42b6ed08901a237056e38d6927d6ed
|
cecilmalone/lista_de_exercicios_pybr
|
/4_exercicios_listas/07_soma_multiplicacao.py
| 464
| 4.28125
| 4
|
"""
7. Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a
multiplicação e os números.
"""
count = 1
numeros = []
soma = 0
multiplicacao = 1
while count <= 5:
numero = int(input("Informe as notas: "))
numeros.append(numero)
count += 1
for numero in numeros:
soma += numero
multiplicacao *= numero
print("Soma: {}".format(soma))
print("Multiplicação: {}".format(multiplicacao))
print("Números: {}".format(numeros))
| false
|
92915ae523567d8f8b3ce1b53d3d1a8b879cdc3c
|
cecilmalone/lista_de_exercicios_pybr
|
/3_estrutura_de_repeticao/25_turma.py
| 697
| 4.125
| 4
|
"""
25. Faça um programa que peça para n pessoas a sua idade, ao final o programa
devera verificar se a média de idade da turma varia entre 0 e 25,26 e 60 e
maior que 60; e então, dizer se a turma é jovem, adulta ou idosa, conforme a
média calculada.
"""
idades = []
idades.append(int(input("Informe a idade: ")))
while 0 not in idades:
idades.append(int(input("Informe a idade: ")))
idades = [int(x) for x in idades]
soma = 0
for n in idades:
soma += n
media = soma / len(idades)
if (media > 0) and (media <= 25):
print("Esta turma é jovem.")
elif (media >= 26) and (media <= 60):
print("Esta turma é adulta.")
elif media > 60:
print("Esta turma é idosa.")
| false
|
82ccbd81e2731115a696f4befa225120274de59e
|
cecilmalone/lista_de_exercicios_pybr
|
/2_estrutura_de_decisao/20_media_tres_notas.py
| 871
| 4.375
| 4
|
"""
20. Faça um Programa para leitura de três notas parciais de um aluno. O programa
deve calcular a média alcançada por aluno e presentar:
a. A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva
média alcançada;
b. A mensagem "Reprovado", se a média for menor do que 7, com a respectiva
média alcançada;
c. A mensagem "Aprovado com Distinção", se a média for igual a 10.
"""
nota_1 = float(input("Informe uma nota: "))
nota_2 = float(input("Informe uma nota: "))
nota_3 = float(input("Informe uma nota: "))
media = (nota_1 + nota_2 + nota_3) / 3
if (media >= 0) and (media < 7):
print("Reprovado, com a média {:.1f}".format(media))
elif (media >= 7) and (media < 10):
print("Aprovado, com a média {:.1f}".format(media))
else:
print("Aprovado com Distinção, com a média {:.1f}".format(media))
| false
|
31cdd9f82986db34c1f9e108a2e0e95ba89d2945
|
cecilmalone/lista_de_exercicios_pybr
|
/3_estrutura_de_repeticao/46_salto_distancia.py
| 2,039
| 4.15625
| 4
|
"""
46. Em uma competição de salto em distância cada atleta tem direito a cinco
saltos. No final da série de saltos de cada atleta, o melhor e o pior
resultados são eliminados. O seu resultado fica sendo a média dos três
valores restantes. Você deve fazer um programa que receba o nome e as cinco
distâncias alcançadas pelo atleta em seus saltos e depois informe a média dos
saltos conforme a descrição acima informada (retirar o melhor e o pior salto e
depois calcular a média). Faça uso de uma lista para armazenar os saltos.
Os saltos são informados na ordem da execução, portanto não são ordenados.
O programa deve ser encerrado quando não for informado o nome do atleta.
A saída do programa deve ser conforme o exemplo abaixo
Atleta Rodrigo Curvêllo
Primeiro Salto 6.5 m
Segundo Salto 6.1 m
Terceiro Salto 6.2 m
Quarto Salto 5.4 m
Quinto Salto 5.3 m
Melhor salto 6.5 m
Pior salto 5.3 m
Média dos demais saltos 5.9 m
Resultado final
Rodrigo Curvêllo 5.9 m
"""
valor_saltos = 0
lista_saltos = []
while nome != "":
nome = input("Informe o nome do atleta: ")
dados = input("Informe a nota dos saltos: ").split()
lista_saltos.append({'Nome': nome, 'Saltos': [float(x) for x in lista_saltos]})
melhor = max(lista_saltos['Saltos'])
pior = min(lista_saltos['Saltos'])
lista_saltos.remove(melhor)
lista_saltos.remove(pior)
for x in lista_saltos['Saltos']:
valor_saltos += x
media = valor_saltos / 3
print(nome)
print()
print("Primeiro Salto {:.f} m".format(lista_saltos['Saltos'][0]))
print("Segundo Salto {:.f} m".format(lista_saltos['Saltos'][1]))
print("Terceiro Salto {:.f} m".format(lista_saltos['Saltos'][2]))
print("Quarto Salto {:.f} m".format(lista_saltos['Saltos'][3]))
print("Quinto Salto {:.f} m".format(lista_saltos['Saltos'][4]))
print()
print("Melhor salto {:.f} m".format(melhor))
print("Pior salto {:.f} m".format(pior))
print("Média dos demais saltos {:.f} m".format(media))
print()
print("Resultado final")
print("{} {:.f} m".format(nome, media))
| false
|
cd5ffbdc46848cf58c13146f5d0cb0b510d7b30c
|
cecilmalone/lista_de_exercicios_pybr
|
/4_exercicios_listas/16_comissoes_vendas.py
| 1,547
| 4.3125
| 4
|
"""
16. Utilize uma lista para resolver o problema a seguir.
Uma empresa paga seus vendedores com base em comissões. O vendedor recebe $200
por semana mais 9 por cento de suas vendas brutas daquela semana.
Por exemplo, um vendedor que teve vendas brutas de $3000 em uma semana recebe
$200 mais 9 por cento de $3000, ou seja, um total de $470. Escreva um programa
(usando um array de contadores) que determine quantos vendedores receberam
salários nos seguintes intervalos de valores:
a. $200 - $299
b. $300 - $399
c. $400 - $499
d. $500 - $599
e. $600 - $699
f. $700 - $799
g. $800 - $899
h. $900 - $999
i. $1000 em diante
Desafio: Crie ma fórmula para chegar na posição da lista a partir do
salário, sem fazer vários ifs aninhados.
"""
salarios = []
print("a. $200 - $299: {}".format([salarios.count(x) for x in range(200, 300)]))
print("b. $300 - $399: {}".format([salarios.count(x) for x in range(300, 400)]))
print("c. $400 - $499: {}".format([salarios.count(x) for x in range(400, 500)]))
print("d. $500 - $599: {}".format([salarios.count(x) for x in range(500, 600)]))
print("e. $600 - $699: {}".format([salarios.count(x) for x in range(600, 700)]))
print("f. $700 - $799: {}".format([salarios.count(x) for x in range(700, 800)]))
print("g. $800 - $899: {}".format([salarios.count(x) for x in range(800, 900)]))
print("h. $900 - $999: {}".format([salarios.count(x) for x in range(900, 1000)]))
print("i. $1000 em diante: {}".format([salarios.count(x) for x in range(1000, 9999)]))
| false
|
e843204b28588578d284e08e901284295d73b6db
|
cecilmalone/lista_de_exercicios_pybr
|
/2_estrutura_de_decisao/16_equacao_segundo_grau.py
| 1,327
| 4.25
| 4
|
"""
16. Faça um programa que calcule as raízes de uma equação do segundo grau, na
forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as
consistências, informando ao usuário nas seguintes situações:
a. Se o usuário informar o valor de A igual a zero, a equação não é do
segundo grau e o programa não deve fazer pedir os demais valores, sendo
encerrado;
b. Se o delta calculado for negativo, a equação não possui raizes reais.
Informe ao usuário e encerre o programa;
c. Se o delta calculado for igual a zero a equação possui apenas uma raiz
real; informe-a ao usuário;
d. Se o delta for positivo, a equação possui duas raiz reais; informe-as
ao usuário;
"""
import sys
a = int(input("Informe o a: "))
if a == 0:
sys.exit(0)
b = int(input("Informe o b: "))
c = int(input("Informe o c: "))
delta = (b ** 2) - 4 * (a * c)
if delta < 0:
print("A equação não posui raizes reais.")
sys.exit(0)
elif delta == 0:
print("A equação possui apenas uma raiz real")
x = -b / (2 * a)
print ("X' = X'' = {}".format(x))
elif delta > 0:
print("A equação possui duas raiz reais")
x_1 = (-b + delta) / (2 * a)
x_2 = (-b - delta) / (2 * a)
print ("X' = {}".format(x_1))
print ("X'' = {}".format(x_2))
| false
|
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
|
a4fd41d397324487c11c4ec571e6d3aabdf8b6d8
|
remusezequiel/Python
|
/paso_a_paso/diccionarios/diccionarios.py
| 656
| 4.15625
| 4
|
#diccionario = {"clave":valor}, donde el valor puede ser de cualquier tipo.
#Las claves seran inmutables
dic = {
'a': 55,
'b': "Roberto",
3 : 'Tres',
}
print(dic)
#Los diccionarios pueden crecer o decrecer
dic['c'] = 'nuevo string'
dic['d'] = 2
print(dic)
#Modificar
dic['a'] = 48
print(dic)
#Obtener los datos desde un diccionario
valor = dic['b']
print(valor)
valor = dic.get('z', False)
#Eliminar
del dic['a']
print(dic)
#llaves
key = dic.keys()
print(key)
#valores
value = dic.value()
print(value)
#Listamos esto
list = list(key)
listt = list(value)
print(list)
print(listt)
#Extender diccionario a partir de otro diccionarios
| false
|
cca406321cb796e6005f923529ecee0767706d8e
|
remusezequiel/Python
|
/interesanteee/Curiosidades/split-join/split.py
| 922
| 4.15625
| 4
|
"""
Consideremos la siguiente Cadena:
"""
cadena = "Mi nombre es Ezequiel"
"""
Al utilizar la funcion split, podemos separar palabra por palabra de dicha
cadena de la siguiente forma:
"""
lista_de_la_cadena = cadena.split()
print(lista_de_la_cadena)
"""
Asi como en join, tambien podemos identificar un separador para split.
Si en la cadena de texto deseamos convertir a lista las palabras estuvieran
separadas por un salto de linea, como por ejemplo.
"""
cadena = ''' Fulano
Mengano
suntano'''
lista_de_la_cadena = cadena.split(sep='\n')
"""
Nos interesa convertir strings en listas y viceversa por que los strings
son inmutables, mientras las listas son mutables. Es decir, en una lista podemos
modificar un elemento de la misma mientras que en un string no es posible
hacerlo directamente.
Mas info:
docs.python.org/3.6/library/stdtypes.html#str.split
docs.python.org/3.6/library/stdtypes.html#str.join
"""
| false
|
3111413e51ed01b45493d87f3902179ab7ca7a33
|
remusezequiel/Python
|
/paso_a_paso/Bucles/for.py
| 1,341
| 4.28125
| 4
|
#Permite iterar objetos iterables, ejemplo tuplas, diccionarios, listas y strings
list = [0,1,2,3,4,5,6,7,8,9]
#Iteracion de los elementos de la lista
for i in list:
print(i)
print("----------------------------------")
new_range = range(0,10)
for i in new_range:
print(i)
print("----------------------------------")
new_range = range(0,10,2)#con salto de 2 en 2
for i in new_range:
print(i)
print("----------------------------------")
new_range = range(10,33,3)#con salto de 2 en 2
for i in new_range:
print(i)
print("----------------------------------")
indice = 0
for i in list:
print(i, "tiene el indice", indice)
indice+=1
print('Lo cual es lo mismo que lo siguiente:')
for indice, i in enumerate(list):
print(i, "tiene el indice", indice)
print('Que pasa si los pasamos al reves:')
for i,indice in enumerate(list):
print(i, "tiene el indice", indice)
print("----------------------------------")
#Trabajar con respecto al trabajo de la lista
for valor in range(len(list)):
print(valor,"- Hola")
print("----------------------------------")
#Los strings son iterables
for valor in "Caca":
print(valor,"- Hola")
#Tambien podemos iterar diccionarios
dictionary = {'a': 1, 'b':2, 'c':3, 'd':4}
for key, value in dictionary.items():
print('La llave es: ', key, ' y el valor es: ', value)
| false
|
9124584d7f6f5c623c88fc14a60c1c457ed73839
|
Nejel/coursera-python-specialization-repository
|
/1-getting-started/define function with parameter.py
| 2,680
| 4.1875
| 4
|
def hello(name): # в случае вызова функции без параметра hello() функция вернет ошибку
print("Hello,", name)
hello("Sashka") # "Sashka" -- фактический параметр
def hello(name = "World"): # задан параметр по умолчанию
print("Hello,", name)
hello("Sashka") # "Sashka" -- фактический параметр
# Нормальная функция всю свою суть получает через параметры.
def max2(x = 1, y = 2):
if x > y:
return x # вернуть икс, если это максимум из двух параметров. ВНИМАНИЕ: РЕТЕРН прекращает выполнение функции. Дальше писать код на выполнение не надо.
else:
return y
#или просто
#return y
def max3(x = 1, y = 2, z = 3):
return max2(x, max2(y,z)) # вычисляем большее из трех через ранее заданную функцию большего из двух
print(max3()) # 3
print(max3('ab','ba','bc')) #bc #в качестве аргументов используются стринги из букв. Используется утиная типизация для определния сравнимости стрингов по лексикографическом порядку (первая буква, вторая буква)
# meters to feet converter
def converter(original, coefficient):
return original * coefficient
print(converter(10, 0.3048))
# meters to feet converter with default parameter
def converter(original, coefficient=0.3048):
return original * coefficient
print(converter(10))
# meters to feet converter with changed default parameter (kilometers to miles)
def converter(original, coefficient=0.3048):
return original * coefficient
print(converter(10, 1.6))
#Celsius to Fahrenheit converter
def converter(input):
x = input * (9/5) + 32
return input * x
#Celsius to Fahrenheit converter2
def converter(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
# Обработка исключения
def string_length(mystring):
if type(mystring) == int:
return "Sorry, integers don't have length"
elif type(mystring) == float:
return "Sorry, floats don't have length"
else:
return len(mystring)
#several calls of function:
temperatures = [10, -20, 100]
def cel_to_fahr(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
for temperature in temperatures:
print(cel_to_fahr(temperature))
| false
|
619ac5304b44679e1a044e8a7bae17fff9c5bbb0
|
offenanil/introduction
|
/practice.py
| 997
| 4.15625
| 4
|
# # print("hi \n Anil")
# # print("hi \nAnil")
# # print("hello \t sir")
# # print("hello \tmam")
# name = 'abcdefghijk'
# print(name[2:])
# print(name[:3])
# print(name[3:6])
# print(name[::2])
# # slicing syntax:[start:stop:step] start is slice start number n stop is where to slice stop n step is size of jump
# print(name[::-2])
# name = 'my name is Anil'
# print(name.split('i'))
# print('Anil{}'.format(' Acharya'))
# print('the {} {} {}'.format('fox','brown','quick'))
# my_list = [1, 2, 3]
# print(len(my_list))
# print(my_list[1:])
# my_list.append('acharya')
# print(my_list)
# my_list.pop(1)
# print(my_list)
# new_list = ['a', 'e', 'x', 'b', 'c']
# num_list = [ 4, 1, 8, 3]
# new_list.sort()
# print(new_list)
# num_list.sort()
# a = num_list
# print(a)
# num_list.reverse()
# print(num_list)
# my_dict = {'key1':input('value1'), 'key2':input('value2')}
# print(my_dict)
# print(my_dict['key1'])
d = {'k1':100, 'k2':200}
print(d)
d['k3']= 300
print(d)
print(d.keys())
print(d.values())
| false
|
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
|
b013b4f7ccebcbaa707ed670c8e78583632e2242
|
martinleeq/python-100
|
/day-05/question-041.py
| 516
| 4.15625
| 4
|
"""
问题41
有一个列表[1,2,3,4,5,6,7,8,9,10],使用map()生成一个新的列表,新的列表的元素为原来列表元素的平方
"""
def print_map():
"""
两个知识点:
1. map()函数,对传入的可迭代对象的每个元素进行迭代,对其执行传入的操作
2. labmda表达式,也就是其他语言的匿名函数,显使地使用lambda字符串
"""
pre_list = [x for x in range(1, 11)]
new_list = list(map(lambda x: x**2, pre_list))
print(new_list)
print_map()
| false
|
730539abaef3b6ecfadccbae63215d5f95419082
|
urma/euler-project
|
/problem_09.py
| 578
| 4.375
| 4
|
#!/usr/bin/env python
# A Pythagorean triplet is a set of three natural numbers, a < b < c,
# for which, a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which
# a + b + c = 1000. Find the product abc.
def is_pythagorean_triplet(a, b, c):
return (a < b) and (b < c) and (pow(a, 2) + pow(b, 2) == pow(c, 2))
if __name__ == '__main__':
for a in range(1, 1000):
for b in range(a, 1000):
c = 1000 - a - b
if is_pythagorean_triplet(a, b, c) and (a + b + c == 1000):
print(a * b * c)
| false
|
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
|
b5bfa4b54a727951f0428316e5ffde1ba31fb80d
|
Priclend/Homework
|
/homework1/hi! I'm calculator.py
| 2,926
| 4.28125
| 4
|
print ("Пожалуйста, введите действие, которое вы хотите выполнить."
" Я могу производить: сложение (+), вычитание (-), умножение (*),"
" деление (/) и вычленять корни."
" Чтобы прекратить работу со мной, введите слово 'стоп'")
act = input ()
if act == "+" or act == "сложение" :
while 1:
print ("Вы выбрали действие 'сложение'")
print ("Введите первое число")
a = int (input ())
print ("Введите второе число")
b = int (input ())
print ("a + b =" , a + b)
act = input ()
if act == "стоп":
print ("Всего доброго)")
break
elif act == "-" or act == "вычитание" :
while 1:
print ("Вы выбрали действие 'вычитание'")
print ("Введите первое число, из которого будет производиться вычитание")
a = int (input ())
print ("Введите второе число, которое будут вычитать")
b = int (input ())
print ("a - b =" , a - b)
act = input ()
if act == "стоп":
print ("Всего доброго)")
break
elif act == "*" or act == "умножение" :
while 1:
print ("Вы выбрали действие 'умножение'")
print ("Введите первый множитель")
act = int (input ())
print ("Введите второй множитель")
b = int (input ())
print ("a * b =" , a * b)
act = input ()
if act == "стоп":
print ("Всего доброго)")
break
elif act == "/" or act == "деление" :
while 1:
print ("Вы выбрали действие 'деление'")
print ("Введите делимое")
a = int (input ())
print ("Введите делитель")
b = int (input ())
print ("a / b =" , a / b)
act = input ()
if act == "стоп":
print ("Всего доброго)")
break
elif act == "корень" :
while 1:
print ("Вы выбрали действие 'корень'")
print ("Введите число, из которого я должен вычислить корень")
a = int (input ())
print ("корень из a =" , a ** (1/2))
act = input ()
if act == "стоп":
print ("Всего доброго)")
break
elif act == "стоп" :
print ("Всего доброго)")
| false
|
8bd16d3f97ebb6f3a9de5f29f5e4f52699148c71
|
olcostafilipe/cracking_the_coding
|
/chapter02/question_02.py
| 511
| 4.125
| 4
|
"""
Question 02: Return Kth to Last
Implement an algorithm to find the kth to last element of a list.
"""
import random
def kth_to_last(my_list: list, kth_index: int) -> list:
""" Return the kth to last element of a list """
return my_list[(kth_index - 1):]
def main():
# Example of input
my_list = random.choices(range(20), k=20)
kth = 13
print("List:")
print(my_list)
print("K-th to end list:")
print(kth_to_last(my_list, kth))
if __name__ == '__main__':
main()
| false
|
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
|
f65d2fe7a0fcc787c5855868307afdba3df0d8b6
|
vishalpatil0/Python-cwh-
|
/operaotr overloading and dunder method.py
| 737
| 4.15625
| 4
|
class Student:
def __init__(self,name,age,addr): #__init__(self)==constructor in python
self.name=name
self.age=age
self.addr=addr
def printdetails(self):
print(f"{self.name}\n{self.age}\n{self.addr}\n{self.year}")
def __add__(self, other): # dunder method override print function to add age of 2 objects
return (self.age+other.age) #search mapping operator to functions on google for more opertor overloading
def __truediv__(self,other):
return (self.age/other.age)
def __repr__(self):
return(f"Student({self.name},{self.age},{self.addr})")
vishal=Student("Vishal",20,"Kurha")
namu=Student("namrata",20,"pune")
print(vishal+namu)
print(vishal)
| false
|
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
|
5b68dc3a91c48e21326c8f06f5e5c7b5b1290a3a
|
wangyendt/LeetCode
|
/Contests/101-200/week 185/1418. Display Table of Food Orders in a Restaurant/Display Table of Food Orders in a Restaurant.py
| 1,641
| 4.15625
| 4
|
#!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 2020/4/19 10:43
@Author: wang121ye
@File: Display Table of Food Orders in a Restaurant.py
@Software: PyCharm
"""
class Solution:
def displayTable(self, orders: list(list())) -> list(list()):
menus = sorted(list(set(a[2] for a in orders)))
menus_dic = {m: i for i, m in enumerate(menus)}
customers = sorted(list(set(a[1] for a in orders)), key=lambda x: int(x))
customers_dic = {c: i for i, c in enumerate(customers)}
# print(menus)
# print(customers)
m, n = len(customers), len(menus)
ret = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
ret[0][0] = 'Table'
for i in range(1, n + 1):
ret[0][i] = menus[i - 1]
for i in range(1, m + 1):
ret[i][0] = customers[i - 1]
for order in orders:
ret[customers_dic[order[1]] + 1][menus_dic[order[2]] + 1] += 1
ret = [[str(ret[i][j]) for j in range(len(ret[0]))] for i in range(len(ret))]
return ret
so = Solution()
print(so.displayTable(
orders=[["David", "3", "Ceviche"], ["Corina", "10", "Beef Burrito"], ["David", "3", "Fried Chicken"],
["Carla", "5", "Water"], ["Carla", "5", "Ceviche"], ["Rous", "3", "Ceviche"]]))
print(so.displayTable(
orders=[["James", "12", "Fried Chicken"], ["Ratesh", "12", "Fried Chicken"], ["Amadeus", "12", "Fried Chicken"],
["Adam", "1", "Canadian Waffles"], ["Brianna", "1", "Canadian Waffles"]]))
print(so.displayTable(orders=[["Laura", "2", "Bean Burrito"], ["Jhon", "2", "Beef Burrito"], ["Melissa", "2", "Soda"]]))
| false
|
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
|
2ddccd4ce17f2f4ae285d0a83396516e4e8cb8c9
|
PriyankaJoshi001/DSandA
|
/KeyboardRow.py
| 565
| 4.15625
| 4
|
def findWords(words):
set1 = {'q','w','e','r','t','y','u','i','o','p'}
set2 = {'a','s','d','f','g','h','j','k','l'}
set3 = {'z','x','c','v','b','n','m'}
res = []
for i in words:
wordset = set(i.lower())
if (wordset&set1 == wordset) or (wordset&set2 == wordset) or (wordset&set3 == wordset):
res.append(i)
return res
n= int(input("enter length of array string"))
words=[]
print("enter elements")
for i in range(n):
ele=input()
words.append(ele)
print(findWords(words))
| false
|
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
|
4d565237f40c1ce06df822757f7c5d83dc562dc9
|
ShaneyMantri/Algorithms
|
/Heaps/Super_Ugly_Number.py
| 762
| 4.1875
| 4
|
"""
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
Example:
Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12
super ugly numbers given primes = [2,7,13,19] of size 4.
"""
import heapq
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
heap = [1]
d = {1:0}
while n > 0:
a = heapq.heappop(heap)
for i in primes:
if a*i in d:
continue
heapq.heappush(heap, a*i)
d[a*i] = 1
n -= 1
return a
| false
|
0f5dccdaad1d56be596c2b18b6c89d9a8933e940
|
ShaneyMantri/Algorithms
|
/Heaps/Ugly_Numbers_II.py
| 837
| 4.125
| 4
|
"""
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
"""
import heapq
class Solution:
def find(self, heap, n):
while n>0:
t = heapq.heappop(heap)
n-=1
if n==0:
return t
while len(heap)>0 and heap[0]==t:
heapq.heappop(heap)
heapq.heappush(heap, t*2)
heapq.heappush(heap, t*3)
heapq.heappush(heap, t*5)
def nthUglyNumber(self, n: int) -> int:
heap = [1]
return self.find(heap, n)
| false
|
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
|
34f5402cc1b168addfa13ad134b74f1f5c2955fd
|
a1403893559/rg201python
|
/杂物间/python基础/day07/函数参数一.py
| 458
| 4.1875
| 4
|
'''
思考一个问题,如下:
现在需要定义一个函数,这个函数能够完成2个数的加法运算,并且吧结果打印出来,该怎么设计?下面代码有什么缺陷?
'''
# 无参数函数
#def add2num():
# a = 11
# b = 22
# c = a + b
# print(c)
#
#add2num()
#
# 带有参数的函数
def add2num(a,b):
c = a+b
print(c)
add2num(11,22)#调用带有参数的函数时,需要在小括号中传递数据
| false
|
72944d7d675e602473924b94ed270d85f0c208f2
|
a1403893559/rg201python
|
/杂物间/python基础/day06/作业1.py
| 1,162
| 4.34375
| 4
|
# 创建一个字符 字符串是python 基本的数据类型之一 可以用''或者""括起来 我们需要掌握什么? 对字符串的基本增删改查的操作
#1、作业 创建一个字符串
pstr = '人生苦短,我用python,life is short,you need python'
print('该字符串的内容是%s'%pstr)
#第一个小问题是 统计字符串里面 p的个数和i的个数
# count函数 count() 统计字符串字符出现的个数
p_counts = pstr.count('p')
i_counts = pstr.count('i')
print('该字符串里面P的个数%s'%p_counts)
print('该字符串里面i的个数%s'%i_counts)
# 反向查找S所在的为止
s_find = pstr.rfind('s')
print('s在字符串的%d位'%s_find)
# 将所有小写单词换成 大写
pstr = pstr.upper()
print('小写转换成大写单词%s--成功'%pstr)
# 将所有的大写换成小写
pstr = pstr.lower()
print('大写换成小写单词了%s--成功'%pstr)
# 切片,从字符串里面剪切一个片段出来 (火腿肠,切一小段火腿肠,就可以理解为切片)
# 切片 你要切片的对象 [开始的为止:结束的为止]
# 从头切刀未
newstr = pstr[7:]
print('新的字符串内容为%s'%newstr)
| false
|
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
|
2a70ca3ca3b053c4ba4eacaffe2717522934c096
|
baihaki06/py
|
/KelasTerbuka/Python Dasar/list.py
| 772
| 4.125
| 4
|
Data = [1,4,9,14,25,36,49,64]
#mengakses data
subdata = Data[3]
subdata2 = Data[-3]
subdata3 = Data[2:4]
subdata4 = Data[:4]
subdata5 = Data[:]
#cetak data
print(subdata)
print(subdata2)
print(subdata3)
print(subdata4)
print('subdata5')
print(subdata5)
#mengabungkan list
Data2 = [100,200,300,400,500,600,700,800]
Data3 = Data + Data2
print(Data3)
#mencopy list kedalam variable baru
a = Data3[:]
print(a)
#merubah conten dari list
a[10] = 30
print(a)
#merubah content list dengan metode slicing
Data3[3:4] = [11,12]
print(Data3)
#list dalam list
x = [Data, Data2]
print(x)
#mengakses list dalam multi dimension list
y = x[1][4]
z = x[0][2]
print(y)
print(z)
Data3.append(456)
print(Data3)
#menghitung panjang list
PanjangList = len(Data3)
print(PanjangList)
| false
|
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
|
7aa3fe452d24ed804948b6e161d6d972099c3446
|
nerthul11/PythonTutorial
|
/_13_Funciones.py
| 757
| 4.21875
| 4
|
"""
Aquí veremos cómo definir, estructurar y llamar una función.
En general, conviene ubicar las funciones en las primeras líneas del código, porque para poder utilizarlas
primero deben estar definidas.
Primero, vamos a definir una función que no tome parámetros:
"""
def hola_mundo():
print("Hola, mundo")
# Luego, creamos una función que tome un parámetro y haga algo a partir de ello
def es_par(numero):
return numero % 2 == 0
# Luego llamaremos ambas funciones, un hola_mundo suelto y es_par lo probaremos con dos números
if __name__ == "__main__": # Esta línea la explicaremos mejor en el próximo archivo
hola_mundo()
numero_par = es_par(4)
numero_impar = es_par(3)
print(numero_par)
print(numero_impar)
| false
|
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
|
d60a229a041d8aac66662cdcb651fb9f67c3fa31
|
shuoshuoge/system-development
|
/stuent-grade.py
| 2,539
| 4.28125
| 4
|
class Student:
'''
Student(学号、姓名、性别、专业)
'''
def __init__(self, id, name, gender, major):
self.id = id
self.name = name
self.gender = gender
self.major = major
self.stuCourseGrade = dict()
self.getCredit = 0
def addCourseGrade(self, course, score):
self.stuCourseGrade.update({course: score})
def showCourseScore(self):
total_course_credit = 0
print("学生 {} ".format(self.name))
for k in self.stuCourseGrade:
course_name = k.name
course_credit = k.credit
course_score = self.stuCourseGrade.get(k)
total_course_credit += course_credit
if course_score >= 60:
self.getCredit += course_credit
print("{}: {} \t 应获学分{},实际获得学分{} \t".format(course_name, course_score,course_credit, course_credit))
else:
print("{}: {} \t 应获学分{},实际获得学分{} \t".format(course_name, course_score,course_credit, 0))
print("总学分{}/{}".format(self.getCredit ,total_course_credit))
# 录入成绩
# def addGrade(self, grade):
# self.stuGrade.append(grade.)
class Course:
'''
Course(编号、名称、学时、学分)
'''
def __init__(self, id, name, hour, credit):
self.id = id
self.name = name
self.hour = hour
self.credit = credit
def __str__(self):
return 'id:{}, name:{}, hour:{}, credit:{}'.format(self.id, self.name, self.hour, self.credit)
# class Grade:
# '''
# 学生课程成绩类Grade(课程、分数)63
# 可以为一个学生添加一个或多个课程成绩,可以对某个学生所获学分进行计算
# '''
# def __init__(self, course, score):
# self.gradeslist = {}
#
# def showGrade(self):
# for i in self.gradeslist:
# print(i, self.gradeslist[i])
#
# def appendCourseGrade(self, course, score):
# # score是学生考试成绩
# if score >= 60:
# self.gradeslist[course]
stu1 = Student(1, '小明', '男', '信管')
c1 = Course(id=1, name='计算机基础', hour='36', credit=4)
c2 = Course(id=2, name='python', hour='24', credit=2)
stu1.addCourseGrade(course=c1, score=99)
stu1.addCourseGrade(course=c2, score=59)
stu1.addCourseGrade(course=c1, score=79)
stu1.showCourseScore()
| false
|
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
|
049a449464258ae55d7f8d6311de2e86ff987ced
|
fatimaalheeh/python_stack
|
/_python/assignments/Bubble_sort.py
| 557
| 4.125
| 4
|
def bubble_sort (List):
print("Current values are: ",List)
countswaps=0
for i in range(0,len(List)-1):
for j in range(0,len(List)-1):
if List[i] > List[j+1]:
List[j],List[j+1]=List[j+1],List[j]
countswaps +=1
print("swap",countswaps,"is: ",List)
print("Array is sorted in ",countswaps,"swaps.")
return List
count_the_swaps = 0
myList = [1,10,2,5,4]
bubble_sort(myList)
print(myList)
print("First Element: ",myList[0])
print("First Element: ",myList[len(myList)-1])
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.