blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
06cee3b6c3d1dc86c477216ae1ac9369b75dbdf0
|
chasegarsee/Algorithms
|
/recipe_batches/recipe_batches.py
| 1,679
| 4.1875
| 4
|
#!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
# getting the Keys from the KEY::VALUE pairs
current_recipe = set(recipe.keys())
print(current_recipe) # printing the keys
if current_recipe.intersection(ingredients.keys()) != current_recipe:
# if they keys in current recipe and the keys in ingredients dont match...
# .intersection() finds matching values within two lists of things. nifty find
return 0
ingredients_needed = {key: ingredients[key]
for key in ingredients if key in recipe}
# ingredients_needed sets up a new set of ingredients if both
# keys are found in ingredients and recipe
batches = 999999999 # as many batches as we might need
for value in ingredients_needed:
# for every value in ingredients_needed
if ingredients[value] // recipe[value] < batches:
# if when we perform floor division (lowest whole number)
# to the values of ingredients and recipes and the result is
# less than the values in batches
batches = ingredients[value] // recipe[value]
# create a new number of batches that equals the total number of batches possible.
return batches
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 1, 'butter': 5, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true
|
b5dcd8002e7ffa859e27cd377b9a3b3c57502e9a
|
jollypanther/pylearn
|
/computation/prime.py
| 1,413
| 4.1875
| 4
|
import itertools
from math import sqrt
# Straight Forward
def is_prime1(n):
if n < 2: # to skip 0,1
return False
for i in range(2, n):
if not n % i:
return False
return True
# Optimization
def is_prime(n):
if n < 2:
return False
elif n <= 3: # 2 or 3, to save unnecessary computation below
return True
elif n % 2 == 0: # all even numbers
return False
for i in range(3, int(sqrt(n)) + 1, 2): # sqrt(n) is the largest factor of n
if not n % i:
return False
return True
def primes():
return filter(is_prime, itertools.count(2))
# Straight Forward
def primes_range1(end, start=2):
return (i for i in range(start, end + 1) if is_prime(i))
# Based on https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def primes_upto(end):
sieves = [True] * end
for i in range(2, end):
# Prime Check for every number upto sqrt of count
# because number following sqrt(count) would have been already marked by previous iteration
if sieves[i]:
yield i
# Mark multiples of each number as False
# numbers upto it square are already marked by previous iteration
for m in range(2 * i, end, i):
sieves[m] = False
def prime_range(start, end):
for p in primes_upto(end):
if p > start:
yield p
| false
|
23f2a8f4b69924299a87f3821777b1ba6ddcf691
|
dev-bloke/examples
|
/python/simple/collections.py
| 1,829
| 4.3125
| 4
|
# Simple list and indexing
first_list = [1, 2, 3]
print(first_list[0])
# Working from the end of the list and appending.
second_list = [1, "b", 3, "Hello"]
print(second_list[3])
print(second_list[-2])
second_list[1] = "B"
second_list.append("world")
second_list.append(first_list)
print(second_list)
# Extending, inserting, deleting and removing
third_list = ["a", "b", "c"]
third_list.extend(first_list)
print(third_list)
third_list.insert(3, 4)
print(third_list)
third_list.insert(-1, 5)
print(third_list)
del third_list[3]
print(third_list)
third_list.remove("c")
print(third_list)
# Sorting, copying and reversing
fourth_list = ["Z", "A", "Q"]
fifth_list = fourth_list[:]
fifth_list.sort()
print(fourth_list)
print(fifth_list)
def compare_length(string1):
return len(string1)
sixth_list = ["Parsons", "Alan", "The", "Project"]
sixth_list.sort(key=compare_length)
print(sixth_list)
seventh_list = sixth_list[:]
seventh_list.reverse()
print(seventh_list)
# Membership
if "Alan" in sixth_list:
print("Alan is in the list.")
print(sixth_list.index("Alan"))
if "Bob" not in sixth_list:
print("Bob is not in the list.")
# Dictionaries (maps)
map = {"key1": "value1", "key2": "value2"}
value1 = map.get("key1")
print(value1)
map["key3"] = "value3"
del map["key2"]
eighth_list = map.keys()
print(eighth_list)
print("key3" in map)
print("key2" in map)
value2 = map.get("value2", "missing")
print(value2)
# Sets
ninth_list = [1, 2, 3, 1, 2, 4]
first_set = set(ninth_list)
print(first_set)
print(3 in first_set)
# Tuples
tenth_list = [1, 3, 5]
eleventh_list = ["one", "three", "five"]
tuple = zip(tenth_list, eleventh_list)
print(tuple)
# Comprehension
twelfth_list = [item * item for item in tenth_list]
print(twelfth_list)
second_map = {item: item * item for item in tenth_list}
print(second_map)
| true
|
06dbec69c44712a70985ed9ce526d2c86082c871
|
lovababu/python_basics
|
/datastructures/dictionary.py
| 1,105
| 4.5
| 4
|
about = {"Name": "Avol", "Age": 32, "Address": "Bangalore"} # called dictionary key value pairs.
print(type(about))
# access keys.
# returns all keys as dict_keys (Note: dict_keys is not a list, index access may result type error).
keys = about.keys()
print(type(keys))
print(keys) # keys[0] result type error dict_keys does not support indexing.
# access values.
# returns all values as dict_values (Note: dict_values is not a list, index access may result type error.)
values = about.values()
print(values) # values[0] result type error dict_values does not support indexing.
# access through keys.
print("Name is : ", about.get("Name")) # if no key matches, it returns None object which is null in python.
# iterate over dict.
for key in about.keys():
print(about.get(key))
# change value in dict.
about["Name"] = "Srilekha"
print(about)
# delete by key.
del about["Address"]
print(about)
items = about.items() # returns list of tuples type of dict_items.
print(items) # converting mutable dict into immutable tuple.
a = dict(one=1, two=2, three=3) # dict is a class.
print(a)
| true
|
f98695e91393a328c2a34d197d07c10828069598
|
zefe/python
|
/src/palindromo.py
| 318
| 4.125
| 4
|
def palindromo(word):
reversed_word = word[::-1]
if reversed_word == word:
print('Si es un palindromo')
print(reversed_word)
else:
print('No es un palindromo')
def run():
word = str(input('Ingreasa una palabra: '))
palindromo(word)
if __name__ == '__main__':
run()
| false
|
13f8de43d416d3fce542c6e7db56b88d5af8efe0
|
samirad123/lablec1
|
/q18.py
| 331
| 4.28125
| 4
|
print("1.If you pick an apple a banana.\n""2.If you pick oranges you an pick grapes.\n""3.If you pick grapes you can pick bananas.")
choice = print(input("\nEnter the fruit you want and you will get another fruit: "))
if choice == 'apple':
print("Banana")
elif choice == 'oranges':
print("grapes")
else:
print("Banana")
| false
|
ff2ba366ce3df5ad0049f46db9e44a5e50942675
|
ratanvishal/hello-python
|
/main12.py
| 384
| 4.1875
| 4
|
#a=8
#b=5
#c=sum((a,b))
#print(c)
#def function(a,b):
#print("hello function r u there",a+b)
def function(a,b):
"""This is the function which calculates the average of two numbers. and this function does't work for three numbers"""
average= (a+b)/2
# print(average)
return (average)
#v=function(5,9)
#print(v)
print(function.__doc__)
| true
|
4a1ca395e27d9d76e2aac32577598275fa340796
|
jennyChing/mit-handout_practice
|
/sUsingQ_1.py
| 1,176
| 4.25
| 4
|
class Stack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.q1 = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.q1.append(x)
print("push",self.q1)
def pop(self):
"""
:rtype: nothing
"""
#sort reversively
n = len(self.q1)
while n > 1:
n -= 1
self.q1.append(self.q1.pop(0))
print("while",self.q1)
self.q1.pop(0)
print("pop",self.q1)
def top(self):
"""
:rtype: int
"""
n = len(self.q1)
while n > 1:
n -= 1
self.q1.append(self.q1.pop(0))
print("while",self.q1)
return self.q1[0]
def empty(self):
"""
:rtype: bool
"""
return not self.q1
if __name__ == '__main__':
s=Stack()
s.push(1)
assert s.top()==1, "Stack is empty"
s.push(4)
assert s.top()==4, "Stack is empty"
s.pop()
assert s.top()==1, "Stack is empty"
s.push(3)
assert s.empty()==False, "Stack is empty"
s.push(2)
| false
|
73a6a5a6f21b8e7f0a8a234836b9864c021c12b6
|
green-fox-academy/Unicorn-raya
|
/week-01/day-2/count_from_to.py
| 586
| 4.375
| 4
|
# Create a program that asks for two numbers
# If the second number is not bigger than the first one it should print:
# "The second number should be bigger"
#
# If it is bigger it should count from the first number to the second by one
#
# example:
#
# first number: 3, second number: 6, should print:
#
# 3
# 4
# 5
first_number = int(input("This is first number: "))
second_number = int(input("This is second number: "))
if second_number < first_number:
print("The second number should be bigger")
else:
for i in range(first_number,second_number):
print(str(i)+'\n')
| true
|
1b0fcc447b81b5ee00c14a93b8d87802997c3593
|
green-fox-academy/Unicorn-raya
|
/week-01/day-3/Functions/Sort_that_list.py
| 992
| 4.21875
| 4
|
# Create a function that takes a list of numbers as parameter
# Returns a list where the elements are sorted in ascending numerical order
# Make a second boolean parameter, if it's `True` sort that list descending
def bubble(arr):
arr_length = len(arr)
if arr_length == 0:
return -1
for i in range(arr_length):
for j in range(i,arr_length):
if arr[i] > arr[j]:
arr[i],arr[j] = (arr[j],arr[i])
return arr
def advanced_bubble(arr, is_descending):
arr_length = len(arr)
if arr_length == 0:
return -1
if is_descending == False:
bubble(arr)
else:
for i in range(arr_length):
for j in range(i,arr_length):
if arr[i] < arr[j]:
arr[i],arr[j] = (arr[j],arr[i])
return arr
# Example:
print(bubble([43, 12, 24, 9, 5]))
# should print [5, 9, 12, 24, 34]
print(advanced_bubble([43, 12, 24, 9, 5], True))
# should print [34, 24, 9, 5]
| true
|
aeeb60f44fafdf45d1c48180c6f1957adb84f2c8
|
green-fox-academy/Unicorn-raya
|
/week-01/day-2/draw_pyramid.py
| 460
| 4.25
| 4
|
# Write a program that reads a number from the standard input, then draws a
# pyramid like this:
#
#
# *
# ***
# *****
# *******
#
# The pyramid should have as many lines as the number was
length = int(input())
level = 0
tmp = ""
while level < length + 1:
for i in range(length-level):
tmp += " "
for i in range(2 * level - 1):
tmp += "*"
for i in range(level-1):
tmp += " "
level += 1
print(tmp)
tmp = ""
| true
|
9e464ff53c74b314555a19755b90c971a2d4efbf
|
green-fox-academy/Unicorn-raya
|
/week-01/day-3/Functions/Factorial.py
| 224
| 4.34375
| 4
|
# - Create a function called `factorio`
# that returns it's input's factorial
def factorio( number ):
if number == 1:
return number
else:
return number * factorio (number - 1)
print(factorio(5))
| true
|
df537e9f10b48efe9aaf4c43adb75cc2d1a16984
|
aleluc91/numerical-analysis
|
/src/MCD.py
| 453
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 22 18:47:07 2018
@author: aleluc
"""
def MCD_recursive(m, n):
if m > n:
return MCD_recursive(m-n , n)
elif n > m:
return MCD_recursive(m, n-m)
else:
return m
def MCD(m, n):
while m != n:
if m > n:
m = m - n
elif n > m:
n = n - m
return m
print(MCD_recursive(30 , 18))
print(MCD(30 , 18))
| false
|
9d9afc31d603928f64561a29faafe584b8296be4
|
aduxhi/learnpython
|
/mid_test/lac_string_2.py
| 863
| 4.21875
| 4
|
#!/usr/bin/python
'''
Write a recursive procedure, called laceStringsRecur(s1, s2), which also laces together two strings. Your procedure should not use any explicit loop mechanism, such as a for or while loop. We have provided a template of the code; your job is to insert a single line of code in each of the indicated places.
For this problem, you must add exactly one line of code in each of the three places where we specify to write a line of code. If you add more lines, your code will not count as correct
'''
def laceStringsRecur(s1, s2):
def helpLaceStrings(s1, s2, out):
print(out)
if s1 == '':
return (out+s2)
if s2 == '':
return out+s1
else:
return helpLaceStrings(s1[1:], s2[1:], out+s1[0]+s2[0])
return helpLaceStrings(s1, s2, '')
s1 = 'abcd'
s2 = 'efghi'
x = laceStringsRecur(s1, s2)
print (x)
| true
|
ef6c2b63ae1b3ef0175632bf06fc8123eed45d37
|
aduxhi/learnpython
|
/return_print.py
| 715
| 4.15625
| 4
|
# -*- coding: UTF-8 -*-
'''
the print() function writes, i.e., "prints",a string in the console. The return statement causes your function to exit and hand back a value to its caller.(使函数终止并且返回一个值给它的调用者) The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return to its caller.
Fox example, here's a function utilizing both print() and return.
'''
def foo():
print("hello form inside of foo")
return 1
print("going to call foo: ")
x = foo() # 调用foo(),将返回值赋予 x
print("called foo")
print("foo returned " + str(x))
print(foo()) # 调用 foo()
print(foo) #
print(type(foo))
| true
|
492afa72418991d88094b69f59f6f548abf5fe0a
|
aduxhi/learnpython
|
/ProblemSet3/getGuessedWord.py
| 656
| 4.1875
| 4
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 返回已经猜到的单词
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# FILL IN YOUR CODE HERE...
gussed = []
for i in secretWord:
if i in lettersGuessed:
gussed.append(i)
else:
gussed.append('_ ')
return ''.join(gussed)
secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
print getGuessedWord(secretWord, lettersGuessed)
| true
|
d591b7440e04f08c2c65f2aa93e386db4ef5595b
|
danieltran-97/Python-practice
|
/polygon.py
| 655
| 4.21875
| 4
|
import turtle
class Polygon:
def __init__(self, sides,name, size=100):
self.sides = sides
self.name = name
self.size = size
self.interior_angles = (self.sides -2) * 180
self.angle = self.interior_angles/self.sides
def draw(self):
for i in range(self.sides):
turtle.forward(100)
turtle.right(180-self.angle)
square = Polygon(4, "Square")
pentagon = Polygon(5, "Pentagon")
print(square.sides)
print(square.name)
# print(square.interior_angles)
# print(square.angle)
print(pentagon.sides)
print(pentagon.name)
# pentagon.draw()
hexagon = Polygon(6, "Hexagon")
hexagon.draw()
| true
|
7b6866d61792eb6c0fd76f25fc0ea2a113816620
|
albertopuentes/python-exercises
|
/warmup.py
| 721
| 4.125
| 4
|
# 1
input_truck = "toyota tacoma"
input_truck.split()
make = input_truck.split()[0]
model = input_truck.split()[-1]
truck = dict(make = make, model = model)
print(truck)
# 2
input_truck = "toyota tacoma"
input_truck.split()
make = input_truck.split()[0]
model = input_truck.split()[-1]
truck = dict(make = make, model = model)
truck['make'] = truck['make'].capitalize()
truck['model'] = truck['model'].capitalize()
print(truck)
# 3
trucks = [dict(make='toyota', model='tacoma'),
dict(make='ford', model='F150'),
dict(make='land rover', model ='range rover')]
for truck in trucks:
truck['make'] = truck['make'].title()
truck['model'] = truck['model'].title()
print(trucks)
| false
|
3b6dbcc99b5fddb652c3bf6fc0ff43c3162879b2
|
Karanvir93875/PythonStuff
|
/RealTimeClock.py
| 907
| 4.15625
| 4
|
#This is a program which provides a close to accurate representation of real time
import os #clear screen functioning
import time
#variables display time length
seconds = float(0) #want to display decimals of each second
minutes = int(0) #want min to be dislayed as whole numbers
hours = int(0) #want hours to be displayed as whole numbers
run = input("Press x to run the program. ")
while run.lower() == "x":
if seconds > 59:
seconds = 0
minutes = minutes+1 #when counter hits 60 seconds, counter resets to 0 and adds a minutes
if minutes > 59:
minutes = 0
hours = hours+1 #when counter hits 60 minutes, counter resets to 0 and adds 1 hour
os.system('cls') #clears the command prompt, will just show current time
seconds = (seconds + .1)
print(hours, ":" , minutes, ":", seconds)
time.sleep(.1)
#will suspend execution for approximately .1 seconds
| true
|
bac9df13893156f4d650b4446423ea862246a45a
|
ferryleaf/GitPythonPrgms
|
/numbers/find_armstrong_number.py
| 604
| 4.3125
| 4
|
'''
Find all Armstrong numbers between two integers.
Example:
num=153
len(num)=3
1^3+5^3+3^3=153
Yes Armstrong number.
'''
def find_armstrong_number(lower,upper):
for i in range(lower,upper+1):
order=len(str(i))
temp=i
sum=0
while(temp!=0):
digit=temp%10
sum=sum + (digit ** order)
temp=temp//10
if(i==sum):
print(i,'YES')
#else:
# print(i,'NO')
if __name__=='__main__':
lst=input().rstrip().split()
lower=int(lst[0])
upper=int(lst[1])
find_armstrong_number(lower,upper)
| false
|
2dfe462d34c82b016bb249e719f86b1ca81d9603
|
ferryleaf/GitPythonPrgms
|
/numbers/plus_minus.py
| 2,118
| 4.15625
| 4
|
#!/bin/python3
'''
Given an array of integers,
calculate the fractions of its elements that are positive, negative, and are zeros.
Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems.
The test cases are scaled to six decimal places,
though answers with absolute error of up to 10^-4 are acceptable
For example,
given the array there are elements,
two positive, two negative and one zero.
Their ratios should be printed as
0.400000
0.400000
0.200000
Function Description
Complete the plusMinus function in the editor below.
It should print out the ratio of positive, negative and zero items in the array,
each on a separate line rounded to six decimals.
plusMinus has the following parameter(s):
arr: an array of integers
Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing an array of numbers .
Constraints
0< n <=100
-100 <= arr[i] <=100
Output Format
You must print the following lines:
A decimal representing of the fraction of positive numbers in the array compared to its size.
A decimal representing of the fraction of negative numbers in the array compared to its size.
A decimal representing of the fraction of zeros in the array compared to its size
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are 3 positive numbers, 2 negative numbers, and zero in the array.
'''
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
leng = len(arr)
pos=0
neg=0
zero=0
for ele in arr:
if(int(ele)>= -100 and int(ele)<=100):
if(int(ele)>0):
pos=pos+1
elif (int(ele)<0):
neg=neg+1
else:
zero+=1
print('%.6f'%(pos/leng))
print('%.6f'%(neg/leng))
print('%.6f'%(zero/leng))
if __name__ == '__main__':
n = int(input())
if (n>0 and n<=100):
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
| true
|
11cc4e82a74f71bf0c395392b69bb827e5719544
|
ferryleaf/GitPythonPrgms
|
/arrays/rotate_array.py
| 1,792
| 4.15625
| 4
|
'''
Given an unsorted array arr[] of size N, rotate it by D elements
in the COUNTER CLOCKWISE DIRECTION.
Example 1:
Input:
N = 5, D = 2
arr[] = {1,2,3,4,5}
Output: 3 4 5 1 2
Explanation: 1 2 3 4 5 when rotated
by 2 elements, it becomes 3 4 5 1 2.
Example 2:
Input:
N = 10, D = 3
arr[] = {2,4,6,8,10,12,14,16,18,20}
Output: 8 10 12 14 16 18 20 2 4 6
Explanation: 2 4 6 8 10 12 14 16 18 20
when rotated by 3 elements, it becomes 8 10 12 14 16 18 20 2 4 6.
Solution:
reverse(a, a+d) Reverse array from beginning till D
reverse(a+d, a+n) Reverse array from D till N
reverse(a, a+n) Reverse the whole array
UC 1:
77 69
40 13 27 87 95 40 96 71 35 79 68 2 98 3 18 93 53 57 2 81 87 42 66 90 45 20 41 30 32 18 98 72 82 76 10 28 68 57 98 54 87 66 7 84 20 25 29 72 33 30 4 20 71 69 9 16 41 50 97 24 19 46 47 52 22 56 80 89 65 29 42 51 94 1 35 65 25
Output:
29 42 51 94 1 35 65 25 40 13 27 87 95 40 96 71 35 79 68 2 98 3 18 93 53 57 2 81 87 42 66 90 45 20 41 30 32 18 98 72 82 76 10 28 68 57 98 54 87 66 7 84 20 25 29 72 33 30 4 20 71 69 9 16 41 50 97 24 19 46 47 52 22 56 80 89 65
UC 2:
5 2
1 2 3 4 5
Output: 3 4 5 1 2
UC3
10 3
2 4 6 8 10 12 14 16 18 20
Output: 8 10 12 14 16 18 20 2 4 6
'''
# More time consuming
def rotate_array(A, D, N):
a = A[D-1::-1]
b = A[N-1:D-1:-1]
a = a + b
return a[::-1]
# Faster
def rotateArr(A, D, N):
temp = A[:D]
for i in range(N):
if i < N - D:
A[i] = A[i + D]
else:
A[i] = temp[ i - (N - D)]
if __name__ == '__main__':
# arr = list(map(input().rstrip().split()), int)
arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print(arr)
print(rotate_array(arr, 3, 10))
print(arr)
print()
arr = [1, 2, 3, 4, 5]
print(arr)
print(rotate_array(arr, 2, 5))
print(arr)
| true
|
d9b2b796b2d33143feb70e02676cc6b701d36c54
|
ferryleaf/GitPythonPrgms
|
/trees/binary_search/level_order_traversal.py
| 2,050
| 4.34375
| 4
|
# Convert Tree into List/Queue
class Node:
def __init__(self, ele):
self.ele = ele
self.left = None
self.right = None
# Inserting an Element into Tree in Binary Search Tree Style
def insert(self, ele):
if self.ele is None:
self.ele = Node(ele)
else:
if ele < self.ele:
if self.left:
self.left.insert(ele)
else:
self.left = Node(ele)
elif ele >= self.ele:
if self.right:
self.right.insert(ele)
else:
self.right = Node(ele)
# Print all Nodes in Tree
def PrintNode(self):
if self.left:
self.left.PrintNode()
print(self.ele, end=" ")
if self.right:
self.right.PrintNode()
# Level Order Traversal of Binary Tree/Binary Search Tree
def level_order_traversal(self):
lists = []
if self.ele is None:
return
else:
if len(lists) == 0:
lists.append(self)
node = self
idx = 0
while node is not None:
if node.left is not None:
lists.append(node.left)
if node.right is not None:
lists.append(node.right)
idx += 1
if idx != len(lists):
node = lists[idx]
else:
break
for node in lists:
print(node.ele, end=" ")
if __name__ == '__main__':
# Use the insert method to add nodes
root = Node(1)
root.insert(2)
root.insert(3)
root.insert(4)
root.insert(5)
root.insert(6)
root.level_order_traversal()
# Use the insert method to add nodes
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(31)
root.insert(10)
root.insert(19)
# root.PrintNode()
print()
root.level_order_traversal()
| false
|
fd461e5e74a42b5e42b6d28e7d656811263f8c69
|
ferryleaf/GitPythonPrgms
|
/numbers/factor_of_numbers.py
| 450
| 4.125
| 4
|
'''
Find the Factors of a Number:
Example:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320
'''
import math
class Solution:
def find_factors(self,num:int) -> None:
factors=list()
for i in range(1,int(math.sqrt(num))+1):
if(num%i==0):
factors.append(i)
factors.append(int(num/i))
print(factors)
if __name__=='__main__':
Solution().find_factors(int(input()))
| true
|
de46cea01e81b8c4fe93c82a4e692ae76fc5a493
|
ferryleaf/GitPythonPrgms
|
/strings/strstr.py
| 1,504
| 4.125
| 4
|
'''
Your task is to implement the function strstr. The function takes two strings
as arguments (s,x) and locates the occurrence of the string x in the string s.
The function returns and integer denoting the first occurrence of the string x
in s (0 based indexing).
Example 1:
Input:
s = GeeksForGeeks, x = Fr
Output: -1
Explanation: Fr is not present in the
string GeeksForGeeks as substring.
Example 2:
Input:
s = GeeksForGeeks, x = For
Output: 5
Explanation: For is present as substring
in GeeksForGeeks from index 5 (0 based
indexing).
Your Task:
You don't have to take any input. Just complete the strstr() function which
takes two strings str, target as an input parameter. The function returns -1
if no match if found else it returns an integer denoting the first occurrence
of the x in the string s.
Expected Time Complexity: O(|s|*|x|)
Expected Auxiliary Space: O(1)
Note : Try to solve the question in constant space complexity.
Constraints:
1 <= |s|,|x| <= 1000
'''
def strstr(s, p):
s_len = len(s)
p_len = len(p)
for i in range(s_len-p_len+1):
cnt = 0
for j in range(p_len):
if s[i+j] != p[j]:
break
else:
cnt += 1
idx = i
if cnt == p_len:
return idx
return -1
if __name__ == '__main__':
print(strstr('ceaaddfddbcdefbbffdacbaaaaedaafafdfcaeebdaefdfeaf', 'abf'))
print(strstr('GeeksForGeeks', 'For'))
print(strstr('abcabcabcd', 'abcd'))
| true
|
e2c29fc113ab6d9f05e9d32e34127571032502f5
|
ferryleaf/GitPythonPrgms
|
/searching_sorting/binary_search.py
| 1,390
| 4.125
| 4
|
'''
Given a sorted array arr[] of N elements, write a function to search a
given element X in arr[] using Binary Search Algorithm.
'''
def binary_search_iterative(arr, X):
left = 0
right = len(arr) - 1
while(left <= right):
mid = left + ((right - left) // 2)
if arr[mid] == X:
return mid
if X < arr[mid]:
right = mid - 1
else:
left = mid + 1
return -1
def binary_search_recursive(arr, X, left, right):
if left <= right:
mid = left + ((right - left)//2)
if arr[mid] == X:
# print(mid)
return mid
if X < arr[mid]:
return binary_search_recursive(arr, X, left, mid - 1)
else:
return binary_search_recursive(arr, X, mid + 1, right)
return -1
if __name__ == '__main__':
list_of_arrs = [([1, 2, 3, 4, 5, 6], 2),
([1, 2, 3, 4, 5, 6, 7, 8], 8),
([10, 20, 25, 30, 60, 65, 110, 120, 130, 170], 110),
([10, 20, 25, 30, 60, 65, 110, 120, 130, 170], 175),
([10, 20, 25, 30, 60, 65, 110, 120, 130, 170], 170),
([10], 10),
([10], 20)]
for arr, X in list_of_arrs:
print(arr, X, 1 + binary_search_recursive(arr, X, 0, len(arr)-1))
print(arr, X, 1 + binary_search_iterative(arr, X))
| false
|
2279685ca3bb5e6292f371a5b51f798a48d638a7
|
iicoom/Note
|
/Interview/Algorithm-DS/Sort/1.冒泡/BubbleSort.py
| 287
| 4.21875
| 4
|
rawArr = [1, 3, 5, 10, 9, 8]
print rawArr
for i in range(0, len(rawArr))
print rawArr[i]
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
| false
|
5d4a34e282b9f7a119110f197a9d5af1c791adc6
|
Gaurav-Dutta/python_learning
|
/Basics/Functions/function1.py
| 921
| 4.21875
| 4
|
#a function is defined by using the ketyword "def". The block of code following the funciton definition is called function block
#function may or may not return a value if the function returns a value it uses the return keyword to return a value
#the first functionn below does not return any value, the second function returns the full name of a person given first name, middle
#initial, and last name
def print_personal_info(name, city):
print(f"Hello {name}")
print(f"I live in {city}")
print_personal_info("Gaurav", "Houston")
print_personal_info(name = "Indra", city = "Houston")
print(type(print_personal_info))
def get_full_name(firstName, middleInitial, lastName):
#return firstName + " " + middleInitial + " " + lastName
return f"{firstName} {middleInitial} {lastName}"
#the return value from a function should be assigned to a variable
x = get_full_name("Gaurav", "Kumar", "Dutta")
print(x)
| true
|
56a689b12738635f8e5afbefe694677f81e2e51b
|
Gaurav-Dutta/python_learning
|
/Basics/datatypes/list3.py
| 544
| 4.65625
| 5
|
#many times we have to access each item in a list and do something with it, a process called list iteration
#the simplest way of doing list iteration is using for each method on the list
myList = ["dog", "cat", "penguin", "giraffe"]
for animal in myList:
print(animal.capitalize())
print("hello")
#adding other animals to the list
myList.append("monkey")
myList.append("bat")
print(myList)
#removing cat
myList.remove("cat")
print(myList)
#inserting animals
myList.insert(1, "horse")
myList.insert(3, "elephant")
print(myList)
| true
|
84c3d33f89d054cda35e0533dbd82ad4ad30bbb5
|
shaikhjawad94/MITx-6.00.1x
|
/PS2/P3.py
| 1,124
| 4.125
| 4
|
low = balance / 12
high = (balance * (1 + (annualInterestRate/12.0))**12.0) / 12.0
minPay = (low + high) / 2
rerun = True
#low is the lowest minimum possible payment, i.e., when interest is 0%
#high is highets possible payment, i.e., when one payment made at the end of the year
def FixedPayBis(balance, annualInterestRate, minPay):
"""
Parameters
----------
balance : The outstanding balance on the credit card
annualInterestRate : Annual interest rate as a decimal
minPay : Smallest Monthly payment to the cent
Returns
-------
balance : New outstanding balance on the credit card
"""
month = 1
while month <= 12:
balance -= minPay
balance += balance*(annualInterestRate/12.0)
month += 1
return balance
while rerun == True:
a = FixedPayBis(balance, annualInterestRate, minPay)
if round(a) < 0:
high = minPay
minPay = (low + high) / 2
elif round(a) > 0:
low = minPay
minPay = (low + high) / 2
elif round(a) == 0:
rerun = False
print("Lowest Payment: " + str(round(minPay,2)))
| true
|
91a74cdc29907b5227b6fd6f0163f50aa85c2eac
|
rohw/InClassGit
|
/divisor.py
| 227
| 4.1875
| 4
|
def divisor(x):
print("The divisors are:", end=" ")
i = 1
while i <= x:
if (x % i == 0):
print(i, end=" ")
i += 1
x = int(input("Please enter a number for its divisors: "))
divisor(x)
| false
|
23efc9bf59c75c93eb3dc71c5c170943b5b24df2
|
tarunsingh8090/twowaits_python_programs
|
/Day 3/Problem 5.py
| 503
| 4.15625
| 4
|
size1 =int(input("Enter the no. of elements that you want to enter in List1:"))
List1=[]
print("Enter elements in List1 one by one:")
for i in range(size1):
List1.append(input())
size2= int(input("Enter the no. of elements that you want to enter in List2:"))
List2=[]
print("enter elements in List2 one by one:")
for i in range(size2):
List2.append(input())
intersectionList=list(set(List1).intersection(set(List2)))
print("The intersection of List1 and List2 is:",intersectionList)
| true
|
b197373baee082d3870197644e098d5ccdc4c9a6
|
evamaina/Basics
|
/sort.py
| 317
| 4.25
| 4
|
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for number in start_list:
number = number**2
square_list.append(number)
square_list.sort()
print square_list
"""Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list.
Then sort square_list!"""
| true
|
68834fc74c7c5b40e0d42b732cac0612cb2a8992
|
evamaina/Basics
|
/my_dict2.py
| 386
| 4.46875
| 4
|
my_dict = {
'name': 'Nick',
'age': 31,
'occupation': 'Dentist',
}
print my_dict.items()
print my_dict.keys()
print my_dict.values()
"""While .items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary:
The .keys() method returns a list of the dictionary's keys, and
The .values() method returns a list of the dictionary's values."""
| true
|
faf3315834df46189041f21df16000fe277bb240
|
Pytho-pixel/Calculator-Python-
|
/main.py
| 364
| 4.3125
| 4
|
num_1 = int(input('Enter Number 1 - '))
operator = input('Enter operator - ')
num_2 = int(input('Enter Number 2 Here - '))
if operator == '+':
print(num_1 + num_2)
elif operator == '-':
print(num_1 - num_2)
elif operator == '*':
print(num_1 * num_2)
elif operator == '/':
print(num_1 / num_2)
else:
print('Invalid Operator Entered')
| false
|
33246c7deb869e8eb6f06f45aa2ca9137d29b68b
|
gtmkr1234/learn-python39
|
/learn-python39/looping/else_with_loop.py
| 716
| 4.125
| 4
|
# else part with for loop
# optional section
n = int(input('enter the last range '))
for k in range(1, n+1):
if k > 5:
break
print(k, end=' ')
print('next>', end='')
else:
print('else part of for loop')
print('\nafter loop')
# prime no. without using third variable
k = int(input('Enter the number '))
for i in range(2, k):
if k%i==0:
print("Not Prime.")
break
else:
print("Prime No.")
n = 8
for i in range(1, n+1):
if i>5:
break
print(i, end=' ')
print("next>", end='')
else:
print("else part of for")
print("After for loop")
for i in range(1, 5):
continue
print(i, end=' ')
else:
print('loop completed')
| false
|
bce4ab96307b6335aacbdf6efcbaf38f92387e83
|
JPoser/python-the-hardway
|
/Exercise 33/ex33st5.py
| 389
| 4.1875
| 4
|
# Learn Python The Hard Way - Exercise 33 study drill 5
# Copied by Joe Poser
i = 2
max = 10
numbers = []
increase = 2
def count(i):
for i in range(i, max):
print "At the top i is %d" % i
numbers.append(i)
i = i + increase
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
count(i)
for num in numbers:
print num
| true
|
6e517cac536fb7bc827979ee81e448c89ca6cf9e
|
JPoser/python-the-hardway
|
/Exercise 30/ex30st4.py
| 1,224
| 4.34375
| 4
|
# Learn Python The Hard Way - Exercise 30
# Copied by JPoser
# Sets the value of people to 30
people = 30
# Sets the value of cars to 40
cars = 40
# Sets the value of buses to 15
buses = 15
# Checks if cars are greater than people
if cars > people:
# If cars are greater than people prints this string
print "We should take the cars."
# Checks if cars are less than people
elif cars < people:
# If cars are less than people prints this string
print "We should not take the cars."
# Checks if neither cases are true (cars equal people)
else:
# if so prints this line
print "We can't decide."
# Checks if buses are greater than cars
if buses > cars:
# if so prints this string
print "That's too many buses."
# checks if buses are less than cars
elif buses < cars:
# if so prints this string
print "Maybe we could take the buses."
# if neither (buses = cars)
else:
# prints this string
print "We still can't decide."
# checks if people are greater than buses
if people > buses:
# if so prints this string
print "Alright, let's just take the buses."
# checks if either people are less than buses or the same
else:
# prints this string
print "Fine, Let's stay home then."
| true
|
cff2259fbf8e9b71c9cf246627600695c1baed45
|
JPoser/python-the-hardway
|
/Exercise 7/ex7st1.py
| 1,043
| 4.15625
| 4
|
# Learn Python The Hard Way. Exercise 7 Study Drill 1.
# Copied by JPoser
# prints string
print "Mary had a little lamb."
# prints string with string nested inside
print "It's fleece was white as %s." % 'snow'
# prints string
print "And everywhere that mary went."
# prints string 10 times
print "." * 10 # what'd that do?
# sets variable to string
end1 = "C"
# sets variable to string
end2 = "h"
# sets variable to string
end3 = "e"
# sets variable to string
end4 = "e"
# sets variable to string
end5 = "s"
# sets variable to string
end6 = "e"
# sets variable to string
end7 = "B"
# sets variable to string
end8 = "u"
# sets variable to string
end9 = "r"
# sets variable to string
end10 = "g"
# sets variable to string
end11= "e"
# sets variable to string
end12 = "r"
# whatch that comma at the end. try removing it to see what happens
# prints concatenation of strings
print end1 + end2 + end3 + end4 + end5 + end6
# prints concatenation of strings
print end7 + end8 + end9 + end10 + end11 + end12
| true
|
f4db9cf283618b2912702f42d61dca43e86f0504
|
JPoser/python-the-hardway
|
/Exercise 4/ex4st3.py
| 1,276
| 4.34375
| 4
|
# Learn Python The Hard Way, Exercise 4 Study Drill 3.
# Copied by JPoser.
# Assigns variable "cars" to the integer (in future written as int) 100
cars = 100
# Assigns variable "space_in_a_car" to the floating number 4.0
space_in_a_car = 4.0
# Assigns the variable "drivers" to int 30
drivers = 30
# Assigns the variable "passengers" to the int 90
passengers = 90
# Assigns the variable "cars_not_driven" to the subtraction of the variables "cars" and "drivers"
cars_not_driven = cars - drivers
# Assigns the variable "cars_driven" to the variable "drivers"
cars_driven = drivers
# Assigns the variable "carpool_capacity" to multiplication of the variables "cars_driven" and "space_in_a_car"
carpool_capacity = cars_driven * space_in_a_car
# Assigns the variable "average_passengers_per_car" to the division of the variables "passengers" and "cars_driven"
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "we have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
| true
|
e821fa06ec048569e90cde1194aeb4faf15d10b4
|
RidaATariq/ITMD_413
|
/Assignment-4/HW_4/program-2/main.py
| 1,482
| 4.25
| 4
|
"""
This program asks the user to enter two 3x3 matrices to be multiplied
and then it gets the result.
Name: Cristian Pintor
"""
matrixA = []
matrixB = []
print('Enter a 3x3 matrix for matrix A: ')
for i in range(9):
matrixA.append(eval(input()))
print('Enter a 3x3 matrix for matrix B')
for i in range(9):
matrixB.append(eval(input()))
print('Matrix A: ', matrixA)
print('Matrix B: ', matrixB)
# multiplying
for i in matrixA:
c_11 = (matrixA[0]*matrixB[0]) + (matrixA[1]*matrixB[3]) + (matrixA[2]*matrixB[6])
c_21 = (matrixA[3]*matrixB[0]) + (matrixA[4]*matrixB[3]) + (matrixA[5]*matrixB[6])
c_31 = (matrixA[6]*matrixB[0]) + (matrixA[7]*matrixB[3]) + (matrixA[8]*matrixB[6])
c_12 = (matrixA[0]*matrixB[1]) + (matrixA[1]*matrixB[4]) + (matrixA[2]*matrixB[7])
c_22 = (matrixA[3]*matrixB[1]) + (matrixA[4]*matrixB[4]) + (matrixA[5]*matrixB[7])
c_32 = (matrixA[6]*matrixB[1]) + (matrixA[7]*matrixB[4]) + (matrixA[8]*matrixB[7])
c_13 = (matrixA[0]*matrixB[2]) + (matrixA[1]*matrixB[5]) + (matrixA[2]*matrixB[8])
c_23 = (matrixA[3]*matrixB[2]) + (matrixA[4]*matrixB[5]) + (matrixA[5]*matrixB[8])
c_33 = (matrixA[6]*matrixB[2]) + (matrixA[7]*matrixB[5]) + (matrixA[8]*matrixB[8])
print('The multiplication of the matrices is: ')
print(format(c_11, ',.1f'), format(c_12, ',.1f'), format(c_13, ',.1f'))
print(format(c_21, ',.1f'), format(c_22, ',.1f'), format(c_23, ',.1f'))
print(format(c_31, ',.1f'), format(c_32, ',.1f'), format(c_33, ',.1f'))
| true
|
6f557ae80a05f830d801d159aa2e54c612e58ae3
|
RidaATariq/ITMD_413
|
/Assignment_15/cpintor_HW_15/question_17.1/main.py
| 2,109
| 4.375
| 4
|
import sqlite3
connection = sqlite3.connect('books.db')
import pandas as pd
# 1. Select all authors' last names from the authors
# table in descending order
output_1 = pd.read_sql("""SELECT last
FROM authors
ORDER BY last DESC""",
connection)
print('Question #1: \n', output_1)
# 2. Select all book titles from the titles table in ascending order
output_2 = pd.read_sql("""SELECT title
FROM titles
ORDER BY title ASC""", connection)
print('Question #2: \n',output_2)
# 3.
output_3 = pd.read_sql("""SELECT first, last, title, copyright, ISBN
FROM titles
INNER JOIN authors
ON authors.last = 'Deitel' AND authors.first = 'Harvey'
ORDER BY title""", connection).head()
print('Question #3: \n',output_3)
# 4. Insert a new author into the authors table
cursor = connection.cursor()
cursor = cursor.execute("""INSERT INTO authors (first, last)
VALUES ('Bill', 'Gates')""")
output_4 = pd.read_sql('SELECT * FROM authors', connection)
print('Question #4: \n',output_4)
#5.
# inserting isbn into author_ISBN table
print('\ne. ** Inserting data pertaining to new author in author_ISBN and titles tables**')
cursor.execute("""INSERT INTO author_ISBN (id, isbn)
VALUES ('6', '1493379921')""")
print(pd.read_sql('SELECT * FROM author_ISBN ORDER BY id ASC', connection))
#inserting data into titles table
cursor.execute("""INSERT INTO titles (isbn, title, edition, copyright)
VALUES ('1593279922', 'How to Write Your First Python Program', '1', '2020')""")
print(pd.read_sql('SELECT * FROM titles ORDER BY title ASC', connection))
print('\n\nQuestion #5: ')
print(pd.read_sql("""SELECT authors.id, titles.title, authors.last, authors.first, author_ISBN.isbn, titles.copyright
FROM authors
INNER JOIN author_ISBN
ON authors.id = author_ISBN.id
INNER JOIN titles
ON author_ISBN.isbn = titles.isbn
ORDER BY authors.id ASC""", connection))
| true
|
61269f6c768d5965e50de89834b6d89fad9c88b1
|
RidaATariq/ITMD_413
|
/Assignment-2/Module-3_Lopping/while-loop-2.py
| 462
| 4.1875
| 4
|
'''
This program demonstrates the concept of while loop.
'''
import random
# Generate a random number to be guessed
number = random.randint(0, 100)
print("Guess a magic number between 0 and 100")
guess = -1
while guess != number:
guess = eval(input("Enter your guess: "))
if guess == number:
print("Yes the number is", number)
elif guess > number:
print("Your guess is too high")
else:
print("Your guess is too low")
| true
|
3812633581de8a898f8d978cf0c7e589323d4b30
|
RobRoger97/test_tomorrowdevs
|
/cap3/63_Average.py
| 363
| 4.21875
| 4
|
#Read a value from user
num = int(input("Enter a number: "))
sm=0.00
count=0
#Loop
if num==0:
print("Error message: the first number can't be 0")
else:
while num!=0:
count=count+1
sm = sm+num
num = int(input("Enter a number: "))
#Compute the average
average=sm/count
#Display the result
print("The average is:",average)
| true
|
8d68b11c78a261b452176bcf9dc7abd61732c276
|
RobRoger97/test_tomorrowdevs
|
/cap2/58_Is_It_a_Leap_Year.py
| 622
| 4.375
| 4
|
# Read the year from the user
year = int(input("Enter a year: "))
# Determine if it is a leap year
#Any year that is divisible by 400 is a leap year.
if year % 400 == 0:
isLeapYear = True
#Of the remaining years, any year that is divisible by 100 is not a leap year.
elif year % 100 == 0:
isLeapYear = False
#Of the remaining years, any year that is divisible by 4 is a leap year.
elif year % 4 == 0:
isLeapYear = True
#All other years are not leap years.
else:
isLeapYear = False
# Display the result
if isLeapYear:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
| true
|
31dca49e06b0a06e436dd8abed18510140e6ec16
|
RobRoger97/test_tomorrowdevs
|
/cap2/62_Roulette_Payouts.py
| 1,319
| 4.125
| 4
|
##
# Display the bets that pay out in a roulette simulation.
#
from random import randrange
# Simulate spinning the wheel, using 37 to represent 00
value = randrange(0, 38)
if value == 37:
print("The spin resulted in 00...")
else:
print("The spin resulted in %d..." % value)
# Display the payout for a single number
if value == 37:
print("Pay 00")
else:
print("Pay", value)
# Display the color payout
# The first line in the condition checks for 1, 3, 5, 7 and 9
# The second line in the condition checks for 12, 14, 16 and 18
# The third line in the condition checks for 19, 21, 23, 25 and 27
# The fourth line in the condition checks for 30, 32, 34 and 36
if value % 2 == 1 and value >= 1 and value <= 9 or \
value % 2 == 0 and value >= 12 and value <= 18 or \
value % 2 == 1 and value >= 19 and value <= 27 or \
value % 2 == 0 and value >= 30 and value <= 36:
print("Pay Red")
elif value == 0 or value == 37:
pass
else:
print("Pay Black")
# Display the odd vs. even payout is no work to be performed.
if value >= 1 and value <= 36:
if value % 2 == 1:
print("Pay Odd")
else:
print("Pay Even")
# Display the lower numbers vs. upper numbers payout
if value >= 1 and value <= 18:
print("Pay 1 to 18")
elif value >= 19 and value <= 36:
print("Pay 19 to 36")
| true
|
e8f9c0ab9af876319bcec91df8d79769920effc0
|
RobRoger97/test_tomorrowdevs
|
/cap5/ex110_Sorted_Order.py
| 382
| 4.375
| 4
|
#Read a integer from the user
integ = int(input("Enter a integer: "))
# Start with an empty list
lis=[]
#While loop
while integ!=0:
lis+=[integ]
print(lis)
integ = int(input("Enter a integer: "))
#Sort the value of the list
lis.sort()
#Display the values in ascending order
print("The values, sorted into ascending order, are:")
for integ in lis:
print(integ)
| true
|
bbc19ce55b709f62bc8e97b08ea104851ba49728
|
RobRoger97/test_tomorrowdevs
|
/cap2/55_Wavelengths_of_Visible_Light.py
| 625
| 4.25
| 4
|
#Read the wavelenght from the user
w_lenght = int(input("Enter a wavelenght: "))
#Report its color
if w_lenght>= 380 and w_lenght<450:
color = "Violet"
elif w_lenght>=450 and w_lenght<495:
color = "Blue"
elif w_lenght>=495 and w_lenght<570:
color = "Green"
elif w_lenght>=570 and w_lenght<590:
color = "Yellow"
elif w_lenght>=590 and w_lenght<620:
color = "Orange"
elif w_lenght>=620 and w_lenght<=750:
color = "Red"
else:
color = ""
#Display the result
if color == "":
print("That wavelenght is ouside of the visible spectrum.")
else:
print("The color of that wavelenght is: %s" %color)
| false
|
fad3b778a58587f27e8a349ab5195914ba9f25d1
|
RobRoger97/test_tomorrowdevs
|
/cap2/42_Note_to_Frequency.py
| 725
| 4.1875
| 4
|
#Note's frequency
C4_f = 261.63
D4_f = 293.66
E4_f = 329.63
F4_f = 349.23
G4_f = 392.00
A4_f = 440.00
B4_f = 493.88
#Read the note name from user
name = input ("Enter the two character note name, such as C4: ")
#Store the note and its octave in separate variables
note = name[0]
octave = int(name[1])
#Get the frequency of the note, assuming it is in the fourth octave
if note=="A":
f = A4_f
elif note=="B":
f = B4_f
elif note=="C":
f = C4_f
elif note=="D":
f = D4_f
elif note=="E":
f = E4_f
elif note=="F":
f = F4_f
elif note=="G":
f = G4_f
#Now adjust the frequency to bring it into the crrect octave
freq = f/(2**(4-octave))
#Display the result
print("The frequency of ", name, "is", freq)
| true
|
93d7bdb71b4db9b716b7b5aa22ab1e821e1cb6e3
|
RobRoger97/test_tomorrowdevs
|
/cap3/75_Is_a_String_a_Palindrome.py
| 513
| 4.40625
| 4
|
# Read the string from the user
line = input("Enter a string: ")
is_palindrome = True
i = 0
#While loop to scroll through the string
while i < len(line) / 2 and is_palindrome:
# If the characters do not match then mark that the string is not a palindrome
if line[i] != line[len(line) - i - 1]:
is_palindrome = False
# Move to the next character
i+=1
# Display a meaningful output message
if is_palindrome:
print(line, "is a palindrome")
else:
print(line, "is not a palindrome")
| true
|
3d01523003458f3d773435d65c4cee5905eb55dd
|
RobRoger97/test_tomorrowdevs
|
/cap6/ex140_postal_codes.py
| 1,043
| 4.125
| 4
|
code = input("Enter a postal code: ").upper()
lis = list(code)
dic = {'Newfoundland':'A','Nova Scotia':'B','Prince Edward Island':'C','New Brunswick':'E',\
'Quebec':['G','H','J'],'Ontario':['K','L','M','N','P'],'Manitoba':'R','Saskatchewan':'S',\
'Alberta':'T','British Columbia':'V','Nunavut':'X','Northwest Territories':'X','Yukon':'Y'}
if len(code)<=6:
if lis[0]=='D' or lis[0]=='F' or lis[0]=='I' or\
lis[0]=='O' or lis[0]=='Q' or lis[0]=='U' or\
lis[0]=='W' or lis[0]=='Z' or lis[0].isdigit or lis[1].isdigit()==False:
print("Error message: That is not a right postal code")
else:
if lis[0] == 'X':
result = 'Nunavut or Northwest'
else:
for d in dic:
if lis[0]==dic[d]:
result = d
if lis[1] == 0:
address = 'rural'
else:
address = 'urban'
print("The postal code",code,"is for a(an)",address,"address in",result)
else:
print('This is not a right postal code!')
| false
|
4567fafd5bce319bb17e7b1b90c455e6cda5a3f5
|
RobRoger97/test_tomorrowdevs
|
/cap2/44_Faces_on_Money.py
| 677
| 4.21875
| 4
|
#Name and value
G_Wash = "George Washington"
T_Jeff = "Thomas Jefferson"
A_Lin = "Abraham Lincoln"
A_Ham = "Alexander Hamilton"
A_Jack = "Andrew Jackson"
U_Sg = "Ulysses S. Grant"
B_Fran = "Benjamin Franklin"
#Read the denomination from user
d = int(input("Enter the denomination of a banknote: "))
#Check of name and denomination of banknote
if d==1:
name = G_Wash
elif d==2:
name = T_Jeff
elif d==5:
name = A_Lin
elif d==10:
name = A_Ham
elif d==20:
name = A_Jack
elif d==50:
name = U_Sg
elif d==100:
name = B_Fran
else:
name = ""
#Display result
if name == "":
print("There is no denomination that corresponds to a bankonote.")
else:
print("This denomination ",d," corresponds to ", name, " face.")
| false
|
677e1fa22ecacc625f85aef5b2d586b202e0b9fe
|
muondu/datatypes
|
/megaprojects/strings/st4.py
| 429
| 4.125
| 4
|
print("Enter your name in small letters")
a = input("Enter your first word of your name: ")
print(a.upper())
b = input("Enter your second word of your name: ")
print(b)
c = input("Enter your third word of your name: ")
print(c.upper())
d = input("Enter your fourth word of your name: ")
print(d)
e = input("Enter your fifth word of your name: ")
print(e.upper())
f = input("Enter your sixth word of your name: ")
print(f)
| true
|
5766ba5c7fd8c06a386984124c24074d19f06764
|
sacheenanand/pythonbasics
|
/quick_sort.py
| 1,231
| 4.3125
| 4
|
#Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays.
#A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and
#another array holds values greater than the pivot value.
#Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays.
#This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(nLogn) and image.png(n2), respectively.
#The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element.
list = [3,1,2,4,5,3,5,6,7,1]
def quick_sort(list, low, high):
if low < high:
p = partion(list, low, high)
quick_sort(list, low, p-1)
quick_sort(list, p+1, high)
def partion(list, low, high):
divider = low
pivot = high
for i in range(low, high):
if list[i] < list[pivot]:
list[i], list[divider] = list[divider], list[i]
divider +=1
list[divider],list[pivot] = list[pivot],list[divider]
return divider
quick_sort(list, 0, 9)
print("here you go", list)
| true
|
58fbd02b4bd79c57b9ec7d5a52016ca6689bab8c
|
Judy-special/Python
|
/02-basic-201807/is_Palindrome.py
| 576
| 4.15625
| 4
|
# coding = utf8
def is_Palindrome(the_str):
"""
本函数用来判别是否为回文字符串
"""
l = len(the_str) - 1
n = int(l/2)
if len(the_str) == 0:
print("The String is Null")
elif len(the_str) > 0:
temp = []
for i in range(n):
if the_str[i]==the_str[l-i]:
temp.append("True")
elif the_str[i] != the_str[l-i]:
temp.append("False")
if 'False' in temp:
print("No,the string is not palindrome")
else:
print("Yse,the string is palindrome")
| true
|
e343c335766ff26481a4daf445d7bf5615de2486
|
Pajace/coursera_python_miniproject
|
/miniproject2.py
| 2,442
| 4.125
| 4
|
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# 1. initialize global variable
num_range = 100
remaining_guesses = 7
user_guesses = 0
secret_number = random.randrange(0, num_range)
# 2. helper function to start and restart the game
def new_game():
global secret_number
secret_number = random.randrange(0, num_range)
print_new_game_message()
def print_new_game_message():
print "New game. Range is from 0 to ", num_range
print "Number of remaining guesses is ", remaining_guesses
print ""
def print_lose_message():
print "You ran out of guesses. The number was ", secret_number
print ""
def start_game_by_range():
if num_range == 100:
range100()
elif num_range == 1000:
range1000()
def is_number(number):
try:
int(number)
return True
except ValueError:
return False
def setGuessesRange(range, countOfGuesses):
global num_range, remaining_guesses
num_range = range
remaining_guesses = countOfGuesses
# 4. define event handlers for control panel
def range100():
setGuessesRange(100, 7)
new_game()
def range1000():
setGuessesRange(1000, 10)
new_game()
def input_guess(guess):
global remaining_guesses, user_guesses
if not is_number(guess):
print "Please input a valid integer\n"
return
user_guesses = int(guess)
remaining_guesses = remaining_guesses - 1
print "Guess was ", user_guesses
print "Number of remaining guesses is ", remaining_guesses
if user_guesses == secret_number:
print "Correct!\n"
start_game_by_range()
elif remaining_guesses == 0:
print_lose_message()
start_game_by_range()
elif user_guesses < secret_number:
print "Higher!\n"
elif user_guesses > secret_number:
print "Lower!\n"
# 5. create frame
frame = simplegui.create_frame("Guess the number", 200, 200)
# 6. egister event handlers for control elements and start frame
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
frame.add_input("Enter a guess", input_guess, 200)
# 7. call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true
|
d4be5236a64fdc4114e017a4b5e65da20a4b6f18
|
aronaks/algorithms
|
/algorithms/gfg_arrays2.py
| 543
| 4.34375
| 4
|
def find_leaders(keys):
"""
Write a function that prints all the LEADERS in the array. An element is leader
if it is greater than all the elements to its right side. And the rightmost
element is always a leader. For example int the array {16, 17, 4, 3, 5, 2},
leaders are 17, 5 and 2.
"""
keys_length = len(keys)
all_leaders = []
leader = 0
for i in range(keys_length-1, -1, -1):
if keys[i] > leader:
leader = keys[i]
all_leaders.append(leader)
return all_leaders
| true
|
e1dbe97738f28b03916540a49a6ebe0db0e25bbd
|
nicholas0417/python-tutorial
|
/data_types/product.py
| 238
| 4.15625
| 4
|
# Q1
num1 = int (input("please enter number1:"))
num2 = int (input("please enter number2:"))
product = num1 * num2
# If product is greater than 1000
if (product < 1000):
print("The product is : " product)
else:
print(num1 + num2)
| true
|
91cc8136c752f5397b51511012fe2be70a3993fd
|
AaronAikman/MiscScripts
|
/Py/AlgorithmsEtc/BuildingHeight.py
| 351
| 4.15625
| 4
|
# CalculateBuildingHeight.py
# Aaron Aikman
# Calculate height of a building based upon the inputted number of floors
while True:
numFloors = input("Enter a number of floors (returns cm):")
if (numFloors == ""):
break
buildingHeight = ((3.1 * numFloors) + 7.75 + (1.55 * (numFloors / 30)))
print buildingHeight * 100
print "\n"
| true
|
2d635fb9dd499cd344039e1b980c938188e08b09
|
Gaurav715/DDS1
|
/main.py
| 2,596
| 4.28125
| 4
|
# Python program for implementation of BubbleSort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Python program for implementation of InsertionSort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
# Python program for implementation of SelectionSort
def selectionSort(arr):
for i in range(len(arr)):
# Find the minimum element in remaining
minPosition = i
for j in range(i+1, len(arr)):
if arr[minPosition] > arr[j]:
minPosition = j
# Swap the found minimum element with minPosition
temp = arr[i]
arr[i] = arr[minPosition]
arr[minPosition] = temp
return arr
# Example to test code above
arr1 = [64, 34, 25, 12, 22, 11, 90, 123, 42134, 342,-2]
# bubbleSort(arr1)
# selectionSort(arr1)
mergeSort(arr1)
#selectionSort(arr1)
print ("Sorted array is:")
for i in range(len(arr1)):
print (arr1[i]),
| true
|
5a801a5c74adfcf8384e518c6715671834d81cc8
|
bogdan19adrian/b2b_festival
|
/common/common.py
| 437
| 4.125
| 4
|
import re
# Make a regular expression
# for validating an Email
regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
# Define a function for
# for validating an Email
def validate_email(email):
# pass the regualar expression
# and the string in search() method
if (re.search(regex, email)):
print("Valid Email " + email)
return True
else:
print("Invalid Email " + email)
return False
| false
|
de3fa85ee012acb070b0023e2be345d43f3aab43
|
CaptainCrossbar/CodeWars
|
/(8) Is it a number?.py
| 348
| 4.1875
| 4
|
def isDigit(string):
#Check to see if string is an integer
try:
int(string)
return True
#String was no an integer
except:
#Check to see if string is a float
try:
float(string)
return True
#String is no a valid integer or float
except:
return False
| true
|
c1dbde41aa30ce350a1ef3266c92f8ec8cec96bd
|
melissav00/Python-Projects
|
/project_exercise2.py
| 479
| 4.1875
| 4
|
start = int(input("Pick a starting number for a list:"))
end = int(input("Pick a ending number for a list:"))
def generateNumbers(start,end):
num_list=[]
if start == end:
print("Both values are equal to each other. Please input opposite values.")
elif start > end:
print("Enter a start values less than end.")
while (start < end):
start = start + 1
num_list.append(start)
print(num_list)
generateNumbers(start,end)
| true
|
c26edaa2be2871462292fd22c1e45ef0fc24c386
|
fp-computer-programming/cycle-3-labs-p22cgussen
|
/lab2-2.py
| 260
| 4.21875
| 4
|
# Author CCG 9/28/21
number = input("Type a number")
if int(number) % 2 == 0:
print("You have an even number!")
else:
print("You have an odd number!")
if int(number) >= 0:
print("x is a positive number")
else:
print("x is a negative number")
| false
|
71400360a39ed118953261791fbac2066c112d27
|
Moiz-khan/Piaic_Assignment01
|
/co-ordinate.py
| 377
| 4.21875
| 4
|
#program to measure distance
def distance(x1, y1, x2, y2):
return (x2 - x1)**2 + (y2 - y1)**2
x1 = int(input("Enter Co-ordinate of x1: "))
y1 = int(input("Enter Co-ordinate of y1: "))
x2 = int(input("Enter Co-ordinate of x2: "))
y2 = int(input("Enter Co-ordinate of y2: "))
print("Distance between points(",x1,",",y1,") and (",x2,",",y2,") is",distance(x1, y1, x2, y2))
| false
|
bdd47bd94d25de8b95debacc99fbed3fc14f294a
|
Moiz-khan/Piaic_Assignment01
|
/copiesof string.py
| 208
| 4.21875
| 4
|
#program to print copies of string
str = input("Enter String: ")
n = int(input("How many copies of String you need: "))
print(n, "copies of",str,"are ",end=" ")
for x in range(1,n+1):
print(str,end=" ")
| true
|
9ce34e74be5fd35c0c2c2638b7dc7057b562a83d
|
Moiz-khan/Piaic_Assignment01
|
/divisible.py
| 318
| 4.21875
| 4
|
#number is completely divisible by another number
num = int(input("Enter Numerator: "))
deno = int(input("Enter Denominator: "))
if( num%deno == 0):
{
print("Number", num , "is completely divisible by", deno)
}
else:
{
print("Number", num , "is not completely divisible by", deno)
}
| false
|
5e48ffd4a519bf0a0a5e2f42f645f2ae37f9cb22
|
heis-divine/PythonCalculator
|
/main.py
| 1,309
| 4.28125
| 4
|
# Calculator project
print("What Calculation would you like to perform?")
print("1)Addition\n2)Subtraction\n3)Multiplication\n4)Division")
choice = int(input("Enter preferred Option: "))
if choice == 1:
print("Addition")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
total = num1 + num2
print(total)
print("The sum of the two numbers entered are:", total)
print("Thanks for using our calculator")
elif choice == 2:
print("Subtraction")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
total1 = num1 - num2
print("The difference of the two numbers entered are:" , total1)
print("Thanks for using our calculator")
elif choice == 3:
print("Multiplication")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
total2 = num1 * num2
print("The product of the two numbers entered are:" , total2)
print("Thanks for using our calculator")
elif choice == 4:
print("Division")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
total3 = num1 / num2
print("The quotient of the two numbers entered are:" , total3)
print("Thanks for using our calculator")
| true
|
c994c56cf773a7c24b6aef21fe93e1dfbad83fc4
|
SivaCn/Bigdata.model
|
/src/utils/chains.py
| 2,000
| 4.25
| 4
|
#! /usr/bin/python
"""Linked list Representation and implementation.
"""
# -*- coding: utf-8 -*-
## ------ Imports ------ ##
## ------ Imports ------ ##
__author__ = "Siva Cn (cnsiva.in@gmail.com)"
__website__ = "http://www.cnsiva.com"
class Node:
"""Referential Structure used to create new nodes"""
def __init__(self, **kwargs):
"""Constructor."""
self.data = kwargs.get('filaname', '')
self.next = None
self.col_name = None
self.hashcode = None
class Meta:
"""A meta class contains info about the tree at any moment.
"""
def __init__(self, **kwargs):
"""Constructor."""
self.start = None
self.size = 0
self._id_start, self._id_end = kwargs.get('_id_range', (-1, -1))
def __repr__(self):
"""."""
return "SubList({0}, {1})".format(self._id_start, self._id_end)
class LinkedList:
def __init__(self, **kwargs):
"""Constructor."""
self._list = Meta(**kwargs)
self._list.start = None
def insert(self, data):
"""Insert a new node with in the tree.
"""
_temp = Node(data)
if not self._list.start:
self._list.start = _temp
return
walker = self._list.start
while walker.next:
walker = walker.next
self._list.size += 1
walker.next = _temp
def show(self):
"""Display the Tree as it traverses LEFT -> ROOT -> RIGHT."""
walker = self._list.start
while walker:
print walker.data
walker = walker.next
if __name__ == "__main__":
"""This is the first block of Statements to be executed."""
tree = LinkedList() # Root Node
tree.insert(5) # child
tree.insert(5) # child
tree.insert(15) # child
tree.insert(25) # child
tree.insert(1) # child
tree.insert(2) # child
tree.insert(20) # child
tree.insert(500) # child
tree.insert(3) # child
tree.show()
| false
|
75752fa8139a12de337fa40553785211469139d2
|
Zahidsqldba07/PythonPrac
|
/Time & Calendar.py
| 618
| 4.25
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import time
import datetime
import calendar
# In[2]:
### Get the current date and time
print(datetime.datetime.now())
# In[3]:
### Get just the current time
print(datetime.datetime.now().time())
# In[4]:
start = time.time()
print("hello")
end = time.time()
print(end - start)
# In[5]:
#print calender of the given month,year
yy = 2019
mm = 12
# display the calendar
print(calendar.month(yy, mm))
# In[6]:
print ("The calender of year 2019 is : ")
print (calendar.calendar(2020, 3, 1, 2)) # year, width, height , spacing
# In[ ]:
| true
|
9eaa0b1c7da2c45fe62ee929143597f3beddeb9c
|
Zahidsqldba07/PythonPrac
|
/Python Tips.py
| 1,336
| 4.21875
| 4
|
#!/usr/bin/env python
# coding: utf-8
# # Swapping Values
# In[1]:
x,y = 10, 5
print(x,y)
# In[2]:
x,y =y,x
print(x,y)
# # Combining a list of strings into a single one
#
# In[3]:
sentence = ['Why','is','the','rum','gone','?']
concat_sen = "".join(sentence)
print(concat_sen)
# # Initiallizing a list
# In[4]:
[0]*10
# In[5]:
[7]*10
# # Merging List
# In[6]:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)
# # Reversing a String
# In[7]:
name = "Jack Sparrow"
name[::-1]
# # List Comprehension
# In[8]:
a = [1, 2, 3]
b = [i*2 for i in a] # Create a new list by multiplying each element in a by 2
print(b)
# # Iterating over a dictionary
# In[9]:
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in m.items():
print('{0}: {1}'.format(key, value))
# # Iterating over list values while getting the index too
# In[10]:
m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
print('{0}: {1}'.format(index, value))
# # Removing useless characters on the end of your string
# In[11]:
name = "Jack "
name_2 = "Sparrow///"
name.strip() # prints "Jack"
# In[12]:
name_2.strip("/") # prints "Sparrow"
# # Found the most frequent value in the list
# In[13]:
test = [1, 2, 3, 4, 2, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
# In[ ]:
| false
|
5e4f7196eece576d7a5cc69017c35eeee6056d75
|
Zahidsqldba07/PythonPrac
|
/Logic 1.py
| 2,303
| 4.21875
| 4
|
#!/usr/bin/env python
# coding: utf-8
# # You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe).
#
#
# In[1]:
def date_fashion(you, date):
if you <= 2 or date <=2:
return 0
elif you >=8 or date >=8:
return 2
else:
return 1
date_fashion(5, 10)
# # The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number.
#
#
# In[2]:
def love6(a, b):
return a == 6 or b == 6 or a+b == 6 or abs(a-b) == 6
love6(6, 4)
# # Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
#
#
# In[4]:
def alarm_clock(day, vacation):
week_preset = "7:00" if not vacation else "10:00"
weekend_preset = "10:00" if not vacation else "off"
return week_preset if day not in [6,0] else weekend_preset
alarm_clock(0, False)
# # You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases
# In[6]:
def caught_speeding(speed, is_birthday):
speeding = speed - (65 if is_birthday else 60)
if speeding > 20:
return 2
elif speeding > 0:
return 1
else:
return 0
caught_speeding(65, False)
# In[ ]:
| true
|
38c45a4fbd57093e586ed9c1fe820b958a1d0343
|
codevr7/samples
|
/one-bit_binary_adder.py
| 275
| 4.15625
| 4
|
#binary adder
choices = ['0','1']
problem = input("select 2 numbers between 0 and 1(0,1)")
if problem != '0' or problem != '1':
print("binary adder cannot process numbers other than 1 and 0")
if problem_1 != :
print("binary adder cannot process numbers more than 1")
| true
|
1b36b1abc616005a72e5b7bd72dbf081152b62e1
|
codevr7/samples
|
/odd_sort.py
| 536
| 4.28125
| 4
|
# A function for sorting only odd numbers from a list of mixed numbers
def odd_sort(n):
l = len(n)# The length of the input
for i in range(0, l):# A range for 0 to length of input
for j in range(i, l):# A second range for evaluating for each number
if n[i]%2 != 0:# Evaluating each number, whether odd or not
if n[j]%2 != 0:# Eval
if n[i] > n[j]:
n[i], n[j] = n[j], n[i]
return n
| true
|
f06708b1981654e8736f6d959c675e9d7f50f683
|
CyborgVillager/Learning_py_info
|
/py_4_evry_one/Dictionary/bk0/dic0.py
| 1,853
| 4.21875
| 4
|
# making a dictio maps englihs to spanish words
# importing from spanish_numb_info
# install PyDictionary
# exception error list: https://www.programiz.com/python-programming/exceptions
"""''''''
from PyDictionary import PyDictionary
english_to_spanish = PyDictionary()
print(english_to_spanish.translate("Range",'es'))
''''''"""
# english_to_spanish = dict()
english_to_spanish = {'one': 'uno', 'two': 'dos', 'three': 'tres', 'four': 'cuatro', 'five': 'cinco', 'six': 'seis',
'seven': 'siete', 'eight': 'ocho', 'nine': 'nueve', 'ten': 'diez'}
def spanish_func0():
try:
print(english_to_spanish)
# index the dicto using the keys
print(english_to_spanish['three'])
# in operator -> tells you if something appears a key in the dictio
# check if the key is in the dictio
check_if_key_in_dictio = 'three'
if check_if_key_in_dictio in english_to_spanish:
print('yes the key --', check_if_key_in_dictio, '-- is not in the dicto')
else:
print('No the key --', check_if_key_in_dictio, '-- is not in the dictio')
except KeyError:
print('not in dicto, please try again!')
# spacing between the statements
def spacing():
space_time = 1
print('\n' * space_time)
# checking the value in the dictio
def spanish_func1():
try:
value_in_the_dictio = list(english_to_spanish.values())
spanish_number = 'ocho'
if spanish_number in value_in_the_dictio:
print('yes the spanish number --', spanish_number, '-- is in the dictionary')
else:
print('no the spanish number --', spanish_number, '-- is not in the dictionary')
except KeyError:
print('not in dicto, please try again!')
def main():
spanish_func0()
spacing()
spanish_func1()
main()
| false
|
3ece7ee246f9e1367949690c1c38ddabac94a198
|
pragyatwinkle06/Python_patterns_and_codes
|
/ZIGZAG PATTERN CHALLENGE3.py
| 1,149
| 4.40625
| 4
|
# Python3 ZIGZAG PATTERN CHALLENGE3
# Function to print any string
# in zigzag fashion
def zigzag(s, rows):
# Store the gap between the major columns
interval = 2 * rows - 2
# Traverse through rows
for i in range(rows):
# Store the step value for each row
step = interval - 2 * i
# Iterate in the range [1, N-1]
for j in range(i, len(s), interval):
# Print the character
print(s[j], end = "")
if (step > 0 and step < interval and
step + j < len(s)):
# Print the spaces before character
# s[j+step]
for k in range((interval - rows - i)):
print(end = " ")
# Print the character
print(s[j + step], end = "")
# Print the spaces after character
# after s[j+step]
for k in range(i - 1):
print(end = " ")
else:
# Print the spaces for first and
# last rows
for k in range(interval - rows):
print(end = " ")
print()
if __name__ == '__main__':
# Given Input
s = input("enter string: ")
rows=int(input("enter a no"))
# Function Call
zigzag(s, rows)
# enter no. of rows u want
| true
|
303052540a0f284b4c1b97143cb54b1cd7c05e52
|
LauraValentinaHernandez/Taller-estructuras-de-control-selectivo
|
/Ejercicio14.py
| 901
| 4.28125
| 4
|
"""
Desarrolle un programa en Python que calcule y muestre el monto que debe pagar ar suscriptor por concepto de consumo de luz eléctrica y servicio de aseo urbano. Dicho monto se calcula multiplicando la diferencia de la lectura anterior y la lectura actual por el costo de cada Kilovatio hora, según la siguiente escala:
"""
lecturanterior=int(input("Digite lectura anterior: "))
lecturactual=int(input("Digite lectura actual: "))
D=lecturactual-lecturanterior
if(D>0 and D<=100):
totalpago=D*4.600
print("Monto total a pagar es: {:.0f}".format(totalpago))
elif(D>101 and D<=300):
totalpago=D*80.00
print("Monto total a pagar es: {:.0f}".format(totalpago))
elif(D>301 and D<=500):
totalpago=D*100.000
print("Monto total a pagar es: {:.0f}".format(totalpago))
elif(D>501):
totalpago=D*120.000
print("Monto total a pagar es: {:.0f}".format(totalpago))
else:
print("!!!ERRORRR¡¡¡¡")
| false
|
6dbaeac22713d2537bc8eae746781641e8b0a86a
|
NoahNacho/python-solving-problems-examples
|
/Chapter7/Exercise1.py
| 308
| 4.28125
| 4
|
# Write a function to count how many odd numbers are in a list.
# Base of function was taken from Chap6 Exercise14
def is_even(n):
num = 0
for odd in n:
if (odd % 2) == 0:
pass
else:
num += 1
return num
odd_list = [1, 2, 3, 4, 5]
print(is_even(odd_list))
| true
|
8cb6d0552df6cbd44d7462aa9a0fdc5b91f90474
|
denny61302/100_Days_of_Code
|
/Day19 Racing Game/main.py
| 1,371
| 4.1875
| 4
|
from turtle import Turtle, Screen
import random
colors = ["red", "yellow", "green", "blue", "black", "purple"]
turtles = []
for _ in range(6):
new_turtle = Turtle(shape="turtle")
turtles.append(new_turtle)
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win?")
if user_bet:
is_race_on = True
index = 0
for turtle in turtles:
turtle.penup()
turtle.color(colors[index])
turtle.goto(x=-230, y=-170 + index * 50)
index += 1
while is_race_on:
for turtle in turtles:
if turtle.xcor() > 230:
is_race_on = False
winner_color = turtle.pencolor()
if winner_color == user_bet:
print("You win")
else:
print(f"You lose, the winner is {winner_color} turtle")
turtle.forward(random.randint(0, 10))
# def forward():
# turtle.forward(10)
#
#
# def backward():
# turtle.backward(10)
#
#
# def clock():
# turtle.right(5)
#
#
# def counter_clock():
# turtle.left(5)
#
#
# def reset():
# turtle.reset()
#
#
# screen.listen()
# screen.onkey(key="w", fun=forward)
# screen.onkey(key="s", fun=backward)
# screen.onkey(key="a", fun=counter_clock)
# screen.onkey(key="d", fun=clock)
# screen.onkey(key="c", fun=reset)
screen.exitonclick()
| true
|
c0f64d4b90693d45bfe23da72c3cba4a2632bd61
|
darrenredmond/programming-for-big-data_10354686
|
/CA 1/TestCalculator.py
| 2,884
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 16 19:08:49 2017
@author: 10354686
"""
# Import the Python unittest functions
import unittest
# Import the functions defined in the 'Calculator' file
from Calculator import *
# Create a class which extends unittest.TestCase
class TestCalculator(unittest.TestCase):
# This function is defined to test the add function created
def testAdd(self):
self.assertEqual(add(2,2),4)
self.assertEqual(add(5,3),8)
self.assertEqual(add(4,0),4)
# This function is defined to test the subtract function created
def testSubtract(self):
self.assertEqual(subtract(2,2),0)
self.assertEqual(subtract(5,3),2)
self.assertEqual(subtract(4,0),4)
# This function is defined to test the multiply function created
def testMultiply(self):
self.assertEqual(multiply(2,2),4)
self.assertEqual(multiply(5,3),15)
self.assertEqual(multiply(4,0),0)
# This function is defined to test the divide function created
def testDivide(self):
# 4 / 1 = 4
# 4 / 2 = 2
# 2 / 2 = 1
# 0 / 1 = 0
# 5 / 4 = 1.25
# Divide by zero - return error
self.assertEqual(divide(4,1),4)
self.assertEqual(divide(4,2),2)
self.assertEqual(divide(2,2),1)
self.assertEqual(divide(0,1),0)
self.assertEqual(divide(5,4),1.25)
self.assertEqual(divide(5,0),'error')
# This function is defined to test the exponent function created
def testExponent(self):
self.assertEqual(exponent(2,2),4)
self.assertEqual(exponent(2,3),8)
self.assertEqual(exponent(3,3),27)
# This function is defined to test the square root function created
def testSqrroot(self):
self.assertEqual(sqrroot(4),2)
self.assertEqual(sqrroot(16),4)
self.assertEqual(sqrroot(36),6)
# This function is defined to test the tan function created
def testTan(self):
self.assertEqual(tan(0),0)
self.assertEqual(tan(0.5),0.5463024898437905)
self.assertEqual(tan(1),1.5574077246549023)
# This function is defined to test the cos function created
def testCos(self):
self.assertEqual(cos(0),1)
self.assertEqual(cos(0.5),0.8775825618903728)
self.assertEqual(cos(1),0.5403023058681397)
# This function is defined to test the sin function created
def testSin(self):
self.assertEqual(sin(0),0)
self.assertEqual(sin(0.5),0.479425538604203)
self.assertEqual(sin(1),0.8414709848078965)
# This function is defined to test the factorial function created
def testFactorial(self):
self.assertEqual(factorial(5),120)
self.assertEqual(factorial(8),40320)
self.assertEqual(factorial(6),720)
if __name__ == '__main__':
unittest.main()
| true
|
af68068c121d2eeebb9a1f1e1daaadb89af9b634
|
abby-does-code/machine_learning
|
/quiz2.py
| 2,781
| 4.5
| 4
|
# Start#
"""You are to apply skills you have acquired in Machine Learning to correctly predict the classification of a group of animals. The data has been divided into 3 files.
Classes.csv is a file describing the class an animal belongs to as well as the name of the class. The class number and class type are the two values that are of most importance to you.
animals_train.csv download - is the file you will use to train your model. There are 101 samples with 17 features. The last feature is the class number (corresponds to the class number from the classes file). This should be used as your target attribute. However, we want the target attribute to be the class type (Mammal, Bird, Reptile, etc.) instead of the class number (1,2,3,etc.).
animals_test.csv download - is the file you will use to test your model to see if it can correctly predict the class that each sample belongs to. The first column in this file has the name of the animal (which is not in the training file). Also, this file does not have a target attribute since the model should predict the target class.
Your program should produce a csv file that shows the name of the animal and their corresponding class as shown in this file -predictions.csv """
import pandas as pd
import csv
animal_class = pd.read_csv("animal_classes.csv")
X = pd.read_csv("animals_train.csv")
X.columns = [
"hair",
"feathers",
"eggs",
"milk",
"airborne",
"aquatic",
"predator",
"toothed",
"backbone",
"breathes",
"venomous",
"fins",
"legs",
"tail",
"domestic",
"catsize",
"class_number",
]
y = X["class_number"]
X = X.drop(columns="class_number")
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X, y)
test = pd.read_csv("animals_test.csv")
test_data = test.drop(columns="animal_name") # feed everything except the target
predicted = knn.predict(X=test_data)
print(predicted[:10])
# predicted = [animal_class.target_names[i] for i in predicted]
class_number = animal_class["Class_Number"]
animal_name = test["animal_name"].to_list()
class_names = animal_class["Class_Type"]
print(class_names[:10])
# predicted = [class_number[i] for i in predicted]
# print(predicted)
name_num_dict = {
1: "Mammal",
2: "Bird",
3: "Reptile",
4: "Fish",
5: "Amphibian",
6: "Bug",
7: "Invertebrate",
}
predicted = [name_num_dict[x] for x in predicted]
print(predicted[:10])
"""match the animal name in test data to an animal name in the list in animal_classes based on the class number"""
i = 0
with open("model_predictions_file.csv", "w") as model_file:
for p in predicted:
line = animal_name[i] + "," + p + "\n"
i += 1
model_file.write(line)
| true
|
b883911a98cd09445da07329c1cdca5ebb24391e
|
joedo29/DataScience
|
/MatplotlibPractices.py
| 733
| 4.25
| 4
|
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = x*2
z = x**2
# Exercise 1: Create a single plot
fig1 = plt.figure()
ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_title('Outer Plot')
ax1.plot(x,y)
# Exercise 2: plot inside a plot
ax2 = fig1.add_axes([0.25, 0.55, 0.2, 0.2]) # left - bottom - width - height
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_title('Inner Plot')
ax2.plot(x, z, color='red')
# Exercise 3: create subplot 2 row by 2 columns
fig3, ax3 = plt.subplots(nrows=2, ncols=2, figsize=(12, 6))
ax3[0, 0].plot(x, y, linestyle='--', color='blue', linewidth=5)
ax3[1, 1].plot(x, z, color='red', linewidth=10)
# plt.tight_layout()
plt.show()
| true
|
737baea08cfb3099f127d972318818e92f915437
|
mattyice89/LearnPythonTheHardWay
|
/ex19.py
| 1,243
| 4.15625
| 4
|
# defining the argument Cheese and crackers and naming your variables
def cheese_and_crackers(cheese_count,boxes_of_crackers):
# printing out the first variable, named "cheese_count"
print(f"You have {cheese_count} cheeses!")
# printing out the second variable, named "boxes_of_crackers"
print(f"You have {boxes_of_crackers} boxes of crackers!")
# some bullshit
print("Man that's enough for a party!")
# more bullshit
print("Get a blanket.\n")
# loading the exact numbers you want into your function
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
# you can create new variables and call them in your function
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
# using math instead of variables - note that this doesn't then Get
# stored as the variables that we defined in the previous step
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
# prints using the variables we defined two steps ago plus some math
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
| true
|
96c2ccd7e834bb194bb50973e772580784ee9455
|
trustme01/PythonCrashCourse2
|
/ch_3/cars.py
| 753
| 4.59375
| 5
|
# Sorting a list PERMANENTLY with the sort() method.
# Alphabetically:
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# Reverse alphabetically:
cars.sort(reverse=True)
print(cars)
# Sorting a list TEMPORARILY with the sort() method.
cars2 = ['bmw', 'audi', 'toyota', 'subaru']
print('\nHere is the original list: ')
print(cars2)
print('\nHere is the sorted (alphabetical) list: ')
print(sorted(cars2))
print('\nHere is the original list again: ')
print(cars2)
# Reverse alphabetically:
print('\nHere is the list reversed in alphabetical order: ')
print(sorted(cars2, reverse=True))
# Printing a List in Reverse Order
# reverse() method
cars3 = ['bmw', 'audi', 'toyota', 'subaru']
print(cars3)
cars3.reverse()
print(cars3)
| true
|
9be69557321c8e1c498e26371acb00e06fc3bad5
|
MDCGP105-1718/portfolio-S191617
|
/ex8.py
| 730
| 4.25
| 4
|
portion_deposit = 0.20
current_savings = 0
r = 0.04
monthly_interest = current_savings*(r/12)
monthly_salary= annual_salary/12
total_cost = float(input("Total cost of the house"))
annual_salary= float(input("Enter the starting annual salary:"))
portion_saved= float(input("How much money do you want to save?"))
semi_annual_raise=float(input("By what proportion does you salary increase every six months?"))
portion_deposit = total_cost*portion_deposit
months = 0
while current_savings < total_cost*portion_deposit:
current_savings += current_savings*(r/12)
current_savings += monthly_salary * portion_saved
months += 1
monthly_salary += monthly_salary * (semi_annual_raise/12)
print("Number of months:", months)
| true
|
2288678a651b13e959bcb43c28771c64a2ec3dd8
|
amey-kudari/NN_nLines
|
/I_am_trask/basic-python-network/2-layer-simple.py
| 2,282
| 4.15625
| 4
|
"""
code taken from "https://iamtrask.github.io/2015/07/12/basic-python-network/"
I learnt about neural networks from here, but I feel this is a little complicated
as it needs you to actually compute the matricies on paper to see what is happening.
I made a simpler model that isnt full batch training, and in my opinion, its
easier to understand for a beginner who started off like me :)
Also, the reason I find this easy is because I first learnt about neural
networks from 3blue1brown, and my model is based on that.
"""
import numpy as np
x=np.array([[1,1,1],
[1,0,1],
[0,0,1],
[0,1,1]])
y=np.array([[1,1,0,0]]).T
np.random.seed(1)
# effectively, this is the neural network.
syn=2*np.random.random((3,1))-1 # mean 0
def sig(x):
return 1/(1+np.exp(-x))
def der(x):
return x*(1-x)
syn0 = np.array(syn)
for it in range(1000):
tsyn0 = np.array(syn0)
serror = []
for i in range(len(x)):
# layer 0, in this case is x[i],
# layer 1, is the output layer, computed as
# sig(x[i].syn0) for ith input.
# layer 1 is a simple single node.
"""
neural network in this model:
layer 0 | layer 1
x[i][0]___
\
tsyn[0]
\
x[i][1]----tsyn[1] ========> l1
/
tsyn[2]
/
x[i][2]---
"""
error = y[i]-sig(np.dot(x[i],syn0))
serror.append(error[0])
dl = error*der(sig(np.dot(x[i],syn0)))
tsyn0 += np.array([dl[0]*x[i]]).T
# comment following line to get full batch training.
syn0 = tsyn0
# the exact same model, just that back weights get
# updated once per batch
serror = np.array(serror)
syn0 = tsyn0
l0=x
l1=sig(np.dot(l0,syn))
error=y-l1
dl=error*der(l1)
syn+=np.dot(l0.T,dl)
#print(error.T)
#print(dl.T)
#print(np.dot(l0.T,dl))
print(syn0.T,syn.T)
print(serror,error.T)
while True:
print("enter array to predict : ")
tp = np.array([int(x) for x in input().split()])
print("my model , trask's model")
print(float(sig(np.dot(tp,syn0))),float(sig(np.dot(tp,syn))))
| true
|
eb48a58c8578f145a0b9a892c5b4efb100314fdd
|
Ridwanullahi-code/basic-python
|
/exercise1.py
| 313
| 4.4375
| 4
|
# write a python program which accepts the users's first and last name
# and print them in reverse order with space between them
# assign first name value
first_name = 'Ridwanullahi'
last_name = 'Olalekan'
# To display the input values
print(f'{last_name} {first_name}')
print(name)
print("school")
| true
|
b686a22202aa61eb9a909d195d83fc6197595a51
|
mccarvik/cookbook_python
|
/1_data_structs_algos/1_17_extract_subet_dict.py
| 636
| 4.125
| 4
|
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# Make a dict of all prices over 200
p1 = {key:value for key,value in prices.items() if value > 200}
print(p1)
# Make a dict of all tech names
tech_names = ['AAPL','IBM','HPQ','MSFT']
p2 = {key:value for key,value in prices.items() if key in tech_names}
print(p2)
# creating a sequence of tuples and passing them to dict function
p1 = dict((key,value) for key,value in prices.items() if value>200)
print(p1)
# Another way to do it
tech_names={'AAPL','IBM','HPQ','MSFT'}
p2 = {key:prices[key] for key in prices.keys() & tech_names}
print(p2)
| false
|
181165441ccf08e506b38f64ad9b5dea8de93f33
|
jesusdmartinez/python-labs
|
/14_list_comprehensions/14_04_fish.py
| 277
| 4.15625
| 4
|
'''
Using a listcomp, create a list from the following tuple that includes
only words ending with *fish.
Tip: Use an if statement in the listcomp
'''
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
list = [w for w in fish_tuple if w[-4:] == 'fish']
print(list)
| true
|
fef717e2f35131316bf6f6d9bfd2b4f69df91e53
|
jesusdmartinez/python-labs
|
/03_more_datatypes/1_strings/03_04_most_characters.py
| 445
| 4.40625
| 4
|
'''
Write a script that takes three strings from the user and prints the one with the most characters.
'''
string1 = str(input("please input a string1"))
string2 = str(input("please input a string2"))
string3 = str(input("please input a string3"))
len1 = len(string1)
len2 = len(string2)
len3 = len(string3)
big = max(len1, len2, len3)
if big == len1:
print(string1)
if big == len2:
print(string2)
if big == len3:
print(string3)
| true
|
1c6d7f8e10eee6f71804df3c4847cacb24e60966
|
jesusdmartinez/python-labs
|
/13_aggregate_functions/13_03_my_enumerate.py
| 333
| 4.25
| 4
|
'''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate():
my_num = input("create a list of anything so I can enumerate")
new_num = my_num.split()
print(list(enumerate(new_num)))
my_enumerate()
| true
|
7a4c9ddf6fe4e1f00bdc287e1efbcf11c50127fd
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Task 2/3.py
| 635
| 4.15625
| 4
|
#TASK TWO
#OPERATORS AND DECISION MAKING STATEMENT
#3. Write a program in Python to implement the given flowchart:
a, b, c = 10, 20, 30
avg = (a + b + c) / 3
print("Avg = ", avg)
if avg > a and avg > b and avg > c:
print("Avg higher than a, b, c")
elif avg > a and avg > b:
print("Avg higher than a, b")
elif avg > a and avg > c:
print("Avg higher than a, c")
elif avg > b and avg > c:
print("Avg higher than b, c")
elif avg > a:
print("Avg only higher than a")
elif avg > b:
print("Avg is just higher than b")
elif avg > c:
print("Avg is just higher than c")
| false
|
347b7a7baabf1a8713e4a30df0bbc95ed1c179b0
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Task 4/11.py
| 592
| 4.125
| 4
|
# TASK FOUR
# TRADITIONAL FUNCTIONS,ANONYMOUS FUNCTIONS &
# HIGHER ORDER FUNCTIONS
# 11. Write a program which uses map() and filter() to make a list whose elements are squares of even
# numbers in [1,2,3,4,5,6,7,8,9,10].
# Hints: Use filter() to filter even elements of the given listUse map() to generate a list of squares of the
# numbers in the filtered list. Use lambda() to define anonymous functions.
# result = filter(lambda x: x % 2 == 0, range(1, 11))
# print(list(result))
square = map(lambda z: z ** 2, filter(lambda x: x % 2 == 0, range(1, 11)))
print(list(square))
| true
|
b8d6cefaa900afdff0cb72b063f2b8d3f2e55f38
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Task 2/4.py
| 499
| 4.15625
| 4
|
#TASK TWO
#OPERATORS AND DECISION MAKING STATEMENT
#4. Write a program in Python to break and continue if the following cases occurs:
#If user enters a negative number just break the loop and print “It’s Over”
#If user enters a positive number just continue in the loop and print “Good Going”
x = int(input("Enter a number: "))
while True:
if x < 0:
print("It's over")
break
else:
print("Good Going")
x = int(input("Enter a number: "))
| true
|
a30e6a2547e8a4e3227359660e1be7b4c7a55aeb
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Additional Task/5.py
| 388
| 4.15625
| 4
|
# EXTRA TASK
# DATA STRUCTURES
# 5. Write a program in Python to reverse a string and
# print only the vowel alphabet if it exists in the
# string with their index.
x = input("Enter the String: ")
y = x[::-1]
print("Reversed String: ", y)
vow = ['a','e','i','o','u','A','E','I','O','U']
print("Only Vowels: ")
for i in range(len(y)):
if y[i] in vow:
print(y[i], i)
| false
|
7e0b5ce3a86eae805fad3f1de40b0340c8978032
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Task 1/4.py
| 263
| 4.34375
| 4
|
#TASK ONE NUMBERS AND VARIABLES
#4. Write a program that takes input from the user and prints it using both Python 2.x and Python 3.x Version.
color = raw_input("Enter the color name: ")
#print(color)
color = input("Enter the colour name: ")
print(color)
| true
|
5154b91ee876350111fd6f0a8c35d268798ee742
|
ankitpatil30/Ankit_Python_Projects
|
/Python_Assignments/Task 4/9.py
| 624
| 4.34375
| 4
|
# TASK FOUR
# TRADITIONAL FUNCTIONS,ANONYMOUS FUNCTIONS &
# HIGHER ORDER FUNCTIONS
# 9. Write a function called showNumbers that takes a parameter called limit. It should print all the
# numbers between 0 and limit with a label to identify the even and odd numbers.
# Sample input: show Numbers(3) (where limit=3)
# Expected output:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
def showNumbers(limit):
for i in range(0, limit+1):
if i % 2 == 0:
print(i, "EVEN")
elif i % 2 != 0:
print(i, "ODD")
return 'Null'
x = int(input("Enter the limit: "))
print(showNumbers(x))
| true
|
adaf84e3ecda29d8d4748db2590325e3e5a0baff
|
nandoangelo/nandoangelo-python-cursoemvideo
|
/mundo-1/desafio000.py
| 490
| 4.25
| 4
|
# DESAFIO 000
# Aqui eu resolvi experimentar o uso das variáveis em Python
#
# -------------------------------------- Mundo I / Aula 04 ----
# Entradas
nome = input ('Qual o seu nome?\n')
idade = input ('Quantos anos você tem?\n')
# Saida
print('Olá,', nome,'. Com ', idade, 'anos eu também já programava.')
'''
Usando entrada de dados no Python 3 e montando a saída usando
vírgulas. Detalhe que quando usamos vírgula o interpretador
adiciona espaços na impressão.
'''
| false
|
a712f5b8ba3aaf1e1a8c219e54b4c07b7b1d50e4
|
himsila/CP3-Sila-Sobaeam
|
/Lecture50_Sila_S.py
| 430
| 4.1875
| 4
|
def Plus(x, y):
print(f"{x} + {y} = {x + y}")
def Minus(x, y):
print(f"{x} - {y} = {x - y}")
def Multiplying(x, y):
print(f"{x} * {y} = {x * y}")
def Division(x, y):
print(f"{x} / {y} = {int(x / y)}")
print("-------- Let's Cal! --------")
x = int(input("First number : "))
y = int(input("Second number : "))
print("-------- Results --------")
Plus(x, y)
Minus(x, y)
Multiplying(x, y)
Division(x, y)
print("Done.")
| false
|
4fcadc2b4105a17dc95f54cca290644e3436b75a
|
ujwalnitha/stg-challenges
|
/learning/basics12_number_converter_class.py
| 1,108
| 4.15625
| 4
|
''''
This file is to wrap number to words code in a class
Reference: https://www.w3schools.com/python/python_classes.asp
If we have to use a method from Class, outside calling file
-we have to import the class in calling file
-create an object and call function
-if it is a static function, call ClassName.function_name()
This method will just digits to words, not to a number sentence wrt to digit place
'''
class NumberToWordsClass:
def get_number_in_word(self, input_number=0):
number_words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
# Each item in list hs index starting from 0, so number_words[2] will return "Two" in this case
# using conversion to string to tokenize
number_string = str(input_number)
number_sentence = ""
for x in number_string:
digit = int(x) # Convert to number
word = number_words[digit]
print(word) # From list, get corresponding word
number_sentence = number_sentence + number_words[digit] + " "
return number_sentence
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.