blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
9f3e5247a1c58d8c2e625138306b8422bc430afc
|
mayIlearnloopsbrother/Python
|
/chapters/chapter_6/ch6a.py
| 300
| 4.15625
| 4
|
#!/usr/bin/python3
#6-5 Rivers
rivers = {
'nile': 'egypt',
'mile': 'fgypt',
'oile': 'ggypt',
}
for river, country in rivers.items():
print(river + " runs through " + country)
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for country in rivers.values():
print(country)
| false
|
e65ff801f6792b85f1878d3520b994f2e9dfa682
|
Ernestbengula/python
|
/kim/Task3.py
| 269
| 4.25
| 4
|
# Given a number , check if its pos,Neg,Zero
num1 =float(input("Your Number"))
#Control structures -Making decision
#if, if else,elif
if num1>0:
print("positive")
elif num1==0 :
print("Zero")
elif num1<0:
print(" Negative")
else:
print("invalid")
| true
|
7737b93b5c93234ab9a28e8a3b6d3b23f740dd76
|
abhiranjan-singh/DevRepo
|
/calculater.py
| 383
| 4.1875
| 4
|
def mutiply(x, y):
return x*y
print(mutiply(int(input("enter the 1st number ")),int(input("Enter the second number "))))
#m = int(input("enter the 1stnumber "))
#n = int(input("enter the second number "))
# print(mutiply(input("enter the 1st number"),input("enter the second number")))
#print(mutiply(m, n))
#print('m' + '*' + 'n' + '=' + mutiply(m, n))print(mutiply(m, n))
| false
|
4359dd4f67584016be61c50548e51c8117ee2bc7
|
xpbupt/leetcode
|
/Medium/Complex_Number_Multiplication.py
| 1,043
| 4.15625
| 4
|
'''
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
'''
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
t_a = self.get_real_and_complex(a)
t_b = self.get_real_and_complex(b)
c = self.calculate(t_a, t_b)
return c[0] + '+' + c[1] +'i'
def get_real_and_complex(self, c):
a = c.split('+')[0]
b = c.split('+')[1].split('i')[0]
return (int(a), int(b))
def calculate(self, a, b):
return (str(a[0]*b[0] - a[1]*b[1]), str(a[0]*b[1] + a[1]*b[0]))
| true
|
509db82ab08a4667d0642c5f952301717c291fb9
|
patiregina89/Exercicios-Logistica_Algoritimos
|
/Condicao_Parada999.py
| 1,444
| 4.21875
| 4
|
print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Condição parada 999")
print(("*"*42))
'''
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai
parar quando o usuário digitar o valor de 999 (flag), que é a condição de parada. No
final mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag - 999)
'''
soma = 0
num_digitado = 0
while True:
num = int(input("Digite um número ou 999 para sair: "))
if num == 999:
break
soma = soma + num
num_digitado = num_digitado + 1
print("A soma dos números digitados é: ",soma)
print("A quantidade de números digitados é: ", num_digitado)
'''
Criei uma variável soma atribuida o valor de 0, pois pedem a soma dos valores digitados.
Também criei a variável num_digitado com valor atribuido de 0 pois, o exercicio quer saber quantos números foram digitados.
Usei o while true pois significa que enquanto a condição for verdadeira, o sistema irá se repetir. Então:
enquanto o número digitado for diferente de 999, ele vai repetir o pedido de digitar novo número.
Assim que o usuário digitar 999, o programa se encerra e ele informa a soma dos números digitados e a quantidade de números digitados.
'''
| false
|
a83d4a66c989c107a57dadf4dcfb8e597e14a107
|
CoCode2018/Refresher
|
/Python/笨办法学Python3/Exercise 18.py
| 1,416
| 4.71875
| 5
|
"""
Exercise 18: Names, Variables, Code, Functions
1.Every programmer will go on and on about functions
introduce
vt.介绍;引进;提出;作为…的
about to
即将,正要,刚要;欲
explanation
n.解释;说明;辩解;(消除误会后)和解
tiny
adj.极小的,微小的
n.小孩子;[医]癣
related
adj.有关系的;叙述的
vt.叙述(relate过去式和过去分词)
break down
失败;划分(以便分析);损坏;衰弱下来
except that
n.除了…之外,只可惜
asterisk
n.星号,星状物
vt.加星号于
parameter
n.[数]参数;<物><数>参量;限制因素;决定因素
indenting
n.成穴的
v.切割…使呈锯齿状( indent的现在分词 );缩进排版
colon
n.冒号;<解>结肠;科郎(哥斯达黎加货币单位
right away
就;立刻,马上;当时
"""
# this one if like your scripts with argv
def print_two(*args):
arg1, arg2, arg3 = args
print(F"arg1: {arg1}\narg2: {arg2}\narg3: {arg3}\nargs: {args}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(F"arg1: {arg1}\narg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(F"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed", "Shaw", "ZhouGua")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
| false
|
edace158002f255b7bbfd8d5708575912ab065d9
|
Varsha1230/python-programs
|
/ch4_list_and_tuples/ch4_lists_and_tuples.py
| 352
| 4.1875
| 4
|
#create a list using[]---------------------------
a=[1,2,4,56,6]
#print the list using print() function-----------
print(a)
#Access using index using a[0], a[1], a[2]
print(a[2])
#change the value of list using------------------------
a[0]=98
print(a)
#we can also create a list with items of diff. data types
c=[45, "Harry", False, 6.9]
print(c)
| true
|
c43b35b690a329f582683f9b406a66c826e5cabf
|
Varsha1230/python-programs
|
/ch3_strings/ch3_prob_01.py
| 435
| 4.3125
| 4
|
#display a user entered name followed by Good Afternoon using input() function--------------
greeting="Good Afternoon,"
a=input("enter a name to whom you want to wish:")
print(greeting+a)
# second way------------------------------------------------
name=input("enter your name:")
print("Good Afternoon," +name)
#-----------------------------------------------------
name=input("enter your name:\n")
print("Good Afternoon," +name)
| true
|
5b3ef497693bc27e3d5fee58a9a77867b8f18811
|
Varsha1230/python-programs
|
/ch11_inheritance.py/ch11_1_inheritance.py
| 731
| 4.125
| 4
|
class Employee: #parent/base class
company = "Google"
def showDetails(self):
print("this is an employee")
class Programmer(Employee): #child/derived class
language = "python"
# company = "YouTube"
def getLanguage(self):
print("the language is {self.language}")
def showDetails(self): #overwrite showDetails()-fn of class "Employee"
print("this is an programmer")
e = Employee() # object-creation
e.showDetails() # fn-call by using object of class employee
p = Programmer() # object-creation
p.showDetails() # fn-call by using object of class programmer
print(p.company) # using claas-employee's attribute by using the object of class programmer
| true
|
1c424c81442732b5b5c2d7616919ac81bc4dfcd2
|
mittgaurav/Pietone
|
/power_a_to_b.py
| 637
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 13:57:40 2019
@author: gaurav
cache half power results. O(log n)
"""
def power(a, b):
"""power without pow() under O(b)"""
print("getting power of", a, "for", b)
if a == 0:
return 0
if b == 1:
return a
elif b == 0:
return 1
elif b < 0:
return 1 / power(a, -b)
else: # positive >1 integer
half_res = power(a, b // 2)
ret = half_res * half_res
if b % 2: # odd power
ret *= a
return ret
for A, B in [(4, 5), (2, 3), (2, -6), (12, 4)]:
print(A, B, ":", pow(A, B), power(A, B))
| false
|
e0e4e39fd90e6e7bb8024ff3636229043ae63b40
|
eddylongshanks/repl-code
|
/Week 1 Example Code/_week1-program.py
| 1,984
| 4.125
| 4
|
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __str__(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "User(name, age)"
# Inherit from User
class Admin(User):
def details(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
# __str__ will return this line when calling the class. eg: print(user1)
def __str__(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "Admin(User)"
class Users:
def __init__(self):
self.users = []
def AddUser(self, user):
# Check for the type of the object to determine admin status
if user is type(Admin):
user = Admin(user.name, user.age)
elif user is type(User):
user = User(user.name, user.age)
self.users.append(user)
def GetUsers(self):
print("There are {0} users\n".format(str(len(self.users))))
for user in self.users:
print(user.details())
def __str__(self):
return "There are {0} users\n".format(str(len(self.users)))
def __repr__(self):
return "Users()"
users = Users()
numberOfUsers = int(input("How many users do you want to add?: "))
userCount = 1
while userCount <= numberOfUsers:
name = input("What is the name of user " + str(userCount) + "?: ")
age = input("What is the age of user " + str(userCount) + "?: ")
# Create a new user with the accepted information
currentUser = User(name, age)
# Add new user to the list
users.AddUser(currentUser)
userCount += 1
# Create an admin user and add to the list
admin = Admin("Chris", 30)
users.AddUser(admin)
# List the current users
users.GetUsers()
| false
|
c25ee297552465456ca50c12ce5df934c9d399bf
|
IsaacMarovitz/ComputerSciencePython
|
/MontyHall.py
| 2,224
| 4.28125
| 4
|
# Python Homework 11/01/20
# In the Monty Hall Problem it is benefical to switch your choice
# This is because, if you switch, you have a rougly 2/3 chance of
# Choosing a door, becuase you know for sure that one of the doors is
# The wrong one, otherwise if you didnt switch you would still have the
# same 1/3 chance you had when you made your inital guess
# On my honour, I have neither given nor received unauthorised aid
# Isaac Marovitz
import random
num_simulations = 5000
no_of_wins_no_switching = 0
no_of_wins_switching = 0
# Runs Monty Hall simulation
def run_sim(switching):
games_won = 0
for _ in range(num_simulations):
# Declare an array of three doors each with a tuple as follows (Has the car, has been selected)
doors = [(False, False), (False, False), (False, False)]
# Get the guess of the user by choosing at random one of the doors
guess = random.randint(0, 2)
# Select a door at random to put the car behind
door_with_car_index = random.randint(0, 2)
# Change the tuple of that door to add the car
doors[door_with_car_index] = (True, False)
# Open the door the user didn't chose that doesn't have the car behind it
for x in range(2):
if x != door_with_car_index and x != guess:
doors[x] = (False, True)
# If switching, get the other door that hasn't been revealed at open it, otherwise check if
# the current door is the correct one
if switching:
for x in range(2):
if x != guess and doors[x][1] != True:
games_won += 1
else:
if guess == door_with_car_index:
games_won += 1
return games_won
# Run sim without switching for first run
no_of_wins_no_switching = run_sim(False)
# Run sim with switching for the next run
no_of_wins_switching = run_sim(True)
print(f"Ran {num_simulations} Simulations")
print(f"Won games with switching: {no_of_wins_switching} ({round((no_of_wins_switching / num_simulations) * 100)}%)")
print(f"Won games without switching: {no_of_wins_no_switching} ({round((no_of_wins_no_switching / num_simulations) * 100)}%)")
| true
|
155a6195c974de35a6de43dffe7f1d2065d40787
|
IsaacMarovitz/ComputerSciencePython
|
/Conversation2.py
| 1,358
| 4.15625
| 4
|
# Python Homework 09/09/2020
# Inital grade 2/2
# Inital file Conversation.py
# Modified version after inital submisions, with error handeling and datetime year
# Importing the datetime module so that the value for the year later in the program isn't hardcoded
import datetime
def userAge():
global user_age
user_age = int(input("How old are you? (Please only input numbers) "))
print("\nHey there!", end=" ")
user_name = input("What's your name? ")
print("Nice to meet you " + user_name)
user_age_input_recieved = False
while (user_age_input_recieved == False):
try:
userAge()
user_age_input_recieved = True
except ValueError:
print("Invalid Input")
user_age_input_recieved = False
# I got this datetime solution from StackOverflow
# https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu
print("So, you were born in " + str((datetime.datetime.now().year-user_age)) + "!")
user_colour = input("What's your favourite colour? ")
if user_colour.lower() == "blue":
print("Hey, my favourite is blue too!")
else:
print(user_colour.lower().capitalize() +
"'s a pretty colour! But my favourite is blue")
print("Goodbye!")
input("Press ENTER to exit")
# On my honor, I have neither given nor received unauthorized aid
# Isaac Marovitz
| true
|
774ce49dd157eca63ab05d74c0d542dd33b4f14a
|
Nyame-Wolf/snippets_solution
|
/codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py
| 629
| 4.5
| 4
|
Summation
Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer
greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
tests
test.describe('Summation')
test.it('Should return the correct total')
test.assert_equals(summation(1), 1)
test.assert_equals(summation(8), 36)
others solution:
def summation(num):
return (1+num) * num / 2
or
def summation(num):
return sum(range(1,num+1))
or
def summation(num):
if num > 1:
return num + summation(num - 1)
return 1
| true
|
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f
|
DanielOram/simple-python-functions
|
/blueberry.py
| 2,627
| 4.625
| 5
|
#Author: Daniel Oram
#Code club Manurewa intermediate
#This line stores all the words typed from keyboard when you press enter
myString = raw_input()
#Lets print out myString so that we can see proof of our awesome typing skills!
#Try typing myString between the brackets of print() below
print()
#With our string we want to make sure that the first letter of each word is a capital letter
#Try editing myString by calling .title() at the end of myString below - This Will Capitalise Every Word In Our String
myCapitalString = myString
print("My Capitalised String looks like \"" + myCapitalString + "\"")
#Now we want to reverse myString so that it looks backwards!
#Try reversing myString by putting .join(reversed(myCapitalString)) after the empty string below - it will look like this -> ''.join(reversed(myCapitalString))
myBackwardsString = ''
#Lets see how we did!
print(myBackwardsString)
#Whoa that looks weird!
#Lets reverse our string back so that it looks like normal!
#Can you do that just like we did before?
myForwardString = '' #remember to use myBackwardsString instead of myCapitalString !
print("My backwards string = " + "\"" + myBackwardsString + "\"")
#Ok phew! we should be back to normal
#Lets try reverse our string again but this time we want to reverse the word order! NOT the letter order!
#To do this we need to find a way to split our string up into the individual words
#Try adding .split() to the end of myForwardString kind of like we did before
myListOfWords = ["We", "want", "our", "String", "to", "look", "like", "this!"] #replace the [...] with something that looks like line 27!
#Now lets reverse our List so that the words are in reverse order!
myBackwardsListOfWords = reversed(["Replace","this", "list", "with", "the", "correct", "list"]) #put myListOfWords here
#Before we can print it out we must convert our list of words back into a string!
#Our string was split into several different strings and now we need to join them back together
#HINT: we want to use the .join() function that we used earlier but this time we just want to put our list of words inside the brackets and
# NOT reversed(myBackwardsListOfWords) inside of the brackets!
myJoinedString = ''.join(["Replace", "me", "with", "the", "right", "list!"]) # replace the [...] with the right variable!
print(myJoinedString)
#Hmmm our list is now in reverse.. but it's hard to read!
#Go back and fix our issue by adding a space between the '' above. That will add a space character between every word in our list when it joins it together!
#Nice job! You've finished blueberry.py
| true
|
15cc2f889516a57be1129b8cad373084222f2c30
|
viniciuschiele/solvedit
|
/strings/is_permutation.py
| 719
| 4.125
| 4
|
"""
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Question:
Given two strings, write a method to decide if one is a permutation of the other.
"""
from unittest import TestCase
def is_permutation(s1, s2):
if not s1 or not s2:
return False
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
class Test(TestCase):
def test_valid_permutation(self):
self.assertTrue(is_permutation('abc', 'cab'))
self.assertTrue(is_permutation('159', '915'))
def test_invalid_permutation(self):
self.assertFalse(is_permutation('abc', 'def'))
self.assertFalse(is_permutation('123', '124'))
| true
|
9332ac35cb63d27f65404bb86dfc6370c919c2be
|
viniciuschiele/solvedit
|
/strings/is_permutation_of_palindrome.py
| 1,117
| 4.125
| 4
|
"""
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Palindrome is a word or phrase that is the same forwards and backwards.
A string to be a permutation of palindrome, each char must have an even count
and at most one char can have an odd count.
Question:
Given a string, write a function to check if it is a permutation of a palindrome.
"""
from unittest import TestCase
def is_permutation_of_palindrome(s):
counter = [0] * 256
count_odd = 0
for c in s:
char_code = ord(c)
counter[char_code] += 1
if counter[char_code] % 2 == 1:
count_odd += 1
else:
count_odd -= 1
return count_odd <= 1
class Test(TestCase):
def test_valid_permutation_of_palindrome(self):
self.assertTrue(is_permutation_of_palindrome('pali pali'))
self.assertTrue(is_permutation_of_palindrome('abc111cba'))
def test_non_permutation_of_palindrome(self):
self.assertFalse(is_permutation_of_palindrome('pali'))
self.assertFalse(is_permutation_of_palindrome('abc1112cba'))
| true
|
67fe9255295af578c9721b7847299ebe185cf5b8
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Personal_programs/Input_E_rapprString.py
| 676
| 4.34375
| 4
|
# La funzione input(...) restituisce un tipo stringa, anche se viene passato un numero int o float
# Puoi rappresentare una stringa concatenata in diversi modi:
# 1- Concatenandola con + e convertendo i numeri con str() ----> 'numero: ' + str(3.6)
# 2- Utilizzando la virgola( , ) come separatore tra stringhe e numeri o altre stringhe: 'numero' , ':' , 5
# 3- Mediante Formatted-String Literal ----> f"Il numero è { 5 }"
print('numero: ' + str(3.6))
print('numero', ':', 5)
print(f"Il numero è { 5 }")
print(f"numero uno: { 10 }, numero2: { 22 }, loro somma: { 10 + 22 } \n")
prova = input('Inserisci qualcosa: \n')
print(f"Hai inserito '{ prova }', complimenti!'")
| false
|
7de1ba91ebbb95ade3f54e652560b2c65369b1e3
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s8_center_method.py
| 720
| 4.25
| 4
|
# The one-parameter variant of the center() method makes a copy of the original string,
# trying to center it inside a field of a specified width.
# The centering is actually done by adding some spaces before and after the string.
# Demonstrating the center() method
print('[' + 'alpha'.center(10) + ']')
print('[' + 'Beta'.center(2) + ']')
print('[' + 'Beta'.center(4) + ']')
print('[' + 'Beta'.center(6) + ']')
# The two-parameter variant of center() makes use of the character from the second argument,
# instead of a space. Analyze the example below:
print('[' + 'gamma'.center(20, '*') + ']')
s1 = "Pasquale".center(30)
print(s1)
print("length:", len(s1))
s2 = "Pasquale Silvestre".center(50, "-")
print(s2)
print(len(s2))
| true
|
27598f79de97818823527e23f3969c27959f8702
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s15_split.py
| 617
| 4.46875
| 4
|
# The
# split()
# method does what it says - it splits the string and builds a list of all detected substrings.
# The method assumes that the substrings are delimited by whitespaces - the spaces don't take part in the operation,
# and aren't copied into the resulting list.
# If the string is empty, the resulting list is empty too.
# Demonstrating the split() method
print("phi chi\npsi".split())
# Note: the reverse operation can be performed by the join() method.
print("-------------------------")
# Demonstrating the startswith() method
print("omega".startswith("meg"))
print("omega".startswith("om"))
| true
|
0c10af8575d97394bbcb9c2363a82fe424df2bd0
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/integers_octal_exadecimal.py
| 1,053
| 4.53125
| 5
|
# If an integer number is preceded by an 0O or 0o prefix (zero-o),
# it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only.
# 0o123 is an octal number with a (decimal) value equal to 83.
print(0o123)
# The second convention allows us to use hexadecimal numbers.
# Such numbers should be preceded by the prefix 0x or 0X (zero-x).
# 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can manage these values too.
print(0x123)
print(4 == 4.0)
print(.4)
print(4.)
# On the other hand, it's not only points that make a float. You can also use the letter e.
# When you want to use any numbers that are very large or very small, you can use scientific notation.
print(3e8)
print(3E8)
# The letter E (you can also use the lower-case letter e - it comes from the word exponent)
# is a concise record of the phrase times ten to the power of.
print("----------------------------------------------------------")
print(0.0000000000000000000001)
print(1e-22)
| true
|
fd80e5cecb0c723cf52c16e6b112648476b37388
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Nested_Functions/NestedFunc1.py
| 548
| 4.1875
| 4
|
# Define three_shouts
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1), inner(word2), inner(word3))
# Call three_shouts() and print
print(three_shouts('a', 'b', 'c'))
print()
tupla_prova = three_shouts('Pasquale', 'Ignazio', 'Laura')
print(tupla_prova)
var1, var2, var3 = tupla_prova
print(var1, var2, var3)
| true
|
15d42320cb2c5217991e7b6202330c9e5e5fa414
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s7.py
| 458
| 4.4375
| 4
|
# Demonstrating the capitalize() method
print('aBcD'.capitalize())
print("----------------------")
# The endswith() method checks if the given string ends with the specified argument and returns True or False,
# depending on the check result.
# Demonstrating the endswith() method
if "epsilon".endswith("on"):
print("yes")
else:
print("no")
t = "zeta"
print(t.endswith("a"))
print(t.endswith("A"))
print(t.endswith("et"))
print(t.endswith("eta"))
| true
|
a959f8c5d7ec65d50fea6f6ca640524a04e13501
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Regular_Expressions_in_Python/Positional_String_formatting/Positional_formatting1.py
| 812
| 4.15625
| 4
|
# positional formatting ------> .format()
wikipedia_article = 'In computer science, artificial intelligence (AI), sometimes called machine intelligence, ' \
'is intelligence demonstrated by machines, ' \
'in contrast to the natural intelligence displayed by humans and animals.'
my_list = []
# Assign the substrings to the variables
first_pos = wikipedia_article[3:19].lower()
second_pos = wikipedia_article[21:44].lower()
# Define string with placeholders
my_list.append("The tool '{}' is used in '{}'")
# Define string with rearranged placeholders
my_list.append("The tool '{1}' is used in '{0}'") # That's why it's called 'POSITIONAL FORMATTING'
# Use format to print strings
for my_string in my_list:
print(my_string.format(first_pos, second_pos))
| true
|
968bee9c854610fd5799d875dae04d4227c74cfe
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Functions and packages/PackagesInPython/MathPackageInPython.py
| 653
| 4.34375
| 4
|
"""
As a data scientist, some notions of geometry never hurt. Let's refresh some of the basics.
For a fancy clustering algorithm,
you want to find the circumference, C, and area, A, of a circle.
When the radius of the circle is r, you can calculate C and A as:
C=2πr
A=πr**2
To use the constant pi, you'll need the math package.
"""
# Import the math package
import math
# Definition of radius
r = 0.43
# Calculate C
C = 2*r*math.pi
# Calculate A
A = math.pi*r**2
# Build printout
print("Circumference: " + str(C))
print("Area: " + str(A))
print()
print(math.pi)
print("PiGreco dal package math = " + str(math.pi))
| true
|
100d7f48a899c20b52ee5479eccd7422a87aa667
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Python_Lists/Python_Lists11.py
| 707
| 4.125
| 4
|
# you can also remove elements from your list. You can do this with the del statement:
# Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change!
x = ["a", "b", "c", "d"]
print(x)
del(x[1]) # del statement
print(x)
areas = ["hallway", 11.25, "kitchen", 18.0,
"chill zone", 20.0, "bedroom", 10.75,
"bathroom", 10.50, "poolhouse", 24.5,
"garage", 15.45]
print(areas)
del(areas[-4:-2])
print(areas)
"""
The ; sign is used to place commands on the same line. The following two code chunks are equivalent:
# Same line
command1; command2
# Separate lines
command1
command2
"""
| true
|
1ff840fef8bc267fcf37268800d9bd29dd86f521
|
Pasquale-Silv/Improving_Python
|
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py
| 462
| 4.34375
| 4
|
# [ LIST COMPREHENSION ]
# ( GENERATOR )
# Recall that generator expressions basically have the same syntax as list comprehensions,
# except that it uses parentheses () instead of brackets []
# Create generator object: result
result = (num for num in range(31))
# Print the first 5 values
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
# Print the rest of the values
for value in result:
print(value)
| true
|
6ab7b8b1135b74d6572efd98bb64f86f85e468ce
|
ryanmp/project_euler
|
/p076.py
| 1,263
| 4.15625
| 4
|
''' counting sums
explanation via example:
n == 5:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
if sum == 5 -> there are 6 different combos
'''
def main():
return 0
# how many different ways can a given number be written as a sum?
# note: combinations, not permutations
def count_sum_reps(n):
''' my gut tells me that this can be formulated as a math problem...
let's first see if we can detect the pattern:
1 -> 1
2 -> 1
3 -> 1+2,
1+1+1: 2
4 -> 1+3,
2+2,2+1+1,
1+1+1+1: 4
5 -> 6
6 -> 5+1,
4+2, 4+1+1,
3+3, 3+2+1, 3+1+1+1,
2+2+2, 2+2+1+1, 2+1+1+1+1,
1+1+1+1+1+1 : 10
7 -> 6+1
5+2 5+1+1
4+3 4+2+1 4+1+1+1
3+3+1 3+2+2 3+2+1+1 3+1+1+1+1
2+2+2+1 2+2+1+1+1 2+1+1+1+1+1
(7x)+1
: 14
8 -> 7+1
6+2 6+1+1
5 = "3"
4 = "4"
3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+(5x)+1 "5"
2+2+2+2 ... "4"
"1"
: 19
9 ->
yikes, I'm seeing the emergence of a pattern, n-1 rows. growing by +1
descending.. until it reaches the corner,
but i would need to do several more in order to see the pattern on the bottom
rows (after the corner), assuming there is a pattern
'''
return 'not finished yet'
if __name__ == '__main__':
import boilerplate, time
boilerplate.all(time.time(),main())
| true
|
240066b054c327e6a05ab214ce54466ba9b39d6f
|
gonzrubio/HackerRank-
|
/InterviewPracticeKit/Dictionaries_and_Hashmaps/Sherlock_and_Anagrams.py
| 992
| 4.15625
| 4
|
"""Given a string s, find the number of pairs of substrings of s that are anagrams of each other.
1<=q<=10 - Number of queries to analyze.
2<=|s|<=100 - Length of string.
s in ascii[a-z]
"""
def sherlockAndAnagrams(s):
"""Return the number (int) of anagramatic pairs.
s (list) - input string
"""
n = len(s)
anagrams = dict()
for start in range(n):
for end in range(start,n):
substring = ''.join(sorted(s[start:end+1]))
anagrams[substring] = anagrams.get(substring,0) + 1
count = 0
for substring in anagrams:
freq = anagrams[substring]
count += freq*(freq-1) // 2
return count
def main():
#tests = ['abba','abcd','ifailuhkqq','kkkk']
#for test in tests: # 1<=q<=10
for _ in range(int(input())): # 1<=q<=10
print(sherlockAndAnagrams(input())) # 2<=|s|<=100
if __name__ == '__main__':
main()
| true
|
d38f462e41e1f2fd0e9f07623bca3fc6a5619272
|
mikaelgba/PythonDSA
|
/cap5/Metodos.py
| 1,411
| 4.25
| 4
|
class Circulo():
# pi é um varialvel global da classe
pi = 3.14
# com raio = 'x valor' toda vez que criar um objeto Circulo ele automaticamnete já concidera que o raio será 'x valor'
#mas se colocar um outro valor ele vai sobreescrever o 'x valor'
def __init__( self, raio = 3 ):
self.raio = raio
def area( self ):
return ((self.raio * self.raio) * Circulo.pi)
def getRaio( self ):
return self.raio
def setRaio( self, novo_circulo ):
self.raio = novo_circulo
circulo = Circulo(4)
print(circulo.getRaio(),"\n")
print(circulo.area(),"\n")
circulo.setRaio(7)
print(circulo.area(),"\n")
#Classe quadrado
class Quadrado():
def __init__( self, altura, largura ):
self.altura = altura
self.largura = largura
def area( self ):
return ( self.altura * self.largura )
def getAltura( self ):
return self.altura
def setAltura( self, nova_altura ):
self.altura = nova_altura
def getLargura( self ):
return self.largura
def setLargura( self, nova_largura ):
self.largura = nova_largura
quad = Quadrado(2,2)
print("Altura:",quad.getAltura(),"Largura:", quad.getLargura(),"\n")
print(quad.area(),"\n")
quad.setAltura(4)
print(quad.getAltura(),"\n")
quad.setLargura(4)
print(quad.getLargura(),"\n")
print(quad.area(),"\n")
| false
|
5a9c5719e053d265dd173e766008bc33118b6dae
|
peterzhou84/datastructure
|
/samples/python/array.py
| 1,542
| 4.4375
| 4
|
#coding=utf-8
#!/usr/bin/python3
'''
展示在Python中,如何操作数组
'''
#################################################
### 一维数组 http://www.runoob.com/python3/python3-list.html
squares = [1, 4, 9, 16, 25, 36]
print("打印原数组:")
print(squares)
'''
Python的编号可以为正负
+---+---+---+---+---+---+
| 1 | 4 | 9 | 16| 25| 36|
+---+---+---+---+---+---+
0 1 2 3 4 5 从第一个开始编号为0
-6 -5 -4 -3 -2 -1 从最后一个开始,编号为-1
'''
## 找到特定下标的元素
print("打印下标为4的元素:")
print(squares[4]) # 从第一个开始数,指向25
print("打印下标为-2的元素:")
print(squares[-2]) # 从最后一个开始数,指向25
## 找到特定下标范围的元素
print("打印下标为2(包含)到4(不包含)之间的所有元素:")
print(squares[2:4])
print("打印下标从4开始(包含)到数组最后的所有元素:")
print(squares[4:])
print("打印第一个元素到第-2(不含)的元素:")
print(squares[:-2])
## 设置数组元素的值
print("下标为2的元素乘以10:")
squares[2] *= 10
print(squares)
## 删除数组里面的元素
print("删除下标为4的元素")
del squares[4]
print(squares)
#################################################
### 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,列表使用方括号。
tup1 = ('Google', 'Runoob', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
| false
|
d1d844be30625c6e2038e0596b19c05cf9a489fa
|
DarioBernardo/hackerrank_exercises
|
/recursion/num_decodings.py
| 2,241
| 4.28125
| 4
|
"""
HARD
https://leetcode.com/problems/decode-ways/submissions/
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with 0.
The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
Hence, there are no valid ways to decode this since all digits need to be mapped.
Example 4:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
"""
from functools import lru_cache
def num_decodings(s: str):
@lru_cache(maxsize=None) # This automatically implement memoisation
def recursive(s: str, index=0):
if index == len(s):
return 1
# If the string starts with a zero, it can't be decoded
if s[index] == '0':
return 0
if index == len(s) - 1:
return 1
answer = recursive(s, index + 1)
if int(s[index: index + 2]) <= 26:
answer += recursive(s, index + 2)
return answer
return recursive(s, 0)
din = [
"234",
"2101",
"1201234"
]
dout = [
2,
1,
3
]
for data_in, expected_result in zip(din, dout):
actual_result = num_decodings(data_in)
print(f"Expected: {expected_result} Actual: {actual_result}")
assert expected_result == actual_result
| true
|
5d792080e230b43aa25835367606510d0bb63af7
|
feynmanliang/Monte-Carlo-Pi
|
/MonteCarloPi.py
| 1,197
| 4.21875
| 4
|
# MonteCarloPi.py
# November 15, 2011
# By: Feynman Liang <feynman.liang@gmail.com>
from random import random
def main():
printIntro()
n = getInput()
pi = simulate(n)
printResults(pi, n)
def printIntro():
print "This program will use Monte Carlo techniques to generate an"
print "experimental value for Pi. A circle of radius 1 will be"
print "inscribed in a square with side length 2. Random points"
print "will be selected. Since Pi is the constant of proportionality"
print "between a square and its inscribed circle, Pi should be"
print "equal to 2*2*(points inside circle/points total)"
def getInput():
n = input("Enter number of trials: ")
return n
def simulate(n):
hit = 0
for i in range(n):
result = simulateOne()
if result == 1:
hit = hit + 1
pi = 4 * float(hit) / n
return pi
def simulateOne():
x = genCoord()
y = genCoord()
distance = x*x + y*y
if distance <= 1:
return 1
else:
return 0
def genCoord():
coord = 2*random()-1
return coord
def printResults(pi, n):
print "After", n, "simulations, pi was calculated to be: ", pi
if __name__ == "__main__": main()
| true
|
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27
|
revanth465/Algorithms
|
/Searching Algorithms.py
| 1,403
| 4.21875
| 4
|
# Linear Search | Time Complexity : O(n)
import random
def linearSearch(numbers, find):
for i in numbers:
if(i==find):
return "Found"
return "Not Found"
numbers = [1,3,5,23,5,23,34,5,63]
find = 23
print(linearSearch(numbers,find))
# Insertion Sort | Time Complexity : O(N^2)
def insertionSort(numbers):
i = 2
while(i <= len(numbers)):
j = i-1
while( j > 0 ):
if(numbers[j] < numbers[j-1]):
temp = numbers[j-1]
numbers[j-1] = numbers[j]
numbers[j] = temp
j -= 1
else:
break
i += 1
return numbers
# Binary Search | Time Complexity : O(logN) | With Insertion Sort : O(N^2)
def binarySearch():
# Let's build a list of random numbers and a random value to find in the list.
numbers = [random.randint(1,21) for i in range(10)]
find = random.randint(1,21)
numbers = insertionSort(numbers)
low = 0
high = len(numbers) -1
while(low <= high):
middle = (low + high) /2
if(numbers[middle] == find):
return "Number Found"
elif(find < numbers[middle]):
high = middle - 1
else:
low = middle + 1
return "Number Not Found"
print(binarySearch())
| true
|
e9c965347e640a3dc9c568f854d7840faa5ff31a
|
OlegZhdanoff/python_basic_07_04_20
|
/lesson_2_2.py
| 809
| 4.21875
| 4
|
"""
2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами
0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка
элементов необходимо использовать функцию input().
"""
my_list = []
el = 1
i = 0
while el:
el = input('Введите элемент списка\n')
if el:
my_list.append(el)
print('Ваш список: ', my_list)
while i < len(my_list)-1:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
i += 2
print('Результат: ', my_list)
| false
|
6c82627929fa81cdd0998309ec049b8ef4d7bc86
|
Helen-Sk-2020/JtBr_Arithmetic_Exam_Application
|
/Arithmetic Exam Application/task/arithmetic.py
| 2,032
| 4.125
| 4
|
import random
import math
def check_input():
while True:
print('''Which level do you want? Enter a number:
1 - simple operations with numbers 2-9
2 - integral squares of 11-29''')
x = int(input())
if x == 1 or x == 2:
return x
break
else:
print('Incorrect format.')
def check_answer(answer):
while True:
x = input()
if x.strip('-').isdigit():
if int(x) == answer:
print('Right!')
return 'Right!'
else:
print('Wrong!')
break
else:
print('Incorrect format.')
def simple_operations():
total = 0
a = random.randint(2, 9)
b = random.randint(2, 9)
operator = random.choice('+-*')
print(f"{a} {operator} {b}")
if operator == "+":
total = int(a) + int(b)
elif operator == "-":
total = int(a) - int(b)
elif operator == "*":
total = int(a) * int(b)
return total
def integral_squares():
num = random.randint(11, 29)
print(num)
square = math.pow(num, 2)
return square
def save_result(level, n):
print("What is your name?")
name = input()
if level == 1:
level_description = 'simple operations with numbers 2-9'
elif level == 2:
level_description = 'integral squares of 11-29'
results = open('results.txt', 'a', encoding='utf-8')
results.write(f'{name}: {n}/5 in level {level} ({level_description})')
results.close()
print('The results are saved in "results.txt".')
level = check_input()
counter = n = 0
while counter < 5:
if level == 1:
result = simple_operations()
elif level == 2:
result = integral_squares()
if check_answer(result) == 'Right!':
n += 1
counter += 1
print(f"Your mark is {n}/5. Would you like to save the result?")
user_answer = str(input())
if user_answer.lower() == 'yes' or user_answer == 'y':
save_result(level, n)
| true
|
b513eaa39db2de8aab8d3e3b99d2d4f342d26b14
|
Gi-lab/Mathematica-Python
|
/07-Mate.py
| 351
| 4.3125
| 4
|
lista_numeros = []
quantidade = int(input('Quantos numeros voce deseja inserir? '))
while len(lista_numeros) + 1 <= quantidade:
numero = int(input('Digite um numero '))
lista_numeros.append(numero)
maior_numero = max(lista_numeros)
print(f'O maior número da lista é {maior_numero}')
input('Digite uma tecla para fechar o programa')
| false
|
0a6b38b73eea3f054edadbf5dc5f08ee4c524cb1
|
Jrjh27CS/Python-Samples
|
/practice-python-web/fibonacci.py
| 690
| 4.21875
| 4
|
#Challenge given by https://www.practicepython.org
#Jordan Jones Apr 16, 2019
#Challenge: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the number of numbers in the sequence to generate.
def fib(x):
z = []
if x == 0:
return z
z.append(0)
if x == 1:
return z
z.append(1)
if x == 2:
return z
while len(z) != x:
z.append(z[len(z)-1] + z[len(z)-2])
return z
num = int(input("How many fibonacci numbers would you like starting from 0? Num:"))
print(fib(num))
| true
|
dcbe36488dc453401fb81abd4a01dd2fe29bcbbf
|
moribello/engine5_honor_roll
|
/tools/split_names.py
| 1,231
| 4.375
| 4
|
# Python script to split full names into "Last Name", "First Name" format
#Note: this script will take a .csv file from the argument and create a new one with "_split" appended to the filename. The original file should have a single column labled "Full Name"
import pandas as pd
import sys
def import_list():
while True:
try:
listname1 = sys.argv[1]
list1 = pd.read_csv(listname1)
break
except:
print(listname1)
print("That doesn't appear to be a valid file. Please try again.")
break
return list1, listname1
def split_fullnames(df, listname):
# new data frame with split value columns
new = df["Full Name"].str.split(" ", n = 1, expand = True)
# making separate first and last name columns from new data frame
df["First Name"]= new[1]
df["Last Name"]= new[0]
df = df.drop(columns=['Full Name'])
new_filename = listname[:-4]
df.to_csv(new_filename+"_split.csv", index=False)
print("Spaces removed. Changes written to file {}_split.csv.".format(new_filename))
def main():
list1, listname1 = import_list()
split_fullnames(list1, listname1)
if __name__ == "__main__":
main()
| true
|
50d6496496531c365527290d9d12bcf4fb1f1c5f
|
DanilkaZanin/vsu_programming
|
/Time/Time.py
| 559
| 4.125
| 4
|
#Реализация класса Time (из 1 лекции этого года)
class Time:
def __init__(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def time_input(self):
self.hours = int(input('Hours: '))
self.minutes = int(input('Minutes: '))
self.seconds = int(input('Seconds: '))
def print_time(self):
print(f'{self.hours}:{self.minutes}:{self.seconds}')
time = Time(1 , 2 , 3)
time.time_input()
time.print_time()
| false
|
86773d8aa5d642f444192ecc1336560c86d718ca
|
siddu1998/sem6_labs
|
/Cloud Computing/Assignment 1/question9.py
| 218
| 4.40625
| 4
|
# Write a Python program to find whether a given number (accept from the user)
# is even or odd, print out an appropriate message to the user.
n=int(input("please enter the number"))
print("even" if n%2==0 else "odd")
| true
|
316aa2bdc7e255944d154ce075592a157274c9bc
|
Jeremyreiner/DI_Bootcamp
|
/week5/Day3/daily_challenges/daily_challenge.py
| 2,874
| 4.28125
| 4
|
# Instructions :
# The goal is to create a class that represents a simple circle.
# A Circle can be defined by either specifying the radius or the diameter.
# The user can query the circle for either its radius or diameter.
# Other abilities of a Circle instance:
# Compute the circle’s area
# Print the circle and get something nice
# Be able to add two circles together
# Be able to compare two circles to see which is bigger
# Be able to compare two circles and see if there are equal
# Be able to put them in a list and sort them
# ----------------------------------------------------------------
import math
class Circle:
def __init__(self, radius, ):
self.radius = radius
self.list = []
def area(self):
return self.radius ** 2 * math.pi
def perimeter(self):
return 2*self.radius*math.pi
def __le__(self, other):
if self.radius <= other.radius:
return True
else:
return False
def __add__(self, other):
if self.radius + other.radius:
return self.radius + other.radius
def add_circle(self):
for item in self.list:
if item not in self.list:
self.list.append(item)
def print_circle(self):
return print(self.list)
circle = Circle(50)
circle_2 = Circle(7)
print(circle.area())
Circle.add_circle(circle)
Circle.add_circle(circle_2)
print(Circle.print_circle(circle))
print(circle.perimeter())
print(circle.__le__(circle_2))
print(circle.__add__(circle_2))
# bigger_circle = n_circle.area + n_circle_2.area
# print(bigger_circle.area())
# !class Racecar():
# def __init__(self, model, reg_no, top_speed=0, nitros=False):
# self.model = model
# self.reg_no = reg_no
# self.top_speed = top_speed
# self.nitros = nitros
# if self.nitros:
# self.top_speed += 50
# def __str__(self):
# return self.model.capitalize()
# def __repr__(self):
# return f"This is a Racecar with registration: {self.reg_no}"
# def __call__(self):
# print(f"Vroom Vroom. The {self.model} Engines Started")
# def __gt__(self, other):
# if self.top_speed > other.top_speed:
# return True
# else:
# return False
# def drive(self, km):
# print(f"You drove the {self.model} {km} km in {km / self.top_speed} hours.")
# def race(self, other_car):
# if self > other_car:
# print(f"I am the winner")
# else:
# print(f"The {other_car.model} is the winner")
# class PrintList():
# def __init__(self, my_list):
# self.mylist = my_list
# def __repr__(self):
# return str(self.mylist)
# car1 = Racecar("honda", "hello", 75, True)
# car2 = Racecar("civic", "bingo", 55, True)
# print(car1.__gt__(car2))
| true
|
0cdc78355fca028bb19c771c343ae845b702f555
|
Jeremyreiner/DI_Bootcamp
|
/week5/Day1/Daily_challenge/daily_challenge.py
| 2,265
| 4.40625
| 4
|
# Instructions : Old MacDonald’s Farm
# Take a look at the following code and output!
# File: market.py
# Create the code that is needed to recreate the code provided above. Below are a few questions to assist you with your code:
# 1. Create a class called Farm. How should this be implemented?
# 2. Does the Farm class need an __init__ method? If so, what parameters should it take?
# 3. How many methods does the Farm class need?
# 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should this function have? How many…?
# 5. Test your code and make sure you get the same results as the example above.
# 6. Bonus: nicely line the text in columns as seen in the example above. Use string formatting.
class Farm():
def __init__(self, name):
self.name = name
self.animals = []
self.sorted_animals = []
def add_animal(self, animal, amount = ""):
if animal not in self.animals:
added_animal = f"{animal} : {str(amount)}"
self.animals.append(added_animal)
def show_animals(self):
# for animal in self.animals:
print(f"These animals are currently in {self.name}'s farm: {self.animals}")
# Expand The Farm
# Add a method called get_animal_types to the Farm class.
# This method should return a sorted list of all the animal types (names) in the farm.
# With the example above, the list should be: ['cow', 'goat', 'sheep'].
def get_animal_types(self):
if __name__ == '__main__':
sorted_by_name = sorted(self.animals, key=lambda x: x.animals)
print(sorted_by_name)
# Add another method to the Farm class called get_short_info.
# This method should return the following string: “McDonald’s farm has cows, goats and sheep.”.
# The method should call the get_animal_types function to get a list of the animals.
macdonald = Farm("McDonald")
macdonald.add_animal('cow', 5)
macdonald.add_animal('sheep')
macdonald.add_animal('sheep')
macdonald.add_animal('goat', 12)
macdonald.show_animals()
all_animals = macdonald.animals
macdonald.get_animal_types()
# print(macdonald.get_info())
# McDonald's farm
# cow : 5
# sheep : 2
# goat : 12
# E-I-E-I-0!
| true
|
44971d0672295eea12f2d5f3ad8dad4faea2c47f
|
Bawya1098/python-Beginner
|
/Day3/Day3_Assignments/hypen_separated_sequence.py
| 273
| 4.15625
| 4
|
word = str(input("words to be separated by hypen:"))
separated_word = word.split('-')
sorted_separated_word = ('-'.join(sorted(separated_word)))
print("word is: ", word)
print("separated_word is:", separated_word)
print("sorted_separated_word is: ", sorted_separated_word)
| true
|
8ea1a9399f7b7325159494391e648245e0e76179
|
Danielkaas94/Any-Colour-You-Like
|
/code/python/PythonApplication1.py
| 2,115
| 4.1875
| 4
|
def NameFunction():
name = input("What is your name? ")
print("Aloha mahalo " + name)
return name
def Sum_func():
print("Just Testing")
x = input("First: ")
y = input("Second: ")
sum = float(x) + float(y)
print("Sum: " + str(sum))
def Weight_func():
weight = int(input("Weight: "))
unit_option = input("(K)g or (L)bs:")
if unit_option.upper() == "K":
converted_value = weight / 0.45
print("Weight in Lbs:" + str(converted_value))
else:
converted_value = weight * 0.45
print("Weight in Kg:" + str(converted_value))
NameFunction(); print("")
Sum_func(); print("")
birth_year = input("Enter your birth year: ")
age = 2020 - int(birth_year)
print(age)
course = 'Python for Beginners'
print(course.upper())
print(course.find('for'))
print(course.replace('for', '4'))
print('Python' in course) #True
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
print(10 * 3) # 30
x = 10
x = x + 3
x += 3
x = 10 + 3 * 2
temperature = 35
if temperature > 30:
print("Hot night, in a cold town")
print("Drink infinite water")
elif temperature > 20:
print("It's a fine day")
elif temperature > 10:
print("It's a bit cold")
else:
print("It's cold")
print("LORT! ~ Snehaderen")
Weight_func(); print("")
i = 1
while i <= 1_1:
#print(i)
print(i * '*')
i += 1
names = ["Doktor Derp", "Jens Jensen", "John Smith", "Toni Bonde", "James Bond", "Isaac Clark", "DOOMGUY"]
print(names)
print(names[0])
print(names[-1]) # Last Element - DOOMGUY
print(names[0:3]) # ['Doktor Derp', 'Jens Jensen', 'John Smith']
numbers = [1,2,3,4,5]
numbers.append(6)
numbers.insert(0,-1)
numbers.remove(3)
#numbers.clear()
print(numbers)
print(1 in numbers)
print(len(numbers))
for item in numbers:
print(item)
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
#range_numbers = range(5)
#range_numbers = range(5, 10)
range_numbers = range(5, 10, 2)
print(range_numbers)
for number in range_numbers:
print(number)
for number in range(7,45,5):
print(number)
numbers2 = (1,2,3) #Tuple
| false
|
26b5cff2b5c9a9eca56befae9956bc895690c60e
|
sundusaijaz/pythonpractise
|
/calculator.py
| 681
| 4.125
| 4
|
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
op = input("Enter operator to perform operation: ")
if op == '+':
print("The sum of " + str(num1) + " and " + str(num2) + " = " +str(num1+num2))
elif op == '-':
print("The subtraction of " + str(num1) + " and " + str(num2) + " = " +str(num1-num2))
elif op == '*':
print("The multiplication of " + str(num1) + " and " + str(num2) + " = " +str(num1*num2))
elif op == '/':
print("The division of " + str(num1) + " and " + str(num2) + " = " +str(num1/num2))
elif op == '%':
print("The mod of " + str(num1) + " and " + str(num2) + " = " +str(num1%num2))
else:
print("Invalid Input")
| false
|
3da597b2bcdcdaf16bfa50bc86a060fa56173667
|
ND13/zelle_python
|
/chapter_2/futval.py
| 792
| 4.15625
| 4
|
#!/usr/bin/python3.6
# File: futval.py
# A program that computes an investment carried 10 years into future
# 2.8 Exercises: 5, 9
def main():
print("This program calculates the future value of a 10-year investment.")
principal = float(input("Enter the principal amount: "))
apr = float(input("Enter the annualized interest rate: "))
length = int(input("Enter the length in years of investment: "))
inflation = float(input("Enter yearly rate of inflation: "))
apr = apr * .01
inflation = inflation * .01
for i in range(length):
principal = principal * (1 + apr)
principal = principal / (1 + inflation)
year = i + 1
print(f"Year {year}: {principal:.2f}")
print(f"The amount in {length} years is: {principal:.2f}")
main()
| true
|
7482b65b788259f74c8719944618f9d856417780
|
ND13/zelle_python
|
/chapter_3/pizza.py
| 450
| 4.3125
| 4
|
# sphere_2.py
# calculates the price per square inch of circular pizza using price and diameter
def main():
price = float(input("Enter the price for your pizza: $"))
diameter = float(input("Enter the diameter of the pizza: "))
radius = diameter / 2
area = 3.14159 * radius ** 2
price_per_sq_inch = price / area
print(f"The price per square inch of pizza is ${price_per_sq_inch:.2f}")
if __name__ == '__main__':
main()
| true
|
f75081ff4aa02c2d226247c160a69e941149c980
|
zhaokaiju/fluent_python
|
/c07_closure_deco/p05_closure.py
| 728
| 4.34375
| 4
|
"""
闭包:
闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。
函数是不是匿名的没关系,关键是它能访问定义体之外定义的非全局变量。
"""
def make_averager():
"""
闭包
"""
# 局部变量(非全局变量)(自由变量)
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total / len(series)
return averager
def use_make_averager():
avg = make_averager()
print(avg(10))
print(avg(12))
# 输出结果:
"""
10.0
11.0
"""
if __name__ == '__main__':
use_make_averager()
| false
|
171042e8da302efa359e350feaf92915e9d33b8b
|
codeking-hub/Coding-Problems
|
/AlgoExpert/find3LargestNums.py
| 711
| 4.125
| 4
|
def findThreeLargestNumbers(array):
# Write your code here.
three_largest = [None, None, None]
for num in array:
updateThreeLargest(num, three_largest)
return three_largest
def updateThreeLargest(num, three_largest):
if three_largest[2] == None or num > three_largest[2]:
shiftValue(three_largest, num, 2)
elif three_largest[1] == None or num > three_largest[1]:
shiftValue(three_largest, num, 1)
elif three_largest[0] == None or num > three_largest[0]:
shiftValue(three_largest, num, 0)
def shiftValue(array, num, idx):
for i in range(idx + 1):
if i == idx:
array[i] = num
else:
array[i] = array[i+1]
| false
|
a9bbd74af9b343cf940c2a7eeb6de12dbcc4bdd9
|
ElenaPontecchiani/Python_Projects
|
/0-hello/12-calculatorV2.py
| 466
| 4.1875
| 4
|
n1 = float(input("First number: "))
n2 = float(input("Second number: "))
operator = input("Digit the operator: ")
def calculatorV2 (n1, n2, operator):
if operator == '+':
return n1+n2
elif operator == '-':
return n1-n2
elif operator == '*':
return n1*n2
elif operator == '/':
return n1/n2
else:
print("Error, operator not valid")
return 0
result = calculatorV2(n1, n2, operator)
print(result)
| false
|
def2e855860ded62733aa2ddcfe4b51029a8edd2
|
PSReyat/Python-Practice
|
/car_game.py
| 784
| 4.125
| 4
|
print("Available commands:\n1) help\n2) start\n3) stop\n4) quit\n")
command = input(">").lower()
started = False
while command != "quit":
if command == "help":
print("start - to start the car\nstop - to stop the car\nquit - to exit the program\n")
elif command == "start":
if started:
print("Car has already started.\n")
else:
started = True
print("Car has started.\n")
elif command == "stop":
if started:
started = False
print("Car has stopped.\n")
else:
print("Car has already stopped.\n")
else:
print("Input not recognised. Please enter 'help' for list of valid inputs.\n")
command = input(">").lower()
print("You have quit the program.")
| true
|
f6b50fb2c608e9990ed1e3870fd73e2039e17b3d
|
ananyo141/Python3
|
/uptoHundred.py
| 301
| 4.3125
| 4
|
#WAP to print any given no(less than 100) to 100
def uptoHundred(num):
'''(num)-->NoneType
Print from the given number upto 100. The given num should be less than equal to 100.
>>>uptoHundred(99)
>>>uptoHundred(1)
'''
while(num<=100):
print(num)
num+=1
| true
|
437c321c8a52c3ae13db3bfa5e48c7a5dac2c1eb
|
ananyo141/Python3
|
/gradeDistribution/functions.py
| 2,519
| 4.15625
| 4
|
# This function reads an opened file and returns a list of grades(float).
def findGrades(grades_file):
'''(file opened for reading)-->list of float
Return a list of grades from the grades_file according to the format.
'''
# Skip over the header.
lines=grades_file.readline()
grades_list=[]
while lines!='\n':
lines=grades_file.readline()
lines=grades_file.readline()
while lines!='':
# No need to .rstrip('\n') newline as float conversion removes it automatically.
grade=float(lines[lines.rfind(' ')+1:])
grades_list.append(grade)
lines=grades_file.readline()
return grades_list
# This function takes the list of grades and returns the distribution of students in that range.
def gradesDistribution(grades_list):
'''(list of float)-->list of int
Return a list of ints where each index indicates how many grades are in these ranges:
0-9: 0
10-19: 1
20-29: 2
:
90-99: 9
100 : 10
'''
ranges=[0]*11
for grade in grades_list:
which_index=int(grade//10)
ranges[which_index]+=1
return ranges
# This function writes the histogram of grades returned by distribution.
def writeHistogram(histogram,write_file):
'''(list of int,file opened for writing)-->NoneType
Write a histogram of '*'s based on the number of grades in the histogram list.
The output format:
0-9: *
10-19: **
20-29: ******
:
90-99: **
100: *
'''
write_file.write("0-9: ")
write_file.write('*' * histogram[0]+str(histogram[0]))
write_file.write('\n')
# Write the 2-digit ranges.
for i in range(1,10):
low = i*10
high = low+9
write_file.write(str(low)+'-'+str(high)+': ')
write_file.write('*'*histogram[i]+str(histogram[i]))
write_file.write('\n')
write_file.write("100: ")
write_file.write('*' * histogram[-1]+str(histogram[-1]))
write_file.write('\n')
write_file.close
# Self-derived algorithm, have bugs.(Not deleting for further analysis and possible debugging.)
# for i in range(0,100,9):
# write_file.write(str(i))
# write_file.write('-')
# write_file.write(str(i+9))
# write_file.write(':')
# write_file.write('*'*histogram[(i//10)])
# write_file.write(str(histogram[(i//10)]))
# write_file.write('\n')
# write_file.close()
| true
|
67613b888eaa088a69a0fec26f1ace376f95cbbb
|
ananyo141/Python3
|
/calListAvg.py
| 624
| 4.15625
| 4
|
# WAP to return a list of averages of values in each of inner list of grades.
# Subproblem: Find the average of a list of values
def calListAvg(grades):
'''(list of list of num)--list of num
Return the list of average of numbers from the list of lists of numbers in grades.
>>> calListAvg([[5,2,4,3],[4,6,7,8],[4,3,5,3,4,4],[4,35,3,45],[56,34,3,2,4],[5,3,56,6,7,6]])
[3.5, 6.25, 3.833, 21.75, 19.8, 13.833]
'''
avg_list=[]
for sublist in grades:
total=0
for grade in sublist:
total+=grade
avg_list.append(total/len(sublist))
return avg_list
| true
|
b7e98df96a4a263667a93d2ae87d397457cd0cb4
|
ananyo141/Python3
|
/addColor.py
| 362
| 4.1875
| 4
|
#WAP to input colors from user and add it to list
def addColor():
'''(NoneType)-->list
Return the list of colors input by the user.
'''
colors=[]
prompt="Enter the color you want to add, press return to exit.\n"
color=input(prompt)
while color!='':
colors.append(color)
color=input(prompt)
return colors
| true
|
1766b55fbf0337bcff4a3514a1e6542c8bceb78e
|
ktkthakre/Python-Crash-Course-Practice-files
|
/Chapter 3/guestlist.py
| 1,767
| 4.4375
| 4
|
#list exercise 3.4
guest = ['dog','cat','horse']
print(f"Please join us to dinner Mr.{guest[0].title()}.")
print(f"Please join us to dinner Mr.{guest[1].title()}.")
print(f"Please join us to dinner Mr.{guest[2].title()}.")
#list exercise 3.5
print(f"\nOh No, Mr.{guest[2].title()} cannot join us for dinner.")
cancled = guest.pop(2)
guest.append('cow')
print(f"So, Mr.{guest[2].title()} will be joining us instead.")
print(f"Atleast Mr.{guest[0].title()} and Mr.{guest[1].title()} will be still with us")
#list exercise 3.6
print("Hey, I just found a bigger table.")
guest.insert(0, 'bird')
guest.insert(4, 'boar')
guest.append('bull')
print("\nHere are the new invites : ")
print(f"\nPlease join us to dinner Mr.{guest[0].title()}.")
print(f"Please join us to dinner Mr.{guest[1].title()}.")
print(f"Please join us to dinner Mr.{guest[2].title()}.")
print(f"Please join us to dinner Mr.{guest[3].title()}.")
print(f"Please join us to dinner Mr.{guest[4].title()}.")
print(f"Please join us to dinner Mr.{guest[5].title()}.")
#displaying number of list using len() method
print(f"{len(guest)} guests will be joining us for dinner.")
#list exercise 3.7
print("\nHoly cow, the bigger table I ordered won't be here in time.\n\tOnly two guests can be adjusted at the dinner.")
print(f"\nSorry Mr.{guest[5].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[4].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[3].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[2].title()}, for letting you down.")
guest.pop()
print(f"Mr.{guest[0].title()} you will still be with us.\nAnd you too Mr.{guest[1].title()}")\
del guest[1]
del guest[0]
print(guest)
| false
|
66c033aa71f59194e22a89054896197aa2c42757
|
GowthamSingamsetti/Python-Practise
|
/rough10.py
| 899
| 4.25
| 4
|
# PYTHON program for bubble sort
print("PYTHON PROGRAM FOR BUBBLE SORT TECHNIQUE (Ascending Order)")
print("-"*70)
list = [12,4,45,67,98,34]
print("List before sorting" , list)
for i in range(0,6):
flag = 0
for j in range(0,5):
if(list[j]>list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
flag = 1
if(flag == 0):
break;
print("\nList after sorting" , list)
print("PYTHON PROGRAM FOR BUBBLE SORT TECHNIQUE (Descending Order)")
print("-"*50)
list = [12,4,45,67,98,34]
print("List before sorting" , list)
for i in range(0,6):
flag = 0
for j in range(0,5):
if(list[j]<list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
flag = 1
if(flag == 0):
break;
print("\nList after sorting" , list)
| false
|
cf8f65d4d28bdc98a8a7cc9cf2ce7d0453bfb980
|
hudaoling/hudaoling_20200907
|
/Python全栈_老男孩Alex/3-列表-字典-字符串-购物车/String_UseMethod.py
| 2,733
| 4.21875
| 4
|
# Author:Winnie Hu
name="My Name is {name},She is a worker and She is {year} old"
print(name.capitalize())#首字母
print(name.count("i"))
print(name.center(50,"-")) #打印50个字符,不够用-补齐,并摆放中间
print(name.endswith("ker")) #判断是否以什么结尾
print(name.expandtabs(tabsize=30))# \ 把这个键转换成多少个空格
print(name.find("is")) #取字符的索引位置,从0开始计算
print(name[name.find("is"):13])#返回索引的目的就是为了切片取字符串
print(name[name.find("is"):])#从is取数到最后
print(name.format(name='Winnie Hu',year=32))#给变量赋值
print(name.format_map({'name':'Winnie Hu','year':32}))#给变量赋值,不常用
#print(name.index())
print('ab23'.isalnum())#判断name变量,是不是阿拉伯数字
print('abcde'.isalpha())#判断是不是纯英文字母
print('2'.isdigit())#判断是不是十进制
print('100'.isdigit())#判断是不是整数
print('name_of_you'.isidentifier())#判断是不是一个合法的标识符(合法的变量名)
print('1name'.islower())#判断是不是小写
print('MY NAME '.isupper())#判断是不是大写
print('33'.isnumeric())#判断是不是一个数字
print(name.isspace())#判断是不是空格
print('My Name Is '.istitle())#判断是不是标题,单词首个字母大写是标题
print('My Name Is '.isprintable())#判断是不是能打印
print('+'.join(['1','2','3','4']))#把列表合并为字符串格式
print(name.ljust(100,'*'))#用*补全到指定的字符数量,字符串在左边
print(name.rjust(100,'-'))#用*补全到指定的字符数量,字符串在右边
print('\nWinnie Del\n'.strip())#\n代表换行,strip默认去掉两头的空格或回车
print('Winnie Del\n'.lstrip())#\n代表换行,lstrip去掉左边的空格或回车
print('Winnie Del\n'.rstrip())#\n代表换行,lstrip去掉右边的空格或回车
print('Winnie'.lower())#转换成小写
print('Winnie'.upper())#转换成大写
p = str.maketrans("abcdefli",'123$@456')#定义字符串与另一串字符串的对应关系
print("alex li".translate(p))#对alex li,根据上面的对应关系进行逐一替换,可用于密码加码等
print('alex li'.replace('l','L',1))#替换字符串
print('alex lil'.rfind('l'))#查找到从右边开始的某个字符串
print('al ex lil'.split())#按照指定的分割符拆分列,结果是list
print('al-ex-lil'.split('-'))#按照指定的分割符拆分列
print('1+2+3+4'.split('+'))#按照指定的分割符拆分列
print('1+2\n+3+4'.splitlines())#按空格或换行来拆分列
print('Alex Li'.swapcase())#大小写转换
print('alex li'.title())#变更为标题,首字母大写
print('alex li'.zfill(50))#字符串不够的时候,补0
name2='\n@qq.com' #\n代表换行
| false
|
29e7e1d222edafc4c2a4c229949848a004ae4285
|
hudaoling/hudaoling_20200907
|
/Python全栈_老男孩Alex/7 面向对象编程/静态方法-类方法-属性方法.py
| 2,048
| 4.21875
| 4
|
# Author:Winnie Hu
#动态方法
class Dog(object):
def __init__(self,name):
self.name=name
def eat(self,food):
print("动态方法self.:","%s is eating %s"%(self.name,food))
d=Dog("jinmao")
d.eat("baozi")
#静态方法
class Dog(object):
def __init__(self,name):
self.name=name
# 静态方法,实际上跟类没什么关系了,就可理解为类下面的一个普通函数
@staticmethod#只装饰某一方法,不影响下面其它方法
def eat(name,food):
print("静态方法@staticmethod:","%s is eating %s"%(name,food))
def talk(self):
print("不受影响", "%s is talking" % (self.name))
d=Dog("jinmao")
d.eat("jinmao","baozi")
d.talk()
#类方法,作用在类变量
class Dog(object):
name="huabao"#类变量
def __init__(self,name):
self.name=name
#类方法,只能访问类变量,不能访问实例变量。无法访问实例里面的变量。
#一般用于强制该方法只能调用类变量。
@classmethod
def eat(self,food):
print("类方法@classmethod:","%s is eating %s"%(self.name,food))
d=Dog("jinmao")
d.eat("baozi")
#属性方法
class Dog(object):
def __init__(self,name):
self.name=name
self.__food=None
#属性方法,把一个方法变成一个静态属性。
@property
def eat(self):
print("属性方法@property:","%s is eating %s"%(self.name,self.__food))
#如果要给eat赋值时,可以采用以下方法
@eat.setter
def eat(self,food):
print("set to food:",food)
self.__food=food#给私有属性self.__food赋值food
d=Dog("jinmao")
d.eat #d.eat变成了一个属性(既变量)。属性方法不用括号,不用传参,只能用常量值(例如"baozi")
d.eat="niurou" #赋值后,d.eat也会跟着变为“niurou”
d.eat
#del d.name #属性既变量,可以删除
#print(d.name)
del d.eat #属性方法默认无法删除
@eat.deleter
def eat(self):
del self.__food
print("删完了")
| false
|
6ccdbdcc90fffe223051131e8b7cc1b2c5bb9341
|
vlytvynenko/lp
|
/lp_hw/ex8.py
| 780
| 4.28125
| 4
|
formatter = "{} {} {} {}" #Defined structure of formatter variable
#Creating new string based on formatter structure with a new data
print(formatter.format(1, 2, 3, 4))
#Creating new string based on formatter structure with a new data
print(formatter.format('one', 'two', 'three', 'four'))
#Creating new string based on formatter structure with a new data
print(formatter.format(True, False, False, True))
#Creating new string based on formatter structure with a formatter variable
print(formatter.format(formatter, formatter, formatter, formatter))
#New structure for the last string
formatter2 = "{}; {}; {}; {}!"
#printed new string based on formatter2 structure
print(formatter2.format(
"Lya, lya, lya",
"Zhu, Zhu, zhu",
"Ti podprignizh",
"Ya vsazhu"
))
| true
|
738774b4756d730e942bcb8c88ec3801afe4b54c
|
legitalpha/Spartan
|
/Day_9_ques1_Russian_peasant_algo.py
| 285
| 4.125
| 4
|
a = int(input("Enter first number : "))
b = int(input("Enter second number : "))
count = 0
while a!=0:
if a%2==1:
count +=b
b=b<<1
a=a>>1
if a%2==0:
b=b<<1
a=a>>1
print("The product of first and second number is ",count)
| true
|
edbbed7b9a0ebeae3e1478b4988008deed3cee2e
|
dgquintero/holbertonschool-machine_learning
|
/math/0x03-probability/binomial.py
| 1,951
| 4.125
| 4
|
#!/usr/bin/env python3
"""class Binomial that represents a Binomial distribution"""
class Binomial():
""" Class Binomial that calls methos CDF PDF """
def __init__(self, data=None, n=1, p=0.5):
""" Class Binomial that calls methos CDF PDF """
self.n = int(n)
self.p = float(p)
if data is None:
if self.n <= 0:
raise ValueError("n must be a positive value")
elif self.p <= 0 or self.p >= 1:
raise ValueError("p must be greater than 0 and less than 1")
else:
if type(data) is not list:
raise TypeError("data must be a list")
elif len(data) < 2:
raise ValueError("data must contain multiple values")
else:
mean = sum(data) / len(data)
v = 0
for i in range(len(data)):
v += ((data[i] - mean) ** 2)
variance = v / len(data)
self.p = 1 - (variance / mean)
self.n = int(round(mean / self.p))
self.p = mean / self.n
def pmf(self, k):
"""Method that returns the pmf"""
k = int(k)
if k > self.n or k < 0:
return 0
factor_k = 1
factor_n = 1
factor_nk = 1
for i in range(1, k + 1):
factor_k *= i
for i in range(1, self.n + 1):
factor_n *= i
for f in range(1, (self.n - k) + 1):
factor_nk *= f
comb = factor_n / (factor_nk * factor_k)
prob = (self.p ** k) * ((1 - self.p) ** (self.n - k))
pmf = comb * prob
return pmf
def cdf(self, k):
""" Method that returns the Cumulative Distribution Function"""
k = int(k)
if k < 0:
return 0
else:
cdf = 0
for i in range(k + 1):
cdf += self.pmf(i)
return cdf
| true
|
d5491b784640d17450cbf52b9ecd8019f5b630a7
|
kvanishree/AIML-LetsUpgrade
|
/Day4.py
| 1,393
| 4.25
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[8]:
#Q1
print("enter the operation to perform")
a=input()
if(a=='+'):
c=(3+2j)+(5+4j)
print(c)
elif(a=='-'):
c=(3+2j)-(5+4j)
print(c)
elif(a=='*'):
c=(3+2j)*(5+4j)
print(c)
elif(a=='/'):
c=(3+2j)/(5+4j)
print(c)
elif(a=='//'):
print("floor division of two number is not possible\n")
elif(a=='%'):
print("module is not possible to do in complex numbers\n")
else:
print("enter correct operation")
# #Q2
# range()
# range(start,stop,step)
# start:it is not compulsory but if we want we can mention this for where to start..
# stop:it is required and compulsory to mention , this for where to stop..
# step: it is not compulsory to mention , but if we requird to print one step forward number of every number..
#
# In[21]:
#ex
for i in range(5):
print(i)
print("---------------")
list=[1,2,3,4,5,6,7]
for list in range(1,5,2):
print(list)
# In[23]:
#Q3
a=int(input(print("enter the num1\n")))
b=int(input(print("enter the num1\n")))
c=a-b
if(c>25):
print("multiplication is = ",a*b)
else:
print("division is = ",a/b)
# In[2]:
#Q4
l=[1,2,3,4,5,6]
for i in range(len(l)):
if(l[i]%2==0):
print("square of the number minus 2\n")
# In[3]:
#Q5
l2=[12,14,16,17,8]
for i in range(len(l2)):
if (l2[i]/2)>7:
print(l2[i],end=" ")
# In[ ]:
| true
|
dcbe69d5095815419df2130635fca147b87a0c74
|
gaurab123/DataQuest
|
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/11_UsingColumnIndexes.py
| 1,692
| 4.15625
| 4
|
import pandas as pd
titanic_survival = pd.read_csv('titanic_survival.csv')
# Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns.
drop_na_columns = titanic_survival.dropna(axis=1, how='any')
# Drop all rows in titanic_survival where the columns "age" or "sex"
# have missing values and assign the result to new_titanic_survival.
new_titanic_survival = titanic_survival.dropna(axis=0, subset=['age', 'sex'], how='any')
# Sort the new_titanic_survival DataForm by age
new_titanic_survival = new_titanic_survival.sort_values('age', ascending=False)
# Assign the first ten rows from new_titanic_survival to first_ten_rows
first_ten_rows = new_titanic_survival.iloc[0:10]
# Assign the fifth row from new_titanic_survival to row_position_fifth
row_position_fifth = new_titanic_survival.iloc[4]
# Assign the row with index label 25 from new_titanic_survivalto row_index_25
row_index_25 = new_titanic_survival.loc[25]
# Assign the value at row index label 1100, column index label
# "age" from new_titanic_survival to row_index_1100_age.
row_index_1100_age = new_titanic_survival.loc[1100,'age']
print(row_index_1100_age)
raw_input("Press Enter To Continue")
# Assign the value at row index label 25, column index label
# "survived" from new_titanic_survival to row_index_25_survived.
row_index_25_survived = new_titanic_survival.loc[25, 'survived']
print(row_index_25_survived)
raw_input("Press Enter To Continue")
# Assign the first 5 rows and first three columns from new_titanic_survival to five_rows_three_cols
five_rows_three_cols = new_titanic_survival.iloc[0:5,0:3]
print(five_rows_three_cols)
| false
|
5a29550eb1b08000b460873abfbc9bf3b5b7ed3d
|
alwinsheejoy/College
|
/SNIPPETS/Python/strings/strings.py
| 381
| 4.1875
| 4
|
str_name = 'Python for Beginners'
#012356789
print(str_name[0]) # P
print(str_name[-1]) # s
print(str_name[0:3]) # 0 to 2 Pyt
print(str_name[0:]) # 0 to end(full) Python for Beginners
print(str_name[:5]) # 0 to 4 Pytho
print(str_name[:]) # [0:end] (full) - copy/clone a string.
copied_str = str_name[:] # copy
print(str_name[1:-1]) # 1 to end-1 ython for Beginner
| false
|
45031662df9be1dafbac90323ea6b977949328f5
|
Jerwinprabu/practice
|
/reversepolish.py
| 596
| 4.34375
| 4
|
#!/usr/bin/python
"""
reverse polish notation evaluator
Functions that define the operators and how to evaluate them.
This example assumes binary operators, but this is easy to extend.
"""
ops = {
"+" : (lambda a, b: a + b),
"-" : (lambda a, b: a - b),
"*" : (lambda a, b: a * b)
}
def eval(tokens):
stack = []
for token in tokens:
if token in ops:
arg2 = stack.pop()
arg1 = stack.pop()
result = ops[token](arg1, arg2)
stack.append(result)
else:
stack.append(int(token))
return stack.pop()
print "Result:", eval("7 2 3 + -".split())
| true
|
c5363e8be7c3e46cd35561d83880c3162f6ece0f
|
ataicher/learn_to_code
|
/careeCup/q14.py~
| 911
| 4.3125
| 4
|
#!/usr/bin/python -tt
import sys
def isAnagram(S1,S2):
# remove white space
S1 = S1.replace(' ',''); S2 = S2.replace(' ','')
# check the string lengths are identical
if len(S1) != len(S2):
return False
# set strings to lower case
S1 = S1.lower(); S2 = S2.lower()
# sort strings
S1 = sorted(S1); S2 = sorted(S2)
if S1 == S2:
return True
else:
return False
def main():
print 'find out if two strings are anagrams'
if len(sys.argv) == 3:
S1 = sys.argv[1]
S2 = sys.argv[2]
print 'S1 =', S1
print 'S2 =', S2
else:
S1 = 'Namibia'
S2 = 'I am a bin'
print 'using default strings:\nS1 = Namibia\nS2 = I am a bin'
if isAnagram(S1,S2):
print 'the two strings are anagrams!'
else:
print 'sorry. The two strings are not anagrams'
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
| true
|
9317aaa0cb94a12b89f6960525791598088003d6
|
HeavenRicks/dto
|
/primary.py
| 2,273
| 4.46875
| 4
|
#author: <author here>
# date: <date here>
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# 2 - create a print statement that prints the sum of three numbers
# 3 - create a print statement the prints the sum of two negative numbers
print(7+3)
print(3+6+2)
print(-5+-7)
# subtraction
# instructions
# 1 - create a print statement that prints the difference of two numbers
# 2 - create a print statement that prints the difference of three numbers
# 3 - create a print statement the prints the difference of two negative numbers
print(10-4)
print(24-8-3)
print(-9--3)
# multiplication and true division
# instructions
# 1 - create a print statement the prints the product of two numbers
# 2 - create a print statement that prints the dividend of two numbers
# 3 - create a print statement that evaluates an operation using both multiplication and division
print(8*4)
print(16/2)
print(4*6/2)
# floor division
# instructions
# 1 - using floor division, print the dividend of two numbers.
print(24//8)
# exponentiation
# instructions
# 1 - using exponentiation, print the power of two numbers
print(18**2)
# modulus
# instructions
# 1 - using modulus, print the remainder of two numbers
print(50%7)
# --------------- Section 2 --------------- #
# ---------- String Concatenation --------- #
# concatenation
# instructions
# 1 - print the concatenation of your first and last name
# 2 - print the concatenation of five animals you like
# 3 - print the concatenation of each word in a phrase
print('Heaven' + 'Ricks')
print('Dolphins'+'Pandas'+'Monkeys'+'Goats'+'Horse')
print('i'+'love'+'dolphins')
# duplication
# instructions
# 1 - print the duplpication of your first name 5 times
# 2 - print the duplication of a song you like 10 times
print('heaven'*5)
print('solid'*10)
# concatenation and duplpication
# instructions
# 1 - print the concatenation of two strings duplicated 3 times each
print('Heaven'+'Ricks'*3)
| true
|
2c4c928322977ee0f99b7bfe4a97728e09402656
|
PropeReferio/practice-exercises
|
/random_exercises/temp_converter.py
| 586
| 4.28125
| 4
|
unit = input("Fahrenheit or Celsius?")
try_again = True
while try_again == True:
if unit == "Fahrenheit":
f = int(input("How many degrees Fahrenheit?"))
c = f / 9 * 5 - 32 / 9 * 5
print (f"{f} degrees Fahrenheit is {c} degrees Celsius.")
try_again = False
elif unit == "Celsius":
c = int(input("How many degrees Celsius?"))
f = c * 9 / 5 + 32
print (f"{c} degrees Celsius is {f} degrees Fahrenheit.")
try_again = False
else:
print ("What unit is that?")
unit = input("Fahrenheit or Celsius?")
| false
|
849c615ac2f77f6356650311deea9da6c32952bf
|
andrearus-dev/shopping_list
|
/myattempt.py
| 1,719
| 4.1875
| 4
|
from tkinter import *
from tkinter.font import Font
window = Tk()
window.title('Shopping List')
window.geometry("400x800")
window.configure(bg="#2EAD5C")
bigFont = Font(size=20, weight="bold")
heading1 = Label(window, text=" Food Glorious Food \n Shopping List",
bg="#2EAD5C", fg="#fff", font=bigFont).pack(pady=10)
# Adding input text to the list
def add_command():
text = entry_field.get()
for item in my_list:
list_layout.insert(END, text)
# Deleting one item at a time
def delete_command():
for item in my_list:
list_layout.delete(ACTIVE)
# Deleting all items with one click of a button
def delete_all_command():
list_layout.delete(0, END)
# Variable holding empty list
my_list = [""]
# Frame and scroll bar so the user can view the whole list
my_frame = Frame(window, bg="#00570D")
scrollBar = Scrollbar(my_frame, orient=VERTICAL)
# List box - where the items will be displayed
list_layout = Listbox(my_frame, width=40, height=20,
yscrollcommand=scrollBar.set)
list_layout.pack(pady=20)
# configure scrollbar
scrollBar.config(command=list_layout.yview)
scrollBar.pack(side=RIGHT, fill=Y)
my_frame.pack(pady=20)
heading2 = Label(window, text="Add items to your list \n Happy Shopping!",
bg="#2EAD5C", fg="#fff", font=1).pack(pady=5)
# Entry Field
entry_field = Entry(window)
entry_field.pack(pady=5)
# Buttons - when clicked the function is called
Button(window, text="Add Item", command=add_command).pack(pady=5)
Button(window, text="Delete Item", command=delete_command).pack(pady=5)
Button(window, text="Delete ALL Food Items",
command=delete_all_command).pack(pady=10)
window.mainloop()
| true
|
026dc30173ab7427f744b000f55558ffc19099e8
|
glaxur/Python.Projects
|
/guess_game_fun.py
| 834
| 4.21875
| 4
|
""" guessing game using a function """
import random
computers_number = random.randint(1,100)
PROMPT = "What is your guess?"
def do_guess_round():
"""Choose a random number,ask user for a guess
check whether the guess is true and repeat whether the user is correct"""
computers_number = random.randint(1,100)
while True:
players_guess = int(input(PROMPT))
if computers_number == int(players_guess):
print("correct!")
break
elif computers_number > int(players_guess):
print("Too low")
else:
print("Too high")
while True:
print("Starting a new round")
print("The computer's number should be "+str(computers_number))
print("Let the guessing begin!!!")
do_guess_round()
print(" ")
| true
|
46f70133d8fc36aa8c21c51ba8cd35efd18fcfc7
|
MenggeGeng/FE595HW4
|
/hw4.py
| 1,520
| 4.1875
| 4
|
#part 1: Assume the data in the Boston Housing data set fits a linear model.
#When fit, how much impact does each factor have on the value of a house in Boston?
#Display these results from greatest to least.
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
#load boston dataset
boston = load_boston()
#print(boston)
data = pd.DataFrame(boston['data'], columns= boston['feature_names'])
print(data.head())
data['target'] = boston['target']
print(data.head())
# The correlation map
correlation = data.corr()
sns.heatmap(data = correlation, annot = True)
plt.show()
# The correlation coefficient between target and features
print(correlation['target'])
#prepare the regression objects
X = data.iloc[:, : -1]
Y = data['target']
print(X.shape)
print(Y.shape)
#build regression model
reg_model = LinearRegression()
reg_model.fit(X,Y)
print('coefficient : \n ', reg_model.coef_)
#The impact of each factor have on the value of a house in Boston
coef = pd.DataFrame(data= reg_model.coef_, index = boston['feature_names'], columns=["value"])
print(coef)
#Display these results from greatest to least.
coef_abs = abs(reg_model.coef_)
coef_1 = pd.DataFrame(data= coef_abs , index = boston['feature_names'], columns=["value"])
print("Display these coefficient from greatest to least:")
print(coef_1.sort_values("value",inplace=False, ascending=False))
| true
|
9d723b583cec6a1c2ec2aea6497eec0d6dd6d27f
|
ageinpee/DaMi-Course
|
/1/Solutions/Solution-DAMI1-Part3.py
| 2,024
| 4.15625
| 4
|
''' Solution to Part III - Python functions. Comment out the parts you do not wish to execute or copy
a specific function into a new py-file'''
#Sum of squares, where you can simply use the square function you were given
def sum_of_squares(x, y):
return square(x) + square(y)
print sum_of_squares(3, 5) # Try out yourself
#Increment by 1
x = 0
y = 0
def incr(x):
y = x + 1
return y
print incr(5) # Try out yourself
# Increment by any n; quite straightforward, right?
x = 0
y = 0
def incr_by_n(x, n):
y = x + n
return y
print incr_by_n(4,2) # Try out yourself
#Factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("The number you want to compute the factorial of: ")) # User input
print "Result:", factorial(4) # Try out yourself
#Display numbers between 1 and 10 using 'for' ...
for a in range(1, 11):
print a
#... and 'while'
a=1
while a<=10:
print a
a+=1
#Test if a number is between 1 and 10 (can be of any range though)
def number_in_range(n):
if n in range(1,10):
print( " %s is in the range"%str(n))
else :
print "The number is outside the given range."
test_range(8) # Try out yourself
'''Multiple if-conditionals
Note, that no keyword 'end' is needed! Instead, program blocks are controlled via indentation.
For beginners, indentation errors are most likely to occur, so playing around and extending smaller
code snippets to bigger program code can better help understanding the underlying
Python interpretation process'''
def chain_conditions(x,y):
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
chain_conditions(50, 10) # Try out yourself
#Prime number
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(7)) # Try out yourself
| true
|
45fc9452f03b169869eb753bf3ffc017540dd052
|
sejinwls/2018-19-PNE-practices
|
/session-5/ex-1.py
| 620
| 4.1875
| 4
|
def count_a(seq):
""""THis function is for counting the number of A's in the sequence"""
# Counter for the As
result = 0
for b in seq:
if b == "A":
result += 1
# Return the result
return result
# Main program
s = input("Please enter the sequence: ")
na = count_a(s)
print("The number of As is : {}".format(na))
# Calculate the total sequence lenght
tl = len(s)
# Calculate the percentage of As in the sequence
if tl > 0:
perc = round(100.0 * na/tl, 1)
else:
perc = 0
print("The total lenght is: {}".format(tl))
print("The percentage of As is {}%".format(perc))
| true
|
e14736ccc657561a7db0a6653d64f05953b85d30
|
aratik711/100-python-programs
|
/eval_example.py
| 320
| 4.28125
| 4
|
"""
Please write a program which accepts basic mathematic expression from console and print the evaluation result.
Example:
If the following string is given as input to the program:
35+3
Then, the output of the program should be:
38
Hints:
Use eval() to evaluate an expression.
"""
exp = input()
print(eval(exp))
| true
|
d33e36b0734802ce63caaa7310a21ecb2b6081d6
|
aratik711/100-python-programs
|
/subclass_example.py
| 382
| 4.125
| 4
|
"""
Question:
Define a class named American and its subclass NewYorker.
Hints:
Use class Subclass(ParentClass) to define a subclass.
"""
class American:
def printnationality(self):
print("America")
class NewYorker:
def printcity(self):
American.printnationality(self)
print("New York")
citizen = NewYorker()
citizen.printcity()
| true
|
2f133b9e5687578ca73e329c24c3197512b7d790
|
sureshpodeti/Algorithms
|
/dp/slow/min_steps_to_minimize_num.py
| 740
| 4.15625
| 4
|
'''
Minimum steps to minimize n as per given condition
Given a number n, count minimum steps to minimize it to 1 according to the following criteria:
If n is divisible by 2 then we may reduce n to n/2.
If n is divisible by 3 then you may reduce n to n/3.
Decrement n by 1.
brute-force solution:
time complexicity: O(3^n)
'''
def min_steps(n):
if n == 0 or n==1:
return n
if n == 2 or n == 3:
return 1
if n%3 ==0 and n%2 ==0:
return 1+min(min_steps(n/3), min_steps(n/2), min_steps(n-1))
elif n%3 == 0:
return 1 + min(min_steps(n/3), min_steps(n-1))
elif n%2 == 0:
return 1+min(min_steps(n/2), min_steps(n-1))
return 1+min_steps(n-1)
n = int(raw_input())
print "no.of steps:{}".format(min_steps(n))
| false
|
f7b05c070eb88efe3ea889c2d77647a6e9cf6b4d
|
sureshpodeti/Algorithms
|
/dp/slow/min_cost_path.py
| 1,157
| 4.125
| 4
|
'''
Min cost path:
Given a matrix where each cell has some interger value which represent the cost incurred
if we visit that cell.
Task is found min cost path to reach (m,n) position in the matrix from (0,0) position
possible moves: one step to its right, one step down, and one step diagonally
brute-force : generate and test
Let f(i,j) denote the min cost path needed to reach (i,j) position from (0,0) position
Suppose, if we have f(i-1,j), f(i-1, j-1), and f(i, j-1) ,
Is it possible to find f(i,j) from know values ???
answer: yes, we can as shown below
f(i,j) = A[i][j]+min{f(i-1, j-1), f(i-1,j), f(i, j-1)}
base condition : if i<0 or j<0 then return 0
if i ==j and i==0 then return A[i][j]
'''
from sys import maxint
def min_cost_path(A, m,n):
if m<0 or n<0:
return maxint
if m==n and m==0:
return A[m][n]
return A[m][n]+ min(min_cost_path(A, m-1, n), min_cost_path(A, m-1, n-1), min_cost_path(A, m, n-1))
A = [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ]
inp = raw_input().split(' ')
m,n = map(int, inp)
print "min_cost_path({}):{}".format(A, min_cost_path(A, m, n))
| true
|
e8019a0d7da90f1633bd139a32ca191887b08c10
|
naroladhar/MCA_101_Python
|
/mulTable.py
| 1,074
| 4.125
| 4
|
import pdb
pdb.set_trace()
def mulTable(num,uIndexLimit):
'''
Objective : To create a multiplication table of numbers
Input Variables :
num : A number
uIndexLimit: The size of the multiplication table
Output Variables:
res : The result of the product
return value:none
'''
for i in range(0,uIndexLimit+1):
res=num*i
print("%d X %d = %d" %(num,i,res))
def main():
'''
Objective : To create a multiplication table of numbers
Input Variables :
num : A number
uIndexLimit: The size of the multiplication table
Output Variables:
res : The result of the product
return value:none
'''
start=int(input(" Enter a start: "))
finish = int(input(" Enter a finish: "))
uIndexLimit = int(input(" Enter size of the table: "))
for start in range(start,finish+1):
print("*******Time Table for ",start,"*********")
mulTable(start,uIndexLimit)
if __name__=='__main__':
main()
| true
|
92aca135af4da75cb0cd32b9bfac71515384e04d
|
hakanguner67/class2-functions-week04
|
/exact_divisor.py
| 376
| 4.125
| 4
|
'''
Write a function that finds the exact divisors of a given number.
For example:
function call : exact_divisor(12)
output : 1,2,3,4,6,12
'''
#users number
number = int(input("Enter a number : "))
def exact_divisor(number) :
i = 1
while i <= number : # while True
if ((number % i )==0) :
print (i)
i = i + 1
exact_divisor(number)
| true
|
89aa00e1cd5480b1e976fe94a3bbd044f8f671de
|
hakanguner67/class2-functions-week04
|
/counter.py
| 590
| 4.21875
| 4
|
'''
Write a function that takes an input from user and than gives the number of upper case letters and smaller case letters of it.
For example :
function call: counter("asdASD")
output: smaller letter : 3
upper letter : 3
'''
def string_test(s):
upper_list=[]
smaller_list=[]
for i in s:
if i.isupper():
upper_list.append(i)
elif i.islower():
smaller_list.append(i)
else :
pass
print("Smaller Letter : ",len(smaller_list))
print("Upper Letter :",len(upper_list))
s = input("Enter a word : ")
string_test(s)
| true
|
38ed49911be4adb634aa662aed898a56c244c5ac
|
mariadiaz-lpsr/class-samples
|
/5-4WritingHTML/primeListerTemplate.py
| 944
| 4.125
| 4
|
# returns True if myNum is prime
# returns False is myNum is composite
def isPrime(x, myNum):
# here is where it will have a certain range from 2 to 100000
y = range(2,int(x))
# subtract each first to 2
primenum = x - 2
count = 0
for prime in y:
# the number that was divided will then be divided to find remainder
rem_prime = int(x) % int(prime)
if rem_prime != 0:
count = count + 1
# if it is prime it will print it and append it to the ListOfPrime
if count == primenum:
print(x)
myNum.append(x)
ListOfPrime = []
# the file numbers.txt will open so it can be append the numbers that are prime only
prime = open("numbers.txt", "w")
# the range is from 2 to 100000
r = range(2, 100000)
for PList in r:
numberss = isPrime(PList, ListOfPrime)
for y in ListOfPrime:
# the prime numbers will be written in a single list
prime.write(str(y) + "\n")
# the file that was open "numbers.txt" will close
prime.close()
| true
|
120526d1004799d849367a701f6fa9c09c6bbe05
|
mariadiaz-lpsr/class-samples
|
/quest.py
| 1,314
| 4.15625
| 4
|
print("Welcome to Maria's Quest!!")
print("Enter the name of your character:")
character = raw_input()
print("Enter Strength (1-10):")
strength = int(input())
print("Enter Health (1-10):")
health = int(input())
print("Enter Luck (1-10):")
luck = int(input())
if strength + health + luck > 15:
print("You have give your character too many points! ")
while strength + health + luck < 15:
print(character , "strength" + strength + "health" + health + "luck" + luck)
if strength + health + luck == 15:
print(character," you've come to a fork in the road. Do you want to go right or left? Enter right or left. ")
if right or left == "left":
print("Sorry you lost the game.")
# if user chooses right and has strength over 7
if strength >= 7:
print(character,"you're strength is high enough you survived to fight the ninjas that attacked you. You won the game!")
else:
print("You didn't have sufficient strength to defeat the ninjas. Sorry you lost the game :(. ")
# if health is greater than 8
if health >= 8:
print("You had enough energy to pass by the ninjas."
else:
print("Sorry your health was not enough to survive the spriral ninja stars wound. ")
# if the number of luck is greater than 5 it wil print out the first line if not it will directly go to the else line
if luck >= 5:
print("You had ")
| true
|
7251ebc79e8c4968588276efb33d05320b032750
|
mariadiaz-lpsr/class-samples
|
/names.py
| 1,010
| 4.3125
| 4
|
# it first prints the first line
print("These are the 5 friends and family I spend the most time with: ")
# these are the 2 list name names and nams
names = ['Jen', 'Mom', 'Dad', 'Alma', 'Ramon']
nams = ['Jackelyn', 'Judy', 'Elyssa', 'Christina', 'Cristian']
# it is concatenating both of the lists
names_nams = names + nams
# its changing the word in that number to another thing to print out instead
for nms in names:
names[0] = "1. Jen"
for nms in names:
names[1] = "2. Mom"
for nms in names:
names[2] = "3. Dad"
for nms in names:
names[3] = "4. Alma"
for nms in names:
names[4] = "5. Ramon"
for nms in names:
names[5] = "6. Jackelyn"
for nms in names:
names[6] = "7. Judy"
for nms in names:
names[7] = "8. Elyssa"
for nms in names:
names[8] = "9. Christina"
for nms in names:
names[9] = "10. Cristian"
# it will print out both the names and nams lists
print(names_nams)
# it will reverse the list
names.reverse()
# it will print out the list been in reverse order
print(names_nams)
| true
|
434182c9ca2fa8b73c4f2fd0b4d9197720b7d406
|
pktippa/hr-python
|
/basic-data-types/second_largest_number.py
| 430
| 4.21875
| 4
|
# Finding the second largest number in a list.
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split())) # Converting input string into list by map and list()
new = [x for x in arr if x != max(arr)] # Using list compressions building new list removing the highest number
print(max(new)) # Since we removed the max number in list, now the max will give the second largest from original list.
| true
|
3c09d0c67801c8748794d163a275a6c6f5b88378
|
pktippa/hr-python
|
/itertools/permutations.py
| 678
| 4.15625
| 4
|
# Importing permutations from itertools.
from itertools import permutations
# Taking the input split by space into two variables.
string, count = input().split()
# As per requirement the given input is all capital letters and the permutations
# need to be in lexicographic order. Since all capital letters we can directly use
# sorted(str) and join to form string
string = ''.join(sorted(string))
# Calling permutations to get the list of permutations, returns list of tuples
permutation_list = list(permutations(string, int(count)))
# Looping through all elements(tuples)
for element in permutation_list:
print(''.join(element)) # forming string from a tuple of characters
| true
|
e03cc807d94143ba7377b192d5784cbdb07b1abd
|
pktippa/hr-python
|
/math/find_angle_mbc.py
| 376
| 4.34375
| 4
|
# importing math
import math
# Reading AB
a = int(input())
# Reading BC
b = int(input())
# angle MBC is equal to angle BCA
# so tan(o) = opp side / adjacent side
t = a/b
# calculating inverse gives the value in radians.
t = math.atan(t)
# converting radians into degrees
t = math.degrees(t)
# Rounding to 0 decimals and adding degree symbol.
print(str(int(round(t,0))) + '°')
| true
|
bed0fc094ed0b826db808aa4449cbf31686cbd2a
|
aryakk04/python-training
|
/functions/dict.py
| 549
| 4.53125
| 5
|
def char_dict (string):
""" Prints the dictionary which has the count of
each character occurrence in the passed string
argument
Args:
String: It sould be a string from which character
occurrence will be counted.
Returns:
Returns dictionary having count of each character
in the given string.
"""
char_dic = {}
for char in string:
if char not in char_dic:
char_dic[char] = string.count(char)
return char_dic
string = input("Enter a string : ")
char_dic = char_dict (string)
print (char_dic)
| true
|
2e0deae0231338db84a2f11cd64994bf82900b33
|
seanakanbi/SQAT
|
/SampleTests/Sample/classes/Calculator.py
| 1,677
| 4.375
| 4
|
import math
from decimal import *
class Calculator():
"""
A special number is any number that is
- is between 0 and 100 inclusive and
- divisible by two and
- divisible by five.
@param number
@return message (that displays if the number is a special number)
"""
def is_special_number(self, num_in):
# Verify the number is within the valid range.
if num_in < 0 or num_in > 100:
message = " is not a valid number."
else:
# Determine if the number is a special number.
if num_in % 2 != 0:
message = " is not an even number."
elif num_in % 5 != 0:
message = " is not divisible by five."
else:
message = " is a special number"
#Remember this will return your number plus the message!
return str(num_in) + message
"""
This method does a strange/alternative calculation
* @param operand
* @return calculated value as a Decimal
"""
def alternative_calculate(self, operand):
calculated_value = operand * 100 / math.pi
return Decimal(calculated_value)
if __name__ == '__main__':
print("****** ******* ")
print("****** Running calculator ******* ")
calc = Calculator()
num1 = int(input("Please enter a number to check if it is special: " ))
print("-> ", calc.is_special_number(num1))
num2 = int(input("Please enter a number to run an alternative calculation on it: " ))
print("-> ", round(calc.alternative_calculate(num2),4))
| true
|
0df98d530f508a752e42a67ad7c6fe0a2608f823
|
JaiAmoli/Project-97
|
/project97.py
| 266
| 4.21875
| 4
|
print("Number Guessing Game")
print("guess a number between 1-9")
number = int(input("enter your guess: "))
if(number<2):
print("your guess was too low")
elif(number>2):
print("your guess was too high")
else:
print("CONGRATULATIONS YOU WON!!!")
| true
|
7b9c3c2cd1a9f753a9f3df2adeb84e846c9eb1b4
|
mschaldias/programmimg-exercises
|
/list_merge.py
| 1,395
| 4.34375
| 4
|
'''
Write an immutable function that merges the following inputs into a single list. (Feel free to use the space below or submit a link to your work.)
Inputs
- Original list of strings
- List of strings to be added
- List of strings to be removed
Return
- List shall only contain unique values
- List shall be ordered as follows
--- Most character count to least character count
--- In the event of a tie, reverse alphabetical
Other Notes
- You can use any programming language you like
- The function you submit shall be runnable
For example:
Original List = ['one', 'two', 'three',]
Add List = ['one', 'two', 'five', 'six]
Delete List = ['two', 'five']
Result List = ['three', 'six', 'one']*
'''
def merge_lists(start_list,add_list,del_list):
set_start = set(start_list)
set_add = set(add_list)
set_del = set(del_list)
set_final = (set_start | set_add) - set_del
final_list = list(set_final)
final_list.sort(key=len, reverse=True)
return final_list
def main():
start_list = ['one', 'two', 'three',]
add_list = ['one', 'two', 'five', 'six']
del_list = ['two', 'five']
#final_list = ['three', 'six', 'one']
final_list = merge_lists(start_list,add_list,del_list)
print(final_list)
main()
| true
|
d089ecb536c7d01e7387f82dbe93da65da98358c
|
yogabull/TalkPython
|
/WKUP/loop.py
| 925
| 4.25
| 4
|
# This file is for working through code snippets.
'''
while True:
print('enter your name:')
name = input()
if name == 'your name':
break
print('thank you')
'''
"""
name = ''
while name != 'your name':
name = input('Enter your name: ')
if name == 'your name':
print('thank you')
"""
import random
print('-----------------')
print(' Number Game')
print('-----------------')
number = random.randint(0, 100)
guess = ''
while guess != number:
guess = int(input('Guess a number between 1 and 100: '))
if guess > number:
print('Too high')
print(number)
if guess < number:
print('Too low')
print(number)
if guess == number:
print('Correct')
print(number)
print('---------------------')
print(' f-strings')
print('---------------------')
name = input('Please enter your name: ')
print(f'Hi {name}, it is nice to meet you.')
| true
|
8837287f4ef533b32c594b35c8b432216cb8c628
|
yogabull/TalkPython
|
/ex3_birthday_program/ex3_program_birthday.py
| 1,221
| 4.28125
| 4
|
"""This is a birthday app exercise."""
import datetime
def main():
print_header()
bday = get_user_birthday()
now = datetime.date.today()
td = compute_user_birthday(bday, now)
print_birthday_info(td)
def print_header():
print('-----------------------------')
print(' Birthday App')
print('-----------------------------')
print()
def get_user_birthday():
print("When is your birthday?")
year = int(input('Year [YYYY]: '))
month = int(input('Month [MM]: '))
day = int(input('Day [DD]: '))
bday = datetime.date(year, month, day)
return bday
def compute_user_birthday(original_date, today):
# this_year = datetime.date(
# year=today.year, month=original_date.month, day=original_date.day)
""" Refactored below."""
this_year = datetime.date(
today.year, original_date.month, original_date.day)
td = this_year - today
return td.days
def print_birthday_info(days):
if days > 0:
print(f"Your birthday is in {days} days.")
elif days < 0:
print(f"Your birtdahy was {-days} days ago.")
else:
print("Happy Birthday!")
print()
print('-----------------------------')
main()
| false
|
ce930feff941e3e78f9629851ce0c8cc08f8106b
|
yogabull/TalkPython
|
/WKUP/fStringNotes.py
| 694
| 4.3125
| 4
|
#fString exercise from link at bottom
table = {'John' : 1234, 'Elle' : 4321, 'Corbin' : 5678}
for name, number in table.items():
print(f'{name:10} --> {number:10d}')
# John --> 1234
# Elle --> 4321
# Corbin --> 5678
'''
NOTE: the '10' in {name:10} means make the name variable occupy at least 10 spaces.
This is useful for making columns align.
'''
'''
f-Strings:
Another method to output varibles within in a string.
Formatted String Literals
This reads easily.
year = 2019
month = 'June'
f'It ends {month} {year}.'
>>> It ends June 2019.
https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings
'''
| true
|
c7fc3ced3296f7e181ba9714534800b59d20dd53
|
thevirajshelke/python-programs
|
/Basics/subtraction.py
| 586
| 4.25
| 4
|
# without user input
# using three variables
a = 20
b = 10
c = a - b
print "The subtraction of the numbers is", c
# using 2 variables
a = 20
b = 10
print "The subtraction of the numbers is", a - b
# with user input
# using three variables
a = int(input("Enter first number "))
b = int(input("Enter first number "))
c = a - b
print "The subtraction of the numbers is", c
# using 2 variables
# int() - will convert the input into numbers if string is passed!
a = int(input("Enter first number "))
b = int(input("Enter first number "))
print "The subtraction of the numbers is", a - b
| true
|
ef45e2377ab4276345644789a17abdd20da69aca
|
johnehunt/computationalthinking
|
/week4/tax_calculator.py
| 799
| 4.3125
| 4
|
# Program to calculate tax band
print('Start')
# Set up 'constants' to be used
BASIC_RATE_THRESHOLD = 12500
HIGHER_RATE_THRESHOLD = 50000
ADDITIONAL_RATE_THRESHOLD = 150000
# Get user input and a number
income_string = input('Please input your income: ')
if income_string.isnumeric():
annual_income = int(income_string)
# Determine tax band
if annual_income > ADDITIONAL_RATE_THRESHOLD:
print('Calculating tax ...')
print('Your highest tax rate is 45%')
elif annual_income > HIGHER_RATE_THRESHOLD:
print('Your highest tax rate is 40%')
elif annual_income > BASIC_RATE_THRESHOLD:
print('Your highest tax rate is 20%')
else:
print('You are not liable for income tax')
else:
print('Input must be a positive integer')
print('Done')
| true
|
8d7ca111c403010de98909a1850ae5f7a1d54b2b
|
johnehunt/computationalthinking
|
/number_guess_game/number_guess_game_v2.py
| 1,262
| 4.34375
| 4
|
import random
# Print the Welcome Banner
print('===========================================')
print(' Welcome to the Number Guess Game')
print(' ', '-' * 40)
print("""
The Computer will ask you to guess a number between 1 and 10.
""")
print('===========================================')
# Initialise the number to be guessed
number_to_guess = random.randint(1, 10)
# Set up flag to indicate if one game is over
finished_current_game = False
# Obtain their initial guess and loop to see if they guessed correctly
while not finished_current_game:
guess = None
# Make sure input is a positive integer
input_ok = False
while not input_ok:
input_string = input('Please guess a number between 1 and 10: ')
if input_string.isdigit():
guess = int(input_string)
input_ok = True
else:
print('Input must be a positive integer')
# Check to see if the guess is above, below or the correct number
if guess < number_to_guess:
print('Your guess was lower than the number')
elif guess > number_to_guess:
print('Your guess was higher than the number')
else:
print('Well done you won!')
finished_current_game = True
print('Game Over')
| true
|
0f25b7552ca48fbdc04ee31bd873d899ffae26c6
|
johnehunt/computationalthinking
|
/week4/forsample.py
| 813
| 4.34375
| 4
|
# Loop over a set of values in a range
print('Print out values in a range')
for i in range(0, 10):
print(i, ' ', end='')
print()
print('Done')
print('-' * 25)
# Now use values in a range but increment by 2
print('Print out values in a range with an increment of 2')
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
print('Done')
print('-' * 25)
# This illustrates the use of a break statement
num = int(input('Enter a number: '))
for i in range(0, 6):
if i == num:
break
print(i, ' ', end='')
print('Done')
print('-' * 25)
# This illustrates the use of a continue statement
for i in range(0, 10):
print(i, ' ', end='')
if i % 2 == 1: # Determine if this is an odd number
continue
print('its an even number')
print('we love even numbers')
print('Done')
| true
|
2acb0005b760b130fc4c553b8f9595c91b828c0e
|
tainagdcoleman/sharkid
|
/helpers.py
| 2,892
| 4.125
| 4
|
from typing import Tuple, List, Dict, TypeVar, Union
import scipy.ndimage
import numpy as np
import math
Num = TypeVar('Num', float, int)
Point = Tuple[Num, Num]
def angle(point: Point,
point0: Point,
point1: Point) -> float:
"""Calculates angles between three points
Args:
point: midpoint
point0: first endpoint
point1: second endpoint
Returns:
angle between three points in radians
"""
a = (point[0] - point0[0], point[1] - point0[1])
b = (point[0] - point1[0], point[1] - point1[1])
adotb = (a[0] * b[0] + a[1] * b[1])
return math.acos(adotb / (magnitude(a) * magnitude(b)))
def find_angles(points: List[Point])-> List[float]:
"""Finds angles between all points in sequence of points
Args:
points: sequential list of points
Returns:
angles in radians
"""
return angle(points[len(points) // 2], points[0], points[-1])
def magnitude(point: Point) -> float:
"""Finds the magnitude of a point, as if it were a vector originating at 0, 0
Args:
point: Point (x, y)
Returns:
magnitude of point
"""
return math.sqrt(point[0]**2 + point[1]**2)
def dist_to_line(start: Point, end: Point, *points: Point, signed=False) -> Union[float, List[float]]:
"""Finds the distance between points and a line given by two points
Args:
start: first point for line
end: second point for line
points: points to find distance of.
Returns:
A single distance if only one point is provided, otherwise a list of distances.
"""
start_x, start_y = start
end_x, end_y = end
dy = end_y - start_y
dx = end_x - start_x
m_dif = end_x*start_y - end_y*start_x
denom = math.sqrt(dy**2 + dx**2)
_dist = lambda point: (dy*point[0] - dx*point[1] + m_dif) / denom
dist = _dist if signed else lambda point: abs(_dist(point))
if len(points) == 1:
return dist(points[0])
else:
return list(map(dist, points))
def gaussian_filter(points:List[Point], sigma=0.3):
return scipy.ndimage.gaussian_filter(np.asarray(points), sigma)
def distance(point1: Point, point2: Point):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def coord_transform(points: List[Tuple[int, int]])-> float:
start_x, start_y = points[0]
end_x, end_y = points[-1]
inner = points[1:-1]
perp_point_x = start_x - (end_y - start_y)
perp_point_y = start_y + (end_x - start_x)
ys = dist_to_line((start_x, start_y), (end_x, end_y), *inner, signed=True)
xs = dist_to_line((start_x, start_y), (perp_point_x, perp_point_y), *inner, signed=True)
return xs, ys
def remove_decreasing(xs, ys):
maxx = xs[0]
for x, y in zip(xs, ys):
if x > maxx:
yield x, y
maxx = x
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.