blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ac93859eed5948738ef94820a4e863e88c4adca0 | kamilczerwinski22/Advent-of-Code | /main_files/year_2017/day_3/year2017_day3_part1.py | 2,358 | 4.375 | 4 | # --- Day 3: Spiral Memory ---
# You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
#
# Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while
# spiraling outward. For example, the first few squares are allocated like this:
#
# 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very
# space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only
# access port for this memory system) by programs that can only move up, down, left, or right. They always take the
# shortest path: the Manhattan Distance between the location of the data and square 1.
#
# For example:
#
# - Data from square 1 is carried 0 steps, since it's at the access port.
# - Data from square 12 is carried 3 steps, such as: down, left, left.
# - Data from square 23 is carried only 2 steps: up twice.
# - Data from square 1024 must be carried 31 steps.
#
# How many steps are required to carry the data from the square identified in your puzzle input all the way to the
# access port?
from math import ceil, sqrt
def calculate_distance(number_to_check: int) -> int:
# initial variables
full_power = ceil(sqrt(number_to_check))
if full_power % 2 == 0:
full_power += 1
full_power_distance = full_power ** 2 - number_to_check
# main logic - algorithmic approach for best time complexity
if full_power_distance < full_power: # bottom wall
coordinates = [(full_power - 1) // 2, ((full_power - 1) // 2) - (full_power_distance % (full_power - 1))]
elif full_power_distance < full_power * 2 - 1: # left wall
coordinates = [((full_power - 1) // 2) - (full_power_distance % (full_power - 1)), -((full_power - 1) // 2)]
elif full_power_distance < full_power * 3 - 2: # up wall
coordinates = [(full_power - 1) // 2, -((full_power - 1) // 2) + (full_power_distance % (full_power - 1))]
else: # right wall
coordinates = [-((full_power - 1) // 2) + (full_power_distance % (full_power - 1)), (full_power - 1) // 2]
return sum(abs(x) for x in coordinates)
if __name__ == '__main__':
puzzle_input = 361527
result = calculate_distance(puzzle_input)
print(f"Distance is: {result}")
| true |
320232c8cd1de5f8664df46d3516b1b1f0390bba | kamilczerwinski22/Advent-of-Code | /main_files/year_2017/day_4/year2017_day4_part2.py | 1,533 | 4.25 | 4 | # --- Part Two ---
# For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no
# two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged
# to form any other word in the passphrase.
#
# For example:
#
# - abcde fghij is a valid passphrase.
# - abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word.
# - a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word.
# - iiii oiii ooii oooi oooo is valid.
# - oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word.
#
# Under this new system policy, how many passphrases are valid?
from collections import Counter
def validate_phrases() -> int:
# read file
with open('year2017_day4_challenge_input.txt', 'r') as f:
data = f.read().splitlines()
# main logic
valid_passphrases_num = 0
for line in data:
if check_for_rearranged_words(line):
valid_passphrases_num += 1
return valid_passphrases_num
def check_for_rearranged_words(line: str) -> bool:
prepared_data = [Counter(word) for word in line.split(' ')]
for i in range(len(prepared_data)):
if prepared_data[i] in (prepared_data[:i] + prepared_data[i + 1:]):
return False
return True
if __name__ == '__main__':
result = validate_phrases()
print(f"Number of valid passphrases: {result}")
| true |
a1aec8d641ea2cf17268fd44546f1b864b4970e0 | AI-MOO/PythonProjects | /T02_domain_info_finding/info_domain.py | 519 | 4.25 | 4 | import whois
def getDomainInfo():
# ask the user to enter a domain to get info
domain = input("Please enter a domain/website to get information about it: ")
# use whois method to get the domain information
information = whois.whois(domain)
print(information)
# to get particular information deal with "information" variable as dictionary data type.
print('Name:', information['name'])
print('Country:', information['country'])
print('Email', information['emails'])
getDomainInfo()
| true |
8feb267ed7bd97dcfca4a3ff894a4dc9656b2ba8 | kothamanideep/iprimedpython | /day7tasks/menu.py | 360 | 4.1875 | 4 | while(True):
print("select an option from menu:\n")
print("1.addition")
print("2.subtraction")
print("3.exit")
choice=int(input("enter your choice:"))
if choice==1:
print("addition selected")
if choice==2:
print("subtraction selected")
if choice==3:
break
else:
print("wrong choice")
| true |
29d1c5b842413f6a5d64b341da9e72d29ac30e36 | mpigelati/Python_adb | /7.py | 281 | 4.3125 | 4 | #7. take a string from the user and check contains only special chars or not?
str=input("enter a string:")
for i in str:
if ((i>='A' and i<='Z') or (i>='a' and i<='z') or (i>='0' and i<='9')):
print("alphanumeric")
break
else:
print("only special chars")
| true |
b11b4c53de8e0f8d26432a2156dd24429d4d8574 | derekngoh/PfolioProject---Offline-Password-Vault | /binaryConvert.py | 976 | 4.25 | 4 |
"""
Converts messages to unicode or ascii encodings and then further converts
the encodings to binary strings for encryption.
"""
#convert number to binary
def conv_num_to_binary(num, bits=8):
binary = []
while num > 0:
binary = [str(0)] + binary if num%2 == 0 else [str(1)] + binary
num = num//2
binary = int(''.join(binary))
binary = ('%0' + str(self.bits) + 'd') % binary
return binary
#converts text to unicode/ ascii encodings, then to binary strings
def conv_text_to_binary(text):
binary = []
for i in text:
binary = binary + [str(self.conv_num_to_binary(ord(i)))]
binary = ''.join(binary)
return binary
#converts binary strings to unicode or ascii texts
def conv_binary_to_text(text, bits=8):
str_text = ''
while True:
if not text[:bits]:
return str_text
char = chr(int(text[:bits], 2))
text = text[bits:]
return str_text + char + self.conv_binary_to_text()
| true |
986b81e080c07dcf7c0e7bdf90a44136a76ed327 | cdrcsy/python-webapp-test | /if.py | 393 | 4.125 | 4 | #! /usr/bin/env python
#coding:utf-8
num=int(raw_input('please input your guess number(1-100):'))
if 0<= num < 88:
print "your number:%d "%num
print "number less than XX"
elif num == 88:
print "your number:%d "%num
print "yes,your guess right,it's 88."
elif 88 < num <=100:
print "your number:%d "%num
print "number more than XX "
else:
print " Are you a human?"
| false |
d8c75c1b1fe9efbd1f06ac0e3d43e683921b8fd5 | yindao50/python100 | /python40.py | 516 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
题目:将一个数组逆序输出。
程序分析:用第一个与最后一个交换。或者用另一个空的数组重新放一遍
"""
def reverseList(nList):
N = len(nList)
print nList
for i in range(len(nList)/2):
nList[i],nList[N-i-1] = nList[N-i-1],nList[i]
print nList
def newList(nList):
print nList[::-1],
def main():
aList = [1,2,3,4,5]
bList = aList[:]
cList = aList[:]
reverseList(bList)
newList(cList)
if __name__ == '__main__':
main() | false |
d752d4604fad074cd6ea989d30120471452fdc8a | Gurpreetkr/GK2019 | /venv/Session4C.py | 765 | 4.1875 | 4 | alphabets = ["A", "B", "C", "D", "E"]
#length = len(alphabets)
#print(length)
print(len(alphabets))
print(max(alphabets))
print(min(alphabets))
print()
print("******")
#Iterate in list
for k in range(len(alphabets)):
print(alphabets[k])
print("========")
#Enhanced for loop / For each loop
for word in alphabets:
print(word)
print("******")
"""
data = [1, 2, 3, 4, 5]
#length = len(data)
#print(length)
print(len(data))
print(max(data))
print(min(data))
print()
print("======")
# Iterate in list
for i in range(len(data)):
print(data[i])
print("======")
print()
# Enhanced For Loop / For-Each Loop
for elm in data:
print(elm)
print("======")
print([x**2 for x in data])
numbers = list(range(1, 101,3))
print(numbers)
""" | false |
4a7c717c2a9fd7825c1dc5412a40741960d68b5c | EricHeGitHub/code-challenge-for-reference | /Dynamic Programming/Coin_recursive.py | 1,080 | 4.125 | 4 | #problem:
#You are working at the cash counter at a fun-fair, and you have different types of coins available to you
#in infinite quantities. The value of each coin is already given.
#Can you determine the number of ways of making change for a particular number of units using the given types of coins?
#Coin Problem using recursive solution
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the getWays function below.
def getWays(n, c):
return _getWays(n, c, len(c))
def _getWays(n, c, m):
if n == 0:
return 1
if n < 0:
return 0
if m <= 0 and n >= 1:
return 0
return _getWays(n, c, m - 1) + _getWays(n - c[m - 1], c, m)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
c = list(map(int, input().rstrip().split()))
# Print the number of ways of making change for 'n' units using coins having the values given by 'c'
ways = getWays(n, c)
fptr.write(str(ways) + '\n')
fptr.close()
| true |
85a7537ff6efcb0fb57fa728c469d683c7ec3ecf | nikolska/Games-room-2001 | /main.py | 1,575 | 4.1875 | 4 | import random
def roll_the_dice():
'''
Function simulates rolling two six-sided dice.
:return: the amount of rolls, type - int
'''
roll_twice = [random.randint(1, 6), random.randint(1, 6)]
return sum(roll_twice)
def game_rounds(points):
'''
Function checks the sum of the rolls: if the sum = 7, the points are divided
without a remainder by 7, if the sum = 11 - the points are multiplied by 11,
if the sum is any other number - the sum is added to the points.
:return: score result, type - int
'''
new_points = points
rolling = roll_the_dice()
if rolling == 7:
new_points //= 7
elif rolling == 11:
new_points *= 11
else:
new_points += rolling
return new_points
def game():
'''
The main function, checks the results of the players' points, if the result
is equal to or greater than 2001 - the game is finished, the player has won.
:user_points type: int
:computer_points type: int
'''
user_points = 0
computer_points = 0
while user_points < 2001 or computer_points < 2001:
print('Press ENTER to roll the dice')
input()
user_points = game_rounds(user_points)
print('user points =', user_points)
computer_points = game_rounds(computer_points)
print('compute points =', computer_points)
if user_points >= 2001:
print('You win!')
break
elif computer_points >= 2001:
print('I win!')
break
if __name__ == '__main__':
game()
| true |
d5b442773ccbe91150249369d13d2cc20ee63d32 | usmanity/practice | /python/real/try-except.py | 437 | 4.34375 | 4 | print("360 is a small but very divisible number, try dividing it a small number")
try:
number = int(input('enter a number: '))
if (360 / number) % 2 == 0:
print("360 is divisible by {}!".format(number))
else:
print("try another number.")
except ValueError:
print('Please input a number.')
except ZeroDivisionError:
print('You can\'t divide using zero.')
except:
pritn('Maybe there was a mistake') | true |
a62b6b86a085dc2f73ce0ca38309aa6a737bd197 | LoisChoji/practice_python | /matrix.py | 268 | 4.1875 | 4 | #nested lists are a common way to create matices
#check how to add matrices or sub with python
#here the inner list comprehension fills the the rows values
#the outer list comprehension creates 6 rows
matrix = [[i for i in range(5)] for _ in range(6 )]
print(matrix) | true |
4c596035648e25c13f4c59d0b07d9fcc68bd30f6 | IrmaGC/Mision-03 | /RendimientoAuto.py | 1,117 | 4.125 | 4 | #Irma Gómez Carmona
#Calcular el rendimeitno de un auto en KM/L y hacer la conversion de MI/GAL. Además de calcular cuantos litros se
#necesitan para recorrer la distancia introducida por el usuario
def calcularRendimiento(km, l):
rendimiento=km/l
return rendimiento
def calcularRendimientoConversion (km,l):
rendimiento2=(km/1.6093)/(l*0.264)
return rendimiento2
def calcularKilometros(km,l,distancia):
litros=distancia*l/km
return litros
def main ():
kilometros=int(input("Teclea el número de km recorridos: "))
litros = int(input("Teclea el número de litros de gasolina usados: "))
km=calcularRendimiento(kilometros,litros)
l=calcularRendimientoConversion(kilometros,litros)
print("""
Si recorres %d kms con %d litros de gasolina, el rendimiento es:
%.2f km/l
%.2f mi/gal
"""%(kilometros,litros,km,l))
kmViajar=int(input("¿Cuantos kilometros va a recorrer? "))
distancia=calcularKilometros(kilometros,litros,kmViajar)
print("""
Para recorrer %d km necesitas %.2f litros de gasolina"""%(kmViajar,distancia))
main()
| false |
29596533e9ba76a4f944e3b31333443eb1b83e78 | hhoangphuoc/data-structures-and-algorithms | /data-structure-questions/binary_tree/isomorphic_trees.py | 1,323 | 4.3125 | 4 | # -*- coding: UTF-8 -*-
'''
Write a function to detect if two trees are isomorphic. Two trees are called isomorphic if one of them can be
obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any
number of nodes at any level can have their children swapped. Two empty trees are isomorphic.
'''
def isomorphic_trees(a, b):
if a is None and b is None:
return True
if a is None or b is None:
return False
if a.data != b.data:
return False
return (isomorphic_trees(a.left, b.left) and isomorphic_trees(a.right, b.right)) \
or (isomorphic_trees(a.right, b.left) and isomorphic_trees(a.left, b.right))
if __name__ == "__main__":
import binary_tree
n1 = binary_tree.Node(1)
n1.left = binary_tree.Node(2)
n1.right = binary_tree.Node(3)
n1.left.left = binary_tree.Node(4)
n1.left.right = binary_tree.Node(5)
n1.right.left = binary_tree.Node(6)
n1.left.right.left = binary_tree.Node(7)
n1.left.right.right = binary_tree.Node(8)
n2 = binary_tree.Node(1)
n2.left = binary_tree.Node(3)
n2.right = binary_tree.Node(2)
n2.right.left = binary_tree.Node(4)
n2.right.right = binary_tree.Node(5)
n2.left.right = binary_tree.Node(6)
n2.right.right.left = binary_tree.Node(8)
n2.right.right.right = binary_tree.Node(7)
print isomorphic_trees(n1, n2)
| true |
d5320f3bcfd1d4a44b293fd08558985dcf877efc | hhoangphuoc/data-structures-and-algorithms | /data-structure-questions/binary_tree/level_order_traversal_line_by_line.py | 1,232 | 4.375 | 4 | # -*- coding: UTF-8 -*-
# Print level order traversal line by line using iterative level order traversal
from __future__ import print_function
import binary_tree
import Queue
def level_order_traversal_helper(root, level):
'''Print the node if the level is 1'''
if root is None:
return
if level == 1:
print(root.data, end=" ")
else:
level_order_traversal_helper(root.left, level-1)
level_order_traversal_helper(root.right, level-1)
def level_order_traversal(tree):
'''Call the level order helper at each level of the tree'''
height = tree.height(tree.root)
for i in range(1, height+1):
level_order_traversal_helper(tree.root, i)
print ("\n")
def level_order_traversal_using_queue(root):
'''Print level order traversal using queue'''
q = Queue.Queue()
q.put(root)
while not q.empty():
number_of_nodes = q.qsize()
while (number_of_nodes):
temp = q.get()
print(temp.data, end=" ")
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
number_of_nodes -= 1
print("\n")
if __name__ == "__main__":
tree = binary_tree.construct_binary_tree()
level_order_traversal(tree)
print("Level order traversal using queue")
level_order_traversal_using_queue(tree.root)
| true |
c05974b58134c3ed33514c5090e5e061e4ef016b | hhoangphuoc/data-structures-and-algorithms | /cracking_the_coding_interview/linked_list/intersection_linked_lists.py | 2,938 | 4.1875 | 4 | # coding: UTF-8
'''
Problem: Write a program to find the intersection of two linked list.
Solution: First compare the tail of two linked lists, if not same return False, otherwise look for intersection point.
Calculate the length of both linked lists and find the difference between the two. Then move a pointer in the
longer linked list forward by the difference in lengths, then compare each node of the linked list. If two nodes
matches, check rest of the linked list and if same, return the intersection point.
Example:
33 4 8 41 9 6 13 5 4
8 10 9 6 13 5 4
Result: 9
'''
import linked_list
def get_size_and_tail(linked_list):
'''Return the tail and size of linked list'''
current = linked_list.head
size = 0
while(current.nextnode is not None):
size += 1
current = current.nextnode
return current, size+1
def check_Rest_of_node(linked_list1, linked_list2):
'''When two nodes matches, check if remaining lists are same'''
while (linked_list1 != None and linked_list2 != None):
if (linked_list1 != linked_list2):
return False
linked_list1 = linked_list1.nextnode
linked_list2 = linked_list2.nextnode
return True
def find_intersection(linked_list1, linked_list2, difference):
'''Check if two linked lists are intersecting'''
for i in range(difference):
linked_list1 = linked_list1.nextnode
while (linked_list1 != None and linked_list2 != None):
if linked_list1 == linked_list2:
intersection_node = linked_list1.data
if check_Rest_of_node(linked_list1, linked_list2):
return intersection_node
linked_list1 = linked_list1.nextnode
linked_list2 = linked_list2.nextnode
return False
def find_intersection_helper(linked_list1, linked_list2):
'''Calculate the difference between length of two linked lists and call find_intersection function'''
tail1, len_1 = get_size_and_tail(linked_list1)
tail2, len_2 = get_size_and_tail(linked_list2)
# IF the tails of two linked list are different, then they do not intersect
if tail1 != tail2:
return False
if len_1 > len_2:
difference = len_1 - len_2
return find_intersection(linked_list1.head, linked_list2.head, difference)
else:
difference = len2 - len_1
return find_intersection(linked_list2, linked_list1, difference)
if __name__ == "__main__":
# Initialize linked list 1
linked_list1 = linked_list.initialize_linked_list()
# Initialize linked list 2
linked_list2 = linked_list.LinkedList()
linked_list2.head = linked_list1.head.nextnode.nextnode.nextnode.nextnode
linked_list2.insert(10)
linked_list2.insert(8)
linked_list1.print_list()
linked_list2.print_list()
print find_intersection_helper(linked_list1, linked_list2)
| true |
be31177ba0a7741cb1a1c65f065202af2022c4e3 | hhoangphuoc/data-structures-and-algorithms | /data-structure-questions/string/sentence_reverse.py | 1,066 | 4.28125 | 4 | # -*- coding: UTF-8
'''
You are given an array of characters arr that consists of sequences of characters separated by space characters.
Each space-delimited sequence of characters defines a word.
Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.
'''
arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
def reverse(arr, st, end):
while st < end:
arr[st], arr[end] = arr[end], arr[st]
end -= 1
st += 1
def reverse_arr(arr):
arr = arr[::-1] # this will reverse the string and copy its element to a new string
st_index = 0
length = len(arr)
for i, val in enumerate(arr):
if val == ' ':
end_index = i-1
reverse(arr, st_index, end_index)
st_index = end_index + 2
if i == length - 1:
reverse(arr, st_index, length-1)
return arr
print reverse_arr(arr)
print reverse_arr([' ', ' ', ' '])
| true |
cf9564cd7fd3b604bad42c45fa0b51a2a14b4449 | hhoangphuoc/data-structures-and-algorithms | /cracking_the_coding_interview/recursion_and_dynamic_programming/step_count.py | 1,024 | 4.5 | 4 | # -*- coding: UTF-8 -*-
'''
Problem: A child is running up the staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the stairs.
'''
def step_recursive(n):
''' Recursive solution to count the possible ways to run up the stairs '''
if n < 0:
return 0
if n == 0:
return 1
else:
return step_recursive(n-1) + step_recursive(n-2) + step_recursive(n-3)
def step_dynamic(n):
'''Count the number of ways to take n steps usng dynamic programming'''
soln = [0] * (n+1)
soln[0] = 1
for i in range(1, n+1):
if i >= 1:
soln[i] += soln[i-1]
if i >= 2:
soln[i] += soln[i-2]
if i >= 3:
soln[i] += soln[i-3]
return soln[n]
if __name__ == "__main__":
print "Counting possible ways using recursion"
print step_recursive(4)
print step_recursive(5)
print step_recursive(6)
print "Counting possible ways using dynamic programming"
print step_dynamic(4)
print step_dynamic(5)
print step_dynamic(6)
| true |
12be60ee9c72d1317d22f078fcaaa47330a2a06a | PhilippeCarphin/tests | /Python_tests/variables_vs_objects.py | 1,119 | 4.25 | 4 | """ This test shows the subtleties of the difference between python variables
and python objects.
As someone put it: an "a = b" could be thought of as binding 'a' to the same
object as 'b'.
As part of this subject, we also demonstrate the copy and deepcopy modules
"""
from copy import copy, deepcopy
class Phil:
def __init__(self, val, d=None):
self.val = val
self.d = d
def __str__(self):
return str(self.val) + ' d --> ' + str(self.d)
print("======== Initial objects ===========")
a = Phil(4)
b = Phil(5)
print(a)
print(b)
print("========= Assignment-like statement =======")
""" This makes a 'point to' the same object as b """
a = b
a.val = 99
print(a)
print(b)
print("====copy===")
a = Phil(10)
b = Phil(99)
print(a)
print(b)
print("==")
b = a
a.val =88
print(a)
print(b)
print("===========")
a = 4
b = 5
b = a
a = 99
print(a)
print(b)
print("============== copy vs deepcopy ================")
dictionnaire = {'phil':50, 'godefroy':60}
a = Phil(88, dictionnaire)
d = deepcopy(a)
b = copy(a)
b.d['marcus'] = 42
c = a
c.val = 67
for v in [a,b,c,d]:
print(v)
| true |
871d844c7d5e3ef209483d6c49c1c57ea71edf77 | SAYANTAN-SANYAL/Python-Development-Task-1-by-Sayantan-Sanyal | /Question 1.py | 358 | 4.25 | 4 | # To accept 2 integer numbers from user and return their product
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
product = num1 * num2
print("Product of numbers is: ",product)
# if the product is greater than 1000 then return their sum
if (product > 1000):
sum = num1 + num2
print("sum of numbers is: ",sum)
| true |
000fd89ad5681a4cb9db6d88ebbaeac05a280062 | IMDCGP105-1819/portfolio-Danbob-Airsoft | /ex8.py | 806 | 4.125 | 4 | Total_Cost = float (input ("How much does your dream home cost? "))
Portion_deposit = Total_Cost * 0.20
Current_Savings = 0
Annual_Salary = float(input ("What is your annual salary? "))
Portion_Saved = float(input ("How much of your salary (as a decimal) would you like to save? "))
Monthly_Salary = Annual_Salary /12
Monthly_Saving = Monthly_Salary * Portion_Saved
Months_To_Save = 0
semi_annaul_sallery = float(input("Please input your semi annual raise "))
while Current_Savings < Total_Cost:
Current_Savings = Current_Savings + Monthly_Saving
Current_Savings += Current_Savings * 1.04/12
Months_To_Save = Months_To_Save + 1
if Months_To_Save % 6 == 0:
Annual_Salary += Annual_Salary * (semi_annaul_sallery)
print (f"It will take {Months_To_Save} months to save for this home")
| true |
d19a6bc9a7e27ae144f91faf4dd9127acc159b23 | NorimasaNabeta/projecteuler | /problem0004.py | 975 | 4.25 | 4 | # -*- mode: python; encoding:utf-8-unix -*- -*-
#
#
import os, sys
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def ispalindrome( number ):
flag = True
strrep = "%i" % number
for i in range(0, int(len(strrep)/2)):
if (strrep[i] != strrep[len(strrep)-1-i]):
flag = False
break
# print ( number, flag )
return flag
#
#
#
if __name__ == "__main__":
# ispalindrome( 123321 )
# ispalindrome( 1234321 )
maxvalue = 0
for i in range(999, 101, -1):
for j in range(i-1, 102, -1):
rslt = i * j
tmp = ispalindrome( rslt )
if tmp :
if maxvalue < rslt:
maxvalue = rslt
print (tmp, i, j, rslt )
print ("MAX:", maxvalue)
# True 993 913 906609
| false |
0c2801d5f9cb22b582db1de9b4b3ce090ea73b15 | calypsobronte/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 268 | 4.125 | 4 | #!/usr/bin/python3
def uppercase(str):
str = str + "\n"
for i in str:
letter = "abcdefghijklmnopqrstuvwxyz"
if i in letter:
letter = ord(i) - 32
else:
letter = ord(i)
print("{:c}".format(letter), end='')
| false |
00f155a7b308726f421e4158ce1296ab69b68dc9 | dxxjing/python-test | /base_program/list.py | 814 | 4.125 | 4 | #!/usr/bin/python3
# list 列表 一个列表可以包含任意类型
# 索引值以 0 为开始值,-1 为从末尾的开始位置。
list1 = [1, 'test', 1.2, True]
tinyList = [4, 'tiny']
print(list1) # [1, 'test', 1.2, True]
# 截取
print(list1[0])
print(list1[:])
print(list1[0:])
print(list1[0:2])
print(list1 + tinyList) # 拼接
print(tinyList * 2) # 连续输出
print(list1[0:-1:2]) # 第三个参数表步长 与string一致
'''
1
[1, 'test', 1.2, True]
[1, 'test', 1.2, True]
[1, 'test']
[1, 'test', 1.2, True, 4, 'tiny']
[4, 'tiny', 4, 'tiny']
[1, 1.2]
'''
# 与string 不同的是 list内的元素是可以改变的
list1[0] = 111
print(list1) # [111, 'test', 1.2, True]
print(list1[-1::-1]) # 从末尾开始截取且步长为-1 用于反转列表 [True, 1.2, 'test', 111]
| false |
44e3fcbd0357264f6811408b7d6c427728b7803f | dxxjing/python-test | /base_program/thread3.py | 1,381 | 4.15625 | 4 | #!/usr/bin/python3
import time
import threading # 推荐使用
# 线程同步
# 同步的效果是 一个线程 一旦拿到锁就会一直执行到结束,即使遇到io操作也不会让出执行权,所以打印出来的线程编号不会是错乱的
threadLock = threading.Lock()
threads = []
class myThread(threading.Thread):
def __init__(self, thread_id, thread_name, counter):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.thread_name = thread_name
self.counter = counter
def run(self):
print("开启线程: " + self.thread_name)
# 获取锁,用于线程同步
threadLock.acquire()
print_time(self.thread_name, self.counter)
# 释放锁,开启下一个线程
threadLock.release()
# 线程执行函数
def print_time(thread_name, counter):
while counter:
time.sleep(2)
print("%s: %s, num=>%d" % (thread_name, time.ctime(time.time()), counter))
counter -= 1
# 创建线程
t1 = myThread(1, 'thread-1', 3)
t2 = myThread(2, 'thread-2', 3)
t3 = myThread(3, 'thread-3', 3)
# 等待5s并发执行
time.sleep(3)
# 启动线程
t1.start()
t2.start()
t3.start()
# 添加线程到 线程列表
threads.append(t1)
threads.append(t2)
threads.append(t3)
# 阻塞等待回收线程
for t in threads:
t.join()
print("主线程退出")
| false |
ac2afb4ea0791cf0a36e1b36da6a4ac085423668 | weezybusy/Cracking-the-Coding-Interview | /Problems/1/check_permutation/check_permutation.py | 1,162 | 4.21875 | 4 | #!/usr/bin/env python3
"""
check_permutation: given two strings, write a method to decide if one is a
permutation of the other.
"""
# Time complexity: O(nlogn)
# Space complexity: O(n)
def check_permutation_sort(s1: str, s2: str):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
# Time complexity: O(n)
# Space complexity: O(n)
def check_permutation_hash(s1: str, s2: str):
if len(s1) != len(s2):
return False
letters = {}
for letter in s1:
if letters.get(letter) is None:
letters[letter] = 0
letters[letter] += 1
for letter in s2:
if letters.get(letter) is None:
return False
elif letters[letter] > 1:
letters[letter] -= 1
else:
letters.pop(letter)
return True
# Time complexity: O(n)
# Space complexity: O(n)
def check_permutation_list(s1: str, s2: str):
if len(s1) != len(s2):
return False
letters1 = [0] * 128
letters2 = [0] * 128
for letter in s1:
letters1[ord(letter)] += 1
for letter in s2:
letters2[ord(letter)] += 1
return letters1 == letters2
| true |
c63aac578f5c2cb8d0945dc003f0868cf8650fdd | thomas-harris-git/Learning-Python | /Advanced/Classes+Objects.py | 1,758 | 4.625 | 5 | # Python is an object oriented programming language.
# A Class is like an object constructor, or a "blueprint" for creating objects.
#Create a class named MyClass, with a property named x:
class MyClass:
x = 5
# Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
# All classes have a function called __init__(), which is always executed when
# the class is being initiated. Use the __init__() function to assign values
# to object properties, or other operations that are necessary to do when the
# object is being created:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
# Objects can also contain methods. Methods in objects are functions that
# belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
# The 'self' parameter is a reference to the current instance of the class,
# and is used to access variables that belongs to the class. It does not have
# to be named 'self' , you can call it whatever you like, but it has to be
# the first parameter of any function in the class:
class Person:
def __init__(random_name, name, age):
random_name.name = name
random_name.age = age
def myfunc(differentName):
print("Hello my name is " + differentName.name)
p1 = Person("John", 36)
p1.myfunc()
# You can modify properties on objects like this:
p1.age = 40
# You can delete properties on objects by using the 'del' keyword:
del p1.age
# You can delete objects by using the del keyword:
del p1
| true |
04e7680968349d82b732377bb31420937e713fa6 | tribudiyono93/python | /reverse_and_index_array.py | 307 | 4.125 | 4 | import array
arr = array.array('i', [1,2,3,1,2,5])
print("The new created array is ")
for i in range(0,6):
print(arr[i], end=" ")
print("\r")
print("The index of 1st of 2 is ")
print(arr.index(2))
arr.reverse()
print("The array after reversing is ")
for i in range(0,6):
print(arr[i], end=" ") | true |
ee4237dc60457f15b94f3fa139a7178cdd71cc8f | plummonke/diceroller | /dice.py | 1,249 | 4.46875 | 4 | import random
def roll_die(sides):
"""
roll_die() returns a function to simulate rolling a die with n sides.
Parameters:
sides: an integer greater than 0.
Example:
d10 = roll_die(10)
d10() # Returns an integer 1 through 10.
"""
def roll():
return random.randint(1, sides)
return roll
def roll_dice(n, die_func):
"""
roll_dice() is a recursive function returning an integer value to simulate
rolling n number of dice.
Parameters:
n: integer greater than 0
die_func: a function returning a single integer
Example:
rolldice(5, roll_die(6)) # Simulates rolling 5d6.
"""
if n <= 1:
return die_func()
return die_func() + roll_dice(n - 1, die_func)
def roll_with_modifier(n, die_func, modifier):
"""
roll_with_modifier() simulates rolling n number of dice and adds an integer
to the final value.
Parameters:
n: an integer greater than 0
die_func: function returning a single integer
modifier: an integer
Example:
roll_with_modifier(3, roll_die(8), 3) # Simulates rolling 3d8+3
"""
def roll():
return roll_dice(n, die_func) + modifier
return roll
| true |
8663e4a3e925290a07802936ae15a9cb23cfb017 | nengdaqin/Python | /Study/Python_Basic_Study/Object-oriented/inherit/qnd_03_多态.py | 741 | 4.125 | 4 | """
多态性:指在父类被子类继承后,可以具有不同的状态或表现
"""
class Dog(object):
def __init__(self, name):
self.name = name
def game(self):
print("%s蹦蹦跳跳的玩耍..." % self.name)
class XiaoTianDog(Dog):
def game(self):
print("%s飞到天上去玩耍..." % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def game_with_dog(self, dog):
print("%s和%s快乐的玩耍..." % (self.name, dog.name))
dog.game()
def main():
# wangcai = Dog("旺财")
xiaoming = Person("小明")
wangcai = XiaoTianDog("飞天旺财")
xiaoming.game_with_dog(wangcai)
if __name__ == '__main__':
main()
| false |
83f7e5c678eb817f0371ab91fe3ac3e005c85a7b | nengdaqin/Python | /Study/Python_Basic_Study/Object-oriented/inherit/qnd_04_类属性.py | 800 | 4.15625 | 4 | """
3.类属性和实例属性
3.1概念和使用
类属性就是给类对象中定义的属性
通常用来记录与这个类相关的特征
类属性不会用于记录具体对象的特征
"""
# 示例需求
# 定义一个工具类
# 每件工具都有自己的name
# 需求 知道使用这个类,创建了多少个对象
class Tool(object):
# 使用赋值语句定义类属性,记录创建工具对象总数
count = 0
def __init__(self, name):
self.name = name
# 针对类属性做计数+1
Tool.count += 1
def main():
# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("铲子")
tool3 = Tool("刀")
# 输出工具对象的总数
print("工具总数为:%d" % Tool.count)
if __name__ == '__main__':
main() | false |
84b51405007dd77bb38be82e39ab5b56641989a0 | nengdaqin/Python | /Study/Python_Basic_Study/module/qnd_01_Car.py | 616 | 4.1875 | 4 | """
汽车类
"""
class Car(object):
def __init__(self, brand, model, color, year):
self.brand = brand
self.model = model
self.color = color
self.year = year
def show_car(self):
print("品牌:%s\n型号:%s\n颜色:%s\n年份:%s"
% (self.brand, self.model, self.color, self.year))
# 定义一个print_line函数打印组成一条分割线
def print_line(self):
print("=" * 50)
def main():
my_car = Car("Audi", "A4L", "White", 2020)
my_car.show_car()
# my_car.print_line()
if __name__ == '__main__':
main() | false |
10e06ff85d80ef1b38407cd94fa53f176289d065 | ggoma5879/p1_201110081 | /w6Main.py | 1,397 | 4.1875 | 4 | """
@author KSM
@since 160406
"""
def multiple3and5():
print "sum of multiple 3 and 5"
startNumber=int(raw_input("set a start number\n"))
number=int(raw_input("set a objective number\n"))
sum=0
for i in range(startNumber,number+1):
if (i%3==0):
sum=i+sum
elif (i%5==0):
sum=i+sum
print "sum :",sum
def findQYear():
qYear=int(raw_input("leap year = what year are you wondering?"))
if ((qYear % 4 == 0 and qYear% 100 != 0) or qYear % 400 == 0):
print qYear,"is leap YEAR."
else :
print "No,",qYear,"is not leap year"
def upAndDown():
print "High low game, first user enter the hidden number and the guess user turn"
nMax=1000
i=1
obNumber = 0
count=0
obNumber =int(raw_input("hidden number"))
while( i!=0):
number=int(raw_input("input number"))
if number == obNumber:
print "CORRECT"
break
elif number <= obNumber:
print "up"
elif number >= obNumber :
print "down"
else :
print "Error, plz enter numbers"
count= count + 1
print "Correct, you guessed just" ,count+1
def lab6():
multiple3and5()
def lab6_1():
findQYear()
def lab6_2():
upAndDown()
def main():
lab6()
lab6_1()
lab6_2()
if __name__=="__main__":
main()
| false |
3faa389671eb2aae7f3c3bedc10a773928a612bc | savageblossom/pythonPlayground | /lab4.py | 2,852 | 4.3125 | 4 | # Lab 4
# Checking to see if x is a number
def isNumber(item):
try:
float(item)
return True
except ValueError:
return False
def readExpression():
# Gets string and deletes whitespace
astring = raw_input('Enter your expression: \n')
astring = astring.replace(" ", "")
# After that it will check if there are any unsupported characters in the string
for item in astring:
if item not in '0123456789+-*/.()':
print ("Error! \nUnsupported character: " + item)
exit()
# Then it creates the list and adds each individual character to the list
list = []
for item in astring:
list.append(item)
# It combines individual numbers into actual numbers based on input
count = 0
while count < len(list) - 1:
if isNumber(list[count]) and isNumber(list[count + 1]):
list[count] += list[count + 1]
# print(list[count])
# print(list[count+1])
del list[count + 1]
elif isNumber(list[count]) and list[count + 1] == ".":
list[count] += list[count + 1] + list[count + 2]
del list[count + 2]
del list[count + 1]
else:
count += 1
# print(list)
return list
def performOperation(n1, operand, n2):
if operand == "+":
return str(float(n1) + float(n2))
elif operand == "-":
return str(float(n1) - float(n2))
elif operand == "*":
return str(float(n1) * float(n2))
elif operand == "/":
try:
n = str(float(n1) / float(n2))
return n
except ZeroDivisionError:
print ("Error! Division by zero!")
exit()
main = readExpression()
# If the length of the list is 1, there is only 1 number, meaning an answer has been reached.
while len(main) != 1:
# print("".join(main))
'''
If there are parentheses around a single list item, the list item is
obviously just a number, eliminate parentheses.
Will check to see if the first parentheses exists first so that it does not
throw an index error
'''
for i, e in enumerate(main):
if main[i] == "(":
if main[i + 2] == ")":
del main[i + 2]
del main[i]
# Multiply OR Divide
for i, e in enumerate(main):
if main[i] in ["*", "/"] and not (main[i+1] in '()' or main[i-1] in '()'):
main[i - 1] = performOperation(main[i - 1], main[i], main[i + 1])
del main[i + 1]
del main[i]
# Add OR Substract
for i, e in enumerate(main):
if main[i] in ["+", "-"] and not (main[i+1] in '()' or main[i-1] in '()'):
main[i - 1] = performOperation(main[i - 1], main[i], main[i + 1])
del main[i + 1]
del main[i]
print(main[0])
| true |
1287104c4911964ca77eb0d65367e83e57a5a092 | Ethan-CS/PythonFundamentals | /04 Lists/04_Exercises.py | 998 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 4: Lists Exercises
#
# 1. Reverse a given list, e.g. if you get the list `[10, 20, 30, 40, 50]` you should print `[50, 40, 30, 20, 10]`.
# * There are two possible ways you might try this. The first is using the `reverse()` function (which is a bit like cheating), and the second is using a _scicing operator._ If you can't find anything to help online, have a look at the solutions.
# In[2]:
# Your solution goes here
# 2. Square every number in a given list of numbers, e.g. if you're given the list `[1, 2, 3, 4, 5]` you should return `[1, 4, 9, 16, 25]`.
# In[3]:
# Your solution goes here
# 3. Write a program that counts the number of times a specified element occurs within a given list. You should try writing this inside a function.
# In[4]:
# Your solution goes here
# 4. Write a program that, given a list of numbers, removes any even numbers and returns a list of all the odd numbers
# In[5]:
# Your solution goes here
| true |
5ae41aa82aab57477a9919ddd82bc261f82a7391 | councit/datastructures | /arrays/threenumsum.py | 610 | 4.1875 | 4 | '''
Given an array return a len 3 list if the sum == target value
'''
def threeNumberSum(array, targetSum):
array.sort()
trip_arr = []
for i in range(len(array) - 2):
left = i + 1
right = len(array) - 1
while left < right:
currentSum = array[i] + array[left] + array[right]
if currentSum == targetSum:
trip_arr.append((array[i], array[left], array[right]))
left += 1
right -= 1
elif currentSum < targetSum:
left += 1
elif currentSum > targetSum:
right -= 1
return trip_arr
#Test
arr = [12, 3, 1, 2, -6, 5, -8, 6]
target = 0
print(threeNumberSum(arr, target)) | true |
2146faf58f1536bbf7a26962845262bc04c9f096 | MirasAmanov/CSMirasAmanov | /3.py | 357 | 4.21875 | 4 | num1=int(input("Введите первое число:"))
num2=int(input("Введите второе число:"))
num1*=5
print("Result:",num1+num2)
print("Result:",num1-num2)
print("Result:",num1/num2)
print("Result:",num1*num2)
print("Result:",num1**num2)
print("Result:",num1//num2)
word= "Hi"
print(word*2)
word=True
| false |
49e7314aff09537a2e1365ad4ffbd6f24a972787 | joaquinipar/python_course | /tuples.py | 270 | 4.34375 | 4 | #tuples : cannot be changed
numbers = (1,2,3,4,5)
1 in numbers
print(numbers[1])
#iterating tuples
for x in numbers:
print(x)
days= ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
for day in days:
print(day)
while i<len(numbers)-1
| true |
0b41ff6a21b6ef79eb07a82904a2f9f747ae8224 | edagotti689/PYTHON-11-LAMBDA | /8_generator.py | 595 | 4.46875 | 4 | '''
1. Using generator we can execute a block of code based on demand using next() function.
2. using yield keyword we can create a generator.
'''
def gen_fun(n):
for i in range(n):
print('Before return')
yield i
print('After return')
yield i
gen_obj = gen_fun(10)
print(next(gen_obj))
# print(next(gen_obj))
# print(next(gen_obj))
## Iterate based on for loop
#for i in gen_obj:
# print(' For Loop ', i)
# def gen_fun(n):
# print('Before return')
# yield 9
# print('After return')
# yield 5
| true |
8fd45ace3df708acb3b1daf09dd441f93bdebf82 | GDUT-Condi/Data-structure-and-algorithm | /select_sort.py | 472 | 4.125 | 4 | #coding=utf-8
#遍历选出最大,放到右边
#选出次大,放到次右边
def Select_Sort(lists):
max_lists = len(lists)
for j in range(max_lists):
temp = 0
for i in range(1,max_lists-j):
if lists[i] > lists[temp]:
temp = i
lists[temp],lists[max_lists-1-j] = lists[max_lists-1-j],lists[temp]
return lists
if __name__ == '__main__':
lists = [11,1,8,9,9,7,5,2,4]
print(Select_Sort(lists))
| false |
d87366796feddb608b9dd399ead09dc1193105d0 | Asabe041/AminSaber | /Python Applications/University Assignments/a3/a3_Q3_30059636.py | 773 | 4.1875 | 4 | def longest_run(l):
"""
(list)->int
Precondition: numbers in the list
This function returns the length of the longest run
"""
accumulator=1
x=1
y=0
if len(l)==0:
x=0
else:
for i in range(len(l)-1):
if l[i]==l[i+1]:
accumulator=accumulator+1
x=accumulator
else:
y=x
accumulator=1
if x<y:
x=y
return x
#main
numbers_list=[]
strings_for_list = input("Please input a list of numbers sepertated by space: ").strip().split()
for num in strings_for_list:
numbers_list.append(float(num))
length_of_run=longest_run(numbers_list)
print('The length of the longest run is', length_of_run)
| true |
c311c2defe3a48a926933eb8081eacdae561f3c3 | denyadenya77/beetroot_lessons | /lesson_8/presentation/1.py | 368 | 4.4375 | 4 | # Написать функцию, которая будет принимать температуру по цельсию и возвращать ее перевод в температуру по
# фаренгейту по формуле: (temp - 32) * (5/9)
def temp_f(a):
c = a * 1.8 + 32
return c
user = int(input('Enter temp: '))
print(temp_f(user)) | false |
bf0d03909f17b69ebd054a845043674b3ec9d330 | mra1385/Next-Prime | /NextPrime.py.py | 940 | 4.40625 | 4 | ### Assignment ###
#
# Your assignment is to implement the
# following function: `find_next_prime`.
# As the name states, given the number `n` the
# function should return the next closest prime.
#
# Examples:
# * `find_next_prime(6)` should return 7.
# * `find_next_prime(10)` should return 11.
# * `find_next_prime(11)` should return 13.
#
# You can use whatever you want (data structures,
# language features, etc).
#
# Unit tests would be a plus. Actually, just knowing what
# they are would be a plus :)
#
### End Assignment ###
# Do your coding here
n = raw_input("What is your number? ")
n = int(n)
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if (n % i) == 0:
return False
return True
def print_next_prime(n):
number = n
while True:
number += 1
if n <= 1:
print(2)
break
elif is_prime(number):
print(number)
break
print_next_prime(n) | true |
3c0c8bc98ffb6afec3d2b4c2e546745b13eef643 | matrixcal/python-practice | /practice1.py | 1,231 | 4.46875 | 4 | number1=7
if number1>0:
print "Number is positive"
else:
if number1==0:
print "Number is 0"
else:
print "Number is Negative"
##Find factorial of the number
num=num1=7
fact=1
while(num1>0):
fact=fact*num1
print fact,num1
num1=num1-1
print "Factorial of ",num, "is", fact
#Check if number is even or odd
num2=10
if num2%2==0:
print "Number is even"
else:
print "Number is Odd"
#check if year is leap year or not
#if year is divisible by 400 then is_leap_year
#else if year is divisible by 100 then not_leap_year
#else if year is divisible by 4 then is_leap_year
#else not_leap_year
year=1992
if year%4==0:
if year%100==0:
if year%400==0:
print("Year",year,"is leap year")
else:
print("Year", year, "is NOT leap year")
else:
print("Year", year, "is leap year")
else:
print("Year", year, "is NOT leap year")
#find the largest number among three numbers
number1=10
number2=12
number3=15
if number1>number2 and number1>number3:
print(number1,"is largest number")
if number2>number1 and number2>number3:
print(number2, "is largest number")
if number3>number1 and number3>number2:
print(number3, "is largest number") | false |
b0f379e7e883a1c39c1bf0d5ec496326fac03ad8 | JonesPaul98/guvi | /area of circle.py | 237 | 4.34375 | 4 | radius=int(input('enter the number:'))
diameter=2*radius
circumference=2*3.14*radius
area=3.14*radius*radius
print("diameter of a circle is",diameter)
print("circumference of a circle is",circumference)
print("area of a circle is",area)
| true |
68affef82654e0be1ac7b333e243268d148285ea | ranjan352/calculator.py | /calculator1_final.py | 2,432 | 4.15625 | 4 | # A simple calculator
# commaSeperated
# spaceSeperated
# newLine : loop
def get_input():
numbers = []
numbers_string = input("Enter comma separated integer value : ")
for num in numbers_string.split(','):
try: # use for value error
numbers.append(int(num))
print('asdf')
except ZeroDivisionError:
print("Skipping wrong value", num)
except ValueError:
print("Skipping wrong value", num)
else:
print("else block got executed")
# except ZeoDivisionError
print(numbers)
return numbers
#function for adding the number.
def add():
# '1,2,3,4,5,6,7,8,9,10'
numbers = get_input()
sum = 0
for num in numbers:
sum = sum + num
print(sum)
return sum
#function for Subtracting.
def sub():
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
sub = num1 - num2
print(sub)
return sub
#function for multiplication the number.
def mul():
numbers_string = input("Enter comma separated integer value : ")
# '1,2,3,4,5,6,7,8,9,10'
numbers = get_input()
prod = 1
for num in numbers:
prod = prod * num
print(prod)
return prod
def div():
num1 = int(input("Enter Divisor"))
num2 = int(input("Enter Dividend"))
try:
result = num2/num1
except ZeroDivisionError:
print("cannot divided by zero")
def square():
num = int(input("Enter the number:\n"))
square = num * num
print(square)
return square
def show_menu():
'''
Shows the list of available operations
:return: None
'''
print('\n\n', '*' * 70)
print("Choose from the following")
print("1. Add")
print("2. Subtract two numbers")
print("3. Multiply")
print("4. Divide")
print("5. square")
print("6. Exit the program")
option = input("Enter your choice of operation to be performed : ")
print('\n')
if option == str(6):
print("exiting the function")
exit(0)
elif option == str(5):
square()
elif option == str(4):
div()
elif option == str(3):
mul()
elif option == str(2):
sub()
elif option == str(1):
add()
# nums = input('user')
# add(*args)
# option = input("Enter your choice of operation to be performed")
#
while True:
show_menu()
| true |
35a3a35859947ee10aaa32398e5c04edd735b653 | k43lgeorge666/Python_Scripting | /functions/program4.py | 1,443 | 4.3125 | 4 | #!/usr/bin/python
def Add_Numbers(number1, number2):
resp = number1 + number2
print("The result is: " + str(resp))
def Substract_Numbers(number1, number2):
resp = number1 - number2
print("The result is: " + str(resp))
def Multiply_Numbers(number1, number2):
resp = number1 * number2
print("The result is: " + str(resp))
def Divide_Numbers(number1, number2):
resp = number1 / number2
print("The result is: " + str(resp))
def main():
opc = 0
while True:
print ""
print "-----------------------------"
print "[1] SUMAR DOS NUMEROS |"
print "[2] RESTAR DOS NUMEROS |"
print "[3] MULTIPLICAR DOS NUMEROS |"
print "[4] DIVIDIR DOS NUMEROS |"
print "[5] SALIR |"
print "-----------------------------"
print ""
num1 = input("Escribe el valor del primer numero: ")
num2 = input("Escribe el valor del segundo numero: ")
opc = input("Elije una opcion del menu: ")
if opc == 1:
Sumar(num1,num2)
elif opc == 2:
Restar(num1, num2)
elif opc == 3:
Multiplicar(num1, num2)
elif opc == 4:
Dividir(num1, num2)
elif opc == 5:
print "Saliendo del programa...."
exit(0)
else:
print "La opcion " + str(opc) + " no existe, elige otra"
if __name__ == '__main__':
main()
| false |
72e43455f7f2994a35546ca9085877625e56ac61 | Neoakay005/BalancedParentheses | /main.py | 1,748 | 4.25 | 4 | """
Problem
........
Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses.
Given an expression as input, we need to find out whether the parentheses are balanced or not.
For example, "(x+y)*(z-2*(6))" is balanced, while "7-(3(2*9))4) (1" is not balanced.
The problem can be solved using a stack.
Push each opening parenthesis to the stack and pop the last inserted opening parenthesis whenever a closing parenthesis is encountered.
If the closing bracket does not correspond to the opening bracket, then stop and say that the brackets are not balanced.
Also, after checking all the parentheses, we need to check the stack to be empty -- if it's not empty, then the parentheses are not balanced.
Implement the balanced() function to return True if the parentheses in the given expression are balanced, and False if not.
Sample Input:
(a( ) eee) )
Sample Output:
False
------------------------
You can use a simple list for a stack. Use list.insert(0, item) to push on the stack, and list.pop(0) to pop the top item. You can access the top element of the stack using list[0].
------------------------
"""
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.insert(0, item)
def pop(self):
return self.items.pop(0)
def print_stack(self):
print(self.items)
cl = Stack()
def balanced(expression):
for i in expression:
if i == "(":
cl.push(i)
elif i == ")":
try:
cl.pop()
except:
return False
return cl.is_empty()
print(balanced(input())) | true |
01058927ffbc225a538ca793218e1213949dc34a | Aakarsh2406/ChatterBox | /leap_year.py | 303 | 4.15625 | 4 | q=int(input('Enter the year'))
def is_leap(year):
if year%4==0:
return True
elif year%100==0 and year%400==0:
return True
else :
return False
q=is_leap(q)
if q==True:
print('You Entered a Leap Year::! congrats')
else :
print('Sorry,Try again')
| false |
42eb4ab4bf10dc16d7c595783b269fb6512d119f | xmenji/RSA | /rsa.py | 1,631 | 4.21875 | 4 | #RSA Assignment for Discrete Mathematics Class
print("Enter 2 PRIME numbers for 'p' and 'q'.")
#USER INPUTS NUMBER
p = input("p: ")
q = input("q: ")
n = int(p) * int(q)
print("\nn = " + str(n))
#Public Key is made of n and e : (n,e)
tempE = 2
#e cannot be a factor of n
e = 0
#phi = (p-1)*(q-1)
phi = (int(p)-1) * (int(q)-1)
print("phi = " + str(phi))
#ENCRYPTION
#CALCULATE PUBLIC KEY : e
# 1 < e < phi(n)
# e != a factor of n
for x in range(0, phi):
if n % tempE == 0 or phi % tempE == 0:
tempE += 1
if tempE % 2 == 0:
tempE += 1
else:
e = tempE
print("e = " + str(e))
print("ENCRYPTION KEY= (" + str(e) + ", " + str(n) + ")")
#DECRYPTION
#CALCULATE PRIVATE KEY : d
#d = d * e (mod phi(n)) = 1
d = 10
while True:
if (d * e) % phi == 1 :
break
else:
d += 1
print("d = " + str(d))
print("DECRYPTION KEY= (" + str(d) + ", " + str(n) + ")")
#create letters array for simple word messages
alphabet = ".abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letters = list(alphabet)
#ENCRYPTING THE MESSAGE
# c = (m^e) % n
# c = ciphertext; m = letter to be encrypted
encryptedMsg = []
#GET MESSAGE
msg = input("\nEnter simple message (letters only): ")
msgArray = list(msg)
print(msgArray)
#encrypt
for x in msgArray:
encryptedMsg.append( ( letters.index(x)**e) % n )
#FINAL ENCRYPTED MESSAGE
print("\nEncrypted message: ")
print(encryptedMsg)
#DECRYPTING THE MESSAGE
# m = (c^d) % n
# m = decrypted letter; c = ciphertext
decryptedMsg = []
for x in encryptedMsg:
decryptedMsg.append( letters[(x**d) % n] )
print("\nDecrypted Message: ")
print(decryptedMsg)
| false |
a9a129f61241e532862a313e76c1d2b5ce4398bd | SoniyaMG/Cross-Language-Clone-Detection-Threat-to-Validity | /data/docker-generated-data/code_clones/p34.py | 1,028 | 4.28125 | 4 | def binarySearch(arr, l, r, x):
if (r >= l):
mid = int(l + (r - l) / 2)
# If the element is present at one
# of the middle 3 positions
if (arr[mid] == x): return mid
if (mid > l and arr[mid - 1] == x):
return (mid - 1)
if (mid < r and arr[mid + 1] == x):
return (mid + 1)
# If element is smaller than mid, then
# it can only be present in left subarray
if (arr[mid] > x):
return binarySearch(arr, l, mid - 2, x)
# Else the element can only
# be present in right subarray
return binarySearch(arr, mid + 2, r, x)
# We reach here when element
# is not present in array
return -1
# Driver Code
arr = [3, 2, 10, 4, 40]
n = len(arr)
x = 4
result = binarySearch(arr, 0, n - 1, x)
if (result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result) | true |
097e27e1337c52b4cccd379dfd7ddce81fe0aa5c | ermeydan-coder/Python-IT-Fundamentals | /workshop_exercises/5_Armstrog_module.py | 658 | 4.1875 | 4 | '''Soru 4 de yazdığınız fonksiyonu is_int.py uzantılı olarak kaydedin ve daha önceden yaptığınız amstrong sayısını
bulma ödevinde kullanmak üzere import edip kullanın.'''
from is_int import get_integer
while True:
number = get_integer("Please enter a number to check if it's an Armstrong Number : ")
len_num = len(number)
list_num = list(number)
armstrong = 0
for i in list_num:
armstrong += int(i) ** len_num
if int(number)==armstrong:
print("{} is an Armstrong number".format(int(number)))
break
else:
print("{} is not an Armstrong number".format(int(number)))
| false |
9baffc7db14de19b4697739a00dfb038c86643e4 | OFAutomation/OFAutomation | /examples/Assert/Assert.py | 2,729 | 4.21875 | 4 | #!/usr/bin/env python
'''
Created on 26-Nov-2012
@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
'''
class Assert:
'''
This example shows the usage of the assert
assert_equal :
-------------
utilities.assert_equals(expect=1,actual=1,
onpass="Expected result equal to Actual",
onfail="Expected result not equal to Actual")
assert_matches:
--------------
expect = "Res(.*)"
actual = "Result : Test Passed"
utilities.assert_equals(expect=expect,actual=actual,
onpass="Expected result matches with Actual",
onfail="Expected result didn't matched with Actual")
assert_greater:
--------------
expect = 10
actual = 5
utilities.assert_greater(expect=expect,actual=actual,
onpass=str(expect)+" greater than the "+str(actual),
onfail=str(expect)+" is not greater than "+str(actual))
assert_lesser:
-------------
expect = 5
actual = 10
utilities.assert_lesser(expect=expect,actual=actual,
onpass=str(expect)+" is lesser than the "+str(actual),
onfail=str(expect)+" is not lesser than the "+str(actual))
ofautomation>run Assert example 1
'''
def __init__(self):
self.default = ""
def CASE1(self,main):
'''
This test case will showcase usage of assert to verify the result
'''
main.case("Using assert to verify the result ")
main.step("Using assert_equal to verify the result is equivalent or not")
expect = main.TRUE
actual = main.TRUE
utilities.assert_equals(expect=expect,actual=actual,onpass=str(expect)+" is equal to "+str(actual),onfail=str(expect)+" is not equal to "+str(actual))
main.step("Using assert_matches to verify the result matches or not")
expect = "Res(.*)"
actual = "Result"
utilities.assert_matches(expect=expect,actual=actual,onpass=expect+" is matches to "+actual,onfail=expect+" is not matching with "+actual)
main.step("Using assert_greater to verify the result greater or not")
expect = 10
actual = 5
utilities.assert_greater(expect=expect,actual=actual,onpass=str(expect)+" greater than the "+str(actual),onfail=str(expect)+" is not greater than "+str(actual))
main.step("Using assert_greater to verify the result lesser or not")
expect = 5
actual = 10
utilities.assert_lesser(expect=expect,actual=actual,onpass=str(expect)+" is lesser than the "+str(actual),onfail=str(expect)+" is not lesser than the "+str(actual))
| true |
4d1d82a466723ac19ecbf9ea6b757b21ae88a8ce | yeomye/pyworks | /day18/loopexample/for_1to10.py | 433 | 4.21875 | 4 | # for문 사용하기
# range(시작값, 종료값+1, 증감값)
# 1은 기본이므로 생략 가능
for i in range(1, 11, 1):
print(i , end=" ")
print( )
# 0 ~ 9 출력 : 초기값이 없는 경우 0부터 시작임
for i in range(10):
print(i , end=" ")
print( )
for i in range(1, 11, 2):
print(i, end=" ")
print()
# 1~ 10 중 홀수 출력
for i in range(1, 11, 1):
if i%2 == 1:
print(i , end=" ")
| false |
7e7f02b7a9c486b24593ee4c7ebdb19bcaf89af0 | anthonyandras/python-playground | /allMyCats.py | 486 | 4.1875 | 4 | # a very bad way to write this program
print('Enter the name of cat 1: ')
catName1 = input()
print('Enter the name of cat 2: ')
catName2 = input()
print('Enter the name of cat 3: ')
catName3 = input()
print('Enter the name of cat 4: ')
catName4 = input()
print('Enter the name of cat 5: ')
catName5 = input()
print('Enter the name of cat 6: ')
catName6 = input()
print('The cat names are:')
print("{} {} {} {} {} {}".format(catName1, catName2, catName3, catName4, catName5, catName6)
| true |
0e18b8becc42db0819e4da08663c136c27de9a7b | thiago1623/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 390 | 4.21875 | 4 | #!/usr/bin/python3
"""
function that adds 2 integers.
"""
def add_integer(a, b=98):
"""method that return a + b"""
try:
if isinstance(a, (float, int)) is False:
raise TypeError("a must be an integer")
if isinstance(b, (float, int))is False:
raise TypeError("b must be an integer")
return(int(a) + int(b))
except:
raise
| true |
677492a51bbb9858dd50816bfd2622d004e22cda | dasgeekchannel/RandomPythonCode.py | /RestaurantBill.py | 607 | 4.15625 | 4 | #Restaurant Bill Calculator
#Created by DasGeek
#Get inputs
total_bill = input("What's the total on the bill? : ")
tip_perc = input("What is the percent of tip you want to leave (Ex: 15, 20) : ")
sharing = input("How many people are sharing the bill? : ")
tip_amount = float(total_bill) * float(tip_perc) / 100 #calculate tip amount converting to floats
print("Tip Amount $", tip_amount) # printing total tip
ftotal = float(total_bill) + float(tip_amount) #creating total of tip and full bill
print("total bill $", ftotal/int(sharing)) #dividing total of bill w/ tip by the amount of people sharing bill
| true |
484743298a58454a0d03a8512579e4c6ea809c59 | lsl-88/OCT-GAN-Generator | /Dataset/Dataset.py | 1,303 | 4.15625 | 4 | from abc import ABC, abstractmethod
class DatasetError(Exception):
pass
class Dataset(ABC):
"""
Abstract base class representing a dataset. All datasets should subclass from this baseclass and need to implement
the 'load' function. Initializing of the dataset and actually loading the data is separated as the latter may
require significant time, depending on where the data is coming from.
"""
def __init__(self, **kwargs):
"""Initialize a dataset."""
@abstractmethod
def data_details(self):
"""Obtain the data details.
:return: self
"""
return self
@abstractmethod
def load(self, **kwargs):
"""Load the data list.
:param kwargs: Arbitrary keyword arguments
:return: self
"""
return self
@property
def print_stats(self):
"""This function prints information on the dataset. This method uses the fields that need to be implemented
when subclassing.
"""
if self.condition == 'CNV':
print('Condition: ', self.condition)
print('Total images: ', self.total_imgs)
elif self.condition == 'DME':
print('Condition: ', self.condition)
print('Total images: ', self.total_imgs)
elif self.condition == 'Drusen':
print('Condition: ', self.condition)
print('Total images: ', self.total_imgs)
pass
| true |
b9e3b0eab3ee0fc45bb6fbcc624f863d46ea9ee7 | codingEzio/code_py_book_algorithms_unlocked | /AlgoDS_miscellaneous/prime_find_primes_less_than_n.py | 1,094 | 4.125 | 4 | """
This is an implementation based the ancient algorithm for finding
all prime numbers up to any given limit (aka. Sieve of Eratosthenes).
"""
from utils.annotated_types import IntList, BoolList
def get_primes(n: int) -> IntList:
"""Return list of all primes less than n,
Using sieve of Eratosthenes.
"""
if n <= 0:
raise ValueError("'n' must be a positive integer.")
sieve_size: int
if n % 2 == 0:
sieve_size = n // 2 - 1
else:
sieve_size = n // 2
sieve: BoolList = [True for _ in range(sieve_size)]
prime_list: IntList = []
if n >= 2:
prime_list.append(2)
for i in range(sieve_size):
if sieve[i]:
value_at_i = i * 2 + 3
prime_list.append(value_at_i)
for j in range(i, sieve_size, value_at_i):
# print(i, sieve[i])
# print(j, sieve_size, value_at_i)
sieve[j] = False
return prime_list
if __name__ == "__main__":
inputs: IntList = [17, 25, 1000]
for i in inputs:
print(f"{i:>2} {get_primes(i)}")
| false |
97d1f38657d9148a5b613ef8fd0bee9332843a45 | jasper-lu/portfolio | /algorithms/sorting/insertion_sort.py | 478 | 4.1875 | 4 | import utils
#my implementation of insertion sort
#insertion sort works by iterating and inserting the values in their correct spots
def insertion_sort(arr):
for n in xrange(1, len(arr)):
for m in xrange(n, 0, -1):
if arr[m] < arr[m - 1]:
utils.swap(arr, m, m - 1)
else:
break
return arr
if __name__ == "__main__":
sortedarr = insertion_sort(utils.random_array(10))
print(utils.test(sortedarr))
| true |
d9731f059d66d13bbaa59712691486c88245972e | BishuPoonia/coding | /Python/matrix_multiplication_modified.py | 1,660 | 4.21875 | 4 | def rc():
a_r, a_c, b_r, b_c = 0, 0, 0, 0
print("Enter the no. of Rows and Columns for matrix A and B:")
a_r = int(input("no. of rows in matrix A: "))
a_c = int(input("no. of column in matrix A: "))
b_r = int(input("no. of rows in matrix B: "))
b_c = int(input("no. of columns in matrix B: "))
print("Order of Matrix A: ", a_r, "x", a_c, sep='')
print("Order of Matrix B: ", b_r, "x", b_c, sep='')
if a_r != b_c:
print("Multiplication of two matrices is only possible if " + \
"no. of rows in Matrix A equals to " + \
"no. of columns in Matrix B.")
rc()
else:
return a_r, b_r
def result_matrix(n):
r = []
temp = 0
for i in range(n):
r.append([])
for j in range(n):
r[i].append(temp)
return r
def matrix_input(a_row, b_row):
print("Elements in Matrix A:\n")
for i in range(a_row):
a.append(list(map(int, input().split())))
print("Elements in Matrix B:\n")
for j in range(b_row):
b.append(list(map(int, input().split())))
def matrix_multiplication():
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
result[i][j] += a[i][k] * b[k][j]
def display():
print("Matrix A:\n")
for i in a: print(i)
print("Matrix B:\n")
for i in b: print(i)
print("Multiplication of Matrix A and B:\n")
for i in result: print(i)
a, b = [], []
a_row, b_row = rc()
result = result_matrix(a_row)
matrix_input(a_row, b_row)
matrix_multiplication()
display()
| true |
3bdb069b14da405c5ca4d0734f3f7a90856c1793 | BishuPoonia/coding | /Python/List.py | 467 | 4.25 | 4 | # Creating a List
a = [1,2,3,4,5,6,7,8,9,0]
b = [0,9,8,7,6,5,4,3,2,1]
# Printing a List
print(a) # prints entire List
print(a[4]) # prints an element on a specific Index
print(b[-1]) # prints an element from the right side
for i in (-1,-len(b)-1, -1): # Starting from Right(-1), total elements in the list (length), steps per iteration(-1)
print(b[i])
# Dropping a List
x = [1,1,1,1,1,1,1,1,1,1]
print(x)
drop(x)
print(x)
| true |
c692019be35dbaa5f9eb1ecf742f7e1a3d70b776 | Puzyrinwrk/Stepik | /Поколение Python/Соотношение.py | 981 | 4.21875 | 4 | """
Напишите программу, которая проверяет, что для заданного четырехзначного числа выполняется следующее соотношение:
сумма первой и последней цифр равна разности второй и третьей цифр.
Формат входных данных
На вход программе подаётся одно целое положительное четырёхзначное число.
Формат выходных данных
Программа должна вывести «ДА», если соотношение выполняется, и «НЕТ» — если не выполняется.
Sample Input 1:
1614
Sample Output 1:
ДА
Sample Input 2:
1234
Sample Output 2:
НЕТ
"""
n = int(input())
a = n // 1000
b = ((n // 100) % 10)
c = ((n // 10) % 10)
d = n % 10
if a + d == b - c:
print('ДА')
else:
print('НЕТ') | false |
6fb26cd81b4fba5ef29e558772b358e9b1590e3c | Puzyrinwrk/Stepik | /Поколение Python/Номер_купе .py | 1,209 | 4.25 | 4 | """
В купейном вагоне имеется 9 купе с четырьмя местами для пассажиров в каждом. Напишите программу,
которая определяет номер купе, в котором находится место с заданным номером (нумерация мест сквозная, начинается с 1).
Формат входных данных
На вход программе подаётся целое число – место с заданным номером в вагоне.
Формат выходных данных
Программа должна вывести одно число – номер купе, в котором находится указаное место.
Sample Input 1:
1
Sample Output 1:
1
Sample Input 2:
2
Sample Output 2:
1
Sample Input 3:
3
Sample Output 3:
1
"""
n = int(input()) # Место в вагоне
if 0 < n < 5:
print(1)
elif 4 < n < 9:
print(2)
elif 8 < n < 13:
print(3)
elif 12 < n < 17:
print(4)
elif 16 < n < 21:
print(5)
elif 20 < n < 25:
print(6)
elif 24 < n < 29:
print(7)
elif 28 < n < 33:
print(8)
else:
print(9)
| false |
81c628bbecbc28fe08169f00c50c046967e24270 | Puzyrinwrk/Stepik | /Поколение Python/Правильный_многоугольник.py | 997 | 4.25 | 4 | """
Правильный многоугольник — выпуклый многоугольник, у которого равны все стороны и все углы между смежными
сторонами.
Даны два числа: натуральное число n и вещественное число a. Напишите программу, которая находит площадь указанного
правильного многоугольника.
Формат входных данных
На вход программе подается два числа n и a, каждое на отдельной строке.
Формат выходных данных
Программа должна вывести вещественное число – площадь многоугольника.
Sample Input:
3
2.0
Sample Output:
1.7320508075688779
"""
from math import *
n = int(input())
a = float(input())
print(float((n * (a ** 2)) / (4 * tan(pi / n))))
| false |
928e06682c42ee44a7296fe9d543606b66d6031f | Puzyrinwrk/Stepik | /Поколение Python/Дробная_часть.py | 571 | 4.28125 | 4 | """
Дано положительное действительное число. Выведите его дробную часть.
Формат входных данных
На вход программе подается положительное действительное число.
Формат выходных данных
Программа должна вывести дробную часть числа в соответствии с условием задачи.
Sample Input 1:
44.45
Sample Output 1:
0.45
"""
a = float(input())
print(a % int(a))
| false |
919af70a1cb2790b8af4acd2474da9dc3dff38e6 | Puzyrinwrk/Stepik | /Поколение Python/Пол_и_потолок.py | 583 | 4.28125 | 4 | """
Напишите программу, вычисляющую значение [x] + [x] по заданному вещественному числу x.
Формат входных данных
На вход программе подается одно вещественное число x.
Формат выходных данных
Программа должна вывести одно число – значение указанного выражения.
Sample Input 1:
5.5
Sample Output 1:
11
"""
from math import *
x = float(input())
print((ceil(x)) + floor(x))
| false |
f6fd2a9a478e2c30da4d3187b0f13874a9c1c01b | Puzyrinwrk/Stepik | /Поколение Python/Возрастная_группа.py | 1,058 | 4.375 | 4 | """
Напишите программу, которая по введённому возрасту пользователя сообщает, к какой возрастной группе он относится:
до 13 включительно – детство;
от 14 до 24 – молодость;
от 25 до 59 – зрелость;
от 60 – старость.
Формат входных данных
На вход программе подаётся одно целое число – возраст пользователя.
Формат выходных данных
Программа должна вывести название возрастной группы.
Sample Input 1:
4
Sample Output 1:
детство
Sample Input 2:
91
Sample Output 2:
старость
Sample Input 3:
40
Sample Output 3:
зрелость
"""
age = int(input())
if age <= 13:
print('детство')
elif 14 <= age <= 24:
print('молодость')
elif 25 <= age <= 59:
print('зрелость')
else:
print('старость')
| false |
a96bfa2b01ff52037ec8266af0bab6da7a512219 | Puzyrinwrk/Stepik | /Поколение Python/Your_name.py | 937 | 4.46875 | 4 | """
Напишите программу, которая считывает с клавиатуры две строки – имя и фамилию пользователя и выводит фразу:
«Hello [введенное имя] [введенная фамилия]! You just delved into Python».
Формат входных данных
На вход программе подаётся две строки (имя и фамилия), каждая на отдельной строке.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
Примечание. Между firstname lastname вставьте пробел =)
Sample Input 1:
Anthony
Joshua
Sample Output 1:
Hello Anthony Joshua! You just delved into Python
"""
name = input()
lastname = input()
print(f'Hello {name} {lastname}! You just delved into Python')
| false |
254ab7504125b0ef37e20c0cb396dd6d8b357da4 | AntoineGF/AdventOfCode2018 | /day2/puzzle2.py | 2,987 | 4.15625 | 4 | # Exercise:
# Scan the likely candidate boxes and count the number that have an ID containing
# EXACTLY TWO OF ANY LETTER, and those containing EXACTLY THREE of any letter.
# Multiply those two to get a checksum
# ----- PART ONE -----
import os
path = 'your_path'
os.chdir(path)
# Read the data from the text file
results = []
i = 0
with open('input.txt', newline = '') as inputfile:
data = inputfile.readlines()
# Remove the '\n' from elements
for ele in data:
print(ele)
data[i] = ele[:-1]
i += 1
# example data
# data = ['abcdef', 'bababc', 'abbcde', 'abcccd', 'aabcdd', 'abcdee', 'ababab']
total2 = 0
total3 = 0
for row in data:
# Get a dictionary that counts the occurences of every character in the element (row)
occurences = dict((letter, row.count(letter)) for letter in set(row))
# Get the values only
counting = list(occurences.values())
# Count the EXACT number 2 and EXACT 3
two_letters = sum([ele == 2 for ele in counting])
three_letters = sum([ele == 3 for ele in counting])
# Controlling for the specific conditions
if two_letters >= 1 and three_letters >= 1:
total2 += 1
total3 += 1
elif two_letters >= 1 and three_letters == 0:
total2 += 1
total3 += 0
elif two_letters == 0 and three_letters >= 1:
total2 += 0
total3 += 1
# Results:
print(str(total2) + ' boxes contain a letter which appears exactly twice.')
print(str(total3) + ' boxes contain a letter which appears exactly three times.')
print('Out of ' + str(len(data)) + ' Box IDs.')
print('RESULT: ' + str(total2 * total3))
## ----- PART TWO -----
# Ex: What letters are common between the two correct box IDs?
# data = ['abcde', 'fghij', 'vweyo', 'fguij']
foundID = False
i = 0
check = [None]*len(data[0]) # 26 is length of a row in input.txt
for row in data:
print("Checking the " + str(i) +"th row.")
letters_initial = [letter for letter in data[i]]
# Index to compare the rest of the data (could probably be more efficient)
for j in range(i + 1, len(data)):
letters_compare = [letter for letter in data[j]]
for pos in range(0, len(letters_initial)):
check[pos] = ( letters_initial[pos] == letters_compare[pos] )
# If (len(letters) - 1) elements in common, it means that only one letter is different.
if sum(check) == len(letters_initial) - 1:
# print(letters_initial)
# print(letters_compare)
print(data[i])
print(data[j])
# If found, do not iterate over the remaining obsverations
foundID = True
break
# Break if found the two desired IDs.
if foundID:
break
# Use the next row and compare it with rest of data input
i += 1
# Store the common strings
result = ''
for idx in range(0, len(data[i])):
if check[idx]:
result += letters_initial[idx]
print('The common string are: ' + result + '.')
| true |
7df7caff24b05ef188ccdd01678d1be985aa3d91 | JeffUsername/python-stuff | /python/test/Ch3/CollatSeq.py | 294 | 4.28125 | 4 | def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = number * 3 + 1
print(number)
return number
num = input()
try:
num = int(num)
while num != 1:
num = collatz(num)
except ValueError:
print('Enter an int, stupid') | false |
473bb74048be2e01ec298eff936aef30221d40c1 | sashaobucina/interview_prep | /python/medium/word_search.py | 1,427 | 4.125 | 4 | from typing import List
def word_search(board: List[List[int]], word: str) -> bool:
"""
# 79: Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
those horizontally or vertically neighboring. The same letter cell may not be used more than once.
This sol'n uses backtracking (DFS) to search for the word.
"""
m, n = len(board), len(board[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def dfs(word, x, y):
if word == "":
return True
ret_val = False
if 0 <= x < m and 0 <= y < n:
ch, rest = word[0], word[1:]
if board[x][y] != ch:
return False
board[x][y] = "#"
for dx, dy in directions:
if dfs(rest, x + dx, y + dy):
ret_val = True
break
board[x][y] = ch
return ret_val
for i in range(m):
for j in range(n):
if dfs(word, i, j):
return True
return False
if __name__ == "__main__":
board = [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
]
assert word_search(board, "ABCCED")
assert word_search(board, "SEE")
assert not word_search(board, "ABCB")
print("Passed all tests!")
| true |
f30fa19cc46d27e9129a99da225f691f40625993 | sashaobucina/interview_prep | /python/isomorphic_strings.py | 687 | 4.21875 | 4 | """
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order
of characters. No two characters may map to the same character but a character may map to itself.
"""
def is_isomorphic(s: str, t: str):
if (len(s) != len(t)):
return False
mapping = {}
char_set = set()
for i in range(len(s)):
if (s[i] not in mapping):
if t[i] in char_set:
return False
mapping[s[i]] = t[i]
char_set.add(t[i])
else:
if mapping[s[i]] != t[i]:
return False
return True
if __name__ == "__main__":
print(is_isomorphic("ab", "aa")) | true |
03e821f81b0e0fff1b84021495120882ffa0a6d0 | sashaobucina/interview_prep | /python/min_moves.py | 816 | 4.125 | 4 | """
Given a non-empty integer array of size n, find the minimum number of moves required to make all
array elements equal, where a move is incrementing n - 1 elements by 1.
"""
def minMoves(nums: list) -> int:
# Increasing n - 1 elements by 1 is same as decreasing the max element by 1.
return sum(nums) - min(nums) * len(nums)
"""
Given a non-empty integer array, find the minimum number of moves required to make all array elements
equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
"""
def minMovesII(nums: list) -> int:
nums.sort()
count, i, j = 0, 0, len(nums) - 1
while i < j:
count += nums[j] - nums[i]
i += 1
j -= 1
return count
if __name__ == "__main__":
nums = [1, 2, 3, 5, 7]
print(minMoves(nums))
print(minMovesII(nums)) | true |
98fb9c706640f8c6a32984b6a4cecf9df79e31c0 | sashaobucina/interview_prep | /python/move_zeros.py | 574 | 4.25 | 4 | from typing import List
def move_zeros(nums: List[int]) -> None:
"""
# 283: Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
"""
count = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[count], nums[i] = nums[i], nums[count]
count += 1
if __name__ == "__main__":
nums = [0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]
move_zeros(nums)
assert nums == [1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0, 0]
print("Passed all tests!")
| true |
a351b1c1ca5da18e02bd93a1c724428b1793e4bf | sashaobucina/interview_prep | /python/easy/unique_email_addresses.py | 1,655 | 4.25 | 4 | from typing import List
def num_unique_emails(emails: List[str]) -> int:
"""
# 929: Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?
"""
email_set = set()
for email in emails:
local, domain = email.split("@")
# ignore anything after '+' sign
if "+" in local:
local = local[:local.index("+")]
# remove all periods
local = local.replace(".", "")
email_set.add(local + "@" + domain)
return len(email_set)
if __name__ == "__main__":
emails = [
"test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"
]
assert num_unique_emails(emails) == 2
print("Passed all tests!")
| true |
89ca36c26ae487d8076aaa6b615da55e708068f3 | sashaobucina/interview_prep | /python/medium/valid_sudoku.py | 2,324 | 4.25 | 4 | from typing import List
def valid_sudoku(board: List[List[str]]) -> bool:
"""
# 36: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
"""
if not board or len(board) != len(board[0]):
return False
for idx in range(len(board)):
if not (_validate_row(board, row=idx) and _validate_col(board, col=idx)
and _validate_box(board, box=idx)):
return False
return True
def _validate_row(board: List[List[int]], row: int) -> bool:
s = set()
for val in board[row]:
if val == ".":
continue
if val in s:
return False
s.add(val)
return True
def _validate_col(board: List[List[int]], col: int) -> bool:
s = set()
for row in range(len(board)):
curr_val = board[row][col]
if curr_val == ".":
continue
if curr_val in s:
return False
s.add(curr_val)
return True
def _validate_box(board: List[List[int]], box: int) -> bool:
s = set()
row = 3 * (box // 3)
col = 3 * (box % 3)
for i in range(row, row + 3):
for j in range(col, col + 3):
val = board[i][j]
if val == ".":
continue
if val in s:
return False
s.add(val)
return True
if __name__ == "__main__":
board = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]
]
assert valid_sudoku(board)
print("Passed all tests!")
| true |
56cacff40ac99d16f5b0037347376b8b5619f3c7 | sashaobucina/interview_prep | /python/medium/queue_reconstruction_w_height.py | 845 | 4.125 | 4 | from typing import List
def reconstruct_queue(people: List[List[int]]) -> List[List[int]]:
"""
# 406: Suppose you have a random list of people standing in a queue. Each person is described by
a pair of integers (h, k), where h is the height of the person and k is the number of people in
front of this person who have a height greater than or equal to h. Write an algorithm to
reconstruct the queue.
"""
q = []
people.sort(key=_lambda)
for p in people:
q.insert(p[1], p)
return q
def _lambda(person):
return -person[0], person[1]
if __name__ == "__main__":
people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
actual = reconstruct_queue(people)
expected = [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
assert actual == expected
print("Passed all tests!")
| true |
23b9d6713e72830df1d9a4f5b2604ba0051c84e8 | sashaobucina/interview_prep | /python/medium/sort_colors.py | 1,476 | 4.40625 | 4 | from typing import List
from collections import defaultdict
RED = 0
WHITE = 1
BLUE = 2
def sort_colors(colors: List[int]) -> None:
"""
# 75: Given an array with n objects colored red, white or blue, sort them in-place so that
objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
NOTE: You are not suppose to use the library's sort function for this problem.
"""
# counting sort solution
d = defaultdict(int)
for color in colors:
d[color] += 1
i, color = RED, 0
while color <= BLUE:
if d[color] == 0:
color += 1
continue
colors[i] = color
d[color] -= 1
i += 1
def sort_colors_one_pass(colors: List[int]) -> None:
i = 0
red, blue = 0, len(colors) - 1
while i <= blue:
if colors[i] == RED:
colors[i], colors[red] = colors[red], colors[i]
red += 1
i += 1
elif colors[i] == BLUE:
colors[i], colors[blue] = colors[blue], colors[i]
blue -= 1
else:
i += 1
if __name__ == "__main__":
colors = [2, 0, 2, 1, 1, 0]
sort_colors(colors)
assert colors == [0, 0, 1, 1, 2, 2]
colors = [2, 0, 2, 1, 1, 0]
sort_colors_one_pass(colors)
assert colors == [0, 0, 1, 1, 2, 2]
print("Passed all tests!")
| true |
13c811ea4b5bc2dce6442701b3c39b5656cebde2 | sashaobucina/interview_prep | /python/easy/valid_palindrome.py | 896 | 4.1875 | 4 | def is_palindrome(s: str) -> bool:
"""
# 125: Given a string, determine if it is a palindrome, considering only alphanumeric characters
and ignoring cases.
NOTE: For the purpose of this problem, we define empty string as valid palindrome.
"""
s = s.lower()
lo, hi = 0, len(s) - 1
while lo < hi:
if s[lo].isalnum() and s[hi].isalnum():
if s[lo] != s[hi]:
return False
lo += 1
hi -= 1
continue
if not s[lo].isalnum():
lo += 1
if not s[hi].isalnum():
hi -= 1
return True
if __name__ == "__main__":
assert is_palindrome("")
assert is_palindrome("racecar")
assert is_palindrome("aba_")
assert not is_palindrome("0P")
assert not is_palindrome("hello")
assert not is_palindrome("5racecare")
print("Passed all tests!")
| true |
336259ae18fac5eff6eedc75616077453d4d0ae2 | sashaobucina/interview_prep | /python/is_power_of_three.py | 563 | 4.40625 | 4 | def is_power_of_three(n: int) -> bool:
"""
# 326: Given an integer, write a function to determine if it is a power of three.
"""
if n == 0:
return False
curr = n
while curr % 3 == 0:
curr //= 3
return curr == 1
if __name__ == "__main__":
assert is_power_of_three(1)
assert is_power_of_three(3)
assert is_power_of_three(27)
assert not is_power_of_three(28)
assert not is_power_of_three(0)
assert not is_power_of_three(-3)
assert not is_power_of_three(-28)
print("Passed all tests!")
| false |
d062fe55f1e8a5e91ed4b580ce8b79bf763670dc | sashaobucina/interview_prep | /python/easy/most_common_word.py | 1,329 | 4.1875 | 4 | import string
from typing import List
from collections import defaultdict
def most_common_word(paragraph: str, banned: List[str]) -> str:
"""
# 819: Given a paragraph and a list of banned words, return the most frequent word that is not in
the list of banned words.
It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation.
Words in the paragraph are not case sensitive.
The answer is in lowercase
"""
# remove all punctuation and make paragraph case insensitive
exclude = set(string.punctuation)
paragraph = "".join(
ch.lower() if ch not in exclude else " " for ch in paragraph)
# count all occurences of non-banned words
banned = set(banned)
d = defaultdict(int)
for word in paragraph.split():
if not word in banned:
d[word] += 1
# extract most frequent non-banned word
_max, res = 0, ""
for word, count in d.items():
if count > _max:
_max = count
res = word
return res
if __name__ == "__main__":
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
assert most_common_word(paragraph, ["hit"]) == "ball"
print("Passed all tests!")
| true |
d5d5300cc780e02e7a8a39b51f8e0c2ea6538530 | sashaobucina/interview_prep | /python/easy/water_bottles.py | 753 | 4.34375 | 4 | def num_water_bottles(num_bottles: int, num_exchange: int) -> int:
"""
# 1518: Given numBottles full water bottles, you can exchange numExchange empty water bottles for
one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Return the maximum number of water bottles you can drink.
"""
ans = num_bottles
while num_bottles >= num_exchange:
x, y = divmod(num_bottles, num_exchange)
ans += x
num_bottles = x + y
return ans
if __name__ == "__main__":
assert num_water_bottles(9, 3) == 13
assert num_water_bottles(15, 4) == 19
assert num_water_bottles(5, 5) == 6
assert num_water_bottles(2, 3) == 2
print("Passed all tests!")
| true |
6daf8d5d4ca60ca0813ca42b183c7b13682eafde | mohanashwin999/Python-Tutorial | /functions.py | 1,464 | 4.125 | 4 | def my_function():
print("Hello from a function")
my_function()
#passing arguements
# def my_function(fname):
# print(fname + " Refsnes")
# my_function("Emil")
# my_function("Tobias")
# my_function("Linus")
#Number of Arguements
# def my_function(fname, lname):
# print(fname + " " + lname)
# my_function("Emil", "Refsnes")
#Variable length arguements
# def my_function(*kids):
# print("The youngest child is " + kids[2])
# my_function("Emil", "Tobias", "Linus")
#Keyword arguements
# def my_function(child3, child2, child1):
# print("The youngest child is " + child3)
# my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
#Variable keyword arguements
# def my_function(**kid):
# print("His last name is " + kid["lname"])
# my_function(fname = "Tobias", lname = "Refsnes")
#Default parameters
# def my_function(country = "Norway"):
# print("I am from " + country)
# my_function("Sweden")
# my_function("India")
# my_function()
# my_function("Brazil")
#list as arguement
# def my_function(food):
# for x in food:
# print(x)
# fruits = ["apple", "banana", "cherry"]
# my_function(fruits)
#return Statement
# def my_function(x):
# return 5 * x
# print(my_function(3))
# print(my_function(5))
# print(my_function(9))
#Lambda function
# x = lambda a : a + 10
# print(x(5))
#More arguements
# x = lambda a, b, c : a + b + c
# print(x(5, 6, 2)) | true |
2d8a673848b1e4b03693a9cb3afc37084b0663e1 | 15032373556/mystudy | /study/chapter4/section.py | 400 | 4.5625 | 5 | pizzas = ['onion','chicken','cheese','beef','ham']
#打印前三
print('The first three items in the list are: ')
for pizza in pizzas[:3]:
print(pizza)
#打印中间三个
print('\nThree items from the middle of the list are: ')
for pizza in pizzas[1:4]:
print(pizza)
#打印后三
print('\nThe last three items in the list are: ')
for pizza in pizzas[-3:]:
print(pizza) | true |
02a47d8e29da58c131c6b3d5e1c8d92fb4f5ccac | voyager1684/Basic-Physics | /4FunctionCalculator.py | 421 | 4.1875 | 4 | problem = input("Enter the operation (Put a space between each element): \n")
num1 = float(problem[0:problem.find(" ")])
operator = str(problem[problem.find(" ") + 1 : problem.find(" ") + 2])
num2 = float(problem[problem.find(" ") + 3:])
if operator == "+":
print(num1+num2)
elif operator == "-":
print(num1-num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1/num2)
| true |
3d54abf78e3adc15c3763576c85456fe73ba664c | MalayAgr/linear_regression | /regression.py | 2,897 | 4.5625 | 5 | import numpy as np
import matplotlib.pyplot as plt
def cost_function(X, y, theta, m, *, reg_param=0):
'''
Calculates the value of the cost function
For a given X, y, theta and m
The formula for the cost function is as follows:
cost, J = (1/2 * m) * (sum((X * theta - y) ^ 2) + sum(theta[1:] ^ 2))
Arguments:
X: ndarray, (m, n) matrix consisting of the features
y: ndarray, (m, 1) matrix with y-values
theta: ndarray, (n, 1) matrix with parameter values
m: int, number of training examples
reg_param: int, keyword-only argument, the regularization parameter
Returns:
J: ndarray, (1,1) matrix with value of cost function
'''
predictions = X @ theta
sqr_err = np.square(predictions - y)
theta_sqr = np.square(theta[1:])
return 1 / (2 * m) * (sum(sqr_err) + reg_param * np.sum(theta_sqr))
def plot_cost(costs):
'''
Plots the values of the cost function
Against number of iterations
If gradient descent has converged, graph flattens out
And becomes constant near the final iterations
Otherwise, it shows a different trend
'''
plt.plot(costs)
plt.xlabel("Number of iterations")
plt.ylabel("J(theta)")
plt.title("Iterations vs Cost")
plt.show()
def gradient_descent(X, y, theta, alpha, num_iters, m, *, reg_param=0):
'''
Runs gradient descent num_iters times
To get the optimum values of the parameters
The algorithm can be looked at here:
https://en.wikipedia.org/wiki/Gradient_descent
It can be vectorized as follows:
theta = theta - (alpha / m) * (((X * theta - y)' * X)' + reg_param * theta[1:])
Arguments:
X: ndarray, (m, n) matrix consisting of the features
y: ndarray, (m, 1) matrix with y-values
theta: ndarray, (n, 1) matrix with initial parameter values
alpha: float, the learning rate
num_iters: int, the number of times algorithm is to be run
m: int, the number of training examples
reg_param: int, keyword-only argument, the regularization parameter
Returns:
theta: ndarray, (n, 1) matrix with optimum param values
'''
# Array to store cost values at each iteration
# Will be used to check convergence of the algorithm
j_vals = np.zeros((num_iters, 1))
for i in range(num_iters):
# (X * theta - y)'
difference = np.transpose((X @ theta - y))
# ((X * theta - y)' * X)'
delta = np.transpose(difference @ X)
# Regularization is not done for the first theta value
# A temporary variable is used where the first theta value is 0
temp = theta
temp[0] = 0
theta = theta - (alpha / m) * (delta + reg_param * temp)
j_vals[i][0] = cost_function(X, y, theta, m)
# Plotting the cost values
plot_cost(j_vals)
return theta
| true |
a729ac4ee74ca47b4adacadef00377c56ef4723d | Orixur/CTEDA---2020 | /practica1/cola.py | 542 | 4.1875 | 4 | class Cola(object):
"""
Esta implementación representa una cola (FIFO). Podría utilizarse la clase
que provee Python, queue.Queue
"""
def __init__(self):
self._data = []
def put(self, _data):
self._data.append(_data)
def head(self):
return self._data[0]
def get(self):
head = self._data[0]
del self._data[0]
return head
@property
def queue(self):
return self._data
@property
def isEmpty(self):
return not self._data | false |
e8f4b2f631dd4f1a46fd6319aef33d3b679e91c9 | coloriordanCIT/pythonlabs | /lab2/Lab2/Q3.py | 2,454 | 4.125 | 4 | '''
Created on 01 Oct 2018
@author: colinoriordan
Application that will ask the user to enter the number of packages purchased. The
program will display the amount of the discount (if any) and the total amount of the
purchase after the discount. If a user indicates a negative quantity then they
should be told that the quantity value should be greater than zero.
'''
#Global Variables
packageCost=99
minQuantity=1
#main function of the application
def main():
quantity=getNumPackages()
calculateCostOfOrder(quantity, calculateDiscountPc(quantity))
"""
getNumPackages function - gets user input of how many orders they would like to purchase
(int)return numPackages - no. of packages the buyer would like to purchase.
"""
def getNumPackages():
#no. of packages variable
numPackages=0
#Prompts user for an input until the input is valid i.e. >0.
while numPackages<1:
numPackages=int(input("How many packages would you like to order? "))
#User is told the quantity of packages should be greater than the minimum quantity to proceed.
if numPackages<minQuantity:
print("\nQuantity of packages should be at least ", minQuantity, "\n")
quantity=numPackages
return numPackages
"""
calculateDiscountPc function - calculates the % discount the buyer is eligible for
arg quantity - the quantity of packages in the order
return discountPc - the % discount the buyer is eligible for
"""
def calculateDiscountPc(quantity):
#discount percentage variable - default at 0% for quantity of 1-9
pcDiscount=0
#if the quanity is 10-19, percentage discount is 20%
if quantity>9 and quantity<20:
pcDiscount=20
#if the quanity is 20-49, percentage discount is 30%
elif quantity>19 and quantity<50:
pcDiscount=30
#if the quanity is 20-49, percentage discount is 40%
elif quantity>49 and quantity<100:
pcDiscount=40
#if the quanity is 100 or >, percentage discount is 250%
elif quantity>99:
pcDiscount=50
return pcDiscount
def calculateCostOfOrder(quantity, pcDiscount):
totalCost=packageCost*quantity
discount=(totalCost/100)*pcDiscount
discountedCost=totalCost-discount
print("Total cost before discount: ", totalCost)
print("Discount : ", discount)
print("Discounted cost : ", discountedCost)
main()
| true |
4295cda6133253e76cb87e0c8edda02dd86410c8 | aldrinbrillante/python-decorators | /Code_prac_inOrder/4_Nested_Funcs.py | 705 | 4.25 | 4 | # repl.it: https://repl.it/@MakeSchool/NestedFunctions#main.py
def print_msg(msg):
# This is the outer enclosing function
print("I am in the outer function")
def printer(txt):
# This is the nested function
print("I am in the nested function")
print(txt)
printer(msg)
# print_msg("Hello")
#The code below will throw an error. Read the error.
# printer("Hello")
# def weather(temp):
# def say_weather(t):
# print(f"Today's temp is: {t}")
def weather(90):
def say_weather(t):
# prints todays temperature
print(f"today's temp is {t}")
def say_goodnight():
print("Good night!")
say_weather(90)
say_goodnight()
weather(90)
| true |
838cc4cf1aa06a0f997cf35a62ca3e0794741be8 | Umang070/Python_Programs | /dict_intro.py | 537 | 4.15625 | 4 | # unordered collections of data in key : value pair.
user = {'name' : "umang", 'age':19,'fav_movies' : ["3 idiots","dhamal"]}
# user = dict( name ="umang", age=19)
# print(user)
# print(user['name'])
if 'umang' in user.values():
print("present")
else :
print("not present")
# numbers ,,,,, string,,,list can be added in dict.
# user_i = {}
# user_i['number'] = 20
# print(user_i)
for i in user.values():
print(i)
for key,val in user.items():
print(f"key is : {key} and value is : {val}") | true |
ea73cec97b5634b9494989ce5d3d0646caeadef2 | MDCGP105-1718/portfolio-gpcroucher | /week3/ex8.py | 1,005 | 4.3125 | 4 | import math
annual_salary = float(input("How much do you earn per year? "))
semi_annual_raise = float(input("By what proportion does your salary increase every six months? "))
portion_saved = float(input("What proportion of your income will you save? "))
total_cost = float(input("How much does your dream house cost? "))
portion_deposit = 0.2
current_savings = 0
investment_return = 0.04
monthly_interest = current_savings * (0.04 / 12)
monthly_salary = annual_salary / 12
months_required = 0
while current_savings < portion_deposit * total_cost: # while savings is less than deposit
for x in "abcdef": # runs six times
current_savings += current_savings * (investment_return / 12) # adds monthly interest
current_savings += monthly_salary * portion_saved # adds earnings
months_required += 1 # increments months elapsed so far
monthly_salary += monthly_salary * (semi_annual_raise / 12) # adds raise every six months
print ("Number of months:", months_required)
| true |
ffea3d3724984547e3ea04fd5a95f047cb0e51a4 | MDCGP105-1718/portfolio-gpcroucher | /week2/ex7.py | 512 | 4.15625 | 4 | import math
annual_salary = float(input("How much do you earn per year? "))
portion_saved = float(input("What proportion of your income will you save? "))
total_cost = float(input("How much does your dream house cost? "))
portion_deposit = 0.2
current_savings = 0
monthly_interest = current_savings * (0.04 / 12)
monthly_salary = annual_salary / 12
months_required = math.ceil((portion_deposit * total_cost) / ((monthly_salary * portion_saved) + monthly_interest))
print("Number of months:", months_required)
| true |
62fa4fda1c971a380ede2c837b04dd14c5cae584 | monika200/AWS | /Python/Programs/python2.py | 423 | 4.40625 | 4 | # Python program to demonstrate
# nested if statement
i = 13
if (i == 13):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 12 and smaller than 15")
| true |
68e5f2487ce791ea28111a6d71299e54c33785f4 | lucascavalare/python3 | /basics/sum_integers.py | 293 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Sum integer numbers until 0 is typed.
When the program finds typed 0, then goes out showing the sum amount.
"""
sum = 0
while True:
x = int(input("Type the number: (0 goes out): "))
if x == 0:
break
sum = sum + x
print ("Sum: %d" %sum)
| true |
0d003f3d899dac0a3f2081b73c0ff215d55f7463 | febacc103/febacc103 | /advanced python/exception handling/constructor/constructor1.py | 573 | 4.3125 | 4 | #initialize instance variable
# class Person:
# def __init__(self,name,age):
# self.age=age
# self.name=name
# def printvalue(self):
# print("name",self.name)
# print("age:",self.age)
# obj=Person("feba",29)
# obj.printvalue()
#4. Create an Animal class using constructor and build a child class for Dog?
class Animal:
def __init__(self,Aname):
self.name=Aname
class Dog(Animal):
def
def printvalue(self):
print("name",self.name)
print("age:",self.age)
obj=Person("feba",29)
obj.printvalue()
| true |
5992fd547b3c5c8aacecef0a81762da554e0385b | aushafy/Python-Write-and-Read-File | /write.py | 512 | 4.53125 | 5 | """
Simple program to write an instance to a file.
open() argument: 'w' to write in empty file, 'a' to appending to a file.
"""
filename = 'empty.txt' # select file that you want to add some text inside.
with open(filename, 'w') as file_obj: # open function with 'w' argument it is mean you will add some text in empty file
file_obj.write("I love programming!\n") # write() function to writes some text inside files
file_obj.write("I love Python!\n") # to write multiple lines with \n in the end of line | true |
63c8b44682e00cc7efc30e7755d0987331f60d2a | alvaronaschez/amazon | /leetcode/easy/math/power_of_three.py | 585 | 4.25 | 4 | """
https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/745/
Power of Three
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
"""
from math import log
class Solution:
def isPowerOfThree(self, n: int) -> bool:
try:
return 3**round(log(n, 3)) == n
except ValueError:
return False
| true |
fe1150ad0c42f438ebded1ee357f6bcb89e849ea | alvaronaschez/amazon | /leetcode/amazon/arrays_and_strings/rotate_image.py | 1,631 | 4.15625 | 4 | """
https://leetcode.com/explore/interview/card/amazon/76/array-and-strings/2969/
Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the
input 2D matrix directly. DO NOT allocate another 2D matrix and do the
rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
from typing import List
import unittest
def rotate(m: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
Es más difícil de lo que parece
"""
N = len(m)
for k in range(N // 2):
for i in range(k, N - k - 1):
m[k][i], m[i][-1-k], m[-1-k][-1-i], m[-1-i][k] = \
m[-1-i][k], m[k][i], m[i][-1-k], m[-1-k][-1-i]
class TestRotate(unittest.TestCase):
def test_rotate(self):
m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r1 = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
m2 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
r2 = [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
rotate(m1)
rotate(m2)
self.assertEqual(m1, r1)
self.assertEqual(m2, r2)
if __name__ == "__main__":
unittest.main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.