blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
35bb652c0f240421bfa70a6199e254096aebbefa | robgoyal/CodingChallenges | /Exercism/python/reverse-string/reverse_string.py | 236 | 4.375 | 4 | def reverse(text):
"""
str -> str
Reverse a string.
Examples:
>>> reverse("")
""
>>> reverse("hello")
"olleh"
>>> reverse("What's your name?")
"?eman ruoy s'tahW"
"""
return text[::-1]
| true |
9663daead070165822cbb191d30fbd4eaa73be25 | robgoyal/CodingChallenges | /CodeFights/Arcade/Intro/darkWilderness/knapsackLight.py | 574 | 4.125 | 4 | # Name: knapsackLight.py
# Author: Robin Goyal
# Last-Modified: July 21, 2017
# Purpose: Check the total weight your knapsack can hold from
# the weight of two different items
# Note: Forced solution
def knapsackLight(value1, weight1, value2, weight2, maxW):
if (weight1 + weight2) <= maxW:
return value1 + value2
elif weight1 <= maxW and weight2 <= maxW:
return max(value1, value2)
elif weight1 <= maxW and weight2 > maxW:
return value1
elif weight2 <= maxW and weight1 > maxW:
return value2
else:
return 0 | true |
0cef65ad00a794aee620f23d9c13faaf878bb46c | robgoyal/CodingChallenges | /FireCode/Level_1/missingNumberFrom1To10.py | 474 | 4.375 | 4 | # Name: missingNumberFrom1To10.py
# Author: Robin Goyal
# Last-Modified: August 7, 2017
# Purpose: Find the number missing in the order of 1 to 10
# Note: Found other solutions where the sum of 1 to 10 minus the sum of the list
# returned the missing number
def find_missing_number(list_numbers):
# Check if the list from 1 to 10 if equal to value in list parameter
for i in range(1, len(list_numbers) + 1):
if list_numbers[i-1] != i:
return i | true |
8e40c15622ed0abbf7e635e3941f2d05b93dec83 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/11-to-20/betweenTwoSets.py | 1,186 | 4.15625 | 4 | # Name: betweenTwoSets.py
# Author: Robin Goyal
# Last-Modified: November 12, 2017
# Purpose: Count the number of times a value is a multiple of all elements
# in list A and a factor of all elements in list B
def main():
n, m = list(map(int, input().strip().split(' ')))
a = list(map(int, input().strip().split(' ')))
b = list(map(int, input().strip().split(' ')))
print(get_total(a, b))
def get_total(A, B):
'''
a: list of numbers
b: list of numbers
x must be a multiple of all elements in A and a factor
of all elements in B
output: return the number of x's that meet the conditions
'''
count_x = 0
# Only the max value in A could be a multiple of all elements in A
# Only the min value of B could be a factor of all elements in B
for i in range(max(A), min(B) + 1, max(A)):
# List of T/F values which meet the conditions
cond_a = list(map(lambda elem: i % elem == 0, A))
cond_b = list(map(lambda elem: elem % i == 0, B))
# Check if any values in lists didnt meet this condition
if not(False in cond_a or False in cond_b):
count_x += 1
return count_x
| true |
14977d9de6c198fd7492ed70decde4d6c4f9144c | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/21-to-30/electronicsShop.py | 1,516 | 4.21875 | 4 | # Name: electronicsShop.py
# Author: Robin Goyal
# Last-Modified: November 21, 2017
# Purpose: Calculate the amount of money spent at an electronics shop
def getMoneySpent(keyboards, drives, s):
'''
The maximum amount of money that can be spent on a single keyboard
and drive without exceeding her budget
s: max budget
keyboards: list of prices for keyboards
drives: list of prices for drives
return: int represent money spent, -1 if no money spent
'''
# Initialize max
max_combo_price = -1
for keyboard in keyboards:
# View current maximum combo price for 1 keyboard and match with all drives
curr_max_combo_price = -1
for drive in drives:
combo_price = keyboard + drive
# Check if combo is greater than the current max and if less than budget
if combo_price > curr_max_combo_price and combo_price < s:
current_max = combo_price
# Update the maximum combo price
if current_max > max_combo_price:
max_combo_price = curr_max_combo_price
return max_combo_price
def main():
# Retrieve problem inputs
s, n, m = list(map(int, input().strip().split(' ')))
keyboards = list(map(int, input().strip().split(' ')))
drives = list(map(int, input().strip().split(' ')))
# Max amount of money she can spend on a keyboard and drive
# -1 if she can't purchase both items
moneySpent = getMoneySpent(keyboards, drives, s)
print(moneySpent)
| true |
0d8df21193abb042e99156135f5896754e8c4f86 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/41-to-50/flatlandSpaceStations.py | 1,027 | 4.4375 | 4 | # Name: flatlandSpaceStations.py
# Author: Robin Goyal
# Last-Modified: January 31, 2018
# Purpose: Determine the maximum distance an astronaut will
# have to travel to a space station
def flatlandSpaceStations(n, c):
'''
(int, list: int) -> int
n is the number of cities and c is the indices at which
a city contains a space station.
Return the maximum distance for an astronaut to travel
from any city to a space station.
>>> flatlandSpaceStations(7, [1, 5, 6])
2
'''
stations = sorted(c)
max_distance = 0
# Calculate distances for cities at ends which don't contain stations
if stations[0] != 0:
max_distance = max(max_distance, stations[0] - 0)
if stations[-1] != (n - 1):
max_distance = max(max_distance, (n - 1) - stations[-1])
# Maximum distance for cities in between stations is halfway
for i in range(len(stations) - 1):
max_distance = max(max_distance, (stations[i + 1] - stations[i]) // 2)
return max_distance
| true |
c9a8f2a748fa632dc1a2a1feeb275b1968f5e3c5 | robgoyal/CodingChallenges | /CodeWars/8/multiply.py | 326 | 4.3125 | 4 | # Name: multiply.py
# Author: Robin Goyal
# Last-Modified: March 3, 2018
# Purpose: Implement multiply
def multiply(a, b):
"""
(int, int) -> int
Return the multiplication of a and b
Examples:
>>> multiply(2, 5)
10
>>> multiply(-1, 3)
-3
>>> multiply(-3, -4)
12
"""
return a * b
| false |
51cae524f60d055e449dca4873941206325d4d5d | robgoyal/CodingChallenges | /CodeWars/7/numberPeopleInBus.py | 557 | 4.40625 | 4 | # Name: numberPeopleInBus.py
# Author: Robin Goyal
# Last-Modified: June 7, 2018
# Purpose: Calculate the remaining number of people
# on the bus after the last stop
def number(bus_stops):
"""bus_stops
Return the remaining number of people
on the bus after the last stop.
Examples:
>>> number([[10, 0], [5, 3], [2, 4], [7, 4]])
13
>>> number([[5, 0], [5, 5], [3, 6], [0, 2]])
0
"""
hop_ons = sum(stop[0] for stop in bus_stops)
hop_offs = sum(stop[1] for stop in bus_stops)
return hop_ons - hop_offs
| true |
1e189ea6efb35bf1d8f0ab74b3f558a83fc5ab98 | robgoyal/CodingChallenges | /CodeFights/Arcade/Intro/throughTheFog/circleOfNumbers.py | 269 | 4.25 | 4 | # Name: circleOfNumbers.py
# Author: Robin Goyal
# Last-Modified: July 13, 2017
# Purpose: Given a circular radius n and an input number,
# find the number which is opposite the input number
def circleOfNumbers(n, firstNumber):
return (firstNumber + n / 2) % n | true |
806b3371f326efcbfa503d157529e9431dadef74 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/41-to-50/sherlocksAndSquares.py | 775 | 4.375 | 4 | # Name: sherlocksAndSquares.py
# Author: Robin Goyal
# Last-Modified: December 14, 2017
# Purpose: Calculate the number of squares in between a range
import math
def sherlocksAndSquares(A, B):
'''
A -> int: start of range
B -> int: end of range
return -> int: number of squares in between [A, B]
'''
# Obtain a value whose square is greater than A
start = math.ceil(math.sqrt(A))
end = start
# Increment end to test number of values which are squared are less than B
while (end ** 2 <= B):
end += 1
return (end - start)
def main():
tests = int(input().strip())
for test in range(tests):
A, B = [int(i) for i in input().strip().split()]
result = sherlocksAndSquares(A, B)
print(result)
| true |
722582520522b4fa825ad4ecb6b21c860aa2f7f3 | robgoyal/CodingChallenges | /CodeWars/6/sortTheOdd.py | 663 | 4.4375 | 4 | # Name: sortTheOdd.py
# Author: Robin Goyal
# Last-Modified: March 17, 2018
# Purpose: Implement solution to Sort the Odd
def sort_array(arr):
"""
(list: int) -> list: int
Return an array of the odd numbers in sorted order
while the even numbers remain in place.
Examples:
>>> sort_array([5, 3, 2, 1, 5, 4, 8, 7])
[1, 3, 2, 5, 5, 4, 8, 7]
"""
odds = sorted([i for i in arr if i % 2 == 1])
index = 0
sorted_arr = []
for i, value in enumerate(arr):
if value % 2 == 1:
sorted_arr.append(odds[index])
index += 1
else:
sorted_arr.append(value)
return sorted_arr
| true |
d25f598c24122cf9cf1544bfc27c383d8dfe4aba | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/41-to-50/encryption.py | 1,234 | 4.40625 | 4 | # Name: encryption.py
# Author: Robin Goyal
# Last-Modified: February 16, 2018
# Purpose: Encrypt a string
import math
def encryption(s):
"""
(str) -> str
Return a string by encrypting a string s using
the following encryption scheme.
Split s into rows (floor(sqrt(s)) and cols (ceil(sqrt(s))).
Create words from letters in each column and split separate
the words by a string.
Examples:
>>> encryption("haveaniceday")
hae and via ecy
>>> encryption("feedthedog")
fto ehg ee dd
>>> encryption("chillout")
clu hlt io
"""
# Initialize rows and cols for the grid
rows = math.floor(math.sqrt(len(s)))
cols = math.ceil(math.sqrt(len(s)))
# Increment rows if grid size is < size of s
if rows * cols < len(s):
rows += 1
# Create grid for encryption scheme
grid = [s[i:i + cols] for i in range(0, len(s), cols)]
encrypted_msg = ""
for i in range(cols):
for j in range(rows):
# Access letter if index exists
try:
encrypted_msg += grid[j][i]
except IndexError:
pass
# Separate words with space
encrypted_msg += " "
return encrypted_msg
| true |
81b86a6268ff3d043cfe3fe95bbbbe419c1b6307 | robgoyal/CodingChallenges | /CodeWars/7/sumNNumbers.py | 422 | 4.375 | 4 | # Name: sumNNumbers.py
# Author: Robin Goyal
# Last-Modified: March 13, 2018
# Purpose: Return the sum of the first n numbers
def f(n):
"""
(int) -> int or None
Return None if n is a positive integer, else
return the sum of the first n numbers.
Examples:
>>> f(100)
5050
>>> f(-5)
None
>>> f(6.0)
None
"""
return n * (n + 1) // 2 if (type(n) == int and n > 0) else None
| true |
dcf235636f58ccff76d4f24b22417e6d9a796e2c | robgoyal/CodingChallenges | /Exercism/python/bob/bob.py | 775 | 4.125 | 4 | def hey(phrase):
"""
str -> str
Return responses depending on what is said to Bob.
>>> hey("Tom-ay-to, tom-aaaah-to.")
"Whatever."
>>> hey("WATCH OUT!")
"Whoa, chill out!"
>>> hey("You are, what, like 15?")
"Sure."
>>> hey("WHAT THE HELL WERE YOU THINKING?")
"Calm down, I know what I'm doing!"
>>> hey("")
"Fine. Be that way!"
"""
phrase = phrase.strip()
answer = ""
if phrase.endswith("?") and phrase.isupper():
answer = "Calm down, I know what I'm doing!"
elif phrase.endswith("?"):
answer = "Sure."
elif phrase.isupper():
answer = "Whoa, chill out!"
elif not phrase:
answer = "Fine. Be that way!"
else:
answer = "Whatever."
return answer
| false |
d4ce245927f33fc5f58140997a35c756a86d0800 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/11-to-20/catsAndMouse.py | 858 | 4.15625 | 4 | # Name: catsAndMouse.py
# Author: Robin Goyal
# Last-Modified: November 17, 2017
# Purpose: Determine which cat will reach the mouse first
def catAndMouse(a, b, c):
'''
a: position of cat A
b: position of cat B
c: position of mouse C
result: "Cat A" if cat A reaches mouse first
"Cat B" if cat B reaches mouse first
"Mouse C" if both reach at the same time
'''
# Check for absolute locations in case mouse is in between the cats
if abs(a - c) < abs(b - c):
print("Cat A")
elif abs(a - c) > abs(b - c):
print("Cat B")
else:
print("Mouse C")
def main():
q = int(input().strip())
for a0 in range(q):
x, y, z = list(map(int, input().strip().split(' ')))
result = catAndMouse(x, y, z)
print(result)
if __name__ == "__main__":
main()
| true |
7d4b342b0188b0d97bfeb8510edf6c63afd96a23 | CPrimbee/scripts_python | /scriptBasico.py | 1,461 | 4.125 | 4 | #!/usr/bin/python
#coding: utf-8
print "O cabeçalho em script é: #!/usr/bin/env python ou #!/usr/bin/python"
print "Para não aparecer o erro (SyntaxErro: Non-ASCII character), use essa linha logo abaixo do cabeçalho: #coding :utf-8"
print "Os comentários começam com: #"
print "Para imprimir na tela, ex.: print Olá, mundo!"
print "Não precisa do ';' no final, mas coloquei aqui e não apresentou erro;";
print "Pode ter comentários no meio da linha como aqui e não aparece" # comentário
variavel = "Minha Variável"
print variavel
print "Cria-se variáveis assim: variavel = 'Minha Variável' , pode usar aspas simples ou duplas"
soma = 8+8;
print "Operações aritiméticas (soma+, subtração-, multiplicação*, divisão/): print 8+8 = ",soma
print "Para concatenar strings basta usar o +, ex.: print 'Pala'+'vra'"
print 'Pala'+'vra'
print "Mas pra concatenar strins e integer, use-se vírgula(,) (soma é uma variável/integer 8+8), ex.: print '8+8', soma"
print "Pode-se usar a vírgula para separar também strings, no entanto, ficará com espaço, ex.: 'Pala','vra' --> Pala vra"
"comentário aspas duplas"
'comentário aspas simples'
print "Comentários também podem ser entre aspas simples ou duplas, como há nesse script, mas não pode misturá-los num mesmo comentário"
print 7/2
print 7.0/2
print 'Na divisão quando quiser obter números irracionais(float), tem de fazer também com float, como exemplo acima'
| false |
606e46df077d834a86a684b4bb6bc0bf9542cdac | kranz912/Algorithms | /Problems/5-CheckPangram.py | 606 | 4.3125 | 4 | '''
Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.
Examples :
"The quick brown fox jumps over the lazy dog" is a Pangram [Contains all the characters from 'a' to 'z']
"The quick brown fox jumps over the dog" is not a Pangram [Doesn't contains all the characters from 'a' to 'z', as 'l', 'z', 'y' are missing]
'''
def checkPangram(S):
dict = {}
S= S.lower()
for s in S:
if s.isalpha():
dict.update({s:1})
return len(dict) ==26
print(checkPangram("The quick brown fox jumps over the lazy dog"))
| true |
527ffee1162fb0545368a799e3763483ccb6d093 | krsnvijay/prime | /prime_consecutive_check.py | 2,155 | 4.25 | 4 | import sys
from functools import cache
import primesieve
@cache
def sum_digits(number):
"""
Sums all the digits of a number recursively to a single digit number
eg: 192 = 1 + 9 + 2 = 12
=> 12 = 1 + 2 = 3
so 192 will turn to 3
"""
result = sum(int(digit) for digit in str(number))
# exit condition
if result < 10:
return result
else:
# recursively call sum_digits
return sum_digits(result)
def primes_to_digits(number):
"""
Generator fn to get a prime number and a sum of its digits
"""
it = primesieve.Iterator()
prime = it.next_prime()
while prime < number:
agg_prime = sum_digits(prime)
yield prime, agg_prime
prime = it.next_prime()
def count_frequencies(number):
"""
Counts the frequencies of digit sum of primes in a given range
"""
freq = {}
for prime, agg in primes_to_digits(number):
if agg in freq:
freq[agg] += 1
else:
freq[agg] = 1
print(f"{number}: {freq}")
def check_consecutive_primes(number):
"""
Checks if prev prime and next prime have the same digit sum
"""
primes_digits = primes_to_digits(number)
prev = next(primes_digits)
for cur in primes_digits:
result = True
if prev[1] == cur[1]:
result = False
print(prev, cur, result)
yield prev, cur, result
prev = cur
def prime_digits_to_csv(generator, full_log="output\prime2digits_all.csv", false_log="output\prime2digits_false.csv"):
"""
Logs the comparision results
"""
full_log_file = open(full_log, 'w')
false_log_file = open(false_log, 'w')
for prime, agg_prime, result in generator:
if not result:
false_log_file.write(f"{prime},{agg_prime},{result}\n")
full_log_file.write(f"{prime},{agg_prime},{result}\n")
full_log_file.close()
false_log_file.close()
if __name__ == "__main__":
number = 100000
if sys.argv == 3:
number = int(sys.argv[2])
prime_digits_to_csv(check_consecutive_primes(number))
# count_frequencies(1000000000)
| true |
379af50325a45d8a599fd3d89f6a9268f02fcd95 | dhillonfarms/core-python-scripts | /NumericalProjects/fibonacci.py | 1,764 | 4.15625 | 4 | """
Discussing various approaches for generating fibonacci sequences
Using Python timeit module to find most efficient approach
"""
__author__ = 'https://github.com/dhillonfarms'
import timeit
# Using classic loop approach to get fibonacci series
def get_fibonacci_classic(num):
a = 1
b = 1
output = []
for n in range(num):
output.append(a)
c = a+b
a = b
b = c
return output
# Using generators to get fibonacci series
def get_fibonacci_generators(num):
a = 1
b = 1
for n in range(num):
yield a
c = a + b
a = b
b = c
# Using recursion to get fibonacci series
def get_fibonacci_recursion(num):
# This method will return the nth element of fibonacci series
if num == 0 or num == 1:
return num
else:
return get_fibonacci_recursion(num-1)+get_fibonacci_recursion(num-2)
# Using memonization to get fibonacci series
store_fibonacci = {}
def get_fibonacci_memonization(num):
if num == 0 or num == 1:
store_fibonacci[num] = num
if num not in store_fibonacci.keys():
store_fibonacci[num] = get_fibonacci_memonization(num-1)+get_fibonacci_memonization(num-2)
return store_fibonacci[num]
num = 20
print(get_fibonacci_recursion(10))
print(get_fibonacci_generators(10))
print(get_fibonacci_classic(10))
print(get_fibonacci_memonization(10))
print(timeit.timeit('get_fibonacci_classic(num)', 'from __main__ import get_fibonacci_classic, num', number=10000)*1000)
print(timeit.timeit('get_fibonacci_generators(num)', 'from __main__ import get_fibonacci_generators, num', number=10000)*1000)
print(timeit.timeit('get_fibonacci_recursion(num)', 'from __main__ import get_fibonacci_recursion, num', number=10000)*1000) | true |
d51c5108c8a63b7220134bdd5889bc1d0ec1576b | gokerguner/Playground | /Python/goker_miletos/pythons/isprime.py | 657 | 4.125 | 4 | #Goker Guner
import math
num=int(input("Bir sayi girin:"))
def isprime(num):
count=0
if num<0:
print("{} sayısı negatiftir".format(num))
return 0
elif num == 1:
print("1 sayısı asal veya değildir denemez.")
return 0
for i in range(2,math.floor(math.sqrt(num))+1):
if num%i == 0:
count+=1
break
if(count!=0):
print("{} sayısı asal değildir".format(num))
else:
print("{} sayısı asaldır".format(num))
return 0
isprime(num)
"""
import argparse konut satırından değer girmek için kulllanılır.
arguments=sys.argv liste olarak döner.
"""
| false |
d942c3cd31a0c0f76a79f437cca969e85ec8d5d5 | tianxingqian/study-py | /knowlage/004_functional_programming/001_Higher-order function/001_map_reduce.py | 865 | 4.4375 | 4 | # map/reduce
'''
Python内建了map()和reduce()函数。
我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:
'''
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
'''
map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
你可能会想,不需要map()函数,写一个循环,也可以计算出结果:
L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
L.append(f(n))
print(L)
''' | false |
9001e276ee0c12d82c392afaea05438824a6b6de | onahirniak/algorithms | /app/main/lists/linked_list.py | 2,335 | 4.15625 | 4 | from app.main.base.node import Node
class LinkedListNode(Node):
def __init__(self, val):
Node.__init__(self, val)
self.next = None
class LinkedList:
def __init__(self):
self.root = None
def push(self, val):
node = LinkedListNode(val)
node.next = self.root
self.root = node
def append(self, val):
if self.root:
current = self.root
while current.next:
current = current.next
current.next = LinkedListNode(val)
else:
self.root = LinkedListNode(val)
def search(self, val):
current = self.root
while current:
if current.val == val:
return current
current = current.next
return None
def reverse(self):
# Initialize three pointers prev as NULL, curr as head and next as NULL.
prev = None
current = self.root
# Iterate trough the linked list. In loop, do following.
while current:
# Before changing next of current,
# store next node
next = current.next
# Now change next of current
# This is where actual reversing happens
current.next = prev
# Move prev and curr one step forward
prev = current
current = next
self.root = prev
def remove(self, val):
# (1) -> (2) -> (3)
if not self.root:
return False
if self.root.val == val:
self.root = self.root.next
return True
prev = None
current = self.root
while current:
if current.val == val:
prev.next = current.next
return True
prev = current
current = current.next
def printList(self):
print("LINKED LIST STARTS")
current = self.root
while current:
self.visit(current)
current = current.next
print("LINKED LIST ENDS")
def search_and_print(self, val):
node = self.search(val)
if node:
print("FOUND: " + str(node.val))
else:
print("NOT FOUND: " + str(val))
def visit(self, node):
print(node.val) | true |
4066bbd2c27a2c2b5fa65d35e55e6eb6104e8279 | modcomlearning/pythonOnline | /Lesson4.py | 637 | 4.65625 | 5 | # Today , we do while loop
# While Loop repeats a task n-times
# With while a loop you can do an infinite loop(loops forever)
# There are three steps you need to do:
# 1. Create a variable to start your loop i.e x = 0
# 2. Set a condition, loop will run only if this condition is true
# The loop will not run if the condition is false
# 3. Increment - to increase
# While loop version
# Step 1
x = 0
# Step 2
while(x < 10):
print('Looping with while', x)
x = x + 1
# The for loop version
for i in range(0,10):
print('Looping with for ', i)
# The only difference is while loop can be infinite (loop forever)
| true |
c825f98e03cecae1489ff35b61f8f868677efca5 | jorjilour/python_files | /queues.py | 2,395 | 4.5 | 4 | from queue import Queue
import sys
# Initializing a queue
q = Queue(maxsize=3)
# qsize() give the maxsize
# of the Queue
print(q.qsize())
# Adding of element to queue
q.put('a')
q.put('b')
q.put('c')
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
# QUEUE USING LIST #
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
# QUEUE.DEQUE
from collections import deque
# Initializing a queue
q = deque()
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
# Removing elements from a queue
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
print("\nQueue after removing elements")
print(q)
# QUEUE AS A CLASS #
class MyQueue:
def __init__(self, maxsize=sys.maxsize):
self.queue = []
self.maxsize = maxsize
def __str__(self):
return str(self.queue)
def is_empty(self):
return self.queue == []
def is_full(self):
return len(self.queue) == self.maxsize
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if self.is_empty():
return None
return self.queue.pop(0)
def peek(self):
if self.is_empty():
return None
return self.queue[0]
def last(self):
if self.is_empty():
return None
return self.queue[-1]
def size(self):
return len(self.queue)
myQ = MyQueue(maxsize=9)
myQ.enqueue(1)
myQ.enqueue(2)
myQ.enqueue(3)
myQ.enqueue(4)
print(myQ)
myQ.dequeue()
print(myQ)
myQ.dequeue()
print(myQ)
print(myQ.maxsize)
| true |
e69fc704dceb397e33194a91bf85b96f2607913a | idaks/explanation-visualization | /prime-or-composite/prime-or-composite.py | 2,120 | 4.28125 | 4 | #!/usr/bin/env python3
import sys
print("### Running", *sys.argv, "###") # a bit of logging
N = int(sys.argv[1]) # number N > 2 to test
assert N > 2
d = 2 # trial divisor d = 2,3, ...
c = 0 # count 'composite' proofs
composite = False
while d*d <= N: # try up to d <= sqrt(N)
print()
print(".. arranging {0} in {1} columns:".format(N,d))
q,r = divmod(N,d) # Number = Quotient * Divisor + Remainder
for i in range(1, q+1): # create q*d rectangle with q rows
print("{0:3}".format(i), d * "o ") # .. and d columns
if r == 0: # No remainder?
composite = True # .. we got a composite for sure!
c = c + 1
print("==> {0} = {1} cols * {2} rows; PROVED {0} is COMPOSITE".format(N,d,q), 29 * "-")
else:
print(" ", r * "* ") # .. for now: only display remainder
print("==> {0} = {1} cols x {2} rows + {3} remaining".format(N,d,q,r))
d = d + 1
print()
print("## We are DONE! ##########################################################")
# Now d*d > N, so do one more rectangle to show we're done:
print(" ... since {0} * {0} > {1}".format(d,N))
q, r = divmod(N,d)
print(" ... and we have a WIDE rectangle with {0} cols > {1} rows:".format(d,q))
for i in range(1, q+1):
print("{0:3}".format(i), d * "o ")
print(" ", r * "* ")
print(" [ {0} = {1} cols x {2} rows + {3} remaining ]".format(N,d,q,r))
print()
print(74 * "#")
print("Using",d-2,"trial divisors,", end=" ")
if composite:
print("proved {0} times over that {1} is COMPOSITE!".format(c,N))
else:
print("PROVED ONCE ==> {0} is PRIME!".format(N))
print("Q.E.D.")
# Another way to show that we're done!?
# 17 = 4 x 4 + 1
# 5*5 = 25 = 17 + 8
# 8 = 1 x 5 + 3
# 1 o o o o o
# 2 o o o o o
# 3 o o o o o
# 4 o o . . .
# 5 . . . . .
| true |
4f8bebc809322aa2d144bcc9b1837934939076ce | SunnyVikasMalviya/Python | /Sockets/Sockets_Intro.py | 2,321 | 4.34375 | 4 | import socket
#Sockets aid in communication between 2 entities
#For example, a client and a server are 2 entities and the client requests a \
#url. Servers have their ports open that they use to serve different kinds of \
#requests. So the client generates a socket that plugs into the port of the \
#server and help communicate the server and the client.
#port 80 is used by websites for serving https requests
#port 20 for ftp
#port 22 for ssh
#lower number ports are very specific
#higher number ports are general purpose ports that can be used for any function
#Creating a Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#AF_INET denotes the connection type that we want to use, here IPv4
#can use sock_dgram in place of SOCK_STREAM
#SOCK_STREAM allows us to have a tcp connection
print(s)
'''
This was the result:
<socket.socket fd=768, family=AddressFamily.AF_INET, \
type=SocketKind.SOCK_STREAM, proto=0>
'''
server = 'pythonprogramming.net'
port = 80 #We will act like a browesr
server_ip = socket.gethostbyname(server) #Getting the ip address of our server.
#ping is a command used in prompt to get ip of the servers
print(server_ip)
#104.237.143.20
request = "GET / HTTP/1.1\nHost: "+server+"\n\n" #Forming our request
s.connect((server, port)) #Connecting our socket to the server's port
s.send(request.encode()) #Sending the request
result = s.recv(1024) #Storing the result in a variable
#1024 is the band width in which the data from the server is sent to the client.
print(result)
file = open("socket_result.txt", "w")
file.write(str(result))
file.close()
'''
result was:
b'HTTP/1.1 301 Moved Permanently\r\nDate: Tue, 20 Nov 2018 14:53:44 GMT\r\nServer:
Apache/2.4.10 (Ubuntu)\r\nLocation: https://pythonprogramming.net/\r\nContent-Length:
325\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n<!DOCTYPE HTML PUBLIC "-//
IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>301 Moved Permanently</title>\n</head>
<body>\n<h1>Moved Permanently</h1>\n<p>The document has moved <a href="https://
pythonprogramming.net/">here</a>.</p>\n<hr>\n<address>Apache/2.4.10 (Ubuntu) Server
at pythonprogramming.net Port 80</address>\n</body></html>\n'
'''
#The b at the start of the result denotes byte strings.
| true |
347c04e45398da2ca4ea23a7ce9e544afa970696 | SunnyVikasMalviya/Python | /HackerRank-Solutions/Count-SubString.py | 453 | 4.40625 | 4 | def count_substring(string, sub_string):
'''
Function to count number of times a substring occurs in a string.
'''
n = len(string)-len(sub_string)+1
cnt = 0
for _ in range(n):
if string[_:_+len(sub_string)] == sub_string:
cnt = cnt+1
return cnt
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
| true |
b873309e52739c7f8f3b79c73d6dd3ebf2d0259a | SunnyVikasMalviya/Python | /Intermediate Python/Generators.py | 2,416 | 4.25 | 4 | '''
Generators
'''
#Generators don't return things, they yield it.
#We will create our own simple generator
def gen_func():
"""
Simple example of our own generator.
"""
yield 'Corona Corona'
yield 'Corona Corona'
yield 'Corona Corona'
yield 'Me hun ek Corona'
def normal_func_without_gen():
"""
A function trying to break the secret combo without using a generator.
See how many break statements are present to cease the processing and also
so many logic statements involved.
"""
found_combo = False
for c1 in range(10):
if found_combo:
break
for c2 in range(10):
if found_combo:
break
for c3 in range(10):
if (c1, c2, c3) == correct_combo:
print('Found the combo: {}'.format((c1,c2,c3)))
found_combo = True
break
print(c1, c2, c3)
def combo_gen():
"""
Our generator to break the combo.
"""
for c1 in range(10):
for c2 in range(10):
for c3 in range(10):
yield (c1, c2, c3)
def with_gen_func():
"""
A function trying to break the secret combo by using a our own generator
functoin combo_gen().
See how only a single break statement is present to cease the processing
and also only a single logic statement is involved.
"""
for i in combo_gen():
print(i)
if i == correct_combo:
print("Found the combo: {}".format(i))
break
if __name__ == '__main__' :
#for i in gen_func(): #means while the func is yielding a value
#print(i)
correct_combo = (4, 6, 3)
print("Finding combo using normal function without Generator.")
normal_func_without_gen()
print("\n\n")
print("Finding combo using function with generator function.")
with_gen_func()
#OUTPUT
"""
Finding combo using normal function without Generator.
0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
.
.
.
.
.
4 5 8
4 5 9
4 6 0
4 6 1
4 6 2
Found the combo: (4, 6, 3)
Finding combo using function with generator function.
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 0, 4)
(0, 0, 5)
.
.
.
.
.
(4, 5, 9)
(4, 6, 0)
(4, 6, 1)
(4, 6, 2)
(4, 6, 3)
Found the combo: (4, 6, 3)
"""
| true |
9c42e5d7f60f1e531877044fc08f7344a06b766e | SunnyVikasMalviya/Python | /Prime_In_List.py | 510 | 4.15625 | 4 | from Prime_Check import is_prime
def prime_in_list(list_):
"""
The prime_in_list function takes a list argument, iterates through all the
elements in the list, and returns a list of all the prime numbers in the
list.
"""
lst = []
for x in list_:
if is_prime(x):
lst.append(x)
return lst
#For Debugging
#print(prime_in_list([1, 2, 3, 4, 5, 6, 'A', 7, 8, 9]))
"""
INPUT
[1, 2, 3, 4, 5, 6, 7, 8, 9]
OUTPUT
[2, 3, 5, 7]
"""
| true |
807628db2cf3320fb368c29a8297cd4bd81012e0 | SunnyVikasMalviya/Python | /Mersenne_Prime.py | 710 | 4.375 | 4 | from Prime_Check import is_prime
def Mersenne_prime(n):
"""
In mathematics, a Mersenne Prime is a prime number that is one less than a
power of 2 i.e. M(n) = 2^n - 1 should be prime for some n.
The Mersenne_prime function takes a integer argument which is n in M(n) and
returns a list of Mersenne prime numbers.
"""
lst = []
for x in range(n):
num = (2**x)-1
if is_prime(num):
lst.append(num)
return lst
#For Debugging
#try :
# print(Mersenne_prime(int(input())))
#except ValueError :
# print("Enter Positive Integers Only")
"""
INPUT
31(Maximum Input)
OUTPUT
[3, 7, 31, 127, 8191, 131071, 524287]
"""
| true |
d66f9d41acb3608bfe1ab2735c1649254bbc33e5 | SunnyVikasMalviya/Python | /Intermediate Python/Multiprocessing.py | 2,138 | 4.375 | 4 | import multiprocessing
"""
CPUs have different number of processors i.e.the number of cores in your CPU.
All the programs not using multiprocessing will be allocated only a single core
to work with. So at a time you will only be using a fraction of what your whole
CPU is capable of. Say, you have a quad core processor, meaning a normal program
will be using just 25% of your CPUs capability.
Using multiprocessing, you can divide the work among all your cores and use a
larger fraction of your CPUs capability.
In the below example we want to call a function named spawn() 10 times, which should
take 10 times the time of a single call. But by using multiprocessing, we divide
the work among our cores and get the work done in lesser time.
We can actually look at the multiple process running using task manager.
"""
#Everything that you want to multiprocess needs to be put inside a fuction and then
#called through the target parameter of a Process() of a multiprocessing object.
def spawn(num):
print("Spawned {}".format(num))
if __name__ == '__main__': #Doing this is important for multiprocessing
for i in range(10):
p = multiprocessing.Process(target=spawn, args=(i,)) `,
#A trailing ',' is required if there is only a single argument
p.start() #Starts the multiprocessing
p.join()
#join() waits for one process to get finished before calling the next
#process. Without it, the processes will not wait for each other.
"""
HOW TO USE
1. Open cmd prompt and nevigate to the folder where the file is kept.
2. Run the program using 'py filename.py'
"""
"""
OUTPUT in the command prompt will look like:
#With join
C:\MvikBack\Python\ToUpload\Intermediate python>py Multiprocessing.py
Spawned 0
Spawned 1
Spawned 2
Spawned 3
Spawned 4
Spawned 5
Spawned 6
Spawned 7
Spawned 8
Spawned 9
#Without join
C:\MvikBack\Python\ToUpload\Intermediate python>py Multiprocessing.py
Spawned 1
Spawned 2
Spawned 4
Spawned 0
Spawned 7
Spawned 9
Spawned 3
Spawned 6
Spawned 5
Spawned 8
"""
| true |
623e6e566cdc9fb40d5e6da93b1600cf2d9bb366 | SunnyVikasMalviya/Python | /Radius_From_Chord_Parts.py | 1,059 | 4.15625 | 4 | """
Program for finding chord lengths or radius when two intersecting chords
are given with their lengths.
formula :
4r^2 = x^2 + y^2 + z^2 + w^2
where r = radius
x = 1st part of chord one
y = 2nd part of chord one
z = 1st part of chord two
w = 2nd part of chord two
"""
def finding_fourth_part(x, y, z):
w = (x * y) / z
return w
def finding_radius(x, y, z, w):
r = (((x**2) + (y**2) + (z**2) + (w**2)) / 4)**0.5
return r
a = int(input("How many chord parts do you know?"))
if a <= 2 or a > 4:
print("More than two chord parts should be known.")
elif a == 3:
print("Enter the known three chord parts:")
x = int(input())
y = int(input())
z = int(input())
w = finding_fourth_part(x, y, z)
r = finding_radius(x, y, z, w)
print("Radius : {}".format(r))
else :
print("Enter the known four chord parts:")
x = int(input())
y = int(input())
z = int(input())
w = int(input())
r = finding_radius(x, y, z, w)
print("Radius : {}".format(r))
| false |
493334dae982fa4307c233234bc1ad00e9b3d5a4 | Muzashii/Exercicios_curso_python | /exercicios seção 6/ex 16.py | 270 | 4.1875 | 4 | """
numeros naturais ate o numeor escolhido decrecente par
"""
numero = int(input(f'Digite um numero: '))
if(numero%2) == 0:
numero -= 1
for num in range(numero, -1, -2):
print(num)
else:
for num in range(numero, -1, -2):
print(num) | false |
773f7f6dafb220d32fb023cae1363e1eba50b742 | jeetpatel242/turtlebot3_astar | /scripts/utils.py | 1,964 | 4.15625 | 4 | #!/usr/bin/env python3
import numpy as np
import math
# Function to check if the given point lies outside the final map or in the obstacle space
def check_node(node, clearance):
# Checking if point inside map
offset = 5.1
if node[0] + clearance >= 10.1 - offset or node[0] - clearance <= 0.1 - offset or node[1] + clearance >= 10.1 - offset or node[1] - clearance <= 0.1 - offset:
print('Sorry the point is out of bounds! Try again.')
return False
# Checking if point inside circles
elif ((node[0] - (2.1 - offset)) ** 2 + (node[1] - (2.1 - offset)) ** 2 - (1 + clearance) ** 2 < 0): # circle
print('Sorry the point is in the circle 1 obstacle space! Try again')
return False
elif ((node[0] - (2.1 - offset)) ** 2 + (node[1] - (8.1 - offset)) ** 2 - (1 + clearance) ** 2 < 0): # circle
print('Sorry the point is in the circle 2 obstacle space! Try again')
return False
# Checking if point inside squares
elif (((node[0] - (0.35 - offset) + clearance > 0) and (node[0] - (1.85 - offset) - clearance < 0)) and (
(node[1] - (4.35 - offset) + clearance > 0) and (node[1] - (5.85 - offset) - clearance < 0))):
print('Sorry the point is in the square 1 obstacle space! Try again')
return False
elif (((node[0] - (3.75 - offset) + clearance > 0) and (node[0] - (6.45 - offset) - clearance < 0)) and (
(node[1] - (4.25 - offset) + clearance > 0) and (node[1] - (5.95 - offset) - clearance < 0))):
print('Sorry the point is in the square 2 obstacle space! Try again')
return False
elif (((node[0] - (7.35 - offset) + clearance > 0) and (node[0] - (8.85 - offset) - clearance < 0)) and (
(node[1] - (2.10 - offset) + clearance > 0) and (node[1] - (4.10 - offset) - clearance < 0))):
print('Sorry the point is in the square 3 obstacle space! Try again')
return False
else:
return True
| true |
3a7778a7a96577c76dde47bed0dc1c41bc649d4f | sarahdactyl71/lpthr | /exercises/ex33.py | 402 | 4.28125 | 4 | def while_loop(times, increment):
i = 0
numbers = []
while i < times:
print(f"At the top i is {i}")
numbers.append(i)
i += increment
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
print(f"""Here is the result of the while loop: \n
{while_loop(6, 2)}
""")
| true |
91178a5ee27fa127d03c2b8f6db73673f6735c37 | ancylq/leetcode | /detect_capital.py | 840 | 4.46875 | 4 | # coding:utf-8
'''
Given a word, you need to judge whether the usage of capitals in it is
right or not.
We define the usage of capitals in a word to be right when one of the
following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital if it has more than
one letter, like "Google".
'''
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word is not None and ( \
word.isupper() or \
word.islower() or \
(word[0].isupper() and word[1:].islower()))
if __name__ == '__main__':
word = 'USA'
s = Solution()
print s.detectCapitalUse(word) | true |
cf7d3496fa7bd37aecdd0268bfd6628f5e5f7034 | florin-postelnicu/PythonFlorin01 | /IfElseElif/Multiplication4.py | 1,244 | 4.21875 | 4 |
import random
yesno = True
correct = 0
incorrect = 0
while(yesno):
print(" This program helps you to learn the multiplication table!")
a = random.randint(1, 10)
b = random.randint(1, 10)
print("Find the product of the numbers :", a , " * ", b)
product = a*b
print("Please Enter your answer ")
guess = int(input("Answer "))
count = 0
while( count <3):
count = count + 1
if(product == guess):
print ("Your answer is correct, Congrats!")
correct +=3
break;
else:
incorrect +=1
print("Sorry, you should try again, the real answer is not that \nYou have some more trails " )
print("You have 3 trails. So far you tryied :", count , " time(s)")
print("Find the product of the numbers :", a, " * ", b)
print("Please Enter your answer")
guess = int(input("Answer "))
score = correct - incorrect
print("Score is ", score)
print("Do you want to play again? y/n ")
yn = str(input("Enter y or n "))
if(yn != 'y'):
yesno = False
print("Thank you for playing thegame. Your score is ", score)
exit()
| true |
1915944dbe1b4a252697b765a26087e65c8102b9 | michaelbenninghoven-sparks/PythonPrograms | /3a) Map+ReverseMap.py | 1,264 | 4.4375 | 4 | import time
#Asking for first name
name1=input("Enter a name.\n")
name1=name1.rstrip()
#Asking for first number
number1=input("Enter their phone number.\n")
number1=number1.rstrip()
#Asking for second name
name2=input("Enter a name.\n")
name2=name2.rstrip()
#Asking for second number
number2=input("Enter their phone number.\n")
number2=number2.rstrip()
#Asking for third name
name3=input("Enter a name.\n")
name3=name3.rstrip()
#Asking for third number
number3=input("Enter their phone number.\n")
number3=number3.rstrip()
#put responses into map and show map
phoneBook={name1:number1,name2:number2,name3:number3}
#Asking for and finding a phone number by searching with a person
namSearch=input("\n\nWhich name would you like to find the phone number of?\n")
print("The phone number for %s is %s.\n\n"%(namSearch,phoneBook[namSearch]))
time.sleep(5)
#reversing "phone book" so keys become values and values become keys
reversedPhoneBook = dict(map(reversed, phoneBook.items()))
#Asking for and finding a person by searching with a phone number
numSearch=input("Which person would you like to find via phone number?\n")
print("The person with the phone number %s is %s.\n"%(numSearch,reversedPhoneBook[numSearch]))
| true |
ee0a8c14349e16c6ed4f4dd3cc710c53f009eb29 | SACHSTech/ics2o1-livehack2-practice-StephanieHCTam | /problem2.py | 720 | 4.21875 | 4 | """
-------------------------------------------------------------------------------
Name: problem2.py
Purpose: This program determines if a triangle is a right angle triangle.
Author: Tam.S
Created: 12/02/2021
------------------------------------------------------------------------------
"""
print(" ****** Summer Destination Calculator ****** ")
# get mark
mark = float(input("Enter your mark: "))
# get earnings before the summer
earnings = float(input("Enter your earnings before summer: "))
# compute and output summer destination
if mark >= 80 and earnings >= 500:
print("You get to go to Europe!")
elif mark >= 80:
print("You get to go to California!")
else:
print("You don't get to go away.") | true |
7331f3222ce90576e93745e90e3755b82d095266 | tjhobbs1/python | /Module7/fun_with_lists/search_sort_list.py | 1,300 | 4.625 | 5 | """
Program: search_sort_list.py
Author: Ty Hobbs
Last Day Modified: 10/08/2019
The purpose of the program is to create a list of numbers and return it to the user. It will be used for testing
Basic List Exceptions
"""
def make_list():
# This function will run a for loop calling the get_input function to get three numbers
# Params: none
# Returns a list of numbers for display to the user. Throws a ValueError if non-numeric number is caught.
list_of_numbers =[] # Empty list to store numbers in.
for i in range(3):
returned_number = get_input()
try:
returned_number = int(returned_number) # Trys and set the value to an int
list_of_numbers.append(returned_number) # If no error is caught it will append it to the list.
except ValueError:
raise ValueError # Raises a ValueError if the variable can't be changed to an int.
return list_of_numbers
def get_input():
# This function gets the user's inputs and returns it back to the make_list() function.
# Params: None
# Returns a value back to the make_list() function in the form of a string.
user_input = input("Enter a number: ")
print(user_input)
return user_input
if __name__ == '__main__':
print(make_list())
| true |
67a015f1f98a9724eec728c7cfe5442bc3bda742 | tjhobbs1/python | /Module11/override_test.py | 1,095 | 4.125 | 4 | class Shape:
"""Shape class"""
colors = ['BLUE', 'GREEN', 'ORANGE', 'PURPLE', 'RED', 'YELLOW']
def __init__(self, color='BLUE'):
self._color = color
def change_color(self, new_color):
if new_color not in self.colors:
raise InvalidColorError
self._color = new_color
def display_color(self):
return str(self._color)
class InvalidColorError(Exception):
"""InvalidColorError is derived class of Excpetion base class"""
pass
class Rectangle(Shape): # Base class is Shape
"""Rectangle derived class of Shape base class"""
def __init__(self, color='RED', l=0, w=0): # default values
super().__init__(color) # calls the base constructor
self._length = l
self._width = w
def area(self):
return self._length * self._width
def display_color(self):
return str('Rectangle color ' + self._color)
# Driver
r = Rectangle('BLUE', 3, 4.5)
try:
r.change_color('PURPLE')
except InvalidColorError:
print('Invalid color, color not changed!')
print(r.display_color())
| true |
5d46e5cd5da5caa8cad966d40f214d32cc537e0f | tjhobbs1/python | /Module6/payroll_calc.py | 1,769 | 4.40625 | 4 | """
Program: payroll_calc.py
Author: Ty Hobbs
Last date modified: 09/30/2019
The purpose of this program is to take an employees name, the number of hours they work and their rate of pay.
It will then return the total amount of pay that employee will receive.
"""
def hourly_employee_input():
# This function will get the users inputs of number of hours worked and hourly pay rate and print the paycheck amount.
# :param
# :returns: prints to the screen.
# :raises ValueError: when input is not an int
employee_name = ""
hourly_rate = 0
hours_worked = 0
# Get the employee's name.
while employee_name == "":
employee_name = input("Enter an Employee's Name: ")
# Gets the user input of the rate of pay for the employee.
while hourly_rate <= 0:
try:
hourly_rate = float(input("Enter employee's rate of pay"))
except ValueError as err: # Returns an error.
print("Enter a positive numeric value")
hourly_rate = float(input("Enter employee's rate of pay"))
# Get the user input of the number of hours worked.
while hours_worked <= 0:
try:
hours_worked = int(input("Enter the number of hours the employee worked: "))
except ValueError as err: # Returns an error.
print("Enter a positive numeric value")
hours_worked = int(input("Enter the number of hours the employee worked: "))
total_pay = hourly_rate * hours_worked
print(employee_name, "total pay is $",total_pay)
if __name__ == '__main__':
try: # check for ValueError
hourly_employee_input()
except ValueError as err:
print("Enter a positive numeric value")
hourly_employee_input()
| true |
cdbb311a8c65ef52b6a37a35e182b636a7ba3c43 | nitin2149kumar/INFYTQ-Modules | /Data Structure/Day-4/Ex_11.py | 1,384 | 4.25 | 4 | #DSA-Exercise-11
import random
def find_it(num,element_list):
#Remove pass and write the logic to search num in element_list using linear search algorithm
#Return the total number of guesses made
guesses=0
for i in element_list:
guesses+=1
print(guesses)
if num==i:
return i
#Initializes a list with values 1 to n in random order and returns it
def initialize_list_of_elements(n):
list_of_elements=[]
for i in range(1,n+1):
list_of_elements.append(i)
mid=n//2
for j in range(0,n):
index1=random.randrange(0,mid)
index2=random.randrange(mid,n)
num1=list_of_elements[index1]
list_of_elements[index1]=list_of_elements[index2]
list_of_elements[index2]=num1
return list_of_elements
def play(n):
# Step 1: Invoke initialize_list_of_elements() by passing n
# Step 2: Generate a random number from the list of elements. The number should be between 1 and n (both inclusive)
# Step 3: Invoke find_it() by passing the number generated at Step 2 and list generated at Step 1 and display the return value
# Remove pass and write the code to implement the above three steps.
element_list=[i for i in range(n)]
num=random.randrange(1,n)
print(find_it(num,element_list))
#Pass different values to play() and observe the output
play(400)
| true |
65b1767df2e775cdf12f28362e0a552647793684 | nitin2149kumar/INFYTQ-Modules | /Data Structure/Day-5/Ex_19.py | 902 | 4.125 | 4 | #DSA-Exer-19
def swap(num_list, first_index, second_index):
#Remove pass and copy the code written earlier for this function
num_list[first_index],num_list[second_index]=num_list[second_index],num_list[first_index]
def find_next_min(num_list,start_index):
#Remove pass and copy the code written earlier for this function
for i in range(len(num_list)-1):
min_index=num_list.index(min(num_list[start_index:]))
return min_index
def selection_sort(num_list):
#Remove pass and implement the selection sort algorithm to sort the elements of num_list in ascending order
for i in range(len(num_list)-1):
min_index=find_next_min(num_list,i)
swap(num_list,i,min_index)
#Pass different values to the function and test your program
num_list=[8,2,19,34,23, 67, 91]
print("Before sorting;",num_list)
selection_sort(num_list)
print("After sorting:",num_list)
| true |
5d57618679bb7c706274e5b5fe0f24f7b8b8a489 | ekarademir/algorithms_cormen_book | /ch2/insertion_sort.py | 473 | 4.125 | 4 | #!/usr/bin/python3
# -*- coding: utf8 -*-
from pprint import pprint
import random
def insertion_sort(arr):
for i in range(1, len(arr)):
pivot = arr[i]
j = i - 1
while j > -1 and arr[j] > pivot:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = pivot
return arr
if __name__ == "__main__":
random.seed(42)
arr = list(range(10))
random.shuffle(arr)
pprint(arr)
insertion_sort(arr)
pprint(arr)
| false |
e1aa509aec8569119b0eb5d467b4598677959751 | bagreve/MCOC-Proyecto-0 | /loss-of-significance.py | 2,429 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
@author:
"""
# una perdida de significancia ocurre con el cambio de numeros flotantes a binarios debido a que tienen un sesgo de
# aproximacion al tener que sumar 127 al sector de exponentes no siendo exacto.
# un caso donde se puede ver es en la funcion de aproximacion, si se aproxima a la decima estos numeros dan el mismo resultado
print round(3.45, 1)
# = 3,5
print round(3.55, 1)
# = 3,5
# El cambio ocurre ya que el programa toma el numero, lo pasa a binario, lo aproxima y lo pasa a numero nuevamente
# pero al pasar a binario acurre lo siguiente:
from decimal import Decimal
print Decimal(3.45)
#3.45000000000000017763568394002504646778106689453125
print Decimal(3.55)
#3.54999999999999982236431605997495353221893310546875
# Estos errores de aproximacion son solo un ejemplo de perdida de significancia, dentro de la pequeña variacion de decimales
# que se produce por el cambio a binario y biceversa.
# Al redondear, estas pequeñas variaciones son las que dicen si se aproxima hacia arriba o hacia abajo
def binarizar(decimal):
binario = ''
while decimal // 2 != 0:
binario = str(decimal % 2) + binario
decimal = decimal // 2
return str(decimal) + binario
numero = int(input("Introduzca la parte entera del numero a convertir en binario: "))
if numero>=0:
signo=0
if numero<0:
signo=1
bit=binarizar(numero)
print"En binario:",(binarizar(numero))
x = float(raw_input("Introduzca la parte decimal del numero a convertir en binario: "))
p = 0
while ((2**p)*x) %1 != 0:
p += 1
# print p
num = int (x * (2 ** p))
# print num
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num / 2
for i in range (p - len(result)):
result = '0' + result
result = result[0:-p] + result[-p:]
print "En binario:", result
print ""
n=int(binarizar(numero))
exponente=0
while n > 2:
exponente += 1
n= n/10
print "Exponente igual a:", exponente, "donde se debe sumar", 127
mantiza= int(bit) * 10**(22-exponente)
# es decir para pasar el numero ingresado a binario hay que pasar este nuevo exponente abinario e irá en el sector de exponente
print "Es decir, el sector binario de excedente será",binarizar(exponente+127)
print ""
print "Y el número completo en binario se escribirá como:"
print signo,binarizar(exponente+127),mantiza
| false |
49dd1f1a4ac77bb1c3a8c6c0d3e9500514fd2cca | rchicoli/ispycode-python | /Data-Types/Numbers/Booleans.py | 383 | 4.15625 | 4 |
# True behaves like 1
print( int(True) )
# False behaves like 0
print( int(False) )
# non zero numbers evaluates to True
print( bool(99) )
# 0 evaluates to False
print( bool(0) )
# boolean expressions using the logical operators
print "not True :" , not True
print "not False :" , not False
print "True and False :" , True and False
print "True or False :" , True or False
| true |
c0805de1cd404c8258fb5e91a7408de33db58f81 | Carter0/learningPython | /vector.py | 1,150 | 4.375 | 4 | #!/usr/local/bin/python3
from math import hypot
# Also another example from the book. This time about vectors.
class Vector:
# What is interesting to note here is that...
# We have created 6 special methods and most are not called by the user. Most are called by the python interpreter.
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# Gets the string reprentation of the object for inspection. Like toString in java?
# Also that is basically string.format()
# Instead of <Vector object at <memory address>> we get something human readable
# %r means the fields are integers, not strings
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
# bool(x) calls x.__bool__() and returns true or false
# Returns false if magnitude 0, true otherwisev
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.x + other.x
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
| true |
4383772d34f8f68671a65e594e6775143f8337c0 | kuldeeparyadotcom/coding_interview | /sum_target/SumTarget.py | 2,941 | 4.1875 | 4 | #!/usr/bin/env python
# vim: tabstop=8 expandtab widthsize=4 softtabstop=4
"""
Problem - A list of numbers is given. A target number (integer) is given. Write a function that returns a boolean value if any two numbers in list sum up the given target number.
Input -
List of integers
target integer
Output -
True if any two integers in given list sum up given target integer
False if no two numbers in given list sum up given target integer
Assumption -
1. No duplicate number is allowed in input list of integers
2. Each number can be used only once
"""
import logging
logging.basicConfig(level=logging.DEBUG)
def is_target_sum_achievable(input_list, target_integer): #take list of integers as arguments
logging.debug("Input List: %s Target Integer: %s" %(input_list, target_integer))
len_input_list = len(input_list) #Capture length of input list
#Edge case 01
if len_input_list < 2: #Not a valid case
logging.debug("Edge Case 01 - Input list container less than 2 items")
return False #Not possible
#Edge case 02
if len_input_list == 2: #Only two integers in list
logging.debug("Edge Case 02 - Input list contains only two numbers")
if input_list[0] + input_list[1] == target_integer: #Sum of both elements equals to target integer
logging.debug("Sum of both numbers %s and %s match the target: %s" %(input_list[0], input_list[1], target_integer))
return True
else:
logging.debug("Sum of both numbers %s and %s DON'T match the target: %s" %(input_list[0], input_list[1], target_integer))
return False
#If length of input list is >=3 then proceed further
members = set(input_list) #Form a set out of given list of integers to check membership
logging.debug("Traversing provided input list")
for item in input_list: #Traverse list
logging.debug("Processing item: %s" %item)
expected_value = target_integer - item #Expected value to meet sum criteria
logging.debug("Checking if expected value %s is in the list: %s" %(expected_value, input_list))
if expected_value != item and expected_value in members: #Assumption 2
logging.debug("expected value found")
logging.debug("Integer %s and Integer %s sum up %s" %(item, expected_value, target_integer))
return True
break #No need to proceed further
else:
logging.debug("No two integers found in the list: %s that sums up: %s" %(input_list, target_value))
return False #else will execute only when for loop is exhausted
if __name__ == "__main__":
raw_list = input("Enter space separated integers: ")
input_list = []
for item in raw_list.split():
input_list.append(int(item))
target_value = int(input("Enter target integer: "))
output = is_target_sum_achievable(input_list, target_value)
print(output)
| true |
11a092e1eea851c85df75938bc0f2df28fce8f71 | kuldeeparyadotcom/coding_interview | /q004/prime_classification.py | 1,157 | 4.125 | 4 | #!/usr/bin/env python
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
def classify_list(l):
"""
Purpose - function classifies prime numbers vs non-prime numbers
Input - a list of positive integers
Ouput - For each number in list, program confirms whether it is prime or not
"""
for n in l: #Traverse through the given list
is_prime = True
first_divisor = 1 #default initialization
remainder_by_first_divisor = 1 #Default initialization
for d in range(2,n): #See if number n is devisible by any number other than 1 and itself
if n % d == 0: #number n is divisible by d that is neither 1 nor number n
is_prime = False
first_divisor = d
remainder_by_first_divisor = n // d
break
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number", n,"=",first_divisor,"*",remainder_by_first_divisor)
else:
print("Classification complete!!!")
#Test it locally
if __name__ == "__main__":
classify_list([1,2,3,4,5,6,7,8,9,10,11,12,13,14])
| true |
42fda741883c2092888795118c130777edaf9448 | abi-oluwade/engineering-48-Mr-Miyagi-Game | /mr_miyagi_sensei_edition.py | 1,501 | 4.28125 | 4 | print ("Hello young grasshopper,")
# The 'while True' here means that the whole loop will run on forever/infinitely it will always be a true condition ,
# but can be broken with the use of the 'break' keyword after a condition has been met and will print the statement
# at the end outside the loop.
while True:
user_input = str(input("what do you seek from me?"))
substring1 = "?"
if user_input.count(substring1) > 0:
print("Questions are wise, but for now. Wax on, and Wax off!")
# 'find' returns an integer representing the index of where the search item was found. If it isn't found,
# it returns -1. And this can be used in conjunction with the while loop and if-elif statement to
# print the appropriate response.
elif user_input.find("Sensei") < 0 and user_input.find("sensei") < 0:
print("You are smart, but not wise - address me as Sensei please")
elif user_input.find("Block") > 0 or user_input.find("block") > 0:
print("Remember, best block, not to be there..")
elif user_input.find(" ") > 0 and user_input.find("Sensei, I am at peace"):
print("Do not lose focus. Wax on. Wax off.")
elif user_input == str("Sensei, I am at peace"):
break
# 'break' here is critical as it stops the loop from being infinite once the condition is satisfied.
print("Sometimes, what heart know, head forget")
# https://www.w3schools.com/python/python_conditions.asp
# https://www.w3schools.com/python/python_while_loops.asp
| true |
ea36fe328a8653132ddf456d18745196bea80a84 | SMinTexas/phone_book_console_app | /phonebook.py | 2,049 | 4.59375 | 5 | # You will write a command line program to manage a phone book.
# When you start the phonebook.py program, it will print out a menu
# and ask the user to enter a choice:
# $ python3 phonebook.py
# Electronic Phone Book
# =====================
# 1. Look up an entry
# 2. Set an entry
# 3. Delete an entry
# 4. List all entries
# 5. Quit
# What do you want to do (1-5)?
# 1. If they choose to look up an entry, you will ask them for the person's name, and then look up the person's phone number by the given name and print it to the screen.
# 2. If they choose to set an entry, you will prompt them for the person's name and the person's phone number,
# 3. If they choose to delete an entry, you will prompt them for the person's name and delete the given person's entry.
# 4. If they choose to list all entries, you will go through all entries in the dictionary and print each out to the terminal.
# 5. If they choose to quit, end the program.
import book
import menu
import lookups
import adds
import deletes
import display_list
import options
menu.print_menu()
menu_choice = 0
while menu_choice != 5:
menu_choice = int(options.select_option())
if menu_choice == 1:
option = input(options.print_prompt(menu_choice))
if option == "N":
name = input(options.print_subprompt(menu_choice, option))
print(name)
lookups.get_phone_by_name(name)
elif option == "P":
phone = input(options.print_subprompt(menu_choice, option))
lookups.get_name_by_phone(phone)
elif menu_choice == 2:
name = input(options.print_add_name_prompt())
phone = input(options.print_add_phone_prompt())
adds.add_new_entry(name, phone)
elif menu_choice == 3:
name = input(options.print_prompt(menu_choice))
deletes.del_entry(name)
elif menu_choice == 4:
display_list.print_entries()
elif menu_choice == 5:
print(options.print_prompt(menu_choice))
else:
print(options.print_prompt(menu_choice))
| true |
d7b2c4dd0a7b106730e4731819dbbe31b4dc18db | Arun-07/python_100_exercises | /Question_2.py | 395 | 4.34375 | 4 | # Question 2
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program: 8 Then, the output should be:40320
n = int(input('Enter a number: '))
result = 1
for i in range(1, n+1):
result *= i
print('The factorial of %d is : %d' % (n, result))
| true |
44a5e5d629980e316a750c26037d41be1ae1a74b | Arun-07/python_100_exercises | /Question_12.py | 435 | 4.1875 | 4 | # Write a program, which will find all such numbers between 1000 and 3000 (both included)
# such that each digit of the number is an even number.
# The numbers obtained should be printed in a comma-separated sequence on a single line.
import re
odd_pattern = re.compile(r"['1', '3', '5', '7', '9' ]")
for num in range(1000, 3000):
if num%2 == 0:
if not odd_pattern.search(str(num)):
print(num, end=' ')
| true |
cfaf8e864df4eb7d0a30e03466184abd33f3c2d3 | Arun-07/python_100_exercises | /Question_35.py | 315 | 4.3125 | 4 | # Define a function which can generate a list where
# the values are square of numbers between 1 and 20 (both included).
# Then the function needs to print the last 5 elements in the list.
def sqrd_list():
num_list = [i**2 for i in range(1, 21)]
for j in num_list[:-6:-1]:
print(j)
sqrd_list()
| true |
15d687c7ae68b28c20e713ae165c59576cb1690c | schase15/cs-module-project-hash-tables | /applications/word_count/word_count.py | 2,328 | 4.3125 | 4 | # Already did this with the histo.py example
# Only works on 3 out of 5 test with the special characters if statement
# I think the test is wrong, based on the Readme. It says if no special characters are
# removed it should return a blank dictionary.
# In the second one, "Hello hello", there are no special characters
# so it should return a blank dictionary, not 'hello' : 2
# For the last test, python already ignores \'s and the following letter so it
# Returns no special characters removed
def word_count(s):
'''
Take in string
Strip any punctuation away
If the input contains no ignored characters, return an empty dictionary
Split on whitespaces
Add to dictionary while counting
'''
charac_ignore = ' " : ; , . - + = / \ | [ ] } { ( ) * ^ & '.split(' ')
## Clean the punctuation out
# Blank string to filter cleaned text into
empty_string = ""
# Count if special characters are removed, if this is equal to 0 at the end,
# print out empty dictionary
removed = 0
# Filter out all of the punctuation
for c in s:
# Ignore punctuation
if c in charac_ignore:
# count if special characters are removed
removed += 1
continue
# Make it all lower case
c = c.lower()
# Add it to the blank string
empty_string += c
# Empty dictionary to store word and the count
d = {}
# If no special characaters are removed, return empty dictionary
# if removed == 0:
# print('No special characters removed')
# return d
# Split the string into a list of individual words - split on whitespace
arr = empty_string.split()
# Iterate through the split words array, count the occurance of each word
for word in arr:
# If the word isn't in the dictionary, add it
if word not in d:
d[word] = 0
# Increment the count
d[word] += 1
# Return the dictionary
return d
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.')) | true |
496109a8720fd12f0aaf8065423224ce46097081 | SR-Sunny-Raj/Hacktoberfest2021-DSA | /33. Python Programs/binconversion.py | 204 | 4.1875 | 4 | '''Problem Statement : Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent binary number. '''
n=int(input("Enter Number : "))
print(bin(n)[2:])
| true |
0cd1dd82c16e2fc272087e3c55578aa107a3b44c | SR-Sunny-Raj/Hacktoberfest2021-DSA | /05. Searching/BinarySearch.py | 1,266 | 4.3125 | 4 | # Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
# Begin with an interval covering the whole array.
# If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
# Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
# Enter the sorted list
n = list(map(int, input("Enter List ").split()))
# Enter Element to be Searched
a = int(input("Enter Element to be Searched "))
# Defining a function that can perform task accordingly to given variables
def binary_search(n, a):
# Variable Assigning to perform Binary Search
low = 0
mid = 0
high = len(n)-1
# For loop can be used but we don't know the number of occurances, So, using while loops
while low <= high:
mid = (high + low)//2
if n[mid] < a:
low = mid + 1
elif n[mid] > a:
high = mid - 1
else:
return mid
return "Element is Not Found"
# Calling Function
search = binary_search(n, a)
# Conditional Statements
if search == "Element is Not Found":
print("Element is Not Present")
else:
print("Element is Present at index", str(search))
| true |
2f836eba2f03aa2af3d26029f16f760624e144bd | SR-Sunny-Raj/Hacktoberfest2021-DSA | /33. Python Programs/create_sublist.py | 2,113 | 4.1875 | 4 | Python3 program to find a list in second list
class Node:
def __init__(self, value = 0):
self.value = value
self.next = None
# Returns true if first list is
# present in second list
def findList(first, second):
# If both linked lists are empty/None,
# return True
if not first and not second:
return True
# If ONLY one of them is empty,
# return False
if not first or not second:
return False
ptr1 = first
ptr2 = second
# Traverse the second LL by
# picking nodes one by one
while ptr2:
# Initialize 'ptr2' with current
# node of 'second'
ptr2 = second
# Start matching first LL
# with second LL
while ptr1:
# If second LL become empty and
# first not, return False,
# since first LL has not been
# traversed completely
if not ptr2:
return False
# If value of both nodes from both
# LLs are equal, increment pointers
# for both LLs so that next value
# can be matched
elif ptr1.value == ptr2.value:
ptr1 = ptr1.next
ptr2 = ptr2.next
# If a single mismatch is found
# OR ptr1 is None/empty,break out
# of the while loop and do some checks
else:
break
# check 1 :
# If 'ptr1' is None/empty,that means
# the 'first LL' has been completely
# traversed and matched so return True
if not ptr1:
return True
# If check 1 fails, that means, some
# items for 'first' LL are still yet
# to be matched, so start again by
# bringing back the 'ptr1' to point
# to 1st node of 'first' LL
ptr1 = first
# And increment second node element to next
second = second.next
return False
# Driver Code
# Let us create two linked lists to
# test the above functions.
# Created lists would be be
# node_a: 1->2->3->4
# node_b: 1->2->1->2->3->4
node_a = Node(1)
node_a.next = Node(2)
node_a.next.next = Node(3)
node_a.next.next.next = Node(4)
node_b = Node(1)
node_b.next = Node(2)
node_b.next.next = Node(1)
node_b.next.next.next = Node(2)
node_b.next.next.next.next = Node(3)
node_b.next.next.next.next.next = Node(4)
if findList(node_a, node_b):
print("LIST FOUND")
else:
print("LIST NOT FOUND")
| true |
3b4d75e13e90c3f80307badb1fe07be84aaee4f5 | SR-Sunny-Raj/Hacktoberfest2021-DSA | /20. Dynamic Programming/rod_cutting.py | 1,423 | 4.34375 | 4 | """
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.
Example:
If length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
"This is exactly same as unbounded knapsack without any variation"
"""
price=[1, 5, 8, 9, 10, 17, 17, 20]
N=8
length=[i for i in range(1,N+1)]
def rodCutting(price,length,N):
#Mapping from unbounded knapsack is:
#val => price and wt=> length
size=len(price)
#creating dp array of size 'size x N' where size is length of price array and N is length of rod
dp=[[0 for j in range(N+1)]for i in range(size+1)]
#loop starting from 2nd row to last row
for i in range(1,size+1):
#loop from 1st column to last column
for j in range(N+1):
#we include the length
if length[i-1]<=j:
dp[i][j]=max(price[i-1]+dp[i][j-length[i-1]],dp[i-1][j])
#we dont include the length
else:
dp[i][j]=dp[i-1][j]
return dp[size][N]
print("The max value will be: ",rodCutting(price,length,N))
| true |
6d3a0183b835bed116980eab41cd43df8bd54c46 | Hanu-Homework/SS1 | /week02/hw_ex05_vowels_and_consonants.py | 796 | 4.28125 | 4 | def count_vowels_and_consonants(string: str) -> tuple:
# A constant tuple holding all of the vowels
all_vowels = ('a', 'e', 'i', 'o', 'u')
vowels_count = 0
consonants_count = 0
# Convert all the characters of the string to lowercase
string = string.lower()
# Iterate through each characters of the string
for char in string:
if char in all_vowels:
vowels_count += 1
# Else if the character is a lowercase letter
elif 'a' <= char <= 'z':
consonants_count += 1
return vowels_count, consonants_count
if __name__ == "__main__":
s = input("Enter a string: ")
vowels, consonants = count_vowels_and_consonants(s)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
| true |
e2ff807c46dafdfe5ca57a85cba6c52f3fdab478 | Hanu-Homework/SS1 | /week02/tut_ex01_digits_sum.py | 647 | 4.3125 | 4 | # Get the input number from the user
num = int(input("Enter a number: "))
def calculate_digits_sum(number: int) -> int:
"""
Return the sum of all digits in a number
Args:
number (int): the input number
Returns:
(int): the sum of all digits of the input number
"""
# Return value
ret = 0
while number != 0:
# Extract the last digit number and add it to ret
ret += number % 10
# Delete the last digit of the number
number //= 10
return ret
# Print out the sum result
print(
f"The sum of all digits of the number {num} is: {calculate_digits_sum(num)}")
| true |
c86a4161ca43e6fad5387ba5c8aa795480549a08 | dbrgn/projecteuler | /python/0009/9.py | 769 | 4.28125 | 4 | """
Problem 9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import sys
def triplet(m, n):
"""Euclid's formula. Generates a pythagoraen triple given an arbitrary pair
of positive integers m and n with m > n."""
a = m**2 - n**2
b = 2 * m * n
c = m**2 + n**2
return a, b, c
for m in xrange(2, 100):
for n in xrange(1, m - 1):
t = triplet(m, n)
result = sum(t)
if result == 1000:
print 'FOUND TRIPLET!', t, result
print 'Product:', t[0] * t[1] * t[2]
sys.exit(0)
print t, result
| true |
f6152c426e22d59b0b2ea333f0873ec3bc3591db | betts888/my-first-blog | /python_intro.py | 1,101 | 4.3125 | 4 | if 3 > 2:
print('it works!')
if 5>2:
print('5 is indeed greater than 2')
else:
print('5 is not greater than 2')
name = 'Sonja'
if name == 'Ola':
print('Hey Ola!')
elif name == 'Sonja':
print('Hey Sonja!')
else:
print('Hey awesome')
volume = 57
if volume < 20:
print("its kinda quiet")
elif 20 <= volume < 40:
print("it's nice for background music")
elif 40 <= volume < 60:
print ("perfect, I can hear all the details")
elif 60 <= volume < 80:
print ("nice for parties")
elif 80 <= volume < 100:
print ("a bit loud")
else:
print ("my ears!")
if volume < 20 or volume > 80:
volume = 50
print ("well done")
def hi():
print ('hello beautiful')
print ('hows it hanging?')
hi()
def hi(name):
if name == 'Ola':
print ('Hi Ola')
elif name == 'Sonja':
print ('Hi Sonja')
else: print('hi love')
hi('Bettina')
def hi(name):
print ('hi ' + name + '!')
hi('Bettina')
girls = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'Bettina']
for name in girls:
hi(name)
print('next girl')
for i in range (1, 6):
print(i)
| false |
8b2094f561c9088f0da99fe268820fd59f4fd93e | thomasren681/MIT_6.0001 | /ps4/ps4a.py | 2,481 | 4.3125 | 4 | # Problem Set 4A
# Name: Thomas Ren
# Collaborators: None
# Time Spent: x: About a quarter to an hours
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'bac', 'bca', 'acb', 'cab', 'cba']
>>> get_permutations('def')
['def', 'edf', 'efd', 'dfe', 'fde', 'fed']
>>> get_permutations('ijk')
['ijk', 'jik', 'jki', 'ikj', 'kij', 'kji']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
if len(sequence) == 1:
return list(sequence)
else:
insert_str = sequence[0]
sequence = sequence[1:]
permutation = []
latter_permutation = get_permutations(sequence)
for string in latter_permutation:
string_list = list(string)
length = len(string)+1
for i in range(length):
temp = string_list.copy()
temp.insert(i,insert_str)
temp_str = ''.join(temp)
permutation.append(temp_str)
return permutation
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
example_input = 'abc'
print('Input:', example_input)
print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
print('Actual Output:', get_permutations(example_input))
example_input = 'def'
print('Input:', example_input)
print('Expected Output:', ['def', 'edf', 'efd', 'efd', 'fed', 'fde'])
print('Actual Output:', get_permutations(example_input))
example_input = 'ijk'
print('Input:', example_input)
print('Expected Output:', ['ijk', 'jik', 'jki', 'ikj', 'kij', 'kji'])
print('Actual Output:', get_permutations(example_input)) | true |
a2650327ea1d4d9e989e94bf082e0801899cd5ba | Katarzyna-Bak/Coding-exercises | /Triangle area.py | 766 | 4.21875 | 4 | """
Task.
Calculate area of given triangle. Create a function t_area that will take a string which will represent triangle, find area of the triangle, one space will be equal to one length unit. The smallest triangle will have one length unit.
Hints
Ignore dots.
Example:
.
. .
. . . ---> should return 2.0
.
. .
. . .
. . . . ---> should return 4.5
"""
def t_area(t_str):
return 0.5 * (t_str.count('\n')-2) ** 2
print("Tests:")
print(t_area('\n.\n. .\n. . .\n. . . .\n. . . . .\n'))
print(t_area('\n.\n. .\n. . .\n'))
print(t_area('\n.\n. .\n. . .\n. . . .\n. . . . .\n. . . . . .\n. . . . . . .\n. . . . . . . .\n. . . . . . . . .\n'))
print(t_area('\n.\n. .\n')) | true |
aeb77a185e0947f5eb2e7d95884cdf6b11697dc9 | Katarzyna-Bak/Coding-exercises | /Right to Left.py | 1,761 | 4.46875 | 4 | """
"For centuries, left-handers have suffered unfair discrimination in a world designed for right-handers."
Santrock, John W. (2008). Motor, Sensory, and Perceptual Development.
"Most humans (say 70 percent to 95 percent) are right-handed, a minority (say 5 percent to 30 percent) are left-handed, and an indeterminate number of people are probably best described as ambidextrous."
Scientific American. www.scientificamerican.com
One of the robots is charged with a simple task: to join a sequence of strings into one sentence to produce instructions on how to get around the ship. But this robot is left-handed and has a tendency to joke around and confuse its right-handed friends.
You are given a sequence of strings. You should join these strings into a chunk of text where the initial strings are separated by commas. As a joke on the right handed robots, you should replace all cases of the words "right" with the word "left", even if it's a part of another word. All strings are given in lowercase.
Input: A sequence of strings.
Output: The text as a comma-separated string.
Example:
left_join(("left", "right", "left", "stop")) == "left,left,left,stop"
left_join(("bright aright", "ok")) == "bleft aleft,ok"
left_join(("brightness wright",)) == "bleftness wleft"
left_join(("enough", "jokes")) == "enough,jokes"
How it is used: This is a simple example of operations using strings and sequences.
Precondition:
0 < len(phrases) < 42
"""
def left_join(phrases: tuple) -> str:
return ','.join(phrases).replace('right', 'left')
print('Tests:')
print(left_join(("left", "right", "left", "stop")))
print(left_join(("bright aright", "ok")))
print(left_join(("brightness wright",)))
print(left_join(("enough", "jokes"))) | true |
bae89e5416fca377bce925552209a6c3eb97bf23 | Katarzyna-Bak/Coding-exercises | /Filling an array (part 1).py | 468 | 4.15625 | 4 | """
We want an array, but not just any old array, an array with
contents!
Write a function that produces an array with the numbers 0
to N-1 in it.
For example, the following code will result in an array
containing the numbers 0 to 4:
arr(5) // => [0,1,2,3,4]
Note: The parameter is optional. So you have to give it
a default value.
"""
def arr(n = 0):
return [x for x in range(n)]
print('Tests:')
print(arr(4))
print(arr(0))
print(arr()) | true |
8d02064e8feb688e01ece44ce2921f23b79b758c | Katarzyna-Bak/Coding-exercises | /Double Char.py | 502 | 4.125 | 4 | """
Given a string, you have to return a string in
which each character (case-sensitive) is repeated once.
double_char("String") ==> "SSttrriinngg"
double_char("Hello World") ==> "HHeelllloo WWoorrlldd"
double_char("1234!_ ") ==> "11223344!!__ "
Good Luck!
"""
def double_char(s):
output = ''
for i in range(len(s)):
output += s[i]*2
return output
print('Tests:')
print(double_char("String"))
print(double_char("Hello World"))
print(double_char("1234!_ ")) | true |
657a70dba9da3ec8793d9a4116f0d737775643eb | Katarzyna-Bak/Coding-exercises | /BASIC Making Six Toast.py | 857 | 4.6875 | 5 | """
Story:
You are going to make toast fast, you think that you
should make multiple pieces of toasts and once. So,
you try to make 6 pieces of toast.
Problem:
You forgot to count the number of toast you put into
there, you don't know if you put exactly six pieces
of toast into the toasters.
Define a function that counts how many more (or less)
pieces of toast you need in the toasters. Even though
you need more or less, the number will still be positive,
not negative.
Examples:
You must return the number of toast the you need to put
in (or to take out). In case of 5 you can still put 1
toast in:
six_toast(5) == 1
And in case of 12 you need 6 toasts less (but not -6):
six_toast(12) == 6
"""
def six_toast(num):
return abs(6-num)
print('Tests:')
print(six_toast(15))
print(six_toast(6))
print(six_toast(3)) | true |
d7317c89f49fdd717c8a251bab1576bdc9954716 | Katarzyna-Bak/Coding-exercises | /Multiplication table for number.py | 802 | 4.46875 | 4 | """
Your goal is to return multiplication table for number that is always an integer from 1 to 10.
For example, a multiplication table (string) for number == 5 looks like below:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
P. S. You can use \n in string to jump to the next line.
Note: newlines should be added between rows, but there should be no trailing newline at the end.
"""
def multi_table(number):
result = ''
for r in range(1, 11):
if r < 10:
result += '{0} * {1} = {2}\n'.format(r, number, r * number)
else:
result += '{0} * {1} = {2}'.format(r, number, r * number)
return result
print("Tests:")
print(multi_table(5))
print(multi_table(1)) | true |
4cd58172be2558a2bf3e20e38817d39f0c7551f2 | Katarzyna-Bak/Coding-exercises | /Majority.py | 780 | 4.5625 | 5 | """
We have a List of booleans. Let's check if the majority of elements
are true.
Some cases worth mentioning: 1) an empty list should return false; 2)
if trues and falses have an equal amount, function should return false.
Input: A List of booleans.
Output: A Boolean.
Example:
is_majority([True, True, False, True, False]) == True
is_majority([True, True, False]) == True
"""
def is_majority(items: list):
return items.count(True) > items.count(False)
print('Examples:')
print(is_majority([True, True, False, True, False]))
print(is_majority([True, True, False]))
print(is_majority([True, True, False, False]))
print(is_majority([True, True, False, False, False]))
print(is_majority([False]))
print(is_majority([True]))
print(is_majority([])) | true |
66df0d705d7c17cd804e3ca813e8764dd1fa1461 | Katarzyna-Bak/Coding-exercises | /Grasshopper - Terminal game move function.py | 491 | 4.15625 | 4 | """
Terminal game move function
In this game, the hero moves from left to right.
The player rolls the die and moves the number of
spaces indicated by the die two times.
Create a function for the terminal game that takes the
current position of the hero and the roll (1-6) and
return the new position.
Example:
move(3, 6) should equal 15
"""
def move(position, roll):
return position + 2 * roll
print("Tests:")
print(move(0, 4))
print(move(3, 6))
print(move(2, 5)) | true |
30e788b6aa05a95b1e2ff60316c673f40a87c915 | Katarzyna-Bak/Coding-exercises | /L1 Set Alarm.py | 761 | 4.28125 | 4 | """
Write a function named setAlarm which receives two parameters.
The first parameter, employed, is true whenever you are
employed and the second parameter, vacation is true whenever
you are on vacation.
The function should return true if you are employed and
not on vacation (because these are the circumstances under
which you need to set an alarm). It should return false
otherwise. Examples:
setAlarm(true, true) -> false
setAlarm(false, true) -> false
setAlarm(false, false) -> false
setAlarm(true, false) -> true
"""
def set_alarm(employed, vacation):
return employed and not vacation
print("Tests:")
print(set_alarm(True, True))
print(set_alarm(False, True))
print(set_alarm(False, False))
print(set_alarm(True, False))
| true |
62e4fc0551e05077fa9973fb9f1b3e6084e2bc0f | Katarzyna-Bak/Coding-exercises | /Count of positives sum of negatives.py | 952 | 4.125 | 4 | """
Given an array of integers.
Return an array, where the first element is the count of
positives numbers and the second element is sum of negative
numbers.
If the input array is empty or null, return an empty array.
Example
For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13,
-14, -15], you should return [10, -65].
"""
def count_positives_sum_negatives(arr):
negSum = 0
posCount = 0
for a in arr:
if a > 0: posCount += 1
elif a < 0: negSum += a
return [posCount, negSum] if len(arr) > 0 else []
print("Tests:")
print(count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]))
print(count_positives_sum_negatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]))
print(count_positives_sum_negatives([1]))
print(count_positives_sum_negatives([-1]))
print(count_positives_sum_negatives([0,0,0,0,0,0,0,0,0]))
print(count_positives_sum_negatives([])) | true |
9e783f91b7cb733caab0c177293b3da8b7a41c76 | Katarzyna-Bak/Coding-exercises | /Days in the year.py | 1,198 | 4.40625 | 4 | """
A variation of determining leap years, assuming only
integers are used and years can be negative and positive.
Write a function which will return the days in the year
and the year entered in a string. For example 2000,
entered as an integer, will return as a string 2000
has 366 days
There are a few assumptions we will accept the year 0,
even though there is no year 0 in the Gregorian Calendar.
Also the basic rule for validating a leap year are as
follows
Most years that can be divided evenly by 4 are leap years.
Exception: Century years are NOT leap years UNLESS they
can be evenly divided by 400.
So the years 0, -64 and 2016 will return 366 days. Whilst
1974, -10 and 666 will return 365 days.
"""
def year_days(year):
days = 365
if str(year).endswith('00'):
if year % 400 == 0:
days = 366
elif year % 4 == 0:
days = 366
return f'{year} has {days} days'
print('Tests:')
print(year_days(0))
print(year_days(-64))
print(year_days(2016))
print(year_days(1974))
print(year_days(-10))
print(year_days(666))
print(year_days(1857))
print(year_days(2000))
print(year_days(-300))
print(year_days(-1)) | true |
f921bbe245fbf3cfe15671f2aeca902f5e82903c | Katarzyna-Bak/Coding-exercises | /First Word II.py | 1,037 | 4.46875 | 4 | """
You are given a string where you have to find its first word.
When solving a task pay attention to the following points:
There can be dots and commas in a string.
A string can start with a letter or, for example, a dot or space.
A word can contain an apostrophe and it's a part of a word.
The whole text can be represented with one word and that's it.
Input: A string.
Output: A string.
Example:
first_word("Hello world") == "Hello"
first_word("greetings, friends") == "greetings"
1
2
How it is used: the first word is a command in a command line
Precondition: the text can contain a-z A-Z , . '
"""
def first_word(text: str) -> str:
repl = [',', '.']
for r in repl:
text = text.replace(r, ' ')
return text.split()[0]
print('Tests:')
print(first_word("Hello world"))
print(first_word(" a word "))
print(first_word("don't touch it"))
print(first_word("greetings, friends"))
print(first_word("... and so on ..."))
print(first_word("hi"))
print(first_word("Hello.World")) | true |
e7ac5307c1db801bcb856f70346cef9b5c1a1c60 | Katarzyna-Bak/Coding-exercises | /Triple Trouble.py | 767 | 4.21875 | 4 | """
Triple Trouble
Create a function that will return a string that
combines all of the letters of the three inputed
strings in groups. Taking the first letter of all
of the inputs and grouping them next to each other.
Do this for every letter, see example below!
E.g. Input: "aa", "bb" , "cc" => Output: "abcabc"
Note: You can expect all of the inputs to be the same length.
"""
def triple_trouble(a, b, c):
result = ''
for i in range(len(a)):
result += a[i]+b[i]+c[i]
return result
print('Tests:')
print(triple_trouble("aaa","bbb","ccc"))
print(triple_trouble("aaaaaa","bbbbbb","cccccc"))
print(triple_trouble("burn", "reds", "roll"))
print(triple_trouble("Bm", "aa", "tn"))
print(triple_trouble("LLh", "euo", "xtr")) | true |
d80789651f5243b5db2f13859c49021ae7f9f1a1 | Katarzyna-Bak/Coding-exercises | /Is n divisible by x and y.py | 639 | 4.3125 | 4 | """
Create a function that checks if a number n is divisible
by two numbers x AND y. All inputs are positive, non-zero
digits.
Examples:
1) n = 3, x = 1, y = 3 => true because 3 is divisible
by 1 and 3
2) n = 12, x = 2, y = 6 => true because 12 is divisible
by 2 and 6
3) n = 100, x = 5, y = 3 => false because 100 is not
divisible by 3
4) n = 12, x = 7, y = 5 => false because 12 is neither
divisible by 7 nor 5
"""
def is_divisible(n,x,y):
return n % x == 0 and n % y == 0
print('Tests:')
print(is_divisible(3,2,2))
print(is_divisible(3,3,4))
print(is_divisible(12,3,4))
print(is_divisible(8,3,4)) | true |
121ff2983e49ba7f50cee2366dee25a2052e2691 | Katarzyna-Bak/Coding-exercises | /Is Even.py | 514 | 4.46875 | 4 | """
Check if the given number is even or not. Your function should return True if the number is even, and False if the number is odd.
Input: An int.
Output: A bool.
Example:
is_even(2) == True
is_even(5) == False
is_even(0) == True
How it’s used: (math is used everywhere)
Precondition: both given ints should be between -1000 and 1000
"""
def is_even(num: int) -> bool:
return True if num %2 == 0 else False
print("Tests:")
print(is_even(2))
print(is_even(5))
print(is_even(0)) | true |
7a63aa0ea780d23783a3b2941577a461c62d60e8 | Katarzyna-Bak/Coding-exercises | /Find numbers which are divisible by given number.py | 598 | 4.40625 | 4 | """
Complete the function which takes two arguments and returns
all numbers which are divisible by the given divisor.
First argument is an array of numbers and the second is
the divisor.
Example
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]
"""
def divisible_by(numbers, divisor):
return [n for n in numbers if n % divisor == 0]
print("Tests:")
print(divisible_by([1,2,3,4,5,6], 2))
print(divisible_by([1,2,3,4,5,6], 3))
print(divisible_by([0,1,2,3,4,5,6], 4))
print(divisible_by([0], 4))
print(divisible_by([1,3,5], 2))
print(divisible_by([0,1,2,3,4,5,6,7,8,9,10], 1)) | true |
0c1b756b5c1992a1156f2ea12277680771dc1455 | Katarzyna-Bak/Coding-exercises | /Beginner - Reduce but Grow.py | 343 | 4.25 | 4 | """
Given a non-empty array of integers, return the result
of multiplying the values together in order.
Example:
[1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24
"""
def grow(arr):
b = 1
for a in arr:
b = b*a
return b
print("Tests:")
print(grow([1, 2, 3]))
print(grow([4, 1, 1, 1, 4]))
print(grow([2, 2, 2, 2, 2, 2])) | true |
c5582c5662069dfdbb87b8cd5957b45786427e3c | Katarzyna-Bak/Coding-exercises | /Keep Hydrated!.py | 596 | 4.21875 | 4 | """
Nathan loves cycling.
Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.
You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.
For example:
time = 3 ----> litres = 1
time = 6.7---> litres = 3
time = 11.8--> litres = 5
"""
import math
def litres(time):
return math.floor(time * 0.5)
print("Tests:")
print(litres(2))
print(litres(1.4))
print(litres(12.3))
print(litres(0.82))
print(litres(11.8))
print(litres(1787))
print(litres(0)) | true |
3227c95714004341e4b61d6dd84453d3233957c1 | luislauriano/python-data-structures-and-algorithms | /src/data_structures/arrays/left_rotation.py | 497 | 4.59375 | 5 | """
A left rotation operation on an array of size 'n'
shifts each of the array's elements 1 unit to the left.
For example, if 2 left rotations are performed on array [1, 2, 3, 4, 5],
then the array would become [3, 4, 5, 1, 2].
Given an array of n integers and a number, 'd', perform 'd' left rotations on the array.
Then print the updated array as a single line of space-separated integers.
"""
def left_rotation(a, d):
return a[d:] + a[:d]
a = [1, 2, 3, 4, 5]
print(left_rotation(a, 4))
| true |
d0ef60a4b7a858f15afbc1fc0212af098818682b | andrewonyango/bioinformatics | /1-finding-hidden-messages-in-dna/week1/pattern_count.py | 485 | 4.3125 | 4 | def pattern_count(string, pattern):
"""
returns the number of occurences of *pattern* in *string*
string: the string to search on
pattern: the substring to look for in *string*
"""
count = 0
text_length = len(string)
pattern_length = len(pattern)
# compare only up to the last possible substring...
for i in range(text_length - pattern_length + 1):
if string[i: i + pattern_length] == pattern:
count += 1
return count
| true |
83de70501c82f7fbbb843e5e4b05e9451a5b841d | ferminhg/training-python | /patterns/behavioral-design-patterns/template.py | 1,010 | 4.125 | 4 | # Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
# Template Method lets subclasses redefine certain steps of an algorithm without changing
# the algorithm's structure.
# Use when you have to define steps of the algorithm once and let subclasses
# to implement its behaviour.
class Tax(object):
def calc(self, value):
if (value >= 1000):
value = self.overThousand(value)
return self.complementaryFee(value)
def complementaryFee(self, value):
return value + 10
class Tax1(Tax):
def __init__(self):
return super(Tax1, self).__init__()
def overThousand(self, value):
return value * 1.1
class Tax2(Tax):
def __init__(self):
return super(Tax2, self).__init__()
def overThousand(self, value):
return value * 1.2
def main():
tax1 = Tax1()
tax2 = Tax2()
print(tax1.calc(1111))
print(tax2.calc(1111))
if __name__ == '__main__':
main()
| true |
ebc925161eaa9b1804c9bde35c56d90c01901489 | patonelli/numericoPython | /gauss2.py | 1,602 | 4.15625 | 4 | # gauss elimination as seen in the classroom
import numpy as np
# A is type array from numpy
# remember: A[0.0] is the first element
# Elementary row operations:
def troca_linha(A,i,j):
'''Troca as linhas i e j da matriz A'''
buffer = A[i].copy()
A[i] = A[j]
A[j] = buffer
return A
def mult_linha(A,i,alfa):
'''Multiplica por alfa a linha i'''
A[i] = alfa*A[i]
return A
def subs_linha(A,i,k,alfa):
'''soma a linha i com um multiplo da linha k'''
A[i] = A[i] + alfa*A[k]
return A
# step k of gauss elimination:
def gauss_step(A,k):
'''O k-esimo passo na eliminacao de gauss'''
L=range(len(A))
for j in L[k+1:]:
m=-A[j,k]/A[k,k]
A=subs_linha(A,j,k,m)
A[j,k]=-m # Aproveitamos a matriz A pra guardar o multiplicador
return A
# triangle form, without care and pivoting
def triangle_form(A):
'''Retorna a matriz escalonada,
com os multiplicadores na parte triangular inferior'''
L=len(A)
for k in range(L-1):
p=pivo(A,k)
troca_linha(A,k,p)
gauss_step(A,k)
return A
def pivo(A,n):
''' retorna o indice de pivotacao da matriz A na coluna n,
a partir da linha n'''
l=len(A) # numero de linhas de A
c=len(A[0]) # numero de colunas
if (l<=n) or (c<=n):
raise ValueError("n deve ser menor que dimensao de A")
p=n # inicio o pivo como n, e vou aumentando
for k in range(n,l):
if abs(A[k,n]) > abs(A[p,n]):
p=k
return p
# roda um teste
A=np.array([[1,2,3],
[2,-1,9],
[3.,0., 2.]])
B=triangle_form(A)
| false |
3bb124cac40c17cf765168b0d654b8663dd38eae | MarielenaDominguez/PC2TALLER | /ejercicio2.py | 1,085 | 4.25 | 4 | #historia de usuario
#la historia de usuario es como un pequeño resumen de una actividad que se quiere realizar
#historia: demora al comprar un producto en una tienda
#como: implementar una página web, para poder comprar en línea
#quiero_lograr: un fácil acceso a las personas, para poder comprar
n = input("ingrese su nombre: ")
def menu():
print("=-="*30)
print ("Seleccione una opción: ")
print ("\t1 - usted eligio comprar una blusa ")
print ("\t2 - usted eligio comprar una pantalon ")
print ("\t3 - usted eligio comprar una zapatos ")
print ("\t4 - salir ")
while True:
menu()
menu_opciones = input("Ingrese un número: ")
if menu_opciones == "1":
print("")
print("usted eligio comprar una blusa")
elif menu_opciones == "2":
print("")
print("usted eligio comprar una pantalon")
elif menu_opciones == "3":
print("")
print("usted eligio comprar una zapatos")
elif menu_opciones == "4":
print("")
print("Haz pulsado la opción salir ")
| false |
ced048c3be05466bfe8e9aef6c310446ecb498ff | apontejaj/Python-Bootcamp | /for loop.py | 624 | 4.3125 | 4 | l = []
for num in range(0,10):
l.append(num)
for num in l:
print (num)
print ("-- We can also put a third parameter which is a step")
l = []
for num in range(0,10,2):
l.append(num)
for num in l:
print (num)
print ("how to iterate over dictionaries")
dict = {"k1":0, "k2":1, "k3":2}
print dict
for item in dict:
print item # Only gives you the keys
print dict[item]
for k,v in dict.iteritems():
print ("key: {} value: {}".format(k,v))
print ("key: %s value: %s" %(k,v))
for k,v in dict.items():
print ("key: {} value: {}".format(k,v))
print ("key: %s value: %s" %(k,v))
| false |
c5cf7830c0a8ea665795a9cf738eadb4e72fd8c2 | prasannagiri2072/python-practice | /spreedsheet work3/Untitled-6.py | 741 | 4.21875 | 4 | # String characters balance Test
# We’ll say that a String s1 and s2 is balanced if all the chars in the string1 are there in s2. characters position doesn’t matter.
# For Example:
# stringBalanceCheck(yn, Pynative) = True
def flag_statment(s1,s2):
flag = True
for char in s1:
if char in s2:
continue
else:
flag = False
return flag
s1 = "yn"
s2 = "Pynative"
flag = flag_statment(s1,s2)
print("s1 and s2 are balanced",flag)
s1 = "ynf"
s2 = "Pynative"
flag = flag_statment(s1,s2)
print("s1 and s2 are balanced",flag)
#Solution by Gopal
s1 = "h"
s2 = "hello"
if s1 in s2:
print(f"{s1} is in {s2}. So it is balanced.")
else:
print(f"{s1} is not in {s2}. So it is not balanced.") | true |
5c286e31b47eef1bae59a1dc311ca8e03b5219d1 | enterpriseih/easyTest | /SRC/demo/imooc/imooc_requests/part2_2urllib_demo.py | 1,304 | 4.21875 | 4 |
'''
urllib介绍
1.urllib和urllib2是相互独立的模块
2.requests库使用了urllib3(多场请求重复使用一个socket)
'''
# # bytes object
# b = b"example"
#
# # str object
# s = "example"
#
# # str to bytes
# bytes(s, encoding = "utf8")
#
# # bytes to str
# str(b, encoding = "utf-8")
#
# # an alternative method
# # str to bytes
# str.encode(s)
#
# # bytes to str
# bytes.decode(b)
from urllib.parse import urlencode
from urllib.request import urlopen
URL_IP='http://httpbin.org/ip'
URL_GET='http://httpbin.org/get'
def use_simple_urllib():
response=urlopen(URL_IP)
print('>>>Response Headers:')
print(response.info())
print('>>>Response Body:')
print(''.join([bytes.decode(line) for line in response.readlines()]))
def use_params_urllib():
#构建请求参数
params=urlencode({'param1':'Hello','param2':'world'})
print('Request Params:')
print(params)
#发送请求
response=urlopen('?'.join([URL_GET,'%s'])%params)
print('>>>Response Headers:')
print(response.info())
print('>>>Status Code:')
print(response.getcode())
print('>>>Response Body:')
print(''.join([bytes.decode(line) for line in response.readlines()]))
if __name__=='__main__':
print('>>>Use simple urllib:')
use_simple_urllib()
print()
print('>>>Use params urllib:')
use_params_urllib()
| false |
82d7ca65232a511f08307d0405768db40c1f0440 | enterpriseih/easyTest | /SRC/demo/基础实例/part7.py | 223 | 4.21875 | 4 | # 题目:将一个列表的数据复制到另一个列表中。
# 程序分析:使用列表[:]。
numbers=[x for x in range(10)]
n2=numbers[:]
n3=numbers
numbers[2]='abc'
del numbers
print(n2)
print(n3)
print(numbers) | false |
6414e75ab4378fe13a0e4f9d242466db693c20f6 | langigo/algorithm_python | /MergeSort.py | 1,437 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Idea of merge sort:
_Recursively split unsorted list into 2 sub-list, split until each sub-lists has only 1 memeber
_For each 2 sub-lists, join them together by comparing 2 first members of 2 sub-lists, and append to the result-list of the join
"""
#implementation: acceptance parameter is a list
def merge_sort(target, decrease=False):
if len(target)<=1:
return target
#center of the list
mid_index = int(len(target)/2)
#divine into 2 sub-lists
sub_left = target[:mid_index]
sub_right = target[mid_index:]
#recursively sort sub-list
sub_left = merge_sort(sub_left, decrease)
sub_right = merge_sort(sub_right, decrease)
#merge sorted sub-lists
return merging(sub_left, sub_right, decrease)
def merging(sleft, sright, decr):
combine = []
while len(sleft)>0 or len(sright):
if len(sleft)>0 and len(sright)>0:
if decr is False:
combine.append(sleft.pop(0) if sleft[0]<=sright[0] else sright.pop(0))
else:
combine.append(sleft.pop(0) if sleft[0]>=sright[0] else sright.pop(0))
else:
combine+=sleft+sright
break
return combine
if __name__ == '__main__':
mode = input("Sort in numerical or lexicographical?(N/L): ").lower()
target = input("Enter a list: ").split()
if mode=="n":
target = [int(x) for x in target]
decr = input("Is this a decreasing sort? (Y/N): ").lower()
decrease = True if decr =="y" else False
print(merge_sort(target, decrease)) | true |
bf3612377e123c1bf3e6584f81737584de1feaf4 | dsrizvi/algo-interview-prep | /old/general/findPivotPoint.py | 518 | 4.125 | 4 | def findPivot(array, left, right):
if left > right:
return -1
if left == right:
return left
mid = (left+right)/2
if array[mid-1] > array[mid]:
return array[mid]
if array[mid+1] < array[mid]:
return array[mid+1]
if array[mid] > array[right]:
return findPivot(array, mid+1, right)
else:
return findPivot(array, left, mid-1)
def main():
array = [4,5,6,7,1,2,3]
array2 = [7,1,2,3,4,5,6]
array3 = [7,8,9,1,2,3,4,5,6]
print findPivot(array3, 0, len(array3)-1)
if __name__ == '__main__':
main() | true |
ec2e68215caa750e057ac6732c4eed87f400acf8 | dsrizvi/algo-interview-prep | /hacker-rank/warmup/solved/staircase.py | 386 | 4.1875 | 4 | # https://www.hackerrank.com/challenges/staircase
import sys
def build_staircase(total_steps):
curr_step = 1
while curr_step <= total_steps:
spaces = ' ' * (total_steps - curr_step)
hashtags = '#' * curr_step
print(spaces + hashtags)
curr_step += 1
return
def main():
total_steps = int(input().strip())
build_staircase(total_steps)
if __name__ == '__main__':
main() | false |
ecaadd0b6312df92027978094a7f8013659ceb54 | dsrizvi/algo-interview-prep | /old/general/sort/mergeRemove.py | 712 | 4.125 | 4 | def mergeSort(array):
if len(array) < 2:
return array
mid = len(array)/2
left = array[:mid]
right = array[mid:]
left = mergeSort(left)
right = mergeSort(right)
return merge(left, right)
def merge(left, right):
merged = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
merged.append(left[i])
i = i + 1
elif left[i] > right[j]:
merged.append(right[j])
j = j + 1
else:
j = j+1
while i < len(left):
merged.append(left[i])
i= i + 1
while j < len(right):
merged.append(right[j])
j = j + 1
return merged
def main():
print mergeSort([6,6,3,3,3,3,5,6,6,6,6,5,5,5,5,7,8,11])
print mergeSort([4,5,3,2])
if __name__ == '__main__':
main()
| false |
a7cd2b08a7cc82d65424b5e8f74d75dc22ad69f0 | Taraslut/Python_circle | /5_list/list_1.py | 417 | 4.1875 | 4 | weekdays = []
print(weekdays)
weekdays = ['Monday', "Tuesday", 'Weednesday']
print(weekdays)
# first item in the list
print(weekdays[0])
#slice
print(weekdays[0:2])
another_list = list()
print(another_list)
# iterate by string
ll1 = list('cat')
print(ll1)
ll2 = ['cat']
print(ll2)
ll3 = ['cat', 'dog']
print(ll3)
# # error
# ll4 = list('cat', 'dog')
# print(ll4)
# magic :)
ll4 = list(('cat', 'dog'))
print(ll4) | false |
796ac8e33482626e4c5e72b0ff52e71864f79ba6 | abolfazl-sadeghian/text_to_morse_code | /main.py | 812 | 4.1875 | 4 | from morse_code_table import CODE
from art import logo
from playsound import playsound
# A text-based Python program to convert Strings into Morse Code.
print(logo)
text = input("Please enter a text to turn into morse code : \n").upper().split(' ')
morse_code = []
def word_to_morse_code(word: str):
for char in word:
morse_code.append(CODE[char])
morse_code.append('|')
for item in text:
word_to_morse_code(item)
print()
print("*" * 100)
print("Your text :\t",*text, sep=" ")
print("Morse Code :\t", *morse_code, sep=" ")
print("*" * 100)
for code in morse_code:
for char in code:
if (char == '-'):
playsound('sound/morse_line.mp3')
elif (char == '.'):
playsound('sound/morse_dot.mp3')
elif(char == '|'):
continue
| true |
b35aec7bf7a170c1893b162d4f90e9210b40cc66 | DevonLetendre/Distributions | /distribution.py | 2,297 | 4.1875 | 4 | from random import randrange
'''
The Distribution class models a distribution and provides methods
which allow a user to interact with the distribution.
'''
class Distribution:
def __init__(self):
self.dict = {}
self.eventspace = 0
self._L = []
self.flag = None
self.leftoff_at = 1
self.slider_begin = 0
self.slider_end = 0
def _numevent(self, e):
#Factotred out repetition.
return self.dict[e][1] - self.dict[e][0] + 1
def add(self, e, multiplicity = 1):
'''
Updates the Distribution to add the event e. The second parameter,
multiplicity counts how many "copies" of e to add. The default
multiplicity is 1, i.e. single events.
'''
self.flag = True
self.eventspace += multiplicity
if e in self.dict:
temp = self.dict[e]
self.dict[e] = [self.leftoff_at, self.leftoff_at +
multiplicity + self._numevent(e) - 1]
self.leftoff_at = self.leftoff_at + self._numevent(e) + multiplicity
else:
self.dict[e] = [self.leftoff_at, self.leftoff_at + multiplicity - 1]
self.leftoff_at = self.leftoff_at + multiplicity
def count(self, e):
'''
Returns the number of events that are e.
'''
return self._numevent(e)
def prob(self,e):
'''
Return the fraction of the total events that are e .
'''
if self.eventspace > 0:
return (self._numevent(e))/ self.eventspace
else:
raise ZeroDivisionError
def sample(self):
'''
Returns an event from the distribution. The returned results are
randomly selected and the probability of a given an event e
is prob(e).
'''
if self.flag:
self._L = sorted(self.dict.items(), key=lambda x: x[1])
self.slider_begin = self._L[0][1][0]
self.slider_end = self._L[-1][1][1]
self.flag = False
return self._modified_bs(randrange(self.slider_begin, self.slider_end + 1))
def _modified_bs(self, rand):
'''
A modified binary search.
'''
left = 0
right = len(self._L)
while True:
mid = (right + left) // 2
if rand >= self._L[mid][1][0] and rand <= self._L[mid][1][1]:
return self._L[mid][0]
elif rand < self._L[mid][1][0]:
right = mid
elif rand > self._L[mid][1][1]:
left = mid
def __len__(self):
'''
Returns the number of distinct events.
'''
return len(self.dict)
def __str__(self):
return str(self.dict)
| true |
b4bbbd4c520eb8f8e1b598dea851ab75b6dfb2cf | FelipeLinares04/LaboratorioRepeticionRemoto | /mayor.py | 253 | 4.1875 | 4 | print("Bienvenido a el espacio donde sabras cuando un numero entero es mayor a cero")
for i in range(1,11):
x=int(input("ingrese el numero "))
if x>0:
print("es un numero es postivo")
else:
print ("es un numero negativo")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.