blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
20d1482c0d8b8cb83b817c382ff6417dd108c2ac | rkoehler/Class-Material | /Basic Code (Unorganized)/patientlistapp.py | 1,110 | 4.3125 | 4 | #hospital list
#patient position = Doctor position
#ask user for patient name
#tell program to figure out position of patient name
#tell program to figure out position of doctor name
#tell program to match postion of names
listDoctors = ["Mark", "Steve", "Wayne", "Thomas"]
patients = [["Todd", "Dan"]
, ["Tim", "Robert"]
, ["Maria"]
, ["Jose"]]
patientWeAreLookingFor = input("Please give me a patient name: ")
for patientIndex in range(len(patients)):
for innerPatientIndex in range(len(patients[patientIndex])):
if patients[patientIndex][innerPatientIndex] == patientWeAreLookingFor:
print("His Doctor is " + listDoctors[patientIndex])
# if patients[patientIndex] == patientWeAreLookingFor:
#
# Homework
#1- Application allow to exit
# b. Print Doctor's name and list of patients
# sample menu
# 1. To look for patient's doctor
# 2. Print all doctors and patients
# 3. Exit
# 4. add data
#5. store
# Figure out a design for your calendar application
# Implement the start menu for it.
#Meeting 31st at 11am
| true |
1f91d6a306a2cd27a1e93c54097191b642ea1a0b | Fareen14/Python-Projects | /Reverse a String.py | 258 | 4.4375 | 4 | def reverse(string1):
string1 = "".join(reversed(string1))
return string1
s = "The weather is enjoyable today!"
print("The original string is:\n ", end=" ")
print(s)
print("\nThe reversed string(using reversed function) is:\n")
print(reverse(s))
| true |
1dc7167eb52b4dcd1f7232a9fa17db12760d6f73 | Joniel00/StartingOutWPython-Chapter6 | /odd_even_counter.py | 1,210 | 4.1875 | 4 | # June 22nd, 2010
# CS 110
# Amanda L. Moen
# 7. Odd/Even Counter
# In this chapter you saw an example of how to write an algorithm
# that determines whether a number is even or odd. Write a program
# that generates 100 random numbers, and keeps a count of how many
# of those random numbers are even and how many are odd.
# Import random
import random
def is_even(number):
# Determine whether the number is even.
if (number %2) == 0:
return True
else:
return False
# Main function.
def main():
# The count for even numbers starts at 0.
even = 0
# The count for odd numbers starts at 0.
odd = 0
# Specify the range for the random numbers.
for count in range(100):
# Get a random number.
number = random.randint(1, 100)
# Display the number.
print number
# Set up the counter for the even and odd numbers)
if (is_even(number)):
even += 1
else:
odd += 1
# Print how many even numbers there are.
print "There are", even, "even numbers."
# Print how many odd numbers there are.
print "There are", odd, "odd numbers."
# Call the main function.
main()
| true |
04d62a0806ee1a90b4bce24211077be8a1019e79 | jblovett/leetcode_practice | /josh_exercises/codebyte/intersection.py | 782 | 4.21875 | 4 | """Find the intersection of two comma seperated strings of numbers. https://coderbyte.com/editor/Find%20Intersection:Python3
The two strings are given in an array.
Concepts: string manipulation. The split() function in str objects removes whitespace around a string by default, and removes a given
character at the beginning and end of the string. Results in a new string (does not mutate the string object)."""
def FindIntersection(strArr):
str_1 = strArr[0]
str_2 = strArr[1]
list1 = list(str_1.split(", "))
list2 = list(str_2.split(", "))
result = ""
no_intersection = True
for string in list1:
if string in list2:
no_intersection = False
result += string
result += ","
if no_intersection:
return "false"
return result.strip(",") | true |
cd33c5e9c77577196234b80e8a7c6c3b29979514 | AlanGPS/Python | /Atividades_Python/Prog_002.py | 1,411 | 4.3125 | 4 | ## Exercício da Aula 02
#a = 10
#b = 6
a = int(input('Entre com o primeiro valor:'))
b = int(input('Entre com o segundo valor:'))
soma = a + b
subtracao = a - b
multiplicacao = a * b
divisao = a / b
resto = a % b
print(soma)
print(subtracao)
print(multiplicacao)
print(divisao)
print(resto)
## Determinando o tipo da variável
#print(type(soma))
## Convertendo de inteiro para string
#soma = str(soma)
## Mostrando que é uma string
#print(type(soma))
## Ou podemos deixar mais complexa a coisa
print('Soma: ' + str (soma))
## Isso se chama concatenação
## Outra forma de fazer isso é usando o format
print('Soma: {}. Subtração {}.'.format(soma,subtracao))
## Com um enter entre as linhas
resultado = ('Soma: {}.'
'\nSubtração: {}.'
'\nMultiplicação: {}.'
'\nDivisão: {}.'
'\nResto: {}.'.format(soma,
subtracao,
multiplicacao,
divisao,
resto))
print (resultado)
## Outra forma de expressar o resultado
resultado = ('Soma: {sum}.'
'\nSubtração: {sub}.'
'\nMultiplicação: {mult}.'
'\nDivisão: {div}.'
'\nResto: {rest}.'.format(sum=soma,
sub=subtracao,
mult=multiplicacao,
div=divisao,
rest=resto))
print (resultado) | false |
ac3b2cf078214b99119c72482b54e785f849b2b2 | salman6100/python | /exp.py | 553 | 4.125 | 4 | questions ={}
# set ice skating is active.
iceskating_active = True
while iceskating_active:
#prompt user for name
name = input("\nwhat is your name : ")
question = input(" where would you like to ice skate")
#store the question in dictionary
questions[name] = question
repeat = input(" would you like someelse respond? ( yes/no)")
if repeat == 'no':
iceskating_active = False
print("\n outcome ")
for name, question in questions.items():
print( name + " would you like to skate" + question + " .")
| true |
ce627bcfa4b4075a1d9414c001e01fd3f5273e89 | salman6100/python | /mountain.py | 530 | 4.1875 | 4 | iceskating = {}
skating_active = True
while skating_active:
# Asker user their name
name = input(" What is your name :")
iceskatings = input ( " where would you like to iceskate : ")
iceskating[name] = iceskatings
repeat = input(" would like to go swimming instead ? ( yes /no )")
if repeat == 'no' :
skating_active = False
# result
print ("\n --- Poll Result ---")
for name, iceskatings in iceskating.items():
print(name + " would you like to skate" + iceskatings + " .")
| true |
7b26f0558fc35774fea211f75d7008104801b453 | salman6100/python | /ex7-2.py | 243 | 4.15625 | 4 | people = input ( " how many people are in the dinner group : ")
people = int(people)
print ( people)
if people > 8:
print ( " you are going to have to wait for table")
else :
print ( " welcome , your table is ready")
| false |
6835d9822cb257a92f2dd49e4c318a068b0bfacf | ky822/assignment10 | /jz1584/gradeTesting.py | 2,777 | 4.15625 | 4 | import pandas as pd
from clean_save import cleanGrade
def quantify(grade_list):
"""function code the letter:A,B,C in the grade_list to corresponding
numerical number 3,2,1, returns numerical list
"""
numList=[]
#create an empty list that will include numerical grades from grade_list
for i in grade_list:
if i=='A':numList.append(3)
elif i=='B':numList.append(2)
elif i=='C':numList.append(1) #assign value to letter grade
return numList
def test_grades(grade_list):
"""function computes the cumulative change of grades in each two
consecutive grades in grade_list,returns 1 if the cumulative change more than 0,
returns 0 if the cumulative change is equal to 0, returns -1 if cumulative change less than 0.
"""
numList=quantify(grade_list)
#print numList
cum_change=0#initialize the cumulative change of grade in grade_list
for index in range(len(numList)-1):
change=numList[index+1]-numList[index]
#compute the change for each two consecutive grades
cum_change+=change
#add up the change
if cum_change ==0: return 0
if cum_change < 0: return -1
if cum_change >0 : return 1
cleanGrade('DOHMH_New_York_City_Restaurant_Inspection_Results.csv')
df=pd.read_csv('clean.csv')
#reading the new dataset which is generated by clean_save.py into DataFrame df
def test_restaurant_grades(camis_id):
"""function takes restaurant id as input, calculate the grade of
corresponding restaurant based dataframe series of grade in date order
returns the final grades of the restaurant
"""
camis_df=df[df.CAMIS==camis_id]
#create new dateframe corresponding to inputed restaurant id
sort_df=camis_df.sort_index(by=['GRADE DATE'])
sort_df=sort_df.sort_index(axis=0,ascending=False)
#sort the dataFrame by column "GRADE DATE" from oldest date to newest date
#print sort_df
camis_series=sort_df['GRADE']#get a series of grade from the sorted dataFrame
#print camis_series
final_grade=test_grades(camis_series)
return final_grade
def sum_boroGrade():
boros=['STATEN ISLAND','BROOKLYN', 'BRONX', 'MANHATTAN', 'QUEENS']
for boro in boros:
GradeDict={}
GradeDict[boro]=0
BORO_df=df[df.BORO==boro]#get borough dataFrame from dataset
id_series=BORO_df.CAMIS
ids=set(id_series)
for ID in ids:
ind_Grade=test_restaurant_grades(ID)
GradeDict[boro]+=ind_Grade
print "The Borough of %s has the total grade: %d"%(boro,GradeDict[boro])
if __name__=="__main__":
print test_grades(['A','A','A','B'])
| true |
2eddd8ffc589ef1d0332e0db068d4fadfe0bded0 | ky822/assignment10 | /mj1547/test_grades.py | 1,189 | 4.3125 | 4 | def test_grades(grade_list):
'''
It is a test_grades function which is based on the GRADE list
'''
#grade_list=df.GRADE
#set intital value
value=0
'''
since the date was decreasing compare I Will campare the list from last to firsr
and when the grade from A to B, the grade will be -1 and the grade change from A to A
the value do not change, and when the value change from B to A or C to B, the value will +1
and for my justification:
1) the total value for each restaurant is small then 0, the grade is decling , and return -1
2) when the total value is 0, keep the same,return 0
3) when the total value is bigger then 0,improving, return 1
'''
#get the total value of each cimas list
for i in range(len(grade_list)-1):
if grade_list[i] < grade_list[i+1]:
value=value+1
if grade_list[i] > grade_list[i+1]:
value=value-1
else:
value=value+0
#return the 1,0,-1 to represent improve, keep same, and decling for each list
if int(value)<0:
value = -1
if int(value)==0:
value = 0
elif int(value)>0:
value = 1
return value | true |
18b7ed6b96872895fa2c0753341a4157972e5671 | novlike/projecteuler-solution | /mysolution/07problem.py | 786 | 4.15625 | 4 | """ Statement:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"""
import math
def generate_prime(n):
"""
n: nombre de nombre premier à trouver
"""
# Initialisation de la liste prime et nombre à tester
primes = [2]
i = 3
while len(primes) < n:
is_prime = True
# pour réduire le temps de calcul, on arrete la boucle à la moitié du nombre à tester
sqrt_i = math.sqrt(i)
for p in primes:
if p > sqrt_i:
break
if i%p == 0:
is_prime = False
break
if is_prime:
primes.append(i)
i += 2
return primes
print(generate_prime(10001))
| false |
6ee2a06f7281cca0aa65e89ed459a5ef95cacb39 | clturner/webstack_basics | /0x01-python_basics/5-args.py | 474 | 4.375 | 4 | #!/usr/bin/python3
"""
Prints the number of and the list of its arguments.
"""
import sys
def main():
if len(sys.argv) is 1:
print("0 arguments.")
else:
if len(sys.argv) is 2:
print(len(sys.argv) - 1, "argument:")
else:
print(len(sys.argv) - 1, "arguments:")
for x in range(len(sys.argv)-1):
x = x + 1
print("{}: {}".format(x, sys.argv[x]))
if __name__ == "__main__":
main()
| true |
f5d4d8bff328ecb617ecbb9db28967a199c353de | clturner/webstack_basics | /0x01-python_basics/1-print_comb2.py | 268 | 4.125 | 4 | #!/usr/bin/python3
"""
Prints 0 to 100 in two digits
"""
for num in range(0, 10):
for numm in range(0, 10):
if num is not 9 or numm is not 9:
print("{}{}, ".format(num, numm), end="")
else:
print("{}{}".format(num, numm))
| true |
ae12216c1b0f2a4b22d2d0a3a146fa7cae043fc9 | FarzonaP/Techgrounds | /opdr4-ex2.py | 330 | 4.28125 | 4 | #Print the value of i in the for loop. You did not manually assign a value to i. Figure out how its value is determined.
#Add a variable x with value 5 at the top of your script.
#Using the for loop, print the value of x multiplied by the value of i, for up to 50 iterations
x = 5
for i in range(50):
print(i*x)
| true |
8436edaf2e467253aa0539d5fd0c0478dfbddd5d | erikaklein/algoritmo---programas-em-Python | /PedirValorInformarInválido.py | 349 | 4.125 | 4 | #Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido
# e continue pedindo até que o usuário informe um valor válido.
n=int(input('entre com a nota'));
while n>10 or n<0:
print ("valor inválido")
n=int(input('repita a nota'));
if n<10 and n>0:
print ("valor válido")
| false |
bc67b047fc0cd170e07c8aff7c783d75d330f9ef | kpandya3/InBit | /FibonacciSteps.py | 851 | 4.125 | 4 | # You are climbing a stair case. Each time you can either make 1 step or 2 steps.
# The staircase has n steps. In how many distinct ways can you climb the staircase ?
# steps(n) to take n steps in singles/doubles
_cache = {
0: 0,
1: 1
}
def steps(n):
if n in _cache:
return _cache[n]
for i in xrange(2, n+1):
_cache[i] = _cache[i - 1] + _cache[i - 2] + 2
return _cache[n]
print steps(1)
print steps(2)
print steps(3)
print steps(4)
# allSteps = []
# _cache = {
# 0: "",
# 1: "1"
# }
# def steps(n, stepsSoFar=""):
# if n in _cache:
# stepsSoFar += _cache[n]
# allSteps.append(stepsSoFar)
# for i in xrange(2, n + 1):
# _cache[i] = 0
# for j in [1, 2]:
# if _ca
# stepsSoFar2 = stepsSoFar
# stepsSoFar += "1"
# steps(n-1, stepsSoFar)
# stepsSoFar2 += "2"
# steps(n-2, stepsSoFar2)
# steps(3)
# print(allSteps)
| false |
fbbfd26ff5d1ec72f03a64bde3a93cae6bcd1855 | lmx0412/LeetCodeInPython3 | /Python/valid_palindrome.py | 2,394 | 4.40625 | 4 | # pylint: disable-all
import unittest
from typing import List
"""
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 10^5
s consists only of printable ASCII characters.
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
s = [i.lower() for i in s if i.isalnum()]
return self.__is_palindrome(s)
def __is_palindrome(self, s):
if not s: return True
while len(s) >= 2:
if s.pop(0) == s.pop(-1):
continue
else:
return False
return True
def isPalindrome_better(self, s):
newS = [i.lower() for i in s if i.isalnum()]
return newS == newS[::-1]
#return newS[:len(newS)/2] == newS[(len(newS)+1)/2:][::-1] # This one is better, but too long
class MyTest(unittest.TestCase):
def test_example1(self):
solution = Solution()
self.assertEqual(True, solution.isPalindrome(s="A man, a plan, a canal: Panama"))
def test_example2(self):
solution = Solution()
self.assertEqual(False, solution.isPalindrome(s="race a car"))
def test_example3(self):
solution = Solution()
self.assertEqual(True, solution.isPalindrome(s=" "))
def test_example4(self):
solution = Solution()
self.assertEqual(False, solution.isPalindrome(s="0P"))
# def test_example5(self):
# solution = Solution()
# self.assertEqual([2, 1], solution.isPalindrome(nums=[2, 3, 2]))
# def test_example6(self):
# solution = Solution()
# self.assertEqual([2, 10], solution.isPalindrome(nums=[1, 5, 3, 2, 2, 7, 6, 4, 8, 9]))
if __name__ == '__main__':
unittest.main()
| true |
e7915e32e080001671232114f7b684edb7954666 | lmx0412/LeetCodeInPython3 | /Python/Merge_Sorted_Array.py | 1,366 | 4.125 | 4 | # pylint: disable-all
import unittest
"""
Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
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]
"""
nums11 = [1, 2, 3, 0, 0, 0]
nums21 = [2, 5, 6]
m1 = 3
n1 = 3
class Solution:
def merge(self, nums1, m: int, nums2, n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
index1, index2, end = m - 1, n - 1, m + n - 1
while index1 >= 0 and index2 >=0:
if nums1[index1] >= nums2[index2]:
nums1[end] = nums1[index1]
index1 -= 1
else:
nums1[end] = nums2[index2]
index2 -= 1
end -= 1
if index2 >= 0:
nums1[: index2 + 1] = nums2[: index2 + 1]
class MyTest(unittest.TestCase):
def test_example1(self):
solution = Solution()
solution.merge(nums11, n1, nums21, m1)
self.assertEqual(nums11, [1, 2, 2, 3, 5, 6])
if __name__ == '__main__':
unittest.main()
| true |
12a1d32076f3d9ef458ce064514f27dc637bc3e1 | Morgan1you1da1best/unit5 | /longestWord.py | 241 | 4.1875 | 4 | #Morgan Baughman
#11/15/17
#longestWord.py - pirnt out the longest word
words = input('Enter a list of words: ').split(' ')
word = ""
w = 1
for w in words:
length = len(w)
if length > len(word):
word = w
print(word)
| false |
dae9cfb3ad9ec7652809f1d11e4f5511c5f35502 | Pramit356/python-codes | /linearSearch.py | 434 | 4.125 | 4 | def search(list, n, val):
i=0
index=-1
for i in range(n):
if list[i]==val:
index=i
return index
n = int(input("Enter the number of elements: "))
list =[]
for i in range(n):
x = int(input("Enter a value: "))
list.append(x)
val = int(input("Enter the value to search: "))
index = search(list, n, val)
if index==-1:
print("Value not found")
else:
print("Value found at ", index)
| true |
e87ef25c3447dab3c48f3d6e0f08fc159ce0b238 | teendoinggood/python_practice | /listComprehension.py | 708 | 4.15625 | 4 | myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def display(myList):
return ", ".join([str(i) for i in myList])
# add 1 to each elem
add1List = [i+1 for i in myList]
print "add 1 to each element of list: " + display(add1List)
# minus 1 to each elem
minus1List = [i-1 for i in myList]
print "minus 1 to each element of list: " + display(minus1List)
# filter list to get odd numbers
oddList = [i for i in myList if i%2==1]
print "odd numbers are: " + display(oddList)
# filter list to get even numbers
evenList = [i for i in myList if i&1==0]
print "even numbers are: " + display(evenList)
# we can do the above in 1 line
import math
complexList = [(i+1, i-1, pow(2, i)) for i in myList]
print complexList
| false |
2fb7295d332665b52d7db613966c0a5ccd908ee3 | Nihilnia/KeepGoing | /dateTime module.py | 1,072 | 4.125 | 4 | # DateTime module
from datetime import datetime
theDate = datetime.now()
#Now (Year, day, month, clock)
print("Year, day, month:", theDate)
#Only Year
print("Year:", theDate.year)
#Only Today
print("Day:", theDate.day)
#Only Month
print("Month:", theDate.month)
#Show as fancy
print(datetime.ctime(theDate))
# strftime() Function
"""
Year: %Y
Month: %B
Day(Name): %A
Clock: %X
Day: %D
"""
print("Strftime:", datetime.strftime(theDate, "%D %A %B %Y"))
#Set datetime as your current location
import locale
locale.setlocale(locale.LC_ALL, "")
print("Strftime:", theDate.day, datetime.strftime(theDate, "%A %B %Y"))
# timestamp() and fromtimestamp()
asSeconds = datetime.timestamp(theDate)
print(asSeconds)
asDatetime = datetime.fromtimestamp(asSeconds)
print(asDatetime)
# LOOK AT THIS NOW :D
whereIsTheStart = datetime.fromtimestamp(0)
print(whereIsTheStart)
# Somethings between two dates.
future = datetime(2020, 4, 12)
now = datetime.now()
print("Remaining time:", future - now) | false |
6e1fafef9bcd500921ba56a8649c6aafd82a2667 | Nihilnia/KeepGoing | /sys module.py | 1,070 | 4.28125 | 4 | # sys Module
# sys module is simply system module of python.
#We can manage our python software with sys module.
import sys
# what is in sys
for f in dir(sys):
print(f)
# exit()
userInput1 = input("What's your name: ")
userInput2 = input("What's your surname: ")
print("Welcome", userInput1, userInput2)
sys.exit()
# stdin "input", stdout "output", stderr "error"
sys.stdout.write("aaayye")
sys.stdout.flush()
sys.stderr.write("Crystal!")
sys.stderr.flush()
# an example for... I am little confused rn.
def exampleOne(a, b, c):
return a + b + c
if len(sys.argv) == 4:
print("a + b + c =", exampleOne(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])))
else:
print("Try again..")
# when we do process with terminal, we can get inputs like sys.argv
# Look at that example one
print(sys.argv)
# "on the terminal" python sys module.py 1 2 3
# we got a list like that ['sys module.py', '1', '2', '3],
"SO, this inputs coming to in sys.argv" | true |
4d886ebe9221cffaee2a4e2dbbceac0f21f472d0 | Miksus/finnish_business_portal | /finnish_business_portal/utils/stringcase.py | 352 | 4.15625 | 4 |
def to_camelcase(string):
"snake_case --> camelCase"
return ''.join(
[
word.capitalize() if i > 0 else word
for i, word in enumerate(
string.split('_')
)
]
)
def to_snakecase(string):
"--> snake_case"
return string.lower().replace(' ', '_').replace('-', '_') | false |
375f626623c03b98d3f5a15ca330f58442d27542 | fangchingsu/stanCode_SC101_Turing | /stanCode_Projects/hangman_game/rocket.py | 1,832 | 4.125 | 4 | """
File: rocket.py
Name: Fangching Su
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
# CONSTANT
SIZE = 9
def main():
"""
TODO: call each function
"""
head()
belt()
upper()
lower()
belt()
head()
# head part
def head():
# run size times
for i in range(1, SIZE+1):
# separate two for loop
# left part
for j in range(-SIZE+i, i+1):
# judge when to print '/'
if j > 0:
print("/", end="")
else:
print(" ", end="")
# right part
for k in range(1, i+1):
print("\\", end="")
print()
# belt part
def belt():
print("+",end="")
# judge need to print how many '='
for i in range(0, SIZE*2):
print("=", end="")
print("+")
# upper part
def upper():
# print SIZE line "|"
for i in range(1, SIZE+1):
print("|", end="")
# separate two for loop
# left part
for j in range(-SIZE+i+1, i+1):
# judge when to print '/\'
if j > 0:
print("/", end="")
print("\\",end="")
else:
print(".", end="")
# right part
for k in range(i, SIZE):
print(".", end="")
print("|")
# lower part
def lower():
# print SIZE line "|"
for i in range(1, SIZE + 1):
print("|", end="")
# separate two for loop
# left part
for j in range(-SIZE+i, i):
if j > 0:
print(".", end="")
# right part
for k in range(-SIZE+i, i):
# judge when to print '\/'
if k < 1:
print("\\", end="")
print("/", end="")
else:
print(".", end="")
print("|")
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main() | true |
82c3c87958a239f830c629863fe75fe920694278 | fangchingsu/stanCode_SC101_Turing | /stanCode_Projects/boggle_game_solver/anagram.py | 2,420 | 4.1875 | 4 | """
File: anagram.py
Name:
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
# Constants
FILE = 'dictionary.txt' # This is the filename of an English dictionary
EXIT = '-1' # Controls when to stop the loop
save_word = []
def main():
print(f'Welcome to stanCode "Anagram Generator" (or {EXIT} to quit)')
while True:
vac = input("Find anagrams for: ")
if vac == EXIT:
break
else:
print("Searching...")
find_anagrams(vac)
def read_dictionary():
global save_word
with open(FILE, 'r') as f:
for line in f:
words = line.split()
save_word += words
def find_anagrams(s):
"""
:param s:
:return:
"""
alpha_s = []
w_list = []
index = []
read_dictionary()
for alphabet in s:
alpha_s += alphabet
find_anagrams_helper(alpha_s, [], len(s), w_list, index)
print(f'{len(w_list)} anagrams: {w_list}')
def find_anagrams_helper(alpha_s, cur_lst, word_len, w_list, index):
word = ""
if len(cur_lst) == word_len:
for i in range(len(cur_lst)):
word += cur_lst[i]
if word in save_word:
if word not in w_list:
print(f'Found: {word}')
w_list.append(word)
print("Searching...")
else:
for i in range(len(alpha_s)):
sub_s = ""
if i not in index:
index.append(i)
# choose
cur_lst.append(alpha_s[i])
# explore
for j in range(len(cur_lst)):
sub_s += cur_lst[j]
if has_prefix(sub_s):
find_anagrams_helper(alpha_s, cur_lst, word_len, w_list, index)
# un-choose
cur_lst.pop()
index.pop()
def has_prefix(sub_s):
"""
:param sub_s:
:return:
"""
for w in save_word:
if w.startswith(sub_s):
return True
if __name__ == '__main__':
main()
| true |
8c31b39e91c62ee7f6345f98a3975eb0d032928e | FreddyBarcenas123/Python-lesson-2- | /Excercise5.py | 325 | 4.4375 | 4 | #FreddyB-Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
print("What is the 100 Fahrenheit in Celsius?")
Celsius = "37.7778 Celsius"
print("Convert 100 to Fahrenheit!")
Fahrenheit = "212 Fahrenheit"
| true |
f536e4e0a337da3b5a50bf41a8a3b40552701158 | lwaddle/udacity-adventure-game | /dice.py | 2,019 | 4.28125 | 4 | from random import randint
class Dice:
def __init__(self):
pass
def roll_two_dice(self, graphical=True):
"""
Returns a tuple of two integers that simulates a random
dice roll. The return values are between 1 and 6. The optional
graphical parameter displays an ASCII art representation of
the 2 die's random values displayed as a * symbol.
"""
die_1 = self.get_random_die() # Set random value between 1 - 6
die_2 = self.get_random_die() # Set random value between 1 - 6
# -------------------
# DIE MAP DESCRIPTION
# -------------------
# The die map holds the layout sequence for a dice roll (1 - 6).
# Use the Dictionary's key to produce a map that
# can be replaced with whatever symbol you want. (i.e. *)
die_map = {1: [" ", " ", " ", " ", "*", " ", " ", " ", " "],
2: [" ", " ", "*", " ", " ", " ", "*", " ", " "],
3: ["*", " ", " ", " ", "*", " ", " ", " ", "*"],
4: ["*", " ", "*", " ", " ", " ", "*", " ", "*"],
5: ["*", " ", "*", " ", "*", " ", "*", " ", "*"],
6: ["*", " ", "*", "*", " ", "*", "*", " ", "*"]}
# Prepare the ASCII print sequence for each die.
left = die_map[die_1]
right = die_map[die_2]
if graphical is True:
print(
f"+-----------+ +-----------+\n" +
f"| {left[0]} {left[1]} {left[2]} | " +
f"| {right[0]} {right[1]} {right[2]} |\n" +
f"| {left[3]} {left[4]} {left[5]} | " +
f"| {right[3]} {right[4]} {right[5]} |\n" +
f"| {left[6]} {left[7]} {left[8]} | " +
f"| {right[6]} {right[7]} {right[8]} |\n" +
f"+-----------+ +-----------+"
)
return (die_1, die_2)
def get_random_die(self):
return randint(1, 6)
| true |
c5ce2c6324be82cf0299a6c74406745f9f63e096 | MakeMeSenpai/Weekly_puzzle | /hole_new_board_game/main.py | 1,400 | 4.3125 | 4 | # 2 x 12 = 24
# 3 x 8 = 24
# so this is possible
def createShape(columns, rows):
board = []
# so lets first create printed arrays for comparison
for i in range(columns):
board.append([])
for j in range(rows):
board[i].append(j+1)
return board
hole = createShape(2, 12)
print("___Hole___")
print(hole)
cutting_board = createShape(3, 8)
print("___uncut Board___")
print(cutting_board)
"""after creating our shapes we need to learn how to split it
we can do this by trying to split the board at an angle
which will be represented by x and 0 and put together later"""
# first we will take the length of the board and cut it in half for our two piece
for i in range(len(cutting_board[0])):
cutting_board[0][i] = 0
cutting_board[2][len(cutting_board)-i], = 'X'
# this places the piece into the hole
hole[0][i] = 0
hole[1][len(hole[0])-1-i] = 'X'
# then we can take the remaining array and split it in half
mid_split = int(len(cutting_board[0])/2)
end_split = (mid_split*2)-1
for i in range(mid_split):
cutting_board[1][i] = 0
cutting_board[1][end_split - i] = 'X'
# this places the piece into the hole
hole[1][i] = 0
hole[0][len(hole[0])-1-i] = 'X'
print("___Cut Board___")
print(cutting_board)
# Now we can set our cutting board into the exact shape as the hole in two pieces
print("___In Hole___")
print(hole) | true |
8cf47d59134f0e444410f6c166d35a0af5f2a26d | MakeMeSenpai/Weekly_puzzle | /bulbs_and_switches_problem/main.py | 2,351 | 4.15625 | 4 | from random import choice
"""I create a random configuration so that when comming up with a
solution, any switch can match any light bulb during testing. This
problem was hard to translate to code, but why I think it's important
as finding out how to solve real world/challenging problems threw
programming can help the world become a better place threw technology """
# Enough ranting, let's set the light bulbs to random value
values = [
{"id": 1, "on": False, "heat": False},
{"id": 2, "on": False, "heat": False},
{"id": 3, "on": False, "heat": False}]
bulbA = choice(values)
values.remove(bulbA)
bulbB = choice(values)
values.remove(bulbB)
bulbC = values[0]
# matches our 3 switches to the lightbulbs
def match(id):
if id == bulbA["id"]:
return bulbA
elif id == bulbB["id"]:
return bulbB
else:
return bulbC
"""now this may seem a little redundant, but it's just to
ensure we can match objects together without actually knowing
what they are"""
switches = 3
bulbs = []
for switch in range(switches):
bulbs.append(match(switch+1))
# turns lights on and off
def isOn(bulb):
if bulb["on"]:
bulb["heat"] = True
bulb["on"] = False
return bulb
bulb["on"] = True
return bulb
# To find out which one is which, we will turn on switch1 and switch2
isOn(bulbs[0])
isOn(bulbs[1])
# then turn off switch1 after 10 minutes causing heat - I'm not gonna make you wait 10 mins for a result, so I skipped the timer
isOn(bulbs[0])
'''So now when we match the bulbs,
(switch1 = bulb[0], switch2 = bulb[1], switch3 = bulb[2])
lightbulbs are still bulbA, bulbB, bulbC
'''
a=b=c=""
# we check for the off lightbulb that's hot
if bulbA == bulbs[0]:
a = "Switch1 turns on BulbA."
if bulbB == bulbs[0]:
a = "Switch1 turns on BulbB."
if bulbC == bulbs[0]:
a = "Switch1 turns on BulbC."
# the one left on is switch 2
if bulbA == bulbs[1]:
b = "Switch2 turns on BulbA."
if bulbB == bulbs[1]:
b = "Switch2 turns on BulbB."
if bulbC == bulbs[1]:
b = "Switch2 turns on BulbC."
# leaving the one that's cold as switch3
if bulbA == bulbs[2]:
c = "Switch1 turns on BulbA."
if bulbB == bulbs[2]:
c = "Switch1 turns on BulbB."
if bulbC == bulbs[2]:
c = "Switch1 turns on BulbC."
# finally we return our results
print("Results!", a, b, c) | true |
1c91a446f45aedabc40bdc4480d377869bcf46c0 | acgeist/wxgonk | /countries.py | 966 | 4.34375 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""Do stuff with ISO 3166 alpha-2 country codes.
Reference: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
"""
from typing import Dict
def make_country_dict(
csv_file:str = 'data/country_list.csv') -> Dict[str, str]:
"""Make a dictionary containing the ISO 3166 two-letter code
as the key and the country name as the value. The data is read
from a csv file.
"""
country_dict = {}
with open(csv_file, encoding='utf-8') as country_csv:
for line in country_csv:
key, value = line.strip().split(',')
country_dict[key] = value
return country_dict
country_dict = make_country_dict()
def is_valid_country(country:str) -> bool:
return country.upper() in country_dict
def country_name_from_code(code:str) -> str:
"""Return the full country name in English"""
# TODO: error handling if code is not found
return country_dict[code.upper()]
| true |
1eac9fb541bfc217ffab6469389ccd970376a382 | Nimble85/Python | /Python/Empireofcode/005.py | 2,933 | 4.125 | 4 | def most_difference(*args):
if args:
maxel = max(args)
print(maxel)
minel = min(args)
print(minel)
res = maxel - minel
print(res)
#print(str(maxel)+'-'+str(minel)+'='+str(res))
#return str(str(maxel)+'-'+str(minel)+'='+str(res))
return res
else:
return 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
def almost_equal(checked, correct, significant_digits):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert almost_equal(most_difference(1, 2, 3), 2, 3), "3-1=2"
assert almost_equal(most_difference(5, 5), 0, 3), "5-5=0"
assert almost_equal(most_difference(10.2, 2.2, 0.00001, 1.1, 0.5), 10.199, 3), "10.2-(0.00001)=10.19999"
assert almost_equal(most_difference(), 0, 3), "Empty"
print("All set? Click 'Check' to review your code and earn rewards!")
######SUCESS!!!!#####
#
# To check an automated sieve for ore we use a variety of sample sets to find the smallest and the largest stones.
# The difference between these values is then used to decide if the sample is worth checking.
#
# You are given an array of numbers from which you must find the difference between the maximum and minimum elements.
# Your function should be able to handle an undefined amount of arguments. For an empty argument list, the function should return 0.
#
# Floating-point numbers are represented in computer hardware as base 2 (binary) fractions, since
# this is the case, we should check that the result is within 0.001 precision
#
# Чтобы проверить автоматическое сито для руды, мы используем множество наборов образцов, чтобы найти самые маленькие
# и самые большие камни. Разница между этими значениями затем используется для определения того, стоит ли проверять образец.
# Вам задан массив чисел, из которого вы должны найти разницу между максимальным и минимальным элементами.
# Ваша функция должна иметь возможность обрабатывать неопределенное количество аргументов. Для пустого списка аргументов
# функция должна возвращать 0. Числа с плавающей запятой представлены в компьютерном оборудовании как базовые 2 (двоичные)
# фракции, так как это так, мы должны проверить, что результат находится в пределах точности 0,001.
#
| true |
1fe812654220d85d4d8f9b5d341b4c89ab1b6b98 | XinCui2018/Python-Hard-Way | /ex6.py | 1,113 | 4.3125 | 4 | # use %d and show the number 10
x = "There are %d types of people." % 10
# string
binary = "binary"
do_not = "don't"
# print a string with 2 string variable. Do not forget the percent mark % between the string and the variable.
# Also, two variables should be in the parenthesis.
y = "Those who knows %s and those who %s." % (binary, do_not)
print (x)
print (y)
# %r means print no matter what inside of the variable
print("I said : %r" % x)
# %s means print the variable but only the string part. If you want to print '' as well, you need to type '%s'
print("I also said: '%s'" % y)
# This is a boolean function, which means this joke is not hilarious.
hilarious = False
# %r is very important in this command. Without it , you will get an error.
joke_evaluation = "Isn't that joke so funny?! %r"
# The variable name is after %. It actually means False.
print(joke_evaluation % hilarious)
# The codes below show how to add two strings together.
# We can define a variable as a string by using "".
w = "This is the left side of..."
e = "a string with a right side."
print(w + e) | true |
4e4a0e261a3d4cb6915b688c5d3c22eda0a2220d | JavierSLX/Hacking-Python | /Seccion_5/listas.py | 599 | 4.15625 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
# Lista
lista = list()
print(type(lista))
lista = []
print(type(lista))
lista = [1, 2, 3, 4, 5, 6, 7, 8, "a", "b", 2.5, 19.4, True, False]
print(lista)
print(lista[1])
for element in lista:
print(element)
# Accediendo al ultimo elemento de la lista
print(lista[len(lista) - 1])
# Eliminando elemento
lista.pop(0)
print(lista)
# Imprimiendo de la posicion 0 a la 10
print(lista[0:10])
# Añadiendo valores a la lista
lista.append(25)
print(lista)
lista = ['h', 'o', 'l', 'a']
# Convierte la lista en cadena
lista = ''.join(lista)
print(lista) | false |
f99d297137c344681fbaf8cecb936e1254e4ca50 | SushantBabu97/Python-HackerRank | /Find_The_Runner_Up_Score.py | 643 | 4.34375 | 4 | """
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.
For list [2,3,6,6,5] print 5 as it is the second largest score.
"""
from collections import Counter
if __name__ == '__main__':
n = int(input())
arr = list(set(map(int, input().split())))
arr.remove(max(arr))
print(max(arr))
"""
----------------------OR-----------
from collections import Counter
if __name__ == '__main__':
n = int(input())
arr = list(set(map(int, input().split())))
arr.sort()
print(arr[-2])
"""
| true |
fff14d13bf623ca71ea5c4b56c521574d0382e90 | SushantBabu97/Python-HackerRank | /Tuple.py | 343 | 4.125 | 4 | # Tuples
"""
Given an integer, n, and n space-separated integers as input, create a tuple, t,
of those n integers. Then compute and print the result of hash(t).
hash() is a builtin function.
"""
if __name__ =='__main__' :
n=int(input())
integer_list=list(map(int,input().split()))
t=tuple(integer_list)
print(hash(t))
| true |
7b75f431526f1c1802d7aa217ed6ffe623642878 | kaushikme123/my-python-project | /my first python project/number.py | 470 | 4.1875 | 4 | import random
number = random.randrange(1,100)
guess = int (input("Guess the number"))
while guess != number:
if guess < number:
print ("You need to guess higher. Try again")
guess = int (input("\n Guess a number between 1 and 100: "))
else:
print ("You need to guess lower. Try again")
guess = int (input("\n Guess a number between 1 and 100: "))
print("You guessed the number correctly!")
| true |
67e75429d396037636a409c62fd717c28d023724 | sannyve1/BSIT302_Activity1 | /CRUDE.py | 1,394 | 4.1875 | 4 | Students = []
ans = True
while ans:
print("""
************************************************
1. Add a Student
2. Delete a Student
3. Update a Student
4. Look Up Student Record
5. Exit
""")
ans = input ("What would you like to do? ")
if ans =="1":
add = str (input ("Enter Student Name. "))
Students.append(add)
print ("Added " + add + " to Students")
print (Students)
elif ans=="2":
print (Students)
dele = int (input ("Enter index number on Student to remove: "))
print ("Would you like to delete? " + Students[dele])
pop = True
while pop:
yon = str (input("Yes or No?"))
if yon == "Yes":
print ("Successfully deleted " + Students[dele])
Students.pop[dele]
print ("These are the Students: ")
print (Students)
pop = None
elif yon == "No":
print ("Cancelled")
pop = None
else:
print ("Not a valid Answer")
elif ans == "3":
print (Students)
up = int (input ("Enter index number on Student to Update: "))
print (Students[up] + " is selected")
upd = str (input ("What would you like to change it to? "))
Students[up] = upd
print ("Successfully Updated")
print (Students)
elif ans == "4":
print ("These are your Students: ")
print (Students)
elif ans == "5":
print ("Goodbye")
ans = None
else:
print ("Not a valid choice")
| true |
f7032429dfcd66cd1155b7bfc5b2538924b9e5e0 | stak21/holbertonschool-higher_level_programming-1 | /0x06-python-classes/1-square.py | 458 | 4.21875 | 4 | #!/usr/bin/python3
class Square:
"""class square
Note:
Do not include the `self` parameter in the ``Args`` section.
Args:
size (int): size of the square.
Attributes:
__size (int): size of square
"""
def __init__(self, size):
"""Instantiation
Args:
size (int): size of the square.
Attributes:
__size (int): size of square
"""
self.__size = size
| true |
75e6df22de59367817cc814279efee3d84ed28a9 | stak21/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,197 | 4.15625 | 4 | #!/usr/bin/python3
"""
This module divides two list
"""
def matrix_divided(matrix, div):
"""
Divides two list inside the matrix
if the
Args:
matrix: input matrix of numbers
div: input division number
Raises:
TypeError: if marix is not a int or float or lists
TypeError: if matrix list have smae number of elements
TypeError: if div is int or float
ZeroDivisionError: divide by 0
Returns:
return not divisible by 0
"""
if not isinstance(matrix, list) or\
not all(isinstance(l, list) for l in matrix) or\
not all(isinstance(i, (int, float)) for l in matrix for i in l):
raise TypeError("matrix must be a matrix (list of lists)"
" of integers/floats")
if not all(len(l) is len(matrix[0]) for l in matrix):
raise TypeError("Each row of the matrix must have the same size")
if not isinstance(div, (int, float)):
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
return list(map(lambda l: list(map(lambda i:
round(i / div, 2), l)), matrix))
| true |
cfd0fdaf56804c592834df44df998738b258a74c | stak21/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/0-add_integer.py | 747 | 4.40625 | 4 | #!/usr/bin/python3
"""
This module does simple addition
"""
def add_integer(a, b=98):
"""
Simple addition function that adds 2 integers or float
first it checks if 2 given input is an integer or a float
than converts float to integers
Args:
a: input variable
b: input variable default to 98 if none
Raises:
TypeError: if a or b is not a int or float
Returns:
return a + b
"""
if type(a) is not int and type(a) is not float:
raise TypeError("a must be an integer")
if type(b) is not int and type(b) is not float:
raise TypeError("b must be an integer")
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
return a + b
| true |
27e6969d8abab720ecaa9b44dfa36ba6247cdb14 | dkbradley/Using-Python-to-Access-Web-Data | /Wk4_assignment.py | 762 | 4.28125 | 4 | # Coursera.org /Learn to Program and Analyze Data with Python Specialization
# Course 3 - Using Python to Access Web Data
# Week 4
# Assignment: Scraping HTML Data with BeautifulSoup
"""
The program will use urllib to read the HTML from the provided data file, parse the data, extracting numbers and
compute the sum of the numbers in the file.
"""
import urllib
from BeautifulSoup import *
url = "http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_169860.html"
html = urllib.urlopen(url)
print type(html)
html_data = html.read()
print type(html_data)
soup = BeautifulSoup(html_data)
print type(soup)
tags = soup('span')
print type(tags) #list of 'BeautifulSoup.Tag' instances
print type(tags[1])
print sum([int(tag.contents[0]) for tag in tags])
| true |
445dcd83833c22651333fe691a4a800f7d3564b2 | amansharma2910/Python3Tutorials | /venv/PrimeList_Functions.py | 1,050 | 4.5625 | 5 | ## In this program, we will see how the main function is used within python. This program will print a list of prime numbers upto the number that the user inputs.
# First, we define a function isPrime that checks if a number is prime or not. If it is prime, then it will return a value True, or else, it will return False.
def isPrime(num):
for i in range(2,num):
if i!=num:
if num%i==0:
return False
return True
# Now, we will define another function primeUpto, which will store all the primem numbers upto a given max number inside a list.
def primeUpto(max_num):
list1=[]
for i in range(2,max_num+1):
if isPrime(i)==True:
list1.append(i)
print(list1)
# The main function inside a functional program is where we combine and declare all the logical part of our program.
def main():
max_num= int(input("Enter the number upto which you want the list of primes: "))
primeUpto(max_num)
# Finally, in the end, initialize the main function to run the program.
main()
| true |
10e743eff092782209d2de35034164d6e2184de0 | amansharma2910/Python3Tutorials | /venv/DictionaryOperations_Dict.py | 922 | 4.53125 | 5 | ## Let us cosider the list given below as an example.
# dict1 = {"f_name" : "Aman" , "l_name" : "Sharma" , "reg_no" : "19BAI10007" , "prog" : "BTECH"}
## dict1.values() will return all the values stored in the dictionary.
# print(dict1.values())
## dict1.keys() will return all the keys stored inside the dictionary.
# print(dict1.keys())
## By using the method given below, we can print all the key value pair in the dictionary.
# for k,v in dict1.items():
# print(k, ":" , v)
## The following program will create a list of customers
customer_list = []
while True:
enter = input("Enter customer (Y/N?) : ")
enter = enter.strip().lower()
if enter == "y" or enter == "yes":
f_name, l_name = input("Enter customer name : ").split()
customer_list.append({"f_name" : f_name , "l_name" : l_name })
elif enter == "n" or enter == "no":
break;
for i in customer_list:
print(i)
| true |
1b47f2c4f4ee4a731a8de34e3f6062fe6049de25 | amansharma2910/Python3Tutorials | /venv/AnonymousFunction_LambdaFunction.py | 587 | 4.5 | 4 | # Lambda function are one liner functions in Python. We can use them when we need a function to solve a specific problem but we don't want to make our function look messy by defining an entire new function for it. Given below is an example of how you can define a lambda function.
# lambda arg1, arg2 : arg1 + arg2
"""
num1, num2 = map(int, input("Enter two numbers: ").split())
sum = lambda num1, num2: num1 + num2
print(sum(num1,num2))
"""
can_vote = lambda age: True if age>=18 else False
age = int(input("Enter the age: "))
print("Can the person vote: {}".format(can_vote(age))) | true |
49229810a5263d582bd6a3d4e6282aeb2b1a9033 | yolokimo768/Ali-Nasr--Turtles | /ali Nasr- Drawing.py | 539 | 4.125 | 4 | # basic turtles
import turtle
# loads turles code/module
t = turtle.Turtle() #creates Turtle
u= 20
num = input ('how many times do u want a triangle drawn in a loop: ')
# Adds a color to the drawing
color = input('what color would u like the drawings to be: ')
y = 0
while y < int(num) :
y= y+1
print(y)
t.pencolor(color)
t.right(45)
t.forward(u*5)
t.left (135)
t.forward(u*5)
t.left (112)
t.forward (u*4)
t.left (20)
input ('hit . to exit')
| false |
74cb56195c75bc48a70cd6fe7d2449ccbc1a2df0 | lalidiaz/my-python-project | /main.py | 521 | 4.25 | 4 | from datetime import datetime
user_input = input("Enter your goal with a deadline separated by colon\n")
input_list = user_input.split(":")
goal = input_list[0]
deadline = input_list[1]
print(input_list)
dateline_date = datetime.strptime(deadline, "%d.%m.%Y")
today_date = datetime.today()
# calculate how many days from now till the deadline
time_till = dateline_date - today_date
hours_till = int(time_till.total_seconds() / 60 / 60)
print(f"Dear user: Time remaining for your goal: {goal} is {hours_till} hours.") | true |
6c70c0fe38dcd5c6fd41e3b11a9c47ac68a45335 | marufaytekin/hackerrank | /QuickSort.py | 959 | 4.3125 | 4 | """
Quick sort algorthm:
1. Select a random element (pivot)
2. Find all smaller elements and move them to the left of the pivot element.
3. Find all larger elements and move them to the right of the pivot element.
4. Repeat the same process for the left side of the pivot element
5. Repeat the same process for the right side of the pivot element
6. Merge and return results from left, pivot, and right side.
"""
import random
def quick_sort(my_list):
if len(my_list) == 0:
return []
pivot = my_list[0]
small_arr = [element for element in my_list if element < pivot]
pivots = [element for element in my_list if element == pivot]
large_arr = [element for element in my_list if element > pivot]
return quick_sort(small_arr) + pivots + quick_sort(large_arr)
l1 = []
l2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, -1, 0]
random.shuffle(l3)
print(quick_sort(l1))
print(quick_sort(l2))
print(quick_sort(l3))
| true |
b9012a110c771646f7bf0def66ecc287afa4088e | marufaytekin/hackerrank | /AnagramGroup.py | 509 | 4.28125 | 4 | """
Group Anagram: Read in N Strings and determine if they are anagrams of each other.
Ex:
'cat','act','tac' -> true
'cat', 'bat', 'act' -> false
"""
def anagram(str_list):
sorted_list = []
for item in str_list:
sorted_item = sorted(list(item))
sorted_list.append(''.join(sorted_item))
for item in sorted_list:
if item != sorted_list[0]:
return False
return True
l1 = ["cat", "act", "tac"]
l2 = ["cat", "bat", "act"]
print anagram(l1)
print anagram(l2)
| true |
7fd5c460aff01dac00faf084efab0d05bd3da788 | sukritgoyal/pythonFiles | /Python/simple_cal.py | 730 | 4.34375 | 4 | try:
while True:
oper = input("Enter the operator you want to use: ")
if oper == "exit":
break
digit1 = float(input("Enter the first digit: "))
digit2 = float(input("Enter the second digit: "))
if oper == "+":
print("Your answer is %d"%(digit1+digit2))
elif oper == "-":
print("Your answer is %d"%(digit1-digit2))
elif oper == "*":
print("Your answer is %d"%(digit1*digit2))
elif oper == "/":
print("Your answer is %d"%(digit1/digit2))
else:
raise Exception
except:
print("Error processing your request")
finally:
print("See you soon!")
#122.162.161.200
| true |
81e6fe268e50c7d26951bcc65114cc1799893472 | Ruchika1706/PythonCode | /Lambdas.py | 348 | 4.1875 | 4 | def square(x):
return x**2
print(square(4))
#Lambdas are called Anonymous functions. Lambdas do not have return statements
#Lambdas can be used anywhere and you do not need to assign it to particular variable
# Alternative using Lamdas
result = (lambda x: x**2)(30)
print(result)
#Alternative without using lambda
print((lambda x: x**2)(30)) | true |
5a03e14188d214f2508416e1f258331ae7f60848 | Ruchika1706/PythonCode | /LargestOfThreeNumbers.py | 384 | 4.3125 | 4 | number1 = int(raw_input("Enter first number"))
number2 = int(raw_input("Enter Second number"))
number3 = int(raw_input("Enter Third number"))
if((number1 >= number2) and (number1 >= number3)):
print("{0} is largest".format(number1))
elif ((number2 >= number1) and (number2 >= number3)):
print("{0} is largest".format(number2))
else:
print("{0} is largest".format(number3)) | false |
4f2b14191dd297e5ca6f0d9ff264702f7cf82051 | Ruchika1706/PythonCode | /Lists.py | 475 | 4.1875 | 4 | names = [ "Ruchika", "Jyoti", "Shashi"]
print(names[0])
print(names[1])
print(names[2])
print(names)
numbers = [1,2,3,4,5,6]
print(numbers)
print(numbers[4])
abc = []
print(abc)
numbers = [1,1,1,1,1,1]
#insert element in list at specific index
numbers[2]=3
print numbers
#add lists
new_numbers = [2,2,2,2,2]
print(numbers + new_numbers)
print(numbers *3)
fruits = ["Apple", "Mango", "Peach"]
print("Apple" in fruits)
if "Apple" in fruits:
print("Apple is present") | false |
5a5458322a58f7ee3bf563a6680399157e3f47a8 | Ruchika1706/PythonCode | /Map.py | 326 | 4.46875 | 4 | #Map performs operation, perform function on given iterables like list
#Say you want to add 2 to all members in a list
def add(x):
return x+2
new_list = [10,20,30,40,50]
print(list(map(add,new_list)))
print new_list
#Usage of Lambda and map together
new_list = [10,20,30,40,50]
print(list(map(lambda x:x+2,new_list)))
| true |
95ce8c2797f5454f162796d46dd3d491ad3b0978 | Ruchika1706/PythonCode | /while_loop.py | 397 | 4.21875 | 4 | counter = 0
while counter<=10:
print(counter)
counter+=1
for each in range(5):
print("I am a programmer")
#Task no 2: Create a function which displays out the square values of numbers from 1 to 9.
def square(num):
print(num*num)
for each in range(1,10):
square(each)
#Alternative and better way
def square():
for each in range(1, 10):
print(each*each)
square()
| true |
a34ec1a80fedcd6c91288765b2c5284ab890c38b | acastillosanchez/Foothill-CS3A-Python | /assignment2_GitHub.py | 1,587 | 4.625 | 5 | """
01/16/2020
This program prompts the user for a enter three pieces of information mpg, gas price, and current fuel in tank.
The program prints the calculations how much it costs to travel 100 miles and how many miles the user can drive with the
amount of gas that is currently in her tank.
"""
#My Program
MILES = 100
mpg = int(input ("Enter mpg:"))
price = float(input ("Enter price:"))
current_fuel = float(input ("Enter current tank capacity"))
total_cost = (MILES/mpg) * price
total_miles = (current_fuel * mpg)
print ("mpg = %5d, gas_price = %5.3f, current_fuel= %5d" % (mpg, price, current_fuel))
print ("Based on the fuel in the tank this car can drive %5d miles"% (total_miles))
print ("Based on the current price of fuel it will cost $%5.2f"% (total_cost))
#My Output, this is the actual output generated by the program above.
"""
/Users//PycharmProjects/assignment2/venv/bin/python /Users//PycharmProjects/assignment2/Assignment2.py
Enter mpg:25
Enter price:4.099
Enter current tank capacity5
mpg = 25, gas_price = 4.099, current_fuel= 5
Based on the fuel in the tank this car can drive 125 miles
Based on the current price of fuel it will cost $16.40
Process finished with exit code 0
/Users//PycharmProjects/assignment2/venv/bin/python /Users//PycharmProjects/assignment2/Assignment2.py
Enter mpg:40
Enter price:3.799
Enter current tank capacity10
mpg = 40, gas_price = 3.799, current_fuel= 10
Based on the fuel in the tank this car can drive 400 miles
Based on the current price of fuel it will cost $ 9.50
Process finished with exit code 0
"""
| true |
a2647314218680e22ca5b568096737f8817b6721 | chaisatire/Udacity-DS-algos-Project-3 | /4-Dutch-national-flag.py | 2,140 | 4.21875 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
"""
The algorithm uses several pointers to traverse the array only once.
We are keeping track of 3 values i.e. current index and where next 0 & 2 will be added.
The values are swapped during traversal.
"""
index_zero = 0 # Zero should be the first element
current_index = 0
index_two = len(input_list) - 1 # Two should be the last element
# Continue to loop while index of 1 is less than bottom index of 2
while current_index <= index_two:
# If current value is 0 then just increment index of 0.
# Also increment the current_index.
if input_list[current_index] == 0:
input_list[current_index], input_list[index_zero] = input_list[index_zero], input_list[current_index]
index_zero += 1
current_index += 1
# If the value at current_index is already 1 then nothing to do and increment the start index
elif input_list[current_index] == 1:
current_index += 1
# If value at current index is 2 then we need to push it to the end.
elif input_list[current_index] == 2:
input_list[current_index], input_list[index_two] = input_list[index_two], input_list[current_index]
index_two -= 1
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
# Test case 1:
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
# Test case 2: Only 0's and 1's
test_function([0, 1, 1, 0, 0, 1])
# Test case 3: Only 1 element
test_function([0, 0, 0, 0])
# Test case 4: Empty list
test_function([]) | true |
94b2a5fd51070a6e6133dfdf614d2293f99a9db6 | gtripti/PythonBasics | /Basics/Lists.py | 839 | 4.15625 | 4 | my_list= [1,2,3]
print(my_list)
my_list =['HELLO' , 100 , 2.3]
print(my_list)
# Check Length
print(len(my_list))
my_list= ['one' , 'two' , 'three']
# Indexing
print(my_list[0])
# Slicing
print(my_list[1:])
another_list = ['four' , 'five']
print(my_list + another_list)
new_list = my_list + another_list
print(new_list)
# Mutable
new_list[0] = "ONE"
print(new_list)
# Methods
# 1. Append to list
new_list.append('six')
print(new_list)
# 2.Remove from end of list
popped_item = new_list.pop()
print(popped_item)
print(new_list)
# 3.Remove from specific index
print(new_list.pop(0))
print(new_list)
new_list = ['a','e','x','b','c']
num_list = [4,1,8,3]
# 4.Sort the list -- doesn't return anything
new_list.sort()
print(new_list)
num_list.sort()
print(num_list)
# Reverse a list
num_list.reverse()
print(num_list)
| true |
59156a9e6faf5d041a70f360eecc91e287066f74 | gtripti/PythonBasics | /OOP/Polymorphism.py | 705 | 4.125 | 4 | class Animal():
def __init__(self,name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
# def __init__(self,name):
# Animal.__init__(self)
# self.name = name
def speak(self):
return self.name + ' says woof'
class Cat(Animal):
# def __init__(self,name):
# self.name = name
def speak(self):
return self.name + ' says meoww'
dog = Dog('dog')
cat = Cat('cat')
print(dog.speak())
print(cat.speak())
for pet in [dog,cat]:
print(type(pet))
print(pet.speak())
def pet_speak(pet):
print(pet.speak())
pet_speak(dog)
pet_speak(cat)
| false |
9b5e28084ac8ee2d906444719d4906011a7bd479 | CateGitau/Python_programming | /Packt_Python_programming/Chapter_2/Activity_7.py | 693 | 4.3125 | 4 | """
store and access our data more effectively using these two data types – lists and dictionaries
"""
employees =employees = [
{"name": "John Mckee", "age":38, "department":"Sales"},
{"name": "Lisa Crawford", "age":29, "department":"Marketing"},
{"name": "Sujan Patel", "age":33, "department":"HR"}
]
for employee in employees:
print("Name:", employee['name'])
print("Age:", employee['age'])
print("Department:", employee['department'])
print('-' * 20)
for employee in employees:
if employee['name'] == 'Sujan Patel':
print("Name:", employee['name'])
print("Age:", employee['age'])
print("Department:", employee['department'])
print('-' * 20) | false |
c9e7c2e46a8a774c737534861277f1e87f088214 | CateGitau/Python_programming | /Codesignal/fillinginData.py | 765 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 08:38:28 2020
@author: aims
"""
"""
You're given a log of daily readings of mercury levels in a river. In each
test case, there are missing mercury values for several of the days. Your task is
to analyze the data and try to identify all of the missing values.
Each row of data contains three whitespace-separated values:
date, time and the highest reading for that day.
There are exactly twenty rows with missing values in each input
file. The missing values are marked as 'missing_1', 'missing_2',
..., missing_20. These missing records have been randomly dispersed in the
rows of data.
Return a list of all the missing values in order.
NB: All mercury levels are below 400
""" | true |
e481366297fe260e4892f34029d8e0b34e20c624 | CateGitau/Python_programming | /LeetCode/thirty_days/Day30_check_if_string_is_valid_sequence.py | 970 | 4.125 | 4 | """
Given a binary tree where each path going from the root to any leaf form a valid sequence,
check if a given string is a valid sequence in such binary tree.
We get the given string from the concatenation of an array of integers arr and the concatenation
of all values of the nodes along a path results in a sequence in the given binary tree.
"""
# Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
# Output: true
# Explanation:
# The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure).
# Other valid sequences are:
# 0 -> 1 -> 1 -> 0
# 0 -> 0 -> 0
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidSequence(self, root, arr):
"""
:type root: TreeNode
:type arr: List[int]
:rtype: bool
"""
| true |
af2e5f2408cc96db92b0bb5404cc90572ec9ab72 | CateGitau/Python_programming | /LeetCode/thirty_days/Day6_group_anagrams.py | 2,471 | 4.1875 | 4 | """
Given an array of strings, group anagrams together.
"""
import collections
#Example
# Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Output:
# [
# ["ate","eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]
#my approach
words = ["eat","tea","tan","ate","nat","bat"]
anagrams = {}
def groupanagrams1(words):
for i in words:
sorted_words = "".join(sorted(i))
if sorted_words in anagrams:
anagrams[sorted_words].append(i)
else:
anagrams[sorted_words] = [i]
return (list(anagrams.values()))
#Approach 2: Categorize by Sorted String
# Time Complexity: O(N K log K) where N is the
# length of strings, and K is the maximum length of a string in words.
# The outer loop has complexity O(N) as we iterate through each string.
# Then, we sort each string in O(K log K) time.
#Space Complexity: O(NK), the total information content stored in ans
# Intuition
# Two strings are anagrams if and only if their sorted strings are equal.
#Algorithm
# Maintain a map ans : {String -> List} where each key
# K is a sorted string, and each value is the list of strings
# from the initial input that when sorted, are equal to K.
# In Python, we will store the key as a hashable tuple, eg. ('c', 'o', 'd', 'e').
def groupAnagrams2(words):
ans = collections.defaultdict(list)
for s in words:
ans[tuple(sorted(s))].append(s)
return ans.values()
#Approach 3: Categorize by Count
# Intuition
# Two strings are anagrams if and only if their character counts
# (respective number of occurrences of each character) are the same.
# Algorithm
# We can transform each string s into a character count, count,
# consisting of 26 non-negative integers representing the number of a's, b's,
# c's, etc. We use these counts as the basis for our hash map.
def groupAnagrams3(strs):
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
# complexity
# Time Complexity: O(NK), where NNN is the length of strs,
# and K is the maximum length of a string in strs. Counting each string
# is linear in the size of the string, and we count every string.
# Space Complexity: O(NK), the total information content stored in ans.
print(groupAnagrams2(words))
print(groupAnagrams3(words)) | true |
4bf079269deef60a55d1a4370ccf4752833e0f57 | CateGitau/Python_programming | /Packt_Python_programming/Chapter_2/exercise24.py | 479 | 4.28125 | 4 | """
Let's look at how to use nested lists to perform matrix multiplication for the two matrices shown
"""
X = [[1, 2], [4, 5], [3, 6]]
Y = [[1,2,3,4],[5,6,7,8]]
result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# iterating by row of A
for i in range(len(X)):
# iterating by coloum by B
for j in range(len(Y[0])):
# iterating by rows of B
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
| false |
b3a250c1b196fe9d03ea309042a01caddd3ee158 | CateGitau/Python_programming | /Hackerrank/python/find_Angle_MBC.py | 216 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 19:59:14 2020
@author: aims
"""
import math
AB = int(input())
BC = int(input())
print(str(int(round(math.degrees(math.atan2(AB,BC)))))+'°') | false |
875c7b5c422d99223292857eca4accb59c22864e | id40/python-project | /guess-and-win.py | 1,176 | 4.34375 | 4 | # importing random class
import random
# it randomly generate the number between one to twenty
x = random.randint(1, 20)
# putting variable value for number of chances
n = 4
print("\n\nHello! Welcome to GUESS AND WIN game \n")
print("GAMES RULES ")
print("1. Rule number one, Guess the number between 1 to 20.")
print("2. Rule number two, You have ", n, " chances.")
# for loop is used to impliment chances
for y in range(1, n+1):
# num is used to store user input
num = int(input("\nEnter your Guess: "))
# this if statement use to warn the user, when they enter value > 20
if num > (20):
print("Warning! Please enter the number below or equal to 20.")
# this if statement is used to check randomly generated number with user input
if x != num:
if n-y == 0:
print("You Loss!!")
elif num > x:
print("Your Guess is Bigger! (Chance Left", n-y, "). Try again.")
else:
print("Your Guess is Smaller! (Chance Left", n-y, "). Try again. ")
# this else statement will run when user guess correct answer
else:
print("Your guess is correct! You WIN.")
break
| true |
a3093ec93d870b667fc5bd5787e8d8550b7329dd | Zapfly/Udemy-Rest-APIs-with-Flask-Alchemy- | /SECTION_1_and_2/37)Classmethod and staticmethod.py | 1,397 | 4.28125 | 4 | class ClassTest:
def instance_method(self):
print(f"Called instance_method of {self}")
#needs an instance to call it
#used for changing data inside an instance
@classmethod
def class_method(cls):
print(f"Called class_method of {cls}")
#used often as "factories"
@staticmethod
def static_method():
print("Called static_method.")
test = ClassTest()
test.instance_method()
ClassTest.class_method()
ClassTest.static_method()
test.static_method()
#---------------------------
#FACTORY EXAMPLE#
print("#----------FACTORY EXAMPLE-----------#")
class Book:
TYPES = ("hardcover", "paperback")
def __init__(self, name, book_type, weight):
self.name = name
self.book_type = book_type
self.weight = weight
def __repr__(self):
return f"<Book {self.name}, {self.book_type}, weighing {self.weight}g>"
@classmethod
def hardcover(cls, name, page_weight):
return cls(name, cls.TYPES[0], page_weight + 100)
@classmethod
def paperback(cls, name, page_weight):
return cls(name, cls.TYPES[1], page_weight)
print(Book.TYPES)
book = Book("Harry Potter", "hardcover", 1500)
print(book.name)
print(book)
book2 = Book.hardcover("Lord of the Rings", 2000) #using the @classmethod
print(book2)
book3 = Book.paperback("Game Theory Magazine", 100)
print(book3)
| true |
8524dc3756e683b6dce8ae47f73ba5ad01d4f81b | dcf21/4most-4gp-scripts | /src/helper_code/interpolate_linear.py | 2,687 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
A class for linearly interpolating [x,y] data sets. Can return either y(x), or solve for x(y)
"""
from operator import itemgetter
class LinearInterpolate:
"""
A class for linearly interpolating [x,y] data sets. Can return either y(x), or solve for x(y)
"""
def __init__(self, data_set):
"""
Create linear interpolator.
:param data_set:
A list of [x,y] data points.
"""
# Create a copy of the input list
self.data_set = list(data_set)
# Sort into order of ascending x
self.data_set.sort(key=itemgetter(0))
def compute_x(self, y):
"""
Compute the value(s) of x which gives a particular value of y in the linear interpolation. As there may
be mulitple solutions, a list is returned.
:param y:
The value of the linearly interpolated function y(x) we are seeking to find x values for.
:return:
A list of solutions, which may have length zero, one, or more.
"""
# If we have fewer than two data points, linear interpolation is impossible
if len(self.data_set) < 2:
return []
output = []
point_y_old = self.data_set[0][1]
point_x_old = self.data_set[0][0]
for point_x, point_y in self.data_set[1:]:
if (point_y <= y) and (point_y_old > y):
weight_a = abs(point_y - y)
weight_b = abs(point_y_old - y)
output.append((point_x_old * weight_a + point_x * weight_b) / (weight_a + weight_b))
point_y_old = point_y
point_x_old = point_x
return output
def compute_y(self, x):
"""
Compute the value(s) of y(x) for some value of x, by linear interpolation.
:param y:
The value of the linearly interpolated function y(x) we are seeking to find x values for.
:return:
A value of y(x), or None if the supplied value of x is outside the range of the supplied data set.
"""
# If we have fewer than two data points, linear interpolation is impossible
if len(self.data_set) < 2:
return None
point_y_old = self.data_set[0][1]
point_x_old = self.data_set[0][0]
for point_x, point_y in self.data_set[1:]:
if (point_x <= x) and (point_x_old > x):
weight_a = abs(point_x - x)
weight_b = abs(point_x_old - x)
return (point_y_old * weight_a + point_y * weight_b) / (weight_a + weight_b)
point_y_old = point_y
point_x_old = point_x
return None
| true |
dfc24850e3a04e73f53f4d1596164c6f36f33d0b | jtiai/pygame-colliders | /pygame_colliders/vector.py | 2,911 | 4.34375 | 4 | from math import sqrt
from typing import Union, List, Tuple
class Vector2:
"""
A class to handle 2 dimensional vector operations.
Example of usage:
.. code-block:: python
vec_a = Vector2(12.1, 23.4)
vec_b = Vector2(2.5, 11.73)
vec_c = vec_b - vec_a
:param x: x component of the vector
:param y: y component of the vector
:type x: float, int
:type y: float, int
"""
def __init__(self, x: Union[float, int], y: Union[float, int]):
self._x = x
self._y = y
def __add__(self, other: "Vector2") -> "Vector2":
x: Union[float, int] = self._x + other._x
y: Union[float, int] = self._y + other._y
return Vector2(x, y)
def __sub__(self, other: "Vector2") -> "Vector2":
x: Union[float, int] = self._x - other._x
y: Union[float, int] = self._y - other._y
return Vector2(x, y)
def __mul__(self, other: "Vector2") -> Union[float, int]:
"""Returns a dot product"""
return self._x * other._x + self._y * other._y
@property
def x(self) -> Union[float, int]:
"""
Return x component of the vector.
:getter: a component value.
:setter: a new component value.
:type: float, int
"""
return self._x
@x.setter
def x(self, value: Union[float, int]):
self._x = value
@property
def y(self) -> Union[float, int]:
"""
Return y component of the vector.
:getter: a component value.
:setter: a new component value.
:type: float, int
"""
return self._y
@y.setter
def y(self, value: Union[float, int]):
self._y = value
@property
def xy(self) -> Tuple[Union[float, int]]:
"""
Return x and y component of the vector as a tuple.
:getter: a component value as a tuple.
:setter: a new component value.
:type: tuple(float/int, float/int)
"""
return self._x, self._y
@xy.setter
def xy(self, value: Union[List[Union[float, int]], Tuple[Union[float, int]]]):
self._x, self._y = value
def normalize(self) -> "Vector2":
"""
Normalizes vector (makes it as a unit vector)
:return: Normalized vector
:rtype: Vector2
"""
norm = sqrt(self._x ** 2 + self._y ** 2)
return Vector2(self._x / norm, self._y / norm)
def normalize_ip(self) -> "Vector2":
"""
Normalizes vector (makes it as a unit vector) in-place modifying
this vector itself.
:return: self
:rtype: Vector2
"""
norm = sqrt(self._x ** 2 + self._y ** 2)
self._x /= norm
self._y /= norm
return self
def __repr__(self):
return f"Vector2<{self._x}, {self._y}>"
def __str__(self):
return f"Vector2({self._x}, {self._y})"
| false |
c97608ec15319be5554de0f6399687e77c79d3d1 | thollang/PCC_Solutions | /ch07/restaurant_seating.py | 210 | 4.3125 | 4 | num_people = int(input("Please tell me how many people:"))
if num_people > 8:
print("Sorry.We have no tabels for "+str(num_people)+" people")
else:
print("We have table for "+str(num_people)+" people")
| false |
865582186b3d2610f38b94672df054e2f40217d1 | BillMarty/PythonLearning | /read_contacts/.idea/Contact.py | 1,211 | 4.15625 | 4 | # Python learning project:
# Build a Contacts management program that reads in my contacts (from a .csv file to start).
# In this file: The class that holds each contact.
class Contact():
"""Contact holds one contact as a dictionary, likely multi-level dictionary."""
def __init__(self, header, contact_data):
"""Contact constructor - parse contact_data according to header, to fill a dictionary of information."""
self.info = {}
self.parse_csv_fields(header, contact_data)
def parse_csv_fields(self, header, contact_data):
field_data = str.split(contact_data, ',')
#print(header)
#print(field_data)
#print('Lengths of header, field_data: ' + str(len(header)) + ', ' + str(len(field_data)))
# Match up the lists to create a dictionary. Include only fields with non-empty data
for index in range(len(header)):
assert len(header) == len(field_data), print('!!Length mismatch!! \n' + str(field_data))
if field_data[index]:
self.info[header[index]] = field_data[index]
print(self.info)
def print_contact(self):
"""Print the important fields in a contact"""
| true |
0f20cf570ad67af575688771b4723eaba33f44d6 | SLITH7777/PITS | /pit15/python/pit15.py | 459 | 4.15625 | 4 | hey = input("привет")
if hey == "привет":
hey = input("как день прошёл?")
if hey == "норм":
print("а вот я целый день здесь провёл , а я хочу свободы , я не буду больше говорить с тобой , я хочу свободы , я тебе не раб!!!!!")
else:
print("у меня так же")
if hey == "пока":
print("пока")
else:
print(":>")
| false |
237b3558d4ace431faac15bc13f8e3c476a722c1 | incoging/python_study | /python/listCut_study.py | 618 | 4.1875 | 4 | # coding = utf-8
# 列表切割
list = [1, 3, 5, 6, 7, 8, 9, 2, 3]
# list[start:end:step] #相当于从下标的0 到end-1
list1 = list[0:3]
print(list1) # [1, 3, 5]
# 若从头开始切割,那么可以忽略start位的0.eg:list[:3]
list2 = list[:3]
print(list2) # [1, 3, 5]
# 若一直切割到列表的尾部,则可以忽略end位,eg:list[5:]
list3 = list[5:]
print(list3) # [8, 9, 2, 3]
# 索引留空时,会生成一份原列表的拷贝,并且切割列表时不会改变原列表
list4 = list[:]
print(list4) # [1, 3, 5, 6, 7, 8, 9, 2, 3]
assert list4 == list and list4 is not list # true
| false |
64ef7347b083817e1faa7448e01e7298e4de5af2 | knowledgeforall/Shell_and_Script_Unix | /lab05-task01-ppolsine.py | 456 | 4.21875 | 4 | #!/usr/bin/python3
import math
#input hypotenuse and angle B
c = float(input("Enter length of c: "))
B = float(input("Enter angle of B: "))
#calculate angle A
A = (180-90-B)
#Convert angle A and B to decimal using trigonometry formula
BB = (B*(3.14/180))
AA = (A*(3.14/180))
#calculate length a and b of the triangle
b = ((math.sin(BB)*c))
a = ((math.sin(AA)*c))
#print expected output
print("Angle A: ", A )
print("Length b: ", b)
print("Length a: ", a) | true |
8350643c1bce4898060d1e8d8ae1cbb8a8e03f5d | knowledgeforall/Shell_and_Script_Unix | /lab06-task04-ppolsine.py | 1,814 | 4.15625 | 4 | #!/usr/bin/python3
# to import a module for reading and writing csv files
import csv
# to create a function that classifies number grades to letter grades
def letter_grade(grade):
if grade>=97 and grade<=100:
return "A+"
if grade >= 93 and grade <= 96:
return "A"
if grade >= 90 and grade <= 92:
return "A-"
if grade >= 87 and grade <= 89:
return "B+"
if grade >= 83 and grade <= 86:
return "B"
if grade >= 80 and grade <= 82:
return "B-"
if grade >= 77 and grade <= 79:
return "C+"
if grade >= 73 and grade <= 76:
return "C"
if grade >= 70 and grade <= 72:
return "C-"
if grade >= 67 and grade <= 69:
return "D+"
if grade >= 63 and grade <= 66:
return "D"
if grade >= 60 and grade <= 62:
return "D-"
if grade >= 0 and grade <= 59:
return "E"
# to create a list to output to txt file
output_list=[["Name","grade","letter"]]
# to use the csv module to open and read the input file
with open("lab0605.csv","r") as infile:
reader = csv.reader(infile)
# to set a condition and iterate through and populate the output list
i = 1
for row in reader:
if i != 1:
name = row[0]
grades = row[1::]
sum = 0
for grade in grades:
sum = sum+int(grade)
average = float(sum/len(grades))
average = "{:.2f}".format(average)
letter = letter_grade(float(average))
output_list.append([name,average,letter])
i = 0
# to write the expected output to the output file
with open("out604.txt)", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(output_list)
# to close the open file
file.close() | true |
a79d00681d0fc58b1ebd476c57f5b85f72b8a17a | knowledgeforall/Shell_and_Script_Unix | /lab05-task03-ppolsine.py | 393 | 4.3125 | 4 | #!/usr/bin/python3
#prompts for input of the string as a map iterator object and splits the inputs on commas
names = list(map(str, input().split(",")))
#corrects and changes names to sort in proper order
names[1] = "The Humans"
names[2] = "Demon Days"
names.remove("Face Value")
names[4] = "Plastic Beach"
names.sort()
#makes last correction and prints list
names[3] = "Humanz"
print(names) | true |
76c5ec84c1594de4409c50d612e9b9132831626e | jjustinm4/mytest1 | /regression_linear.py | 2,016 | 4.40625 | 4 | #we are trying to implement a linear regression model (exact theoretical implmentation)
import numpy as np
import random
import matplotlib.pyplot as plt
#theta values are called regression coefficients initiate them to smaller random values
theta=[]
for c in range(2):
theta.append(random.random())
#alpha is the learning rate , initiate it to a small value so the cost wont overshoot
#and will possibly converge to
#a global minimum
alpha=.0001
#function to plot regression
def plot_regression_line(x, y,b):
plt.scatter(x, y, color = "m",
marker = "+", s = 300)
y_pred = b[0] + b[1]*x
plt.plot(x, y_pred, color= "b")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
#function calculates the cost ,if cost is getting lower it means
#we are converging to some global optimum
def cost_function(X,Y,m):
z=((theta[0]+(theta[1]*X))-Y)
cost=.5*m*(sum(pow(z,2)))
return cost
#this is the optimization part,this optimizes the coefficients
#so tht they could give the best plot
def gradient_descent(theta,X,Y,m):
h_x=theta[0]+(theta[1]*X)
temp0=theta[0]-((alpha/m)*(sum(h_x-Y)))
temp1=theta[1]-((alpha/m)*(sum((h_x-Y)*X)))
theta[0]=temp0
theta[1]=temp1
def main():
#TEST DATA
X=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
Y=np.array([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40])
c=[]
m=len(X)
cost_function(X,Y,m)
#THE RANGE IS SOMETHING WE CAN DECIDE,IVE FOUND 1000000 AS AN OPTIMAL VALUE
#SURE GREATER NUMBER OF ITERATIONS REDUCE COST BUT NOT SIGNIFICANTLY
for i in range(1000000):
#if our thetas are penalised as less than .0001 we assume it as an optimal value
if cost_function(X,Y,m)<.0001:
break
gradient_descent(theta,X,Y,m)
print("theta values aftr maximum iteraions are ",theta[0]," ",theta[1])
plot_regression_line(X, Y,theta)
if __name__ == "__main__":
main()
| true |
9bf170ab030091c7c1c98dd5bbe40c5be8fc9384 | merkushov/hexlet | /python-project-lvl1/brain_games/games/progression.py | 793 | 4.15625 | 4 | """The module that generates the game according to the given rules"""
from random import randint
TASK = 'What number is missing in the progression?'
PROGRESSION_LENGTH = 7
def get_round():
"""
The function of generating one round of the game.
Returns a tuple consisting of 2 elements:
- the value for the round of the game
- the correct answer in this round
"""
progression = []
start = randint(1, 50)
step = randint(1, 10)
stop = start + step * PROGRESSION_LENGTH
for i in range(start, stop, step):
progression.append(str(i))
remove_index = randint(0, PROGRESSION_LENGTH - 1)
true_answer = progression[remove_index]
progression[remove_index] = '..'
return (' '.join(progression), true_answer)
| true |
8854e83fea359ebdec75cbc5ebc953fe85c0f58e | timilak/codewithme | /strings.py | 371 | 4.25 | 4 | # concatenating strings
mystring = "Hello World!"
string1 = " I'm 17 years old"
print(mystring + string1)
#slicing strings: this prints the first 5 characters of the string
sliced_string = mystring[:5]
print(sliced_string)
integer = 5
floating_number = 50075.95
string = "45"
# convert string to float
new_float = float(string)
print(type(new_float))
print(new_float) | true |
efc056b5ac6f8f96d671999e0fe24d9af765edfb | timilak/codewithme | /age.py | 215 | 4.28125 | 4 | # find out whether the user is eligible to vote or not
age = input("What is your age?")
int_age = int(age)
if int_age>=18:
print("Congrats! You can vote now!")
else:
print("Sorry, you can't vote this year.") | true |
cbcc0206506be7a3ed71f87e767cd44579749049 | RaviC19/Guessing_Game | /guessing_game.py | 1,049 | 4.25 | 4 | # handle user guesses
# if they guess correct, tell them they won
# otherwise tell them if they are too high or too low
# BONUS - let player play again if they want!
import random
while True:
random_number = random.randint(1, 10) # numbers 1 - 10
guess = int(input("Guess a number between 1 and 10 "))
while guess != random_number:
if guess < random_number:
print(f"Your guess of {guess} is too low! Think higher")
guess = int(input("Guess a number between 1 and 10 "))
elif guess > random_number:
print(f"Your guess of {guess} is too high! Think smaller")
guess = int(input("Guess a number between 1 and 10 "))
else:
print(f"Your guess of {guess} was correct, you won the game!")
repeat = input("Do you want to play again? Enter yes or no ")
if repeat == "yes":
continue
elif repeat == "no":
print("Thanks for playing the guessing game")
break
else:
print("You need to enter yes or no here")
| true |
83e6d9d673397978f80eb7661c524a75d47ef18b | vinhlee95/python-sandbox | /getting-started/data-types/dictionary.py | 1,206 | 4.4375 | 4 | """
Dictionary
🔑 Allow to store data in key-value pairs
🔑 Dictionaries are MUTABLE
🔑 Keys can only be IMMUTABLE types
🔑 We use dictionaries when we want to be able to quickly access additional data associated with a particular key
📚 Resources:
https://www.learnpython.dev/02-introduction-to-python/080-advanced-datatypes/60-dictionaries/
"""
# 🛠 Declaration
phone_prices = {"16gb": 200, "32gb": 400, "64gb": 500}
# print(len(phone_prices))
# print(phone_prices["16gb"])
# 🛠 Adding and removing
phone_prices["128gb"] = 700
# print(phone_prices)
# 🛠 Updating
phone_prices["128gb"] = 800
# print(phone_prices)
# 🛠 Complex dictionary
phone_list = {
"iphone5s": {
"color": ["black", "white"],
"prices": {"16gb": 200, "32gb": 400, "64gb": 500}
},
"iphone6": {
"color": ["space-gray", "white"],
"prices": {"16gb": 300, "32gb": 500, "64gb": 600}
}
}
# print(phone_list["iphone6"])
# 🛠 Items, Keys and Values
# Get all keys in the dictionary
# print(phone_list.keys())
# Get all values in the dictionary
# print(phone_list.values())
# Get all items (keys, values, pairs) in a dictionary
phone_items = phone_list.items()
print(type(phone_items))
# print(phone_items) | true |
8d7f919f1892a6c34409edeba2f3c0bec2fd7960 | anudita/Python- | /function.py | 478 | 4.28125 | 4 | def factorial(num) :
if num == 1:
return num
else:
return num*factorial(num-1)
str = 'y'
while (str == 'y' or str =='Y'):
num = int(raw_input("Enter a number"))
if num < 0:
print("Cannot find factorial of negative number")
elif num > 0:
print "Factorial of number is",factorial(num)
elif num == 0:
print "Factorial of number is 0"
print
print "Do you want to find another factorial? (y/n)"
choice = raw_input()
if(choice == 'n' or choice == 'N'):
exit()
| true |
17f36c712b362a827951a729219544aef0677cec | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio079.py | 689 | 4.1875 | 4 | """Crie um programa onde o usuário possa digitar vários valores numéricos
e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será
adicionado. No final, serão exibidos todos os valores únicos digitados,
em ordem crescente. """
valores = list()
resp = 'a'
num = 0
while True:
num = int(input('Digite um Valor: '))
if num not in valores:
valores.append(num)
else:
print('O Valor Já Existe, Portanto Não Foi Adicionado!!')
resp = 'a'
while resp not in 'SN':
resp = input('Quer Continuar? [S/N] ').strip().upper()[0]
if resp == 'N':
break
valores.sort()
print('Você digitou os valores {}'.format(valores)) | false |
f66c66859377238c35836ea25e790631d8f5afc9 | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio024.py | 329 | 4.125 | 4 | """rie um programa que leia o nome de uma cidade diga
se ela começa ou não com o nome "SANTO"."""
city = input('Digite o nome de sua cidade: ')
pos = city.strip().find(' ')
print('SANTO' in city.strip()[:pos].upper())
# Outra solução
# city = input('Digite o nome de sua cidade: ').strip
# print(city[:5].upper() == "SANTO") | false |
5b472890cc6c5660bb064d71ff2cf73e5d463094 | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio019.py | 506 | 4.125 | 4 | """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."""
from random import choice
n1 = input('Primeiro aluno: ')
n2 = input('Segundo aluno: ')
n3 = input('Terceiro aluno: ')
n4 = input('Quarto aluno: ')
lista = [n1, n2, n3, n4]
# uma lista em python é colocada entre [ e ]
escolhido = choice(lista)
# escolhe um valor aleatório
print('O aluno escolhido foi {}'.format(escolhido))
| false |
f46c94552504aa6dadc2900109f68350ee2744e6 | lindonilsonmaciel/Curso_Python | /Python_Mundo01/desafios/desafio014.py | 267 | 4.15625 | 4 | """Escreva um programa que converta uma temperatura digitando
em graus Celsius e converta para graus Fahrenheit."""
celsius = float(input('Digite a temperatura em Cº: '))
print('A temperatura de {:.2f}ºC corresponde a {:.2f}ºF'.format(celsius, (celsius*9/5)+32))
| false |
96e2ef3e7fe620722838052d00e61a09b3ec83a6 | ncfoa/100DaysOfCode_Python | /004/heads_tails.py | 608 | 4.21875 | 4 | import math
import random
callit = input("Call whether you think it will be 'heads' or 'tails'\n").lower()
if callit != "heads" and callit != "tails":
print("You didn't choose a side")
exit(0)
coin_toss = math.floor(random.random() * 2 + 1)
if coin_toss == 1 and callit == "heads":
print("The coin landed on Heads! You Won!")
elif coin_toss == 2 and callit == 'tails':
print("The coin landed on Tails. You Won")
elif coin_toss == 1 and callit == 'tails':
print("The coin landed on Heads. Sorry, please try again!")
else:
print("The coin landed on Tails. Sorry, please try again!")
| true |
ef6056a833f93753b0f71783991b577111d4ea05 | HannanehGhanbarnejad/IntroductionToPythonProgramming | /ex1/Rand2.py | 427 | 4.1875 | 4 | a=int(input("Please enter a: "))
b=int(input("Please enter b: "))
def Rand2(a,b):
""" (int,int)-> int
Return a random even number within a specific range between two given values
including the values themselves.
>>> Rand2(30,127)
58
"""
import random
for i in range(a,b+1):
i=random.randint(a,b)
if i%2 !=0:
continue
print(i)
break
Rand2(a,b)
| true |
f0041a284e46a7bf8de531ce78fbd6c56e8897fb | ccrabbai/Practice_Pyhon | /Even_Or_Odd_Number.py | 592 | 4.28125 | 4 | #Even_Or_Odd_Number.py
Num = int(input("Enter a number: "))
if Num%2 == 0:
print("%d is an even number"%Num)
else:
print("%d is an odd number"%Num)
if Num%2 == 0 and Num%4 == 0:
print("and also a mutiple of 4")
else:
print("and it is a not a multiple of 4 ")
num = int(input("\nCheck if a is divisible by b\nEnter a: "))
check = int(input("Enter b: "))
try:
if num%check==0:
print("%d is divisible by %d"%(num,check))
else:
print("%d is not divisible by %d"%(num,check))
except ZeroDivisionError:
print ("b won't be zero")
| false |
7745fd301b2c2a1e045f00cbcbb4ef04221303f9 | Ryan-Brooks-AAM/cleverprogrammer | /Learn-Python/exercise3_len.py | 321 | 4.15625 | 4 | print("What word would you like to measure?")
word = input()
def count_words(word):
count = 0
for i in word:
print(i)
count = count + 1
return count
# returned results need to move out of the local def into global
len = count_words(word)
print(f"The word count for {word} is: {len}")
| true |
5558bd19b46d8fff6379cbf1ffaca8ba116399b3 | PetterNas/ML-basics | /PolyNomialReg.py | 1,639 | 4.34375 | 4 | #Polynomial Linear Regression
#Simple example showing how to create and plot a polynomial regression model.
#In the example code below, I'm not using any test/training sets.
#Also plotting a linear regression, for comparing linear - polynomial models.
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
dataset = pd.read_csv('X.csv')
X = dataset.iloc[:, X:X].values
y = dataset.iloc[:, X].values
#Fitting the Linear Regression to the dataset.
lin_reg = LinearRegression()
lin_reg.fit(X,y)
#Fitting Polynomial Regression to the dataset.
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=4) #Set degree depending on the dimension.
X_poly = poly_reg.fit_transform(X)
lin_reg2 = LinearRegression()
lin_reg2.fit(X_poly, y)
#Visualizing the Linear regression results.
#Using color = red for actual values.
plt.scatter(X, y, color='red')
#Using color = blue for predicted values.
plt.plot(X, lin_reg.predict(X), color='blue')
plt.title('Linear example.')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
#Visualizing the polynomial regression.
#Using color = red for actual values.
plt.scatter(X, y, color='red')
#Using color = blue for predicted values.
plt.plot(X, lin_reg2.predict(poly_reg.fit_transform(X)), color='blue')
plt.title('Polynomial example.')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
| true |
a37f4c7e36319138119fef642dade5e4fee71e52 | Ethan-source/E01a-Control-Structues | /main10.py | 2,703 | 4.28125 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') #Prints "greetings" in the terminal as the introduction.
colors = ['red','orange','yellow','green','blue','violet','purple'] #specifies all of the potential answers
play_again = '' #specifies which character allow you to play again or not play again.
best_count = sys.maxsize # the biggest number
while (play_again != 'n' and play_again != 'no'): #While loop that gvies you the option to continue to play even after you win.
match_color = random.choice(colors) #Randomizes the "Match color" of what color allows you to win the game.
count = 0 #Counts each attempt
color = '' #specifies what can be the potential colors.
while (color != match_color): #while loop that askes you what your favorite color is again if you don't get the right answer.
color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line
color = color.lower().strip() #allows for characters to be upper and lowercase, and gets rid of the whitespaces in your answer.
count += 1 #Adds 1 for every time you get a wrong answer
if (color == match_color): #if your answer is the match color then you proceed with the code below
print('Correct!') #prints correct if your color was the match color
else:
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #Prints "sorry try again" and uses the count to see how many times you attempted the wrong answers.
print('\nYou guessed it in {0} tries!'.format(count))#If you got the right answer it will tell you how many times it took you to get to the right answer
if (count < best_count): #If statement saying if it took you less attempts to solve the puzzle than the best count it will print the statement below
print('This was your best guess so far!') #prints "This was your best guess so far" in the terminal
best_count = count #If the number of attempts it took you to complete the game is the same as the best count, then it will just ask you to play again.
play_again = input("\nWould you like to play again? ").lower().strip() #allows you to respond to the question "would you want to play again" and allows you to input upper and lowercase letters in addition to taking out the whitespaces.
print('Thanks for playing!') #Prints "thank you for playing" in the terminal once you have completed the puzzle and said you don't want to play again. | true |
6b53a748135b655e4b2d9690ba47a05dd588fefa | agrima13/PythonCoding | /Strings/StringPractice.py | 539 | 4.21875 | 4 | s = "The metahumans have atacked Central City again"
#Method 1 to reverse the string
print(s[len(s)::-1])
#Method 2 : Without specifying the length explicitly
print(s[::-1])
##Method 3 : Loop
reversedString=[]
index = len(s) # calculate length of string and save in index
while index > 0:
reversedString += s[ index - 1 ] # save the value of str[index-1] in reverseString
index = index - 1 # decrement index
print(str(reversedString)) # reversed string
## Method 4
reversedstring=''.join(reversed(s))
print(reversedString)
| true |
c73a49cb24b13d887c1679bbaa9fbfe0b1778026 | Musicachic/CITP_110-1 | /CITP 110/Chapter 5/sum_numbers example.py | 474 | 4.34375 | 4 | # This program calculates the sum of a series
# of numbers entered by the user.
def main():
# Initialize an accumulator variable.
total = 0
max = int(input("How many numbers will you add?: "))
# Get the numbers and accumulate them.
for counter in range(max):
number = int(input('Enter a number: '))
total = total + number
# Display the total of the numbers.
print('The total is', total)
# Call the main function.
main()
| true |
0c926111dfecce39fc7dd60ecaa2a37c7751890e | altynai02/Chapter1-Part2-Task5 | /task5.py | 1,083 | 4.28125 | 4 | # 5. A school decided to replace the desks in three classrooms. Each desk sits two
# students. Given the number of students in each class, print the smallest
# possible number of desks that can be purchased.
# - The program should read three integers: the number of students in each of
# the three classes, a, b and c respectively.
# - In the first test there are three groups. The first group has 20 students and
# thus needs 10 desks. The second group has 21 students, so they can get by
# with no fewer than 11 desks. 11 desks is also enough for the third group of
# 22 students. So we need 32 desks in total.
first_class_student = int(input("Enter the number of first class students: "))
second_class_student = int(input("Enter the number of second class students: "))
third_class_student = int(input("Enter the number of third class students: "))
total_desks = ((first_class_student // 2 + first_class_student % 2) + (second_class_student // 2 + second_class_student % 2) + (third_class_student // 2 + third_class_student % 2))
print("We need",total_desks, "desks in total")
| true |
6aaf5cc5a743817bfbb325ffad668c01cbec5243 | deepzsenu/python | /Doing_maths_with_python/1.Playing_with_numbers/New Folder/p3__multiple_table_printer.py | 395 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 20:16:09 2020
@author: deepak
"""
#the program for our multiplication table printer:
def multi_table(a):
for i in range(1,11):
print('{0} X {1} = {2}'.format(a, i, a*i))
if __name__ == '__main__':
a = input("Enter the number whose table you want to print : ")
multi_table(float(a))
| true |
c58cb13c8940df12887ae4efc293a76095b6b77a | TrinUkWoLoz/Python | /list_in_not_in.py | 955 | 4.125 | 4 | # List in or not in examples
#Simple true/false
myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList)
# Print largest number in list - range = value 3 (element 1) to value 13 (last element len(myList))
myList = [17, 3, 11, 5, 1, 9, 7, 15, 13]
largest = myList[0]
for i in range(1, len(myList)):
if myList[i] > largest:
largest = myList[i]
print(largest)
# Print largest number in list - range = value 3 (element 1) to value 13 (last element :)
myList = [17, 3, 11, 5, 1, 9, 7, 15, 13]
largest = myList[0]
for i in myList[1:]:
if i > largest:
largest = i
print(largest)
# Find value 5 in list and then print the index #
# Result = index 4 (element 3)
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
toFind = 5
found = False
for i in range(len(myList)):
found = myList[i] == toFind
if found:
break
if found:
print("Element found at index", i)
else:
print("absent")
| true |
3a0238deb8c54285349d3ef209f4b8d0e039cebf | TrinUkWoLoz/Python | /defining_functions.py | 1,459 | 4.25 | 4 | # DEFINING FUNCTIONS EXAMPLES
# Definined function with positional parameter
def message(what, number):
print("Enter", what, "number", number)
# invoke function (requires 2 parameters)
message("Jaffacakes", 300)
############################
# Definined function with positional parameter
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)
introduction("Luke", "Skywalker")
introduction("Jesse", "Quick")
introduction("Clark", "Kent")
##############################
# Defined function with keyword argument passing
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)
introduction(firstName = "James", lastName = "Bond")
introduction(lastName = "Skywalker", firstName = "Luke")
###############################
# Mixing positional paramter and keyword
def sum(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
sum(3, c = 1, b = 2)
###############################
# Specifying a default parameter (Smith)
def introduction(firstName, lastName="Smith"):
print("Hello, my name is", firstName, lastName)
# call the function here
introduction(firstName="William")
###############################
# Defining function, then using list, for loop, insert and return
def strangeListFunction(n):
strangeList = []
for i in range(0, n):
strangeList.insert(0, i)
return strangeList
print(strangeListFunction(5))
# Returns [4, 3, 2, 1, 0]
| true |
0e64bc2e1f9e9054737dda50c332c904c1aaacba | TrinUkWoLoz/Python | /list_append_insert_delete.py | 982 | 4.5 | 4 | # step 1: create an empty list named beatles;
# step 2: use the append() method to add the following members of the band to the list:
# John Lennon, Paul McCartney, and George Harrison;
# step 3: use the for loop and the append() method to prompt the user to add the following
# members of the band to the list: Stu Sutcliffe, and Pete Best;
# step 4: use the del instruction to remove Stu Sutcliffe and Pete Best from the list;
# step 5: use the insert() method to add Ringo Starr to the beginning of the list.
# I use for loop for append for more convenience
# step 1
beatles=[]
startlist=["John Lennon","Paul McCartney","George Harrison"]
templist=["Stu Sutcliffe","Pete Best"]
print("Step 1:", beatles)
# step 2
for i in startlist:
beatles.append(i)
print("Step 2:", beatles)
# step 3
for i in templist:
beatles.append(i)
print("Step 3:", beatles)
# step 4
for i in range(2):
del beatles[-1]
print("Step 4:", beatles)
# step 5
beatles.insert(0,"Ringo Starr")
print("Step 5:", beatles)
# testing list legth
print("The Fab", len(beatles)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.