blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ac89d9024de18d1c8b50ecf983248ac2eb757e03 | connorS119987/CNA267-Spring-Semester-2020 | /CH05/23Lab5-3.py | 305 | 4.25 | 4 | #------------------------------------#
# Connor Seemann Seat 23 Lab 5.2 #
#------------------------------------#
# This program will display a staircase of numbers
print("This program will display a staircase of numbers")
for i in range(1, 7 + 1):
for j in range(1, i):
print(j, end='')
print()
| true |
b027f055ea16d1edd45afc9defb7d809a5c960d5 | ConnorMaloney/AOCStudy | /2018/Python/Sandbox/questionSix.py | 549 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
'''
Let a and b be positive integers such that ab + 1 divides a^2 + b^2.
Show that a^2 + b^2 / ab + 1 is the square of an integer.
'''
import random
from math import sqrt
def question_six(a,b):
return ((a**2 + b**2) / (a*b + 1))
def is_square(n):
return sqrt(n).is_integer()
for x in range(1,100000001):
a = random.randint(1,1001)
b = random.randint(1,1001)
#print(a,b)
if (is_square(question_six(a,b))):
print(a,b)
| true |
5e4a761f319753507141b940763710350f5e8ab8 | LisCoding/Python-playground | /dictionary_basics.py | 546 | 4.625 | 5 | # Assignment: Making and Reading from Dictionaries
# Create a dictionary containing some information about yourself.
# The keys should include name, age, country of birth, favorite language.
# Write a function that will print something like the following as it executes:
my_info = {
"name": "Liseth",
"age": 27,
"country": "Bolivia",
"favority_lenguage": "Ruby"
}
print "My name is:", my_info["name"]
print "My age is:", my_info["age"]
print "My country is:", my_info["country"]
print "My favority lenguage is:", my_info["favority_lenguage"]
| true |
ba23cd3a47498efe55c1cffaa07a62b39ec74ccc | LisCoding/Python-playground | /coin_tosses.py | 1,395 | 4.15625 | 4 | # Assignment: Coin Tosses
# Write a function that simulates tossing a coin 5,000 times. Your function should print
# how many times the head/tail appears.
#
# Sample output should be like the following:
# Starting the program...
# Attempt #1: Throwing a coin... It's a head! ... Got 1 head(s) so far and 0 tail(s) so far
# Attempt #2: Throwing a coin... It's a head! ... Got 2 head(s) so far and 0 tail(s) so far
# Attempt #3: Throwing a coin... It's a tail! ... Got 2 head(s) so far and 1 tail(s) so far
# Attempt #4: Throwing a coin... It's a head! ... Got 3 head(s) so far and 1 tail(s) so far
# ...
# Attempt #5000: Throwing a coin... It's a head! ... Got 2412 head(s) so far and 2588 tail(s) so far
# Ending the program, thank you!
import random
num = 5000
def coin_tosses(num):
head, tails = 0, 0
print "Starting the program"
for i in range(1, num+1):
toss_coin_res = random.random()
toss_coin_res = round(toss_coin_res)
if toss_coin_res == 1:
head += 1
print "Attempt #" + str(i) + ": Throwing a coin... It's a head! ... Got " + str(head) + " head(s) so far and " + str(tails) + " tail(s) so far"
else:
tails += 1
print "Attempt #" + str(i) + ": Throwing a coin... It's a tail! ... Got " + str(head) + " head(s) so far and " + str(tails) + " tail(s) so far"
print
coin_tosses(num)
| true |
b459267ba763621fde1026adb4ceb2afdbe5cec8 | prithajnath/Algorithms | /Sorts/merge_sort.py | 967 | 4.1875 | 4 | #!/usr/bin/python3
# MergeSort
# Kevin Boyette
def merge_sort(array):
if len(array) <= 1:
return array
else:
left = []
right = []
middle = len(array) // 2
for eachLeftOfMiddle in array[:middle]:
left.append(eachLeftOfMiddle)
for eachRightOfMiddle in array[middle:]:
right.append(eachRightOfMiddle)
left = merge_sort(left)
right = merge_sort(right)
if left[-1] <= right[0]:
left.extend(right)
return left
result = merge(left, right)
return result
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left[1:]
else:
result.append(right[0])
right = right[1:]
if len(left) > 0:
result.extend(left)
if len(right) > 0:
result.extend(right)
return result
| false |
28c7d53836fef43aefe02088cafb730f63ca2502 | vinothini92/Sorting_algorithms | /mergesort_iterative.py | 1,030 | 4.1875 | 4 | def mergesort_iterative(nums):
length = len(nums)
if length < 2:
print "array is already in sorted order"
return
step = 1
while step < length:
i = 0
j = step
while j + step <= length:
merge(nums,i,i+step,j,j+step)
i = j + step
j = i + step
if j < length:
merge(nums,i,i+step,j,length)
step = step*2
print "sorted array: "
print nums
def merge(nums,l,m,r,q):
temp1 = []
temp2 = []
i,k =0,r
while(i<len(temp2)-1):
temp2.append(nums[k])
k+=1
j,p = 0,1
while(j<len(temp1)-1):
temp1.append(nums[p])
p+=1
s,x,y= l,0,0
while(s<q):
nums.append(min(temp2[x],temp2[y])
def get_input():
a=[]
while(1):
x = int(raw_input())
if(x==-1):
break
a.append(x)
return a
if __name__ == '__main__':
#get input from user
nums = get_input()
#sort the list
mergesort_iterative(nums)
| true |
5468009ffd7e5673c98643efbdfb0e8bbbac8d9e | Shreyassavanoor/grokking-coding-interview | /1_sliding_window/max_sum_subarray.py | 772 | 4.25 | 4 | '''Given an array of positive numbers and a positive number ‘k’,
find the maximum sum of any contiguous subarray of size ‘k’.
Ex:1
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
'''
def find_max_sum_subaarray(arr, k):
window_start = 0
max_sum = 0
window_sum = 0
for window_end in range(len(arr)):
window_sum += arr[window_end]
if window_end >= k - 1:
max_sum = max(max_sum, window_sum)
window_sum -= arr[window_start]
window_start += 1
print(f'Maximum sum is {max_sum}')
def main():
find_max_sum_subaarray([2, 1, 5, 1, 3, 2], 3)
find_max_sum_subaarray([2, 3, 4, 1, 5], 2)
if __name__ == '__main__':
main() | true |
df7c65ec8e67a28961f914ce8ffeafb6ca35af38 | DizzleFortWayne/python_work | /Learning Modules/Python_Basics/bicycles.py | 467 | 4.53125 | 5 | ## Learning lists
bicycles=['trek','cannondale','redline','specialized']## brackets create list
##print(bicycles) prints full list
##print(bicycles[0]) ## prints first (0) on the list
##print(bicycles[0].title()) ## Capitalizes like a title
##print(bicycles[-1]) ## -1 prints the last of the list
## -2 is second from the last -3 is third from the last and so on
##using with a variable
message="My first bike was a " +bicycles[0].title() +"."
print(message)
| true |
b4ebe9e15eeb10a523356d2047cb0c6b4b1b9c97 | nayana8/Prep1 | /Interview-Week2/goldStars.py | 1,789 | 4.125 | 4 | """
Alice is a teacher with a class of n children, each of whom has been assigned a numeric rating. The classroom is seated in a circular arrangement, with Alice at the top of the circle. She has a number of gold stars to give out based on each child's rating, but with the following conditions:
Each child must receive at least one gold star
Any child with a higher rating than his or her immediate neighbor should get more stars than that neighbor
Assuming n >= 3, what is the minimum total number of stars Alice will need to give out?
Write a program which takes as its input an int[] containing the ratings of each child, ordered by seating position, and returns an int value for the minimum total number of stars that Alice will need to give out.
Hint: this problem can be solved with an algorithm that runs in O(n) time.
For example:
In a class of three children with ordered ratings of {1, 2, 2}, Alice will need to give out {1, 2, 1} stars accordingly, for a total number of 4 stars overall
"""
import sys
def getStars(arr):
if len(arr) == 0:
return 0
if len(arr) == 1:
return 1
stars = []
if arr[0] > arr[1]:
stars.append(2)
else:
stars.append(1)
for i in range(1,len(arr)):
cur = arr[i]
neigh = arr[i-1]
if neigh >= cur:
stars.append(stars[i-1]-1)
else:
stars.append()
stars.append(stars[i-1]+1)
#print stars
totalStars = 0
for i in range(len(stars)):
if stars[i] <= 0:
totalStars += i + 1
else:
totalStars += stars[i]
#print totalStars
return totalStars
def main():
arr = [7,6,5,4,3,2]
res = getStars(arr)
print res
if __name__ == "__main__":
main()
| true |
b10dd96c07453971d05d96317426b0dafab1c873 | echau01/advent-of-code | /src/day7.py | 1,962 | 4.1875 | 4 | from typing import Dict
# Each bag type T is associated with a dict that maps bag types to the quantities
# of those bag types that T must contain.
rules: Dict[str, Dict[str, int]] = dict()
def contains(bag_type: str, target_type: str) -> bool:
"""
Returns True if a bag with type bag_type must eventually contain a bag with
type target_type. Returns False otherwise.
"""
if bag_type == target_type:
return True
inner_bag_types = rules[bag_type]
for _bag_type in inner_bag_types:
if contains(_bag_type, target_type):
return True
return False
def num_bags(bag_type: str) -> int:
"""
Returns the number of bags contained inside the bag with given type.
Does not include the outermost bag itself.
"""
result = 1
for key, value in rules[bag_type].items():
# We add 1 to num_bags(key) so that we count the actual bag with type key.
result += value * (num_bags(key) + 1)
return result - 1
with open("day7.txt", "r") as f:
for line in f:
line = line.strip(".\n")
line_components = line.split(" contain ")
bag_type = " ".join(line_components[0].split(" ")[:-1])
bag_rules = line_components[1].split(", ")
if bag_type not in rules:
rules[bag_type] = dict()
if bag_rules[0] != "no other bags":
for rule in bag_rules:
rule_components = rule.split(" ", 1)
quantity = int(rule_components[0])
inner_bag_type = " ".join(rule_components[1].split(" ")[:-1])
rules[bag_type][inner_bag_type] = quantity
gold_bag_counter = 0
for bag_type in rules:
if contains(bag_type, "shiny gold"):
gold_bag_counter += 1
# Why do we subtract 1? We want to calculate the number of bag types *other* than "shiny gold"
# that eventually contain a shiny gold bag.
print(gold_bag_counter - 1)
print(num_bags("shiny gold"))
| true |
3a68961820b57fbe002b739c49dac2a725d600f1 | qidCoder/python_OOPbankAccount | /OOP_bankAcount.py | 2,482 | 4.21875 | 4 | #Created by Shelley Ophir
#Coding Dojo Sep. 30, 2020
# Write a new BankAccount class.
# The BankAccount class should have a balance. When a new BankAccount instance is created, if an amount is given, the balance of the account should initially be set to that amount; otherwise, the balance should start at $0.
class BankAccount:
def __init__(self, amount = 0, rate = 0.01):
self.balance = amount
# The account should also have an interest rate, saved as a decimal (i.e. 1% would be saved as 0.01), which should be provided upon instantiation. (Hint: when using default values in parameters, the order of parameters matters!)
self.rate = rate
# The class should also have the following methods:
# deposit(self, amount) - increases the account balance by the given amount
def deposit(self, amount):
self.balance += amount
return self
# withdraw(self, amount) - decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5
def withdrawl(self, amount):
if (self.balance - amount < 0):
print("Insufficient funds: Charging a $5 fee")
self.balance -= 5
else:
self.balance -= amount
return self
# display_account_info(self) - print to the console: eg. "Balance: $100"
def display_account_info(self):
print("Balance:", self.balance)
# yield_interest(self) - increases the account balance by the current balance * the interest rate (as long as the balance is positive)
def yield_interest(self):
if (self.balance > 0):
self.balance = format(self.balance * (1 + self.rate), ".2f")
#round to 2 decimal places
return self
# Create 2 accounts
# To the first account, make 3 deposits and 1 withdrawal, then yield interest and display the account's info all in one line of code (i.e. chaining)
account1 = BankAccount(rate = .03)
account1.deposit(10).deposit(30).deposit(60).withdrawl(40).yield_interest().display_account_info()
# To the second account, make 2 deposits and 4 withdrawals, then yield interest and display the account's info all in one line of code (i.e. chaining)
account2 = BankAccount(rate = .05)
account2.deposit(80).deposit(45).withdrawl(1).withdrawl(3).withdrawl(5).withdrawl(18).yield_interest().display_account_info() | true |
d10b96f7262f0b9e028a2fc0d72328c3aadebe21 | czer0/python_work | /Chapter4/4-3_counting_to_twenty.py | 326 | 4.40625 | 4 | # Using for loops to print the numbers 1 to 20
# Method 1 - create a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
for numbers in numbers:
print(numbers)
print ("\n")
# Method 2 - generate list
numbers = [value for value in range (1,21)]
for numbers in numbers:
print(numbers)
| true |
cb428fa6112712e7d084f7bfdfb94d26b202e11f | czer0/python_work | /Chapter7/7-3_multiples_of_ten.py | 262 | 4.15625 | 4 | prompt = "Enter a number, and I'll tell you if it's "
prompt += "a multiple of ten: "
number = input(prompt)
number = int(number)
if number % 10 == 0:
print(str(number) + " is a multiple of ten")
else:
print(str(number) + " is not a multiple of ten")
| true |
36f11b0637f48e7418019fd1aea58eeedbae3509 | czer0/python_work | /Chapter6/6-11_cities.py | 1,110 | 4.84375 | 5 | # Uses a dictionary called cities with the names of three cities as
# keys. Uses a nested dictionary of information about
# each city which includes the country that the city is in, its
# approximate population, and a fact about the city. The keys for each
# city’s dictionary are country, population, and fact
# Output prints the name of each city and all of the information stored
# about it.
cities = {
'halifax': {
'country': 'canada',
'population': '403,131',
'fact': 'located in nova scotia',
},
'toronto': {
'country': 'canada',
'population': '2810000',
'fact': 'located in ontario',
},
'vancouver': {
'country': 'canada',
'population': '2,463,431',
'fact': 'located in british columbia',
},
}
for city, info in cities.items():
country = info['country']
pop = info['population']
fact = info['fact']
print("\nThe city of " + city.title() + ", " + country.title() + " has " +
str(pop) + " living in it as of 2016, and is " + fact + ".")
| true |
a4578f52a1ab2d87cdeca56f75a60dcf98a1f952 | feladie/D07 | /HW07_ch10_ex02.py | 793 | 4.25 | 4 | # I want to be able to call capitalize_nested from main w/ various lists
# and get returned a new nested list with all strings capitalized.
# Ex. ['apple', ['bear'], 'cat']
# Verify you've tested w/ various nestings.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
def capitalize_nested(t):
"""Capitalizes all strings within a nested list
"""
res = [] # resulting list
for s in t: # for each item in list
if isinstance(s, str): # if string
res.append(s.capitalize())
else: # if list
res.append(capitalize_nested(s))
return res
def main():
# print(capitalize_nested(['anna', 'anthony', 'andrew']))
# print(capitalize_nested([['anna', 'anthony', ['angel']], 'andrew']))
...
if __name__ == '__main__':
main()
| true |
22d3c0954921f4cc18a50b7dd2a5242eec080dba | meekmillan/cti110 | /M6T2_McMillan.py | 369 | 4.40625 | 4 | #CTI-110
#M6T2 - feet to inches conversion
#Christian McMillan
#11/30
#This program will convert feet to inches
# km to mi
ft_inch = 12
def main():
# feet input
ft = float(input('Enter a distance in feet:'))
show_inch(ft)
def show_inch(ft):
# conversion
inch = ft * ft_inch
# display inches
print(ft, 'feet equals', inch, 'inches')
main()
| true |
6134935d22a54e6d840c065065136f3afb0d4d0f | CharlesIvia/python-exercises-repo | /Palindromes/palindrome.py | 306 | 4.25 | 4 | #Write a Python function that checks whether a word or phrase is palindrome or not
def palindrome(word):
text = word.replace(" ", "")
if text == text[::-1]:
return True
else:
return False
print(palindrome("madam"))
print(palindrome("racecar"))
print(palindrome("nurses run")) | true |
9fd654c67138f52c97a833d0bf12982f761aa27d | Abdur-Razaaq/python-operators | /main.py | 778 | 4.28125 | 4 | # Task 1 Solution
# Pythagoras
# Given two sides of a right angled triangle calculate the third side
# Get two sides from the user ie. AB & BC
ab = input("Please enter the length of AB: ")
bc = input("Please enter the length of BC: ")
ac = (int(ab)**2 + int(bc)**2)**(1/2)
print("AC is: " + str(ac))
# Calculating the area
area = (int(bc) * int(ab))/2
print("The area of the right angled triangle is: " + str(area))
# Converting the area to Binary
print("The area of the right angled triangle in binary is: " + bin(int(area)))
# Finding the lowest and highest numbers in a list.
my_list = [2, 56, 12, 67, 1000, 32, 89, 29, 44, 39, 200, 11, 21]
print("The highest number in my list is: " + str(max(my_list)))
print("The lowest number in my list is: " + str(min(my_list)))
| true |
4f8e1140f52b020a5f75ffe14e50e7ebb5847d38 | fsckin/euler | /euler-4.py | 604 | 4.21875 | 4 | # A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def palindrome(object):
object = str(object)
if object[::-1] == object:
return True
else:
return False
largest_palindrome=0
for x in range(100, 1000):
for y in range(100, 1000):
product=x*y
if palindrome(product):
if product >= largest_palindrome:
largest_palindrome = product
print(str(largest_palindrome))
| true |
3f075fb88594147f94bc91f346d9987cb1ed95d3 | omertasgithub/data-structures-and-algorithms | /leet code/Array/1572. Matrix Diagonal Sum.py | 499 | 4.15625 | 4 | #1572. Matrix Diagonal Sum
#related topics
#array
mat = [[1,2,3],
[4,5,6],
[7,8,9]]
mat2 = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
mat3 = [[5]]
#first solution
def diagonalSum(mat):
l=len(mat[0])
s=0
for i in range(l):
s+=mat[i][-1-i]+mat[i][i]
if l%2!=0:
s-=mat[l//2][l//2]
return s
print(diagonalSum(mat))
print(diagonalSum(mat2))
print(diagonalSum(mat3)) | false |
556c10da0c21b743d598a383bbe8389a9f4f9374 | fhenseler/practicepython | /6.py | 543 | 4.5625 | 5 | # Exercise 6
# Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
import myFunctions
word = myFunctions.get_str("Insert a word: ")
wordLower = word.lower()
wordLength = len(word)
reverse = ""
for index in range(wordLength):
reverse += wordLower[wordLength-1-index]
if myFunctions.check_palindrome(wordLower, reverse):
print("The word " + word + " is a palindrome")
else:
print("The word " + word + " is NOT a palindrome") | true |
7aeabd445b25bb6fc050e44e02f7555ec99c25f3 | AndrewAct/DataCamp_Python | /Dimensionality Reduction in Python/4 Feature Extraction/02_Manual_Feature_Extraction_II.py | 658 | 4.125 | 4 | # # 6/17/2020
# You're working on a variant of the ANSUR dataset, height_df, where a person's height was measured 3 times. Add a feature with the mean height to the dataset, then drop the 3 original features.
# Calculate the mean height
height_df['height'] = height_df[['height_1', 'height_2', 'height_3']].mean(axis = 1)
# Drop the 3 original height features
reduced_df = height_df.drop(['height_1', 'height_2', 'height_3'], axis=1)
print(reduced_df.head())
# <script.py> output:
# weight_kg height
# 0 81.5 1.793333
# 1 72.6 1.696667
# 2 92.9 1.740000
# 3 79.4 1.670000
# 4 94.6 1.913333 | true |
28be55ad77877327a2cc547cb802d2c737b16191 | AndrewAct/DataCamp_Python | /Machine Learning for Time Series Data/1 Time Series and Machine Learning Primer/03_Fitting_a_Simple_Model_Classification.py | 1,153 | 4.28125 | 4 | # # 6/27/2020
# In this exercise, you'll use the iris dataset (representing petal characteristics of a number of flowers) to practice using the scikit-learn API to fit a classification model. You can see a sample plot of the data to the right.
# Print the first 5 rows for inspection
print(data.head())
# <script.py> output:
# sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) \
# 50 7.0 3.2 4.7 1.4
# 51 6.4 3.2 4.5 1.5
# 52 6.9 3.1 4.9 1.5
# 53 5.5 2.3 4.0 1.3
# 54 6.5 2.8 4.6 1.5
# target
# 50 1
# 51 1
# 52 1
# 53 1
# 54 1
from sklearn.svm import LinearSVC
# Construct data for the model
X = data[["petal length (cm)", "petal width (cm)"]]
y = data[['target']]
# Fit the model
model = LinearSVC()
model.fit(X, y)
| true |
cadef1d87824ed154302b2a7231c371009e4a739 | AndrewAct/DataCamp_Python | /Image Processing with Keras in Python/2 Using Convolutions/04_Convolutional_Network_for_Image_Classification.py | 786 | 4.15625 | 4 | # # 8/16/2020
# Convolutional networks for classification are constructed from a sequence of convolutional layers (for image processing) and fully connected (Dense) layers (for readout). In this exercise, you will construct a small convolutional network for classification of the data from the fashion dataset.
# Import the necessary components from Keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
# Initialize the model object
model = Sequential()
# Add a convolutional layer
model.add(Conv2D(10, kernel_size=3, activation='relu',
input_shape= (img_rows, img_cols, 1)))
# Flatten the output of the convolutional layer
model.add(Flatten())
# Add an output layer for the 3 categories
model.add(Dense(3, activation='softmax')) | true |
852dedaa543ac6a97839644fab333e1dd1bba6ca | AndrewAct/DataCamp_Python | /Introduction to TensorFlow in Python/2 Linear Models/06_Train_a_Linear_Model.py | 1,241 | 4.1875 | 4 | # # 7/29/2020
# In this exercise, we will pick up where the previous exercise ended. The intercept and slope, intercept and slope, have been defined and initialized. Additionally, a function has been defined, loss_function(intercept, slope), which computes the loss using the data and model variables.
# You will now define an optimization operation as opt. You will then train a univariate linear model by minimizing the loss to find the optimal values of intercept and slope. Note that the opt operation will try to move closer to the optimum with each step, but will require many steps to find it. Thus, you must repeatedly execute the operation.
# Initialize an adam optimizer
opt = keras.optimizers.Adam(0.5)
for j in range(100):
# Apply minimize, pass the loss function, and supply the variables
opt.minimize(lambda: loss_function(intercept, slope), var_list=[intercept, slope])
# Print every 10th value of the loss
if j % 10 == 0:
print(loss_function(intercept, slope).numpy())
# Plot data and regression line
plot_results(intercept, slope)
# <script.py> output:
# 9.669481
# 11.726705
# 1.1193314
# 1.6605749
# 0.7982892
# 0.8017315
# 0.6106562
# 0.59997994
# 0.5811015
# 0.5576157 | true |
d675355b3058bbb592cccab10fc5c111ab27c2b0 | AndrewAct/DataCamp_Python | /Hyperparameter Tunning in Python/1 Hyperparameter and Parameters/1 Hyperparameter and Parameters/01_Extracting_a_Logistic_Regression_Parameter.py | 2,626 | 4.1875 | 4 | # # 8/16/2020
# You are now going to practice extracting an important parameter of the logistic regression model. The logistic regression has a few other parameters you will not explore here but you can review them in the scikit-learn.org documentation for the LogisticRegression() module under 'Attributes'.
# This parameter is important for understanding the direction and magnitude of the effect the variables have on the target.
# In this exercise we will extract the coefficient parameter (found in the coef_ attribute), zip it up with the original column names, and see which variables had the largest positive effect on the target variable.
# You will have available:
# A logistic regression model object named log_reg_clf
# The X_train DataFrame
# sklearn and pandas have been imported for you.
# Create a list of original variable names from the training DataFrame
original_variables = X_train.columns
# Extract the coefficients of the logistic regression estimator
model_coefficients = log_reg_clf.coef_[0]
# Create a dataframe of the variables and coefficients & print it out
coefficient_df = pd.DataFrame({"Variable" : original_variables, "Coefficient": model_coefficients})
print(coefficient_df)
# Print out the top 3 positive variables
top_three_df = coefficient_df.sort_values(by="Coefficient", axis=0, ascending=False)[0:3]
print(top_three_df)
# <script.py> output:
# Variable Coefficient
# 0 LIMIT_BAL -2.886513e-06
# 1 AGE -8.231685e-03
# 2 PAY_0 7.508570e-04
# 3 PAY_2 3.943751e-04
# 4 PAY_3 3.794236e-04
# 5 PAY_4 4.346120e-04
# 6 PAY_5 4.375615e-04
# 7 PAY_6 4.121071e-04
# 8 BILL_AMT1 -6.410891e-06
# 9 BILL_AMT2 -4.393645e-06
# 10 BILL_AMT3 5.147052e-06
# 11 BILL_AMT4 1.476978e-05
# 12 BILL_AMT5 2.644462e-06
# 13 BILL_AMT6 -2.446051e-06
# 14 PAY_AMT1 -5.448954e-05
# 15 PAY_AMT2 -8.516338e-05
# 16 PAY_AMT3 -4.732779e-05
# 17 PAY_AMT4 -3.238528e-05
# 18 PAY_AMT5 -3.141833e-05
# 19 PAY_AMT6 2.447717e-06
# 20 SEX_2 -2.240863e-04
# 21 EDUCATION_1 -1.642599e-05
# 22 EDUCATION_2 -1.777295e-04
# 23 EDUCATION_3 -5.875596e-05
# 24 EDUCATION_4 -3.681278e-06
# 25 EDUCATION_5 -7.865964e-06
# 26 EDUCATION_6 -9.450362e-07
# 27 MARRIAGE_1 -5.036826e-05
# 28 MARRIAGE_2 -2.254362e-04
# 29 MARRIAGE_3 1.070545e-05
# Variable Coefficient
# 2 PAY_0 0.000751
# 6 PAY_5 0.000438
# 5 PAY_4 0.000435 | true |
50948ffffc4106dbee4e19e0b1144a1f3f05c57b | zhudaxia666/shuati | /LeetCode/刷题/二叉树/144二叉树的前序遍历.py | 1,738 | 4.1875 | 4 | '''
给定一个二叉树,返回它的 前序 遍历。(通过迭代算法完成)
思路:
有两种通用的遍历树的策略:
深度优先搜索(DFS)
在这个策略中,我们采用深度作为优先级,以便从跟开始一直到达某个确定的叶子,然后再返回根到达另一个分支。
深度优先搜索策略又可以根据根节点、左孩子和右孩子的相对顺序被细分为前序遍历,中序遍历和后序遍历。
宽度优先搜索(BFS)
我们按照高度顺序一层一层的访问整棵树,高层次的节点将会比低层次的节点先被访问到。
从根节点开始,每次迭代弹出当前栈顶元素,并将其孩子节点压入栈中,先压右孩子再压左孩子。
在这个算法中,输出到最终结果的顺序按照 Top->Bottom 和 Left->Right,符合前序遍历的顺序。
算法复杂度
时间复杂度:访问每个节点恰好一次,时间复杂度为 O(N)O(N) ,其中 NN 是节点的个数,也就是树的大小。
空间复杂度:取决于树的结构,最坏情况存储整棵树,因此空间复杂度是 O(N)。
'''
class TreeNode(object):
""" Definition of a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self,root):
if not root:
return []
stack=[root]
res=[]
while stack:
node=stack.pop()
if node:
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
| false |
a0949891d44af529535b61c60a8e7de3d4d3cbff | dougscohen/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 1,050 | 4.25 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
"""
Takes in a word/phrase and returns the amount of times 'th' occurs.
Parameters:
word (str): a word, phrase, sentence, etc. that is a string.
Returns:
count (int): number of times that 'th' occurs in the input.
"""
# if length of the string is less than two characters, it won't contain any
# instances of 'th' so return 0
if len(word) < 2:
return 0
# TBC - first two characters of string are 'th', so add one and recur
#. starting at the next index
elif word[0:2] == 'th':
return 1 + count_th(word[1:])
# Otherwise, recur starting at the next index over
else:
return count_th(word[1:])
# word = 'THis thing goes fourth'
# print(count_th(word))
| true |
6f34824a78939e24f29dc71ad83496f2c7a9488f | karthikdwarakanath/PythonPrograms | /findMinSumArr.py | 625 | 4.1875 | 4 | # Minimum sum of two numbers formed from digits of an array
# Given an array of digits (values are from 0 to 9), find the minimum possible
# sum of two numbers formed from digits of the array. All digits of given array
# must be used to form the two numbers.
def findMinSum(inputList):
inList = sorted(inputList)
a = ''
b = ''
i = 0
while i < len(inList) - 1:
a += str(inList[i])
b += str(inList[i+1])
i += 2
if len(inList) % 2 != 0:
a += str(inList[len(inList) - 1])
return int(a) + int(b)
print findMinSum([6, 8, 4, 5, 2, 3])
print findMinSum([5, 3, 0, 7, 4])
| true |
194575590af98ef6cbdf73578daad8502e1c8705 | Daria-Lytvynenko/homework14 | /homework14.py | 2,444 | 4.125 | 4 | from functools import wraps
import re
from typing import Union
# task 1 Write a decorator that prints a function with arguments passed to it.
# NOTE! It should print the function, not the result of its execution!
def logger(func):
@wraps(func)
def wrap(*args):
print(f'{func.__name__} called with {args}')
print(func(*args))
return wrap
@logger
def add(x: Union[int, float], y: Union[int, float]) -> Union[int, float]:
return x + y
@logger
def square_all(*args: Union[int, float]) -> Union[int, float]:
return [arg ** 2 for arg in args]
# task 2 Write a decorator that takes a list of stop words and replaces them with * inside the decorated function
def stop_words(words: list):
def insert_stop_words(func):
@wraps(func)
def wrap(name):
result = func(name)
results = ''
for word in re.findall(r"[\w']+|[.,!?;]", result):
if word in words:
results += ('* ')
else:
results += (word + ' ')
print(results)
return wrap
return insert_stop_words
@stop_words(['pepsi', 'BMW'])
def create_slogan(name: str) -> str:
return (f"{name} drinks pepsi in his brand new BMW!")
# task 3 Write a decorator `arg_rules` that validates arguments passed to the function.
# A decorator should take 3 arguments: # max_length: 15 # type_: str # contains: [] - list of symbols that an argument
# should contain. If some of the rules' checks returns False, the function should return False and print the reason
# it failed; otherwise, return the result.
def arg_rules(type_: type, max_length: int, contains: list):
def check_rules(func):
@wraps(func)
def wrap(name):
if type(name) != type_:
print('incorrect type: should be string')
if len(name) > max_length:
print('incorrect length: should not be more than 15')
if list not in contains:
print("incorrect name: should contain ['05' and'@']")
else:
print('everything is correct')
return func(name)
return wrap
return check_rules
@arg_rules(type_=str, max_length=15, contains=['05', '@'])
def create_slogan(name: str) -> str:
return f"{name} drinks pepsi in his brand new BMW!"
| true |
680783c22a0b03f5fe6b97efc77a33731dce3894 | maxgud/Python_3 | /Exercise_38_arrays.py | 1,560 | 4.125 | 4 | #this is just a variable that is equal to a string
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
#this turns the variable into an array
#it splits the array where ever there is a ' ' aka space
stuff = ten_things.split(' ')
#this is a second array
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
#while the number of elements in stuff does not equal 10
#run the following lines of code
while len(stuff) != 10:
#this .pop() takes the last element off of the array
#more_stuff
#you can set this to a variable which is done
next_one = more_stuff.pop()
#this prints the variable being added to the
#stuff array
print("Adding: ", next_one)
stuff.append(next_one)
#this interpolates how many elements are in the
#array stuff
print(f"There are {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
#this prints the second element in stuff
print(stuff[1])
#this prints the last element in stuff
print(stuff[-1]) # whoa! fancy
#this removes the last element in stuff and prints it
print(stuff.pop())
#this joins all the elements in stuff with a space
#this can be used to turn an array into a string
print(' '.join(stuff)) # what? cool!
#this joins all the elements in stuff into a string
#joining them with a hash#
print('#'.join(stuff)) # super stellar!
#this joins only the 4th and 5th elements in the array
#stuff with a hash
print('#'.join(stuff[3:5])) | true |
27937d9585a75e3da0480f28d811c919247390ae | siggioh/2019-T-111-PROG | /exams/retake/grades.py | 1,552 | 4.125 | 4 | def open_file(filename):
''' Returns a file stream if filename found, otherwise None '''
try:
file_stream = open(filename, "r")
return file_stream
except FileNotFoundError:
return None
def read_grades(file_object):
''' Reads grades from file stream and returns them as a list of floats '''
grade_list = []
for grade_str in file_object:
grade_str = grade_str.strip()
try:
grade = float(grade_str)
except ValueError:
continue
grade_list.append(grade)
return grade_list
def get_average(a_list):
''' Returns the average of the numbers in the given list '''
return sum(a_list) / len(a_list)
def get_median(a_list):
''' Returns the median of the given list, a_list.
Assumes that a_list is sorted in a ascending order '''
length = len(a_list)
middle_idx = length // 2
if length % 2 != 0: # The length of the list is odd
median = a_list[middle_idx]
else:
median = (a_list[middle_idx] + a_list[middle_idx - 1]) / 2
return median
def print_results(average, median):
print("Average: {:.2f}".format(average))
print("Median: {:.2f}".format(median))
# Main program starts here
file_name = input("Enter file name: ")
file_object = open_file(file_name)
if file_object:
grade_list = read_grades(file_object)
average = get_average(grade_list)
median = get_median(sorted(grade_list))
print_results(average, median)
else:
print("File {} not found!".format(file_name))
| true |
edc7cb3f249f29202907a23c11f48c0981bee364 | WQ-GC/Python_AbsoluteBeginners | /CH5_SharedReferences.py | 1,607 | 4.25 | 4 | #Shared References
myList = [1,2,3,4,5]
print(type(myList), " myList: ", myList)
myListRef1 = myList
myListRef2 = myListRef1
print(type(myListRef1), " myListRef1 is a reference to myList")
print(type(myListRef2), " myListRef2 is a reference to myList")
for item in myList:
item = 111
#print("item: ", item)
#Item is not a reference
print("item is NOT a reference variable")
print()
########################################################
#Change myList[i] changes references
for i in range(5):
myList[i] = i * 111
# print(i, ": ", myList[i])
print("modify myList: ", myList)
print("myListRef1 : ", myListRef1)
print("myListRef2 : ", myListRef2)
print()
print("===========================================")
print("Changing through reference var: myListRef1")
for i in range(5):
myListRef1[i] = i * 1
# print(i, ": ", myListRef1[i])
print("myList : ", myList)
print("modify myListRef1: ", myListRef1)
print("myListRef2 : ", myListRef2)
print()
print("===========================================")
print("Changing through reference var: myListRef2")
for i in range(5):
myListRef2[i] = i * 3
# print(i, ": ", myListRef2[i])
print("myList : ", myList)
print("myListRef1 : ", myListRef1)
print("modify myListRef2: ", myListRef2)
print()
print("*******************************************")
print("Making a Copy of an object does NOT reference the original")
myCopyList = myList.copy()
for i in range(5):
myCopyList[i] = 111
print("copy to myCopyList: ", myCopyList)
print("myList : ", myList)
| false |
f00e7ad1364e2e4fccf0028f943c28e49a86d3e2 | alshil/zoo | /square.py | 603 | 4.28125 | 4 | #Depends on the figure name an app calculates figure`s square
import math
figure_name = str(input("figure name "))
if figure_name == "triangle":
a = float(input ("1 side "))
b = float(input ("2 side "))
c = float(input ("3 sideа "))
if a + b > c or b + c > a or c + a > b:
p = (a + b + c) / 2
print(p * (p -a) * (p - b) * (p -c) **0.5)
else:
print("Wrong parametrs. A sum of 2 sides is always bigger than a one`s length")
elif figure_name == "rectangle":
a = float(input("1 side "))
b = float(input("2 side "))
print(a * b)
else:
r = float(input("radius ")
print((r ** 2) * math.pi)
| true |
4845f043a91b35d0599e68681f2030996161e541 | JaneNjeri/Think_Python | /ex_10_05.py | 569 | 4.15625 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 28.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 10. Lists
# Exercise 10.5
# Write a function called chop that takes a list, modifies it
# by removing the first and last elements, and returns None.
def middle(listik):
listik = listik[1:len(listik)-1]
print(listik)
return
print(middle([1,2,3,4]))
print(middle([1,2,[3,4,5,6],7,8]))
print(middle([1,2,3]))
print(middle([]))
print(middle([1,3]))
#END | true |
08a13096dd54f87860a2bfdfd89540d998ab6d71 | JaneNjeri/Think_Python | /ex_13_3.py | 2,660 | 4.125 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 29.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 13. Case study: data structure selection
#STATUS: check for refactoring
# Exercise 13.3
# Modify the program from the previous exercise to print
# the 20 most frequently-used words in the book.
import string, time
def del_punctuation(item):
'''
This function deletes punctuation from a word.
'''
punctuation = string.punctuation
for c in item:
if c in punctuation:
item = item.replace(c, '')
return item
def break_into_words():
'''
This function reads file, breaks it into
a list of used words in lower case.
'''
book = open('tsawyer.txt')
words_list = []
for line in book:
for item in line.split():
item = del_punctuation(item)
item = item.lower()
#print(item)
words_list.append(item)
return words_list
def create_dict():
'''
This function calculates words frequency and
returns it as a dictionary.
'''
words_list = break_into_words()
dictionary = {}
for word in words_list:
if word not in dictionary:
dictionary[word] = 1
else:
dictionary[word] += 1
# I don't know why the following code doesn't work
# efficient with big data, however in the book it's said it's
# 'more concisely' then a variant with if.
#if word not in dictionary:
# print(word)
# dictionary[word] = words_list.count(word) # running time is is 22.3023 s
# or
#dictionary[word] = dictionary.get(word, words_list.count(word)) # is smth wrong here?
dictionary.pop('', None) # accidentally 5 empty strings appeared in the dictionary. why?
return dictionary
def words_popularity():
'''
This function returns the 20 most
frequently-used words in the book
'''
dictionary = create_dict()
print(dictionary)
dict_copy = dictionary
counter = 0
popular_words = []
while counter < 20 :
popular_word = max(dict_copy, key=dict_copy.get)
popular_words.append(popular_word)
dict_copy.pop(popular_word, None)
counter += 1
return popular_words
start_time = time.time()
print('The 20 most frequently-used words in the book: {}'.format(words_popularity()))
function_time = time.time() - start_time
print('Running time is {0:.4f} s'.format(function_time))
#END | true |
a48d58eebbac192fb4210041e733d640004d1cef | JaneNjeri/Think_Python | /ex_03_4.py | 1,522 | 4.5625 | 5 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 24.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 3. Functions
# Exercise 3.4
# A function object is a value you can assign to a variable or
# pass as an argument. For example, do_twice is a function that
# takes a function object as an argument and calls it twice:
# def do_twice(f):
# f()
# f()
# Here is an example that uses do_twice to call a function named
# print_spam twice.
# def print_spam():
# print 'spam'
# do_twice(print_spam)
# 1. Type this example into a script and test it.
# 2. Modify do_twice so that it takes two arguments, a function
# object and a value, and calls the function twice, passing the
# value as an argument.
# 3. Write a more general version of print_spam, called print_twice,
# that takes a string as a parameter and prints it twice.
# 4. Use the modified version of do_twice to call print_twice twice,
# passing 'spam' as an argument.
# 5. Define a new function called do_four that takes a function object
# and a value and calls the function four times, passing the value as
# a parameter. There should be only two statements in the body of this
# function, not four.
arg = 'spam'
def do_twice(f, arg):
f(arg)
f(arg)
def print_twice(arg):
print(arg)
print(arg)
do_twice(print_twice, arg)
print()
def do_four(f, arg):
do_twice(f, arg)
do_twice(f, arg)
do_four(print_twice, arg)
#END | true |
5cc5ecde9e975a12d7e32f2c34185708d352cb52 | JaneNjeri/Think_Python | /ex_09_4_2.py | 799 | 4.34375 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 27.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 9. Case study: word play
# Exercise 9.4
# Can you make a sentence using only the letters acefhlo?
# Other than Hoe alfalfa?
def uses_only(word, string):
for letter in word:
if letter not in string:
return False
return True
string = 'acefhlo'
fin = open('words.txt')
count = 0
for line in fin:
word = line.strip()
if word != 'hoe' and word != 'alfalfa':
if uses_only(word, string):
count +=1
print(word)
print('You have {} words which contain only "acefhlo" letters to make a sentance.'.format(count))
# This code returns
#END | true |
8db91bd009e8a4fc9c9e5f0bddec486845f13364 | JaneNjeri/Think_Python | /ex_08_01.py | 580 | 4.71875 | 5 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 25.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 8. Strings
# Exercise 8.1
# Write a function that takes a string as an argument and
# displays the letters backward, one per line.
def print_string_backward(string):
index = len(string)
while index > 0:
print(string[index-1])
index -=1
print_string_backward('string')
print()
print_string_backward('Merry Christmas and Happy New Year!')
#END | true |
bd89a3468942ea72efeb8da8a24d479b905100dd | JaneNjeri/Think_Python | /ex_12_1.py | 389 | 4.375 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 29.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 12. Tuples
# Exercise 12.1
# Write a function called sumall that takes any number of
# arguments and returns their sum.
def sumall(*t):
return sum(t)
print(sumall(1,2,3,4,5))
#END | true |
27fba10b5b159591924eb0ab1e00a8ac92d8dbdf | JaneNjeri/Think_Python | /ex_06_8.py | 1,076 | 4.125 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 25.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 6. Fruitful functions
# Exercise 6.8
# The greatest common divisor (GCD) of a and b is the largest number
# that divides both of them with no remainder.
# One way to find the GCD of two numbers is Euclids algorithm, which
# is based on the observation that if r is the remainder when a is
# divided by b, then gcd(a, b) = gcd(b, r). As a base case,
# we can use gcd(a, 0) = a.
# Write a function called gcd that takes parameters a and b and returns
# their greatest common divisor.
def gcd(a, b):
if a >= b and b != 0:
r = a % b
if r == 0:
print(b)
else:
return gcd(b, r)
elif a <= b and a != 0:
r = b % a
if r == 0:
print(a)
else:
return gcd(a, r)
else:
print('Zero division')
gcd(18, 2)
gcd(2, 18)
gcd(9, 18)
gcd(4,4)
gcd(4,0)
gcd(11, 13)
#END | true |
151f141f0ed7e3dd88904c4ebc30af256887ee43 | JaneNjeri/Think_Python | /ex_06_2.py | 1,119 | 4.21875 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 24.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 6. Fruitful functions
# Exercise 6.2
# Use incremental development to write a function called
# hypotenuse that returns the length of the hypotenuse of
# a right triangle given the lengths of the two legs as
# arguments. Record each stage of the development process as you go.
def hypotenuse(leg1,leg2):
# stage 1:
# return 0
# stage 2:
# leg1_square = leg1**2
# leg2_square = leg2**2
# print(leg1_square, leg2_square)
# return 0
# stage 3:
# leg1_square = leg1**2
# leg2_square = leg2**2
# legs_sum = leg1_square + leg2_square
# print(legs_sum)
# return 0
# stage 4:
# leg1_square = leg1**2
# leg2_square = leg2**2
# legs_sum = leg1_square + leg2_square
# hyp = legs-sum**0.5
# print(hyp)
# return 0
# stage 5:
hyp = (leg1**2 + leg2**2)**0.5
return hyp
print('{0:.2f}'.format(hypotenuse(1,2)))
#END | true |
4e95ec47fd13d8432cf465c12bc2cd46bd35b586 | LeeSinCOOC/Data-Structure | /chapter1/C-1.26.py | 267 | 4.21875 | 4 | def arithmetic():
a = int(input('a:'))
b = int(input('b:'))
c = int(input('c:'))
if a + b == c or a == b - c or a*b == c:
return True
return False
# 算术逻辑的本质是?
# 还有许多情况需要考虑
a = arithmetic()
print(a)
| false |
915cb0ad8cddbe30e4af593993eb10b7a11a4292 | MichaelCzurda/Python-Data-Science-Beispiele | /Python_Basics/07_RegularExpression/0710_substitute_strings.py | 1,442 | 5.03125 | 5 | #! python3
#0710_substitute_strings.py - Substituting Strings with the sub() Method
#Regular expressions can not only find text patterns but can also substitute
#new text in place of those patterns. The sub() method for Regex objects is
#passed two arguments. The first argument is a string to replace any matches.
#The second is the string for the regular expression. The sub() method returns
#a string with the substitutions applied.
import re
namesRegex = re.compile(r'Agent \w+')
print(namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.'))
#CENSORED gave the secret documents to CENSORED.
#Sometimes you may need to use the matched text itself as part of the
#substitution. In the first argument to sub(), you can type \1, \2, \3, and so
#on, to mean “Enter the text of group 1, 2, 3, and so on, in the substitution.”
#For example, say you want to censor the names of the secret agents by
#showing just the first letters of their names.To do this, you could use the
#regex Agent (\w)\w* and pass r'\1****' as the first argument to sub(). The \1
#in that string will be replaced by whatever text was matched by group 1—
#that is, the (\w) group of the regular expression.
agentNamesRegex = re.compile(r'Agent (\w)\w*')
print(agentNamesRegex.sub(r'\1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.'))
#A**** told C**** that E**** knew B**** was a double agent.
| true |
55742544b628d6d08ee04f8f87a9fc0947c3578d | MichaelCzurda/Python-Data-Science-Beispiele | /Python_Basics/09_Organizing_Files/0905_folder_into_zip.py | 1,984 | 4.34375 | 4 | #!python3
#0905_folder_into_zip.py - Project: Backing Up a Folder into a ZIP File
#create ZIP file “snapshots” from an entire folder. You’d like to keep different versions, so you want the ZIP file’s filename to increment each
#time it is made; for example, {name}_1.zip, {name}_2.zip, {name}_3.zip, and so on.
#Write a program that does this task for you.
#The code for this program will be placed into a function named backupToZip().
#This will make it easy to copy and paste the function into other Python programs that need this functionality.
##########################################################
#Step 1: Figure Out the ZIP File’s Name #
#Step 2: Create the New ZIP File #
#Step 3: Walk the Directory Tree and Add to the ZIP File #
##########################################################
import zipfile, os
def backupToZip(folder):
#Step 1
folder = os.path.abspath(folder) #make sure folder is absolute
# Figure out the filename this code should use based on what files already exist.
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
print(zipFilename)
if not os.path.exists(os.path.join(folder,zipFilename)):
break
number +=1
#Step 2
print('Creating {}....format(zipFilename)')
backupZip = zipfile.ZipFile(os.path.join(folder,zipFilename), 'w')
#Step 3
for folderName, subfolders, filenames in os.walk(folder):
print('Adding files in {}... '.format(folderName))
# Add the current folder to the ZIP file.
backupZip.write(folderName)
# Add all the files in this folder to the ZIP file.
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
else:
backupZip.write(os.path.join(folderName, filename))
print(os.path.join(folderName, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\Users\\michaelc.AITC\\Documents\\Python Scripts\\ATBS')
| true |
456c1823e4f5230bcd742e0592ed3dcd890f08b1 | Alexey-Nikitin/PythonScripts | /pycode.py | 1,634 | 4.21875 | 4 | def calc():
print("Введите какое действие вы хотите сделать. (+, -, *, /)")
whattodo = input()
if whattodo != "+" and whattodo != "-" and whattodo != "*" and whattodo != "/":
print("Ошибка! Нужно ввести только +, -, * или /")
print(" ")
calc()
else:
print("Введите два числа с которыми нужно выполнить действие. (После ввода каждого числа нажимайте Enter)")
x = input()
y = input()
if x.isdigit() and y.isdigit():
x = int(x)
y = int(y)
if whattodo == "+":
result = x + y
result = str(result)
print("Результат: " + result)
elif whattodo == "-":
result = x - y
result = str(result)
print("Результат: " + result)
elif whattodo == "*":
result = x * y
result = str(result)
print("Результат: " + result)
else:
result = x / y
result = str(result)
print("Результат: " + result)
else:
try:
x = float(x)
y = float(y)
if whattodo == "+":
result = x + y
result = str(result)
print("Результат: " + result)
elif whattodo == "-":
result = x - y
result = str(result)
print("Результат: " + result)
elif whattodo == "*":
result = x * y
result = str(result)
print("Результат: " + result)
else:
result = x / y
result = str(result)
print("Результат: " + result)
except ValueError:
print("Введите число!")
while True:
print(" ")
print(" ")
calc() | false |
a59b90c5687d90c4d59de9e38c721a52d933eea5 | ShoonLaeMayLwin/SFUpython01 | /If_Else_Statements.py | 2,286 | 4.15625 | 4 | #Boolean Expression -> True or False
print(20 > 10)
print(20 == 10)
print(20 < 10)
print(bool("Hello World"))
print(bool(20))
Python Conditions
Equals -> x == y
Not Equals -> x != y
Less than -> x < y
Less than or equal to -> x <= y
Greater than -> x > y
Greater than or equal to -> x >= y
Boolean OR -> x or y , x | y
Boolean AND -> x and y, x & y
Boolean NOT -> not x
if -
else -
#If Statement
x = 70
y = 60
if x > y:
print("x is greater than y ")
#Elif
x = 70
y = 70
if x < y:
... print("x is greater than y")
... else:
... print("x is not greater than y")
...
x is not greater than y
>>> if x > y:
... print("x is greater than y")
... elif x >= y:
... print("x is greater or equal to y")
... elif y < x:
... print("y is smaller than x")
... else:
... print("x is nothing")
#Short Hand If
if x > y: print("x is greater than y")
#Short Hand If...Else
print(x) if x > y else print(y)
#And is logical operator
x = 50
y = 40
z = 100
if x > y and z > x:
print("All Conditions are True")
if x < y and z > x:
print("All Conditions are True")
else:
print("Some Conditions are False")
#Or is logical operator
x = 50
y = 40
z = 100
if x > y or z < y:
print("One of the conditions is True")
elif x > y and z > y:
print("All conditions are True")
else:
print("nothing else")
if x > y and z > y and x > z:
print("Answer 1")
elif x == y or z == y or z > y and x > y:
print("Answer 2")
elif z > y and y < x or z > y:
print("Answer 3")
else:
print("Default")
x = int(input("Please Enter exam result: "))
if x < 101 and x > 89 or x == 100:
print("A")
elif x < 89 and x > 79:
print("B")
elif x < 79 and x > 59:
print("C")
elif x < 59 and x > 49:
print("D")
elif x < 49 and x > 0 or x == 0 or x == 49:
print("F")
else:
print("Check Again")
x = int(input("Please Enter your number:"))
if 100 > and 90 <
print("A")
#Nested If is if statements in if statements
x = 50
if x > 10:
print("x is ten")
if x > 20:
print("x is greater than 20")
else:
print("No,x is not greater than 20")
if x > 10 and x != 10 or x > 20:
print("x is greater than 10 and 20")
else:
print("x is not greater than 10 & 20")
if student
if batch
if gender
else
not
student = "SFU"
batch = "3"
gender = "male"
| false |
d16edae81fe36827801aa7681389c8fc42e73755 | Safal08/LearnPython | /Integers & Float.py | 852 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 09:49:00 2020
@author: safal
"""
num=3
print(type(num)) #shows the integer
num1=3.14
print(type(num1)) #shows the float
#Arithmetic Operations
print(5+2) #Addition
print(5-2) #Subtraction
print(5/2) #Division
print(5//2) #Floor Division
print(5**2) #Exponent
print(5%2) #Modulus
num=num+1 #increment
print(num)
num-=1 #decrement shorthand operator
print(num)
print(abs(-3)) #abs function
print(round(3.23)) #round function
print(round(4.3334,2)) #round with 2 argument
#comparisons
num_1=3
num_2=4
print(num_1==num_2) #Equal return boolean
print(num_1!=num_2) #Not Equal return boolean
print(num_1>num_2) #Greater than
print(num_1<num_2) #Less Than
print(num_1<=num_2) #Less than equal to
print(num_1>=num_2) #Greater than equal to
a='200'
b='300'
a=int(a) #casting
b=int(b) #casting
print(a+b) | true |
6fbf62b2549c9035c593df7e5bea53ee8a7ea98e | Granada2013/python-practice | /tasks/All_Balanced_Parentheses.py | 615 | 4.25 | 4 | """
Write a function which makes a list of strings representing all of the ways you can balance n pairs of parentheses
Examples:
balanced_parens(0) => [""]
balanced_parens(1) => ["()"]
balanced_parens(2) => ["()()","(())"]
balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"]
"""
from functools import lru_cache
@lru_cache(maxsize=None)
def balanced_parens(n):
if n == 0: return [""]
elif n == 1: return ["()"]
else:
res = []
for elem in balanced_parens(n - 1):
res.extend([elem[:i] + "()" + elem[i:] for i in range(len(elem))])
return list(set(res))
| true |
64c795e5bdc98fc5cafd923369d6ed8bc117b035 | lel352/PythonAulas | /Aula15/Aula15b.py | 600 | 4.125 | 4 | #f string
soma = 10
print(f'Soma é {soma}')
#f string
nome = 'Julio'
idade = 33
print(f'O {nome} tem {idade} anos.')
salário = 987.35
print(f'O {nome} tem {idade} anos e ganha R${salário:.2f}')
print(f'O {nome} tem {idade} anos e ganha R${salário:.1f}')
print(f'O {nome:^20} tem {idade} anos e ganha R${salário:.2f}')
print(f'O {nome:20} tem {idade} anos e ganha R${salário:.2f}')
print(f'O {nome:-^20} tem {idade} anos e ganha R${salário:.2f}')
print(f'O {nome:->20} tem {idade} anos e ganha R${salário:.2f}')
print(f'O {nome:-<20} tem {idade} anos e ganha R${salário:.2f}')
| false |
ce3f48c4f55ae5cbbef40d5f3c29abe81d06ceb5 | lel352/PythonAulas | /PythonExercicios/Desafio033.py | 459 | 4.15625 | 4 | print('=========Desafio 033========')
numero1 = int(input('Numero 1: '))
numero2 = int(input('Numero 2: '))
numero3 = int(input('Numero 3: '))
maior = numero1
menor = numero1
if maior < numero2 and maior > numero3:
maior = numero2
elif maior < numero3:
maior = numero3
if menor > numero2 and menor < numero3:
menor = numero2
elif menor > numero3:
menor = numero3
print('Maior Numero: {} \nmenor numero {}'.format(maior, menor))
| false |
0994ff0f127182eaa3954f8c31c10b1228912216 | panu2306/Python-programming-exercises | /geeksforgeeks/string_problems/palindrome.py | 882 | 4.625 | 5 | # Python program to check if a string is palindrome or not
def using_for(sent_string):
s = ""
for c in sent_string:
s = c + s
return s
def using_reversed(sent_string):
s = "".join(reversed(sent_string))
return s
def using_recursion(sent_string):
if(len(sent_string) == 0):
return sent_string
else:
return using_recursion(sent_string[1:]) + sent_string[0]
def using_slice(sent_string):
return sent_string[::-1]
if __name__ == "__main__":
sent_string = "121"
returned_string = using_for(sent_string)
returned_string = using_reversed(sent_string)
returned_string = using_recursion(sent_string)
returned_string = using_slice(sent_string)
if(sent_string == returned_string):
print("String is a Palindrome String")
else:
print("String is not a Palindrome String") | false |
ae2da29ae4d1fc6346d1db65a497aa018e5d57ab | Elkip/PythonMorsels | /add.py | 1,578 | 4.25 | 4 | """
09/18/2019
a function that accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding
numbers in the two given lists-of-lists added together.
It should work something like this:
>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]
>>> matrix1 = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
>>> matrix2 = [[1, 1, 0], [1, -2, 3], [-2, 2, -2]]
>>> add(matrix1, matrix2)
[[2, -1, 3], [-3, 3, -3], [5, -6, 7]]
Try to solve this exercise without using any third-party libraries
For the first bonus, modify your add function to accept and "add" any number of lists-of-lists. ✔️
>>> add([[1, 9], [7, 3]], [[5, -4], [3, 3]], [[2, 3], [-3, 1]])
[[8, 8], [7, 7]]
For the second bonus, make sure your add function raises a ValueError if the given lists-of-lists aren't all the same shape. ✔️
>>> add([[1, 9], [7, 3]], [[1, 2], [3]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "add.py", line 10, in add
raise ValueError("Given matrices are not the same size.")
ValueError: Given matrices are not the same size.
"""
def add(*matrices):
matrix_shapes = {
tuple(len(m) for m in matrix) for matrix in matrices
}
if len(matrix_shapes)>1:
raise ValueError("Given Matrices do not match")
return [
[sum(values) for values in zip(*rows)]
for rows in zip(*matrices)
]
matrix1 = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
matrix2 = [[1, 1, 0], [1, -2, 3], [-2, 2, -2]]
print(add(matrix1, matrix2))
| true |
697a58f2e0289a9ea3aeef8bfd3fc2fad179c4c7 | Siddiqui-code/Python-Problems-Lab-6 | /factorial.py | 379 | 4.28125 | 4 | # Nousheen Siddiqui
# Edited on 02/19/2021
# Question 6:A for statement is used to calculate the factorial of a user input value.
# Print this value as well as the calculated value using the factorial function in the math module.
import math
factorial = int(input("Provide a number"))
x=1
for i in range(1, factorial+1):
x = x*i
print(x)
print(math.factorial(factorial))
| true |
4786d5aa3b0128ad503b2fdee1b1587fb7ec5642 | ChristopherCaysido/CPE169P-Requirements | /Mod1_PE01/recursive.py | 1,232 | 4.65625 | 5 |
'''
Write a recursive function that expects a pathname as an argument.
The path- name can be either the name of a file or the name of a directory.
If the pathname refers to a file, its name is displayed,
followed by its contents. Otherwise, if the pathname refers to a directory,
the function is applied to each name in the directory.
Test this function in a new program.
Name: Christopher Nilo Caysido
'''
import os
def recursiveFunc(path):
if os.path.isdir(path): #If argument is a directory
files = os.listdir(path) #Make a list of the files within a path
dirName = os.path.basename(path)
for i in range(0,len(files)):
files[i] = path +"/"+ files[i]
for item in files: #Then for every file or directory
print("Directory: " + dirName + "\n")
recursiveFunc(item) #recursively call the recursive function
elif os.path.isfile(path): #else
file_read = open(path,'r') # Create a file read variable
file_name = os.path.basename(path)
print("File Name: "+file_name + "\n" + "Content: " + "\n")
print(file_read.read()+"\n") # Print the contents
else:
print("The argument entered is neither a directory or a path try again")
| true |
a114fbc6d189ae3ae0d0393eb6090ccfec1b6d95 | nicholsonjb/PythonforEverybodyExercises | /exercise4.6.py | 2,119 | 4.15625 | 4 | # Written by James Nicholson
# Last Updated March 27, 2019
#Use a costum function to do the following:
# Given (1) number of hours, and (2) rate of pay
# This program computes gross pay according to the formula: number of hours * rate of pay
#For hours worked beyond 40. pay = 1.5 * number of hours * rate of pay
#Use try/catch expection handling to gracefullly exit not non-numeric user input.
import sys
# Initialize variables to be used in the program
fixedHours = 40
floatOTRate = 1.5
def computePay(iHours, fRate):
#Use conditional loop to carry out the two different calculations on user-supplied hours
#Round the compuation to two decimal places
if iHours > fixedHours:
hoursOverFixed = iHours - fixedHours
#pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.
grossPay = round((fixedHours * fRate) + (floatOTRate * hoursOverFixed * floatRate), 2)
else:
#pay computation to give pay for less than 40 hours.
grossPay = round((iHours * fRate), 2)
return grossPay
# Prompt user for the number of hours worked.
hours = input("Enter number of hours: ")
# Convert input to integer, because the input statement accepts user input as a string by default.
# Wrap this within a try-except code block to exit gracefully as the conversion to integer will fail if the user supplied a non-numeric input!
try:
intHours = int(hours)
except ValueError:
print ("Hours worked must be an integer. Please try again. Goodbye.")
sys.exit()
# Prompt user for the rate of pay
rate = input("Enter rate of pay: ")
# Convert this rate to float, because the input statement accepts user input as a string by default.
# Wrap this within a try-except code block to exit gracefully as the conversion to float will fail if the user supplied a non-numeric input!
try:
floatRate = float(rate)
except ValueError:
print ("Rate of pay must be numeric. Please try again. Goodbye.")
sys.exit()
# Print the result
grossPayRecieved = computePay(intHours, floatRate)
print("Gross pay is: $" + str(grossPayRecieved))
| true |
78060ff7bb9c0f4be4a3ba920430cbfe4b2cc845 | nicholsonjb/PythonforEverybodyExercises | /Data 620 Assignments/Assignment8.2-score-function.py | 1,688 | 4.21875 | 4 | #Data 620 Assignment 8.2 Python Score
#Severance Chapter 4 - Exercise 7 – ASSIGNMENT
#Written by James Nicholson
#Last Updated March 27, 2019
#Use a custome function to do the following:
# Write a program to prompt for a score between 0.0 and
#1.0. If the score is out of range, print an error message. If the score is
#between 0.0 and 1.0, print a grade using the following table:
#print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#Use try/catch expection handling to gracefullly exit not non-numeric user input.
import sys
def computegrade(fScore):
#Use conditional loop to to determine grade on user supplied input.
if fScore > 1.0 or fScore < 0.0:
print('Bad score')
elif fScore > 0.9:
print('The grade is A!')
elif fScore > 0.8:
print('The grade is B!')
elif fScore > 0.7:
print('The grade is C!')
elif fScore > 0.6:
print('The grade is D!')
else:
print('The grade is F!')
return fScore
print("This program will calculate a letter grade based on the student's score.")
# Prompt user for the score
# Convert this input to float, because the input statement accepts user input as a string by default.
# Wrap this within a try-except code block to exit gracefully as the conversion to float will fail if the user supplied a non-numeric input!
try:
inputScore = input('Enter score: ')
floatScore = float(inputScore)
except:
score = -1
print ("Score must be an integer. Please try again. Goodbye.")
sys.exit()
#Invoke computegrade function with the user-supplied score
scoreRecieved = computegrade(floatScore)
#End Script
| true |
eba0511a4332caddb52f67914e1f1b307b8cf92e | kashyap99saksham/python | /chapter12.py | 387 | 4.21875 | 4 | # INTRO OF LAMBDA EXPRESSIONS(ANONYMUS FUNCTION)
add = lambda a,b : a+b #USE ADD AS A NORMAL FUNCTION
print(add(2,3))
# MAKE IS_EVEN ODD PRGM USING LAMBA FUNCTION
e_o = lambda a : a%2==0
print(e_o(4))
# OR USING IF ELSE
e_o = lambda a : True if a%2==0 else False
print(e_o(4))
# PRINT LAST CHAR OF STRING USING LF
lc = lambda s : s[-1]
print(lc('saksham')) | false |
58c42b2fab76b1367bd43c79a2d13c8e8cbe6dac | kashyap99saksham/python | /chapter6.py | 1,327 | 4.375 | 4 | # # TUPLE DATA STRUCTURE
# # TUPLE CAN STORE ANY TYPE OF VALUES
# # MOST IMPORTANT , TUPLE ARE IMMUTABLE : CANT MODIFY/CHANGES
# # NO APPEND,NO INSERT,NO POP,NO REMOVE IN TUPLE
# # TUPLE ARE FASTER THEN LIST
# t = ('a','b','c')
# print(t)
# # METHODS USED WITH TUPLES
# # COUNT : COUNT ITEM IN TUPLE
# # LEN : LENGTH OF TUPLE
# # INDEX : ITEM INDEX
# # SLICING
# # LOOPING IN TUPLE
# a = ('a','b','c')
# for i in a:
# print(i)
# # TUPLE WITH ONE ELEMENT
# num1 = ('one') #This is string typle ,not tuple
# num2 = ('one',) #This is tuple
# num3 = (1) #This is int typle ,not tuple
# num4 = (1,) #This is tuple
# print(type(num4)) #OUTPUT : TUPLE
# # TUPLE WITHOUT PARENTHESIS
# tu = 'a','b','c','d','e' #This is tuple
# print(type(tu)) #OUTPUT:TUPLE
# # TUPLE UNPACKING
# color = 'red','black','green','blue'
# col1,col2,col3,col4 = color #col1=red,col2=black,col3=green,col4=blue
# print(col1) #OUTPUT : RED
# # LIST INSIDE TUPLE
# color = 'red','black',['green','blue']
# color[2].append('white') #OUTPUT :('red', 'black', ['green', 'blue', 'white'])
# color[2].pop() #OUTPUT : ('red', 'black', ['green', 'blue'])
# print(color)
# # FUNCTION USED WITH TUPLE
# # MIN,MAX,SUM
# s = 1,2,3,4,5
# print(sum(s)) #OUtPUT:15
| false |
e75ca1fbf6c29ec375c0f80a1fa8514c5a7497c7 | GulzarJS/Computer_Science_for_Physics_and_Chemistry | /PW_2/circle.py | 2,338 | 4.125 | 4 | import math as mt
import random
import time as t
# Functions for finding area of circle with trapezoid method
# Function to find the angle between radius and the part until to chord
def angle_of_segment(r, a):
cos_angle = a / r
angle = mt.acos(cos_angle)
return angle
# Function to find the length of the chord
def length_of_chord(r, a):
return 2 * r * mt.sin(angle_of_segment(r, a)).__round__(2)
# Function to find area of trapezoid
def area_trapezoid(a, b, h):
return ((a + b) / 2) * h
def area_of_circle_trapezoid(r, n):
h = r / n
half_area_sum = 0
chords = list()
chords.append(r * 2)
for i in range(1, n):
chords.append(length_of_chord(r, i * h))
for i in range(0, n - 2):
half_area_sum += area_trapezoid(chords[i], chords[i + 1], h)
area = half_area_sum * 2
return area.__round__(2)
# Functions for finding area of circle with trapezoid method
def area_of_circle_monte_carlo(radius, n):
# nb of points which is inside of square. I will show area of circle
inside = 0
for i in range(0, n):
x2 = random.uniform(-1, 1) ** 2
y2 = random.uniform(-1, 1) ** 2
if mt.sqrt(x2 + y2) < 1.0:
inside += 1
pi = 4 * inside / n
area = pi * mt.sqrt(radius)
return area
radius = 1
print("Circle are with Trapezoid Method:")
start = t.time()
print("n = 10 => ", area_of_circle_trapezoid(radius, 10))
end = t.time()
time = end - start
print(time.__round__(8))
start = t.time()
print("n = 100 => ", area_of_circle_trapezoid(radius, 100))
end = t.time()
time = end - start
print(time.__round__(8))
start = t.time()
print("n = 1000 => ", area_of_circle_trapezoid(radius, 1000))
end = t.time()
time = end - start
print(time.__round__(8))
print("Circle are with Monte Carlo Method:")
print("n = 10 => ", area_of_circle_monte_carlo(radius, 10))
print("n = 100 => ", area_of_circle_monte_carlo(radius, 100))
print("n = 1000 => ", area_of_circle_monte_carlo(radius, 1000))
print("n = 10000 => ", area_of_circle_monte_carlo(radius, 10000))
print("n = 100000 => ", area_of_circle_monte_carlo(radius, 100000))
print("\nCONCLUSION: I think that the most efficient method is Trapezoid method with high value of n")
| true |
218258b57bd2792615610fb9f04b18e37518678b | ChangXiaodong/Leetcode-solutions | /1/225-Implement-Stack-using-Queues.py | 1,778 | 4.1875 | 4 | '''
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
'''
from collections import deque
class Stack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.quene = deque()
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.quene.append(x)
def pop(self):
"""
:rtype: nothing
"""
if not self.empty():
buf = []
for v in range(len(self.quene)-1):
buf.append(self.quene[v])
self.quene = buf
def top(self):
"""
:rtype: int
"""
if not self.empty():
return self.quene[-1]
else:
return []
def empty(self):
"""
:rtype: bool
"""
if len(self.quene)==0:
return True
else:
return False
if __name__ == "__main__":
test = Stack()
test.push(1)
test.top()
print test.empty()
print test.quene | true |
a7b5005ded6f1bc65d6fcc82aacacca7f6e41a36 | divyaparmar18/saral_python_programs | /maximum.py | 707 | 4.1875 | 4 | # here we are making a function which will take list of students marks and print their highest marks
def max_num(list_of_marks):# here we made a function of name max_num
index = 0# here we declared the index of the list as 0
while index < len(list_of_marks):# here we give the condition to run the loop till the index is less thn lenght of the list
print max(list_of_marks[index])# this will remove the max number from the list as max is the inbuit function in pytohn
index=index+1# here we did the increment of the index
max_num([[45, 21, 42, 63], [12, 42, 42, 53], [42, 90, 78, 13], [94, 89, 78, 76], [87, 55, 98, 99]])# here we called the function with a list in list parameter
| true |
428636df3ef2962a5071c0d31a2dd1da4e3848aa | divyaparmar18/saral_python_programs | /Alien.py | 2,821 | 4.15625 | 4 | # here we will make a game in which we will fight with the alien
from random import randint # allows you to generate a random number
# variables for the alien
alive = True
stamina = 10
# this function runs each time you attack the alien
def report(stamin):
if stamin > 8:#here we give the condition
print "The alien is strong! It resists your pathetic attack!" # if upper condition is true this will be printed
elif stamin > 5:# if upper condition is not true loop comes here to another condition
print "With a loud grunt, the alien stands firm."# this gets printed if upper condition is true
elif stamin > 3:# so if stamin is less thn 3 then condition will be true
print "Your attack seems to be having an effect! The alien stumbles!"# and this will get printed
elif stamin > 0:# here one more condition is given if upper all conditions are false, loop comes here
print "The alien is certain to fall soon! It staggers and reels!"# and this gets printed
else:# if above all conditions are false then loop comes to the else part
print "That's it! The alien is finished!"# and this is printed
# main function - accepts your input for fight with the alien
def fight(stam): # stamina
while stam > 0:# here condition is given if stam to run the loop till stam is greater thn 0
# won't enter this loop ever. The function will always return False.
response = raw_input("> Enter a move 1.Hit 2.attack 3.fight 4.run")# here give a option to user to choose
# chose a response from ( hit, attack, fight and run)
# fight scene
if "hit" in response or "attack" in response:# here we give the condition
less = randint(0, stam)# if upper condition is true by using builtin function computer choses a number between 0 and stam
stam = stam - less # subtract random int from stamina
report(stam) # see function above
elif "fight" in response:# if user choses to fight
print "Fight how? You have no weapons, silly space traveler!"# this will be printed
elif "run" in response:# if user choses run
print "Sadly, there is nowhere to run.",# then this will be printed
print "The spaceship is not very big."
else:# if upper all the conditions are not true loop comes here
print "The alien zaps you with its powerful ray gun!"# this gets printed
return True# and it returns true
return False
print "A threatening alien wants to fight you!\n"
# quotes at the end.
# call the function - what it returns will be the value of alive
alive = fight(stamina)
if alive: # means if alive == True
print "\nThe alien lives on, and you, sadly, do not.\n"
else:
print "\nThe alien has been vanquished. Good work!\n"
| true |
d30e41a2f8bf944b1969a547f5898b48c5d3c1ce | divyaparmar18/saral_python_programs | /nested.py | 598 | 4.21875 | 4 | age = (input("enter the age:"))# here we will se the nested condition which means condition inside a condition, so hewre we will take the age of user
if age > 5:# so if the age of user is more thn 5
print ("you can go to school")# this will be printed
if age > 18:# condition
print ("you can vote")#if condition true gets printed
if age > 21:#condition
print ("you can drive a car")# if condition true gets printed
if age > 24:#condition
print ("you can drink")#if condition true gets printed
if age > 25:#condition
print ("you can marry now")#if conditiion true gets printed
| true |
49df96e91a1b039335488c7ce1b2bdf4a8e2bd86 | divyaparmar18/saral_python_programs | /input.py | 1,034 | 4.4375 | 4 | #here we will take the input from the user and we will see how to work with strings ,integers and floats
name = raw_input("put your name: ")
surname = raw_input("put your surname: ")
whole_name = (name + surname)
print (whole_name)#this will add the string and print both the srting to gether bcoz raw input means that user will input sometihng in string form
first = input("enter a number")
second = input("enter another number")
third = (first+second)
print (third)#this will add both the nubmers bcoz we took the input that means in a integer or floatr form
fourth = raw_input("enter a float")
fifth = raw_input("enyter another float")
sixth = (fourth+fifth)
print (sixth)#this will print both the floats together bcoz the input is taken in as a raw input which means that it is in strijng format
#so now we will convert the raw_input which is in string form in a integer
seventh = int(fourth)
eight = int(fifth)
nine = (seventh+eight)
print (nine)#here we have converted the raw_input to integer so now they will add the numbers | true |
955e48e827cd268c3f1f9ce579b238fc280cf7b4 | suraj-singh12/python-revision-track | /09-file-handling/questions/91_read_find.py | 459 | 4.1875 | 4 | try:
file = open("myfile.txt","r")
except IOError:
print("Error opening the file!!")
exit()
file = file.read()
file = file.lower() # converting all read content into lowercase, as we are ignoring the case in finding the word,
# i.e. for us twinkle and Twinkle are same
word = "twinkle"
if word in file:
print(f"YES!, {word} exists in the file.")
else:
print(f"NO!, {word} does NOT exists in the file.")
| true |
135d327f5aeb122c5c61838c1bcd42170afcc3af | mandalaalex1/MetricsConverionTool | /MetricsConversionTool.py | 1,906 | 4.15625 | 4 | print("Options:")
print("[P] Print Options")
print("[C] Convert from Celsius")
print("[F] Convert from Fahrenheit")
print("[M] Convert from Miles")
print("[KM] Convert from Kilometers")
print("[In] Convert from Inches")
print("[CM] Convert from Centimeters")
print("[Q] Quit")
while True:
Option1 = input("Option: ")
if Option1 == "C":
Celsius = int(input("Celsius Temperature: "))
F1 = float(Celsius*9//5 +32)
print("Fahrenheit: " + str(F1))
elif Option1 == "F":
Fahrenheit = int(input("Fahrenheit Temperature: "))
C1 = float((Fahrenheit-32)*5//9)
print("Celcius: " + str(C1))
elif Option1 == "M":
Miles = int(input("Miles Distance: "))
M1 = float((Miles//1.609))
print("Kilometers: " + str(M1))
elif Option1 == "KM":
Kilometers = int(input("Kilometers Distance: "))
KM1 = float((Kilometers*1.609))
print("Miles: " + str(KM1))
elif Option1 == "In":
Inches = int(input("Inches: "))
In = float((Inches*2.54))
print("Centimeters: " + str(In))
elif Option1 == "CM":
Centimeters = float(input("Centimeters: "))
CM1 = float((Centimeters//2.54))
print("Inches: " + str(CM1))
elif Option1 == "Y":
Yard = float(input("Yard: "))
Y1 = float((Yard//1.094))
print("Meters: " + str(Y1))
elif Option1 == "MT":
Meters = float(input("Meters: "))
MT1 = float((Meters*1.094))
print("Yard: " + str(MT1))
elif Option1 == "P":
print("[C] Convert from Celsius")
print("[F] Convert from Fahrenheit")
print("[M] Convert from Miles")
print("[KM] Convert from Kilometers")
print("[In] Convert from Inches")
print("[CM] Convert from Centimeters")
print("[Q] Quit")
elif Option1 == "Q":
print("Good bye!! :)")
break | false |
c70b9cde6d3208965fe1b4508b2ce84bea37643f | helalkhansohel/Python_Functions_Libraries | /Python Core/Basic Command/JSON.py | 682 | 4.125 | 4 |
#-------------------JSON----------------------------------
def MyJson():
import json
#Convert from JSON to Python:
x='{"Name":"Helal" ,"age":26}'
y=json.loads(x)
print(y["Name"])
#Convert from Python to JSON:
x={
"name": "John",
"age": 30,
"city": "New York"
}
y=json.dumps(x)
print(y)
#Convert Python objects into JSON strings, and print the values:
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
| false |
014ccca1f5bf022a761b58747a3720981c2dc45f | publicmays/LeetCode | /implement_queue_using_stacks.py | 1,491 | 4.46875 | 4 |
class Queue(object):
def __init__(self):
self.stack1 = [] # push
self.stack2 = [] # pop
def push(self, x):
self.stack1.append(x)
def pop(self):
if not self.stack2:
self.move()
self.stack2.pop()
def peek(self):
if not self.stack2:
self.move()
return self.stack2[-1]
def empty(self):
if not self.stack2:
self.move()
if not self.stack2:
return True
else:
return False
def move(self):
# move elements from stack 1 to stack 2
# creates an actual stack
# 1 2 3 4 5 --> 5 4 3 2 1
while self.stack1:
self.stack2.append(self.stack1.pop())
"""
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
* You must use only standard operations of a stack -- which means only push to
top, peek/pop from top, size, and is empty operations are valid.
* Depending on your language, stack may not be supported natively. You may
simulate a stack by using a list or deque (double-ended queue), as long as you
use only standard operations of a stack.
* You may assume that all operations are valid (for example, no pop or peek
operations will be called on an empty queue).
""" | true |
af852014b50d6e1b423f6bc18ab2d6ab4da33e18 | Shri-85535/OOPS | /Class&Object.py | 695 | 4.125 | 4 | '''
"Class" is a design for an object. Without design we cannot create anything.
A class is a collection of Objects
The Object is an entity that has a state and behavior associated with it. More specifically, any single integer or any single string is an object
'''
class Computer:
#1 Attributes(Variables)
#2 Behaviours(methods)
def config(self):
print("i5", "16gb", "1TB")
a = 'Shri'
x = 9
comp1 = Computer() #comp1 is an object
comp2 = Computer() #comp2 is an object
print(type(a)) #>>> <class 'str'>
print(type(x)) #>>> <class 'int'>
print(type(comp1)) #>>> <class '__main__.Computer'>
Computer.config(comp1)
Computer.config(comp2)
comp1.config()
comp2.config()
| true |
1726c1c108097b18d5f0a8fd73a6aab037834eca | aeciovc/sda_python_ee4 | /SDAPythonBasics/tasks_/task_03.py | 525 | 4.375 | 4 | """
Write a program that based on the variable temperature in degrees Celsius - temp_in_Celsius (float),
will calculate the temperature in degrees Farhenheit (degrees Fahrenheit = 1.8 * degrees Celsius + 32.0)
and write it in the console.
Get the temperature from the user in the console using argument-less input().
"""
celsius_str = input("Type the temperature in Celsius:")
celsius = float(celsius_str)
fahrenheit = 1.8 * celsius + 32.0
print(f"The temperature in Celsius {celsius}, it is in Fahrenheit {fahrenheit}")
| true |
cfe42df919522c35dc69de03d479b1fa81ba53a4 | AbhishekKumarMandal/SL-LAB | /SL_LAB/partA/q8.py | 1,112 | 4.34375 | 4 | from functools import reduce
l=[1,2,3,4,5,6]
m=[x*3 for x in l] #using list comprehension
print('list l: ',l)
print('list m: ',m)
#using reduce and lambda function
print('sum of list l: ',reduce(lambda a,b:a+b, l))
print('sum of list m: ',reduce(lambda a,b:a+b, m))
'''
A list comprehension generally consist of these parts :
Output expression,
input sequence,
a variable representing member of input sequence and
an optional predicate part.
For example :
lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
here, x ** 2 is output expression,
range (1, 11) is input sequence,
x is variable and
if x % 2 == 1 is predicate part.
####################################################################
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
####Syntax#####
lambda arguments : expression
x = lambda a : a + 10
print(x(5))
here x is a variable which is assigned a lambda function so now x is a function x(a)
where a is the argument form the lambda function
'''
| true |
7f2927ae1943864e1c0fcafd2a258e208b59f234 | talt001/Java-Python | /Python-Fundamentals/Loan Calculations/combs_loan_calculations_program.py | 1,840 | 4.3125 | 4 | #Step 1 write a python function that will calculate monthly payments on
# a loan.
#Step 2 pass the following to your function
#Principle of $20,000, with an APR of 4% to be paid in
# 1.) 36 months
# 2.) 48 months
# 3.) 60 months
# 4.) 72 months
#Step 3 include code for user supplied loan terms and comment out
#define the main function
def main():
#set some global constants for loan terms
Principle = 20000.00
APR = 0.04
rate = APR / 12
print('On a $20,000.00 loan, with 4% APR:')
print()
#iterate through 3, 4, 5, and 6 'years' and multiply by twelve to provide the argument 'n' in
#the proper terms - months
for years in range(3, 7):
n = years * 12
#assign the function to a variable for formatting in the print statements to follow
#calling the function directly within print() produces an error
payment = Calculate_monthly_payment(Principle, n, rate)
print('Your monthly payments will be $', format(payment, ',.2f'), ' when you borrow for ', n,' months.', sep = '')
print()
# code for user provided loan terms
# x, y, z = Get_loan_terms()
# payment = Calculate_monthly_payment(x, y, z)
# print('Your monthly payment will be $', format(payment, ',.2f'), sep = '')
# code for user provided loan terms
##def Get_loan_terms():
## Principle = float(input('Enter the loan amount: '))
## n = int(input('Enter duration of loan in months: '))
## APR = float(input('Enter the APR: '))
## rate = APR / 12
## return Principle, n, rate
#define the function to calculate monthly payments by writing a math expression
#return the value to mainn()
def Calculate_monthly_payment(Principle, n, rate):
monthly = Principle*((rate*(1+rate)**n))/((1+rate)**n - 1)
return monthly
#call the main function
main()
| true |
0ee112181b34e75917e80e23dd3411f06d3a3282 | andy-buv/LPTHW | /mystuff/ex33.py | 769 | 4.1875 | 4 | from sys import argv
x = int(argv[1])
y = int(arg[2])
# Remember to cast an input as an integer as it is read in as a string
# I forgot this because I was not using the raw_input() method
def print_list_while(number, step):
i = 0
numbers = []
while i < number:
print "At the top i is %d" % i
numbers.append(i)
i = i + step
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
def print_list_for(number, step):
numbers =[]
for i in range(0,number,step):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
print_list_while(x,y)
print_list_for(x,y) | true |
b96ec4a68ba1b9b370fb9c690cbb3e8cf0f1335d | andy-buv/LPTHW | /mystuff/ex23.py | 893 | 4.25 | 4 | Reading from Python Source Code for General Assembly DAT-8 Course
github.com
launchpad.net
gitorious.org
sourceforge.net
bitbucket.org
# LISTS
nums = [5, 5.0, 'five'] # multiple data types
nums # print the list
type(nums) # check the type: list
len(nums) # check the length: 3
nums[0] # print first element
nums[0] = 6 # replace a list element
nums.append(7) # list 'method' that modifies the list
help(nums.append) # help on this method
help(nums) # help on a list object
nums.remove('five') # another list method
sorted(nums) # 'function' that does not modify the list
nums # it was not affected
nums = sorted(nums) # overwrite the original list
sorted(nums, reverse=True) # optional argument
| true |
43d84ba163b1f8a4ecbfd84df0d54433b8e890f4 | Rita-Zey/python_project1 | /coffee_machine.py | 2,746 | 4.1875 | 4 | # Write your code here
import sys
ESPRESSO = [250, 0, 16, 4]
LATTE = [350, 75, 20, 7]
CAPPUCCINO = [200, 100, 12, 6]
class Coffee:
all_water = 400
all_milk = 540
all_beans = 120
all_cups = 9
all_money = 550
def coffee_machine_has():
print('The coffee machine has:')
print(Coffee.all_water, "of water")
print(Coffee.all_milk, "of milk")
print(Coffee.all_beans, "coffee of beans")
print(Coffee.all_cups, "of disposable cups")
print("$" + str(Coffee.all_money), "of money")
print("")
def take_money():
print("I gave you $" + str(Coffee.all_money))
Coffee.all_money = 0
print("")
def fill():
print("Write how many ml of water do you want to add:")
fill_water = int(input())
Coffee.all_water += fill_water
print("Write how many ml of milk do you want to add:")
fill_milk = int(input())
Coffee.all_milk += fill_milk
print("Write how many grams of coffee beans do you want to add:")
fill_beans = int(input())
Coffee.all_beans += fill_beans
print("Write how many disposable cups of coffee do you want to add:")
fill_cups = int(input())
Coffee.all_cups += fill_cups
print("")
def what_coffee_we_can(coffee):
if coffee[0] <= Coffee.all_water and coffee[1] <= Coffee.all_milk and coffee[2] <= Coffee.all_beans and Coffee.all_cups >= 1:
print("I have enough resources, making you a coffee!")
make_coffee(coffee)
elif coffee[0] > Coffee.all_water:
print("Sorry, not enough water!")
elif coffee[1] > Coffee:
print("Sorry, not enough milk!")
elif coffee[2] > Coffee:
print("Sorry, not enough beans!")
else:
print("Sorry, not enough cups!")
print("")
def make_coffee(coffee):
Coffee.all_water -= coffee[0]
Coffee.all_milk -= coffee[1]
Coffee.all_beans -= coffee[2]
Coffee.all_money += coffee[3]
Coffee.all_cups -= 1
def buy_coffee(number):
if number == "1":
what_coffee_we_can(ESPRESSO)
elif number == "2":
what_coffee_we_can(LATTE)
else:
what_coffee_we_can(CAPPUCCINO)
def action_coffee(my_action):
if my_action == "fill":
fill()
elif my_action == "buy":
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
number = input()
if number == "back":
main()
else:
buy_coffee(number)
elif my_action == "remaining":
coffee_machine_has()
else:
take_money()
main()
def main():
print("Write action (buy, fill, take, remaining, exit):")
action = input()
print("")
if action == "exit":
sys.exit(0)
else:
action_coffee(action)
main()
| true |
6eba0e3cfaca03bc2754cc690c1cfa5468af787e | aprilxyc/coding-interview-practice | /ctci/ctci-urlify.py | 695 | 4.3125 | 4 | # problem 1.3 ctci
""" Write a method to replace all spaces in a string with %20. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given
the 'true' length of the string.
E.g.
Input: 'Mr John Smith ", 13
Output: 'Mr%20John%20Smith'
"""
def urlify(string, str_len):
total_len = len(string)
num_spaces = total_len - str_len
final_index = total_len - num_spaces
complete_word = string[0:final_index]
for i in complete_word:
complete_word = complete_word.replace(" ", "%20")
complete_word = complete_word + "%20"
return complete_word
if __name__ == "__main__":
print(urlify("Mr John Smith ", 13))
| true |
ba3c1522f31525085aede553ba0a476e9a5ddb57 | aprilxyc/coding-interview-practice | /leetcode-problems/1252-cells-odd-values.py | 1,917 | 4.21875 | 4 | # nested list comprehension example
# answer = [[i*j for i in range(1, j+1)] for j in range(1, 8)]
indices = [[0,1],[1,1]]
matrix = [[0 for a in range(3)] for b in range(2)]
print(matrix)
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
# O(N^2) because it has to go through the list of indices and when it goes through, it has to
# go through the number of numbers to change
# create the matrix using a nested list comprehension
matrix = [[0 for i in range(m)] for i in range(n)] # learn this properly and memorise!
# loop through the indices list
for i in indices:
# go through the matrix and increment this row
for j in range(m):
matrix[i[0]][j] += 1
# go through the matrix and increment the column
for j in range(n):
matrix[j][i[1]] += 1
# then go through the matrix and count which numbers are odd
odd_count = 0
for i in range(n):
for j in range(m):
if matrix[i][j] % 2 != 0:
odd_count += 1
return odd_count
# my most recent attempt 11/01/ 2020
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
# create the matrix
matrix = [[0 for i in range(m)] for j in range(n)] # [[1,3,1],[1,1,1]].
for i in indices: #[[0,1],[1,1]]
row = i[0] # 1
col = i[1] # 1
# now increment the col
for j in range(0, len(matrix)):
matrix[j][col] += 1
# increment the entire row
matrix[row]= [s + 1 for s in matrix[row]]
# find the number of cells with odd values
result = 0
for i in range(n):
for j in range(m):
if matrix[i][j] % 2 != 0:
result += 1
return result
| true |
6cfaa8f0048bff952d17bfb591b90849423cf5f4 | aprilxyc/coding-interview-practice | /leetcode-problems/350-intersection-of-two-arrays-ii.py | 2,771 | 4.15625 | 4 | """
https://leetcode.com/problems/intersection-of-two-arrays-ii/
Good solution to look at:
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82247/Three-Python-Solutions
What if the given array is already sorted? How would you optimize your algorithm? Use pointers
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
- Be careful of intersection of two arrays (whether they want all occurrences of duplicates or not) - a dictionary can only keep 1 id in it so you cannot use this if the question asks for all occurrences (icludig duplicates) - use pointers here
"""
# note this solution below is incorrect because I didn't read the question properly.
# It wants to show ALL occurrences of numbers including duplicates so you cannot just use set or a dictiomary that only stores it once
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
num_dict = {}
for i in nums1:
if i not in num_dict:
num_dict[i] = 0 # add it to dictionary
result = []
for i in nums2:
if i in num_dict:
result.append(i)
return result
# optimise algorithm if sorted
# you can simply use pointers to find your algorithm
# this may be faster because in the other one, the number could be anyway. Here, we know where it is already and can quicly eliminate other
# possibilities once we have traversed the sections that concern our numbers. However, sorting takes up extra time with heapsort for NlogN.
# CORRECT SOLUTION HERE
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
# Time complexity: O(m + n) where m is num of elements in nums1 and n is num of elements in nums2
# O(max(m, n)) where it is the longest list that we have to go through
res = []
# sort it first and it will be faster to get the result
nums1.sort()
nums2.sort()
index_i, index_j = 0, 0
while index_i < len(nums1) and index_j < len(nums2):
if nums1[index_i] == nums2[index_j]:
res.append(nums1[index_i])
index_i += 1
index_j += 1
elif nums1[index_i] > nums2[index_j]:
index_j += 1
else:
index_i += 1
return res
class Solution(object):
def intersect(self, nums1, nums2):
counts = {}
res = []
for num in nums1:
counts[num] = counts.get(num, 0) + 1
for num in nums2:
if num in counts and counts[num] > 0:
res.append(num)
counts[num] -= 1
return res | true |
880c9c52bc8fd1faa1ede09b498470129b007018 | aprilxyc/coding-interview-practice | /leetcode-problems/232-implement-queue-using-stacks.py | 1,773 | 4.15625 | 4 | """
https://leetcode.com/problems/implement-queue-using-stacks/
"""
# a very bad first implementation 27/01
# space is O(N)
# time complexity stays constant and is O(1) amortised
# we look at the overarching algorithm's worst case
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.push_stack = []
self.pop_stack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
# simply push the element to the push stack
self.push_stack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.empty():
return None
if len(self.pop_stack) == 0: # if the pop stack is empty, check the push stack
while self.push_stack:
item = self.push_stack.pop()
self.pop_stack.append(item)
return self.pop_stack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if self.empty():
return None
if len(self.pop_stack) == 0:
while self.push_stack:
item = self.push_stack.pop()
self.pop_stack.append(item)
return self.pop_stack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if len(self.pop_stack) == 0 and len(self.push_stack) == 0:
return True
return False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty() | true |
194db0f16c84d40c6b193d54c0810579e7eba82b | emtee77/PBD_MJ | /muprog/cities.py | 634 | 4.25 | 4 | myfile = open('cities.txt', 'w') #This is used to open a file, w-writes to the file
myfile.write("Dublin\n")
myfile.write("Paris\n")
myfile.write("London\n")
myfile.close() #it is good to always close the file when you are done with it
myfile = open("cities.txt", "r") #This is used to open a file, r-reads the file
s1 = myfile.readline()
print s1
s2 = myfile.readline()
print s2
s3 = myfile.readline()
print s3
myfile.close()
myfile = open("cities.txt", "r")
lines = myfile.readlines()
myfile.close()
print lines
for line in lines:
print line
myfile = open("cities.txt", "r")
for line in myfile:
print line
myfile.close() | true |
19177be68bd64b821ed2ac20f347cfd85ca5548d | typemegan/Python | /CorePythonProgramming_2nd/ch09_files/commentFilter.py | 398 | 4.25 | 4 | #!/usr/bin/python
'''
Exercise 9-1:
display all the lines of file, filtering the line beginning with "#"
Problem:
extra credit: strip out comments begin after the first character
'''
name = raw_input('enter a filename> ')
f = open(name,'r')
i = 1 # counting file lines
for eachLine in f:
if eachLine.[0] != '#':
print i, eachLine.strip()
else:
print i, '#comments'
i += 1
f.close()
| true |
df495a122a08bbde2fdbe1b6b03bbd15c4f343cd | typemegan/Python | /Errors/Exception/StandardError/RuntimeError/maxRecursionDepth.py | 346 | 4.1875 | 4 | '''
there is a limit in recursion depth
'''
#example
def Factorial(n):
if n > 1:
return n * Factorial(n-1)
elif n == 1 or n == 0:
return 1
'''
test result:
10! = 3628800
1000!: RuntimeError:maximum recursion depth exceeded
原因:递归展开(深度)存在限制
试验结果:当n>=999时报错
'''
| false |
5e05c5a64587e06dcb7422350c90fb683fe5ef5c | typemegan/Python | /CorePythonProgramming_2nd/ch08_loops/getFactors.py | 447 | 4.15625 | 4 | #!/usr/bin/python
'''
Exercise 8-5:
get all the factors of a given integer
'''
def getFactors(num):
facts = [num]
# while
# count = num/2
# while count >= 1:
# if num % count == 0:
# facts.append(count)
# count -= 1
# for
for count in range(num/2, 0, -1):
if num % count == 0:
facts.append(count)
return facts
num = int(raw_input('enter an integer> '))
facts = getFactors(num)
print "the factors of %d are:" % num
print facts
| true |
07782b22ea28d71b07d515bca3affed7684d3193 | PxlPrfctJay/currentYear | /leapYear.py | 2,189 | 4.4375 | 4 | # A Program that has three functions to return a day of year
#Function One:
# A function that checks if a given year is a leap year
#Function Two:
# A function that returns number of days in month
# (28,29,30,31) depending on the given month(1-12) and year
# which uses isYearLeap(year) to determine a leap year
#Function Three:
# A function that returns a day of the year in month/day/year format
# It will return 'None' if the given day is more than 31 or less than 1
# It will return a Type if month is more than 12 or less than 1
def isYearLeap(year):
#check if year is equally divisible by 4
if(year%4==0):
#if year divisible by 4, check if divisble by 100
if(year%100==0):
#if year divisible by 100 check if year alos divisible by 400
#if true year is leap and return True
if(year%400==0):
return True
#if not divisible by 400 return false, not a leap year
else:
return False
#if not divisible by 100 but by 4, return true for leap year
else:
return True
#if not divisible by 4, return false for no leap year
else:
return False
def daysInMonth(year, month):
#create two lists to account for 30 day months and 31 day months
thirtyDays = [4,6,9,11]
thirtyOneDays = [1,3,5,7,8,10,12]
#run given month thru if statements to determine number of days in month
if(month in thirtyOneDays):
#return 31 if the given month is in thirtyOneDays list
return 31
elif(month in thirtyDays):
return 30
#return 30 if the given month is in thirtyDays list
elif(month==2):
#Since month is Feb, check if year is Leap, 29 if yes, 28 if not.
if(isYearLeap(year)):
return 29
else:
return 28
def dayOfYear(year, month, day):
#check if given day is valid, if not return None
if(day>(daysInMonth(year, month)) or day<1):
return None
else:
#return the day of year in month/day/year format
return "{}/{}/{}".format(month,day,year)
#call Function Three
print(dayOfYear(2020, 12, 29)) | true |
dc7570703a8820221bdbb033220db2a9d6427063 | Adioosin/DA_Algo_Problems | /Sum of pairwise Hamming Distance.py | 1,273 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Hamming distance between two non-negative integers is defined as the number of positions at which the corresponding bits are different.
For example,
HammingDistance(2, 7) = 2, as only the first and the third bit differs in the binary representation of 2 (010) and 7 (111).
Given an array of N non-negative integers, find the sum of hamming distances of all pairs of integers in the array.
Return the answer modulo 1000000007.
Example
Let f(x, y) be the hamming distance defined above.
A=[2, 4, 6]
We return,
f(2, 2) + f(2, 4) + f(2, 6) +
f(4, 2) + f(4, 4) + f(4, 6) +
f(6, 2) + f(6, 4) + f(6, 6) =
0 + 2 + 1
2 + 0 + 1
1 + 1 + 0 = 8
"""
def hammingDistance(A):
total = 0
largest = 0
ln = len(A)
A = list(A)
for i in range(0,ln):
#b = i[0]^i[1]
A[i] = bin(A[i])[2:]
l = len(A[i])
if(l>largest):
largest = l
for i in range(0,ln):
l = len(A[i])
if(l<largest):
A[i] ='0'*(largest-l)+A[i]
#print(A)
for i in range(0,largest):
x = 0
y = 0
for j in A:
if(j[i]=='0'):
x = x + 1
else:
y = y + 1
total = total + 2 * x * y
return total%1000000007
print(hammingDistance([2,4,6])) | true |
b1e8af4694fc7f951b4a0cc8bbb6acda2549f3be | bn06a2b/Python-CodeAcademy | /pizza_lens_slice.py | 838 | 4.625 | 5 | #addding toppings list
toppings=['pepperoni','pineapple','cheese','sausage','olives','anchovies','mushrooms']
#adding corresponding price list
prices=[2,6,1,3,2,7,2]
#number of pizzas and printing string to show no. of pizzas
num_pizzas=len(toppings)
print("We sell " +str(num_pizzas) + " different kinds of pizza!")
#combining toppings and prices into one list called pizzas and print output
pizzas=list(zip(prices,toppings))
#print(pizzas)
#sort the pizza prices from lowest to highest and update the list
prices.sort()
pizzas.sort()
print(pizzas)
#creating the cheapest pizza and most expensive pizza variables
cheapest_pizza=pizzas[0]
priciest_pizza=pizzas[-1]
#obtain the 3 lowest cost pizzas and display
three_cheapest=pizzas[:3]
print(three_cheapest)
num_two_dollar_slices=prices.count(2)
print(num_two_dollar_slices)
| true |
23b372d9bc54c9d5989bc21c8af1fe1312dd1995 | Dannyh0198/Module-3-Labs | /Module 3 Labs/Working Area.py | 422 | 4.15625 | 4 | my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]
list_without_duplicates = []
for number in my_list: # Browse all numbers from the source list.
if number not in list_without_duplicates: # If the number doesn't appear within the new list...
list_without_duplicates.append(number) # ...append it here.
my_list = list_without_duplicates[:] # Make a copy of new_list.
print("The list with unique elements only:")
print(my_list) | true |
170afd5d9894788e49bd328bce7bca8987b49458 | parveenkhatoon/python | /ifelse_question/age_comp.py | 338 | 4.25 | 4 |
age = int(input("Enter the age:"))
if age <= 2:
print("person is baby")
if age > 2 and age < 4:
print("person is a toddler")
if age >= 4 and age < 13:
print("person is the kid")
if age >= 13 and age < 20:
print("person is a teenager")
if age >= 20 and age < 65:
print("person is an adult")
if age >= 65:
print("person is an elder") | true |
84e282e8ec93ff960e6ddf42b3605023ce875b38 | parveenkhatoon/python | /mix_logical/reverse.py | 522 | 4.1875 | 4 |
'''reverse with while loop'''
number=int(input("number:"))
reverse=0
while (number>0):
reminder=number%10
reverse=(reverse*10)+reminder
number=number//10
print("reverse number",reverse)
'''reverse is using if condition'''
num=int(input("number:"))
rev=0
if num>1:
ram=num%10
rev=(rev*10)+ram
num=num//10
if num>=0:
ram=num%10
rev=(rev*10)+ram
num=num//10
if num>=0:
ram=num%10
rev=(rev*10)+ram
num=num//10
if num>=0:
ram=num%10
rev=(rev*10)+ram
num=num//10
print("reverse number",rev)
| true |
bfd8c45b831a6d3e40b30b7645b20a8ad51051ab | englisha4956/CTI110 | /P1HW2_BasicMath_EnglishAnthony.py | 575 | 4.21875 | 4 | # Netflix MONTHLY & ANNUAL FEE GENERATOR +TAX
# 9/26/2021
# CTI-110 P1HW2 - Basic Math
# Anthony English
#
charge = 17.99
tax = charge * .06
monthly = charge + tax
annual = monthly * 12
name = ('Netflix')
print('Enter name of Expense:', end=' ')
name = input()
print('Enter monthly charge:', end=' ')
monthly = input()
print()
print('Bill: Netflix', end=' ')
print('---------', end=' ')
print('Before Tax: $17.99 ')
print('Monthly Tax: $1.08 ')
print('Monthly Charge: $19.07 ')
print('Annual Netflix Charge: $228.84 ')
print()
| true |
d6d98709ce72d98aedc1f3eb3e287d6239d36564 | abhirathmahipal/Practice | /Python/Core Python Programming/Chapter - 2/BasicForLoops.py | 497 | 4.53125 | 5 | # Iterating over a for loop. It doesn't behave like a traditional
# counter but rather iterates over a sequence
for item in ['email', 'surfing', 'homework', 'chat']:
print item,
# Modifying for loops to behave like a counter
print "\n"
for x in xrange(10):
print x,
# Iterating over each character in a string
foo = 'abcd'
print "\n"
for c in foo:
print c,
print "\n"
# Using enumerate in a for loop
for i, ch in enumerate(foo):
print ch, '(%d)' %i
help(enumerate)
| true |
311b031bcd268c43ddce442463c06b62c7e550f2 | tedmcn/Programs | /CS2A/PA1/prime.py | 713 | 4.3125 | 4 | def prime(num):
"""
Tester - Takes an input number from the user and tests whether it is prime
or not. Then, it returbns True or False depending on the number and prompts
the user if it is prime or not. Returns True or False if prime or not.
Example answers:
prime(10)
prime(227)
prime(617)
"""
for i in range(2, num):
if num%i == 0 and i != num:
return False
return True
if __name__ =="__main__":
print("This program will check if the inputted number is prime.")
user_num = int(input("Enter value: "))
if prime(user_num) == False:
print("It is not a prime number.")
else:
print("It is a prime number.")
| true |
74c22afb2fcbc02a2ca574e6e780f62a1c6bcfce | htbo23/ITP-Final-Project | /Waiter.py | 2,793 | 4.125 | 4 | # Tiffany Bo
# ITP 115, Fall 2019
# Final Project
from Menu import Menu
from Diner import Diner
class Waiter():
def __init__(self, menu):
# sets it to an empty list
self.diners = []
self.menu = menu
# adds a diner to the list
def addDiner(self, diner):
self.diners.append(diner)
#finds how many diners there are
'''
inputs: none
returns: number of diners
'''
def getNumDiners(self):
length = len(self.diners)
return length
'''
inputs: none
returns: none
'''
def printDinerStatuses(self):
STATUSES = ["seated", "ordering", "eating", "paying", "leaving"]
for stat in STATUSES:
print("Diners who are currently", stat + ":")
for diner in self.diners:
if diner.STATUSES[diner.status] == stat:
print("\t" + str(diner))
# if the diner's status. parameters: none. returns: none.
def takeOrders(self):
#loops through all of the diners
for diner in self.diners:
# checks if the diner's status is 1, meaning they're ordering
if diner.status == 1:
#loops through the menu keys
print("\n")
for j in self.menu.menuItemDictionary.keys():
print("\n-----" + j + "s-----")
#loops though all of the menu items in each key(category)
for k in range(len(self.menu.menuItemDictionary[j])):
#prints a numbered list and description of the menu item accessing the __str__ method
print(str(k) + ") " + str(self.menu.menuItemDictionary[j][k]))
# after the menu items in each category are printed out, it asks the user for input
request = int(input(diner.name + ", please select a " + j + " menu item number.\n>"))
# error checking
count = 0
for item in self.menu.menuItemDictionary[j]:
count += 1
while request > count-1 or request < 0:
request = int(input(">"))
menuitem = self.menu.menuItemDictionary[j][request]
diner.order.append(menuitem)
#prints out the diner's order
print(diner.name, "ordered:")
for i in diner.order:
print("-", i)
# no inputs or return values
def ringUpDiners(self):
for diner in self.diners:
# checks if the diner's status is 3, meaning they're paying
if diner.status == 3:
cost = diner.calculateMealCost()
print("\n" + diner.name + ", your meal cost $"+ str(round(cost, 2))+ ".")
# no inputs or return values
def removeDoneDiners(self):
for diner in self.diners:
if diner.status == 4:
print("\n" + diner.name + ", thank you for dining with us! Come again soon!")
for i in reversed(range(len(self.diners))):
if self.diners[i].status == 4:
del self.diners[i]
# no inputs or return values
def advanceDiners(self):
self.printDinerStatuses()
self.takeOrders()
self.ringUpDiners()
self.removeDoneDiners()
#advances all the diners
for diner in self.diners:
diner.updateStatus() | true |
6db19a61d62c41144e6dcdbd510e8a6c63f4c8d8 | vikasvisking/courses | /python practic/list_less_then_10.py | 850 | 4.375 | 4 | """Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5."""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for element in a:
if element < 5 :
print(element)
# Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
newList = []
for element in a:
if element < 5:
newList.append(element)
print(newList)
# Write this in one line of Python.
newlist = [i for i in a if i<5]
print (newlist)
# Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
number = int(input("please enter a number: "))
lst = [i for i in a if i< number]
print(lst) | true |
f36e514a1fad77868fb66799b4ea313d0708ebb1 | GuuMee/ExercisesTasksPython | /1 Basics/25_units_of_time2.py | 1,215 | 4.40625 | 4 | """
In this exercise you will reverse the process described in the previous exercise.
Develop a program that begins by reading a number of seconds from the user.
Then your program should display the equivalent amount of time in the form
D:HH:MM:SS, where D, HH, MM, and SS represent days, hours, minutes and sec�onds respectively. The hours, minutes and seconds should all be formatted so that
they occupy exactly two digits, with a leading 0 displayed if necessary.
"""
# Convert a number of seconds to days, hours, minutes and seconds
SECONDS_PER_DAY = 86400
SECONDS_PER_HOUR = 3600
SECONDS_PER_MINUTE = 60
# Read input from the user
seconds = int(input("Enter a number of seconds: "))
# Compute the days, hours, minutes and seconds
days = seconds / SECONDS_PER_DAY
seconds = seconds % SECONDS_PER_DAY
hours = seconds / SECONDS_PER_HOUR
seconds = seconds % SECONDS_PER_HOUR
minutes = seconds / SECONDS_PER_MINUTE
seconds = seconds % SECONDS_PER_MINUTE
# Display the result with the desired formatting
print("The equivalent duration is %d:%02d:%02d:%02d." % (days, hours, minutes, seconds))
# the %02d format specifier tells Python to format the integer using two digits, adding a leading 0 if necessary
| true |
54e634be4757a88da539d5db29f0ac33efb69a82 | GuuMee/ExercisesTasksPython | /5 Lists/_116_latin_improved.py | 2,508 | 4.4375 | 4 | """
Extend your solution to Exercise 115 so that it correctly handles uppercase letters and
punctuation marks such as commas, periods, question marks and exclamation marks.
If an English word begins with an uppercase letter then its Pig Latin representation
should also begin with an uppercase letter and the uppercase letter moved to the end of
the word should be changed to lowercase. For example, Computer should become
Omputercay. If a word ends in a punctuation mark then the punctuation mark
should remain at the end of the word after the transformation has been performed.
For example, Science! should become Iencescay!.
"""
vowels = ["a", "e", "i", "o", "u"]
punctuations = [".", ",", "!", "?", '"']
def pig_latin(s):
length = len(s)
if s[-1] not in punctuations:
if s[0] not in vowels:
if s[1] not in vowels:
if s[2] not in vowels:
lov1 = s[0].lower()
removed = lov1+s[1:3]
changed = s[3].upper() + s[4:length-1]+removed+"ay"
return changed
lov1 = s[0].lower()
removed = lov1 + s[1:2]
changed = s[2].upper() + s[3:length - 1] + removed + "ay"
return changed
lov1 = s[0].lower()
removed = lov1
changed = s[1].upper() + s[2:length - 1] + removed + "ay"
return changed
elif s[0] in vowels:
changed = s + "way"
return changed
elif s[-1] in punctuations:
if s[0] not in vowels:
if s[1] not in vowels:
if s[2] not in vowels:
lov1 = s[0].lower()
removed = lov1 + s[1:3]
changed = s[3].upper() + s[4:length - 1] + removed + "ay" + s[-1]
return changed
lov1 = s[0].lower()
removed = lov1 + s[1:2]
changed = s[2].upper() + s[3:length - 1] + removed + "ay" + s[-1]
return changed
lov1 = s[0].lower()
removed = lov1
changed = s[1].upper() + s[2:length - 1] + removed + "ay" + s[-1]
return changed
elif s[0] in vowels:
changed = s[0:length-1] + "way" + s[-1]
return changed
def main():
line = input("Enter the line of the text: ")
p_latin = pig_latin(line)
print("The result of the translated text to pig latin:", p_latin)
if __name__ == '__main__':
main()
| true |
566912a27657e29b961c7a24fcc3fa76c65d2d94 | GuuMee/ExercisesTasksPython | /4_Functions/94_random_password.py | 1,216 | 4.59375 | 5 | """
Write a function that generates a random password. The password should have a
random length of between 7 and 10 characters. Each character should be randomly
selected from positions 33 to 126 in the ASCII table. Your function will not take
any parameters. It will return the randomly generated password as its only result.
Display the randomly generated password in your file’s main program. Your main
program should only run when your solution has not been imported into another file.
Hint: You will probably find the chr function helpful when completing this
exercise. Detailed information about this function is available online.
"""
from random import randint
SHORTEST = 7
LONGEST = 10
MIN_ASCII = 33
MAX_ASCII = 126
def random_password():
random_length = randint(SHORTEST, LONGEST)
result = ""
for i in range(random_length):
random_char = chr(randint(MIN_ASCII, MAX_ASCII))
# chr() takes an ASCII code as its parameter. It returns a string containing the
# character with that ASCII code as its result
result += random_char
return result
def main():
print("Your random password is:", random_password())
if __name__ == '__main__':
main()
| true |
279b21d9e3839e9755e24e8fdf682135caab2d6a | GuuMee/ExercisesTasksPython | /1 Basics/23_area_polygon.py | 804 | 4.5 | 4 | """
A polygon is regular if its sides are all the same length and the angles between all of
the adjacent sides are equal. The area of a regular polygon can be computed using
the following formula, where s is the length of a side and n is the number of sides:
area = (n*s^2)/4*tan(pi/n)
Write a program that reads s and n from the user and then displays the area of a
regular polygon constructed from these values.
"""
import math
def area_polygon():
s = int(input("Enter the length of a side: "))
n = int(input("Enter the number of sides: "))
area = (n * s ** 2) / 4 * math.tan(math.pi / n)
print("Area of the Regular Polygon will be %.2f" % area)
# Results:
# Enter the length of a side: 23
# Enter the number of sides: 8
# Area of the Regular Polygon will be 438.24
| true |
4a762a39608178aca8325026ef78449181d91656 | GuuMee/ExercisesTasksPython | /1 Basics/31_sum_of_digits.py | 594 | 4.125 | 4 | """
Develop a program that reads a four-digit integer from the user and displays the sum
of the digits in the number. For example, if the user enters 3141 then your program
should display 3+1+4+1=9.
"""
# Read the input of the digits from the user
digits = input("Enter the 4-digit integer number: ")
# Convert to int each element of the string
dig1 = int(digits[0])
dig2 = int(digits[1])
dig3 = int(digits[2])
dig4 = int(digits[3])
# Compute the sum of the digits
sum_of_digits = dig1 + dig2 + dig3 + dig4
# Display the result
print("The sum of the digits in the number =", sum_of_digits)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.