blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c5e262c8472a994f0e5629f4b59e21490333fc41 | podkolzinmir/Tri567 | /TestTriangle.py | 1,376 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from triangle import classify_triangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html has a nice description of the framework
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
def testRightTriangleA(self):
self.assertEqual(classify_triangle(3,4,5),'Right','3,4,5 is a Right triangle')
def testRightTriangleB(self):
self.assertEqual(classify_triangle(5,3,4),'Right','5,3,4 is a Right triangle')
def testEquilateralTriangles(self):
self.assertEqual(classify_triangle(1,1,1),'Equilateral','1,1,1 should be equilateral')
def testIsoscelesTriangles(self):
self.assertEqual(classify_triangle(10,10,12),'Isoceles','Should be Isoceles')
self.assertEqual(classify_triangle(6,7,6), 'Isoceles', 'Should be Isoceles')
def testTriangle(self):
self.assertEqual(classify_triangle(10,15,30),'NotATriangle','Should be NotATriangle')
self.assertEqual(classify_triangle(-6,-7,-6), 'InvalidInput', 'Should be InvalidInput')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
| true |
77e4f87501bf5694991be053ee37a35de64492da | Aeternix1/Python-Crash-Course | /Chapter_6/dictionary.py | 1,054 | 4.28125 | 4 |
print("alien.py")
#Dictionary allows us to contain relevant information about an entity
alien_0 = {'color': 'green', 'points': 5}
#We access the values like so
print(alien_0)
print(alien_0['color'])
print(alien_0['points'])
#Adding new key value pairs
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#To modify values in a dictionary
alien_0['color'] = 'yellow'
print(alien_0)
#Using the dictionary to modify useful values
#depending on the speed of the alien I'm going to move is x units to the right
alien_0['speed'] = 'fast'
if alien_0['speed'] == 'fast':
x_increment = 3
elif alien_0['speed'] == 'medium':
x_increment = 2
elif alien_0['speed'] == 'slow':
x_increment = 1
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(alien_0['x_position'])
#Deleting a key value pair
del alien_0['points']
#Dictionaries can also be used to store similar objects
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print(favourite_languages)
| true |
98a0e568aa660736c0b2708588d8ebab864279a5 | Aeternix1/Python-Crash-Course | /Chapter_7/input.py | 762 | 4.28125 | 4 | #Input stores the value as a variable
# message = input("Tell me something, and I will repeat it back to you: ")
# print(message)
# print("\n greeter.py")
# name = input("Please enter your name: ")
# print("Hello, " + name + "!")
# #making a prompt spread out over a few lings with += on the variable
# prompt = "If you tell us who you are, we can personalize the messages you see."
# prompt += "\nWhat is your first name? "
# name = input(prompt)
# print("\n Hello, " + name.title() + "!")
#Use the int function to convert string inputs into numbers
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
| true |
509cfe81519a7cb9d0198a39f24167ca04216a9b | Aeternix1/Python-Crash-Course | /Chapter_6/nesting.py | 2,907 | 4.15625 | 4 | #Listing allows you to store dictionaries
print("\n aliens.py")
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points':10}
alien_2 = {'color': 'red', 'points':15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
#Randomly generating aliens
print("\n Randomly generating aliens")
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
#Changing the values of the dictionaries stored in the list
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
#Use case (d in list) when each dictionary contains lots of information about an
#Object e.g. list of users
print('\n A list inside a dictionary')
#Use case -> When an aspect of an object in the dictionary has multiple
#Information
pizza = {
'crust':'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
#Summarise the order
print("You ordered a " + pizza['crust'] + "-crust pizza" + "with the following\
toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
print('\n Favourite Languages')
favourite_languages = {
'jen' : ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil' : ['python', 'haskell'],
}
#Note the use of languages in the key value pair, all values are lists
for name, languages in favourite_languages.items():
if len(languages) == 1:
print("\n" + name.title() + "'s favourite languages is:")
for language in languages:
print("\t" + language.title())
else:
print("\n" + name.title() + "'s favourite languages are:")
for language in languages:
print("\t" + language.title())
#NOTE: Too much nesting is problematic, try to keep it at an understandable
#Level
#Dictionary in a dictionary
print('\n users.py')
users = {
'aeinstien': {
'first': 'albert',
'last': 'einstien',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
#Using the title key will captialise all the values in a sentence
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
#Try to ensuer that the structure of nested dictionaries are the same ,
#This makes it much easier to work with
| true |
619efd9bc1c336f01c3815aab3195313d76eb9b0 | momentum-cohort-2019-02/kb | /w2/examples/palindrome.py | 1,270 | 4.21875 | 4 | def is_palindrome(text):
"""Return True or False if the text is a palindrome."""
text = remove_non_letters(text.lower())
# i => -(i + 1)
# 0 => -1
# 1 => -2
# 2 => -3
for idx in range(len(text) // 2):
# print(text, text[idx], text[-(idx + 1)])
if text[idx] != text[-(idx + 1)]:
return False
return True
def is_palindrome_recursive(text):
"""Return True or False if the text is a palindrome."""
text = remove_non_letters(text.lower())
# print(text)
if len(text) <= 1:
return True
if text[0] != text[-1]:
return False
return is_palindrome_recursive(text[1:-1])
def is_palindrome_easy(text):
"""Return True or False if the text is a palindrome."""
text = remove_non_letters(text.lower())
return text == text[::-1]
def remove_non_letters(text):
"""Strip out every character that is not a letter."""
all_letters = "abcdefghijklmnopqrstuvwxyz"
all_letters += all_letters.upper()
new_text = ""
for char in text:
if char in all_letters:
new_text += char
return new_text
text = input("Enter a possible palindrome: ")
if is_palindrome(text):
print("is a palindrome")
else:
print("is not a palindrome")
| true |
91fecc9f482dff85f49aa14c4e535c21e35ea0e1 | akb9115/python_training | /for_loop_concept.py | 328 | 4.34375 | 4 | #simple for loop
# for i in range(1,21):
# print(i)
# jumping for loop
# for i in range(0,21,2):
# print(i)
#
# 3 digit jump
# for i in range(3,31,3):
# print(i)
# ODD NUMBER
# for i in range(1,20,2):
# print(i)
# GOING REVERSE
# for i in range(10,1,-1):
# print(i)
for i in range(20,0,-2):
print(i)
| false |
56d0e64e869ee144aa9da1e353b82b4d1407eafd | aaronwu000/Learning-Python | /PYA02.py | 285 | 4.28125 | 4 | a = eval(input())
if a % 3 == 0 and a % 5 == 0:
print('{} is a multiple of 3 and 5.'.format(a))
elif a % 3 == 0:
print('{} is a multiple of 3.'.format(a))
elif a % 5 == 0:
print('{} is a multiple of 5.'.format(a))
else:
print('{} is not a multiple of 3 or 5'.format(a)) | false |
33dce1037477b584e890ef345c7158cb5c3fc44a | saltyscript/CTCI---Python | /unique_characters.py | 671 | 4.25 | 4 | # Implement an algorithm to determine if a string has all unique characters , without using additional data structures
def string_unique_characters(s):
s = s.lower()
if (len(s) < 127) :
bool_list = [False] * 127
for i in s:
value = ord(i)
if bool_list[value] is not True:
bool_list[value] = True
else:
return False
return True
else:
return False
if __name__ == "__main__" :
s = "Pradeep"
u ="abr"
t = "Abrac"
result = string_unique_characters(t)
if result:
print("Unique String")
else:
print("Not a unique String") | true |
bfac1fe120f90ea2419b185ea09d89d78f007fff | mrsmyth-git/programming-notes | /python/loops-iterables.py | 448 | 4.1875 | 4 | ## For loops
# Loops and data structures always start with 0
# This represents numbers in a range from and including 0 and 99
for x in range(100):
print('x')
# By using the break and continue statement
# you can "break" or "continue" the loop as you see fit
for x in range(100):
print('x')
if x == 50:
break
else:
continue
## While loops
condition = True
while condition:
print('This could be anything')
| true |
1ec570af280a7005d7ce088f25bb145c3a1dbffa | RutyRibeiro/CursoEmVideo-Python | /Exercícios/Desafio_37.py | 396 | 4.15625 | 4 | # Recebe número e converte para binario, hexadecimal ou octal
num=int(input('Digite um número: '))
resp=input('1 - Binário\n2 - Octal\n3 - Hexadecimal\nConverter para: ')
if resp == '1':
print('{} em binário equivale a: {:b}'.format(num,num))
elif resp == '2':
print('{} em octal equivale a: {:o}'.format(num,num))
else:
print('{} em hexadecimal equivale a: {:x}'.format(num,num)) | false |
a26e3fdd9e2b1b3fc933cd95ffa565686393f56d | RutyRibeiro/CursoEmVideo-Python | /Exercícios/Desafio_86.py | 317 | 4.21875 | 4 | # gera uma matriz 3x3 e a imprime corretamente, demonstrando linhas e colunas
from random import randint
matriz=[[],[],[]]
for i in range(0,3):
for j in range(0,3):
matriz[i].append(randint(10,20))
for i in range(0,3):
for j in range(0,3):
print(f'[ {matriz[i][j]} ] ',end='')
print('\n') | false |
19e7cdaccbed2a5b03d73c2eebaa45a3cb21656c | Ahmed-Abdelhak/Problem-Solving | /Problem Solving Techniques/Three Pointers/Third String Match Order.py | 1,119 | 4.375 | 4 | """
Write a program that receives three strings and tells if the third string is a result of mixing the two first strings together while keeping their respective order.
Ex.:
- abc def adbecf --> true
- abc def abdecf --> true
- abc def adbcfe --> false
adbefc --> false
# 1- third length is sum of the two, otherwise return False
# 2- three pointer i,j,k = 0
# 3- iterate over the third string
# 4- if i < len(arr1)) && arr3[k] == arr1[i] : i += 1
# 5- elif j < len(arr2) && j < i arr3[k] == arr2[i] : j += 1
# 5- else: return False
"""
def third_string_is_combination_in_order(str1,str2,str3):
if len(str3) != len(str1) + len(str2) or not str3:
return False
i = 0
j = 0
for k in range(len(str3)):
if i < len(str1) and str3[k] == str1[i] :
i += 1
elif j < len(str2) and str3[k] == str2[j] and j < i:
j += 1
else:
return False
return True
print(third_string_is_combination_in_order('abc', 'def', 'adbefc'))
| true |
d62e62a75aaeca379272fdff038c8d328425668b | jazzmanmike/python-intro | /solutions/1_5_extra.py | 1,123 | 4.28125 | 4 | seq = "MKALIVLGLVLLSVTVQGKVFERCELARTLKRLGMDGYRGISLANWMCLAKWESGYNTRATNYNAGDRSTDYGIFQINSRYWCNDGKTPGAVNACHLSCSALLQDNIADAVACAKRVVRDPQGIRAWVAWRNRCQNRDVRQYVQGCGV"
# unique amino acids in the sequence
unique_aa = set(list(seq))
# sorted amino acids
unique_aa_sorted = sorted(list(unique_aa))
print unique_aa_sorted
# storing the occurences in a dictionary
aa_counts = {}
aa_counts['A'] = seq.count('A')
aa_counts['C'] = seq.count('C')
aa_counts['D'] = seq.count('D')
# etc...
print aa_counts
# printing the results
print 'A has', aa_counts['A'], 'occurrence(s)'
print 'C has', aa_counts['C'], 'occurrence(s)'
print 'D has', aa_counts['D'], 'occurrence(s)'
print "etc..."
# To fully solve this problem, you'll need to learn about loops which are described
# in the next course section
# Add counts one by one to an empty dictionary
aa_counts = {}
for aa in set(seq):
aa_counts[aa] = seq.count(aa)
# Sort the keys of the dictionary in alphabetic order:
keys = aa_counts.keys()
keys.sort()
# Print the results by key sorted by alphabetic order
for aa in keys:
print "%s has %i occurrence(s)" % (aa, aa_counts[aa])
| false |
849830b1877597dfa993afc61330d802ad46dba4 | Iswaria-A/ishu | /python/ex27.py | 293 | 4.1875 | 4 | def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num=int(input("Enter number:"))
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
print("The Factorial of",num,"is",recur_factorial(num)) | false |
1132e3065e921cfb2e754e24a9350beae1590462 | comeeasy/study | /python/sw-academy-python1/use-function/function-prac6.py | 737 | 4.25 | 4 | ##################################################
'''
정렬된 숫자를 가진 리스트에서 특정 숫자를 찾는 함수를 정의하고,
이 함수를 이용해 임의의 숫자의 포함 여부를 출력하는 프로그램을 작성하십시오.
'''
##################################################
def is_num_exist(numlist, num) :
for val in numlist :
if num == val :
return True
return False
##################################################
num_list = [2, 4, 6, 8, 10]
num1, num2 = 5, 10
print(num_list)
print("{0} => {1}".format(num1, is_num_exist(num_list, num1)))
print("{0} => {1}".format(num2, is_num_exist(num_list, num2)))
################################################## | false |
09e22f54728277b0398d5b8d576b6e88fb13dc08 | oakeef/five-numbers | /Five Numbers.py | 1,304 | 4.53125 | 5 | __author__ = 'Evan'
#Enter 5 values
value1 = int(input("Enter value #1: "))
value2 = int(input("Enter value #2: "))
value3 = int(input("Enter value #3: "))
value4 = int(input("Enter value #4: "))
value5 = int(input("Enter value #5: "))
#Store 5 values in list
list = [value1, value2, value3, value4, value5]
print("----------------------------------------")
#display in reverse order
print("Numbers in reverse order")
list.reverse()
#the reverse function reverse the order of the list
#this loop prints the values in the list for the length of the list
for n in list:
print(n)
print("----------------------------------------")
#display average of all numbers
#calculates the average of all numbers in the list
average = sum(list)/len(list)
print("The average of the number is:",average)
print("----------------------------------------")
#display all numbers greater than average
print("Numbers that are greater than the average")
#create a new list that has all numbers from the other list that are larger than the average found earlier
#this uses a list comprehension
list2 = [n for n in list if n > average]
list2.sort()
#this loop prints the values in the new list of values higher than the average for the length of the list
for n in list2:
print(n) | true |
cbfc54247000b0df1acdaf832bccce9ab6ccce9a | AnshumanSharma05/Python | /io.py | 525 | 4.375 | 4 | """Imagine that you are in a desert and all of a sudden, a space shuttle lands
in front of you. An alien walks out of the space shuttle and greets you.
Write a Python program to welcome this friendly alien to our planet - Earth.
Get the name of the alien from the user and display the welcome message as
given in the sample output.
"""
"""Sample Input:
Enter the name:Naoto
Sample Output:
Hello Naoto! Welcome to our planet Earth.
"""
name=input("Enter the name")
print("Hello "+name+"! Welcome to out planet Earth.") | true |
66f72f5b949f86b6ea9d94793dda0dc5541da841 | Tracyliumm/data-wrangle-openstreetmaps-data_1 | /uniformcityname.py | 856 | 4.1875 | 4 | #!/usr/bin/env python
"""
Your task is as follows:
- To uniform the city name field by removing the redundant info (Oakland, Ca,),
uniform the upper case and lower case issue with only capitalizing
the first letter and correcting the misspelling issues
"""
def uniformaddress(city_name, node):
# remove any space before and after the city name and uniform the format by capitalize. If it contains multiple fields which is sperated by ".",
# only output the first part
city_name = city_name.strip().capitalize().split(".")[0]
# correct the mainly common typo
if city_name == "San Francicsco":
city_name = "San Francisco"
if "address" not in node:
node['address'] = {}
# add the uniform city name to the final address
node["address"]["city"] = city_name
return node
| true |
a89032b1b14e59af526f705f9fc58f92ac81a1d3 | Chiazam99/Learning-python | /range.py | 1,347 | 4.28125 | 4 | # Print range as a list
result = range(1,11)
print(result) # result will be range(1,11) because it has to be put in a list or set to show the values
# if not if the result should be in a new line per value, use a loop
list1 = (list(result))
print(list1)
range2 = range(11,21)
list2 = (list(range2))
print(list2)
combined_list = list1 + list2
print(combined_list)
combined_list2 = [*list1,*list2]
print(combined_list2)
list1.extend(list2)
print(list1)
# Combining dictionaries with operators
dict1 = {'shoe': 'heels'}
dict2 = {'hair':'cornrows'}
dict_combined = dict1|dict2
print(dict_combined)
dict1.update(dict2)
print(dict1)
for value in range(1,11):
print(value, 'interation')
range3 = range(6) # it will start from zero if the start figure isn't given
# range(3,9) ..... 3 is start and 9 is stop
print(list(range3))
# ITERATE A LOOP 5 TIMES
for i in range(5): # the loop starts from 0-4 (5 iterations )
print(i)
# range has a default increment value of 1 range(1,11,1)
# One can change the increment by cahnging the last one to whatever increment is desired.
range4 = range(0,30,5)
print(list(range4))
range5 = range(-10,12,2)
print(list(range5))
range6 = range(10,-10,-3)
print(list(range6))
# Task
print(list(range(3,31,3)))
# while loop
number = 1
while i in range(6):
print(i)
number = number +1
| true |
de9e13ee083a7d12fe794a6d0ee87699ac20404b | Chiazam99/Learning-python | /Textual_data_strings.py | 1,835 | 4.15625 | 4 | i = 'Chineye said: \'Who\'s there\''
print(i[-1])
j = 'Chiazam said: \'What\'s up with you girl?'
print(j[1])
k = "Chiazam is a spec"
print(k[7])
l = """Hello there
reallly!!!!!!!!!!!!!""" # 3 quotations is used for typing code in multiple lines
print(l[-1])
# Acessing characters from strings (Index is beside the print call in the above examples )
# For slicing, the 1st index is inclusive but the last index isn't. eg. below
m = 'ICE Commercial Power'
print(m[-1:-6]) # Neagtive indexing doesn't work for slicing a string probably because it will slice it backwards
print(m[0:3])
print(m[0:-1])
print(m[0:-5])
print(m[:-1]) # : - starts from first character
print(m[4:]) # continues to last character
#m[0] = 'E' # You can't change characters in a string using index but replace .... further down
print(m)
# Concatenation
n = 'Food'
o = 'is'
p = 'sweet.'
q = ' '
join = n+q+o+q+p
print(join)
join2 = n+q+'is'+q+p
print(join2)
r = p * 3
print(r)
for character in n:
print(character)
print(len(n))
print('d' in n) # d is in n(Food) [true]
print('do' in n) # do is not in the correct order in n(Food) [false]
print('od' in n) # od is in the correct order in n(Food) [true]
#String methods
s = 'Chiazam is a good girl.'
result = s.lower() # Change to lower case
print(result)
result2 = s.upper() # Change to upper case
print(result2)
result3 = s.find('l') # Change the index number for a character or word
print(result3)
result4 = s.find('girl') # For a word, it will give the index of the 1st letter.
print(result4)
result5 = s.replace('good', 'bad') # replacing a word
print(result5)
# Replacing a letter
m = 'ICE Commercial Power'
replace = m.replace('I','E')
print(replace)
quote = "Talk is cheap. Show me the code."
print('1.',quote[3])
print('2.',quote[-3])
print('3.',quote.replace('code','program'))
| true |
8a728c9710f8e1d31b9392d55c7ba6c7300c31ef | asweigart/PyTextCanvas | /tests/textStorageComparison.py | 2,379 | 4.1875 | 4 | """
This script tests the speed of different ways of storing a 2D field of text.
- list of lists, using [x][y] to access the 2D point
- one long list, using y*width+x to access the 2D point
- dictionary, using [(x, y)] to access the 2D point
These tests show that the list-of-lists approach is faster and uses much less memory.
"""
import cProfile
import random
WIDTH = 80
HEIGHT = 25
TRIALS = 1000000
def listOfListsStorage():
global storage
storage = [[None] * HEIGHT for i in range(WIDTH)]
cProfile.run('testListsOfListsStorage()')
def testListsOfListsStorage():
random.seed(42)
for t in range(TRIALS):
x, y = random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1)
storage[x][y] = 'X'
x = storage[x][y]
def dictionaryStorage():
global storage
storage = {}
cProfile.run('testDictionaryStorage()')
def testDictionaryStorage():
random.seed(42)
for t in range(TRIALS):
x, y = random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1)
storage[x, y] = 'X'
x = storage[x, y]
def oneLongList():
global storage
storage = [None] * (WIDTH * HEIGHT)
cProfile.run('testOneLongList()')
def testOneLongList():
random.seed(42)
for t in range(TRIALS):
x, y = random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1)
storage[(y * WIDTH) + x] = 'X'
x = storage[(y * WIDTH) + y]
print('SPEED TEST')
print('List of lists storage method:')
listOfListsStorage()
print('Dictionary storage method:')
dictionaryStorage()
print('One long list storage method:')
oneLongList()
# =========================================================
from pympler import asizeof
import random
width = 80
height = 25
grid = [[None] * height for i in range(width)]
d = {}
random.seed(42)
for i in range(800):
x = random.randint(0, width-1)
y = random.randint(0, height-1)
grid[x][y] = 'X'
d[x, y] = 'X'
print('MEMORY TEST')
print('List of list storage method (sparse):')
print(asizeof.asizeof(grid))
print('Dictionary storage method (sparse):')
print(asizeof.asizeof(d))
print()
for x in range(width):
for y in range(height):
grid[x][y] = 'X'
d[x, y] = 'X'
print('List of list storage method (completed):')
print(asizeof.asizeof(grid))
print('Dictionary storage method (completed):')
print(asizeof.asizeof(d))
| true |
23a86a7066d9fb1352887e6999ac918767930e65 | aakritsubedi/learning-python | /basics/05_tuples.py | 494 | 4.46875 | 4 | # Python Tuples
'''
Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
'''
# Create a tuple
fruits = ("apple", "banana", "cherry")
print(fruits)
# Get a value
print(fruits[1])
# Can't change value
# fruits[0] = 'Pears' TypeError: 'tuple' object does not support item assignment
numbers = tuple((1,2,3,4,5,6,7,8,9))
# Get Length
print(len(numbers))
# Delete a tuple
del numbers
| true |
b7277a862ab60c5f806ddb4e474dc5620e72524d | ElHa07/Python | /Curso Python/Aula05/Exercicios/Exercicios04.py | 550 | 4.1875 | 4 | #Exercício Python #04 - Custo da Viagem
#Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
# Primeiro Exemplo
distancia = float(input('Qual é a distancia da sua Viagem? '))
print('Você está prestes a começar uma viagem de {}Km' .format(distancia))
if distancia <= 200:
preço = distancia * 0.50
else:
preço = distancia * 0.45
print('È o preço da sua viagem sera de R${:.2f}'.format(preço))
#
#
# | false |
93b44cbf97bcd7dab61b50ec7b07d9680bab2c38 | ElHa07/Python | /Curso Python/Aula02/Exercicios/Exercicios04.py | 460 | 4.125 | 4 | # Exercício Python #004 - Conversor de Medidas.
# Exercício: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
medida = float(input('Uma distancia em metros: '))
mm = medida * 1000
cm = medida * 100
dm = medida * 10
dam = medida / 10
hm = medida / 100
km = medida / 1000
print('a media de {}m coresponde a \n{}km \n{}hm \n{}dam \n{:.0f}dm \n{:.0f}cm \n{:.0f}mm'.format(medida, km, hm, dam, dm, cm, mm)) | false |
2592cc96f20cd36862b2f2fa640d685616aeed7c | ElHa07/Python | /Curso Python/Aula07/Exercicios/Exercicios04.py | 345 | 4.15625 | 4 | # Exercício Python 04
# Exercício : Refaça o DESAFIO, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
print('-=' * 25)
tab = int(input('Digite um número para saber a sua Tabuada: '))
for c in range(0, 11):
print('{} x {:2} = {}'.format(tab,c,tab*c))
print('-=' * 25)
print('FIM!')
| false |
3c60a0ce25fe185dd94c9cdcecc1df8b7aba45e4 | ElHa07/Python | /Curso Python/Aula03/Exercicios/Exercicios04.py | 871 | 4.125 | 4 | # Exercício Python #004 - Sorteando um item na lista
# Exercício: Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
# Primeiro Exemplo
#import random
# n1 = str(input('Primeiro Aluno: '))
# n2 = str(input('Segundo Aluno: '))
# n3 = str(input('Terceiro Aluno: '))
# n4 = str(input('Quarto Aluno: '))
# lista = [n1, n2, n3, n4]
# escolhido = random.choice(lista)
# print('O Aluno escolhido foi {}'.format(escolhido))
# Segundo Exemplo
from random import choice
n1 = str(input('Primeiro Aluno: '))
n2 = str(input('Segundo Aluno: '))
n3 = str(input('Terceiro Aluno: '))
n4 = str(input('Quarto Aluno: '))
n5 = str(input('Quinto Aluno: '))
lista = [n1, n2, n3, n4,n5]
escolhido = choice(lista)
print('O Aluno escolhido foi {}'.format(escolhido)) | false |
1693f2c70e08095a87533cba6a7b84b699f0b07c | Lost-Accountant/csc148_2016_s | /Assignments/a1/customer.py | 2,936 | 4.34375 | 4 |
class Customer:
"""A Customer.
This class represents a customer in the simulation. Each customer will
enter the simulation at _entry_time, will wait at most _patience turns.
The restaurant need _prepare_time turns to prepare this customer order,
and will receive _profit if can serve this customer on time.
Your main task is to implement the remaining methods.
"""
# === Private Attributes ===
# :type _entry_time: int
# The turn time when a customer walks in
# :type _id: str
# A unique id that is used to easily identify that customer
# :type _profit: float
# The profit the restaurant will earn if served
# :type _prepare_time: int
# The number of turns needed to prepare the order
# :type _patience: int
# The maximum number of turns that this customer will wait for their order
def __init__(self, definition):
"""
Initialize a customer profile
:type definition: str
:param definition: a string with all information separated by tab
"""
info = definition.split()
# entry time is int
self._entry_time = int(info[0])
# id is str
self._id = info[1]
# profit is float
self._profit = float(info[2])
# rest are int
(self._prepare_time, self._patience) = \
(int(info[3]), int(info[4]))
def __eq__(self, other):
"""
Determine whether two customer profile are equal.
:param other: another customer profile
:type other: Customer
:rtype: bool
>>> a = Customer("3\t38623\t11\t8\t3")
>>> b = Customer("3\t38623\t11\t8\t3")
>>> a.__eq__(b)
True
>>> c = Customer("3\t38623\t12\t8\t5")
>>> a == c
False
"""
return type(self) == type(other) and \
(self._entry_time, self._id, self._profit, self._prepare_time, self._patience) == \
(other._entry_time, other._id, other._profit, other._prepare_time, other._patience)
def id(self):
"""
Return the id of this Customer self
:rtype: str
>>> a = Customer("3\t38623\t11\t8\t3")
>>> print(a.id())
38623
"""
return self._id
def entry_turn(self):
"""
Return the turn when the Customer self walks into the restaurant.
:rtype: int
>>> a = Customer("3\t38623\t11\t8\t3")
>>> print(a.entry_turn())
3
"""
return self._entry_time
def patience(self):
"""
Return the maximum number of turns the Customer self will wait for their order.
:rtype: int
>>> a = Customer("3\t38623\t11\t8\t3")
>>> print(a.patience())
3
"""
return self._patience
# TODO: Complete this part
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
456226f0d49df6c0993fa561d2049039baf525ec | Lost-Accountant/csc148_2016_s | /Lectures/week2/week2_point_solution.py | 2,452 | 4.5 | 4 | class Point:
"""
A point in 2D coordinate system
Public Attributes:
==================
:type x: int
the number of units to the right of origin
:type y: int
the number of units above origin
"""
def __init__(self,x,y):
"""
Construct a new 2D point self at coordinates x and y
:param x: number of units to the right of the origin
:type x: int
:param y: number of units above the origin
:type y: int
"""
self.x, self.y = x, y
def __eq__(self,other):
"""
Determine if point self is equivalent to point other
:param other: a 2D point
:type other: Point
:return: whether coordinates of point self is the same as of the other
:rtype: bool
>>> p1 = Point(6,7)
>>> p2 = Point(7,6)
>>> p3 = Point(6,7)
>>> p1 == p2
False
>>> p1 == p3
True
"""
return (type(self) == type(other) and
self.x == other.x and
self.y == other.y)
def __str__(self):
"""
Produce a user-friendly string representation of point self
:return: string representation of point self
:rtype: str
>>> p = Point(3,4)
>>> print(p)
(3,4)
"""
return "({},{})".format(self.x,self.y)
def distance_to_origin(self):
"""
Calculate distance from this point to origin
:return: square root of x^2 + y^2
:rtype: float
>>> p = Point(3, 4)
>>> p.distance_to_origin()
5.0
"""
return (self.x ** 2 + self.y ** 2) ** (1 / 2)
def __add__(self, other):
"""
Sum point self and the other
:param other: a 2D point
:type other: Point
:return: a new point whose coordinates are sum of coordinates of
point self and the other, respectively
:rtype: Point
>>> p1 = Point(3,5)
>>> p2 = Point(4,6)
>>> print(p1.__add__(p2))
(7,11)
>>> print(p1+p2)
(7,11)
"""
return Point(self.x + other.x, self.y + other.y)
if __name__ == "__main__":
import doctest
doctest.testmod()
p1 = Point(20,30)
p2 = Point(12,13)
p1 == p2
p1 + p2
p1.distance_to_origin()
x = Point(3,4)
print("x: ",x)
print("distance to origin: ",x.distance_to_origin())
| true |
89867636d4c887bdbd461b50d236e0e723d18630 | Lost-Accountant/csc148_2016_s | /Labs/lab6/nested_list_solution.py | 2,642 | 4.25 | 4 | # recursion exercises with nested lists
# we provide this helper function
def gather_lists(list_):
"""
Return the concatenation of the sublists of list_.
@param list[list] list_: list of sublists
@rtype: list
>>> list_ = [[1, 2], [3, 4]]
>>> gather_lists(list_)
[1, 2, 3, 4]
"""
# this is a case where list comprehension gets a bit unreadable
new_list = []
for sub in list_:
for element in sub:
new_list.append(element)
return new_list
# this is equivalent to
# sum(list_, [])
def list_all(obj):
"""
Return a list of all non-list elements in obj or obj's sublists, if obj
is a list. Otherwise, return a list containing obj.
:param obj: object to list
:type obj: list|object
:rtype: list
>>> obj = 17
>>> list_all(obj)
[17]
>>> obj = [1, 2, 3, 4]
>>> list_all(obj)
[1, 2, 3, 4]
>>> obj = [[1, 2, [3, 4], 5], 6]
>>> all([x in list_all(obj) for x in [1, 2, 3, 4, 5, 6]])
True
>>> all ([x in [1, 2, 3, 4, 5, 6] for x in list_all(obj)])
True
"""
if not isinstance(obj, list):
return [obj]
else:
return gather_lists([list_all(x) for x in obj])
def max_length(obj):
"""
Return the maximum length of obj or any of its sublists,
if obj is a list. Otherwise return 0.
:param obj: object to return length of
:type obj: object|list
:rtype: int
>>> max_length(17)
0
>>> max_length([1, 2, 3, 17])
4
>>> max_length([[1, 2, 3, 3], 4, [4, 5]])
4
"""
if not isinstance(obj, list):
return 0
else:
return max([max_length(x) for x in obj] + [len(obj)])
def list_over(obj, n):
"""
Return a list of strings of length greater than n in obj,
or sublists of obj, if obj is a list. Otherwise, if obj
is a string return a list containing obj if obj has
length greater than n, otherwise an empty list.
:param obj: possibly nested list of strings, or string
:type obj str|list
:param n: non-negative integer
:type n: int
:rtype: list[str]
>>> list_over("five", 3)
['five']
>>> list_over("five", 4)
[]
>>> L = list_over(["one", "two", "three", "four"], 3)
>>> all([x in L for x in ["three", "four"]])
True
>>> all([x in ["three", "four"] for x in L])
True
"""
if not isinstance(obj, list) and len(obj) > n:
return [obj]
elif not isinstance(obj, list):
return []
else:
return gather_lists([list_over(x, n) for x in obj])
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
d6ac004456a1a6773574abda563111473d96ebea | Lost-Accountant/csc148_2016_s | /Lectures/week6/tree_burst.py | 1,153 | 4.375 | 4 | import turtle
# constant for choosing color by number
COLOR = ("red", "green", "blue")
def tree_burst(level, base, turtle_):
"""
Draw a ternary tree of height level, edge length base, using turtle_.
:param level: how many levels of recursion to use
:type level: int
:param base: pixels to draw base shape
:type base: int
:param turtle_: drawing turtle
:type turtle_: Turtle
:rtype: None
"""
if level == 0:
pass
else:
turtle_list = [] # place to keep 3 turtles
for h in range(3):
# store new turtle
turtle_list.append(turtle_.clone())
# set colour, using weird spelling
turtle_list[h].color(COLOR[h])
# set direction
turtle_list[h].setheading(120 * h)
# draw a little
turtle_list[h].forward(base)
# 1/2 size version
tree_burst(level - 1, base / 2, turtle_list[h])
if __name__ == "__main__":
import time
T = turtle.Turtle()
T.color("red")
T.speed("slow")
# hide the tail...
T.hideturtle()
tree_burst(4, 128, T)
time.sleep(5)
| true |
477b509404ad54d12518f3eac0ce9d658c12c574 | VladyslavTokar/python | /HomeWork-Tech/1/1.1.py | 2,934 | 4.28125 | 4 | #!/usr/bin/env python3
#-*- coding: UTF-8 -*-
counter_total_answers = 0
counter_of_write_answers = 0
language = input('1. What language do we learn?: ')
if language == 'Python' or language == 'python':
print('Yes, we learn ' + language)
counter_of_write_answers += 1
else:
print('No, we learn ' + 'Python')
counter_total_answers +=1
type_after_division = input('2. What number type we get after division? (1-int; 2-float; 3-complex)? ')
if type_after_division == '2' or type_after_division == '2-float' or type_after_division == 'float':
print('Yes, it\'s float')
counter_of_write_answers += 1
else:
print('No, it\'s float')
counter_total_answers +=1
symbols_in_variables = input('3. What symbols can we use to name variables? (1-latin,all spec,numbers; 2-latin,only "_",numbers; 3-latin,numbers) ')
if symbols_in_variables == '2':
print('Yes')
counter_of_write_answers += 1
else:
print('No, we can use "latin,only "_",numbers"')
counter_total_answers +=1
name_len = input('4. What len of your name? ')
name = input('Please enter your name: ')
if int(name_len) == len(name):
print('Yes, your name {} has {} symbols'.format(name, name_len))
counter_of_write_answers += 1
else:
print('No, your name {} has {} symbols'.format(name, name_len))
counter_total_answers +=1
print('5. What booling type do you know: 1-True; 2-None; 3-False; 4-Var? (Need two answers)')
first_answer = input('Enter first answer: ')
second_answer = input('Enter second answer: ')
if first_answer == '1' and second_answer == '3':
print('Yes')
counter_of_write_answers += 1
else:
print('No, There are "True" and "False"')
counter_total_answers +=1
coding_utf8 = input('6. Does python understand UTF-8 coding? (yes/no) ')
if coding_utf8 == 'yes' or coding_utf8 == 'y':
print(True)
counter_of_write_answers += 1
else:
print(False)
counter_total_answers +=1
print('7. Enter two numbers for check human comparison:')
number_one = input('Number One: ')
number_two = input('Number Two: ')
user_answer = input('Is {} greater then {}? (yes/no): '.format(number_one, number_two))
comparison = int(number_one) > int(number_two)
if user_answer == 'yes':
if comparison == bool(True):
print('Correct')
counter_of_write_answers += 1
else:
print('Not correct')
elif user_answer == 'no':
if comparison == bool(False):
print('Correct')
counter_of_write_answers += 1
else:
print('Not correct')
counter_total_answers +=1
print('8. Has your name a some letter?')
letter = input('Enter some letter: ')
name = input('Enter your name: ')
if letter in name:
print(letter + 'is in your name')
counter_of_write_answers += 1
else:
print('There is no letter ' + letter + ' in your name')
counter_total_answers +=1
print('Total answers is: ' + str(counter_total_answers))
print('Correct answers is: ' + str(counter_of_write_answers)) | false |
b7668af27a7c841b6f06ab16663d626ff82885a7 | deepakbairagi/Python3Challenges | /challenge5.py | 353 | 4.1875 | 4 | #!/usr/bin/python3
import time
name=input("Please Enter Your Name: \n")
currtime=int(time.strftime("%H"))
if currtime>5 and currtime<11:
print("Good Morning "+name)
elif currtime>=11 and currtime<16:
print("Good Afternoon "+name)
elif currtime>=16 and currtime<21:
print("Good Evening "+name)
else:
print("Good Night "+name)
| false |
09291e397b4cf3fb5acbed4bd47c6e1a6a373ac2 | pengfei99/PyTorchTuto | /basics/source/FashionMNISTImageClassifier.py | 2,949 | 4.125 | 4 | from torch import nn
""" A classifier model for Fashion MNIST Image
We creat this module by sub classing nn.Module, a Module can contain other modules
The common use modules:
- nn.Flatten: The nn.Flatten layer is commonly used to convert multi-dimension input tensor to a one-dimension tensor.
As a result, it's often used as input layer. In this example, the flatten layer transform a 2D 28x28
image into a contiguous array of 784 pixel values.
- nn.Linear: The linear layer is a module that applies a linear transformation on the input by using the stored
weights and biases of the layer.
- nn.ReLU: This module use a Non-linear activations which can create the complex mappings between the model's inputs
and outputs. They are applied after linear transformations to introduce non-linearity, helping neural
networks learn a wide variety of phenomena.
- nn.Sequential: nn.Sequential is an ordered container of modules. The data is passed through all the modules in the
same order as defined. You can use sequential containers to put together a network of modules.
- nn.Softmax: This module is used to normalize raw values in [-infty, infty] to values in [0, 1]. As a result, this
module is often used as output layer for multiple class classification. The outputs of this layer
represents the model's predicted probabilities for each class. The 'dim' parameter indicates the
dimension along which the values must sum to 1. It means the output possibility values for each class
are dependent of this dimension, and the sum is 1. For example:
input values: -0.5, 1.2, -0.1, 2.4
SoftMax output values: 0.04, 0.21, 0.05, 0.70
The sum is 1
- nn.Sigmoid: This module also normalize raw values in [-infty, infty] to values in [0, 1] or [-1,1]. This module is
often used as output layer for binary class classification. The output possibility values for each class
are independent, and the sum can be any value. For example:
input value: -0.5, 1.2, -0.1, 2.4
Sigmoid output values: 0.37, 0.77, 0.48, 0.91
The sum is 2.53
In this model, we use nn.ReLU between our linear layers, but there's other activations to introduce non-linearity in
your model.
"""
class FashionMNISTImageClassifier(nn.Module):
def __init__(self):
super(FashionMNISTImageClassifier, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
| true |
75d68ccca8a496fe68da4f8250e5d7c1a6976371 | patcharinka/15016406 | /Exercises/4.14.py | 335 | 4.375 | 4 | """
File: octaltodecimal.py
Project 4.14
Converts a string of octal digits to a decimal integer.
"""
ostring = input("Enter a string of octal digits: ")
decimal = 0
exponent = len(ostring) - 1
for digit in ostring:
decimal = decimal + int(digit) * 8 ** exponent
exponent = exponent - 1
print("The integer value is", decimal)
| true |
6f799e5e3975bdf872b1dbf9594e01d2e89d586d | patcharinka/15016406 | /Exercises/3.2.py | 621 | 4.5 | 4 | """
Program: right.py
Project 3.2
Determine whether or not three input sides compose a
right triangle.
"""
# Request the inputs
side1 = int(input("Enter the first side: "))
side2 = int(input("Enter the second side: "))
side3 = int(input("Enter the third side: "))
# Compute the squares
square1 = side1 ** 2
square2 = side2 ** 2
square3 = side3 ** 2
# Determine the result and display it
if square1 + square2 == square3 or \
square2 + square3 == square1 or \
square1 + square3 == square2:
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
| true |
a49aef1674e66e02628300e5a8dfece490f92966 | minhaz1217/python-workshop-preparation | /01. D. Outputs.py | 556 | 4.3125 | 4 | #different ways to print
print("HELLO WORLD")
print("Hello \n\nWorld")
print("Hello \t\t World")
print("Printing without the auto end: ")
print("Hello", end="")
print(" World")
print("Different ways to print concat")
name = "World"
print("Hello", name)
print("Hello {}".format(name))
print("Hello %s" %name)
a = 5
print("%d" %a)
b = 14.123123123123
print("%f" % b)
b = 15.312321231
print("Printf Style: %d %.3f" % (a, b))
b = 10
c = 20
print(a,b,c)
print("{} {} {}".format(a,b,c))
print("{0} {1} {2}".format(a,b,c))
print("{2} {1} {0}".format(a,b,c))
| false |
351893d866b0e1f9b1c3805d1c0869f1cb74fda7 | mmoscovics/holbertonschool-higher_level_programming | /0x05-python-exceptions/0-safe_print_list.py | 359 | 4.125 | 4 | #!/usr/bin/python3
""" Function that prints x elements of a list with exception handling. """
def safe_print_list(my_list=[], x=0):
""" Prints x elements of a list with exception handling. """
for i in range(0, x):
try:
print(my_list[i], end="")
except:
print()
return i
print()
return x
| true |
a2c522a937565795e1b143281d9d6879fe1e1991 | mmoscovics/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 298 | 4.1875 | 4 | #!/usr/bin/python3
""" Returns new dictionary with all values multiplied by 2 """
def multiply_by_2(a_dictionary):
""" Returns new dictionary with values multiplied by 2 """
new_dict = {}
for key, value in a_dictionary.items():
new_dict[key] = value * 2
return new_dict
| true |
9e4389b99cc00dfb84719dacc6061981de26c5ec | mmoscovics/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 334 | 4.1875 | 4 | #!/usr/bin/python3
""" Function that writes to a text file
Returns the number of characters written.
"""
def write_file(filename="", text=""):
""" Writes a string to a text file
Returns number of characters written. """
if filename is '':
return
with open(filename, "w+") as f:
return f.write(text)
| true |
997540d45f6df81faf75cb39a8ce48b629f50492 | habibor144369/python-all-data-structure | /dictionary-5.py | 730 | 4.15625 | 4 | # this is dictionary---
student_data = {'name': 'Habibor Rahaman', 'id': '144369', 'phone': '01768280237', 'high': 5.6, 'occupation': 'Student', 'address': 'Dhaka-mohammodpur-1207'}
student_data ['color'] = 'cyan' # new keys and value add in dictionary--
print(student_data)
# empty dictionary defined and insert to keys and values---
student = {}
student ['name'] = 'Habibor Rahaman'
student['id'] = '14'
student ['address'] = 'Dhaka, Bangladesh'
student ['occupation'] = 'student'
print(student)
# we are want to every things set to key in a dictionary not noa a allowed list or set below example here---
example = {}
example [(2, 3, 4)] = 10101
li = (203034)
example [li] = 10101
lit = 'hello'
example [lit] = 'programmer'
print(example)
| false |
32e9298ce783df2a56177e4b73b27a0f7adb3b98 | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_01/fabio01_10_quociente-resto.py | 332 | 4.15625 | 4 | # entrada
valor_numero = int(input('Digite o dois numeros: '))
# processamento
numero1 = valor_numero // 10
numero2 = valor_numero % 10
quociente = numero1 // numero2
resto = numero1 - (quociente*numero2)
# saida
print('O quociente da divisão dos dois numeros é: {} e \
o resto {}'.format(quociente,resto))
| false |
77d23c5ccea6139883b26cc069a57f883d29749b | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_02b-Revisao_Condicional/fabio_02b_08_desconto_ir.py | 2,783 | 4.15625 | 4 | def main():
valor_hora = float(input('Digite o valor da hora trabalhada: '))
quant_hora = int(input('Digite a quantidade de horas trabalhadas: '))
salario_bruto = valor_hora * quant_hora
valor_inss = salario_bruto * 0.1
valor_fgts = salario_bruto * 0.11
# Isento
if salario_bruto <= 900:
salario_liquido = salario_bruto - valor_inss
total_descontos = valor_inss
print('\nSalario Bruto:({}*{}) :R${:.2f}\
\n(-)IR(0%) :R$0.00\
\n(-)INSS(10%) :R${:.2f}\
\nFGTS(11%) :R${:.2f}\
\nTotal de descontos :R${:.2f}\
\nSalario Liquido :R${:.2f}\n'\
.format(valor_hora,quant_hora,salario_bruto,valor_inss,\
valor_fgts,total_descontos,salario_liquido))
# 5% de desconto
elif 900 < salario_bruto <= 1500:
valor_ir = salario_bruto * 0.05
salario_liquido = salario_bruto - valor_inss - valor_ir
total_descontos = valor_inss + valor_ir
print('\nSalario Bruto:({}*{}) :R${:.2f}\
\n(-)IR(5%) :R${:.2f}\
\n(-)INSS(10%) :R${:.2f}\
\nFGTS(11%) :R${:.2f}\
\nTotal de descontos :R${:.2f}\
\nSalario Liquido :R${:.2f}\n'\
.format(valor_hora,quant_hora,salario_bruto,valor_ir,valor_inss,\
valor_fgts,total_descontos,salario_liquido))
# 10% de desconto
elif 1500 < salario_bruto <= 2500:
valor_ir = salario_bruto * 0.1
salario_liquido = salario_bruto - valor_inss - valor_ir
total_descontos = valor_inss + valor_ir
print('\nSalario Bruto:({}*{}) :R${:.2f}\
\n(-)IR(10%) :R${:.2f}\
\n(-)INSS(10%) :R${:.2f}\
\nFGTS(11%) :R${:.2f}\
\nTotal de descontos :R${:.2f}\
\nSalario Liquido :R${:.2f}\n'\
.format(valor_hora,quant_hora,salario_bruto,valor_ir,valor_inss,\
valor_fgts,total_descontos,salario_liquido))
# 20% de desconto
else:
valor_ir = salario_bruto * 0.20
salario_liquido = salario_bruto - valor_inss - valor_ir
total_descontos = valor_inss + valor_ir
print('\nSalario Bruto:({}*{}) :R${:.2f}\
\n(-)IR(20%) :R${:.2f}\
\n(-)INSS(10%) :R${:.2f}\
\nFGTS(11%) :R${:.2f}\
\nTotal de descontos :R${:.2f}\
\nSalario Liquido :R${:.2f}\n'\
.format(valor_hora,quant_hora,salario_bruto,valor_ir,valor_inss,\
valor_fgts,total_descontos,salario_liquido))
if __name__ == '__main__':
main()
| false |
745910b60977c84053e59304ac69f7e224a25e89 | Kushal6070/FutureCalendar | /calendarMaker.py | 2,590 | 4.15625 | 4 | #import datetime module
import datetime
#Set the constants
MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December')
DAYS = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday')
#ask user for the year by looping over
while True:
print('Please enter a year: ')
response = input('> ')
if response.isdecimal() and 1<=len(response)<=4 :
year = int(response)
break
print('Please enter a year like 2023:')
continue
#ask user for the month
while True:
print('Please enter month for the calendar, 1-12: ')
response = input('>')
if not response.isdecimal():
print('Enter a numeric month, like 4 for April.')
continue
month = int(response)
if 1<=month<=12:
break
print('Please enter a number from 1 to 12.')
#print the calendar intro
print('Welcome to the calendar maker by Kushal. Please enter the year and month you want to go to.')
#get calendar function
def getCalendar(year, month):
#caltext will contain the string of the calendar
calText = ''
#Add the month and year at the top of calendar
calText += (' '*34)+ MONTHS[month - 1]+ ' '+str(year)+'\n'
#Add the days of the week to the calendar
calText += '...Sunday.....Monday....Tuesday...Wednesday...Thursday....Friday....Saturday..\n'
#The horizontal line string that seperate weeks:
weekSeparator = ('+----------' * 7) + '+\n'
#Days seperator with blank rows
blankRow = ('| ' * 7 + '|\n')
#Getting the first date of the month with datetime module
currentDate = datetime.date(year, month, 1)
#Roll back currentdate until it is Sunday.
#weekday() returns 6 for Sunday, not 0
while currentDate.weekday() != 6:
currentDate -= datetime.timedelta(days=1)
#loop over each week in month
while True:
calText += weekSeparator
#dayNumberRow is the row with the day number labels:
dayNumberRow = ''
for i in range(7):
dayNumberLabel = str(currentDate.day).rjust(2)
dayNumberRow += '|' + dayNumberLabel + (''*8)
currentDate += datetime.timedelta(days=1) #Goes to next day
dayNumberRow += '|\n'
#check if we're done with the month
if currentDate.month != month:
break
#Add horizontal line at the bottom of the calendar
calText += weekSeparator
return calText
calText = getCalendar(year, month)
print(calText) #Display the calendar
| true |
924a2cc3754a840a9e4dedebdfb93d61aa6c4642 | anywayalive/Barloga | /СodeWars/Will there be enough space.py | 440 | 4.1875 | 4 | # You have to write a function that accepts three parameters:
# cap is the amount of people the bus can hold excluding the driver.
# on is the number of people on the bus.
# wait is the number of people waiting to get on to the bus.
# If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.
def enough(cap, on, wait):
if cap >= on + wait: return 0
else: return abs(cap - (on + wait)) | true |
c5afe3bd49957ffa58bff007f20f51cbf13871d7 | jordanchenml/leetcode_python | /0088_MergeSortedArray.py | 999 | 4.34375 | 4 | '''
-The number of elements initialized in nums1 and nums2 are m and n respectively.
-You may assume that nums1 has enough space (size that is greater or equal to m + n)
to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
'''
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2[:n]
nums1.sort()
class Solution1:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
while n > 0:
if m <= 0 or nums2[n - 1] >= nums1[m - 1]:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
else:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
| true |
e81de12b2c1f96151ffa01fe2d177bc7b662f2d0 | jordanchenml/leetcode_python | /0069_Sqrt.py | 1,109 | 4.1875 | 4 | '''
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
# Since the return type is an integer, the decimal digits are truncated and
only the integer part of the result is returned.
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
'''
import math
class Solution:
def mySqrt(self, x: int) -> int:
return int(math.sqrt(x))
class Solution1:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
for i in range(x + 1):
if i * i > x:
return i - 1
class Solution2:
def mySqrt(self, x: int) -> int:
r = x
while r * r > x:
r = int(r - (r * r - x) / (2 * r))
return r
class Solution3:
def mySqrt(self, x: int) -> int:
l = 0
h = x
while l <= h:
mid = (l + h) / 2
if mid ** 2 <= x:
l = mid + 1
else:
h = mid - 1
return int(l - 1)
a = Solution3()
print(a.mySqrt(90))
| true |
e887da11253860ddd91c380dcf0b6bc986194f78 | ojuulian/python | /recursividad.py | 636 | 4.1875 | 4 | # Importamos el modulo sys que nos permitira modificar la recursion
import sys
def factorial(n):
"""Calcula el factorial de n
n int > 0
returns n!
"""
print(n)
if n == 1:
return 1
return n * factorial(n - 1)
n = int(input('Escribe un entero: '))
# Imprimimos el limite de recursion que trae python por defecto con la funcion sys.getrecursionlimit() que trae el modulo sys.
print(sys.getrecursionlimit())
# Modificamos el limite de recursion a 2000 con la funcion sys.setrecursionlimit() que trae el modulo sys
sys.setrecursionlimit(2000)
print(factorial(n)) | false |
228ab54830523e08e68578cb5a8e28451f66c403 | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 3/1 - Tuplas/DESAFIO 072 - Número extenso.py | 775 | 4.1875 | 4 | """Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso."""
extenso = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',
'quatorze','quinze','dezesseis','dezesete','dezoito','dezenove','vinte')
while True:
while True:
num = int(input('Digite um número entre 0 e 20: '))
if 0 <= num <= 20:
break
print('Tente novamente. ', end='')
print(f'Você digitoou o número {extenso[num]}')
resp = input('Deseja continuar? [S/N] -> ').upper().strip()[0]
if resp in 'N':
break
print('Programa finalizado!')
| false |
fa516a2d7de1ff3f090cc5162e24084b487a9aa9 | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 2/Repetições em Python (while)/Laços (while) com interrupções/DESAFIO 067 - Tabuada v3.0.py | 663 | 4.125 | 4 | """Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário.
O programa será interrompido quando o número solicitado for negativo"""
print('=-'*10, '|', 'TABUADA v3.0', '|', '-='*10)
n = int(input('Digite um número do qual deseje ver sua tabuada: '))
cont = 1
while True:
print(f'{n} x {cont} = {n*cont}')
cont += 1
if cont == 11:
print('=-'*31)
n = int(input('Deseja ver qual número agora? (um número negativo, fecha o app)'
'\nDigite aqui -> '))
cont = 0
print('=-'*30)
if n < 0:
break
print('FIM DO PROGRAMA!')
| false |
d6f2ecf0f4b946bb60ea8f0d5f66f1a22de5e076 | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 3/3 - Dicionários/DESAFIO 095 - Aprimorando os Dicionários.py | 1,674 | 4.1875 | 4 | """Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de visualização
de detalhes do aproveitamento de cada jogador."""
jogador = dict()
partidas_l = []
time = []
gol = partida_v = totgols = 0
while True:
jogador.clear()
jogador['nome'] = input('Nome: ').capitalize()
partida_v = int(input('Quantidade de partidas: '))
partidas_l.clear()
for c in range(0, partida_v):
gol = int(input(f'Quantos gols {jogador["nome"]} fez na {c+1}ª partida: '))
partidas_l.append(gol)
jogador['partidas'] = partidas_l[:]
jogador['total'] = sum(jogador['partidas'])
time.append(jogador.copy())
resp = input('Quer continuar?[S/N] -> ').upper()[0]
while resp not in 'SN':
resp = input('\033[:31mCaractere inválido\033[m. Quer continuar?[S/N] -> ').upper()[0]
if resp == 'N':
break
print('-='*20)
print('='*40)
print('cod ', end='')
for i in jogador.keys():
print(f'{i:<15}', end='')
print()
print('='*40)
for k, v in enumerate(time):
print(f'{k:>3} ', end='')
for d in v.values():
print(f'{str(d):<15}', end='')
print()
print('='*40)
while True:
busca = int(input('Mostrar dados de qual jogador? (999 para parar) -> '))
if busca == 999:
break
if busca >= len(time):
print(f'!ERRO. Não existe jogador com código {busca}')
else:
print(f' -- LEVANTAMENTO DO JOGADOR {time[busca]["nome"]}:')
for i, g in enumerate(time[busca]['partidas']):
print(f' No jogo {i+1} fez {g} gols.')
print(f' Totalizando {time[busca]["total"]}.')
print('='*40)
print('='*40)
print('FIM')
| false |
03acf0aaa45b8e681baa68f634ad9c5a33bc287b | ChuhanXu/LeetCode | /Dynamic Programming/waterArea.py | 1,635 | 4.25 | 4 |
# how to find the height of tallest pillar to the left:
# 1.iterate from the first value and record every height
# 2.initialize the max array and leftMax,because the leftmax of the first value will be 0
# 3.update the leftMax by comparing with every height and got the bigger one
# 4.if we want to use one array to replace three array,we can adjust our order of operation,because you know we already konw that the rightmax value of
# the final index in the input array is 0, there is nothing after the final index.
# 5.we can calculate the amount of water at the final index first and then update our rightmax array
def waterArea(heights):
maxes = [0 for x in heights]
leftMax = 0
for i in range(len(heights)):
height = heights[i]
maxes[i]=leftMax
leftMax = max(leftMax,height)
rightMax = 0
for i in reversed(range(len(heights))):
height = heights[i]
# 这个时候的maxes[i]就是对应的左边最大pillar
minHeight = min(rightMax,maxes[i])
if height < minHeight:
maxes[i]=minHeight - height
else:
maxes[i]=0
# 在更换rightMax的值,可以用一个数组完成三个数组的事情,1,当前位置的左边最大pillars,2,当前位置的右边最大pillar 3,当前位置左右pillars的较小的那个pillar减去height
rightMax = max(rightMax,height)
return sum(maxes)
print(waterArea([0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3]))
# leftmax [0, 0, 8, 8, 8, 8, 8, 8, 10,10,10,10,3,0]
# water [ ,0 ] | true |
2c0a5f2259b0384ed0194a7bfca9601927f86110 | pkumar2015181/Aritificial-Intelligence-Assignments | /Assignment-2/Code/N-queens problem/hill_climbing.py | 1,631 | 4.25 | 4 | """
IMPORT REQUIRED LIBRARIES
"""
def hill_climbing(problem):
# To return comma sepated tuple of positions on queens
#Example: for 4 queens your algorithm returns (2,0,1,3)
"""
YOUR CODE HERE
"""
j = 5
while j > 0:
j = j-1
start = problem.initial()
val_start = problem.value(start)
print("Iteration = ",5-j)
print("Initial position = ", start, " with value = ", val_start)
goal_found = False
max_state = start
max_val = val_start
flag = 1
while flag:
flag = 0
# print("\nState = ", max_state)
# print("State val = ", max_val)
ch = problem.children(max_state)
# print("\nchildren = ", ch)
for i in ch:
val_i = problem.value(i)
# print("state = ", i, ", val = ", val_i)
if val_i > max_val:
max_val = val_i
max_state = i
flag = 1
if problem.goal_test(max_state) == True:
goal_found = True
print("Max. state = ", max_state, " with value = ", max_val)
if goal_found == True:
print("GOAL IS FOUND")
else:
print("GOAL IS NOT FOUND")
if j > 1:
print("\n")
# print("children = ",ch)
# val = problem.value(start)
# print("Value = ", val)
# goal = problem.goal_test(start)
# print("goal = ", goal)
# rc = problem.random_child(start)
# print("RC = ", rc)
return max_state
| true |
1389f0409ef476e51319b9d7ada6125578bb7f1a | yyashpatell/Yash_Patel_8736546_assignment1 | /it support (bilkhu)/exersice week 3.py | 276 | 4.125 | 4 | celsius = 0.0
celsius = float(input("enter your temperature in degree celsius."))
defreeFahrenheit = ((celsius * 9/5) + 32)
stringCelsius = (celsius)
print("the value you entered was " + stringCelsius + " degreed celsius, which is " + degreeFarenheit + "degrees fahrenheit ") | true |
815f3eb58f272501d0674a5dd4284c9896792b96 | Prajwalprakash3722/python-programs | /bmi.py | 1,156 | 4.28125 | 4 | # program to calculate bmi(Body Mass Index)
is_weight = int(input("What is your weight? "))
is_unit = input("(K)gs, (P)ounds ")
is_height = int(input("What is your height? "))
is_unita = input("(C)m, (I)nch, (F)t ")
mass = 1
# checking the weight is it is in pounds then converting it to kg
if is_unit.lower() == 'k':
mass = int(is_weight)
elif is_unit.lower() == 'p':
mass = int(is_weight) * 0.4535
else:
print(f"Type only given Letters, you have typed {is_unit.upper()} instead of K or P")
meter = 1
# Checking the height and converting to Metter units
if is_unita.lower() == 'c':
meter = int(is_height) * 0.01
elif is_unita.lower() == 'i':
meter = int(is_height) * 0.0254
elif is_unita.lower() == 'f':
meter = int(is_height) * 0.3047999
else:
print(f"Type only given Letters, you have typed {is_unita.upper()} instead of C or I or F")
# Calculating the BMI
h = meter * meter
bmi = mass / h
if bmi < 18.5:
type = "Under weight"
elif bmi>=18.5 and bmi<=24.9:
type = "Normal"
elif bmi >= 25 and bmi <= 29.9:
type = "Over-weight"
else:
type = "Obese"
print(f"Your BMI(Body Mass Index) is {bmi}, You are {type}")
| false |
6ec6b3c5e831bd4536a4dc6f4268604542fda643 | siddharthaarora/kcah | /private/dev/ChallengePy/binarysearchtree2.py | 1,473 | 4.125 | 4 | import queue
class Node:
def __init__(self):
self.value = None
self.left = None
self.right = None
self.parent = None
class Tree:
def __init__(self):
self.root = None
def CreateBSTOfSize(n):
a = list(range(1,n))
return CreateBSTFromSortedArray(a)
def CreateBSTFromSortedArray(a):
bst = Tree()
if (a != None or len(a) != 0):
start = 0
end = len(a) - 1
bst.root = CreateBSTInternal(a, start, end, bst.root)
return bst
return bst
def CreateBSTInternal(a, start, end, parent):
if (end < start):
return None
node = Node()
node.parent = parent
node.value = a[(end + start) // 2]
node.left = CreateBSTInternal(a, start, (start + end) // 2 - 1, node)
node.right = CreateBSTInternal(a, (start + end) // 2 + 1, end, node)
return node
def TraverseBST(t):
if (t == None):
print("Tree is empty!")
q = queue.Queue()
q.put(t.root)
while(q.empty() == False):
n = q.get()
print(n.value, end = ": ")
if (n.parent != None):
print("Parent-->", n.parent.value, end=" ")
if (n.left != None):
q.put(n.left)
print("Left-->", n.left.value, end=" ")
if (n.right != None):
q.put(n.right)
print("Right-->", n.right.value, end = " ")
print()
# driver code
def main():
bst = CreateBSTOfSize(10)
TraverseBST(bst)
#main() | true |
bb3b4bb86d6998423954202204d15968d428080d | siddharthaarora/kcah | /private/dev/ChallengePy/palindromePermutation.py | 2,153 | 4.15625 | 4 | # Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards. A permutation
# is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
# EXAMPLE
# Input: Tact Coa
# Output: True (permutations: "taco cat", "atco e t a " , etc.)
# if len(s) is even, then each char should appear twice. Else, one char should appear once.
# Sol 1 - use hash table to store the chars and counts, then check if each char has count of 2 and only char has count of 1; Time - O(n); Space - O(2n)
# Sol 2 - use a bit vector to basically implement Sol 1 with less space
# Sol 3 - Sol 1 and 2 are crap. The most elegant solution is to have a bit vector of length 26 (a-z) and then set the bit for each char.
# At the end, check that there is one bit that is set or all zeros depending on length of the input.
import BinaryOperations
def PalindromePermutation(s):
v = [0] * 26
for i in range(0, len(s)):
if (s[i] == " "):
continue
idx = ord(s[i]) - 97
if (v[idx] == 0):
v[idx] = 1
else:
v[idx] = 0
count1s = 0
print(v)
for i in range(0, 26):
if (v[i] == 1):
count1s = count1s + 1
if (count1s == 0 or count1s == 1):
print(s, "is a permutation of a palindrome!")
else:
print(s, "is NOT a permutation of a palindrome!")
def PalindromePermutationUsingBitManipulation(s):
v = 0
for i in range(0, len(s)):
if s[i] == " ":
continue
v = v ^ (1 << ord(s[i]) - 97)
count1s = 0
for i in range (0, 26):
count1s = count1s + (1 & (v >> 1))
v = v >> 1
if (count1s == 0 or count1s == 1):
print(s, "is a permutation of a palindrome!")
else:
print(s, "is NOT a permutation of a palindrome!")
PalindromePermutationUsingBitManipulation("tacz cat")
PalindromePermutationUsingBitManipulation("sss x sss")
PalindromePermutationUsingBitManipulation("atco c t a")
PalindromePermutationUsingBitManipulation("atco e t a")
| true |
44a5f8ce7e9bacaac23c47ed3f67ba7737d1bcbe | siddharthaarora/kcah | /private/python/sumofpositivenumbers.py | 542 | 4.5 | 4 | # Allow the user to enter a sequence of non-negative numbers.
# The user ends the list with a negative number. At the end the
# sum of the non-negative numbers entered is displayed.
# The program prints zero if the user provides no non-negative numbers.
def sumofpositivenumbers():
number = 0
sum = 0
while 5 == 5:
sum = sum + number
print('sum: ', sum, 'number: ', number)
number = eval(input('enter a number'))
print('sum of non-negative numbers is: ', sum)
sumofpositivenumbers()
| true |
e4ef72d0618f3c4d9f8a8abdbf24a903478d92fe | Max-Peterson/Project-Euler | /Project Euler/Complete/002_Even_fibonacci_numbers.py | 653 | 4.1875 | 4 | #Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
#we know simply from the example here that the 2nd term and every 3rd term thereafter will be even
x=0
array = [1,2]
sum1=2
while x < 4000000:
x=array[-1]+array[-2]
array.append (array[-1]+array[-2])
if x % 2 == 0:
sum1 += x
print("The sum of the even valued terms in the Fibonacci sequence is",sum1)
| true |
479dafecdf2b9c78e31b7c4884f306de6bf7435d | it-consult-cloud/Python | /Lesson-002/WorkHome-VN-L02-0401.py | 1,310 | 4.28125 | 4 | # Создать программу которая будет конвертировать значение
# (указанное в метрах и введенное с клавиатуры) в указанную
# пользователем единицу (пользователь вводит это значение с
# клавиатуры, это могут быть мм, см, км)
count = float(input('Введіть число в метрах до конвертування в інші одиниці виміру: '))
EA = input("Введіть код одиниці виміру (1-мм., 2-см., 3-км.): ")
if EA == '1':
print("Ви вибрали одиницю розрахунку міліметри")
# c= float(count * 1000)
print(f'В міліметрах це буде: ', (count * 1000), "мм.")
elif EA == '2':
print("Ви вибрали одиницю розрахунку сантіметри")
# c= float(count * 1000)
print(f'В сантіметрах це буде: ', (count * 100), "см.")
elif EA == '3':
print("Ви вибрали одиницю розрахунку кілометри")
# c= float(count * 1000)
print(f'В кілометрах це буде: ', (count / 1000), "км.")
else:
print("Ошибка ввода") | false |
e4c4dc6de7e6b25eef3e4a3494fed110c5c548c4 | Nazdorovye/VeAPython | /2020_lecture_03_tasks/task03.py | 673 | 4.5 | 4 | # Write a script that determines whether a triangle can be created from user-entered edge
# lengths. If it can, calculate and output the area and perimeter of this triangle.
# Condition for creating a triangle: the sum of any two sides is greater than the third side.
a = float(input("Type the length for the edge a -> "))
b = float(input("Type the length for the edge b -> "))
c = float(input("Type the length for the edge c -> "))
if a + b > c and b + c > a and c + a > b:
print("Area of specified triangle is:", (a + b + c) / 2)
print("Perimeter of the triangle is:", a + b + c)
else:
print("Triangle cannot be built with a=%.2f b=%.2f c=%.2f" % (a, b, c)) | true |
0c10da855b3af237bd734fd0a02d06b3d7ab5677 | Nazdorovye/VeAPython | /2020_lecture_02_tasks/task04.py | 359 | 4.53125 | 5 | # Write a script, that calculates and outputs volume and surface area for a sphere with R-radius
# (input by user).
# PI could be defined as const, or used from math module implementation.
PI = 3.14159265358979
r = float(input("Type in sphere radius -> "))
print("Sphere volume is:", 1.33333333333*PI*r**3)
print("Sphere surface area is: ", 4*PI*r*r) | true |
6b3115cf764ea6e6532b0455dc8565891b31b0c0 | Nazdorovye/VeAPython | /2020_lecture_10_tasks/task03.py | 2,058 | 4.40625 | 4 | # There is a list with integers and two separate sets s0 and s1, each of which contains integers.
# Jānītis likes all the s0 ints and does not like all the s1 ints.
# Jānītis initial happiness index is 0.
# For each integer from the array:
# if 𝑖 ∈ s0, the happiness index must be incremented;
# if 𝑖 ∈ s1, the happiness index must be decremented;
# if default, the happiness index is not changed.
# Because s0 and s1 are sets, they do not have repeating elements, and the array may contain
# repeating values. In the program it is desirable to use the functions designed to work with sets.
#
# Perform the following actions in the program:
# 1. Create a list with n (𝑛 = 6) integer random numbers from the interval [1; 10].
# 2. Create two sets s0 and s1 with m (𝑚 = 3) elements, where each set element belongs to the
# interval [1; 10]. To obtain two separated sets in the program, the following algorithm is
# implemented:
# 1) create a set s2 with all numbers from 1 to 10 (use a range object).
# 2) create set s0 - use the sample function from the module random, which returns a list of
# k random elements from a sequence or set of numbers (uses the set s2 created in point 1).
# 3) create the set s1 - use the sample function, which returns a list of k random elements
# from a sequence or set of numbers. To make the elements of the set s1 different from the elements
# of the set s0, the difference between sets s2 and s0 is used as the argument to the sample
# function.
# 3. Calculates the happiness index.
# 4. Outputs the list, both sets and the happiness index.
from random import randint, sample
N = 6
M = 3
lst = [randint(1, 10) for i in range(N)]
print("\nIndex list: ", lst)
s1 = set(range(1, 11))
s0 = set(sample(s1, M))
s1 = set(sample(s1 - s0, M))
print("Set A: ", s0)
print("Set B: ", s1)
hapIdx = 0 # happiness index
for elm in lst:
if elm in s0:
hapIdx += 1
elif elm in s1:
hapIdx -= 1
print("Happiness index: %d\n" % hapIdx) | true |
df5e16e21948cd44c7c806f1b5dfc9757dffc51d | skrishna1978/CodingChallenge-January-2019- | /1.9.2019 | cipherTextRotate.py | 1,013 | 4.375 | 4 | #1.9.2019 - Shashi
#accept a string of text and a key value. cipher the original text based on key value.
#mapping only for lower case letters from a-z.
def cipher(text,key): #function starts here
arr = "abcdefghijklmnopqrstuwxyz" #lookup variable for all letters.
text = text.lower() #convert original text to lower
ctext = "" #variable to hold final output
for c in text: #loop through every character in string
#if c is part of alphabet, look up index of c in arr, add key value and mod the whole value by 26
#(for high value keys) and look up its equivalent in arr
if c.isalpha() : ctext += arr[(arr.index(c)+key)%26]
else: ctext += c
#if c is not in the alphabet, then add it in as is. Example digits, special characters.
return ctext #return final output back
#testing function with same message but diff. cipher keys.
print(cipher("Hello World 123",3))
print(cipher("Hello World 123",13))
print(cipher("Hello World 123",9))
#end of program
| true |
0346b55e9384986227fbd86155178cb9ad9023e2 | skrishna1978/CodingChallenge-January-2019- | /1.6.2019 | highestScoringWord.py | 1,065 | 4.125 | 4 | #1.6.2019
#Return highest scoring word with a=1, b=2, c=3, ... z=26.
#all input is lower case and valid.
def highestScore(sentence): #function starts here
words=sentence.split(' ') #split the sentence based on space and make an array
scoreslist = [] #create list for holding scores for each word
for word in words: #loop through each word in the sentence
score = [sum([ord(char) - 96 for char in word])] # critical line : each character of each word's value is loaded and total added via sum()
scoreslist.append(score) #final score for that word added to scoreslist
#loop continues until all words are processed.
return words[scoreslist.index(max(scoreslist))] #max(scoresList[]) returns the highest value which is sent to .index() that pulls out its position
#words[positon] then is the specific word that has highest score.
print(highestScore("hakuna matata. what a wonderful phrase!"))
print(highestScore("wishing everyone a happy new year with a lot of zzzzz"))
| true |
4b6a2ff4afdb5ab345fcb8e10cc881dd255ff5e2 | AlanJIANGPENG/python_study_case | /test3.py | 2,506 | 4.125 | 4 | # -*- coding: utf-8 -*-
print ('hello world')
# # 面向对象最重要的概念就是类(Class)和实例(Instance)
# # 类是抽象的模板
# # 实例是根据类创建出来的一个个具体的“对象”,
# # 每个对象都拥有相同的方法,但各自的数据可能不同。
# # 通过class关键字定义类
class Kids(object):
pass
# # class后面紧接着是类名(如Students),类名通常是大写开头的单词,
# # 紧接着是(object),表示该类是从哪个类继承下来的,
# # 如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类
# # 定义好了类,就可以根据类创建出实例,
# # 创建实例是通过类名+()
# # 由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。
# # 通过定义一个特殊的__init__方法,在创建实例的时候,就把某些属性绑上去:
class Students(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_p1(self, gender):
print('%s is %s and the score is %s' % (self.name, gender, self.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
# 注意:__init__方法的第一个参数永远是self,表示创建的实例本身,
# 因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
# 有了__init__方法,在创建实例的时候,就不能传入空的参数了,
# 必须传入与__init__方法匹配的参数,
# 但self不需要传,Python解释器自己会把实例变量传进去:
# 和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,
# 并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,
# 所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。
a1 = Students('bob', 59)
a2 = Students('alan', 87)
# a3 = Students()
print('a1.name =', a1.name)
print('a2.score =', a2.score)
a2.print_p1('M') # 封装结果
# a3.print_p1("F")
print('bob grade:', a1.get_grade())
print('alan grade:', a2.get_grade())
| false |
e8d5bdcdb19a1fa99fe4c5da81acfb265db11241 | Valerie280499/Leerjaar-1-Blok-1 | /Informatica/Informatica theorie/les 5/les5.py | 784 | 4.1875 | 4 | # Voorbeelden behorend bij les 5
# Voorbeeld behorend bij slide 6
hello = "Hello World!"
print(hello[2])
print(hello.index("e"))
# Voorbeeld behorend bij slide 8
s = "Hello World!"
print(s[2]) #print index 2
print(s[:2]) #print index 0,1 (begin tot 2)
print(s[2:]) #print index 2,3,4 etc (2 tot en met eind)
print(s[2:4]) #print index 2 en 3 (2 tot 4)
print(s[-1]) #print index -1 (einde)
print(s[:-1]) #print vanaf 0 tot -1 (begin tot -1) (alles behalve einde)
print(s[-1:]) #print vanaf index -1 (einde tot en met einde)
print(s[-4:-1]) #print index -4 tot -1 (4 geteld vanaf einde tot -1)
print(s[-1:-4]) #que?
# Voorbeeld horend bij het onderwerk Tuples
# Zoals je ziet hebben tuples, net als strings en lists, ook indices
tup = ("a","b")
print(tup[0])
| false |
e8912d0fa4c73aac8291b7a23cb60dada84f6425 | jerrylui803/test2 | /02/src/turtle.py | 2,690 | 4.21875 | 4 | '''Turtles.'''
class Turtle:
'''Turtle.'''
def __init__(self, name, stands_on=None):
'''Init a new Turtle with the given name and the Turtle to stand on.
'''
self._name = name
self._stands_on = stands_on
def name(self):
'''Return the name of this Turtle.'''
return self._name
def stands_on(self):
'''Return the Turtle on which this Turtle stands.'''
return self._stands_on
def all_the_way_down(self):
return TurtlesAllTheWayDownIterator(self)
def _comparison(self, other_turtle):
a = self._name
b = other_turtle._name
return (a > b) - (a < b)
def __eq__(self, other_turtle):
return self._comparison(other_turtle) == 0
def __ne__(self, other_turtle):
return self._comparison(other_turtle) != 0
def __gt__(self, other_turtle):
return self._comparison(other_turtle) > 0
def __ge__(self, other_turtle):
return self._comparison(other_turtle) >= 0
def __lt__(self, other_turtle):
return self._comparison(other_turtle) < 0
def __le__(self, other_turtle):
return self._comparison(other_turtle) <= 0
def __iter__(self):
return TurtleIterator(self)
def __str__(self):
return self._name
class TurtleIterator:
'''Iterator over the Turtles.'''
def __init__(self, turtle=None):
self._curr_turtle = turtle
def __iter__(self):
return self
def __next__(self):
curr_turtle = self._curr_turtle
if curr_turtle:
self._curr_turtle = curr_turtle.stands_on()
return curr_turtle
else:
raise StopIteration
class TurtlesAllTheWayDownIterator:
'''It's turtles, all the way down!'''
def __init__(self, turtle=None):
self._iter = TurtleIterator(turtle)
def __iter__(self):
return self
def __next__(self):
try:
return next(self._iter)
except StopIteration:
return Turtle("Another Turtle")
if __name__ == '__main__':
'''Just some sample calls. Do not examine for presence of bugs in this
part.
'''
# comparisons
mr1 = Turtle('Mr.Turtle')
mr2 = Turtle('Mr.Turtle')
ms = Turtle('Ms.Turtle')
print (mr1 < ms)
print (mr1 == mr2)
# iteration
turtle = Turtle('T0', Turtle('T1', Turtle('T2')))
print (turtle)
for t in turtle:
print(t, 'on', end=' ')
print ('what?')
# super iteration
turtle = Turtle('T0', Turtle('T1', Turtle('T2')))
print (turtle)
for t in turtle.all_the_way_down():
print(t, 'on', end=' ')
print ('what?')
| false |
569b7b19fbebf699f70a9272abf270384e90cf47 | danjpark/python-projecteuler | /001.py | 276 | 4.28125 | 4 | """Add all the natural numbers
below one thousand that are
multiples of 3 or 5."""
def main():
totalSum = 0
for i in range(1000):
if (i % 5 == 0) or (i % 3 == 0):
totalSum += i
print(totalSum)
if __name__ == "__main__":
main()
| true |
a8ff658c79a480b8e3b6bf38407ae2234d28401f | GuduruDhanush/Python | /Basic/rockpaperscissor.py | 1,179 | 4.1875 | 4 | import random
print('WELCOME TO ROCK PAPER SCISSORS GAME!')
# initializing
rock = '🤜'
paper = '✋'
scissors = '🤞'
computer = random.choice([rock, paper, scissors])
player = input(
'Enter your choice (r for rock, p for paper, s for scissors : \n').lower()
# validating user input
if player == 'r':
you = rock
print('You : ', you)
comp = computer
print('Computer : ', comp)
elif player == 'p':
you = paper
print('You : ', you)
comp = computer
print('Computer : ', comp)
elif player == 's':
you = scissors
print('You : ', you)
comp = computer
print('Computer : ', comp)
else:
you = 'invalid'
comp = 'invalid'
# checking for tie, win and lose conditions
if (you == rock and comp == rock) or (you == paper and comp == paper) or (you == scissors and comp == scissors):
print('TIE!!')
elif (you == rock) and (comp == scissors) or (you == scissors) and (comp == paper) or (you == paper) and (comp == rock):
print('you win!')
elif (you == 'invalid') and (comp == 'invalid'):
print('you entered invalid input, you lose!')
else:
print('you lose!')
| false |
d1507e7be85941863b01c460dba855180f8dec01 | DaftBeowulf/Data-Structures | /queue/queue.py | 1,884 | 4.125 | 4 | class Queue:
def __init__(self):
self.size = 0
# what data structure should we
# use to store queue elements?
self.storage = LinkedList()
def enqueue(self, item):
self.storage.add_tail(item)
def dequeue(self):
return self.storage.remove_head()
def len(self):
return self.storage.get_length()
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_tail(self, value):
new_node = Node(value)
# list currently has zero items
if self.head == None and self.tail == None:
self.head = new_node
self.tail = new_node
else:
self.tail.set_next(new_node)
self.tail = new_node
def remove_head(self):
# list has zero items
if not self.head and not self.tail:
return None
# list has one item (so remove all items from list)
elif self.head is self.tail:
removed = self.head
self.head = None
self.tail = None
return removed.get_value()
# list has more than one item
else:
removed = self.head
self.head = removed.get_next()
return removed.get_value()
def get_length(self):
length = 0
current = self.head
# if list is empty, will immediately leave while loop and return 0
while current != None:
length += 1
current = current.get_next()
return length
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, node):
self.next_node = node
q = Queue()
print(q.len())
| true |
ff173dd9a75d166015e5928db7ed3bde0d85a003 | teddyr00se/PythonDataInformatics | /Assignment-4.6.py | 1,042 | 4.3125 | 4 | #4.6 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
def computepay(h,r):
if h > 40:
pay = (r * 40) + ((h-40)*r *1.5)
else :
pay = r * h
return pay
try:
hrs = float(raw_input("How many hours do you got: "))
rate = float(raw_input("How much rate do you got: "))
except:
print "Please enter valid numbers"
exit()
p = computepay(hrs, rate)
print p | true |
16333961e77cd92f5d5640aa35d6bb0c035ff726 | andcoelho/IntroducaoPython | /aula 011 - exerícios.py | 1,609 | 4.40625 | 4 | #Aula 011 - exerícios
"""
Faça um programa que leia três números e mostre-os
em ordem decrescente.
"""
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
c = int(input("Digite o terceiro número: "))
if a > b > c:
print(a, b, c)
elif a > c > b:
print(a, c, b)
elif b > a > c:
print(b, a, c)
elif b > c > a:
print(b, c, a)
elif c > a > b:
print(c, a, b)
else:
print(c, b, a)
""" Caso os números sejam iguais, o programa buga
necessário colocar não apenas o maior
mas sim o maior ou igual ( => )
"""
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
c = int(input("Digite o terceiro número: "))
if a >= b >= c:
print(a, b, c)
elif a >= c >= b:
print(a, c, b)
elif b >= a >= c:
print(b, a, c)
elif b >= c >= a:
print(b, c, a)
elif c >= a >= b:
print(c, a, b)
else:
print(c, b, a)
#Exercícios para casa!
"""
PROGRAMA 1
Faça um programa que leia um número inteiro menor que 1000 e
imprima a quantidade de centenas, dezenas e unidades do mesmo.
Observando os tempos no plural a colocação do "e", da vírguula entre outros. exemplo:
326 = 3 centenas, 2 dezenas e 6 unidades
12 - 1 dezena e 2 unidades.
Testar com: 326, 300, 100, 320, 310, 305, 301, 101, 311
111, 25, 20, 10, 21, 11, 1, 7, 16
----------
PROGRAMA 2
Faça um programa que leia três númerso e mostre o maior o menor deles.
"""
print("programa 1")
num = int(input("Digite o número"))
if num < 1000:
print(num//10, "dezena")
else:
print("numero inválido, only less than 1000")
| false |
d56707ac2e83a847ab0e7d47e0d4af15f0614a79 | andcoelho/IntroducaoPython | /Aula 007 - exercícios.py | 752 | 4.15625 | 4 | """
Programa 1:
Faça um programa que peça as 4 notas bimestrais e mostre a média
"""
"""
Programa 2:
Faça um programa que pergunte quanto você ganha por hora e número
de horas trabalhas
Calcule e mostre o total do seu salário no referido mês
"""
print("Programa 1: ")
x = int(input("Qual sua nota em matemática? "))
y = int(input("Qual sua nota em física? "))
w = int(input("Qual sua nota em Química? "))
z = int(input("Qual sua nota em biologia? "))
print("Sua média nesse bimestre é:", (x+y+w+z)/4)
print("Programa 2: ")
num = int(input("Quanto você ganha por hora? "))
num2 = int(input("Quantas horas você trabalha? "))
num3 = int(input("Quantos dias ao mês você trabalha? "))
print("Seu salário é: ", num*num2*num3, "reais")
| false |
102b7faa09fd52276dde51bf888058ec17f53820 | MasBad/pythonintask | /IVTp/2014/Grigoriev_A/task_5_2.py | 852 | 4.125 | 4 | #Задача №5, Вариант 2
#Напишите программу, которая бы при запуске случайным образом отображала название одного из цветов радуги.
#Григорьев А.О.
#23.05.2016
import random
a="красный"
b="оранжевый"
с="желтый"
d="зеленый"
e="голубой"
q="синий"
w="фиолетовый"
country=random.randint(1,7)
print("Программа случайным образом отображает название одного из цветов радуги")
if country==1:
print(a)
elif country==2:
print(b)
elif country==3:
print(c)
elif country==7:
print(d)
elif country==4:
print(e)
elif country==5:
print(q)
elif country==6:
print(w)
input("Нажмите Enter для выхода.") | false |
214c2cdde2dc1403f476b5a1bb69c8541ee3398a | MasBad/pythonintask | /PMIa/2014/KUCHERYAVENKO_A_I/task_5_38.py | 973 | 4.4375 | 4 | # Задача 5. Вариант 38.
# Напишите программу, которая бы при запуске случайным образом
# отображала имя одной из семи птиц,
# доступных с первой версии игры Angry Birds.
# Kucheryavenko A. I.
# 31.03.2016
import random
print("Программа случайным образом отображает имя одной из семи птиц,доступных с первой версии игры.")
birds = random.randint(1,7)
print('\nИмя птицы с первой версии игры', end=' ')
if birds == 1:
print('Ред')
elif birds == 2:
print('Джейк')
elif birds == 3:
print('Чак')
elif birds == 4:
print('Бомб')
elif birds == 5:
print('Матильда')
elif birds == 6:
print('Хэл')
elif birds == 7:
print('Теренс')
input("\n\nНажмите Enter для выхода.")
| false |
f1b098eaa0ebcb712758d14d1373795dd4da7373 | villejacob/codepath-internship-prep | /week_1/challenges/5_longest_palindrome_substring.py | 1,391 | 4.125 | 4 | '''
Write a program which takes a String as input and returns a String which is the longest palindromic substring in the
input, given the following assumptions about the input string:
its maximum length is 1000
it contains one unique, longest palindromic substring
Examples:
"abdbabbdba" should return "abdba"
"abdbbbbdba" should return "abdbbbbdba"
'''
def longestPalindromeSubstring(input_string):
max_length = 1
start = 0
end = 0
# Treat each character as center of palindrome, then iterate outwards O(n^2)
for i in xrange(1, len(input_string)):
# Even length substring
low = i - 1
high = i
while low >= 0 and high < len(input_string) and input_string[low] == input_string[high]:
if high - low + 1 > max_length:
max_length = high - low + 1
start = low
end = high
low -= 1
high += 1
# Odd length substring
low = i
high = i
while low >= 0 and high < len(input_string) and input_string[low] == input_string[high]:
if high - low + 1 > max_length:
max_length = high - low + 1
start = low
end = high
low -= 1
high += 1
return max_length, input_string[start:end+1], all_palindromes
print longestPalindromeSubstring("abdbbbbdba") | true |
ae19a3202e913e2d01d886e40bf17609d615835e | zhuxingyue/pythonDemo | /python基础/day07/hm_05_循环嵌套.py | 367 | 4.5625 | 5 | """
循环嵌套:
while 表达式:
代码:
while 表达式:
代码
"""
"""
连续输出5行,打印:
*
**
***
"""
row = 1
while row <= 5:
print("*" * row)
row += 1
row = 1
while row <= 5:
num = 1
while num <= row:
print("*", end="")
num += 1
print("")
row += 1 | false |
325f2e7d398c5443fe9ae6cb6e5bd3cecd34466c | zhuxingyue/pythonDemo | /python基础/day06/hm_01_逻辑运算符.py | 333 | 4.21875 | 4 | """
逻辑运算符:python中的逻辑运算符就3种
and 与
or 或
not 非
"""
a = 10
b = 20
c = 30
if a < b and c > a:
print("b最小")
if a > b or c > b:
print("ce")
# 关系运算符
if a != b:
print("a不等于b")
# 逻辑运算符
if not not b:
print("阿斯顿看风景")
| false |
f90517f805d919a442875a8a51866f008fe1cf33 | sakhawath19/MIMO-detectors | /python_pandas.py | 1,688 | 4.1875 | 4 | # Import all libraries needed for the tutorial
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
import sys #needed to determine python version number
import matplotlib #needed to determine python matplotlib version
import os # it will be used to remove csv file
print('Python version:' + sys.version)
print('Matplotlib version:' + matplotlib.__version__)
print('Pandas version:' + pd.__version__)
# The initial set of baby names and birth dates
names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel']
births = [968, 155, 77, 578, 973]
# To merge these two list we will use zip function
baby_data_set = list(zip(names,births))
# df is a dataframe object
df = pd.DataFrame(data=baby_data_set,columns=['Names','Births'])
location = r'C:\Python\Pandas_file\births_1880.csv'
# It will create csv file in same directory
#df.to_csv('births_1880.csv')
# It will create csv file in the preffered location. It is not exporting index or header
df.to_csv(location,index=False,header=False)
# Header and index was not exported, so header needed to set null while reading the file
#df = pd.read_csv(location,header=None)
# We have specified the columns name
df = pd.read_csv(location,names=['Names_','Births_'])
os.remove(location)
#os.remove(r'C:\Python\births_1880.csv')
print(df.dtypes)
# checking data type and outlier
print('Data type in births column',df.Births_.dtype)
sorted = df.sort_values(['Births_'],ascending=False)
print('Maximum number of same name:',df['Births_'].max())
print('data sorted according to births number in decending order \n',sorted)
print(sorted.head(1))
print(df)
| true |
a3d49397ae8cfdf78c405c7e4262bae015db6ee2 | fullerharrison/afs505_u1 | /assignment2/ex5.py | 554 | 4.125 | 4 | name = "Harrison D. Fuller"
age = 25
height = 71 # inches
weight = 220 #lbs
eyes = 'Brown'
teeth = 'White'
hair = 'Brown'
cm = 2.54 * height
kg = weight * 0.45
print(f"Let's talk about {name}.")
print(f"He's {height} centimeters tall.")
print(f"He's {kg} kilograms heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee.")
#This line is tricky, try to get it exactly right
total = age + height + kg
print(f"If I add {age}, {height}, and {kg} I get {total}.")
| true |
c8ab39aa3f789a90a5be6e5e128e6e7f4752af49 | fullerharrison/afs505_u1 | /assignment2/ex6.py | 816 | 4.125 | 4 | # variable of typ_ppl
typ_ppl = 10
# variable of string with variable embedded
x = f"There are {typ_ppl} types of people."
# 2 variables coded as strings
# one variable coded as a string with 2 string variables
bnry = "binary"
do_not = "don't"
y = f"Those who know {bnry} and those who {do_not}."
#prints a variable but out put is a string
print(x)
print(y)
#prints a string with a variable embedded strings
print(f"I said: {x}")
print(f"I also said: '{y}'")
#variable as a condition
hilarious = False
# variable with empty format
jk_eval = "Isn't that joke so funny?! {}"
# prints variable and inserts formated variable condition
print(jk_eval.format(hilarious))
# 2 strings denoted as objects
w = "This is the left side of ..."
e = "a string with a right side."
# prints the addition of e to w
print(w+e)
| true |
fdc445942df1ff28255bc09de710fee363ac5230 | copetty/test-repository | /python_refresher/21_unpacking_arguments/code.py | 507 | 4.15625 | 4 | def mulitply(*args):
print(args)
total = 1
for arg in args:
total = total * arg
return total
print(mulitply(1, 3, 5))
def add(x, y):
return x + y
nums = [3, 5]
print(add(*nums))
nums2 = {"x": 15, "y" : 25}
print(add(**nums2))
def apply(*args, operator):
if operator == "*":
return mulitply(*args)
elif operator == "+":
return sum(args)
else:
return "No valid operator provide to apply()"
print(apply(1, 3, 4, 5, operator = "+"))
| true |
6b721fdb47ba81a4343d5cced4012df40265f82a | umanav/Lab206 | /Python/Fundamentals/Scores_and_Grades.py | 688 | 4.21875 | 4 | #Scores and Grades
#Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score.
import random
def scores():
counter = 0
print "Scores and Grades"
while counter< 10:
number = random.randint(60,101)
if number < 70:
print "Score:",number,"; Your grade is D"
elif number < 80:
print "Score:",number,"; Your grade is C"
elif number < 90:
print "Score:",number,"; Your grade is B"
elif number < 101:
print "Score:",number,"; Your grade is A"
counter+=1
scores() | true |
427555f607f5b91e8724496249065645db0ecb7b | jeanazurdia/Python-Projects | /matrix_2_picture.py | 779 | 4.1875 | 4 | #turning the 1s into *, and 0 into blanks
matrix = [
[0,0,0,1,0,0,0],
[0,0,1,1,1,0,0],
[0,1,1,1,1,1,0],
[1,1,1,1,1,1,1],
[0,0,0,1,0,0,0],
[0,0,0,1,0,0,0]
]
for i in matrix: #for row in matrix
for j in i: #for cell in row
if j == 0: #if cell equals 0
print(" ", end = "") #make it blank "". The end="" section stops print from creating a new line after every cell
else:
print('*', end = "") #if it's anything else (not zero), then make it *
print('') #this last print is within first loop (outside of second), so the when we finish the entire row, we print nothing, but
#the "end" on print(,end), which we left blank/no arguement, allows for a new line to be added after every row
| true |
fc8dad4ed174195c4f68ef6dff951df449ab922d | jeanazurdia/Python-Projects | /If_magician.py | 318 | 4.125 | 4 | #learning if statements w/elif, else
is_magician = False
is_expert = True
if is_magician and is_expert:
print('you are a master magician')
elif is_magician > is_expert: #elif is_magician and not is_expert
print("at least you're getting there")
else: #elif not is_magician
print('You need magic powers')
| false |
b029a71a48847f766257f81890b790dd6e0a12f7 | momentum-cohort-2019-05/w2d1-house-hunting-christopherwburke | /househunting.py | 769 | 4.25 | 4 | portion_down_payment = 0.25
current_savings = 0
r = (.04/12)
#ask input for annual_salary , savings_rate, and cost_of_home
annual_salary=int(
input("What is your annual salary? "))
savings_rate=float(input("What percentage of your annual salary will you save each month? Answer in the form of a decimal. "))
cost_of_home=int(input("How expensive is your dream home? "))
#Down Payment Amount = portion_down_payment * total_cost
down_payment = portion_down_payment * cost_of_home
### monthly_savings = annual salary /12 * savings rate ###
monthly_savings = (annual_salary / 12) * savings_rate
n = 0
while current_savings < down_payment:
n = n+1
current_savings = current_savings + monthly_savings + ((current_savings + monthly_savings)*r)
print(n) | true |
d79416fb205573cddfe1a050ae28988d1ac3a1b5 | shelibenm/processingsheli | /lesson_4/Recursion.pyde | 977 | 4.3125 | 4 | """
Recursion.
A demonstration of recursion, which means functions call themselves.
Notice how the drawCircle() function calls itself at the end of its block.
It continues to do this until the variable "level" is equal to 1.
"""
#TODO-run the code-
def setup():
size(640, 360)
noStroke()
noLoop()
#TODO-add more circles-change the number of levels
def draw():
drawCircle(width / 2, 280, 6)
def drawCircle(x, radius, level):
tt = 126 * level / 4.0
fill(tt)
ellipse(x, height / 2, radius * 2, radius * 2)
if level > 1:
#TODO-try to make less recursion cycles by changing the level value
#for example level= level -2
level = level - 1
drawCircle(x - radius / 2, radius / 2, level)
drawCircle(x + radius / 2, radius / 2, level)
#TODO-add more recursion function for example:drawrect()that create diagmol pattern
#not horizontal like the drawCircle() above
#
| true |
56d7f3b38f1ad73347c2c11e95ec023caa1add84 | Chris166/Auth-System | /database.py | 354 | 4.25 | 4 | import sqlite3
with sqlite3.connect("main.db") as db:
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS info(
userID INTEGER PRIMARY KEY,
username VARCHAR(20) NOT NULL,
firstname VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL);
''')
cursor.execute("SELECT * FROM info")
print(cursor.fetchall())
| true |
3de68317e63db6672a24e7967297238a3a6cabfe | gj-sq/program_language_test | /python-test/concatenation_string.py | 207 | 4.46875 | 4 | # the adjacent string
str_1 = "hello" "world"
str_2 = "hello"
"world"
str_3 = "hello"\
"world"
print("the str_1 is: ", str_1)
print("the str_2 is: ", str_2)
print("the str_3 is: ", str_3)
| false |
aebb3363deaca8a1da847407035fcd925b7735bc | Ian100/Curso_em_Video-exercicios- | /desafio_26.py | 536 | 4.15625 | 4 | # Faça um programa que leia uma frase pelo teclado
# e mostre quantas vezes aparece a letra "A",
# em que posição ela aparece na primeira vez
# e em que posição ela aparece na última vez.
frase = str(input('Digite uma frase: ')).strip().upper()
print('A letra \'A\' aparece {} vezes na frase'.format(frase.count('A')))
print('A primeira vez que \'A\' aparece na frase é na posição {}'.format(frase.find('A')+1))
print('A última vez em que letra \'A\' aparece na frase é na posição {}'.format(frase.rfind('A')+1))
| false |
cae9eddaf9ba367ed47c251036d9eff1a4a6436d | Ian100/Curso_em_Video-exercicios- | /desafio_86.py | 465 | 4.25 | 4 | # Crie um programa que crie uma matriz de dimensão 3x3 e preencha
# com valores lidos pelo teclado. No final, mostre a matriz na tela com a
# formateção correta.
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range(0, 3):
matriz[i][j] = int(input(f'Digite um valor para [{i}, {j}]: '))
print('-=' * 30)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]:^5}]', end='')
print()
| false |
a8fd339a3351ce5f5d2ce964eb4b54ac5dd1c03c | Carina6/algorithms | /leetcode/algorithms/58_length_of_last_word.py | 481 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 58. Length of Last Word
def test_length_of_last_word():
'''
思路:
时间复杂度:
'''
def method1(s):
count = 0
s = s.strip()
for c in s[::-1]:
if c == ' ':
return count
else:
count += 1
return count
def method2(s):
return len(s.strip().split(' ')[-1])
print()
print(method2('hello world '))
| false |
73a4d1ae9fda89a2047c198aab58b5e5e1022d0e | league-python-student/level2-module0-dencee | /_01_file_io/_a_intro/_b_file_io_intro.py | 1,492 | 4.125 | 4 | """
Intro exercises for file input and output
"""
import unittest
import random
from pathlib import Path
# TODO 1) Read the filename and return a string containing the contents.
# Assume the file exists.
def reading_file(filename):
return None
# TODO 2) Write the specified text to the given filename. If the file doesn't
# exist the function should create it.
def write_file(filename, text):
return None
# TODO 3) Return True if the filename exists at the given directory and return
# False otherwise
def file_exists(directory_from_cwd, filename):
return None
# ======================= DO NOT EDIT THE CODE BELOW =========================
class FileIOTests(unittest.TestCase):
read_file_pass = False
def test_reading_and_writing_file(self):
filename = 'sample.txt'
self.assertEqual('This is a sample text file\n', reading_file(filename))
# Test below only runs if no failures/asserts above
filename = 'test_writing_file.txt'
rand_num = random.randint(0, 100)
text = 'writing sample ' + str(rand_num)
write_file(filename, text)
self.assertEqual(text, reading_file(filename))
def test_file_exists(self):
filename = 'Alices_Adventures_In_Wonderland.txt'
directory_from_cwd = 'text_files'
self.assertTrue(file_exists(directory_from_cwd, filename))
self.assertFalse(file_exists(directory_from_cwd, 'unknown.txt'))
if __name__ == '__main__':
unittest.main()
| true |
08c83fbb068d7af1d929a65c58b9680c19598a18 | Bojanpp/Python_domaca_naloga | /Homework1_3.py | 346 | 4.25 | 4 | print("CALCULATOR")
x = int(input("Enter value for x: "))
y = int(input("Enter value for y: "))
operation = input ("Choose your math operation: ")
if operation == "+":
print(x+y)
elif operation == "-":
print (x-y)
elif operation == "*":
print (x*y)
elif operation == "/":
print (x/y)
else:
print("Not a correct operation")
| false |
60b1ad8c45ff170619f260deca3b9a78c5cdd73f | sk055/Data-Structures-using-python | /Linear Data Structures/Array/03-Deleting.py | 356 | 4.3125 | 4 | from array import *
print("Deleting element in array\n")
array_3 = array('i', [1,2,3,4,5]) #defining array
for k in array_3:
print(k)
print("\nResult")
# array_3.remove(1) #removes element upto this index
array_3.pop(1) #removes the specified index element
for k in array_3: #Traversing array after Deletion
print(k)
| true |
71463de4dff9dc9f1d1e1546c957104b65fa97dd | khush611/algodaily | /day42.py | 1,220 | 4.15625 | 4 | # Python3 implementation of smallest
# difference triplet
# Function to find maximum number
def maximum(a, b, c):
return max(max(a, b), c)
# Function to find minimum number
def minimum(a, b, c):
return min(min(a, b), c)
# Finds and prints the smallest
# Difference Triplet
def smallestDifferenceTriplet(arr1, arr2, arr3, n):
# sorting all the three arrays
arr1.sort()
arr2.sort()
arr3.sort()
# To store resultant three numbers
res_min = 0; res_max = 0; res_mid = 0
# pointers to arr1, arr2,
# arr3 respectively
i = 0; j = 0; k = 0
# Loop until one array reaches to its end
# Find the smallest difference.
diff = 2147483647
while (i < n and j < n and k < n):
sum = arr1[i] + arr2[j] + arr3[k]
max = maximum(arr1[i], arr2[j], arr3[k])
min = minimum(arr1[i], arr2[j], arr3[k])
if (min == arr1[i]):
i += 1
elif (min == arr2[j]):
j += 1
else:
k += 1
if (diff > (max - min)):
diff = max - min
res_max = max
res_mid = sum - (max + min)
res_min = min
print(res_max, ",", res_mid, ",", res_min)
arr1 = [5, 2, 8]
arr2 = [10, 7, 12]
arr3 = [9, 14, 6]
n = len(arr1)
smallestDifferenceTriplet(arr1, arr2, arr3, n)
| true |
dd3e254573a783650d4beb17c5ef0303486df5b7 | laxmigurung/fileHandlingCodeLabs | /studentContractCustom.py | 2,877 | 4.15625 | 4 | """
Program: studentContractCustom.py
Programmer: Laxmi Gurung
Purpose: To input the name and contract points of students of the prompted week.
Date: 06/03/2021
"""
# Importing datetime to get the current data time using now()
import datetime
#Displays the current date and time
current = datetime.datetime.now()
print("Lab 13.4:", current.strftime("%X on %A, %B %d, %Y \n"))
#Calling main function
def main():
#Prompting user to input week number and storing it in a variable week
#Prompting user to input how many students user want to write for.
week = int(input("Enter Week Number: "))
student = int(input("Enter the number of students: "))
#Opening the file studentContract.txt in write mode and creating a variable student_file
#for the instance to open the file
student_file = open('studentContract.txt','w')
#Using for to let the user input the informations for the number od students stored in variable 'student'
#Prompt the user to input name and point
for num in range(1, student +1):
name = input("Enter the name of the student: ")
point = int(input("Enter the contract point: "))
#this writes the name and point to the file.
#using str(point) because it was int when prompting user to input
# as we need to concatenate '\n', we have to convert int to str.
student_file.write(name + '\n')
student_file.write(str(point) + '\n')
#closing the file
student_file.close()
#Opening the file to read the data.
student_file = open('studentContract.txt', 'r')
print(f"\nThese are Contract Points for Week : {week}")
print("------------------------------------------------")
# reading the first line of the file.
name = student_file.readline()
#Using while condtion in order to read the all line until while condition is false.
while name != '':
point = student_file.readline()
#We need to remove the new line '\n', in order to place the data in the required position.
#Using rstrip we can remove the \n. Also try commenting out the line 55 and 56, then you will see that
#we should remove the \n.
name = name.rstrip('\n')
point = point.rstrip('\n')
#Using the if statement to let the user know students below 100 are in risk.
if int(point) <= 100:
print(f'Name: {name} Contract Point: {point} DANGER!! ')
else:
print(f'Name: {name} Contract Point: {point}')
#After it readline the second line, it needs to read the third line which is another name
#so we need to write the following statement again for the loop to continue.
name = student_file.readline()
#Closing the file
student_file.close()
#calling the main function
main()
| true |
1feb53bb79b7152e4412f20c2167c79ae9b96695 | greatcrock/First | /ex19.py | 2,653 | 4.28125 | 4 | """
You are given a list of files. You need to sort this list by the file extension. The files with the same extension should be sorted by name.
Some possible cases:
Filename cannot be an empty string;
Files without the extension should go before the files with one;
Filename ".config" has an empty extension and a name ".config";
Filename "config." has an empty extension and a name "config.";
Filename "table.imp.xls" has an extension "xls" and a name "table.imp";
Filename ".imp.xls" has an extension "xls" and a name ".imp".
Input: A list of filenames.
Output: A list of filenames.
"""
from typing import List
def personal(elem):
q = elem.split(".")
if q[0] == "" and len(q) == 2:
back = q[0] + "." + q[1]
elif len(q) == 3:
back = q[-1] + "." + q[0] + "." + q[1]
else:
back = q[1] + "." + q[0]
return back
def sort_by_ext(files: List[str]) -> List[str]:
# your code here
return sorted(files, key=personal)
# for i in a:
# k = i[0]
# v = i[-1]
# pain[k] = v
# print(k, v)
# m = sorted([(v, k) for k,v in pain.items()])
# print(m)
# m = [(str(k) + str(v)) for v, k in m]
print(sort_by_ext(['1.cad', '1.bat', '1.aa', ".ff.bb"]))
print(sort_by_ext(['1.cad', '1.bat', '1.aa', '2.bat']))
print(sort_by_ext(['1.cad', '1.bat', '1.aa', '.bat']) == ['.bat', '1.aa', '1.bat', '1.cad'])
print("Itself", sort_by_ext(['1.cad', '1.bat', '1.aa', '.bat']))
# These "asserts" are used for self-checking and not for an auto-testing
print(1,sort_by_ext(['1.cad', '1.bat', '1.aa']) == ['1.aa', '1.bat', '1.cad'])
print(2,sort_by_ext(['1.cad', '1.bat', '1.aa', '2.bat']) == ['1.aa', '1.bat', '2.bat', '1.cad'])
print(3,sort_by_ext(['1.cad', '1.bat', '1.aa', '.bat']) == ['.bat', '1.aa', '1.bat', '1.cad'])
print(4,sort_by_ext(['1.cad', '1.bat', '.aa', '.bat']) == ['.aa', '.bat', '1.bat', '1.cad'])
# assert sort_by_ext(['1.cad', '1.', '1.aa']) == ['1.', '1.aa', '1.cad']
print(5,sort_by_ext(['1.cad', '1.bat', '1.aa', '1.aa.doc']) == ['1.aa', '1.bat', '1.cad', '1.aa.doc'])
print(6,sort_by_ext(['1.cad', '1.bat', '1.aa', '.aa.doc']) == ['1.aa', '1.bat', '1.cad', '.aa.doc'])
print(6,sort_by_ext(['1.cad', '1.bat', '1.aa', '.aa.doc']))
print(7,sort_by_ext(['1.cad', '1.bat', '1.aa', '.aa.doc']))
print(sort_by_ext([".config","my.doc","1.exe","345.bin","green.bat","format.c","no.name.","best.test.exe"]) == [".config","no.name.","green.bat","345.bin","format.c","my.doc","1.exe","best.test.exe"])
print(sort_by_ext([".config","my.doc","1.exe","345.bin","green.bat","format.c","no.name.","best.test.exe"])) | true |
288d36fed78a6b296920daa59f26923b09b75873 | greatcrock/First | /ex14.py | 1,151 | 4.5 | 4 | """
Every true traveler must know how to do 3 things: fix the fire, find the water and extract useful information from the nature around him.
Programming won't help you with the fire and water, but when it comes to the information extraction - it might be just the thing you need.
Your task is to find the angle of the sun above the horizon knowing the time of the day.
Input data: the sun rises in the East at 6:00 AM, which corresponds to the angle of 0 degrees.
At 12:00 PM the sun reaches its zenith, which means that the angle equals 90 degrees. 6:00 PM is the time of the sunset so the angle is 180 degrees.
If the input will be the time of the night (before 6:00 AM or after 6:00 PM), your function should return - "I don't see the sun!".
Input: The time of the day.
Output: The angle of the sun, rounded to 2 decimal places.
"""
from typing import Union
def sun_angle(time: str) -> Union[int, str]:
h, m = map(int,time.strip().split(":"))
angle = m + int(h * 60)
return (angle - 360) * (15 / 60) if angle // 60 in range(6, 19) else "I don't see the sun"
print(sun_angle("01:23"))
print(sun_angle("07:00")) | true |
1cec3fea8eece03e0798b0dc69e3adfcedb8073a | greatcrock/First | /ex13.py | 1,216 | 4.15625 | 4 | """
Вам предоставляется набор координат, в которых расставлены белые пешки.
Вы должны подсчитать количество защищенных пешек.
Входные данные: Координаты расставленных пешек в виде набора строк.
Выходные данные: Количество защищенных пешек в виде целого числа.
"""
def safe_pawns(pawns: set) -> int:
defenced = 0
pawns = list(pawns)
print(pawns)
for pawn in pawns:
p_l = chr(ord(pawn[0]) - 1) # previous letter
n_l = chr(ord(pawn[0]) + 1) # next letter
p_p = str(int(pawn[1]) - 1) # previous position
if (p_l + p_p in pawns) or (n_l + p_p in pawns):
defenced += 1
print(pawn)
else:
continue
return defenced
print(safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}))
#safe_pawns({"b2", "a1"})
# m = {"b1", "c2", "c3"}
# if "b" + str(1) in m:
# print("JFD")
# u = "b1"
# for i in m:
# print(str(chr(ord(i[0]) + 1)) + str(i[1]))
# print(chr(ord(u[0]) +1)) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.