blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
17ee83f78ffc75ddc60789152a67d32531fff727 | mzanzilla/Python-For-Programmers | /Exceptions/ex1.py | 656 | 4.375 | 4 | #demonstrating how to handle a division by zero exception
while True:
#attempt to convert and divide values
try:
number1 = int(input("Enter numerator: "))
number2 = int(input("Enter denuminator: "))
result = number1 / number2
except ValueError: #Tried to convert non-numeric value to integer
print("You must enter two integers\n")
except ZeroDivisionError: #denominator was zero
print("Attempted to divide by zero\n")
else:
print(f"{number1:.3f}/{number2:.3f} = {result:.3f}")
break #If no exceptions occur print the numerater/denominator and the result and terminate the program
| true |
4461ea009cb18cfc2b7167372e5d31c1a8e35c2f | tmemud/Python-Projects | /ex72.py | 1,110 | 4.40625 | 4 | # Use the file name mbox-short.txt as the file name
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
#looking for lines of the form: X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and
#compute the average of those values and produce an output as shown below.
#Do not use the sum() function or a variable named sum in your solution.
#You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
#when you are testing below enter mbox-short.txt as the file name.
#Average spam confidence: 0.750718518519
fname = input("Enter file name: ")
fh = open(fname)
count = 0
add = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
sval = line.find(":")
numbers = line[sval+2 : ]
fval = float (numbers)
add += fval
count += 1
average = add/count
print("Average spam confidence:", average)
#count = count + 1
#print(count)
#print(line)
#print (count)
#print("Done")
| true |
b527e70db8dd5f3cf9afa0047c9a4140cbb94e82 | bkoehler2016/python_projects | /forloop.py | 458 | 4.28125 | 4 | """
a way to print objects in a list
"""
a = ["Jared", 13, "Rebecca", 14, "Brigham", 12, "Jenn", 3, "Ben", 4]
# printing the list using * operator separated
# by space
print("printing the list using * operator separated by space")
print(*a)
# printing the list using * and sep operator
print("printing lists separated by commas")
print(*a, sep = ", ")
# print in new line
print("printing lists in new line")
print(*a, sep = "\n") | true |
091ad70053e25fc51ac502a53946d36d96219715 | OctaveC/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 566 | 4.375 | 4 | #!/usr/bin/python3
"""
This is a module that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
def text_indentation(text):
""" This function indents text based on special characters """
if type(text) is not str:
raise TypeError("text must be a string")
leap = True
for char in text:
if not (char is ' ' and leap is True):
print(char, end="")
leap = False
if char in [':', '.', '?']:
print()
print()
leap = True
| true |
183e49a5349c95ef8196ad65754fec65fedf3a35 | Invecklad-py/New_start | /What_is_your_name_input.py | 295 | 4.125 | 4 | first_name = input("What's your first name?")
last_name = input("What's your last name?")
answer = input("So your name is " + first_name + " " + last_name + "?")
if answer == "yes":
print("Great!")
if answer == "no":
print("I'm sorry we got that wrong, please try again")
| true |
104df48126c81aaade444844a5c67c501a98126a | Lumiras/Treehouse-Python-Scripts | /Beginning_python/general_exercises/shopping_list_4.py | 2,236 | 4.125 | 4 | shopping_list = []
def clear_list():
confirm = input("Are you sure you want to completely clear the list?\nThere is no way to undo this!\nType YES to confirm ")
if confirm == 'YES':
del shopping_list[:]
def move_item(idx, mov):
index = idx - 1
item = shopping_list.pop(index - 1)
shopping_list.insert(mov, item)
def remove_item(idx):
index = idx - 1
item = shopping_list.pop(index)
print("Removed {} ".format(item))
def show_help():
print("\nSeparate each item with a comma")
print("Type DONE to quit\nType SHOW to see the current list\nType HELP to get this message\nType REMOVE to delete an item")
def show_list():
if len(shopping_list) > 0:
count = 1
for item in shopping_list:
print("{} -> {}".format(count, item))
count += 1
else:
print("\nYour shopping list is currently empty")
def prompt():
print("\nGive me a list of things you want to shop for: ")
show_help()
while True:
prompt()
new_stuff = input(">>")
if new_stuff == "DONE":
print("\nHere's your list:")
show_list()
break
elif new_stuff == "HELP":
show_help()
continue
elif new_stuff == "SHOW":
show_list()
continue
elif new_stuff == "REMOVE":
show_list()
idx = input("Which item do you want to remove? ")
remove_item(int(idx))
continue
elif new_stuff == "MOVE":
show_list()
idx = input("Which item do you want to move? ")
mov = input("Where do you want to move the item? ")
move_item(int(idx), int(mov))
elif new_stuff == "CLEAR":
clear_list()
else:
new_list = new_stuff.split(",")
index = input("Add this at a certain spot? Press ENTER to insert at the end of the list "
"\nor give me a number to place it at a certain spot. You currently have {} items in your list: ".format(len(shopping_list)))
if index:
spot = int(index)-1
for item in new_list:
shopping_list.insert(spot, item.strip())
spot += 1
else:
for item in new_list:
shopping_list.append(item.strip())
| true |
04f1caf80aaf3699dfe4e525c7f69909c5a33476 | clarencekwong/CSCA20-B20 | /e4.py | 1,672 | 4.15625 | 4 | import doctest
def average_list(M):
'''(list of list of int) -> list of float
Return a list of floats where each float is the average of the
corresponding list in the given list of lists.
>>> M = [[0,2,1],[4,4],[10,20,40,50]]
>>> average_list(M)
[1.0, 4.0, 30.0]
>>> M = []
>>> average_list(M)
[]
'''
new = []
for i in range(len(M)):
avg = sum(M[i])/len(M[i])
new.append(avg)
return new
def increasing(L):
'''(list of int) -> bool
Return True if the given list of ints is in increasing order and
False otherwise.
>>> increasing([4,3,2,1])
False
>>> increasing([2,4,6,8])
True
>>> increasing([0,0,1,2])
False
>>> increasing([3])
True
>>> increasing([1,2,4,3])
False
'''
index = 0
while index < (len(L)-1):
if L[index] >= L[index+1]:
return False
index += 1
return True
def merge(L1, L2):
'''(list of int, list of int) -> (list of int)
Return a list of ints sorted in increasing order that is the merge
of the given sorted lists of integers.
>>> merge([0,2,4],[1,3,5])
[0, 1, 2, 3, 4, 5]
>>> merge([2,4],[1,2,4])
[1, 2, 2, 4, 4]
>>> merge([0,1,2],[3,4])
[0, 1, 2, 3, 4]
>>> merge([],[1,3,4])
[1, 3, 4]
'''
new_lst = []
while L1 and L2:
if L1[0] < L2[0]:
new_lst.append(L1.pop(0))
elif L1[0] > L2[0]:
new_lst.append(L2.pop(0))
else:
new_lst.append(L1.pop(0))
new_lst.append(L2.pop(0))
return new_lst + L1 + L2
if __name__ == '__main__':
doctest.testmod(verbose=True)
| true |
27ff7f866f125b4930facd5f7f28d04e151b0f79 | pinardy/Digital-World | /Week 3/wk3_hw4.py | 622 | 4.21875 | 4 | def isPrime(x):
if x==2:
return True
elif x<2 or x % 2 == 0:
return False
elif x==2:
return True
else:
return all(x % i for i in xrange(2, x))
#all function: Return True if all elements of the iterable are true
#(or if the iterable is empty).
#range returns a Python list object and xrange returns an xrange object.
print 'isPrime(2)'
ans=isPrime(2)
print ans
print 'isPrime(3)'
ans=isPrime(3)
print ans
print 'isPrime(7)'
ans=isPrime(7)
print ans
print 'isPrime(9)'
ans=isPrime(9)
print ans
print 'isPrime(21)'
ans=isPrime(21)
print ans
| true |
6435a57030eda2023e17f57b4c127cce9c45163c | TheManTheLegend1/python_Projects | /updateHand.py | 2,062 | 4.1875 | 4 | import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print # print an empty line
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
numVowels = n / 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
userHand = {'e': 2, 'h': 1, 'n': 1, 'u': 1, 't': 3, 'w': 1, 'y': 1}
def updateHand(hand, word):
h = hand.copy()
for letter in word:
if h[letter] >= 0:
h[letter] -= 1
return h
print updateHand(userHand, 'teeth')
| true |
d1dbff287e9541cab7ec2f46958e0990ccc73eb6 | Arya16ap/moneyuyyyyyof.py | /countingWords.py | 403 | 4.125 | 4 | introString = input("enter your introduction: ")
characterCount = 0
wordCount = 1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount = wordCount+1
characterCount = characterCount-1
if(wordCount<5):
print("invalid intro")
print("no. of words in the string: ")
print(wordCount)
print("no. of letters in the string: ")
print(characterCount) | true |
99355b9314b27ebb7d7ec5a4c523cdeaaf3e97fd | NAMELEZS/Python_Programs | /length_function.py | 248 | 4.15625 | 4 | ### 03/28/2021
### Norman Lowery II
### How to find the length of a list
# We can use the len() fucntion to find out how long a list is
birthday_days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
print(len(birthday_days)) | true |
4f247571b9e29902cdfab301b0b2039e6c0e3d3b | lebronjames2008/python-invent | /w3schools/Scopes.py | 799 | 4.375 | 4 | # A variable is only available from inside the region it is created. This is called scope.
def myfunc():
x = 300
print(x)
myfunc()
# A variable created inside a function is available inside that function
x = 300
def myfunc():
print(x)
myfunc()
print(x)
# Printing 2 300's
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
# The function will print the local x, and then the code will print the global x:
def myfunc():
global x
x = 300
myfunc()
print(x)
# Another way to print with global
# Also, use the global keyword if you want to make a change to a global variable inside a function.
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
# To change the value of a global variable inside a function, refer to the variable by using the global keyword:
| true |
469cf9247ced31818e7060426dfb7f1f67d91ad6 | lebronjames2008/python-invent | /w3schools/Inheritance.py | 1,945 | 4.34375 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
#Use the pass keyword when you do not want to add any other properties or methods to the class.
class Student(Person):
pass
# In student class, you are borrowing parent classes things and just doing it in a easier way, so basically its inheriting from the parent class.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
# Python also has a super() function that will make the child class inherit all the methods and properties from its parent
# By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
| true |
a5a700f7fa77777ea9a3c65669d67f0fd4313dd0 | lebronjames2008/python-invent | /chapter9/testlist1.py | 706 | 4.34375 | 4 | names_list = ['sibi', 'rahul', 'santha', 'scott', 'james']
# print all the elements in the list
print(names_list)
# print the 4th index of the list
print(names_list[4])
print(names_list[-5])
thislist = ["apple", "banana", "cherry"]
print(thislist)
thislist[1] = "blackcurrant"
print(thislist)
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
# find the size of the list
print(len(names_list))
# append is adding a new element to the end of the list
names_list.append('rishi')
print(names_list)
names_list.insert(3, 'jeremy')
print(names_list)
# The pop() method removes the specified index, (or the last item if index is not specified):
names_list.pop()
print(names_list)
| true |
71039d8b5847e341112b2194918eebe219589a40 | vlad-zankevich/LearningPython | /album.py | 1,222 | 4.1875 | 4 | def run():
# Theme with function
def make_album(singer_name, album_name, track_number=''):
"""This function will make the dictionary with your album"""
# Album dictionary, empty in default
album = {}
# You can enter quantity of tracks in album if you want
if track_number:
album['track number'] = track_number
# Here you enter singer name
album['singer name'] = singer_name
# Here you enter album name
album['album name'] = album_name
# The dictionary with entering data returns
return album
users_dict = {}
while True:
user_name = input("Please, enter your name: ")
user_album = make_album(input("Enter singer or group name: "),
input("Enter album name: "),
input("If you want, enter track numbers"
"\nIf not, just press 'Enter': "))
users_dict[user_name] = user_album
message = input("Print 'q' if you don't want to continue: ")
# Exit from cycle
if message == 'q':
break
print(users_dict)
if __name__ == "__main__":
run()
| true |
a900892c18dfd7679221269c3a7d8cfe3a1586a7 | mblahay/blahay_standard_library | /regexp_tools.py | 1,129 | 4.25 | 4 | import re
import itertools
import blahay_standard_library as bsl
def regexp_like(args, argp):
'''
A simple wrapper around the re.search function. The result
of that function will be converted to a binary True/False.
This function will return a simple True or False, no match object.
Parameters:
-----------
args - This is the string argument which is to be searched.
argp - This is the pattern that is used when searching args
'''
return bool(re.search(argp, args)) # Simply execute the search method using the string and pattern,
# then interpret the existance of a returned match object into
# a True of False using the bool constructor.
def regexp_substr():
pass
def regexp_replace():
pass
def regexp_parse(args, pat):
'''
Separate the string args by pat and denote which elements are
a pattern match and which ones are not.
'''
x=zip(re.split(pat,args),itertools.repeat(False))
y=zip(re.findall(pat,args),itertools.repeat(True))
return bsl.interleave(x,y)
| true |
322747201ef9fe9aa660c5a8831e396266789520 | Santhosh-27/Practice-Programs | /N_day_profit_sell_k_times.py | 1,317 | 4.34375 | 4 | '''
Stock Buy Sell to Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.
For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
'''
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
def stockBuySell(price, n):
# Prices must be given for at least two days
if (n == 1):
return
i=0
profit = 0
while(i<n-1):
while(i<n-1 and price[i+1]<=price[i]):
i += 1
buy = i
i += 1
while(i<n and price[i]>=price[i-1]):
i += 1
sell = i-1
profit = price[buy]+price[sell]
print("Buy on day:"+str(buy)+" and sell on day:"+str(sell))
print("Total Profit:"+str(profit))
# Driver code
# Stock prices on consecutive days
#price = [100, 180, 260, 310, 40, 535, 695]
price = [1,5,2,3,7,6,4,5]
n = len(price)
# Fucntion call
stockBuySell(price, n)
| true |
095cf2d2b9c6d71f606901fc6c3aef5ab75b0ac7 | bc-townsend/aco_example | /aco_example/path.py | 2,145 | 4.40625 | 4 | import pygame
from math import sqrt
class Path:
"""Represents a path object. These are connections between nodes.
"""
def __init__(self, color, node1, node2):
"""Initialization method for a path object.
Args:
color: The color of this path.
node1: One of the nodes to be connected as neighbors.
node2: The other node to be connected as neighbors.
"""
self.color = color
self.node1 = node1
self.node2 = node2
self.start_pos = node1.rect.center
self.end_pos = node2.rect.center
self.width = 30
# Pheromone value determines how likely an ant is to travel along this path.
self.pheromone = 1
self.phero_evap = 0.1
self.font = pygame.font.SysFont('Arial', 28)
def get_dist(self, node_size):
"""Returns the length/distance of this path.
Args:
node_size: Used to calculate the distance so that the numbers are not incredibly large due to pixel measurements.
"""
x_diff = self.node2.rect.centerx - self.node1.rect.centerx
y_diff = self.node2.rect.centery - self.node1.rect.centery
return sqrt(x_diff ** 2 + y_diff ** 2) / node_size
def draw(self, surface):
"""Draws this path on the specified surface.
Args:
surface: The pygame surface to draw this path on.
"""
pygame.draw.line(surface, self.color, self.start_pos, self.end_pos, self.width)
center_point = ((self.end_pos[0] + self.start_pos[0]) / 2, (self.end_pos[1] + self.start_pos[1]) / 2)
text = self.font.render(f'{round(self.get_dist(80), 1)}', True, (255, 255, 255))
surface.blit(text, center_point)
def phero_evaporation(self):
"""Controls how much pheromone this path loses.
"""
self.pheromone -= (self.pheromone * self.phero_evap)
def __eq__(self, obj):
return isinstance(obj, Path) and self.node1 is obj.node1 and self.node2 is obj.node2
def __str__(self):
return f'Path {self.node1.node_id}->{self.node2.node_id}. Phero: {self.pheromone}'
| true |
33901933c76acda3b74577e52e989c1e4d4e34a8 | NiteshKumar14/MCA_SEM_1 | /Assignments/OOPs pythonn/synonym_using_existing_dict.py | 1,495 | 4.46875 | 4 | # create an empty my_dictionary
my_my_dict={
"sad":"sure",
"depressed":"Sad",
"Dejected":"Sad",
"Heavy":"Sad",
"Amused":"Happy",
"Delighted":"Happy",
"Pleased":"Happy",
"Annoyed":"Angry",
"Agitated":"Angry",
"Mad":"Angry",
"Determined":"Energized",
"Creative":"Energized",
}
def display(dict):
iterator=1
for keys,values in dict.items():
print(iterator,"\t\t",keys,"\t\t",values)
iterator+=1
def key_found(key):
for k in my_dict.keys():
if k==key:
return True
return False
# def display(my_dict):
# for k in my_dict.keys():
# print(k,"type ",type(k))
# print("hello MR.X \n just enter number of words then follow the format. \n you are good to go \n we will take care of your synonym dairy ")
my_dict={}
#input number of words with their coreesponding meaning
no_of_words=int(input("Number of words: "))
#creating a my_dictionary with key as meaning and values as list of words
print("enter in format words : meaning")
#loop until all words are entered
while(no_of_words):
word=input()
meaning=input(":")
#display(my_dict)
#if my_dict is empty:
if key_found(meaning):
#print("key found")
my_dict[meaning].append(word)
#display(my_dict)
else:
my_dict[meaning]=list()
my_dict[meaning].append(word)
display(my_dict)
no_of_words-=1
iterator=1
print("Page\t\tMeaning\t\tSynonymns)")
| true |
b08167b84bd467cc501f5b59165ca3ef8c100f38 | NiteshKumar14/MCA_SEM_1 | /Assignments/OOPs pythonn/happy_sum_of_squares.py | 2,261 | 4.125 | 4 |
def sum_of_squares(sqdnumber): #defining a function that take a string and return its elements sum
sqdNumber_result=0 #initializing sum array for storing sum
iteratator=len(sqdnumber)-1 #iterating till the length of string in descending order
if not iteratator: #if the length of string is 1(here iterator will be zero)
return int(sqdnumber[0])**2
while iteratator: #looping digits
sqdNumber_result+=int(sqdnumber[iteratator])**2
iteratator-=1
if(iteratator==0): #for the last index(0) as loop will exit now
sqdNumber_result+=int(sqdnumber[iteratator])**2
return sqdNumber_result
def happy_number(number): #happy function determines whether a number is happy or not
iterator=10 #performing 10 iteration to prevent infinite loop.
if sum_of_squares(number)==1: #edge case if the number sum of squares is 1
return True
while iterator:
number=sum_of_squares(str(number)) #storing the sum of squares of the number
if sum_of_squares(str(number))==1: #condition for happy number
return True
iterator-=1
return False
# test_case=int(input("test_cases:\t")) #taking input as string
number=input()
print("sum of squares :",sum_of_squares(number)) #invoking sum of squares function
if happy_number(number) :
print("Its a Happy Number")
else:
print("Not a Happy Number ")
# number=input("enter a number:\t")
# if happy_number(str(iterator)):
# print(sum_of_squares(str(iterator)),"\t",end='')
# print(iterator)
# # print("Its a Happy Number\t")
# # else:
# # print("Not a Happy Number\t")
# test_case-=1
| true |
5f5df0b3966bb1a5c613d0c4f6e4f524cee0c742 | freebrains/Python_basics | /Lesson_3.3.py | 580 | 4.3125 | 4 | """
Реализовать функцию my_func(), которая принимает три позиционных
аргумента, и возвращает сумму наибольших двух аргументов.
Implement the my_func () function, which takes three positional
arguments, and returns the sum of the largest two arguments.
"""
def my_func(var_1=int(input("Enter first number - ")), var_2=int(input("Enter second number - ")),
var_3=int(input("Enter third number - "))):
return sorted([var_1, var_2, var_3])[1:]
print(sum(my_func()))
| true |
1d40d049794faa916c6f4a845d138e1b02ae8ef7 | jamilcse13/python-and-flask-udemy | /16. whileLoop.py | 598 | 4.1875 | 4 | count = 0
while count<10:
count += 1
print("count=", count)
print("good bye!")
## while loop else statement
count = 0
while count<10:
print(count, "is less than 10")
count += 1
else:
print(count, "is not less than 10")
print("good bye!")
# single statement suits
flag = 1 #it eill be an infinite loop
# while (flag): print('Given flag is really true! ')
print('bye bye!')
## infinite loop: break by pressing ctrl+c
var = 1
while var ==1: #it generates an infinite loop
num = int(input("Enter a number: "))
print("You entered: ", num)
print("Good bye!") | true |
6a40da9daeb7b5c96488dd8552caafac2f0e0044 | tedgey/while_loop_exercises | /p_a_s_II.py | 346 | 4.15625 | 4 | # print a square II - user chooses square size
square_size_input = input("How long should the square's sides be? ")
square_size_length = int(square_size_input)
symbol_count = square_size_length * ("*")
counter = 0
while counter < square_size_length:
counter = counter + 1
if counter <= square_size_length:
print(symbol_count) | true |
22f7df39cb5e448034c348c6b3587138de937361 | MTDahmer/Portfolio | /hw2.py | 2,972 | 4.28125 | 4 | # File: hw2.py
# Author: Mitchell Dahmer
# Date: 9/18/17
# Section: 503
# E-mail: mtdahmer@tamu.edu
# Description: a program that takes two operands from a user and then modifies them based on the operation given by the user in the form of a string
import math
def main():
firstInteger = int(input("Please enter the first operand: ")) #these three lines take the desired inputs from the user in the form of two numbers and an operation respectively
secondInteger = int(input("Please enter the second operand: "))
userOper = str(input("Please enter the operation: "))
operation= userOper.lower() #turns the strin input by the user into all lowercase letters for easier identification
print("Operand 1 is %.0f" % firstInteger) #three lines that print off the variables input by the user
print("Operand 2 is %.0f" % secondInteger)
print("The operation is %s" % userOper)
if (operation=='add'): #adds the integers together if the input operation is add and then prints the total
total = firstInteger+secondInteger
print("Your result is %.3f" % total)
elif (operation=='subtract'): #subtracts the integers from each otherif the input operation is subtract and then prints the total
total = firstInteger-secondInteger
print("Your result is %.3f" % total)
elif (operation=='multiply'): #multiplies the integers together if the input operation is multiply and then prints the total
total = firstInteger*secondInteger
print("Your result is %.3f" % total)
elif (operation=='divide'): #divides the integers by each other if the input operation is divide and then prints the total
if(secondInteger==0): #gives the user and error if the second operand is a 0
print("Division by zero is not allowed")
else:
total = firstInteger/secondInteger
print("Your result is %.3f" % total)
else:
print("Invalid operation") #gives an error if the operation given is not one of the four
total = abs(total) #three lines that take the absolute value of the total and turn the total into a string whose integers can be counted to find length
strTotal = str(total)
numb = len(strTotal)
if ((firstInteger>0) and (secondInteger>0)) or ((firstInteger<0) and (secondInteger<0)) or ((numb>2)): #prints a line between the total and the special conditions only if any exist
print('------------------------------')
if (firstInteger>0) and (secondInteger>0): #prints notifcation if both operand are positive
print("Both operand are positive")
elif(firstInteger<0) and (secondInteger<0): #prints notifcation if both operand are negative
print("Both operand are negative")
if (numb>2): #prints notification if the number has over three digits
print("The result is has three or more digits")
main() | true |
6d63f96591f210049407b3930d131435727b2dfa | nicodlv99/100-days-of-code | /basics/sequence-types.py | 1,657 | 4.59375 | 5 | #Creating a string
s = "Hello World, how are you doing!" #Creating a string to print
print(s)
s1 = """This is a
line of code
with multiple ines"""
print(s1) #defining a string that contains multiple lines
print(s[0]) #indexing to find the first letter in a word using dictionaries
#first number in a dictionary is 0
print(s*2) #will print it three times
print(len(s1)) #used to find the length of a string
print(len(s))
#Slicing
print(s[0:5]) #Slicing - using to find index within a string
print(s[0:]) #not closing off the index means it will splice the whole string
print(s[0:8])
print(s[-3:-1]) #splicing using negative numbers means it indexes from the back to front
print(s[0:9:2]) #returns by skipping on variable at a time
print(s[15:: -1]) #will come from the end all the way to the beginning in reverse
print(s[::-1]) #will return the string but reversed
#Stripping
print(s.strip()) #will strip out the spaces in a string
print(s.lstrip()) #will do a left strip
print(s.rstrip()) #will do a right strip
print(s.find("ell"), 0, len(s)) #to find location of a substring. Use 0 to state where to start the search to till the length of string
print(s.count("o")) #counts the number of occurences of a given substring
print(s.replace("Hello", "Howdy")) #used to replace a substring, word to get replaced goes first followed by the new word
print(s.upper) #will return string in uppercase
print(s.lower) #will return string in lowercase
print(s.title()) #returns a title case version of the string
| true |
621c0d35b6e0a2ff8fad1f30b74164b30c09115b | kicksmackbyte/project_euler | /p004.py | 589 | 4.3125 | 4 | """
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(i):
str_ = str(i)
if str_ == str_[::-1]:
return True
else:
return False
def main():
num_1 = 999
num_2 = 999
palindromes = []
for i in range(900):
a = 999 - i
for j in range(900):
b = 999-j
product = a * b
if is_palindrome(product):
palindromes.append(product)
largest_palindrome = max(palindromes)
print(largest_palindrome)
if __name__ == "__main__":
main()
| true |
8faa9ef69ed763164ec130d4a91088df7d30030d | satishraut/inter-prep | /oops/methodOverLoadingAndRiding.py | 799 | 4.125 | 4 | '''
Override means having two methods with the same name but doing different tasks.
It means that one of the methods overrides the other.
Like other languages (for example method overloading in C++) do, python does not supports method overloading.
We may overload the methods but can only use the latest defined method.
'''
class Rectangle():
def __init__(self, lentgh, breadth):
self.lentgh = lentgh
self.breadth = breadth
def getArea(self):
print(self.lentgh * self.breadth,"Is area of rectangle")
class Square(Rectangle):
def __init__(self, side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side,"is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()
| true |
0bf5883db8abc4f19b9fa91778012fc4a0faa28d | pkiuna/CS490-MachineLearning-Python | /ICP2/ICP2.py | 1,350 | 4.15625 | 4 | class employee:
# Members to count employees and find average salary
counter = 0
salary = 0
#contructor to initialize family, salary, department using self
def _init_(self, name, family, salary_num, department):
self.name = name
self.family = family
self.salary_num = salary_num
self.department = department
employee.counter += 1 # count of employees
employee.salary += salary_num # Average the salaries of employees
# calculate average salary
def get_avg_salary(self):
avg_salary = self.salary / self.counter
print("The average salary is: " + str(avg_salary))
return
def _init_(self, name, family, salary_num, department): # inherit of employee class when initializing
employee._init_(self, name, family, salary_num, department)
def main():
emp1 = employee("Paul", "Kiuna", 4000, "IT")
emp1.display()
emp2 = employee("Rachel", "Morris", 4000, "CS")
emp2.display()
emp3 = employee("Matthew", "Stocks", 4000, "IT")
emp3.display()
emp4 = employee("Rachel", "Stills", 4000, "CS")
emp4.display()
emp5 = employee("Morgan", "Belle", 4000, "IT")
emp5.display()
emp6 = employee("George", "Kiuna", 4000, "CS")
emp6.display()
if __name__ == '__main__':
main() | true |
7e24870e885624f70f0532f545823d73e3a16a1a | annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan | /Lecture_6/insertion_sort.py | 345 | 4.15625 | 4 | def insertion_sort(num):
for i in range(1, len(num)):
value_to_insert = num[i]
j = i - 1
while j >= 0 and value_to_insert < num[j]:
num[j + 1], num[j] = num[j], num[j + 1]
j -= 1
numbers = [int(elem) for elem in input("enter the numbers: ").split()]
insertion_sort(numbers)
print(numbers)
| true |
26eb512c18e30d70e0a383ca748302bfef9a3681 | samarthgowda96/pycharprojects | /pal.py | 493 | 4.15625 | 4 | string= input("enter the input"+" ")
def isPalindrome(str):
length = len(str)
first = 0
last = length - 1
palindrome = 1
while first < last:
if(str[first] == str[last]):
first = first + 1
last = last - 1
continue
else:
palindrome= 0
break
return palindrome
palindrome= isPalindrome(string)
if(palindrome):
print(string+" "+"it is a palindrome")
else:
print("Please try again :)")
| true |
8b89a4b42869fb143357174fcf98e5c0d50170e8 | srujanprophet/PythonPractice | /11 - Unit 4/4.1.12.py | 407 | 4.1875 | 4 | str = "Global Warming"
print str[-4:]
print str[4:9]
if str.isalpha() == True:
print "It has alphanumeric characters"
else:
print "It does not have alphanumeric characters"
print str.strip("ming")
print str.strip("Glob")
print str.index('Wa')
print str.swapcase()
if str.istitle() == True:
print "It is in Title Case"
else:
print "It is not in Title case"
print str.replace('a','*')
| true |
f02ac49567bc1f4089fcc75e4307c397ffc9cdf0 | saurabhpati/python.beginner | /OperatorsAndConditionals/elif.py | 535 | 4.40625 | 4 | # elif keyword is used to make the else if statement in python
# Requirement for this example: User gives the amount.
# 1. If amount is less than 1000, discount is 5%
# 2. If amount is less than (or equal to) 5000, discount is 10%
# 3. If amount is more than 5000, discount is 15%
amount = input('Enter the amount: ');
amount = int(amount);
if amount < 1000:
discount = amount * 0.05;
elif amount <= 5000:
discount = amount * 0.10;
else:
discount = amount * 0.15;
print('The total amount to be paid', amount - discount); | true |
fe5b725a5760c7c55a3aeff33b85cce2aaa6aa5a | saurabhpati/python.beginner | /Lists/list-operations.py | 1,426 | 4.5 | 4 | # iterating over a list.
testList = [1, 2, 3] ;
for x in testList:
print(x, end='\n');
# extend will the given list to the list on which extend is called.
languagesKnownList = ['c#', 'javascript','python'];
languagesKnownList.extend(testList)
print('Languages known and extended:', languagesKnownList);
# append will only add a single element to the list at the end of the list.
languagesKnownList.append('C');
print('The good old forgotten friend: ', languagesKnownList);
# pop will remove the last element from the list and return the same.
print('Popped', languagesKnownList.pop());
# index will return the lowest index of the required element.
print('index of javascript is: ', languagesKnownList.index('javascript'));
# insert will add a list at a given index.
languagesKnownList.insert(0, 'C');
print('Good old friend is back at index 0: ', languagesKnownList);
cleansedList = [];
# This loop will try to convert the element in language list into ints,
# if successful meaning no exceptions were raised, then value of the element is an integer.
# cleansed list will contain only strings.
# Note: This is done because if the list contains both strings and integers,
# then using sort method will throw an error.
for language in languagesKnownList:
try:
value = int(language);
except:
cleansedList.append(language);
cleansedList.sort();
print('Cleansed list: ', cleansedList); | true |
3ec9c0250c484d50af12a557650e415956c1303f | saurabhpati/python.beginner | /OperatorsAndConditionals/arithmetic.py | 287 | 4.3125 | 4 | # This programs intends to highlight between the differences of '/' and '//' operators.
x = input('Enter the dividend: ');
y = input('Enter the divisor: ');
x = int(x);
y = int(y);
print('x/y = ', x/y);
print('x//y = ', x//y);
print('divident raised to the power of divisor = ', x**y); | true |
a0050a3c5375653743e52283756fbe648cb01e62 | kazmanbanj/Practice_on_Python | /file io/script.py | 953 | 4.1875 | 4 | # my_file = open('test.txt')
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# print(my_file.readlines())
# my_file.close()
# Standard way to Read, write, append in python
# with open('test.txt', mode='r+') as my_file:
# print(my_file.readlines())
# with open('test.txt', mode='r+') as my_file:
# text = my_file.write(':)')
# print(text)
# with open('test.txt', mode='a') as my_file:
# text = my_file.write('\nthis will append to the text file with the mode a')
# print(text)
# with open('testAnother.txt', mode='w') as my_file:
# text = my_file.write('\nthis will create a new text file with the mode w')
# print(text)
# file paths
try:
with open('movedHere/testAnother.txt', mode='r') as my_file:
print(my_file.read())
except FileNotFoundError as err:
print('file does not exist')
except IOError as err:
print('IO error') | true |
c666e839c06a7dcb299706f8fb77bbccf29d1e70 | kb9zzw/arcpy_scripts | /distanceTry.py | 1,012 | 4.1875 | 4 | #Name: distanceTry.py
#Purpose: converts miles to kilometers or vice-versa
#Usage: distanceTry.py <numerical_distance> <distance_unit>
#Example: distanceTry.py 5 miles
#Author: Jon Burroughs (jdburrou)
#Date: 2/16/2012
import sys
# get distance value from user (assume they'll provide it correctly)
distance = float(sys.argv[1])
try :
# attempt to get units from the user.
units = sys.argv[2].lower()
except IndexError :
# warn user, then set default units to 'miles'
print "Warning: no distance_unit was provided. Default unit, miles used."
units = "miles"
if units == 'miles' :
# convert mi to km
print "%.1f miles is equivalent to %.1f kilometers." % (distance, distance * 1.609344)
elif units == 'kilometers' :
# conver km to mi
print "%.1f kilometers is equivalent to %.2f miles." % (distance, distance / 1.609344)
else :
# punt
print "I don't know how to convert from '%s', distance_unit should be 'miles' or 'kilometers'." % units | true |
8713d7b1db28ea750666376aecce9231393655bf | PromytheasN/Project_Euler_Solutions_1-10 | /Task 5 Solution.py | 1,201 | 4.1875 | 4 | import numpy
def small_divident():
"""
This is a function that calculates the smallest divident number,
evenly divisable by all numbers between 1 to 20.
"""
#If our number is evenly divisable with the list bellow, it should be evenly divisable with
#1 to 10 as well as all the numbers bellow are primes or multiples of numbers of 1 to 10.
#This will increasae the time efficiency of our function.
#Here we create an array of our list using NumPy module
div_array = numpy.array([20,19,18,17,16,15,14,13,12,11])
#20*19 = 390, that would be the smallest possible number that could be divided both from 20 and 19.
#Using that number instead of just adding 20 for each failed attempt will increase time efficiency
num = 390
nofound = True
while nofound:
#Checking if we have evenly division between num and our array
div = num % div_array
#Checking if all elements in our div list are 0
if all(element == 0 for element in list(div)):
nofound = False
#If not we increase num and repeat the process
else:
num += 390
return num
| true |
afa0a8a76248a73be56eec3d388a23ec11945f96 | anandtakawale/classcodes | /optimizations_sem8/fibonacci.py | 2,787 | 4.15625 | 4 | import texttable
import math
def fibonacciMethod(f, a, b, epsilon):
"""
Returns minima of the function
"""
#calculating number of iterations
fn = (b - a) / epsilon
n = fibFinder(fn)
print n
k = 0
table = texttable.Texttable()
table.add_row(["Iteration", "a", "b", "x1", "x2", "f(x1)", "f(x2)"])
while k <= (n - 3):
l = float(b - a)
#creating factor obtained from fibonacci series
factor = float(fib(n-k-1))/ fib(n-k)
x1 = a + (1 - factor) * l
x2 = a + factor * l
f1 = f(x1)
f2 = f(x2)
#adding rows to table
table.add_row([k, a, b, x1, x2, f1, f2])
#elimination of region
if f2 < f1:
a = x1
elif f1 < f2:
b = x2
else:
a = x1
b = x2
k += 1
print table.draw() + '\n'
return (x1 + x2) / 2
def fibonacciIter(f, a, b, n):
"""
Fibonacci search method based on number of iterations reuiqred as as per book
f: function to be minimized
(a, b): interval of search
n: number of iterations required
"""
L2star = float(fib(n - 2))/ fib(n) * (b - a)
j = 2
table = texttable.Texttable()
table.add_row(["Function evals", "a", "b", "x1", "x2", "f(x1)", "f(x2)", "L2"])
while j <= n:
L1 = b - a
if L2star > L1/2.0:
x2 = a + L2star
x1 = b - L2star
else:
x2 = b - L2star
x1 = a + L2star
f1 = f(x1)
f2 = f(x2)
#adding row to table
table.add_row([j, a, b, x1, x2, f1, f2, L2star])
#eliminating correct interval
if f2 < f1:
a = x1
L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a)
elif f2 > f1:
b = x2
L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a)
else:
a = x1
b = x2
L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a)
j += 1
j += 1
print table.draw(), '\n'
return a, b
def fibFinder(fibo):
"""
Returns number n such that fib(n) > fibo
"""
n = 1
while fib(n) < fibo:
n += 1
return n
def f(x):
"""
Returns value of the function of f(x)
"""
return x**2 + 54 / x
#return x**4 - 15*x**3 + 72*x**2 - 1135*x
#return math.exp(x) - x**3
def fib(x, cache = {}):
"""
Returns fibonacci series by using dynamic programming.
Observe use of dictionary cache.
"""
if x == 0:
return 1
elif x == 1:
return 1
else:
if x not in cache.keys():
cache[x] = fib(x-1) + fib(x-2)
return cache[x]
if __name__ == '__main__':
print fibonacciIter(f, 0, 6, 10)
| true |
35cd0814bb7aaedc923c533943637886830c0593 | AshVijay/Leetcode_Python | /496.py | 2,433 | 4.125 | 4 | """
496. Next Greater Element I
Easy
1103
1685
Add to List
Share
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
"""
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
great_dict= {}
index_dict = {}
#To store corresponding indices across arrays
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i] == nums2[j]:
index_dict[nums1[i]] = j
#To store largest elements to the right
for i in range(len(nums1)) :
j = index_dict[nums1[i]]+1
if j == len(nums2):
great_dict[i] = -1
while j < len(nums2) :
if j == len(nums2) -1 and nums2[j] <= nums1[i] :
great_dict[i] = -1
break
if nums2[j] > nums1[i] :
great_dict[i] = nums2[j]
break
j+=1
final = [-1 for elm in nums1]
for i in range(len(nums1)):
final[i] = great_dict[i]
return final
| true |
70ac588cf1ba0c9fd8db5fe5688ed44730e73efe | Tadrop/30_days_of_code | /day9.py | 484 | 4.21875 | 4 | def fibSum(number):
if not isinstance(number,int):
return 'Invalid input, number must be positive integer'
if number == 0 :
return 0
elif number < 0:
return "Invalid, number can't be negative"
elif number > 0:
pass
num =0
a,c=0,1
while c>=number:
a,c= c, a+c
if (c%2) == 0 :
number+=c
return number
print(fibSum(10))
print(fibSum(0))
print(fibSum(-3))
print(fibSum('a'))
| true |
69c2bc890089754abd6ca0021ba726b2ebe7844b | Abinesh1991/Numpy-tutorial | /NumpyTutorial8.py | 755 | 4.28125 | 4 | """
Python, Numpy and Probability
Random using numpy
"""
import numpy as np
outcome = np.random.randint(1, 7, size=10)
print(outcome)
# generated 5*4 matrix using the random number range from 1 - 7
"""
output:
[[4 4 5 4]
[4 4 5 2]
[3 3 3 4]
[3 5 4 5]
[6 1 2 6]]
"""
print(np.random.randint(1, 7, size=(5, 4)))
# Random Choices with Python
"""
choice' is another extremely useful function of the random module.
This function can be used to choose a random element from a non-empty sequence.
"""
# using choice we can pick random from string or list
from random import choice
professions = ["scientist", "philosopher", "engineer", "priest"]
print(choice("abcdefghij"))
print(choice(professions))
print(choice(("apples", "bananas", "cherries")))
| true |
409cb01cecf4af685af65480648c49c8efaf57c0 | Abinesh1991/Numpy-tutorial | /NumpyTutorial5.py | 2,239 | 4.1875 | 4 | """
Data type object 'dtype' is an instance of numpy.dtype class. It can be created with numpy.dtype.
"""
import numpy as np
# sample example with int16 data type
i16 = np.dtype(np.int16)
print(i16)
lst = [[3.4, 8.7, 9.9],
[1.1, -7.8, -0.7],
[4.1, 12.3, 4.8]]
A = np.array(lst, dtype=i16)
print(A)
"""
We create a structured array with the 'density' column. The data type is defined as np.dtype([('density', np.int)]).
We assign this data type to the variable 'dt' for the sake of convenience.
We use this data type in the darray definition, in which we use the first three densities
Output:
[(393,) (337,) (256,)]
The internal representation:
array([(393,), (337,), (256,)],
dtype=[('density', '<i4')])
"""
# defining the dataType for density
dt = np.dtype([('density', np.int32)])
# also we can write above code like this
dt = np.dtype([('density', 'i4')])
# creating an array
x = np.array([(393,), (337,), (256,)],
dtype=dt)
print(x)
print("\nThe internal representation:")
print(repr(x))
"""
Defining a data type for each fields:
S20 - String can contains length 20
i2 - int16
i4 - int32
"""
dt = np.dtype([('country', 'S20'), ('density', 'i4'), ('area', 'i4'), ('population', 'i4')])
x = np.array([('Netherlands', 393, 41526, 16928800),
('Belgium', 337, 30510, 11007020),
('United Kingdom', 256, 243610, 62262000),
('Germany', 233, 357021, 81799600),
('Liechtenstein', 205, 160, 32842),
('Italy', 192, 301230, 59715625),
('Switzerland', 177, 41290, 7301994),
('Luxembourg', 173, 2586, 512000),
('France', 111, 547030, 63601002),
('Austria', 97, 83858, 8169929),
('Greece', 81, 131940, 11606813),
('Ireland', 65, 70280, 4581269),
('Sweden', 20, 449964, 9515744),
('Finland', 16, 338424, 5410233),
('Norway', 13, 385252, 5033675)],
dtype=dt)
print(x[:4])
print(x['density'])
print(x['country'])
print(x['area'][2:5])
# example1:
# defining the user defined data type
time_type = np.dtype(np.dtype([('time', [('h', int), ('min', int), ('sec', int)]),
('temperature', float)]))
times = np.array([((2, 42, 17), 20.8), ((13, 19, 3), 23.2)], dtype=time_type)
print(times)
print(times['time'])
print(times['time']['h'])
print(times['temperature'])
| true |
8b57cdcbba3d3c0f7d0203ec3be8e29167c11a8d | Helianus/Python-Exercises | /src/SumOfNumbers.py | 452 | 4.25 | 4 | #Given two integers a and b, which can be positive or negative,
# find the sum of all the numbers between including them too and return it.
# If the two numbers are equal return a or b.
# Note: a and b are not ordered!
def get_sum(a, b):
sum = 0
if a == b:
return a
elif a > b:
for i in range(b, a+1):
sum += i
else:
for i in range(a, b+1):
sum += i
return sum
print(get_sum(0, 5)) | true |
11ef074543b310af32ce9d0b43a2a23111422650 | mor16fsu/bch5884 | /tempconversion.py | 286 | 4.25 | 4 | #!/usr/bin/env python3
#github.com/mor16fsu/bch5884
import math
x=float(input("Please enter a value in degrees Farenheit to convert to degrees Kelvin:"))
print (type (x))
x=float(x)
y=math.floor(x-32)*5/9+273.15
print (y)
print ("The calculation is complete: Degrees Kelvin")
| true |
6db4d82f13ebcf3bb99365d2b8af9ff458ca5961 | puhelan/150 | /1. DS/1.1.py | 1,364 | 4.3125 | 4 | ''' 1.1
_______________________________________________________________________________
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures?
_______________________________________________________________________________
Notes:
1. with hash map
2. nxn
3. sort and copmare
time complexity, memory
O(n) =
_______________________________________________________________________________
'''
def all_unique_characters(string):
alphabet = {}
for char in string:
if char in alphabet:
alphabet[char] += 1
else:
alphabet[char] = 1
for x in alphabet.values():
if x > 1:
return False
return True
def all_unique_characters2(string):
for char in string:
if string.count(char) > 1:
return False
return True
def all_unique_characters3(string):
string = ''.join(sorted(string))
for i, char in enumerate(string[:-1]):
if char == string[i + 1]:
return False
return True
if __name__ == '__main__':
strings = ['az obicham mach i boza',
'superb',
'Kakv0 st@va?',
'уникат',
'уникатт'
]
print(strings)
print('\n 1. with hash map')
print([* map(all_unique_characters, strings)])
print('\n 2. nxn')
print([* map(all_unique_characters2, strings)])
print('\n 3. sort and copmare')
print([* map(all_unique_characters3, strings)]) | true |
cdacc8f0adeea4aab139c8bb9d714415fc294c9a | BryceBoley/PythonExercises | /Exercise_2.py | 1,059 | 4.28125 | 4 | # getting user input and checking that it is a number and not zero
gas = input("\nWelcome to the fun conversion tool!\n\nPlease enter a number to represent gallons of gasoline: ")
while not gas.isdigit() or int(gas) == 0:
gas = input("A number you numskull, not a letter or zero!\nEnter your number")
# math for conversions
gas = float(gas)
liter = gas * 3.7854
oil = gas / 19.5
co2 = gas * 20
etoh = (gas * 115000)/75700
cost = gas * 4.00
# print converted values to user using string formatting
print("_" * 80 + "\n" + "Original number of gallons is %.1f" % gas)
print("_" * 80 + "\n" + "%.1f gallons is the equivalent of %.1f liters" % (gas, liter))
print("%.1f gallons of gasoline requires %.1f barrels of oil" % (gas, oil))
print("%.1f gallons of gasoline produces %.1f pounds of CO2" % (gas, co2))
print("%.1f gallons of gasoline is energy equivalent to %.3f gallons of ethanol" % (gas, etoh))
print("%.1f gallons of gasoline requires %.2f US dollars" % (gas, gas * 4.00))
print("_" * 80 + "\n" + "Thanks for tyring the amazing conversion tool!")
| true |
1429b690d10a055ef3dfcdb7fd855470b5c4a310 | Teldrin89/DBPythonTut | /LtP11_custom_exception.py | 991 | 4.15625 | 4 | # it is possible to create a custom exception - it has to be
# inherited from the exception class
# create a new class for handling custom made exception - use
# inheritance of exception build in class
class DogNameError(Exception):
# initialize the class with init function
def __init__(self, *args, **kwargs):
# use exception method to initialize
Exception.__init__(self, *args, **kwargs)
# the try block contains the input from user
try:
# ask for dog name
dogName = input("What is your dogs name: ")
# check if in any of the characters for dog name is a digit
# using both if statement and for loop inside
if any(char.isdigit() for char in dogName):
# if there is a digit raise an exception and call
# for custom exception created
raise DogNameError
# exception handling block with custom exception to execute
except DogNameError:
# printout the error message
print("Your dogs name can't contain a number")
| true |
50b4bc46338d0e7ff766988ea9ed05f565aaa7a0 | Teldrin89/DBPythonTut | /Problem_23.py | 1,445 | 4.28125 | 4 | import re
# Problem 23:
# Use regular expressions to match email addresses
# from the list with set rules for what is an email
# address (just find how many there are):
# 1. 1 to 20 lowercase and uppercase letters, numbers,
# plus ._%+- symbols
# 2. An @ symbol
# 3. 2 to 20 lower case and uppercase letters, numbers
# plus .- symbols
# 4. A period
# 5. 2 to 3 lowercase and uppercase letters
# create a dummy list of emails, not all following the rules
emailList = "db@aol.com me@.com @apple.com db@.com"
# email = "db@.com"
# printout how many of email addresses there are that follow
# the rules using re.findall - specified characters in []
# brackets and number of characters in {} brackets
print("Email Matches: ", len(re.findall("[\w._%+-]{2,20}@"
"[\w.-]{2,20}."
"[A-Za-z]{2,3}",
emailList)))
# some additional solution - mine - printout the email address
# that fulfills the criteria
# first, split string with all addresses and create a list
listOfEmails = emailList.split()
# run for loop by all email addresses from the list
for email in listOfEmails:
# use re.search function with the same set of criteria
if re.search("[\w._%+-]{2,20}@"
"[\w.-]{2,20}."
"[A-Za-z]{2,3}", email):
# printout email address if criteria are met
print("Email: ", email)
| true |
21c8f84e8b76eff91026f0c155d2a552952b8edb | Teldrin89/DBPythonTut | /LtP13_list_comprehension.py | 1,970 | 4.8125 | 5 | # list comprehension is going to execute an expression
# against an iterable - much as "map" and "filter"
# while a list comprehension is powerful it has to be used
# with cautious to not get overcomplicated
# use different methods to obtain the same list
# of values: multiplication by 2 using map and lc
# a) map
print(list(map((lambda x: x*2), range(1,11))))
# b) list comprehension - it is stored in [] brackets
# and automatically generates a list (therefore no need
# to specify list in expression)
print([2 * x for x in range(1, 11)])
# use different methods to obtain the same list
# of values: only odds using filter and lc
# a) filter - get only odd values
print(list(filter((lambda x: x % 2 != 0), range(1, 11))))
# b) list comprehension - use the same expression but
# put it in "if" statement inside "for" loop
print([x for x in range(1, 11) if x % 2 != 0])
# more complicated example - generate 50 values and take
# to the power of 2; then return only multiples of 8
print([i ** 2 for i in range(50) if i % 8 == 0])
# it is also allowed to use multiple "for" loops inside
# list comprehension method - prepare a script that
# generates a list of 2 other lists multiplied by one
# another
print([x*y for x in range(1, 3) for y in range(11, 16)])
# it is possible to put list comprehension inside other
# list comprehension (lc), example: generate a list of 10
# values, multiply them by 2 and return multiples of 8
print([x for x in [i * 2 for i in range(10)]
if x % 8 == 0])
# list comprehension in work with multidimensional lists
multi_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# printout the second character from each of inner lists
# from multidimensional list
print([col[1] for col in multi_list])
# printout diagonal from multidimensional list - this
# calls out for the place in array using 2 of the same
# values ("[i][i]", hence we get diagonal
print([multi_list[i][i] for i in range(len(multi_list))])
| true |
bc22d61afc37ca167a7550f922397c394f9c4d9a | Teldrin89/DBPythonTut | /Problem17.py | 1,317 | 4.375 | 4 | # Problem 17:
# - create a file named "mydata2.txt" - put any type of data
# - use methods from LtP8 how to open a file without "with"
# (open in "try" block)
# - catch FileNotFoundError
# - in "else" print contents of the file
# - in finally print out some msg that will always be on screen
# - try to open nonexistent file mydata3.txt - test
# create a try block
try:
# inside open file using built in method open, by default
# it is set to read, remember about encoding format
my_file = open("mydata2.txt", encoding="utf-8")
# create an except block for handling error - in particular
# the error which will handle the missing of file
# define the error as variable "ex"
except FileNotFoundError as ex:
# printout msg in case of an exception
print("That file was not found")
# printout additional information about the exception
print(ex.args)
# create an else block - in case it finds the set file
else:
# printout the information from text file - read function
# of assigned variable for the file open method
print("File: ", my_file.read())
# close the file
my_file.close()
# create a "finally" block
finally:
# printout the massage that will be shown regardless if
# the file has been found or not
print("Finished working with exception handling")
| true |
58684c61c8d6dcecc16fb15542f46ef9a6dcffe0 | Teldrin89/DBPythonTut | /LtP14_threads_example.py | 2,750 | 4.40625 | 4 | # example of threads usage: whenever threads are used
# it is possible to block one of the threads - the
# real world script that can utilize this option
# will cover a modeling of bank account: let's say
# that there is 100$ in the account but there are 3
# different people that can withdraw money from that
# account, the script will block the possibility
# of withdrawing money from the account while
# one of the person is taking the money at a time
import threading
import time
import random
# create a class for bank account with threads
class BankAccount(threading.Thread):
# static variable
accountBalance = 100
# initialize a thread with name and amount of
# money requested
def __init__(self, name, moneyRequest):
threading.Thread.__init__(self)
# assign name of person that want to
# withdraw money
self.name = name
# get the amount of money to be withdrawn
self.moneyRequest = moneyRequest
# run property definition
def run(self):
# create locking property - not to be able
# to acquire the money from other threads
threadLock.acquire()
# access to get the money from account
BankAccount.getMoney(self)
# release the lock for a thread after first
# withdraw to work
threadLock.release()
# create a static method for getting money
@staticmethod
def getMoney(customer):
# printout the msg about who, how much and
# when wants to withdraw money from account
print("{} tries to withdraw {}$ at"
"{}".format(customer.name,
customer.moneyRequest,
time.strftime("%H:%M:%S",
time.gmtime())))
# what to do in case of enough money in account
if BankAccount.accountBalance - customer.moneyRequest > 0:
BankAccount.accountBalance -= customer.moneyRequest
print("New account balance: "
"{}$".format(BankAccount.accountBalance))
# what to do in case there is not enough money
else:
print("Not enough money in account")
print("Current balance: "
"{}$".format(BankAccount.accountBalance))
# time to sleep after execution - needed to see the
# difference in execution of next threads
time.sleep(3)
# thread lock method assigned
threadLock = threading.Lock()
# 3 people wants to take specific amount of money
luke = BankAccount("Luke", 1)
john = BankAccount("John", 100)
jean = BankAccount("Jean", 50)
# start all threads
luke.start()
john.start()
jean.start()
# join all threads
luke.join()
john.join()
jean.join()
# end printout msg
print("Execution Ends")
| true |
56ecd290945ebaceecad8e9ea69386558474eb74 | Teldrin89/DBPythonTut | /LtP1.py | 999 | 4.25 | 4 | # Ask the user to input their name and assign
# it to a variable named name
name = input('What is your name ')
# Print out hello followed by the name they entered
print('Hello ', name)
# Ask the user to input 2 values and store them in variables
# num1 and num2
num1, num2 = input('Enter 2 numbers: ').split()
# Convert the strings into regular numbers
num1 = int(num1)
num2 = int(num2)
# Add the values entered and store in sum
summ = num1 + num2
# Subtract values and store in difference
difference = num1 - num2
# Multiply values and store in product
product = num1 * num2
# Divide values and store in quotient
quotient = num1 / num2
# Use modulus on the values to find the remainder
remainder = num1 % num2
# Print results
print("{} + {} = {}".format(num1, num2, summ))
print("{} - {} = {}".format(num1, num2, difference))
print("{} * {} = {}".format(num1, num2, product))
print("{} / {} = {}".format(num1, num2, quotient))
print("{} % {} = {}".format(num1, num2, remainder))
| true |
45f2072b3cf0ab1858f85048ebf2c1672e904e6c | Teldrin89/DBPythonTut | /LtP6_lists.py | 1,900 | 4.21875 | 4 | import random
import math
# list generated similar as to in problem 11
num_list = []
for i in range(5):
num_list.append(random.randrange(1, 10))
# sorting list
num_list.sort()
# reverse sorting
num_list.reverse()
# change value at specific index -in this example it inserts
# number "10" at index 5
num_list.insert(5, 10)
# remove item from list
num_list.remove(10)
# remove item at specific index
num_list.pop(2)
for k in num_list:
print(k, end=", ")
print()
# list comprehensions - a way to create a list by doing operations
# on each item in a list
# this will generate list of 10 items, each multiplied by 2
even_list = [i*2 for i in range(10)]
# printout the resulting list
for i in even_list:
print(i)
# Create a list of lists with the same method (using multiple
# different calculations)
# List of 5 items
numberList = [1,2,3,4,5]
# List of 5 lists with 3 items in each (to the power of 2,3 and 4)
listOfValues = [[math.pow(m, 2), math.pow(m,3), math.pow(m, 4)]
for m in numberList]
# printout results
for i in listOfValues:
print(i)
print()
# create 10x10 list of lists - this one is populated by "0"
multiDlist = [[0] * 10 for i in range(10)]
for i in multiDlist:
print(i)
print()
# change values in the list
multiDlist[0][1] = 10
for i in multiDlist:
print(i)
print()
# Specific indexes for 2D matrix (list of lists)
# Establish "empty" (filled with "0") list of lists - 4x4
listTable = [[0]*4 for i in range(4)]
# for loops going through 2 dimensions of matrix (call them "x"
# and "y") and store the indexes in each value separated by "|"
for i in range(4):
for j in range(4):
listTable[i][j] = "{} : {}".format(i, j)
# printout the results - each value and each row in new line
for i in range(4):
for j in range(4):
print(listTable[i][j], end=" | ")
print()
# printout full list of lists
print(listTable)
| true |
33ba04c4c59b0e51ef8f8e5acd62f2cffb9e05bb | AricA05/Python_OOP | /encapsulation.py | 1,480 | 4.34375 | 4 | #4.Encapsulation
'''It is the concept of wrapping data such that the outer world has access only to exposed properties.
Some properties can be hidden to reduce vulnerability.
This is an implementation of data hiding.
For example, you want buy a pair of trousers from an online site.
The data that you want is its cost and availability.
The number of items present and their location is information that you are not bothered about. Hence it is hidden.
In Python this is implemented by creating private, protected and public instance variables and methods.
Private properties have double underscore (__) in the start, while protected properties
have single underscore (_). By default, all other variable and methods are public.
Private properties are accessible from within the class only and are not available for child class(if inherited).
Protected properties are accessible from within the class but are available to child class as well.
All these restrictions are removed for public properties.
The following code snippets is an example of this concept:'''
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def _protected_method(self):
print("protected method")
def __private_method(self):
print("privated method")
if __name__ == "__main__":
p = Person("mohan", 23)
p._protected_method() # shows a warning
p.__private_method() # throws Attribute error saying no such method exists | true |
f7c22e308aa4f6903129e8b7d76842ff5c830e14 | dansackett/learning-playground | /project-euler/problem_1.py | 321 | 4.25 | 4 | #!/usr/bin/python
"""
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
limit = 1000
print sum(x for x in xrange(limit) if not x % 3 or not x % 5)
| true |
d01b142a983b9c682f5412d7c504b642fd847cd3 | adimukh1234/python_projects | /hangman1.py | 871 | 4.125 | 4 | import random
name = input("What is your name?\n")
print("Hello ", name)
print("Welcome to the Hangman Game \nBest of luck")
words = ["balloon", "hook", "octopus", "communication", "piano", "honey", "playstation"]
guesses = ''
word = random.choice(words)
print("Guess the characters!")
turns = 6
# main loop of game
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char)
else:
print("_")
failed += 1
if failed == 0:
print("You win")
print("The word is ", word)
break
# taking user input
guess = input("guess any letter: ")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print(f"You have {turns} turns left")
if turns == 0:
print("You Lose")
| true |
ca8a612e654795d55625e199997945549b713a1c | untalinfo/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 296 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Basic annotations - to string
"""
def to_str(n: float) -> str:
"""takes a float n as argument and returns the string representation
of the float
Args:
n (float): number
Returns:
str: convert float to string
"""
return str(n)
| true |
a16d910dad34c229805ed9875e638a077216b788 | StarTux/DailyCodingProblem | /003-2019-03-07-TreeSerialize.py | 1,154 | 4.125 | 4 | #!/usr/bin/python3
# Problem #3 [Medium]
# Given the root to a binary tree, implement serialize(root),
# which serializes the tree into a string, and deserialize(s),
# which deserializes the string back into the tree.
#
# For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
DELIM = '|'
def serialize(node):
result = node.val + DELIM
if node.left is not None:
result += serialize(node.left)
result += DELIM
if node.right is not None:
result += serialize(node.right)
return result
def deserialize(str):
toks = str.split(DELIM)
return deserializeHelper(toks, 0)
def deserializeHelper(toks, index):
val = toks[index]
if len(val) == 0: return None
left = deserializeHelper(toks, index + 1)
right = deserializeHelper(toks, index + 2)
return Node(val, left, right)
# The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
print(serialize(node))
| true |
0aebab530dfa54a10e1d98bd2ba6ad0458f85b2b | jp117/codesignal | /Arcade/Intro/010 - commonCharacterCount.py | 804 | 4.125 | 4 | '''
https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
Input/Output
[execution time limit] 4 seconds (py3)
[input] string s1
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ s1.length < 15.
[input] string s2
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ s2.length < 15.
[output] integer
'''
def commonCharacterCount(s1, s2):
count = 0
i = 0
for i in range(len(s1)):
if s1[i] in s2:
s2 = s2.replace(s1[i], '', 1)
count += 1
return count | true |
14c11a27484edf19581bca75d54f84ad101b16c0 | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/1-sensitivity.py | 736 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Calculates sensitivity in a confusion matrix
"""
import numpy as np
def sensitivity(confusion):
"""
Calculates the sensitivity for each class in a confusion matrix
Args:
- confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices represent the correct labels and column
indices represent the predicted labels
* classes: is the number of classes
Return:
A numpy.ndarray of shape (classes,) containing the sensitivity of each
class
"""
positive = np.sum(confusion, axis=1)
true_positive = np.diagonal(confusion)
sensitivity = true_positive / positive
return np.array(sensitivity)
| true |
30f5b94defb435a4bb6d98c51b865b46446ef48c | deepika-13-alt/Python-Assignment | /assignment2/second_smallest.py | 1,087 | 4.34375 | 4 | '''
Program: WAP to input 3 numbers and find the second smallest.
'''
import re
# Declarations
regex_float = '[+-]?[0-9]+\.[0-9]+'
regex_int = "[-+]?[0-9]+$"
small_list = []
small_1 = 0
small_2 = 0
# Taking input from users
print("Enter 3 numbers for finding smallest among them")
for i in range(3):
inp = input("Enter any number to insert: ")
if re.search(regex_float, inp):
inp = float(inp)
small_list.append(inp)
elif re.search(regex_int, inp):
inp = int(inp)
small_list.append(inp)
else:
print("Invalid data entered!")
break
# Processing data
if len(small_list) == 3:
for item in small_list[1:]:
if item < small_1:
small_2 = small_1
small_1 = item
elif small_2 == 0 or small_2 > item:
small_2 = item
# Display output
print("The entered elements are: ", end=" ")
for item in small_list:
print(item, end=" ")
print(f"and, the second smallest number is: {small_2}")
else:
print("Unable to compute data! Insufficient data received!") | true |
9ea111f75ba5c9ceb956b78c3ac9f70fdf69540d | tachyonlabs/raspberry_pi_pyladies_presentation | /hello_world_blink.py | 1,566 | 4.28125 | 4 | # See https://github.com/tachyonlabs/raspberry_pi_pyladies_presentation
# for information on the wiring and the presentation in general
# The Rpi.GPIO library makes it easy for your programs to read from and write to
# the Raspberry Pi's GPIO (General Purpose Input/Output) pins
import RPi.GPIO as GPIO
import time
# GPIO.BCM mode selects the pin numbering system of GPIO pin channels
# as opposed to GPIO.BOARD mode which uses P1 connector pin numbers
GPIO.setmode(GPIO.BCM)
# Any Raspberry Pi pin you use needs to be set as either an input or an output
# Here we are setting pin GPIO 20 as an output to control the LED (I didn't choose
# GPIO pin 20 for any particular reason - you can use whichever GPIO pin or pins
# you like so long as you use the same pins in your circuit and your software)
led_pin = 20
GPIO.setup(led_pin, GPIO.OUT)
# Blink the LED twenty times, with a frequency of one second on, one second off
number_of_times_to_blink = 20
number_of_seconds = 1
for i in range(number_of_times_to_blink):
# Output high (3.3 volts) on pin 20, to turn the LED on
GPIO.output(led_pin, GPIO.HIGH)
# Leave the LED on for one second
time.sleep(number_of_seconds)
# Output low (0 volts) on pin 20, to turn the LED off
GPIO.output(led_pin, GPIO.LOW)
# Leave the LED off for one second
time.sleep(number_of_seconds)
# This resets any ports used in your program
GPIO.cleanup()
# Why not? :-)
print("Hello World!")
# This will print some general info about your Raspberry Pi
print("Raspberry Pi stats: {}".format(GPIO.RPI_INFO))
| true |
f4a1d0b9f4725cbb845088e97bf460d1931dc301 | mdeakyne/IT150 | /Blank Class Activities/0119Blank.py | 2,694 | 4.90625 | 5 | """
This assignment is worth 10 points and you should be able to answer the following questions after completing it:
What is the difference between a variable and a literal?
How do you assign variables in python?
How do you deal with errors in python?
What are different types of python variables?
How do you make a multiline comment?
How do you handle exponents in python?
What does % do in python?
"""
print "\nProblem 1----------------Errors-----------------------------"
#In this lab, you will deal with many errors. IndentErrors and NameErrors are the most common.
#Many times, it's because you've mispelled a variable you did define.
#Below there are three errors for you to deal with. Do not delete any lines, just add to the below code.
#You may edit the names of variables.
print "The variable name contains",name
def printName():
name = "Deakyne"
print "The variable name contains",name
printName()
print "The variable name contains",nmae
print "\nProblem 2----------------Comments--------------------------"
#These are all comments.
Make this into a comment
Instead
Of
Commenting
Out
Every
Line
Here
You
Can
Quickly
Comment
Multiple
Lines.
Please
Do
So.
print "Done with comments"
print "\nProblem 3----------------Literals vs. Variables---------------"
"This is a literal" # a literal is anything that only has one value.
variable = "This is a variable" # a variable can have many values, and can be reassigned.
variable = "Something different" # our variable has been reassigned a new value.
#below we have a variable named a and a literal 'b'. Add another variable b, and give it any value
a = 'b'
print "The variable a contains",a
print "The variable b contains",b
print "The literal a prints as",'a'
print "The literal b prints as",'b'
print "\nProblem 4-----------------Types-----------------------------"
#We will be introducing more types later in the course. Here are four variables, have python print the types
#As a reminder, you can use the type function. I'll refresh your memory.
f = 3.14
i = 7
s = "Hello there"
b = False
print "The type of printName is",type(printName)
print "The type of f is",type() #fill in these with the appropriate variable, following the example above
print "The type of i is",type()
print "The type of s is",type()
print "The type of b is",type()
print "\nProblem 5------------------Math----------------------------"
#Codecademy introduced *, +, -, /, ** and %
#Use them to figure out the following, and print the result
print "3243 + 23424 =",
print "10^2", #did you use python syntax?
print "10 / 6=", #double check this one, why is there no remainder?
print "10 % 6=", #Oh, that's where the remainder went.
| true |
8b0222d0314beb0a3ceb76d601ff1dd7803b8834 | jazywica/Computing | /_01_Interactive_Programming_1/_01_Rock-paper-scissors-lizard-Spock.py | 2,086 | 4.3125 | 4 | """ ROCK-PAPER-SCISSORS-LIZARD-SPOCK - simple game: player vs random computer choice """
# use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_uPVHROOe6b_2.py
# The key idea of this program is to equate the strings "rock", "paper", "scissors", "lizard", "Spock" to numbers as follows:
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
def name_to_number(name): # this is a helper function that will convert between NAMES and NUMBERS
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
return "Illegal name"
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
return "Illegal number"
def rpsls(player_choice):
player_number = name_to_number(player_choice)
computer_number = random.randrange(0, 5)
computer_choice = number_to_name(computer_number)
print
print "Player choose " + player_choice
print "Computer choose " + computer_choice
difference = (player_number - computer_number) % 5 # first - second = difference, which we then take modulo 5(total amount of elements) so we only have numbrs 0, 1, 2, 3, 4
if difference == 1 or difference == 2: # we have designed the 'wheel' in a way that two elements to the right are win and two to the left is loose...
print "Player wins!"
elif difference == 3 or difference == 4: # so it is easy to split it into 1,2 and 3,4
print "Computer wins!"
else:
print "Player and computer tie!"
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
| true |
6658a147827c0582c57c8c2cfb644a1342ef51ef | arnaudmiribel/streamlit-extras | /src/streamlit_extras/word_importances/__init__.py | 2,050 | 4.15625 | 4 | from typing import List
import streamlit as st
from .. import extra
@extra
def format_word_importances(words: List[str], importances: List[float]) -> str:
"""Adds a background color to each word based on its importance (float from -1 to 1)
Args:
words (list): List of words
importances (list): List of importances (scores from -1 to 1)
Returns:
html: HTML string with formatted word
"""
if importances is None or len(importances) == 0:
return "<td></td>"
assert len(words) == len(importances), "Words and importances but be of same length"
tags = ["<td>"]
for word, importance in zip(words, importances[: len(words)]):
color = _get_color(importance)
unwrapped_tag = (
'<mark style="background-color: {color}; opacity:1.0; '
' line-height:1.75"><font color="black"> {word} '
" </font></mark>".format(color=color, word=word)
)
tags.append(unwrapped_tag)
tags.append("</td>")
html = "".join(tags)
return html
def _get_color(importance: float) -> str:
# clip values to prevent CSS errors (Values should be from [-1,1])
importance = max(-1, min(1, importance))
if importance > 0:
hue = 120
sat = 75
lig = 100 - int(50 * importance)
else:
hue = 0
sat = 75
lig = 100 - int(-40 * importance)
return "hsl({}, {}%, {}%)".format(hue, sat, lig)
def example():
text = (
"Streamlit Extras is a library to help you discover, learn, share and"
" use Streamlit bits of code!"
)
html = format_word_importances(
words=text.split(),
importances=(0.1, 0.2, 0, -1, 0.1, 0, 0, 0.2, 0.3, 0.8, 0.9, 0.6, 0.3, 0.1, 0, 0, 0), # fmt: skip
)
st.write(html, unsafe_allow_html=True)
__title__ = "Word importances"
__desc__ = "Highlight words based on their importances. Inspired from captum library."
__icon__ = "❗"
__examples__ = [example]
__author__ = "Arnaud Miribel"
| true |
d9760fcbe2c615552887a271c707beb0bc7018b3 | sonyarpita/ptrain | /function_recursive.py | 260 | 4.53125 | 5 | def calc_factorial(x):
"""This is recursive function
to find the factorial of an integer"""
# return(x*calc_factorial(x-1))
if x == 1:
return 1
else:
return (x*calc_factorial(x-1))
num=5
fact=calc_factorial(num)
print("Factorial of",num,"=",fact)
| true |
662ed97b3d686b28c2345a53425b37ffd871055d | sonyarpita/ptrain | /ReModule/Metacharacters/alternation.py | 222 | 4.34375 | 4 | import re
str = "The stays rain in Spain maui falls mainly in the plain!"
#Check if the string contains "falls" or "stays"
x=re.findall("falls|stays",str)
print(x)
if (x):
print("match")
else:
print("No Match")
| true |
8f167f28002b91f926c295843a0131fa194c04b9 | sonyarpita/ptrain | /Advanced_Functions/unzip_1.py | 570 | 4.25 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
print("\n")
#unzip
namez,roll_noz,marksz=zip(*mapped)
print("Unzipped results: \n",end=" ")
#print initial list
print("Name list= ",end=" ")
print(namez)
print("Roll Number list= ",end=" ")
print(roll_noz)
print("Marks list= ",end=" ")
print(marksz)
| true |
f63386a5b3cb3c829f318691f3e87fb878d4a56a | sonyarpita/ptrain | /ReModule/Metacharacters/Period.py | 235 | 4.125 | 4 | import re
str = "hello world helo"
# search for a sequence that starts with "he", followed by two (any)characters, and an "o"
x=re.findall("he..o", str)
print(x)
x=re.findall("he...o", str)
print(x)
x=re.findall("he.o", str)
print(x)
| true |
3a9d2e9ddcb4ded42e2df4130db0cb1b87e5cf35 | sonyarpita/ptrain | /Advanced_Functions/zip_1.py | 317 | 4.28125 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
| true |
bb699c692c649f5a3a6a2a5df0a2ff6b598eb0f2 | dubirajara/learning_python | /add_length.py | 274 | 4.125 | 4 | '''
write a function that takes a String and returns an
list with the length of each word added to each element.
'''
def add_length(words):
return [f'{i} {str(len(i))}' for i in words.split()]
assert add_length('carrot cake') == ['carrot 6', 'cake 4'] # testcase
| true |
66d50bc8acfe3e1a4a3997170fa10f6f00302f07 | kamat-o/MasteringPython | /27_08_2019/AddTwoNumbers.py | 239 | 4.1875 | 4 |
# get the input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
#compute the addition
result = num1 + num2
#print the result
print ("The sum of {0} and {1} is {2}".format(num1,num2,result)) | true |
a65c5f2d60e78fda18111cbf5498d5855d49bfc7 | hina-murdhani/python-project | /pythonProject3/demo/set.py | 1,391 | 4.375 | 4 | # set has no duplicate elements, mutabable
set1 = set()
print(set1)
set1 = set("geeksforgeeks")
print(set1)
string = 'geeksforgeeks'
set1 = set(string)
print(set1)
set1 = set(["geeks", "for", "geeks"])
print(set1)
set1 = set(['1', '2', '3', '4'])
print(set1)
set1 = set([1, 2, 'geeks', 'for', 3, 3])
# add() method is use for for addign element to the set
set1 = set()
set1.add(8)
set1.add(7)
set1.add(9)
set1.add((5, 8))
for i in range(1, 6):
set1.add(i)
print(set1)
# to add morethan one elemnet update() method is useful
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
# for accessing the element in set
for i in set1:
print(i, end=" ")
# check for element is present or not in set
print("Geeks" in set1)
# remove() and discard() method use for removing element of set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
set1.remove(5)
set1.remove(6)
print(set1)
set1.discard(2)
set1.discard(3)
print(set1)
# clear() is used for removing all the elements from the set
set1.clear()
print(set1)
# pop() methos is use for removing element its remove last element and return the last element
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Intial Set: ")
print(set1)
# Removing element from the
# Set using the pop() method
set1.pop()
print("\nSet after popping an element: ")
print(set1)
| true |
2f4b40b0b435a50c8a59dbb0d3d3eb93cb772e86 | hina-murdhani/python-project | /pythonProject3/demo/array.py | 1,710 | 4.3125 | 4 | import array as arr
# by importing array module we can generate the array
a = arr.array('i', [1, 2, 3])
for i in range(0, 3):
print(a[i])
a = arr.array('d', [1.3, 4.5, 6.7])
for i in range(0, 3):
print(a[i])
# can add element in array using insert():- at any index ,method and append() method : at the end of array
a = arr.array('i', [1, 3, 4])
a.insert(1, 4)
for i in range(0, len(a)):
print(a[i])
a.append(5)
for i in range(0, len(a)):
print(a[i])
# can access element using the index for array
a = arr.array('i', [1, 2, 3, 4, 5, 6])
# accessing element of array
print("Access element is: ", a[0])
# accessing element of array
print("Access element is: ", a[3])
# remove() use to remove particular element , pop() return thee removed element , can remove element at particular index
a = arr.array('i', [1, 2, 3, 1, 5])
a.pop(2)
for i in range(0, len(a)):
print(a[i])
a.remove(1)
for i in range(0, len(a)):
print(a[i])
# array slicing
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l1)
slice_arr = a[3:8]
print(slice_arr)
slice_arr = a[5:]
print(slice_arr)
slice_arr = a[:]
print(slice_arr)
# searching the element in array using index() method
a = arr.array('i', [1, 2, 3, 1, 2, 5])
print(a.index(2))
print(a.index(1))
# for updating the element in array we need to just reassign the value to that index
a = arr.array('i', [1, 2, 3, 1, 2, 5])
# printing original array
print("Array before updation : ", end="")
for i in range(0, 6):
print(a[i], end=" ")
print("\r")
# updating a element in a array
a[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(a[i], end=" ")
print()
for i in reversed(range(1, 10, 3)):
print(i)
| true |
9dcd641e1b18997ab78e66fdde81c400eecfce7f | DahlitzFlorian/python-training-beginners | /code/solutions/solution_04.py | 263 | 4.40625 | 4 | # This is a possible solution for exercise_04.py
word = input("Enter a word (possible palindrom): ")
reversed_word = word[::-1]
if word == reversed_word:
print("Your submitted word is a palindrom.")
else:
print("Your submitted word is not a palindrom.")
| true |
1a020f32b2a6b3a72571371ca42c2534f816c579 | mr-parikshith/Python | /S05Q02_MaxMinNumber.py | 1,366 | 4.1875 | 4 | """
S05Q02
- Ask the user to enter a number till he enters 0.
Print the maximum and minimum values among all entered numbers.
Print the number of single, two and three digit numbers entered.
"""
def print_CurrentMaxMin(Max, Min):
print("Current Maximum Number is ", Max)
print("Current Minimum Number is ", Min)
def print_FinalMaxMin(Max, Min):
print("Final Maximum Number is ", Max)
print("Final Minimum Number is ", Min)
def EnterNumber():
Number = input("Enter a Number : ")
Number = int(Number)
MaximumNumber = Number
MinimumNumber = Number
print_CurrentMaxMin(MaximumNumber, MinimumNumber)
while Number != 0:
Number = input("Enter a Number : ")
Number = int(Number)
if Number == 0:
print_FinalMaxMin(MaximumNumber, MinimumNumber)
break
elif Number >= MaximumNumber :
MaximumNumber = Number
print_CurrentMaxMin(MaximumNumber, MinimumNumber)
elif Number <= MinimumNumber:
MinimumNumber = Number
print_CurrentMaxMin(MaximumNumber, MinimumNumber)
else :
print_CurrentMaxMin(MaximumNumber, MinimumNumber)
else:
print_FinalMaxMin(MaximumNumber, MinimumNumber)
# Main starts here
EnterNumber()
| true |
1163df1cb6c0cad5800a2f74913a90e5d9bbc9d4 | mr-parikshith/Python | /S08Q03_NumberAsString.py | 610 | 4.1875 | 4 | """
S08Q03
Ask the user to enter a number.
- If the user enters a number as 5, then
generate the following string :
- 00001111222233334444
- If the user enters the number as 3, then
generate the following string :
- 001122
"""
def enterNumber():
Number = int(input("Enter Number : "))
while Number != 3 or Number != 5:
Number = int(input("Enter Number : "))
#continue
if Number == 5:
print("00001111222233334444")
break
elif Number == 3:
print("001122")
break
#Enter main here
enterNumber()
| true |
4c11ef1533db7dc7f2dfebe2239878e69d9ec9c4 | mattlorme/python | /coursera/list_8.4.py | 823 | 4.34375 | 4 | #!/usr/bin/python2.7
# 8.4 Open the file romeo.txt and read it line by line.
# For each line, split the line into a list of words
# using the split() function.
# The program should build a list of words.
# For each word on each line
# check to see if the word is already in the list
# and if not append it to the list.
# When the program completes, sort and print the resulting
# words in alphabetical order.
fname = raw_input("Enter file name: ")
#if nothing is provided for fname use path /root....../mbox-t..
if len(fname) == 0:
fname = '/root/Documents/Python/coursera/data/romeo.txt'
fh = open(fname)
lst = list()
for line in fh:
line = line.strip()
alst = line.split()
for word in alst:
if word in lst:
continue
else:
lst.append(word)
lst.sort()
print lst
| true |
21164843eccf32ab55d740847f8990ec306255de | OmniaSalah/CompilerProject | /regex.py | 652 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 23:00:55 2021
@author: LENOVO
"""
import rstr
import re
# ask the user to input the regular expression
regex=input("Enter regex :\n")
# print examples for strings that accepted
print("Examples for regex :\n",rstr.xeger(regex))
# ask the user to input if he want to check some string acceptance
check=input("Do you want to check specific string acceptance :Enter Y :\n")
# check if the string accepted or not
if check =='y' or check=='Y':
string=input("Enter string :\n")
if re.fullmatch(regex,string):
print("accepted")
else:
print ("not accepted") | true |
ac937e2d1d61950723beddbbd3ed6f4f2d5466db | rohegde7/competitive_programming_codes | /Interview-TestPress-Reverse_of_number.py | 839 | 4.1875 | 4 | '''
Given a number N, print reverse of number N.
Note: Do not print leading zeros in output.
For example N = 100 Reverse of N will be 1 not 001.
Input: Input contains a single integer N. Output: Print reverse of integer N.
Constraints: 1<=N<=10000
'''
number = input() #storing the numeber in string format to iterate through it
len_number = len(number)
reverse_number = ""
flag = 1 #this will be used for avoiding leading zeros, 1 signifies that the 1st non-zero digit is not yet found
for i in range(len_number-1, -1, -1): #iterate the string in reverse order
if flag == 1 and int(number[i]) == 0: #check for leading zero
continue
flag = 0 #confirms that we found 1st non-zero digit, now zeros are allowed
reverse_number = reverse_number + number[i]
print(reverse_number) | true |
79cba5c7d8c031964a6648c34191448a774f373a | shenoyrahul444/CS-Fundamentals | /Trees/Flatten Binary Trees.py | 1,033 | 4.25 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root:
nodes = []
self.preorder(root, nodes)
for i in range(len(nodes) - 1):
nodes[i].left = None
nodes[i].right = nodes[i + 1]
nodes[-1].left = nodes[-1].right = None
def preorder(self, root, nodes):
if root:
nodes.append(root)
self.preorder(root.left, nodes)
self.preorder(root.right, nodes)
| true |
13a9a16ed598e6b2f79f666ad34ae0012064e9dd | ashwin-5g/LPTHW | /ex3.py | 704 | 4.375 | 4 | #prompt for chicken count
print "I will now count my chickens:"
#display hens' count
print "Hens", 25 + 30 / 6
#display roosters' count
print "Roosters", 100 - 25 * 3
% 4
#display eggs' count
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
#comparison operation in use
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
#addition
print "What is 3 + 2?", 3 + 2
#subtraction
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
#greater than function
print "Is it greater?", 5 > -2
#greater than or equal function
print "Is it greater or equal?", 5 >= -2
#less than or equal function
print "Is it less or equal?", 5 <= -2
| true |
90012c431612c0221318d69ee94b8bed263a9736 | Garvit-32/Opencv_code | /15_adaptive_thresholding.py | 775 | 4.125 | 4 | import cv2 as cv
import numpy as np
# Adaptive Thresholding algorithm provide the image in which Threshold values vary over the image as a function of local image characteristics. So Adaptive Thresholding involves two following steps
# (i) Divide image into strips
# (ii) Apply global threshold method to each strip.
img = cv.imread('sudoku.png',0)
_, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2);
th3 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2);
cv.imshow("Image", img)
cv.imshow("THRESH_BINARY", th1)
cv.imshow("ADAPTIVE_THRESH_MEAN_C", th2)
cv.imshow("ADAPTIVE_THRESH_GAUSSIAN_C", th3)
cv.waitKey(0)
cv.destroyAllWindows() | true |
a8dbc4ead47024aaae3146f4860fd8930a4f21b4 | cromptonhouse/examplesPi | /hiworld.py | 750 | 4.53125 | 5 | # This is a comment! If we type a # we can type what we want and the computer ignores it!
print "hello world" # prints words, know in code as a string - "Hello World"
# We are going to learn about variables"
# A variable is somewhere (memory) where we can store information"
x = 6 # we have assigned the variable x with the number 6
print x # this line prints 6 - as x is 6
x = "Still six" # we have now assigned x with a string, a set of words - "still six"
print x # now it prints still 6
####--------- PRACTICE 1 ---------------####
#Edit the code below to print your name below
# print "My name is ...."
# x = #put your name in this variable
# print x # it`ll print your name
| true |
53d6443c954e116282e4048a560cc1e0650a9df7 | dannydiaz92/MIT_IntroToCS | /Pset2/ps2_hangman.py | 2,974 | 4.375 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
#Python 2 format
#inFile = open(WORDLIST_FILENAME, 'r', 0)
#Python 3
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
## wordlist = string.split(line) #(python 2 format)
#Python 3
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program
wordlist = load_words()
# your code begins here!
#Computer selects random word
word = choose_word(wordlist)
print("the secret word is: ", word)
#Initalize the number of guesses (tries)
guesses = 8
#List of available letters
avail_letters = list(string.ascii_lowercase)
#Pattern '_ _ _ _'
pattern = '_ '*len(word)
#Set of letters in word
word_letters = set(word)
print("Welcome to the game of Hangman!")
print("I am thinking of a word that is : ", len(word), " letters long")
print("--------------------")
# While have not
# 1) exhausted guesses and
# 2) Have not completed word
while (guesses > 0) and (len(word_letters) != 0):
print("You have ", guesses, " guesses left.")
print("Available letters: ", ''.join(avail_letters))
user_input = input("Please guess a letter: ").lower()
if (user_input in word) and (user_input in avail_letters):
del avail_letters[avail_letters.index(user_input)]
word_letters.remove(user_input)
char_index = [index for index, char in enumerate(word) if char == user_input]
print('index in word where letter is found: ', char_index)
#Trying doing this with a list comprehension
for letter_index in char_index:
pattern = pattern[:letter_index*2] + user_input + pattern[letter_index*2 + 1:]
print("Good guess: ", pattern)
print('-----------')
elif user_input not in avail_letters:
print("Already used that word. Please choose a word in available letters.")
else:
print("Oops! That letter is not in my word: ", pattern)
del avail_letters[avail_letters.index(user_input)]
print('-----------')
guesses -= 1
if len(word_letters) == 0:
print("Congrats, you won!")
| true |
801f87165fd8036da1aece5348751af8a68dd685 | Frootloop11/lectures | /week 10/warm_up.py | 576 | 4.28125 | 4 | """
Take in a file
Find and return the longest line in that file
print the line number and length character
"""
def main():
line_number, length = find_longest_line("warm_up.py")
print(line_number, length)
def find_longest_line(file_name):
max_line_number, max_length = -1, 0
with open(file_name, 'r') as in_file:
for i, line in enumerate(in_file, 1): # enumerate starts the file at 1
if len(line) > max_length:
max_length = len(line)
max_line_number = i
return max_line_number, max_length
main()
| true |
06e6492146dc1e08ca2aa72428d72cb2c59431be | nick-lehmann/SnakeCharmerGuide | /games/ninjas.py | 744 | 4.21875 | 4 | """
The wall has been breached and cobras are attacking the castle 🏰
We see that there are 50 cobras approaching 🐍
Fortunately we have special ninjas that can defeat the cobras 🥷
Every ninja can defeat 3 cobras.
Can we defeat all the cobras with the ninjas we have?
1. Define a variable "ninjas" and one "cobras" and print if we win or loose based on the variables
Bonus Points: Say how many more ninjas do we need to win the fight!
"""
cobras = 50
ninjas = 20
if ninjas * 3 < cobras:
print('The cobras won 🐍')
# Bonus
remaining_cobras = cobras - ninjas * 3
more_ninjas_needed = remaining_cobras / 3
print(f'We need {more_ninjas_needed} more ninjas to win the fight')
else:
print('The ninjas won 🥷')
| true |
78ec49439d956378c5f414bf673cc92f3c3bccda | nick-lehmann/SnakeCharmerGuide | /games/pizza.py | 687 | 4.28125 | 4 | """
Mario is eating a pizza.
The pizza is so tasty that every time he eats a slice he wants to say "Mhhhhhh".
Every time he eats a slice his hunger gets lowered by 1.
If he is full, he stops eating and says "I'm full 🤤"
When he is finished he says "Mamma mia! Buonissima! 😋"
Say if he is still hungry after eating all the slices
Start: Define two variables, "slices" and "hunger"
"""
slices = 8
hunger = 10
for slice in range(slices):
if hunger == 0:
print("I'm full 🤤")
break
hunger = hunger - 1
print(f'Mhhhh 🍕 {slice + 1}')
print('Mamma mia! Buonissima! 😋👩🍳')
if hunger > 0:
print(f'...but could eat {hunger} more slice/s 😍')
| true |
f93c3a294a435212eceb18e67c5e7c5f86a7e403 | nick-lehmann/SnakeCharmerGuide | /games/rock_paper_scissors.py | 1,841 | 4.40625 | 4 | """
You want to play rock-paper-scissors against the computer.
1. Define a dictionary for each player that stores its name and current score.
2. Ask the player about his or her name and ask how many round should be played.
3. Each round, ask the player for his or her choice. The computer should pick a random choice.
4. Evaluate each round and print who has won.
Bonus Points: Accept different spelling of each choice ('rock', 'Rock', 'rOcK') and maybe even abbreviations.
"""
from random import choice
options = ['rock', 'paper', 'scissor']
user_name = input('What is your name?: ')
number_of_rounds = int(input('How many rounds do you want to play?: '))
user_score = 0
computer_score = 0
for index in range(1, number_of_rounds + 1):
print('==========')
print(f'Round {index}')
user_choice = None
while not user_choice:
raw = input('What is your choice?: ')
if not raw.lower() in options:
print('Invalid choice')
else:
user_choice = raw.lower()
computer_choice = choice(options)
print(f'The computer has chosen {computer_choice}')
if user_choice == computer_choice:
print('Draw! Nobody wins..')
continue
# User option is always the first element
options_where_user_wins = [
['rock', 'scissor'],
['scissor', 'paper'],
['paper', 'rock']
]
if [user_choice, computer_choice] in options_where_user_wins:
user_score += 1
print(f'{user_name} has won!')
else:
print(f'The computer has won!')
computer_score += 1
print('----------------------')
print(f'User: {user_score} -- Computer: {computer_score}')
if user_score > computer_score:
print(f'{user_name} has won')
elif user_score < computer_score:
print('Computer has won')
else:
print('It was a draw')
| true |
88d46bf4694d95c6f9e62726f88cc21871ccbea6 | Greensahil/CS697 | /Playground/listAndTuples.py | 2,067 | 4.4375 | 4 | #sequence an object that contains multiple items of data
#list is mutable can be changed in place in memory
#tuple cannot be modified unless you are reassigining to a different place in memory
list = [1,2]
print(list)
#list is similar to array list in java
#list is dynamic and we can change the size
#list can be herttogenous
list = [1,2, 'some string', 1.34343]
print(list)
for item in range(len(list)):
print(list[item])
print(len(list))
list2 = ['asdas','asdas']
print(list + list2)
print(list.extend(list2)) #same thing
l1 = [1,2]
print(l1*5) #[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
for item in list:
print(item)
print(list[-1]) #last element in the list
#since list are mutable
list[1] = 5
#list slicing
#start index is inclusive and lst idex is not. Last one is step if -ve it starts from the right
l1[1:] #print everything from start to end of the list
print(l1[0:5:2])
#check to see if a list contains something
print(0 in l1)
#add to the end of the list
l1.append(9)
print(l1.index(9))
#insert at any point in the list
l1.insert(1,4)
l1.sort()
#Remove by value and not index
l1.remove(4)
#By index and it also returns the value that was removeed
print(l1.pop(1))
print(l1)
#list are mutable so to copy youcannot do
#l2 = l1
#method 1
#l2 =[]
#l2 = l2 + l1
#method 2
#l2=l1[::]
#method 3
#you can create a loop to copy each element
#to copy list from l1.extend() l1.append() will not work
#to square each item and create in a different
# newList = [len(item) for item in list1]
# newList = [item for item in list1 if item < 10 ]
#l2 = [item for item in range(1001) if 3 in str(item)]
#l2 = [item for item in years if year % 4 ==0 and year % 100! = 0]
print("Random numbers")
import random
#Both starts and stop are both inclusive
print(random.randint(0,100))
#More customixation with step. All even numbers
print(random.randint(0,100))
for i in range(10):
print(random.randint(0,10))
rlist = [random.randint(0,10) for i in range(10)]
slist = random.sample(range(0,100),10) #unique number
print(rlist)
| true |
8401ef69843234d30758eecc923f15296cc9b1a3 | Greensahil/CS697 | /Playground/passwordchecker.py | 757 | 4.3125 | 4 | password = input("Enter a string for password:")
validPassword = True
#A password must have at least eight characters.
if len(password) < 8:
validPassword = False
#A password consists of only letters and digits
if not password.isalnum():
validPassword = False
#A password must contain at least two digits
#A password must contain at least one uppercase character
digitCounter = 0
upperCaseCounter = 0
for index in range(len(password)):
if(password[index].isnumeric()):
digitCounter += 1
if(password[index].isupper()):
upperCaseCounter += 1
if digitCounter < 2:
validPassword = False
if upperCaseCounter < 1:
validPassword = False
if validPassword:
print("valid password")
else:
print("invalid password") | true |
5a9cae303fbc660ac7566063f5593a78c263dabf | half-rice/daily_programmer | /easy_challenge_1.py | 699 | 4.21875 | 4 | # create a program that will ask the users name, age, and username. have it
# tell them the information back, in the format:
# your name is (blank), you are (blank) years old, and your username is (blank)
# for extra credit, have the program log this information in a file to be
# accessed later.
file = open("easy_challenge_1_save.txt", "w")
name = raw_input("enter your name: ")
age = raw_input("enter your age: ")
username = raw_input("enter your username: ")
print("\nwriting data to file...")
file.write(name+"\n")
file.write(age+"\n")
file.write(username+"\n")
print("completed\n\n")
print("your name is "+name+", you are "+age+" years old, and your username is "+username)
file.close() | true |
870430a89fb57bdadf8863b9ee8a43ccd3bff287 | NhatNam-Kyoto/Python-learning | /100 Ex practice/ex8.py | 375 | 4.125 | 4 | '''Write a program that accepts a comma separated sequence of words
as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
'''
inp = input('Nhap chuoi: ')
l = inp.split(',')
l.sort()
print(','.join(l)) | true |
a93dd6d0d3929fb5e0004fc9f86ae9703c0a7a60 | Lifefang/python-labs | /CFU07.py | 1,880 | 4.25 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: Matthew Rodriguez
# Section: 537
# Assignment: CFU-#9
# Date: 10/23/2019
# this program is going to allow the user to enter in values for height in both feet and inches
# it will do this until the user enters in 0 0
# the program is then going to return theses values in centimeters
user_input = input('Please input the height in the form feet followed by inches separated by row_3 single space:').split()
# making the strings row_3 points_to_evaluate
cm_list = [] # making row_3 empty points_to_evaluate that will be the final output
while user_input[0] and user_input[1] != 0: # making row_3 loop to check the user input every time
if user_input[0] and user_input[1] == 0: # if the value of 0 0 is entered the program should stop
break # breaking out of the program so no more inputs can be placed, the break will print the final points_to_evaluate of cms
print('you have inputted the height of', user_input[0], 'feet', user_input[1], 'inches')
inch_conversion = float(user_input[0]) * 12 + float(user_input[1]) # feet times 12 + how ever many inches gets
# total inches
cm_conversion = inch_conversion * 2.54 # the conversion for inches to cm
print('The entered height of', user_input[0], 'feet', user_input[1], 'inches is:', cm_conversion, 'cm.') # output
user_input = input(
'Please input another height in the form feet followed by inches:').split() # getting another input for the
# points_to_evaluate
cm_list.append(float(cm_conversion)) # making the points_to_evaluate append to the final out put
print(cm_list) # this is the points_to_evaluate of heights converted to cms
| true |
0311d830fd6398fc5056583cfe1ac83e2b1ea5bf | Lifefang/python-labs | /Lab3_Act1_e.py | 1,031 | 4.25 | 4 | # By submitting this assignment, all team members agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Names: Isaac Chang
# Matthew Rodriguez
# James Phillips
# Ryan Walterbach
# Section: 537
# Assignment: Lab 3, Act 1
# Date: 9/10/2019
# This program converts number of Miles per Hour to Meters per Second
print("This program converts number of miles per hour to number of meters per second")
Miles_Per_Hour_Input = float(input("Please enter the number of miles per hour to be converted to meters per second:"))
Meters_Per_Second_Output = (Miles_Per_Hour_Input * 0.44704) # 1 mile per hour is equivalent to 0.44704 meters per
# second
print(str(Miles_Per_Hour_Input)+" Milers per hour is equivalent to",str(Meters_Per_Second_Output) + "Meters per "
"second.")
| true |
0e1b7ba647bf813dc211973b5a06720dc2c77eb2 | Lifefang/python-labs | /Lab3_Act1_a.py | 894 | 4.125 | 4 | # By submitting this assignment, all team members agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Names: Isaac Chang
# Matthew Rodriguez
# James Phillips
# Ryan Walterbach
# Section: 537
# Assignment: Lab 3, Act 1
# Date: 9/10/2019
# This program converts number of pounds to number of Newtons
print("This program converts number of pounds to number of Newtons")
pounds_input = float(input("Please enter the number of pounds to be converted to Newtons:"))
# # float must be added because trying to multiply row_3 string by row_3 non-float int cant be complied.
Newtons_output = (pounds_input * 4.4482216) # 1 pound is 4.4482216 Newtons
print(str(pounds_input)+" Pounds is equivalent to",str(Newtons_output)+"Newtons.")
| true |
41c89e83236a971c90349a0cef1c89753a191993 | lcgarcia05/370-Group5Project | /name/backend_classes/temporary_storage.py | 1,293 | 4.15625 | 4 |
from name.backend_classes.playlist import Playlist
class TemporaryStorage:
""" A class which will handle the temporary storage of a created
playlist and store the list of songs in a text file.
"""
def __init__(self, temp_playlist):
""" Initializes the temp_playlist class and converts playlist
to a string.
temp_playlist: A playlist object
"""
self.temp_playlist = temp_playlist
self.my_string = self.convert_to_string()
def convert_to_string(self):
"""Retrieves the necessary data from the playlist object
and converts it to a string for display in a file.
"""
song_names = [i.song_name for i in self.temp_playlist.songs]
to_print = "Playlist name: " + self.temp_playlist.playlist_name + "\n"
to_print = to_print + "Songs: " + "\n"
for song_name in song_names:
to_print = to_print + " " + song_name + "\n"
return to_print
def save_to_file(self):
"""Saves the current playlist to a .txt file with the same
name as the playlist.
"""
file_name = self.temp_playlist.playlist_name
f = open(file_name + ".txt", "w")
f.write(self.my_string)
f.close() | true |
6a350be7b75cc55510365c0992478dea32fabef0 | apatten001/strings_vars_ints_floats | /strings.py | 786 | 4.3125 | 4 |
print('Exercise is a good thing that everyone can benefit from.')
var1 = "This is turning a string into a variable"
print(var1)
# now i'm going to add two strings together
print("I know im going to enjoy coding " + ","+ " especially once I've put the time in to learn.")
# now lets print to add 2 blank lines in between strings
print('\n' * 2)
var2 = "This is the string after the blank lines"
print(var2)
# here I am going to format with the strings
print('\n')
print("{} is a great {} to learn for my {} coding experience".format("Python","language", "first"))
# now lets use % to add characters strings intergers and floats
print("My favorite letter is %c. I love to %s. I'm going to the bahamas in %i months. My college gpa was %.2f"
%('A','read', 3, 3.61))
| true |
d2ad7cfbd2bb9c727dc6e60d38da40a323b3105d | CaseyNord-inc/treehouse | /Write Better Python/docstrings.py | 457 | 4.3125 | 4 | # From Docstrings video in Writing Better Python course.
def does_something(arg):
"""Takes one argument and does something based on type.
If arg is a string, returns arg * 3;
If arg is an int or float, returns arg + 10
"""
if isinstance(arg, (int, float)):
return arg + 10
elif isinstance(arg, str):
return str * 3
else:
raise TypeError("does_something only takes int, floats, and strings")
| true |
c9b4ec541b0b9ab0f390b6792fe553789c2c3302 | Rrawla2/cs-guided-project-python-i | /src/demonstration_1.py | 1,696 | 4.375 | 4 | """
Define a function that transforms a given string into a new string where the original
string was split into strings of a specified size.
For example:
If the input string was this:
"supercalifragilisticexpialidocious"
and the specified size was 3, then the return string would be:
"sup erc ali fra gil ist ice xpi ali doc iou s"
The assumptions we are making about our input are the following:
- The input string's length is always greater than 0.
- The string has no spaces.
- The specified size is always a positive integer.
"""
def split_in_parts(s, part_length):
# we need to split the input string into smaller chucks of whatever
# the specified size is
# initialize an output array to hold the split letters
# initialize a an empty substring to hold counted letters
output = []
s_substring = ""
# iterate over characters in the input string
for letter in s:
# add letter to the substring until it's equal to the part_length
if len(s_substring) < part_length:
s_substring += letter
# when substring is equal to part_length, append to output and reset
# substring to empty string to start over
if len(s_substring) == part_length:
output.append(s_substring)
s_substring = ""
# if any letters are left over, add them at the end.
if s_substring != "":
output.append(s_substring)
# make the array into a string
result = " ".join(output)
# return output array
return result
print(split_in_parts("supercalifragilisticexpialidocious", 3))
print(split_in_parts("supercalifragilisticexpialidocious", 5))
print(split_in_parts("oscargribble", 5)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.