blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
293e894a12b3f1064a46443f84cbfe4d0b70db6e
|
tuhiniris/Python-ShortCodes-Applications
|
/basic program/count set bits in a number.py
| 724
| 4.21875
| 4
|
"""
The program finds the number of ones in the binary representation of a number.
Problem Solution
1. Create a function count_set_bits that takes a number n as argument.
2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0.
3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n.
4. Thus the number of operations required to make n zero is the number of set bits in n.
"""
def count_set_bits(n):
count = 0
while n:
n &= n-1
count += 1
return count
n=int(input("Enter a number: "))
print(f"Number of set bits (number of ones) in number = {n} where binary of the number = {bin(n)} is {count_set_bits(n)}")
| true
|
6d7a32d214efdcef903bd37f2030ea91df771a05
|
tuhiniris/Python-ShortCodes-Applications
|
/number programs/check if a number is an Armstrong number.py
| 414
| 4.375
| 4
|
#Python Program to check if a number is an Armstrong number..
n = int(input("Enter the number: "))
a = list(map(int,str(n)))
print(f"the value of a in the program {a}")
b = list(map(lambda x:x**3,a))
print(f"the value of b in the program {b} and sum of elements in b is: {sum(b)}")
if sum(b)==n:
print(f"The number {n} is an armstrong number.")
else:
print(f"The number {n} is not an armstrong number.")
| true
|
5f4083e687b65899f292802a57f3eb9b1b64ca5a
|
tuhiniris/Python-ShortCodes-Applications
|
/basic program/program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5.py
| 295
| 4.125
| 4
|
#program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5
lower = int(input("Enter the lower range: "))
upper = int(input("Enter the upper range: "))
for i in range(lower,upper+1):
if i%7 == 0 and i%5==0:
print(i)
| true
|
7599d879058a9fca9866b3f68d93bcf2bda0001c
|
tuhiniris/Python-ShortCodes-Applications
|
/number programs/Swapping of two numbers without temperay variable.py
| 1,492
| 4.15625
| 4
|
##Problem Description
##The program takes both the values from the user and swaps them
print("-------------------------------Method 1-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a=a+b
b=a-b
a=a-b
print("After swapping First number is {0} and Second Number is {1}".format(a,b))
print("-------------------------------Method 2-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a=a*b
b=a//b
a=a//b
print("After swapping First number is {0} and Second Number is {1}".format(a,b))
print("-------------------------------Method 3-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
temp= a
a=b
b=temp
print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
print("-------------------------------Method 4-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b))
a = a ^ b
b= a ^ b
a = a ^ b
print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
| true
|
ad835b40d50ac5db87b17903ac17f79c3fc820ef
|
tuhiniris/Python-ShortCodes-Applications
|
/matrix/find the transpose of a given matrix.py
| 1,212
| 4.6875
| 5
|
print('''
Note!
Transpose of a matrix can be found by interchanging rows with the column that is,
rows of the original matrix will become columns of the new matrix.
Similarly, columns in the original matrix will become rows in the new matrix.
If the dimension of the original matrix is 2 × 3 then,
the dimensions of the new transposed matrix will be 3 × 2.
''')
matrix=[]
row=int(input('enter size of row of matrix: '))
column=int(input('enter size of column of matrix: '))
for i in range(row):
a=[]
for j in range(column):
j=int(input(f'enter elements of matrix at poistion row({i})column({j}): '))
a.append(j)
print()
matrix.append(a)
print('Elements of matrix: ')
for i in range(row):
for j in range(column):
print(matrix[i][j],end=" ")
print()
#Declare array t with reverse dimensions and is initialized with zeroes.
t = [[0]*row for i in range(column)];
#calcutaes transpose of given matrix
for i in range(column):
for j in range(row):
#converts the row of original matrix into column of transposed matrix
t[i][j]=matrix[j][i]
print('transpose of given matrix: ')
for i in range(column):
for j in range(row):
print(t[i][j],end=" ")
print()
| true
|
ae96cee9c409b9af3ee4f2cca771093eb5fd32cd
|
tuhiniris/Python-ShortCodes-Applications
|
/list/Generate Random Numbers from 1 to 20 and Append Them to the List.py
| 564
| 4.53125
| 5
|
"""
Problem Description
The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list.
Problem Solution
1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list.
4. Then print the randomised list.
4. Exit.
"""
import random
a=[]
n=int(input("Enter number of elements: "))
for i in range(n):
a.append(random.randint(1,20))
print(f"randomised list: {a}")
| true
|
4730566ea55fb752722cfb9257308de6de3ccc9c
|
tuhiniris/Python-ShortCodes-Applications
|
/recursion/Find if a Number is Prime or Not Prime Using Recursion.py
| 539
| 4.25
| 4
|
'''
Problem Description
-------------------
The program takes a number
and finds if the number is
prime or not using recursion.
'''
print(__doc__,end="")
print('-'*25)
def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print(f"Number: {n}, is not prime")
return False
else:
return check(n, div-1)
else:
print(f"Number: {n}, is a prime")
return 'True'
n=int(input("Enter number: "))
check(n)
| true
|
ef045cb0440d1fe1466a7fda39915e68db973872
|
mwnickerson/python-crash-course
|
/chapter_9/cars_vers4.py
| 930
| 4.1875
| 4
|
# Cars version 4
# Chapter 9
# modifying an attributes vales through a method
class Car:
"""a simple attempt to simulate a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""return a descriptive name of a car"""
long_name =f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""reads odometer"""
print(f"This car has {self.odometer_reading}")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value
"""
self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()
| true
|
7e79127380cc86a94a1c4c5e836b8e00158481dc
|
mwnickerson/python-crash-course
|
/chapter_7/pizza_toppings.py
| 321
| 4.28125
| 4
|
# pizza toppings
# chapter 7 exercise 4
# a conditional loop that prompts user to enter toppings
prompt ="\nWhat topping would you like on your pizza?"
message = ""
while message != 'quit':
message = input(prompt)
topping = message
if message != 'quit':
print(f"I will add {topping} to your pizza!")
| true
|
8b5ff94d3edf0eca7b35b1c67ea764816fe236aa
|
mwnickerson/python-crash-course
|
/chapter_6/cities.py
| 623
| 4.125
| 4
|
# Cities
# dictionaries inside of dictionaries
cities = {
'miami': {
'state': 'florida',
'sports team': 'hurricanes',
'attraction' : 'south beach'
},
'philadelphia': {
'state': 'pennsylvania',
'sports team': 'eagles',
'attraction': 'liberty bell'
},
'new york city': {
'state': 'new york',
'sports team': 'yankees',
'attraction': 'times square'
}
}
for city, city_info in cities.items():
print(f"\nCITY: {city.title()}")
state = city_info['state'].title()
sports_team = city_info['sports team'].title()
attraction = city_info['attraction'].title()
print(state)
print(sports_team)
print(attraction)
| false
|
1520778db31a0b825694362dea70bd80327640d9
|
mwnickerson/python-crash-course
|
/chapter_6/rivers.py
| 605
| 4.5
| 4
|
# a dictionary containing rivers and their country
# prints a sentence about each one
# prints river name and river country from a loop
rivers_0 = {
'nile' : 'egypt',
'amazon' : 'brazil',
'mississippi' : 'united states',
'yangtze' : 'china',
'rhine' : 'germany'
}
for river, country in rivers_0.items():
print(f"The {river.title()} river runs through {country.title()}")
print(f"\nThe rivers that I thought of:")
for river in rivers_0.keys():
print(river.title())
print(f"\nThe countries with rivers are:")
for country in rivers_0.values():
print(country.title())
| false
|
22bdf928b3a3d79e5dccd1361536f8fb7f0136f1
|
mwnickerson/python-crash-course
|
/chapter_5/voting_vers2.py
| 218
| 4.25
| 4
|
# if and else statement
age = 17
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
else:
print("Sorry you are too young to vote.")
print("Please register to vote as you turn 18!")
| true
|
7393500c1f9e8b7d3e3ceafce7f4e923d9111ae1
|
hangnguyen81/HY-data-analysis-with-python
|
/part02-e13_diamond/diamond.py
| 703
| 4.3125
| 4
|
#!/usr/bin/env python3
'''
Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape.
Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond.
Do this using the eye and concatenate functions of NumPy and array slicing.
'''
import numpy as np
from numpy.core.records import array
def diamond(n):
inital_array = np.eye(n, dtype=int)
half_diamond = np.concatenate((inital_array[::-1],inital_array[:,1:]), axis=1)
full_diamond = np.concatenate((half_diamond[:-1],half_diamond[::-1]), axis=0)
return full_diamond
def main():
print(diamond(4))
if __name__ == "__main__":
main()
| true
|
14f3fd6898259a53461de709e7dc409a28ba829f
|
hangnguyen81/HY-data-analysis-with-python
|
/part01-e07_areas_of_shapes/areas_of_shapes.py
| 902
| 4.15625
| 4
|
#!/usr/bin/env python3
import math
def main():
while 1:
chosen = input('Choose a shape (triangle, rectangle, circle):')
chosen = chosen.lower()
if chosen == '':
break
elif chosen == 'triangle':
b=int(input('Give base of the triangle:'))
h=int(input('Give height of the triangle:'))
area = (b * h)/2
print(f"The area is {area}")
elif chosen == 'rectangle':
w = int(input('Give width of the rectangle:'))
h = int(input('Give height of the rectangle'))
area = w * h
print(f"The area is {area}")
elif chosen == 'circle':
r = int(input('Give radius of the circle:'))
area = math.pi * r**2
print(f"The area is {area}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
| true
|
554a21528be4e8dc0ecdd9635196766071c0e4a0
|
Julian-Arturo/FundamentosTaller-JH
|
/EjercicioN9.py
| 1,323
| 4.59375
| 5
|
"""Mostrar en pantalla el promedio
de un alumno que ha cursado 5 materias
(Español, Matemáticas, Economía, Programación, Ingles)"""
#Programa que calcula el promedio de un estudiantes que cursa 5 materias
print ("Programa que calcula el promedio de un estudiantes que cursa 5 materias")
matematicas = 45
español = 39
economía = 40
programación = 50
ingles = 50
Promedio = matematicas + español + economía + programación + ingles
Resultado = Promedio/5
print ("El promedio del estudiante es de: ",Resultado)
#Julian Hernandez
#Profe, el ejercicio no estuvo muy claro, no decia a que se le sacaba promedio,
# por que me di a la tarea de hacer dos ejercicio de este.
# Quitarle la comillas al segundo para ser ejecutado. Muchas gracias
"""
print ("Programa que calcula el promedio de un estudiantes que cursa 5 materias")
matematicas1=float(input("Ingrese la nota final de matematicas: "))
español1=float(input("Ingrese la nota final de español: "))
economía1=float(input("Ingrese la nota final de economía: "))
programación1=float(input("Ingrese la nota final de programación: "))
ingles1=float(input("Ingrese la nota final de ingles: "))
Promedio = matematicas1 + español1 + economía1 + programación1 + ingles1
Resultado = Promedio/5
print ("El promedio del estudiante es de: ",Resultado)"""
#Julian Hernandez ..
| false
|
f86510558d0e668d9fc15fd0a3ff277ac93ec656
|
keerthisreedeep/LuminarPythonNOV
|
/Functionsandmodules/function pgm one.py
| 1,125
| 4.46875
| 4
|
#function
#functions are used to perform a specific task
print() # print msg int the console
input() # to read value through console
int() # type cast to int
# user defined function
# syntax
# def functionname(arg1,arg2,arg3,.................argn):
# function defnition
#---------------------------------------------------------
# function for adding two numbers
def add(n1,n2):
res=n1+n2
print(res)
#calling function by using function name
add(50,60)
#------------------------------------------------------
# function for subtracting two numbers
def sub(n1,n2):
res=n1-n2
print(res)
#calling function by using function name
sub(50,60)
#--------------------------------------------------------
# function for multiply two numbers
def mul(n1,n2):
res=n1*n2
print(product)
#calling function by using function name
product(50,60)
#--------------------------------------------------------
# function for divide two numbers
def div(n1,n2):
res=n1/n2
print(quotioent)
#calling function by using function name
quotient(50,60)
#---------------------------------------------------------
| true
|
cb1e9921d2f54d3bc3e3cb8bf67ca3e2af019197
|
mgeorgic/Python-Challenge
|
/PyBank/main.py
| 2,471
| 4.25
| 4
|
# Import os module to create file paths across operating systems
# Import csv module for reading CSV files
import csv
import os
# Set a path to collect the CSV data from the Resources folder
PyBankcsv = os.path.join('Resources', 'budget_data.csv')
# Open the CSV in reader mode using the path above PyBankiv
with open (PyBankcsv, newline="") as csvfile:
# Specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Create header row first
header = next(csvreader)
monthly_count = []
# Empty lists to store the data
profit = []
profit_change = []
# Read through each row of data after the header
for row in csvreader:
# populate the dates in column "monthly_count"
monthly_count.append(row[0])
# Append the profit information
profit.append(int(row[1]))
#Deleted unneccesary calculations bc I'll do them in print functions
#Calculate the changes in Profit over the entire period
for i in range(len(profit)):
# Calculate the average change in profits.
if i < 85:
profit_change.append(profit[i+1]-profit[i])
#Average of changes in Profit
avg_change = sum(profit_change)/len(profit_change)
# Greatest increase in profit (date and amount)
greatest_increase = max(profit_change)
greatest_index = profit_change.index(greatest_increase)
greatest_date = monthly_count[greatest_index+1]
# Greatest decrease in profit (date and amount)
greatest_decrease = min(profit_change)
lowest_index = profit_change.index(greatest_decrease)
lowest_date = monthly_count[lowest_index+1]
# Print the summary table in display
# Use f-string to accept all data types without conversion
# len counts the total amount of months in column "Monthly_Count"
# sum adds up all the profits in column "Profit"
# Round the average change to two decimals
report = f"""Financial Analysis
-----------------------
Total Months:{len(monthly_count)}
Total: ${sum(profit)}
Average Change: ${str(round(avg_change,2))}
Greatest Increase in Profits: {greatest_date} (${str(greatest_increase)})
Greatest Decrease in Profits: {lowest_date} (${str(greatest_decrease)})"""
print (report)
# Export the file to write
output_path = os.path.join('analysis','Simplified_budget_data.txt')
# Open the file using write mode while holding the contents in the file
with open(output_path, 'w') as txtfile:
# Write in this order
txtfile.write(report)
| true
|
dc56e7a5a4fa8422088b3e0cba4b78d2a86a1be3
|
roctbb/GoTo-Summer-17
|
/day 1/6_words.py
| 425
| 4.15625
| 4
|
word = input("введи слово:")
words = []
words.append(word)
while True:
last_char = word[-1]
new_word = input("тебе на {0}:".format(last_char.upper())).lower()
while not new_word.startswith(last_char) or new_word in words:
print("Неверно!")
new_word = input("тебе на {0}:".format(last_char.upper())).lower()
word = new_word
print("Следующий ход!")
| false
|
672c5c943f6b90605cf98d7ac4672316df20773a
|
vittal666/Python-Assignments
|
/Third Assignment/Question-9.py
| 399
| 4.28125
| 4
|
word = input("Enter a string : ")
lowerCaseCount = 0
upperCaseCount = 0
for char in word:
print(char)
if char.islower() :
lowerCaseCount = lowerCaseCount+1
if char.isupper() :
upperCaseCount = upperCaseCount+1
print("Number of Uppercase characters in the string is :", lowerCaseCount)
print("Number of Lowercase characters in the string is :", upperCaseCount)
| true
|
d614fd1df5ad36a1237a29c998e72af51dec2c99
|
ahmedbodi/ProgrammingHelp
|
/minmax.py
| 322
| 4.125
| 4
|
def minmax(numbers):
lowest = None
highest = None
for number in numbers:
if number < lowest or lowest is None:
lowest = number
if number > highest or highest is None:
highest = number
return lowest, highest
min, max = minmax([1,2,3,4,5,6,7,8,9,10])
print(min, max)
| true
|
7e22899c704700d2d302fed476d6237c6a0ad4c8
|
JeonWookTae/fluent_python
|
/chapter2/list_in_list.py
| 523
| 4.125
| 4
|
board = [['_']*3 for _ in range(3)]
print(board)
board[2][1] = 'X'
print(board)
# [['_', '_', '_'], ['_', '_', '_'], ['_', 'X', '_']]
# 참조를 가진 3개의 리스트가 생성된다.
board = [['_']*3]*3
print(board)
board[2][1] = 'X'
print(board)
# [['_', 'X', '_'], ['_', 'X', '_'], ['_', 'X', '_']]
l = [1,2,3]
print(id(l))
l *= 2
print(id(l))
print(l)
t = (1,2,3)
print(id(t))
t *= 2
print(id(t))
#튜플은 id가 변한다. 시퀀스가 추가되면 시퀀스 전체를 삭제후 다시 생성한다.
print(t)
| false
|
fa050769df11502c362c3f7000dae14a0373a5c9
|
jbenejam7/Ith-order-statistic
|
/insertionsort.py
| 713
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 29 18:02:06 2021
@author: djwre
"""
import random
#Function for InsertionSort
def InsertionSort(A, n):
#traverse through 1 to len(arr)
for i in range(1, n):
key = A[i]
#move elements of arr [0..i-1], that are
#greater than key, to one position ahead
#of the current position
j = i-1
while j >= 0 and key < A[j]:
A[j+1] = A[j]
j -= 1
A[j+1] = key
'''
#driver code to test above
n = 5
A = random.sample(range(1, 99), n)
InsertionSort(A, n)
for i in range(len(A)):
print ("%d" %A[i])
'''
| true
|
9a6829d0e2e6cd55e7b969674845a733a14d31d2
|
rabi-siddique/LeetCode
|
/Lists/MergeKSortedLists.py
| 1,581
| 4.4375
| 4
|
'''
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
#Created a list to store values for all list elements
arr = []
for l in lists:
while l:
arr.append(l.val)
l = l.next
#Sorting the array containing values from all lists
arr = sorted(arr)
#Creating a dummyNode which will assist in creating a sorted list
dummyNode = ListNode(0)
#head is set to the dummyNode
#this is done to return head.next which
#is the sorted list
head = dummyNode
for value in arr:
dummyNode.next = ListNode(value)
dummyNode = dummyNode.next
return head.next
| true
|
55d2c65bb61b82e52e00c2f2f768399f17e78367
|
evanmascitti/ecol-597-programming-for-ecologists
|
/Python/Homework_Day4_Mascitti_problem_2.py
| 2,766
| 4.40625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 21:16:35 2021
@author: evanm
"""
# assign raw data to variables
observed_group_1_data = [1, 4, 5, 3, 1, 5, 3, 7, 2, 2]
observed_group_2_data = [6, 7, 9, 3, 5, 7, 8, 10, 12]
combined_data = observed_group_1_data + observed_group_2_data
# define a function to compute the difference between the mean of two groups
def mean_diff(group_1, group_2):
group_1_mean = sum(group_1)/len(group_1)
group_2_mean = sum(group_2)/len(group_1)
experiment_diff = abs(group_1_mean - group_2_mean)
return(experiment_diff)
# apply the function to the observed data set
observed_difference = abs(mean_diff(group_1 = observed_group_1_data,
group_2 = observed_group_2_data))
# import the `random` library
import random
# Run the simulations by taking a random sample of half the observations from
# the whole data set. Allow the user to choose the number of simulations.
# Start the iteration number at 1
i = 1
# create an empty list that will be used to store the results of the simulations
x = []
# as user to supply number of simulations
n_simulations = int(input("How many random simulations do you want to run?"))
# Use a while loop to repeat the action as long as the iteration number
# is less than the desired number of simulations. For each iteration, append
# the list to house the mean difference for that simulation
while i <= n_simulations:
group_1 = random.sample(combined_data, len(observed_group_1_data))
group_2 = list(set(combined_data) - set(group_1))
departure = abs(mean_diff(group_1, group_2))
i += 1
x.append(departure)
# create another empty list which will be used to store whether the difference
# in the observed data set was larger than the randomly chosen data set
larger_diff_count = []
# loop over the mean of each simulation and append the list with a logical
# statement about whether it was larger or not.
for i in x:
if i >= 1:
larger_diff_count.append(True)
else:
larger_diff_count.append(False)
# The `larger_diff_count` list now contains the results of whether the observed
# difference was larger or smaller than the randomly generated data. Tally the number
# that exceeded the randomly chosen samples and print the results.
n_random_exceed = n_simulations - sum(larger_diff_count)
print("The difference betwen groups was ", round(observed_difference, 2), ".", sep="")
print("A difference at least this large occurred", n_random_exceed, "times out of", n_simulations, "simulations.")
print("p-value:", round(n_random_exceed / n_simulations, 3))
| true
|
b33973eb0714d992fdccd08ed66588930020244e
|
ckubelle/SSW567-HW1
|
/hw01triangle.py
| 2,062
| 4.125
| 4
|
import unittest
import math
def classify_triangle(a,b,c):
if a == b and b == c:
return "Equilateral"
if a == b or b == c or a == c:
if int(a*a + b*b) == int(c*c):
return "Right Isosceles"
else:
return "Isosceles"
if int(a*a + b*b) == int(c*c):
return "Right"
return "Scalene"
class TestTriangles(unittest.TestCase):
def testEquilateral(self):
self.assertEqual(classify_triangle(5,5,5),'Equilateral','5,5,5 is a Equilateral triangle')
self.assertEqual(classify_triangle(10,10,10),'Equilateral','10,10,10 is a Equilateral triangle')
def testIsosceles(self):
self.assertEqual(classify_triangle(7,7,10),'Isosceles','7,7,10 is a Isosceles triangle')
self.assertEqual(classify_triangle(10,7,10),'Isosceles','10,7,10 is a Isosceles triangle')
self.assertEqual(classify_triangle(7,10,10),'Isosceles','7,10,10 is a Isosceles triangle')
self.assertEqual(classify_triangle(15,15,15*math.sqrt(2)),'Right Isosceles','15,15,15sqrt(2) is a Right Isosceles triangle')
def testRight(self):
self.assertEqual(classify_triangle(3,4,5), 'Right', '3,4,5 is a Right Triangle')
self.assertEqual(classify_triangle(6,8,10), 'Right', '6,8,10 is a Right Triangle')
#This next test case is to show a bug in my program, that if the values are converted to ints, then small changes in lengths will still result in the same answer
self.assertEqual(classify_triangle(3.1,4,5), 'Right', '3.1,4,5 is a Right Triangle')
def testScalene(self):
self.assertEqual(classify_triangle(2,3,5), 'Scalene', '2,3,5 is a Scalene Triangle')
self.assertEqual(classify_triangle(123,234234,506786), 'Scalene', '123,234234,506786 is a Scalene Triangle')
self.assertEqual(classify_triangle(33,4123,5123123123), 'Scalene', '33,4123,5123123123 is a Scalene Triangle')
if __name__ == '__main__':
unittest.main(exit=True)
| false
|
373ecc01e393f54d7d67e3fcba648bc9bdae323f
|
Teresa-Rosemary/Text-Pre-Processing-in-Python
|
/individual_python_files/word_tokenize.py
| 880
| 4.15625
| 4
|
# coding: utf-8
import nltk
from nltk import word_tokenize
def word_tokenize(text):
"""
take string input and return list of words.
use nltk.word_tokenize() to split the words.
"""
word_list=[]
for sentences in nltk.sent_tokenize(text):
for words in nltk.word_tokenize(sentences):
word_list.append(words)
return word_list
def main():
text = """Harry Potter is the most miserable, lonely boy you can imagine. He's shunned by his relatives, the Dursley's, that have raised him since he was an infant. He's forced to live in the cupboard under the stairs, forced to wear his cousin Dudley's hand-me-down clothes, and forced to go to his neighbour's house when the rest of the family is doing something fun. Yes, he's just about as miserable as you can get."""
print (word_tokenize(text))
if __name__ == '__main__':
main()
| true
|
60154b97d18346acc13abb79f1026e4cf07f80e0
|
scott-currie/data_structures_and_algorithms
|
/data_structures/binary_tree/binary_tree.py
| 1,400
| 4.125
| 4
|
from queue import Queue
class Node(object):
""""""
def __init__(self, val):
""""""
self.val = val
self.left = None
self.right = None
def __repr__(self):
""""""
return f'<Node object: val={ self.val }>'
def __str__(self):
""""""
return str(self.val)
class BinaryTree(object):
""""""
def __init__(self, it=None):
""""""
self.root = None
if it:
for el in it:
self.insert(el)
def __repr__(self):
""""""
pass
def __str__(self):
""""""
pass
def insert(self, val):
"""Insert a new node with supplied value in the first open position, following
breadth-first traversal order.
"""
new_node = Node(val)
if self.root is None:
self.root = new_node
return
q = Queue()
q.put(self.root)
while q.full():
def breadth_first(self, func=lambda x: print(x)):
if self.root is None:
print('No root.')
return
q = Queue()
q.put(self.root)
while not q.empty():
curr = q.get()
# print(curr)
if curr.left:
q.put(q.left)
if curr.right:
q.put(q.right)
func(curr)
# print(curr.val)
| true
|
9964fcd07621271656f2ad95b8befd93f6546a54
|
scott-currie/data_structures_and_algorithms
|
/data_structures/stack/stack.py
| 1,756
| 4.15625
| 4
|
from .node import Node
class Stack(object):
"""Class to implement stack functionality. It serves as a wrapper for
Node objects and implements push, pop, and peek functionality. It also
overrides __len__ to return a _size attribute that should be
updated by any method that adds or removes nodes from the stack.
"""
def __init__(self, _iterable=None):
"""Initialize a stack.
param: _iterable: Optional list that can be used to seed the stack.
"""
self.top = None
self._size = 0
if not _iterable:
_iterable = []
if type(_iterable) is not list:
raise TypeError('Iterable must be list type.')
for value in _iterable:
self.push(value)
def __len__(self):
"""Override __len__ builtin to return _size. Methods extending the class
that push or pop nodes need to update _size accordingly.
return: _size: an int representing the number of nodes in the stack
"""
return self._size
def push(self, val):
"""Create a new node with data value and push onto stack."""
node = Node(val)
node._next = self.top
self.top = node
self._size += 1
def pop(self):
"""Remove the top node from the stack and return it.
return: Node object that was previously top of the stack
"""
if self.top:
node = self.top
self.top = node._next
self._size -= 1
return node
return None
def peek(self):
"""Return the top node.
return: Node object that is currently top of the stack
"""
if self.top:
return self.top
return None
| true
|
134ad277c30c6f24878f0e7d38c238f147196a64
|
scott-currie/data_structures_and_algorithms
|
/challenges/array_binary_search/array_binary_search.py
| 788
| 4.3125
| 4
|
def binary_search(search_list, search_key):
"""Find the index of a value of a key in a sorted list using
a binary search algorithm. Returns the index of the value if
found. Otherwise, returns -1.
"""
left_idx, right_idx = 0, len(search_list) - 1
# while True:
while left_idx <= right_idx:
mid_idx = (right_idx + left_idx) // 2
# search_key is left of middle value
if search_key < search_list[mid_idx]:
right_idx = mid_idx - 1
# search key is right of middle value
elif search_key > search_list[mid_idx]:
left_idx = mid_idx + 1
else:
return mid_idx
# If we get here, the value was not found.
return -1
if __name__ == '__main__':
binary_search([1, 2, 3], 4) == -1
| true
|
16f21ae65b3d5e3aba3f44decb5a1a4c556c95a5
|
scott-currie/data_structures_and_algorithms
|
/challenges/multi-bracket-validation/multi_bracket_validation.py
| 900
| 4.25
| 4
|
from stack import Stack
def multi_bracket_validation(input_str):
"""Parse a string to determine if the grouping sequences within it are
balanced.
param: input_str (str) string to parse
return: (boolean) True if input_str is balanced, else False
"""
if type(input_str) is not str:
raise TypeError('Input must be of type str')
openers = ('[', '{', '(')
opposites = {']': '[', '}': '{', ')': '('}
stack = Stack()
for c in input_str:
# Push symbol if it's an opener
if c in openers:
stack.push(c)
if c in opposites.keys():
# If it's an opener, but its opposite isn't on the stack, return False
if stack.pop().val != opposites[c]:
return False
# If we get here, and the top is None, all symbols found opposites
if stack.top is None:
return True
return False
| true
|
d46fc6f5940512ae2764ba93f4ad59d920ea16c4
|
rentheroot/Learning-Pygame
|
/Following-Car-Game-Tutorial/Adding-Boundries.py
| 2,062
| 4.25
| 4
|
#learning to use pygame
#following this tutorial: https://pythonprogramming.net/displaying-images-pygame/?completed=/pygame-python-3-part-1-intro/
#imports
import pygame
#start pygame
pygame.init()
#store width and height vars
display_width = 800
display_height = 600
#init display
gameDisplay = pygame.display.set_mode((display_width,display_height))
#name window
pygame.display.set_caption('A bit Racey')
#define rgb colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
#tell program where right side of car is
car_width = 73
#set the game's clock
clock = pygame.time.Clock()
#load the car image
carImg = pygame.image.load('racecar.png')
#function to place car on display
#blit draws car to screen
def car(x,y):
gameDisplay.blit(carImg, (x,y))
#make main game loop
def game_loop():
#define x and y for car
x = (display_width * 0.45)
y = (display_height * 0.8)
#define x_change
x_change = 0
#game not exited
gameExit = False
#run until game exits
while not gameExit:
#log game events
for event in pygame.event.get():
#if user exits window
if event.type == pygame.QUIT:
crashed = True
#print out user actions
print(event)
#move the car
#check for keydown event
if event.type == pygame.KEYDOWN:
#check if left arrow key
if event.key == pygame.K_LEFT:
#change x variable by -5
x_change = -5
#check if right arrow key
elif event.key == pygame.K_RIGHT:
#change x variable by 5
x_change = 5
#check if key is released
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
#make x variable 0
x_change = 0
#move car along x axis
x += x_change
#make everything currently in the game white
gameDisplay.fill(white)
#put car in postition
car(x,y)
#check if car has hit edge of window
if x > display_width - car_width or x <0:
gameExit = True
#update display
pygame.display.update()
#run at 60 fps
clock.tick(60)
#run main game loop
game_loop()
#quit game
pygame.quit()
quit()
| true
|
49fe160812ab26303e82a2bead21905940f5e626
|
lpizarro2391/HEAD-FIRST-PYTHON
|
/vowels3.py
| 331
| 4.15625
| 4
|
vowels=['a','e','i','o','u']
word=input("Provide a word to searh for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
for vowel in found:
print(vowel)
found={}
for k in sorted (found):
print(k,'was found', found[k],'time(s).')
| false
|
a0e4c3feb2b27548e37c583aa5c091110329d73a
|
logan-ankenbrandt/LeetCode
|
/RemoveVowels.py
| 1,043
| 4.21875
| 4
|
def removeVowels(s: str) -> str:
"""
1. Goal
- Remove all vowels from a string
2. Example
- Example #1
a. Input
i. s = "leetcodeisacommunityforcoders"
b. Output
i. "ltcdscmmntyfcfgrs"
- Example #2
a. Input
i. s = "aeiou"
b. Output
i. ""
3. Implementation
- Steps
a. Initialize a list of the characters in the
s string and a list of the vowels
b. Iterate through the values in the vowels list,
c. Write a while loop that will remove the vowels
while they are still in the vowels list
"""
s_arr = list(s)
vowels = list("aAeEiIoOuU")
for vowel in vowels:
while vowel in s_arr:
s_arr.remove(vowel)
return ''.join(s_arr)
print(removeVowels("leetcodeisacommunityforcoders"))
| true
|
e696cb31e3dd97c552b6b3206798e74a29027b0d
|
logan-ankenbrandt/LeetCode
|
/MajorityElement.py
| 1,072
| 4.40625
| 4
|
from collections import Counter
from typing import List
def majorityElement(self, nums: List[int]) -> int:
"""
1. Goal
a. Return the most frequent value in a list
2. Examples
a. Example #1
- Input
i. nums = [3, 2, 3]
- Output
i. 3
3. Implementation
a. Summary
- Use counter to count the frequency, find the max
of the values in the dict, loop through the dict,
if a value equals the max value, return the key
b. Steps
- Count the frequency of the numbers in the list
w the Counter() module and set it to a variable
- Set the max of the values to a variable
- Loop through the items in the dictionary
- Write a conditional to check if the values in the dict
are equal to the max
- If it does, return the key
"""
c = Counter(nums)
m = max(c.values())
for key, values in c.items():
if values == m:
return key
| true
|
150c6c8f6e603b1ab89367e04150829b11c31df3
|
logan-ankenbrandt/LeetCode
|
/MostCommonWord.py
| 1,404
| 4.125
| 4
|
from typing import List
from collections import Counter
import re
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
"""
1. Goal
- Return the most common word in a string that is not banned
2. Examples
- Example #1
a. Input
i. paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.",
banned = ["hit"]
b. Output
i. "ball"
3. Implementation
- Steps
a. Convert all of the characters in the paragraph string to
lowercase and set it to the varaible p
b. Use the re module to find only words in the p string
c. Initialize a Counter() variable to count the frequency of words in the list
d. Loop through the words in the banned array
i. If it is in the dictionary, delete it
e. Return the key with the greatest value in the dictionary
- Summary
a. Use the re module to find only words, loop through a counter dictionary
to remove the banned words, return the key with the greatest value
"""
p = paragraph.lower()
l = re.findall(r'[\w]+', p)
c = Counter(l)
for i in banned:
if i in c:
del c[i]
return max(c, key=c.get)
| true
|
441be31aa36e6c446bc891e5cb84e0ee9abdb924
|
logan-ankenbrandt/LeetCode
|
/CountSubstrings.py
| 1,979
| 4.28125
| 4
|
import itertools
import snoop
@snoop
def countSubstrings(s: str) -> int:
"""
1. Goal
- Count the number of substrings that are palindromes.
2. Examples
- Example #1
a. Input
i. "abc"
b. Output
i. 3
c. Explanation
- The palindromes are "a", "b", and "c".
3. Implementation
- Steps
a. Initialize a count variable
b. Loop over the indexes of the string
c. Set two variables, left and right, to the indexes
d. Write a function that:
i. Contains a while loop that:
- Runs while
a. Left is greater than 0 and right is less
than the length of the string
b. And the value at the left index is equal to
the value at the right index
c. This ensures that it is a palindrome
- Increments the count variable by 1
- Decrements left variable to the left by 1
a. This is to ensure that the left index
is always less than the right index
- Increments right variable to the right by 1
i. Set the l variable to the index and set the r variable
to the index plus one
e. Return the count variable
- Summary
a. Each char in str as middle and expand outwards,
do same for pali of even len; maybe read up on manachers
alg
"""
count = 0
for i in range(len(s)):
count += countPalindrome(s, i, i)
count += countPalindrome(s, i, i + 1)
return count
def countPalindrome(s, l, r):
count = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count
print(countSubstrings("abc"))
| true
|
a3ae007c55ee2cfe220cd9094b4eaa38822ded38
|
CountTheSevens/dailyProgrammerChallenges
|
/challenge001_easy.py
| 803
| 4.125
| 4
|
#https://www.reddit.com/r/dailyprogrammer/comments/pih8x/easy_challenge_1/
# #create a program that will ask the users name, age, and reddit username. have it tell them the information back,
#in the format: your name is (blank), you are (blank) years old, and your username is (blank)
#for extra credit, have the program log this information in a file to be accessed later.
name = input("What is your name? ")
age = input("How old are you? ")
if age is not int:
age = input("Please enter a numeric value for your age. ")
redditName = input("What's your Reddit username? ")
f = open('challenge001_easy_output.txt', 'a')
print('Your name is', name,', you\'re', age, 'years old, and your Reddit username is', redditName, '.')
out = name,age, redditName
f.write(str(out))
f.write('\n')
f.close()
| true
|
199cc666d97a3fdc6e1afc98ec06c33f005ae051
|
iSkylake/Algorithms
|
/Tree/ValidBST.py
| 701
| 4.25
| 4
|
# Create a function that return True if the Binary Tree is a BST or False if it isn't a BST
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def valid_BST(root):
inorder = []
def traverse(node):
nonlocal inorder
if not node:
return
traverse(node.left)
inorder.append(node.val)
traverse(node.right)
traverse(root)
if sorted(inorder) == inorder:
return True
else:
return False
a = Node(5)
b = Node(2)
c = Node(7)
d = Node(4)
e = Node(9)
a.left = b
a.right = c
c.left = d
c.righ = e
print(valid_BST(a))
a = Node(5)
b = Node(2)
c = Node(7)
d = Node(4)
e = Node(9)
a.left = b
b.right = d
a.right = c
c.righ = e
print(valid_BST(a))
| true
|
7c6895415c7f493062c06626e567fa32c3e66928
|
iSkylake/Algorithms
|
/Array/Merge2Array.py
| 735
| 4.15625
| 4
|
# Given two sorted arrays, merge them into one sorted array
# Example:
# [1, 2, 5, 7], [3, 4, 9] => [1, 2, 3, 4, 5, 7, 9]
# Suggestion:
# Time: O(n+m)
# Space: O(n+m)
from nose.tools import assert_equal
def merge_2_array(arr1, arr2):
result = []
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
while i < len(arr1):
result.append(arr1[i])
i += 1
while j < len(arr2):
result.append(arr2[j])
j += 1
return result
class Merge_2_Array(object):
def test(self, func):
assert_equal(func([1, 5, 7, 8], [2, 3, 4, 10]), [1, 2, 3, 4, 5, 7, 8, 10])
print("TEST PASSED")
t = Merge_2_Array()
t.test(merge_2_array)
| false
|
92803502bd1d37d5c73015816ba141e760938491
|
iSkylake/Algorithms
|
/Linked List/LinkedListReverse.py
| 842
| 4.15625
| 4
|
# Function that reverse a Singly Linked List
class Node:
def __init__(self, val=0):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def append(self, val):
new_node = Node(val)
if self.length == 0:
self.head = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
# First Attempt
def reverse_list(node):
previous = None
current = node
next_node = node.next
while current != None:
current.next = previous
previous = current
current = next_node
if current != None:
next_node = current.next
# Cleaner
def reverse_list(node):
previous = None
current = node
next_node = node.next
while current != None:
next_node = current.next
current.next = previous
previous = current
current = next_node
| true
|
0824e7d93385a87358503bc289e984dfeae38f8c
|
hShivaram/pythonPractise
|
/ProblemStatements/EvenorOdd.py
| 208
| 4.4375
| 4
|
# Description
# Given an integer, print whether it is Even or Odd.
# Take input on your own
num = input()
# start writing your code from here
if int(num) % 2 == 0:
print("Even")
else:
print("Odd")
| true
|
7f77696fcdae9a7cef174f92cb12830cde16b3cb
|
hShivaram/pythonPractise
|
/ProblemStatements/AboveAverage.py
| 1,090
| 4.34375
| 4
|
# Description: Finding the average of the data and comparing it with other values is often encountered while analysing
# the data. Here you will do the same thing. The data will be provided to you in a list. You will also be given a
# number check. You will return whether the number check is above average or no.
#
# ----------------------------------------------------------------------
# Input:
# A list with two elements:
# The first element will be the list of data of integers and
# The second element will be an integer check.
#
# Output:
# True if check is above average and False otherwise
# Take input here
# we will take input using ast sys
import ast
from functools import reduce
input_str = input()
input_list = ast.literal_eval(input_str)
# Remember how we took input in the Alarm clock Question in previous Session?
# Lets see if you can finish taking input on your own
data = input_list[0]
check = input_list[1]
s = 0
# start writing your code to find if check is above average of data
s = int(reduce(lambda x, y: x + y, data))
avg = s / len(data)
print(check > avg)
| true
|
5b54d69790c6d524c1b253b8bec1c32ad83c4bf8
|
LoktevM/Skillbox-Python-Homework
|
/lesson_011/01_shapes.py
| 1,505
| 4.25
| 4
|
# -*- coding: utf-8 -*-
# На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику,
# которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д.
#
# Функция рисования должна принимать параметры
# - точка начала рисования
# - угол наклона
# - длина стороны
#
# Функция-фабрика должна принимать параметр n - количество сторон.
import simple_draw as sd
def get_polygon(n):
def draw_shape(point, angle, length):
v_first = sd.get_vector(start_point=point, angle=angle, length=length, width=3)
sd.line(v_first.start_point, v_first.end_point, width=3)
v_next = v_first
for i in range(n - 1):
if i != n - 2:
v_next = sd.get_vector(start_point=v_next.end_point, angle=angle + (360 / n) * (i + 1),
length=length,
width=3)
sd.line(v_next.start_point, v_next.end_point, width=3)
else:
sd.line(v_next.end_point, v_first.start_point, width=3)
return draw_shape
draw_triangle = get_polygon(n=8)
draw_triangle(point=sd.get_point(200, 200), angle=13, length=100)
sd.pause()
| false
|
63a055bb9ee454b6c6ad68defb6b540b6cb74323
|
Hosen-Rabby/Guess-Game-
|
/randomgame.py
| 526
| 4.125
| 4
|
from random import randint
# generate a number from 1~10
answer = randint(1, 10)
while True:
try:
# input from user
guess = int(input('Guess a number 1~10: '))
# check that input is a number
if 0 < guess < 11:
# check if input is a right guess
if guess == answer:
print('Correct, you are a genius!')
break
else:
print('Hey, are you insane! I said 1~10')
except ValueError:
print('Please enter number')
| true
|
233b8e8cc6295adad5919285230971a293dfde80
|
abhaydixit/Trial-Rep
|
/lab3.py
| 430
| 4.1875
| 4
|
import turtle
def drawSnowFlakes(depth, length):
if depth == 0:
return
for i in range(6):
turtle.forward(length)
drawSnowFlakes(depth - 1, length/3)
turtle.back(length)
turtle.right(60)
def main():
depth = int(input('Enter depth: '))
drawSnowFlakes(depth, 100)
input('Close the graphic window when done.')
turtle.mainloop()
if __name__ == '__main__':
main()
| true
|
51558f22e5262038813d7f4ce3e5d2ad2836e6d9
|
Creativeguru97/Python
|
/Syntax/ConditionalStatementAndLoop.py
| 1,372
| 4.1875
| 4
|
#Condition and statement
a = 300
b = 400
c = 150
# if b > a:
# print("b is greater than a")
# elif a == b:
# print("a and b are equal")
# else:
# print("a is greater than b")
#If only one of statement to excute, we can put togather
# if a == b: print("YEAHHHHHHHHH !!!!!!!!!!!")
# print("b is greater than a") if b > a else print("a is greater than b")
#or
print("b is greater than a") if b > a else print("a and b are equal") if a == b else print("a is greater than b")
# if a > b and c > a:
# print("Both condtions are true!!!!!")
# if a > b or c > a:
# print("one of the condtions are true!!!!!")
fruits = ["apple", "banana", "cherry"]
# for x in fruits:
# print(x)
#
# for x in "apple":
# print(x)
#
# for x in fruits:
# print(x)
# if x == "banana":
# break
#
# for x in fruits:
# if x == "banana":
# break
# print(x)
# for x in fruits[0:2]:# Specify the range in the list
# print(x)
#With continue statement, we can skip the iteration and go next
# for x in fruits:
# if x == "banana":
# continue
# print(x)
#Specify the range
fruits2 = ["apple", "banana", "cherry", "berry", "melon", "grape"]
# for x in range(4): # 0 - 3
# print(x)
#
# for x in range(2, 9): # 2 - 8
# print(x)
#
# for x in range(2, 30, 3): #Specify the increment value by adding a third parameter
| false
|
d988912a14c4fe3d6bb41458d10898d6cddc991a
|
fairypeng/a_python_note
|
/leetcode/977有序数组的平方.py
| 825
| 4.1875
| 4
|
#coding:utf-8
"""
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
示例 2:
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
提示:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return sorted([i*i for i in A])
s = Solution()
A = [-4,-1,0,3,10]
print(s.sortedSquares(A))
| false
|
663ac97205d487837d27cd973cb1a91bdf9b8702
|
Antoniel-silva/ifpi-ads-algoritmos2020
|
/Fabio 2b/Questão 7.py
| 1,890
| 4.25
| 4
|
#7. As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe
#contrataram para desenvolver o programa que calculará os reajustes. Escreva um algoritmo que leia o
#salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
#o salários até R$ 280,00 (incluindo) : aumento de 20%
#o salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
#o salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
#o salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
#· o salário antes do reajuste;
#· o percentual de aumento aplicado;
#· o valor do aumento;
#· o novo salário, após o aumento.
#entradas
salario = float(input("Digite o salário do colaborador: "))
if salario <= 280:
novo_salario = salario + (salario * .2)
print(f'O salario antes do reajuste é {salario}')
print('O percentual de aumento foi de 20%')
print(f'O aumento foi de {novo_salario - salario}')
print(f'O novo salario é: {novo_salario}')
elif salario > 280 and salario <= 700:
novo_salario = salario + (salario * .15)
print(f'O salario antes do reajuste é {salario}')
print('O percentual de aumento foi de 15%')
print(f'O aumento foi de {novo_salario - salario}')
print(f'O novo salario é: {novo_salario}')
elif salario > 700 and salario <= 1500:
novo_salario = salario + (salario * .10)
print(f'O salario antes do reajuste é {salario}')
print('O percentual de aumento foi de 10%')
print(f'O aumento foi de {novo_salario - salario}')
print(f'O novo salario é: {novo_salario}')
elif salario > 1500:
novo_salario = salario + (salario * .05)
print(f'O salario antes do reajuste é {salario}')
print('O percentual de aumento foi de 5%')
print(f'O aumento foi de {novo_salario - salario}')
print(f'O novo salario é: {novo_salario}')
| false
|
9921976bf20825da1a5ce71bf4ba52d01ee5f106
|
Antoniel-silva/ifpi-ads-algoritmos2020
|
/App celular.py
| 2,066
| 4.15625
| 4
|
def main():
arquivo = []
menu = tela_inicial()
opcao = int(input(menu))
while opcao != 0:
if opcao == 1:
listacel = cadastrar()
arquivo.append(listacel)
elif opcao == 2:
lista = listar(arquivo)
print(lista)
elif opcao == 3:
print("Voce selecionou a busca por celulares cadastrados!")
a = str(input("Digite uma palavra chave: "))
for a in arquivo[0]["marca"] == True:
print(a)
else:
print("""
Essa opção não é válida!
________________________
""")
input("Precione enter e continue a execução. . . ")
opcao = int(input(menu))
def tela_inicial():
menu = "<<<<<<<<<< App Celular >>>>>>>>>>\n"
print()
menu += '1 - Cadastre um novo modelo de celular\n'
menu += '2 - Lista todos os modelos cadastrados\n'
menu += '3 - Fazer busca nos celulares cadastrados\n'
menu += '0 - para sair\n'
menu += 'Digite sua opção: '
return menu
def cadastrar():
listacell = {}
print()
print("Voce selecionou cadastro de novos celulares!")
print()
marca = str(input("Digite a fabricante do dispositivo: "))
modelo = str(input("Digite o modelo do dispositivo: "))
tela = str(input("Digite o tamaho da tela do dispositivo: "))
valor = float(input("Digite quanto custa o dispositivo: "))
listacell["Marca"] = marca
listacell["Modelo"] = modelo
listacell["Tela"] = tela
listacell["Valor"] = valor
#arquivo.append(listacell)
print("Dados gravados com sucesso!")
return listacell
def listar(tamanho):
print()
print("Foram localizados", len(tamanho), "cadastros!")
print()
print("<<<<<Mostrando lista de dispositivos cadastrados>>>>>")
print()
for i in tamanho:
print(i)
print()
main()
| false
|
4bb55dfeb2640ca2ba99d32ff68d1c1440126898
|
Antoniel-silva/ifpi-ads-algoritmos2020
|
/Fabio 2b/Questão 13.py
| 1,567
| 4.21875
| 4
|
#13. Faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
#a) "Telefonou para a vítima ?"
#b) "Esteve no local do crime ?"
#c) "Mora perto da vítima ?"
#d) "Devia para a vítima ?"
#e) "Já trabalhou com a vítima ?"
#O algoritmo deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa
#responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como
#"Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
#entradas
contador = 0
pergunta1 = str(input("Telefonou para a vítima ? "))
pergunta2 = str(input("Esteve no local do crime ? "))
pergunta3 = str(input("Mora perto da vítima ? "))
pergunta4 = str(input("Devia para a vítima ? "))
pergunta5 = str(input("Já trabalhou com a vítima ? "))
if pergunta1 == "s" and pergunta2 == "s" and pergunta3 == "s" and pergunta4 == "s" and pergunta5 == "s":
print("Assassino")
elif pergunta1 == "s" and pergunta2 == "s":
print("Suspeita")
elif pergunta2 == "s" and pergunta3 == "s":
print("Suspeita")
elif pergunta1 == "s" and pergunta3 == "s":
print("Suspeita")
elif pergunta3 == "s" and pergunta4 == "s":
print("Suspeita")
elif pergunta4 == "s" and pergunta5 == "s":
print("Suspeita")
elif pergunta3 == "s" and pergunta5 == "s":
print("Suspeita")
elif pergunta1 == "s" and pergunta5 == "s":
print("Suspeita")
elif pergunta1 == "s" and pergunta4 == "s":
print("Suspeita")
| false
|
373d5194589ea6da392963fa046cb8478a9d52c4
|
yegeli/Practice
|
/第16章/threading_exercise02.py
| 483
| 4.15625
| 4
|
"""
使用Thread子类创建进程
"""
import threading
import time
class SubThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "子线程" + self.name + "执行,i=" + str(i)
print(msg)
if __name__ == "__main__":
print("------主进程开始-------")
t1 = SubThread()
t2 = SubThread()
t1.start()
t2.start()
t1.join()
t2.join()
print("------主进程结束-------")
| false
|
df273e0b1a4ec97f7884e64e0fe1979623236fb2
|
bdjilka/algorithms_on_graphs
|
/week2/acyclicity.py
| 2,108
| 4.125
| 4
|
# Uses python3
import sys
class Graph:
"""
Class representing directed graph defined with the help of adjacency list.
"""
def __init__(self, adj, n):
"""
Initialization.
:param adj: list of adjacency
:param n: number of vertices
"""
self.adj = adj
self.size = n
self.clock = 1
self.post = [0 for _ in range(n)]
self.visited = [0 for _ in range(n)]
def previsit(self):
self.clock += 1
def postvisit(self, v):
self.post[v] = self.clock
self.clock += 1
def explore(self, v):
self.visited[v] = 1
self.previsit()
for u in self.adj[v]:
if not self.visited[u]:
self.explore(u)
self.postvisit(v)
def deepFirstSearch(self):
"""
Visits all nodes and marks their post visit indexes. Fills list post[].
"""
for v in range(self.size):
if not self.visited[v]:
self.explore(v)
def acyclic(self):
"""
Checks whether graph has edge in that post visit index of source vertex is less than its end vertex post index.
If such edge exists than graph is not acyclic.
:return: 1 if there is cycle, 0 in other case.
"""
self.deepFirstSearch()
for v in range(self.size):
for u in self.adj[v]:
if self.post[v] < self.post[u]:
return 1
return 0
if __name__ == '__main__':
"""
Input sample:
4 4 // number of vertices n and number of edges m, 1 <= n, m <= 1000
1 2 // edge from vertex 1 to vertex 2
4 1
2 3
3 1
Output:
1 // cycle exists: 3 -> 1 -> 2 -> 3
"""
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
graph = Graph(adj, n)
print(graph.acyclic())
| true
|
4b3922cdedf4f4c7af87235b94af0f763977b191
|
nguyenl1/evening_class
|
/python/labs/lab23final.py
| 2,971
| 4.25
| 4
|
import csv
#version 1
# phonebook = []
# with open('lab23.csv') as file:
# read = csv.DictReader(file, delimiter=',')
# for row in read:
# phonebook.append(row)
# print(phonebook)
#version2
"""Create a record: ask the user for each attribute, add a new contact to your contact list with the attributes that the user entered."""
# phonebook = []
# while True:
# name = input("Enter your name. ")
# fav_fruit = input("Enter your your favorite fruit. ")
# fav_color = input("Enter your your favorite color. ")
# phonebook.append({
# 'name': name,
# 'fav fruit': fav_fruit,
# 'fav color': fav_color})
# with open('lab23.csv', 'a') as csv_file:
# writer = csv.writer(csv_file, delimiter = ',')
# row = [name,fav_fruit,fav_color]
# writer.writerow(row)
# cont = input("Want to add another? Y/N ")
# if cont != "Y":
# break
# print(phonebook)
"""Retrieve a record: ask the user for the contact's name, find the user with the given name, and display their information"""
# phonebook = []
# with open('lab23.csv') as file:
# read = csv.DictReader(file, delimiter=',')
# for row in read:
# phonebook.append(row)
# print(phonebook)
# user_input = input("Please enter the name of the person you would information of. ").lower()
# for row in phonebook:
# if row['name'] == user_input:
# print(row)
"""Update a record: ask the user for the contact's name, then for which attribute of the user they'd like to update and the value of the attribute they'd like to set."""
# phonebook = []
# with open('lab23.csv') as file:
# read = csv.DictReader(file, delimiter=',')
# for row in read:
# phonebook.append(row)
# print(phonebook)
# user_input = input("Please enter the name of the person you would information of. ").lower()
# for i in phonebook:
# if i['name'] == user_input:
# print(i)
# break
# att = input("Which attribute would you like to update? (name, fav fruit, fav color) ")
# change = input("What would you like to update it to? ")
# if att == "name":
# i["name"] = change
# print (i)
# elif att == "fav fruit":
# i["fav fruit"] = change
# print (i)
# elif att == "fav color":
# i['fav color'] = change
# print (i)
# else:
# print("Try again")
""" Delete a record: ask the user for the contact's name, remove the contact with the given name from the contact list. """
# phonebook = list()
# user_input = input("Please enter the name of the person you would like to delete ").lower()
# with open('lab23.csv', 'r') as file:
# read = csv.reader(file)
# for row in read:
# phonebook.append(row)
# for i in row:
# if i == user_input:
# phonebook.remove(row)
# with open('lab23.csv', 'w') as writeFile:
# writer = csv.writer(writeFile)
# writer.writerows(phonebook)
| false
|
3bd0c70f91a87d98797984bb0b17502eac466972
|
nguyenl1/evening_class
|
/python/labs/lab18.py
| 2,044
| 4.40625
| 4
|
"""
peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right.
valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right.
peaks_and_valleys - uses the above two functions to compile a single list of the peaks and valleys in order of appearance in the original data.
# """
data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9]
noindex= [0, 1, 2, 3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13,14,15,16,17,18,19,20]
def peaks():
length = len(data)
middle_index = length//2
first_half = data[:middle_index]
second_half = data[middle_index:]
# peak = first_half.index('P')
peak = data.index(max(first_half))
peak_2 = data.index(max(second_half))
print(f"The index of the peak on the left is {peak}")
print(f"The index of the peak on the right is {peak_2}")
# peaks()
def valleys():
valleys = []
for i in noindex[1:]:
if data[i] <= data[i-1] and data[i] <= data[i+1]:
valleys.append(i)
# return valleys
print(f"The indices of the valleys are {valleys}")
# valleys()
def peaks_and_valleys():
peaks()
valleys()
peaks_and_valleys()
def p_v():
for i in data:
print ("x" * i)
p_v()
#jon's ex:
"""
def get_data():
data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9]
return data
def get_valleys(data):
valleys = []
index_list = list(range(len(data)))
for i in index_list:
if (i-1) in index_list and (i+1) in index_list: # makes the index start at 1 so the indexing is not out of range?
if data[i] <= data[i-1] and data[i] <= data[i+1]:
valleys.append(i)
return valleys
def get_peaks(data):
peaks = []
index_list = list(range(len(data)))
for i in index_list:
if (i-1) in index_list and (i+1) in index_list:
if data[i] >= data [i-1] and data [i] >= data [i+1]:
peaks.append(i)
return peaks
"""
| true
|
39c5729b31befc2a988a0b3ac2672454ae99ea9a
|
krsatyam20/PythonRishabh
|
/cunstructor.py
| 1,644
| 4.625
| 5
|
'''
Constructors can be of two types.
Parameterized/arguments Constructor
Non-parameterized/no any arguments Constructor
__init__
Constructors:self calling function
when we will call class function auto call
'''
#create class and define function
class aClass:
# Constructor with arguments
def __init__(self,name,id):
self.name=name
self.id=id
#print(self.id)
#print(self.name)
#simple function
def show(self):
print("name=%s id= %d "%(self.name,self.id))
#call a class and passing arguments
obj=aClass("kumar",101)
obj2=aClass("rishave",102)
obj.show()
obj2.show()
#second ExAMPLE
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
#creates the object of the class Student
s = Student("John",101,22)
#s = Student() TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'age'
print("*************befoer set print***********")
print(getattr(s,'name'))
print(getattr(s,'id'))
print(getattr(s,'age'))
print("**********After set print***********")
setattr(s,'age',23)
print(getattr(s,'age'))
setattr(s,'name','kumar')
print(getattr(s,'name'))
# Constructor - non parameterized
print("************ Non parameters ***********")
class Student:
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
#student.show("Kuldeep")
| true
|
f2744631653064a83857180583c831b187a8f53c
|
TiwariSimona/Hacktoberfest-2021
|
/ajaydhoble/euler_1.py
| 209
| 4.125
| 4
|
# List for storing multiplies
multiplies = []
for i in range(10):
if i % 3 == 0 or i % 5 == 0:
multiplies.append(i)
print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
| true
|
16ad6fbbb5ab3f9a0e638a1d8fd7c4469d349c11
|
TiwariSimona/Hacktoberfest-2021
|
/parisheelan/bmi.py
| 957
| 4.15625
| 4
|
while True:
print("1. Metric")
print("2. Imperial")
print("3. Exit")
x=int(input("Enter Choice (1/2/3): "))
if x==1:
h=float(input("Enter height(m) : "))
w=float(input("Enter weight(kg) : "))
bmi=w/h**2
print("BMI= ",bmi)
if bmi<=18.5:
print("Underweight")
elif bmi>=25:
if bmi>=30:
print("Obese")
else:
print("Overweight")
else:
print("Normal")
elif x==2:
h=float(input("Enter height(in) : "))
w=float(input("Enter weight(lbs) : "))
bmi=(w*703)/h**2
print("BMI= ",bmi)
if bmi<=18.5:
print("Underweight")
elif bmi>=25:
if bmi>=30:
print("Obese")
else:
print("Overweight")
else:
print("Normal")
elif x==3:
break
else:
print("wrong input")
| false
|
0211584a0d5087701ee07b79328d4eb6c101e962
|
pintugorai/python_programming
|
/Basic/type_conversion.py
| 438
| 4.1875
| 4
|
'''
Type Conversion:
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
str(x)
Converts object x to a string representation.
eval(str)
Evaluates a string and returns an object.
tuple(s)
Converts s to a tuple.
list(s)
Converts s to a list.
set(s)
Converts s to a set.
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
and So on
'''
x="5"
xint = int(x);
print("xint = ",xint)
| true
|
3597f00172708154780a6e83227a7930e034d166
|
csu100/LeetCode
|
/python/leetcoding/LeetCode_225.py
| 1,792
| 4.5
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/31 10:37
# @Author : Zheng guoliang
# @Version : 1.0
# @File : {NAME}.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode-cn.com/problems/implement-stack-using-queues/
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
2.实现过程:
"""
from queue import Queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = Queue()
def push(self, x):
"""
Push element x onto stack.
"""
if self.stack.empty():
self.stack.put(x)
else:
temp = Queue()
temp.put(x)
while not self.stack.empty():
temp.put(self.stack.get())
while not temp.empty():
self.stack.put(temp.get())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
"""
if self.stack.empty():
raise AttributeError("stack is empty!")
return self.stack.get()
def top(self):
"""
Get the top element.
"""
if self.stack.empty():
raise AttributeError("stack is empty!")
a=self.stack.get()
self.push(a)
return a
def empty(self):
"""
Returns whether the stack is empty.
"""
return True if self.stack.empty() else False
if __name__ == '__main__':
mystack = MyStack()
print(mystack.empty())
for i in range(4):
mystack.push(i * i)
print(mystack.empty())
while not mystack.empty():
print(mystack.pop())
| true
|
0768a12697cd31a72c3d61ecfa4eda9a1aa0751e
|
csu100/LeetCode
|
/python/leetcoding/LeetCode_232.py
| 1,528
| 4.46875
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/31 17:28
# @Author : Zheng guoliang
# @Version : 1.0
# @File : {NAME}.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode-cn.com/problems/implement-queue-using-stacks/submissions/
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
2.实现过程:
"""
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self._myqueue = []
def push(self, x):
"""
Push element x to the back of queue.
"""
if len(self._myqueue) < 1:
self._myqueue.append(x)
else:
temp = self._myqueue[::-1]
temp.append(x)
self._myqueue = temp[::-1]
def pop(self):
"""
Removes the element from in front of queue and returns that element.
"""
if len(self._myqueue) < 1:
raise AttributeError("queue is empty!")
return self._myqueue.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if len(self._myqueue) < 1:
raise AttributeError("queue is empty!")
return self._myqueue[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return True if len(self._myqueue) < 1 else False
| false
|
d57b48fe6ebac8c1770886f836ef17f3cadf16c7
|
alma-frankenstein/Grad-school-assignments
|
/montyHall.py
| 1,697
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#to illustrate that switching, counterintuitively, increases the odds of winning.
#contestant CHOICES are automated to allow for a large number of test runs, but could be
#changed to get user input
import random
DOORS = ['A', 'B', 'C']
CHOICES = ["stay", "switch"]
def main():
num_runs = 100
monty(num_runs)
def monty(num_runs):
switchAndWin = 0 #times winning if you switch
stayAndWin = 0 #times winning if you stay
runs = 0
while runs <= num_runs:
prize = random.choice(DOORS)
picked_door = random.choice(DOORS)
#Monty open a door that was neither chosen nor containing the prize
for door in DOORS:
if door != prize and door != picked_door:
openedDoor = door
break
#the contestant can either stay with picked_door or switch to the other unopened one
stayOrSwitch = random.choice(CHOICES )
if stayOrSwitch == "stay":
final = picked_door
if final == prize:
stayAndWin += 1
else: #switch
for door in DOORS:
if door != openedDoor and door != picked_door:
final = door
if final == prize:
switchAndWin += 1
break
runs += 1
percentSwitchWin = (switchAndWin/num_runs) * 100
percentStayWin = (stayAndWin/num_runs) * 100
print("Odds of winning if you stay: " + str(percentStayWin))
print("Odds of winning if you switch: " + str(percentSwitchWin))
if __name__ == '__main__':
main()
| true
|
8b8644a5fbc3a44baff3a5ad1156c5a644b60f56
|
drod1392/IntroProgramming
|
/Lesson1/exercise1_Strings.py
| 1,026
| 4.53125
| 5
|
## exercise1_Strings.py - Using Strings
#
# In this exercise we will be working with strings
# 1) We will be reading input from the console (similar to example2_ReadConsole.py)
# 2) We will concatenate our input strings
# 3) We will convert them to upper and lowercase strings
# 4) Print just the last name from the "name" variable
# 5) EXTRA - Use proper capitalization on first and last name
print("Section 1 - Read input\n")
# Prompt the user to enter first and last name seperately
# Use two input() commands to read first and last name seperately.
# Use variable names "first" and "last" to store your strings
print("\nSection 2 - Concatenate")
# Concatenate first and last name together in variable "name"
# Print out the result
print("\nSection 3 - Upper and Lower")
# Print "name" in all uppercase
# Print "name" in all lowercase
print("\nSection 4 - Only Last Name")
# Print just the last name from "name"
print("\nSection 5 - Capitalization")
# Extra - use proper capitalization on first and last name
| true
|
df9cea82395dfc4c540ffe7623a0120d2483ea9e
|
imyogeshgaur/important_concepts
|
/Python/Exercise/ex4.py
| 377
| 4.125
| 4
|
def divideNumber(a,b):
try:
a=int(a)
b=int(b)
if a > b:
print(a/b)
else:
print(b/a)
except ZeroDivisionError:
print("Infinite")
except ValueError:
print("Please Enter an Integer to continue !!!")
num1 = input('Enter first number')
num2 = input('Enter second number ')
divideNumber(num1,num2)
| true
|
2d95e7c4a3ff636c2ec5ff400e43d273bc479f48
|
akshitha111/CSPP-1-assignments
|
/module 22/assignment5/frequency_graph.py
| 829
| 4.40625
| 4
|
'''
Write a function to print a dictionary with the keys in sorted order along with the
frequency of each word. Display the frequency values using “#” as a text based graph
'''
def frequency_graph(dictionary):
if dictionary == {'lorem': 2, 'ipsum': 2, 'porem': 2}:
for key in sorted(dictionary):
print(key, "-", "##")
elif dictionary == {'This': 1, 'is': 1, 'assignment': 1, '3': 1,\
'in': 1, 'Week': 1, '4': 1, 'Exam': 1}:
for key in sorted(dictionary):
print(key, "-", "#")
elif dictionary == {'Hello': 2, 'world': 1, 'hello': 2, 'python': 1, 'Java': 1, 'CPP': 1}:
for key in sorted(dictionary):
print(key, "-", dictionary[key])
def main():
dictionary = eval(input())
frequency_graph(dictionary)
if __name__ == '__main__':
main()
| true
|
a5c6578d3af315b00a5f2c2278d8f3ab1ef969a0
|
edgeowner/Python-Basic
|
/codes/3_2_simple_calculator.py
| 679
| 4.34375
| 4
|
error = False
try:
num1 = float(input("the first number: "))
except:
print("Please input a number")
error = True
try:
num2 = float(input("the second number: "))
except:
print("Please input a number")
error = True
op = input("the operator(+ - * / **):")
if error:
print("Something Wrong")
else:
if num2 == 0 and op == '/':
print("The division can't be 0")
elif op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
elif op == '**':
print(num1 ** num2)
else:
print("Unknown Operator")
| false
|
e51964055f7eea8dc2c8a3d38601dd48aacf7bc1
|
edgeowner/Python-Basic
|
/codes/2_exercise_invest.py
| 211
| 4.1875
| 4
|
money = float(input("How much money"))
month = float(input("How many months"))
rate = float(input("How much rate"))
rate = rate / 100
total = money * (1 + rate) ** month
interest = total - money
print(interest)
| false
|
f0995f652df181115268c78bbb649a6560108f47
|
ciciswann/interview-cake
|
/big_o.py
| 658
| 4.25
| 4
|
''' this function runs in constant time O(1) - The input could be 1 or 1000
but it will only require one step '''
def print_first_item(items):
print(items[0])
''' this function runs in linear time O(n) where n is the number of items
in the list
if it prints 10 items, it has to run 10 times. If it prints 1,000 items,
we have to print 1,000 times'''
def print_all_items(items):
for item in items:
print(item)
''' Quadratic time O(n^2)'''
def print_all_possible_ordered_pairs(items):
for first_item in items:
for second_item in items:
print(first_item, second_item)
print_all_possible_ordered_pairs([0,6,8,9])
| true
|
29a21b7d3b694268ebc6362f1dc4bb044c2b3883
|
luispaulojr/cursoPython
|
/semana_01/aula01/parte02_condicionais.py
| 309
| 4.1875
| 4
|
"""
Estrutura de decisão
if, elseif(elif) e else
"""
# estrutura composta
idade = 18
if idade < 18:
print('Menor de idade')
elif idade == 18:
print('Tem 18 anos')
elif idade < 90:
print('Maior de 18 anos')
else:
print('Já morreu')
# switch case
# https://www.python.org/dev/peps/pep-0634/
| false
|
a39d746b7b7b615e54c0266aba519956a96c492c
|
luispaulojr/cursoPython
|
/semana_02/aula/tupla.py
| 871
| 4.40625
| 4
|
"""
Tuplas são imutáveis
arrays - listas são mutáveis
[] utilizado para declaração de lista
() utilizado para declaração de tupla
"""
"""
# declaração de uma tupla utilizando parenteses
"""
tupla1 = (1, 2, 3, 4, 5, 6)
print(tupla1)
"""
# declaração de uma tupla não utilizando parenteses
"""
tupla2 = 1, 2, 3, 4, 5, 6
print(type(tupla2))
"""
# a tupla pode ser heterogêneco
"""
tupla3 = (4, 'senac')
print(type(tupla3[0]))
print(type(tupla3[1]))
print(type(tupla3))
# desempacotamento
tupla4 = 'Curso de python', 'para os melhores professores'
curso, elogio = tupla4
print(curso)
print(elogio)
"""
# a tupla pode ser heterogêneco
"""
tupla5 = (1, 2, 3, 4, 5, 6)
print(sum(tupla5))
print(max(tupla5))
print(min(tupla5))
print(len(tupla5))
"""
# a tupla pode ser incrementada
"""
tupla6 = 23, 10, 2021
tupla6 += 'Python',
print(tupla6)
| false
|
d0249ae72e0a0590cffda71a48c5df0993d1ee18
|
zongxinwu92/leetcode
|
/CountTheRepetitions.py
| 788
| 4.125
| 4
|
'''
Created on 1.12.2017
@author: Jesse
''''''
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.
You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.
Example:
Input:
s1="acb", n1=4
s2="ab", n2=2
Return:
2
"
'''
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.