blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3a9d223b46ddf42fa5441b463b4ced1b1fad7ed2 | avi527/Array | /copyElements.py | 421 | 4.4375 | 4 | # Python program to copy all elements of one array into another array
arr1 = [1, 2, 3, 4, 5];
arr2=[None]*len(arr1)
for i in range(0,len(arr1)):
arr2[i]=arr1[i]
#Displaying elements of array arr1
print("Elements of original array: ");
for i in range(0,len(arr1)):
print(arr1[i])
#Displaying elements of array arr2
print("Elements of new array: ");
for i in range(0,len(arr2)):
print(arr2[i]) | true |
2aeb3098eed13470afc7d93b807fc042656de5cd | juandarr/ProjectEuler | /23.py | 1,168 | 4.125 | 4 | """
Finds the sum of all numbers that can be expressed as the sum of two abundant numbers
Author: Juan Rios
"""
import math
"""
Sum of proper divisors
"""
def sum_proper_divisors(n):
if n==1:
return 0
total = 1
sqrt_n = math.sqrt(n)
if n%sqrt_n==0:
total += sqrt_n
limit_range = int(sqrt_n)
else:
limit_range = int(sqrt_n) + 1
for d in range(2, limit_range):
if n%d==0:
total += d + n//d
return total
def abundant(n):
abundant = []
for i in range(2,n+1):
if i < sum_proper_divisors(i):
abundant.append(i)
sum_abundant = [0]*(n+1)
for index in range(len(abundant)):
value = abundant[index]
for addition in range(index, len(abundant)):
if (value+abundant[addition])<(n+1):
sum_abundant[value+abundant[addition]] = 1
total = 0
for i in range(1,n+1):
if sum_abundant[i]==0:
total += i
return total
if __name__ == "__main__":
limit_n = 28123
print('The sum of all numbers that can be expressed as the sum of two abundant numbers is {1}'.format(limit_n, abundant(limit_n))) | true |
e69c01e60f4450a77a46b822db62571a44bd0128 | juandarr/ProjectEuler | /46.py | 2,516 | 4.15625 | 4 | """
Finds the smallest odd composite that cannot be written as the sum of a prime and twice a square
Author: Juan Rios
"""
import math
"""
Returns an array with prime numbers using the prime sieve
This array can be in two forms:
- An array of the primes themselves
- Array of ones and zeros, where value is '1' where the index corresponds to a prime number
"""
def prime_factors(upper_limit, explicit_primes = True):
values = [1]*(upper_limit+1)
values[0] = 0
values[1] = 0
for i in range(4,upper_limit+1,2):
values[i] = 0
current_value = 3
while (current_value<upper_limit):
if values[current_value]==1:
for i in range(2*current_value,upper_limit+1,current_value):
values[i] = 0
current_value += 2
if not(explicit_primes):
return values
else:
primes = []
for i in range(len(values)):
if values[i]==1:
primes.append(i)
return primes
"""
Returns an array with twice a square values under upper limit
This array can be in two forms:
- An array of twice a square themselves
- Array of ones and zeros, where value is '1' where the index corresponds to twice a square
"""
def twice_a_square(upper_limit, explicit_array = True):
values = [0]*(upper_limit+1)
i = 1
while (2*i**2<=upper_limit):
values[2*i**2] = 1
i += 1
if not(explicit_array):
return values
else:
twice_square = []
for i in range(len(values)):
if values[i]==1:
twice_square.append(i)
return twice_square
"""
Returns the smallest odd composite that cannot be written as the sum of a prime and twice a square
"""
def smalles_odd_compositve():
primes_array = prime_factors(10**6, False)
primes = prime_factors(10**6, True)
twice = twice_a_square(10**6, False)
i = 9
while True:
if primes_array[i]==0:
condition = False
for p in primes:
if (p<i):
j = i - p
if twice[j]==1:
condition = True
break
else:
break
else:
i += 2
continue
if not(condition):
return i
i += 2
if __name__ == "__main__":
print('The smallest odd composite that cannot be written as the sum of a prime and twice a square is {0}'.format(smalles_odd_compositve())) | true |
e8c40cd1680ff25f45e2ac0e3d51ef95ed9158e1 | juandarr/ProjectEuler | /3.py | 826 | 4.25 | 4 | """
Finds the largest prime factor of a number
Author: Juan Rios
"""
import math
import itertools
# Finds the prime factors of number
def prime_factors(number):
primes = []
# Loop through number 2, and every odd number below sqrt(number)
for i in itertools.chain([2],range(3,math.floor(math.sqrt(number))+1,2)):
# If number is divisible by i
while(number%i==0):
primes.append(i) # Add the number to the list of prime decomposition
number /= i # Get the complement factor, where oldNumber = newNumber*i
if number==1:
# If number is 1, return primes list
return primes
return primes
if __name__ == "__main__":
number = 600851475143
print('The largest prime factor of the number {0} is {1}'.format(number, prime_factors(number)[-1]))
| true |
944b097ff11c85a82b95787ee16a3d2553d7dafa | juandarr/ProjectEuler | /9.py | 475 | 4.375 | 4 | """
Finds the product of the Pytagorean triplet for which a+b+c=1000
Author: Juan Rios
"""
import math
# Finds the product of the pythagorean triplet for which a+b+c=1000
def triplet_product():
for b in range(498,2,-1):
for a in range(b-1,1,-1):
if ((1000*(a+b)-a*b)==(1000**2)/2):
return a*b*(1000-a-b)
if __name__ == "__main__":
print('The product of the pythagorean triplet for which a+b+c=1000 is {0}'.format(triplet_product())) | true |
af2e25611062c917b1e4f01c40c12eb27d877567 | juandarr/ProjectEuler | /62.py | 2,801 | 4.21875 | 4 | """
Finds the smallest cube that has exactly 5 permutations that are also cubes
Author: Juan Rios
"""
import math
from utils import elements_perm_k
from itertools import permutations
"""
Returns the smallest cube that has exactly 5 permutations that are also cubes
"""
def find_smallest_cube(cube_permutations):
visited= {}
number = 345
while True:
cube = number**3
cube_string = ''.join(sorted(str(cube)))
if cube_string not in visited:
visited[cube_string]=1
cubes = 1
tmp_number = number+1
cube_tmp_number = tmp_number**3
while len(str(cube_tmp_number))==len(cube_string):
if ''.join(sorted(str(cube_tmp_number)))==cube_string:
cubes += 1
tmp_number += 1
cube_tmp_number = tmp_number**3
if cubes == cube_permutations:
return cube
number += 1
"""
Returns the smallest cube that has exactly 5 permutations that are also cubes
"""
def find_smallest_cube_alt(cube_permutations):
visited= {}
number = 345
counter = 0
min_value = float('inf')
candidates = []
while True:
cube = number**3
cube_string = ''.join(sorted(str(cube)))
if cube_string not in visited:
visited[cube_string]=[cube,1]
else:
visited[cube_string][1]+=1
if visited[cube_string][1]==cube_permutations:
candidates.append(visited[cube_string][0])
tmp_number = number+1
cube_tmp_string = ''.join(sorted(str(tmp_number**3)))
min_value = visited[cube_string][0]
while len(cube_tmp_string)==len(cube_string):
if cube_tmp_string not in visited:
visited[cube_tmp_string]=[cube,1]
else:
visited[cube_tmp_string][1]+=1
if visited[cube_tmp_string][1]==cube_permutations:
if min_value > visited[cube_tmp_string][0]:
candidates.append(visited[cube_tmp_string][0])
print(candidates)
min_value = visited[cube_tmp_string][0]
elif visited[cube_tmp_string][0] in candidates:
candidates.remove(visited[cube_tmp_string][0])
tmp_number += 1
cube_tmp_string = ''.join(sorted(str(tmp_number**3)))
return candidates[-1]
number += 1
if __name__ == "__main__":
cube_permutations = 6
print('The smallest cube with {0} permutations that are also cubes is {1}'.format(cube_permutations, find_smallest_cube_alt(cube_permutations))) | true |
14584e74de3253ea3e9001bf375781a370ce3920 | AnteDujic/pands-problem-sheet | /secondString.py | 632 | 4.25 | 4 | # Program that asks user to input a string and outputs every second letter in reverse order
# Author: Ante Dujic
# Inputting a string (Prompting user for the input)
stringInput = input ("Please enter a sentence: ")
# Taking every second character of a string
stringSecond = (stringInput [1::2])
# Outputting every second character in reverse
print (stringSecond [::-1])
"""
REFERENCES:
- string slicing:
https://stackoverflow.com/questions/509211/understanding-slice-notation
https://www.w3schools.com/python/python_strings_slicing.asp
https://www.educative.io/edpresso/how-do-you-reverse-a-string-in-python
""" | true |
7ee31ee0d3f7dcf2955d7c4c54ea88e008a1553d | rushilmtron/Python | /53_type_of_method_1.py | 1,823 | 4.21875 | 4 | class student:
# here we creat class variable
school = 'Mechatron'
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
# Here we create the method for calculating average of m1,m1 & m3
# its a instance method
def avg(self):
return (self.m1+ self.m2 + self.m3)/3
# to get m1 value get_1 method is created it is a method
def get_1(self):
return self.m1
# to get m2 value get_2 method is created it is a method
def get_2(self):
return self.m2
# to get m3 value get_3 method is created it is a method
def get_3(self):
return self.m3
# to set value of m1 we createc set_1 method
def set_m1(self,value1):
self.m1 = value1
return (value1)
# to set value of m1 we createc set_1 method
def set_m1(self, value2):
self.m2 = value2
return (value2)
# to set value of m1 we createc set_1 method
def set_m1(self, value3):
self.m3 = value3
return (value3)
# create 2 object we can also pass the value in ()
a = int(input('Enter m1 for s1:'))
b = int(input('Enter m2 for s1:'))
c = int(input('Enter m3 for s1:'))
s1 = student(a,b,c)
s2 = student(80,85,95)
# print the avg value
print(s1.avg())
print(s2.avg())
# get value of m1, m2, m3
print(s1.get_1())
print(s1.get_2())
print(s1.get_3())
# set value of m1, m2, m3 we can also give input from assign variable to the while passing values in class ref. line 42
#x = int(input(('Enter the updated marks od s1 in m1 sub:')))
#print(s1.set_m1(x))
#y = int(input(('Enter the updated marks od s1 in m2 sub:')))
#print(s1.set_m1(y))
#z = int(input(('Enter the updated marks od s1 in m3 sub:')))
#print(s1.set_m1(z))
| true |
654ab14938585c5939405a87e916002cbdc6bc03 | Habibur-Rahman-007/python_project | /Madlibs_HOW_THEY_MET.PY | 2,296 | 4.375 | 4 | print("How They Met")
loop=1
while loop<10:
grooms_name=input("Enter Groom's Name: ")#
brides_name=input("Enter Bride's Name: ")
noun1=input("Enter a Noun: ")
number1=input("Enter a Number: ")
school_name=input("Enter a School Name: ")
place_on_campus=input("Enter a place on Campus: ")
verb1=input("Enter a Verb(ing): ")
verb2=input("Enter a Verb(ed): ")
greeting=input("Enter a Greeting: ")
adjective1=input("Enter an Adjective : ")
adverb1=input("Enter an Adverb: ")
adjective2=input("Enter an Adverb : ")
verb3=input("Enter a Verb(ed) : ")
plural_noun1=input("Enter a Plural noun : ")
verb4=input("Enter a Verb(ed): ")
noun2=input("Enter a Noun: ")
number2=input("Enter a Number: ")
verb5=input("Enter a Verb(ing): ")
plural_noun2=input("Enter a Plural Noun: ")
number3=input("Enter a Number: ")
verb6=input("Enter a Verb(ed): ")
fancy_restaurant=input("Enter a Fancy Restaurant name: ")
adverb2=input("Enter an Adverb: ")
number3=input("Enter a Number: ")
special_event=input("Enter a Special Event: ")
noun3=input("Enter a Noun: ")
verb7=input("Enter a Verb(ing): ")
noun4=input("Enter a Noun: ")
print("WHEN",grooms_name,"MET",brides_name,"IT WAS",noun1,"AT")
print(number1,"SIGHT.HE SAW HER AT",school_name,"HIGH SCHOOL AS SHE WAS")
print("STANDING NEXT TO THE",place_on_campus,".",verb1,"TO ANOTHER FRIEND")
print("OF HIS. HE",verb2,"OVER TO SAY",greeting,"INTRODUCED HIMSELF")
print("AND ASKED HER NAME. SHE WAS SO",adjective1,"! 'HI THERE'. SHE SAID.")
print(adverb1,". MY NAME IS",brides_name,". SHE HAD SEEN HIM AROUND")
print("AND THOUGHT HE WAS SUPER",adjective2,". THEY",verb3,"FOR A")
print("WHILE AND THEN EXCHANGED",plural_noun1,"LATER HE",verb4,"TO")
print("ASK HER OUT ON A",noun2,"ON THEIR",number2,"DATE.THEY")
print("WENT",verb5,"AND HAD",plural_noun2,"OF FUN. THE",number3)
print("TIME THE",verb6,"OUT. HE TOOK HER TO",fancy_restaurant,"SINCE")
print("THINGS WENT SO",adverb2,"ON THEIR",number3,"DATE HE INVITED")
print("HER TO HIS",special_event,"AFTER THAT THEY WERE OFFICIALLY A")
print(noun3,"AND HE STARTED",verb7,"HER AS HIS",noun4,".")
loop+=1 | false |
963015a29d42b14763992c7c0707a419c878d71c | WXLyndon/Data-structures-and-algorithms-review | /hash_table/first_recurring_character.py | 519 | 4.125 | 4 | # Google Question
# Given an array = [2,5,1,2,3,5,1,2,4]:
# It should return 2
# Given an array = [2,1,1,2,3,5,1,2,4]:
# It should return 1
# Given an array = [2,3,4,5]:
# It should return undefined
def first_recurr_char(arr):
dict = {}
for char in arr:
if char in dict:
return char
dict[char] = 1
return None
arr1 = [2,5,1,2,3,5,1,2,4]
print(first_recurr_char(arr1))
arr2 = [2,1,1,2,3,5,1,2,4]
print(first_recurr_char(arr2))
arr3 = [2,3,4,5]
print(first_recurr_char(arr3)) | true |
8cd1b52c289b02c0026f488c78b04e4f0b247b2b | ianmuyumba/python-techcamp | /week_2/flow_control/intro.py | 1,328 | 4.15625 | 4 | """
- A program’s control flow is the order in which the program’s code executes.
- The control flow of a Python program is regulated by conditional statements and loops.
"""
"""
DECISION CONTROL STRUCTURES
* if...elif...else
"""
# print("Hello World")
# x: int = 20
# y: int = 10
# if x>y:
# print(f"{x} is greater than {y}")
# z = int(input("Enter number: "))
#
# if z > 0:
# print(f"{z} is a positive number")
# else:
# print(f"{z} is NOT a positive number")
#
Check if a number is even or odd
num = int(input("Enter Number: "))
# if num%2 == 0:
# print(f"{num} is an even number")
# else:
# print(f"{num} is not an even number")
# #shorthand option
print("Even Number") if num%2 == 0 else print("Odd Number")
num2 = int(input("Enter Number: "))
if num2>0:
print(f"{num2} is a positive number")
elif num2==0:
print(f"{num2} is Zero")
else:
print(f"{num2} is a negative number")
# Nested If statements - check if the number is positive or negative or zero
# Indentation is the key in nested statements
num = float(input("Enter a number: "))
if num >= 0: # If the expression is false, the nested statement wont be executed
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
# Python
| true |
1d6a63896dd4f889f378ff38511cd8103aff6474 | ianmuyumba/python-techcamp | /basics/env/task.py | 360 | 4.25 | 4 | """
Write a program that takes your full name as input and displays the abbreviations
of the first and middle names except the last name which is displayed as it is.
For example, if your name is Robert Brett Roser, then the output should be R.B.Roser.
"""
firstName = "Robert"
middleName = "Brett"
lastName = "Roser"
print(f"{firstName[0]}.{middleName[0]} {lastName}")
| true |
5ae3900c2c487dd988308d39102eb0b4ddab57f8 | qhweng/using-basic-algorithms | /square_root.py | 1,087 | 4.4375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
# Base cases
if number == 1 or number == 0 or number is None:
return number
# Negative number cases
if number < 0:
return -1
# Follow binary search algorithm to calculate sqrt
start = 0
end = number
mid = -1
while start <= end or start == mid:
mid = (start + end) // 2
if mid**2 == number:
return mid
if mid**2 > number:
end = mid - 1
else:
start = mid + 1
return mid
# Test case: regular values
assert 3 == sqrt(9)
assert 4 == sqrt(16)
assert 0 == sqrt(0)
assert 1 == sqrt(1)
# Test case: values with remainders
assert 5 == sqrt(27)
assert 5 == sqrt(33)
assert 1 == sqrt(2)
assert 1 == sqrt(3)
# Test case: negative value
assert -1 == sqrt(-10)
assert -1 == sqrt(-15)
# Test case: none value
assert None == sqrt(None)
# print("Finished testing")
| true |
54b21903a60ba0c3fe70ed21050f35ccc919fded | HaoNiein/python-learning | /untitle3-problem2.py | 683 | 4.1875 | 4 | 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.
'''
s="" #defining s as a empty string for adding the letter or blank
for i in secretWord: #defining i as the letters in secreword
if i in lettersGuessed : #adding i in s if i is in the letterGuessed
s+=i
else:
s+="_" #if not, adding a blank
return s
| true |
ef39700d61e4ed54137308ffcb6f4907416c024e | FULLMETALALCHMIST/IEECS | /design_lab1/Extracting.py | 233 | 4.15625 | 4 |
number = float(input('Please input a number'))
guess = float(input('Please input a guess number'))
while guess * guess - number > 0.0001 or number - guess * guess > 0.0001:
guess = (guess + number / guess) / 2
print(guess)
| false |
4965ae8278bfe0214f2f227bbea8a5f188c29b4d | jonathanchaney96/Hello-You-Project. | /Hello You!.py | 494 | 4.4375 | 4 | #Ask user for name
name = input("what is your name?: ")
print(name)
#Ask user for age
age = input("What is your age?: ")
print(age)
#Ask user for city
city = input("City living in?: ")
print(city)
#Ask user what they enjoy
love= input ("what do you love doing?: ")
print(love)
#Create output text
string = "your name is {} and you are {}. you live in {} and you love {}"
output = string.format(name, age, city, love)
#print output to screen
print(output)
| false |
32a914868267d9ba07e26b951931f01f230e24af | cquan808/simple-python-app | /main.py | 1,160 | 4.59375 | 5 | # This is a simple application to convert your weight from lbs to kg or
# from kg to lbs
import unitConverter
class PrintResults():
def print_results(name, weight, unit_result):
# only for python version 3+
# print(f"Hello {name}, your weight is {weight} in {unit_result}.")
print("Hello " + name + ", your weight is " + weight + " in " + unit_result + ".")
'''
name = input("What is your name: ")
try:
weight = int(input("What is your weight: "))
except ValueError:
print("Invalid value")
unit = (input("(K)g or (l)bs: ")).upper()
'''
name = "Chris"
weight = int(143)
unit = "l"
unit_result = ""
if unit.upper() == "K":
unit_result = "lbs"
weight = unitConverter.kg_to_lbs(weight)
# print(f"Hello {name}, your weight is {weight} in {unit_result}")
PrintResults.print_results(name, weight, unit_result)
elif unit.upper() == "L":
unit_result = "kg"
weight = unitConverter.lbs_to_kg(weight)
# print(f"Hello {name}, your weight is {weight} in {unit_result}")
PrintResults.print_results(name, weight, unit_result)
else:
print("Unit must be 'k' for kg or 'l' for lbs, please try again") | true |
af51e1c59333688213c7076385612cb610941855 | axuereb/LearnPythonWithBQNT | /solutions/sum_iterables.py | 503 | 4.375 | 4 | def sum_numbers(iterable, start=0):
"""
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
"""
result = start
for number in iterable:
result += number
return result
print(sum_numbers(range(0,10), start=100)) # 145
print(sum_numbers([10,20,30])) # 60 | true |
17b602145c6998dad05b0f6f7707feeab134547c | mkoundo/google_python_class | /basic/wordcount_try2.py | 2,358 | 4.375 | 4 | import sys
def print_words(filename):
'''function that counts how often each word appears in the text and prints: word1 count1 etc.'''
word_dict = word_list(filename)
for word in sorted(word_dict.keys()):
print word, word_dict[word]
#=======================
def print_top(filename):
'''function that list top 20 occuring words in textfile'''
word_dict = word_list(filename)
items = sorted(word_dict.items(), key=count_tuple, reverse=True) #copy dict word/count pairs into a list of tuples
#sort by second entry (i.e. word count) in tuple using a function
#reverse sort order so the highest word count is listed first
#print top 20 word/count pairs:
for item in items[:20]:
print item[0], item[1]
#<---------------------------------UTILITIES--------------------------------------------------------->
def word_list(filename):
# utility to read in filename and split the words into a list
textfile = open(filename, 'r')
word_dict = {}
for line in textfile:
all_words = line.split() #read each line of filename and split out the words into a list
for word in all_words:
word = word.lower() #ensure all words are lowercase
if not word in word_dict: #insert each word into a dict and count the number of occurence in the dict
word_dict[word] = 1
else:
word_dict[word] = word_dict[word] + 1
textfile.close() #close text file
return word_dict
def count_tuple(tuple_item):
'''with a list [(word1, count1), (word2, count2), ...], this function extracts the count from each tuple'''
return tuple_item[1]
#----------------------------------------------------------------------------------------------------
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
| true |
06bdcea967048faeada4f1c328149e80b3b81cef | ITT-21SS-UR/assignment_introduction_linux_python-RealWhimsy | /circle.py | 1,660 | 4.46875 | 4 | """My implementation of circle.py. Draws a circle with a given radius. Awesome stuff."""
import sys
import math
import turtle
from turtle import *
arguments = len(sys.argv) - 1
def main():
"""
Starting point of this script. Takes a number (radius) as command line argument
"""
if arguments < 1:
print("Please pass a number as argument")
return
if arguments > 1:
print("Too many arguments! Exiting.")
return
try:
radius = float(sys.argv[1])
except ValueError:
print("Please enter a valid number!")
return
draw_center(radius)
setup_colors()
move_to_start(radius)
draw_circle(radius)
done()
def draw_center(radius):
"""
Draws a dot at the center
:param radius: the radius of the circle
"""
original_size = turtle.pensize()
turtle.pensize(radius / 10)
turtle.forward(1)
turtle.back(1)
turtle.pensize(original_size)
def setup_colors():
"""
sets the background + turtle colors
"""
bgcolor("darkgray")
color('black', 'orange')
def move_to_start(radius):
"""
moves to the start drawing location
:param radius: the radius of the circle
"""
penup()
forward(radius)
left(90)
pendown()
begin_fill()
def draw_circle(radius):
"""
draws the circle by alternating moving forward and turning left
:param radius: the radius of the circle
"""
moves = 0
while True:
forward(2 * math.pi * radius / 360)
left(1)
moves += 1
if moves >= 360:
break
end_fill()
if __name__ == "__main__":
main()
| true |
e52c710fb5f39997a2fa0486c27e5c00a08364e7 | Pankaj-GoSu/Python-Exercises | /Problem 6/Solution_try.py | 1,836 | 4.21875 | 4 |
import random
import getpass # With this module we give input as a password which is not visible to other person.
a = int(input("Enter first number \n"))
b = int(input("Enter second number \n"))
lst =[]
for i in range(a,b+1): # making a list , which contain integer value from a to b
lst.append(i)
print(lst)
r = random.choice(lst) # Choosing random value from this list "lst"
# print(r) # For testing our generated value
print(f"Your range of Guessing is between {a} and {b}\n")
print("Player 1 Turn\n")
i = 1 # initializing player 1 attempt.
while(True):
player1_inp = int(getpass.getpass("Enter Number Don't worry Your number is not visible to your friend "))
# player1_inp = int(input(" Enter Number "))
if (player1_inp == r):
print(f"Your Guess is right and you took {i} attempt")
break
elif(player1_inp > r):
print("Your Guess is greater then that number please guess smaller one")
i += 1
elif(player1_inp < r):
print("Your Guess is lesser then that number please guess greater number")
i += 1
print(f"Your range of Guessing is between {a} and {b}\n")
print("Player 2 Turn\n")
j = 1 # initializing player 2 attempt.
while(True):
player2_inp = int(getpass.getpass("Enter Number Don't worry Your number is not visible to your friend "))
if (player2_inp == r):
print(f"Your Guess is right and you took {j} attempt")
break
elif(player2_inp > r):
print("Your Guess is greater then that number please guess smaller one")
j += 1
elif(player2_inp < r):
print("Your Guess is lesser then that number please guess greater number")
j += 1
if (i>j):
print(f"Player 2 win the game by {i - j} points")
elif (j>i):
print(f"Player 1 win the game by {j - i} points")
else:
print("Match is Draw")
| true |
9e106bb230b738394f71ef77e76b2b5a81953c3f | YoungCheolChoi/Python-for-Everybody-Class | /Chapter_03_Exercise_02.py | 603 | 4.21875 | 4 | # Exercise 2
#
# Rewrite your pay program using try and except
# so that your program handles non-numeric input gracefully
# by printing a message and exiting the program.
# The following shows two execitions of the program :
try :
hrs = input('Enter Hours : ')
hrs = float(hrs)
except :
print('Error, please enter numeric input')
quit()
try :
rate = input('Enter Rate : ')
rate = float(rate)
if hrs > 40 :
pay = ((hrs - 40) * rate * 1.5) + (40 * rate)
print(pay)
else :
pay = hrs * rate
print(pay)
except :
print('Error, please enter numeric input')
| true |
37746e8d47150d74c150d079eeaf2e9630820721 | techsuni2023/code-bert | /test_files/test_code_add.py | 250 | 4.125 | 4 | def add(a, b):
"""
sums two numbers and returns the result
"""
return a + b
def return_all_even(lst):
"""
numbers that are not really odd
"""
if not lst:
return None
return [a for a in lst if a % 2 == 0]
| true |
f49d956543dbd427a8380732b26bc8afcc3e219c | ptyork/au-aist2120-20fa | /BTh/funcs_903.py | 2,583 | 4.5 | 4 | # COMMENT
" HELLO WORLD "
'''
MULTI
LINE
STRING
BECOMES
A
MULTI
LINE
COMMENT
'''
'''
name: get_name
params: none
returns: the user-entered name in title case
'''
def get_name():
while True:
name = input("Enter you name: ")
name = name.strip()
if len(name) == 0:
print("PLEASE GIVE ME A REAL NAME")
continue
# break
name = name.title()
return name
'''
name: get_int
params: prompt (string)
returns: an integer that the user entered
'''
def get_int(prompt):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("PLEASE GIVE SOMETHING")
continue
# if numstr.isnumeric() == False:
if not numstr.isnumeric():
print("THAT'S NOT A NUMBER")
continue
# if finally we get here, then we know numstr is valid
num = int(numstr)
return num
'''
name: get_int_in_range
params: prompt (string)
minval (int)
maxval (int)
returns: an integer that the user entered between the values
'''
def get_int_in_range(prompt, minval, maxval):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("PLEASE GIVE SOMETHING")
continue
# if numstr.isnumeric() == False:
if not numstr.isnumeric():
print("THAT'S NOT A NUMBER")
continue
# if finally we get here, then we know numstr is valid
num = int(numstr)
if num < minval or num > maxval:
print("OUT OF RANGE")
continue
# if finally we get here, then we know num is valid
return num
'''
name: get_int_in_rangeA
params: prompt (string)
minval (int)
maxval (int)
returns: an integer that the user entered between the values
'''
def get_int_in_rangeA(prompt, minval, maxval):
while True:
num = get_int(prompt)
if num < minval or num > maxval:
print("OUT OF RANGE")
continue
# if finally we get here, then we know num is valid
return num
###################################
username = get_name()
print(f"You entered {username}")
age = get_int_in_range("Enter your age: ", 1, 120)
print(f"You say you are {age} but you don't look a day over {age-1}")
weight = get_int("Enter your weight: ")
print(f"You say you weigh {weight} pounds...that's awesome (fatty)")
| true |
b2d31b2ae1a631c1287912a2ee1ecccb326c1762 | ptyork/au-aist2120-20fa | /BTu/funcs_901.py | 2,306 | 4.125 | 4 | # Comments
" COMMENT "
'''
MULTI
LINE
STRING
IS GREAT FOR LONG COMMENTS
'''
'''
name: get_name
params: none
returns: a user-entered name
'''
def get_name():
while True:
namestr = input("Enter your name: ")
namestr = namestr.strip()
if len(namestr) == 0:
print("PLEASE ENTER A REAL NAME")
continue
# else:
# break
namestr = namestr.title()
return namestr
'''
name: get_int
params: prompt (string)
return: a user-supplied positive integer
'''
def get_int(prompt):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("YOU MUST ENTER A VALUE")
continue
# if numstr.isnumeric() == False:
if not numstr.isnumeric():
print("THAT DON'T LOOK LIKE NO NUMBER TO ME")
continue
num = int(numstr)
return num
'''
name: get_int_in_range
params: prompt (string)
minval (int)
maxval (int)
return: a user-supplied positive integer
'''
def get_int_in_range(prompt, minval, maxval):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("YOU MUST ENTER A VALUE")
continue
if not numstr.isnumeric():
print("THAT DON'T LOOK LIKE NO NUMBER TO ME")
continue
num = int(numstr)
if num < minval or num > maxval:
print("OUT OF RANGE")
continue
return num
'''
name: get_int_in_rangeA
params: prompt (string)
minval (int)
maxval (int)
return: a user-supplied positive integer
'''
def get_int_in_rangeA(prompt, minval, maxval):
while True:
num = get_int(prompt)
if num < minval or num > maxval:
print("OUT OF RANGE")
continue
return num
############################################
name = get_name()
print(f"Oh, hi {name}")
age = get_int("Please enter your age: ")
print(f"You said you are {age} but ha ha you are really {age+25} you old fart.")
weight = get_int_in_range("Please enter your weight: ", 50, 500)
print(f"You said you are {weight} pounds, you fatty!!")
| true |
74e9f865b9c52d7ca2a1af04afe8c9a13b5cf493 | ptyork/au-aist2120-20fa | /common/timestuff_1113.py | 1,245 | 4.4375 | 4 | from datetime import date
import time
import datetime
print(time.ctime()) # prints current date/time in a pretty format
curr = time.time() # gets a current timestamp as a float of seconds and milliseconds
for i in range(100000):
pass
now = time.time() # do it again
elapsed = now - curr # how much time in between
elapsed_ms = elapsed * 1000
print(f"{elapsed_ms:.2f} milliseconds have elapsed")
# for t in range(10,1,-1):
# print(t)
# time.sleep(1)
# Normally you'd have a loop that looks at an external resource
# at regular intervals and waits for something to happen.
# while True:
# if something:
# do something
# break
# else:
# time.sleep(some period)
# CURRENT datetime
now = datetime.datetime.now()
# FUTHER OR PAST date time
ny2019 = datetime.datetime(2019,12,31)
ny2020 = datetime.datetime(2020,12,31)
# DELTA or DIFFERENCE BETWEEN DATES
betweenyears = ny2020 - ny2019 # this is a timedelta
print(betweenyears)
tilnewyears = ny2020 - now
print(tilnewyears)
# Can also be used as an advanced elapsed timer
now = datetime.datetime.now()
time.sleep(2.333)
later = datetime.datetime.now()
elapsed = later - now
print(f'{elapsed.seconds}s:{elapsed.microseconds}ms')
| true |
d2e9d713d4be8a1f85ea7a6af617e6c00b2bbbcd | ptyork/au-aist2120-20fa | /ATh/funcs_903.py | 2,700 | 4.3125 | 4 |
# SINGLE LINE COMMENTS
" HELLO WORLD "
'''
MULTI
LINE
COMMENT
REALLY
A
MULTI
LINE
STRING
'''
'''
name: get_name
parameters: none
returns: a user specified name as a string
'''
def get_name():
while True:
name = input('Enter your name: ')
name = name.strip()
# Check for something
if len(name) == 0:
print("PLEASE GIVE ME A REAL NAME")
continue # try again if bad
name = name.title()
# exit the loop
return name
'''
name: get_int
params: prompt
returns: a user supplied number as an int
'''
def get_int(prompt):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("PLEASE GIVE ME SOMETHING")
continue
# if numstr.isnumeric() == False:
if not numstr.isnumeric():
print("PLEASE GIVE A REAL NUMBER")
continue
# once we get here, we're golden...convert and return
num = int(numstr)
return num
'''
name: get_int_in_range
params: prompt (string)
minval (int)
maxval (int)
returns: a user supplied number as an int
'''
def get_int_in_range(prompt, minval, maxval):
while True:
numstr = input(prompt)
numstr = numstr.strip()
if len(numstr) == 0:
print("PLEASE GIVE ME SOMETHING")
continue
# if numstr.isnumeric() == False:
if not numstr.isnumeric():
print("PLEASE GIVE A REAL NUMBER")
continue
# once we get here, we're golden...convert
# (but hold off on returning)
num = int(numstr)
if num < minval or num > maxval:
print("THAT'S OUT OF RANGE")
continue
# WHEW! the number is valid so return it
return num
'''
name: get_int_in_range
params: prompt (string)
minval (int)
maxval (int)
returns: a user supplied number as an int
'''
def get_int_in_rangeA(prompt, minval, maxval):
while True:
num = get_int(prompt)
if num < minval or num > maxval:
print("THAT'S OUT OF RANGE")
continue
# WHEW! the number is valid so return it
return num
################################
username = get_name()
print(f"Oh hi, {username}")
# exit() # explicitly exit a SCRIPT
age = get_int_in_range("Enter your age: ", 1, 120)
print(f"Haha, you THINK you are {age} but really you are {age+20}")
weight = get_int("Enter your weight: ")
print(f"You look mahvelous for someone who weights {weight} pounds")
| true |
be6e9f8210fdb4d874421c876a5f793008fdf0d3 | ptyork/au-aist2120-20fa | /BTu/818a.py | 532 | 4.125 | 4 | print('hello world')
print("paul wuz here")
name = "paul"
print(name + " wuz here")
age = 39
print("you are " + str(age) + " years old")
#lessgood
# print("enter your first name:")
# fname = input()
#better (opinion)
#FACT: this works in Mimir
fname = input("enter your first name: ")
print("hi", fname)
# yob = input('when you born? ')
# iyob = int(yob)
# age = 2020 - iyob
# yob = int(yob) # DON'T REUSE VARIABLES!!!
# age = 2020 - yob
yob = int(input('when you born? '))
age = 2020 - yob
print('you are', age, 'year old')
| false |
e2310e10ca0de5848ef1b978400c096758a24fda | FernandoJPaz/PythonBasicoC | /clase6.py | 1,435 | 4.1875 | 4 | #sintaxis
# class IdentificadorClase :
# Atributos
# Metodos / Funciones
#Crear una clase
class MyClass:
#Atributos de myclase
edad = 18
#Operaciones(Metodos/Funciones) de myclase
def ImprimirEdad(edad):
print(edad)
#Crear objeto
#MyClass c = new MyClass() --- JAVA
# Todos los atributos y metodos los va tener (C)
#nombreVariable
clase1 = MyClass()
print("La edad de myclass es: ", clase1.edad)
miObjeto = MyClass()
miObjeto.edad = 1000
print("Mi edad es", miObjeto.edad)
# JAVA
# public void myMetodo(string name , int age){
#
# }
#La función __init __ ()
class Person:
def __init__(self, name, age):
self.name = name #Equivalente a this en java
self.age = age
p1 = Person("John", 36)
p2 = Person("Fernando jose Paz", 24)
print(p1.name)
print(p1.age)
print("----")
print(p2.name)
print(p2.age)
#Métodos de objetos
class Person:
#1 prioridad
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Fernando", 24)
p1.myfunc()
#El auto parámetro
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(cualquierparametro):
print("Hello my name is " + cualquierparametro.name)
p1 = Person("Curso de Python", 36)
p1.myfunc()
#Modificar las propiedades del objeto
p1.age = 40
#Eliminar propiedades de objeto
del p1.age
del p1 | false |
43c0ec5c6d68b85f1189667c7eab4abfde1565d0 | vaibhav0012/artificial_intelligence_and_machine_learning | /machine_learning_algorithms_using_frameworks/python_files/regression/salary_regression/Simple-Linear-Regression/simple_linear_regression 4.07.30 PM.py | 1,620 | 4.375 | 4 |
# python implementation of simple Linear Regression on salary data of software engineers
# import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
dataset = pd.read_csv('collected_salary_data.csv')
inputx = dataset.iloc[:, :-1].values
outputy = dataset.iloc[:, 1].values
input_train, input_test, output_train, output_test = train_test_split(inputx, outputy, test_size = 1/3, random_state = 0)
print(input_test)
# using simple Linear Regression model to train
model = LinearRegression()
model.fit(input_train, output_train)
# model predicting the Test set results
predicted_output = model.predict(input_test)
print(predicted_output)
years = float(input("Give number of years of experience "))
testinput = [[years]]
predicted_output = model.predict(testinput)
print('The number of years of experience is ',testinput)
print('The salary is ',predicted_output)
yes = input("Can I proceed")
# Visualising the training results
plt.scatter(input_train, output_train, color = 'red')
plt.plot(input_train, model.predict(input_train), color = 'yellow')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
# Visualising the testing results
plt.scatter(input_test, output_test, color = 'red')
plt.plot(input_train, model.predict(input_train), color = 'yellow')
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
| true |
8929d8fe9e6f46c04c6f31c83d8d966b552278ef | MitraNami/data-science-python | /chapter-4/linearAlgebra_vectors.py | 2,336 | 4.21875 | 4 | # vectors
from typing import List
Vector = List[float] # a type alias, saying a Vecor is a list of floats
def add(v: Vector, w: Vector) -> Vector:
""" Adds corresponding elements"""
assert len(v) == len(w), "Vectors must be the same length"
return [v_el + w_el for (v_el, w_el) in zip(v, w)]
# try:
# add([1, 2, 3], [4, 5])
# except AssertionError as inst:
# print(inst) # inst is an obj with method __str__ that return "Vectors ..."
# # inst.__str__() is called when printing inst
def subtract(v: Vector, w: Vector) -> Vector:
""" Subtracts corresponding elements """
assert len(v) == len(w), "Vectors must have the same length"
return [v_i - w_i for (v_i, w_i) in zip(v, w)]
assert subtract([5, 7, 9], [4, 5, 6]) == [1, 2, 3]
def vector_sum(vectors: List[Vector]) -> Vector:
""" Sums all corresponding elements """
# Check that vectors is not empty
assert vectors, "no vectors provided!"
# Check the vectors are all the same size
num_elements = len(vectors[0])
assert all(len(vector) == num_elements for vector in vectors), "Vectors must be the same length"
return [sum(element) for element in zip(*vectors)]
assert vector_sum([[1, 2], [3, 4], [5, 6], [7, 8]]) == [16, 20]
def scalar_multiply(c: float, v: Vector) -> Vector:
""" Multiplies every element by c """
return [c * v_i for v_i in v]
assert scalar_multiply(2, [1, 2, 3]) == [2, 4, 6]
def vector_mean(vectors: List[Vector]) -> Vector:
""" Computes the element-wise average """
sum_vector = vector_sum(vectors)
n = len(vectors)
return scalar_multiply(1/n, sum_vector)
assert vector_mean([[1, 2], [3, 4], [5, 6]]) == [3, 4]
def dot(v: Vector, w: Vector) -> float:
""" Computes v_1 * w_1 + ... + v_n * w_n """
assert len(v) == len(w), "Vectors must have same length"
return sum(v_i * w_i for (v_i, w_i) in zip(v, w))
assert dot([1, 2, 3], [4, 5, 6]) == 32
def sum_of_squares(v: Vector) -> float:
""" Computes v_1 * v_1 + ... + v_n * v_n """
return dot(v, v)
assert sum_of_squares([1, 2, 3]) == 14
import math
def magnitude(v: Vector) -> float:
""" Computes the magnitude/length of v """
return math.sqrt(sum_of_squares(v))
assert magnitude([3, 4]) == 5
def squared_distance(v: Vector, w: Vector) -> float:
distance_vector = subtract(v, w)
return magnitude(distance_vector) | true |
ab2bbd2d67905354da4f6e0f3fe82e2c7347b827 | hoops92/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 1,299 | 4.125 | 4 | def intersection(arrays):
"""
Find intersection between different lists of integers
"""
# Create a cache to save "seen" integers
cache = {}
# Your code here
# Get the total # of lists to look through
num_list = len(arrays)
# Create a lsit to save the intersection values
result = []
# Create a for loop to go through each list
for lst in arrays:
# Loop through each item in list
for item in lst:
# Add the items in cache as keys if not there
# Count in how many lists have items present as values
if item not in cache:
cache[item] = 1
else:
# Ff the element in already in the cache
# Increment its value by 1
cache[item] += 1
# Did the item count reach the total number of lists?
# If yes, add the number in the result list
if cache[item] == num_list:
result.append(item)
return result
if __name__ == "__main__":
arrays = []
arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])
arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])
arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])
print(intersection(arrays))
| true |
0f117f22c1ef72576d96ec47c881094694abcd99 | chinmoysihi/PersonalWorkspace | /DataStructure/Sorting/venv/Programs/bubble.py | 639 | 4.21875 | 4 | # Bubble Sort of a user given list of element
from builtins import range
def bubble_Sort(arr):
for i in range(len(arr), 0, -1):
for j in range(len(arr) - 1):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
print(arr)
return arr
if __name__ == '__main__':
numOfElem = int(input("Please enter no of values & Enter the numbers in new Line: "))
numArr = []
for i in range(0, numOfElem):
newNum = input().split('\n')
numArr.append(int(newNum[0]))
numArr = bubble_Sort(numArr)
print(numArr)
| true |
5f61d469950ae94ae6e5edae7b3e5399e9ccac0c | shatheesh171/recursion | /power_of_number.py | 218 | 4.125 | 4 | def power(base,exp):
assert exp>=0 and int(exp)==exp,'Exponent must be positive integer here'
if exp==0:
return 1
if exp==1:
return base
return base*power(base,exp-1)
print(power(2,3)) | true |
958d49621eb05a15d786c98bc02ad4e217ee32db | Leticiamkabu/globalCode-18 | /advPython/Map,Filter & Lambda/filter.py | 394 | 4.25 | 4 | # returns value if it is an Even
def is_even(x):
if x % 2 == 0:
return x
originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#using the filter func, each value in originalList is tested
# even if true add to the newList
newlist = list(filter(is_even,originalList))
#print the two lists
print("The original list: {}".format(originalList))
print("The filtered list: {}".format(newlist)) | true |
8eb4a0ccbfea836322d8218d7d15f5226106d425 | Leticiamkabu/globalCode-18 | /advPython/lambda.py | 664 | 4.1875 | 4 | #def is_even(): num = input('>Enter a number: ')
# if num % 2 == 0:
# return 'True'
#print(is_even())
#items = [1,2,3,4]
#squares = list(map((lambda x: x ** 2), items)) #bring list for python3
#print(squares)
numbers = [1,56,234,87,4,76,42,69,90,135]
#using function
#def is_even2():
# for number in numbers:
# if number%2 == 0:
# print(number)
#is_even2()
#using lambda
showList = list(map((lambda arg: arg), numbers)) #map ... used to print all elements
print(showList)
is_even = list(filter((lambda arg: arg%2 == 0), numbers)) #filer...to get a subset of elements
print(is_even)
is_odd = list(filter(lambda x: arg%2 != 0, number))
| true |
f42718d4043d52ce46ee2f6c296c7a9beffe63c5 | addilahz/Code-Sitters-Exercise | /loops_practice/loops_practice_Q1.py | 678 | 4.15625 | 4 | # Stage 1 Questions
#
# No.1
# for numbers in range(0,13):
# print numbers
#
# No.2
#for numbers in range(1,13):
# print numbers
# No.3
#for numbers in range (1,13):
# numbers=numbers*-1+13
# print numbers
# No.4
#for numbers in range (1,13):
# numbers=numbers*2
# print numbers
#
# No.1 w
#
# num = 1
# while num < 13:
# print num
# num = num + 1
#
# No. 2 W
# num = 1
# while num < 13:
# print num
# num = num + 1
# No. 3 W
# num = 1
# while num < 13:
# print num *-1+13
# num=num +1
# No. 4 W
#num = 1
# while num <13:
# print num * 2
# num = num + 1
#
# EXAMPLE
# n = 5
# while n > 0:
# print n
# n = n -1
# print "YAY!"
#
| false |
7ec24209d6c2f50f35e4b98b7de2767b9a4c9d3f | maberf/python | /src/Aula07a.py | 393 | 4.28125 | 4 | nome = input ('Qual o seu nome? ')
print('Olá,{:>15}!'.format(nome)) #espaçamento 15 caracteres alinhado à direita
print('Olá,{:<15}!'.format(nome)) #alinhado à esquerda
print('Olá,{:^15}!'.format(nome)) #centralizado
print('Olá,{:=^15}!'.format(nome), end=' ') #preenchido com = e emenda com print seguinte
print(f'Olá,{nome:=^15}!') #centralizado preenchido com instrução diferente | false |
d8906f48a13cfacac9b4cc88794f6ebbcf56b6f4 | maberf/python | /src/Aula19Dicionarios.py | 1,273 | 4.15625 | 4 | '''filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'}
print(filme['titulo']) #acesso a elemento via chave
print(filme["titulo"]) #acesso via chave com declaração de referência entre aspas
print('-'*30)
for k, v in filme.items():
print(f'O {k} é {v}.') #uso de laço no dicionário {k-chave} e {v-valor}
print('-'*30)
#No print formatado, declaração de referência TEM QUE SER COM ASPAS!
print(f'O filme {filme["titulo"]} foi feito em {filme["ano"]}.')
print('-'*30)
del filme['diretor'] #apaga diretor do vetor.
filme['ano'] = '1978' #alteração do ano
filme['genero'] = 'ação'#adição de elemento, NÃO USA APPEND
for k, v in filme.items():
print(f'O {k} é {v}.')
print('-'*30)'''
#
#print(filme.values())
#print(filme.keys())
#print(filme.items())
#
#Dicionário dentro de lista
'''Brasil = [] #lista
estado1 = {'UF':'São Paulo', 'Sigla':'SP'} #dicionário
estado2 = {'UF':'Rio Grande do Sul', 'Sigla':'RS'} #dicionário
Brasil.append(estado1)
Brasil.append(estado2)
print(Brasil)
print(Brasil[1]['UF'])'''
#
#uso do copy()
estado = dict()
Brasil = list()
for i in range(0, 2):
estado['UF'] = str(input('Nome do Estado: ')).strip()
estado['Sigla'] = str(input('Sigla: ')).strip()
Brasil.append(estado.copy())
print(Brasil)
| false |
5b8ad37b62d81c824afdc3f66ebe5799ea129d16 | maberf/python | /src/Aula10ex35.py | 293 | 4.125 | 4 | #condição de existência de um triângulo
a = int(input('Reta a: '))
b = int(input('Reta b: '))
c = int(input('Reta c: '))
if abs(b - c) < a < (b + c) and abs(a - c) < b < (c + c) and abs(a - b) < c < (a + b):
print('Triângulo Viável!')
else:
print('Triângulo Inviável!') | false |
b3663f57ce0d15227abee1dac24067e8f6f08ab8 | GirlsFirst/SIP-Facilitator | /Unit2-Python/U2L2/proj_rps_solutions.py | 2,782 | 4.3125 | 4 | '''
proj_rps_solutions.py
Description: Project solution file for rock paper scissors for U2L2.
Project objective will explore variables, conditionals, and while loops.
Author: GWC Curriculum Team
Date Created: May 2020
'''
import random
#Part 1: Introduction and Start of the Game
#TODO: Write the opening introduction of your game
print("Welcome to the automated Rock, Paper, Scissors Game!")
print("The typical rules of the game is as follows:")
print("There will be 3 rounds in total")
print("You will choose either rock, paper, or scissors (remember that spelling counts!)")
print("Rock beats Scissors")
print("Paper beats Rock")
print("Scissors beats Paper")
print("You will be battling the computer in this game")
print("In the event of a tie, no one wins the round")
#TODO: Add variables to use throughout the program in this section
choices = ["rock", "paper", "scissors"]
round = 0
player_win = 0
comp_win = 0
#Part 2: Running Each Round
#TODO: Update while loop to loop through as many rounds as you want for your game!
while (round < 3):
#TODO: Ask for player's choice
player = input("Pick rock, paper, or scissors: ")
#Randomly chooses the computer's choice from the choices list.
#The computer's choice will either be "rock", "paper", or "scissors"
comp = random.choice(choices)
print ("The computer chose " + comp)
#TODO: Add rules of game
if (player == "rock"):
if (comp == "rock"):
print("It's a tie")
elif (comp == "paper"):
print("You lose!")
comp_win+=1
else:
print("You win!")
player_win+=1
elif (player == "scissors"):
if (comp == "scissors"):
print("It's a tie")
elif (comp == "rock"):
print("You lose!")
comp_win+=1
else:
print("You win!")
player_win+=1
elif (player == "paper"):
if (comp == "paper"):
print("It's a tie")
elif (comp == "scissors"):
print("You lose!")
comp_win+=1
else:
print("You win!")
player_win+=1
else:
print("I'm sorry, that is not a valid choice. Remember spelling counts!")
#TODO: Increment the round variable
round+=1
#Part 3: Finishing Results and End of the Game
#TODO: Determine the overall winner
if (comp_win > player_win):
print("Sorry, you lost this time. The computer is the overall winner")
elif (comp_win < player_win):
print("You are the overall winner! Congratulations")
else:
print("Both you and the computer tied!")
#TODO: Add a statement here to let your player know the game has ended!
print("The game has ended. Thank you for playing.")
print("Rerun the program to play again!") | true |
919b75a007e588aa24b1673ddc40bc707880565e | muzikmyth/python-scripts-bible | /scripts/dectohex.py | 215 | 4.125 | 4 | # Filename : dectohex.py
# Creator : Abhijit Kumar
# Created : 5 November, 2018
# Description : Converts decimal number to hexadecimal number.
dec_num = input('Enter the decimal number\n')
print(hex(int(dec_num)))
| true |
285c42f45c5ae677184a1682ec20ec5b1c0d630f | thesumitshrestha/Python-Exercise | /Basic/reverse.py | 350 | 4.4375 | 4 | # Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.
firstName = raw_input("Enter your first name: ")
lastName = raw_input("Enter your last name: ")
print ("Your full name is " + firstName + " " + lastName)
print ("Your reverse full name is " + lastName + " " + firstName)
| true |
6a8938d18c669bff97553f0410c39d58a667f927 | thesumitshrestha/Python-Exercise | /Basic/histogram.py | 287 | 4.1875 | 4 | # Write a Python program to create a histogram from a given list of integers
def histogram(list):
for n in list:
output = ''
times = n
while (times > 0):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 4, 5])
| true |
6a4e83a92fb7641753ef3a0eca54e3aeb0a9ffed | sandrofunk/Python | /Criando Variáveis.py | 487 | 4.1875 | 4 | # Criando Variáveis
# As variáveis armazenam valores inteiros, string,
# float, entre outros, e lembrando que saõ Case Sensitive,
# ou seja, não podemos criar uma variável com uma letra
# maiuscula, e na impressão escrever a variável com letra
# minuscula. Por exemplo: variavel e Variavel
var1 = "Teste" #string
var2 = 3 #inteiro
var3 = 4.2 #float
var4 = True #booleana
var5 = False #booleana
print(var1)
print(var2)
print(var3)
print(var4)
print(var5) | false |
2f94303f64f077fb4aae3637550c35ed5ff485d3 | ammoran/SES350_Work | /SES350_Work/Homework 3/Homework 3.py | 599 | 4.25 | 4 | # Third Problem
# Write a program to calculate the area of a triangle given the length of its three sides a, b, and c using these
# formulas:
#
# s = (a+b+c)/2
# A = sqrt(s(s-a) (s-b) (s-c))
import math
print "What are the lenghths of the 3 sides of the triangle?"
n = 1
sides = []
while n < 4:
i = input("Side" + " " + str(n) + ": ")
print "Side %d is: %d" % (n, i)
sides.append(i)
n += 1
a, b, c = sides[0], sides[1], sides[2]
s = (a + b + c) / 2
A = math.sqrt(s * (s - a) * (s - b) * (s-c))
print "The area of the trinagle is %s units" % format(A, '.2f')
| true |
72c3e98c22e341a670c690513ac84618e187efec | zolcsika71/JBA_Python | /Duplicate File Handler/Topics/Basic string methods/Latin equivalents/main.py | 404 | 4.1875 | 4 | name = input()
def normalize(name_):
replace_char = {
'é': 'e',
'ë': 'e',
'á': 'a',
'å': 'a',
'œ': 'oe',
'æ': 'ae'
}
new_name = ''
for char in name_:
for key in replace_char.keys():
if key == char:
new_name = name_.replace(char, replace_char[key])
return new_name
print(normalize(name))
| false |
20b471ea6b7ab01ad1be49fae3590fc5b3d8d9c2 | kelseyziomek/exercises | /intro_class_kelseyz/conditionals.py | 1,191 | 4.375 | 4 | #my_name = raw_input("What is your name?")
#partners_name = raw_input("What is your partner's name?")
#if(my_name>partners_name):
# print "My name is greater!"
#elif (my_name == partners_name):
# print "Our names are equal!"
#else:
# print "Their name is greater!"
#todays_date = int(raw_input("What is today's date?"))
#if (todays_date>15):
# print "Oh, we're halfway there!"
#else:
# print "The month is still young."
#today = raw_input("What day of the week is today?").lower
#if (today == "monday"):
# print "Yay class day!"
#elif (today == "tuesday"):
# print "Sigh, it's only Tuesday"
#elif (today == "wednesday"):
# print "HUMPDAY"
#elif (today == "thursday"):
# print "#tbt"
#elif (today == "friday"):
# print "TGIF"
#else:
# print "Yeah, it's the weekend!"
#age = int(raw_input("What is your age?"))
#if (age>=21):
# print "I can vote and go to a bar."
#elif (age<21 and age>=18):
# print "I can vote, but I cannot go to a bar."
#else:
# print "I can't vote or go to a bar."
number = int(raw_input("What is your number?"))
if (number %2 == 0):
print "The number",number,"is even."
else:
print "The number",number,"is odd."
| true |
e069693d9b3bad28d49e18ddf8d505eeb59f6623 | aqib-mehmood/Python | /Lab03.py | 2,558 | 4.15625 | 4 | # Task 01
# Write a program to create a basic chatbot application.
'''
response = ["Hi, How may I help you?", "I hope you enjoy this conversation. \nGood bye take care.",
"RAM is Random-access memory is a form of computer memory that can be read and changed in any order, typically used to store working data and machine code.",
"Sorry, I didn't get you!",
"Computer is an Electronic machine that accept data as input and provide output by processing that data.",
"You can google it to find more."]
print("Hi I am a Computer Specialist Ask me anything.")
while True:
quest1 = input("YOU : ")
if ("hi" in quest1 or "hello" in quest1):
print("BOT : " + response[0])
elif ("bye" in quest1 or "exit" in quest1):
print("BOT : "+response[1])
break
elif ("what" in quest1 and "ram" in quest1 or "RAM" in quest1):
print("BOT : "+response[2])
elif ("what" in quest1 and "COMPUTER" in quest1 or "computer" in quest1):
print("BOT : "+response[4])
elif ("why" in quest1 or "keyborad" in quest1 or "ROM" in quest1 or "hardisk" in quest1):
print("BOT : "+response[5])
else:
print("Sorry, I didn't get you!")
'''
# Task 02
# Make a questionnaire about yourself and get response from AI based chatbots before and after providing your information. Note: You can take assistance from chatbot examples on the internet.
response = ["Hi, Welcome!",
"Please Introduce Yourself and tell me for what job are you applying for?",
"I hope you enjoy this conversation. \nGood bye take care.",
"what is web development?",
"what is software development?",
"what are your weeknesses?",
"Why I hire you for this post?"]
print("Hi I am your Mentor for practicing Inteview Question.")
while True:
quest2 = input("YOU : ")
if ("hi" in quest2 or "hello" in quest2):
print("BOT : " + response[0] + " \n" +response[1])
elif ("bye" in quest2 or "exit" in quest2):
print("BOT : "+response[2])
break
elif ("web develop" in quest2):
print("BOT : "+response[3])
elif ("software" in quest2):
print("BOT : "+response[4])
elif ("development" in quest2):
print("BOT : "+response[5])
elif ("perfect" in quest2 or "motivated" in quest2 or "hardworking" in quest2 or "work hard" in quest2):
print("BOT : "+response[6])
else:
print("Great, So what else you know about the post.") | true |
a46375f6ebd301ddc69db4f1946b2abee2816ce9 | RohitV123/cs043 | /lab_projects/telephone.py | 1,256 | 4.1875 | 4 | from database import Simpledb
loop=True
db = Simpledb('telephone.txt')
db.__repr__()
while loop==True:
print('Would you like to:\n1:Delete a phone number?\n2:Update a phone number?\n3:Add another phone number?\n4:Find a phone number?\n5:Quit the program\nEnter a number 1-5')
choice=input()
while choice!='1' and choice!='2' and choice!='3' and choice!='4' and choice!='5':
print('Please type 1, 2, 3, 4, or 5.')
choice=input()
if choice=='1' or choice=='2' or choice=='3' or choice=='4' or choice=='5':
break
if choice=='1':
print('Whose number would you like deleted (enter a name)')
name=input()
db.delete(name)
print('Number is deleted.')
if choice=='2':
print('Whose number would you like to update?')
name=input()
print('What number would you like to update with?')
number=input()
db.update(name,number)
if choice=='3':
print('What number would you like added?')
number=input()
print('Whose number is it?')
name=input()
db.add(name,number)
if choice=='4':
print('Whose number is it?')
name=input()
db.find(name)
if choice=='5':
loop=False | true |
be47dede8cd2cabcdbad3f6a7ee3f1c83ca43c17 | mcclayac/python101 | /tutorial/tutorialTuples.py | 592 | 4.15625 | 4 | #!/usr/bin/env python3
tuple = ()
tuple3 = (3,)
personalinfo = ("Diana", 32, "New york")
print(personalinfo[0])
print(personalinfo[1])
print(personalinfo[2])
name, age, country, career = ("Diana", 32, 'Cananda', 'CompSci')
print('name:' , name)
print('country:', country)
listNumbers = [ 6, 3, 7, 4]
# python 3
#tupleList = tuple(listNumbers)
#print(tupleList)
listNumbers2 = list(personalinfo)
print('tuple:', personalinfo)
print('list:', listNumbers2)
# Python3 issues
#person = ('Alison','Victoria','Brenda','Rachel','Trevor')
#person = tuple(sorted(person))
#print(person)
| false |
f11661c0bfa1204ab28d9609cc01b1ee2caeac6d | IntellEyes/PythonProgramming | /OOPs Examples/4. Dice Simulation Application.py | 1,247 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 19:24:57 2018
@author: Rajath Kumar K S
Hello All,
Please Solve this Question using OOPS Concept.
1. Dice Rolling Simulator
The Goal: Like the title suggests, this project involves writing a program that
simulates rolling dice. When the program runs, it will randomly choose a number
between 1 and 6. (Or whatever other integer you prefer — the number of sides on
the die is up to you.) The program will print what that number is. It should
then ask you if you’d like to roll again. For this project, you’ll need to set
the min and max number that your dice can produce. For the average die, that
means a minimum of 1 and a maximum of 6. You’ll also want a function that
randomly grabs a number within that range and prints it.
Concepts to keep in mind:
*Random
*Integer
*While Loops
"""
import random
class dice():
player_no = 0
def __init__(self,name):
self.name = name
dice.player_no += 1
self.player_no = dice.player_no
def rolldice(self):
self.roll = random.randint(1,7)
with open('log.txt','a') as fl:
fl.write(' \n '+str(self.player_no)+' '+str(self.roll)+' '+self.name)
print(self.roll) | true |
0297a732a8e05a894adfa34ac3b491d77aad36ec | woodsj0125/cti110 | /P4HW1- Budget Analysis.py | 1,075 | 4.40625 | 4 | #Write a program that asks the user to enter the amount that he or she has budgeted for a month.It then should loop the prompt for user to enter their expenses for the month and keep running a total.
#12/2/2018
#CTI-110 P4HW1 - Budget Analysis
#Javonte Woods
#Needed Information
expense = 0.0
budget = 0.0
difference = 0.0
expenseTotal = 0.0
total_expense = 0
keep_going = 'y'
#Input Information
budget = float(input("What is your budget for the month?"))
print("Please begin entering the amounts of each of your monthly expenses:")
while keep_going == 'y':
expense = float(input("Monthly expense amount? $"))
total_expense = total_expense + expense
keep_going = input("Do you have any other expenses? (Enter y for yes.)")
#Calculations Module
if total_expense < budget:
difference = budget - total_expense
print("You were $", difference, " under budget.")
elif total_expense > budget:
difference = total_expense - budget
print("You were $", difference, " over budget.")
else:
print("You were right on budget. Smart shopping!!!")
| true |
1bd6d4f14649acc90d99dbe94d39a0b9ef9cc36d | THTatsuishi/finite-group-analyzer | /application/calc/calctools.py | 1,469 | 4.1875 | 4 | """
数値計算に使用する関数など。
"""
import numpy
import collections
def calc_divisor(a: int, include_one: bool) -> 'tuple[int]':
"""
指定の値の約数を求める。
自明な約数も含む。
厳密な意味での約数とは異なるが、include_one=Trueの場合には1を含める。
Parameters
----------
a : int
正の整数。
should_include_one : bool
約数の一覧に1を含めるかどうか。
True:
1を含める。
False:
1を含めない。
Returns
-------
'tuple[int]'
約数の一覧。
降順に並ぶ。
"""
div_set = set()
div = 1 if include_one else 2
div_max = numpy.sqrt(a)
while div <= div_max:
quot,mod = divmod(a,div)
if mod == 0:
div_set = div_set | {div,quot}
div += 1
return tuple(sorted(list(div_set),reverse=True))
def prime_factorize(n: int):
"""
正の整数を素因数分解する。
Parameters
----------
n : int
正の整数。
Returns
-------
TYPE
DESCRIPTION.
"""
prime_list = []
while (n % 2 == 0):
prime_list.append(2)
n //= 2
f = 3
while (f * f <= n):
if (n % f == 0):
prime_list.append(f)
n //= f
else:
f += 2
if n != 1: prime_list.append(n)
return collections.Counter(prime_list) | false |
2ecc3f8f440172a4e0669cf9227f7a5a415308cd | chaitanyakulkarni21/Python | /Practice/sumOfSq.py | 275 | 4.1875 | 4 | # Program to find the sum of squares of first n natural numbers
def sumOfSq(n):
s = 0
for i in range(1, n+1):
s = s + i**2
return s
n = int(input("Enter the last number in the series: "))
sum = print("The Sum of squares of the natural numebers is : ",sumOfSq(n)) | true |
82df081591b11f87f8a3d0e4a49117b2e30a6a23 | chaitanyakulkarni21/Python | /ObjectOrientedPrograming/oop2.py | 1,257 | 4.125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myFunc(self):
print("Hello, my name is {} and age is {}".format(self.name,self.age))
p = Person('Chaitanya', 26)
p.myFunc()
print(' ')
class ArithmeticOperations:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def printNum(self):
print("Two numbers are :",self.num1, self.num2)
class Sum(ArithmeticOperations):
def __init__(self, num1, num2):
ArithmeticOperations.__init__(self, num1, num2)
def calSum(self):
self.num3 = self.num1 + self.num2
print("Sum = ",self.num3)
class Difference(ArithmeticOperations):
def __init__(self, num1, num2):
ArithmeticOperations.__init__(self, num1, num2)
def calDiff(self):
self.num3 = self.num1 - self.num2
print("Difference = ",self.num3)
class Product(ArithmeticOperations):
def __init__(self, num1, num2):
ArithmeticOperations.__init__(self, num1, num2)
def calProd(self):
self.num3 = self.num1 * self.num2
print("Product = ",self.num3)
x = int(input("Enter num 1: "))
y = int(input("Ente num 2: "))
sum = Sum(x,y)
sum.printNum()
sum.calSum()
prod = Product(x,y)
prod.calProd()
diff = Difference(x,y)
diff.calDiff()
print(' ') | false |
58abe3efb8de9998c3f31561c833377e51b2b248 | chaitanyakulkarni21/Python | /If_else/greatestOfThreeNumbers.py | 252 | 4.25 | 4 | #Greatest of Three Numbers
x = input("Enter num1 : ")
y = input("Enter num2 : ")
z = input("Enter num3 : ")
if (x > y) and (x > z):
largest = x
elif (y > x) and (y > z):
largest = y
else:
largest = z
print("The largest number is",largest) | false |
3bef4a4a5c528961a76e0c406b8ca4c883bbc4d7 | aaronlio/ESC180 | /Lecture6.py | 2,207 | 4.46875 | 4 | #<----------------------------------- Lecture 6 ----------------------------------->
#<------------- For Loops -------------->
"Used to repeat a block a number of times, and do something each time it repeats"
for i in range(5):
print("I <3 EngSci")
for i in range(5):
print( 2 * i )
print(i)
print("==========")
#a^n : a^a * ....... * a (n times)
def my_pow(a, n):
'''Return a^n, where n is a non-negative integer'''
prod = 1
for i in range(n):
prod = prod * a
return prod
#<------------------- While Loops ------------------->
"""Repeat block while the condition is True
While condition:
some code
"""
i = 0
while i < 5:
print("hi", i)
i = i + 1
#<------ Same thing as a for loop ------->
for i in range(5):
print("hi", i)
#<------------ Compute log10(n) ----------->
# 10 ^ a = n, solve for a
# try 10^0, 10^1, 10^2, until you encounter 10 ^ a = n
def my_log(n):
res = 1
i = 0
# When we're entering the loop, res = 10 ^ i
while res < n:
res = res * 10
i += 1
return i
for j in range(10):
print(j)
#for i in range(start, stop, step)
for i in range(5, 14, 2):
print(i)
#<---------- Problem Solving with Modulus ------------->
"""Write a function that returns True if the input n is prime, false otherwise"""
# 7 % 2 = 1
# 7/2, remainder 1
"""The first thing we could try is to divide by every number... not efficient at all. Instead...
"""
def is_prime(n):
'''Return True iff n is prime, n is an integer'''
if n <= 1:
return False
if n == 2:
return True
for i in range(2, n):
if n % 1 == 0:
return False
return True # This will only be reached if the other return statement is never passed
# A different way of doing it
def is_prime3(n):
'''Return True iff n is prime, n is an int'''
if n <= 1:
return False
if n ==2:
return True
for i in range(n-2):
if n % (2+i) == 0: #n=121, i = 9: n % (9+2) == 0
return False
#If we are here, that means that we never returned False, so we tried
#all the possible factors and it turned out that
return True | true |
5bee2a8bd6b39d700e5f6861dfa6944a30191eb3 | jhglick/c110s02lab6 | /comp110_lab06.py | 1,192 | 4.15625 | 4 | """
Module: comp110_lab06
Exercises from lab 06, dealing with string accumualators.
"""
import sound
def create_sound(sound_string):
"""
Function that uses sound_string to create a sound object.
Each character is either a letter signifying a note
(a, b, c, d, e, f, g, each could be upper or lower case), or
a single digit number (1, 2, 3, 4, 5, 6, 7, 8, 9), or s to indicate
a silent sound.
The function should create and return a sound object consisting
of the notes specified in the string (in the same order as they
appear in the string.) Each note should be inserted into the sound
object for one half second, and it should be at the default octave.
If, however, the character before a note is a digit, then the note should
appear for longer. For example, if the digit is 4, then the next note
should be inserted with a length of 4 times one half second, or 2 seconds.
"""
return None # replace this when you're done.
# Do not modify anything after this point.
if __name__ == "__main__":
snd = create_sound("3Eabcde2Sc2e2Sc2egacadca")
snd.play()
sound.wait_until_played() | true |
512b6c79813cd0517da39939298b951e9aa26cef | Wangsherpa/python_assignment | /ineuron/assignment_1/app_3.py | 243 | 4.125 | 4 | """
Write a Python program to find the volume of a sphere with diameter 12 cm.
Formula: V=4/3 * π * r^3
"""
import math
diameter = 12
r = diameter/2
volume_of_sphere = 4 / 3 * math.pi * r ** 3
print(f"Volume of Sphere: {volume_of_sphere}") | true |
9017834de929f51ed0d70b07228cd48e74c14911 | vimm0/algorithm-challenges | /python/tutorial/class.py | 1,412 | 4.78125 | 5 | # https://docs.python.org/3/tutorial/classes.html
class MyClass:
"""A simple example class"""
i = 12345
def __init__(self):
"""
classes like to create objects with instances customized to a specific initial state.
class may define a special method named __init__()
"""
self.data = []
def f(self):
return 'hello world'
# valid attribute references
print(MyClass.i) # 12345
print(MyClass.f) # <function MyClass.f at 0x..>
# More information
print(MyClass.__name__) # 'MyClass'
print(MyClass.__doc__) # 'A simple example class'
# Class instantiation uses function notation
x = MyClass()
# invoke special method, because initial data initialized there
# x.data # []
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
print(x.f)
print(MyClass.f)
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i) # (3.0, -4.5)
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
d = Dog('Fido')
e = Dog('Buddy')
print(d.kind) # 'canine' # shared by all dogs
print(e.kind) # 'canine' # shared by all dogs
print(d.name) # 'Fido' # unique to d
print(e.name) # 'Buddy' # unique to e
| true |
e27c6c73ed23606865d5e6a05082e1b3d318737e | EMIAOZANG/assignment4 | /im965/answer8.py | 352 | 4.21875 | 4 | #answer8.py
#im965 program for assignment 04, question 08
#!/usr/bin/env python
#operate on a list to get the desired final list
d={'first':[1,2],'second':[2,3],'third':[3,4]}
print d
# a
temp=d['first']
d['first']=d['third']
d['third']=temp
print d
# b
d['third'].sort()
print d
#c
d['fourth']=d['second']
print d
# d
del d['second']
print d
| false |
19fd9bdc931d869ffa7130c4093a5aaacca7f2bc | manoj2904/python-projects | /15.list4.py | 566 | 4.40625 | 4 | #program using list
list=['p','y','t','h','o','n']
print("Initial list :" + str(list))
#to slice list
slicelist=list[1:4]
print("\nThe sliced list is" +str(slicelist))
#to slice till a particular element
slicelist=list[:-2]
print("\nThe sliced list to a particular element is :" + str(slicelist))
#to slice from a particular element
slicelist=list[2:]
print("\nThe sliced list from a particular element is :" + str(slicelist))
#to print element in reverse
slicelist=list[::-1]
print("\nThe sliced list in reverse order is :" + str(slicelist))
| true |
c313e0e3a680f66a5c20c19a580dcedef66fe16b | manoj2904/python-projects | /10.median.py | 324 | 4.1875 | 4 | #to find the median of the given elements
list=[10,23,35,44,56,45]
#sorting the list in ascending order
list.sort()
length=len(list)
if length%2==0:
median1=list[length//2]
median2=list[length//2-1]
median=(median1+median2)/2
else:
median=list[length//2]
print("the median is " +str(median))
| true |
44a13499b61479cef1c6117abafaa56f42ac50a6 | mervetak/G5PythonLectures | /Week_2/09_IfElifElse_4.py | 528 | 4.3125 | 4 | # Challenge
# Get a name from the user
# If the name is Max or John or Eli greet them with a Welcome message
# if the name is different than those above print "the name is invalid"
name = input("Enter a name: ")
name_list = ["Max", "John", "Eli"]
# 1st Solution
# if name.capitalize() in name_list:
# print("Welcome", name)
# else:
# print("The name is invalid")
# 2nd Solution
name = name.lower()
if name == "max" or name == "john" or name == "eli":
print("Welcome", name)
else:
print("The name is invalid")
| true |
9259c612bec7249ff96f5da625de54b1d779bf50 | mervetak/G5PythonLectures | /Week_2/12_IfElifElse_7.py | 458 | 4.15625 | 4 | # Calculator Example
# We are going to get 2 numbers from the user
# We are going to ask for an operator(+, -, *, /)
x = int(input("First number: "))
y = int(input("Second number: "))
operator = input("Enter the first letter of the operation[A, S, M, D] ").upper()
if operator == 'A':
print(x + y)
elif operator == 'S':
print(x - y)
elif operator == 'M':
print(x * y)
elif operator == 'D':
print(x / y)
else:
print("Invalid operator")
| true |
9cb66a8cf731fd83df4be4bfccb5d9cdf8b90184 | mervetak/G5PythonLectures | /Week_2/14_ForLoops.py | 2,060 | 4.40625 | 4 | # for variable in [value1, value2, etc.]:
# statement
# statement
# etc.
# The variable is assigned to first value in the list
# then the statements in the block will be executed
# Then, variable is assigned to the next value
# and the statements in the block will be executed again.
# This continues until the variable has been assigned to the last value in the list
c = ['orange', 'banana', 'apple']
# print every item
print(c[0])
print(c[1])
print(c[2])
for element in c:
print(element)
# For loops iterate over a given sequence
prime = [2, 3, 5, 7]
for i in prime:
print(i, end=' ')
print()
# Range is a built-in function that returns a sequence
# range(start:end:step)
# range(number) start from 0 to number - 1
# Prints out the number 0, 1, 2, 3, 4
for i in range(5):
print(i)
print()
# prints out 3, 4, 5
for x in range(3, 6):
print(x)
print()
# prints out 3, 5, 7
for x in range(3, 8, 2):
print(x)
# list creates a list
list1 = list(range(10))
print(list1)
# Add even numbers using range function
list2 = list(range(0, 11, 2))
print(list2)
# list of numbers from 0 - 10
list3 = list(range(11))
print("list3 :", list3)
for i in list3:
if i % 2 == 0:
print(i, end=' ')
print("\n")
for num in list3:
if num % 2 == 0:
print(num)
else:
print("Odd number")
# break and continue
# break is used to exit a for loop
# continue is used to skip the current block, and return to the for loop
# print only odd numbers : 1, 3, 5, 7, 9
for i in range(10): # i = 4
if i % 2 == 0:
continue
print(i)
print("After the break")
# when you use break statement it will exit the loop
# it will not iterate through the next items
for i in range(10): # i = 1
if i % 2 == 1:
break
print(i)
print()
# print 1, 2, 3
for letter in [1, 2, 3, 4, 5, 6]: # letter = 4
if letter == 5:
break
print(letter) # 1 2 3
print()
# continue
list4 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in list4:
if i == 3 or i == 5 or i == 7:
continue
print("i :", i)
| true |
5b271aca38dcd58a5095fa03aec6a6ac89b477de | mervetak/G5PythonLectures | /Week_1_Recap/03_Numbers.py | 398 | 4.25 | 4 | # int
# float
# complex numbers
# whole numbers == int
x = 5
# decimal numbers == float
y = 3.14
# complex numbers == complex
z = 2j
# type() to get the type of a value
print(type(x))
print(type(y))
print(type(z))
# Data Type Conversion
# convert from int to float
b = float(x)
# convert from float to int
d = int(y)
# convert from int to complex
f = complex(x)
print(b)
print(d)
print(f)
| true |
98f0948f46f115a1ce0d8442edd7b05b4a8a35e3 | AkashMullick/IntroToCompSci | /WhileExercises.py | 753 | 4.34375 | 4 | # Instructions
# 1. Convert the following into code that uses a while loop.
# print 2
# prints 4
# prints 6
# prints 8
# prints 10
# prints Goodbye!
i = 2;
while (i <= 10):
print(i)
i += 2
print("Goodbye!")
# 2. Convert the following into code that uses a while loop.
# prints Hello!
# prints 10
# prints 8
# prints 6
# prints 4
# prints 2
i = 10;
print("Hello!")
while (i > 0):
print(i)
i -= 2
# 3. Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:
# 21
# which is 1 + 2 + 3 + 4 + 5 + 6.
end = 6
i = 1
total = 0
while (i <= end):
total += i
i += 1
print(total)
| true |
9cde41d75a918c69c62b3d34d2bc4694956afb5d | 89chandu/PythonChandu | /recursion.py | 201 | 4.28125 | 4 | def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
number =int(input("Enter the number"))
print(factorial_recursive(number))
| false |
d48c22bb395768870024223e7d772060db2d9a18 | faizanjaved5/python-sir-syed | /Datatypes/numbers.py | 1,510 | 4.5625 | 5 | # numbers in python
# arithmetic operations on integers
num_one = 61
num_two = 40
# perform addition and print the result
print("integer addition:", num_one + num_two)
# perform subtraction and print the result
print("integer subtraction:", num_one - num_two)
# perform multiplication and print the result
print("integer multiplication:", num_one * num_two)
# perform division and print the result
print("integer division:", num_one / num_two)
# perform modules and print the result that is remainder of division
print("integer modules:", num_one % num_two)
# perform exponents and print the result
print("integer exponent:", num_one ** num_two)
# perform floor division and prints result
print("integer floor division:", num_one // num_two)
print("_________________________________________\n")
num_one = 2.4
num_two = 3.5
# perform addition and print the result
print("floats addition: ", num_one + num_two)
# perform subtraction and print the result
print("floats subtraction: ", num_one - num_two)
# perform multiplication and print the result
print("floats multiplication: ", num_one * num_two)
# perform division and print the result
print("floats division: ", num_one / num_two)
# perform modules and print the result that is remainder of division
print("floats modules: ", num_one % num_two)
# perform exponents and print the result
print("floats exponent: ", num_one ** num_two)
# perform floor division and prints result
print("floats floor division: ", num_one // num_two)
| true |
e783752854accf44ed127ff01641d98785aa274a | jallen2034/CS50 | /Houses/import.py | 1,582 | 4.28125 | 4 | import sys
import csv
from cs50 import SQL
# https://cs50.harvard.edu/x/2020/psets/7/houses/
def main():
if len(sys.argv) != 2:
print("Invalid usage, please enter: python import.py characters.csv")
sys.exit(1)
# give us access to the students db within our python script
db = SQL("sqlite:///students.db")
# open up the CSV file that was passed in as a command line argument & begin to read this csv file, row by row with a dictreader
with open(sys.argv[1], newline='') as characters_csv_file:
csv_reader = csv.DictReader(characters_csv_file)
# loop through for each row being read in dictreader
for row in csv_reader:
# pick the first keyvalue pair from this dictionary, parse the students name in this keyvaluepair, use split method in python to split the string in this keyvaluepair into multiple words, where there are spaces
split_name = row["name"].split()
# check after doing this split, if the amount of names in the first keyvaluepair = 3
if len(split_name) == 2:
# insert 'None' in the list at "split_name[1]" between this students first "split_name[0]" and last "split_name[2]" to make a null the middle value
split_name.insert(1, None)
# INSERT a row into the dbs table from the current row of keyvaluepairs, last and middle name (along with their house + birth)
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?);",
split_name[0], split_name[1], split_name[2], row["house"], row["birth"])
if __name__ == "__main__":
main()
| true |
a1dfffbbbb413f2038508ed8b30cf39c76bac16e | a4wc/rock-paper-scissors-game | /main.py | 969 | 4.1875 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
if choice < 0 or choice > 2:
print("You input an invalid number!")
else:
choices = [rock, paper, scissors]
computer_choice = random.randint(0,2)
print(choices[choice])
print(f"Computer choose\n{choices[computer_choice]}")
if choice == computer_choice:
print("It's a tie!")
elif choice == 0 and computer_choice == 2:
print("You win!")
elif computer_choice == 0 and choice == 2:
print("You lose!")
elif choice > computer_choice:
print("You win!")
elif computer_choice > choice:
print("You lose!")
| false |
0ebe61292cfdd8eceb7355c52c702842bd2ab926 | ambrosmt/CodingDojo | /Python/Intro/TypeList.py | 782 | 4.1875 | 4 | #given a list print a message
def ListFilter(arr):
newStr = ""
for elements in arr:
# #print elements
# #print type(elements)
# if isinstance(elements, str):
# newStr = 'String: '
if isinstance(elements, str):
temp = arr.index(elements)
newStr += arr[temp] + ' '
if arr.index(elements) is arr[-1]:
newStr = "String: ", newStr
print newStr
# print "String:", newStr
if isinstance(elements, int):
newInt = sum(arr)
print "Sum:", newInt
# input
l = ['magical','unicorns']
N = [2,3,1,7,4,12]
#"The list you entered is of integer type"
#"Sum: 29"
#output
#"The list you entered is of string type"
#"String: magical unicorns"
ListFilter(l)
| true |
5360f930f3c54e6e4da2641d248f5f23f824c0e3 | mmirmoosavi/revert_linked_list | /reverse_linklist.py | 1,868 | 4.1875 | 4 | ### time complexity of algorithm o(n)
### space complexity of algorithm o(1)
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __str__(self):
return str(self.value)
def __eq__(self, other):
if not isinstance(other, Node):
# don't attempt to compare against unrelated types
return NotImplemented
return self.value == other.value
class Link_list:
def __init__(self):
self.head = None
def __eq__(self, other):
if not isinstance(other, Link_list):
# don't attempt to compare against unrelated types
return False
temp = self.head
temp2 = other.head
while temp is not None and temp2 is not None:
if temp != temp2:
return False
temp = temp.next
temp2 = temp2.next
if temp2 is not None or temp is not None:
return False
return True
def print_list(self):
temp = self.head
while temp is not None:
print(temp.value, end=' ')
temp = temp.next
print()
def push_node(self, node_value):
new_node = Node(node_value)
new_node.next = self.head
self.head = new_node
def reverse(self):
#### each of the temp, reversed, list_to_do occupy 1 space which means space complexity = 3 ~ o(1)
### if size of list is 0 or 1 do nothing
if self.head is None or self.head.next is None:
return
list_to_do = self.head.next
reversed = self.head
reversed.next = None
while (list_to_do != None):
temp = list_to_do
list_to_do = list_to_do.next
temp.next = reversed
reversed = temp
self.head = reversed
return
| true |
864a045d88e0c980cfd50706b7b3f5dd569174ac | pp201/driving | /driving.py | 441 | 4.125 | 4 | country = input('What is your nationality: ')
age = input('Enter your age: ')
age = int(age)
if country == 'Taiwan':
if age >= 18:
print('Bro, go get the license. ')
else:
print('Sorry, you are too young for the drive license. ')
elif country == 'USA':
if age >= 16:
print('Bro, go get the license. ')
else:
print('Sorry, you are too young for the driver\'s license. ')
else:
print('Sorry man, you can only enter Taiwan or USA') | true |
4a2eb22a1984be51977b798c023a43990b5c7801 | Zhene4ka/python_task_from_habrahabr | /1.1.py | 470 | 4.34375 | 4 | from math import sqrt
#Составить программу расчета гипотенузы прямоугольного треугольника. Длина катетов запрашивается у пользователя.
a = int(input("Введите длину первого катета:"))
b = int(input("Введите длину второго катета:"))
m = sqrt(a**2 + b**2)
print("Длина гипотенузы равна {}".format(m))
| false |
3bcac17d0045f0028c5cef4ac55cbb62617f70ed | williamz97/CS361 | /PythonExercises/Exercise6.py | 1,151 | 4.125 | 4 | print("Exercise 6 \n")
#-----------Part A-----------
def is_prime(n):
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i < n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
#-----------Part C-----------
def primes_up_to(n):
counter = 2
list_of_primes = []
while counter <= n:
if is_prime(counter):
list_of_primes.append(counter)
counter += 1
return(list_of_primes)
#-----------Part D-----------
def first_n_primes(n):
num_primes = n
counter = 2
list_of_primes = []
while num_primes > 0:
if is_prime(counter):
num_primes = num_primes - 1
list_of_primes.append(counter)
counter += 1
return(list_of_primes)
#-----------Tests-----------
print("Check if 230 is prime:", is_prime(230))
print("Prints all primes up to 100:", primes_up_to(100))
print("Prints first 50 primes", first_n_primes(50)) | false |
af4c149c40141e59d28cb4330077a9c758fab234 | Jonathan-Nuno/Assignments | /week_1/d3-wkend.py | 1,319 | 4.15625 | 4 | ### Weekend assignment - todolist
# Add task to list
def add(todo, x, y):
todo[x] = y
# Remove task from list
def remover(todo, number):
index = number - 1
d = list(todo)[index]
del todo[d]
# View all task
def view2(x):
n_order = 0
for key, val in x.items():
n_order += 1
print("{0} - {1} - {2}".format(n_order, key, val))
# Dictionary & array
todo = {}
# Syntax
loop = True
while loop:
print("TODO List")
print("1. Add a task")
print("2. Remove a task")
print("3. View all tasks")
print("Enter Q to quit")
sel = (input("Please enter your selection: "))
if sel in ('1', '2', '3', "q" , "Q"):
if sel == '1': #add task
name = input("Please provide a task name: ")
prio = input("Please select prioty level (High | Medium | Low): ")
add(todo, name, prio)
elif sel == '2': #remove task
number = int(input("Please provide list number to remove: "))
remover(todo, number)
elif sel == '3': #print todo list
view2(todo)
elif sel == "q" or sel == "Q": #exit todo list
print("You have quit the TODO List")
break
else: #repeat loop if invalid selection occurs
print("Please enter a valid secltion")
| true |
052a1d4d4ca6d12e6a40db16b590d175f766aed5 | Jonathan-Nuno/Assignments | /week_1/d2-a2.py | 528 | 4.28125 | 4 | ### Day 2 - Assignment 2 - Palindrome detector
###Solution 1
#print("Palindrome Checker")
#stc = input("Enter a word: ")
#if stc == stc [::-1]:
# print("This word is a palindrome")
#else:
# print("This word is not a palindrome")
### Solution 2
print("Palindrome Checker")
def palin(n):
for index in range(0,int(len(n)/2)):
if n[index] != n[len(n) -index -1]:
return False
return True
w = input("Please enter a word: ")
ans = palin(w)
if (ans):
print("Yes")
else:
print("No") | true |
2bcdb5d533b002d8f61510073a0eb07458d72b6d | gdincu/py_thw | /4_File_Handling.py | 2,098 | 4.34375 | 4 | #Ex15
import sys
filename = sys.argv[1]
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Read a File
'r' is the default mode. It opens a file for reading and reads the entire content of the file.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
f=open(filename, "r")
if f.mode == 'r':
contents =f.read()
print(contents)
#readlines - used to read the contents of a file line by line
fTemp = f.readlines()
for x in fTemp:
print(x)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Adds to the file
'w' opens the file for writing. If the file doesn't exist it creates a new file. If the file exists it truncates the file.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
f= open("template.txt","w+")
print("Adds lines to the file: ")
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Create a new file
'x' creates a new file. If the file already exists, the operation fails.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
f= open("newFile.txt",'x')
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Append Data to a File
'a' opens a file in append mode. If the file does not exist, it creates a new file
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
f=open(filename, "a+")
for i in range(2):
f.write("Appended line %d\r\n" % (i+1))
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Truncate a file
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
#Opens the file & provides writing permission
print("Opening the file....")
txt = open(filename,'w+')
#Truncates the file
print("Truncating the file")
txt.truncate()
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Close a file
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
target.close()
| true |
ce813565803546b73951b0c5e8169dc03449275e | bradAnders/me499 | /lab2/reverse.py | 1,319 | 4.46875 | 4 | #!/usr/bin/env python
# File: reverse.py
# Author: Brad Anderson
# Date: January 32, 2018
# File: ME499 Lab2 - iterative and recursive reverse
# Description: Reverses a list of numbers with both a recursive
# and an iterative method
# Collaborators: Kenzie Brian
import copy
# Reverses a list iteratively
def reverse_i(nums_in):
numbers = copy.copy(nums_in)
n = len(numbers)
print str(n) + " numbers"
for i in range((n/2)):
print "i = " + str(i)
# Swap mirrored indicies
temp = numbers[i]
numbers[i] = numbers[n-1-i]
numbers[n-1-i] = temp
# end for
return numbers
# end def
# Reverses a list recursively
def reverse_r(nums_in):
n = len(nums_in)
# End case
if n < 2:
return nums_in
# end if
# Swap first and end entries, and then reverse list[1:n-1]
# Concatenate them in the return
return [nums_in[n-1]] + reverse_r(copy.copy(nums_in[1:n-1])) + [nums_in[0]]
# end def
# MAINNNNN
if __name__ == "__main__":
nums = [3, 2, 5, -1, 77, -3, 0, 31, 0]
print "Original list is " + str(nums)
print "Iterative reverse is " + str(reverse_i(nums))
print "Recursive reverse is " + str(reverse_r(nums))
# end main
| true |
a715023ed2767ce98fa6b6450966fa56dcf75aee | derflahax/bad_encryption | /temp_cryptation.py | 941 | 4.25 | 4 | #############################
# OBS the encryption is #
# random and will be gone #
# when the program restarts.#
# Don't use this for real #
#############################
import random
encrypt = {}
decrypt = {}
chars = ['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f']
securitylevel = 32
def derflas_encryption(x):
if x in encrypt:
return encrypt[x]
else:
str = ''
for a in range(securitylevel):
str += random.choice(chars)
encrypt[x]=str
decrypt[str] = x
return str
def derflas_decrypt(str):
if str in decrypt:
return decrypt[str]
else:
return None
crypting = True
while crypting:
sort = input("encrypt or decrypt?? (e/d)")
if sort == 'd' or sort == 'D':
print(derflas_decrypt(input("text to decrypt")))
if sort == 'e' or sort == 'E':
print(derflas_encryption(input("text to encrypt")))
| true |
f5455621ad738a251bf0f57873721962bd675c87 | AlexMora23/Tarea_Phyton | /4_es_vocal.py | 571 | 4.15625 | 4 | def es_vocal():
return()
letra = input("Ingrese una letra>")
if(letra=='a' or letra=='e' or letra=='i' or letra=='o' or letra=='u'):
print(True)
elif(letra=='A' or letra=='E' or letra=='I' or letra=='O' or letra=='U'):
print(True)
else:
#if(letra=='e'):
print(False)
# else:
# if(letra=='i'):
# print(True)
# else:
# if(letra=='o'):
# print(True)
# else:
# if(letra=='u'):
# print(True)
# else:
# print("False")
| false |
454f7bd69c26dfaddac708e2397c0b3041cc303b | RossMelville/python_hello_world | /hello_world.py | 614 | 4.40625 | 4 | message = "Hello World!"
print (message)
message = "Hello Python Crash Course World"
print (message)
#this is to show that the title will capitalise the seperate words and upper and lower will put the words into those cases
name = "ross melville"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "victoria"
last_name = "scordecchia"
full_name = first_name + " " + last_name
print(full_name.title())
print("Hello " + full_name.title() + "!")
message = "Hello " + full_name.title() + " & " + name.title()
print(message)
print("Python")
print("\tPython")
print("Languages:\nJava\nRuby\nPython") | true |
916b8499c8bc160521a3b8377664521dc9d5a042 | soyalextreme/YT-minicurso-Python-Algoritmos | /Funciones.py | 1,042 | 4.25 | 4 | """
ABSTRACCION DE CODIGO CON LAS FUNCIONES
ESCRIBE UNA VEZ USALO MUCHAS
"""
def verify_friend_name_age(my_age, my_friend_age, my_friend_name, my_name="Alex" ):
""" Verifica que mi amigo y yo tengamos la misma edad y nos llamemos igual """
# body function
if my_name == my_friend_name and my_age == my_friend_age:
print("My friend and I have the same name and the same age")
elif my_name != my_friend_name and my_age == my_friend_age:
print("We dont have the same name but we have the same age")
elif my_name == my_friend_name and my_age != my_friend_age:
print("We have the same name but we have diferent ages")
else:
print("We dont have the same name neither the same age")
# implement new functions here
def say_hello():
print("Hello world")
if __name__ == "__main__":
say_hello()
verify_friend_name_age(22, 19, "David")
verify_friend_name_age(22, 22, "Alex", "Fernando")
verify_friend_name_age(22, 22, "David")
| false |
51a9aec39dcba2e8bb817c4eea5bf05539807ae1 | sunuvw/Python | /ex7_if&elif&else.py | 968 | 4.34375 | 4 | # -*- coding: utf-8 -*-
#习题:条件判断
######################
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
# if语句是从上往下判断,如果在某个判断上是True,执行该判断对应的语句,就会忽略掉剩下的elif和else
x = "" # 只要x是非零数值、非空字符串、非空list,就判断为True,否则为False
if x:
print("True")
else:
print("False")
birth = input("your birth is: ")
birth = int(birth) # input()返回的数据类型是字符串str,不能直接和整数比较,必须先把str转换成整数,使用int()函数实现转换
if birth < 2000:
print("00前")
else:
print("00后")
# 练习
height = 1.75
weight = 80.5
bmi = 80.5 / (1.75 * 1.75)
print(bmi)
if bmi < 18.5:
print("过轻")
elif bmi >= 18.5 and bmi <= 25:
print("正常")
elif bmi >25 and bmi <= 28:
print("过重")
elif bmi >28 and bmi <= 32:
print("肥胖")
else:
print("严重肥胖") | false |
99d673f3ac2560605e80a73b7ebdece8ab0d202f | bwynn/python_cc | /part_1/dictionaries/favorite_languages.py | 1,915 | 4.21875 | 4 | # favorite_languages = {
# 'jen': 'python',
# 'sarah': 'c',
# 'edward': 'ruby',
# 'phil': 'python'
# }
# print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
# loop through key,value pairs in object/dictionary
# for name, language in favorite_languages.items():
# print(name.title() + "'s favorite language is " + language.title() + ".")
################################################################################
# loop through keys in dictionary
# for name in favorite_languages.keys():
# print(name.title())
################################################################################
# adding in conditional check to return specific values
# friends = ['phil', 'sarah']
# for name in favorite_languages.keys():
# print(name.title())
# if name in friends:
# print(" Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")
# looping through dictionary keys in order
# for name in sorted(favorite_languages.keys()):
# print(name.title() + ", thank you for taking the poll.")
################################################################################
# looping through the values
# print("The following languages have been mentioned:")
# for language in favorite_languages.values():
# print(language.title())
# use a set() to remove any repetitions in values
# for language in set(favorite_languages.values()):
# print(language.title())
################################################################################
# Multiple values in a dictionary
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell']
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
| false |
937138aa330309238cd12ccf3a4cdea69f25fb9e | tanajis/python | /dataStructure/dynamic_programming/dynamic_fib.py | 1,716 | 4.3125 | 4 | #=============================================================================================
#!/usr/bin/env python
#title :dynamic_fib.py
#description :This is demo of dynamic programming with fibonacci series.
#author :Tanaji Sutar
#date :2020-Jan-28
#python_version :2.7/3
#Notes: Fibonacci Series: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
#============================================================================================
def fib_rec(n):
#This is using just recursion
if n==1 or n==2:
return 1
else:
return fib_rec(n-1) + fib_rec(n-2)
def fib_rec_memo(n,memo):
#This is fibonacci series using recursion and memoization.
#memo needs to be declared outside the function(global) and cant be inside the function.
if n==1 or n==2:
return 1
elif memo[n] is not None:
return memo[n]
else:
res=fib_rec_memo(n-1,memo)+fib_rec_memo(n-2,memo)
memo[n]=res
return res
def fib_bottom_up(n):
#memo can be declared inside function.
#No recursion is used.
memo2=[None]*(n+1)
if n==1 or n==2:
return 1
else:
memo2[1]=1
memo2[2]=1
i=3
while(i<=n):
memo2[i]=memo2[i-1] +memo2[i-2]
i=i+1
return memo2[n]
if __name__ == "__main__":
n=10
print('Using recursion only:',fib_rec(n))
#In python index starts at 0 hence take n+1 and keep start blank & unused
memo=[None]*(n+1)
#print(memo)
print('Using recustion with memoization:',fib_rec_memo(n, memo))
#print(memo)
print('Using bottomup with memoization:',fib_bottom_up(n))
| true |
63692417281f0d453bbf01f567c3d08a7e3deac3 | tanajis/python | /dailyCoding/problem006.py | 2,593 | 4.28125 | 4 | ###############################################################################
# problem 6
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Google.
# An XOR linked list is a more memory efficient doubly linked list.
# Instead of each node holding next and prev fields, it holds a field
# named both, which is an XOR of the next node and the previous node.
# Implement an XOR linked list; it has an add(element) which adds the element to the end,
# and a get(index) which returns the node at index
###############################################################################
#XOR Doubly linked list
# a-->b--->c--d
#list is empty. insert a .npx will be XOR(None,None )= None
#insert b. npx of b will be XOR(npx(a),None)
#Python id() function returns the "identity" of the object.
#The identity of an object is an integer, which is guaranteed to be unique and
# constant for this object
class Node:
def __init__(self, data):
self.data = data
self.nexprev = id(data)
def __repr__(self):
return str(self.data)
class LinkedList:
def __init__(self, data):
new_node = Node(data)
self.head = new_node
self.tail = new_node
self.dict = {}
self.dict[data] = id(new_node)
def add(self, data):
#Create new Node
newNode = Node(data)
#update last elements pointer
self.tail.nexprev =self.tail.nexprev ^ id(newNode.data)
#update new element pointing prev element
newNode.nexprev = id(self.tail.data)
#set tail pointer to new Node
self.tail = newNode
self.dict[data] = id(newNode)
def printLinkList(self):
prev = None
curr = self.head
next = curr.nexprev
print(prev,next,curr)
"""
while(1):
print(curr.data)
prev = curr
next = curr.nexprev
if curr == self.tail:
break
"""
"""
def get(self, index):
prev_node_address = 0
result_node = self.head
for i in range(index):
next_node_address = prev_node_address ^ result_node.both
prev_node_address = id(result_node.data)
result_node = id_map[next_node_address]
return result_node.data
"""
llist = LinkedList('a')
llist.add('b')
llist.add('c')
llist.add('e')
llist.printLinkList()
print(llist.dict)
"""
assert llist.get(0) == "c"
assert llist.get(1) == "d"
assert llist.get(2) == "e"
assert llist.get(3) == "a"
"""
| true |
0d9decaa304afee809d8e74b7c767b2654c2a7f4 | tanajis/python | /dailyCoding/problem005.py | 1,051 | 4.3125 | 4 | #########################################################################################
# Problem 5 : medium
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Jane Street.
# cons(a, b) constructs a pair, and car(pair) and cdr(pair)
# returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
# Given this implementation of cons:
# def cons(a, b):
# def pair(f):
# return f(a, b)
# return pair
# Implement car and cdr.
#########################################################################################
#This is an example of functional programming
# functional you have a function (interface) that
# accepts another function (implementation) and calls it inside.
#Ref : https://galaiko.rocks/posts/dcp/problem-5/
def cons(a, b):
return lambda f: f(a, b)
def car(f):
z = lambda x, y: x
return f(z)
def cdr(f):
z = lambda x, y: y
return f(z)
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
| true |
7fb3b98ba703779965f661e04135593a6fb3ebae | rnarodit/100daysofcode | /Day 26/list_comprehension.py | 938 | 4.5625 | 5 | # list comprehension is a case in which you create a new list from a previous list w/o using a for loop
# ex: new_list = [new_item for item in list]
numbers = [1,2,3]
#new_list = []
# for n in list :
# add_1 = n+1
# new_list.append(add_1)
# new_list = [n+1 for n in numbers] # list comprehension
# name="Angela"
# new_list2 = [letter for letter in name] # can also use list comprehension on strings
# print (new_list2)
#python sequences : list , range, string , touples all work with list comprehension
new_list = [n*2 for n in range (1,5)]
print (new_list)
#conditional list comprehension:
# new_list = [new_item for item in list if test] # only add new item and perform code if the test passes
names = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"]
short_names = [name for name in names if len(name) <= 4]
print (short_names)
long_names = [name.upper() for name in names if len(name) > 5 ]
print (long_names)
| true |
af8b451dd132212cb3b6411138b5031c23ff5ef0 | rnarodit/100daysofcode | /Day 2/dataTypes.py | 1,098 | 4.28125 | 4 | #data types
#strings-> string of charachters enclosed by double quotes /single quotes .
#can refer to a specific charachter in a string. remember 0 represents the first position in the string -> pulling an element from a string is called subscript
print("Hello"[4])
#putting number in quotes make them a string so addition will just concactinate them
print("123"+"345")
#Integer-> to declare just write number w/o anything else
print(123+345)
#can put undersocres in a large number instead of commas to make it more readable and the computer will ignore it
print(123_456)
#Float -> floating ponit number, number that has a decimal
3141.59
#Boolean -> two possible value. begin with capital T or F
True
False
#Type erros using data types where they cannot be used
# len(2) for ex
#can use type check funciton to check the data type of something -> type()
num_char= len(input("what is your name? "))
print(type(num_char))
#you can convert data types -> str(), int() , float()
new_num_char= str(num_char)
print("Your name has "+ new_num_char + " characters.")
a=float(123)
print (type(a)) | true |
65fd908a8debcd003f2f59178b2d93e1a2381688 | rnarodit/100daysofcode | /Day 18/pythonTuples.py | 1,013 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
#python tuple data type that looks like -> my tuple = (1,3,8)
# to access element in the tupple -> my_tupple[0]
# you cannot change the values in a tupple unlike a list
# you cannot remove, or add values to a tupple
# a tupple is immutable
# you can convert tupple into a list -> list (my_tupple)
def randomColor ():
r = random.randrange(0,255)
g = random.randrange(0,255)
b = random.randrange(0,255)
return (r,g,b) # returning a tupple
def choosedirection (turtle):
directions = [0, 90, 180, 270]
direction = random.choice(directions)
turtle.setheading(direction)
timmy_the_turtle = Turtle ()
timmy_the_turtle.shape("turtle")
timmy_the_turtle.color("blue")
screen = Screen ()
screen.colormode(255)
timmy_the_turtle.pensize(10)
timmy_the_turtle.speed("fastest")
for i in range (0,100):
timmy_the_turtle.pencolor(randomColor())
timmy_the_turtle.forward(30)
choosedirection(timmy_the_turtle)
screen.exitonclick()
| true |
f77aeacfd65b0a5cde8f545cfff6ec49f7329409 | rnarodit/100daysofcode | /Day 26/pandas_iteration.py | 713 | 4.34375 | 4 | student_dict ={
"student": ["Angela","Ron", "Bob"],
"score": [56,76,98]
}
# for (key,value) in student_dict.items(): # loop through dictionary
# print (key)
# print (value)
# looping through a data frame is very similar to dictionary
import pandas
student_data = pandas.DataFrame(student_dict)
print (student_data)
for (key,value) in student_data.items(): #loop through data frame
print(key)
print(value)
#Loop through rows of a data frame
for (index,row_data) in student_data.iterrows():
#print (row_data.score)
if row_data.student == "Angela":
print (row_data.score)
students ={row.student:row.score for (index, row) in student_data.iterrows() }
print (students) | false |
789b7ea62bf4cfc9704ad5fb40b0d9cbce290a14 | Resires/tietopythontraining-basic | /students/uss_tomasz/lesson_03_functions/calculator.py | 1,821 | 4.625 | 5 | def display_options():
"""This function is needed in order to display which are possible inputs for user.
"""
print("a - add")
print("s - subtract")
print("m - multiply")
print("d - divide")
print("p - power")
print("h,? - help")
print("q - QUIT")
def collect_variables():
"""Function is asking user to write two integers.
Returns:
Two variables. They are needed to calculate result, for example adding
"""
var_1 = int(input("Input 1st operand:"))
var_2 = int(input("Input 2nd operand:"))
return var_1, var_2
def execute_command(command_name, function_type):
"""
Param:
command_name - string. this value will be displayed for user in order to identify which command was performed
function_type - lambda function. containing two arguments and relations between them. Normally it is adding,
subtracting, multiplying, dividing or power.
Returns:
Value is calculated based on two operands from user input and lambda function.
"""
print(command_name)
operand1, operand2 = collect_variables()
print("Result:")
print(function_type(operand1, operand2))
print("Welcome to organized calculator:")
display_options()
while True:
print("Enter option:")
option = input()
if option == "a":
execute_command("ADDING", lambda a, b: a + b)
if option == "s":
execute_command("SUBTRACT", lambda a, b: a - b)
if option == "m":
execute_command("MULTIPLY", lambda a, b: a * b)
if option == "d":
execute_command("DIVIDE", lambda a, b: a / b)
if option == 'p':
execute_command("POWER", lambda a, b: a ** b)
if option == "h" or option == "?":
display_options()
if option == "q":
print("GOOD BYE")
break
| true |
02279d180a39415e37a178221707a8bec8532984 | tirth/Genetic-Algorithms | /python/genetic_simple.py | 1,718 | 4.15625 | 4 | __author__ = 'tirth'
# Given the digits 0 through 9 and the operators +, -, * and /,
# find a sequence that will represent a given target number.
# The operators will be applied sequentially from left to right as you read.
from population import Population
# --------- VALUES ---------
target = 142
population_size = 100
crossover_rate = 0.5
mutation_rate = 0.001
codon_length = 4
gene_size = 20
generation_reset = 200
max_generations = 100000
# --------------------------
# get input and create population
print('max value: ', Population(1).max_value)
# target = float(input('enter target (numbers please): '))
pop_pop = Population(population_size, target, crossover_rate, mutation_rate,
codon_length, gene_size)
print('initial population fitness', pop_pop.population_fitness)
solutions = set([chromosome.equation for chromosome in pop_pop.population
if chromosome.fitness > 1])
generations = 0
# keep generating until we find an answer or hit the limit
while len(solutions) < 1 and generations < max_generations:
pop_pop.extinction_event() if generations % generation_reset == 0 else \
pop_pop.next_generation()
generations += 1
solutions = set([chromosome.equation for chromosome in pop_pop.population
if chromosome.fitness == chromosome.perfect_fit])
print('gen', generations, 'population fitness:',
pop_pop.population_fitness)
# for chromosome in pop_pop.population:
# print(chromosome.value, end=', ')
# see what we got
if len(solutions) > 0:
print('evolved {0} for {1} in {2} generations'.format(
solutions.pop(), target, generations))
else:
print('limit reached without success') | true |
81cf13bbb4988f9ef1a9b36fa1e13c9e02d9584b | ncarr/First-Pull-Request | /sierspinksi.py | 1,696 | 4.25 | 4 | #imports and name program. This is a gr8 program that will draw triangles inside triangles inside triangles inside triangles...
import turtle;
import random
import re
import sys #to take command line arguments
import logging #to tell your console stuff that you did wrong or right
PROGNAME = 'Sierpinski'
#make turtle, draw in white and control speed
pen = turtle.Turtle()
pen.speed(1)
pen.pencolor("fuglehorn")
#hide the turtle
turtle.hideturtle()
pen.ht()
#manage screen, random background
screen = turtle.getscreen()
screen.colormode(255)
r = random.randrange(0, 257, 10)
g = random.randrange(0, 257, 10)
b = random.randrange(0, 257, 10)
screen.bgcolor(r, g, b)
#TODO: Make it expand to screen size. Hopefully python will make it easy for me.
points = [[-280,-200],[0,280],[280,-200]] #plots points. 1.4x between the numbers
#I'm trying to practice commenting but this function is real straightforward.
def getMid(p1,p2):
return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2)
function triangle(points,depth):
pen.up()
pen.goto(points[0][0],points[0][1])
pen.down()
pen.goto(points[1][0],points[1][1])
pen.goto(points[2][0],points[2][1])
pen.goto(points[0][0],points[0][1])
if depth>0:
triangle([points[0],
getMid(points[0], points[1]),
getMid(points[0], points[2])], depth-1)
triangle([
points[1],
getMid(points[0],
points[1]),
getMid(points[1],
points[2])]
,depth-1)
triangle([points[2],
getMid(points[2],
points[1]),
getMid(points[0],
points[2])],
depth-1)
triangle(points,6)
| true |
89c66179e4c619c70e4d4ae22b7aa82cffd004b8 | caicanting/programming-niukeOJ-python | /prime number.py | 1,305 | 4.28125 | 4 | # 功能:质数因子
# 要求:按照从小到大的顺序输出它的所有质数的因子。
# 输入格式:输入一个long型整数
# 输出格式:按照从小到大的顺序输出它的所有质数的因子,以空格隔开。最后一个数后面也要有空格。
# 样例:输入:180
# 输出:2 2 3 3 5
import sys
import math
def is_prime(number):
if number == 2:
return True
else:
for j in range(2, int(math.ceil(number ** 0.5)), 1):
if number % j == 0:
return False
return True
def prime_element(number):
if is_prime(number):
print(number, end=' ')
else:
result = []
prime_number = [2]
for i in range(3, number // 2 + 1, 1):
if is_prime(i):
prime_number.append(i)
i = 0
while number != 1:
if number % prime_number[i] == 0:
result.append(prime_number[i])
number = number // prime_number[i]
else:
i = i + 1
for k in range(len(result)):
print(result[k], end=' ')
def main():
number = int(sys.stdin.readline().strip())
prime_element(number)
if __name__ == '__main__':
main()
| false |
0b5f6d928729a3bdc29f22e6d3b96be75855541e | esthompson1365/gw-data-hw | /Pandas homework/Part_2/GoodReadsSummary.py | 2,257 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Good Reads Summary
#
# #### The objective of this assignment is for you to explain what is happening in each cell in clear, understandable language.
#
# #### _There is no need to code._ The code is there for you, and it already runs. Your task is only to explain what each line in each cell does.
#
# #### The placeholder cells should describe what happens in the cell below it.
# **Example**: The cell below imports `pandas` as a dependency because `pandas` functions will be used throughout the program, such as the Pandas `DataFrame` as well as the `read_csv` function.
# In[1]:
import pandas as pd
# First, we specify the the path to our csv file and store the path in `goodreads_path`. Then we load the csv file to a dataframe called `goodreads_df` and display the first 5 rows.
# In[2]:
goodreads_path = "Resources/books_clean.csv"
goodreads_df = pd.read_csv(goodreads_path, encoding="utf-8")
goodreads_df.head()
# The first line below counts the number of authors in the dataframe `goodreads_df["Authors"].unique()` references the column named 'Author' and returns a list of authors without duplicates. The `len()` function then counts the length of this list or, in other words, the number of unique authors in the dataframe.
#
# Then we write the minimum and maximum publication years to `earliest_year` and `latest_year`.
#
# We create a new column called 'Total Reviews' which contains the sum of columns 4-8. The sum of all the rows in `goodreads_df['Total Reviews']` is taken and stored in the object `total reviews`
# In[ ]:
author_count = len(goodreads_df["Authors"].unique())
earliest_year = goodreads_df["Publication Year"].min()
latest_year = goodreads_df["Publication Year"].max()
goodreads_df['Total Reviews'] = goodreads_df.iloc[:, 4:].sum(axis=1)
total_reviews = sum(goodreads_df['Total Reviews'])
# Using the pandas function pd.DataFrame, we create a table with our summary statistics
# In[ ]:
summary_table = pd.DataFrame({"Total Unique Authors": [author_count],
"Earliest Year": earliest_year,
"Latest Year": latest_year,
"Total Reviews": total_reviews})
summary_table
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.