blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0161be485ecedd4e17fd86e5049d4ef2bea9191d | liyouzhang/Algos_Interviews | /sum_of_two_values.py | 1,254 | 4.375 | 4 | def find_sum_of_two_one(A, val):
'''
input - array of numbers; val - a number
output - bool
1. native:
- try all combinations of two numbers in array: 2 for loops
- for each, test if == target
'''
#1. naive approach
for a in A:
for b in A:
if b != a:
if a + b == val:
return True
return False
#space - O(1)
#running time - O^2
def find_sum_of_two_two(A, val):
'''
approach 2. find if val-current_num is in the list
create a set of found_values
loop through the array,
check if val-value is in the found_values, if yes, return true
else, add to the set
'''
found_values = set()
for i in A:
if val-i in found_values:
return True
found_values.add(i)
return False
#space - O(n) set
#run time - O(n) 1 for loop
def find_sum_of_two_three(A, val):
'''
approach 3.
use two indexes to avoid for loop
1. sort array
2. use two idx
3. sum, if sum < target, then move left +1 ; if > target, then move right -1
'''
i = 0
j = len(A) - 1
A.sort()
if A[i] + A[j] < val:
i += 1
if A[i] + A[j] > val:
j -= 1
if A[i] + A[j] == val:
return True
return False
| true |
50b40bb9f10c8abbe769296dea8d895e517ee13e | liyouzhang/Algos_Interviews | /819_most_common_word.py | 2,900 | 4.34375 | 4 | '''
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
Example:
Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Note:
1 <= paragraph.length <= 1000.
0 <= banned.length <= 100.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
There are no hyphens or hyphenated words.
Words only consist of letters, never apostrophes or other punctuation symbols.
'''
# my try 20200502
# failed because sometimes words are not split by ' ' but by punctuation, so in solution it used regex
def most_common_word (paragraph, banned):
# input: para = string, banned = a list of strings
# output: a string (word), lower case
# split the string to a list of words
# process every word into lower case
# iterate through the list, to add the not_banned words into a new list
# iterate through the filtered list:
# if the word is found more than once, then counter += 1
# the counter is a dictionary
# find out the max of the value, and return the key
import string
l1 = paragraph.split(' ')
filtered_list = []
for i in l1:
i_transformed = ''.join(ch for ch in i if ch not in set(string.punctuation)).lower()
if i_transformed not in banned:
filtered_list.append(i_transformed)
counter = {}
for i in filtered_list:
if i in counter.keys():
counter[i] += 1
else:
counter[i] = 1
l3 = list(counter.values())
l4 = list(counter.keys())
return l4[l3.index(max(l3))]
# solution
def most_common_word (paragraph, banned):
import re
word_list = re.split('\W+', paragraph.lower())
max_freq,max_word, freq, banned_set = 0, None, {}, set(banned)
for word in word_list:
if word not in banned_set:
freq[word] = freq.get(word, 0) + 1
if freq[word] > max_freq:
max_freq, max_word = freq[word], word
return max_word | true |
87ae2f7ef55554516cf8cdce8e1a57837533b3e8 | doraithodla/py101 | /learnpy3/word_freq_2.py | 783 | 4.15625 | 4 | # wordfreq2 - rewrite the wordfreq program to take the text from a file and count the words
def word_freq1(str):
"""
takes a string and calculates the word frequency table
:param str: string input
:return: frequency dictionary
"""
frequency = {}
for word in str.split():
if word in frequency:
frequency[word] = frequency[word] + 1
else:
frequency[word] = 1
return frequency
def read(file_name):
"""
reads a file and returns the number of lines in the file
:param file_name: name of the file to be read
:return: number of lines in the file
"""
with open(file_name, "r") as f:
text = f.read()
return text
file_text = read("something.txt")
print(word_freq1(file_text))
| true |
16ba194d28de4bf38a2764f173606bce7cde982b | doraithodla/py101 | /shapes.py | 282 | 4.28125 | 4 | from turtle import forward, right
def shape(sides,length):
for i in range(sides):
forward(length)
right(360/sides)
'''
length = int(input("Length: "))
sides = int(input("Number of sides:"))
'''
for sides in range(3,5):
shape(sides, 100)
| true |
7f7bc72b412846e06bf9b6b5a0c720a4bdc05798 | doraithodla/py101 | /learnpy5/dictionary.py | 2,124 | 4.625 | 5 | # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'HP', 2: 'compaq', 3: 'dell'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'HP', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'HP', 2: 'compaq', 3: 'dell'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'HP'), (2, 'Dell')])
print("\nDictionary with each item as a pair: ")
print(Dict)
# Creating a Nested Dictionary
Dict = {1: {'A': 'dell', 'B': 'HP', 'C': 'asus'},
2: {'D': 'HCl', 'E': 'lenovo', 'F': 'IBM'}}
print("\nNested Dictionary: ")
print(Dict)
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'HP'
Dict[2] = 'DELL'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
# Initial Dictionary
Dict = {5: 'dell', 6: 'hp', 7: 'asus',
'A': {1: 'something', 2: 'to', 3: 'do'},
'B': {1: 'something', 2: 'else'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
# Deleting a Key
# using pop()
Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)
# Deleting a Key
# using popitem()
Dict.popitem()
print("\nPops first element: ")
print(Dict)
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)
| false |
41b4bb8bda85667c76cc72387e98ef65fc4fd871 | doraithodla/py101 | /learnpy2/wordset.py | 328 | 4.125 | 4 | noise_words = {"if", "and", "or", "the", "add"}
def wordset(string):
"""
converts a list of words to a set
:param list: string input from the user
:return: set object
"""
string_set = set(string.split())
print(string_set)
print(noise_words)
wordset("a is a test to check the test of sets ")
| true |
bea6d8a0680e3c04423bf50c4e89d162cdace2af | eternalseptember/CtCI | /04_trees_and_graphs/01_route_between_nodes/route_between_nodes.py | 1,044 | 4.1875 | 4 | """
Given a directed graph, design an algorithm to find out whether there is
a route between two nodes.
"""
class Node():
def __init__(self, name=None, routes=None):
self.name = name
self.routes = []
if routes is not None:
for item in routes:
self.routes.append(item)
def __str__(self):
list_of_routes = []
for route in self.routes:
list_of_routes.append(route.name)
return 'name: {0}\t\troutes: {1}'.format(self.name, list_of_routes)
def has_route_between_nodes(from_node, to_node):
# return True if there is a route between the two
# return False if there isn't a route
if from_node == to_node:
return True
visited = []
queue = [from_node]
if from_node == to_node:
return True
while len(queue) > 0:
current_node = queue.pop(0)
for route in current_node.routes:
if route == to_node:
return True
else:
if (route not in queue) and (route not in visited):
queue.append(route)
# record node as visited if there isn't a path
visited.append(current_node)
return False
| true |
275a53e865259a0d15f82cdacdc2a58a641b9343 | eternalseptember/CtCI | /07_object-oriented_design/11_file_system/file_system.py | 2,226 | 4.28125 | 4 | """
Explain the data structures and algorithms that you would use to design an
in-memory file system. Illustrate with an example in code where possible.
"""
# What is the relationship between files and directories?
class Entry():
def __init__(self, name, parent_dir):
self.name = name
self.parent_dir = parent_dir # directory object
# there should be error checking here.
if parent_dir is not None:
parent_dir.add_entry(self)
def get_full_path(self):
if self.parent_dir is None:
return self.name
else:
return '{0}/{1}'.format(self.parent_dir.get_full_path(), self.name)
def rename(self, new_name):
self.name = new_name
def __str__(self):
return str(self.name)
class File(Entry):
def __init__(self, name, parent_dir):
Entry.__init__(self, name, parent_dir)
self.content = None
self.size = 0
def set_content(self, content):
self.content = content
self.size = len(content)
def get_content(self):
return str(self.content)
def get_size(self):
return str(self.size)
class Directory(Entry):
def __init__(self, name, parent_dir):
Entry.__init__(self, name, parent_dir)
self.contents = []
# self.num_of_items = 0
def add_entry(self, item):
item_type = type(item)
item_name = item.name
# Search through list.
for folder_item in self.contents:
if (folder_item.name == item_name) and (type(folder_item) == item_type):
print('File with that name exists.')
return False
# Can add this item?
self.contents.append(item)
# self.num_of_items += 1
return True
def delete_entry(self, item):
# Delete an item in this folder.
try:
self.contents.remove(item)
# self.num_of_items -= 1
except:
print('File or folder does not exist.')
def get_contents(self):
content_str = ''
for content in self.contents:
if len(content_str) > 0:
content_str += '\n'
content_str += str(content)
# content_str += '\n'
print(content_str)
def get_size(self):
size = 0
for item in self.contents:
if type(item) is File:
size += item.size
else:
# Get the size of the contents within that folder.
size += item.get_size()
return size
def get_num_of_items(self):
return len(self.contents)
| true |
005103cb3b2736711e6dd9a194a19cb0db8bd420 | jcs-lambda/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,016 | 4.34375 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# initialize first window and max
window = nums[:k]
current_max = max(window)
maxes = [current_max]
# slide window
for x in nums[k:]:
# add newest value to window
window.append(x)
# remove oldest value from window, and,
# if it equals the current max,
# then recalculate the current max
if window.pop(0) == current_max:
current_max = max(window)
# check if newest value is max
elif x > current_max:
current_max = x
# store maximum for this window
maxes.append(current_max)
return maxes
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
9a40b9d9bee4f82ba28a3f9d2124440df6cf9ab7 | DAGG3R09/coriolis_training | /assignments/Q10_overlapping.py | 318 | 4.125 | 4 |
def is_overlapping (l1, l2):
for le1 in l1:
for le2 in l2:
if le1 == le2:
return True
return False
if __name__ == "__main__":
l1 = [1, 2, 3, 4, 5]
l2 = [5, 6, 7, 8, 9]
l3 = [6, 7, 8, 9, 10]
print(is_overlapping(l1, l2))
print(is_overlapping(l1, l3)) | false |
f01f3cb9fdf5bd6c4167da2ff209ec7df0308681 | subashchandarA/Python-Lab-Pgms-GE8151- | /11MostFrequentWord.py | 660 | 4.34375 | 4 | #Most Frequent word in a string
#str="is program is to find the of the word in the string"
filename=input("Enter the file name to find the most frequent word: ")
fo=open(filename,'r')
str=fo.read()
print("The given string is :",str)
wordlist = str.split(" ")
d={}
for s in wordlist:
if( s in d.keys()):
d[s]=d[s]+1
else:
d[s]=1
#Frequency: each word as key and frequency is its value
print("Dictionary containing word and its frequency:",d)
m = max(d.values())
print(m)
for key in d:
if(d[key]==m):
result=key
print(" The most frequent word : ",result)
print(" It is present ",m," times")
| true |
5dac50e3ef0821386d271fe18a353c279e69ea1e | subashchandarA/Python-Lab-Pgms-GE8151- | /6.1 selecion sort(python method).py | 1,356 | 4.21875 | 4 | def selectionsort(lt):
"select the min value and insert into its position"
for i in range(len(lt)-1):
#min_pos=x
#for x in range(i+1,len(lt)):
# if(lt[min_pos]>lt[x]):
# min_pos=x
min_pos=lt[i:].index(min(lt[i:])) # FIND THE INDEX OF MINIMUM ELEMENT FROM i
lt[min_pos+i],lt[i]=lt[i],lt[min_pos+i] # SWAP THE MINIMUM ELEMENT WITH ith ELEMENT
print(lt) #Print the list to see the each step of selection sort
n=int(input("Enter the number of values:"))
lt = [] # creation of empty list
#getting n values and store in a list
i=30
while(i<n):
number=int(input("Enter a value to store:"))
lt.append(number)
i=i+1
lt=[5,8,12,55,3,7,50]
print("Before Selcection Sort : ",lt)
selectionsort(lt)
print("After Selcection Sort : ",lt)
#OUTPUT 1
#Enter the number of values:6
#Enter a value to store:23
#Enter a value to store:80
#Enter a value to store:250
#Enter a value to store:10
#Enter a value to store:500
#Enter a value to store:50
#Before Selcection Sort : [23, 80, 250, 10, 500, 50]
#[10, 80, 250, 23, 500, 50]
#[10, 23, 250, 80, 500, 50]
#[10, 23, 50, 80, 500, 250]
#[10, 23, 50, 80, 500, 250]
#[10, 23, 50, 80, 250, 500]
#After Selcection Sort : [10, 23, 50, 80, 250, 500]
| true |
773762755424c84ef55b4218da57e14bfcdaf07a | kevinpalacio/AprendiendoPython | /Aleatorio.py.py | 1,010 | 4.21875 | 4 | # Autor : Kevin Oswaldo Palacios Jimenez
# Fecha de creacion: 16/09/19
# Python tendra varios modulos(module), estos modulos son
# librerias que tiene python
# Se necesita in modulo para un programa,
# import, es la primera instruccion que debera estan presente
# en la consola
import random
# Definimos una variable float con un valor asignado
numero1=float(10.5)
# Debemos usar una funcion ya que estan cuentan
# con cumplir con un objetivo en especial
# despues de la funcion se mostrara en la pantalla
# lo que sera parte de la funcion siempre y cuando
# este dentro de ella de esa manera se cumplira
def miFuncion():
# random.randrange lo que hace es tener un numero al azar
# el cual se convierte en tipo float
numero2=float(random.randrange(1,10))
mensaje="La suma de {} y {} es de {}"
print(mensaje.formart(numero1,numero2.numero1+numero2))
# Al terminar la funcion con la cual tengamos las indicaciones
# correctas esta definira el codigo
miFuncion() | false |
a7cd794a1ef6fc543980181f1cf7144b6dd6639f | ShreyaPriyanil/Sorting-in-Python | /insertionsort.py | 514 | 4.21875 | 4 | def insertionSort(alist):
for index in range(1,len(alist)):
print("TRAVERSAL #: ",index)
position = index
while position>0 and alist[position-1]>alist[position]:
temp = alist[position]
alist[position] = alist[position-1]
alist[position-1] = temp
position = position-1
print("ARRAY AFTER TRAVERSAL #:",index," ", alist)
alist = [5,4,3,2,1]
print("---------------------NEW---------------------")
insertionSort(alist)
print(alist)
| true |
df1eb693316cd623603e43fbee56746b8445b821 | shivdazed/Python-Projects- | /Exceptionhandling.py | 324 | 4.15625 | 4 | try:
a = int(input("Enter the number A:"))
b = int(input("Enter the number B:"))
c = a/b
print(c)
#except Exception as e:
# print(e)
except ZeroDivisionError:
print("We can't divide by zero")
except ValueError:
print("Your entered value is wrong")
finally:
print("Sum = ",a+b)
| true |
8b886230b5e8b749480f899bac95868e99d0c48b | shivdazed/Python-Projects- | /Calci.py | 553 | 4.28125 | 4 | print("Enter two numbers into the calci\n")
n1 = int(input("Enter the first number---"))
n2 = int(input("Enter the second number---"))
o = input("Choose operator--\n'+'~Addition \n'-'~Subtraction\n'*'~Multiplication\n'/'~Division\n")
if o == '+':
print(f"The sum of {n1} and {n2} ={n1+n2}")
elif o == '-':
print(f"The difference of {n1} and {n2} ={n1-n2}")
elif o == '*':
print(f"The product of {n1} and {n2} ={n1*n2}")
elif o == '/':
print(f"The quotient of {n1} and {n2} ={n1/n2}")
else:
print("Invalid Input")
| false |
08e7e22f6f39a02caca937e0fca7982fb33c901c | Poonam-Singh-Bagh/python-question | /Loop/multiplication.py | 228 | 4.21875 | 4 | ''' Q.3 Write a program to print Multiplication of two numbers
without using multiplication operator.'''
i = 1
a = int(input("enter a no."))
b = int(input("enter a no."))
c = 0
while i <= b:
c = c + a
i = i + 1
print (c) | true |
13cd95427f9fed8977a2b5de25abae5c22d361c6 | ONJoseph/Python_exercises | /index game.py | 1,013 | 4.375 | 4 | import random
def main():
# 1. Understand how to create a list and add values
# A list is an ordered collection of values
names = ['Julie', 'Mehran', 'Simba', 'Ayesha']
names.append('Karel')
# 2. Understand how to loop over a list
# This prints the list to the screen one value at a time
for value in names:
print(value)
# 3. Understand how to look up the length of a list
# Use randint to select a valid "index"
max_index = len(names) - 1
index = random.randint(0, max_index)
# 4. Understand how to get a value by its index
# Get the item at the chosen index
correct_answer = names[index]
# This is just like in Khansole Academy...
# Prompt user for an answer and check whether correct or not
prompt = 'Who is in index...' + str(index) + '? '
answer = input(prompt)
if answer == correct_answer:
print('Good job')
else:
print('Correct answer was', correct_answer)
if __name__ == '__main__':
main()
| true |
ca67ed3630bf2bf15468aaacd138312cb1854ad8 | shubhamjha25/FunWithPython | /coin_flipping_game/coinflipgame.py | 635 | 4.21875 | 4 | import random
import time
print("-------------------------- COIN FLIPPING GAME -----------------------------")
choice = input("Make your choice~ (heads or tails): ")
number = random.randint(1,2)
if number == 1:
result = "heads"
elif number == 2:
result = "tails"
print("-------------------------------- DECIDING ----------------------------------")
time.sleep(2)
if choice == result:
print("WOOOOO WELL DONE YOU WON!!!! The coin you flipped were", result)
else:
print("Awww man, you lose. But you can run the script again y'know, The coin you flipped were", result)
print("Thanks for playing the coin flipping game!!!") | true |
d1cee333a1147bc53c0040e732128b8a5d05abca | Anisha7/Tweet-Generator | /tasks1-5/rearrange.py | 1,612 | 4.28125 | 4 | # build a script that randomly rearranges a set of words provided as command-line arguments to the script.
import sys
import random
# shuffles given list of words
def rearrange(args):
result = []
while (len(args) > 0) :
i = random.randint(0, len(args)-1)
result.append(args.pop(i))
return result
# takes string word and reverses it
def reverse_word(word):
rev_word = ""
for i in range(len(word)):
rev_word += word[len(word) - 1 - i]
return rev_word
# takes in a string sentence and returns reversed string
def reverse_sentence(sentence):
l = sentence.split(" ")
new = ""
for i in range(len(l)):
new += l[len(l) - 1 - i] + " "
return new;
def game():
option = input("Do you want to (A) rearrange, (B) reverse word, (C) reverse sentence? ")
if (option == 'A' or option == 'a'):
args = input("Give me a list of words: ")
result = rearrange(args.split(" "))
print(" ".join(result))
elif (option == 'B' or option == 'b'):
word = input("Give me a word to reverse: ")
result = reverse_word(word)
print(result)
else :
sentence = input("Give me a sentence to reverse: ")
result = reverse_sentence(sentence)
print(result)
return;
def run():
# args = sys.argv[1:]
# result = rearrange(args)
# print(" ".join(result))
gameState = input("Do you want to play (y/n)? ")
while (gameState == 'y' or gameState == 'Y'):
game();
gameState = input("Do you want to play again (y/n)? ")
return;
run() | true |
bb8749c3abda670d006b2184f7b620449bb54f07 | joseramirez270/pfl | /Assignment4/generate_model.py | 1,180 | 4.1875 | 4 | """modify this by generating the most likely next word based on two previous words rather than one. Demonstrate how it works with a corresponding conditional frequency distribution"""
import nltk
"""essentially, this function takes a conditional frequency distribution of bigrams and a word and makes a sentence.
Each time, a loop prints the current word, then looks for the next word by finding the most frequent word that appears in texts after it.
It then prints that word, and the process repeats again, generating the random sentence"""
def generate_model(cfdist, word, num=15):
for i in range(num):
print(word, end = ' ')
word = cfdist[word].max()
def generate_model2(cfdist, bigram, num=15):
for i in range(num):
print(bigram[0], end = ' ')
bigram = cfdist[bigram].max()
text = nltk.corpus.genesis.words('english-kjv.txt')
bigrams = nltk.bigrams(text)
bigramsofbigrams = nltk.bigrams(bigrams)
cfd = nltk.ConditionalFreqDist(bigramsofbigrams)
bigrams = nltk.bigrams(text)
cfd2 = nltk.ConditionalFreqDist(bigrams)
generate_model(cfd2, 'in')
print('\n')
generate_model2(cfd, ('in', 'the'))
#print(cfd[('in', 'the')].max())
| true |
0a93e0ded92ef09809aa22bd801667587171f6ed | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_10_19Projects/dateClass.py | 1,918 | 4.15625 | 4 | #Class practice
class Date:
def __init__(self, m, d):
self.__month = m
self.__day = d
#Returns the date's day
def get_day(self):
return self.__day
#Returns the date's month
def get_month(self):
return self.__month
#Returns number of days in this date's month
def days_in_month(self):
print()
#Modifies date by 1
def next_day(self):
print()
def compare(self, mon, day):
if mon > self.__month:
return -1
elif mon == self.__month and day == self.__day:
return 0
elif mon == self.__month and day < self.__day:
return 1
elif mon == self.__month and day > self.__day:
return -1
else:
return 1
def main():
dayList = [31,30,31,30,31,30,31,31,30,31,30,31]
try:
month = int(input("Enter month #: "))
day = int(input("Enter the day #: "))
secMonth = int(input("Enter second month #: "))
secDay = int(input("Enter the second day #: "))
except ValueError:
print("(ノಠ益ಠ)ノ彡┻━┻")
else:
if (month > 12 or month < 0) or dayList[month - 1] < day or day < 0:
print("(ಥ ╭╮ಥ )")
print("Check Your Dates...")
elif (secMonth > 12 or secMonth < 0) or dayList[month - 1] < secDay or day < 0:
print("ಡ _ಡ")
print("Check Your Dates...")
else:
dateVar = Date(month, day)
compRes = dateVar.compare(secMonth, secDay)
if compRes == -1:
print("First date comes before the second date.")
elif compRes == 0:
print("SAME DAY REEEEEE")
else:
print("Second date comes before the first date.")
main() | true |
ac1971b1544ccb491d9ed862258cc4bf3dbccae2 | inbsarda/Ccoder | /Python_codes/linked_list.py | 2,030 | 4.1875 | 4 | ###################################################
#
# Linked List
#
###################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
def insertAtBegining(head,data):
'''
Insert node at begining
'''
newnode = node(data)
newnode.next = head
return newnode
def insertAtEnd(head, newnode):
'''
Insert node at the end
'''
if head is None:
head = newnode
return
while head.next != None:
head = head.next
head.next = newnode
def insertInBetween(middlenode, newnode):
'''
Insert node in between of the list
'''
if middlenode is None:
print("Node is absent")
return
newnode.next = middlenode.next
middlenode.next = newnode
def deleteNode(head, data):
'''
Remove the node from linked list
'''
if head.data == data:
Head = head
head = head.next
Head = None
return
while head.data != data:
prev = head
head = head.next
if head is None:
break
if head is None:
print("node not found")
return
else:
prev.next = head.next
head = None
def findMiddle(head):
'''
Find middle of the linked list
'''
node1 = node2 = head
if head is None:
print("Empty list")
while node2 is not None and node2.next is not None:
node1 = node1.next
node2 = node2.next.next
return node1
def printList(head):
'''
Trverse and print the list
'''
while head != None:
print(head.data)
head = head.next
head = node("mon")
e1 = node("Tue")
e2 = node("wed")
head.next = e1
e1.next = e2
e3 = node("thu")
insertAtEnd(head, e3)
e4 = node("fri")
insertInBetween(head.next, e4)
head = insertAtBegining(head, "sun")
deleteNode(head, "fri")
deleteNode(head, "sun")
printList(head)
middle = findMiddle(head)
print(middle.data)
| true |
a4c58d8162dbb4317ec0cfced87e8e3c71860f74 | inbsarda/Ccoder | /Python_codes/reverse_list.py | 1,161 | 4.3125 | 4 | ##################################################################
#
# Reverse the linked list
#
##################################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head = None
def insert(self, data):
ptr = node(data)
if self.head is None:
self.head = ptr
return
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = ptr
def printlist(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
def reverselist(self):
temp = self.head
prev = None
fwd = None
while temp is not None:
#print(temp.data)
fwd = temp.next
temp.next = prev
prev = temp
temp = fwd
self.head = prev
llist = linkedlist()
llist.insert("sun")
llist.insert("mon")
llist.insert("tue")
llist.insert("wed")
llist.printlist()
llist.reverselist()
llist.printlist()
| true |
a1593b01f3f3c09d1c392c63612e81506d90243a | doritger/she-codes-git-course-1 | /ex2.py | 1,049 | 4.28125 | 4 | from datetime import datetime
# imports current date and time
def details():
first_name = input("Please enter your first name: ")
surname = input("Please enter your surname: ")
birth_year = input("Please enter the year of your birth: ")
# asks the user to enter name, surname and year of birth
print (first_name)
print (surname)
print (birth_year)
# prints the name, surname and year of birth of the user
currentYear = datetime.now().year
# calcuates current year
age = (int (currentYear)) - (int (birth_year))
# changes the strings 'currentYear' & 'birth_year' to intergals
# and calcuates the user's age according to current year
print ("Your initials are " + first_name[0].upper()
+surname[0].upper() + " and you are " + str (age)
+ " years old.")
# changes the intergal 'currentYear' to a string
# and prints the user's initials (first letter of the name & surname)
# and the user's age
# .upper() to have the initials in uppercase letters
details()
| true |
57044de69024d956548f000f130d1afe3b48e66a | Raiane-nepomuceno/Python | /Parte 1/Lista 01/011.py | 501 | 4.25 | 4 | n= int(input('Digite o número:'))
if n%2== 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por:2,5,10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por 5 e 10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 != 0:
print('O número {} é divisível apenas por 5'.format(n))
elif n%2== 0 and n%5 != 0 and n%10 != 0:
print('O número {} é divisível apenas por 2'.format(n))
else:
print('Nenhum dos números são divisíveis')
| false |
7d315d98c3d2b268a600eee898b046512c0a42df | Raiane-nepomuceno/Python | /Parte 2/EXERCÍCIOS DE LISTAS/004.py | 600 | 4.15625 | 4 | #Crie um programa que leia
#Inicialmente uma sequencia de
#N números inteiros
#e mostre ao final 2 listas: uma sem repetição e outra dos elementos repetidos
op = 1
lista_rep = []
lista3 = []
while op == 1:
op = int(input('Deseja adicionar o elemento [1-sim/2-não]:'))
if op == 1:
n = int(input('Num:'))
if n not in lista3:
lista3.append(n)
elif n in lista3:
lista_rep.append(n)
if op == 2:
print('Lista sem repetição:',lista3)
print('Lista dos elementos repetidos:',lista_rep)
| false |
59c1517b2ad8cfac4d186e417859ae5dbd190575 | pythoncoder999/Python | /AutomateTheBoringStuff/myPets.py | 272 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 01:06:29 2019
@author: Gunardi Saputra
"""
myPets = ["One", "Two", "Three"]
print("Enter a pet name: ")
name = input()
if name not in myPets:
print("I do not have a pet named " + name)
else:
print(name + " is my pet.")
| false |
5fe884067f7af8df12f114e84a40953cab414d6e | abby-does-code/youtube_practice_intmd | /dictionaries!!.py | 2,766 | 4.3125 | 4 | # START
## Keep chugging away bb!
# Dictionary: data type that is unordered and mutable
##Consists of key:value pairs; maps value to associated pair
# Create a dictionary(30:00)
mydict = {"name": "Max", "age": 28, "city": "New York"}
print(mydict)
# Dict method for creation
# mydict2 = dict(name = "Mary", age = 27, city = "Boston")
# print(mydict2)
# Acessing values (31:35)
value = mydict["name"]
print(value)
# Weird, i thought that created a value.
value = mydict["age"]
print(value)
# Adding or changing values (32:18)
##Dictionaries are mutable!
###Fun note: name was moved to the back of the dictionary?
mydict["email"] = "Max@xyz.com"
print(mydict)
"""
# Deleting a method
###I commented this out so I can keep working without retyping code lol###
del mydict["name"]
print(mydict)
mydict.pop("age")
print(mydict)
mydict.popitem() #removes the first item??
print(mydict)
"""
# Checking for value
if "name" in mydict:
print(mydict["name"])
##Try and except method? (35:05)
try:
print(mydict["name"])
except:
print("Error")
try:
print(mydict["lastname"])
except:
print("Error! That's not in the dictionary silly goose.")
# Iterating through a dictionary (36:00)
# For loops:
for key in mydict:
print(key) # prints all keys
for key in mydict.keys():
print(key)
for value in mydict.values():
print(value)
for key, value in mydict.items():
print(key, value)
# Copyign a dictionary
##Be careful!
mydict_copy = mydict
print(mydict_copy)
# Modifying the copy modifies the OG! commented out so the proper code works lol
"""
mydict_copy["email"] = "max@123.com"
print(mydict_copy, mydict)
"""
# Notice, just like lists, this changes the OG as well. This is becuase you're referencing the same point in the memory.
# Making a copy that's independent of your OG:
mydict_copy = mydict.copy()
print(mydict_copy)
mydict_copy["email"] = "max@123.com"
print(mydict_copy, mydict)
# Updating a dictionary (39:15)
my_dict = {"name": "Max", "age": 56, "email": "eww@eww.com"}
my_otherdict = dict(name="Martha", age=102, city="Hotlanta")
my_dict.update(my_otherdict)
print(my_dict)
# This is FASCINATING! All existing key pairs were overwritten; email was NOT becuase it was not an item in my_otherdict
# Possible key types
##Can use any immutable type
###Can even use a tuple???
my_dict = {3: 9, 6: 36, 9: 81}
print(my_dict)
# value = my_dict[0]
# Error! Zero isn't in our list and it's not an index. Use the actual key to access.
value = my_dict[3]
print(value) # This will return the value 9!
# Use a tuple as a key
mytuple = (8, 7)
my_dict = {mytuple: 15}
print(my_dict)
# Tuples are possible, but a list would throw an exception
# Lists are mutable and can be changed; so it's not hashable and can't be used as a key
| true |
a6e6b869f5de7d169dc668b4967332bea5498ae1 | shanbumin/py-hundred | /Day01-15/Day12/demo01/main.py | 1,103 | 4.4375 | 4 | # 字符串常用操作
print('My brother\'s name is \'007\'') # 转义字符
print(r'My brother\'s name is \'007\'') # 原始字符串
# -------------------------------------------------------
str = 'hello123world'
print('he' in str) #True
print('her' in str) #False
print(str.isalpha()) # 字符串是否只包含字母 False
print(str.isalnum()) # 字符串是否只包含字母和数字 True
print(str.isdecimal()) # 字符串是否只包含数字 False
print(str[0:5].isalpha()) #True
print(str[5:8].isdecimal()) #True
# ------------------------------------------------------------------
list = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']
print('-'.join(list)) #床前明月光-疑是地上霜-举头望明月-低头思故乡
#----------------------------------------------
sentence = 'You go your way I will go mine'
words_list = sentence.split()
print(words_list) #['You', 'go', 'your', 'way', 'I', 'will', 'go', 'mine']
#----------------------------------------------
email = ' jackfrued@126.com '
print(email)
print(email.strip())
print(email.lstrip())
| false |
18f75cc839f336f3a2f815a578eb5871ad2a7f5c | pranabsg/python-dsa | /get_fibonacci.py | 381 | 4.28125 | 4 | """Implement a function recursively to get the desired
Fibonacci sequence value.
"""
def get_fib(position: int) -> int:
if position == 0 or position == 1:
return position
return get_fib(position - 1) + get_fib(position - 2)
def main():
# Test cases
print(get_fib(2))
print(get_fib(11))
print(get_fib(0))
if __name__ == '__main__':
main()
| true |
f78a79c275e90a90394269b230cdef39dbc4d979 | danecashion/python_example_programs | /first_largest.py | 284 | 4.5625 | 5 | """
Python program to find the largest element and its location.
"""
def largest_element(a):
""" Return the largest element of a sequence a.
"""
return None
if __name__ == "__main__":
a = [1,2,3,2,1]
print("Largest element is {:}".format(largest_element(a)))
| true |
ba9c31ebc3df8d7c0379d0face66c3e4dfecd9e1 | deepdc19/Practice_Problems | /piToNth_chudnovsky.py | 1,006 | 4.1875 | 4 | from decimal import Decimal
from decimal import getcontext
def factorial(n):
'''
Factorial function to find the factorial of the functions
https://en.wikipedia.org/wiki/Factorial
'''
if n < 1:
return 1
else:
return n * factorial(n-1)
def piToNth(num):
'''
chudnovsky-algorithm to compute pi to 'num' digit
https://en.wikipedia.org/wiki/Chudnovsky_algorithm
'''
pi = Decimal(0)
k = 0
while k < num:
first = Decimal(-1)**(k)
second = Decimal(factorial(6*k))
third = Decimal((545140134*k + 13591409))
fourth = Decimal(factorial(3*k))
fifth = Decimal((factorial(k)**3))
sixth = Decimal((640320)**((3*k+3)/2))
pi += (first*second*third)/(fourth*fifth*sixth)
k = k + 1
pi = (pi ** Decimal(-1)) / Decimal(12)
return pi
num = Decimal(input("Give the position till which you want the Pi to be tracked: "))
getcontext().prec = int(num)
print(piToNth(num))
| false |
8bf8929bbfe763af15cf61cdb294ca78b59bc057 | annamwebley/PokerHand | /deck.py | 2,626 | 4.15625 | 4 | # Project 3b
# Anna Markiewicz
# May 12
# deck.py
# Shuffle the Card objects in the deck
import random
from card import Card
class Deck:
"""Card Deck, which takes self as input, and creates a deck of cards
"""
def __init__(self):
self.cards = [ ]
for suit in ['C', 'D', 'H', 'S']:
for rank in range(2,15):
# print(f"I am creating suit = {suit}, rank = {rank}")
# create a new card with the specified rank
# and suit and append it to the list.
self.cards.append(Card(rank, suit))
def __str__(self):
output = ""
# Concatenate card to
# the output variable
for card in self.cards:
output = output + str(card) + " "
return output
def __repr__(self):
return str(self)
def shuffle(self):
# print("I am shuffling cards...")
random.shuffle(self.cards)
def deal_card(self):
# # Remove the card from the top of the cards list and save it as the Card object c
# print (len(self.cards))
# print("I am popping one card...")
return self.cards.pop()
def pop_card(self):
# # Remove the card from the top of the cards list and save it as the Card object c
# print (len(self.cards))
# print("I am popping one card...")
return self.cards.pop()
def count_cards(self):
# print("I am counting cards...")
return (len(self.cards))
def is_empty(self):
if not self.cards:
return True
else:
return False
def add_to_top(self, rank, suit):
# Create a new card with the specified rank and suit and append it to the cards in the deck
c = Card(rank, suit)
self.cards.append(c)
return self.cards[-1]
def add_to_bottom(self, rank, suit):
# Insert the card c at the bottom of the deck (before the item with index 0)
c = Card(rank, suit)
self.cards.insert(0, c)
return self.cards[0]
if (__name__) == '__main__':
deck = Deck()
#print(f"deck.cards = {deck.cards[7]}")
# for card in deck.cards:
# print(card)
deck.shuffle()
print(deck)
deck.deal_card()
print(deck.deal_card())
deck.pop_card()
print(deck.pop_card())
deck.count_cards()
print(deck.count_cards())
deck.is_empty()
print(deck.is_empty())
c = Card(10, "H")
deck.add_to_top(10, "H")
print(deck.add_to_top(10, "H"))
c = Card(8, "C")
deck.add_to_bottom(8, "C")
print(deck.add_to_bottom(8, "C"))
| true |
492eddbeffe120a0ca71fc4767ce8e6523b04978 | lshpaner/python-datascience-cornell | /Analyzing and Visualizing Data with Python/Importing and Preparing Data/LoadDataset.py | 2,531 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Analyzing the World Happiness Data
#
#
# ### Preparing the data for analysis
# In this exercise, we will do some initial data imports and preprocessing to get the data ready for further analysis. We will repeat these same basic steps in subsequent exercises. Begin by executing the code cell below to import some necessary packages. Note that the last line in the code cell below is intended to instruct pandas to display floating point numbers to 2 decimal places (`.2f`). This is just one of many pandas display options that can be configured, as described [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html).
# In[1]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
pd.options.display.float_format = '{:.2f}'.format
# ### Step 1
#
# Create a Pandas dataframe named ```dfraw``` by reading in the data in the worksheet named "Table2.1" from the spreadsheet "WHR2018Chapter2OnlineData.xls".
# In[2]:
dfraw = pd.read_excel('WHR2018Chapter2OnlineData.xls', sheet_name='Table2.1')
# To facilitate working with the data, it will be useful to select a subset of the data from the full dataset and to rename the columns to make them less verbose. In the code cell below, the variable ```cols_to_include``` contains a list of column names to extract.
# Execute the cell.
# In[3]:
cols_to_include = ['country', 'year', 'Life Ladder',
'Positive affect','Negative affect',
'Log GDP per capita', 'Social support',
'Healthy life expectancy at birth',
'Freedom to make life choices',
'Generosity', 'Perceptions of corruption']
# ### Step 2
#
# Using the variables defined above, in the code cell below, write and evaluate an expression to create a new dataframe named `df` that includes the subset of data in `cols_to_include`.
# ## Graded Cell
#
# This cell is worth 100% of the grade for this assignment.
# In[4]:
df = dfraw[cols_to_include]
# ## Self-Check
#
# Run the cell below to test the correctness of your code above before submitting for grading.
# In[5]:
# Run this self-test cell to check your code; do not add code or delete code in this cell
from jn import testDf
try:
print(testDf(df, dfraw))
except Exception as e:
print("Error!\n" + str(e))
# ### Step 3.
#
# Take a peek at the head of the new dataframe.
# In[6]:
df.head()
| true |
28b512c74e3fd196b8ca592e9c81d72bfe1f9672 | lshpaner/python-datascience-cornell | /Constructing Expressions in Python/Computing the Average (Mean) of a List of Numbers/exercise3.py | 975 | 4.53125 | 5 | """
Computing the Average (Mean) of a List of Numbers
Author: Leon Shpaner
Date: July 19, 2020
In exercise3.py in the code editor window, create a new list containing a
mixture of letters and numbers: my_other_list = [1, 2.3, 'a', 4.7, 'd'], and
write an expression computing its average value using a similar expression as
the one you previously wrote, storing the result in my_other_list_average.
"""
my_other_list = [1, 2.3, 'a', 4.7, 'd']
# Set a running total for elements in the list, initialized to 0
total = 0
# Set a counter for the number of elements in the list, initialized to 0
num_elements = 0
# Loop over all the elements in the list
for element in my_other_list:
# Add the value of the current element to total
total = total + element
# Add 1 to our counter num_elements
num_elements = num_elements + 1
# Compute the average by dividing the total by num_elements
average = total / num_elements
my_other_list_average= total/len(my_other_list) | true |
98269365703f82e15da200949483316583454b29 | lshpaner/python-datascience-cornell | /Writing Custom Python Functions, Classes, and Workflows/Simple Ciphers With Lists and Dictionaries/exercise.py | 2,492 | 4.59375 | 5 | """
Simple Ciphers With Lists and Dictionaries
Author: Leon Shpaner
Date: August 14, 2020
"""
# Examine the starter code in the editor window.
# We first define a character string named letters which includes all the
# upper-case and lower-case letters in the Roman alphabet.
# We then create a dictionary (using a one-line dictionary comprehension) named
# cipher that maps each letter to another letter shifted three to its left in
# the list of all letters.
# Run the starter code in the interpreter and print the contents of the cipher.
# You should see that it maps each letter in letters to a different letter.
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
cipher = {letters[i]: letters[(i-3) % len(letters)] for i in range(len(letters))
}
# Let’s encrypt some messages now, using cipher. In the code editor, write the
# function named transform_message(message, cipher) that takes two inputs: a
# message that you want to encrypt, and a cipher to do the encryption. The body
# of this function is rather simple: it initializes an empty string named tmsg,
# loops over the characters in the input message, transforms them according to
# the cipher, and sticks that transformed character onto the end of tmsg. Once
# the entire message is transformed, the transformed message is returned.
def transform_message(message, cipher):
tmsg = ''
for c in message:
tmsg = tmsg + (cipher[c] if c in cipher else c)
return tmsg
"""
The starter code has a test message (named test). Try your transform_message
function on the test message: does the output look like this:
'F Zljb ql Yrov zXbpXo, klq ql moXfpb efj.'? In addition to having it printed
out on the screen, you should also save the transformed message to a variable
named ttest, so that we can reuse it later.
"""
test = "I come to bury Caesar, not to praise him."
# Having a coded message does not help you so much if you don’t have a way to
# decode it. Fortunately, we can do that just by creating another cipher. In the
# code editor, define a new dictionary named decoder that maps from a
# transformed letter back to the original letter, i.e., it just undoes the
# transformation that the original cipher did. The easiest way to do this is to
# recognize that the cipher is a dictionary that maps keys to values, and you
# want a different dictionary that maps the values back to keys.
decoder = {letters[i]: letters[(i+3) % len(letters)] for i in range(len(letters)
)} | true |
060467da007c90e930786d0e4cb38b8cb52940e5 | eyjolfurben/Assignment5 | /Fair traffic lights.py | 1,316 | 4.28125 | 4 | north_int = int(input("Number of cars travelling north: "))
south_int = int(input("Number of cars travelling south: "))
east_int = int(input("Number of cars travelling east: "))
west_int = int(input("Number of cars travelling west: "))
sum_of_all_cars = north_int + south_int + east_int + west_int
north_counter = north_int
south_counter = south_int
east_counter = east_int
west_counter = west_int
north_and_south_sum = north_counter + south_counter
east_and_west_sum = east_counter + west_counter
while sum_of_all_cars > 0:
if north_and_south_sum >= east_and_west_sum:
print("Green light on N/S")
north_counter -= 5
south_counter -= 5
if north_counter < 0:
north_counter = 0
if south_counter < 0:
south_counter = 0
north_and_south_sum = north_counter + south_counter
elif east_and_west_sum > north_and_south_sum:
print("Green light on E/W")
east_counter -= 5
west_counter -= 5
if east_counter <0:
east_counter = 0
if west_counter < 0:
west_counter =0
east_and_west_sum = west_counter + east_counter
sum_of_all_cars = east_and_west_sum + north_and_south_sum
print("No cars waiting, the traffic jam has been solved!") | false |
bcdb572bcbba2ed318e0d0d9121285be989d6621 | lastcanti/effectivePython | /item3helperFuncs.py | 848 | 4.4375 | 4 | # -----****minimal Python 3 effective usage guide****-----
# bytes, string, and unicode differences
# always converts to str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
# always converts to bytes
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str,str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
# create str var a and make sure its str
a = to_str("andrew")
print(a)
# create str var and convert to bytes
a = to_bytes(a)
print(a)
# bytes are sequences of 8-bit values
# bytes and str instances are not compatible
# use helper functions to ensure inputs are proper type
# always open file in binary mode('rb' or 'wb') if you want to
# read or write to file
| true |
dca014bef7c07c1f91b5d666afeb53f930ff0892 | shobnaren/python-codes | /Sorting Algorithms/Bubble_sort.py | 391 | 4.21875 | 4 |
def Bubble_sort(arr):
for k in range(0,len(arr)-2):
for i in range(0,len(arr)-k-1):
if arr[i+1] < arr[i]:
temp = arr[i+1]
arr[i+1]=arr[i]
arr[i]=temp
print(arr)
print("Sorted array using Buble sort:",arr)
if __name__ == '__main__':
Arr = [0,3,4,5,1,6,7,8]
print(Arr)
Bubble_sort(Arr)
| false |
6e27535bde7a1978b86b9d03381e72a745af83ed | VladislavRazoronov/Ingredient-optimiser | /examples/abstract_type.py | 1,520 | 4.28125 | 4 | class AbstractFood:
"""
Abstract type for food
"""
def __getitem__(self, value_name):
if f'_{value_name}' in self.__dir__():
return self.__getattribute__(f'_{value_name}')
else:
raise KeyError('Argument does not exist')
def __setitem__(self, value_name, value):
if f'_{value_name}' in self.__dir__():
self.__setattr__(f'_{value_name}', value)
else:
raise KeyError('Argument does not exist')
def compare_values(self, other, value):
"""
Compares given values of two food items
"""
if value in self.__dir__() and value in other.__dir__():
return float(self.__getattribute__(value)) > float(other.__getattribute__(value))
else:
return "Can't compare values"
def __eq__(self, other):
"""
Checks if two food items are the same
"""
if self is other:
return True
if type(self) == type(other):
return self._name == other._name and self._calories == other._calories and \
self._carbohydrates == other._carbohydrates and self._fat == other._fat\
and self._proteins == other._proteins
def __str__(self):
"""
Returns string representation of food
"""
return f'{self._name} has {self._calories} calories, {self._carbohydrates}' +\
f'g. carbohydrates, {self._fat}g. of fat and {self._proteins}g. of proteins'
| true |
d30b39de24b1a1692b5c27899af47a1a73b1d1e5 | Confucius-hui/LeetCode | /从排序数组中删除重复项.py | 1,180 | 4.1875 | 4 | '''
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
'''
class Solution:
def removerDuplicates(self,nums):
'''
:param nums: list[int]
:return: int
'''
i = 0
while i<len(nums)-1:
if nums[i] == nums[i+1]:
nums.remove(nums[i+1])
else:
i+=1
return len(nums)
if __name__ == '__main__':
nums = [1,1,2]
s = Solution()
length = s.removerDuplicates(nums)
print(length)
print(nums)
'''
#remove删除首个符合条件的元素,并不删除特定的索引。
n =[1,2,2,3,4,5]
n.remove(3)
print (n)
#输出 [1, 2, 2, 4, 5]
####----------------#######################
#pop按照索引删除字符,返回值可以付给其他的变量,返回的是你弹出的那个数值。
n =[1,2,2,3,4,5]
a=n.pop(4)
print (a)
print (n)
#输出
4
[1, 2, 2, 3, 5]
#####--------#####
#del按照索引删除字符,返回值不可以付给其他的变量。
n =[1,2,2,3,4,5]
del(n[3])
print (n)
#输出
[1, 2, 2, 4, 5]
''' | false |
498efd52ff80b4f7defd7b9fa0ca851e79ea39b7 | Confucius-hui/LeetCode | /排序算法/Sort.py | 1,873 | 4.15625 | 4 | ##快速排序、冒泡排序、归并排序
class Sort:
def Quicksort(self,nums,start,end):
if start<end:
i = start
j = end
x = nums[start]
while i<j:
while i<j and nums[j]>x:
j-=1
if i<j:
nums[i] = nums[j]
i+=1
while i<j and nums[i]<x:
i+=1
if i<j:
nums[j] = nums[i]
j-=1
nums[i] = x
self.Quicksort(nums,start,i-1)
self.Quicksort(nums,i+1,end)
def BubbleSort(self,nums):
for i in range(len(nums)-1):
for j in range(len(nums)-i-1):
if nums[j]>nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
def MergeSort(self,nums):
if len(nums)<=1:
return nums
mid = len(nums)//2
left = self.MergeSort(nums[:mid])
right = self.MergeSort(nums[mid:])
return self.Merge(left,right)
def Merge(self,left,right):
i = 0
j = 0
result = []
while i<len(left) and j<len(right):
if left[i]<right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
result+=left[i:]
result+=right[j:]
return result
def test_function():
sort = Sort()
nums = [1,2,4,6,21,9,10,3,3]
sort.Quicksort(nums,0,len(nums)-1)
print("The result of QuickSort is :",nums)
nums = [1, 2, 4, 6, 21, 9, 10, 3,3]
sort.BubbleSort(nums)
print("The result of BuffleSort is:",nums)
nums = [1, 2, 4, 6, 21, 9, 10, 3,3]
nums = sort.MergeSort(nums)
print("The result of MergeSort is :",nums)
if __name__ == '__main__':
test_function() | false |
e4cf60bedc9df20bb65fdec96560b95f4d05d655 | hankangbok/almanacautomation | /FindDaylightSavingsDates.py | 933 | 4.21875 | 4 | import calendar
def findDSTforYear(year):
Sundaycounter=0
#To find the 2nd Sunday in march for a given year
for i in range(1,15):
ScndSundayCheck=calendar.weekday(year, 3, i)
if ScndSundayCheck==0:
Sundaycounter+=1
if Sundaycounter==2:
DSTStart=[year,3,i]
arrayStart=''.join(str(DSTStart))
print arrayStart
Sundaycounter=0
#To find the last sunday in november for a given year
for i in range(1,31):
#we want the last sunday in the month
#count how many sundays are in the given month for the given year?
ScndSundayCheck=calendar.weekday(year, 11, i)
if ScndSundayCheck==0:
Sundaycounter+=1
if Sundaycounter==2:
DSTEnd=[year,11,i]
arrayEnd=''.join(str(DSTEnd))
print arrayEnd
Sundaycounter=0
print DSTStart
print DSTEnd
return DSTStart
return DSTEnd
#test statements
findDSTforYear(2018)
findDSTforYear(2019)
findDSTforYear(2020)
| false |
f9956ce992ed0d0d7024a5829af2f6c4a05cfbff | andywakefield97/Sparta_Training | /Day_6.py | 2,526 | 4.25 | 4 | # class Students:
#
# def __init__(self, name, age, gender):
# self.name = name
# self.age = age
# self.gender = gender
#
# def year(self):
# if self.age == '14':
# return '{} is in Year 7'.format(self.name)
# elif self.age == '12':
# return '{} is in Year 5'.format(self.name)
#
# def what_gender(self):
# if self.gender == 'Male':
# return '{} is male'.format(self.name)
#
#
# x = Students('Jack', '12', 'Male')
# y = Students('Jill', '14', 'Female')
#
# print(x.what_gender())
# print(y.year())
# class Smurf:
# def __init__(self, height, age, weight):
# self.height = height
# self.age = age
# self.weight = weight
#
# def fat_or_skinny(self):
# if self.weight <= 40:
# return 'Skinny Smurf'
# elif self.weight >40:
# return 'Fat Smurf'
#
# smurf_1 = Smurf(45,2,65)
# smurf_2 = Smurf(56,4,39)
# smurf_3 = Smurf(52,5,86)
#
#
# print(smurf_1.fat_or_skinny())
#Four pillars of Object oriented programming
# Abstraction, Inheritance, Encapsulation and Polymorphism
# Abstraction is displaying only essential information to the user and hiding the details from the user
from Day_3 import *
#Inheritance is the mechanism in which one class acquires the property of another class.
class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def talk(self):
Nickname = input ('What is your nickname?')
return ('Hi my name is {}'.format(Nickname))
person_1 = Person('Andrew', 'Wakefield')
print(person_1.talk())
#Encapsulation is an object oreitned python program you can restrict access to methods and variables. Preventing data from being modified by accident
# '__' before a method encapsulates so that it cannot be used by the subclass
#Polymorphism = Defines methods in the child class that have the same name as the methods in the parent class#
#It is possible to modify a method in a cgild class that is inherited from the parent class and this is called method overriding
# method overrriding is a type of polymorphism
#Lambda functions
#Lambdas are essentially anonymous function that can take multiple parameters but return only one expression
# def add (num1,num2):
# return num1 + num2
#
# addition = lambda num1, num2:num1 +num2
#
# savings= [237,567,674,78]
#
# bonus= list(map(lambda x: x * 1.1, savings))
#
# print(bonus)
import pytest
| false |
6c291c935764c099d5c861d070780800d69d965d | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/11-square.py | 1,102 | 4.28125 | 4 | #!/usr/bin/python3
"""
11-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
Including __str__ method to represent the Square
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Represents a class called Square with a private instance
attribute called size
"""
def __init__(self, size):
"""
Initialization of the private instance attribute
Size will be validated using the integer_validator
implemented in the base class
"""
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def area(self):
"""Function that returns the area of the Square"""
return self.__size ** 2
def __str__(self):
"""
Function str that defines the string representation of the Square
"""
return "[Square] {}/{}".format(str(self.__size),
str(self.__size))
| true |
da4284aa2521689c430d51e0c275b40f2f86348d | HOL-BilalELJAMAL/holbertonschool-python | /0x0C-python-input_output/0-read_file.py | 393 | 4.125 | 4 | #!/usr/bin/python3
"""
0-read_file.py
Module that defines a function called read_file that reads
a text file (UTF8) and prints it to stdout
"""
def read_file(filename=""):
"""
Function that reads a text file and prints it to stdout
Args:
filename (file): File name
"""
with open(filename) as f:
for line in f:
print(line, end="")
| true |
0bbcccf7cb91667ab15a317c53ac951c900d93a6 | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/10-square.py | 819 | 4.28125 | 4 | #!/usr/bin/python3
"""
10-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Represents a class called Rectangle with a private instance
attribute called size
"""
def __init__(self, size):
"""
Initialization of the private instance attribute
Size will be validated using the integer_validator
implemented in the base class
"""
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def area(self):
"""Function that returns the area of the rectangle"""
return self.__size ** 2
| true |
adee2a41e59f94a940f45ebbf8fddb16582614a6 | sonsus/LearningPython | /pywork2016/arithmetics_classEx1018.py | 1,334 | 4.15625 | 4 | #Four arithmetics
class Arithmetics:
a=0
b=0
#without __init__, initialization works as declared above
def __init__(self,dat1=0,dat2=0):
a=dat1
b=dat2
return None
def set_data(self,dat1,dat2):
self.a=dat1
self.b=dat2
return None
def add(self):
return self.a+self.b
def sub(self):
return self.a-self.b
def mul(self):
return self.a*self.b
def div(self):
if self.b!=0: pass
else:
print("error! cannot div by 0") #printed
return None
return self.a/self.b
#if we dont want to execute below when only opened this file, not imported by others
if __name__=="__main__":
A=Arithmetics(3,4)
#let us see how initialization works when we dont define init manually
print(A.a)
print(A.b) #initialization as declared.
# A.set_data(1,0)
#same as the expression on the right: Arithmetics.setdata(A,1,2)
print(A.add())
print(A.sub())
print(A.mul())
print(A.div())
#Inheritance?
print("inheritance test")
class test(Arithmetics):
pass
def testprint(self):
print(self.a)
print(self.b)
I=test()
I.testprint()
#output:
#1
#0 | true |
aa226fc06796e2e12132527b270f9671bd66bb55 | annabalan/python-challenges | /Practice-Python/ex-01.py | 489 | 4.25 | 4 | #Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
def aging():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
number = int(input("Enter a number: "))
year = str((2018 - age)+100)
print(("\nHello " + name + "!" + " You are " + str(age) + "." + " You will be 100 years old in the year," + str(year) + ".") * (number))
aging()
| true |
bc917efa9ab9aef3260e21326d9c10c7f51cbc0e | strawhatasif/python | /calculate_average_rainfall.py | 2,396 | 4.5 | 4 | # This program calculates and displays average rainfall based on rainfall amounts per month entered by the user.
# constant for number of months in a year
NUMBER_OF_MONTHS_IN_YEAR = 12
# stores the number of years entered by the user
number_of_years = int((input('Please enter the number of years: ')))
# if the initial entry for number of years is less than or equal to zero, display an error message.
# also, ask user to reenter number of years.
while number_of_years <= 0:
print('Invalid entry! The number of years must be greater than zero.')
# stores the number of years entered by the user (subsequent attempt).
number_of_years = int(input('Please reenter the number of years: '))
# accumulator variable for rainfall total.
total_rainfall = 0.0
# iterate once per year
for year in range(number_of_years):
# years start at 1, not 0. format as a string for display purposes.
print('Enter monthly rainfall for year ' + str(year + 1))
# iterate for the number of months in a year (Gregorian calendar).
for month in range(NUMBER_OF_MONTHS_IN_YEAR):
# months start at 1, not 0. format as a string for display purposes.
display_month = str(month + 1)
# stores the monthly rainfall entered by the user.
# format as a string for display purposes
monthly_rainfall = float(input('Enter rainfall for month ' + display_month + ': '))
# if the entry for monthly rainfall is less than zero, display an error message and ask user to reenter value.
while monthly_rainfall < 0:
print('Invalid entry! Monthly rainfall must be greater than zero.')
# stores the monthly rainfall entered by the user (subsequent attempt).
monthly_rainfall = float(input('Reenter rainfall for month ' + display_month + ': '))
total_rainfall += monthly_rainfall
# Display the total number of months. As a reminder, months begin at 1 and not 0.
total_months = int(display_month) * number_of_years
print('Number of months: ' + str(total_months))
# Displays the total rainfall for all months. Formatted to display 2 decimal places.
print('Total inches of rainfall: ' + format(total_rainfall, ',.2f'))
# The average rainfall formula is TOTAL RAINFALL divided by the NUMBER OF MONTHS.
# Formatted to display 2 decimal places.
print('Average rainfall: ' + format(total_rainfall/total_months, '.2f'))
| true |
e6c7ddd18304dd9cb6fadb4d98058483494c0300 | strawhatasif/python | /commission_earned_for_investor.py | 2,983 | 4.34375 | 4 | # This program tracks the purchase and sale of stock based on investor input.
# constant percentage for how much commission an investor earns.
COMMISSION_RATE = 0.03
# PURCHASE OF STOCK SECTION
# Stores the name of the investor when entered.
investor_name = input('What is your name? ')
# Stores the number of shares purchased (assuming whole numbers only)
number_of_shares_purchased = int(input('How many shares did you purchase? (whole numbers only) '))
# Stores the price per share. Assumption: USD format
price_per_share = float(input('What is the price per share? (in dollars) '))
# the product between number of shares purchased and price per share
purchase_amount = number_of_shares_purchased * price_per_share
# the investor earns 3% of the purchase amount
purchase_commission = purchase_amount * COMMISSION_RATE
# Displays the purchase amount as a floating point with a precision of 2 decimal places
print('The purchase amount is $' + format(purchase_amount, ',.2f'))
# Displays the total commission earned for the purchase as a floating point with a precision of 2 decimal places
print('The commission earned for this purchase is $' + format(purchase_commission, ',.2f'))
# SALE OF STOCK SECTION
# Stores of the name of the investor when entered.
investor_name = input('What is your name? ')
# Stores the number of shares sold (assuming whole numbers only)
number_of_shares_sold = int(input('How many shares did you sell? (whole numbers only) '))
# Stores the cost per share. Assumption: USD format
cost_per_share = float(input('What is the price per share? (in dollars) '))
# the product between number of shares sold and the cost per share
sale_amount = number_of_shares_sold * cost_per_share
# the investor earns 3% of the sale amount.
sale_commission = sale_amount * COMMISSION_RATE
# Displays the sale amount as a floating point with a precision of 2 decimal places
print('The sale amount is $' + format(sale_amount, ',.2f'))
# Displays the total commission earned for the sale as a floating point with a precision of 2 decimal places
print('The commission earned for this sale is $' + format(sale_commission, ',.2f'))
# SUMMARY OF TRANSACTIONS SECTION
# This is the total commission earned by the investor as a floating point with a precision of 2 decimal places.
total_commission = float(format((purchase_commission + sale_commission), '.2f'))
# Displays the investor's name
print('Name of investor: ' + investor_name)
# Prints the total commission earned by the investor as a floating point with a precision of 2 decimal places.
print('Total commission earned: $' + format(total_commission, ',.2f'))
# Prints an amount which represents either a profit or loss and is the result between the purchase and sale amounts.
# The format is a floating point with a precision of 2 decimal places
print('Profit/Loss amount: $' + format((sale_amount -
(number_of_shares_sold * price_per_share) - total_commission), ',.2f'))
| true |
6fc6becc03fbd9d920f80033889746e04d5852ed | justintuduong/CodingDojo-Python | /Python/intro_to_data_structures/singly_linked_lists.py | 1,957 | 4.125 | 4 |
class SLNode:
def __init__ (self,val):
self.value = val
self.next = None
class SList:
def __init__ (self):
self.head = None
def add_to_front(self,val):
new_node = SLNode(val)
current_head = self.head #save the current head in a variable
new_node.next = current_head # SET the new node's next To the list's current head
self.head = new_node #return self to allow for chaining
return self
def print_values(self):
runner = self.head #a pointer to the list's first node
while(runner != None): #iterating while runner is a node and None
print(runner.value) #print the current node's value
runner = runner.next #set the runner to its neighbor
return self#once the loop is done, return self to allow for chaining
#not needed
# def add_to_back(self,val): #accepts a value
# new_node = SLNode(val) #create a new instance of our Node class with the given value
# runner = self.head
# while (runner.next != None): #iterator until the iterator doesnt have a neighbor
# runner = runner.next #increment the runner to the next node in the list
# runner.next = new_node #increment the runner to the next node in the list
# return self
#-------------------
def add_to_back(self,val):
if self.head == None: # if the list is empty
self.add_to_front(val) #run the add_to_front method
return self # let's make sure the rest of this function doesnt happen if we add to the front
new_node = SLNode(val)
runner = self.head
while (runner.next != None):
runner = runner.next
runner.next = new_node #increment the runner to the next node in the list
return self # return self to allow for chaining
my_list=SList()
my_list.add_to_front("are").add_to_front("Linked lists").add_to_back("fun!").print_values()
| true |
5457e1f66077f12627fd08b2660669b21c3f34d3 | AmonBrollo/Cone-Volume-Calculater | /cone_volume.py | 813 | 4.28125 | 4 | #file name: cone_volume.py
#author: Amon Brollo
"""Compute and print the volume of a right circular cone."""
import math
def main():
# Get the radius and height of the cone from the user.
radius = float(input("Please enter the radius of the cone: "))
height = float(input("Please enter the height of the cone: "))
# Call the cone_volume function to compute the volume
# for the radius and height that came from the user.
vol = cone_volume(radius, height)
# Print the radius, height, and
# volume for the user to see.
print(f"Radius: {radius}")
print(f"Height: {height}")
print(f"Volume: {vol}")
def cone_volume(radius, height):
"""Compute and return the volume of a right circular cone."""
volume = math.pi * radius**2 * height / 3
return volume
main()
| true |
e93a9c53e043b7c1689f8c5c89b6365708153861 | diamondhojo/Python-Scripts | /More or Less.py | 928 | 4.21875 | 4 | #Enter min and max values, try to guess if the second number is greater than, equal to, or less than the first number
import random
import time
min = int(input("Enter your minimum number: "))
max = int(input("Enter your maximum number: "))
first = random.randint(min,max)
second = random.randint(min,max)
print ("The first number is " + str(first))
choice = input("Do you think the second number will be higher, lower, or the same as the first number? ")
if choice == "higher" or choice =="lower" or choice == "same":
if choice == "higher" and second > first:
print ("You're correct")
elif choice == "lower" and first > second:
print("You're correct")
elif choice == "same" and first == second:
print("You're correct")
else:
print("You're wrong")
time.sleep(1)
print("Idiot.")
time.sleep(1)
else:
print("Answer with 'higher', 'lower', or 'same'")
| true |
01d4ea985f057d18b978cdb28e8f8d17eac02a6d | matthew-kearney/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,938 | 4.28125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
index_a = 0
index_b = 0
# Iterate through all indices in merged array
for i in range(elements):
# Make sure that we aren't past the end of either of the two input arrays
if index_a == len(arrA):
merged_arr[i] = arrB[index_b]
index_b += 1
elif index_b == len(arrB):
merged_arr[i] = arrA[index_a]
index_a += 1
# Set merged array at i to the smaller of the two elements at the current index in either array
# Increment appropriate index
elif arrA[index_a] < arrB[index_b]:
merged_arr[i] = arrA[index_a]
index_a += 1
else:
merged_arr[i] = arrB[index_b]
index_b += 1
# increment pionter
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
# Your code here
# If at base case (1 element) return array as it is already sorted
if len(arr) <= 1:
return arr
# Divide in half
mid = len(arr) // 2
# Merge sort either half of the array
left_array = merge_sort(arr[0:mid])
right_array = merge_sort(arr[mid:len(arr)])
# Now we operate as if each half has already been sorted
arr = merge(left_array, right_array) # Merge using our helper function
return arr
# # STRETCH: implement the recursive logic for merge sort in a way that doesn't
# # utilize any extra memory
# # In other words, your implementation should not allocate any additional lists
# # or data structures; it can only re-use the memory it was given as input
# def merge_in_place(arr, start, mid, end):
# # Your code here
# def merge_sort_in_place(arr, l, r):
# # Your code here
| true |
00b7d2b18548c195bedf516c25a3eda1f4a169ed | Joewash1/password | /Password2-2.py | 596 | 4.21875 | 4 | s=input("please enter your password :: ")
Password = str( 'as1987Jantu35*^ft$TTTdyuHi28Mary')
if (s == Password):
print("You have successfully entered the correct password")
while (s != Password):
print("Hint:1 The length of your password is 32 characters")
s=input("please enter your password :: ")
if(s!= Password):
print("Your password has 8 numbers")
s= input("please enter your password :: ")
if (s!= Password):
print("Your password has 1 i in it")
if (s == Password):
break
print("You successfully entered the correct password")
| true |
bdb4ad158aeda38ada8f2ca88850aab3338393b4 | elrosale/git-intro | /intro-python/part1/hands_on_exercise.py | 1,140 | 4.3125 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print(type(pi), (pi))
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if i < 50:
print("i es menor a 50")
elif i > 50:
print("i es mayor a 50")
print("valor de i es:", i)
# TODO: Write a conditional that prints the color of the picked fruit
picked_fruit = random.choice(["orange", "strawberry", "banana"])
print(picked_fruit)
if picked_fruit == "orange":
print("Fruit color is orange")
elif picked_fruit == "strawberry":
print("Fruit color is red")
elif picked_fruit == "banana":
print("Fruit color is yellow")
# TODO: Write a function that multiplies two numbers and returns the result
# Define the function here.
def times(num1, num2):
result = num1 * num2
return result
# TODO: Now call the function a few times to calculate the following answers
print("12 x 96 =", times(12, 96))
print("48 x 17 =", times(48, 17))
print("196523 x 87323 =", times(196523, 87323))
| true |
277001f219bf21982133779920f98e4b77ca9ec0 | DeLucasso/WePython | /100 days of Python/Day3_Leap_Year.py | 465 | 4.3125 | 4 | year = int(input("Which year do you want to check? "))
# A Leap Year must be divisible by four. But Leap Years don't happen every four years … there is an exception.
#If the year is also divisible by 100, it is not a Leap Year unless it is also divisible by 400.
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not a leap year.")
else:
print("Leap year.")
else:
print("Not a leap year.")
| true |
435f96309f8dbcc0ebf5de61390aae7f06d4d7e9 | ashwin1321/Python-Basics | /exercise2.py | 1,541 | 4.34375 | 4 | ##### FAULTY CALCULATOR #####
def calculetor():
print("\nWellcome to Calc:")
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
Enter Your Choise:
''')
num1 = int(input("Enter first Number: "))
num2 = int(input("Enter second Number: "))
if operation == '+':
if num1 == 56 and num2 ==9:
print("56 + 9 = 77")
else:
print(f"{num1} + {num2} = {num1 + num2}")
elif operation == '-':
print(f"{num1} - {num2} = {num1 - num2}")
elif operation == '*':
if num1 == 45 and num2 == 3:
print("45 * 3 = 555")
else:
print(f"{num1} * {num2} = {num1 * num2}")
elif operation == '/':
if num1 == 56 and num2 == 4:
print("56/6 = 4")
else:
print(f"{num1} / {num2} = {num1 / num2}")
elif operation == '**':
print(f"{num1} ** {num2} = {num1 ** num2}")
elif operation == '%':
print(f"{num1} % {num2} = {num1 % num2}")
else:
print("You Press a Invalid Key")
again()
def again():
cal_again = input('''
Do you want to calculate again?
Please type y for YES or n for NO.
''')
if cal_again == 'y':
calculetor()
elif cal_again == 'n':
print("See You Later")
else:
again()
calculetor() | true |
1b022a05c38b11750eeb5bc824ea2968628533a5 | ashwin1321/Python-Basics | /lists and its function.py | 1,724 | 4.625 | 5 |
########## LISTS #######
# list is mutable, we can replace the items in the lists
'''
grocery = [ 'harpic', ' vim bar', 'deodrant', 'bhindi',54] # we can include stirng and integer together in a list
print(grocery)
print(grocery[2])
'''
'''
numbers = [12,4,55,16,7] # list can also be empty [], we can add items in it later
print(numbers)
print(numbers.sort()) # it gives none output
numbers.sort() # it sorts the numbers in ascending order in a list
print(numbers)
numbers.reverse() # it sorts the numbers in reverse order
print(numbers)
numbers.append(17) # .append adds the item in the last of the list
print(numbers)
numbers.insert(1,123) # . insert(index,item), we can add item in the desired index
print(numbers)
numbers.remove(55) # .removes the items we want to remove
print(numbers)
numbers.pop() # .pop is used to remove the last items, Or it pops out the last item in the list
print(numbers)
numbers[1] = 45 # we can replace the item in the list with desired item
print(numbers)
'''
# MUTABLE = can change
# IMMUTABLE = cannot change
####### TUPLES #######
# tuples are immutable, as we cannot change the items in a tuple as of lists
tuple = (1,2,3,4,5)
print(tuple)
# tuple[1] = 6 # see, we cannot replace the items in tuple, as its immutable
# print(tuple)
'''
a=9
b=1
a,b = b,a # in this we can swap the values in python. like in traditional programming we use (temp=a, a=b, b= temp)
print(a,b)
'''
| true |
53b0a04657a620aaaf20bfee9f8a5b8e9b08e322 | ashwin1321/Python-Basics | /oops10.public, protected and private.py | 1,231 | 4.125 | 4 | class Employee:
no_of_leaves = 8 # This is a public variable having access for everybody inside a class
var = 8
_protec = 9 # we write a protected variable by writing "_" before a variable name. Its accessible to all the child classses
__pr = 98 # this is a private variable. we write this by writing "__" before a variable name
def __init__(self, aname, asalary, arole):
self.name = aname
self.salary = asalary
self.role = arole
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
emp = Employee("harry", 343, "Programmer")
print(emp._Employee__pr) # to access the private class we use ( ._"Class_name"__"private variable") | true |
0209c76a48557122b10eaedbac5667641078a631 | jvansch1/Data-Science-Class | /NumPy/conditional_selection.py | 292 | 4.125 | 4 | import numpy as np
arr = np.arange(0,11)
# see which elements are greater than 5
bool_array = arr > 5
#use returned array of booleans to select elements from original array
print(arr[bool_array])
#shorthand
print(arr[arr > 5])
arr_2d = np.arange(50).reshape(5,10)
print(arr_2d[2:, 6:)
| true |
dc914377bfebde9b6f5a4e2b942897d4cd2a8e25 | lilimehedyn/Small-projects | /dictionary_practice.py | 1,082 | 4.125 | 4 | #create a dict
study_hard = {'course': 'PythonDev', 'period': 'The first month', 'topics': ['Linux', 'Git', 'Databases','Tests', 'OOP'] }
# add new item
study_hard['tasks'] = ['homework', 'practice online on w3resourse', 'read about generators', 'pull requests',
'peer-review', 'status', 'feedback']
#print out items
print(study_hard)
print(study_hard.get('course'))
print(study_hard.get('period'))
print(study_hard.get('topics'))
print(study_hard.get('tasks'))
#updating the dict
study_hard.update({'course': 'Phyton Developer'})
print(study_hard)
print("The lenth of dictionary is", len(study_hard))
print(study_hard.keys())
print(study_hard.values())
# for loop for dict
for key, value in study_hard.items():
print(key, value)
for value in study_hard:
print(study_hard['period'])
# dictionary comprehension, how it works
# first step - create 2 lists
courses = ['JS Developers', 'Java Developers', 'Python Developers']
period = ["2 months", '5 months', '4 months']
my_dict = {cour: time for cour, time in zip (courses,period)}
print(my_dict) | true |
97dce44d9bdd9dfad2fd37f8e79d5956f6c64bd0 | Vagacoder/LeetCode | /Python/DynamicProgram/Q0122_BestTimeBuySellStock2.py | 2,454 | 4.15625 | 4 | #
# * 122. Best Time to Buy and Sell Stock II
# * Easy
# * Say you have an array prices for which the ith element is the price of a given
# * stock on day i.
# * Design an algorithm to find the maximum profit. You may complete as many
# * transactions as you like (i.e., buy one and sell one share of the stock multiple
# * times).
# * Note: You may not engage in multiple transactions at the same time (i.e., you
# * must sell the stock before you buy again).
# * Example 1:
# Input: [7,1,5,3,6,4]
# Output: 7
# Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
# Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
# * Example 2:
# Input: [1,2,3,4,5]
# Output: 4
# Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
# engaging multiple transactions at the same time. You must sell before buying again.
# * Example 3:
# Input: [7,6,4,3,1]
# Output: 0
# Explanation: In this case, no transaction is done, i.e. max profit = 0.
# * Constraints:
# 1 <= prices.length <= 3 * 10 ^ 4
# 0 <= prices[i] <= 10 ^ 4
#%%
class Solution:
# * Solution 1
# ! Dynamic programming
def maxProfit1(self, prices: list) -> int:
n = len(prices)
if n == 0:
return 0
# * Since k is no limited, we don't need consider k any longer
dp = [[0, 0] for _ in range(n)]
for i in range(n):
# * Base case
# * since k is not considered, we only consider base case fo first day
if i == 0:
dp[i][0] = 0
dp[i][1] = -prices[i]
else:
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
return dp[n-1][0]
# * Solution 2
# ! Greedy algorithm
def maxProfit2(self, prices:list) -> int:
n = len(prices)
if n == 0:
return 0
maxProfit = 0
for i in range(1, n):
maxProfit += max(0, prices[i] - prices[i-1])
return maxProfit
sol = Solution()
a1 = [7,1,5,3,6,4]
r1 = sol.maxProfit2(a1)
print(r1)
a1 = [1,2,3,4,5]
r1 = sol.maxProfit2(a1)
print(r1)
a1 = [7,6,4,3,1]
r1 = sol.maxProfit2(a1)
print(r1)
# %%
| true |
6396751b5e099078737ff179113ceda89fbce28c | dishashetty5/Python-for-Everybody-Functions | /chap4 7.py | 743 | 4.40625 | 4 | """Rewrite the grade program from the previous chapter using
a function called computegrade that takes a score as its parameter and
returns a grade as a string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F"""
score=float(input("enter the score:"))
def computegrade(score):
try:
if(score > 1 or score < 0):
return"bad score"
elif(score > 0.9):
return"A"
elif(score > 0.8):
return"B"
elif(score > 0.7):
return"C"
elif(score > 0.6):
return"D"
elif(score <= 0.6):
return"F"
else:
return"bad score"
except:
return"Bad score"
print(computegrade(score))
| true |
08de98547c3bd1f48944e321e9abaece43563aa9 | nurur/GeneralProgramming | /TernaryOperator.py | 265 | 4.28125 | 4 | # Ternary Operator in Python
# Rule: a if testCondition else b
x=1; y=2; z=4
print 'x, y, z values are ', x, y, z
print ' '
m = x if (x<y) else z
print 'Ternary operator result:', m
n = x if (x>y) else z
print 'Ternary operator result:', n
| false |
dfe1b71f4bca7dc0438ae83fd418ad131fb8aba9 | huzaifahshamim/coding-practice-problems | /Lists, Arrays, and Strings Problems/1.3-URLify.py | 1,061 | 4.1875 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation in place.)
"""
def URLify(str1, true_length):
modified = []
for place in range(true_length):
if str1[place] == ' ':
modified.append('%20')
else:
modified.append(str1[place])
back_to_str = ''.join(modified)
return back_to_str
""""
Since we are using appending to a list. TC will be O(true_length) + O(len(modified)) due to the .join. The length of
modified will be larger than true_length.
Time Complexity: O(len(modified))
"""
"""
Using a list and appending values to it.
Space Complexity: ~O(n)
"""
ans1 = URLify('Mr John Smith ', 13)
print(ans1)
ans2 = URLify('what is popp in', 15)
print(ans2)
ans3 = URLify('hello ', 6)
print(ans3)
ans4 = URLify(' DOG', 4)
print(ans4) | true |
6fc675f43ea490852e171cb978a9b9442c5f565d | Oscar883/AprendiendoPython | /Concatenacion.py | 443 | 4.1875 | 4 | #Se declaran dos variables con input para ingresar la informacion
#necesaria en este caso nombre y apellido
nombre=input("Nombre:")
apellidos=input("Apellidos:")
#Se concatenan los valores str, junto con la literal " " (para tomar un espacio)
NombreCompleto=nombre+" "+apellidos
#Se asigna a la variable la representacion en mayusculas
#de lo que contenia (Nombre/Apellidos)
NombreCompleto=NombreCompleto.upper()
print(NombreCompleto) | false |
e294f151d8eaded0356ab30f0cc961a31aff3698 | vishnuvs369/python-tutorials | /inputs.py | 421 | 4.21875 | 4 | # inputs
name = input("Enter your name")
email = input("Enter your email")
print(name , email)
#-------------------------------------------------
num1 = input("Enter the first number") #The input number is in string we need to convert to integer
num2 = input("Enter the second number")
#num1 = int(input("Enter the first number"))
#num2 = int(input("Enter the second number"))
sum = num1 + num2
print(sum) | true |
0bddc508ce2a5079507fdd0dbe4f55a0c09a2ef7 | Joezeo/codes-repo | /python-pro/io_prac.py | 508 | 4.15625 | 4 | forbideen = ('!', ',', '.', ';', '/', '?', ' ')
def remove_forbideen(text):
text = text.lower()
for ch in text:
if ch in forbideen:
text = text.replace(ch, '')
return text
def reverse(text):
return text[::-1]# 反转字符串
def is_palindrome(text):
return text == reverse(text)
instr = input('Please input a string:')
instr = remove_forbideen(instr)
if is_palindrome(instr):
print('Yes, it is a palindrome')
else:
print('No, it is not a palindrome')
| true |
6e83d95f12ae67d956867620574d63000b4ed848 | famosofk/PythonTricks | /ex/dataStructures.py | 800 | 4.40625 | 4 | #tuples
x = ('string', 3, 7, 'bh', 89)
print(type(x))
#tuples are imatuble. This is a list of different types object. We create tuples using (). In python this would be listof
y = ["fabin", 3, "diretoria", 8, 73]
y.append("banana")
print(type(y))
#lists are mutable tuples. We create lists using []
#both of them are iterable so we can do this
for element in x:
print(element)
#We can access elements using index as well. To do this you can simply use brackets y[3]
#to discover the length of a list or tuple we can use length.
# Operation: + concatenate lists. * repeats the list
#Dictionaries are collections of objects with key and value. They don't have index and we create them with curly braces
dic = {"fabiano" : "fabiano.junior@nobugs.com.br", "jace" : "jacevenator@gmail.com"}
nome, sobrenome = dic
print(dic[nome])
| true |
03dae7a8d59866b3c788c42fbc5c43a09d4e89ef | famosofk/PythonTricks | /2-DataStructures/week3/files.py | 739 | 4.3125 | 4 | # to read a file we need to use open(). this returns a variable called file handler, used to perform operations on file.
#handle = open(filename, mode) #Mode is opcional. If you plan to read, use 'r', and use 'w' if you want to write
#each line in file is treated as a sequence of strings, so if you want to print
name = input('Enter filename: ')
file = open(name, 'r')
#for word in file:
# print(word)
#How to read the whole file
readedFile = file.read()
#print(len(readedFile))
#Read all the stuff as a string
print(readedFile)
fhand = open('file.txt', 'r')
for line in fhand:
if line.startswith('o fabin'):
print(line)
#to remove the double \n just use .rstrip() in print, like this: print(line.rstrip())
| true |
8a781a70cc04d0d89c28c3db8da5d5ee0e9b49da | AhmadAli137/Base-e-Calculator | /BorderHacks2020.py | 1,521 | 4.34375 | 4 | import math #library for math operation such as factorials
print("==============================================")
print("Welcome to the Exponent-Base-e Calculator:")
print("----------------------------------------------")
print(" by Ahmad Ali ") #Prompts
print(" (BorderHacks 2020) ")
print("----------------------------------------------")
exp = float(input(" Enter your exponent: "))
sd = int(input(" Enter number of correct significant digits: ")) #User input
print("----------------------------------------------")
n = 1
sol = 1
Es = (0.5*10**(2-sd)) #formula to calculate error tolerance given number of significant digits
print("Error Tolerance: "+str(Es)+"%")
#Loop represents algorithm for a numerical calculation which
# becomes increasingly accurate with each iteration
# This calculation is only approximate to analytical calculation which has an infinite process
Repeat = True
while Repeat == True:
solOld = sol
sol = 1
n = n + 1
for i in range(n):
sol += (((exp)**(i+1))/(math.factorial(i+1)))
Ea = 100*(sol - solOld)/sol #Calculating approximation error between interations
if Ea < Es:
Repeat = False #loop ends once approximation error is below error tolerance
exponent_base_e = sol
print("Answer: "+str(exponent_base_e))
print("[correct to at least "+str(sd)+ " significant digits] ") #User Output
print("==============================================")
| true |
ee5ff425f61a596cc7edddb5bc3b11211cdc2e56 | urandu/Random-problems | /devc_challenges/interest_challenge.py | 938 | 4.21875 | 4 |
def question_generator(questions):
for question in questions:
yield question.get("short") + input(question.get("q"))
def answer_questions(questions):
output = "|"
for answer in question_generator(questions):
output = output + answer + " | "
return output
questions = [
{
"q": "Hi whats your name? ",
"short": "Name :"
},
{
"q": "Which year did you start writing code? ",
"short": "Year I began coding: "
},
{
"q": "Which stack is your favorite? ",
"short": "Preferred stack: "
},
{
"q": "One fact about you? ",
"short": "Fun fact: "
},
]
print(answer_questions(questions))
"""
The task is to write a simple function that asks one to input name, year started coding, stack and fun_fact,
then outputs(prints) all the inputs in a single line. Screen shot code then nominate two others to do the same
"""
| true |
96a39f4843822454b01e4ab1506825bd053518ca | Linkin-1995/test_code1 | /day05/homework/exercise06(弹球高度while).py | 808 | 4.40625 | 4 | """
6. 一个小球从100m高度落下,每次弹回原高度一半.
计算:
-- 总共弹起多少次?(最小弹起高度0.01m) 13 次
-- 全过程总共移动多少米?
"""
height = 100
count = 0
distance = height # 开始落下 -- 计算初始高度
# 判断弹之前的高度height
# 判断弹之后的高度height / 2
# 0.01 弹起来的最小高度
while height / 2 > 0.01:
# 弹起来
height /= 2
count += 1
distance += height * 2 # 弹起过程 -- 累加起落距离
# print("第" + str(count) + "次弹起来的高度是" + str(height))
print("第%d次弹起来的高度是%f" % (count, height))
# print("总共弹起" + str(count) + "次")
print("总共弹起%d次" % count)
print("全过程总共移动%f米" % distance) # 最终落地 -- 获取最终距离
| false |
83ac9d92121137cce3d7c1bc53e375432a10cae8 | Linkin-1995/test_code1 | /day07/demo05(两层for).py | 597 | 4.28125 | 4 | """
for for
练习:exercise04
"""
"""
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print() # 换行
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print() # 换行
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print() # 换行
"""
# 外层循环执行一次 内层循环执行多次
for r in range(3): # 0 1 2
for c in range(5): # 01234 01234 01234
print("#", end=" ")
print() # 换行
| false |
0133e987d946fc4e4d9672eca7afc40c69809fb9 | Linkin-1995/test_code1 | /day09/homework/exercise03(输数字查课程名:简化版).py | 811 | 4.21875 | 4 | """
练习:参照day03/exercise05案例,
定义函数,根据课程编号计算课程名称。
if course == "1":
print("Python语言核心编程")
elif course == "2":
print("Python高级软件技术")
elif course == "3":
print("Web 全栈")
elif course == "4":
print("网络爬虫")
elif course == "5":
print("数据分析、人工智能")
"""
def get_course_name(course):
dict_course_infos = {
"1": "Python语言核心编程",
"2": "Python高级软件技术",
"3": "Web 全栈",
"4": "网络爬虫",
"5": "数据分析、人工智能",
}
if course in dict_course_infos:
return dict_course_infos[course]
# return None
print( get_course_name("1")) # Python语言核心编程
| false |
ed9548882b35f9957bf9a9008cfeaea36ef4a508 | Linkin-1995/test_code1 | /day13/demo01(复合运算符重载).py | 758 | 4.25 | 4 | class Vector2:
"""
二维向量
"""
def __init__(self, x, y):
self.x = x
self.y = y
# + :创建新数据
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
# +=:尽量在原有基础上改变(不可变对象只能创建新,可变对象不创建新)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
v01 = Vector2(1, 2)
v02 = Vector2(3, 4)
print(id(v01))
v01 += v02 # v01.__iadd__(v02)
print(id(v01))
print(v01.__dict__)
# +=:可变对象不创建新
list01 = [1]
print(id(list01))
list01+=[2]
print(id(list01))
# +=:不可变对象创建新
tuple01 = (1,)
print(id(tuple01))
tuple01+=(2,)
print(id(tuple01)) | false |
da69bc85053c2d6ca956cae41f7c9d7f87d774d2 | Linkin-1995/test_code1 | /day06/demo03(浅拷贝内存图).py | 303 | 4.28125 | 4 | """
列表内存图
列表嵌套
浅拷贝
"""
list01 = [
"a",
["b", "c"]
]
# 浅拷贝,只备份一层数据(两份)
# 第二层数据只有一份
list02 = list01[:]
list01[0] = "A" # 修改第一层
list01[1][0] = "B" # 修改第二层
print(list02) # ['a', ['B', 'c']]
| false |
06f2ebe240539323ed232937bd118ce44ed6f9cf | Linkin-1995/test_code1 | /day04/demo03.py | 401 | 4.28125 | 4 | """
while 循环 - 循环计数
语法:
count = 0 # 循环前 -- 开始值
while count < 5: # 循环条件 -- 结束值
循环体
count += 1 # 循环体 -- 间隔
作用:
固定次数的重复
练习:exercise02~04
"""
# 执行5次
count = 0
while count < 5:
# print("跑圈")
print(count)
count += 1 # 0 1 2 3 4
| false |
71bd0c8d1b96b291eff6f280315e1b4f85b349fb | Linkin-1995/test_code1 | /day09/exercise04(星号args).py | 262 | 4.15625 | 4 | # 练习:定义数值累乘的函数
# 1,2,3,4
# 4,54,5,56,67,78,89
def multiplicative(*args):
result = 1
for number in args:
result *= number
return result
print(multiplicative(1, 2, 3, 4))
print(multiplicative(4, 54, 5, 56, 67, 78, 89))
| false |
26cffb891edbf40f373f56458f44427cf2c03d92 | Isaac-Yuri/menu-de-opcoes-matematicas | /principal.py | 1,798 | 4.34375 | 4 | from funcoes import menu, linha, continuar
from math import sqrt
while True:
print('===> SUAS OPÇOES <===')
menu()
linha(23)
opcao = int(input('Digite sua opção: '))
if opcao == 1:
while True:
num = int(input('Digite um número para checar se é par ou ìmpar: '))
linha()
print(f'O número {num} é ', end='')
if num % 2 == 0:
print('PAR!')
else:
print('ÍMPAR!')
if continuar():
break
elif opcao == 2:
while True:
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
linha()
print(f'{num1} multiplicado por {num2} é {num1*num2}.')
if continuar():
break
elif opcao == 3:
while True:
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
linha()
print(f'{num1} divido por {num2} é {num1/num2}.')
if continuar():
break
elif opcao == 4:
while True:
num = int(input('Digite um número para ver sua raiz quadrada: '))
linha()
print(f'A raiz quadrada de {num} é {sqrt(num)}.')
if continuar():
break
elif opcao == 5:
while True:
num = int(input('Digite um número: '))
potencia = int(input('A qual potência deseja que seu número seja elevado? '))
print(f'{num} elevado a {potencia} é igual a {num**potencia}.')
if continuar():
break
elif opcao == 6:
break
else:
print('Digite uma opção válida!')
linha()
| false |
c44ca53b2a11e083c23a725efcb3ac17df10d8ee | bowersj00/CSP4th | /Bowers_MyCipher.py | 1,146 | 4.28125 | 4 | alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def shifter(start_string, shift):
new_string=""
for character in start_string:
if character.isalpha():
new_string=new_string+(alphabet[(alphabet.index(character)+shift)%26])
else:
new_string=new_string+character
print(new_string)
is_active=True
while is_active:
start_string=str(input("Enter the string you wish to change:\n"))
which=input("Would you like to encode (e), decode (d), or brute force (b)?\n")
if which=="e":
shift=int(input("How many letters to shift by? (Enter as Number)\n"))
print("Your output is:")
shifter(start_string,shift)
elif which=="d":
shift=int(input("How many letters was it shifted by?\n"))
print("Your output is:")
shifter(start_string,26-shift)
elif which=="b":
print("Cipher possibilities are:\n")
for i in range(1,26):
shifter(start_string,i)
again=input("would you like to do another? (y or n)\n")
if again=="n":
is_active=False | true |
e486049e3ee77222325cf474606cb0886ac13e35 | Ryoichi-Ueno/Self_Taught | /challenge13_1.py | 1,409 | 4.125 | 4 | class Shape:
def __init__(self):
self.my_name = 'I am shape!'
def what_am_i(self):
print(self.my_name)
class Rectangle(Shape):
def __init__(self, base, height):
super().__init__()
self.base = base
self.height = height
def calculate_perimeter(self):
return self.base * self.height
class Square(Shape):
square_list = []
def __init__(self, base):
super().__init__()
self.base = base
self.square_list.append(self)
def __repr__(self):
return '{} by {} by {} by {}'.format(self.base, self.base, self.base, self.base)
def calculate_perimeter(self):
return self.base ** 2
def change_size(self, val):
self.base += val
if __name__ == '__main__':
base_list = []
sq1 = Square(10)
sq2 = Square(20)
sq3 = Square(30)
sq4 = Square(40)
for sq in Square.square_list:
base_list.append(sq.base)
print(base_list)
for sq in Square.square_list:
print(sq)
"""
rec = Rectangle(10, 20)
squ = Square(15)
print(rec.calculate_perimeter())
print(squ.calculate_perimeter())
rec.base = 100
squ.base = 100
print(rec.calculate_perimeter())
print(squ.calculate_perimeter())
squ.change_size(-10)
print(squ.calculate_perimeter())
rec.what_am_i()
squ.what_am_i()
"""
| false |
d86b80e7d3283ff2ee1b062e14539dbb87e34206 | anillava1999/Innomatics-Intership-Task | /Task 2/Task3.py | 1,778 | 4.40625 | 4 | '''
Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.
Example
The ordered list of scores is , so the second lowest score is . There are two students with that score: . Ordered alphabetically, the names are printed as:
alpha
beta
Input Format
The first line contains an integer, , the number of students.
The subsequent lines describe each student over lines.
- The first line contains a student's name.
- The second line contains their grade.
Constraints
There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.
Sample Input 0
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output 0
Berry
Harry
Explanation 0
There are students in this class whose names and grades are assembled to build the following list:
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
The lowest grade of belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.
'''
Result =[]
scorelist = []
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
Result+=[[name,score]]
scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
for a,c in sorted(Result):
if c==b:
print(a)
| true |
3664b39e29387cb4c7beb0413249014d34b132bc | Arsalan-Habib/computer-graphics-assignments | /mercedez-logo/main.py | 1,719 | 4.21875 | 4 | import turtle
# initializing the screen window.
canvas = turtle.Screen()
canvas.bgcolor('light grey')
canvas.title('Mercedez logo')
# initializing the Turtle object
drawer = turtle.Turtle()
drawer.shape('turtle')
drawer.speed(3)
# Calculating the radius of the circumscribing circle of the triangle.
# The formula is: length of a sides/sqrt(3)
radius = 200/(3**(1/float(2)))
# drawing the concentric circles.
drawer.circle(radius+10)
drawer.penup()
drawer.setpos((0,10))
drawer.pendown()
drawer.circle(radius)
# Moving turtle to the initial position for drawing triangle.
drawer.penup()
drawer.setpos((0, (radius*2)+10 ))
drawer.pendown()
drawer.left(60)
# initializing empty arrays for cornerpoints of the outer triangle and the inner points.
endPoints = []
centrePoints=[]
# Drawing the triangle and adding the points to the array.
for i in range(3):
endPoints.append(drawer.pos())
drawer.right(120)
drawer.forward(200)
# Calculating and adding the innner points to the array.
for i in range(3):
drawer.penup()
drawer.setpos(endPoints[i])
drawer.setheading(360-(60+(120*i)))
drawer.forward(100)
drawer.right(90)
drawer.forward(40)
centrePoints.append(drawer.pos())
# Joining the outer points to the inner points.
for i in range(3):
drawer.penup()
drawer.color('black')
drawer.setpos(centrePoints[i])
drawer.pendown()
drawer.setpos(endPoints[i])
drawer.setpos(centrePoints[i])
drawer.setpos(endPoints[(i+1)%3])
# Erasing the outer triangle.
for i in range(3):
drawer.setpos(endPoints[i])
drawer.color('light grey')
drawer.setheading(360-(60+(120*i)))
drawer.forward(200)
drawer.penup()
drawer.forward(50)
turtle.done() | true |
49fb9f94501503eedfd7f5913efb3c8ffe656e68 | Saij84/AutomatetheBoringStuff_Course | /src/scripts/12_guessNumber.py | 968 | 4.3125 | 4 | import random
#toDo
'''
-ask players name
-player need to guess a random number between 1 - 20
-player only have 6 guesses
-player need to be able to input a number
-check need to be performed to ensure number us between 1 - 20
-check that player is imputing int
-after input give player hint
-"Your guess is too high"
-"Your guess is too low"
-"You guessed right, the number i thinking of is {number}
'''
randInt = random.randint(1, 20)
print("what is your name?")
playerName = input()
print("Hi {}".format(playerName))
for count in range(1, 7):
print("Please guess a number from 1 - 20")
guess = input()
try:
int(guess)
except ValueError:
print("Please enter a number")
if int(guess) < randInt:
print("Your guess is too low")
elif int(guess) > randInt:
print("Your guess is too high")
else:
print("Correct {}! The number is {}".format(playerName, randInt))
break
| true |
d28b91aa36ee49eb6666a655e1ef9fb6239b1413 | geisonfgf/code-challenges | /challenges/find_odd_ocurrence.py | 701 | 4.28125 | 4 | """
Given an array of positive integers. All numbers occur even number of times
except one number which occurs odd number of times. Find the number in O(n)
time & constant space.
Input = [1, 2, 3, 2, 3, 1, 3]
Expected result = 3
"""
def find_odd_ocurrence(arr):
result = 0
for i in xrange(len(arr)):
result = result ^ arr[i]
return result
if __name__ == '__main__':
print "Input [1, 2, 3, 2, 3, 1, 3]"
print "Expected result: 3"
print "Result: ", find_odd_ocurrence([1, 2, 3, 2, 3, 1, 3])
print "Input [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]"
print "Expected result: 5"
print "Result: ", find_odd_ocurrence([2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2])
| true |
7eb356997cc0862b77e09a80699b1681f0b51952 | geisonfgf/code-challenges | /challenges/evaluate_reverse_polish_notation.py | 560 | 4.21875 | 4 | """
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
"""
def evaluate(expression):
stack = []
while expression:
val = expression.pop(0)
if (str(val) == "+" or str(val) == "*" or
str(val) == "-" or str(val) == "/"):
x, y = stack.pop(), stack.pop()
stack.append(eval("{0}{1}{2}".format(y, val, x)))
else:
stack.append(val)
return stack[0]
print evaluate(["2", "1", "+", "3", "*"])
print evaluate(["4", "13", "5", "/", "+"]) | false |
1758af802adc1bf5dbf6b10bf4c04fd19d48e975 | mk9300241/HDA | /even.py | 209 | 4.34375 | 4 | #Write a Python program to find whether a given number (accept from the user) is even or odd
num = int(input("Enter a number:"))
if (num%2==0):
print(num," is even");
else:
print(num," is odd");
| true |
8712ae37e691e8e0c135a5d10601beac865591c3 | tussharbhatt/all_projects | /PycharmProjects/MyOwnStuff/data_Structure_progs/remove_common.py | 293 | 4.125 | 4 |
def main():
items=[]
for i in range(5):
items.append(input("enter values "))
dict={}
for item in items:
#print(item)
if item not in dict:
dict['key']=item
#for keys in dict.items():
print(dict['key'])
main() | false |
9979472aca0ae85cffffb3ddbee68ecb7a3d4b01 | tussharbhatt/all_projects | /PycharmProjects/pyStart/syntax_test.py | 405 | 4.21875 | 4 |
import datetime
#date1=datetime.datetime.now()
#print(now)
#print(now._day)
#date=datetime.datetime(date1._year,date1._month,date1._day)
'''def print_date(now1):
date1=now1
date2=datetime.date(,now1.month,now1.day)
print(date2)
'''
now=datetime.date.today()
#print_date(now)
year=int(input("enter year [YYYY]"))
date=datetime.date(year,now.month,now.day)
print(date)
| false |
8bd4e4cdb8f32f99c9c0683aa454a4719f0ece73 | quinn3111993/nguyenphuongquynh-lab-c4e21 | /lab3/calc.py | 610 | 4.25 | 4 | # x = int(input("x = "))
# op = input("Operation(+, -, *, /): ")
# y = int(input("y = "))
# if op == '+':
# z = x + y
# print(x, '+', y, '=', z)
# elif op == '-':
# z = x - y
# print(x, '-', y, '=', z)
# elif op == '*':
# z = x * y
# print(x, '*', y, '=', z)
# elif op == '/':
# z = x / y
# print(x, '/', y, '=', z)
# else:
# print('Invalid operator')
def calculate(x,y,op):
result = 0
if op == '+':
result = x+y
elif op == '-':
result = x-y
elif op == '*':
result = x*y
elif op == '/':
result = x/y
return result
| false |
3c16a7d51658806c1233e14640f6ce6d3cabda12 | voksmart/python | /QuickBytes/StringOperations.py | 1,601 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 13:35:40 2019
@author: Mohit
"""
# String Assignment
str1 = "Hello"
str2 = "John"
# Checking String Length
print("Length of String is :",len(str1))
# String Concatenation (join)
print(str1 + " "+str2)
# String Formatting
# inserting name of guest after welcome
print("Welcome %s.Enjoy your stay"%(str2))
# Changing String Case
guestname = "John Smith"
# converts string to lower case
print(guestname.lower())
# converts string to UPPER case
print(guestname.upper())
# converts string to title case
# First letter of every word is capital
print(guestname.title())
# Stripping White Spaces
# string below has leading and trailing
# white space
message = " Good Morning John "
# remove all leading and trailing whitespace
print(message.strip())
# remove leading white space
print(message.lstrip())
# remove trailing white space
print(message.rstrip())
# String Formatting
# Using format{} function
guest = "John Smith"
city = "New York"
mobile="iphone"
price=199.234
# Simple Formatter with place holders
print("Hello {}! Welcome to {}".format(guest,city))
print("My {} cost me {}".format(mobile,price))
# With positional arguments
# Note changed position in format function
print("My {1} cost me {0}".format(price,mobile))
# controlling display with format specifiers
print("My {1:s} cost me {0:.2f}".format(price,mobile))
# Formatting using fstring
print(f"Hello {guest}. Welcome to {city}")
print(f"My new {mobile} cost me {price:.2f}")
| true |
c5e7b72cabf084c40320d31eb089b93451d7072d | ErosMLima/python-server-connection | /average.py | 217 | 4.375 | 4 | num = int(input("how many numbers ?"))
total_sum = 0
for n in range (num):
numbers = float(input("Enter any number"))
total_sum += numbers
avg = total_sum / num
print('The Average number is?'. avg) | true |
3a926ac51f31f52184607c8e4b27c99b4cbb9fb8 | AnujPatel21/DataStructure | /Merge_Sort.py | 863 | 4.25 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
middle = len(unsorted_list) // 2
left_half = unsorted_list[:middle]
right_half = unsorted_list[middle:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
return list(merge(left_half,right_half))
def merge (left_half,right_half):
result = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
result.append(left_half[0])
left_half.remove(left_half[0])
else:
result.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
result = result + right_half
else:
result = result + left_half
return result
unsorted_list = [9,8,7,6,5,4,3,2,1]
print(merge_sort(unsorted_list))
| true |
9fe71cad659e416a3c9349114ceebacae3895b15 | 12agnes/Exercism | /pangram/pangram.py | 317 | 4.125 | 4 | def is_pangram(sentence):
small = set()
# iterate over characters inside sentence
for character in sentence:
# if character found inside the set
try:
if character.isalpha():
small.add(character.lower())
except:
raise Exception("the sentence is not qualified to be pangram")
return len(small) == 26 | true |
c5a777c88c3e6352b2890e7cc21d5df29976e7e7 | edwardcodes/Udemy-100DaysOfPython | /Self Mini Projects/turtle-throw/who_throw_better.py | 1,371 | 4.3125 | 4 | # import the necessary libraries
from turtle import Turtle, Screen
import random
# Create custom screen
screen = Screen()
screen.setup(width=600, height=500)
guess = screen.textinput(title="Who will throw better",
prompt="Guess which turtle will throw longer distance?")
colors = ["red", "orange", "blue", "green", "purple"]
turtles = []
y_positions = [-85, -60, -35, -10, 15, 40, 65]
# Create multiple turtles and ask them to throw
for turtle_index in range(0, 5):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(colors[turtle_index])
new_turtle.goto(x=-285, y=y_positions[turtle_index])
turtles.append(new_turtle)
# Check whether user given guessed color as input
dist = {}
if guess:
for turtle in turtles:
rand_throw = random.randint(0, 500)
turtle.fd(rand_throw)
dist[turtle.pencolor()] = rand_throw
winning_turtle = max(dist, key=dist.get)
winning_dist = max(dist.values())
if winning_turtle == guess:
print(
f"you've won! The winning turtle is {winning_turtle} with covered distance of {winning_dist}")
else:
print(
f"you've lost! The winning turtle is {winning_turtle} with covered distance of {winning_dist}")
# Show results to the user whether he guessed right or wrong
screen.exitonclick()
| true |
8680ed0c79f30dead7add45ccba90fa253374d76 | Nam1130Tx/Python | /Python Assignments/abstraction.py | 597 | 4.28125 | 4 | #Python: 3.9.0
#Author: Nicholas Mireles
#Assignment: Abstraction Assignment
from abc import ABC, abstractmethod
class Shapes(ABC):
def sides(self):
print('How many sides does a ')
@abstractmethod
def num(self):
pass
class Triangle(Shapes):
def num(self):
print('triangle have?: 3')
class Hex(Shapes):
def num(self):
print('hexagon have?: 6')
if __name__ == "__main__":
obj = Triangle()
obj.sides()
obj.num()
obj = Hex()
obj.sides()
obj.num()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.