blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c212b2ae3fcd5040399a38559baca2752208f570 | sumitbro/python_assignment_2 | /data_type/q12.py | 274 | 4.25 | 4 | #Write a Python script that takes input from the user and displays that input
#back in upper and lower cases
input_user = input("What's your first programming language? ")
print("My first language is ", input_user.upper())
print("My first language is ", input_user.lower()) | true |
4d2e9f5a37f8dde52407cd869f0b0d22aa0b8bfa | 3amMcspicy/hack-program | /snake/snake.py | 2,978 | 4.21875 | 4 | #!/usr/bin/env python3
import datetime
import pandas as pd
from datetime import date
URL = "https://raw.githubusercontent.com/richard512/Little-Big-Data/master/famous-birthdates.csv"
"""
Functions of hello-world type code
Returns a Yes or No to confirm if the date today is
the anniversary of the nokia snakes game release date (25th Jan).
"""
def isit_snakes(arg):
today = date.today()
thisYear = datetime.datetime.today().year
anniversary = datetime.datetime(thisYear, 1, 25)
if arg == "today":
if today == anniversary:
print(f"yesssss")
else:
print(f"noooooooo")
print
# Essentialy the same thing as the conditions above, it just prints
# different sentences with different arguments
if arg == "yet":
if today == anniversary:
print(f"It is snakes now")
else:
print(f"not yet snakeroo")
"""
The following class has famous people and their birthdays.
It returns whether the celebrity's birthday falls on Snake's anniversary. If not,
it returns how many days to the most recent one. It also returns a column describing the number
of days they could have potentially played the game since they were born.
"""
class snakeSensei:
def __init__(self):
self.data = pd.read_csv(URL,delimiter=" ")
#sampling same as tutorial
def random_sample(self,n):
#cleaning up the data.
self.data = self.data[~self.data.birthDate.isna()]
self.data = self.data.sample(n).reset_index(drop=True)
self.data = self.data.loc[:, ["firstname", "lastname", "birthDate"]]
def calculate_celebrity_could_play(self):
self.data["Days_they_could've_played"] = "Not born yet"
self.data["Anniversary?"] = "Nope"
self.data["Days_to_nearest_Anniversary?"] = "Passed already :("
for idx in self.data.index:
bday = self.data.at[idx, "birthDate"]
year, month, day = bday.strip().split("-")
date = datetime.datetime(int(year), int(month), int(day))
diff = datetime.datetime(2005, 1, 25) - date
if date < datetime.datetime(2005, 1, 25):
self.data.loc[idx, "Days_they_could've_played"] = diff.days
if date == datetime.datetime(2005, 1, 25):
self.data.loc[idx, "Anniversary?"] = "OMG yes"
anni_days = date - datetime.datetime(date.year, 1, 25)
if anni_days.days > 0:
self.data.loc[idx,"Days_to_nearest_Anniversary?"] = int(anni_days.days)
#instead of asking for a cmd line argument for size of sample, the program prompts the user
def run(self):
n = int(input("Please Enter a number: "))
self.random_sample(n)
self.calculate_celebrity_could_play()
print(self.data)
if __name__ == "__main__":
isit_snakes("yet")
isit_snakes("today")
p = snakeSensei()
p.run() | true |
acca7f4cbd3639a764f4515e3058ada141986976 | adamcanray/canrayLearnPython | /03_data_structures/1_list_operations.py | 1,539 | 4.1875 | 4 | # ---- header
# operasi dalam list di Python,
# adalah bagaimana cara kita dalam memanipulasi sebuah item/element di dalam list.
# ----- start reading
# Perhatikan:
# * dalam pengoprasian sebuah list ada banyak sekali caranya
# * dipoint ini saya akan menjelaskan kasus yang cukup sederhana saja tetapi akan sering digunakan.
# * dalam pengoprasian sebuah list kita bisa menggunakan fungsi dan method bawaan atau code kita sendiri.
# ----- end.
# ----- start coding
# Implementasi:
# membuat sebuah list buah
buah = ['apel','nanas','salak']
# CREATE
# menambahkan satu item/element pada akhir list menggunakan apend()
buah.append("jeruk") # hanya menerima satu parameter saja
print(buah)
# menggunakan teknik
buah += ['lemon','mangga'] # bisa memasukan item lebih dari satu
print(buah)
# menambahkan satu item juga bisa menggunakan insert(index, item)
buah.insert(0,"nangka")
print(buah)
# EDIT
# mengubah nilai dari item di dalam list
buah[0] = "jambu"
print(buah)
# DELETE
# teknik slicing dalam operasi list
# menghapus sebuah dari list
buah[0:1] = [] # menghapus 1 item di index 0
print(buah)
buah[0:2] = [] # menghapus 2 item di index 0 dan index 1
print(buah)
# REPLACE
buah[0:1] = ["pear"] # menggantikan 1 item di index 0
print(buah)
buah[0:2] = ["leci"] # menggantikan 2 item di index 0 dan index 1
print(buah)
# CLEAR
buah[:] = [] # menghapus semua item pada list
print(buah)
# ----- end.
# note: ada banyak sekali teknik untuk memanipulasi sebuah list di dalam Python,
# ----- silahkan teman-teman cari tahu sendiri. | false |
6ae17eecc0ea408fe2afa108edf6a9e105d49bcb | SuperAme/python | /numberGuessing.py | 533 | 4.125 | 4 | import random
guesses = []
myComputer = random.randint(0,130)
player = int(input("Enter & guess the number between 0 & 9: "))
guesses.append(player)
while player != myComputer:
if player > myComputer:
print("Number is too high")
else:
print("Number is too low")
player = int(input("Enter & guess the number between 0 & 9: "))
guesses.append(player)
else:
print("you've guessed right!")
print("it took you %i quesses " % len(guesses))
print("these were your guesses")
print(guesses) | true |
02404dcec7b3a63cb786ca75c9f470144002de24 | HarryZhang0415/Coding100Days | /100Day_section1/Day12/Sol1.py | 731 | 4.21875 | 4 | '''
Approach 1 : Transpose and then reverse
The obvious idea would be to transpose the matrix first and then reverse each row. This simple approach already demonstrates the best possible time complexity O(N^2)
'''
class Solution:
def rotate(self,matrix):
'''
:type matrix:List[List[int]]
:rtype void Do not return anything, modify matrix in-place instead.
'''
n = len(matrix[0])
# transpose matrix
for i in range(n):
for j in range(i,n):
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]
for i in range(n):
matrix[i].reverse()
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]]
s = Solution()
s.rotate(matrix) | true |
ef202d0373390e72e71bdb04ceee21db4fede246 | youknow88/python_course2 | /hw4.py | 1,201 | 4.15625 | 4 | #Дан массив чисел.
#[10, 11, 2, 3, 5, 8, 23, 11, 2, 5, 76, 43, 2, 32, 76, 3, 10, 0, 1]
#4.1) убрать из него повторяющиеся элементы
#4.2) вывести 3 наибольших числа из исходного массива
#4.3) вывести индекс минимального элемента массива
#4.4) вывести исходный массив в обратном порядке
def remove_repeat_elem(lst):
without_repeat_lst = []
for i in lst:
if i not in without_repeat_lst:
without_repeat_lst.append(i)
return without_repeat_lst
print(remove_repeat_elem([10, 11, 2, 3, 5, 8, 23, 11, 2, 5, 76, 43, 2, 32, 76, 3, 10, 0, 1]))
def get_three_max_numbers(lst):
a = sorted(lst, reverse = True) [0 : 3]
return a
print(get_three_max_numbers([10, 11, 2, 3, 5, 8, 23, 11, 2, 5, 76, 43, 2, 32, 76, 3, 10, 0, 1]))
def min_index(lst):
return lst.index(min(lst))
print(min_index([10, 11, 2, 3, 5, 8, 23, 11, 2, 5, 76, 43, 2, 32, 76, 3, 10, 0, 1]))
def list_reverse(lst):
return lst[::-1]
print(list_reverse([10, 11, 2, 3, 5, 8, 23, 11, 2, 5, 76, 43, 2, 32, 76, 3, 10, 0, 1]))
| false |
31c0804b382105e260af2fb40574bbc8f779fe7d | AshutoshPanwar/Python_udemy_course | /relational_or_comparison_operators.py | 534 | 4.125 | 4 | # relational operators are (<, <= , >, >=) and always return a boolean value
x = 10
y = 20
print(x <= y) #True
x = 'hello'
y = 'python'
print(x > y) #False
#chaining of relational operators
w,x,y,z = 10,20,30,40
print(w < x < y < z) #True
print(w < x > y < z) #False
#Equality operators are Equal to(==), Not Equal to(!=)
x = 10
y = 10.0
z = True
print(x == y) #True
print(x != y) #False
print(1 == z) #True
| false |
940821e8f99b2fc039ad2c0d49ece6b76d3481d9 | AshutoshPanwar/Python_udemy_course | /bitwise_operators.py | 905 | 4.21875 | 4 | #Bitwise operaors are (&, |, ^ , ~ , << , >>) and only works on integers and boolean
#Integers are ocverted into binary numbers and binary numbers are represented as 32 bits
print(9 & 12) #output: 8 (the numbers are first converted to binary numbers)
print(bin(9)) #binary representation of 9
print(bin(12)) #binary representation of 12
print(bin(8)) #binary representation of 8
print(9 | 12) #output: 13 (the numbers are first converted to binary numbers)
print(bin(9)) #binary representation of 9
print(bin(12)) #binary representation of 12
print(bin(13)) #binary representation of 13
#we can apply same for boolian values
print(True & False)
print(True | False)
#Assignment opperators( += , -= , *= , /= , %= , //=, **=)
x = 10
x += 2
print(x) #output: 12 (x = x+2)
x *= 2
print(x) #output: 20 (x = x*2)
| true |
4def99a53746d328f5900b5a91ac5dafd74ae6e5 | AnthonyWhite73/pyhton-game | /game_trial1.py | 2,964 | 4.4375 | 4 | #This code makes a nested list (a list of lists) that populates it with records for #three characters'''
#a character will have:
#name (A string)
#age (an integer)
#gender (true false for male female)
#health points (an integer)
#weapon (list/function that returns a damage die)
#armour (integer)
#dead (boolean)
#7 fields of data in total so 7 columns
#will try 3 characters, so 3 rows
#element indexes will be:
#0=name, 1=age, 2=gender, 3=health points, 4=weapon, 5=armour, 6 = dead
#so list of lists for three characters
def bark(textIn):
print("ADMIN MESSAGE -----> "+textIn)
bark("Beginning program!")
charList = [
["Name","Age","Is Male?", "Hit Points", "Weapon", "Armour", "Is Dead?"],
["Stealy the Thief", 13, False, 10, "Dagger", 3, False],
["Lenny the Idiot", 32, True, 30, "Sledgehammer", 5, False],
["Shooty the Murderer", 25, False, 20, "Gun", 4, False],
]
#foundChar is set to true when callled in the function 'spitCharData'
foundChar = False
#charChosen is set to true when the while loop confirms the user has picked a character
charChosen = False
charChosenIndex = 0
while charChosen == False:
charSel = input("Choose your character: 'Stealy the Thief', 'Lenny the Idiot' or 'Shooty the Murderer'\n")
if charSel != "Stealy the Thief" and charSel != "Lenny the Idiot" and charSel != "Shooty the Murderer":
print("\n-----------------------------------------------------------------------")
print("You did not choose a character with the proper name. Please try again.")
print("-----------------------------------------------------------------------\n")
elif charSel == "Stealy the Thief":
charChosenIndex = 1
charChosen = True
print("You have chosen " +charSel+".")
print("Let us begin...\n")
elif charSel == "Lenny the Idiot":
charChosenIndex = 2
charChosen = True
print("You have chosen " +charSel+".")
print("Let us begin...\n")
elif charSel == "Shooty the Murderer":
charChosenIndex = 3
charChosen = True
print("You have chosen " +charSel+".")
print("Let us begin...\n")
else:
print("Something went wrong :(")
#element indexes will be:
#0=name, 1=age, 2=gender, 3=health points, 4=weapon, 5=armour, 6 = dead
#Function to spit out all character data from the input one (determined by while loop above)
def spitCharData(input):
global isMale
global isDead
global foundChar
index = int(input)
#va
isMale = charList[input][2]
isDead = charList[input][6]
while foundChar == False:
if charSel == charList[index][0]:
for i in range(0,7):
print(str(charList[0][i]) + ": " + str(charList[input][i]))
foundChar = True
else:
print("Bad juju... so breaking out of loop")
break
spitCharData(charChosenIndex) | true |
aa2b77023c15190250d04c706c0a6c6da3f0e70b | dennyto/Python_SoftUni | /Python Pogramming Basics/07. Complex_Checks/13.Point in the Figure.py | 445 | 4.28125 | 4 | h = float(input())
x = float(input())
y = float(input())
if h < x < h*2 and y == h:
print("Inside")
elif (0 <= x <= h*3 and (y == h or y == 0)) or (0 <= y <= h and (x == 0 or x == h*3)):
print("Border")
elif (h <= x <= h*2 and (y == h or y == h*4)) or (h <= y <= h*4 and (x == h or x == h*2)):
print("Border")
elif (0 < x <h*3 and 0 < y < h) or ( h < x < h*2 and 0 < y < h*4):
print("Inside")
else:
print("Outside")
| false |
852701c6f4cf22b9d6788f0fe30da1e1c134a539 | maninekkalapudi/pythonista | /basics/importingmodules.py | 641 | 4.1875 | 4 | '''
video-> https://youtu.be/CqvZ3vGoGs0
'''
# importing my_module
import my_module # From this statement we're able to access all the functions, variables and etc. in the file
# from my_module import find_index # This will only access to the find_index() in the my_module and nothing else
# List of courses
courses = ['Math', 'Art', 'Physics', 'CompSci']
# Calling the find_index() in my_module by passing list and key value to get the index of the key value in the list
index = my_module.find_index(courses, 'Art')
print(index)
import sys
print(sys.path) # This will print all the modules python will look for when importing something | true |
fdbdcd3ef6b9dee14f3fb98f7db821e79c8160a8 | maninekkalapudi/pythonista | /basics/dictionaries.py | 1,347 | 4.4375 | 4 | '''Dictionaries or Key-Value pairs
Video-> https://youtu.be/DZwmZ8Usvnk
'''
# Dict declaration
student={'name':'John', 'age':24, 'courses':['Math','CompSci']}
# Accessing the values from the dictionary using keys
print(student['name'])
# Accessing the key that is not in the dict
# print(student['phone_number']) ->This will throw 'KeyError:<keyname>' error
# get() to access the elements
print(student.get('age'))
# Accessing an non-existent element using the get(). Second arg is the custom message when the key is not found
print(student.get('phone_number', 'Not Found'))
# Adding an key-value pair to the dictionary
student['phone_number'] = 5555555555 # If the key is already present then the value will be updated
# Here name is updated
student['name'] = 'Jane'
print(student)
# Update using update() -> This can update multiple values at once
student.update({'name': 'Bruce', 'age':26, 'phone_number': 2313121312})
print(student)
# Delete a key using del
# del student['age']
# Delete a key using pop()
age = student.pop('age')
print(age)
# Length of dict
print(len(student))
# Keys in a dict
print(student.keys())
# Values in a dict
print(student.values())
# Keys and values in a dict
print(student.items())
# Loop through all the elements(keys and values) in a dict
for key, value in student.items():
print(key, value)
| true |
8b664f8700aa80671769b479524870e5c87a1d41 | LeloCorrea/Python | /.vscode/python_+100exercicios.py/desafio_06.py | 675 | 4.3125 | 4 | '''Desafio 6 :
Crie um algoritmo que leia um número e mostre o seu dobro, triplo e a raiz quadrada:
'''
'''
#Primeira maneira de fazer
num = int(input('Digite um número: '))
dobro = num*2
triplo = num*3
raiz = num**(1/2) #Raiz representada através de exponenciação (num elevado a meio)
print('O número que você digitou é: {}\nO seu dobro é: {}\nO seu triplo é: {}\nA sua raiz quadrada é: {:.2f}.'.format(num, dobro, triplo, raiz))
'''
#Outra maneira de fazer
n = int(input('Digite um número: '))
print('O número que você digitou é: {}\nO seu dobro é: {}\nO seu triplo é: {}\nSua raiz é: {:.2f}.'.format(n, n*2, n*3, pow(n,1/2))) #Utilizando a função pow. | false |
df7396481d01877b445954b2e07ae1147d6f3499 | LeloCorrea/Python | /.vscode/python_+100exercicios.py/desafio_11.py | 1,572 | 4.40625 | 4 | '''Desafio 11 original:
Faça um programa que leia a largura e a altura de uma parede em metros, calcule sua área e a quantidade de tinta necessária para pinta-lá, sabendo que cada litro de tinta pinta uma área de 2m².
Calculando a área: área (m²) = largura (m) x altura(m)
OBS.: Mudanças que eu fiz em relação ao programa original:
1 - Solicitei a capacidade da tinta.
2 - Solicitei o número de demãos que serão dadas na parede.
3 - Solicitei a largura x altura, para termos a área total.
4 - Apresentei os dados.
'''
capacidadetinta = int(input('Qual a capacidade de pintura do Lt da tinta p/M²: '))
demaos = int(input('Quantas demãos de tinta você irá pintar: '))
largura = float(input('Digite a largura da parede em metros: '))
altura = float(input('Digite a altura da parede em metros: '))
area = largura * altura
demao = ((largura * altura)/demaos)
tinta = ((area / capacidadetinta)*demaos)
print('Sua parede tem a dimensão de {}x{} e sua area total é: {:.3f}m².\nEntão para uma area total de: {:.3f}m², você precisará {:.2f}Lt de tinta, considerando uma tinta que rende {}Lt p/m², pintando {} demão(s)'.format(largura, altura, area, area, tinta, capacidadetinta, demaos))
'''print('A largura é: {} metros e a altura é: {} metros.\nArea total é: {:.2f}m².\nCada litro de tinta pinta uma área de {:.2f}m²\nEntão para uma area total de: {:.2f}m², você precisará {:.2f}Lt de tinta.\nCom {} demão(s) você conseguirá pintar uma área de {:.2f}m²'.format(largura, altura, area, capacidadetinta, area, tinta, demaos, demao))''' | false |
2c103997387abf30a5b8e18fe248924e584de6d3 | LeloCorrea/Python | /.vscode/python_+100exercicios.py/operacoes_aritimeticas.py | 819 | 4.28125 | 4 | '''Fundamentação teórica:
#Programa da aula passada:
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
soma = n1 + n2
print('O resultado da soma é: {}'.format(soma))
'''
'''Operadores aritméticos:
+ Adição
- Subtração
* Multiplicação
/ Divisão
** Potencia
// Divisão inteira ( É o resultado da divisão sem usar a virgula. )
% Resto da divisão ou módulo
#Para testar se uma coisa é igual a outra em python utilizamos ==.
#Pois um símbolo de = é sinal de atribuição.
Todo o operador precisa de operandos, pode ser um número, uma string ou variáveis.
Orde de precedencia entre operadores
1 - ()
2 - **
3 - Quem aparecer primeiro entre (*, /, //, %)
4 - + , -
'''
'''
5+2 = 7
5-2 = 3
5*2 = 10
5/2 = 2.5
5**2 = 25
5//2 = 2
5%2 = 1
'''
| false |
f38f49555d16cabbc85e1700a5a179a9d94dfbb6 | sreenivasgithub/PythonTopics | /Oops/Inheritance/SingleLevelInheritance.py | 1,501 | 4.53125 | 5 | # Inheritance: the process of creating new class based on
# existing class is known as inheritence
#Types3: 1 single level, 2 multi level, 3 multiple
#1 single level:
class Parent:
def __init__(self, name, age):
self.parent_name = name
self.parent_age = age
#print('parent_name: ', name)
#print('parent_age: ', age)
def display(self):
print('parent Name: ',self.parent_name)
print('parent Age: ',self.parent_age)
class Child1(Parent):
def __init__(self, name, age, gender):
self.child1_name = name
self.child1_age = age
self.child1_gender = gender
#print('child1_name: ', name)
#print('child1_age: ', age)
#print('child1_gender: ', gender)
super().__init__('Parent',50)
def display(self):
print('child1 Name: ', self.child1_name)
print('child1 Age: ', self.child1_age)
print('child1 Gender: ', self.child1_gender)
super().display()
class Child2(Parent):
def __init__(self, name, age, gender):
self.child2_name = name
self.child2_age = age
self.child2_gender = gender
super().__init__('Parent', 50)
def display(self):
print('child2 Name: ', self.child2_name)
print('child2 Age: ', self.child2_age)
print('child2 Gender: ', self.child2_gender)
super().display()
#obj1 = Child1('Child1', 20, 'F')
#obj1.display()
obj2 = Child2('c2', 25, 'M')
obj2.display() | false |
ee177b382d5a3bec84264331c7db65973272f477 | sreenivasgithub/PythonTopics | /Oops/Inheritance/MultiLevelInheritance.py | 702 | 4.1875 | 4 | # MultiLevelInheritance: The process of creating a new class based on previous class
class Grandfather:
def __init__(self, name):
self.grand_father = name
def display(self):
print('Grand Father Name: ',self.grand_father)
class Father(Grandfather):
def __init__(self, name):
self.father = name
super().__init__('GrandFather')
def display(self):
print('Father Name: ', self.father)
super().display()
class Child(Father):
def __init__(self, name):
self.child = name
super().__init__('Father')
def display(self):
print('Child Name: ', self.child)
super().display()
C = Child('Child')
C.display() | false |
e48d2e25d15c5be5a621a63b7c5ad12a26ae629f | marcosrodriguesgh/py_CheckIO | /elementaryPlus_ascending-list.py | 1,093 | 4.28125 | 4 | from typing import Iterable
def is_ascending(items: Iterable[int]) -> bool:
'''
Determine whether the sequence of elements items is ascending so that its each element
is strictly larger than (and not merely equal to) the element that precedes it.
:param items: Iterable with ints
:return: Bool
'''
# Minhas solução---------------------------------
# for i in items:
# if items.count(i) > 1:
# return False
# return sorted(items) == items
# Solução Otimizada -----------------------------
return all(items[i] < items[i+1] for i in range(len(items)-1))
if __name__ == '__main__':
print("Example:")
print(is_ascending([-5, 10, 99, 123456]))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_ascending([-5, 10, 99, 123456]) == True
assert is_ascending([99]) == True
assert is_ascending([4, 5, 6, 7, 3, 7, 9]) == False
assert is_ascending([]) == True
assert is_ascending([1, 1, 1, 1]) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
cf701af81f6661950ef14b0348405f7bf7f939ad | poojat7575/Practice | /balanced_brackets.py | 721 | 4.15625 | 4 | def is_balanced(string):
stack = []
open_brackets = "{(["
for bracket in string:
if bracket in open_brackets:
stack.append(bracket)
else:
if not stack:
return False
if not is_matching(stack.pop(), bracket):
return False
if not stack:
return True
return False
def is_matching(opening, closing):
if (opening == '(' and closing == ')') or\
(opening == '[' and closing == ']') or\
(opening == '{' and closing == '}'):
return True
return False
if __name__ == "__main__":
print(is_balanced('{}[]()'))
print(is_balanced('{]('))
print(is_balanced('{[({[}])]}'))
| true |
635c357c7b50574ea6cd41eb335e762e11dbec7d | arevolutioner/Password-Validation-Program | /app.py | 1,575 | 4.34375 | 4 | """
A program to check the validity of password input by users
A website requires the users to input username and password to register.
Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
At least 1 letter between [a-z] At least 1 number between [0-9] At least 1 letter between [A-Z] At least 1 character
from [$#@] Minimum length of transaction password: 6 Maximum length of transaction password:
12 Your program should accept a sequence of comma separated passwords and will check them
according to the above criteria.
Passwords that match the criteria are to be printed, each separated by a comm
"""
import re
a = input('Enter passwords: ').split(',')
pass_pattern = re.compile(r"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$#@]).{6,12}$")
for i in a:
if pass_pattern.fullmatch(i):
print(i)
# def is_low(x):
# for i in x:
# if "a" < i > "z":
# return True
# return False
#
#
# def is_up(x):
# for i in x:
# if "A" < i > "Z":
# return True
# return False
#
#
# def is_num(x):
# for i in x:
# if "0" < i > "9":
# return True
# return False
#
#
# def is_other(x):
# for i in x:
# if i=="$" and i=="#" and i=="@":
# return True
# return False
#
#
# password = input().split(",")
# lst=[]
#
# for i in password:
# length=len(i)
# if 7 < length > 13 and is_up(i) and is_low(i) and is_num(i) and is_other(i):
# lst.append(i)
# print(lst)
#
# print(",".join(lst))
| true |
5f7a982227c24a51345424d9e31da96fbba0e94f | srijanduggal17/Elevation-Profile-Generator-for-Flow-Rates | /linegenerator.py | 557 | 4.125 | 4 | #This code first requests you to input points in the format "x,y"
a = input("first point")
b = input("second point")
#Create a 2-value array for each point
array1 = a.split(',')
array2 = b.split(',')
#Convert from string to float
y1 = float(array1[1])
y2 = float(array2[1])
x1 = float(array1[0])
x2 = float(array2[0])
#Calculate the slope of the line between the points
m = (x2-x1)/(y2-y1)
#Convert to a string for display purposes
z = str(m)
#Define line and print to console
line = "x = %s (y - %s) + %s" % (z,y2,x2)
print(line) | true |
f8f289fc574a9b572f2e33c37c48aa9c40e63fce | andreasoprisan/sudokuSolver | /helpers/timeDisplay.py | 584 | 4.21875 | 4 | # FUNCTIONS
def display(time_value, what):
if time_value > 60:
if time_value > 3600:
hours = int(time_value) // 3600
minutes = int(time_value) % 3600 // 60
seconds = int(time_value) % 3600 % 60
print(
f'{what} is: {hours} hours, {minutes} minutes and {seconds} seconds!')
else:
minutes = int(time_value) // 60
seconds = int(time_value) % 60
print(f'{what} is: {minutes} minutes and {seconds} seconds!')
else:
print(f'{what} is: {time_value} seconds!')
| false |
029c9e0b5d9cb3962368b52b174b8f02fe32ef36 | ibrahimbayramli/Python | /ucgen_hesaplam.py | 1,458 | 4.1875 | 4 | """
İbrahim BAYRAMLI
https://sites.google.com/view/ibrahim-bayramli
"""
import math
while True:
a=float(input("A kenarının uzunluğunu girin: "))
b=float(input("B kenarının uzunluğunu girin: "))
c=float(input("C kenarının uzunluğunu girin: "))
while True :
if abs((a-b))>c or (a+b)<c :
print("Böyle bir üçgen oluşturulamaz. Oluşturulabilecek bir üçgen seçiniz.")
a=float(input("A kenarının uzunluğunu girin: "))
b=float(input("B kenarının uzunluğunu girin: "))
c=float(input("C kenarının uzunluğunu girin: "))
if abs((a-c))>b or (a+c)<b :
print("Böyle bir üçgen oluşturulamaz. Oluşturulabilecek bir üçgen seçiniz.")
a=float(input("A kenarının uzunluğunu girin: "))
b=float(input("B kenarının uzunluğunu girin: "))
c=float(input("C kenarının uzunluğunu girin: "))
if abs((b-c))>a or (b+c)<a :
print("Böyle bir üçgen oluşturulamaz. Oluşturulabilecek bir üçgen seçiniz.")
a=float(input("A kenarının uzunluğunu girin: "))
b=float(input("B kenarının uzunluğunu girin: "))
c=float(input("C kenarının uzunluğunu girin: "))
else :
u=(a+b+c)/2
alan= (u*(u-a)*(u-b)*(u-c))**0.5
print("Hesaplanan alan : ",alan)
break
| false |
f538ca8b78aee63d83af9209f043b77e78892296 | ansarifirdosh/Semister-2 | /My Practice/week 2/Helo+name+how are you.py | 306 | 4.25 | 4 | '''Write a simple program that asks the user to enter their name and
prints out “Hello name, have a nice day!” where name should be
the name that the user entered'''
#Asking the name from user
name=input("enter your name: ")
A=('Hello ')
B=(' Have a nice day')
#printing
print(A+name+B)
| true |
442890e70765e51a7a22cc47c0a9c283d5f2e26a | ansarifirdosh/Semister-2 | /My Practice/week 4/reverese.py | 211 | 4.59375 | 5 | '''
Write a program creates and prints a new list with the elements of an
existing list in reverse order.
[1, 2, 3, 4, 5, 6] -> [6, 5, 4, 3, 2,1]
'''
mylist=[1,2,8,4,5,6]
list=mylist[::-1]
print(list)
| true |
44e709cac1f7559c7d5630e2cf97c7a051ed62d0 | Jason101616/LeetCode_Solution | /Tree/103. Binary Tree Zigzag Level Order Traversal.py | 1,455 | 4.1875 | 4 | # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
# idea: use BFS to traverse each level
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
queue = deque()
queue.append(root)
ans = []
j = 0 # indicate the current level is odd or even
while queue:
curLen = len(queue)
curAns = []
for i in range(curLen):
cur_node = queue.popleft()
curAns.append(cur_node.val)
if cur_node.left:
queue.append(cur_node.left)
if cur_node.right:
queue.append(cur_node.right)
if j % 2 == 0:
ans.append(curAns)
else:
ans.append(curAns[::-1])
j += 1
return ans
| true |
e89506f081abb6589d67c7c313e1a0860109797f | Jason101616/LeetCode_Solution | /Math/461. Hamming Distance.py | 689 | 4.15625 | 4 | # The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
# Given two integers x and y, calculate the Hamming distance.
# Note:
# 0 ≤ x, y < 2^31.
# Example:
# Input: x = 1, y = 4
# Output: 2
# Explanation:
# 1 (0 0 0 1)
# 4 (0 1 0 0)
# ↑ ↑
# The above arrows point to positions where the corresponding bits are different.
def hammingDistance2(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
# Go version:
func
hammingDistance(x
int, y
int) int
{
tmp: = x ^ y
res: = 0
for ;tmp != 0; {
res += 1
tmp = tmp & (tmp - 1)
}
return res
}
| true |
f327d7e46465489a762b9d85552d7d370bb2e826 | Jason101616/LeetCode_Solution | /Array/243. Shortest Word Distance.py | 951 | 4.15625 | 4 | # Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
# For example,
# Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
# Given word1 = “coding”, word2 = “practice”, return 3.
# Given word1 = "makes", word2 = "coding", return 1.
# Note:
# You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
i, j = None, None
res = float('inf')
for index, word in enumerate(words):
if word == word1:
i = index
elif word == word2:
j = index
if i != None and j != None:
res = min(res, abs(i - j))
return res
| true |
2a0c579ab884794ffa5868169c0d384c3335f2f4 | AFishyOcean/py_unit_three | /assignment_three.py | 1,642 | 4.65625 | 5 | # David Jones
# 10/14/2021
# Calculates the surface area of a rectangular prism
print("This program calculates the surface area of a rectangular prism")
def get_width():
"""
Asks for a length then returns the answer as the function
:return:
"""
x = input("What is the width")
return float(x)
def get_height():
"""
Asks for a length then returns the answer as the function
:return:
"""
y = input("What is the height")
return float(y)
def get_length():
"""
Asks for a length then returns the answer as the function
:return:
"""
z = input("What is the length")
return float(z)
def rectangle_area(x, y):
"""
calculates the side areas of the prism
:param x:
:param y:
:return:
"""
side_area = x * y
return side_area
def calculate_surface_area(x, y , z):
"""
calculates all the surface areas then adds them. Spits out the answer as calculate_surface_area
:param x:
:param y:
:param z:
:return:
"""
side1and2 = rectangle_area(x, y)* 2
side3and4 = rectangle_area(x, z) * 2
side5and6 = rectangle_area(y, z) * 2
total = side1and2 + side3and4 + side5and6
return total
def reply(x, y, z, total):
print("Surface area of a rectangular prism with a width of", x, ",height of", y, ", and length of", z, "is", total)
def main():
"""
calls all of the functions then replies to the person
also assigns functions a value
:return:
"""
x = get_width()
y = get_height()
z = get_length()
total = calculate_surface_area()
reply(x, y, z, total)
if __name__ == '__main__':
main() | true |
dd3b56ba961ef6728d13ba928f6045b1c7f7bb30 | alalion/codecademy | /number_guess.py | 1,045 | 4.375 | 4 | """
It is Number Guess game that rolls a pair of dice and asks the user to guess the sum. If the users guess is equal to the total value of the dice roll, the user wins!
"""
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('Guess a number: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print('The maximum possible value is %d') % max_val
guess = get_user_guess()
if guess > max_val:
print('Your guess is invalid: it is higher than maximum value')
else:
print('Rolling...')
sleep(2)
print('First roll: %d') % first_roll
sleep(1)
print('Second roll: %d') % second_roll
total_roll = first_roll + second_roll
print(total_roll)
print('Result...')
sleep(1)
if guess == total_roll:
print('You won!')
else:
print('You lost everything!')
roll_dice(6)
| true |
840036d52a8f644a615a6f727e037d9aa27b6c7a | KhaderA/python | /day2/ops.py | 1,208 | 4.1875 | 4 | import math
def f_add(a,b):
"""Performs addition of given numbers"""
try:
c=a+b
except TypeError:
print "/!\\ Type Error: Enter integer values /!\\"
else:
return c
def f_sub(a,b):
"""Performs subtraction of given numbers"""
try:
c=a-b
except TypeError:
print "/!\\ Type Error: Enter integer values /!\\"
else:
return c
def f_mul(a,b):
"""Performs multiplication of given numbers"""
c=a*b
return c
def f_div(a,b):
"""Performs division of given numbers"""
try:
c=a/b
except ZeroDivisionError:
print "/!\\ Divide By Zero Occurred /!\\"
else:
return c
def f_sin(a):
"Performs sin operation on the given number"
try:
x=math.sin(math.radians(a))
except TypeError:
print "/!\\ Type Error: Enter a float value /!\\"
else:
return x
def f_cos(a):
"Performs cos operation on the given number"
try:
x=math.cos(math.radians(a))
except TypeError:
print "/!\\ Type Error: Enter a float value /!\\"
else:
return x
def f_pow(a,b):
"Performs power operation on the given number"
x=math.pow(a,b)
return x
def f_sqrt(a):
"Performs square-root operation on the given number"
x=math.sqrt(a)
return x
| true |
479d773d268a11e54f565d8dc1e079be256c07f6 | songlh/ist451-2019 | /lab-1/fib.py | 375 | 4.125 | 4 | ## fib is to calculate the nth fibonacci number
## fibonacci numbers are characterized by the fact that
## every number after the first two is the sum of the two
## preceding ones
## fibonacci numbers: 1, 1, 2, 3, 5, 8, 13
## fib(0) == 1
## fib(1) == 1
## fib(2) == 2
## fib(3) == 3
## ..
def fib(n):
if n == 1 or n == 0:
return 1
else:
#add one line of codes here
| false |
9969c4c12e52142f96ee835cf32a3ce76f40c223 | Liam-Jaedick/cp2019 | /p02/q03_determine_grade.py | 421 | 4.1875 | 4 | score = int(input("Enter score: "))
if score < 1 or score > 100:
print("Invalid! Score must be within 0 - 100")
elif 70 <= score <= 100:
print("Grade: A")
elif 60 <= score <= 69:
print("Grade: B")
elif 55 <= score <= 59:
print("Grade: C")
elif 50 <= score <= 54:
print("Grade: D")
elif 45 <= score <= 49:
print("Grade: E")
elif 35 <= score <= 44:
print("Grade: S")
else:
print("Grade: U")
| false |
b9ff7e353f6278b608af26b19d25494e500018f6 | jiriVFX/morse_translator | /main.py | 1,453 | 4.375 | 4 | # Morse code converter
from morse import MorseTranslator
translator = MorseTranslator()
print(""" __ __ _______ _ _
| \/ | |__ __| | | | |
| \ / | ___ _ __ ___ ___ | |_ __ __ _ _ __ ___| | __ _| |_ ___ _ __
| |\/| |/ _ \| '__/ __|/ _ \ | | '__/ _` | '_ \/ __| |/ _` | __/ _ \| '__|
| | | | (_) | | \__ \ __/ | | | | (_| | | | \__ \ | (_| | || (_) | |
|_| |_|\___/|_| |___/\___| |_|_| \__,_|_| |_|___/_|\__,_|\__\___/|_| """)
while True:
choice = input("\nType 'e' for text-to-Morse encoding, 'd' for Morse-to-text decoding or 'q' to quit: \n")
if choice == "e":
print("\nYour text can include:\n1. Letters from english alphabet,\n2. Numbers from 0 to 9"
"\n3. Selected special characters: & " "' " '"' " @ ( ) : , = ! . - % + ? /")
text_to_translate = input("\nText to be translated: \n")
print("Encoded result:\n" + translator.to_morse(text_to_translate))
elif choice == "d":
print("\nYour morse code may include only dots(.), spaces( ), dashes(-) and slashes(/)")
morse_to_decode = input("Morse code to be decoded: \n")
print("Decoded result:\n" + translator.to_text(morse_to_decode))
elif choice == "q":
print("Bye bye!")
break
else:
print("Wrong input, type only 'e', 'd' or 'q', please.")
| false |
24d54c2061e3575cf332d86c448f7e3933fdc82f | bangqae/learn-python | /exponent_function.py | 286 | 4.4375 | 4 | # Exponent Function, Learn Python - Full Course for Beginners [Tutorial]
# print(3**2) # 2 pangkat 3
def raise_to_power(base_num, pow_num):
result = 1
for i in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3)) # Same as 2**3
| true |
f1ce01ebfc8a6c9ce3e330761923859871d3ec2a | bangqae/learn-python | /for_loop.py | 656 | 4.375 | 4 | # For Loop, Learn Python - Full Course for Beginners [Tutorial]
# for letter in "Giraffe Academy": # Print all letter, 1 by 1
# print(letter)
# for index in range(10): # Print all index, from 1 to 9
# print(index)
# for index in range(3, 10): # Print all index, from 3 to 9
# print(index)
# friends = ["Jim", "Carry", "Kevin"]
# for friend in friends: # Print all index, 1 by 1
# print(friend)
# for index in range(len(friends)): # Use len to know the length of array
# print(friends[index])
for index in range(3): # Looping with if
if index == 2:
print("3rd iteration")
else:
print("Not 3rd iteration")
| true |
0f2508931d31b22886b222fecbba5a332288ac9f | nelsonchege/skaehub_developer_projects | /day_3/date_identify.py | 577 | 4.40625 | 4 | import numpy as np
# datetime64() is used to identify time
# when using it will provide the day
# .timedelta64()is used to compliment datetime64()
# snd can be used to know future or past time
# to get the current date
today = np.datetime64('today', 'D')
print("Today is : ", today)
print("+========================+")
# to get the previous day time
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yesterday was: ", yesterday)
# to get the next time
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow will be: ", tomorrow)
| true |
f7b0f0319d2a4c88ad025904f59dc76d72466052 | wmemon/python_assignment_0x02_msrit | /Question2.py | 683 | 4.15625 | 4 | def collatz_length(num):
if not (isinstance(num, int)):
return "This function accepts an integer only."
length = 1
answer = num
while answer != 1:
if answer % 2 == 0:
answer = answer / 2
length += 1
elif answer % 2 == 1:
answer = ((3 * answer) + 1)
length += 1
return length
def main():
print("Please note that we consider 1 as a part of collatz length here.")
num_list = []
for number in range(1, 21):
num_list.append(collatz_length(number))
print(num_list)
print(max(num_list))
print(num_list.index(max(num_list)))
if __name__ == "__main__":
main()
| true |
86f823ff3c515491e1770b543cadc6ea141c9a89 | RodrigoSierraV/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 333 | 4.21875 | 4 | #!/usr/bin/python3
def read_file(filename=""):
""" function that reads a text file (UTF8) and prints it to stdout
Args:
filename: name of the file to read. Can be empty string
Return: Nothing"""
with open(filename, mode='r', encoding='utf-8') as reading:
print(reading.read(), end='')
| true |
10d353b7974f885a31dad0d065c686c2746f6f85 | TheCodeSummoner/Nucats-Codeathon-2019 | /Who am I/Solution/hider.py | 2,135 | 4.3125 | 4 | import cv2
from PIL import Image
from os import remove, path
def convert_to_black_white(file_path: str, output_path: str):
"""
This function is used to convert an image to binary-like values (full black/white)
:param file_path: Path to the file to convert
:param output_path: Path to the output location
"""
# Read the image
img = cv2.imread(file_path)
# Threshold the image
thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# Save the image
cv2.imwrite(output_path, thresh)
def convert_to_binary(file_path: str) -> str:
"""
This function is used to convert a file into a binary string representing it.
:param file_path: Path to the file to convert
:return: Binary representation of the file
"""
# Convert the picture to black and white
convert_to_black_white(file_path, "temp.png")
# Initialise the string to return
binary = ""
# Iterate over the pixels in the image
for pixel in Image.open("temp.png").getdata():
# Add the next binary number
if not pixel:
binary += "0"
else:
binary += "1"
# Remove the temporary file
remove("temp.png")
# Return the formatted string
return binary
def hide_bits(file_path: str, binary: str):
"""
This function is used to hide the binary string representation of an image into a new gradient-like image
:param file_path: Path to the output location
:param binary: Binary representation of an image
"""
# Create a new image of expected size
img = Image.new("RGBA", (128, 128))
# Load the pixel map
pixels = img.load()
# Iterate over the map and set each pixel to create a gradient
for i in range(img.size[0]):
for j in range(img.size[1]):
pixels[i, j] = (i, j, 100, 255 - int(binary[i*128 + j]))
# Save the image
img.save(file_path)
if __name__ == '__main__':
# Hide the original image into a gradient image
hide_bits(path.join("..", "who_am_i.png"), convert_to_binary("pikachu.png"))
| true |
ef41e8d9f7945a4e0f78796ecbf11361ec1ee4c4 | wkdewey/learnpythonthehardway | /ex6.py | 1,218 | 4.46875 | 4 | #define variable x as string and include an integer in it (will be printed with format specifier)
x = "There are %d types of people." % 10
# define variable 'binary' as string
binary = "binary"
# define variable 'do_not' as string
do_not = "don't"
# define variable y as string, including the strings binary and do_not. again uses format specifiers
y = "Those who know %s and those who %s." % (binary, do_not)
#display on screen the string 'x' as defined above
print x
#display on screen the string 'y'
print y
# using the %r character will display the quotes around the string
print "I said: %r." % x
# using the %s character will not display the quotes, so they have to be manually evaluated
print "I also said: '%s'." % y
#define variable 'hilarious' as string
hilarious = False
#define variable 'joke_evaluation'
joke_evaluation = "Isn't that joke so funny?! %r"
#display joke_evaluation with 'hilarious" as the argument (it needs one because of the %r)
print joke_evaluation % hilarious
# define variable w as string
w = "This is the left side of..."
# define variable e as string
e = "a string with a right side."
# example of "adding" two strings together, it just puts one string after the other
print w + e | true |
60998643af20cc573e807025342fb31bd8077922 | comsavvy/Decorators-and-Dataclasses | /repeat_calling.py | 747 | 4.1875 | 4 | #!/bin/env python
import functools as ft
def repeat(_func=None, *, times_no=2):
"""
Code for repeating function calls
The function will be call 2 times by default,
if the 'times_no' is specified the function will be call till the times_no is exhausted
"""
def taken_func(func):
@ft.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times_no):
value = func(*args, **kwargs)
print(value)
return value
return wrapper
if _func is None:
return taken_func
else:
return taken_func(_func)
@repeat
def add(*args):
return sum(args)
if __name__ == '__main__':
add(9, 2, 12, 82, 2, 1)
| true |
e6cda200d11040f094c59bd3216107df9092a092 | SohamGhormade/Python | /my_env/numbers.py | 398 | 4.125 | 4 | #Numbers in Python
x = 3
print(x) # prints 3
print(type(x))
print(x + 1) # prints 4
print(x - 1) # prints 2
print(x * 2) # prints 6
print(x**2) # prints 9
x += 1 # prints 4
print(x)
x *= 2
print(x) # prints 8
y = 2.5
print(type(y)) # prints "class<'float'>"
print(y, y + 1, y * 2, y ** 2) # prints 2.5, 3.5, 5.0, 6.25
# Python does not support unary operators ++,--.
| false |
67f51680a36ab1af96e5e378209a7557b977b5e1 | t-redactyl/Practical-Programming-exercises | /Scripts from book/walk_through5.py | 475 | 4.25 | 4 | def find_two_smallest(L):
'''Return a tuple of the indices of the two smallest values in list L.'''
# set min1 and min2 to the indices of the smallest and next-smallest values at the # beginning of L
if L[0] < L[1]:
min1, min2 = 0, 1
else:
min1, min2 = 1, 0
# examine each value in the list in order
for i in range(2, len(values)):
update min1 and/or min2 when a smaller value is found
return the two indices | true |
d7bcce45514daebc116d379b82e4a887241dbd12 | omriz/coding_questions | /596.py | 704 | 4.1875 | 4 | #!/usr/bin/env python3
r"""
This problem was asked by Google.
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
"""
import typing
class Node(object):
def __init__(
self,
value: str,
left: typing.Optional["Node"] = None,
right: typing.Optional["Node"] = None,
):
self.value = value
self.left = left
self.right = right
def invert_tree(tree:Node) -> Node:
if not tree:
return None
new_right = invert_tree(tree.left)
new_left = invert_tree(tree.right)
tree.left = new_left
tree.right = new_right
return tree
| true |
1d053584365c6bc11f62490b20bd2117764724ec | omriz/coding_questions | /1010.py | 1,490 | 4.15625 | 4 | #!/usr/bin/env python3
'''
The United States uses the imperial system of weights and measures,
which means that there are many different,
seemingly arbitrary units to measure distance.
There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on.
Create a data structure that can efficiently convert
a certain quantity of one unit to the correct amount of any other unit.
You should also allow for additional units to be added to the system.
'''
import logging
class Convertor(object):
def __init__(self):
self._inches = {
"inch": 1.0,
"foot": 12,
"yard": 3*12,
"chain": 22*36,
}
def convert(self,value, source_unit, target_unit):
if source_unit not in self._inches:
logging.error("%s - unknown unit" % source_unit)
return None
if target_unit not in self._inches:
logging.error("%s - unknown unit" % target_unit)
return None
return value*self._inches[source_unit]/(1.0*self._inches[target_unit])
def add_type(self,new_unit, value, current_unit):
if current_unit not in self._inches:
logging.error("%s - unknown unit" % current_unit)
return None
self._inches[new_unit] = value * self._inches[current_unit]
if __name__ == "__main__":
c = Convertor()
assert 66 == c.convert(1,"chain","foot")
c.add_type("moshe", 0.5, "foot")
assert 1 == c.convert(6, "inch", "moshe") | true |
4372916e4b90fa1d012d2fd4fccebfdf698dcf13 | omriz/coding_questions | /617.py | 1,535 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Given a number in Roman numeral format, convert it to decimal.
The values of Roman numerals are as follows:
{
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
In addition, note that the Roman numeral system uses subtractive notation for numbers such
as IV and XL.
For the input XIV, for instance, you should return 14.
"""
VALUES = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}
def compare_characters(a: str, b: str) -> int:
if a == b:
return 0
if a == "M" or b == "I":
return -1
if b == "M" or a == "I":
return 1
if a == "D" or b == "V":
return -1
if b == "D" or a == "V":
return 1
if a == "C" or b == "X":
return -1
if b == "C" or a == "X":
return 1
def compute_word(w: str) -> int:
total = 0
intermediate = VALUES[w[0]]
for i in range(1, len(w)):
compare_result = compare_characters(w[i - 1], w[i])
if compare_result == 0:
intermediate += VALUES[w[i]]
continue
elif compare_result == 1:
total -= intermediate
else:
total += intermediate
intermediate = VALUES[w[i]]
total += intermediate
return total
if __name__ == "__main__":
assert compute_word("XIV") == 14
assert compute_word("MCMXII") == 1912
assert compute_word("MMXX") == 2020
assert compute_word("MM") == 2000
assert compute_word("IIV") == 3
print("PASSED") | true |
1f0a702a23b7887410d4e102e084931cbb4ad428 | omriz/coding_questions | /523.py | 539 | 4.1875 | 4 | #!/usr/bin/env python3
"""
This problem was asked by Jane Street.
Given integers M and N, write a program that counts how many positive integer pairs
(a, b) satisfy the following conditions:
a + b = M
a XOR b = N
"""
import sys
# There's probably some linear algebra trick here.
def count_condition(m: int, n:int) -> int:
count = 0
for a in range(1,m/2 + 1):
b = m - a
if a ^ b == n:
count += 1
return count
if __name__ == "__main__":
print(count_condition(int(sys.argv[1]), int(sys.argv[2]))) | true |
3303648a0f67af96dc8a6472b41244be3ddd4105 | omriz/coding_questions | /516.py | 677 | 4.4375 | 4 | #!/usr/bin/env python3
"""
Let's define a "sevenish" number to be one which is either a power of 7,
or the sum of unique powers of 7. The first few sevenish numbers are 1, 7, 8, 49, and so on.
Create an algorithm to find the nth sevenish number.
"""
import sys
# This is actually funky. The nth number is sort of a binary encoding:
# 1 = 7^0 (1)
# 7 = 7^1 (10)
# 8 = 7^1 + 7^0 (11)
# 49 = 7^2 (100)
# 50 = 7^2 + 7^0 (101)
def get_nth_sevenish(n: int) -> int:
count = 0
sum = 0
while n > 0:
if n % 2:
sum += 7**count
n = n // 2
count +=1
return sum
if __name__ == "__main__":
print(get_nth_sevenish(int(sys.argv[1])))
| true |
854122ac47af8f6d6740c89e9a07ed0297cd1985 | omriz/coding_questions | /581.py | 1,893 | 4.125 | 4 | #!/usr/bin/env python3
"""
Given two rectangles on a 2D graph, return the area of their intersection.
If the rectangles don't intersect, return 0.
For example, given the following rectangles:
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
}
and
{
"top_left": (0, 5),
"dimensions": (4, 3) # width, height
}
return 6.
"""
import typing
class Rectangle(object):
def __init__(self, top_left: typing.Tuple[int,int], dimensions: typing.Tuple[int,int]):
self.top_left = top_left
self.dimensions = dimensions
def get_corners(r1: rectangle) -> typing.Tuple[int,int, int]:
r1_tl = r1.top_left
r1_tr = (r1.top_left[0] + r1.dimensions[0], r1.top_left[1])
r1_bl = (r1.top_left[0], r1.top_left[1] - r1.dimensions[1])
r1_br = (r1.top_left[0] + r1.dimensions[0], r1.top_left[1] - r1.dimensions[1])
return r1_tl, r1_tr, r1_bl
def intersection_area(r1: Rectangle, r2: Rectangle) -> typing.Optional[int]:
r1_tl, r1_tr, r1_bl = get_corners(r1)
r2_tl, r2_tr, r2_bl = get_corners(r2)
int_tl = (0,0)
if r1_tl[0] < r2_tl[0]:
int_tl[0] = r2_tl[0]
if r1_tl[1] < r2_tl[1]:
int_tl[1] = r1_tl[1]
else:
int_tl[1] = r2_tl[1]
else:
int_tl[0] = r1_tl[0]
if r2_tl[1] < r1_tl[1]:
int_tl[1] = r2_tl[1]
else:
int_tl[1] = r1_tl[1]
if r1_tr[0] > r2_tr[0]:
int_tr_x = r2_tr[0]
else:
int_tr_x = r1_tr[0]
if r1_bl[0] < r2_bl[0]:
if r1_bl[1] < r2_bl[1]:
int_bl_y = r2_bl[1]
else:
int_bl_y = r1_bl[1]
else:
if r2_bl[1] < r1_bl[1]:
int_bl_y = r1_bl[1]
else:
int_bl_y = r2_bl[1]
if int_tl[0] > int_tr_x:
return None
if int_bl_y > int_tl[1]:
return None
return (int_tr_x - int_tl[0]) * (int_tl[1] - int_bl_y) | true |
f8537c59531fe5d51933b68389bc4065b0fa94ae | omriz/coding_questions | /437.py | 1,061 | 4.3125 | 4 | #!/usr/bin/env python3
"""
This problem was asked by Square.
Given a string and a set of characters, return the shortest substring containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
import copy
import typing
import sys
def find_shortest_substring(word: str, chars: typing.Set[str]) -> str:
found = None
if not word:
return ""
for i in range(len(word)):
if word[i] not in chars:
continue
i_chars = copy.deepcopy(chars)
i_chars.remove(word[i])
n = i + 1
while n < len(word) and i_chars:
if word[n] in i_chars:
i_chars.remove(word[n])
n += 1
if not i_chars:
if not found or len(found) > n - i:
found = word[i : n + 1]
return found
if __name__ == "__main__":
print(find_shortest_substring(sys.argv[1], set(sys.argv[2:])))
| true |
ade7131680618fef76d054e0644bf43e1a3aaeb7 | xuelang201201/PythonCrashCourse | /09-类/动手试一试/ice_cream_stand.py | 1,060 | 4.28125 | 4 | """
冰淇淋小店:冰淇淋小店是一种特殊的餐馆。编写一个名为 IceCreamStand 的类,让它继承你为完成练习 9-1 或练习 9-4 而
编写的 Restaurant 类。这两个版本的 Restaurant 类都可以,挑选你更喜欢的那个即可。添加一个名为 flavors 的属性,用
于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋的方法。创建一个 IceCreamStand 实例,并调用这个方法。
"""
from restaurant2 import Restaurant
class IceCreamStand(Restaurant):
def __init__(self, name, cuisine_type='ice_cream'):
super(IceCreamStand, self).__init__(name, cuisine_type)
self.flavors = []
def show_flavors(self):
print("\nWe have the following flavors available:")
for flavor in self.flavors:
print("- " + flavor.title())
if __name__ == '__main__':
big_one = IceCreamStand('The Big One')
big_one.flavors = ['vanilla', 'chocolate', 'black cherry']
big_one.describe_restaurant()
big_one.show_flavors()
| false |
0719fc0b14b1e5c30df2c086061306a0c8a5bd37 | xuelang201201/PythonCrashCourse | /05-if语句/动手试一试/alien_colors.py | 1,681 | 4.15625 | 4 | """
外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名为 alien_color 的变量,并将其设置为 'green'、'yellow'或'red'。
1.编写一条 if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了 5 个点。
2.编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
"""
alien_color = 'green'
if alien_color == 'green':
points = 5
print("You got %d points." % points)
"""
外星人颜色#2:编写一个if-else结构。
1.如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了 5 个点。
2.如果外星人不是绿色的,就打印一条消息,指出玩家获得了 10 个点。
3.编写这个程序的两个版本,在一个版本中执行 if 代码块,而在另一个版本中执行 else 代码块。
"""
alien_color = 'red'
if alien_color == 'green':
points = 5
else:
points = 10
print("You got %d points." % points)
"""
外星人颜色#3:if-elif-else 结构。
1.如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 个点。
2.如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 个点。
3.如果外星人是红色的,就打印一条消息,指出玩家获得了 15 个点。
4.编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
"""
alien_color = 'red'
if alien_color == 'green':
points = 5
elif alien_color == 'yellow':
points = 10
else:
points = 15
print("You got %d points." % points)
| false |
61fc30137ed57dab96ea6f9879a9cd015a86a05b | xuelang201201/PythonCrashCourse | /03-列表简介/动手试一试/ways.py | 393 | 4.15625 | 4 | """
自己的列表: 想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。
根据该列表打印一系列有关这些通勤方式的宣言,如 “I would like to own a Honda motorcycle”。
"""
ways = ['walk', 'bicycle', 'motorcycle', 'car', 'bus', 'subway']
for way in ways:
print("I would like to go to work by %s." % way)
| false |
67a03d21728a14332628d5b8b5a5c0c019e1838b | xuelang201201/PythonCrashCourse | /06-字典/动手试一试/glossary.py | 960 | 4.46875 | 4 | """
词汇表:Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
1.想出你在前面学过的 5 个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
2.以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含
义;也可在一行打印词汇,再使用换行符(\n)插入一个空行,然后在下一行以缩进的方式打印词汇的含义。
"""
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
}
for word, meaning in glossary.items():
print("%s: %s" % (word.title(), meaning))
| false |
5f91a34ff4fddbfa5d5371bf4826282e43235a0b | xuelang201201/PythonCrashCourse | /11-测试代码/动手试一试/employee.py | 774 | 4.25 | 4 | """
雇员:编写一个名为 Employee 的类,其方法__init__()接受名、姓和年薪,并将它们都存储在属性中。编写一个名为 give_raise()
的方法,它默认将年薪增加 5000 美元,但也能够接受其他的年薪增加量。
为 Employee 编写一个测试用例,其中包含两个测试方法:test_give_default_raise()和 test_give_custom_raise()。使用方法
setUp(),以免在每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。
"""
class Employee:
def __init__(self, f_name, l_name, salary):
self.first = f_name.title()
self.last = l_name.title()
self.salary = salary
def give_raise(self, amount=5000):
self.salary += amount
| false |
86014e9a28d3fd3d8f6fc84e267b2fa58792f416 | robotcorner/ENG-101 | /HW-3/stammen_myPrime.py | 1,472 | 4.125 | 4 | # Created by Stephen Stammen
# Create an isPrime Function
def isPrime(num):
'''Returns True if n is prime'''
if num > 1: # 1 is not prime
for i in range(2, num): # This excludes 1 when looping
if num % i == 0: #
print('Im returning false')
return False
print('Im returning true')
return True
print('Im returning false')
return False
#Trying to understand the logic above
def main():
# Get a lower and upper integer from user entries
lowerInt = int(input('Input lower range value start point for prime numbers: '))
upperInt = int(input('Input higher range value: '))
numPrime = 0
numNonPrime = 1 # includes 1 because 1 is not checked
myPrimeList = []
for num in range(lowerInt+1, upperInt):
if isPrime(num) == True: # or == 1?
numPrime += 1
myPrimeList.append(num)
elif isPrime(num) == False:
numNonPrime += 1
else:
print('Something Wrong Happened')
print('There are ', str(numPrime), 'prime numbers between', str(lowerInt), 'and',
str(upperInt) + '.')
print('There are ', str(numNonPrime), 'non-prime numbers between', str(lowerInt), 'and',
str(upperInt) + '.')
if upperInt < 200:
print('Prime list', myPrimeList)
main()
# There are 1636 prime numbers between 4,568 and 19,954.
# There are 13750 non-prime numbers between 4,568 and 19,954.
| true |
497699513ad942e1dd9e443266b557f936feef6e | AleksejMoiseev/data-structures | /my_queue.py | 1,047 | 4.15625 | 4 | from linked_list import LinkedList
import time
class Queue:
def __init__(self):
self._linked_list = LinkedList()
def enqueue(self, data):
self._linked_list.append(data=data)
def dequeue(self):
return self._linked_list.erase(index=0)
def front(self):
return self._linked_list.get(index=0)
def back(self):
return self._linked_list.get_last_node()
def is_empty(self):
return self._linked_list.length() == 0
def __str__(self):
return self._linked_list.__str__()
if __name__ == '__main__':
q = Queue()
print("Queue empty: ", q.is_empty())
q.enqueue(data="Fedor")
q.enqueue(data="Bentsi")
q.enqueue(data="Julia")
q.enqueue(data="Roman")
q.enqueue(data="Alexey")
print(q)
print("Fedor is going to leave the Queue...")
time.sleep(3)
print(f"{q.dequeue()} left the Queue.")
print(q)
print("Front item in Queue: ", q.front())
print("Back item in Queue: ", q.back())
print("Queue empty: ", q.is_empty())
| false |
2a6bbb8b291efa08d2804c23900450cccf24cad9 | leemacpherson/hello-world | /mrx4000_Commands.py | 2,893 | 4.25 | 4 | # 2018, Lee MacPherson, leemacpherson@msn.com
# this program takes a list of hex characters and passes them to
#the function "checksum_generator". for
import checksum_generator
import codecs
# Ask for all of the hex values that will be added. These values will be put in a list.
# A while-loop will be used to add all of the elements in the list
# make a list to store all of the values that have to be added
hex_list = []
hex_value = 0
while hex_value != "":
hex_value = input ("enter the MID and Body values: ")
#print ("hex_value is :", hex_value)
hex_list.append(hex_value)
if hex_value == "":
break
#print ("the list of hex pairs is : ", hex_list)
# remove the quotation character. pop([index])removes the element at the specified index and returns that element. If index is not specified, it removes and returns last element from the list.
hex_list.pop()
# pass the list of hex pairs as an argument to the module "checksum_generator"
checksum = checksum_generator.chksum_gen (hex_list)
#indicate that you have had the checksum returned from the module checksum_generator
print ("the 'checksum_generator' module has returned back to 'mrx4000_Commands")
print ("checksum is : ", checksum)
#print ("hex_list is : ", hex_list)
#strip off the leading 0x from checksum
checksum_short = checksum[2:4]
#print ("checksum is : ", checksum_short)
#print ("checksum[0] is : ", checksum_short[0])
#print ("checksum[1] is : ", checksum_short[1])
#print ("type of checksum_short is ", type (checksum_short))
# assume the two checksum characters are lowercase letters (worse case) and convert both to uppercase with the
# str class method upper( )
checksum_upper_1 = checksum_short[0].upper()
checksum_upper_2 = checksum_short[1].upper()
#print("checksums after they are both run through the uppercase coversion: ", checksum_upper_1, checksum_upper_2)
# find the ascii value of each of the two checksum characters so they can put put in with the other characters
checksum_1 = format(ord(checksum_upper_1), "x")
#print ("checksum_1 is :", checksum_1)
checksum_2 = format(ord(checksum_upper_2), "x")
#print ("checksum_2 is :", checksum_2)
# append checksum and 03 to the end of the list
hex_list.append(checksum_1)
hex_list.append(checksum_2)
hex_list.append("03")
#print ("after appending checksum and 03, hex_list is : ", hex_list)
#add 19 to the beginning of the list, then add the percent % character before the 19
hex_list.insert(0, '19')
#print ("after inserting 19 , hex_list is : ", hex_list)
#finally, use the join() method to join each item in the list into one string with the % character between each one
final_list = "%".join(hex_list)
print (" put a '%' in front of the 19 then copy, paste this string into the AIB-4 table ; ", final_list)
| true |
409dfe2fee450655bb15c69e7c47f84ab69b70ac | garladinne/python_codetantra | /strongnum.py | 411 | 4.28125 | 4 | def factorial(n):
if (n==1):
fact=1
return fact
else:
fact=n*factorial(n-1)
return fact
num=int(input("Enter number to find strong or not: "))
n1=num
sum=0
while(num!=0):
n=num % 10
if (n == 0):
sum = 1
else:
sum = sum + factorial(n)
num=num//10
if (sum==n1):
print("The given number",n1,"is a strong number")
else:
print("The given number",n1,"is not a strong number")
| true |
febbbc23216aca31f66abbe3f8fbd42ad069b2cc | garladinne/python_codetantra | /factorial_recursive.py | 294 | 4.3125 | 4 | def factorial(n):
if (n==1):
fact=1
return fact
else:
fact=n*factorial(n-1)
return fact
n=int(input("Enter a number to find its factorial: "))
if (n>0):
fact=factorial(n)
print("The factorial of",n,"is:",fact)
else:
print("Enter a positive value to find its factorial") | true |
0cc2d0bd52f8cda93bdcabe287189f75ef7ac437 | SUREYAPRAGAASH09/Basic-Python-Programming | /Exercise/Even_odd_lenght_palindrome/palindrome.py | 469 | 4.1875 | 4 | Problem Statement :
===================
To check whether the given number is palindrome or not
Input :
=======
Number - Integer
Output :
========
Flag - True if palindrome exsist - Boolean
Flag - False if palindrome does Not exsist - Boolean
Code :
=======
import reverse
def palindrome(Number):
actualNum = Number
reversedNumber = reverse.reversess(N)
flag = False
if actualNum == reversedNumber:
flag = True
return flag
| true |
20bdb3129ece546c7ebf8d4d12f3eb8d7ea49b46 | HXT5/Base | /列表.py | 1,005 | 4.375 | 4 | '''
列表
增
append,insert,extend
删
del,remove,pop,clear
改
查
'''
list=[1,2,5]
#append,追加在末尾
list.append(6)
print("1、append:在列表末尾追加6")
print(list)
#insert,在固定位置插入
list.insert(2,4)
print("2、insert:在列表位置2追加4")
print(list)
#extend,将列表2追加到列表1
list1=[7,8]
list.extend(list1)
print("3、extend:将列表2追加到列表1")
print(list)
#del,删除列表中某个索引的数据
del list[0]
print("4、del:删除列表的第0个元素")
print(list)
#remove,删除列表中第一次出现的指定数据
list.remove(2)
print("5、remove:删除列表2")
print(list)
#pop,删除列表末尾数据
list.pop()
print("6、pop:删除列表最后一个元素")
print(list)
#clear,清空列表
# list.clear()
# print("7、clear:清空列表")
# print(list)
#排序
list.sort()
print("7、列表的正序")
print(list)
list.sort(reverse=True)
print("8、列表的倒序")
print(list)
list.reverse()
print("9、列表的反转")
print(list)
| false |
8d1a29ad93fbd78ed1a0395753e51e558157df39 | thisishaykins/PyBasics | /loops:nested_loops.py | 443 | 4.3125 | 4 | """
Adding one loop into another loop
"""
for x in range(4):
for y in range(3):
print(f"({x}, {y})")
print("")
print("----------------------------")
print("")
numbers = [5, 2, 5, 2, 2]
for number in numbers:
print(number * "*")
print("")
print("----------------------------")
print("")
numbers = [5, 2, 5, 2, 2]
for number in numbers:
output = ''
for count in range(number):
output += '*'
print(output)
| true |
b1aaaf1a4cf1959ee1707384e3ddaaf21260e64c | thisishaykins/PyBasics | /operator_precedence.py | 293 | 4.125 | 4 | x = 10 + 3 * 2
print(x)
# parenthesis
# exponentiation 2 ** 3
# multiplication or division
# addition or subtraction
x = 10 + 3 * 2 ** 2
print(x)
y = (2 + 3) * 10 - 3
yy = (3 + 5) * 10 ** 3
print(y)
print(yy)
vic = "The gram the county of the market infrastructure plans fir the"
print(vic) | false |
12bad211ced9fd8975a95d276049fe2157d9cfdc | AndriyanTW/PRAK-SKD-TUGAS-3 | /SKD_TI D_V3920008_ANDRIYAN T.W_tugas 3.py | 1,867 | 4.1875 | 4 | huruf = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #di sini saya menggunakan huruf Kapital
#huruf = "abcdefghijklmnopqrstuvwxyz" | Huruf Kecil
print ("---------------------------")
namaku = input("Nama : ").upper() # | saya menggunakan huruf kapital maka menggunakan Uppercase
#namaku = input("Nama : ").lower() | Jika ingin menggunakan huruf kecil pada keluarannya maka menggunakan Lowercase
kunci = int(input("Pergeseran Angka : "))
#contoh :
#Urutan normal 123456789
#kemudian memisah angka
#pisahan_pertama - 123
#pisahan_kedua - 456789
#hasilnya- 456789123.
if kunci == 0:#dimulainya penginputan dari 0
urutan_baru = huruf
#Jika menginputkan angka 0 maka hasil dari yang di masukan pada nama tidak akan berubah
#Pada elif ini akan di jalankan jika memasukan angka yang lebih dari 0
elif kunci > 0:
pisahan_pertama = huruf[:kunci]
pisahan_kedua = huruf[kunci:]
urutan_baru = pisahan_kedua + pisahan_pertama
#apabila menginputkan angka 8
# pisahan_pertama akan di tambah dengan pisahan_kedua dan akan membuat hasil urut yang baru
# ketika program di jalankan. maka nama akan Terenkripsi
else:
pisahan_pertama = huruf[:(26 + kunci)]
pisahan_kedua = huruf[(26 + kunci):]
urutan_baru = pisahan_kedua + pisahan_pertama
enkripsi=" "
#Fungsi len() berfungsi untuk mengembalikan panjang (jumlah) dari objek.
for masukan in range(0,len(namaku)):
if namaku[masukan] == " ":
enkripsi += " "
for masukan_huruf in range(0,len(urutan_baru)):
if namaku[masukan] == huruf[masukan_huruf]:
enkripsi+= urutan_baru[masukan_huruf]
# Kemudian membuat output untuk hasil dari Pergeseran angka
print ("---------------------------")
print ("Enkripsi :"+enkripsi)
print ("Dekripsi : "+namaku)
print ("---------------------------") | false |
045ff118fa55e203a9bc974e9b8e190350ab0a50 | seanmenezes/python_projects | /datastructures/map.py | 567 | 4.3125 | 4 | items = [
("Product1",10),
("Product2",9),
("Product3",12),
]
prices = []
for item in items:
prices.append(item[1])
print(prices)
# better or more elegant way
# map(func, *iterables)
# first item lambda function, second item list of iterables
# return x a map object which is another iterable
print('using map object to extract price')
x = map(lambda item: item[1], items)
for item in x:
print(item)
print('after converting map to list')
# other option convert map object to list object
y = list(map(lambda item: item[1], items))
print(y)
| true |
f37dc41de90423b44ebcc4822a0a2c48794c57e1 | streamnsight/python-meetup-topics | /beginners/syntax.py | 963 | 4.125 | 4 | # Basic syntax:
# This is a comment
example = 0 # A comment can also come at the end of a line of code. 2 spaces before the # is recommended
'''
This is a multi-line string, which as stand alone is also a interpreted as comment.
This is the second line
'''
"""
Same goes with the double quotes
"""
# variable names tend to be written in snake_case, but it is not a requirement.
my_variable = 0
# class names tend to be written in CamelCase, but it is not a requirement either
class MyClass:
pass
# function names are also typically in snake_case
def my_function(var1, var2):
"""
:param var1: this is variable 1 in the function
:param var2: this is variable 2 in the function
:return:
"""
# the lines above are called DocStrings, and they are used to document the code.
# they can be parsed by framework like Sphynx to generate a HTML documentation for the code
# triple double quotes are used for DocStrings
pass
| true |
131a8ed7e207d5c26cb60c7aecfaa33a15302f15 | aishsicle/pythbelike | /section5.py | 2,669 | 4.15625 | 4 | While Loops
-continue to execute code WHILE some condition remains TRUE eg) while my pool isnt full, keep adding water
o smtg diff
#Syntax: while some_boolean_condition: do something
#can also include
else: #do smtg diff
x=0
while x < 5: #only runs while this condition is true
print(f'the current value of x is {x}')
x=x+1
x=0
while x < 5: #only runs while this condition is true
print(f'the current value of x is {x}')
x=x+1
the current value of x is 0
the current value of x is 1
the current value of x is 2
the current value of x is 3
the current value of x is 4
else:
print("X IS NOT LESS THAN 5")
x=0
while x < 5: #only runs while this condition is true
print(f'the current value of x is {x}')
x=x+1
# x+=1 same line just more compact lol java
else:
print("X IS NOT LESS THAN 5")
the current value of x is 0
the current value of x is 1
the current value of x is 2
the current value of x is 3
the current value of x is 4
X IS NOT LESS THAN 5
# Lets do this for example
x=50
while x < 5: #only runs while this condition is true
print(f'the current value of x is {x}')
x+=1
else:
print("X IS NOT LESS THAN 5")
#will only execute the else bc the while statement wont execute at all bc it'll never be true
File "<ipython-input-9-1c645c7e6b90>", line 9
print("X IS NOT LESS THAN 5")
^
IndentationError: expected an indented block
USEFUL KEYWORDS (which u probs wont use all the time) break, continue, pass
break: breaks out of current closest enclosing loop
continue: goes to the TOP of the closest enclosing loop
pass: does nothing at all
#pass keyword
#pass keyword
x=[1,2,3]
for item in x:
# if you just put a comment here bc you dont know what to do, you get an error
# solution:
pass
continue
#continue
mystring = 'Sammy'
for letter in mystring:
print(letter)
S
a
m
m
y
my_string='aischwauriya'
for letter in my_string:
if letter == 'a':
continue #so you go back to the top of the code
print(letter)
#lets say i didnt want it to print letter 'a'
my_string='aischwauriya'
for letter in my_string:
if letter == 'a':
continue #so you go back to the top of the code
print(letter)
i
s
c
h
w
u
r
i
y
#break
my_string='shaischwauriya'
for letter in my_string:
if letter == 'a':
break #so mow you dont go back to the top, it stops here
print(letter)
s
h
#break is useful in while loops
#example:
x=0
while x<5:
if x==2:
break
print(x)
x+=1
#break is useful in while loops
#example:
x=0
while x<5:
if x==2:
break
print(x)
x+=1
0
1
| true |
f2709dbe0f07b5219e443f7b55ad8c4bfef3689f | CDog5/AutoUpdate | /Generators.py | 1,113 | 4.1875 | 4 | # generator object that splits a sentence into words
def sentence_to_words(words):
punctuation = [".",",","?","!","-"," ",":",";"]
for punc in punctuation:
words = words.replace(punc," ")
words = words.split()
yield from words
# generator object that splits a string into certain chars
def string_to_chars(string,mode="all"):
chars=[]
if "all" in mode.lower():
for char in string:
chars.append(char)
elif "alpha" in mode.lower():
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in string:
if char.lower() in alphabet:
chars.append(char)
elif "numeric" in mode.lower():
numbers = "0123456789"
for char in string:
if char in numbers:
chars.append(char)
elif "special" in mode.lower():
specials = r"!£$%^&*()_+{}[]#~/*-¬`@\|"
for char in string:
if char in specials:
chars.append(char)
yield from chars
s = string_to_chars("Hello people, I am Bob!","alpha")
print([c for c in s])
| false |
93c7535b270ccf940270d9da6fbf455c664baff7 | Nehanavgurukul/codechef | /A32_3.py | 370 | 4.25 | 4 | price1 = int(input("enter the price"))
price2 = int(input("enter the price"))
price3 = int(input("enter the price"))
if(price1 >= price2):
if(price1 >= price3):
print(price1, "is max")
elif(price2 >= price1):
if(price2 >= price3):
print(price2, "is max")
elif(price3 >= price1):
if(price3 >= price2):
print(price3, "is max")
| true |
e4a197c6820de5051c6dea56bea0e2742cf2b6a8 | Pramukh660/Python_programs | /if_else.py | 278 | 4.125 | 4 | print("Enater any two numbers")
a = input(" ")
b = input(" ")
if a>b:
print(str(a)+" is greater than "+str(b))
elif a<b:
print(str(b)+' is greater than '+ str(a))
else :
print(str(a)+" is equal to "+str(b))
if 1<2: print('program execution completed') | false |
1d1b64304d07a9bac52be823fdcab745147b148b | Apologise/Python_sublime | /第四章/4-10.py | 287 | 4.28125 | 4 | list1 = [1,2,3,4,5,6,7,8,9]
print("The first items in the list are:")
for value in list1[0:3]:
print(value)
print("The mid items in the list are")
for value in list1[3:6]:
print(value, end = " ")
print("The last three items in the list are:")
for value in list1[-3:]:
print(value,)
| true |
21f5fd68b8b3f79cd6658707609f64ef4eb1a8c1 | alfonso-torres/eng84_python_exercises | /exercise_4_extra.py | 2,510 | 4.46875 | 4 | # EXERCISE 4
# Super simple game that will substitute multiples of 3 and 5 for Fizz and
# Buzz respectively, or Fizzbuzz for multiples of the both.
# Tasks
# Write a program that prints the numbers from 1 to 100.
# For multiples of three print "Fizz" instead of the number.
# For the multiples of five print "Buzz" instead of the number.
# For numbers which are multiples of both three and five print "FizzBuzz".
# BUT MAKE IT FUNCTIONAL
# so we can decide which numbers to substitute for fizz and buzz using functions.
# Let's define the two variables to see with which is multiple or not
var_fizz = 3
var_buzz = 5
# Function to generate the correct prints
def generate_fizzbuzz(num1, num2):
for number in range(1, 101, 1): # For loop from 1 to 100
if number % num1 == 0 and number % num2 == 0: # Check if is multiple of both
print("FizzBuzz")
elif number % num1 == 0: # Check if is multiple of fizz
print("Fizz")
elif number % num2 == 0: # Check if is multiple of buzz
print("Buzz")
else:
print(number) # Not multiple
# Function to return the new value of Fizz in the case that user wants to change
def change_value_fizz():
new_fizz = input("Enter new value for Buzz (Only DIGITS): ")
while new_fizz.isdigit() == False: # Check if the input is not a digit
new_fizz = input("Try again... (Only DIGITS): ")
new_fizz = int(new_fizz) # Casting from String to int
return new_fizz
# Function to return the new value of Buzz in the case that user wants to change
def change_value_buzz():
new_buzz = input("Enter new value for Fizz (Only DIGITS): ")
while new_buzz.isdigit() == False: # Check if the input is not a digit
new_buzz = input("Try again... (Only DIGITS): ")
new_buzz = int(new_buzz)
return new_buzz
print("Welcome to the FIZZBUZZ game.")
# Ask user if the want to change the default values or not
answer = input("Would you like to change the default values of Fizz(3) and Buzz(5)? (Y/N): ")
run_program = True
while run_program:
if answer == "N": # In the case if they want to keep the same values
generate_fizzbuzz(var_fizz, var_buzz)
run_program = False
elif answer == "Y": # In the case if they want to change the values
var_fizz = change_value_fizz()
var_buzz = change_value_buzz()
generate_fizzbuzz(var_fizz, var_buzz)
run_program = False
else:
answer = input("Try again... (Y/N): ")
| true |
6cbabd2e2cbb6603184c641239b336bee852a8ce | touilleWoman/Bootcamp_python_MachineLearning | /Day00/ex04/operations.py | 1,164 | 4.1875 | 4 | import sys
def operations(x, y):
if x.lstrip("-").isdigit() and y.lstrip("-").isdigit():
x = int(x)
y = int(y)
if y == 0:
div = "ERROR (div by zero)"
modulo = "ERROR (modulo by zero)"
else:
div = x / y
modulo = x % y
print(
f"sum: {x + y}\n"
f"Difference: {x - y}\n"
f"Product: {x * y}\n"
f"Quotient: {div}\n"
f"Remainder: {modulo}")
else:
print(
"InputError: only numbers\n"
"Usage: python operations.py\n"
"Example:\n"
" python operations.py 10 3"
)
def check_arg():
if len(sys.argv) < 3:
print(
"Usage: python operations.py\n" "Example:\n" " python operations.py 10 3"
)
elif len(sys.argv) > 3:
print(
"InputError: too many arguments\n"
"Usage: python operations.py\n"
"Example:\n"
" python operations.py 10 3"
)
else:
operations(sys.argv[1], sys.argv[2])
if __name__ == "__main__":
check_arg()
| false |
f90ba2f5a9bf09d82347fae52273df68b213789f | NabinKatwal/cryptography | /Lab/caeserCipher.py | 482 | 4.125 | 4 | def encrypt(text, s):
result = ''
for i in range(0, len(text)):
# ENCRYPT UPPERCASE LETTERS
if text[i].isupper():
result += chr((ord(text[i])+s-65)%26+65)
# ENCRYPT LOWERCASE LETTERS
else:
result += chr((ord(text[i])+s-97)%26+97)
return result
if __name__ == "__main__":
text = input("Enter the text: ").strip()
shift = int(input("Enter the shift value: "))
print(f'Cipher: {encrypt(text, shift)}')
| true |
ffc88df53c903279a404a7ef00931151033253c0 | pewo/courses | /ProgrammingForEverybody/test.py | 345 | 4.125 | 4 | #!/usr/bin/python
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
try:
num = int(num)
except:
if num == "done" :
break
else:
print "Invalid input"
if num > largest:
largest = num
if num < smallest or smallest == None:
smallest = num
print "Maximum", largest
print "Minimum", smallest
| true |
b39fe119ed7a2b4d3980f6762bb7c197a7e0cc57 | Aleks-Ya/yaal_examples | /Python+/Python3/src/module/standard/re/pattern.py | 808 | 4.15625 | 4 | # Examine pattern
import re
from re import Match
# Square brackets
line: str = "Cats [are smarter] than dogs"
match: Match = re.match(r'Cats \[(.*?)\] than dogs', line)
assert match
assert match.group(1) == "are smarter"
# Comma
line: str = "123,456"
match: Match = re.match(r'\d{3},\d{3}', line)
assert match
# Comma in character group
line: str = "123,456"
match: Match = re.match(r'\d{3}([,;])\d{3}', line)
assert match
assert match.group(1) == ","
# Parenthesis
line: str = "Cats (are smarter) than dogs"
match: Match = re.match(r'Cats \((.*?)\) than dogs', line)
assert match
assert match.group(1) == "are smarter"
# Ignore case
line: str = "CATS (are smarter) than dogs"
match: Match = re.match(r'Cats \((.*?)\) than dogs', line, re.IGNORECASE)
assert match
assert match.group(1) == "are smarter"
| false |
fdc1b9e8da163ba9319d0fc55672ce11631fe1e1 | Aleks-Ya/yaal_examples | /Python+/Python3/src/core/asterisk.py | 561 | 4.25 | 4 | # Using asterisk function (*) in front of variables
# Asterisk as a function
t = (1, 2, 3)
print(t)
print(*t)
# Single asterisk - any number of arguments AS A TUPLE
a = 1
b = 2
c = 3
def print_args(*args):
print(args)
print_args(a, b, c)
# Double asterisk - any number of arguments AS A DICTIONARY
def print_args(**args):
print(args)
print_args(a=7, b=8, c=9)
# Add key-value pair to a asterisk dictionary
def print_added_args(**args):
print(args)
def add_and_print(**args):
print_added_args(c=3, **args)
add_and_print(a=1, b=2)
| true |
4bfbce6145e3949d302ba781640343aa7f38bba9 | auroprit182/DS-ALGO | /sorting/bubbleSort.py | 467 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 20:13:54 2021
@author: auropritbhanjadeo
"""
def bubbleSort(a):
while True:
swapped=False
for i in range(len(a)-1):
if a[i]>a[i+1]:
a[i],a[i+1]=a[i+1],a[i]
swapped = True
if swapped == False:
break
a = [6,5,3,1,8,7,2,4]
bubbleSort(a)
print(a) | false |
d54a3747e15e0dbb8732d8d5c39c5f0105304aeb | SCHayworth/3-5-mass-and-weight | /mass-and-weight.py | 1,781 | 4.59375 | 5 | # Mass and Weight
# Shaun Hayworth
# CIS 2
# 10-03-2019
# Converts mass in kilograms to weight in newtons, and displays a message that the object is too heavy if it is over 500 newtons
# and too light if it is less than 100 newtons.
# This version of the program uses functions for converting mass to weight, and to loop the program indefinitely until the user
# tells it to stop.
# This function converts mass to weight using the formula weight = mass * 9.8
def convert_to_weight(mass):
return mass * 9.8
# Asks user if they would like to run the program again, and sets the run_again varible to false if not.
def repeat_query():
repeat = ''
while repeat != 'y' or repeat != 'Y' or repeat != 'n' or repeat != 'N':
repeat = input('\nWould you like to run the program again (y/n)? ')
if repeat == 'y' or repeat == 'Y':
return True
elif repeat == 'n' or repeat == 'N':
return False
# main program function
def main():
# Prompt user for mass in kilograms and stores the result in mass
mass = float(input('Please enter an object\'s mass in kg: '))
# Call function to convert mass to weight
weight = convert_to_weight(mass)
# Display the result
print(f'\n{mass} kg is eqal to {weight} newtons.')
# If weight is above 500, prints a message saying the object is too heavy, and if weight is below 100, prints a message
# saying the object is too light.
if weight > 500:
print('\nThis object is too heavy!')
elif weight < 100:
print('\nThis object is too light!')
# Set the run_again variable to True by default
run_again = True
# Loops the main program as long as run_again is True
while run_again == True:
print("\033c") # Clears the screen
main()
another_time = repeat_query()
run_again = another_time
| true |
5efee76e5b439b353f94f08317a4d639a7001e22 | JMJett/ThinkPythonExercises | /Exercise 6.2.py | 272 | 4.125 | 4 | __author__ = 'Jarod Jett'
import math
def hypotenuse(a,b):
squared = a**2 + b**2
c = math.sqrt(squared)
return c
a = float(input("Enter side A of the triangle: "))
b = float(input("Enter side B of the triangle: "))
print("The hypotenuse is ", hypotenuse(a,b))
| true |
8417178347f85a87c00455f5bb58f8c018f96b3f | yuanjie-ai/iNLP | /inlp/missingno/utils.py | 2,136 | 4.21875 | 4 | """Utility functions for missingno."""
import numpy as np
def nullity_sort(df, sort=None):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
else:
return df
def nullity_filter(df, filter=None, p=0, n=0):
"""
Filters a DataFrame according to its nullity, using some combination of 'top' and 'bottom' numerical and
percentage values. Percentages and numerical thresholds can be specified simultaneously: for example,
to get a DataFrame with columns of at least 75% completeness but with no more than 5 columns, use
`nullity_filter(df, filter='top', p=.75, n=5)`.
:param df: The DataFrame whose columns are being filtered.
:param filter: The orientation of the filter being applied to the DataFrame. One of, "top", "bottom",
or None (default). The filter will simply return the DataFrame if you leave the filter argument unspecified or
as None.
:param p: A completeness ratio cut-off. If non-zero the filter will limit the DataFrame to columns with at least p
completeness. Input should be in the range [0, 1].
:param n: A numerical cut-off. If non-zero no more than this number of columns will be returned.
:return: The nullity-filtered `DataFrame`.
"""
if filter == 'top':
if p:
df = df.iloc[:, [c >= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[-n:])]
elif filter == 'bottom':
if p:
df = df.iloc[:, [c <= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[:n])]
return df
| true |
70063e6619f8ee99ed020eb95c62943d8baafcbf | m0ng00se/MIT-SICP | /Recitations-F2007/Recitation-06/python/exercise02.py | 1,384 | 4.21875 | 4 | #!/usr/bin/python
#
# Working definitions (python)
#
def make_units(C,L,H):
return [C,L,H]
def get_units_C(x):
return x[0]
def get_units_L(x):
return x[1]
def get_units_H(x):
return x[2]
def make_class(number,units):
return [number,units]
def get_class_number(x):
return x[0]
def get_class_units(x):
return x[1]
def get_class_total_units(klass):
units = get_class_units(klass)
return get_units_C(units) + get_units_L(units) + get_units_H(units)
def same_class(klass1,klass2):
return get_class_number(klass1) == get_class_number(klass2)
#
# Previous Solutions
#
def empty_schedule():
return []
#
# Exercise 2
#
# Write a selector that when given a class and a schedule, returns a
# new schedule including the new class:
#
def add_class(klass,schedule):
schedule.append(klass)
return schedule
#
# Run some unit tests.
#
# First define some units and classes:
#
u1 = make_units(3,3,3)
calc1 = make_class(101,u1)
calc2 = make_class(102,u1)
#
# Now try to build a schedule using these:
#
s = add_class(calc1,empty_schedule())
s = add_class(calc2,s)
#
# Inspect the schedule:
#
print "First class:\t", s[0]
# ==> [101, [3, 3, 3]]
print "Second class:\t", s[1]
# ==> [102, [3, 3, 3]]
#
# The order of growth in both time and space is linear in the variable
# "schedule", that is, it is O(n) where "n" is the length of the list
# structure "schedule".
#
| true |
7e6efa6c79c1edf61f39c7dc55eeadc08621baee | RyanPennell/6.001.x | /Ps1P3.py | 721 | 4.375 | 4 | #Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
#For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh
#In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
#Longest substring in alphabetical order is: abc
s = input('input string: ')
string = s[0]
tempstring = string
for i in range (1, len(s)):
if ord(s[i]) >= ord(tempstring[-1]):
tempstring += s[i]
if len(tempstring) > len(string):
string = tempstring
else:
tempstring = s[i]
print('Longest substring in alphabetical order is: ' + string)
| true |
c8d9aa3efb94e114f953acdcb3949026357c5b34 | libgy24/Python-OOP-Tutorial | /Python_reading_and_writing_to_files.py | 2,102 | 4.21875 | 4 | # File object
#### read file
f = open('test.txt', 'r')
print(f.name)
print(f.mode)
# when we open a file , we have to explicitly close it.
# if we do not close the file, we may run out file descriptor in the system.
f.close()
# 'r': read flie
# 'w': write file
# 'a': append file
# 'r+': read and write file
# context manager allows us to work with files from within this block and
# after we exit the block, it automatically the file for us.
with open('test.txt', 'r') as f:
# f_contents = f.read()
f_contents_1 = f.readlines()
# print(f_contents)
print(f_contents_1)
# after we exist the block, we still have have access to the variable "f",
# but the file is closed. we cannot read it.
# it is efficient, because it does not all the content all in once.
with open('test.txt', 'r') as f:
for line in f.readlines():
print(line, end = '\t')
with open('test.txt', 'r') as f:
f_contents = f.read(5) # this will grab the first 10 characters in the file
print(f_contents)
while len(f_contents) > 0:
print(f_contents, end = '*')
print(f.tell())
f_contents = f.read(5)
with open('test.txt', 'r') as f:
size_to_read = 10
f_contents = f.read(size_to_read)
print(f_contents, end = "*")
f.seek(0)
while len(f_contents) > 0:
f_contents = f.read(size_to_read)
print(f_contents)
f.seek(0) # return the pointer to the beginning, and this would never end.
f_contents = f.read(size_to_read)
#### write file
with open('test2.txt', 'w') as f:
f.write('This is a test file for python\n this is to test write mode')
with open('test2.txt', 'w') as f:
f.write('Test')
f.seek(0)
f.write('R')
with open('test.txt','r') as rf:
with open('test_copy.txt', 'w') as wf:
for line in rf.readlines():
wf.write(line)
# when we work with jpg file, we have to open the file in binary file
# we are going to read byte.
with open('mini.jpg', 'rb') as rf:
with open('mini_copy.jpg', 'wb') as wf:
for line in rf.readlines():
wf.write(line)
| true |
0962b0f020bd0e104695187b3541138330d6fa98 | rajaram-repo/bioinformatics-repo | /Exercises/exercise_02.py | 2,711 | 4.34375 | 4 | """
exercise_02
2/1/2018
"""
def first_elements(my_list, n):
"""
returns the first n elements in a list.
EX: first_element([0, 1, 2, 3], 2) should return [0, 1]
:param my_list: a non-empty list
:param n: an integer greater than 0
:return: a list of length n
"""
temp_list = my_list[0:n]
#print(temp_list)
return temp_list
q1_list = first_elements([6,7,8,9,10],3)
print('Question 1 ::: The 1st list',q1_list)
def first_element(my_list, n):
"""
returns the last n elements in a list.
EX: last_element([0, 1, 2, 3], 2) should return [2, 3]
:param my_list: a non-empty list
:param n: an integer greater than 0
:return: a list of length n
"""
temp_list = my_list[len(my_list)-n:len(my_list)]
#print(temp_list)
return temp_list
q2_list = first_element([1,2,3,4,5,6,7],2)
print('Question 2 ::: The 2st list',q2_list)
def n_elements(my_list, start, n):
"""
returns n elements in a list, starting at the position "start".
EX: n_elements([0, 1, 2, 3, 4, 5], 2, 3) should return [2, 3, 4]
:param my_list: a non-empty list
:param start: a non-negative integer
:param n: an integer greater than 0
:return: a list of length n
"""
temp_list = my_list[start:start+n]
return temp_list
q3_list= n_elements([0, 1, 2, 3, 4, 5],1,4)
print("Question 3 ::: q3 list is",q3_list)
def count_letters(s):
"""
returns a dictionary containing each letter in s as a key and
the number of times each letter has occurred as the value
:param s: a string
:return: a dictionary
"""
dict = {}
temp_list = set(s)
for x in temp_list:
count = s.count(x)
dict[x] = count
return dict
q4_dict = count_letters('rajaram')
print('Question 4 ::::::::::::')
for i in q4_dict:
print('the letter ',i,'occurs',q4_dict[i],'times')
print(':::::::::::::::::::::')
def protein_wight(protein):
"""
Given a string of amino acids coding for a protein, return the total mass of the protein
:param protiein: a string containing only G, A, L, M, F, W, K, Q, E, S, P, V, I, C, Y, H, R, N, D, and T
:return: a float
"""
AMINO_ACID_WEIGHTS = {'A': 71.04, 'C': 103.01, 'D': 115.03, 'E': 129.04, 'F': 147.07,
'G': 57.02, 'H': 137.06, 'I': 113.08, 'K': 128.09, 'L': 113.08,
'M': 131.04, 'N': 114.04, 'P': 97.05, 'Q': 128.06, 'R': 156.10,
'S': 87.03, 'T': 101.05, 'V': 99.07, 'W': 186.08, 'Y': 163.06}
total_mass = 0
for x in protein:
total_mass = total_mass + AMINO_ACID_WEIGHTS[x]
return total_mass
q5_mass = protein_wight('GA')
print('Question 5 ::: Total mass:',q5_mass)
| true |
df72bb27acec2d512ecd94b81341ff3b5007c1fd | arvindv17/Python-For-Beginners | /Python Data Structures/Assignment8.4.py | 748 | 4.4375 | 4 | """
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
The program should build a list of words.
For each word on each line check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.py4e.com/code3/romeo.txt
"""
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
newline=line.split()
length = len(newline)
length_range = range(length)
for i in length_range:
value = newline[i]
if value not in lst:
lst.append(value)
lst.sort()
print (lst) | true |
af7048ed33e2f50cdee07df5ec795aee00465d1c | prativadas/python-basics | /7. Chapter 7/15_01.py | 1,636 | 4.40625 | 4 |
#simple pyramid pattern
# for i in range(3): #executes for 0 to 2. means rows=3. i = no of rows = 0,1,2
# for j in range(3-i): #executes for 3 to 1. cols=3. j = 3,2,1.
# print('*', end='') #for 1st row j extecutes 3 times then exits loop and i increaments. goes on like this
# print()
# for i in range(3): # 1st row is only empty space as j has range = i=0 false stmnt. i =0,1,2
# for j in range(i): # if j range is till 3 it will print star in 3 col. when i=0,for loop is false and goes to outer for loop print.
# print('*', end='') # i=2, j executes 2 times for i= 0,1. so prints 2 *
# print()
# # prints * smaller to larger
# for i in range(3):
# for j in range(i+1): # to avoid empty space at 1st row, j runs for 1 time for i=0, j runs 2 times for i =1 so on
# print('*', end='')
# print()
# upper program in different ways
# prints * larger to smaller
# prints o/p one by one if we use print() one by one
# difficult to understand. as shown in video
n = 4
for i in range(3): #loop runs 0 to 2 times. i idicates rows.for i=0 all print() executes at once one by one
print('*' * (n-i-1), end="") #for i = 0, (n-1-i)=3; i=1,(n-1-i)=2; i=2,(n-1-i)=1 row wise * will print in a single line. no leftspace required.
# print(" " * (n-i-1)) #for rigtspace, for i=0,rs=3; i=1,rs=2; i=2,rs=1. these spaces are not visible. just imagine the rs there.
print(" " * (i))
# print(" " * (n))
| true |
8dd43ecc414417c73354404581c6d60c4e2999a9 | prativadas/python-basics | /10. Chapter 10/11_pr_03.py | 494 | 4.1875 | 4 | class Sample:
a = "Harry" # class atrr
obj = Sample() # object of class sample
obj.a = "Vikky" # instance atrr with same same name 'a'.
# obj.a = "Vikky" #if we comment ou this, then print(obj.a) returns harry by default value.
# Sample.a = "Vikky" #this way we can change the value of class attr
print(Sample.a) # doesnt change its value.
print(obj.a) # instance attributes takes preferenace over class attribute during assignmnet and retrieval. | true |
356dbbbb7186910458887a16c70f3a1f91da1abf | prativadas/python-basics | /11. Chapter 11/04_multilevel_inheritance.py | 1,498 | 4.28125 | 4 | # when a child class become a parent for another child class
class Person: #parent/base class 1
country = "India"
def takeBreath(self):
print("I am breathing...")
class Employee(Person): # derived/child class 1
company = "Honda"
def getSalary(self):
print(f"Salary is {self.salary}")
def takeBreath(self): # method overwritten from base class 1
print("I am an Employee so I am luckily breathing..")
class Programmer(Employee): # child/derived class 2. Person child class is parent class of Programmer child class
company = "Fiverr"
def getSalary(self): # method overwritten from base class 2
print(f"No salary to programmers")
def takeBreath(self): # method overwritten from base class 1
print("I am a Progarmmer so I am breathing++..")
p = Person() # object of base class 1 is instantiated
p.takeBreath()
# print(p.company) # throws an error as no atrr named company is found in that class
e = Employee() # object of base class 2 is instantiated
e.takeBreath()
print(e.company)
pr = Programmer() #object of base class 1 is instantiated
pr.takeBreath()
print(pr.company)
print(pr.country) # Programmer class doesnt have country attr, so it search in its parent class Person and prints india.
| true |
af8b2d12966b7986c893f1d22bb07c04b785a597 | prativadas/python-basics | /7. Chapter 7/13_my.py | 428 | 4.40625 | 4 | # factorial of n numbers
num = int(input('enter number: '))
fact = 1
# for i in range(1,num+1): # for loop executes 1 to num.
# fact = fact * i # updates variable fact. for num =3, loop runs for 1,2,3. so fact= 1*1=1; fact=1*2=2;fact=2*3=6
# print('factorial is: ', fact)
#using while loop
i = 1
while i<=num:
fact = fact* i
i = i + 1
print('factorial is: ', fact)
| true |
1d65eb3110b2082ec22279899564598a192d7ddb | prativadas/python-basics | /7. Chapter 7/15_pr_07.py | 419 | 4.1875 | 4 | # reverse right angle pyramid
n = 3
for i in range(3): # i = 0,1,2. i indicates rows
print(" " * (n-i-1), end="") # print space in left side. for i=0, leftspace=2, i=1, leftspace=1 so on
print("*" * (2*i+1), end="") # print *, odd number of * printed. for i=0, * printed= 1 so on
print(" " * (n-i-1)) # print space in right side. for i=0,rs=2; i=1,rs=1 so on
| true |
7c756e8b9fc1f323faeb1fe27d4a62329ba527ed | prativadas/python-basics | /advance python/12. Chapter 12/09_enumerate.py | 605 | 4.3125 | 4 | #enumerate() adds counter to an iterable and returns it. here iterable is i/item
list1 = [3, 53, 2, False, 6.2, "Harry"]
# index = 0 # we have to initilize index first, to use it in for loop. its extra work. so use enumerate()
# for i in list1: # i can be replaced with item
# print([index], i)
# index += 1 #python doesnt understand ++, only += works. to print index of items in an list using for loop.
for index, item in enumerate(list1): # to print index of items in an list using enumerate()
print([index], item) | true |
e3767fe34b09f9a9fb67d7b1a843df95a8fe96ce | prativadas/python-basics | /8. Chapter 8/09_my.py | 662 | 4.25 | 4 | # print pattern using function.
# n= int(input('enter any num:' ))
# for i in range(n):
# print('*'*(n-i))
#python function to print such pattern?
#function to print pyramid pattern
def print_pattern(n,i):
print('*'*(n-i))
if i<0: # when i < 0 is false it comes out of the loop if loop.
return
return print_pattern(n,(i-1))
print(print_pattern(4,3))
# def print_pattern(n,i):
# print('*'*(n+i-1))
# if i<-1: # when i < 0 is false it comes out of the loop if loop.
# return
# return print_pattern(n,(i-1))
# print(print_pattern(4,3)) | true |
d967fb081e40130cb7ed2a6aa64efa689838ca1d | iQaiserAbbas/Python | /13-Lists-Methods/exercise-04.py | 1,309 | 4.3125 | 4 | # Uncomment the commented lines of code below and complete the list comprehension logic
# The floats variable should store the floating point values
# for each string in the values list.
values = ["3.14", "9.99", "567.324", "5.678"]
floats = [float(value) for value in values]
print(floats)
# The letters variable should store a list of 5 strings.
# Each of the strings should be a character from name concatenated together 3 times.
# i.e. ['QQQ', 'aaa', 'iii', 'sss', 'eee', 'rrr']
name = "Qaiser"
letters = [letter*3 for letter in name]
print(letters)
# The 'lengths' list should store a list with the lengths
# of each string in the 'elements' list
elements = ["Hydrogen", "Helium", "Lithium", "Boron", "Carbon"]
lengths = [len(element) for element in elements]
print(lengths)
# Declare a destroy_elements function that accepts two lists.
# It should return a list of all elements from the first list that are NOT contained in the second list.
# Use list comprehension in your solution.
#
# EXAMPLES
# destroy_elements([1, 2, 3], [1, 2]) => [3]
# destroy_elements([1, 2, 3], [1, 2, 3]) => []
# destroy_elements([1, 2, 3], [4, 5]) => [1, 2, 3]
def destroy_elements(list1, list2):
return [number for number in list1 if number not in list2]
print(destroy_elements([1, 2, 3], [1, 2])) | true |
299d1c55adb8f77941ae9ef6c8f3fa8687f30640 | iQaiserAbbas/Python | /10-Lists-Iteration/exercise-03.py | 1,272 | 4.1875 | 4 | # Define an in_list function that accepts a list of strings and a separate string.
# Return the index where the string exists in the list.
# If the string does not exist, return -1.
# Do NOT use the find or index methods.
#
# EXAMPLES
# strings = ["enchanted", "sparks fly", "long live"]
# in_list(strings, "enchanted") ==> 0
# in_list(strings, "sparks fly") ==> 1
# in_list(strings, "fifteen") ==> -1
# in_list(strings, "love story") ==> -1
def in_list(strings, search):
for index, string in enumerate(strings):
if string == search:
return index
else:
return -1
strings = ["enchanted", "sparks fly", "long live"]
print(in_list(strings, "enchanted"))
print(in_list(strings, "sparks fly"))
print(in_list(strings, "love story"))
# Define a sum_of_values_and_indices function that accepts a list of numbers.
# It should return the sum of all of the elements along with their index values.
#
# EXAMPLES
# sum_of_values_and_indices([1, 2, 3]) => (1 + 0) + (2 + 1) + (3 + 2) => 9
# sum_of_values_and_indices([0, 0, 0, 0]) => 6
# sum_of_values_and_indices([]) => 0
def sum_of_values_and_indices(numbers):
total = 0
for index, number in enumerate(numbers, 0):
total = total + index + number
return total | true |
d07c700b2021065bc473da262507e6e880df20c6 | iQaiserAbbas/Python | /13-Lists-Methods/exercise-02.py | 1,153 | 4.34375 | 4 | # Define a word_lengths function that accepts a string.
# It should return a list with the lengths of each word.
#
# EXAMPLES
# word_lengths("Mary Poppins was a nanny") => [4, 7, 3, 1, 5]
# word_lengths("Somebody stole my donut") => [8, 5, 2, 5]
def word_lengths(string):
words = string.split(" ")
lengths = []
for word in words:
lengths.append(len(word))
return lengths
print(word_lengths("Mary Poppins was a nanny"))
# Define a cleanup function that accepts a list of strings.
# The function should return the strings joined together by a space.
# There's one BIG problem -- some of the strings are empty or only consist of spaces!
# These should NOT be included in the final string
#
# cleanup(["cat", "er", "pillar"]) => "cat er pillar"
# cleanup(["cat", " ", "er", "", "pillar"]) => "cat er pillar"
# cleanup(["", "", " "]) => ""
def cleanup(strings):
clean_strings = []
for string in strings:
if string.isspace() or len(string) == 0:
continue
clean_strings.append(string)
return " ".join(clean_strings)
print(cleanup(["cat", " ", "er", "", "pillar"])) | true |
59f76ac7d43b22b029585d3a8feb5014f619322f | lalitsaini85/first_mid | /average_n_number.py | 234 | 4.125 | 4 | # average at given number
n=int(input('enter the number ')) # how many numbers
s=0 #initialize variable
for i in range(1,n+1):
number=eval(input('enter the value '))
s += number
average_at_number=s/n
print(average_at_number) | false |
85d64b836c672bd61e419876eb010d0e264898a2 | ehsan4000/MITx-6.00.1x | /Quiz/Problem 5.py | 470 | 4.125 | 4 | def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
# Your Code Here
s=''
i=0
while (len(s1))>i and (len(s2))>i:
s+=s1[i]
s+=s2[i]
i+=1
if len(s1)<len(s2):
s+=s2[i:]
elif len(s1)>len(s2):
s+=s1[i:]
return s
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.