blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4c5a6f6d8e2d5a076872f06d0484d9d5f6f85943 | jacobkutcka/Python-Class | /Week03/rainfall.py | 1,668 | 4.25 | 4 | ################################################################################
# Date: 03/01/2021
# Author: Jacob Kutcka
# This program takes a year count and monthly rainfall
# and calculates the total and monthly average rainfall during that period
################################################################################
def main():
# Establish sum
sum = 0
# Call for year count
years = int(input('Enter the number of years: '))
if years > 0:
# Loop for each year
for i in range(years):
print(' For year No. ' + str(i+1))
# Add sum of rainfall in subject year
sum += year(i)
print('There are ' + str(years*12) + ' months.')
print('The total rainfall is ' + str(format(sum, ',.2f')) + ' inches.')
print('The monthly average rainfall is ' + str(format(sum/(years * 12), ',.2f')) + ' inches.')
else:
print("Invalid input.")
def year(year):
# Establish month list and sum
sum = 0
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Loop for each month
for i in range(len(months)):
# Find rain for subject month
rainfall = float(input(' Enter the rainfall for ' + months[i] + '.: '))
while(rainfall < 0):
# If rainfall is negative, inform user and ask again
print(' Invalid input, please try again.')
rainfall = float(input(' Enter the rainfall for ' + months[i] + '.: '))
# Add together all months' rainfall
sum += rainfall
# return rainfall sum
return sum
if __name__ == '__main__':
main()
| true |
fe40e8644f98b8c2ebf6fedd95938c4dc95175d1 | lukeyzan/CodeHS-Python | /LoopandaHalf.py | 474 | 4.21875 | 4 | """
This program continually asks a user to guess a number until they have guessed
the magic number.
"""
magic_number = 10
# Ask use to enter a number until they guess correctly
# When they guess the right answer, break out of loop
while True:
guess = int(input("Guess my number: "))
if guess == magic_number:
print "You got it!"
break
print "Try again!"
# Print this sentence once number has been guessed
print "Great job guessing my number!" | true |
2e4d716798afd6e737492f33e56165a5de790aaf | rsaravia/PythonBairesDevBootcamp | /Level3/ejercicio4.py | 418 | 4.4375 | 4 | # Write a Python function using list comprehension that receives a list of words and
# returns a list that contains:
# a. The number of characters in each word if the word has 3 or more characters
# b. The string “x” if the word has fewer than 3 characters
low = ['a','este','eso','aquello','tambien']
lor = [len(x) if len(x) >= 3 else 'x' for x in low]
print("Original list: ", low)
print("Output list: ", lor) | true |
6e438a337feb8ef59ca8c8deae05ea6bfcbe1c13 | rsaravia/PythonBairesDevBootcamp | /Level1/ejercicio10.py | 543 | 4.28125 | 4 | # Write a Python program that iterates through integers from 1 to 100 and prints them.
# For integers that are multiples of three, print "Fizz" instead of the number.
# For integers that are multiples of five, print "Buzz".
# For integers which are multiples of both three and five print, "FizzBuzz".
l = [x+1 for x in range(100)]
for each in l:
if ( each%3 == 0 ) and ( each%5 == 0 ):
print ("FizzBuzz")
elif (each%3 == 0):
print ("Fizz")
elif (each%5 == 0):
print ("Buzz")
else:
print(each)
| true |
5df3fa2d2ab2671f2302a582e95716d6a57dc09e | mariebotic/reference_code | /While Loops, For Loops, If Else Statements, & Boolean Operators.py | 2,947 | 4.53125 | 5 | # WHILE LOOPS, FOR LOOPS, IF ELSE STATEMENTS, & BOOLEAN OPERATORS
#______________________________________________________________________________________________________________________________________________________________________________#
import random
while True:
user_input = input("Please enter a number between 1 and 10: ") # asks user to enter a number between 1 and 10
if user_input.isnumeric(): # determines if the user input is all numerical values
user_inputint = int(user_input) # changes user input string into an int
if user_inputint <= 10 and user_inputint >= 1: # determines if the user input is less than or equal to 10
num = random.randint(1,10) # chooses a random int between 1 and 10
print(f"Your input is equal to the secret number: {user_inputint == num}") # determines if user input is equal to secret number
print(f"Your input is not equal to the secret number: {user_inputint != num}") # determines if user input is not equal to secret number
print(f"Your input is greater than the secret number: {user_inputint > num}") # determines if user input is greater than secret numer
print(f"Your input is less than the secret number: {user_inputint < num}") # determines if user input is less than secret number
print(f"The secret number is even: {num%2 == 0}") # determines if secret number is even
guess = input("Please enter your guess for the secret number between 1 and 10: ") # asks user to enter a guess for the secret number between 1 and 10
if guess.isnumeric(): # determines if the user input is all numerical values
guess = int(guess) # changes user input string into an int
if guess <= 10 and guess >= 1: # determines if user input is less than or equal to 10
print(f"Your guess was {guess == num}, the secret number was {num}") # tells user if guess was correct and the value of the secret number
for i in range(num): # prints numers up to but not equal to num
print(i)
response = input("Play again? ") # asks user if they want to play again
if response == "y" or response == "yes" or response == "Yes" or response == "yes" or response == "YES": # accepted user responses
continue # continue through while loop
else:
break # breaks while loop
else:
print("Your number was not between 1 and 10") # tells user that number was not between 1 and 10
else:
print("Invalid type") # tells user that input was invalid
else:
print("Your number was not between 1 and 10") # tells user that number was not between 1 and 10
else:
print("Invalid type") # tells user that input was invalid
for i in range (1,11): # prints numbers 1 - 10
print(i)
for i in "abc": # prints letters a - c
print(i)
#______________________________________________________________________________________________________________________________________________________________________________#
| true |
5b0b217cb0b2b4ef16066e9f2eb722347a7445ba | emjwalter/cfg_python | /102_lists.py | 1,058 | 4.625 | 5 | # Lists!
# Define a list with cool things inside!
# Examples: Christmas list, things you would buy with the lottery
# It must have 5 items
# Complete the sentence:
# Lists are organized using: ___variables____?????
# Print the lists and check its type
dreams = ['mansion', 'horses', 'Mercedes', 'flowers', 'perfume']
print(dreams)
print(type(dreams))
# Print the list's first object
print(dreams[0])
# Print the list's second object
print(dreams[1])
# Print the list's last object ### remember to include -1 at the end to find the last value in the list
print(dreams[len(dreams)-1])
# Re-define the first item on the list and
dreams[0] = 'chateau'
print(dreams)
# Re-define another item on the list and print all the list
dreams[2]= 'BMW'
print(dreams)
# Add an item to the list and print the list
dreams.append('husband')
print(dreams)
# Remove an item from the list and print the list
dreams.remove('horses')
print(dreams)
# Add two items to list and print the list
dreams.append('kitten')
dreams.append('garden')
print(dreams) | true |
4cd98053e49db7a5422d7ec0c410325f228dd5d2 | emjwalter/cfg_python | /104_list_iterations.py | 707 | 4.34375 | 4 | # Define a list with 10 names!
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda']
# use a for loop to print out all the names in the following format:
# 1 - Welcome Angelo
# 2 - Welcome Monica
# (....)
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda']
count = 0 ## note to self: put the count before the block of code ##
edit_r_list = []
for name in register:
# print(name)
# print(count)
print(str(count) + ' - Welcome ' + name)
edit_r_list.append(str(count) + ' - ' + name)
count = count + 1
# optional
print(edit_r_list)
# Sweet! Now do the same using a While loop
| true |
ee9422e8c3398f0fae73489f6079517f2d3396b5 | scress78/Module7 | /basic_list.py | 718 | 4.125 | 4 | """
Program: basic_list.py
Author: Spencer Cress
Date: 06/20/2020
This program contains two functions that build a list for Basic List Assignment
"""
def get_input():
"""
:returns: returns a string
"""
x = input("Please input a number: ")
return x
def make_list():
"""
:returns: a list of numbers
:raises ValueError: returned given non-numeric input
"""
number_list = []
for n in range(1, 4):
x = get_input()
try:
x = int(x)
number_list.append(x)
except ValueError:
print("Invalid Entry, please input a number")
return number_list
if __name__ == '__main__':
make_list()
| true |
0ae7ca84c21ffaa630af8f0080f2653615758866 | VertikaD/Algorithms | /Easy/highest_frequency_char.py | 974 | 4.4375 | 4 | def highest_frequency_char(string):
char_frequency = {}
for char in string:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
sorted_string = sorted(char_frequency.items(),
key=lambda keyvalue: keyvalue[1], reverse=True)
print('Frequencies of all characters:', '\n', sorted_string)
character = [] # defining empty list
for t in sorted_string: # iterating over the sorted string to get each tuple
# the first index[0] of each tuple i.e the characters is added in the list :character
character.append(t[0])
return character[0]
highest_frequency = highest_frequency_char(
'Program to find most repeated character')
print('Most repeated character in the text is : ',
'\n', '|', highest_frequency, '|') # vertical bar is used in case space came out to be the character with highest frequency
| true |
30c2f43d22e30ade58e703b3ac64176db33a3cbf | juancarlosqr/datascience | /python/udemy_machine_learning/02_simple_linear_regression/01_simple_linear_regression.py | 2,083 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 13:49:10 2018
@author: jc
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# data preprocessing
# import dataset
dataset = pd.read_csv('salary_data.csv')
x = dataset.iloc[:, :-1].values
dependant_column_index = 1
y = dataset.iloc[:, dependant_column_index].values
# splitting dataset into training and test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1/3, random_state=0)
# for simple linear regression, the library takes care of the feature scaling
# feature scaling
'''
from sklearn.preprocessing import StandardScaler
x_sc = StandardScaler()
x_train = x_sc.fit_transform(x_train)
x_test = x_sc.transform(x_test)
'''
# fitting simple linear regression to the training sets (x_train, y_train)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
# here the model is created, the model already learned from the data
# in terms of machine learning, that is "machine" equals to the
# simple linear regression model and the "learning" process is when
# this model learned using the data provided to the fit method
regressor.fit(x_train, y_train)
# predicting values with test set (x_test)
y_pred = regressor.predict(x_test)
# visualizing the results
# plotting observation values
plt.scatter(x_train, y_train, color='red')
# plotting the regression line
# we use x_train in the predict method because we want
# to plotthe predictions for the training set
plt.plot(x_train, regressor.predict(x_train), color='green')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
# plotting test values (prediction)
plt.scatter(x_test, y_test, color='red')
# we can keep the same values here because will result
# in the same model, the same line
plt.plot(x_train, regressor.predict(x_train), color='green')
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
| true |
22ebee6a673d7af7cc1a34744d4efeaa07e5c92b | lukasz-lesiuk/algo-workshop | /algo-workshop.py | 729 | 4.40625 | 4 | def get_even_numbers(x, stop, z):
"""
Returns a list containing first 'x' even elements lower than 'stop'.
Those elements must be divisible by 'z'.
"""
raw_list = []
for i in range(1,(stop//2)):
raw_list.append(2*i)
# print(raw_list)
list_sorted = []
for element in raw_list:
if element%z != 0:
list_sorted.append(element)
# print(list_sorted)
for i in range(x):
print(list_sorted[i])
def get_sum_of_greatest_elements(my_list, x):
"""
Returns a single integer, which is a sum of 'x' biggest elements from 'my_list'
i.e. Returns a sum of 3 biggest elements from [2, 18, 5, -11, 7, 6, 9]
"""
pass
get_even_numbers(2, 15, 10) | true |
71c4b61ee65ceb5042908accca49af509fc43210 | cyr1z/python_education | /python_lessons/02_python_homework_exercises/ex_03_lists.py | 1,208 | 4.34375 | 4 | """
Exercise: https://www.learnpython.org/en/Lists
In this exercise, you will need to add numbers and strings
to the correct lists using the "append" list method. You must add
the numbers 1,2, and 3 to the "numbers" list, and the words 'hello'
and 'world' to the strings variable.
You will also have to fill in the variable second_name with the
second name in the names list, using the brackets operator [].
Note that the index is zero-based, so if you want to access
the second item in the list, its index will be 1.
"""
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# write your code here
# the variable second_name with the second name in the names list
SECOND_NAME = names[1]
# add the numbers 1,2, and 3 to the "numbers" list
# using the "append" list method
for i in range(1, 4):
numbers.append(i)
# add the words 'hello' and 'world' to the strings variable
strings.append("hello")
strings.append("world")
if __name__ == "__main__":
# this code should write out the filled arrays and the second
# name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % SECOND_NAME)
| true |
8b9d35551a9f5b123a30c3e63ddf7f637eec279a | collins73/python-practice-code | /app.py | 823 | 4.21875 | 4 | # A simple program that uses loops, list objects, function , and conditional statements
# Pass in key word arguments into the function definition my_name
def my_name(first_name='Albert', last_name='Einstein', age=46):
return 'Hello World, my name is: {} {}, and I am {} years old'.format(first_name,last_name, age)
print(my_name('Henry', 'Ford', 96))
my_list = [1,2,3,4,5, "python", 43.98, "fish", True]
my_list2 = ['grapes', 'oranges','Aegis', 100]
new_list = my_list + my_list2
for letter in new_list:
print(new_list)
#check if the correct interger and string text is in the list
if 20 in new_list and "python" in new_list:
print("That is correct, this is the best programming langauge in the world!")
else:
print("Please chose the correct string or interger value!")
| true |
9ef773c250dab6e409f956fb10844b1e3a22015f | Zakaria9494/python | /learn/tuple.py | 804 | 4.25 | 4 | #A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets.
thistuple = ("apple", "banana",
"cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[1])
# negative Indexing
#Print the last item of the tuple:
print(thistuple[-1])
#range of index
#Return the third, fourth, and fifth item:
print(thistuple[2:5])
#Range of Negative Indexes
#This example returns the items from index -4
# (included) to index -1 (excluded)
print(thistuple[-4:-1])
'''
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns
the position of where it was found
''' | true |
89d56e31f80950b8003903c7d20044b62d56a72a | eventuallyrises/Python | /CW_find_the_next_perfect_square.py | 821 | 4.15625 | 4 | #we need sqrt() so we import the build in math module
import math
#we start the function off taking in the square passed to it
def find_next_square(sq):
#for later we set up the number one higher than the passed square
wsk=sq+1
# Return the next square if sq is a square, -1 otherwise
#here we look to see if the passed number is a perfect square, if it is we look for the next one
if math.sqrt(sq)%1==0:
print("A Perfect Square! the next one is: ")
#here we are looking for the next one by taking the current one incrementing by one and checking for perfection
#im using a modulus on 1 of greater than 0 to check for perfection
while math.sqrt(wsk)%1>0:
wsk=wsk+1
return(wsk)
else:
return -1
#121->144
print(find_next_square(121)) | true |
d0e40a83f302dc6a0117634b7224494dd69ab992 | KuroKousuii/Algorithms | /Prime numbers and prime factorization/Segmented Sieve/Simple sieve.py | 832 | 4.15625 | 4 | # This functions finds all primes smaller than 'limit'
# using simple sieve of eratosthenes.
def simpleSieve(limit):
# Create a boolean array "mark[0..limit-1]" and
# initialize all entries of it as true. A value
# in mark[p] will finally be false if 'p' is Not
# a prime, else true.
mark = [True for i in range(limit)]
# One by one traverse all numbers so that their
# multiples can be marked as composite.
for p in range(p * p, limit - 1, 1):
# If p is not changed, then it is a prime
if (mark[p] == True):
# Update all multiples of p
for i in range(p * p, limit - 1, p):
mark[i] = False
# Print all prime numbers and store them in prime
for p in range(2, limit - 1, 1):
if (mark[p] == True):
print(p, end=" ") | true |
862b61d7ff0c079159910d20570041da0d4747a3 | jasimrashid/cs-module-project-hash-tables | /applications/word_count/word_count_one_pass.py | 2,043 | 4.21875 | 4 | def word_count(s):
wc = {}
# without splitting string
beg = 0
c = ''
word = ''
word_count = {}
for i,c in enumerate(s):
# if character is end of line, then add the word to the dictionary
if i == len(s)-1: #edge case what if there is a space at the end of line or special characters
word += c.lower() if c not in [":",";",",", ".", "-", "+", "=", "/", "|", "[","]", "{", "}", "(", ")", "*", "^", "&",'"'] else c
if word not in word_count:
word_count[word] = 1
word = ''
else:
word_count[word] += 1
word = ''
# if character is a whitespace, then add the word(concatenation of previous characters) to the dictionary
elif c == ' ':
if word not in word_count:
word_count[word] = 1
word = ''
else:
word_count[word] += 1
word = '' #reset word
# if character is: " : ; , . - + = / \ | [ ] { } ( ) * ^ &, skip it
elif c in [":",";",",", ".", "-", "+", "=", "/", "|", "[","]", "{", "}", "(", ")", "*", "^", "&",'"']: # \ and quotes are special special cases
continue #this skips character
else: #when character is part of word
word += c.lower()
print(i, c, word)
return word_count
# edge cases
# case 1: space in begninning / end "padding"
# case 2: weird special characters
# case 3: separate words with only punctuation in between but no spaces
# case 4: two spaces
if __name__ == "__main__":
print(word_count('hello'))
print(word_count('hello world hello'))
print(word_count(' hello world'))
print(word_count(' hello, world a '))
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.'))
print(word_count('Hello hello')) | true |
f5812e58373f52e38f8efa72d8e4a6627526f194 | prateek951/AI-Workshop-DTU-2K18 | /Session1/demo.py | 1,816 | 4.75 | 5 | # @desc Working with Numpy
import numpy as np
# Creating the array using numpy
myarray = np.array([12,2,2,2,2,2])
print(myarray)
# The type of the array is np.ndarray whereas in python it would be list class
print(type(myarray))
# To print the order of the matrix
print(myarray.ndim)
# To print the shape of the array
print(myarray.shape)
# To print a specific element of the array
print(myarray[0])
# To print the last element of the array
# 2 ways of printing the last element of the array
print(myarray[len(myarray) - 1]);
print(myarray[-1])
# Specific methods on the array that we can use
# type(myarray) returns the type of the array
# myarray.ndim returns the dimensions of the array
# myarray.itemsize returns the size of the datatype that we have used for the array
# myarray.size returns the size of the array
# myarray.dtype returns the datatype of the array
# For defining the 2 dimensional arraty using numpy
myarray_2d = np.array([[13132,32,323,23,23],[32,32,32,323,2]]);
print(myarray_2d)
print(myarray_2d.shape)
# Printing the dimensions of the array
print(myarray_2d.ndim)
print(len(myarray_2d))
# Negative index in numpy
newarray = np.array([1,23132,12,122,1])
print(newarray[-1])
print(newarray[-2])
# Slicing in the array
# Using the colon
# myarray[:] : means all the elements
print(newarray[:])
# Extracting the particular slice of the array
print(newarray[1:3])
print(newarray[:-2])
#End of the splitting portion
# To reverse the list of all the elements
array_new = [13,123,132,121,2]
print(array_new[::-1])
# Numpy functions to create arrays
# To create the array of zeroes using numpy
# np.zeroes()
# To create an array of ones using numpy
# np.ones()
# To create the identity matrix using numpy
# np.eye(4) to create a 4 dimensional identity matrix using numpy
| true |
58558f014aa28b29b9e2ad662cd783ff524bd220 | prateek951/AI-Workshop-DTU-2K18 | /Session-5 Working on Various Python Library/numpyops.py | 2,447 | 4.375 | 4 | my_list = [1,2,3]
# Importing the numpy library
import numpy as np
arr = np.array(my_list)
arr
# Working with matrices
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
np.array(my_matrix)
# Create an array
np.arange(0,10)
# Create an array keeping the step size as 2
np.arange(0,10,2)
# Arrays of zeros
np.zeros(3)
# Array of zeros (3 rows and 3 columns)
np.zeros((3,3))
# Array of ones
np.ones(3)
# Array of ones(3 rows and 3 columns)
np.ones((3,2))
# Linspace returns an evenly spaced numbers over a specified interval
np.linspace(0,5,10)
# Create an identity matrix
np.eye(4)
# Create an array of random numbers from a uniform distribution from 0 to 1
np.random.rand(5)
# Same thing but from a Normal Distibution centered around 0
np.random.randn(2)
np.random.randn(2,2)
np.random.randint(1,100,10)
arr = np.arange(25)
arr
ranarr = np.random.randint(0,50,10)
ranarr
# Reshape method to get the same data but in new shape
arr.reshape(5,5)
# Finding the maximum element in the array
ranarr.max()
# Finding the index location of the maximum element in the array
ranarr.argmax()
# Finding the index location of the minimum element
ranarr.argmin()
# Print the shape of vector
arr.shape
# Reshape the vector to a 5,5
arr.reshape(5,5)
arr.shape
# Print the datatyoe of the array
arr.dtype
from numpy.random import randint
randint(2,10)
# Indexing and Selection in Numpy array
newarr = np.arange(0,11)
newarr
newarr[8]
# Performing slicing to get the slice of an array
newarr[1:5]
newarr[0:5]
newarr[:6]
newarr[5:]
newarr[0:5] = 100
newarr
newarr = np.arange(0,11)
newarr
# Creating the slice of an array
slice_of_arr = arr[0:6]
slice_of_arr[:] = 99
slice_of_arr
# To create a copy of elements we can use the copy method
arr_copy = arr.copy()
arr
arr_copy[:] = 100
arr
# Indexing of a two dimensional array
arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]])
arr_2d
# Double bracket format
# Element in the first row and the first column
arr_2d[0][0]
# Using the single bracket format
arr_2d[1,1]
arr_2d[1,2]
arr_2d[2,1]
arr_2d[:2,1:]
# grab the first two rows
arr_2d[:2]
arr_2d[1:2]
# Conditional Selection
arr = np.arange(0,11)
arr
# This will give us a boolean vector
bool_arr = arr > 5
arr[bool_arr]
arr[arr>5]
arr[arr<3]
arr_2dim = np.arange(0,50).reshape(5,10)
arr_2dim
#Create the copy of the two dimensional array
arr_2dim_copy = arr_2dim.copy()
arr_2dim_copy
arr_2dim[2,1:5]
arr_2dim[1,3:5]
arr_2dim[2,3:5] | true |
e4db9a855ebaf188c4190ec4c564a0c46a3c573f | abhiis/python-learning | /basics/carGame.py | 889 | 4.15625 | 4 | command = ""
is_started = False
is_stopped = False
help = '''
start: To start the car
stop: To stop the car
quit: To exit game
'''
print("Welcome to Car Game")
print("Type help to read instructions\n")
while True: #command != "quit": if we write this condition, last else block always gets executed
command = input("> ").lower()
if command == "help":
print(help)
elif command == "start":
if not is_started:
print("Car Started")
is_started = True
else:
print("Already Started!")
elif command == "stop":
if not is_stopped and is_started:
print("Car Stopped")
is_stopped = True
else:
print("Already Stopped!")
elif command == "quit":
print("Bye")
break #this is loop control
else:
print("Sorry, I don't understand...Try Again")
| true |
409e94361c99c3833dcc7990a2593b3ee5b10f10 | amolgadge663/LetsUpgradePythonBasics | /Day7/D7Q1.py | 393 | 4.1875 | 4 | #
#Question 1 :
#Use the dictionary,
#port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"},
#and make a new dictionary in which keys become values and values become keys,
# as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80}
#
port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}
print(port1)
port1 = {value:key for key, value in port1.items()}
print(port1) | true |
59125fe5d98160896e811a9be0cf6421a73e711c | DRCurado/Solids_properties | /Circle.py | 744 | 4.21875 | 4 | #Circle shape
#Calculate the CG of a circle.
import math
#insert the inuts of your shape:
unit = "mm"
#insert the dimensions of your shape:
diameter = 100;
#Software do the calculations
Area = math.pi*(diameter/2)**2;
Cgx = diameter/2;
Cgy = diameter/2;
Ix= (math.pi*diameter**4)/64;
Iy= (math.pi*diameter**4)/64;
#Software print the results:
print("");
print(" ");
print("Welcome to the Circle Properties Calculator");
print("-----------------");
print("Area: "+str(Area)+unit+"^2");
print("-----------------");
print("CGx: "+str(Cgx)+unit);
print("CGy: "+str(Cgy)+unit);
print("-----------------");
print("Moment of inertia:");
print("X axix: "+str(Ix)+unit+"^4");
print("Y axix: "+str(Iy)+unit+"^4");
| true |
45e20efd919cb4ab2fc2b6b03449a8066b8f4f2a | alphaolomi/cryptography-algorithms | /transposition_encryption.py | 1,122 | 4.1875 | 4 | # Transposition Cipher Encryption
def main():
my_message = 'Common sense is not so common.'
my_key = 8
cipher_text = encrypt_message(my_key, my_message)
# Print the encrypted string in cipher_text to the screen, with
# a | (called "pipe" character) after it in case there are spaces at
# the end of the encrypted message.
print(cipher_text + '|')
def encrypt_message(key, message):
# Each string in cipher_text represents a column in the grid.
cipher_text = [''] * key
# Loop through each column in cipher_text.
for col in range(key):
pointer = col
# Keep looping until pointer goes past the length of the message.
while pointer < len(message): # Place the character at pointer in message at the end of the
# current column in the cipher_text list.
cipher_text[col] += message[pointer]
# move pointer over
pointer += key
# Convert the cipher_text list into a single string value and return it.
return ''.join(cipher_text)
# the main() function.
if __name__ == '__main__':
main()
| true |
ca827f71d84324d576adac8192f0391af29a457c | rragundez/utility-functions | /ufuncs/random.py | 699 | 4.1875 | 4 |
def generate_random_string(length, *, start_with=None,
chars=string.ascii_lowercase + string.digits):
"""Generate random string of numbers and lowercase letters.
Args:
length (int): Number of characters to be generated randomly.
start_with (str): Optional string to start the output with.
chars: Types of characters to choose from.
Returns:
str: Randomly generated string with optional starting string.
"""
if start_with:
start_with = '_'.join([start_with, '_'])
else:
start_with = ''
rand_str = ''.join(random.choice(chars) for _ in range(length))
return ''.join([start_with, rand_str])
| true |
c10cb232f6c7b665dbf7fe0b672a8034dd97b6af | lukeitty/problemset0 | /ps0.py | 2,630 | 4.25 | 4 | #Author: Luke Ittycheria
#Date: 3/28/16
#Program: Problem Set 0 Functions
#Function 0
def is_even(number):
'''Returns a value if the number is even or odd'''
if number == 0:
return True
if number % 2 == 0:
return True
else:
return False
return evenOrOdd
###########################################################################
#Function 1
def num_digits(y):
'''Calculates the amount of digits in a given number'''
if y == 0:
count = 1
return count
count = 0
while y > 0:
if y == 0:
count += 1
count += 1
y = y/10
return count
###########################################################################
#Function 2
def sum_digits(n):
'''Calculates the sum of the digits in a given number'''
if n == 0:
return n
s = 0
while n:
s += n % 10
n //= 10
return s
###########################################################################
#Function 3
def sum_less_ints(num):
'''Calculates the sum of all the numbers below the given number'''
if num == 0:
sum = 0
return sum
num = num - 1
sum = 0
while(num > 0):
sum += num
num -= 1
return sum
###########################################################################
#Function 4
def factorial(z):
'''Finds the factorial of a given number'''
if z == 0:
numero = 1
return numero
numero = 1
while z >= 1:
numero = numero * z
z = z - 1
return numero
############################################################################
#Function 5
def factor(baseNum,factor2):
'''Takes two positive integers and sees if the second number is a factor of the first'''
if baseNum % factor2 == 0:
return True
else:
return False
############################################################################
#Function 6
def primeNum(primeNum):
'''Determines whether a number is prime or not (must be greater than 2)'''
if primeNum == 2:
return True
for i in range(3, primeNum):
if primeNum % i == 0:
return False
return True
############################################################################
#Function 7
def isperfect(n):
'''Determines whether a number is perfect of not'''
sum = 0
for x in xrange(1, n):
if n % x == 0:
sum += x
return sum == n
############################################################################
#Function 8
def sumfactor(n):
'''Takes the sum of the numbers digits and determines if it is a factor of the original number'''
sum = sum_digits(n)
factorNum = factor(n, sum)
return factorNum
###########################################################################
| true |
39b91946afdb07d27c8314405268e89e842c8840 | benichka/PythonWork | /favorite_languages.py | 707 | 4.40625 | 4 | favorite_languages = {
'Sara' : 'C',
'Jen' : 'Python',
'Ben' : 'C#',
'Jean-Claude' : 'Ruby',
'Jean-Louis' : 'C#',
}
for name, language in favorite_languages.items():
print(name + "'s favorite language is " + language + ".")
# Only for the keys:
print()
for k in favorite_languages.keys():
print(k.title())
# It can be combined with other function:
print()
for k in sorted(favorite_languages.keys()):
print(k.title())
# It also works with values:
print()
for v in favorite_languages.values():
print(v.title())
# To avoid duplicate, we transform the list into a set:
print()
for v in set(favorite_languages.values()):
print(v.title())
| true |
618e1fdc6d658d3fc80cff91737e74f6f8fc30a6 | benichka/PythonWork | /chapter_10/common_words.py | 553 | 4.25 | 4 | # Take a file and count occurences of a specific text in it.
text_file = input("Choose a text file from which to count occurences of a text: ")
occurence = input("What text do you want to count in the file?: ")
try:
with open(text_file, 'r', encoding="utf-8") as tf:
contents = tf.read()
except:
print("Error trying to read the file.")
else:
occurence_count = contents.lower().count(occurence)
print("There are " + str(occurence_count) + " occurences of the word "
+ occurence + " in the file " + text_file + ".")
| true |
d8947556c73c79505c31eb54718aecb20f1b1c2b | benichka/PythonWork | /chapter_10/addition.py | 787 | 4.28125 | 4 | # Simple program to add two numbers, with exception handling.
print("Input 2 numbers and I'll add them.")
while (True):
print("\nInput 'q' to exit.")
number_1 = input("\nNumber 1: ")
if (number_1 == 'q'):
break
try:
number_1 = int(number_1)
except ValueError:
print("\nOnly number are accepted.")
continue
number_2 = input("\nNumber 2: ")
if (number_2 == 'q'):
break
try:
number_2 = int(number_2)
except ValueError:
print("\nOnly number are accepted.")
continue
try:
result = number_1 + number_2
except:
print("\nError while adding " + number_1 + " and " + number_2 + ".")
else:
print(str(number_1) + " + " + str(number_2) + " = " + str(result))
| true |
8e0f68898778383bcc958dcade2b9f06910d1b61 | ndpark/PythonScripts | /dogs.py | 949 | 4.21875 | 4 | #range(len(list)) can be used to iterate through lists
dogs = []
while True:
name = input('Dog name for dog # ' + str(len(dogs)+1) + '\nType in empty space to exit\n>>')
dogs = dogs + [name] #Making a new list called name, and then adding it to dogs list
if name == ' ':
break
print ('The dog names are:')
for name in dogs:
print('The name is ' + name)
"""for i in range(len(list))
print ('blah' + str(i) + 'blah' + list[i])
If you think about it it makes sense because
'in' and 'not in' can be written to check if something is in an array , similar to search
something.index() can search which value that is passed
example: spam = ['hello','google','dog','cat']
spam.index('hello')
0
etc
spam.insert(1,'dog') will insert the index into the array
sort() works --(reverse==True) to make it go reverse. Must all be the same type.
remove() removes an element
list is mutable; string is not.
tuples are same as lists except immutble | true |
8ade98a9e878e8ba1790be5e225372d9482b6cbb | ndpark/PythonScripts | /backupToZip.py | 859 | 4.21875 | 4 | #! python3
# backupToZip.py - Copies entire folder and its content into a zip file, increments filename
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) #Folder must be absolute
#Figures out what the filename should be
number = 1
while True:
zipFilename = os.path.basename(folder) + '_'+ str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number +1
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in%s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
newBase/ os.path.basename(folder)+'_'
if filename.startswith(newBase) and filename.endswith('.zip')
continue
backupToZip.write(os.path.join(foldername,filename))
backupZip.close()
print('Done')
fileDir = input('Please insert filename')
backupToZip(fileDir) | true |
632a672805914b130a2de77eff69cc66af77c25c | rhitik26/python1 | /python assignments/day4b.py | 471 | 4.125 | 4 | def outer(a):
def inner():
print("this is inner!")
print(type(a))
a()
print("Inner finished execution!")
return inner
@outer #By adding this annotation the function will automatically become wrapper function(the concept is Decorator)
def hello():
print("hello World!")
@outer
def sayhi():
print("hi world!")
#demo1=outer(hello) # function hello is the wrapper function of sayhi,
#demo2=outer(sayhi)
hello()
sayhi()
| true |
13d7ab468faf1f3342bf8f221ca36e51437b131d | bloomsarah/Practicals | /prac_04/lottery_ticket_generator.py | 778 | 4.1875 | 4 | """
Generate program that asks for number of quick picks
print that number of lines, with 6 numbers per line
numbers must be sorted and between 1 and 45
"""
import random
NUMBERS_PER_LINE = 6
MIN = 1
MAX = 45
def main():
number_of_picks = int(input("Enter number of picks: "))
while number_of_picks < 0:
print("Invalid number of picks.")
number_of_picks = int(input("Enter number of picks: "))
for i in range(number_of_picks):
pick = []
for j in range(NUMBERS_PER_LINE):
number = random.randint(MIN, MAX)
while number in pick:
number = random.randint(MIN, MAX)
pick.append(number)
pick.sort()
print(" ".join("{:2}".format(number) for number in pick))
main()
| true |
a4fe0d90b2772844969b34ce6ffa103c294ddfa1 | timeeeee/project-euler | /4-largest-palindrome-product/main.py | 358 | 4.15625 | 4 | # Find the largest palindrome that is the product of 2 3-digit numbers.
def isPalindrome(x):
string = str(x)
return "".join(reversed(string)) == string
maximum = 0;
for a in range(111, 1000):
for b in range(111, 1000):
product = a * b
if isPalindrome(product) and product > maximum:
maximum = product
print maximum
| true |
206deca44b6fa1c1147d3c6d698d92ea2aee44ed | timeeeee/project-euler | /62-cubic-permutations/slow.py | 1,720 | 4.15625 | 4 | """
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
"""
from itertools import permutations
class Cubes:
def __init__(self):
self.c = 1
self.cubes = set()
self.max_cube = 0
def add_cube(self):
new_cube = self.c ** 3
self.cubes.add(new_cube)
self.max_cube = new_cube
self.c += 1
def is_cube(self, n):
while self.max_cube < n:
self.add_cube()
return n in self.cubes
CUBE_COUNTER = Cubes()
def test_cubes():
c = Cubes()
tested_cubes = set()
for x in range(1, 100):
assert(c.is_cube(x**3))
tested_cubes.add(x**3)
for x in range(10000):
if x not in tested_cubes:
assert(not(c.is_cube(x)))
def cubic_permutations(n, number):
count = 0
counted_so_far = set()
for permutation in permutations(str(n)):
p = int("".join(permutation))
if p > n and CUBE_COUNTER.is_cube(p) and p not in counted_so_far:
print "permutation of {} {} is cube".format(n, p)
counted_so_far.add(p)
count += 1
if count == number:
return True
return False
def find_cubic_permutations(start_base, number):
while True:
n = start_base ** 3
if cubic_permutations(n, number):
return n
start_base += 1
def main():
print find_cubic_permutations(340, 5)
if __name__ == "__main__":
main()
| true |
319e95ee89071a5402aaa30aac4f77e2f34a9168 | mkuentzler/AlgorithmsCourse | /LinkedList.py | 771 | 4.1875 | 4 | class Node:
"""
Implements a linked list. Cargo is the first entry of the list,
nextelem is a linked list.
"""
def __init__(self, cargo=None, nextelem=None):
self.car = cargo
self.nxt = nextelem
def __str__(self):
return str(self.car)
def display(self):
if self.car:
print str(self)
if self.nxt:
self.nxt.display()
def next(self):
return self.nxt
def value(self):
return self.car
def reverse(unrev, rev=None):
"""
Reverses a linked list.
"""
if unrev:
return reverse(unrev.next(), Node(unrev.value(), rev))
else:
return rev
B = Node(3)
C = Node(2, B)
A = Node(1, C)
A.display()
print
D = reverse(A)
D.display() | true |
43a5d6ca3431c87af401db8ceda677bca0a1a52e | AjsonZ/E01a-Control-Structues | /main10.py | 2,365 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange','yellow','green','blue','violet','purple'] # make a list of color
play_again = '' # make "play again" empty
best_count = sys.maxsize # the biggest number
while (play_again != 'n' and play_again != 'no'): #start a while loop with two conditions
match_color = random.choice(colors) # using random method to select a color randomly
count = 0 # count strat with 0
color = '' # make color empty
while (color != match_color):
color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line
color = color.lower().strip() # It turns all letters on 'color' into the lower case and delete all the spaces.
count += 1 # the 'count' will plus one after finishing a loop
if (color == match_color): # if color equals to match_color, it will execute the following codes
print('Correct!') # when condition is true, it will print out 'Correct!'
else: # if false
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) # if false, it will print out this line.
print('\nYou guessed it in {0} tries!'.format(count)) # print out this line in the next line with the number of user's tries
if (count < best_count): # if user's tries are less than best_count which is the biggest number
print('This was your best guess so far!') # it will print out this line
best_count = count # let best_count = count
play_again = input("\nWould you like to play again? ").lower().strip() # print this out on the next line and delete all spaces and turn it into lower case.
print('Thanks for playing!') # print out 'Thanks for playing.' | true |
9ebc5c4273361512bd5828dee90938820b41f097 | Andrew-2609/pythonbasico_solyd | /pythonbasico/aula11-tratamento-de-erros.py | 872 | 4.21875 | 4 | def is_a_number(number):
try:
int(number)
return True
except ValueError:
print("Only numbers are allowed. Please, try again!")
return False
print("#" * 15, "Beginning", "#" * 15)
result = 0
divisor = input("\nPlease, type an integer divisor: ")
while not is_a_number(divisor):
divisor = input("Please, type an integer divisor: ")
divisor = int(divisor)
print("\n" + "#" * 7, "Middle", "#" * 7)
dividend = input("Please, type an integer dividend: ")
while not is_a_number(dividend):
dividend = input("Type an integer dividend: ")
dividend = int(dividend)
print("\n" + "#" * 7, "Result", "#" * 7)
try:
result = divisor / dividend
print(f"The division result is {round(result, 2)}")
except ZeroDivisionError as zeroDivisionError:
print("Cannot divide by 0 :(")
print("\n" + "#" * 15, "Ending", "#" * 15)
| true |
bdc98a6f01d7d4a9663fd075ace95def2f25d35c | BipronathSaha99/GameDevelopment | /CurrencyConverter/currencyConverter.py | 608 | 4.34375 | 4 | # >>-----------CurrencyConverter-------------------<<
#To open currency list from text file .
with open("currency.txt") as file:
lines=file.readlines()
#to collect all information create a dictionary
currencyDic={}
for line in lines:
bipro=line.split("\t")
currencyDic[bipro[0]]=bipro[1]
amount=int(input("Enter your amouunt="))
print("Enter your currency name that you want. Available optiions are:")
[print(i) for i in currencyDic.keys()]
currency=input("Enter the currency name =")
print(f"{amount} BDT = {amount*float(currencyDic[bipro[0]]):0.5f} {currency}")
| true |
163d79e904d442ee971f10f698b79a7ee7bf85fa | micahjonas/python-2048-ai | /game.py | 2,514 | 4.3125 | 4 | # -*- coding: UTF-8 -*-
import random
def merge_right(b):
"""
Merge the board right
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_right(test)
[[0, 0, 2, 8], [0, 2, 4, 8], [0, 0, 0, 4], [0, 0, 4, 4]]
"""
def reverse(x):
return list(reversed(x))
t = map(reverse, b)
return [reverse(x) for x in merge_left(t)]
def merge_up(b):
"""
Merge the board upward. Note that zip(*t) is the
transpose of b
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_up(test)
[[2, 4, 8, 4], [0, 2, 2, 8], [0, 0, 0, 4], [0, 0, 0, 2]]
"""
t = merge_left(zip(*b))
return [list(x) for x in zip(*t)]
def merge_down(b):
"""
Merge the board downward. Note that zip(*t) is the
transpose of b
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_down(test)
[[0, 0, 0, 4], [0, 0, 0, 8], [0, 2, 8, 4], [2, 4, 2, 2]]
"""
t = merge_right(zip(*b))
return [list(x) for x in zip(*t)]
def merge_left(b):
"""
Merge the board left
Args: b (list) two dimensional board to merge
Returns: list
"""
def merge(row, acc):
"""
Recursive helper for merge_left. If we're finished with the list,
nothing to do; return the accumulator. Otherwise, if we have
more than one element, combine results of first from the left with right if
they match. If there's only one element, no merge exists and we can just
add it to the accumulator.
Args:
row (list) row in b we're trying to merge
acc (list) current working merged row
Returns: list
"""
if not row:
return acc
x = row[0]
if len(row) == 1:
return acc + [x]
return merge(row[2:], acc + [2*x]) if x == row[1] else merge(row[1:], acc + [x])
board = []
for row in b:
merged = merge([x for x in row if x != 0], [])
merged = merged + [0]*(len(row)-len(merged))
board.append(merged)
return board
def move_exists(b):
"""
Check whether or not a move exists on the board
Args: b (list) two dimensional board to merge
Returns: list
>>> b = [[1, 2, 3, 4], [5, 6, 7, 8]]
>>> move_exists(b)
False
>>> move_exists(test)
True
"""
for row in b:
for x, y in zip(row[:-1], row[1:]):
if x == y or x == 0 or y == 0:
return True
return False
| true |
f6422f0594441635eac2fd372428aa160ca3bbb3 | HamPUG/meetings | /2017/2017-05-08/ldo-generators-coroutines-asyncio/yield_expression | 1,190 | 4.53125 | 5 | #!/usr/bin/python3
#+
# Example of using “yield” in an expression.
#-
def generator1() :
# failed attempt to produce a generator that yields an output
# sequence one step behind its input.
print("enter generator")
value = "start"
while value != "stop" :
prev_value = value
print("about to give %s" % repr(value))
value = yield value
print("gave %s, got back %s" % (repr(prev_value), repr(value)))
#end while
#end generator1
def generator2() :
# a generator that yields the value that was sent to it on the
# previous yield, so the output sequence is one step behind the
# input sequence.
print("enter generator")
value1 = "start"
value2 = yield None # yield a dummy value from initial “send(None)”
while True :
value3 = yield value1
if value1 == "stop" :
break
value1, value2 = value2, value3
#end while
#end generator2
gen = generator2()
print("generator %s created" % gen.__name__)
for val in (None, "something", "anything", "stop", "onemore", "twomore") :
print("about to send %s" % repr(val))
print("%s => %s" % (val, gen.send(val)))
#end for
| true |
3af6228c9d8dcc735c52ae7d8375f007145ffe98 | MukundhBhushan/micro-workshop | /tectpy/if.py | 235 | 4.15625 | 4 | num=int(input("Enter the number to be tested: "))
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
| true |
f9f0e8f9212598847750967c8898eefed9e441ed | ryotokuro/hackerrank | /interviews/arrays/arrayLeft.py | 900 | 4.375 | 4 | #PROBLEM
# A left rotation operation on an array shifts each of the array's elements unit to the left.
# For example, if left rotations are performed on array , then the array would become .
# Given:
# - an array a of n integers
# - and a number, d
# perform d left rotations on the array.
# Return the updated array to be printed as a single line of space-separated integers.
import os
# Complete the rotLeft function below.
def rotLeft(a, d):
b = list(a)
for i in range(len(a)):
b[i-d] = a[i] # b is considering each element in a and shifting to position -d
return b
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().split()))
result = rotLeft(a, d)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
9af20e6ee68952b2f0b61685ce406d13c770cc00 | ryotokuro/hackerrank | /w36/acidNaming.py | 828 | 4.1875 | 4 | '''
https://www.hackerrank.com/contests/w36/challenges/acid-naming
Conditions for naming an acid:
- If the given input starts with hydro and ends with ic then it is a non-metal acid.
- If the input only ends with ic then it is a polyatomic acid.
- If it does not have either case, then output not an acid.
'''
#!/bin/python3
import sys
def acidNaming(acid_name):
# print(acid_name)
classification = 'not an acid'
if acid_name[:5] == 'hydro' and acid_name[-2:] == 'ic':
classification = 'non-metal acid'
elif acid_name[-2:] == 'ic':
classification = 'polyatomic acid'
return classification
if __name__ == "__main__":
n = int(input().strip())
for a0 in range(n):
acid_name = input().strip()
result = acidNaming(acid_name)
print(result)
| true |
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc | amarjeet-kaloty/Data-Structures-in-Python | /linkedList.py | 1,320 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head = node()
#Insert new node in the Linked-List
def append(self, data):
new_node = node(data)
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
cur_node.next = new_node
#Display the Linked-List
def display(self):
elems = []
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
#Length of the Linked-List
def length(self):
total=0
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
total+=1
return total
#Delete the last node
def delete(self):
if(self.head.next == None):
return None
cur_node = self.head
while(cur_node.next.next != None):
cur_node = cur_node.next
cur_node.next = None
return cur_node
myList = linkedList()
myList.delete()
myList.display()
myList.append(40)
myList.display()
myList.delete()
myList.display()
| true |
e84ebb478878b0eba4403ddca10df99dda752a82 | martinloesethjensen/python-unit-test | /star_sign.py | 960 | 4.125 | 4 | def star_sign(month: int, day: int):
if type(month) == int and month <= 12 and type(day) == int and day <= 32: # todo: test case on .isnumeric()
if month == 1:
if day <= 20:
return "Capricorn"
else:
return "Aquarius"
elif month == 5:
if day <= 21:
return "Taurus"
else:
return "Gemini"
else:
if day <= 21:
return "Sagittarius"
else:
return "Capricorn"
elif type(month) is not int or type(day) is not int: # todo: test case on typeerror
raise TypeError("Month and day must be of type int")
elif 0 <= month > 12 and 0 <= day > 32: # todo: test case on valueerror
raise ValueError("Month can't be negative and over 12.\nDay can't be negative either or over 32.")
return None
if __name__ == '__main__':
print(star_sign(1.0, 6))
| true |
2e99e7a24fa53ad663d8d62ee3b2b59d06cf9f11 | Izzle/learning-and-practice | /Misc/decorators_ex.py | 2,915 | 4.53125 | 5 | """
*************************************************
This function shows why we use decorators.
Decorators simple wrap a fucntion, modifying its behavior.
*************************************************
"""
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
print("Yes!")
else:
print("No!")
some_function()
print("Something is happening after some_function() is called.")
return wrapper
def just_some_function():
print("Whee!")
# Instead of using this syntax we can use
# the @something syntax instead as seen below
just_some_function = my_decorator(just_some_function)
just_some_function()
"""
*************************************************
The function below will do the same thing
but uses the decorator syntax.
*************************************************
"""
import time
def timing_decorator(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run function: " + str ((t2 - t1)) + "\n"
return wrapper
# Far cleaner than our previous examples syntax
@timing_decorator
def my_function():
num_list = []
for num in (range(0, 10000)):
num_list.append(num)
print("\nSum of all the numbers: " + str((sum(num_list))))
print(my_function())
"""
*************************************************
One more real world example of decorators
*************************************************
"""
from time import sleep
def sleep_decorator(function):
"""
Limits how fast the function is
called.
"""
def wrapper(*args, **kwargs):
sleep(2)
return function(*args, **kwargs)
return wrapper
@sleep_decorator
def print_number(num):
return num
print(print_number(222))
for num in range(1, 6):
print(print_number(num))
"""
*************************************************
Combining everything I've learned.
I want to call a decorator instead of a decorator,
but mine only take 0 or 1 parameter.
Since decorators are just wrapppers, I only had to think
about it for a minute. Here is my answer!
Decorators are awesome.
*************************************************
"""
"""
I had tried to use two decorators one after another and it didnt work.
for example:
@timing_decorator
@sleep_decorator
def foobar():
pass
Threw an error because timing_decorator only takes 1 function
as a parameter. Below is my solution.
"""
@timing_decorator # Wraps 1 function
def decorator_inception():
print("\nHello world of decorators!")
print(print_number(1337)) # @sleep_decorator is called by print_number()
# Our time will be over 2 seconds due to @sleep_decorator
# being inside @timing_decorator. Hurray!
print(decorator_inception())
| true |
9fd1d80b44dcea4693cb39f43ddc45a25e654a26 | Izzle/learning-and-practice | /theHardWay/ex6.py | 1,727 | 4.5625 | 5 | # Example 6
# Declares variable for the '2 types of people' joke
types_of_people = 10
# Saves a Format string which inputs the variable to make a joke about binary
x = f"There are {types_of_people} types of people."
# Declaring variables to show how to insert variables into strings.
binary = "binary"
do_not = "don't"
# Saves another Format string which is the punchline of the joke.
y = f"Those who know {binary} and those who {do_not}."
# Prints the joke and the punchline.
print(x)
print(y)
# Prints a format string including the previous variables that contain strings
print(f"I said: {x}")
print(f"I also said: '{y}'")
# Declares a variable 'hilarious' and sets it to the Bool value 'False'
hilarious = False
# A variable that contains a sentence with a parameter to insert a variable
joke_evaluation = "Isn't that joke so funny?! {}"
# Prints the joke and passes the value of 'hilarious' as an argument to the variable 'joke_evalution'
print(joke_evaluation.format(hilarious))
# Sets up two variables, one for the West/Left side and the other for the East/Right side
w = "This is the left side of..."
e = "a string with a right side."
# Prints two strings that form a complete sentence.
print(w + e)
#
# Study Drills
#
# 1) Added comments
# 2) There are only 4 places where a string is inside of a string:
# line 12, 19, and 20.
# 3) Yes there are only 4 places. On line 28 we are passing a 'bool' to
# the string - NOT a string inside a string.
not_a_string = type(hilarious)
print(f"Proof that line 28 is passing a bool: {not_a_string}")
# 4) Adding 'w' and 'e' creates a longer string because in python strings
# can be added together. It does so by concatenating the second string to the first. | true |
5fd329e733441ca67be649f8f604538c6697f6a3 | Izzle/learning-and-practice | /python_programming_net/sendEx05.py | 668 | 4.21875 | 4 | # Exercise 5 and 6
# While and For loops in python 3
# Basic while loop
condition = 1
while condition < 10:
print(condition)
condition += 1
# Basic For loop
exampleList = [1, 5, 6, 5, 8, 8, 6, 7, 5, 309, 23, 1]
for eachNumber in exampleList: # Iterates each item in the list and puts it into the variable 'eachNumber'
print(eachNumber)
print('continue program')
# range() is a built in Python function
# range() will go from the starting number up to the last number
# range() will use up your RAM for every slot. If you need to do range(1,10000000000000000000000)
# do not use range(), use xrange() instead
for x in range(1, 11):
print(x)
| true |
7c3d1f965818058958bb143b72a6f03b2824a8d6 | dimatkach11/Torno_Subito | /base_python/the_dictionary.py | 2,936 | 4.625 | 5 | #
# ! A dictionary is a set of objects which we can extract from a key
# * The keys in question are the one we used in the phase of the assignment
print('\n\t\t\t\t\t\tDICTIONARY\n')
keynote = dict()
keynote['tizio'] = '333-3333333'
keynote['caio'] = '444-4444444'
print(keynote)
# * copy() :
keynote_copy = keynote.copy()
# * keys() : showing all the keys
print('\nShowing all the keys :')
print(keynote.keys())
# * values() : showing all values
print('\nvalues() :')
print(keynote.values())
# * items() : showing all elements, keys and values
print('\nitems() :')
print(keynote.items())
# * extract a single value or raise an exception if the key dosn't exist
print('\nextract a single value : key = "caio"')
print(keynote['caio'])
# * get(key, default value) : allows us to extract a default value if the key is not present or the value of key if it is present
print('\nget("sempronio", 0) :')
print(keynote.get('sempronio', 0))
print(keynote)
print('get("tizio", 0) :')
print(keynote.get('tizio', 0))
# * setdefault(key, default value) : allows us to add the key with default value if the key specified doesn't exist
print('\nsetdefault("sempronio", "555-5555555") :')
print(keynote)
keynote.setdefault('sempronio', '555-5555555')
print(keynote)
# * if we wanna know if a key in a dictionary? we can use "in
print('\nWe wanna khow if the key sempronio is in dictionary :')
print('sempronio' in keynote)
# * del keynote['caio] to eliminate this key from dictionary, if not exist raise an exception
print('\nEliminate key = caio :')
del keynote['caio']
print(keynote)
# * clear() : cancel all the element from the dictionary
keynote.clear()
print(keynote)
# ! Comprehension
print('\ncomprehension : ')
keynote = keynote_copy
print(keynote)
# * example, we use the dictionary comprehension to switch the keys with the value
keynote_switch_keys_with_values = {key: value for value, key in keynote.items()}
print(keynote_switch_keys_with_values)
# * with the repeted values, in the final results, we will have one of the keys without establishing wich one
keynote['sempronio'] = '333-3333333'
print(keynote)
keynote_switch_keys_with_values = {key: value for value, key in keynote.items()}
print(keynote_switch_keys_with_values)
# ! Riassunto
'''
____________________________________________________________________________
keynote['tizio] = '333-3333333'
keynote = {'caio': '333-3333333'}
copy()
keys()
values()
items()
get(key, default value)
setdefault(key, default value)
'tizio' in keynote # true or false, depends if the key is exist or not
del keynote['tizio']
clear()
____________________________________________________________________________
switch the keys with the value
{key: value for value, key in keynote.items()}
with the repeted values, in the final results,
we will have one of the keys without establishing wich one
____________________________________________________________________________
''' | true |
cc0f2bc409cc9d72c792ae38c2b84b353d6bcb3d | ChakshuVerma/Python-SEM-3 | /Question 6/code.py | 1,333 | 4.46875 | 4 |
"""
Q6.Consider a tuplet1 ={1,2,5,7,9,2,4,6,8,10}.
Write a program to perform following operations :
a) Print another tuple whose values are even numbers in the given tuple .
b) Concatenate a tuplet2 = {11,13,15) with t1 .
c) Return maximum and minimum value from this tuple .
"""
ch=0
# Given
len=10
t1=(1,2,5,7,9,2,4,6,8,10)
t2=(11,13,15)
#Function to print a temp tuple with even values from t1
def even():
temp=()
print("Even Values : ")
for i in range(0,len,1):
if(t1[i]%2==0):
temp=temp + (t1[i],)
print(temp)
return
#Function to print maximum and minimum values from t1
def max_min():
Max=t1[0]
Min=t1[0]
for i in range (1,len,1):
if(t1[i]>Max):
Max=t1[i]
print("Max Element Is : ",Max)
for i in range (1,len,1):
if(t1[i]<Min):
Min=t1[i]
print("Min Element Is : ",Min)
return
#Main function
def main():
print("Press")
print("1.Print A Tuple Having Even Values From ",t1)
print("2.Concatenate ",t2," with ",t1)
print("3.Print Maximum And Minimum Values From ",t1)
ch=int(input())
if(ch==1):
even()
elif(ch==2):
temp=t1+t2 #concatenating t1 and t2
print(temp)
elif(ch==3):
max_min()
if __name__=="__main__":
main()
| true |
8c67095e3342ea13f00743a814edd8bd25fc1b2c | AshishGoyal27/Tally-marks-using-python | /tally_marks_using_python.py | 301 | 4.25 | 4 | #Retrieve number form end-user
number = int(input("Input a positive number:"))
#how many blocks of 5 tallies: ||||- to include
quotient = number // 5
#Find out how many tallies are remaining
remainder = number % 5
tallyMarks = "||||- " * quotient + "|" * remainder
print(tallyMarks)
| true |
c9e58aa8af5424e5b96811dd63afa86492c47c48 | lucienne1986/Python-Projects | /pythonRevision.py | 1,692 | 4.40625 | 4 | animals = ['cat', 'dog', 'monkey']
for a in animals:
print(a)
#IF you want access to the index of each element within the body of a loop use enumerate
#enums are constants
#%-style formatting: %s and %r call the Enum class’s __str__() and __repr__() respectively;
#other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type.
for index, a in enumerate(animals):
print('#%d: %s' % (index + 1, a))
#List comprehensions:
#used when we want to transform one type of data into another
nums = [0, 1, 2, 3, 4]
#option 1
print("Option 1")
squares = []
for x in nums:
squares.append(x**2)
print(squares)
#option 2
print("Option 2")
squares2 = [x ** 2 for x in nums]
print(squares2)
#List comprehensions can also contain conditions:
print("With conditionals")
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)
#Dictionaries
#a dictionary stores the key, value pairs
d = {'cat' : ' cute', 'dog' : 'furry'}
print(d['cat'])
print('cat' in d) #checks if dictionary has a given key
d['fish'] = 'wet' #add another entry
print(d)
print(d.get('fish', 'N/A'))# Get an element with a default; prints "wet"
#Loops in dictionaries
d2 = {'person' : 2, 'cat' : 4, 'spider':8}
for animal in d2:
legs = d2[animal]
print('A %s has %d legs' % (animal, legs))
#or using items
for animal, legs in d2.items():
print('A %s has %d legs' % (animal, legs))
#Dictionary comprehensions:
#used when we want to transform one type of data into another
print("Dictionary comprehension")
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
| true |
94ab43281970119ab3ffe8e723539c0866f5f12c | amsun10/LeetCodeOJ | /Algorithm/Python/palindrome-number-9.py | 1,068 | 4.125 | 4 | # https://leetcode.com/problems/palindrome-number/
# Determine whether an integer is a palindrome. An
# integer is a palindrome when it reads the same backward as forward.
#
# Example 1:
#
# Input: 121
# Output: true
# Example 2:
#
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
#
# Input: 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Follow up:
#
# Coud you solve it without converting the integer to a string?
class Solution:
def isPalindrome(self, x: int) -> bool:
str_pal = str(x)
i = 0
j = len(str_pal) - 1
while str_pal[i] == str_pal[j]:
i += 1
j -= 1
if i >= j:
break
else:
return False
return True
if __name__ == '__main__':
solution = Solution()
print(solution.isPalindrome(1))
print(solution.isPalindrome(121))
print(solution.isPalindrome(-121))
| true |
cc7abe19bda1f613b2d070d4a2c5ec4eb722107d | oojo12/algorithms | /sort/insertion_sort.py | 612 | 4.34375 | 4 | def insertion_sort(item, least = False):
"""Implementation of insertion sort"""
"""
Parameters:
item - is assumed to be a list item
least - if true returned order is least to greatest. Else it is greatest to least
"""
__author__ = "Femi"
__version__ = "1"
__status__ = "Done"
for curr in range(len(item)):
for next in range(len(item)):
if (item[curr] <= item[next]):
pass
else:
item[curr],item[next] = item[next], item[curr]
if least:
item.reverse()
else:
pass
return item
| true |
238780e18aa4d804e2c1a07b4a7008719e4d1356 | FaezehAHassani/python_exercises | /syntax_function4.py | 781 | 4.25 | 4 | # Functions for returning something
# defining a few functions:
def add(a, b):
print(f"adding {a} + {b}")
return a + b
def subtract(a, b):
print(f"subtracting {a} - {b}")
return a - b
def multiply(a, b):
print(f"multiplying {a} * {b}")
return a * b
def divide(a, b):
print(f"dividing {a} / {b}")
return a / b
print("let's do some math with these functions!")
age = add(30, 12.5)
height = subtract(90, 190)
weight = multiply(13.4, 21.88)
iq = divide(30, 0.5)
print(f"Age: {age}, height: {height}, weight: {weight}, IQ: {iq}")
print("here is a puzzle for you:")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("that becomes:", what, "can you do it by hand?") # when not using f" " no need to use {} for the variable
| true |
9a0494e31845de5b3e38b2e1aaf8cae045185634 | vishnusak/DojoAssignments | /12-MAY-2016_Assignment/python/search.py | 1,219 | 4.28125 | 4 | # String.search
# string.search(val) - search string for val (another string). Return index position of first match ( -1 if not found).
# ---- Bonus: Implement regular expression support
def search(string, val):
val = str(val) #convert the to-be-searched string into a string type
if (len(val) == 0): #if the to-be-searched is an empty string, return 0
return 0
elif (len(val) == 1): #the to-be-searched is a single char.
for char_idx in range(len(string)):
if (string[char_idx] == val):
return char_idx
else:
return -1
else: #the to-be-searched is a string on length > 1
for char_idx in range(len(string) - len(val) + 1):
if (string[char_idx:len(val)+1] == val):
return char_idx
else:
return -1
myStr = "this is yet a34n 2other !str1ng"
mySearchStr = 1
print("\nThe string is '{}'").format(myStr)
print("The search string is '{}'\n").format(mySearchStr)
myResult = search(myStr, mySearchStr)
if (myResult == -1):
print("The '{}' is not found in '{}'\n").format(mySearchStr, myStr)
else:
print("The string '{}' is found at index {}\n").format(mySearchStr, myResult)
| true |
ea4f181fd795b69f92fb4385f7fc9ecf00abee65 | vishnusak/DojoAssignments | /3-MAY-2016_Assignment/python/reversearray.py | 956 | 4.59375 | 5 | # Reverse array
# Given a numerical array, reverse the order of the values. The reversed array should have the same length, with existing elements moved to other indices so that the order of elements is reversed. Don't use a second array - move the values around within the array that you are given.
# steps:
# 1. find length of the array
# 2. use a loop that iterates for exactly half the length (e.g., if len = 5, the iterator end condition will be < 2)
# 3. for every iteration swap a[i] with a[len-1-i]
# 4. print result
# can be done using the .reverse() built-in method
def rev_arr(arr):
l_idx = (len(arr) - 1)
for i in range((len(arr) / 2)):
arr[i], arr[l_idx - i] = arr[l_idx - i], arr[i]
my_array = [1,2,3,4,5,6,7,8,9,0]
print("\nThe original array is {}\n").format(my_array)
rev_arr(my_array)
print("The reversed array is {}").format(my_array)
# ============================================================================
| true |
0296ddc0d579edc89013f4034af9b0b0b6aec661 | vishnusak/DojoAssignments | /2-MAY-2016_Assignment/python/swap.py | 759 | 4.53125 | 5 | # Swap Array Pairs
# Swap positions of successive pairs of values of given array. If length is odd, do not change final element. For [1,2,3,4] , return [2,1,4,3] . For [false,true,42] , return [true,false,42] .
# steps:
# 1 - traverse array in for loop
# 2 - increment counter by 2 each time instead of one
# 3 - for every run of the loop, swap a[i] and a[i+1]
# 4 - run loop till counter is less than length-1
# I couldn't find any built-in function to swap variable values in python
def arrSwap(arr):
for i in range(0, (len(arr) - 1), 2):
arr[i], arr[i+1] = arr[i+1], arr[i]
my_array = [1,2,3,4,5,6,7,8,9]
print("\nThe existing array is {}\n").format(my_array)
arrSwap(my_array)
print("The array after swapping is {}").format(my_array)
| true |
f9d1fb27c3ced358419cad969dba71e8f1d56a75 | helderthh/leetcode | /medium/implement-trie-prefix-tree.py | 1,836 | 4.15625 | 4 | # 208. Implement Trie (Prefix Tree)
# https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie:
def __init__(self, val=""):
"""
Initialize your data structure here.
"""
self.val = val
self.children = []
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self
for letter in word:
found = node.get(letter) # search in children
if not found:
new_node = Trie(letter)
node.children.append(new_node)
node = new_node
else:
node = found
node.children.append(Trie())
def get(self, letter):
for c in self.children:
if c.val == letter:
return c
return None
def _search(self, word: str, should_match: bool) -> bool:
"""
Returns if the word is in the trie.
"""
node = self
for letter in word:
found = node.get(letter)
if not found:
return False
node = found
if not should_match:
return True
return node.get("") is not None
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
return self._search(word, should_match=True)
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
return self._search(prefix, should_match=False)
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
af4caae1454e7fdb4b40d5192c45e7ca16783ff2 | juancadh/mycode | /collatz_conjecture.py | 1,118 | 4.59375 | 5 | """
======== COLLATZ CONJECTURE ========
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.
Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n,
the sequence will always reach 1.
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random as rnd
import seaborn as sb
def collatz_step(n):
r = np.nan
if np.mod(n,2) == 0:
r = int(n/2)
else:
r = int(3 * n + 1)
return r
def collatz(n):
collatz_lst = []
n_steps = 0
r = n
collatz_lst.append(r)
while r != 1:
n_steps += 1
r = collatz_step(r)
collatz_lst.append(r)
return n_steps, collatz_lst
sb.set()
for i in range(2,100):
print(i)
n_steps, gr = collatz(i)
max_val = max(gr)
plt.plot(i, max_val, linestyle = '-', marker = 'o')
plt.show() | true |
4d958cd5c394fd27e09703eaf02a5193c88523fa | tanadonparosin/Project-Psit | /time-count.py | 546 | 4.125 | 4 |
# import the time module
import time
# define the countdown func.
def countdown(t):
big = 0
t += 1
while t != big:
hours = big//3600
left = big%3600
mins, secs = divmod(left, 60)
timer = '{:02d}:{:02d}:{:02d}'.format(hours, mins, secs)
print(timer, end="\r")
time.sleep(1)
big += 1
print('Time Out!')
# input time in seconds
t = input("Enter the time to stop in seconds:")
# function call
countdown(int(t))
| true |
c02aa901d795f6ed60a09cb3aee1ee1c3e61ced3 | AnilKOC/some-scripts | /prime-num-is-it.py | 406 | 4.125 | 4 | import math
def main():
number = int(input("Enter your number :"))
isprime = True
for x in range(2, int(math.sqrt(number) + 1)):
if number % x == 0:
isprime = False
break
if isprime:
print("Your number is an prime number : "+str(number))
else:
print("Sory dude, its not an prime number : "+str(number))
if __name__ == "__main__": main()
| true |
2e4554a4e5d00dedfdf276f950446273d40f45c0 | LyndonGingerich/hunt-mouse | /input.py | 1,224 | 4.40625 | 4 | """Helper methods for getting user input"""
def get_bool_input(message):
"""Gets boolean input from the terminal"""
values = {'y': True, 'yes': True, 'n': False, 'no': False, '': False}
return get_dict_input(message, values)
def get_dict_input(message, values):
"""Selects value from a dictionary by user input"""
input_value = validate_input_of_values(message=message, valid_values=set(values.keys()))
return values[input_value]
def get_natural_input(message):
"""Gets an integer input from the terminal"""
return int(validate_input_of_predicate(
message=message,
condition=lambda x: x.isdigit() and int(x) > 0,
failure_message='Please enter a positive integer.'
))
def validate_input_of_predicate(message, condition, failure_message):
"""Applies a condition to input to check it"""
text = input(message)
while not condition(text):
text = input(failure_message)
return text
def validate_input_of_values(message, valid_values):
"""Checks whether an input is in a set of valid inputs"""
text = input(message).lower()
while text not in valid_values:
text = input(f'Valid inputs: {valid_values}')
return text
| true |
c7a1ed5b4d9eff957d6cebf924aeeb9ab8e0da53 | codingXllama/Tkinter-with-Python | /FirstApp/app.py | 829 | 4.4375 | 4 | import tkinter as tk
# Creating the window
window = tk.Tk()
# Creating a window title
window.title("First Application")
# Creating the window size
window.geometry("400x400")
# creating the LABEL
title = tk.Label(text="Welcome to my First Tkinter APP!",
font=("Times New Roman", 20))
# Placing the title on the window you can use pack,place, or grid
# title.place(x=10, y=20)
# title.pack()
title.grid(column=0, row=0)
# Creating buttons
btn1 = tk.Button(text="click here", bg="red")
# placing the btn1 under the title so we .grid() on the btn instead of .pack
btn1.grid(column=0, row=1)
# Creating the Entry field- a blank box where user can input content inside
entryField1 = tk.Entry()
entryField1.grid(column=0, row=2)
# running the window, mainloop runs everything inside the window
window.mainloop()
| true |
337904dc2450ebaf368a58984385087c15fe2395 | ss4328/project_euler | /problem4.py | 855 | 4.25 | 4 | #The purpose of this program is to find largest 3-digit palindrome product
print("Palindrome problem starting...")
n1 = 100
n2 = 100
ans = 0;
def reverse(num):
rev = 0
while num > 0:
rev = (10 * rev) + num % 10
num //= 10
return rev
def isPalindroms(input):
if(input == reverse(input)):
return True
else:
return False
for i1 in range(100, 1000):
# print("i1 is " + str(i1))
for i2 in range(100, 1000):
# print ("i2 is " + str(i2))
temp = i1*i2
if(isPalindroms(temp) and (temp > ans)):
ans = temp
print("program finished. Largest palindrome: " + str(ans))
# This program can be modified to give a general solution for n digits.
# n can be defined by used input.
# We can change the ranges of i1 and i2 and then define them in terms of 10^n.
| true |
7692e3274550d7ef4dad4e0c3fb65d608d28f7d3 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_8.py | 1,206 | 4.28125 | 4 | # Difference of two columns in Pandas dataframe
# Difference of two columns in pandas dataframe in Python is carried out by using following methods :
# Method #1 : Using ” -” operator.
import pandas as pd
# Create a DataFrame
df1 = {'Name': ['George', 'Andrea', 'micheal',
'maggie', 'Ravi', 'Xien', 'Jalpa'],
'score1': [62, 47, 55, 74, 32, 77, 86],
'score2': [45, 78, 44, 89, 66, 49, 72]}
df1 = pd.DataFrame(df1, columns=['Name', 'score1', 'score2'])
print("Given Dataframe :\n", df1)
# getting Difference
df1['Score_diff'] = df1['score1'] - df1['score2']
print("\nDifference of score1 and score2 :\n", df1)
# Method #2 : Using sub() method of the Dataframe.
# Create a DataFrame
df = {'Name': ['George', 'Andrea', 'micheal',
'maggie', 'Ravi', 'Xien', 'Jalpa'],
'score1': [62, 47, 55, 74, 32, 77, 86],
'score2': [45, 78, 44, 89, 66, 49, 72]}
df1 = pd.DataFrame(df1, columns=['Name', 'score1', 'score2'])
print("Given Dataframe :\n", df1)
df1['Score_diff'] = df1['score1'].sub(df1['score2'], axis=0)
print("\nDifference of score1 and score2 :\n", df1)
# https://www.geeksforgeeks.org/difference-of-two-columns-in-pandas-dataframe/
| true |
fcc9c9b601411e05ff0d28f5a23f8f4502a3b139 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_list_comprehension_assignment_1.py | 2,033 | 4.59375 | 5 | # Python List Comprehension and Slicing
# List comprehension is an elegant way to define and create list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp.
#
# A list comprehension generally consist of these parts :
# Output expression,
# input sequence,
# a variable representing member of input sequence and
# an optional predicate part.
#
# For example :
#
# lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
#
# here, x ** 2 is output expression,
# range (1, 11) is input sequence,
# x is variable and
# if x % 2 == 1 is predicate part.
# Python program to demonstrate list comprehension in Python
# below list contains square of all odd numbers from
# range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(odd_square)
print('********************************************************')
# for understanding, above generation is same as,
odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x ** 2)
print(odd_square)
print('********************************************************')
# below list contains power of 2 from 1 to 8
power_of_2 = [2 ** x for x in range(1, 9)]
print(power_of_2)
print('********************************************************')
# below list contains prime and non-prime in range 1 to 50
noprimes = [j for i in range(2, 8) for j in range(i * 2, 50, i)]
print(noprimes)
# Let’s understand how to use range() function with the help of a simple example.
print('\n********************************************************')
print("Python range() example to print numbers from range 0 to 6")
for i in range(6):
print(i, end=', ')
print('\n********************************************************')
for i in range(2, 8):
for j in range(i*2, 50, i):
print(j)
print('\n********************************************************')
# https://www.geeksforgeeks.org/python-list-comprehension-and-slicing/ | true |
14226708a9f5473ac80b76c4afe7bc47da5b403b | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_2.py | 1,796 | 4.65625 | 5 | # Syntax:
# DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
# Every parameter has some default values execept the ‘by’ parameter.
# Parameters:
# by: Single/List of column names to sort Data Frame by.
# axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.
# ascending: Boolean value which sorts Data frame in ascending order if True.
# inplace: Boolean value. Makes the changes in passed data frame itself if True.
# kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame.
# na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
# Return Type:
# Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame.
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("../../../data/nba.csv")
# display
print(data)
print('********************************************')
data_1 = data.sort_values("Name", axis=0, ascending=True,
inplace=False, na_position='last')
print(data_1)
print('********************************************')
data.sort_values("Name", axis=0, ascending=True,
inplace=True, na_position='last')
print(data)
# sorting data frame by name
data.sort_values("Salary", axis=0, ascending=True,
inplace=True, na_position='first')
# display
print(data)
# https://www.geeksforgeeks.org/python-pandas-dataframe-sort_values-set-1/
# https://www.geeksforgeeks.org/python-pandas-dataframe-sort_values-set-2/
# https://www.geeksforgeeks.org/python-pandas-dataframe-sample/
# https://www.geeksforgeeks.org/python-pandas-series-reset_index/
| true |
7292e151d67f39b26915ecbb13b9f6389674e2b0 | tracyvierra/vigilant-pancake | /TCPM-LPFS/text-2-speech/text_2_speech_live.py | 1,175 | 4.1875 | 4 | # Author: Tracy Vierra
# Date Created: 3/11/2022
# Date Modified: 3/11/2022
# Description: Text to speech example using user input to speech and saved as a file.
# Usage:
from turtle import right
from gtts import gTTS
import os
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import *
# text = open('demo.txt', 'r').read()
# gTTS(text=text, lang='en').save("hello.mp3")
# os.system("start hello.mp3")
def convert(entry, output_file):
text = entry
tts = gTTS(text=text, lang='en')
tts.save(output_file)
output_file = "output.mp3"
root = Tk()
root.title("Text 2 Speech")
canvas1 = tk.Canvas(root, width = 300, height = 100)
canvas1.pack()
entry = tk.Entry(root)
canvas1.create_window(150, 20, window=entry)
canvas1.pack()
button_convert = tk.Button(text='Convert', command= lambda:convert(entry.get(), output_file))
button_convert.configure(background='green', foreground='white')
canvas1.create_window(150, 60, window=button_convert)
canvas1.pack()
button_exit = tk.Button(root, text="Exit", command=lambda: root.destroy())
button_exit.configure(background='red', foreground='black')
button_exit.pack(padx=5, pady=5)
root.mainloop()
| true |
e0fab44a525cc912f7f8d43c618af3fc3f9ed711 | abdulwagab/Demopygit | /Operators1.py | 531 | 4.21875 | 4 |
'''Relational Operators Example in Python'''
def operator(x, y, z): # Functions name and its arguments
a = 1 # Assign variables in Function
b = 2
c = 0
x = a or c and b # Compare variables in Logical operators but not print
y = a and c or b # Compare variables in Logical operators but not print
z = a or b and c # Compare variables in Logical operators but not print
print(x, y, z) # Indirectly Assaign values to variables
operator("x", "y", "z") # Calling the Function
| true |
93d669e04066f345afe68017ab73c30d9145e53d | Vanderscycle/lighthouse-data-notes | /prep_work/Lighthouse lab prep mod katas/.ipynb_checkpoints/ch9-linear_algebra-checkpoint.py | 1,504 | 4.15625 | 4 | import numpy as np
x = np.array([1, 2, 3, 4])
print(x)
# Matrix A
A = np.array([[1,2],[3,4],[5,6]])
print(type(A))
# in which the result is a tuple of (columns, rows)|(3x,2y) of the matrix
print(A.shape)
print(x.shape)
print(len(x)) # returns the length of the array (#in the list)
# transpose an a matrix
A_T = A.T
# this format is also acceptable
A_T = A.transpose()
print(A_T.shape)
# Note: the transpose of a matrix (At) can be obtained by reflecting the elements along its main diagonal
# https://en.wikipedia.org/wiki/Transpose
# Do not confuse transposition (flipping) with the invest of a matrix (a-1). NOTE non square matrices cannot have an inverse matrix because
B = np.array([[2, 5], [7, 4], [4, 3]])
C = A + B
print(C)
print(C + 1)
# dot product
A = np.array([[1, 2], [3, 4], [5, 6]])
B = np.array([[2], [4]])
print(A.shape,B.shape)
C = A.dot(B)
# we change the space
# C = A . B (3,2) . (2, 1) = 3d vector (3,1)
print(C)
# identity matrix
# A-1 * A = I. This provides a way to cancel the linear transformation
I = np.eye(3) # similar to np.identity(n) but you can shift the index of the diagonal
IA = I.dot(A)
print(IA)
#determinant
#area
# non square matrices should be viewed geometrically as transformations between dimensions
M = np.array([[1,2],[3,4]])
det_M = np.linalg.det(M)
print(det_M)
# inverse matrices
A = np.array([[3, 0, 2], [2, 0, -2], [0, 1, 1]])
A_inv = np.linalg.inv(A)
I = A_inv.dot(A)
print(I) | true |
dee0620a9f930628a7ea44f4d73779e76686b4c2 | melphick/pybasics | /week6/w6e2.py | 342 | 4.28125 | 4 | #!/usr/bin/python
"""
Converts a list to a dictionary where the index of the list is used as the
key to the new dictionary (the function will return the new dictionary).
"""
def list_to_dict(a_list):
a_dict = {}
for i in a_list:
print i
a_dict[i] = a_list[i]
return a_dict
a = range(10)
print list_to_dict(a)
| true |
cbd0d974b4b636760e98b1a4da159129e025be14 | patidarjp87/ROCK-PAPER-SCISSOR-GAME | /ROCK.py | 1,438 | 4.1875 | 4 | import random
print("WELCOME TO ROCK PAPER SCISSOR GAME\n")
lst = ["Rock", "Paper", "Scissor"]
computer_score = 0
player_score = 0
game = 0
chance = 6
while game < chance:
choice = random.choice(lst)
turn = input("choose(rock, paper or scissor) : ").lower()
game +=1
if turn == "rock" and choice == "Scissor":
print("Computer's point\n")
computer_score += 1
if turn == "rock" and choice == "Paper":
print("Player's point\n")
player_score += 1
if turn == "rock" and choice == "Rock":
print("No points\n")
elif turn == "paper" and choice == "Scissor":
print("Computer's point\n")
computer_score += 1
elif turn == "paper" and choice == "Rock":
print("Player's point\n")
player_score += 1
elif turn == "paper" and choice == "Paper":
print("No points\n")
elif turn == "scissor" and choice == "Rock":
print("Computer's Point\n")
computer_score += 1
elif turn == "scissor" and choice == "Paper":
print("Player's point\n")
player_score += 1
elif turn == "scissor" and choice == "Scissor":
print("No points\n")
break
print(f'Computer score: {computer_score}\n')
print(f'Player score : {player_score}\n')
if computer_score > player_score:
print("computer win")
elif computer_score < player_score:
print("you win")
else:
print("Nobody win")
input()
| true |
650074bf605a56ddb94a4a6ff9ab260cadf72467 | Souravdg/Python.Session_4.Assignment-4.1 | /Filter Long Words.py | 600 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[14]:
##############################################
# A function filter_long_words() that takes a list of words and an integer n and returns
# the list of words that are longer than n
def filter_long_words(lst,length):
newlst = []
for x in range(len(lst)):
if len(lst[x]) > length:
newlst.append(lst[x])
return newlst
#############################################
lst = ['Sam', 'John', 'Steve']
n = 3
print("Below is the new List of words that are longer than length %s " %(n))
print(filter_long_words(lst,n))
| true |
4235257b90ca960999d780a44b1f7af7607b8fc8 | cyberchaud/automateBoring | /vid04/vid04.py | 1,183 | 4.1875 | 4 | # pythontutor.com/visualize.html
# Indentation in Python indicates a block of code
# Blocks start where the indentation begins and the block stops where the indentation stops
# if block statements are conditions/expressions
# if the condition evaluates to true; then Python executes the indented code
name = 'Bob'
if name == 'Alice':
# Skips the indentation block because the condition is not True
print('Hi {}'.format(name))
print('Done')
password = 'iloveu'
# Python executes one block only
if password == 'swordfish':
print('Access granted')
elif password == 'iloveu':
print('Access granted with your terrible password')
else:
print('Try again')
# Python Truthy or Falsey
# Strings:
# Truthy is any string
# Falsey is a blank string
# Test - bool('Hello') -> True; bool('') -> False
# Integers:
# Truthy is any integer
# Falsey is 0
# Test - bool(42) -> True; bool(0) -> False
print('Enter a name')
name = input()
# Any input will print 'Thank you for entering your 'name'
# Pressing enter (blank input) prints 'You did not enter a name'
if name != '':
print('Thank you for entering your name')
else:
print('You did not enter a name')
| true |
8189b5b2488e0f5f91a999c449089c618a576196 | cyberchaud/automateBoring | /vid22/vid22.py | 1,572 | 4.28125 | 4 | #! /usr/bin/python3
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3]!= '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print(isPhoneNumber('444-53-1234'))
# Looping through 12 char slices in a string
def checkforNumber(message):
foundNumber = False
for i in range(len(message)):
chunk = message[i:i+12]
if isPhoneNumber(chunk):
print('Phone number found: {}'.format(chunk))
foundNumber = True
return True
if not foundNumber:
print('Could find any phone numbers')
return False
print(checkforNumber('Call me at 444-555-1234 for more details'))
print(checkforNumber('Call me at 444-5234 for more details'))
# Regular expression to find a phone number within a string
# Regular expression are a mini-language for specifying text patterns
# Should use raw strings r'string' so Python doesn't try and use escape characters
# Using the re library
# Call compile function
# Call search function
# Use group() method
import re
print('Using a regular expression to see if a string has a phone number pattern')
phoneNumbRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumbRegex.search('Call me at 444-555-1234 for more details')
print(mo.group()) | true |
f407e16b8c2485680862c746d272b752b0d77eb5 | cyberchaud/automateBoring | /vid01/vid01.py | 601 | 4.28125 | 4 | # Python always evaluates down to a single value.
# Integers are whole number
# Any digits with a decimal is a floating point
# Expresssions are made from Values and Operators
print("Adding")
print(2+2)
print("Substraction")
print(5-3)
print("Multiplication")
print(3*7)
print("Division")
print(21/7)
print("PEMDAS")
print(2+3*6)
# (2+3)*6
# Python does:
# (2+3) = 5
# (5)*6
# 30
print((2+3)*6)
# String
# Strings are for text
# Concatenation for strings
print('Alice')
print('Alice' + 'Bob')
#String Replication
print('Alice'*3)
# Variables
spam = 'Hello'
print(spam)
print(spam + ' World') | true |
3b06c59a64a82f7fbaa7eeba84c04c2dc020568c | krausce/Integrify | /WEEK_1/Question_4.py | 1,954 | 4.125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 01:24:18 2019
@author: chris
"""
'''
Question 4 asked us to write a function which looks through a list of int's
and returns '1' if a triplet exists and 0 if not.
My approach to this was to first sort the list using the builtin python
"list.sort()". This places all of the values in ascending order. If you
want to sort them into descending order instead, you simply call:
list_var_name.sort(reverse = True). Or if you simply want to return the
sorted list, use the method "sorted", see syntax below.
The built-in python sort methods have worst-case time complexity of
O(n log n): https://wiki.python.org/moin/TimeComplexity
Next, because the values are sorted, if any of the tests fail with the
first three values, the first value needs to simply push forward to the
position the third value was in (2 spaces) and then run the tests again.
This can be run inside of a loop or this could be done recursively. If at
any time the tests pass, return 1 and the program terminates.
'''
a = [1, 2, 3]
a.sort(reverse=True)
print(a) # Should show "[3, 2, 1]"
a.sort()
print(a)
a = sorted(a, reverse=True)
print(a) # Now they are in descending order again
a = sorted(a)
print(a) # Now the nums are back in ascending order
a = [10, 2, 5, 1, 8, 20]
b = [10, 50, 5, 1]
def tri_count(l_nums):
if len(l_nums) < 3:
return 0
for i in range(len(l_nums)):
if not isinstance(l_nums[i], int):
print(i)
return 0
l_nums.sort()
p = 0
while p in range(len(l_nums)-2):
q = p+1
r = q+1
if check_triple(l_nums[p], l_nums[q], l_nums[r]):
return 1
p += 2
return 0
def check_triple(p, q, r):
return (((p+q) > r) and ((q+r) > p) and ((p+r) > q))
print(tri_count(a)) # Should return 1
print(tri_count(b)) # Should return 0
| true |
fe22ab33e33de67fa988d00f00d58eeb0bb8cb9d | neelima-j/MITOpenCourseware6.0001 | /ps1c.py | 1,967 | 4.3125 | 4 | '''
To simplify things, assume:
1. Your semiannual raise is .07 (7%)
2. Your investments have an annual return of 0.04 (4%)
3. The down payment is 0.25 (25%) of the cost of the house
4. The cost of the house that you are saving for is $1M.
You are now going to try to find the best rate of savings to achieve a down payment on a $1M house in
36 months. Since hitting this exactly is a challenge, we simply want your savings to be within $100 of
the required down payment.
'''
#Getting inputs
annual_salary = float(input("Enter the starting salary: "))
annual_salary_original = annual_salary
#initalizing variables
semi_annual_raise = .07
r = .04
total_cost = 1000000
portion_saved = 1
i=0
max = 1
min = 0
def initialise():
global months
months = 0
global portion_down_payment
portion_down_payment = .25*total_cost
global current_savings
current_savings = 0
global annual_salary
annual_salary = annual_salary_original
initialise()
if annual_salary*3<portion_down_payment:
print("It is not possible to pay the down payment in three years.")
raise SystemExit
while True:
current_savings *= (1+r/12)
current_savings += (annual_salary/12)*portion_saved
months += 1
if months % 6 == 0:
annual_salary *= (1+semi_annual_raise)
if abs(current_savings - portion_down_payment) <=100 and months == 36:
break
elif months == 36:
if (current_savings - portion_down_payment) < 0: #saving less, increase rate
min = portion_saved
portion_saved += (max-min)/2
portion_saved = round(portion_saved ,5)
i+=1
initialise()
else: #saving too much, reduce rate
max = portion_saved
portion_saved -= (max-min)/2
portion_saved = round(portion_saved,5)
i+=1
initialise()
print("Best savings rate: ",round(portion_saved,4))
print("Steps in bisection search: ",i)
| true |
361b4561b6a87cba7a2b35a603e86f04274e94bc | skgbanga/AOC | /2020/23/solution.py | 1,899 | 4.40625 | 4 | # The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle.
# The crab selects a destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead.
# The crab places the cups it just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up.
# The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
class Node:
def __init__(self, val):
self.val = val
self.next = None
circle = '963275481'
d = {}
node = Node(int(circle[0]))
d[node.val] = node
curr = node
for c in circle[1:]:
n = Node(int(c))
d[n.val] = n
node.next = n
node = n
for i in range(10, 1_000_001):
n = Node(i)
d[n.val] = n
node.next = n
node = n
node.next = curr
largest = 1_000_000
def show():
s = curr
for _ in range(9):
print(s.val, end='')
s = s.next
print()
for i in range(10_000_000):
selected = []
for _ in range(3):
selected.append(curr.next.val)
d.pop(curr.next.val)
curr.next = curr.next.next
dst = curr.val - 1
if dst == 0:
dst = largest
while dst in selected:
dst = dst - 1
if dst == 0:
dst = largest
tmp = d[dst]
for s in selected:
n = Node(s)
d[s] = n
n.next = tmp.next
tmp.next = n
tmp = n
curr = curr.next
n = d[1]
print(n.next.val * n.next.next.val)
| true |
891c4f8c7b6e238686e43e4e637f988f4c5652b5 | RavensbourneWebMedia/Ravensbourne | /mymodule.py | 1,210 | 4.625 | 5 | ## mymodule: a module containing functions to print a message, convert temperatures and find the 3rd letter of a word ##
# INSTRUCTIONS
# Write code for the three functions below:
# This function should use 'raw_input' to ask for the user's name, and then print a friendly message including
# the user's name to the command line (e.g. "Hi there Bob! Good to see you again!")
def helloMessage():
print "You need to write your own code before running this function!"
# This function should take in a temperature in Kelvin, convert it to Celsius and print the result as part of a string
# (e.g. 100 degrees Celsius is 373 Kelvin). HINT: you'll need to convert the result of the calculation to a string.
# Google is your best friend!
def Kelvin2Celsius(kelvin):
print "You need to write your own code before running this function!"
# This function should take in a word, and return the third letter of that word as part of a string to the command line
# (e.g. "The third letter of the word banana is 'n'). HINT: you can access the n^th letter of a word using square
# brackets. If you get stuck, ask me!
def thirdLetter(word):
print "You need to write your own code before running this function!"
| true |
c47d32391b8c18705ab43c0129135a3ac36f1a3b | myanir/Campus.il_python | /self.py/dateconvert.py | 213 | 4.15625 | 4 | import calendar
user_input = input("Enter a date: ")
# 01/01/2000
year = int(user_input[-4:])
month = int(user_input[3:5])
day = int(user_input[:2])
print(calendar.day_name[calendar.weekday(year, month, day)]) | true |
221a8faf61fc8d5e507718cd06c76d905ffa22d2 | jeffreybrowning/algorithm_projects | /dynamic/minimum_steps.py | 1,583 | 4.34375 | 4 | def get_min_steps (num):
"""
For any positive integer num, returns the amount of steps necessary to reduce
the number to 1 given the following possible steps:
1) Subtract 1
2) Divide by 2
3) Divide by 3
>>>get_min_steps(15)
4
"""
if num <= 0 or type(num) != int: return None
min_steps_list = [0] * (num + 1)
for i in range(2, num + 1):
print('\n')
print('i = {0}'.format(i))
print(dict(enumerate(min_steps_list)))
# We can either -1, /2 or /3 -- this is the -1 step
min_steps_list[i] = 1 + min_steps_list[i-1]
# for any number i, we either take min_steps_list[i - i] + 1, or the number of steps
# of its /2 or /3 factor (+1 because we have just added one more step)
if i % 2 == 0:
print('divisible by two')
print('''min_steps_list[{0}] = {1} \n1 + min_steps_list[{2}] = {3}'''.format(i, min_steps_list[i], i/2, 1 + min_steps_list[i/2]))
min_steps_list[i] = min( min_steps_list[i] , 1 + min_steps_list[i/2] )
if i % 3 == 0:
print('divisible by three')
print('''min_steps_list[{0}] = {1} \n1 + min_steps_list[{2}] = {3}'''.format(i, min_steps_list[i], i/3, 1 + min_steps_list[i/3]))
min_steps_list[i] = min( min_steps_list[i] , 1 + min_steps_list[i/3] )
return min_steps_list[num]
if __name__ == '__main__':
print(get_min_steps(8))
# print(get_min_steps(247))
def fib(n):
if n == 1: return 1
return fib(n-1) + fib(n-2)
def min_steps_recursive(num):
# if num == 1 return 1
return min(min_steps_recursive(n-1) + min_steps_recursive(n/2) + min_steps_recursive(n/3))
| true |
2692e538d72e8ac46ba2d2cb6db4256b2445e7b4 | henryHTH/Algo-Challenge | /Largest_prime_factor.py | 840 | 4.28125 | 4 | '''
Given a number N, the task is to find the largest prime factor of that number.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains an integer N.
Output:
For each test case, in a new line, print the largest prime factor of N.
Constraints:
1 <= T <= 100
2 <= N <= 1010
Example:
Input:
2
6
15
Output:
3
5
'''
def lpf(num):
while num % 2 == 0:
num = num / 2
if num == 1: return num
n = num
for i in range(3, int(math.sqrt(n)) + 1, 2):
while num % i == 0:
num = num / i
if num == 1:
return i
return num
if __name__ == '__main__':
import math
for i in range(int(input())):
num = int(input())
print(int((lpf(num)))) | true |
0b5348cb514686eae1e95606a94c64043db7e51b | suhaylx/for-loops | /main.py | 535 | 4.34375 | 4 | for item in {1,2,3,4,6}:
for values in {'a', 'b','c'}:
print(item, values)
user = {
'name' : 'Suhaylx',
'age' : 18,
'can_swim' : False
}
for dictionary_items in user.values():
print(dictionary_items)
for dict_items in user.items():
print(dict_items)
for keys, item_s in user.items():
print(keys,item_s)
#There is still other ways to iterate
for example_value in user.items():
dict_keys, dict_values = example_value
#as example_value value is typle we assign values to another two value
print(dict_keys, dict_values) | true |
35bf351112ee5abeb120a3989d17e70c095ea189 | tsunny92/LinuxAcademyScripts | /ex1.py | 301 | 4.21875 | 4 | #!/usr/bin/env python3.6
msg = input("Enter the message to echo : ")
count = int(input("Enter the number of times to display message ").strip())
def displaymsg(msg , count):
if count > 0:
for i in range(count):
print(msg)
else:
print(msg)
displaymsg(msg , count)
| true |
da643f117987410670878690fdfea9807efca07a | yiorgosk/python | /polynomials.py | 1,498 | 4.34375 | 4 | import numpy.polynomial.polynomial as poly
import numpy as np
'''The user can enter 2 polynomial functions and perform the basic math praxis of addition, subtraction, multiplication and division.
Also the user is able to discover the roots of the two function and perform for instance an addiction praxis with a polynomial and an integer, such as number 2'''
def root(a):
return poly.polyroots(a)
def add(a, b):
return np.polyadd(a, b)
def sub(a, b):
return np.polysub(a, b)
def mul(a, b):
return np.polymul(a, b)
def div(a, b):
return np.polydiv(a, b)
def main():
inpt1 = input('Enter the number of polynomial factors \n')
counter1 = 0
pol1 = []
while counter1 < int(inpt1):
factor = input('Insert your factor')
pol1.append(float(factor))
counter1 += 1
inpt2 = input('Enter the number of polynomial factors \n')
counter2 = 0
pol2 = []
while counter2 < int(inpt2):
factor = input('Insert your factor')
pol2.append(float(factor))
counter2 += 1
print('The roots of the first polynomial functions are ', root(pol1))
print('The roots of the second polynomial functions are ', root(pol2))
print('The output of the add function is ', add(pol1, pol2))
print('The output of the subtract function is ', sub(pol1, pol2))
print('The output of the mul function is ', mul(pol1, pol2))
print('The quotient and remainder of div function are ', div(pol1, pol2))
main()
| true |
04b818d3a8e91e3ec412d008dd23bae7ddafdedb | wenyaowu/leetcode | /algorithm/wildcardMatching/wildcardMatching.py | 1,190 | 4.1875 | 4 | # Wildcard Matching
"""
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
"""
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def isMatch(self, s, p):
s_pointer = 0
p_pointer = 0
star = -1
match = 0
while s_pointer<len(s):
if p_pointer<len(p) and (p[p_pointer]==s[s_pointer] or p[p_pointer]=='?'):
p_pointer+=1
s_pointer+=1
elif p_pointer<len(p) and p[p_pointer]=='*': #If there's a start, update
star = p_pointer
match = s_pointer
p_pointer+=1
elif star!=-1:
p_pointer = star+1
match+=1
s_pointer = match
else: return False
while p_pointer<len(p) and p[p_pointer]=='*': p_pointer+=1
return p_pointer==len(p)
| true |
bf3194d31daa0fde740f70f19ef4b502c1d82708 | wenyaowu/leetcode | /algorithm/spiralMatrix/spiralMatrix.py | 948 | 4.1875 | 4 | # Spiral Matrix
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
result = []
while matrix:
try:
result += matrix.pop(0)
except:
break
try:
for row in matrix:
result += [row.pop(-1)]
except:
break
try:
result += matrix.pop(-1)[-1::-1]
except:
break
try:
for row in matrix[-1::-1]:
result += [row.pop(0)]
except:
break
return result
| true |
bc8cab306a5c13eb063336a46464b3f29bc03e26 | wenyaowu/leetcode | /algorithm/maximumSubArray/maximumSubarray.py | 525 | 4.15625 | 4 | # Maximum Subarray
"""
Find the contiguous subarray within an array
(containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def maxSubArray(self, nums):
res = [0 for x in range(len(nums))]
res[0] = nums[0]
for i in range(1, len(nums)):
res[i] = max(res[i-1]+nums[i], nums[i])
return max(res)
| true |
6c1af79866f6e74500b78fbc1bae00e005ed66dc | ghydric/05-Python-Programming | /Class_Practice_Exercises/Lists/List_Functions_Review/append_list.py | 673 | 4.53125 | 5 | ## Append to list
# This function demonstrates how the append method
# can be usesd to add items to a list
def main():
# initialize empty list
name_list = []
# create a variable to control our loop
again = 'y'
# add some names to the list
while again == 'y':
# get a name from the user
name = input('Enter a name: ')
# append the name to the list
name_list.append(name)
# add another one?
print('Do you want to add another name?')
again = input('y = yes, anything else = no: ')
print()
# display the names in the name list
print(name_list)
# run the main function
main() | true |
b2c495513f454f4c992e7c6b89f0a8cb79b7ea69 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/map_func.py | 593 | 4.4375 | 4 | # map() function
# calls the specified function and applies it to each item of an iterable
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
sqrList = map(square, numbers)
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
sqrList2 = map(lambda x: x*x, numbers)
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
tens = [10,20,30,40,50]
indx = [1,2,3]
powers = list(map(pow, tens, indx))
print(powers) | true |
dbbfec55fae84308c068d8b2db6f5502c6ef29a3 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/iter.py | 485 | 4.34375 | 4 | # Python iterator
#old way:
myList = [1,2,3,4]
for item in myList:
print(item)
# what is actually happening using iterators
def traverse(iterable):
it = iter(iterable)
while True:
try:
item = next(it)
print(item)
except StopIteration:
break
L1 = [1,2,3]
item = iter(L1)
print(item.__next__())
print(item.__next__())
print(item.__next__())
print(item.__next__())
print(item.__next__())
# or this method
print(next(it)) | true |
8450a626f5b9179e35e75c4a6296c036913eb583 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Classes/Classes_Exercises_2.py | 2,739 | 4.75 | 5 | """
2. Car Class
Write a class named Car that has the following data attributes:
• __year_model (for the car’s year model)
• __make (for the make of the car)
• __speed (for the car’s current speed)
The Car class should have an __init__ method that accept the car’s year model and make
as arguments. These values should be assigned to the object’s __year_model and __make
data attributes. It should also assign 0 to the __speed data attribute.
The class should also have the following methods:
• accelerate
The accelerate method should add 5 to the speed data attribute each time it is
called.
• brake
The brake method should subtract 5 from the speed data attribute each time it is called.
• get_speed
The get_speed method should return the current speed.
Next, design a program that creates a Car object, and then calls the accelerate method
five times. After each call to the accelerate method, get the current speed of the car and
display it. Then call the brake method five times. After each call to the brake method, get
the current speed of the car and display it.
"""
# Car class
class Car:
# __init__ method creates a Car object with a year_model, make, and speed attributes
def __init__(self, year, make, speed = 0):
self.__year_model = year
self.__make = make
self.__speed = int(speed)
# accelerate method adds 5 to the __speed attribute each time it is called
def accelerate(self):
self.__speed += 5
# brake method subtracts 5 from the __speed attribute each time it is called
def brake(self):
self.__speed -= 5
# get_speed method returns value in the __speed attribute
def get_speed(self):
return self.__speed
# main function creates a Car object, accelerates five times, then brakes five times
# displaying the current speed after each accelerate and brake
def main():
# create the Car object using user input
my_car = Car(
input('Enter the year of your car: '),
input('Enter the make of your car: ')
)
# print the starting speed
print(f'My car\'s starting speed is: {my_car.get_speed()}')
# accelerate 5 times and display the speed after each accelerate
for i in range(1,6):
print('Accelerating now.')
my_car.accelerate()
print(f'My car is now going {my_car.get_speed()}mph.')
# brake 5 times and display the speed after each brake
for i in range(1,6):
print('Braking now.')
my_car.brake()
print(f'My car is now going {my_car.get_speed()}mph.')
# call main function
main() | true |
679154f4340225e10a6dce151354fd1a1588df40 | bhavyajain190/Guess | /un.py | 553 | 4.125 | 4 | import random
print('Hey what is your name?')
name = input()
print('Welcome ' + name + ' I am thinking of a number between 1 and 10')
Num = random.randint(1,10)
for guessesTaken in range(1,3):
print('Take a guess')
guess = int(input())
if guess < Num:
print('Your guess is a lttle low')
elif guess > Num:
print('Your guess is too high')
if guess == Num:
print('congratulations ' + name + ' you have guessed my number in ' + str(guessesTaken) + ' guesses!!')
else:
print('I am sorry number was ' + str(Num)) | true |
75df037a3564e30b1c2ed8b11598ea52bfdf2fc7 | 01FE16BME072/TensorflowBasics | /Tensor_handling3.py | 1,279 | 4.40625 | 4 | '''
TensorFlow is designed to handle tensors of all sizes and operators that can be used to
manipulate them. In this example, in order to see array manipulations, we are going to
work with a digital image. As you probably know, a color digital image that is a MxNx3
size matrix (a three order tensor), whose components correspond to the components of red,
green, and blue in the image (RGB space), means that each feature in the rectangular box for
the RGB image will be specified by three coordinates, i, j, and k.
You can see visualisation of this in this folder only just open refrence_image.png
'''
#Importing the required Libraries
import tensorflow as tf
import matplotlib.image as image #This library is used for reading and showing the image on the screen here you can even replace this with the opencv library
from matplotlib import pyplot as plt
read_img = image.imread("refrence_image.png")
plt.imshow(read_img)
plt.show()
#Now here if we want then we can even see the rank and the shape
read_tensor_img = tf.placeholder("uint8",[None,None,4])
slice_read_tensor_img = tf.slice(read_tensor_img,[100,0,0],[200,200,-1])
with tf.Session() as sess:
slicing = sess.run(slice_read_tensor_img,feed_dict = {read_tensor_img:read_img})
plt.imshow(slicing)
plt.show()
| true |
176313e02cb527f58beefa6a979118618da5446e | BohanHsu/developer | /python/io/ioString.py | 1,776 | 4.78125 | 5 | #in this file we learn string in python
s = 'Hello, world.'
#what str() deal with this string
print(str(s))
#what repr() deal with this string
print(repr(s))
#repr() make a object to a string for the interpreter
print(str(1/7))
print(repr(1/7))
#deal with some transforming characters
hello = 'hello, world\n'
helloStr = str(hello)
helloRepr = repr(hello)
print(helloStr)
print(helloRepr)
#str() translate the '\n' to a new line.
#repr() ignore it
#how those two function deal with object
#this is a tuple!!!!
tuple = (32.5, 4000, ('spam', 'eggs'))
print(str(tuple))
print(repr(tuple))
#ok expect string str() is just same as repr()...
#using print and formatting string
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3),end = '...')
print(repr(x*x*x).rjust(4))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
#the rjust() function is use for right justifies a string
#similarly, there are function ljust() and center()
#those functions not truncate the string
#if you want justifies a string and truncate if the string is too long,
#user str.ljust(n)[:n] or str.rjust(n)[n:]
#hello I'm draft...
#str = '12345678'
#print(str[:5])
#print(str[-5:])
#formal way of using format()
print('{} and {}'.format('first string','second string'))
print('{0} and {1}'.format('first string','second string'))
print('{1} and {0}'.format('first string','second string'))
print('{firstPosition} and {secondPosition}'.format(firstPosition = 'first string',secondPosition = 'second string'))
#use a dictionary to format a string
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
#vars() get all the local variables
varsResult = vars()
print(varsResult)
| true |
e1be98d672f2925301e0c273a5c00a69c3d30213 | BohanHsu/developer | /nlp/assign1/hw1-files/my_regexs.py | 655 | 4.1875 | 4 | import re
import sys
# the first argument is a regular expression
# from the second argument are file path
pattern = sys.argv[1]
files = sys.argv[2:]
# reg_find : regular_expression, list_of_file_path -> list of words
# return a list of words which match the regular expression
# this method will concatenate all the lines in those given file and find patterns
#
def reg_find(pattern,files):
s = ''
for filename in files:
file = open(filename)
for line in file.xreadlines():
s = s + line
file.close()
words = set(re.findall(pattern,s))
print words
print len(words)
return words
reg_find(pattern,files)
def suffix(suff,count):
pass
| true |
4739f2dcad276d9967f2f0d36479e217db737356 | himIoT19/python3_assignments | /assignment_1/Q4.py | 328 | 4.4375 | 4 | # reverse string
def reverse(a_str: str) -> str:
"""
Function used for reversing the string
:param a_str: String
:return: String
"""
string_1 = a_str[::-1]
return string_1
# String to work on
s = "I love python"
print("Old string : {}".format(s))
print(f"New string after reversal: {reverse(s)}")
| true |
014c4247f563ba43e78dd5cc4d3f4f0e19cd41ed | seefs/Source_Insight | /node/Pythons/py_test/test_while.py | 371 | 4.15625 | 4 | #!/usr/bin/python
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
for j in range(9):
print ('The j is:', j)
#// The count is: 0
#// The count is: 1
#// The count is: 2
#// The count is: 3
#// The count is: 4
#// The count is: 5
#// The count is: 6
#// The count is: 7
#// The count is: 8
#// Good bye!
print ("Good bye!")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.