blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
76e97fc42db60802575bb4b9be80a7499298d26e | Ankitpahuja/LearnPython3.6 | /Tutorials - Examples/GUI - Tkinter/boilerplate.py | 1,170 | 4.4375 | 4 | import tkinter as tk
window = tk.Tk()
window.title("Tkinter's Tutorial")
window.geometry("550x400")
# Label
title = tk.Label(text="Hello World. Welcome to tkinter's tutorial!", font=("Times New Roman",20))
title.grid(column=0,row=0)
#Button1
button1 = tk.Button(text="Click Me!", bg="red")
button1.grid(column=0,row=1)
#Entry Field
entry_field1 = tk.Entry()
entry_field1.grid(column=0, row=2)
#Text Field
text_field = tk.Text(master=window, height=10, width=30)
text_field.grid()
# mainloop() fundtion called with windows; it runs everything inside that window. Make sure this function is at the last.
window.mainloop()
'''
Following are the steps you need to follow in ordert to build an app using tkinter:
0. Plan out layout of app
1. Create a window for the app (Add title and geometry)
2. Declare Size, Place labels, buttons, entry fields etc. on the window (Use grids to place them!)
3. Place Labels, buttons, entry fields, onto the window!
4. Connect buttons/entries to one another through functions
5. Use .mainloop() to run the window!
'''
''' More resources can be found at: http://effbot.org/tkinterbook/ '''
| true |
dfe339423b83149a43710cbf6eef8ad51cb9c1e9 | pavanvittanala/Coding_programs | /uniformity.py | 1,475 | 4.15625 | 4 | ''' ----->>>>> PROBLEM STATEMENT <<<<<----- '''
''' You are given a string that is formed from only three characters ‘a’, ‘b’, ‘c’. You are allowed to change atmost ‘k’ characters in the given string while attempting to optimize the uniformity index.
Note : The uniformity index of a string is defined by the maximum length of the substring that contains same character in it.
Input
The first line of input contains two integers n (the size of string) and k. The next line contains a string of length n.
Output
A single integer denoting the maximum uniformity index that can be achieved.
Constraints
1 <= n <= 10^6
0 <= k <= n
String contains only ‘a’, ‘b’, ‘c’.
Sample Input 0
6 3
abaccc
Sample Output 0
6
Explanation
First 3 letters can be changed to ‘c’ and we can get the string ‘cccccc’ '''
''' ----->>>>> SOLUTION: <<<<<---- '''
n,k=map(int,input("\n 6 3").split())
st=input("Enter a string:")
c1,c2,c3=st.count("a"),st.count("b"),st.count("c")
if c1 <=c2:
if c2<=c3 and c1+c2 <=k:
st=st.replace("a","c")
st=st.replace("b","c")
elif c2>c3 and c1+c3<=k:
st=st.replace("a","b")
st=st.replace("c","b")
else:
print("K is Wrong, for given input")
elif c1 <= c3:
st=st.replace("a","c")
st=st.replace("b","c")
else:
st=st.replace("b","a")
st=st.replace("c","a")
print("Final String :",st)
| true |
eccaf13f1f46e435b9547ecffe26c55e63108852 | atseng202/ic_problems | /queues_and_stacks/queue_with_two_stacks/queue_two_stacks.py | 1,371 | 4.125 | 4 | class Stack(object):
def __init__(self):
# """Initialize an empty stack"""
self.items = []
def push(self, item):
# """Push a new item onto the stack"""
self.items.append(item)
def pop(self):
# """Remove and return the last item"""
# If the stack is empty, return None
# (it would also be reasonable to throw an exception)
if not self.items:
return None
return self.items.pop()
def peek(self):
# """Return the last item without removing it"""
if not self.items:
return None
return self.items[-1]
class QueueTwoStacks(object):
# Implement the enqueue and dequeue methods
def __init__(self):
# Enqueue and dequeue using two stacks
self.push_stack = Stack()
self.pop_stack = Stack()
def enqueue(self, item):
# if the push stack has any items, then enqueue onto it
# if self.push_stack.peek():
self.push_stack.push(item)
def dequeue(self):
if not self.push_stack.peek() and not self.pop_stack.peek():
raise ValueError("Cannot dequeue from empty queue")
if self.pop_stack.peek():
first_item = self.pop_stack.pop()
return first_item
else:
# nothing in the pop_stack so we need to look into push stack
if not self.push_stack.peek():
return None
while self.push_stack.peek():
item_to_move = self.push_stack.pop()
self.pop_stack.push(item_to_move)
return self.pop_stack.pop()
| true |
63a9ad33825620de6667c0d694471fbe8e939149 | Garima-sharma814/The-faulty-calculator | /faultycalculator.py | 1,596 | 4.3125 | 4 | # faulty calculator
# Design a calculator which will correctly solve all the problems except the following ones:
# if the combination of number contain 56 and 9 it will give you 77 as the answer no matter what operation your perform
# same for 45 and 3 , 56 and 6
# Your program should take operator and two numbers as input from the user and then return the result
a = int(input("Enter the first number: ")) # First number input
b = int(input("Enter the second number: ")) # second Number input
# select the operation
print("Please choose the Arithematic operation you want to perform")
c = input(" Press + for addition\n Press - for subtraction\n Press * for multiplication\n Press / for divide\n Your selection is: ")
# faults in the program
if a == 56 and b == 9 or b == 56 and a == 9: # First Fault
print("The answer is 77")
elif a == 45 and b == 3 or b == 45 and a == 3: # Second Fault
print("The answer is 555")
elif a == 56 and b == 6 or b == 56 and a == 6: # third fault
print("The answer is 4")
# correct calculations
elif c == "+": # Addition
print("The addition is ", a+b)
elif c == "-": # subtraction
if(a > b):
print("The subtraction is", a-b)
else:
print("ERROR")
elif c == "*": # Multiplication
print("The Multiplication is", a*b)
elif c == "/": # Division
print("The division is", a/b)
else:
# If you have not choosen the operator among the mentioned
print("Invalid Operator")
| true |
ce9b53ac17bff836d778e08c55000090e9a3b1c3 | MAD-reasoning/Python-Programming | /Elementry/Elementry_04.py | 324 | 4.28125 | 4 | # Write a program that asks the user for a number and prints the sum of the numbers 1 to number.
try:
num_sum = 0
number = int(input("Enter a natural number: "))
for i in range(1, number+1):
num_sum += i
except ValueError:
print("Enter a valid number")
else:
print("Sum = ", num_sum)
| true |
e376359a4434b559d8b9e7845b1a9aa428429d71 | GuilhermeBiavati/Trabalho-python | /2.py | 389 | 4.1875 | 4 | # Recebe nome e armazena na variavel
nome = input('Informe o nome: ')
# Transforma string para maiusculo, e substitui as vogais pelos caracteres requiridos
retorno = nome.upper().replace('A', '@').replace('E', '&').replace('I',
'!').replace('O', '#').replace('U', '*')
# Retorno dos resultados
print(nome)
print(retorno)
| false |
e29ff540a0375f255ae163e88d222460ee72e8d9 | jay-bhamare/Python_for_Everybody_Specialization_University_of_Michigan | /PY4E_Python_Data_Structures/Assignment 8.4.py | 996 | 4.1875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: jayvant
#
# Created: 08/04/2020
# Copyright: (c) jayvant 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
# Assignment 8.4
# Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
# The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
# When the program completes, sort and print the resulting words in alphabetical order.
# You can download the sample data at http://www.py4e.com/code3/romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
for i in line.split():
if not i in lst:
lst.append(i)
lst.sort()
print (lst)
| true |
6be03d03fa0505d440baa4a07c9726fb6c752644 | TuhinChandra/PythonLearning | /Basics/Shaswata/test2_video8_Variables.py | 889 | 4.53125 | 5 | print('Variables examples are here...')
x = 10
# Anything in python is an Object unlike other languages
print('x=', x, sep='')
print('type of x :', type(x))
print('id of x :', id(x))
y = 15
print('y=', y, sep='')
print('id of y :', id(y))
# Now see the id of y will change to id of x
y = 10
print('# Now see the id of y has changed to id of x')
print('y=', y, sep='')
print('id of y :', id(y))
# Objects are immutable in python
x = x + 1
print('# Objects are immutable in python thus it would change its id to new')
print('x=', x, sep='')
print('id of x :', id(x))
print('y=', y, sep='')
print('id of y :', id(y))
# Variables of any type can be changed to any other at any time
x = 3.5
print('# Variables of any type can be changed to any other at any time')
print('x=', x, sep='')
print('type of x :', type(x))
x = 'It\'s a String'
print('x=', x, sep='')
print('type of x :', type(x))
| true |
89d6cc60549a3807b8736670d0b28bd12e298f4f | TuhinChandra/PythonLearning | /Basics/Shaswata/test9_video17_relationalOperator.py | 314 | 4.25 | 4 | print('Relational operator examples are here...')
x = 10
y = 5
print('Type of relational operator results :', type(x > y))
print('x > y (True):', x > y)
print('x < y (False):', x < y)
print('x >= y (True):', x >= y)
print('x <= y (False):', x <= y)
print('x == y (False):', x == y)
print('x != y (True):', x != y)
| false |
6e1ebc1b1f077968f102c31e157e7d1af37a0e3a | TuhinChandra/PythonLearning | /Basics/Shaswata/test5_video12_intFunc.py | 599 | 4.375 | 4 | print('int function examples are here...')
x = '1100'
print("x =", x)
print("type of x :", type(x))
# int string -> int
print('int string -> int')
y = int(x) # default base is 10
print("y =", y)
print("type of y :", type(y))
# binary string -> int
print('binary string -> int')
z = int(x, 2)
print("z =", z)
# ValueError: invalid literal for int() with base 2: '1234'
x = '12347'
print("x =", x)
# y = int(x, 2)
# Oct string -> int
print('Oct string -> int')
y = int(x, 8)
print("y =", y)
# Hex string -> int
print('Hex string -> int')
x = '1a'
print("x =", x)
y = int(x, 16)
print("y =", y)
| false |
66858c07ada89061322b79ebf6898778d2bce2b8 | aricaldoni/band-name-generator | /main.py | 390 | 4.28125 | 4 | #Welcome message
print("Welcome to the authomatic Band Name generator.")
#Ask the user for the city that they grew up in
city = input("What city did you grow up in?: \n")
#Ask the user for the name of a pet
pet = input("What is the name of your pet: \n")
#Combine the name of their city and pet and show them their band name.
print("The suggested name for your Band is "+ city + " " + pet)
| true |
5c90d207ec78f0c29467ad3e5f7a66bca9d21e44 | JaredJWoods/CIS106-Jared-Woods | /ses8/PS8p5 [JW].py | 1,144 | 4.1875 | 4 | def incomeTax(gross):
if gross >= 500001:
rate = 0.30
print("You are in the highest tax bracket with a 30% federal income tax rate.")
elif gross >= 200000 and gross <= 500000:
rate = 0.20
print("You are in the middle tax bracket with a 20% federal income tax rate.")
else:
rate = 0.15
print("You are in the lowest tax bracket with a 15% federal income tax rate.")
taxOwed = float(gross * rate)
return rate, taxOwed
#------------------program starts here-------------------
print("Would you like me to calculate your federal income tax?")
choice = str(input("Type 'yes' or 'no': "))
while choice == "yes":
print("Thank you for selecting yes.")
gross = float(input("Please enter your gross income: $"))
print()
print("You entered a gross income of $",gross)
rate, taxOwed = incomeTax(gross)
percent = int (rate*100)
print("You have a tax rate of",percent,"%")
print("The amount of tax you owe is: $",taxOwed)
print()
choice = input("Would you like to compute your income tax again? Enter 'yes' or 'no': ")
print("Thank you for using our income tax calculator. Good bye.")
| true |
28cde805af45660b4d1f69504a1f709f5a9d28a9 | sofiacavallo/python-challenge | /PyBank/Drafts/homework_attempt_4.py | 2,126 | 4.1875 | 4 | # Reading / Processing CSV
# Dependencies
import csv
import os
# Files to load and output
budget_data = "budget_data.csv"
budget_analysis = "budget_analysis.txt"
# Read the csv and convert it into a list of dictionaries
with open(budget_data) as budget_data:
reader = csv.reader(budget_data)
# Read the header row
header = next(reader)
# Initialize a variable called total_months (count of all month values in the CSV)
total_months = 0
# Initialize a variable called net_total (sum of all postive/negative 'profit/loss' values in the CSV)
net_total = 0
# First row advances reader by one line. Otherwise % change comp with 0, mathematical error.
first_row = next(reader)
# Initialize variable for previous row.
previous_row = int(first_row[1])
# Define list called Net Change list
net_change_list = []
#Count total number of months in the data sets. Also the unique values in first column after the header. NOTE: row[1] is the 'Profit/Loss' value, and it is a STRING, thus needing a conversion. int() converts whatever is passed into to an integer
for row in reader:
total_months = total_months + 1
#Calculate net total of profits and losses
net_total = net_total + int(row[1])
#Calculate changes in profits/losses over period. First track the net change. Keep moving prev row forward.
net_change = int(row[1]) - previous_row
previous_row = int(row[1])
net_change_list = net_change_list + [net_change]
# Calculate average percent change
averageChange = sum(net_change_list) / len(net_change_list)
# Print out the data points of interest as the final budget analysis
print("Financial Analysis")
print("-------------------")
print("Total Months: ", {total_months})
print("Total: ", {net_total})
print("Average Change: ", {averageChange})
print("Greatest Increase in Profits: ", {max(net_change_list)})
print("Greatest Decrease in Profits: ", {min(net_change_list)})
# Write the output .txt file
f= open("budget_analysis.txt","w+") | true |
67a4705ab7e55c17de86ac966540fb552e4b645c | qaespence/Udemy_PythonBootcamp | /6_Methods_and_Functions/Homework.py | 2,178 | 4.4375 | 4 |
# Udemy course - Complete Python Bootcamp
# Section 6 Homework Assignment
# Write a function that computes the volume of a sphere given its radius
def vol(rad):
return (4.0/3)*(3.14159)*(rad**3)
print(vol(2))
# Write a function that checks whether a number is in a given range
# (Inclusive of high and low)
def ran_check(num,low,high):
if num in range(low,high+1):
print(f'The number {num} is between {low} and {high}.')
else:
print(f'The number {num} is outside the range of {low} and {high}.')
def ran_bool(num,low,high):
return num in range(low,high+1)
ran_check(3,1,10)
print(ran_bool(3,1,10))
# Write a Python function that accepts a string and calculate the number
# of upper case letters and lower case letters
def up_low(s):
lower_chars = 0
upper_chars = 0
for char in s:
if char.isupper():
upper_chars += 1
if char.islower():
lower_chars += 1
print(f'Original String : {s}')
print(f'No. of Upper case characters : {upper_chars}')
print(f'No. of Lower case characters : {lower_chars}')
up_low('Hello Mr. Rogers, how are you this fine Tuesday?')
# Write a Python function thay takes a list and returns a new list with
# unique elements of the first list
def unique_list(l):
unique_list = []
for num in l:
if num not in unique_list:
unique_list.append(num)
return unique_list
print(unique_list([1,1,1,1,2,2,3,3,3,3,4,5]))
# Write a Python function to multiple all the numbers in a list
def multiply(numbers):
result = 1
for num in numbers:
result *= num
return result
print(multiply([1,2,3,-4]))
# Write a Python function that checks whether a passed string is a
# palindrome or not
def palindrome(s):
words = s.split()
combined = "".join(words).lower()
return combined == combined[::-1]
print(palindrome('helleh'))
# Write a Python function to check whether a string is a pangram or not
import string
def ispangram(str, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str.lower())
print(ispangram("The quick brown fox jumps over the lazy dog"))
| true |
5948ceed31db511b3ec6894e8c76e9a3f80f9865 | lynnvmara/CIS106-Lynn-Marasigan | /Session 5/Extra Credit.py | 935 | 4.21875 | 4 | print("What is your last name?")
name = input()
print("How many hours?")
hours = int(input())
print("What is your rate per hour?")
rate = int(input())
if hours > 40:
print(name + "'s regular pay for the first 40 hours is $" + str(rate) + " per hour for a total of $" + str(40 * rate) + ". The " + str(hours - 40) + " hours of overtime have an overtime pay of $" + str(rate * 1.5) + " per hour for a total of $" + str((hours - 40) * (rate * 1.5)) + ".")
print(name + "'s gross pay is $" + str((40 * rate) + ((hours - 40) * (rate * 1.5))) + " for $" + str(rate) + " per hour over " + str(hours) + " hours.")
else:
print(name + "'s regular pay is $" + str(rate) + " per hour for a total of $" + str(hours * rate) + ". " + name + " did not work any overtime, so " + name + " gets $0 for 0 hours of overtime.")
print(name + "'s gross pay is $" + str(hours * rate) + " for $" + str(rate) + " per hour over " + str(hours) + " hours.") | true |
c25c418679ffdeb532dffb1409fbfe486167ca5a | lynnvmara/CIS106-Lynn-Marasigan | /Session 7/Assignment 2.py | 237 | 4.125 | 4 | print("What is the starting value?")
start = int(input())
print("What is the stop value?")
stop = int(input())
print("What is the increment value?")
increment = int(input())
while start <= stop:
print(start)
start = start + increment | true |
34c244ca5ffea4bd647dd29bc2eb7bccfa436db8 | radunm/jobeasy-algorithms-course | /HW_1.py | 1,789 | 4.1875 | 4 | # Sum of 3 modified
# Rewrite a program with any number of digits.
# Instead of 3 digits, you should sum digits up from n digits number,
# Where User enters n manually. n > 0
from random import randint
min_rand = 1
max_rand = "9"
result = 0
digit = int(input("Please, enter digit: "))
digit -= 1
while digit > 0:
min_rand *= 10
max_rand += "9"
digit -= 1
max_rand = int(max_rand)
random_number = randint(min_rand, max_rand)
print(f'Random number {random_number}')
while random_number > 0:
result = result + (random_number % 10)
random_number = random_number // 10
print(f"Sum: {result}")
# Find max number from 3 values, entered manually from a keyboard
one = int(input("Enter first digit: "))
two = int(input("Enter second digit: "))
three = int(input("Enter third digit: "))
def compare(x, y, z):
if x > y:
if x > z:
return x
else:
return z
else:
if y > z:
return y
else:
return z
print(f"You enter {one}, {two}, {three}")
print(f"Max number {compare(one, two, three)}")
# Count odd and even numbers. Count odd and even digits of the whole number. E.g, if entered number 34560,
# then 3 digits will be even (4, 6, and 0) and 2 odd digits (3 and 5).
digit = abs(int(input("Enter whole number: ")))
odd = []
even = []
countodd = 0
counteven = 0
if digit != 0:
while digit > 0:
temp = digit % 10
if temp % 2 == 0:
even.append(temp)
counteven += 1
else:
odd.append(temp)
countodd += 1
digit = digit // 10
else:
even.append(digit)
counteven += 1
even.reverse()
odd.reverse()
print(f"Number consist of {counteven} even digits {even} and {countodd} odd {odd}.")
| true |
dada4202db884cbeb2c19042d26089564d2fb435 | MorKalo/L10_HomeWork20-10-21 | /Targil 9.py | 1,155 | 4.1875 | 4 | #ייצר את הפונקציות הבאות: div, mul, sub, add
#פונקציות אלו צריכות לקבל שני פרמטרים y, x .כל אחת מהן צריכה לחשב את הפעולה המתמטית שהיא מייצגת ולהחזיר את התוצאה
#כעת קלוט שני מספרים מהמשתמש )באמצעות input ,)קרא לארבעת הפונקציות שכתבת והדפסאת מה שהן החזירו
#default ל- y, x אשר הוא אפס
#add=חיבור
def getDiv(x=0,y=0): #div=חילוק
div=x/y
return div
def getMul (x=0, y=0): #multiplication=כפל
mul=x*y
return mul
def getSub(x=0, y=0): #Subtraction=חיסור
sub=x-y
return sub
def getAdd(X=0, Y=0): #add=חיבור
add=x+y
return add
x=int(input('plz enetr a number for x: '))
y=int(input('plz enter a number for y: '))
print(f'the result of division x({x}) in y({y}) is {getDiv(x,y)}')
print(f'the result of multifunction x({x}) with y({y}) is {getMul(x,y)}')
print(f'the result of subtraction x({x}) in y({y}) is {getSub(x,y)}')
print(f'the result of add x({x}) with y({y}) is {getAdd(x,y)}') | false |
998649baa7285122e041cdaf4a5dfbe984bc7c86 | vishnuap/Algorithms | /Chapter-03-Arrays/Zip-It/Zip-It.py | 1,449 | 4.875 | 5 | # Chapter-3: Arrays
# Zip-It
# 1. Create a function that accepts two arrays and combines their values sequentially into a new array at alternating indices starting with the first array. Extra values of either array should be included afterwards. Given [1,2] and [10,20,30], return [1,10,2,20,30]
# 2. Combine the two arrays in the same way but in the first array instead of creating a new array
# Assume the arguments being passed are both arrays
# Assume use of built in functions (for doing this without builtin functions, use the approach from the Array-Insert-At solution earlier in this chapter)
# 1
def zipIt(arr1, arr2):
result = []
length = len(arr1) + len(arr2)
for i in range(0, length):
if i < len(arr1):
result.append(arr1[i])
if i < len(arr2):
result.append(arr2[i])
return result
# 2
def zipIt2(arr1, arr2):
arr1Len = len(arr1)
arr2Len = len(arr2)
idx = 0
while (len(arr1) < arr1Len + arr2Len):
if (idx < arr1Len):
arr1.insert((idx * 2) + 1, arr2[idx])
else:
arr1.insert(len(arr1), arr2[idx])
idx += 1
myArr1 = [1,2,3,4,5]
myArr2 = [10,20,30,40,50]
print("The original arrays are {} and {}").format(myArr1, myArr2)
print("The zipped array is {}").format(zipIt(myArr1, myArr2))
print("The zipped array is {}").format(zipIt(myArr2, myArr1))
zipIt2(myArr1, myArr2)
print("The zipped array is {}").format(myArr1)
| true |
c847c6634e70a105c0fd65c0f83619e55e07937f | vishnuap/Algorithms | /Chapter-01-Fundamentals/You-Say-Its-Your-Birthday/You-say-its-your-Birthday.py | 385 | 4.21875 | 4 | # Chapter-1: Fundamentals
# You-say-its-your-Birthday:
# If 2 given numbers represent your birth month and day in either order, log "How did you know?", else log "Just another day..."
myBDate = [3, 6]
def bd(num1, num2):
if num1 in myBDate and num2 in myBDate:
print("How did you know?")
else:
print("Just another day...")
bd(1, 2)
bd(3, 6)
bd(6, 3)
bd(5 ,4) | true |
56c6b7dc97ec4603e5ab899bd72463ba3b15db7f | vishnuap/Algorithms | /Chapter-03-Arrays/Array-Nth-Largest/Array-Nth-Largest.py | 2,588 | 4.40625 | 4 | # Chapter-3: Arrays
# Array-Nth-Largest
# Given 'arr' and 'N', return the Nth largest element, where N-1 elements are larger. Return null if needed
# Assume the arguments are an array with integers and an integer and both are passed to the function
# Since we want Nth largest such that N-1 elements are larger, if there are duplicates in the array, then Nth largest will not necessarily be the Nth element from the last in a sorted-in-ascending-order array. Hence the sorted array will have to be looped through to find the Nth largest element
import math
def nthLargest(arr, num):
if num > len(arr):
return None
sortedArray = sort(arr)
length = len(sortedArray)
max = sortedArray[-1]
count = 1
for i in range(length - 2, -1, -1):
if (sortedArray[i] < max):
if count == num - 1:
return sortedArray[i]
else:
max = sortedArray[i]
count += 1
return None
# I am implementing a Radix sort. Currently works with only positive integers
# Will use push() built-in function
def sort(arr):
buckets = [] # empty array to hold the intermediate values
bucketLen = 0 # length of each bucket
bucketIdx = 0
length = len(arr)
div = 10
curSize = 0
maxSize = 0
iter = 0
# Find the maximum number of digits comprising any element in the array. That will decide how many iterations we go into
for i in range(0, length):
curSize = int(math.log10(arr[i])) + 1
maxSize = maxSize if maxSize > curSize else curSize
# Now iterate over the array to sort it. per Wikipedia, I am doing an LSD radix sort (least significant digit)
while iter < maxSize:
# create the empty buckets
buckets = [[] for i in range(0,10)]
# Populate the buckets
for i in range(0, length):
# Find the lest significant digit to sorton. With each iteration, this moves 1 digit to the left
bucketIdx = (arr[i] % div) / (div / 10)
buckets[bucketIdx].append(arr[i])
# Reset the array.
arr = []
# Write contents of buckets back into array
for i in range(0, 10):
for j in range(0, len(buckets[i])):
arr.append(buckets[i][j])
# increment the divisor
div *= 10
# increment the iteration count
iter += 1
# return the sorted array
return arr
myArr = [42, 1, 4, 72, 42, 72, 42, 72]
myNum = 4
print("The Nth largest in {} where N = {} is {}").format(myArr, myNum, nthLargest(myArr, myNum))
| true |
3dc49d530e386fd3b266e007bc640f34d7046ef2 | vishnuap/Algorithms | /Chapter-01-Fundamentals/Always-Hungry/Always-Hungry.py | 489 | 4.1875 | 4 | # Chapter-1: Fundamentals
# Always-Hungry
# Create a function that accepts an array and prints "yummy" each time one of the values is equal to "food". If no array element is "food", then print "I'm hungry" once
# Assume the argument passed is an array
def yummy(arr):
hungry = 1
for i in range(0, len(arr)):
if arr[i] == 'food':
hungry = 0
print("Yummy")
if hungry:
print("I'm hungry")
myArr = ['I', 'food', 'to', 'food']
yummy(myArr)
| true |
93cb895cbc0a72249e25dac5489153f304dcac91 | vishnuap/Algorithms | /The-Basic-13/Print-Ints-and-Sum-0-255/Print-Ints-and-Sum-0-255.py | 260 | 4.28125 | 4 | # The Basic 13
# Print-Ints-and-Sum-0-255
# Print integers from 0 to 255. With each integer print the sum so far
def printIntsSum():
sum = 0
for i in range(0, 256):
sum += i
print("{} - Sum so far = {}").format(i, sum)
printIntsSum()
| true |
23355dd307a13236d38a8bde6571435771f8f1c2 | vishnuap/Algorithms | /Chapter-03-Arrays/Array-Nth-to-Last/Array-Nth-to-Last.py | 453 | 4.46875 | 4 | # Chapter-3: Arrays
# Array-Nth-to-Last
# Return the element that is N from array's end. Given ([5,2,3,6,4,9,7], 3), return 4. If the array is too short return null
# Assume the arguments are an array and an integer and both are passed
def nthToLast(arr, num):
return None if num > len(arr) else arr[-1 * num]
myArr = [5,2,3,6,4,9,7]
myNum = 3
print("Th element that is {} from the last in {} is {}").format(myNum, myArr, nthToLast(myArr, myNum))
| true |
2dee4ac13bfc34d72b3a4bb04d199ab8be5de782 | vishnuap/Algorithms | /Chapter-01-Fundamentals/What-Really-Happened/What-Really-Happened.py | 1,334 | 4.15625 | 4 | # Chapter-1: Fundamentals
# What-really-Happened
# (refer to Poor Kenny for background)
# Kyle notes that the chance of one disaster is totally unrelated to the chance of another. Change whatHappensToday() to whatReallyHappensToday(). In this new function test for each disaster independantly instead of assuming exactly one disaster will happen. In other words, in this new function, all five might occur today or none. Maybe kenny will survive!!
# Assume the probabilities of disasters from the Poor-Kenny question
# 10% chance of volcano, 15% chance of tsunami, 20% chance of earthquake, 25% chance of blizzard and 30% chance of meteor strike
import random as rd
def whatReallyHappensToday():
rVol = int(rd.random() * 20)
rTsu = int(rd.random() * 20)
rEqu = int(rd.random() * 20)
rBli = int(rd.random() * 20)
rMet = int(rd.random() * 20)
none = 1
if rVol >= 0 and rVol <= 1:
print("Volcano")
none = 0
if rTsu >= 0 and rTsu <= 2:
print("Tsunami")
none = 0
if rEqu >= 0 and rEqu <= 3:
print("Earthquake")
none = 0
if rBli >= 0 and rBli <= 4:
print("Blizzard")
none = 0
if rMet >= 0 and rMet <= 5:
print("Meteor Strike")
none = 0
if none:
print("Nothing Happens Today")
whatReallyHappensToday()
| true |
c86a6295b69a14f635b5433edd3ad9f1b6044ca6 | vishnuap/Algorithms | /Chapter-04-Strings-AssociativeArrays/Drop-the-Mike/drop-the-mike.py | 997 | 4.25 | 4 | # Create a function that accepts an input string, removes leading and trailing white spaces (at beginning and ending only), capitalizes the first letter of every word and returns the string. If original string contains the word Mike anywhere, immediately return "stunned silence" instead. Given " tomorrow never dies ", return "Tomorrow Never Dies". Given " Watch Mike and Mike ", return "stunned silence"
# used built-in functions/methods
# lower() - converts the full string into lower case
# index(str2) - provides the starting position of str2 inside str1. If not found, throws an exception
# strip() - strips the leading and trailing whitespaces
# title() - converts the string into titlecase i.e., capitalize first letter in each word of the string
def dropIt(str):
try:
i = str.lower().index('mike')
except:
return str.strip().title()
else:
return "stunned silence"
myStr = " tomorrow never dies "
# myStr = "mike and Mike"
print(dropIt(myStr))
| true |
0d0ffaa8f3359bedd40bb5a1495339eecb8f03bc | vishnuap/Algorithms | /Chapter-01-Fundamentals/Multiples-of-3-But-Not-All/Multiples-of-3-but-not-all.py | 386 | 4.65625 | 5 | # Chapter-1: Fundamentals
# Multiples of 3 - but not all:
# Using FOR, print multiples of 3 from -300 to 0. Skip -3 and -6
# multiples from -300 down means multiply 3 with -100 and down. -3 and -6 are 3 * -1 AND 3 * -2. So if we skip them, the multipliers are -100 down to -3.
for i in range(-100, 1):
if ((i != -1) and (i != -2)):
print("Multiple of 3: {}").format(i * 3) | true |
905092abe8da1ea55e92a9d4a6b7f34565f2597b | vishnuap/Algorithms | /Chapter-02-Fundamentals-2/Statistics-Until-Doubles/Statistics-Until-Doubles.py | 838 | 4.1875 | 4 | # Chapter-2: Fundamentals-2
# Statistics-Until-Doubles
# Implement a 20-sided die that randomly returns integers between 1 and 20 (inclusive). Roll the die, tracking statistics until you get a value twice in a row. After that display number of rolls, min, max and average
import random as rd
def stats():
done = False
max = 1
min = 20
sum = 0
count = 0
prev = 0
roll = 0
while not done:
roll = rd.randint(1,20)
max = max if max > roll else roll
min = min if min < roll else roll
sum += roll
count += 1
if (prev == roll):
done = True
else:
prev = roll
print("After {} rolls, the value repeated is {}. The stats are Max = {}; Min = {}; Sum = {}; Avg = {}").format(count, prev, max, min, sum, sum * 1.0 / count)
stats()
| true |
31b22e49ea518465e4e9b84f9bce3ff9ac222f46 | f-alrajih/Simple-Calculator | /directions.py | 2,879 | 4.5625 | 5 | # Welcome, Faisal, to your first project in Python!
# Today's project is to build a simple calculator that allows the user to choose what type of operation they want to do (add, subtract, multiply, or divide) and then takes the two numbers the user gives it and does the operation.
# You will need to build four different functions for this assignment:
# 1. A function called add_two_numbers with inputs x and y. The function returns the sum of those two numbers.
# 2. A function called subract_two_numbers with inputs x and y. The function returns the difference of those two numbers.
# 3. A function called multiply_two_numbers with inputs x and y. The function returns the product of those two numbers.
# 4. A function called divide_two_numbers with inputs x and y. The function returns the quotient of those two numbers.
# Once you finish these four functions and test them, come to me and I'll give you more directions!
# -------------
# Great! You're ready to move on to creating a menu for the user to select from.
# Create a function called calculator_menu that prints four different strings:
# "Select 1 to add"
# "Select 2 to subtract"
# "Select 3 to multiply"
# "Select 4 to divide"
# Test the calculator_menu() by calling it.
# -------------
# Great! We wrote our menu. But, we need some directions for the user to follow.
# Create a function called greeting_and_directions that prints a greeting and directions for the menu:
# "Welcome to Faisal's Simple Calculator!"
# "Choose one of the options below, then press enter."
# -------------
# Awesome! We're so close!
# Now, we need some kind of way to get the user's answer to our directions so that we know what kind of operation to do. This is called user input.
# Create a variable called menu_choice that takes the user's input when asked "What would you like to do?"
# -------------
# Cool! Let's create two more variables, first_number and second_number, that ask the user for their first and second numbers.
# -------------
# Looking awesome! Let's create a conditional that figures what operation to do based on the user's menu choice.
# If menu_choice equals 1, call add_two_numbers()
# If menu_choice equals 2, call subtract_two_numbers()
# If menu_choice equals 3, call multiply_two_numbers()
# If menu_choice equals 4, call divide_two_numbers()
# ----------
# Okay, so it looks like we have two problems: we can't see the menu and the greeting, and we can't see the answer. Let's fix that.
# Call greeting_and_directions() and calculator_menu() above where you define menu_choice.
# -----------
# Great! We can see the greeting and menu, but we still can't see the answer.
# Go to your conditional statements where you checked for the value of menu choice. Print whatever add_two_numbers(), subtract_two_numbers(), multiply_two_numbers(), and divide_two_numbers() returns.
| true |
9fb5a1366d12831b7f3b22d2f68b65a8ca773910 | rosarioValero/Programacion | /Ejercicios-Pr6/ejercicio9.py | 746 | 4.28125 | 4 | qq"""ROSARIO VALERO MIRANDA - 1º DAW - PRACTICA6 - EJERCICIO 9
Escribe un programa que permita crear una lista de palabras y que, a continuación,
cree una segunda lista con las palabras de la primera,
pero sin palabras repetidas (el orden de las palabras
en la segunda lista no es importante). """
print("Dime cuántas palabras tiene la lista: ")
num=int(input())
if num <1:
print("No es posible!")
else:
lista=[]
for i in range(num):
print("Dime la palabra",str(i + 1) + ": ")
pal=input()
lista +=[pal]
print("La lista creada es: ", lista)
for i in range(len(lista)-1, -1, -1):
if lista[i] in lista[:i]:
del(lista[i])
print("La lista sin repericiones es: ", lista)
| false |
466f1535379027fbf6cc322b1baf90095e73e57e | rosarioValero/Programacion | /Ejercicios-Pr7/ejercicio4.py | 575 | 4.375 | 4 | """ROSARIO VALERO MIRANDA - 1º DAW - PRACTICA7 - EJERCICIO 4
Escribe un programa que pida una frase, y le pase como parámetro a una función
dicha frase. La función debe sustituir todos los espacios en blanco
de una frase por un asterisco, y devolver el resultado para
que el programa principal la imprima por pantalla."""
print("Introduce una frase")
texto=input()
def frase(texto):
blanco= ' '
for i in range(len(texto)):
if texto[i] == ' ':
blanco+='*'
else:
blanco+=texto[i]
return blanco
print (frase(texto))
| false |
d2e1f8e6121ab0aa44fe8e899166b768028f39ed | rosarioValero/Programacion | /Ejercicios-Pr5/ejercicio9.py | 748 | 4.21875 | 4 | """ROSARIO VALERO MIRANDA - 1º DAW - PRACTICA5 - EJERCICIO 9
Escriu un programa que et demani noms de persones i els seus números de telèfon.
Per a terminar de escriure nombres i numeros s'ha de pulsar Intro quan et demani el nom.
El programa termina escribint noms i números de telèfon.
Nota: La llista en la que es guarden els noms i
números de telèfon és [ [nom1, telef1], [nom2, telef2], [nom3, telef3], etc]"""
print("Dame un nombre")
nomb=input()
lista=[]
lista1=[]
while nomb!="":
lista.append(nomb)
print("Introduce un telefono")
telf=(input())
lista.append(telf)
lista1.append(lista)
print("Introduce otro nombre")
nomb=input()
lista=[]
print("Los nombres y telefonos son: ",lista1)
| false |
9d6b104a638a7d302a5aa5f89467ce47d7b5e972 | tarunvelagala/python-75-hackathon | /input_output.py | 239 | 4.125 | 4 | # Input Example
name, age = [i for i in input('Enter name and age:').split()]
# Output Example
print('Hello "{}", Your age is {}'.format(name, age))
print('Hello %s, Your age is %s' % (name, age))
print('Hello', name, 'Your age is', age)
| true |
2ccf71624478a3e9867ca75475630053040631b2 | dheerajsharma25/python | /assignment8/assignment9/ass9_1.py | 437 | 4.3125 | 4 | #Q.1- Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class circle:
def __init__(self,radius):
self.radius=radius
def area(self):
getarea=math.pi*self.radius*self.radius
print(getarea)
def circumference(self):
result=2*math.pi*self.radius
print(result)
a=circle(int(input("enter the radius:")))
a.area()
a.circumference() | true |
47f111e1242d64f5655027c836ebfa25b802f312 | dheerajsharma25/python | /assignment10/ass10_4.py | 646 | 4.15625 | 4 | #Q.4- Create a class Shape.Initialize it with length and breadth Create the method Area.
class shape:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
self.result=self.length*self.breadth
class rectangle(shape):
def arearect(self):
print("area of rectangle:",self.result)
class square(shape):
def areasqur(self):
print("area of square:",self.result)
r=rectangle(int(input("length of rectangle:")),int(input("breadth of rectangle:")))
r.area()
r.arearect()
s=square(int(input("length of square:")),int(input("breadth of square:")))
s.area()
s.areasqur() | true |
c0c4d692956d733993d63a42fdfdcf609c9b7eba | sv1996/PythonPractice | /sortList.py | 509 | 4.28125 | 4 | number =[3,1,5,12,8,0]
sorted_list =sorted(number)
print("Sorted list is " , sorted_list)
#original lst remain unhanged
print("Original list is " , number)
# print list in reverse order
print("Reverse soretd list is " , sorted(number , reverse =True))
#original list remain unchanged
print("Original list is " , number)
#sort the list within itself
lst =[1,20,5.5,4.2]
lst.sort()
print("Sorted list is" , lst)
lst =[1,2,3,4,5]
abc = lst
abc.append(6)
#print original list
print("Original List is " , lst)
| true |
a528ae279f5773160001dd56b9ffb7df47714a86 | viditvora11/GK-quiz | /Python assements/v2 (Instructions and welcome)/v2a_instructions_and_welcome.py | 707 | 4.4375 | 4 | #Asking if they want to know the quiz rules.
rule = input("\nDo you want to read the rules or continue without the rules? \npress y to learn the rules or x to continue without knowing the rules : ")#Asking for the input
if rule == "y" or rule == "yes": #Use if function
print("\nThe basic rules are as follows \n 1. Enter the answer in a,b,c,d.\n 2. Press enter if you don't know the answer.\n(Know that you will not get the point for if you press enter)")#Printing rules
elif rule == "x" : #using elif to the previous if for asking if they want to know the rules to the quiz.
print("You may continue without the rules.")
elif rule == "no":
print("You may continue without the rules.")
| true |
2ca1a0ce4909965a4b4d0bcf2080d406bb9a5732 | FernandoGarciafg/m02_boot_0 | /recursividad.py | 1,503 | 4.1875 | 4 | # la recursividad es una funcion que para repetirse se invoca a si misma, una funcion es recursiva si para definirse se necesita
# solo a si misma y se llama a si misma, la recursividad tiene que tener una condicion de parada
def retroContador(numero):
print("{}\n".format(numero), end = "")
if numero > 0:
retroContador(numero - 1)
def retroContador2(numero):
if numero > 0:
print("{}\n".format(numero), end = "")
while numero > 0:
(retroContador2(numero - 1))
return numero
else:
pass
def sumatorio(numero):
if numero < 0:
pass
elif numero != 0:
return numero + sumatorio(numero - 1)
else:
return 0
def sumatorio2(numero):
while numero > 0:
return numero + sumatorio(numero - 1)
return numero
def factorial(numero):
contador = 1
while contador != numero:
contador += 1
return numero * factorial(numero - 1)
return numero
def factorial(numero):
if numero > 1:
contador = 1
while contador != numero:
contador += 1
return numero * factorial(numero - 1)
elif numero == 0 or numero == 1:
return 1
return
def factorial2(numero):
if numero > 1:
return numero * factorial(numero -1)
elif numero == 0 or numero == 1:
return 1
return
#retroContador(10)
#retroContador2(10)
#print(sumatorio(12))
#print(sumatorio2(12)) | false |
6f013967c7998c120b1a1f8ca681add61a969ae3 | preciousakura/Atividades-Python | /listas.py | 278 | 4.1875 | 4 | num = []
num.append(0)
num.append(9)
num.append(8)
num.append(2)
for x, cont in enumerate(num):
print(f"Na posição {x} encontrei o valor {cont}!")
print("Cheguei ao fim da lista")
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
| false |
c57799bb1ea76d52ec15085c90ede41dc76ea625 | Punkrockechidna/PythonCourse | /advanced_python/functional_programming/map.py | 294 | 4.125 | 4 | # MAP
# previous version
# def multiply_by_2(li):
# new_list = []
# for item in li:
# new_list.append(items * 2)
# return new_list
# using map
def multiply_by_2(item):
return item * 2
print(list(map(multiply_by_2, [1, 2, 3]))) #not calling function, just running it
| true |
947f37fca0d63f02ec4af7a6c063496765ce4f06 | brandon-vargas24/PythonCode | /Python/merge_sort.py | 1,245 | 4.21875 | 4 | #Extra Credit Homework Assignment, Merge Sort
#VARGAS, BRANDON
#April 24, 2017
#Iterative:
def merge_sort_iterative(l, m):
result = []
i = j = 0
total = len(l) + len(m)
while len(result) != total:
if len(l) == i:
result = result + m[j:]
break
elif len(m) == j:
result = result + l[i:]
break
elif l[i] < m[j]:
result.append(l[i])
i = i + 1
else:
result.append(m[j])
j = j + 1
return result
#Recursive:
# call this function first to Merge two arrays and get Merged Array
def merge(array1,array2):
merged_array=[]
while array1 or array2:
if not array1:
merged_array.append(array2.pop())
elif (not array2) or array1[-1] > array2[-1]:
merged_array.append(array1.pop())
else:
merged_array.append(array2.pop())
merged_array.reverse()
return merged_array
#Then call this function with the merged_array to sort the list
def mergeSort(merged_array):
n = len(merged_array)
if n <= 1:
return merged_array
left = merged_array[:n/2]
right = merged_array[n/2:]
return merge(mergeSort(left),mergeSort(right))
| false |
6d3ef737751193c05f7a6791ca698a94c6cc77b7 | ChuqiaoW/Sandbo | /prac_05/hex_colours.py | 572 | 4.3125 | 4 | COLORS = {"aliceblue": "#f0f8ff", "antiquewhite": " #faebd7", "brown": "#a52a2a", "burlywood": "#deb887",
"cadetblue": "#5f9ea0", "coral": "#ff7f50", "chocolate": "#d2691e", "cornflowerblue": "#6495ed",
"darkgoldenrod": "#b8860b", "darkorange": "#ff8c00"}
color_chose = input("Pls enter color name:")
while color_chose != "":
while color_chose.lower() not in COLORS:
print("Invalid colour name.")
color_chose = input("Pls enter color name:")
print(COLORS[color_chose])
color_chose = input("Pls enter color name:")
| false |
7c61b9cc81d4ae45d91866e38ec0051b045cdc00 | khatriajay/pythonprograms | /in_out_list_.py | 418 | 4.4375 | 4 | #! /usr/bin/env python3
#Python3 program for checking if you have a pet with name entered.
petname= ['rosie', 'jack', 'roxy', 'blossom'] #Define a list with pet names
print (' Enter your pet name')
name = input()
if name not in petname: #Check if name exists in list
print ('You dont have a pet named ' + name )
else:
print ('Your pet ' + name + ' missed you while you were away')
| true |
0487755cae67b8f59554449aae3a6612b0dc3b7e | rosteeslove/bsuir-4th-term-python-stuff | /numerical_analysis_methods/gaussianelimination/gauss_elim_partial_pivoting.py | 2,048 | 4.125 | 4 | """
Схема частичного выбора.
"""
import numpy as np
def solve(A: np.array, b: np.array, interactive) -> np.array:
"""
Solves A*x = b that is returns x-vector.
"""
if interactive:
print('Схема частичного выбора:\n')
input()
# securing args:
A = A.copy()
b = b.copy()
# прямой ход:
if interactive:
print('Прямой ход:\n')
input()
for i in range(len(A)):
# choosing the element with the biggest absolute value
# in the column:
new_i = i
for j in range(i+1, len(A)):
if abs(A[i, j]) > abs(A[i, new_i]):
new_i = j
if interactive:
print('''Column #{0}: element {1}x{2} is of the biggest
absolute value.\n'''.format(i, new_i, i))
input()
# swapping rows:
if i != new_i:
A[[i, new_i]] = A[[new_i, i]]
b[[i, new_i]] = b[[new_i, i]]
if interactive:
print('Rows {0} and {1} swapped.\n'.format(i, new_i))
input()
else:
if interactive:
print('No rows were swapped.\n')
input()
assert A[i, i] != 0
# eliminating column elements below the current main one:
b[i] /= A[i, i]
A[i] /= A[i, i]
for j in range(i+1, len(A)):
b[j] -= b[i]*A[j, i]
A[j] -= A[i]*A[j, i]
if interactive:
print('''Step {0} completed: the A-matrix and b-vector are now:
\n{1}\n{2}\n'''.format(i+1, A, b))
input()
# обратный ход:
if interactive:
print('Обратный ход:\n')
input()
x = b
for k in range(len(A)-1, -1, -1):
for m in range(len(A)-1, k, -1):
x[k] -= (A[k, m]*x[m]) / A[k, k]
if interactive:
print('x[{0}] calculated: {1}'.format(k+1, x[k]))
input()
return x
| false |
0cc442ea2ed19f5130e5cdff5886b6dce22441c4 | tayadehritik/NightShift | /fact.py | 217 | 4.1875 | 4 | args = int(input())
def factorial(num):
fact = num
for i in range(num-1,1,-1):
fact = fact * i
return fact
for i in range(args):
num = int(input())
fact = factorial(num)
print(fact)
| true |
cd067c9c7ee918b908e31959d1e77d36dae5b36d | destrauxx/famped.github.io | /turtles.py | 469 | 4.125 | 4 | def is_palindrome(s):
tmp = s[:]
tmp.reverse()
print(s, 'input list')
print(tmp, 'reversed list')
if tmp == s:
return True
else:
return
def word(n):
result = []
for _ in range(n):
element = input('Enter element: ')
result.append(element)
if is_palindrome(result):
print(f'{result} - is palindrome')
else:
print(f'{result} - not a palindrome')
word(3) | true |
42160b7b926a67cfea2f482584f39c38e11c4c17 | ssenviel/Python_Projects-Udemy_zero_to_hero | /Generators_play.py | 909 | 4.46875 | 4 | """
problem 1:
create a Generator that generates the squares of numbers up to some number 'N'
problem 2:
create a generator that yields "n" random number between a low and high number
NOTE: use random.randrange or random.randint
problem 3:
use the iter() function to convert the string 'hello' into an iterator.
"""
import random
def square_generator(N):
i=0
while i < N:
yield i**2
i += 1
def random_generator(N, start, stop):
"""
NOTE: need to figure out how to get unique random numbers
"""
i=0
while i < N:
yield random.randrange(start, stop)
i += 1
def convert_str_to_iter():
my_string = 'hello'
my_str_iter = iter(my_string)
for char in range(0, len(my_string)):
print(next(my_str_iter))
convert_str_to_iter()
| true |
bd160ff2bbf7bc2b6c004d39a51180a45c0e9a84 | MarceloSaied/py | /python/helloworld/python1.py | 485 | 4.15625 | 4 | # print ("hello world")
# counter = 100 # An integer assignment
# miles = 1000.0 # A floating point
# name = "John" # A string
import datetime
currentDate = datetime.date.today()
currentDate=currentDate.strftime('%a %d %b %y')
print(currentDate)
# print (counter)
# print (miles)
# print (name)
# print ("test")
# name = input("what is your name?")
# print (name)
# name = "John" # A string
# print (name.upper())
# print(name.capitalize())
| true |
c648e44b121c114f7fc4d4d28b83700720388604 | jw3329/algorithm-implementation | /sort/selectionsort.py | 600 | 4.1875 | 4 | def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# find minimum element, and swap with its element from the start
def selectionsort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
# after finishing searching, swap it
swap(arr, min_index, i)
import random
arr = random.sample(range(1000), 100)
print('before sorted value:\n', arr)
selectionsort(arr)
print('after calling selectionsort:\n', arr)
print('sorted?', sorted(arr) == arr) | true |
99dddf7531d25ca94c177a77f81c1ace561e7cd5 | alina-j/6 | /8.py | 1,120 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Решите задачу: создайте словарь, связав его с переменной school , и наполните данными,которые бы отражали количество учащихся в разных классах (1а, 1б, 2б, 6а, 7в и т. п.).Внесите изменения в словарь согласно следующему: а) в одном из классов изменилось количество учащихся, б) в школе появился новый класс, с) в школе был расформирован (удален) другой класс. Вычислите общее количество учащихся в школе.
if __name__ == '__main__':
s = 0
school = {'1а': 20, '1б': 21, '2а': 15, '2б': 33, '3a': 29,'3б': 23, '4а': 25, '4б': 33}
print(school.items())
school["1а"] = 30
print(school.items())
school["2б"] = 15
print(school.items())
school.pop("3б")
print(school.items())
print(sum(school.values())) | false |
fbee41e0deb8a6a257f6a4a6977151eb79d273f0 | akomawar/Python-codes | /Practise_Assignments/reverse.py | 238 | 4.375 | 4 | while 1:
string=input("Eneter your string: ")
reverse=string[::-1]
print("Reverse order is : ",reverse)
if(string==reverse):
print('yes it is an palindrome')
else:
print('No it is not a palindrome')
| true |
17ab687aea8f2853c8feadd8d729503651fd2497 | saikiran-gutla/Ifassignment | /Daysinmonth.py | 405 | 4.34375 | 4 | month = input('Enter the month : ')
mon = month[0:3].lower()
print(mon)
if mon == 'jan' or mon == 'may' or mon == 'mar' or mon == 'jul' or mon == 'aug' or mon == 'oct' or mon == 'dec':
print(mon, "has 31 days")
elif mon == 'apr' or mon == 'jun' or mon == 'sep' or mon == 'nov':
print(mon, 'has 30 days')
elif mon == 'feb':
print(mon, 'has 28 days')
else:
print(month, 'is Invalid Month')
| false |
9ec4fc796e36856083bd46e275a5b46aef7b8baa | saikiran-gutla/Ifassignment | /tenp.py | 272 | 4.1875 | 4 | ch = input('Enter a character :')
if ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')) :
print(ch ,'is a character')
elif (ch >= '0' and ch <= '9'):
print(ch ,'is a number')
elif ch ==' ':
print('Its a space')
else:
print('its a special character')
| false |
01956a8f807fea39c05553178b47c9b4a81b73c8 | MarkChuCarroll/pcomb | /python/calc.py | 2,172 | 4.34375 | 4 | # A simple example of using parser combinators to build an arithmetic
# expression parser.
from pcomb import *
## Actions
def digits_to_number(digits, running=0):
"""Convert a list of digits to an integer"""
if len(digits) == 0:
return running
else:
r = (running * 10) + int(digits[0])
return digits_to_number(digits[1:], r)
def unary_to_number(n):
if n[0] == None:
return n[1]
else:
return -n[1]
def eval_add(lst):
"""Evaluate an addition expression. For addition rules, the parser will return
[number, [[op, number], [op, number], ...]]
To evaluate that, we start with the first element of the list as result value,
and then we iterate over the pairs that make up the rest of the list, adding
or subtracting depending on the operator.
"""
first = lst[0]
result = first
for n in lst[1]:
if n[0] == '+':
result += n[1]
else:
result -= n[1]
return result
def eval_mult(lst):
"""Evaluate a multiplication expression. This is the same idea as evaluating
addition, but with multiplication and division operators instead of addition and
subtraction.
"""
first = lst[0]
result = first
for n in lst[1]:
if n[0] == '*':
result = result * n[1]
else:
result = result / n[1]
return result
## The Grammar
# expr : add_expr ( ( '*' | '/' ) add_expr )*
# add_expr : unary_expr ( ( '+' | '-' ) unary_expr )*
# unary_expr : ( '-' )? simple
# simple : number | parens
# parens : '(' expr ')'
# number: digit+
digit = Parser.match(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
number = Action(digit.many(1), digits_to_number)
parens = Action(Parser.match(['(']) & Reference('expr') & Parser.match([')']),
lambda result: result[1])
simple = number | parens
unary_expr = Action(Parser.match(['-']).opt() & simple, unary_to_number)
mult_expr = Action(unary_expr & (Parser.match(['*', '/']) & unary_expr).many(), eval_mult)
add_expr = Action(mult_expr & (Parser.match(['-', '+']) & mult_expr).many(), eval_add)
expr = add_expr
Reference.register_named_parser('expr', add_expr)
inp = StringParserInput("1+2*(3+5*4)*(6+7)")
print(expr.parse(inp).output)
| true |
1789bc3863b74780b5dc95da3544b5ee4eee5c9b | Vijay1234-coder/data_structure_plmsolving | /Heap/NearlyKsortedArray.py | 960 | 4.125 | 4 | '''important'''
'''Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array.
Example:
Input : arr[] = [6, 5, 3, 2, 8, 10, 9]
k = 3
Output : arr[] = {2, 3, 5, 6, 8, 9, 10}
here you have to use complexity O(NlogK)
you have to use min Heap so that if if we push element at the or at front of min heap min element will be present
and when you pop it when size greater than k it will give mini element '''
from heapq import heappop, heappush,heapify
arr =[6, 5, 3, 2, 8, 10, 9]
k = 3
min_heap = []
sorted_lis = []
for i in range(len(arr)):
heappush(min_heap,arr[i])
if len(min_heap)>k:
res =heappop(min_heap)
sorted_lis.append(res)
while min_heap!=[]:
sorted_lis.append(heappop(min_heap))
print(sorted_lis)
| false |
e11491e4a4ee97151df1055abd9ef0a5d9d9b878 | Vijay1234-coder/data_structure_plmsolving | /LINKED_LISTALLMETHODS/InsertionSortLL.py | 1,597 | 4.21875 | 4 | class Node:
def __init__(self,data):
self.data = data
self.nref = None
self.pref = None
class DoublyLL:
def __init__(self):
self.head = None
def print_LL(self): # Forward Direction Traversal
if self.head ==None:
print("Empty LL")
else:
n = self.head
while(n != None):
print(n.data,"-->",end =" ")
n = n.nref
def print_LL_reverse(self): #Backward Traversal
if self.head == None:
print("Linked list is empty")
else:
n = self.head
while n.nref !=None:
n = n.nref
# we come out loop now we are at last node
while n!=None :
print(n.data, "-->",end = " ")
n = n.pref
def insert_end(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
else:
n = self.head
while n.nref != None:
n = n.nref
n.nref = new_node
new_node.pref = n
def insertionSort(self,head):
n = head
n = n.nref
while n!=None:
curr = n
while curr.data < n.pref.data and n!= None:
temp = n.data
n.data = n.pref.data
n.pref.data = temp
n = n.pref
n = n.nref
l = DoublyLL()
l.insert_end(40)
l.insert_end(10)
l.insert_end(20)
l.insert_end(110)
l.insertionSort(l.head)
l.print_LL()
| false |
b6ed10576f670be063516122126826ef88918fb1 | Vijay1234-coder/data_structure_plmsolving | /SEARCHING AND SORTING/Binary Search/Implementation.py | 979 | 4.15625 | 4 | def binary_search(arr,target):
first = 0
last = len(arr)-1
found = False
while (first <= last) and (found == False):
mid = (first+last)//2
if arr[mid] == target:
print("found at index {0}".format(mid))
found = True
else:
if target > arr[mid]:
first = mid +1
else:
last = mid - 1
return found
arr = [1,2,3,4,5,6,7,8,9,10]
print(binary_search(arr,15))
'''recursive Binary Search'''
# def rec_binary_search(arr,target):
# mid = len(arr)//2
# # Base Case
# if len(arr)==0:
# return False
# else:
# if arr[mid] == target:
# return True
# else:
# if target < arr[mid]:
# return rec_binary_search(arr[:mid], target)
# else:
# return rec_binary_search(arr[mid+1:], target)
#
#
#
#
#
# arr = [1,2,3,4,5,6,7,8,9,10]
# print(rec_binary_search(arr,1)) | false |
7cfd67cc83713cec92f7ce1807bcaeed84028c0b | sprajwol/python_assignment_II | /assignment_Q11.py | 863 | 4.71875 | 5 | # # 11. Create a variable, filename. Assuming that it has a three-letter
# # extension, and using slice operations, find the extension. For
# # README.txt, the extension should be txt. Write code using slice
# # operations that will give the name without the extension. Does your
# # code work on filenames of arbitrary length?
# filename = input("Enter the filename with extension:")
# name = filename[:-4]
# print(name)
# 11. Create a variable, filename. Assuming that it has a three-letter
# extension, and using slice operations, find the extension. For
# README.txt, the extension should be txt. Write code using slice
# operations that will give the name without the extension. Does your
# code work on filenames of arbitrary length?
filename = input("Enter a file name with three letter extension:")
only_filename = filename[:-4]
print(only_filename)
| true |
487db65523fc0db80945c254b577d3a9a3cf7f61 | sprajwol/python_assignment_II | /assignment_Q7.py | 1,054 | 4.25 | 4 | # 7. Create a list of tuples of first name, last name, and age for your
# friends and colleagues. If you don't know the age, put in None.
# Calculate the average age, skipping over any None values. Print out
# each name, followed by old or young if they are above or below the
# average age.
import statistics
list_of_data = [("Prajwol", "Shakya", 23), ("Momika", "Sherestha", 22), ("Ashish", "Maharjan", 24), ("Shirisha", "Maharjan", 22), ("Ananda", "Pandey", 25),
("Pramisha", "Kapali", 18), ("Adarsha", "Thapa", 20), ("Tejwol", "Shakya", 18), ("Aayushma", "Shakya", None), ("Shoojan", "Maharjan", 28), ("Subha", "Maharjan", 22)]
age_list = [each_tuple[2]
for each_tuple in list_of_data if each_tuple[2] != None]
print(age_list)
avg_age = statistics.mean(age_list)
for each_tuple in list_of_data:
if (each_tuple[2] == None):
print(each_tuple[0], "!!!No Data!!!")
elif (each_tuple[2] < avg_age):
print(each_tuple[0], "young")
elif (each_tuple[2] > avg_age):
print(each_tuple[0], "old")
| true |
e53d462fc353654d6ebbc5e3b1ad3b654e135a75 | korzair74/Homework | /Homework_4-20/family.py | 235 | 4.34375 | 4 | """
Create a variable called family
Assign it a list of at least 3 names of family members as strings
Loop through the list and print everyone's name
"""
family = ['Shea', 'Owen', 'Chris']
for name in family:
print(name) | true |
6d832510ef2179b0a5fc908e6904c4b12e4d55fa | EOT123/AllEOT123Projects | /All Python Files Directory/Bounties/Bounty11.py | 495 | 4.3125 | 4 | # 10/30/17
# Number flipper opposite output neg=pos/pos=neg
print("")
print("_______________________________________")
print("Welcome To The Opposite Number Flipper")
print("_______________________________________")
print("")
while True:
num = int(input('Enter A Number To Be Flipped: '))
if num > 0:
print("Your Opposite Number Is:", - + num)
elif num < 0:
print("Your Opposite Number Is: ", -num)
print("_______________________________")
print("")
# Done
| false |
b7838d90f734023df37e7de90f8d01373a112fb2 | mogarg/Python-Tutorial-Lynda | /variables-syntax.py | 359 | 4.25 | 4 | #!/usr/bin/python3
def main():
atuple = (1,2,3) #A tuple is immutable
alist = [1,2,3] #A list is mutable
print(atuple,type(atuple))
print(alist,type(alist))
alist.append(5)
print(alist)
alist.insert(2,7)
print(alist)
x = "string" #A string is an immutable sequence
for i in x:
print(i)
if __name__=="__main__":main()
| false |
aebd73b4f15e97b86345ee31cd6e0df8e6e57b6d | matthpn2/Library-Database-Application | /backend_database.py | 1,929 | 4.53125 | 5 | import sqlite3
class Database:
'''
SQLite database which can be viewed, searched, inserted, deleted, updated and closed upon.
'''
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
self.cursor.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
self.connection.commit()
def viewData(self):
'''
Fetches and returns all the rows in the books table.
'''
self.cursor.execute("SELECT * FROM books")
rows = self.cursor.fetchall()
return rows
def insertData(self, title, author, year, isbn):
'''
Inserts data into the books table, given user input.
'''
self.cursor.execute("INSERT INTO books VALUES (NULL, ?, ?, ? , ?)", (title, author, year, isbn))
self.connection.commit()
def searchData(self, title = "", author = "", year = "", isbn = ""):
'''
Fetchs and returns the rows of the books table that matches the user search query.
'''
self.cursor.execute("SELECT * FROM books WHERE title = ? OR author = ? or year = ? or isbn = ?", (title, author, year, isbn))
rows = self.cursor.fetchall()
return rows
def deleteData(self, id):
'''
Deletes data from the books table, using the book id.
'''
self.cursor.execute("DELETE FROM books WHERE id = ?", (id,))
self.connection.commit()
def updateData(self, id, title, author, year, isbn):
'''
Updates data from books table, using the book id.
'''
self.cursor.execute("UPDATE books SET title = ?, author = ?, year = ?, isbn = ? WHERE id = ?", (title, author, year, isbn, id))
self.connection.commit()
def __del__(self):
self.connection.close() | true |
97bc749ebc6f382ace489e57bbe092de06e98025 | AndreiSystem/python_aula | /mundo01/ex031.py | 520 | 4.15625 | 4 | """
Desenvolva um programa que pergunte a distância de uma viagem em Km.
Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km
e R$0.45 para viagens mais longas.
"""
distancia = float(input('Digite a distância da viagem em Km: '))
print(f'Viagem de {distancia:.1f}Km.')
if distancia <= 200:
valor = distancia * 0.50
print(f'Preço da passagem de R${valor:.2f}')
else:
valor = distancia * 0.45
print(f'Preço da passagem de R${valor:.2f}')
print('\033[32mBoa viagem!\033[m')
| false |
018840bac1a0cbb7a539d9a708eeb7d3a022c8d6 | AndreiSystem/python_aula | /mundo01/Modulo.py | 512 | 4.21875 | 4 | """"
**import math importa toda a biblioteca de matemática
import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print(f'A raíz de {num} é igual a {raiz:.2f} e se arrendoda-la resulta em {math.ceil(raiz)}')
#from math import importa somente um módulo especifico
from math import sqrt
num = int(input('Digite um número: '))
raiz = sqrt(num)
print(raiz)
#caso queira consultar mais bibliotecas é só acessar python.org/docs
"""
import random
num = random.randint(1, 10)
print(num) | false |
514acc07466de29f954cb0ff734384a1772592e2 | sharingplay/Introduccion-a-la-programacion | /Recursividad de pila/Listas/listaSumParImpar.py | 850 | 4.15625 | 4 | """Suma valores pares e impares de una lista"""
def suma (lista):
#if type (lista) == list, tambien verifica que lista sea de tipo lista
if isinstance (lista,list):
print "Suma pares: " , validarPar (lista)
print "Suma impares: ",validarImpar(lista)
else:
return "Error, el valor ingresado no es una lista"
def validarPar(lista): #separa los numero pares encontrados en la lista
if lista == []:
return 0
elif lista [0] % 2 == 0:
return lista [0]+ validarPar (lista[1:])
else:
return validarPar (lista [1:])
def validarImpar(lista): #separa y cuenta los numero impares encontrados
if lista == []:
return 0
elif lista [0] % 2 != 0:
return lista [0]+ validarImpar (lista[1:])
else:
return validarImpar (lista [1:])
| false |
6bf7618ce1538e6394f9aa52375cdda7e1fcc3a7 | sharingplay/Introduccion-a-la-programacion | /Python/Matrices/tarea matriz.py | 1,627 | 4.3125 | 4 |
"""multiplica los primeros numeros de una columna contra los numeros de
una fila"""
def multiplicacionMatriz(lista1,lista2):
if isinstance (lista1,list) and (lista2,list):
return matrices(lista1,lista2,0,0,0,0,[],[])
else:
return "Error"
def matrices (lista1,lista2,contCol_1,contCol_2,contFila_1,contFila_2,nueva,final):
if contFila_1 == len(lista1) and contCol_2 == len (lista2[0]):
return final
elif contCol_1 < len(lista1[0]):
return matrices (lista1,lista2,contCol_1 + 1,contCol_2,contFila_1,contFila_2 + 1,nueva + [(lista1[contFila_1][contCol_1]) * (lista2[contFila_2][contCol_2])],final)
elif contCol_1 == len(lista1[0]):
return matrices (lista1,lista2,0,contCol_2 + 1,contFila_1 + 1,0,[],final + [nueva])
#multiplicacionMatriz([[1,2,3],[4,5,6]],[[7,8],[9,10],[11,12]])
#continuar pensando la logica
def multiplicacionMatriz(lista1,lista2):
if isinstance (lista1,list) and (lista2,list):
return matrices(lista1,lista2,0,0,0,0,[],[])
else:
return "Error"
"""def matrices (lista1,lista2,contCol_1,contCol_2,contFila_1,contFila_2,nueva,final):
if contFila_1 == len(lista1) and contCol_2 == len (lista2[0]):
return final
elif contCol_1 < len(lista1[0]):
return matrices (lista1,lista2,contCol_1 + 1,contCol_2,contFila_1,contFila_2 + 1,nueva + [(lista1[contFila_1][contCol_1]) * (lista2[contFila_2][contCol_2])],final)
elif contCol_1 == len(lista1[0]):
return matrices (lista1,lista2,0,contCol_2 + 1,contFila_1 + 1,0,[],final + [nueva[0]])"""
| false |
4e5d7c36099415e09ff077fba1e06bc3262950dc | samhita-alla/flytesnacks | /cookbook/core/basic/task.py | 2,089 | 4.15625 | 4 | """
Tasks
------
This example shows how to write a task in flytekit python.
Recap: In Flyte a task is a fundamental building block and an extension point. Flyte has multiple plugins for tasks,
which can be either a backend-plugin or can be a simple extension that is available in flytekit.
A task in flytekit can be 2 types:
1. A task that has a python function associated with it. The execution of the task would be an execution of this
function
#. A task that does not have a python function, for e.g a SQL query or some other portable task like Sagemaker prebuilt
algorithms, or something that just invokes an API
This section will talk about how to write a Python Function task. Other type of tasks will be covered in later sections
"""
# %%
# For any task in flyte, there is always one required import
from flytekit import task
# %%
# A ``PythonFunctionTask`` must always be decorated with the ``@task`` ``flytekit.task`` decorator.
# The task itself is a regular python function, with one exception, it needs all the inputs and outputs to be clearly
# annotated with the types. The types are regular python types; we'll go over more on this in the type-system section.
# :py:func:`flytekit.task`
@task
def square(n: int) -> int:
"""
Parameters:
n (int): name of the parameter for the task will be derived from the name of the input variable
the type will be automatically deduced to be Types.Integer
Return:
int: The label for the output will be automatically assigned and type will be deduced from the annotation
"""
return n * n
# %%
# In this task, one input is ``n`` which has type ``int``.
# the task ``square`` takes the number ``n`` and returns a new integer (squared value)
#
# .. note::
#
# Flytekit will assign a default name to the output variable like ``out0``
# In case of multiple outputs, each output will be numbered in the order
# starting with 0. For e.g. -> ``out0, out1, out2, ...``
#
# Flyte tasks can be executed like normal functions
if __name__ == "__main__":
print(square(n=10))
| true |
251f4cf3e4b649230e0180803aecd6ef3c0e249d | kimchol0/Python | /range.py | 483 | 4.5625 | 5 | #遍历数字序列
for i in range(10):
print(i,end=" ")
print("\n----------")
#遍历指定区间的值
for i in range(0,20):
print(i,end=" ")
print("\n----------")
#以指定数字开始并指定不同的增量(甚至可以为负数,也叫做“步长”)
for i in range(0,10,3):
print(i,end=" ")
print("\n----------")
#负数
for i in range(-10,-100,-30):
print(i,end=" ")
print("\n----------")
#创建一个列表
createlist=list(range(5))
print(createlist) | false |
5fe0ad7defc54cb146a4d187e0ec03c001da7b82 | manrajpannu/ccc-solutions | /ccc-solutions/2014/Triangle.py | 1,239 | 4.21875 | 4 | # Triangle
# Manraj Pannu
# 593368
# ICS3U0A
# 23 Oct 2018
firstAngle = int(input()) # input: the first angle of the triangle
secondAngle = int(input()) # input: the second angle of the triangle
thirdAngle = int(input()) # input: the third angle of the triangle
totalAngle = (firstAngle + secondAngle + thirdAngle) # calculates the total angle of the triangle
if (firstAngle == 60 and secondAngle == 60 and thirdAngle == 60) : # checks if all the angles have 60 degree angles
print('Equilateral') # output: that the triangle is equilateral
elif (totalAngle == 180 and (firstAngle == secondAngle or secondAngle == thirdAngle or firstAngle == thirdAngle) ): # checks if all the angles equal to 180 and that atleast two of the angles are the same
print('Isosceles') # output: that the triangle is equilateral
elif (totalAngle == 180 and (firstAngle != secondAngle and secondAngle != thirdAngle and firstAngle != thirdAngle) ): # checks if all the angles equal to 180 and that all of the angles arent the same
print('Scalene') # output: that the triangle is equilateral
else : # works if all other conditional statements are false
print('Error') #output : that there is no proper inputs for it to be a triangle
| true |
790b036fd87b8e76e6a41bc2737dce28fc5ef6f3 | sharifnezhad/python-workout1 | /calculator.py | 1,349 | 4.125 | 4 | import math
i='y'
while i=='y':
number_one=int(input('please enter number1:'))
Operator=input('please enter Operator: (+|-|*|/|^|radical|sin|cos|tan|cot|factorial)')
if Operator == '+' or Operator == '-' or Operator == '*' or Operator == '/' or Operator == '^' :
number_two=int(input('please enter number2:'))
if Operator=='+':
result=number_one+number_two
elif Operator=='-':
result=number_one-number_two
elif Operator=='*':
result=number_one*number_two
elif Operator=='/':
if number_two==0:
result='error'
else:
result=number_one/number_two
elif Operator=='^':
result=number_one**number_two
else:
if Operator=='radical':
result=math.sqrt(number_one)
elif Operator=='sin':
result=math.sin(number_one)
elif Operator=='cos':
result=math.cos(number_one)
elif Operator=='tan':
result=math.tan(number_one)
elif Operator=='cot':
result=1/math.tan(number_one)
elif Operator=='factorial':
result=math.factorial(number_one)
print('output: ',result)
print ('\n Do you want to continue calculating? (y/n)')
i=input()
| false |
871d961154232ad57478058b1f58f6ca47c9f03f | JustinLaureano/python_projects | /python_practice/is_prime.py | 563 | 4.3125 | 4 | """
Define a function isPrime/is_prime() that takes one integer argument and
returns true/True or false/False depending on if the integer is a prime.
Per Wikipedia, a prime number (or a prime) is a natural number greater than 1
that has no positive divisors other than 1 and itself.
"""
def is_prime(num):
if num < 2:
return '{} is not prime.'.format(num)
for x in range(2, num):
if int(num) % x == 0:
return '{} is not prime.'.format(num, x)
return '{} is prime.'.format(num)
print(is_prime(-1))
print(is_prime(13))
| true |
e84bee8c7f1151fde0a1d9be3c1bf96400ac5949 | JustinLaureano/python_projects | /python_practice/max_subarray_sum.py | 924 | 4.21875 | 4 | """
The maximum sum subarray problem consists in finding the maximum sum of a
contiguous subsequence in an array or list of integers:
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum
sum is the sum of the whole array. If the list is made up of only negative
numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list
or array is also a valid sublist/subarray.
"""
def maxSequence(arr):
max = []
for x in range(len(arr)):
for pos, number in enumerate(arr):
subarray = arr[pos:x + 1]
total = 0
for num in subarray:
total += num
if total > sum(max):
max = subarray
return max, sum(max)
print(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
# should be 6: [4, -1, 2, 1]
| true |
dea1a14a5d21acab0295d8cf41cfc85deae87015 | itspayaswini/PPA-Assignments | /exception.py | 221 | 4.15625 | 4 | numerator=int(input("enter the numerator "))
denominator=int(input("enter the denominator "))
try:
result= (numerator/denominator)
print(result)
except ZeroDivisionError as error:
print("Division by zero!")
| true |
5db2515b14384ef59c4dc2459305b3d4f0f91853 | perfectgait/eopi | /python2/7.2-replace_and_remove/telex_encoding.py | 1,401 | 4.25 | 4 | """
Telex encode an array of characters by replacing punctuations with their spelled out value.
"""
__author__ = "Matt Rathbun"
__email__ = "mrathbun80@gmail.com"
__version__ = "1.0"
def telex_encode(array):
"""
Telex encode an array of characters using the map of special characters
"""
special_string_length = 0
char_map = {
'.': 'DOT',
',': 'COMMA',
'?': 'QUESTION MARK',
'!': 'EXCLAMATION MARK'
}
for char in array:
if char in char_map:
# Make sure to subtract one for the special character that is being replaced
special_string_length += len(char_map[char]) - 1
if special_string_length > 0:
current_index = len(array) - 1
array += [''] * special_string_length
write_index = len(array) - 1
while current_index >= 0:
if array[current_index] in char_map:
for i in range(len(char_map[array[current_index]]) - 1, -1, -1):
array[write_index] = char_map[array[current_index]][i]
write_index -= 1
else:
array[write_index] = array[current_index]
write_index -= 1
current_index -= 1
return array
string = raw_input('String: ')
original_string = string
print 'The telex encoding of the string %s is %s' % (original_string, ''.join(telex_encode(list(string)))) | true |
2d9b2e241a24df7fa44ce2fd51be999d07a1d40e | Vangasse/NumPyTutorial | /NumPySortSearch.py | 725 | 4.28125 | 4 | # %%
import numpy as np
import matplotlib.pyplot as plt
# %% How to get the indices of the sorted array using NumPy in Python?
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
print(np.argsort(a))
# %% Finding the k smallest values of a NumPy array
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
k = 3
print(np.sort(a)[:k])
# %% How to get the n-largest values of an array using NumPy?
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
k = 3
print(np.sort(a)[-k:])
# %% Sort the values in a matrix
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7]).reshape([3, 3])
print(a)
a = np.sort(np.ravel(a)).reshape([3, 3])
print(a)
# %% Filter out integers from float numpy array
a = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
print(a[a != a.astype(int)] )
# %% | true |
c4d8a7398a895035637e2c36ca6c26f9a2fdf666 | gmendiol-cisco/aer-python-game | /brehall_number-guessing-game.py | 1,073 | 4.1875 | 4 | #random number generator
import random
number=random.randint(1,100)
#define variables.
TOP_NUM=100
MAXGUESS=10
guesscount=0
#game rules
print("Welcome to the Number Guessing Game...")
print("I'm thinking of a number between 1 and", TOP_NUM,". You have", MAXGUESS,"chances to figure it out." )
#collect information
while guesscount <= MAXGUESS:
print("What do you guess?")
guesscount = guesscount + 1
guess = input()
guess = int(guess)
#if guess > TOP_NUM
# print("please choose a number between 1 and", TOP_NUM,")
if guess > TOP_NUM:
print("please guess a number between 1 and", TOP_NUM)
elif guess < 1:
print("please guess a number between 1 and", TOP_NUM)
elif guess < number:
print("I will give you a hint, your guess is too low")
elif guess > number:
print("I will give you a hint, your guess is too high")
elif guess == number:
break
if guesscount > MAXGUESS:
print("I am sorry but you have exceeded your guess count, the number I was thinking of was", number)
if guess == number:
print("Great job!, you have guessed my number")
| true |
ded3e0219922eb6440c7901bc97a3ce4003c8a05 | leeseu95/MetodosNumericos | /Parcial1/SeungLee_P1.py | 2,320 | 4.15625 | 4 | # Seung Hoon Lee Kim - A01021720
# Examen - Parcial 1
# Pregunta 1 Manejo de inventario
# Solución escrita en Python 3
# Librerías utilizadas: random
# Librerías utilizadas: math
# Librerías utilizadas: statistics
import random
import numpy
import math
import statistics
inventory = 0
limite = 5
order = 0
costOrder = 50
costInventory = 26/200 #Costo de unidad de inventario al ano
costMissing = 25
missing = 0
totalMissing = 0
stock = 0
for day in range(0,200):
probDemanda = random.uniform(0, 1)
demanda = 8
if probDemanda < 0.99:
demanda = 7
if probDemanda < 0.96:
demanda = 6
if probDemanda < 0.88:
demanda = 5
if probDemanda < 0.7:
demanda = 4
if probDemanda < 0.4:
demanda = 3
if probDemanda < 0.2:
demanda = 2
if probDemanda < 0.1:
demanda = 1
if probDemanda < 0.04:
demanda = 0
# print("Todays demand", demanda)
if inventory < demanda: #Si el inventario es menor a la demanda
# print("Demanda", demanda, "inventory", inventory)
demanda = demanda - inventory #La demanda le restamos lo que tenemos
inventory = 0 #el inventari ose vuelve 0
missing += demanda #Le agregamos lo que nos falta de la demanda
totalMissing += demanda #se lo agregamos a los costos al final
elif inventory > demanda: #si el inventario es mayor
inventory -= demanda #le quitamos al inventario lo que nos hacia falta
stock += inventory #y al stock le agregamos el costo de inventario
if inventory <= limite: #Si nuestro inventario cae de 5 o menos
inventory += 15 # Ordenados 15 al inventario otra vez despues de cada dia
order += 1
# print("Reordenando 15 mas")
print("\nReordenando cuando el inventario es :", limite, " o menos" )
print("\nCostos en faltantes: $", totalMissing*costMissing)
print("Costos de ordenes: $", order*costOrder)
print("Costos de inventario: $",stock*costInventory)
print("\nCosto total al ano de 200 dias: $", (totalMissing*costMissing + order*costOrder + stock*costInventory))
| false |
ac233558523fd4d10a3f327417816cf9aafcfa9c | kchaoui/me | /week2/exercise1.py | 1,958 | 4.65625 | 5 | """
Commenting skills:
TODO: above every line of code comment what you THINK the line below does.
TODO: execute that line and write what actually happened next to it.
See example for first print statement
"""
import platform
# I think this will print "hello! Let's get started" by calling the print function.
print("hello! Let's get started") # it printed "hello! Let's get started"
some_words = ['what', 'does', 'this', 'line', 'do', '?']
#I think this will print the string contained in the list some_words
for word in some_words:
print(word) #this printed the words from the list in a column, each word from the list is assigned to'word'
#I think this will also print the string contained in the list some_words, x is the index of the string
for x in some_words:
print(x) #this also printed the words from the list in a column, the function assigns each word to 'x'
#I think it will print the string some_words
print(some_words) #prints the string some_words in square brackets and in a row
#I think this will print the phrase 'some_words contains more than 3 words' if the string contains more than 3 words, which it does
if len(some_words) > 3:
print('some_words contains more than 3 words') #it printed 'some_words contains more than 3 words' since there are more than 3 words in the string
#I think this will print out a namedtuple () in round brackets with information about my computer: system, node, release, version, machine, and processor.
def usefulFunction():
"""
You may want to look up what uname does before you guess
what the line below does:
https://docs.python.org/3/library/platform.html#platform.uname
"""
print(platform.uname()) #prints the following computer details: (system='Darwin', node='17kchaoui17', release='19.0.0', version='Darwin Kernel Version 19.0.0: Thu Oct 17 16:17:15 PDT 2019; root:xnu-6153.41.3~29/RELEASE_X86_64', machine='x86_64', processor='i386')
usefulFunction()
| true |
94101d0179b9826da4e12ed61fbb1f08cf93e7e5 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsEasy/543_Diameter_of_binary_tree.py | 2,650 | 4.40625 | 4 | '''
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
Idea:
At a given node, the maximum diameter seen till now is:
max ( left subtree max diameter, right sub tree max diamater, diameter including the current root)
diameter including the current root = 1 + maxPathStartingAtLeftChild + 1 + maxPathStartingAtRightChild
We also compute what the current node can offer interms of the number of edges if thi is selected to be in the diameter.
We pass up the maxdiameter till now and what the current node can offer if it is selected to be part of the diameter.
Why we need what the current node can offer?
Because in the node that called this node, to compute the diameter through that ode it needs to know the max path available in the
left chi;ld and right child then add 2 to it because it is contributing two edges.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def diameterOfBinaryTreeHelper(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# Base case
if not root:
return (0,0)
# Base case 2
elif not root.left and not root.right:
#print " At " + str(root.val)
return (0,0)
else:
(leftDiameter, leftMaxPath) = self.diameterOfBinaryTreeHelper(root.left)
(rightDiameter, rightMaxPath) = self.diameterOfBinaryTreeHelper(root.right)
diameterthroughRoot = 0
if(root.left):
diameterthroughRoot += 1 + leftMaxPath
if(root.right):
diameterthroughRoot += 1 + rightMaxPath
maxDiameterTillNow = max(leftDiameter, rightDiameter, diameterthroughRoot)
maxPathStartingAtRoot = 1 + max(leftMaxPath, rightMaxPath)
#print " At " + str(root.val)
#print " Max dia till now " + str(maxDiameterTillNow) + " max path startig at root " + str(maxPathStartingAtRoot)
return (maxDiameterTillNow, maxPathStartingAtRoot)
def diameterOfBinaryTree(self, root):
return self.diameterOfBinaryTreeHelper(root)[0]
| true |
5ac54dd56d88f98d8a0877706ef05f53f0bcbec1 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsEasy/461_HammingDistance.py | 1,254 | 4.15625 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Hints: XOR followed by count set bits. Counting set bits can be done in many ways. Lookup table in O(1). Brutoforce O(n) Brian- Kerninghan Thets(n)
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
"""
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
differing_positions = x ^ y
# Count set bits
# c = 0
# while(differing_positions):
# differing_positions &= differing_positions - 1
# c += 1
# return c
# Look up Table:
c = 0
bits_by_number = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
mask = 0xF
shifter = 4
for i in range(8):
c += bits_by_number[differing_positions & mask]
differing_positions = differing_positions >> shifter
return c
if __name__ == '__main__':
x = Solution()
print x.hammingDistance(1577962638, 1727613287)
| true |
41df50dd1f20e926992b910468b7c44859377dfe | Aurales/DataStructuresHomework | /Data Structures/Lab 04/Lab04A_KyleMunoz.py | 367 | 4.1875 | 4 | #Kyle Munoz
#Collatz Conjecture Recursively
def CollatzConjecture(n, c = 0):
if n == 1:
print("Steps Taken: ",c)
elif n % 2==0:
return CollatzConjecture(n/2, c + 1)
else:
return CollatzConjecture(((n * 3) + 1), c + 1)
def main():
x = int(input("What number would you like to try? "))
CollatzConjecture(x, c = 0)
main()
| true |
736b387e21f6927a74aedffd1580eb89d92a4f06 | feyfey27/python | /age_calculator.py | 669 | 4.25 | 4 | from datetime import datetime, date
def check_birthdate(year, month, day):
today = datetime.now()
birthdate = datetime(year, month, day)
if birthdate > today:
return False
else:
return True
def calculate_age(year,month,day):
today = datetime.now()
birthdate = datetime(year, month, day)
age = today - birthdate
print("You are %s years old" % (age.days / 365))
year = int(input("Enter year of birth: "))
month = int(input("Enter month of birth: "))
day = int(input("Enter day of birth: "))
if check_birthdate(year, month, day)==True:
calculate_age(year, month, day)
else:
print("invalid birthdate.")
# import datetime
# x = datetime.datetime.now()
| true |
84f9b09013e04222ed26dfc6af70fcc91dcf2324 | aindrila2412/DSA-1 | /Booking.com/power_set.py | 1,609 | 4.1875 | 4 | """
Given an integer array nums of unique elements, return all possible subsets
(the power set).
The solution set must not contain duplicate subsets. Return the solution in
any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
"""
def power_sets(nums):
"""
We define a backtrack function named backtrack(first, curr) which takes the
index of first element to add and a current combination as arguments.
1. If the current combination is done, we add the combination to the final
output.
2. Otherwise, we iterate over the indexes i from first to the length of the
entire sequence n.
- Add integer nums[i] into the current combination curr.
- Proceed to add more integers into the combination : backtrack(i + 1,
curr).
- Backtrack by removing nums[i] from curr.
"""
def backtrack(first=0, curr=[]):
# if the combination is done
if len(curr) == k:
output.append(curr[:])
return
for i in range(first, n):
# add nums[i] into the current combination
curr.append(nums[i])
# use next integers to complete the combination
backtrack(i + 1, curr)
# backtrack
curr.pop()
output = []
n = len(nums)
for k in range(n + 1):
backtrack()
return output
if __name__ == "__main__":
print(power_sets([1, 2, 3]))
| true |
b77cdbe352caec79714a00d9de8536ecb1bf15a6 | aindrila2412/DSA-1 | /Recursion/reverse_a_stack.py | 1,350 | 4.25 | 4 | """
Reverse a Stack in O(1) space using Recursion.
Example 1
Input: st = [1, 5, 3, 2, 4]
Output:[4, 2, 3, 5, 1]
Explanation: After reversing the stack [1, 5, 3, 2, 4]
becomes [4, 2, 3, 5, 1].
Example 2
Input: st = [5, 17, 100, 11]
Output: [11, 100, 17, 5]
Explanation: After reversing the stack [5, 17, 100, 11]
becomes [11, 100, 17, 5]
"""
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def top(self):
if self.is_empty():
return None
return self.stack[-1]
def pop(self):
if self.is_empty():
raise Exception("Underflow condition.")
return self.stack.pop()
def push(self, elm):
self.stack.append(elm)
def print_stack(self):
print(self.stack)
def insert_at_bottom(s, tmp_emp):
if s.is_empty():
s.push(tmp_emp)
else:
current_top = s.top()
s.pop()
insert_at_bottom(s, tmp_emp)
s.push(current_top)
def reverse_stack(s: Stack):
if s.is_empty():
return
tmp_elm = s.top()
s.pop()
reverse_stack(s)
insert_at_bottom(s, tmp_elm)
if __name__ == "__main__":
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.print_stack()
reverse_stack(s)
s.print_stack()
| true |
391ce6e49583edf602e8dca5690384ca5e614bfe | aindrila2412/DSA-1 | /Recursion/ways_to_climb_stairs.py | 1,342 | 4.125 | 4 | """
Given a staircase of n steps and a set of possible steps that we can climb at
a time named possibleSteps, create a function that returns the number of ways
a person can reach to the top of staircase.
Example:
Input:
n = 10
possibleSteps = [2,4,5,8]
Output: 11
Explanation:
[2,2,2,2,2], [2,2,2,4], [2,2,4,2], [2,4,2,2], [4,2,2,2], [4,4,2],
[2,4,4], [4,2,4], [5,5], [8,2], [2,8]
idea here is lets say if someone is at step 2, number of ways one can
jump to step 10 is (10-2)->8 ways and similarly
ways(10) = ways(10-2) + ways(10-4) + ways(10-5) + ways(10-8)
i.e:
ways(10) = ways(8) + ways(6) + ways(5) + ways(2)
ways to jump to 10-2
[2,2,2,2], [4,4] ,[2,2,4], [8], [2,4,2], [4,2,2]
"""
def wtj(stair, possible_steps, call_stack) -> int:
call_stack.append(stair)
print(call_stack)
if stair == 0: # only one way to jumping to step 0
call_stack.pop()
print(call_stack)
return 1
no_of_ways = 0
for steps in possible_steps:
if stair - steps >= 0:
no_of_ways += wtj(stair - steps, possible_steps, call_stack)
call_stack.pop()
print(call_stack)
return no_of_ways
if __name__ == "__main__":
stairs = 10
possible_steps = [2, 4, 5, 8]
print(wtj(10, possible_steps, []))
| true |
03eaa82c091996233aece88866bdf83c04b43d0a | aindrila2412/DSA-1 | /crackingTheCodingInterview/ArrayAndStrings/largest_number_at_least_twice_of_others.py | 1,445 | 4.3125 | 4 | """
You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much
as every other number in the array. If it is, return the index of the largest
element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Example 3:
Input: nums = [1]
Output: 0
Explanation: 1 is trivially at least twice the value as any other number
because there are no other numbers.
"""
def dominantIndex(nums):
"""
1. Iterate through the array and find largest, l_index
2. Iterate the array again and find if largest > 2*nums[i], if not
return -1
3. if yes return l_index
[1,2,3,4]
[3,6,1,0]
"""
if len(nums) == 1:
return 0
largest = -1
l_index = -1
for index, i in enumerate(nums):
if i > largest:
largest = i
l_index = index
print(largest, l_index)
for i in range(len(nums)):
if i == l_index:
pass
elif (2 * nums[i]) > largest:
print(nums[i], i)
return -1
return l_index
if __name__ == "__main__":
print(dominantIndex([3, 6, 1, 0]))
| true |
9bb56f95c93a03afdd983e623f94dad18e526228 | alicetientran/CodeWithTienAndHieu | /1-introduction/Task1-tien.py | 914 | 4.3125 | 4 | """
Task:
Ask the user for a number
Tell the user if the number is odd or even
Hint: use % operator
Extras:
If the number is a multiple of 3, print "Third time's a charm"
Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).
If {check} divides evenly into {num}, print "They are in a family".
If not, print "They are strangers"
"""
#number = int(input('Enter a number'))
#answer = number % 2
#if answer > 0:
#print("This is an odd number.")
#else:
#print("This is an even number.")
charm = int(input('Enter a number'))
task_2 = charm % 3
print(charm)
print(task_2)
if task_2 == 0:
print("Third time is a charm.")
#num = int(input("Enter the first number"))
#check = int(input("Enter the second number"))
#task_3 = check % num
#if task_3 > 0:
#print("They are strangers")
#else:
#print("They are in a family") | true |
b24e15f6714bd51c24148ecc514362f850623233 | houtan1/Python_Data_Cleaner | /helloworld.py | 888 | 4.25 | 4 | # run with python helloworld.py
# print("hello world")
# tab delimited text dataset downloaded from https://doi.pangaea.de/10.1594/PANGAEA.885775 as Doering-etal_2018.tab
# let's read in that data
file = open("data/Doering-etal_2018.tab", "r")
line = file.readlines()
# print(line[28])
# print(len(line))
for x in range(29, len(line)):
# print(line[x].split('\t'))
# print(len(line[x].split('\t')))
thisArray = line[x].split('\t')
# print(len(thisArray))
if thisArray[11] == "\n":
print("Missing Age! Length(mm): " + thisArray[9] + " Diameter(mm): " + thisArray[10])
file.close()
# the above script opens the tab delimited data file in read format
# it then reads the data portion of the file, row by row
# the script searches for data rows which are missing the value for age
# it flags those rows and informs the user of their length and diameter values
| true |
a583763a983846a55d86f58a5ac5146e40d273ce | tzwyf/Learning | /python/学习笔记/输入输出.py | 883 | 4.5 | 4 | # 用户输入
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
if(is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No,it is not a palindrome")
#pickle 模块
#Python 提供了一个叫做 pickle 的标准模块,使用该模块你可以将任意对象存储在
#文件中,之后你又可以将其完整地取出来。这被称为持久地存储对象。
import pickle
# the name of the file where we will store the object
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
#write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f)
f.close()
del shoplist
# read back form the storage
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f)
print(storedlist)
| false |
adde8bcdf70592e681d642befa152e0737ffc754 | marat-biriushev/PY4E | /py.py | 2,071 | 4.21875 | 4 | #!/usr/bin/python3
def f(x, y = 1):
"""
Returns x * y
:param x: int first integer to be added.
:param y: int second integer to be added (Not requared, 1 by default).
:return : int multiplication of x and y.
"""
return x * y
x = 5
#print(f(2))
#a = int(input('type a number'))
#b = int(input('type another number'))
#try:
# print(a / b)
#except ZeroDivisionError:
# print('b cannot be zero. Try again')
def fac(x):
"""
Returns x!
:param x: int integer to be added
:return : int integer x!
"""
if x == 1 or x == 0:
return 1
else:
return x * fac(x-1)
print(fac(4))
#class Orange:
#
# def __init__ (self, weight, color, mold):
# """ all weights are in oz"""
# self.weight = weight
# self.color = color
class Orange():
def __init__(self):
"sfsdf"
self.weight = 6
self.color = 'orange'
self.mold = 0
def rot(self, days, temp):
self.mold = days*(temp* .1)
#################################
#########INHERITANCE#############
#################################
lass Adult():
def __init__(self, name, height, weight, eye):
"comment"
self.name = name
self.height = height
self.weight = weight
self.eye = eye
def print_name(self):
print(self.name)
tom = Adult("Tom", 6, 100, "green")
tom.print_name()
class Kid(Adult):
def print_cartoon(self, fav_cartoon):
print("{}'s favorite cartoon id {}".format(self.name, fav_cartoon))
child = Kid("Lauren", 3, 50, "blue")
child.print_name()
child.print_cartoon('TEST')
####################################################
#################################
#########Composition#############
#################################
class Dog():
def __init__(self, name, breed, owner):
self.name = name
self.breed = breed
self.owner = owner
class Person():
def __init__(self, name):
self.name = name
mik = Person("Mik Jagger")
dog = Dog("Stanley", "Bulldog", mik)
print(dog.owner.name)
| true |
0f71e4012a72306a5c67cae91d404a2229d641c4 | marat-biriushev/PY4E | /ex_7_1.py | 2,122 | 4.625 | 5 | #!/usr/bin/python3
''' Exercise 1: Write a program to read through a file
and print the contents of the file (line by line) all
in upper case.'''
fname = input('Enter a filename: ')
fhand = open(fname)
for line in fhand:
line = line.upper()
line = line.rstrip()
print(line)
############################################
#!/usr/bin/python3
''' Exercise 2: Write a program to prompt for a
file name, and then read through the file and look for
lines of the form: X-DSPAM-Confidence: 0.8475
When you encounter a line that starts with "X-DSPAM-Confidence:"
pull apart the line to extract the floating-point number on the line.
Count these lines and then compute the total of the spam confidence
values from these lines. When you reach the end of the file, print out
the average spam confidence. Average spam confidence: 0.750718518519 '''
fname = input('Enter the filename: ')
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
exit()
count = 0
snum = 0
for line in fhand:
line = line.rstrip()
if line.find('X-DSPAM-Confidence:') == -1:
continue
print(line, float(line[19:]))
snum = snum + float(line[19:])
count += 1
print(snum / count)
print('###########################')
############################
''' Exercise 3: Sometimes when programmers get bored or want to have
a bit of fun, they add a harmless Easter Egg to their program.
Modify the program that prompts the user for the file name so that
it prints a funny message when the user types in the exact file
name "na na boo boo". The program should behave normally for all
other files which exist and don't exist.'''
fname = input('Enter the file name: ')
search = input('Type what are you searching for: ')
if fname == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
exit()
try:
fhand = open(fname)
except:
print('File cannot be opened!', fname)
exit()
count = 0
for line in fhand:
line = line.rstrip()
if line.find(search) == -1:
continue
count += 1
print('Thete were {} {} lines in {}'.format(count, search, fname))
| true |
889e82e3ca53f9e78d1ed1aaf2573b2fc32ab599 | Rodrigs22/ExerciciosCursoEmvideo | /PycharmProjects/PythonexExercícios/ex037.py | 547 | 4.1875 | 4 | numero = int(input('digite um numero inteiro para transformar: '))
c1 = int(input('''[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL
Escolha: '''))
if c1 == 1:
print('O numero {} convertido em binário é, {}.'.format(numero, bin(numero)[2:]))
elif c1 == 2:
print('o Numero {} convertido em octal é, {}.'.format(numero, oct(numero)[2:]))
elif c1 == 3:
print('O numero {} convertido em Hexadecimal é, {}.'.format(numero, hex(numero)[2:]))
else:
print('opção invalida, tente novamente!') | false |
63d20821cc349256ae4929da0ef0a2691713a831 | gchristofferson/credit.py | /credit.py | 2,681 | 4.15625 | 4 | from cs50 import get_int
import math
# prompt user for credit card
# validate that we have a positive integer between 13 and 16 digits
while True:
ccNum = get_int('Enter Credit Card Number: ')
if ccNum >= 0:
break
# reset value of ccNum
copyCCNum = ccNum
count = 0
# count the number of digits in the integer provided by user
while ccNum > 0:
ccNum = math.floor(ccNum / 10)
count += 1
# if user provides a number less than 13 or more than 16, print 'INVALID'
if count < 13 or count > 16:
print('INVALID')
quit()
# reset value of ccNum
ccNum = copyCCNum
# access company identifier (2 digits) at the beginning of card number
divNum = 1
if count == 13:
divNum = 100000000000
elif count == 14:
divNum = 1000000000000
elif count == 15:
divNum = 10000000000000
elif count == 16:
divNum = 100000000000000
identifier = math.floor(ccNum / divNum)
# validate the identifier and assign company to the number if valid
company = ''
if identifier == 34 or identifier == 37:
company = 'AMEX'
elif identifier >= 40 and identifier <= 49:
company = 'VISA'
elif identifier >= 51 and identifier <= 55:
company = 'MASTERCARD'
# if no valid identifier is found, print 'INVALID'
if company == '':
print('INVALID')
# if card doesn't have required number of digits for the company, print 'INVALID'
if company == 'AMEX' and count != 15:
print('INVALID')
quit()
if company == 'VISA' and count < 13:
print('INVALID')
quit()
if company == 'VISA' and count > 16:
print('INVALID')
quit()
if company == 'MASTERCARD' and count != 16:
print('INVALID')
quit()
# validat that we have a real credit card number
# for valid company and number, start with second-to-last digit & multiply every other digit by 2 & then sum those digits
product, splitA, splitB, theSum, secondLastNum = 0, 0, 0, 0, 0
while ccNum > 0:
ccNum = math.floor(ccNum / 10)
secondLastNum = math.floor(ccNum % 10)
product = math.floor(secondLastNum * 2)
splitA = math.floor(product % 10)
splitB = math.floor(product / 10)
theSum = math.floor(theSum + (splitA + splitB))
ccNum = math.floor(ccNum / 10)
ccNum = copyCCNum
# add sum to remaining digits
lastNum = 0
while ccNum > 0:
lastNum = math.floor(ccNum % 10)
ccNum = math.floor(ccNum / 100)
theSum = math.floor(theSum + lastNum)
# validate checksum
lastNumDigit = theSum % 10
if company == 'AMEX' and lastNumDigit == 0:
print('AMEX')
quit()
elif company == 'VISA' and lastNumDigit == 0:
print('VISA')
quit()
elif company == 'MASTERCARD' and lastNumDigit == 0:
print('MASTERCARD')
quit()
else:
print('INVALID')
quit() | true |
dcb7085f360547f5cf4fe1b3f324dedd937b8e02 | rylee-boop7/booga_booga_123 | /celsius.py | 480 | 4.125 | 4 | temp = input ("Imput the tempurture you like to convert? (e.g., 45f, 102c etc.) : ")
degree = int(temp[: _1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() =="F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("input proper conventqion.")
quit()
print("the temperture in", o convention, "is" , result, "degrees.")
| false |
72b76b4fdadfd01b0139c323b6412008fd70e90d | omi-akif/My_Codes | /Python/DataAnalysis/MIS401/Class Resource/1st Class/MIS401-Class 1.py | 1,402 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[12]:
# In[17]:
Name ='Kazi' #Assigning String Variable
# In[56]:
Age=28 #assigning variable
# In[15]:
Name #Printing varibale without using Print
# In[16]:
Age #Printing varibale without using Print
# In[18]:
Name
# In[19]:
print(Name)
# In[21]:
print(Age)
# In[23]:
print(type(Age)) #printing type of age variable
# In[24]:
type(Name)
# In[25]:
num1=47 #assigning num1 and num2
num2=9
# In[34]:
num1%num2 # We have used +,_,*,/,**,//,%
# In[35]:
100000000000**10 # 1 Trillion*power10
# In[36]:
amount=100000 #assigning varibale
Interest_rate=.12
Years=7
# In[40]:
Final_Amount=amount*Interest_rate*Years
# In[41]:
print(Final_Amount)
# In[49]:
final_amount=amount+(amount*Interest_rate*Years)
# In[50]:
print(final_amount)
# In[47]:
Interst=(amount*Interest_rate)/100
# In[48]:
print(Interst)
# In[55]:
Height=1.73
Weight=87
BMI=Weight/(Height)**2
# In[54]:
print(BMI)
# In[59]:
a="Dhaka"
b="Cumilla"
# In[60]:
a+b
# In[62]:
c="100"
# In[63]:
c*10
# In[64]:
new_c=int(c)
# In[65]:
new_c
# In[66]:
d=100
# In[67]:
new_d=float(d)
# In[68]:
new_d
# In[69]:
old_d=int(new_d)
# In[70]:
type(old_d)
# In[71]:
old_d
# In[72]:
e=120
# In[73]:
type(e)
# In[74]:
new_e=str(e)
# In[75]:
new_e
# In[ ]:
| true |
954959ab38ebc709a8f81657b636fcf5f6d3ede3 | tiago-falves/FPRO-Python | /RE/Outros/min_path.py | 1,790 | 4.15625 | 4 | """
5. Minimum path
Write a function min_path(matrix, a, b, visited=[]) that discovers the minimum path
between a and b inside the matrix maze without going through visited twice. Positions a
and b are tuples (line, column), matrix is a matrix of booleans with False indicating no
obstacle and True indicating an obstacle and visited is a list of visited tuples. Valid
movements include all 8 adjacent tiles.
For the maze of the following figure, a minimum path between a and b, in yellow, is 4:
b
a
Save the program in the file min_path.py inside the folder PE3.
For example:
mx = [
[False]*4,
[False, True, False, False],
[False, True, False, False],
[False]*4
]
min_path(mx, (2, 0), (0, 3)) returns the integer 4
min_path(mx, (3, 1), (0, 1)) returns the integer 3
min_path(mx, (0, 0), (3, 3)) returns the integer 4
"""
inf = 1e100
def min_path(matrix, a, b, visited=[]):
if (a[0]<0 or len(matrix ) <= a[0] or a[1]<0 or len(matrix[0]) <= a[1]):
return inf
if a in visited:
return inf
if matrix[a[0]][a[1]]:
return inf
if a == b:
return 0
visited.append(a)
potNW = (a[0]-1, a[1]-1); potNN = (a[0], a[1]-1); potNE = (a[0]+1, a[1]-1)
potWW = (a[0]-1, a[1] ); potEE = (a[0]+1, a[1] )
potSW = (a[0]-1, a[1]+1); potSS = (a[0], a[1]+1); potSE = (a[0]+1, a[1]+1)
l = [potNW, potNE,\
potSW, potSE,\
potNN, potWW, potEE, potSS]
r = inf
for t in l:
r = min(r, min_path(matrix, t, b, visited[:]))
return r+1
"""
mx = [\
[False]*4,\
[False, True, False, False],\
[False, True, False, False],\
[False]*4\
]
print(min_path(mx, (2, 0), (0, 3)))
print(min_path(mx, (3, 1), (0, 1)))
print(min_path(mx, (0, 0), (3, 3)))
"""
| true |
9b2f498eb5a9866cf6feb8f99303d850812b6fb5 | kaizokufox/Python | /ExercRepetição.py | 2,458 | 4.125 | 4 | #1) calcular a soma dos numeros digitados e a media
'''
soma = 0
media = 0
numero = 1
qdt = 0
while numero != 0 :
numero = int(input("Digite um numero: "))
if numero != 0:
soma = soma + numero
qdt = qdt + 1
media = soma / qdt
print("A soma dos números é: %d " % soma)
print("A media dos números é: %d " % media)
'''
#2) somar os pares de 10 numeros
'''
soma = 0
x = 0
while x <10 :
numero = int(input("Digite um número: "))
if (numero % 2) == 0 :
soma = soma + numero # somando o contador
x = x +1
print("A soma dos numeros pares: %d " % soma)
'''
#3)programa q ler 10 numero e mostra os positivos, negativos e 0
'''
x = 0
soma = 0
negat = 0
zero = 0
while x < 5:
numero = int(input("Digite um numero: "))
if numero < 0:
negat = negat + 1
elif numero > 0 :
soma = soma + 1# contador da condição
else:
zero = zero + 1
x=x+1# contador do while
print("Soma dos numeros negativos: %d e dos numeros zero: %d e numeros inteiros: %d" % (negat, zero, soma))
'''
#4)Repetidor de 0 a 50 convertendo celsius para farenheit
'''
tf = 0
tc = 0
while tc < 51:
print("%.2f Graus Celsius para %.2f graus Farenheit:" % (tc, tf ))
tf = (1.8 * tc) + 32
tc = tc +1
print("saiu")
'''
'''
#5)
media = 0
media_turma = 0
soma = 0
conta = 0
while media >= 0:
media = float(input("Digite a media do aluno: "))
if media >=0:
soma = soma + media
conta += 1
media_turma = soma / conta
print("A media da turma é: %.2f " % media_turma)
'''
#Exercicios de FOR
#1)
'''
for i in range (10, 151):
print("%d ao quadrado = %d" % (i, i * i))
'''
#2)
'''
numero = int(input("Digitr um numero: "))
f = 1
#indo de 1 ate numero
for i in range (1, numero+1):
f = f *i
print("Fatorial de %d: %d " % (numero, f))
f = 1
# indo de numero até 1, decrementando em 1
for i in range (numero,0 ,-1):
f = f *i
print("Fatorial de %d: %d " % (numero, f))
'''
#3)
'''
numero = int(input("Digite um numero: "))
for i in range (1, 11):
print("%d X %d = %d" % (numero, i, numero*i))
'''
'''
#4)
numero = int(input("Digite um número: "))
cont = 0
for i in range(2, numero):
if numero % i == 0:
cont = cont + 1
break
if cont == 0:
print("%d é primo" % numero)
else:
print("%d não é primo" % numero)
'''
| false |
8180da315e37a3b95d2b2a5bb98f70040a5951cb | kaizokufox/Python | /Exerc2.py | 1,214 | 4.53125 | 5 | #print("flavia e te amo")
#Operadores aritméticos auxiliares em python
''' ** potenciação Exemplo -> 2**3 = 8
math.sqr Radiciação exemplo -> math.sqrt(4) = 2
% Resto de Divisão Exempl -> 4%3 = 1'''
#Prioridades
'''Pareneses mais internos
pot rad
* / mod
+ -'''
#Exemplo/Exemplo de operação arimética
# A soma de dois números inteiros:
'''num1 = input('Digite um número inteiro: ')
num2 = input('Digite outro número inteiros: ')
num1 = int(num1)
num2 = int(num2)
soma = num1 + num2
#Três maneiras de apresentar o resultado:
print('A soma entre %s e %d vale %d' % (num1, num2, soma))
print('A soma entre', num1, 'e', num2, 'vale', soma)
print('A soma entre {} e {} vale {}'.format(num1,num2,soma))'''
#Exercicio 1
print("Exercício 1")
salario = input('Digite um salário: ')
salario = float(salario)
salario = salario * 1.15
print("Salário com reajuste é de : %.2f " %(salario))
'''
#Exercicio 2
print("Exercício 2")
c = input('Digite o valor do comprimento: ')
c = float(c)
l = input('Digite o valor da largura: ')
l = float(l)
h = input('Digite o valor do volume: ')
h = float(h)
v = c*l*h
print('O volume do Paralelepípedo é: %.2f ' %(v))
'''
| false |
c0896304188088cb6bfa4644741f6ac469b07a28 | absupriya/Applied-Algorithms | /1. Bubble sort/bubble_sort.py | 2,273 | 4.375 | 4 | #Reading the entire input file
orig_file=open('input.txt','r').readlines()
#Convert the input data from strings to integer data type
orig_file = list(map(int, orig_file))
#Create an empty list to hold the average elapsed time and the number of inputs
avg_elap_time_list=[]
num_of_inputs_to_sort=[]
#Setting up the array length in the frequency of 500
for alen in range(500,10001,500):
#Filtering out the requisite input data to be sorted from the original array list.
file=orig_file[0:alen]
#Running the algorithm to run for the same input data 3 times.
for runs in range(3):
elapsed_time=0
#Calculation of the running time.
"""Below 2 lines of code to calculate the running time was referred to in the website
https://stackoverflow.com/questions/15707056/get-time-of-execution-of-a-block-of-code-in-python-2-7"""
import timeit
start_time = timeit.default_timer()
#Bubble sort begins
#Reading through the entire array of numbers
for i in range(0,alen):
#Reading through the array list from the end
for j in range(alen-1,i,-1):
if file[j] < file[j-1]:
file[j], file[j-1] = file[j-1], file[j]
#Bubble sort ends
#Calculating the elapsed time
stop_time = timeit.default_timer()
run_time = stop_time - start_time
elapsed_time=+ run_time
#Calculate the average elapsed time for each iterations
avg_elapsed_time=round((elapsed_time/3),6)
#Append the time and number of inputs to a list for plotting graphs
avg_elap_time_list.append(avg_elapsed_time)
num_of_inputs_to_sort.append(alen)
#importing pyplot package from matplotlib library.
"""Below code to plot the graph was referred to in the website
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot"""
import matplotlib.pyplot as plt
#Defining the x-axis and y-axis data and labels to plot the graph
x=num_of_inputs_to_sort
y=avg_elap_time_list
plt.plot(x, y,'r')
plt.xlabel('Number of Inputs')
plt.ylabel('Time')
plt.title("Bubble sort running time versus the number of inputs")
plt.show() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.