blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e8b6686ac6ecd5d490688ff33633ca530407f6c0 | SHJoon/Algorithms | /arrays/9_rotate_array.py | 705 | 4.15625 | 4 | # Rotate Array
# Implement rotateArr(arr, shiftBy) that
# accepts array and offset. Shift arr’s values to the
# right by that amount. ‘Wrap-around’ any values
# that shift off array’s end to the other side, so that
# no data is lost. Operate in-place: given
# ([1,2,3],1), change the array to [3,1,2].
def rotate_arr(arr, shift_by):
while shift_by > len(arr):
shift_by -= len(arr)
left_arr = arr[0:shift_by]
right_arr = arr[len(arr) - shift_by - 1: len(arr)]
for idx, num in enumerate(right_arr):
arr[idx] = num
for idx, num in enumerate(left_arr):
arr[idx + len(right_arr)] = num
my_list = [1,2,3,4,5,6,7]
rotate_arr(my_list, 3)
print(my_list) | true |
74bb0a85a677c94c0dd5fc5057d4cffb988f51a8 | SHJoon/Algorithms | /hackerrank/warmup/2_counting_valleys.py | 2,221 | 4.78125 | 5 | # An avid hiker keeps meticulous records of their hikes. During the last
# hike that took exactly steps steps, for every step it was noted if it was an uphill, U,
# or a downhill, D step. Hikes always start and end at sea level, and each step up or
# down represents a 1 unit change in altitude. We define the following terms:
# - A mountain is a sequence of consecutive steps above sea level, starting with a
# step up from sea level and ending with a step down to sea level.
# - A valley is a sequence of consecutive steps below sea level, starting with a
# step down from sea level and ending with a step up to sea level.
# Given the sequence of up and down steps during a hike, find and print the number
# of valleys walked through.
# Example
# steps = 8 path = [DDUUUUDD]
# The hiker first enters a valley 2 units deep. Then they climb out and up onto a mountain 2 units high.
# Finally, the hiker returns to sea level and ends the hike.
# Function Description
# Complete the countingValleys function in the editor below.
# countingValleys has the following parameter(s):
# int steps: the number of steps on the hike
# string path: a string describing the path
# Returns
# int: the number of valleys traversed
# Input Format
# The first line contains an integer steps, the number of steps in the hike.
# The second line contains a single string path, of steps characters that describe the path.
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'countingValleys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER steps
# 2. STRING path
#
def countingValleys(steps, path):
# Write your code here
valley = level = 0
for direction in path:
if direction == "U":
level += 1
elif direction == "D":
level -= 1
if direction == "U" and level == 0:
valley += 1
return valley
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
steps = int(input().strip())
path = input()
result = countingValleys(steps, path)
fptr.write(str(result) + '\n')
fptr.close()
| true |
48245c91b2bcf9b78c3fc81c57bb447a85db5231 | maladeveloper/algos-and-data-structures | /Sorting/heap_sort.py | 482 | 4.21875 | 4 | from heap import MinHeap
def heap_sort(arr):
sorted_arr = []
min_heap = MinHeap(array=arr)
for i in range(len(arr)):
sorted_arr.append(min_heap.extract_min())
for i in range(len(sorted_arr)):
arr.append(sorted_arr[i])
if __name__ == "__main__":
arr = [3, 21, 123, 2, 1, 2, 3, 48, 12, 10, 13]
print(f'''Using heap sort to sort the following array {arr}...''')
heap_sort(arr)
print(f'''Sorted array is: {arr}''') | false |
b14444421ce6c71b7ad8ba3e72fbc6558e0bcca9 | maladeveloper/algos-and-data-structures | /StacksAndQueue/reversing_linked_list.py | 1,495 | 4.25 | 4 | from SingleLinkedList import Linked List
'''
Code for reversing a list via both functions was written by me.
'''
my_list = LinkedList()
my_list.append("M")
my_list.append("A")
my_list.append("L")
my_list.print_list()
##Implementation of reversing a linked list using recursion
def reverse_list(prev_node, curr_node):
if curr_node.next is not None:
reverse_list(curr_node, curr_node.next)
else:
my_list.tail = my_list.head
my_list.head = curr_node
curr_node.next = prev_node
reverse_list(None, my_list.head)
print(f'''-----------reversed list---------------''')
my_list.print_list()
##Implementation of reversing a list using for loops.
def reverse_list(my_list):
temp_stack = []
##Put the referances and the nodes to the stack
curr_node = my_list.head
while curr_node.next is not None:
next_node = curr_node.next
temp_stack.append([curr_node, next_node])
curr_node = curr_node.next
my_list.head.next = None #Current head to be tail point None
##Now reverse the stack and point the new referances
for i in range(len(temp_stack)-1, -1, -1):
next_node, curr_node = temp_stack[i]
curr_node.next = next_node
my_list.head = temp_stack[-1][-1]
reverse_list(my_list)
print(f'''-----------reversed list---------------''')
my_list.print_list()
| true |
4ad9e9a083c73a065cd9af7d8f00d56f01971f14 | kantel/nodebox-pyobjc | /examples/Extended Application/sklearn/examples/linear_model/plot_ols.py | 2,804 | 4.15625 | 4 | """
=========================================================
Linear Regression Example
=========================================================
This example uses the only the first feature of the `diabetes` dataset, in
order to illustrate a two-dimensional plot of this regression technique. The
straight line can be seen in the plot, showing how linear regression attempts
to draw a straight line that will best minimize the residual sum of squares
between the observed responses in the dataset, and the responses predicted by
the linear approximation.
The coefficients, the residual sum of squares and the variance score are also
calculated.
"""
print(__doc__)
# Code source: Jaques Grobler
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# nodebox section
if __name__ == '__builtin__':
# were in nodebox
import os
import tempfile
W = 800
inset = 20
size(W, 600)
plt.cla()
plt.clf()
plt.close('all')
def tempimage():
fob = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png', delete=False)
fname = fob.name
fob.close()
return fname
imgx = 20
imgy = 0
def pltshow(plt, dpi=150):
global imgx, imgy
temppath = tempimage()
plt.savefig(temppath, dpi=dpi)
dx,dy = imagesize(temppath)
w = min(W,dx)
image(temppath,imgx,imgy,width=w)
imgy = imgy + dy + 20
os.remove(temppath)
size(W, HEIGHT+dy+40)
else:
def pltshow(mplpyplot):
mplpyplot.show()
# nodebox section end
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]
# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
# Make predictions using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
# plt.show()
pltshow(plt)
| true |
f01c1a88928fec538ea44250e3f0d86eccfce234 | erofes/python_learn | /CribLibrary/functions/function_arguments.py | 606 | 4.25 | 4 | def func(a, b, c = 2): # a, b is necessary! c is not necessary
return a + b + c
print(func(1, 2, 3), func(1, 2), func(a=2, b=3)) # There are ways to use arguments
# 6 5 7
def many(*args): # Must take any number of elements, unnamed tuple
'''Custom description: Return input arguments'''
return args # it's tuple type
print(many(1, 2, 3, 'abc', func), many(1))
# (1, 2, 3, 'abc', <function func at 0x0025B228>) (1,) -> It's tuple!
def other_many(**args): # It takes only NAMED arguments
return args
print(other_many(a=1, b=2, c=3))
# {'a': 1, 'c': 3, 'b': 2} -> It's dictionary!
| true |
781821bec5003263baf4364df0f0d8d92ae3ce44 | jorien-witjas/python-labs | /python_fundamentals-master/07_classes_objects_methods/07_00_planets.py | 629 | 4.21875 | 4 | '''
Create a Planet class that models attributes and methods of
a planet object.
Use the appropriate dunder method to get informative output with print()
'''
class Planet():
def __init__(self, name, size, colour):
self.name = name
self.size = size
self.colour = colour
Jupiter = Planet("jupiter", "big", "Green")
print(Jupiter.name)
print(Jupiter.size)
print(Jupiter.colour)
class MyCustomException(Exception):
def __init__(self, value):
self.value = value
try:
raise (MyCustomException(10))
except MyCustomException as error:
print('A New Exception occurred:', error.value) | true |
3fc8ee0756d2a19b62635047d0d24e0a6f662049 | Aetrix27/CS-1.0-Custom-Calculator | /app.py | 1,205 | 4.6875 | 5 | import math
def calculate_quadratic(coeff_1, coeff_2, coeff_3):
#The formula to calculate the quadratic equation for the positive result given by the square
#root is found below, the inputted into the appropriate variable.
positive_root=(-coeff_2+math.sqrt((coeff_2**2)-(4*(coeff_1*coeff_3))))/(2*coeff_1)
#The formula to calculate the negative root of the quadratic is used to find the second input variable.
negative_root=(-coeff_2-math.sqrt((coeff_2**2)-(4*(coeff_1*coeff_3))))/(2*coeff_1)
return f"The positive root is {positive_root} and the negative root is {negative_root}"
#User is prompted to enter three coefficients that will be used in calculating the roots, using
#the quadratic equation.
print("INPUT OF 3 NUMBER (trinomial) MUST NOT PRODUCE MAKE NEG SQUARE ROOT OR 0 DENOMINATOR")
print("EXAMPLES OF VALID TRINOMIALS TO USE: 2, -9, and 10; 9, 12, and 4; and 2, 7, and -4")
coefficient_1=int(input("Enter the first coefficient. "))
coefficient_2=int(input("Enter the second coefficient. "))
coefficient_3=int(input("Enter the third coefficient. "))
#Calls the function to calculate the roots.
print(calculate_quadratic(coefficient_1,coefficient_2,coefficient_3))
| true |
644b6ce2a21fb0e390fedb77aef04f12c77cf603 | Ben-Lapuhapo/ICS3U-Unit-4-02-Python | /multiplying.py | 878 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Ben Lapuhapo
# Created on: October 2019
# This program shows the factorial of a number
def main():
while True:
# input
sub_answer = 1
total_number = 1
number = input("Input A Positive (+) Number: ")
print()
try:
number_as_number = int(number)
while number_as_number > sub_answer:
# process
print("x {0}".format(sub_answer))
sub_answer = sub_answer + 1
total_number = sub_answer * total_number
print("x {0}".format(number_as_number))
print("The answer is {0}".format(total_number))
except ValueError:
print()
print("Invalid Input")
print()
continue
else:
break
if __name__ == "__main__":
main()
| true |
e1db5c5c64dc952b7f9fc40374ab220159b8f67a | X-R4Y-1/me | /week3/exercise3.py | 1,323 | 4.28125 | 4 | """Week 3, Exercise 3.
Steps on the way to making your own guessing game.
"""
import random
def get_number(message):
while True:
try:
answer = input(message)
answer = int(answer)
return answer
except ValueError:
pass
def advancedGuessingGame():
print("\nWelcome to the guessing game!")
print("A number between _ and _ ?")
lowerBound = input("Enter an lower bound: ")
print("OK then, a lower number is {}".format(lowerBound))
lowerBound = int(lowerBound)
upperBound = input("Enter an upper bound: ")
print("OK then, a number between {} and {} ?".format(lowerBound,upperBound))
upperBound = int(upperBound)
actualNumber = random.randint(lowerBound, upperBound)
guessed = False
while not guessed:
guessedNumber = int(input("Guess a number: "))
print("You guessed {},".format(guessedNumber),)
if guessedNumber == actualNumber:
print("You got it!! It was {}".format(actualNumber))
guessed = True
elif guessedNumber < actualNumber:
print("Too small ur bad, try again :'(")
else:
print("Nope too big ;) Too big, try again :'(")
return "You got it!"
if __name__ == "__main__":
print(advancedGuessingGame())
| true |
a0839d4e963ddf8b987366f7498c3f09f56df718 | lewispark345/p3w | /p3w_01.2b.2.py | 878 | 4.125 | 4 | # A program to perform the following mathematical operations in Python
"""a. Addition"""
"""b. Subtraction"""
"""c. Multiplication"""
"""d. Division"""
print ("# A program to perform the following mathematical operations in Python")
print ("a. Addition")
print ("b. Subtraction")
print ("c. Multiplication")
print ("d. Division")
print ("Enter two numbers: ")
number1 = (int(input("\n")))
print ("number1 is: ", number1)
number2=(int(input("")))
print ("number 2 is: ", number2)
# Addition
print ("a. Addition")
print ("number1 + number2 = ", number1 + number2)
# Subtraction
print ("b. Subtraction")
print ("number1 - number2 = ", number1 - number2)
# Multiplication
print ("c. Multiplication")
print ("number1 * number2 = ", number1 * number2)
# Division
print ("d. Division")
print ("number1 / number2 = ", number1 / number2)
| true |
520720ba773d6bf68bea065eefe96ce412d6ea6b | rahultc26/python | /stringtypes.py | 661 | 4.15625 | 4 |
s0="awesome "
print(s0)
s="my name is rahul " #using string
print(s)
s1="""you are awesome because
your learning python..
all the best""" #you can take single or double quotes instead
print(s1)
s2='i am learning python' #using single quotes
print(s2)
#indexing in strings
print(s[0]) #output : m
print(s1[16]) #output : b
#repetition in strings
print(s*2) #output : my name is rahul my nameis rahul
print(s0*3) #awesome awesome awesome
#finding length of the string
print(len(s0)) #len is inbuilt function in python so it prints length of the s0 string
print(len(s1)) #output : 62 | true |
4391d982f51ae1f6638c866b87c6f6751b72fdd1 | AshuHK/Sorting_Visualization | /text_based_sorts/SelectionSort.py | 522 | 4.125 | 4 | from Swap import _swap
def selection_sort(unsorted):
"""
Does an selection sort on a Python list
Expected Complexity: O(n^2) (time) and O(1) (space)
:param unsorted: unsorted Python list to be sorted
"""
for i in range(len(unsorted)):
# look at each of the remaining values and locate the max value
min_index = i
for j in range(i + 1, len(unsorted)):
if unsorted[min_index] > unsorted[j]:
min_index = j
_swap(unsorted, i, min_index)
| true |
c11eb267e93ff7f97343c593468f6b346289c137 | AshuHK/Sorting_Visualization | /text_based_sorts/Swap.py | 541 | 4.25 | 4 | def _swap(test_list, x, y):
"""
Conducts a Pythonic swap within a list between two indicies
- Note: the order of x and y do not matter as long as both are in an
acceptable range [0, len(test_list)]
Expected Complexity: O(1) (time and space)
:param some_list: Python list of integers where the swap will be done
:param x: integer of the first index to be swapped with
:param y: integer of the second index to be swapped with
"""
test_list[x], test_list[y] = test_list[y], test_list[x]
| true |
28a416eb85a23c3ed0cb0e6a2fe207797f8f9f0b | 92FelipeSantos/CursoEmVideoPython | /CursoEmVideoExercicios/ex005.py | 205 | 4.1875 | 4 | # Digite um número e mostre seu antecessor e seu sucessor
n = int(input('Digite um número: '))
print('O número digitado foi: {}. Seu antecessor é {} e seu sucessor é {}.'.format(n, (n - 1), (n + 1))) | false |
6e29a0b4eb5805051dafdaf5c6dba6501489c298 | FE1979/Dragon | /Python_4/is_sorted.py | 1,086 | 4.1875 | 4 | """
check recursively if list is sorted
"""
def is_sorted(list):
sorted = True
items = len(list)
medium = len(list) // 2
left_list = list[:medium]
right_list = list[medium:]
if items > 4: #end script when left and right lists have 1 or 2 items
if left_list[0] <= left_list[-1] <= right_list[0] <= right_list[-1]: #check
sorted = is_sorted(left_list) and is_sorted(right_list) #true if both are sorted
else:
sorted = False # if not - return False
return sorted
else: #end of script - final check
if left_list[0] <= left_list[-1] <= right_list[0] <= right_list[-1]:
sorted = True
else:
sorted = False
return sorted
return sorted
list_sorted = [i for i in range(10)]
list_unsorted = list_sorted[:]
list_unsorted[3], list_unsorted[7] = list_unsorted[7], list_unsorted[3]
print('Is this list\n{} sorted? - {}\n'.format(list_sorted, is_sorted(list_sorted)))
print('But is this list\n{}\nsorted?\n{}'.format(list_unsorted, is_sorted(list_unsorted)))
| true |
4c236ab912c9fac7847b567d0366657d02ed6d13 | FE1979/Dragon | /Python_3/fibo_recurs.py | 314 | 4.125 | 4 | fibo_top = int(input('Type top of Fibonacci list>'))
list = [0,1]
def fibonacci(list, top):
if list[-1] < top:
list.append(list[-1] + list[-2])
list = fibonacci(list, top)
if list[-1] > top:
list.pop()
return list
print('Fibonacci list\n{}'.format(fibonacci(list,fibo_top)))
| false |
b636c8a39b3c5ef41011fea7f2290cd8f64daf1e | FE1979/Dragon | /Python_3/median.py | 243 | 4.15625 | 4 | first_list_len = int(input('Type a lenght of the first list\n'))
second_list_len = int(input('Type a lenght of the second list\n'))
median = (first_list_len + second_list_len)/2
print('A median of the two merged lists is {}'.format(median))
| true |
76c2e3674764893d0b35594fd0a52d69473e82f0 | Aaronphilip2003/GUI_Tkinter | /18)Databases.py | 2,562 | 4.125 | 4 | from tkinter import *
import sqlite3
root=Tk()
#Create a table
'''
c.execute("""CREATE TABLE addresses(
first_name text,
last_name text,
addresses text,
city text,
state text,
zipcode integer
)""")
'''
f_name=Entry(root,width=30)
f_name.grid(row=0,column=1)
l_name=Entry(root,width=30)
l_name.grid(row=1,column=1)
address=Entry(root,width=30)
address.grid(row=2,column=1)
city=Entry(root,width=30)
city.grid(row=3,column=1)
state=Entry(root,width=30)
state.grid(row=4,column=1)
zipcode=Entry(root,width=30)
zipcode.grid(row=5,column=1)
f_name_label=Label(root,text="First Name")
f_name_label.grid(row=0,column=0)
l_name_label=Label(root,text="Last Name")
l_name_label.grid(row=1,column=0)
address_label=Label(root,text="Address")
address_label.grid(row=2,column=0)
city_label=Label(root,text="City Name")
city_label.grid(row=3,column=0)
state_label=Label(root,text="State Name")
state_label.grid(row=4,column=0)
zipcode_label=Label(root,text="Zipcode")
zipcode_label.grid(row=5,column=0)
def submit():
f_name.delete(0,END)
l_name.delete(0, END)
address.delete(0, END)
city.delete(0, END)
state.delete(0, END)
zipcode.delete(0, END)
# Create/Open a database
conn = sqlite3.connect("address.db")
# Create a Cursor
c = conn.cursor()
#Insert into the table
c.execute("INSERT INTO addresses VALUES (:f_name,:l_name,:address,:city,:state,:zipcode)",
{
'f_name':f_name.get(),
'l_name': l_name.get(),
'address': address.get(),
'city': city.get(),
'state': state.get(),
'zipcode': zipcode.get()
}
)
# Commit Changes
conn.commit()
# Close the Connection
conn.close()
def query():
# Create/Open a database
conn = sqlite3.connect("address.db")
# Create a Cursor
c = conn.cursor()
#Query Database
c.execute("SELECT *, oid FROM addresses")
records=c.fetchall()
print(records)
# Commit Changes
conn.commit()
# Close the Connection
conn.close()
#Create a Submit Button
submit_button=Button(root,text="Add Record to Database",command=submit)
submit_button.grid(row=6,column=0,columnspan=2,padx=10,pady=10,ipadx=137)
#Create a Query Button
query_button=Button(root,text="Show Records",command=query)
query_button.grid(row=7,column=0,columnspan=2,padx=10,pady=10,ipadx=10)
root.mainloop() | false |
d302c81aee46e0abaa5a7e075fef44fb44405410 | Onimanta/pythonHardway | /ex39_drill.py | 486 | 4.21875 | 4 | # -*- coding: utf-8 -*-
cantons = {
'NE': 'Neuchâtel',
'VD': 'Vaud',
'FR': 'Fribourg',
'BE': 'Berne',
'GE': 'Genève'
}
cities = {
'Chaux-de-fonds': 'NE',
'Lausanne': 'VD',
'Bulle': 'FR',
'Bienne': 'BE',
'Meyrin': 'GE'
}
print "The abbreviation of all of the canton: ", cantons.keys()
print "Is Nyon in the cities?"
if 'Nyon' in cities:
print "Yes"
else:
print "No"
print "Ok, so let's put it in."
cities['Nyon'] = 'VD'
print cities | false |
3ec3b48304331486cac681892a9cfdd0974ae0fd | njones777/school_programs | /X&Y.py | 2,533 | 4.25 | 4 | ######################################################################################################################
# Name: Noah Jones
# Date: 9/13/2021
# Description: program to do simple X & Y coordinate calculations such as midpoint and distance between two points
######################################################################################################################
#importing math library for program calculations
import math
# the 2D point class
class Point:
#class constructor with default values set at 0
def __init__(self, x=0, y=0):
self.x = float(x)
self.y = float(y)
#acessor
@property
def x(self):
return self._x
#mutator
@x.setter
def x(self, value):
self._x = value
#acessor
@property
def y(self):
return self._y
#mutator
@y.setter
def y(self, value):
self._y = value
#class method to calculate midpoint
def midpt(set1, set2):
#get necessary point data for calculations
x1, x2 = set1.x, set2.x
y1, y2 = set1.y, set2.y
#algorithm for the midpoint coordinates
midpointX, midpointY = (((x1 + x2) / 2), ((y1 + y2) / 2))
#creating new Point object to in order for new object to use further distance method
new_obj = Point(midpointX, midpointY)
return new_obj
#class method to calculate distance between two points
def dist(set1, set2):
#get necessary point data for calculations
x1, x2 = set1.x, set2.x
y1, y2 = set1.y, set2.y
#algorithm for distance between two points
partx = ((x2-x1)**2)
party = ((y2-y1)**2)
to_be_squared = partx + party
distance = math.sqrt(to_be_squared)
return distance
#magic function to dictate how the object will be printed out
def __str__(self):
return(" ({},{})".format(self.x, self.y))
##########################################################
# ***DO NOT MODIFY OR REMOVE ANYTHING BELOW THIS POINT!***
# create some points
p1 = Point()
p2 = Point(3, 0)
p3 = Point(3, 4)
# display them
print("p1:", p1)
print("p2:", p2)
print("p3:", p3)
# calculate and display some distances
print("distance from p1 to p2:", p1.dist(p2))
print("distance from p2 to p3:", p2.dist(p3))
print("distance from p1 to p3:", p1.dist(p3))
# calculate and display some midpoints
print("midpt of p1 and p2:", p1.midpt(p2))
print("midpt of p2 and p3:", p2.midpt(p3))
print("midpt of p1 and p3:", p1.midpt(p3))
# just a few more things...
p4 = p1.midpt(p3)
print("p4:", p4)
print("distance from p4 to p1:", p4.dist(p1))
| true |
c74b685438df1dbae6fadbe9b39846944921b81a | kstack4074/daily_coding | /#9.py | 1,212 | 4.28125 | 4 | '''
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5.
[5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?
[1, 2, 3, 4] OR [1, 2, 3, 4]
^ ^ ^ ^
For odd lengths:
[1, 2, 3, 4, 5] OR [1, 2, 3, 4, 5]
^ ^ ^ ^ ^
You'll always want to grab the maxium number of elements,
it just depends where you start to hit the max val.
Define two values, the sum starting from 0,
and the sum starting from 1.
Wrong, in [5, 1, 1, 5] example we take the two bound values.
incl = 5, excl = 0
incl = 1, excl = 5
incl = 6, excl = 5
incl = 10, excl = 6
'''
def largest_sum(array):
incl = 0
excl = 0
new_excl = 0
for value in array:
print(incl, excl)
if excl > incl:
new_excl = excl
else:
new_excl = incl
incl = excl + value
excl = new_excl
return (excl if excl > incl else incl)
test1 = [2, 4, 6, 2, 5] #13
test2 = [5, 1, 1, 5] #10
test3 = [5, 5, 10, 100, 10, 5] #110
largest_sum(test2)
| true |
f872c22c73d77b2750d02092aaa396e97e38284b | KyLarson-Research/100Days-21 | /day2.py | 439 | 4.1875 | 4 | #Authored by Kyle Larson 9-30
print('Welcome to the tip calculator.')
bill =input("What was the total bill?")
people = input("How many people to split the bill?")
percentage = input("WHat percentatge tip would you like to give?")
if int(percentage) < 0 or int(percentage) > 100:
print("invalid percentage")
else:
pay = ( float(bill)*(1+int(percentage)/100) )/int(people)
print("Each person should pay: ", round(pay,2) )
| true |
eca17996335c4fa8b1c2de5cc93e7ec170efcc9e | BenRauzi/159.171 | /Workshop 3/13.py | 255 | 4.15625 | 4 | words = []
while True:
word = input("Enter a word: ")
if word.lower() == "end": #.lower() allows any casing from the input, prevents errors in real world scenarios
break
words.append(word)
print("The resulting list is " + str(words)) | true |
53793985ba1d3bca5dd13c74ae15c1867145fc7d | LuisCastellanosOviedo/python3 | /my-python-project/datetime/time-till-deadline.py | 609 | 4.21875 | 4 | from _datetime import datetime
user_input =input("enter your goal with a deadline separated by colon \n")
input_list = user_input.split(":")
goal = input_list[0]
deadline = input_list[1]
print(input_list)
deadline_date = datetime.strptime(deadline, "%d.%m.%Y")
today_date = datetime.today()
print(deadline_date)
print(type(deadline_date))
print(today_date)
# calculate how many days form now till the deadline
print(f"The time left to get the goal es {(deadline_date - today_date).days} days.")
print(f"The time left to get the goal es {int((deadline_date - today_date).total_seconds())} hours.")
| true |
ad1f15c1dd06cf6db543de987c669e5b84a9ae8d | LuisCastellanosOviedo/python3 | /my-python-project/day9_dictionaries_and_nesting/main.py | 505 | 4.15625 | 4 | first_dic = {
"bug": "is a error",
"Function": "A piece of code",
"Loop": "some repetitive",
}
# retrieve all elements from the dic
print(first_dic)
print(f"bug values: {first_dic['bug']}")
# Adding new elements to dictionary
first_dic["Error"] = "A problem in the code"
print(first_dic)
# Create and empty dic
empty_dic = {}
# edit element
first_dic["bug"] = "New value edited !!!!!!"
print(first_dic)
# Loop through a dic
for key in first_dic:
print(key)
print(first_dic[key])
| true |
1568cb71199c1ce51eee28205d95429df363a4c9 | nishalpattan/DataStructures-Algorithms | /Arrays/twoSum.py | 1,021 | 4.3125 | 4 | def twoNumberSum(array, targetSum):
"""
Time Complexity : O(n)
Space Complexity : O(n)
:param array:
:param targetSum:
:return:[number1, number2]
"""
hash_map = dict()
for num in array:
if num in hash_map:
return [num, targetSum - num]
hash_map[targetSum - num] = num
return []
def twoNumberSumSortedArray(array, targetSum):
"""
Time Complexity : O(n)
Space Complexity : O(1)
:param array:
:param targetSum:
:return: [index1, index2]
Use two pointer method to traverse in a sorted array(non-decreasing),
if the sum of numbers at start and end index equals target sum, return those indexes
else if the sum is less than target sum, increment start index , following the increasing order of sorted array
else if the sum is greater than target sum, decrement end index.
"""
start = 0
end = len(array)-1
while start <= end:
curr_sum = array[start]
if curr_sum == targetSum:
return[]
if __name__ == "__main__":
print(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)) | true |
3f4ed5b3ea1a1c83fa58784590f92c1ca0b983d9 | vuthanhdatt/MIT_6.0001 | /ps1/ps1b.py | 681 | 4.25 | 4 | annual_salary = int(input('Enter your annual salary:'))
portion_saved = float(input('Enter the percent of your salary to save:'))
total_cost = int(input('Enter the cost of your house:'))
semi_annual_raise = float(input('Enter the semiannual raise, as a decimal:'))
portion_down_payment = .25
current_savings = 0
r = .04
time = 0
cost = total_cost*portion_down_payment
salary = annual_salary/12
savings = salary*portion_saved
r_month = r/12
while current_savings < cost:
current_savings += savings + current_savings*r_month
time +=1
if time%6 == 0:
salary += salary*semi_annual_raise
savings = salary*portion_saved
print(f'Number of months: {time}') | true |
8375c9db42e10ee289459c316ea6f4e33a0756a1 | gocersensei/Recursion | /totalTheValues.py | 963 | 4.25 | 4 | ##
# Total a collection of numbers entered by the user. The user will enter a blank line to
# indicate that no further numbers will be entered and the total should be displayed.
#
## Total all of the numbers entered by the user until the user enters a blank line
# @return the total of the entered values
def readAndTotal():
# Read a value from the user
line = input("Enter a number (blank to quit): ")
# Base case: The user entered a blank line so the total is 0
if line == "":
return 0
else:
# Recursive case: Convert the current line to a number and use recursion to read the
# subsequent lines
return float(line) + readAndTotal()
# Read a collection of numbers from the user and display the total
def main():
# Read the values from the user and compute the total
total = readAndTotal()
# Display the total
print("The total of all those values is", total)
# Call the main function
main()
| true |
0a95d47a6764e6390bc7a0463ca0113d1673b2d0 | nonamejx/python-design-patterns | /src/factory_method/factory_method.py | 1,304 | 4.53125 | 5 | """
Factory Method Design Pattern.
Intent: Provide an interface for creating an object, but let subclasses decide which class to instantiate.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
class Transport(ABC):
@abstractmethod
def deliver(self) -> str:
pass
class Truck(Transport):
def deliver(self) -> str:
return "Deliver by a Truck"
class Ship(Transport):
def deliver(self) -> str:
return "Deliver by a Ship"
class Logistics(ABC):
"""
The Creator class declares the factory method that is supposed to return an
object of a `Product` class. The Creator's subclasses usually provide the
implementation of this method.
"""
@abstractmethod
def create_transport(self):
pass
def plan_delivery(self) -> None:
transport = self.create_transport()
print(f'Create a {transport.__class__.__name__}')
print(transport.deliver())
class RoadLogistics(Logistics):
def create_transport(self) -> Truck:
return Truck()
class SeaLogistics(Logistics):
def create_transport(self) -> Ship:
return Ship()
def app(creator: Logistics) -> None:
"""Client code"""
creator.plan_delivery()
if __name__ == '__main__':
app(RoadLogistics())
| true |
26f9d146a24929bbf5f4469260754a3c8d377dfe | leilongquan/selfteaching-python-camp | /exercises/1901100231/1001S02E03_calculator.py | 864 | 4.3125 | 4 | #告知这是个计算机小程序
print("""请键入要进行运算的两个数字
并按:
“+”代表加
“-”代表减
“*”代表乘
“/”代表除
“%”代表求余数
“**”代表求次方
的如上所示的规则键入你要进行的运算
本程序只可运行一次,重复计算请重复使用
请切换至英文输入模式进行数字和运算的键入""")
#获取要算的数和运算
x = input()
y = input()
z = input()
#计算器程序
if z == "+":
print(x,"+",y,"=",int(x)+int(y))#加法
elif z== "-":
print(x,"-",y,"=",int(x)-int(y))#减法
elif z== "*":
print(x,"*",y,"=",int(x)*int(y))#乘法
elif z== "/":
print(x,"/",y,"=",int(x)/int(y))#除法
elif z== "%":
print(x,"除以",y,"的余数是",int(x)%int(y))#余数
elif z== "**":
print(x,"的",y,"次方是",int(x)**int(y))#次方
| false |
960bd9b4ab615c14b92f2b0f82f77118e1d3d668 | EmAchieng/myPy | /employees.py | 716 | 4.375 | 4 | #creating an instanciated simple classes
#classes allow us to logically group our data and functions making it easy to reuse
class Employee:
#means you just want to skip it
pass
#each of these will be their own unique instances of the employee class
emp_1 = Employee()
emp_2 = Employee()
#both of these are unique objects that occupy some kind of memory
print(emp_1)
print(emp_2)
#instance variables contains data that is unique to each instance
#we can go ahead and create instance variables
emp_1.first = 'Mary'
emp_2.last = 'John'
emp_1.email = 'marya@gmail.com'
emp_1.pay = 50000
emp_2.first = 'Test'
emp_2.last = 'User'
emp_2.email = 'Test@gmail.com'
emp_2.pay = 60000
print(emp_1.email)
print(emp_2.email) | true |
60bd4f6ad8853b44a62604f8ca56e798af1229c4 | saikiranPadala/basic-projects | /basic projects/calculator.py | 818 | 4.21875 | 4 | # simple calculator
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
def power(x,y):
return pow(x,y)
print("select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Power")
choice = input("enter choice(1/2/3/4/5):")
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
if choice == '1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "x", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
elif choice == '5':
print(num1, "^", num2, "=", power(num1, num2))
else :
print("Invalid Input")
| false |
45242b779548b11bdedea095e68ca9f97db33075 | bcbc-group/PLSCi7202_2021 | /first_python.py | 1,660 | 4.53125 | 5 | #!/usr/local/bin/python3
#testing out python
print("Python is fun!")
#using variables
message = "Python is fun!"
print(message)
#using the title method
name = "suzy strickler"
print(name.title())
#using variables in strings
first_name = "suzy"
last_name = "strickler"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"My name is, {full_name.title()}!")
#Manipulating Lists
states = ['New York', 'Pennsylvania', 'Hawaii']
print(states)
print(states[0]) #access an element in a list
states[0] = 'Texas' #change a list element
print(states)
states.insert(0, 'Montana') #insert an element
print(states)
popped_states = states.pop(1) #remove an element
print(popped_states)
print(states)
#Loops
states = ['New York', 'Pennsylvania', 'Hawaii']
for state in states:
print(state)
print("All states in list printed")
#Loops - if statements
states = ['New York', 'Pennsylvania', 'Hawaii']
for state in states:
if state == 'Hawaii':
print(state.upper())
elif state == 'Montana':
print(state.lower())
else: print(state.title())
#Dictionaries
plants = {'color': 'blue', 'height': 10}
print(plants['color'])
plants['sepal'] = 3 #add a new key-value pair
print(plants)
del plants['color'] #remove a key-value pair
print(plants)
#example of a function
def weather():
"""Find out the weather"""
answer = input("How is the weather?")
print(answer)
weather()
#reading in a file
fasta_file = open("/home/bioinfo/Data/sample1.fasta", "r")
if fasta_file.mode == "r":
contents = fasta_file.read()
outF = open("/home/bioinfo/Data/test_out.fasta", "w")
outF.write(contents)
fasta_file.close()
outF.close()
| true |
f70ecd164dd2177c16d34a2dd2c671a8a73d4169 | sakshambhardwaj523/Python-OOP-Projects | /Assignments/Assignment 3/menu.py | 1,649 | 4.15625 | 4 | """
Stores Menu items for Pizza shop UI.
"""
import pizza
class Menu:
"""
Stores items for menu creation.
"""
start_menu = {
1: "Build your own pizza",
2: "Quit"
}
cheese_menu = {
1: pizza.Ingredient("Parmigiano Reggiano", 4.99),
2: pizza.Ingredient("Fresh Mozzarella", 3.99),
3: pizza.Ingredient("Vegan Cheese", 5.99),
4: "Add other toppings",
5: "Check out",
6: "Quit"
}
cheese_dec = {
1: pizza.ParmigianoPizzaDecorator,
2: pizza.MozzarellaPizzaDecorator,
3: pizza.VeganPizzaDecorator
}
toppings_menu = {
1: pizza.Ingredient("Peppers", 1.5),
2: pizza.Ingredient("Pineapple", 2),
3: pizza.Ingredient("Mushrooms", 1.5),
4: pizza.Ingredient("Fresh Basil", 2),
5: pizza.Ingredient("Spinach", 1),
6: pizza.Ingredient("Pepperoni", 3),
7: pizza.Ingredient("Beyond Meat", 4),
8: "Add more cheese",
9: "Check out",
10: "Quit"
}
toppings_dec = {
1: pizza.PepperPizzaDecorator,
2: pizza.PineapplePizzaDecorator,
3: pizza.MushroomPizzaDecorator,
4: pizza.BasilPizzaDecorator,
5: pizza.SpinachPizzaDecorator,
6: pizza.PepperoniPizzaDecorator,
7: pizza.BeyondPizzaDecorator
}
@staticmethod
def print(menu):
"""
Prints menu items in a nicely formatted manner.
:param menu: Menu dictionary
:return: None
"""
output = "\n"
for num, item in menu.items():
output += f"{num}. {item}\n"
print(output) | true |
4ee97294e3144d500b4045fcff47fa91599d864a | sakshambhardwaj523/Python-OOP-Projects | /Labs/Lab 2/item.py | 2,079 | 4.15625 | 4 | import abc
class Item(abc.ABC):
"""
Represents an Item that is stored in a Catalogue at the Library.
Any class that inherits from this class MUST implement all the
@abstractmethods and @abstractclassmethods.
"""
def __init__(self, title, call_no, author, num_copies):
"""
Initialises Item object.
:param title: as String
:param call_no: as string
:param author: as String
:param num_copies: as int
"""
self._title = title
self._call_no = call_no
self._author = author
self._num_copies = num_copies
def get_title(self):
"""
Return title of Item.
:return: as String
"""
return self._title
def get_copies(self):
"""
Return number of copies available.
:return: as int
"""
return self._num_copies
def set_copies(self, num_copies):
"""
Set number of copies available.
:param num_copies: as int
"""
self._num_copies = num_copies
def get_call_no(self):
"""
Get the call number of Item.
:return: as String
"""
return self._call_no
def check_availability(self):
"""
Return true if there is at least 1 copy.
:return: as boolean
"""
return self._num_copies > 0
@abc.abstractmethod
def __repr__(self):
"""
Format for representing Item object.
:return: as String
"""
return f"Title: {self._title}\n" \
f"Call Number: {self._call_no}\n" \
f"Author: {self._author}\n" \
f"Copies Available: {self._num_copies}\n"
@abc.abstractmethod
def __str__(self):
"""
Format for representing Book object.
:return: as String
"""
return f"Title: {self._title}\n" \
f"Call Number: {self._call_no}\n" \
f"Author: {self._author}\n" \
f"Copies Available: {self._num_copies}\n\n"
| true |
282885f934c239d86252c9f4503fa4174476dbe1 | sakshambhardwaj523/Python-OOP-Projects | /Labs/Lab 0/calculator.py | 1,565 | 4.15625 | 4 | """Demonstrates basics of Python functions."""
def sum(a, b):
"""
Return sum of two ints.
:param a: int
:param b: int
:return: sum as an int
"""
return a + b
def subtract(a, b):
"""
Return difference of two ints.
:param a: int
:param b: int
:return: difference as an int
"""
return a - b
def multiply(a, b):
"""
Return product of two ints.
:param a: int
:param b: int
:return: product as an int
"""
return a * b
def divide(a, b):
"""
Return quotient of two ints.
:param a: dividend as int
:param b: divisor as int
:return: quotient as an int
"""
return a / b
def main():
"""
Print the calculator result based on user input.
:return: sum, product, quotient, and difference of 10 and 5
"""
print("Select from menu:")
print("1. Add")
print("2. Minus")
print("3. Multiple")
print("4. Divide")
choice = int(input("Enter your choice: "))
a = int(input("Enter first value: "))
b = int(input("Enter second value: "))
input_dict = {1: sum(a, b), 2: subtract(a, b), 3: multiply(a, b), 4: divide(a, b)}
answer_dict = {1: "sum", 2: "difference", 3: "product", 4:"quotient"}
print("The {0} of {1} and {2} is {3}.".format(answer_dict.get(choice),
a,
b,
input_dict.get(choice, "Invalid input. Select from menu.")))
if __name__ == "__main__":
main() | true |
e27c41f9b5045a9f45375f2c41d460a13d52a8de | mosest/11th-Python | /8 - Snowflake Fractal.py | 1,054 | 4.21875 | 4 | #Tara Moses
#Assignment 8: Snowflake Fractal
#February 4, 2013
#1. Program draws a snowflake fractal depending on the user-specified fractal order.
#2. Program fills the snowflake with a certain user-specified color.
import turtle,Tkinter
order=int(raw_input("What order fractal would you like? "))
snowflake_color=raw_input("What color would you like it to be? ")
screen_width=turtle.window_width()-50.0
screen_height=turtle.window_height()-50.0
top_corner_x=-1*(screen_width/2.0)
top_corner_y=screen_height/2.0
directions="srsrs"
length=300.0
turtle.speed(0)
if order>4:
turtle.tracer(3)
turtle.dot()
turtle.up()
turtle.goto(-150, 90)
turtle.down()
turtle.fillcolor(snowflake_color)
turtle.fill(True)
for i in range(order):
if order==0:
break
directions=directions.replace("s"," slsrsls ")
length=length/3.0
for letter in directions:
if letter=="s":
turtle.forward(length)
elif letter=="r":
turtle.right(120.0)
elif letter=="l":
turtle.left(60.0)
turtle.fill(False)
turtle.mainloop()
| true |
99d5c42af89537c281fd365e644f76dc3938df39 | mosest/11th-Python | /20 - TicTacToe 1.py | 1,720 | 4.21875 | 4 | #Tara Moses
#Assignment 20: TicTacToe 1
#April 29, 2013
import random
class Board:
def __init__(self):
self.nums=[[0,1,2],[3,4,5],[6,7,8]]
def canPlace(self,pos):
numbers=[0,1,2,3,4,5,6,7,8]
row=pos/3
col=pos%3
spot=self.nums[row][col]
if spot in numbers:
return True
else:
return False
def place(self,pos,token):
row=pos/3
col=pos%3
self.nums[row][col]=token
return
def __str__(self):
output=""
output+=" | | \n"
output+=" "+str(self.nums[0][0])+" | "+str(self.nums[0][1])+" | "+str(self.nums[0][2])+" \n"
output+=" | | \n"
output+="---+---+---\n"
output+=" | | \n"
output+=" "+str(self.nums[1][0])+" | "+str(self.nums[1][1])+" | "+str(self.nums[1][2])+" \n"
output+=" | | \n"
output+="---+---+---\n"
output+=" | | \n"
output+=" "+str(self.nums[2][0])+" | "+str(self.nums[2][1])+" | "+str(self.nums[2][2])+" \n"
output+=" | | \n"
return output
#start actual program now
board=Board()
random_nums=[]
print board
for i in range(50):
x=random.randint(0,8)
random_nums.append(x)
for i in random_nums:
if board.canPlace(i):
print "now placing token at",i
board.place(i,"@")
print board
else:
print "Cannot place token at",i
| false |
1d4b314ca1f36c9e4b84125bbff659cd4fb014ff | mosest/11th-Python | /6.4 - Divisible by 1 to 16.py | 1,895 | 4.15625 | 4 | #Tara Moses
#Assignment 6.4: First Number Divisible by 1, 2, ..., 16
#January 29, 2013
#1. Program tests whether a number is divisible by all numbers 1-16.
#2. Program outputs first number that satisfies conditions.
print("I'll print the first number that is divisible by every number")
print("from 1 to 16.")
num_to_find=700000.0
count=1
while True:
if (num_to_find%16==0):
if (num_to_find%15==0):
if (num_to_find%14==0):
if (num_to_find%13==0):
if (num_to_find%12==0):
if (num_to_find%11==0):
if (num_to_find%10==0):
if (num_to_find%9==0):
print(str(num_to_find)+" is the smallest number divisible by 1-16. Yay!")
break
else:
print("Nope! It stopped at 9.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 10.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 11.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 12.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 13.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 14.")
num_to_find=num_to_find+1.0
else:
print("Nope! It stopped at 15.")
num_to_find=num_to_find+1.0
else:
print("Well, it's not "+str(num_to_find)+"!")
num_to_find=num_to_find+1.0
| true |
0ed7acd5c63b9fce0245800345bcf6dfc292cd67 | rabbit-jump/LPYHW | /exercise/e03.py | 783 | 4.4375 | 4 | #coding=utf-8
print("I will now count my chickens:")
print ("Hens",25+30/6)#计算表达式的值,并输出。除法运算 (/) 永远返回浮点数类型。如果要做 floor division 得到一个整数结果(忽略小数部分)你可以使用 // 运算符
print("25+30/6的整数结果:",25+30//6)
print ("Roosters",100-25*3%4)
print("Now I will count the eggs:")
print(3+2+1-5+4%2-1/4+6)
print("Is it true that 3+2<5-7?")
print(3+2<5-7)#比较表达式计算后的结果,并输出true或false
print("What is 3+2?",3+2)
print("What is 5-7?",5-7)
print("Oh,that's why it 's False.")
print("How about some more.")
print("Is it greater?",5>-2)#计算布尔表达式的结果,并输出true或false
print("Is it greater or equal?",5>=-2)
print("Is it less or equal?",5<=-2)
| false |
9d0423cc0ba16147283f43a697a7a9d417467e9f | andprogrammer/crackingTheCodingInterview | /python/chapter3/3/solution.py | 1,982 | 4.125 | 4 | class Stack(object):
def __init__(self, capacity):
self.capacity = capacity
self.stack = []
self.size = 0
def push(self, elem):
if self.is_full():
raise Exception('Stack is full')
self.size += 1
self.stack.append(elem)
def pop(self):
if self.is_empty():
raise Exception('Stack is empty')
del self.stack[-1]
def top(self):
if self.is_empty():
raise Exception('Stack is empty')
return self.stack[-1]
def is_empty(self):
return not self.size
def is_full(self):
return self.size == self.capacity
def print_stack(self):
for i in reversed(self.stack):
print('[{}]'.format(i))
class StackOfPlates(object):
def __init__(self, max_height):
self.max_height = max_height
self.stacks = []
def push(self, elem):
if self.stacks:
last = self.stacks[-1]
if last.is_full():
self._add_new_stack(elem)
else:
last.push(elem)
else:
self._add_new_stack(elem)
def _add_new_stack(self, elem):
new_stack = Stack(self.max_height)
new_stack.push(elem)
self.stacks.append(new_stack)
def pop(self):
if self.stacks:
last = self.stacks[-1]
last.pop()
def top(self):
if self.stacks:
last = self.stacks[-1]
return last.top()
else:
raise Exception('Stack is empty')
def print_stack(self):
for stack in reversed(self.stacks):
stack.print_stack()
if __name__ == '__main__':
plates = StackOfPlates(3)
plates.push(1)
plates.push(2)
plates.pop()
plates.push(3)
plates.push(4)
plates.pop()
plates.push(5)
print('top=', plates.top())
plates.push(6)
plates.push(7)
print('top=', plates.top())
plates.print_stack() | false |
59b45ba95b8ad280816e2c6c21d151746c23de21 | zhishixiang/python-learning | /012 列表类型的内置函数.py | 604 | 4.1875 | 4 | #count 检查一个数在列表里出现了几次
number = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2]
print(number.count(1))
#index 检索数组中的某个值第一次出现在哪个位置
print(number.index(2))
#限定范围
number2 = [1,1,2,2,1,1,2,2,1,1,2,2,1,1,2,2]
print(number2.index(2,4,8))
#reverse 来过倒组数把
number3 = [1,2,3,4,5,6,7,8,9]
number3.reverse()
print(number3)
#sort 根据指定参数对数组排序,默认从小到大
number4 = [1,6,3,5,3,2,3,5,6,12,431,321,321,21,45,32,65]
number4.sort()
print(number4)
#从大到小排序
number4.sort(reverse=True)
print(number4) | false |
5b4a835de7024a3f8ec9c09b2ead038a303e75e4 | zhishixiang/python-learning | /033 异常处理.py | 1,401 | 4.125 | 4 | #打开一个不存在的文件时会出现FileNotFound的异常
#f = open("我是一个文件.txt")
#print(f.read())
#f.close()
#使用try语句时可以检测抛出的异常
try:
f = open("这是个不存在的文件.txt")
print(f.read)
sum = 1 + '1'
f.close()
#使用except可以决定当某个异常出现时执行什么指令
#except还可以添加一个变量存放错误原因
#变量需要使用str()方法转换为字符
except OSError as error:
print("出现错误!\n错误的原因是"+str(error))
#except可以检测多个错误
#只有第一个出现的语句会触发except
except TypeError:
print("不合法的运算!请重试!")
#当出现的错误不在下方的except时将会抛出异常并终止运行
#只使用except不指定类型时出现任何异常都会触发except
#不推荐上面的做法
#except可以添加多个参数表示捕获多个错误
except(OSError,TypeError):
print("程序出现错误!")
#在上面的例子中,由于sum = 1 + '1'在f.close之上,因此当检测到错误时f.close就不会执行,文件就无法保存。
#finally可以指定当检测到错误时仍然要执行的指令
"""
finally:
f.close()
"""
#raise可以手动引发异常,后面还可以指定一个参数表示异常的名字
#可以指定错误的具体
raise FileNotFoundError('找不到文件 "你妈" ,可能是 你妈 不存在')
| false |
6a3fa81f303c29dbd65df18e20aaf8c89d2921f4 | Edithwml/python | /grammar/内建函数(map、filter、reduce、sorted).py | 2,603 | 4.28125 | 4 | '''
1、range
Python2中range返回列表,Python3中range返回一个迭代值。
如果想要一个列表可以通过list函数
'''
a = range(5)
list(a)
#创建列表的另一种方法
testlist = [x+2 for i in range(5)] #testlist=[2,3,4,5,6]
'''
2、map函数
map函数会根据提供的函数对指定序列做映射
map(...)
map(function, sequence[, sequence, ...]) -> list
function:是一个函数
sequence:是一个或多个序列,取决于function需要一个参数
返回值是一个list
参数序列中的每⼀个元素分别调⽤function函数,返回包含每次function函数
返回值的list
'''
##函数需要一个参数
map(lambda x: x*x, [1, 2, 3])
#结果为:[1, 4, 9]
#函数需要两个参数
map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6])
#结果为:[5, 7, 9]
def f1( x, y ):
return (x,y)
l1 = [ 0, 1, 2, 3, 4, 5, 6 ]
l2 = [ 'Sun', 'M', 'T', 'W', 'T', 'F', 'S' ]
l3 = map( f1, l1, l2 )
print(list(l3))
#结果为:[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5,'S')]
'''
3、filter函数
filter函数会对指定序列执⾏过滤操作
filter(...)
filter(function or None, sequence) -> list, tuple, or string
function:接受一个参数,返回布尔值True或False
sequence:序列可以是str,tuple,list
filter函数会对序列参数sequence中的每个元素调⽤function函数,最后返回
的结果包含调⽤结果为True的元素
'''
filter(lambda x: x%2, [1, 2, 3, 4])
#[1, 3]
filter(None, "she")
#'she'
'''
4、reduce函数
reduce函数,reduce函数会对参数序列中元素进⾏累积
reduce(...)
reduce(function, sequence[, initial]) -> value
function:该函数有两个参数
sequence:序列可以是str,tuple,list
initial:固定初始值
reduce依次从sequence中取一个元素,和上一次调⽤function的结果做参数
再次调⽤function。 第一次调用function时,如果提供initial参数,会以
sequence中的第一个元素和initial 作为参数调⽤function,否则会以序列
sequence中的前两个元素做参数调用function。 注意function函数不能为
None
'''
reduce(lambda x, y: x+y, [1,2,3,4]) #10
reduce(lambda x, y: x+y, [1,2,3,4], 5) #15 5作为x的固定值initial
reduce(lambda x, y: x+y, ['aa', 'bb', 'cc'], 'dd') #'ddaabbcc'
# 在Python3里,reduce函数已经被从全局名字空间中移除了, 它现在被放
# 置在fucntools模块用的话要先引用: from functools import reduce
'''
5、sorted函数
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new iterable
sorted([1,4,2,6,3,5]) #[1,2,3,4,5,6]
sorted([1,4,2,6,3,5],reverse = 1) #[6,5,4,3,2,1]
| false |
7e74ea4cce76fb0be74df39feb492966119031bf | Juan337492/PythonCalculator | /MyCalc.py | 1,131 | 4.28125 | 4 | #Program name: MyCalc
#Lab no: 1
#Description: Input two numbers then select operator
#Your name: Juan Rodriguez
#Date: 06-13-2021
title = "My Calculator"
choice = "y"
while (choice == 'y'):
num1 = int(input("Enter Number 1: "))
num2 = int(input("Enter Number 2: "))
print("Please select operation to be performed:\nadd\nsubtract\nmultiply\ndivide")
operation = input("Your choice: ")
if operation == 'add':
result = num1 + num2
elif operation == 'subtract':
result = num1 - num2
elif operation == 'multiply':
result = num1 * num2
elif operation == 'divide':
result = num1 / num2
else:
print("You didn't enter a valid operator")
print(title)
print("\n")
print("The "+str(operation)+" of "+str(num1)+" and "+str(num2)+" is "+str(result)+", where "+str(operation)+" is the operation entered, "+str(num1)+" and "+str(num2)+" are the numbers entered and "+str(result)+" is the result of the operation")
print("Press 'y' to perform other calculation \n Press 'n' to stop")
choice = input("Your choice: ")
print("Thanks for using the calculator") | true |
889b5fd7a45c3666c29b8eda1efaec1f366fc960 | harperpack/Harper-s-Practice-Repository | /list_practice_4.py | 1,278 | 4.59375 | 5 | # Still practicing with lists, from Python Crash Course
locations = ["japan", "korea", "vietnam", "cambodia", "new zealand"]
print (locations)
print ("\n")
# Adjust each item in the list to be capitalized
for location in locations:
locations.remove(location)
location = location.title()
locations.insert(0, location)
print ("Here is a list of places I would like to go:")
print (locations)
print("\nHere is a list of places I would like to go, sorted alphabetically:")
print (sorted(locations))
print ("\nThe order of the original list has not changed:")
print (locations)
print ("\nHere is a list of places I would like to go, sorted in reverse alphabetical order:")
print (sorted(locations, reverse=True))
print ("\nThe order of the original list still has not changed:")
print (locations)
print ("\nAnd now we have reversed the order of the list:")
locations.reverse()
print (locations)
print ("\nLo! the list has been returned to its original order:")
locations.reverse()
print (locations)
print ("\nLet's sort the list alphabetically - for real this time:")
locations.sort()
print (locations)
print ("\nAnd now we will print the list in reverse alphabetical order:")
locations.sort(reverse=True)
print (locations)
| true |
17308c5c65d56b64070822e1e7ae5e0c1594a5a9 | harperpack/Harper-s-Practice-Repository | /number_work.py | 670 | 4.15625 | 4 | # This is a program built to help me practice representing numbers in Python
# Explore different arithmetic in Python
import time
print(5 + 3)
print(4.0 * 2)
print(2 ** 3)
print(24 / 3)
print(9.0 - 1)
favorite_number = 8.0
print("Can you guess which is my favorite number?")
# Allow the user time to "catch up" with the program output
time.sleep(2)
# Explore arithmetic within a string output
print("\nI'll give you a hint: I've already printed it " + str(favorite_number - 3) + " times!")
time.sleep(2)
print("Time's up! My favorite number is " + str(favorite_number) + "!")
print("Disclaimer: I am not particularly partial to any number.")
| true |
2d489c85552512da120bcdbb1a6b84fdc0a16b15 | malavikasrinivasan/D06 | /HW06_ch09_ex06.py | 1,478 | 4.625 | 5 | #!/usr/bin/env python3
# HW06_ch09_ex05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write additional function(s) to assist you
# - number of abecedarian words:
##############################################################################
# Imports
# Body
def is_abecedarian(word):
""" Returns True if the letters in word appear in alphabetical order
TODO : Handle presence of special characters - Find a way to strip string off of special characters/numbers
"""
word = word.lower() # Converting word to lower case to use ascii values for comparison
word_len = len(word)
if word_len == 1:
return True
for i in range(0, word_len-1):
if ord(word[i]) > ord(word[i+1]): # Checking if the next letter's ASCII
return False
return True
def count_abecedarian():
abecedarian_word_count = 0
with open("words.txt", "r") as f:
file_contents = f.readlines()
for word in file_contents:
if is_abecedarian(word.strip()):
abecedarian_word_count += 1
print("Number of abecedarian words in the file are {}".format(abecedarian_word_count))
##############################################################################
def main():
count_abecedarian()
if __name__ == '__main__':
main()
| true |
cdfffc41e35a60ade6032f9b8522a8751e8e8821 | malavikasrinivasan/D06 | /HW06_ch09_ex02.py | 1,157 | 4.40625 | 4 | #!/usr/bin/env python3
# HW06_ch09_ex02.py
# (1)
# Write a function called has_no_e that returns True if the given word doesn't
# have the letter "e" in it.
# - write has_no_e
# (2)
# Modify your program from 9.1 to print only the words that have no "e" and
# compute the percentage of the words in the list have no "e."
# - print each approved word on new line, followed at the end by the %
# - name your function print_no_e
##############################################################################
# Imports
# Body
def has_no_e(word):
if word.find('e') == -1:
return True
else:
return False
def print_no_e(filename):
with open(filename, "r") as f:
words = f.readlines()
total_words = len(words)
words_without_e = 0
for word in words:
if has_no_e(word.strip()):
print(word.strip())
words_without_e += 1
print("{:.2%} of all the words in the file have no e".format(words_without_e/total_words))
##############################################################################
def main():
print_no_e("words.txt")
if __name__ == '__main__':
main()
| true |
d48b53882f5ef8b7fe23bd28fc407745b284ab7e | ianzapolsky/practice | /euler_problems/4.py | 486 | 4.125 | 4 | # 4.py
# Description: Find the largest palindrome made from the product of two 3-digit
# numbers.
# Author: Ian Zapolsky (10/31/13)
def biggest_p():
biggest_pal = 0
for x in range(100, 1000):
for y in range(100, 1000):
if is_pal(x*y) and (x*y) > biggest_pal:
biggest_pal = (x*y)
y -= 1
x -= 1
return biggest_pal
def is_pal(x):
if str(x) == str(x)[::-1]:
return True
return False
print biggest_p()
| false |
81e3697052ce18a2c72e51ae8c8f06a6b812f8eb | pranavchandran/Automate-with-Python | /stopwatch.py | 1,324 | 4.25 | 4 | # My StopWatch
"""
Track the amount of time elapsed between presses of the ENTER key,
with each key press starting a new “lap” on the timer.
Print the lap number, total time, and lap time.
This means your code will need to do the following:
Find the current time by calling time.time() and store it as a
timestamp at the start of the program, as well as at the start of
each lap.
Keep a lap counter and increment it every time the user presses ENTER.
Calculate the elapsed time by subtracting timestamps.
Handle the KeyboardInterrupt exception so the user can
press CTRL-C to quit.
"""
import time
print('Press Enter to begin.Afterward, press Enter to click the stopwatch.\
Press Cntrl-C to quit')
input()
print('Started')
starttime = time.time()
lasttime = starttime
lapnum = 1
"""Now that we’ve written the code to display the instructions,
start the first lap, note the time, and set our lap count to 1."""
# start tracking lap times
try:
while True:
input()
laptime = round(time.time() - lasttime, 2)
totaltime = round(time.time() - starttime, 2)
print('Lap #%s: %s: (%s)'%(lapnum, totaltime, laptime), end='')
lapnum += 1
lasttime = time.time()
except KeyboardInterrupt:
# handle the cntrl+c exception to keep error message
print('\nDone')
| true |
6193235aaa2f557e8e9c53d8b63ca819788be73a | ToMountainTops/MangoTest | /mango_programming_test_classes.py | 1,847 | 4.25 | 4 | """
Created on Sun Sep 29
For Mango Solutions Python test
For any questions please contact Claire Blejean: claire.blejean@gmail.com
The solution presented here relies on the random sampling function which is part of python.numpy.
A numerical solution can be coded which relies on mapping the inverse cumulative distribution function (cdf) of the chosen distibution onto a uniform sample.
For common pdf, it can be found in python.stats. For unususal cdfs, the inverted function can be found with the pynverse package (provided it is invertible).
"""
#%%
import numpy as np
import matplotlib.pyplot as plt
class Distribution:
def Normal(mean, standard_deviation, size):
return np.random.normal(mean, standard_deviation, size)
def Poisson(lamb, size): #with lamb the average rate of success
return np.random.poisson(lamb, size)
def Binomial(n, p, size): #with n the number of trials and p the probability of success (with p between 0 and 1)
if p<0 or p>1:
raise Bound_exception("p needs to be between 0 and 1.") #raise an error if p is out of bound
else:
return np.random.binomial(n, p, size)
def Summarize(self):
print("Minimum:", np.min(self))
print("Maximum:", np.max(self))
print("Mean:", np.mean(self))
print("Standard deviation:", np.std(self))
def Plot(self):
plt.hist(self)
class Bound_exception(Exception):
pass
#%%
"""
The methods belonging to this distribution class allow to draw from the three types of distributions.
It also allows to summarize the drawn sample and to plot it.
An example is presented below.
"""
sample = Distribution.Normal(0, 1, 100)
Distribution.Summarize(sample)
Distribution.Plot(sample)
| true |
493f17f5e53b46fbccc4cb95b2ea1e9a4a5cc7a3 | IshaBansal0408/HackerRank---Python-Programming | /Understanding Regular Expression/002. Groups in RE.py | 531 | 4.34375 | 4 | """
GROUPS IN REGULAR EXPRESSION
groups() return tuple containing all the captured groups
"""
import re
m=re.search('(\d+),(\d+),(\d+)','123,12763,773687')
print(m)
print(m.groups())
"""
GROUPS IN REGULAR EXPRESSION
group(n) return nth group
"""
print("Empty Group: ",m.group())
print("Group 0: ",m.group(0))
print("Group 1: ",m.group(1))
print("Group 2: ",m.group(2))
print("Group 1 and 2: ",m.group(1,2))
print("Group 2 and 3: ",m.group(2,3))
print("Group 3 and 2: ",m.group(3,2))
print("Group 1,2 and 3: ",m.group(1,2,3))
| false |
66b500e3a58a5fccb6cfc7ff6d6363a798757dfa | ParitoshBarman/Python-Practice | /Chapter-06-Conditional Expression/10_pr05.py | 218 | 4.21875 | 4 | names = ["shubha","sasti","samir","bishu","bishadu"]
name = input("Enter the name to check-->")
if name in names:
print("Your name is present in the list")
else:
print("Your name is not present in the list")
| false |
bdc98d70e73076855eedbe73247b27d05f4e2182 | baileejbrown/Projects | /prac_03/password_entry.py | 429 | 4.1875 | 4 | """Bailee Brown"""
MIN_LENGTH = 6
def main():
password = get_password()
print_asterisks(password)
def print_asterisks(password):
print('*' * len(password))
def get_password():
password = input("Please enter a password 6 digits or longer: ")
while len(password) < MIN_LENGTH:
print("Password not long enough,")
password = input("Please enter a valid password: ")
return password
main()
| false |
1ae0dd893d251b323e662d58dc6e49b62e29e018 | brandon932/learnPython | /CtoF.py | 610 | 4.1875 | 4 | #simple program to convert a temerature to in celcius to fahrenheit
def cel_to_fahr(c):
if c < -273.15:
print("how is that possible")
else:
f = c * 9/5 + 32
print(str(c) + " celcius is " + str(f) + " fahrenheit")
return f
def main():
c = float(input("enter a temperature in celcius: "))
cel_to_fahr(c)
def test():
temp = [10,-20,-289,100]
for c in temp:
cel_to_fahr(c)
def tofile():
temp = [10,-20,-289,100]
file = open("temp.txt",'w+')
for t in temp:
x = cel_to_fahr(t)
if x != None:
file.write(str(x) +"\n")
file.close()
#test()
#main()
tofile()
| false |
da3044772c9b3d4cd03151d1b177e335973dea99 | ChiranthakaJ/Google-Crash-Course-on-Python | /Python_OOP_Documenting_Functions_Classes_Methods.py | 2,451 | 4.65625 | 5 | #We can still use the Python function help to find documentation about classes and methods.
#We can also do this on our own classes, methods, and functions.
#Let's look at the below example.
class Apple:
def __init__(self, color, flavor):
self.color = color
self.flavor = flavor
def __str__(self):
return "This apple is {} and its flavor is {}".format(self.color, self.flavor)
print(help(Apple))
#This will get the below result.
'''
class Apple(builtins.object)
| Apple(color, flavor)
|
| Methods defined here:
|
| __init__(self, color, flavor)
| Initialize self. See help(type(self)) for accurate signature.
|
-- More --
'''
#See how when we asked for help on our class we got a list of the methods that are defined in the class? In this example, the defined methods are the constructor and the conversion to string. But this documentation is super short and to be honest, it doesn't explain a whole lot.
#We want our methods, classes, and functions to give us more information when we or someone else use the help function. We can do that by adding a docstring.
#A docstring is a brief text that explains what something does. Let's have look at the below example.
def to_seconds(hours, minutes, seconds):
"""Returns the amount of seconds in the given hours, minutes and seconds."""
return hours*3600+minutes*60+seconds
#So there we have it, we have a function with a docstring in its body. Let's see how we can use the help function to see it.
print(help(to_seconds))
'''
Help on function to_seconds in module __main__:
to_seconds(hours, minutes, seconds)
Returns the amount of seconds in the given hours, minutes and seconds.
'''
#The help function shows us the string we wrote.
#We can add docstrings to classes and methods too. Let's see it is in an example.
class Piglet:
"""Represents a piglet that can say their name."""
years = 0
name = ""
def speak(self):
"""Outputs a message including the name of the piglet."""
print("Oink! I'm {}! Oink!".format(self.name))
def pig_years(self):
"""Converts the current age to equivalent pig years."""
return self.years*18
print(help(Piglet))
#When we get the help for a particular class, we will have all the Docstrings that was declared within the class. At this moment we will get the Docstrings that are in functions(), methods() and constructors. | true |
3473cb8474c1476efbaedd61785ada112665c321 | ColinLafferty/python_tutorials_2013 | /leap_year.py | 1,238 | 4.65625 | 5 | #!/usr/bin/env python
'''\
Leap years occur according to the following formula: a leap year is divisible
by four, but not by one hundred, unless it is divisible by four hundred.
For example, 1992, 1996, and 2000 are leap years, but 1993 and 1900 are not.
The next leap year that falls on a century will be 2400.
source:http://openbookproject.net/pybiblio/practice/\
'''
def leap_year_check(year):
'''\
Takes a year as input and then returns True or False depending on if the
year is a leap year or not
:param year: Year to check
:type year: int
:returns: Whether a year is leap or not
:rtype: boolean\
'''
if year % 4 == 0:
if year % 100 == 0 and year % 400 != 0:
return False
return True
return False
def main():
'''\
Ask the user for a year as input and then return whether the year is a leap
year or not\
'''
year = int(input("Enter the year that you want to check is leap or not: "))
is_leap = leap_year_check(year)
results = {True: "The year, {0}, is a leap year",
False: "The year, {0}, is not a leap year"}
print(results[is_leap].format(year))
return is_leap
if __name__ == "__main__":
main()
| true |
5cd2a3acd1ef12389804180e51071ad660c84d46 | IsmailFadeli/Python-for-Probability-statistics-and-ML | /Random_Variables.py | 1,100 | 4.125 | 4 | # What is the probability that the sum of the dice equals seven?
# Step 1: associate all of the (a,b) pairs with their sum.
d = {(i,j):i+j for i in range(1,7) for j in range(1,7)}
# Step 2: collect all of the (a,b) pairs that sum each of the possible values from two to twelve.
from collections import defaultdict
dinv = defaultdict(list) # The defaultdict() object creates dictionaries with default values when it encounters a new key.
for i,j in d.items():
dinv[j].append(i)
print(dinv[7]) # dinv[7] contains the list of pairs that sum to seven
# Step 3: Compute the probability measured for each of these items.
X = {i:len(j)/36. for i,j in dinv.items() }
print(X)
# What is the probability that half the product of three dice will exceed their sum?
f = {(i,j,k):((i*j*k)/2>i+j+k) for i in range(1,7)
for j in range(1,7)
for k in range(1,7)}
finv = defaultdict(list)
for i,j in f.items(): finv[j].append(i)
Y = {i:len(j)/6.0**3 for i,j in finv.items()}
print(Y)
| true |
1dd80cfb8fe81573fe4b5b6467ffd12feda38acb | shirishdhar/HW04 | /HW04_ex00.py | 1,270 | 4.21875 | 4 | #!/usr/bin/env python
# HW04_ex00
# Create a program that does the following:
# - creates a random integer from 1 - 25
# - asks the user to guess what the number is
# - validates input is a number
# - tells the user if they guess correctly
# - if not: tells them too high/low
# - only lets the user guess five times
# - then ends the program
################################################################################
def random_guess():
import random
a=random.randrange(25)
count=0
while (count<5):
try :
guess1=int(raw_input('Enter your guess: '))
except:
print('Nice try.Enter an integer')
count+=1
else :
if (guess1>a):
count+=1
print('Too high. Try again !')
elif (guess1<a):
count+=1
print('Too low. Try again !')
else:
print('Great! You got it!')
return
print ('Sorry ! You had 5 chances!!!')
return
################################################################################
def main():
random_guess()
if __name__ == '__main__':
main()
| true |
f77318b267a53148e75bf32c0d564a25c250db34 | Zerl1990/python_essentials | /examples/module_1/06_inputs.py | 211 | 4.40625 | 4 | # Input will show a message in the console, and return what the used types
# The return value can be store in a variable
age = input("What is your age?")
# Print the user input
print("Your age is: " + age)
| true |
d2912a4091ba27c9be145f61b5a1ce2f51c3c60f | Zerl1990/python_essentials | /examples/module_1/03_variables.py | 453 | 4.3125 | 4 | # type function return the type of the variables.
# for example, for number variable, it will return int
number = 5
print("Number Type:")
print(type(number))
decimal = 15.5
print("Decimal Type:")
print(type(decimal))
char = 'A'
print("Char Type:")
print(type(char))
string = 'My String'
print("String Type:")
print(type(string))
boolean = True
print("Boolean Type:")
print(type(boolean))
arr = [0, 1, 2, 3]
print("List Type:")
print(type(arr))
| true |
72873dcfb1b9be8216663493368425738908b1ca | GuoXian88/15112_py | /fluent_py/ch08_obj_ref/ch8_obj_ref.py | 1,852 | 4.3125 | 4 | '''
garbage collection, the del command, and how
to use weak references to “remember” objects without keeping them alive.
reference variables: label attached to objects
下面可以证明赋值是先evluate右边再绑定到左边(Gizmo实例创建成功但是y并没有赋值成功)
To understand an assignment in Python, always read the right-
hand side first: that’s where the object is created or retrieved. Af‐
ter that, the variable on the left is bound to the object, like a label
stuck to it. Just forget about the boxes.
值相等 == 就为True(__eq__实现)
is比较identity
tuple里面的元素是mutable
tuple += 会产生一个新的
The problem is that each default value is eval‐
uated when the function is defined—i.e., usually when the module is loaded—and the
default values become attributes of the function object. So if a default value is a mutable
object, and you change it, the change will affect every future call of the function.
弱引用 An element will be discarded when no strong
reference to it exists any more.
If you need to build a class that is aware of every one of
its instances, a good solution is to create a class attribute with a WeakSet to hold the
references to the instances. Otherwise, if a regular set was used, the instances would
never be garbage collected, because the class itself would have strong references to them,
and classes live as long as the Python process unless you deliberately delete them.
'''
#eg1
class Gizmo:
def __init__(self):
print('Gizmo id: %d' % id(self))
x = Gizmo()
y = Gizmo() * 10 #报错但是实例已经生成
#eg2
l1 = [3, [66, 55, 44], (7, 8, 9)]
l2 = list(l1) #
l1.append(100) #
l1[1].remove(55) #
print('l1:', l1)
print('l2:', l2)
l2[1] += [33, 22] #
l2[2] += (10, 11) #
print('l1:', l1)
print('l2:', l2)
| true |
55f6d217079a25a1bc92c94e6de29af502482c11 | mirandarevans/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 474 | 4.15625 | 4 | #!/usr/bin/python3
def text_indentation(text):
if type(text) != str:
raise TypeError('text must be a string')
newline = True
for char in text:
if newline is True:
if char == ' ':
pass
else:
newline = False
if newline is False:
print(char, end='')
if char == '.' or char == '?' or char == ':':
print('\n')
newline = True
print('\n')
| true |
62c7bb6af2a4ed5fd481d5807f3f83d3ea87910a | vanithaasivakumar/Python---Hands-on | /Advanced Modules/FileIO.py | 640 | 4.125 | 4 | myfile=open('SampleText.txt')
print(myfile.read()) #displays file content
print(myfile.read()) #running it again will display empty string. Cursor is in end of the file
myfile.seek(0) #brings the cursor to the beginning of the file
print(myfile.read())
myfile.seek(0)
print(myfile.readlines()) #['Hello World\n', 'Good Day!\n'] Creates a List of lines as elements
myfile.close()
myfile2=open('D:\\Python\\Sample files\\SampleText.txt') #'/' is used in Mac and linux
myfile2.close()
with open('SampleText.txt') as no_close_file:
contents=no_close_file.read()
print(contents)
#myfile2=open('NotExistFile.txt') | true |
c6d1a211a7fefb816865d1a55aa40c82685cb6cc | Sergi-Simon/INTRODUCTION-TO-PYTHON-PROGRAMMING | /Solutions to Exercises in Lecture Notes, Sections 1-6/week 2 (section 2)/temperature.py | 790 | 4.28125 | 4 | """ temperature.py
Prorgram that converts any temoerature from Fahrenheit to Celsius and
from Celsius to Fahrenheit
Author: Sergi Simon
Last update: October 22, 2020 """
# conversion of Celsius to Fahrenheit
def C_to_F ( c ):
return c*1.8 + 32.
# conversion of Fahrenheit to Celsius
def F_to_C ( f ):
x=f-32.
return x/1.8
# we give the option
opt = input("Would you like to convert \n 1 Celsius to Fahrenheit or \n 2 Fahrenheit to Celsius?")
if opt == "1":
c = float(input("Write the temperature in degrees Celsius "))
f = C_to_F( c )
print("The temperature in degrees Fahrenheit is ",f)
if opt == "2":
f = float(input("Write the temperature in degrees Fahrenheit "))
c = F_to_C( f )
print("The temperature in degrees Celsius is ",c)
| false |
f9caaf9183591321cb40114dc1484fa8c27d8b6b | Sergi-Simon/INTRODUCTION-TO-PYTHON-PROGRAMMING | /Solutions to Exercises in Lecture Notes, Sections 1-6/week 3 (section 3)/vector_cosine.py | 1,455 | 4.21875 | 4 | """ vector_cosine.py
Program returnning the cosine of two vectors with recursive functions
Author: Sergi Simon
Last update: October 26, 2020 """
import math
def take_input( n, string, list0 ):
list1=list0.copy() # you can also write list1=list0 and it will still work
if len( list1 ) == n:
return list1
x = float(input(string+"["+str(len(list1))+"] = ")) # str transforms that number to a string
list1.append(x)
return take_input( n, string, list1 )
#this will be easier with loops
def dot_product ( listx, listy, index, value ):
if index == len (listx):
return value
s = listx[index]*listy[index]
return dot_product ( listx, listy, index+1, value+s )
# this will be easier with exception throwing
def vector_cos( listx, listy ):
tol = 1.e-14
cosine = dot_product(listx,listy,0,0)/(math.sqrt(dot_product(listx,listx,0,0)*dot_product(listy,listy,0,0)))
if abs(cosine - 1) < tol:
print ("The vectors are collinear and in the same direction")
return cosine
if abs(cosine + 1) < tol:
print ("The vectors are collinear and in opposite directions")
return cosine
if abs(cosine) < tol:
print ("The vectors are perpendicular")
return cosine
print ("The vectors are neither perpendicular nor collinear")
return cosine
print("Write the two vectors: ")
x = take_input(2,"x",[])
y = take_input(2,"y",[])
print("The dot product is",dot_product(x,y,0,0))
cosine = vector_cos( x, y )
print("The cosine of their angle is",cosine)
| true |
ea2dc847f4175a358ebf78760f7da0537cb122a8 | Sergi-Simon/INTRODUCTION-TO-PYTHON-PROGRAMMING | /Solutions to Exercises in Lecture Notes, Sections 1-6/week 6 (sections 5, 6)/6/function_graph.py | 1,615 | 4.46875 | 4 | """ function_graph.py
Routine that checks the number of changes in sign in the graph provided in the lecture notes
Author: Sergi Simon
Last Update: November 18, 2020 """
import sys
def verify_signs ( x0, x1 ):
if x0 == -3 or x0 == 2 or x0 == 6 or x1 == -3 or x1 == 2 or x1 == 6:
string = "you have chosen interval limits, please choose other numbers"
# elif x0 >= x1:
# string = "please write numbers such that the first is smaller than the second"
elif x0 < -3:
if x1 < -3:
string = "zero changes in sign"
elif x1 < 2:
string = "one change in sign"
elif x1 < 6:
string = "two changes in sign"
else:
string = "three changes in sign"
elif x0 < 2:
if x1 < 2:
string = "zero changes in sign"
elif x1 < 6:
string = "one change in sign"
else:
string = "two changes in sign"
elif x0 < 6:
if x1 < 6:
string = "zero changes in sign"
else:
string = "one change in sign"
else:
string = "zero changes in sign"
return string
def inputx0x1( ):
global x0, x1
try:
print( "Write x0 and x1")
x0 = float( input("x0 = ") )
x1 = float( input("x1 = ") )
if x0 >= x1:
raise Exception ('numbers but not in the right order')
except ValueError:
print( 'They need to be numbers!')
except Exception as inst:
print( 'These are ', inst )
else:
print( 'We have your two values properly stored')
return True
while True:
if( inputx0x1() ):
print(verify_signs(x0,x1))
break
else:
print( "try proper x0, x1" )
| true |
fe34b8e6d72e091a7dc01eeacc3d09e262c1ef31 | Sergi-Simon/INTRODUCTION-TO-PYTHON-PROGRAMMING | /Solutions to Exercises in Lecture Notes, Sections 1-6/week 4 (section 4)/Solutions to Exercises/1/reverse_tuple_2.py | 316 | 4.34375 | 4 | """ reverse_tuple.py
Function that reverses any tuple
Author: Sergi Simon
Last update: October 26, 2020 """
def reverse_tuple ( Tuple ):
list1 = list( Tuple )
list1.reverse()
return tuple( list1 )
print( reverse_tuple( (1,2,3) ) )
x= 1,2,3,"a","good morning", -1,-2
print( reverse_tuple( x ) )
| false |
9e950dc6b0a0f7941d5d6d1fe1fcc2f354a7495f | Alena-Ryzhko/python_algorithms | /unit_test/reverse_string.py | 478 | 4.125 | 4 | """
Unit Test –> Reverse String
"""
import unittest
class TestStringReversal(unittest.TestCase):
def test_reverse_string(self):
input = "Rosa are red and I am glad"
expected_result = "glad am I and red are Rosa"
output = self.reverse_string(input)
self.assertEqual(expected_result, output)
def reverse_string(self, input: str):
return ' '.join(list(reversed(input.split())))
if __name__ == '__main__':
unittest.main()
| true |
6cdb0e720062ef1b9f3751bd6b5c3d48184d276e | Alena-Ryzhko/python_algorithms | /algorithms_2_num/sum_of_natural_numbers_of_the_random_generated_num.py | 1,012 | 4.1875 | 4 | """
A function which finds the sum of num natural numbers:
(sum of digits of a randomly generated number n)
"""
from random import randint
# Approach 1
def sum_of_natural_numbers_of_num(number_of_digits):
down = 10**(number_of_digits-1)
up = (10**number_of_digits)-1
n = randint(down, up) # randomly generated number n
print(f'We got number {n} ')
sum = 0
i = 0
while i < number_of_digits:
sum += n % 10
n = n // 10
i += 1
print(f'The sum is {sum}')
number_of_digits = int(input('Please enter number of digits of the random generated number '))
sum_of_natural_numbers_of_num(number_of_digits)
# Approach 2
# n = randint(100, 999)
#
# print(f'We got random number {n}')
#
# one = n % 10
# ten = n // 10 % 10
# hundred = n // 100
# sum = one + ten + hundred
#
# print(f'one ' + str(one))
# print(f'ten ' + str(ten))
# print(f'hundred ' + str(hundred))
#
# print(f'sum ' + str(one + ten + hundred))
# # or
# print(f'sum ' + str(sum)) | false |
546b568c45ff86dfec09cf3ed4b2c4c8e6bce0b4 | Alena-Ryzhko/python_algorithms | /algorithms_2_num/fibonacci_sequence.py | 983 | 4.40625 | 4 | """
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,...
where F0 = 0 , F1 = 1 and Fn = Fn-1 + Fn-2
A function to Print the Fibonacci sequence:
"""
# Approach 1
n = int(input("How many numbers will be in the sequence? Enter please "))
def fibonacci(n):
# First Fibonacci number is 0
# Second Fibonacci number is 1
n1, n2 = 0, 1
count = 0
# check if number of nth Fibonacci number is valid
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto", n, ":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
fibonacci(n)
# Approach 2
# Fibonacci sequence using recursion
def fib(n):
if n <= 1:
return n
else:
return fib(n - 2) + fib(n - 1)
print(fib(8))
| true |
b83bdcfc0cee4c86dbcf94cf51d2f910acb3e959 | daniglezmar/Python | /Codigos_De_Clase/Códigos-1/condicionalIF.py | 431 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Comparacion entre varios numeros
print ("Vamos a comparar dos números: ")
numero1 = int (input("Escribe un primer numero: "))
numero2 = int (input("Escribir un segundo numero: "))
if (numero1 < numero2):
print ("Menor: ", numero1, "Mayor: ", numero2)
elif (numero1 > numero2):
print ("Menor: ", numero2, "Mayor: ", numero1)
else:
print ("Los dos numeros son iguales")
| false |
e5c3d33b4d20042bebdfc4ea3d637a0928948663 | Maruthi18/Python_Projects | /Calculator/calculator.py | 1,006 | 4.21875 | 4 | from replit import clear
from art import logo
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
""" here we are taking n1 and n2 values and evaluating and print the answer"""
print(calculator.__doc__)
print(logo)
n1 = float(input("What's the first number?: "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation: ")
n2 = float(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(n1, n2)
print(f"{n1} {operation_symbol} {n2} = {answer}")
if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
n1 = answer
else:
should_continue = False
clear()
calculator()
calculator()
| true |
f293f33656b14932f10e04482a51df8cf9ffd5b0 | 123zrf123/python- | /practice_7.py | 766 | 4.21875 | 4 | #栈的基本操作
class Stack(object):
"""模拟栈"""
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items)==0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
if not self.isEmpty():
return self.items[len(self.items)-1]
def top(self):
if len(self.items) == 0:
return 'Empty Queue'
return self.items[0]
def size(self):
return len(self.items)
s=Stack()
print(s.isEmpty())
s.push(1)
print(s.pop())
s.push(2)
s.push(3)
print(s.top())
print(s.pop())
#print(s.peek())
#s.push(True)
#print(s.size())
#print(s.isEmpty())
print(s.size()) | false |
bcf75ce80a6eb0a2115056ae7172b981dbd047e4 | xlistarer/recurse | /main.py | 2,877 | 4.34375 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
'''
#############################################
# All tasks should be solved using recursion
#############################################
Task 1
from typing import Optional
def to_power(x: Optional[int, float], exp: int) -> Optional[int, float]:
"""
Returns x ^ exp
>>> to_power(2, 3) == 8
True
>>> to_power(3.5, 2) == 12.25
True
>>> to_power(2, -1)
ValueError: This function works only with exp > 0.
"""
pass
Task 2
from typing import Optional
def is_palindrome(looking_str: str, index: int = 0) -> bool:
"""
Checks if input string is Palindrome
>>> is_palindrome('mom')
True
>>> is_palindrome('sassas')
True
>>> is_palindrome('o')
True
"""
pass
Task 3
from typing import Optional
def mult(a: int, n: int) -> int:
"""
This function works only with positive integers
>>> mult(2, 4) == 8
True
>>> mult(2, 0) == 0
True
>>> mult(2, -4)
ValueError("This function works only with postive integers")
"""
Task 4
def reverse(input_str: str) -> str:
"""
Function returns reversed input string
>>> reverse("hello") == "olleh"
True
>>> reverse("o") == "o"
True
"""
Task 5
def sum_of_digits(digit_string: str) -> int:
"""
>>> sum_of_digits('26') == 8
True
>>> sum_of_digits('test')
ValueError("input string must be digit string")
'''
def to_power(x, exp) :
if exp<0 or int(exp)!=exp:
raise ValueError
if exp==0:
return 1
return to_power(x,exp-1)*x
def is_palindrome(str) -> bool:
if str[0]!=str[-1]:
return False
if len(str)<3:
return True
return is_palindrome(str[1:-1])
def mult(a, n) -> int:
if a<0 or n<0:
raise ValueError
if n==0:
return 0
return mult(a,n-1)+a
def sum_of_digits(digit: str):
if digit=='':
return 0
if not digit.isdigit():
raise ValueError
return int(digit[0])+sum_of_digits(digit[1:])
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print(to_power(2,3))
print(to_power(3.5, 2))
str='murmay'
print(is_palindrome('mom'))
print(is_palindrome('sassas'))
print(is_palindrome('sakksas'))
print(mult(2, 4))
print(mult(2, 0) == 0)
print(sum_of_digits('26'))
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
| true |
ba579d74b47eb7dc1a55a242e22701abdbb46997 | roshansinghbisht/hello-python | /day-5-using-a-simple-loop.py | 1,945 | 4.34375 | 4 | # TASK: The provided code stub reads and integer, n, from STDIN.
# For all non-negative integers i<n, print n^2 .
if __name__ == '__main__':
n = int(input("Enter a number between 1 and 20"))
for i in range(n):
print(i**2)
# A module is a file containing Python definitions and statements.
# The file name is the module name with ‘.py’ appended.
# Many programming languages have a special function that is
# automatically executed when an operating system starts to run a
# program. This function is usually called main(). On the other hand,
# the Python interpreter executes scripts starting at the top of the
# file, and there is no specific function that Python automatically
# executes.
# Nevertheless, having a defined starting point for the execution of a
# program is useful for understanding how a program works.
# Say if we wanted to execute some lines of code only when we run the
# script directly, and not when the file is imported in other modules?
# Whenever we run a script, python actually sets a special built-in
# variable called ‘__name__’ for any module. Python recognises the
# module as the main program(the script which runs), and sets the
# __name__ variable for that module as __main__. For any modules which
# are imported in the script, this built-in __name__ variable is just
# set to the name of that module.
# Hence in above code, the if statement just checks whether we are
# running the script directly or not:
# If __name__ = main is True, this means that we're running the
# script directly. Else, we are running it after importing it elsewhere.
# Python For loop syntax:
# for i in <collection>
# <loop body>
# range(<end>) function in Python returns an iterable that yields integers
# starting with 0, up to but not including <end>
# Example: range(4) will return 0,1,2,3.
# --Iterables are objects that can return one of their elements at a time.
| true |
8f3e26501cd9a96e8b9f4677fe3586994afd0869 | roshansinghbisht/hello-python | /day-17-data-structures.py | 1,076 | 4.28125 | 4 | print('Creating a Tuple...............................................')
dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))
# Creating a set fro a list (to remove duplicates from a list).
print('Creating a set.................................................')
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_elements = set(numbers)
print(unique_elements)
print('Creating another set...........................................')
fruit = {"apple", "banana", "orange", "grapefruit"} # define a set
print("watermelon" in fruit) # check for element
fruit.add("watermelon") # add an element
print(fruit)
print(fruit.pop()) # remove a random element
print(fruit)
print('Creating a dictionary..........................................')
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"]) # print the value mapped to "helium"
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the
# dictionary
print("carbon" in elements)
print(elements.get("dilithium"))
| true |
2e8540fb1fdbf26c5d19dee9e5855bf06ac3c484 | Pittor052/SoftUni-Courses | /Python/Basics/0.2-Conditional-Statements/Exercises/converter.py | 496 | 4.21875 | 4 | num_to_convert = float(input())
unit_in = input()
unit_out = input()
if unit_in == "m":
if unit_out == "cm":
num_to_convert *= 100
elif unit_out == "mm":
num_to_convert *= 1000
if unit_in == "cm":
if unit_out == "m":
num_to_convert /= 100
elif unit_out == "mm":
num_to_convert *= 10
if unit_in == "mm":
if unit_out == "m":
num_to_convert /= 1000
elif unit_out == "cm":
num_to_convert /= 10
print(f"{num_to_convert:.3f}") | false |
a9e469a52407aa1004562ab4b212bea5c471e71a | nick-fl/projecteuler | /5.py | 480 | 4.25 | 4 | #infinitely outputs multiples of 20. there is probably and easier way
print("Finding the smallest number that has every number between 1 and 20 as a factor.")
found = 0
a = 0
while found == 0:
counter = 0
b = a + 20
for i in range(1,21):
if b%i == 0:
counter += 1
if counter == 20:
print(b,"is the smallest number that has every number between 1 and 20 as a factor.")
found += 1
break
a = b
| true |
b4513eb73cd6683c02ad1e0d1b413785bdeece4d | BernardWong97/Collatz | /collatz.py | 399 | 4.46875 | 4 | # The number to perform the Collatz operation.
n = int(input("Enter a positive integer: "))
# Keep looping until n = 1 assuming Collatz conjecture is true.
while n != 1:
print(n) # print current value of n.
if n % 2 == 0: # if even, divide by two.
n //= 2
else: # if odd, multiply by three and add one.
n = (3 * n) + 1
# Print last value of n (should be 1)
print(n)
| true |
6936684126b9a4d76c079d0b9638d4dddc8ae96d | Steantc/SENG3110_Lab2_Python_Unit_Testing_Project | /cube.py | 886 | 4.125 | 4 | import math
def surfaceArea(ln):
area = round((6 * ln**2), 2)
return area
def volume(ln):
volume = round((ln**3), 2)
return volume
def lateral(ln):
lateral = round((4* ln**2), 2)
return lateral
def prompt():
print()
print("------------------------------------------------------------")
print("PYTHON PROGRAM TO FIND THE VOLUME AND SURFACE AREA OF A CUBE")
print("------------------------------------------------------------")
length = int(input("Please Enter the Length of any Side of a Cube :"))
print("The Surface Area of a Cube is = ", surfaceArea(length))
print("The Volume Area of a Cube is = ", volume(length))
print("Lateral Surface Area of a Cube = ", lateral(length))
print("------------------------------------------------------------")
print()
return length
if __name__ == '__main__':
prompt() | true |
36ae7457a749d276c36e4e71bfeac919112168d7 | ayumoesylv/draft-tic-tac-toe | /L2 Python Class 1 homework pt 2.py | 260 | 4.125 | 4 | #write a program to count the number of elements in a list.
FruitIndex = ["apple", "orange", "banana", "kiwi", "blueberry", "grape"]
fruitNum = len(FruitIndex)
for i in range(0, len(FruitIndex)):
print(FruitIndex[i], end = " ")
print("total:", fruitNum) | true |
da4b5f37095f003305bbda58c149b0afe8f255e7 | sharma-arpit/cs50 | /Random/stud.py | 245 | 4.28125 | 4 | from student import Student
students = []
for i in range(3):
name = input("name: ")
dorm = input("dorm: ")
students.append(Student(name, dorm))
for student in students:
print("{} is in {}.".format(student.name, student.dorm))
| true |
13d3bc182e07027e3fef6dea8094e3976e55e7eb | paua-app/Python-Stuff | /functional programming/mylen.py | 2,111 | 4.34375 | 4 | """
Task:
Write a function that calculates the length of a list.
Example:
#>>> print(len([1,2,3,4,5]))
5
"""
from auxfuncs import cdr
from auxfuncs import build_list as bl
from auxfuncs import curry
__author__ = 'Aurora'
def my_len_imp(lst):
temp = 0
i = 0
while lst[i] != None:
temp += 1
i += 1
return temp
def my_len_rec(lst):
"""
Recursive approach
:rtype: integer
:param lst: a list of elements which length is to be determined
:return: the length of lst
"""
if not lst:
return 0
else:
return 1 + my_len_rec(cdr(lst))
def my_len_tr(lst, acc=0):
"""
Tail-Recursive approach.
Features a counter for the list length, which is returned when the list is iterated over completely
Default value 0 as neutral element for addition.
:rtype: integer
:param lst: List of which the length is required
:param acc: counter for the length. Should be left blank at function call.
:return: the length of lst
"""
if not lst:
return acc
else:
return my_len_tr(cdr(lst), acc+1)
def my_len_hof(lst):
"""
Approach using Higher-Order Functions
:rtype : integer
:param f: the function to be applied in order to determine the length of lst
:param lst: a list of elements which length is to be determined
:return: the length of lst
"""
return reduce(lst, 0)
def my_len_test():
"""
Test for all three functions
:rtype: string
:return: the test message and a return value of all three main functions (which should be equal)
"""
length = 10
lst = bl(length)
return ("Determining the length of {0}.\n"
"\tShould be: {1}\n"
"\tRecursive approach: {2}\n"
"\tTail-Recursive approach: {3}\n"
"\tHOF-approach: {4}".format(lst,
length,
my_len_rec(lst),
my_len_tr(lst),
my_len_hof(None, lst)))
| true |
89fc0701e224e24bc764f31de5d01efbd59d633b | arsh771/assignment16 | /MONGODB.py | 857 | 4.3125 | 4 | #Q.1- Write a python script to create a databse of students named Students.
import pymongo
client=pymongo.MongoClient()
database=client['Students']
print('STUDENTS DATABASE CREATED')
collection=database['Student Data']
print('STUDENTS DATA TABLE CREATED')
#Q.2- Take students name and marks(between 0-100) as input from user 10 times using loops.4
#Q.3- Add these values in two columns named "Name" and "Marks" with the appropriate data type.
for i in range (1,11):
print('Enter Detail Of Student {}:'.format(i))
name=input('Name:')
marks=int(input('Marks:'))
collection.insert_one({'Name':name,'Marks':marks})
print('VALUES INSERTED')
#Q.4- Print the names of all the students who scored more than 80 marks.
data=collection.find({'Marks':{"$gt" : 80}})
for details in data:
print('MARKS GREATER THAN 80',details)
| true |
861757dc22878e5535c974eb49104a1195beba6f | kshannoninnes/hyprfire | /hyprfire_app/utils/file.py | 534 | 4.34375 | 4 | from pathlib import Path
def get_filename_list(path):
"""
get_filename_list
Helper function to retrieve a list of non-hidden filenames from a directory
Parameters
path: a path to a directory containing files
Return
A list of non-hidden filenames in the directory
"""
file_list = Path(path).glob('*')
filenames = []
for file in file_list:
name = file.stem.lower()
if file.is_file() and not name.startswith('.'):
filenames.append(name)
return filenames
| true |
13365a83cff07ae5eab820f17d288d5f86bc4afc | ujaani/python | /max.py | 373 | 4.125 | 4 | first = input("give me a number")
second = input("give me another number")
first_int = int(first)
second_int = int(second)
if first_int > second_int:
max = first_int
elif first_int == second_int:
print("both no. are equal. the equal no. is " + first)
exit(0)
else:
max = second_int
max_str = str(max)
print("the greater no. is " + max_str) | true |
6a8f1ff7ce2492d3c963e3d8d75a1162b5c4ccf5 | huzefa53/python-learning | /python-learning/dict.py | 779 | 4.21875 | 4 | #!/usr/bin/python
'''Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and
consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces (
[] ). For example:'''
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name':'huzefa', 'age':26, 'job':'IT'}
print dict['one'] #prints value for 'one' key
print dict[2] #print values for 2 key
print tinydict #print complete timydict
print tinydict.keys() #print all the keys
print tinydict.values() #print all the values
| true |
5a6585d058c0dcf1f27f984fc6e436206bd3e90f | AfroHackology/OOP | /coreyS_classes/emp.py | 1,379 | 4.15625 | 4 | class Employee:
num_of_emps = 0
raise_amount = 1.04
names = input([])
tardies = bool(False)
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.apply_raise())
def
emp_1 = Employee('Greg', 'X', 50000)
emp_2 = Employee('Test', 'X', 60000)
# Get information of instance, class or attribute by using __dict__
# print(emp_1.__dict__)
# Changed Employee raise amount
# Employee.raise_amount = 1.05
# Specify the instance you want to apply a raise to
# emp_1.raise_amount = 1.05
# print(Employee.raise_amount)
# print(emp_1.raise_amount)
# print(emp_1.raise_amount)
"""" Both of these work the same but one needs an instance to be called inside
the parens and the other
print(emp_1.fullname()) # This is an instance and doesn't need self to be called because it is done automaticly
print(Employee.fullname(emp_1)) # Called on class so it doesn't know what instance to print so give it one
print(emp_1.fullname())
"""
# # Called emp1.pay and then applied the raise therefore it applied the raise
# print(emp_1.pay)
# emp_1.apply_raise()
# print(emp_1.pay) | true |
0dac3948778f6524def5952f7112c5ca80303b63 | w23023030/sc-projects | /stanCode-Projects/boggle_game_solver/anagram.py | 2,363 | 4.1875 | 4 | """
File: anagram.py
Name: Jasmine Tsai
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
# Constants
FILE = 'dictionary.txt' # This is the filename of an English dictionary
EXIT = '-1' # Controls when to stop the loop
dict_lst = []
counter = 0
found = []
def main():
read_dictionary()
print('Welcome to stanCode \" Anagram Generator\" (or -1 to quit/)')
while True:
inp = input(str('Find anagrams for: ')) # user input
inp = inp.lower()
if inp == EXIT:
break
find_anagrams(inp)
def read_dictionary():
with open(FILE, 'r') as f:
for line in f:
dict_lst.append(line.strip())
def find_anagrams(s):
"""
:param s: user input
:return: None
"""
global counter
print('Searching...')
helper(s, found, '', [])
print(f'{counter} anagrams: {found}')
def helper(s, current_lst, current_word, index):
global counter
if len(current_word) == len(s) and current_word in dict_lst: # if the word in dictionary and length is len(s)
if current_word not in current_lst: # if the word not in list append
current_lst.append(current_word)
print('Found: ' + current_word)
print('Searching...')
counter += 1
else:
for i in range(len(s)):
if i not in index:
# choose
current_word += s[i]
index.append(i)
# explore
if has_prefix(current_word):
helper(s, current_lst, current_word, index)
# un-choose
current_word = current_word[:-1]
index.pop()
def has_prefix(sub_s):
"""
:param sub_s: the un-check combination
:return: the combination is in the dictionary or not
"""
for ch in dict_lst:
if ch.startswith(sub_s):
return ch.startswith(sub_s)
if __name__ == '__main__':
main()
| true |
dc9f2e3e4b34a603913683da5a0d79cc7944cfd0 | nlkek/CodewarsProgs | /SimplePigLatin.py | 475 | 4.1875 | 4 | def pig_it(text):
res = ''
lst = text.split(' ')
for word in lst:
if word.isalnum():
res += word[1:] + word[0] + 'ay '
else:
res += word
return res.rstrip()
"""
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldWay !
"""
| true |
ec9d503e6ee3a5079ee9d71e4077ff9232a69ea3 | Matthew-Barrett/rock_paper_scissors | /rpsv3.py | 1,786 | 4.21875 | 4 | import random
hands = {"r":"Rock", "p": "Paper", "s": "Scissors","e": "exit"}
ai_hands = {"r": "Rock", "p": "Paper", "s":"Scissors" }
print( "Welcome to Rock, Paper, Scissors" )
print( "This is a game of wits, human vs machine." )
print( "You may also concede defeat by pressing e")
game_on = True
while game_on:
x = input("Choose your hand, of rock, paper, or scissors by typing r,p or s:")
ai_hand = random.choice(list(ai_hands))
if x == "r":
print ("You play Rock")
elif x == "p":
print ("You play Paper")
elif x == "s":
print ("You play Scissors")
elif x == "e":
print ("GG")
game_on = False
break
else:
print("Admit defeat and press e, or give it your best shot and enter r, p, or s:")
if ai_hand == "r":
print("I play Rock")
elif ai_hand == "p":
print("I play Paper")
elif ai_hand == "s":
print("I play Scissors")
if x == ai_hand:
print ("Draw")
elif x == "r" and ai_hand == "p":
print("Paper covers Rock: You lose")
elif x== "p" and ai_hand == "r":
print("Paper covers Rock: You Win!")
elif x == "s" and ai_hand == "r":
print("Rock smahes Scissors: you lose")
elif x == "r" and ai_hand == "s":
print("Rock smashes Scissors: You Win!")
elif x == "p" and ai_hand == "s":
print("Scissors cuts Paper: You lose")
elif x == "s" and ai_hand == "p":
print("Scissors cuts Paper: You Win!")
#if x != list.item:player_hand
# def game(human_player,ai_player):
# if human_player.player_hand
#human players turn
#ai_players turn
#ai_player =
#input ("press enter to continue") | false |
2d86a3cacbf4ad14167d00f63d43ae7fccef594c | arwildo/hacker-rank | /30DaysOfCode/day3.py | 383 | 4.15625 | 4 | #!/bin/python3
def checks(N):
odd = 1
if N%2 != odd and N > 20:
print('Not Weird')
elif N%2 != odd and N >= 2 and N <= 5:
print('Not Weird')
elif N%2 != odd and N >= 6 and N <= 20:
print('Weird')
elif N%2 == odd:
print('Not Weird')
else:
print('Weird')
if __name__ == '__main__':
N = int(input())
checks(N)
| false |
0eecdc646a3b101f41ddf1b4580f5cf571849d2a | gahakuzhang/PythonCrashCourse-LearningNotes | /6.dictionaries/6.4.1 a list of dictionaries.py | 320 | 4.21875 | 4 | # 6.4.1 a list of dictionaries 字典列表
aliens=[]
# 创建30个绿色外星人
for alien_number in range(30):
new_alien={'color':'green','points':5,'speed':'slow',}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print('...')
print("The total number of aliens: "+str(len(aliens))) | true |
57cd761fc481808c38c9994b6eb73ac579a0fb77 | gahakuzhang/PythonCrashCourse-LearningNotes | /9.classes/9.3.3 define attributes and methods for the child class.py | 1,205 | 4.34375 | 4 | # 9.3.3 define attributes and methods for the child class 为子类定义属性和方法
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_descriptive_name(self):
long_name=str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(self):
print("This car has "+str(self.odometer_reading)+" miles on it.")
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
self.odometer_reading=mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading+=miles
class ElctricCar(Car):
def __init__(self,make,model,year):
"""初始化父类的属性,再初始化电动汽车特有的属性"""
super().__init__(make,model,year)
self.battery_size=70
def describe_battery(self):
print("This car has a "+str(self.battery_size)+"-kWh battery.")
my_tesla=ElctricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery() | true |
2323d1575e0e3299b67bddaa9c88ac80332a23f3 | YaYaChen827/Udacity_Intro_to_Computer_Science | /Quiz/Lesson5_Quiz_Empty_Hash_Table.py | 1,186 | 4.1875 | 4 | # Creating an Empty Hash Table
# Define a procedure, make_hashtable,
# that takes as input a number, nbuckets,
# and returns an empty hash table with
# nbuckets empty buckets.
def make_hashtable(nbuckets):
hashtable = []
for i in range(0, nbuckets):
hashtable.append([])
return hashtable
#Testing right make_hashtable
print make_hashtable(3)
#>>> [[], [], []]
table = make_hashtable(3)
table[0].append(['Udacity',['https://www.udacity.com']])
print table[0]
#>>> [['Udacity', ['https://www.udacity.com']]]
print table[1]
#>>> []
#In this course, doc says the wrong function(make_hashtable_NOT)
def make_hashtalbe_NOT(nbuckets):
return [[]]*nbuckets
#Testing the wrong function
print make_hashtalbe_NOT(3)
#>>> [[]]
table = make_hashtalbe_NOT(3)
table[0].append(['Udacity',['https://www.udacity.com']])
print table[0]
#>>> [['Udacity', ['https://www.udacity.com']]]
print table[1]
#>>> [['Udacity', ['https://www.udacity.com']]]
#That is tricky function, I think a logical mistake on this way.
#If you use [[]]*buckets and then set a value to any element which equal set all element.
#The next quiz's answer explains each element in the output refer to the same empty list | true |
802e97f5333bb818ff099bcbbcfa7bc204b67dec | robgoyal/CodingChallenges | /CodeWars/7/complementaryDNA.py | 437 | 4.125 | 4 | # Name: complementaryDNA.py
# Author: Robin Goyal
# Last-Modified: March 15, 2018
# Purpose: Return the complement of a DNA string
def DNA_strand(dna):
"""
(str) -> str
Return the DNA complement of dna as a string.
Examples:
>>> DNA_strand("ACTGTAC")
"TGACATG"
"""
complements = {"A": "T", "T": "A", "G": "C", "C": "G"}
complement = [complements[acid] for acid in dna]
return "".join(complement)
| true |
0d85a27d4679d367cf451ab98124bf3722701614 | robgoyal/CodingChallenges | /HackerRank/Algorithms/Implementation/21-to-30/jumpingOnTheCloudsRevisited.py | 884 | 4.375 | 4 | # Name: jumpingOnTheCloudsRevisited.py
# Author: Robin Goyal
# Last-Modified: November 23, 2017
# Purpose: Calculate the remaining energy level after jumping over clouds
def jumpingOnTheCloudsRevisited(n, k, clouds):
'''
n -> int: number of clouds
k -> int: jump size
clouds -> list: clouds of value 0 or 1
return -> int: remaining energy level
Calculate the remaining energy level, starting from 100.
If the cloud landed is a 1, decrease by 3 energy,
Else, decrease by 1 energy
'''
energy = 100
for i in range(0, n, k):
if clouds[i] == 1:
energy -= 3
else:
energy -= 1
return energy
def main():
n, k = list(map(int, input().strip().split(' ')))
clouds = [int(c_temp) for c_temp in input().strip().split(' ')]
result = jumpingOnTheCloudsRevisited(n, k, clouds)
print(result)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.