blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
35131f3bff52c30cf0ca3f99445ec08a53f020f6 | anatulea/codesignal_challenges | /Intro_CodeSignal/07_Through the Fog.py/31_depositProfit.py | 953 | 4.25 | 4 | '''
You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold.
Example
For deposit = 100, rate = 20, and threshold = 170, the output should be
depositProfit(deposit, rate, threshold) = 3.
Each year the amount of money in your account increases by 20%. So throughout the years, your balance would be:
year 0: 100;
year 1: 120;
year 2: 144;
year 3: 172.8.
Thus, it will take 3 years for your balance to pass the threshold, so the answer is 3.
'''
def depositProfit(deposit, rate, threshold):
count = 0
while deposit< threshold:
deposit = deposit + (deposit*rate)/100
count+=1
return count
import math
def depositProfit2(deposit, rate, threshold):
return math.ceil(math.log(threshold/deposit, 1+rate/100)) | true |
40da9655f1ceb1450d203efa31a6bfc9a3748220 | anatulea/codesignal_challenges | /Intro_CodeSignal/01_The Jurney Begins/02_centuryFromYear.py | 1,220 | 4.1875 | 4 | '''
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
centuryFromYear(year) = 17.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer year
A positive integer, designating the year.
Guaranteed constraints:
1 ≤ year ≤ 2005.
[output] integer
The number of the century the year is in.
'''
def centuryFromYear(year):
return (year + 99) // 100
# return (year-1)//100+1
# return int((year - 1) / 100) + 1
'''The Math.ceil() function always rounds a number up to the next largest integer.'''
# return math.ceil(year/100)
# if year % 100 == 0:
# return(int(year/100))
# else:
# return(int(year/100 + 1))
# my solution
def centuryFromYear2(year):
if 1>= year or year<= 100:
return 1
if year>= 2005:
return 21
# x = int(str(year)[:2])
if int(str(year)[2:]) == 00 or int(str(year)[2:]) == 0:
return int(str(year)[:-2])
else:
return int(str(year)[:-2])+1 | true |
67801342d06b60b610ee909bf60712796894cbad | anatulea/codesignal_challenges | /Python/11_Higher Order Thinking/73_tryFunctions.py | 1,391 | 4.40625 | 4 | '''
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extremely difficult to comprehend.
To understand what function is applied to x instead of the one that should have been applied, you decided to go ahead and compare the result with results of all the functions you could come up with. Given the variable x and a list of functions, return a list of values f(x) for each x in functions.
Example
For x = 1 and
functions = ["math.sin", "math.cos", "lambda x: x * 2", "lambda x: x ** 2"],
the output should be
tryFunctions(x, functions) = [0.84147, 0.5403, 2, 1].
'''
def tryFunctions(x, functions):
return [eval(f)(x) for f in functions]
# return [fun(x) for fun in map(eval,functions)]
'''eval(expression, globals=None, locals=None)
-expression - the string parsed and evaluated as a Python expression
-globals (optional) - a dictionary
-locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.
-The eval() method parses the expression passed to this method and runs python expression (code) within the program
''' | true |
7d95aafc8e3b783c05196c5ba11e448578bf5a9e | anatulea/codesignal_challenges | /Python/08_Itertools Kit/48_cyclicName.py | 1,147 | 4.71875 | 5 | '''
You've come up with a really cool name for your future startup company, and already have an idea about its logo. This logo will represent a circle, with the prefix of a cyclic string formed by the company name written around it.
The length n of the prefix you need to take depends on the size of the logo. You haven't yet decided on it, so you'd like to try out various options. Given the name of your company, return the prefix of the corresponding cyclic string containing n characters.
Example
For name = "nicecoder" and n = 15, the output should be
cyclicName(name, n) = "nicecoderniceco".
'''
from itertools import cycle
# Itertools is a module that provides various functions that work on iterators to produce complex iterators.
def cyclicName(name, n):
gen = cycle(name) # defining iterator
res = [next(gen) for _ in range(n)] # Using next function to take the first n char
return ''.join(res)
''' Infinite iterators
- count(start, step): This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default.
'''
| true |
ae12622ea7ab0959a7e0896b504f683487cac457 | anatulea/codesignal_challenges | /isIPv4Address.py | 1,229 | 4.125 | 4 | '''
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
Given a string, find out if it satisfies the IPv4 address naming rules.
Example
For inputString = "172.16.254.1", the output should be
isIPv4Address(inputString) = true;
For inputString = "172.316.254.1", the output should be
isIPv4Address(inputString) = false.
316 is not in range [0, 255].
For inputString = ".254.255.0", the output should be
isIPv4Address(inputString) = false.
There is no first number.'''
def isIPv4Address(inputString):
nums = inputString.split('.')
print(nums)
if len(nums) != 4:
return False
if '' in nums:
return False
for i in nums:
try:
n= int(i)
except ValueError:
return False
if len(i)>1 and int(i[0]) == 0:
return False
if int(i) > 255:
return False
return True
string = "0.254.255.0"
inputString= "0..1.0"
print(isIPv4Address(string))
print(isIPv4Address(inputString)) | true |
79efe0f71e3216d25af3d67500a29423af62a35f | anatulea/codesignal_challenges | /Intro_CodeSignal/03_Smooth Sailing/13_reverseInParentheses.py | 1,577 | 4.21875 | 4 | '''
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
Example
For inputString = "(bar)", the output should be
reverseInParentheses(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
reverseInParentheses(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be
reverseInParentheses(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be
reverseInParentheses(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".
'''
def reverseInParentheses(s):
stack = []
for x in s:
if x == ")":
tmp = ""
while stack[-1] != "(":
tmp += stack.pop()
stack.pop() # pop the (
for item in tmp:
stack.append(item)
else:
stack.append(x)
return "".join(stack)
def reverseInParentheses2(s):
return eval('"' + s.replace('(', '"+("').replace(')', '")[::-1]+"') + '"')
def reverseInParentheses3(s):
for i in range(len(s)):
if s[i] == "(":
start = i
if s[i] == ")":
end = i
return reverseInParentheses3(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s
def reverseInParentheses4(s):
end = s.find(")")
start = s.rfind("(",0,end)
if end == -1:
return s
return reverseInParentheses4(s[:start] + s[start+1:end][::-1] + s[end+1:])
| true |
0f30ab84f246ce8c842d54dd760106bcb464304e | anatulea/codesignal_challenges | /Python/02_SlitheringinStrings/19_newStyleFormatting.py | 1,234 | 4.125 | 4 | '''
Implement a function that will turn the old-style string formating s into a new one so that the following two strings have the same meaning:
s % (*args)
s.format(*args)
Example
For s = "We expect the %f%% growth this week", the output should be
newStyleFormatting(s) = "We expect the {}% growth this week".
'''
def newStyleFormatting(s):
s = s.split('%%')
print(s)# s = ["We expect the %f", "growth this week"]
for i in range(len(s)):
while '%' in s[i]:
idx = s[i].find('%') # find the % index
# modify string "We expect the " + {} + the rest of string
s[i] = s[i][:idx] + '{}' + s[i][idx + 2:]
return '%'.join(s)
import re
def newStyleFormatting2(s):
return re.sub('%\w','{}', s.replace('%%','{%}')).replace('{%}','%')
def newStyleFormatting3(s):
s = re.sub('%%', '{%}', s)
# re.sub(pattern we look for, replacement, string, count=0, flags=0)
s = re.sub('%[dfFgeEGnnxXodcbs]', '{}', s)
return re.sub('{%}','%',s)
import re
def newStyleFormatting4(s):
return "%".join([re.sub("%([bcdeEfFgGnosxX])","{}",S) for S in s.split("%%")])
def newStyleFormatting5(s):
return '%'.join(re.sub('%\w', '{}', part) for part in s.split('%%')) | true |
d4d9a9ae96ebf4a33a9758802b9acdfeb555ccdc | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Exercises/12. recursion_palindrome.py | 401 | 4.25 | 4 | def palindrome(word, index=0, reversed_word=""):
if index == len(word):
if not reversed_word == word:
return f"{word} is not a palindrome"
return f"{word} is a palindrome"
else:
reversed_word += word[-(index + 1)]
return palindrome(word, index + 1, reversed_word)
print(palindrome("abcba"))
print(palindrome("peter"))
print(palindrome("ByyB")) | true |
3a7baad4cf891fe0d8bb6a7b5fa11ce938cbfda8 | om-100/assignment2 | /11.py | 519 | 4.6875 | 5 | """Create a variable, filename. Assuming that it has a three-letter
extension, and using slice operations, find the extension. For
README.txt, the extension should be txt. Write code using slice
operations that will give the name without the extension. Does your
code work on filenames of arbitrary length?"""
def filename(name):
extension = name[-3:]
filename = name[:-3]
print(filename, extension, sep=" is filename and extension is ")
name = input("Enter a filename with extension: ")
filename(name) | true |
13d759a3accaba9725d3b70f6a261fe9d9eca1a9 | owaisali8/Python-Bootcamp-DSC-DSU | /week_1/2.py | 924 | 4.125 | 4 | def average(x):
return sum(x)/len(x)
user_records = int(input("How many student records do you want to save: "))
student_list = {}
student_marks = []
for i in range(user_records):
roll_number = input("Enter roll number:")
name = input("Enter name: ")
age = input("Enter age: ")
marks = int(input("Enter marks: "))
while marks < 0 or marks > 100:
print("Marks range should be between 0 and 100")
marks = int(input("Enter correct marks: "))
student_marks.append(marks)
student_list[roll_number] = [name, age, marks]
print('\n')
print("{:<15} {:<15} {:<15} {:<15}".format(
'Roll Number', 'Name', 'Age', 'Marks'))
print()
for k, v in student_list.items():
name, age, marks = v
print("{:<15} {:<15} {:<15} {:<15}".format(k, name, age, marks))
print("\nAverage: ", average(student_marks))
print("Highest: ", max(student_marks))
print("Lowest: ", min(student_marks))
| true |
f7ccdb31cc184e3603f2f465c1d68f5c694ef9d7 | Ollisteka/Chipher_Breaker | /logic/encryptor.py | 2,968 | 4.3125 | 4 | #!/usr/bin/env python3
# coding=utf-8
import json
import sys
import tempfile
from copy import copy
from random import shuffle
def read_json_file(filename, encoding):
"""
Read data, written in a json format from a file, and return it
:param encoding:
:param filename:
:return:
"""
with open(filename, "r", encoding=encoding) as file:
return json.loads(file.read())
def generate_alphabet_list(start, end):
"""
Function makes a list, containing all the letters from start
to end included.
:type end: str
:type start: str
:return:
"""
return [x for x in map(chr, range(ord(start), ord(end) + 1))]
def make_alphabet(string):
"""
Function makes a list, containing all the letters from the range.
:param string: A-Za-z or А-Яа-яЁё
:return:
"""
letter_range = "".join(
x for x in string if x.islower() or x == '-').strip('-')
if len(letter_range) == 3:
return generate_alphabet_list(letter_range[0], letter_range[2])
defis = letter_range.find('-')
alphabet = generate_alphabet_list(
letter_range[defis - 1], letter_range[defis + 1])
for letter in letter_range:
if letter_range.find(letter) not in range(defis - 1, defis + 2):
alphabet.append(letter)
return alphabet
def generate_substitution(string):
"""
Generate new substitution, based on the given letter's range.
:param string: A-Za-z or А-Яа-яЁё
:return:
"""
alphabet = make_alphabet(string)
shuffled = copy(alphabet)
shuffle(shuffled)
return dict(zip(alphabet, shuffled))
def reverse_substitution(substitution):
"""
Exchange keys with values.
:type substitution: dict
:return:
"""
return {v: k for k, v in substitution.items()}
def code_text_from_file(filename, encoding, substitution):
"""
Code text from file
:param filename:
:param encoding:
:param substitution:
:return:
"""
# noinspection PyProtectedMember
if isinstance(filename, tempfile._TemporaryFileWrapper):
with filename as f:
f.seek(0)
text = f.read().decode(encoding)
return code(text, substitution)
with open(filename, 'r', encoding=encoding) as file:
return code(file.read(), substitution)
def code_stdin(substitution):
"""
Code text from stdin
:param substitution:
:return:
"""
return code(str.join("", sys.stdin), substitution)
def code(text, substitution):
"""
The function encrypts the text, assigning each letter
a new one from the substitution
:type text: str or Text.IOWrapper[str]
:type substitution: dict
:return:
"""
upper_letters = dict(zip([x.upper() for x in substitution.keys()],
[x.upper() for x in substitution.values()]))
_tab = str.maketrans(dict(substitution, **upper_letters))
return text.translate(_tab)
| true |
f84cf15c04be752423408f06737cc5100c7f0cf4 | af94080/bitesofpy | /9/palindrome.py | 1,406 | 4.3125 | 4 | """A palindrome is a word, phrase, number, or other sequence of characters
which reads the same backward as forward"""
import os
import urllib.request
DICTIONARY = os.path.join('/tmp', 'dictionary_m_words.txt')
urllib.request.urlretrieve('http://bit.ly/2Cbj6zn', DICTIONARY)
def load_dictionary():
"""Load dictionary (sample) and return as generator (done)"""
with open(DICTIONARY) as f:
return (word.lower().strip() for word in f.readlines())
def is_palindrome(word):
"""Return if word is palindrome, 'madam' would be one.
Case insensitive, so Madam is valid too.
It should work for phrases too so strip all but alphanumeric chars.
So "No 'x' in 'Nixon'" should pass (see tests for more)"""
word = word.lower()
# remove anything other than alphanumeric
word = ''.join(filter(str.isalnum, word))
reverse_word = ''.join(reversed(word))
return word == reverse_word
def get_longest_palindrome(words=None):
"""Given a list of words return the longest palindrome
If called without argument use the load_dictionary helper
to populate the words list"""
if not words:
words = load_dictionary()
only_palins = filter(is_palindrome, words)
word_by_length = {word : len(word) for word in only_palins}
return sorted(word_by_length, key=word_by_length.get, reverse=True)[0]
| true |
2a482264dc15fc4c17fc27e08d9247351e47815a | chinmaygiri007/Machine-Learning-Repository | /Part 2 - Regression/Section 6 - Polynomial Regression/Polynomial_Regression_Demo.py | 1,317 | 4.25 | 4 | #Creating the model using Polynomial Regression and fit the data and Visualize the data.
#Check out the difference between Linear and Polynomial Regression
#Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the data
data = pd.read_csv("Position_Salaries.csv")
X = data.iloc[:,1].values.reshape(-1,1)
Y = data.iloc[:,2].values
#Since the data is too small no need to Split the data.
#Importing Linear Regression and training the model
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,Y)
#Visualizing the data(Linearly)
plt.scatter(X,Y,color="gray")
plt.plot(X,lin_reg.predict(X),color = "black")
plt.xlabel("Level")
plt.ylabel("Salary")
plt.title("Linear Regression")
plt.show()
#Implement Polynomial Features
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 5)
X_reg = poly_reg.fit_transform(X)
pol_reg = LinearRegression()
pol_reg.fit(X_reg, Y)
#Visualizing the data(Poly)
X_grid = np.arange(min(X),max(X),0.1)
X_grid = X_grid.reshape((len(X_grid),1))
plt.scatter(X,Y,color = "black")
plt.plot(X_grid,pol_reg.predict(poly_reg.fit_transform(X_grid)),color="black")
plt.show()
#Testing the Model
print(pol_reg.predict(poly_reg.fit_transform([[5.5]]).reshape(1,-1)))
| true |
96d90ae34f7e20c90adcc4637b04bdd885aa6865 | HimanshuKanojiya/Codewar-Challenges | /Disemvowel Trolls.py | 427 | 4.28125 | 4 | def disemvowel(string):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for items in vowels:
if items in string:
cur = string.replace(items,"") #it will replace the vowel with blank
string = cur #after completing the operation, it will update the current string
else:
continue #if vomel not find in string then it will continue the program
return string
| true |
7d1547f6d3d93fc3253321c5edd6509165493910 | JCarter111/Python-kata-practice | /Square_digits.py | 2,368 | 4.46875 | 4 | # Kata practice from codewars
# https://www.codewars.com/kata/546e2562b03326a88e000020/train/python
# Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
# codewars Kata for me to use in practising list comprehension type Python statements
import unittest
def square_digits(num):
# find square of every integer in num
# return these as an integer
# e.g. num = 823, return 1649
# placeholder pass
# number must be an integer
# integer number could be negative
# if number is not an integer
# raise an error
# note Boolean value for number is interpreted as 0 or 1
# but can cause code failure
# raise error if Boolean value provided
if not(isinstance(num,int)) or isinstance(num,bool):
raise TypeError("Please provide an integer number")
# num is an integer, convert to list or string
# use list of string to find every square value
squares = int("".join([str(int(x)**2) for x in str(num)]))
return squares
class squareDigits(unittest.TestCase):
# tests from kata
# test.assert_equals(square_digits(9119), 811181)
# test square is returned for one integer
def test_one_integer_square_returned(self):
self.assertEqual(square_digits(2),4)
# test larger integer returns squares
def test_integer_returns_squares(self):
self.assertEqual(square_digits(9119),811181)
# test what happens if num is larger than the maximum integer values
#def test_large_number_returns_squares(self):
# self.assertEqual(square_digits(21574864912),412549166436168114)
# error handling tests
# test that an error is raised if a non-integer number is
# provided
def test_noninteger_raises_error(self):
with self.assertRaises(TypeError):
square_digits(9.5)
with self.assertRaises(TypeError):
square_digits("hello")
with self.assertRaises(TypeError):
square_digits([6,7])
with self.assertRaises(TypeError):
square_digits(True)
#with self.assertRaises(TypeError):
# square_digits(2323232323231212312312424)
if __name__ == "__main__":
unittest.main() | true |
fc22ede62dbfff1d6ad38bc27c353d41def148fe | Talw3g/pytoolbox | /src/pytoolbox_talw3g/confirm.py | 1,356 | 4.5 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def confirm(question, default_choice='yes'):
"""
Adds available choices indicator at the end of 'question',
and returns True for 'yes' and False for 'no'.
If answer is empty, falls back to specified 'default_choice'.
PARAMETERS:
- question is mandatory, and must be convertible to str.
- default_choice is optional and can be:
| None: no preference given, user must enter yes or no
| 'yes'
| 'no'
If no valid input is found, it loops until it founds a suitable answer.
Exception handling is at the charge of the caller.
"""
valid = {'yes':True, 'y':True, 'ye':True, 'no':False, 'n':False}
default_choice = str(default_choice).lower()
if default_choice == 'none':
prompt = ' [y/n] '
elif default_choice == 'yes':
prompt = ' [Y/n] '
elif default_choice == 'no':
prompt = ' [y/N] '
else:
raise ValueError('invalid default answer: "%s"' % default_choice)
while True:
print(str(question) + prompt)
choice = input().lower()
if default_choice != 'none' and choice == '':
return valid[default_choice]
elif choice in valid:
return valid[choice]
else:
print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
| true |
e7d9e99375459e1031bf9dd0c2059421978ef31b | KartikeyParashar/Algorithm-Programs | /calendar.py | 1,434 | 4.28125 | 4 | # To the Util Class add dayOfWeek static function that takes a date as input and
# prints the day of the week that date falls on. Your program should take three
# commandline arguments: m (month), d (day), and y (year). For m use 1 for January,
# 2 for February, and so forth. For output print 0 for Sunday, 1 for Monday, 2 for
# Tuesday, and so forth. Use the following formulas, for the Gregorian calendar (where
# / denotes integer division):
# y0 = y − (14 − m) / 12
# x = y0 + y0/4 − y0/100 + y0/400
# m0 = m + 12 × ((14 − m) / 12) − 2
# d0 = (d + x + 31m0/ 12) mod 7
month = int(input("Enter Month in integer(1 to 12): "))
date = int(input("Enter the Date: "))
year = int(input("Enter the year: "))
class Calendar:
def __init__(self,month,day,year):
self.month = month
self.day = day
self.year = year
def dayOfWeek(self):
y = self.year - (14-self.month)//12
x = y + y//4 - y//100 + y//400
m = self.month + 12*((14 - self.month)//12)-2
d = (self.day + x + 31*m//12)%7
return d
day = Calendar(month,date,year)
if day.dayOfWeek()==0:
print("Sunday")
elif day.dayOfWeek()==1:
print("Monday")
elif day.dayOfWeek()==2:
print("Tuesday")
elif day.dayOfWeek()==3:
print("Wednesday")
elif day.dayOfWeek()==4:
print("Thursday")
elif day.dayOfWeek()==5:
print("Friday")
elif day.dayOfWeek()==6:
print("Saturday")
| true |
b59b0b070037764fc71912183e64d047c53f9cf1 | aruntonic/algorithms | /dynamic_programming/tower_of_hanoi.py | 917 | 4.375 | 4 | def tower_of_hanoi(n, source, buffer, dest):
'''
In the classic problem of the wers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.
The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using stacks.
'''
if n <= 0 :
return
tower_of_hanoi(n-1, source, dest, buffer)
dest.append(source.pop())
tower_of_hanoi(n-1, buffer, source, dest)
if __name__ == '__main__':
source = [5, 4, 3, 2, 1]
buffer = []
dest = []
print(source, buffer, dest)
tower_of_hanoi(5, source, buffer, dest)
print(source, buffer, dest)
| true |
f9f3819c0cacfd8d0aba22d64628ab343e94b5b7 | amulyadhupad/My-Python-practice | /square.py | 202 | 4.15625 | 4 | """ Code to print square of the given number"""
def square(num):
res =int(num) * int(num)
return res
num=input("Enter a number")
ans=square(num)
print("square of "+str(num)+" "+"is:"+str(ans)) | true |
c93c2c8f1a4a7a0a2d8a69ad312ea8c06dc54446 | tuanvp10/eng88_python_oop | /animal.py | 555 | 4.25 | 4 | # Create animal class via animal file
class Animal:
def __init__(self): # self refers to this class
self.alive = True
self.spine = True
self.eyes = True
self.lungs = True
def breath(self):
return "Keep breathing to stay alive"
def eat(self):
return "Nom nom nom nom!"
def move(self):
return "Moving all around the world"
# Create a object of our Animal class
# cat = Animal() # Creating a object of our Animal class = cat
# print(cat.breath()) # Breathing for cat is abstracted | true |
0acbad19ec29c8ce0e13d9d44eff09759e921be0 | Patrick-J-Close/Introduction_to_Python_RiceU | /rpsls.py | 1,779 | 4.1875 | 4 | # Intro to Python course project 1: rock, paper, scissors, lizard, Spock
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# where each value beats the two prior values and beats the two following values
import random
def name_to_number(name):
# convert string input to integer value
if name == "rock":
number = 0
elif name == "Spock":
number = 1
elif name == "paper":
number = 2
elif name == "lizard":
number = 3
elif name == "scissors":
number = 4
else:
print("You did not enter a valid name")
return(number)
def number_to_name(number):
# convert integer input to string
if number == 0:
name = "rock"
elif number ==1:
name = "Spock"
elif number == 2:
name = "paper"
elif number == 3:
name = "lizard"
elif number == 4:
name = "scissors"
else:
print("a valid number was not given")
return(name)
def rpsls(player_choice):
# master function
#print a blank line to seperate consecutive games
print("")
# print player's choice
print("Player chooses", player_choice)
# convert player's choice to number
player_val = name_to_number(player_choice)
# compute random result
comp_val = random.randrange(0,5)
# convert comp_val from integer to sting and print
comp_choice = number_to_name(comp_val)
print("Computer chooses", comp_choice)
# determine winner
dif = (player_val - comp_val) % 5
if dif == 0:
print("It's a draw!")
elif dif == 1 or dif == 2:
print ("Player wins!")
elif dif == 3 or dif ==4:
print("Compuer wins!")
rpsls("rock")
rpsls("paper")
rpsls("scissors")
rpsls("lizard")
rpsls("Spock")
| true |
ee8ff8648e324b2ca1c66c4c030a68c816af1464 | Merrycheeza/CS3130 | /LabAss2/LabAss2.py | 1,331 | 4.34375 | 4 | ###################################
# #
# Class: CS3130 #
# Assignment: Lab Assignment 2 #
# Author: Samara Drewe #
# 4921860 #
# #
###################################
#!/usr/bin/env python3
import sys, re
running = True
# prints the menu
print("--")
print("Phone Number ")
print(" ")
while(running):
# asks for the number
print("Enter phone number: ", end = "")
phone = input()
# checks to see if it's a blank line
if(phone == ""):
running = False
break
else:
#takes out the parenthesis and spaces
phone1 = re.sub('[\s+\(\)]', '', phone)
# checks the length, if it is lesser or greater than 10 digits, it's not a phone number
if len(phone1) == 10:
# checks length again after taking out everything that isn't a number
if(len(re.sub('[^0-9]',"", phone1)) == 10):
print("Number is " + "(" + phone1[0:3] + ")" + " " + phone1[3:6] + " " + phone1[6:])
# if it is not 10 digits, there were characters that were not numbers in the phone number
else:
print("Characters other than digits, hypens, space and parantheses detected")
# length not 10 digits, not a phone number
else:
print("Sorry phone number needs exactly 10 digits")
print("--")
| true |
30e22c55bb0fe9bd5221270053564adbe4d83932 | ine-rmotr-projects/INE-Fractal | /mandelbrot.py | 854 | 4.21875 | 4 | def mandelbrot(z0:complex, orbits:int=255) -> int:
"""Find the escape orbit of points under Mandelbrot iteration
# If z0 isn't coercible to complex, TypeError
>>> mandelbrot('X')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/davidmertz/git/INE/unittest/01-Doctest/mandelbrot1.py", line 4, in mandelbrot
if abs(z) > 2.0:
TypeError: bad operand type for abs(): 'str'
# Orbits must be integer. Traceback abbreviated below
>>> mandelbrot(0.0965-0.638j, orbits=3.1)
Traceback (most recent call last):
TypeError: 'float' object cannot be interpreted as an integer
"""
z = z0
for n in range(orbits):
if abs(z) > 2.0:
return n
z = z * z + z0
return orbits
if __name__ == '__main__':
import doctest; doctest.testmod()
| true |
0d24827c20ed97cbdf445f2691554cac1b99f8c8 | naochaLuwang/Candy-Vending-Machine | /tuto.py | 1,288 | 4.25 | 4 | # program to mimic a candy vending machine
# suppose that there are five candies in the vending machine but the customer wants six
# display that the vending machine is short of 1 candy
# And if the customer wants the available candy, give it to the customer else ask for another number of candy.
av = 5
x = int(input("Enter the number of candies you want: "))
for i in range(x):
if x > av:
remain = x - av
print("Total number of candies available is ", av)
print("We are short of ", remain, 'candies')
if remain != 0:
total = x - remain
print("Do you want", total, 'candies instead?')
ans = input("Enter yes/no: ")
if ans == 'yes':
for j in range(total):
print("Candy")
elif ans == 'no':
print("Do you want to continue or quit?")
choose = input("Enter 'C' to Continue or 'Q' to Quit: ")
if choose == 'C':
ans1 = int(input("Enter the number of Candies you want: "))
for k in range(ans1):
print("Candy")
else:
break
break
else:
print("candy")
print("Thank you for shopping with us. :)")
| true |
789ac887653860972e9788eb9bc2d7c4e6064abc | Sajneen-Munmun720/Python-Exercises | /Calculating the number of upper case and lower case letter in a sentence.py | 432 | 4.1875 | 4 | def case_testing(string):
d={"Upper_case":0,"Lower_case":0}
for items in string:
if items.isupper():
d["Upper_case"]+=1
elif items.islower():
d["Lower_case"]+=1
else:
pass
print("Number of upper case is:",d["Upper_case"])
print("Number of lower case is:", d["Lower_case"])
sentence=input("Enter a Sentence:")
case_letters=case_testing(sentence) | true |
edf7b53def0fffcecef3b00e4ea67464ba330d9c | Malcolm-Tompkins/ICS3U-Unit5-06-Python-Lists | /lists.py | 996 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on June 2, 2021
# Rounds off decimal numbers
def round_off_decimal(user_decimals, number_var):
final_digit = ((number_var[0] * (10 ** user_decimals)) + 0.5)
return final_digit
def main():
number_var = []
user_input1 = (input("Enter your decimal number: "))
try:
user_number = float(user_input1)
user_input2 = (input("Round how many decimals off: "))
try:
user_decimals = int(user_input2)
number_var.append(user_number)
round_off_decimal(user_decimals, number_var)
final_number = int
final_number = round_off_decimal(user_decimals, number_var)
print(final_number)
except Exception:
print("{} is not a positive integer".format(user_input2))
except Exception:
print("{} is not a decimal number".format(user_input1))
finally:
print("Done.")
if __name__ == "__main__":
main()
| true |
3e78ea8629c13cefe4fdcbf42f475eb4da525b2a | vladbochok/university-tasks | /c1s1/labwork-2.py | 1,792 | 4.21875 | 4 | """
This module is designed to calculate function S value with given
accuracy at given point.
Functions:
s - return value of function S
Global arguments:
a, b - set the domain of S
"""
from math import fabs
a = -1
b = 1
def s(x: float, eps: float) -> float:
"""Return value of S at given point x with given accuracy - eps
Arguments:
x - should be real number at least -1 and at most 1.
eps - should be real number greater 0.
Don’t check if eps is positive number. If not so, do infinite loop.
For non relevant x the result may be inaccurate.
"""
el = x * x / 2
sum = 0
k = 0
x4 = -x * x * x * x
while fabs(el) >= eps:
sum += el
el *= x4 / ((4 * k + 3) * (4 * k + 4) * (4 * k + 5) * (4 * k + 6))
k += 1
sum += el
return sum
print("Variant №3", "Vladyslav Bochok", sep="\n")
print("Calculating the value of the function S with given accuracy")
try:
x = float(input(f"Input x - real number in the range from {a} to {b}: "))
eps = float(input("Input eps - real positive number: "))
# Check arguments for domain, calculate S, output
if a <= x <= b and eps > 0:
print("***** do calculations ...", end=" ")
result = s(x, eps)
print("done")
print(f"for x = {x:.6f}", f"for eps = {eps:.4E}", f"result = {result:.8f}", sep="\n")
else:
print("***** Error")
# Check x ans eps for domain, print error description
if x < a or x > b:
print(f"if x = {x:.6f} then S is not convergence to function F")
if eps <= 0:
print("The calculation cannot be performed if eps is not greater than zero. ")
except ValueError or KeyboardInterrupt:
print("***** Error", "Wrong input: x and eps should be float", sep="\n")
| true |
6f0bc83046ec214818b9b8cc6bc5962a5d819977 | thivatm/Hello-world | /Python/Counting the occurence of each word.py | 223 | 4.21875 | 4 | string=input("Enter string:").split(" ")
word=input("Enter word:")
from collections import Counter
word_count=Counter(string)
print(word_count)
final_count=word_count[word]
print("Count of the word is:")
print(final_count)
| true |
0cb00f6f4798c9bc5770f04b8a2a09cb0e3f0c43 | ssavann/Python-Data-Type | /MathOperation.py | 283 | 4.25 | 4 | #Mathematical operators
print(3 + 5) #addition
print(7 - 4) #substraction
print(3 * 2) #multiplication
print(6 / 3) #division will always be "Float" not integer
print(2**4) #power: 2 power of 4 = 16
print((3 * 3) + (3 / 3) - 3) #7.0
print(3 * (3 + 3) / 3 - 3) #3.0
| true |
c54d75b36108590ba19569ae24f6b72fd13b628b | Alankar-98/MWB_Python | /Functions.py | 239 | 4.15625 | 4 | # def basic_function():
# return "Hello World"
# print(basic_function())
def hour_to_mins(hour):
mins = hour * 60
return mins
print(hour_to_mins(float(input("Enter how many hour(s) you want to convert into mins: \n")))) | true |
ce788f6c65b9b8c4e3c47585b7024d2951b59d19 | GLARISHILDA/07-08-2021 | /cd_abstract_file_system.py | 928 | 4.15625 | 4 | # Write a function that provides a change directory (cd) function for an abstract file system.
class Path:
def __init__(self, path):
self.current_path = path # Current path
def cd(self, new_path): # cd function
parent = '..'
separator = '/'
# Absolute path
change_list = self.current_path.split(separator)
new_list = new_path.split(separator)
# Relative path
for item in new_list:
if item == parent:
#delete the last item in list
del change_list[-1]
else:
change_list.append(item)
# Add "/" before each item in the list and print as string
self.current_path = "/".join(change_list)
return self.current_path
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path) | true |
a84755fd8627c33535f669980de25c072e0a3c83 | sandeshsonje/Machine_test | /First_Question.py | 555 | 4.21875 | 4 | '''1. Write a program which takes 2 digits, X,Y as input and generates a
2-dimensional array.
Example:
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Note: Values inside array can be any.(it's up to candidate)'''
row = int(input("Enter number of rows = "))
col = int(input("Enter number of cols = "))
arr=[]
for i in range(0,row):
arr1=[]
for j in range(0,col):
arr1.append(i*j)
arr.append(arr1)
print(arr)
| true |
f5e7a155de761f83f9ad7b8293bc5c81edda3f1f | Luciekimotho/datastructures-and-algorithms | /MSFT/stack.py | 821 | 4.1875 | 4 | #implementation using array
#class Stack:
# def __init__(self):
# self.items = []
# def push(self, item):
# self.items.append(item)
# def pop(self):
# return self.items.pop()
#implementation using lists
class Stack:
def __init__(self):
self.stack = list()
#insertion -> append item to the stack list
def push(self, item):
self.stack.append(item)
#delete -> pop item on the top of the stack, returns this item
def pop(self):
return self.stack.pop()
#return length of stack
def size(self):
return len(self.stack)
#initialize stack
s = Stack()
#adding items to the stack
s.push(56)
s.push(45)
s.push(34)
#Checking for size before and after the pop
print(s.size())
print(s.pop())
print(s.size())
| true |
eab5e0186698af32d9301abf155e1d0af25e5f6f | jzamora5/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 647 | 4.1875 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
"""
In a text file, there is a single character H. Your text editor can execute
only two operations in this file: Copy All and Paste. Given a number n,
write a method that calculates the fewest number of operations needed to
result in exactly n H characters in the file.
Returns an integer
If n is impossible to achieve, returns 0
"""
if not isinstance(n, int):
return 0
op = 0
i = 2
while (i <= n):
if not (n % i):
n = int(n / i)
op += i
i = 1
i += 1
return op
| true |
746c24e8e59f8f85af4414d5832f0ec1bf9a4f7c | joeblackwaslike/codingbat | /recursion-1/powerN.py | 443 | 4.25 | 4 | """
powerN
Given base and n that are both 1 or more, compute recursively (no loops) the
value of base to the n power, so powerN(3, 2) is 9 (3 squared).
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
"""
def powerN(base, n):
if n == 1:
return base
else:
return base * powerN(base, n - 1)
if __name__ == "__main__":
for base, n in [(3, 1), (3, 2), (3, 3)]:
print((base, n), powerN(base, n))
| true |
d6fb1774f0abf4a7dfacc3630206cc2e8fda883c | shenxiaoxu/leetcode | /questions/1807. Evaluate the Bracket Pairs of a String/evaluate.py | 1,448 | 4.125 | 4 | '''
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:
Replace keyi and the bracket pair with the key's corresponding valuei.
If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks).
Each key will appear at most once in your knowledge. There will not be any nested brackets in s.
Return the resulting string after evaluating all of the bracket pairs.
'''
class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = {k: v for k, v in knowledge}
cur = ''
ongoing = False
res = []
for c in s:
if c == '(':
ongoing = True
elif c == ')':
ongoing = False
res.append(d.get(cur,'?'))
cur = ''
elif ongoing:
cur+=c
else:
res.append(c)
return ''.join(res)
| true |
bfe9ecfe1e7c5e04be74a9ad86e0deed0535063e | nikonst/Python | /Core/lists/big_diff.py | 691 | 4.125 | 4 | '''
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) - 7
big_diff([7, 2, 10, 9]) - 8
big_diff([2, 10, 7, 2]) - 8
'''
import random
def b_diff(nums):
if len(nums) == 1:
diff = nums[0]
else:
diff = max(nums) - min(nums)
return diff
theList = []
listSize = random.randint(1,20)
for i in range(0,listSize):
theList.append(random.randint(0, 100))
print 'Size of list ', listSize,' The List : ',theList
print 'Big Difference: ',b_diff(theList) | true |
29dc483eabdfada41277bd0879d4d30db4c5e9e1 | nikonst/Python | /Core/lists/centered_average.py | 859 | 4.21875 | 4 | '''
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value. Use int division to produce the final average.
You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) - 3
centered_average([1, 1, 5, 5, 10, 8, 7]) - 5
centered_average([-10, -4, -2, -4, -2, 0]) - -3
'''
import random
def cent_avg(aList):
return (sum(aList) - min(aList) - max(aList)) / len(list)
list = []
listSize = random.randint(3,20)
for i in range(0,listSize):
list.append(random.randint(1,100))
print 'The Size of List is :', listSize
print 'The List : ', list
print 'Centered Averege = ', cent_avg(list)
| true |
e924c76da60630526344873dfd5523c3bf9bec7d | nikonst/Python | /Core/lists/max_end3.py | 792 | 4.40625 | 4 | '''
Given an array of ints length 3, figure out which is larger, the first or last element in the array,
and set all the other elements to be that value. Return the changed array.
max_end3([1, 2, 3]) - [3, 3, 3]
max_end3([11, 5, 9]) - [11, 11, 11]
max_end3([2, 11, 3]) - [3, 3, 3]
'''
def maxEnd3(nums):
newList = []
print '***', nums[len(nums)-1]
if nums[0] >= nums[len(nums)-1]:
for i in range(0,len(nums)):
newList.append(nums[0])
else:
for i in range(0,len(nums)):
newList.append(nums[len(nums)-1])
return newList
list =[]
x = input('Enter list number (0 - Stop) > ')
while x != 0:
list.append(x)
x = input('Enter list number (0 - Stop) > ')
print list
list = maxEnd3(list)
print list
| true |
2dde45ecac9827dc9804a3d4277054bb07e5be02 | Vaishnavi-cyber-blip/LEarnPython | /Online library management system.py | 1,658 | 4.1875 | 4 | class Library:
def __init__(self, list_of_books, library_name):
self.library_name = library_name
self.list_of_books = list_of_books
def display_books(self):
print(f"Library name is {self.library_name}")
print(f"Here is the list of books we provide:{self.list_of_books}")
def add_book(self):
print("Name of book?")
book = input().capitalize()
self.list_of_books.append(book)
print("Awesome! Here we have a new source of knowledge")
print(self.list_of_books)
def lend_book(self):
print("Enter your name:")
name = input()
# d1 = {}
print("Which book you want to lend?")
book = input().lower()
if book in self.list_of_books:
print(f"Now {name} is the owner of book: {book}")
self.list_of_books.remove(book)
else:
print("Currently not available")
def return_book(self):
print("Name of the book you want to return")
ham = input()
print("Hope you enjoyed reading!")
self.list_of_books.append(ham)
lst = ["hi", "bi", "mi", "vi"]
obj = Library(lst, "Read_Me")
if __name__ == '__main__':
while True:
print("Enter your requirements Sir/Mam: 1.Show Books[show] "
"2.Lend Books[lend] "
"3.Add Book[add] "
"4.Return Book[return]"
)
need = input().upper()
if need == "SHOW":
obj.display_books()
elif need == "LEND":
obj.lend_book()
elif need == "ADD":
obj.add_book()
else:
obj.return_book()
| true |
0d70416d7d6d50d3f69d38ab8bb6878b3e673667 | MarkVarga/python_to_do_list_app | /to_do_list_app.py | 1,819 | 4.21875 | 4 |
data = []
def show_menu():
print('Menu:')
print('1. Add an item')
print('2. Mark as done')
print('3. View items')
print('4. Exit')
def add_items():
item = input('What do you need to do? ')
data.append(item)
print('You have added: ', item)
add_more_items()
def add_more_items():
user_choice = input('Do you want to add anything else? Press Y/N: ')
if user_choice.lower() == 'y':
add_items()
elif user_choice.lower() =='n':
app_on()
elif user_choice.lower() != 'y' or user_choice.lower() != 'n':
print('Invalid choice')
add_more_items()
def remove_items():
item = input('What have you completed? ')
if item in data:
data.remove(item)
print(item, 'has been removed from your list')
remove_more_items()
else:
print('This item does not exist')
app_on()
def remove_more_items():
user_choice = input('Do you want to remove anything else? Press Y/N: ')
if user_choice.lower() == 'y':
remove_items()
elif user_choice.lower() =='n':
app_on()
else:
print('Invalid choice')
remove_more_items()
def show_items():
print('Here is your to-do-list: ')
for item in data:
print(item)
app_on()
def exit_app():
print('Thanks for using the app! See you later!')
def app_on():
show_menu()
user_input = input('Enter your choice: ')
print('You entered:', user_input)
if user_input == '1':
add_items()
elif user_input == '2':
remove_items()
elif user_input == '3':
show_items()
elif user_input == '4':
exit_app()
else:
print('Invalid choice. Please enter 1, 2, 3 or 4')
app_on()
app_on() | true |
ff3ccbf45d3be6f6933f03ec3be4ec8c03c15be1 | j-hmd/daily-python | /Object-Oriented-Python/dataclasses_intro.py | 600 | 4.1875 | 4 | # Data classes make the class definition more concise since python 3.7
# it automates the creation of __init__ with the attributes passed to the
# creation of the object.
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int
price: float
b1 = Book("A Mao e a Luva", "Machado de Assis", 356, 29.99)
b2 = Book("Dom Casmurro", "Machado de Assis", 230, 24.50)
b3 = Book("Capitaes da Areia", "Jorge Amado", 178, 14.50)
# The data class also provides implementations for the __repr__ and __eq__ magic functions
print(b1.title)
print(b2.author)
print(b1 == b2) | true |
975f43786306ca83189c8a7f310bec5b38c1ac84 | Pawan459/infytq-pf-day9 | /medium/Problem_40.py | 1,587 | 4.28125 | 4 | # University of Washington CSE140 Final 2015
# Given a list of lists of integers, write a python function, index_of_max_unique,
# which returns the index of the sub-list which has the most unique values.
# For example:
# index_of_max_unique([[1, 3, 3], [12, 4, 12, 7, 4, 4], [41, 2, 4, 7, 1, 12]])
# would return 2 since the sub-list at index 2 has the most unique values in it(6 unique values).
# index_of_max_unique([[4, 5], [12]])
# would return 0 since the sub-list at index 0 has the most unique values in it(2 unique values).
# You can assume that neither the list_of_lists nor any of its sub-lists will be empty.
# If there is a tie for the max number of unique values between two sub-lists, return the index of the first sub-list encountered(when reading left to right) that has the most unique values.
#PF-Prac-40
#PF-Prac-40
def findUniqueValue(li):
dic = dict()
for i in li:
try:
dic[i] += 1
except:
dic[i] = 1
return len(dic)
def index_of_max_unique(num_list):
#start writing your code here
index = 0
max_len = -1
for i in range(len(num_list)):
unique_values = findUniqueValue(num_list[i])
if max_len < unique_values:
index = i
max_len = unique_values
return index
num_list = [[1, 3, 3], [12, 4, 12, 7, 4, 4],
[41, 2, 4, 7, 1, 12], [1, 2, 3, 4, 5, 6]]
num_list1 = [[4, 5], [12], [3, 8]]
print("Number list:", num_list)
output = index_of_max_unique(num_list)
print("The index of sub list containing maximum unique elements is:", output)
| true |
1e7f67cd95ecd74857bcc0a2aeb4a45e6b13947d | harshonyou/SOFT1 | /week5/week5_practical4b_5.py | 440 | 4.125 | 4 | '''
Exercise 5:
Write a function to_upper_case(input_file, output_file) that takes two
string parameters containing the name of two text files. The function reads the content of the
input_file and saves it in upper case into the output_file.
'''
def to_upper_case(input_file, output_file):
with open(input_file) as x:
with open(output_file, 'w') as y:
print(x.read().upper(), file=y)
to_upper_case('ayy','exo1.txt') | true |
dd0b87ac56156e3f3f7397395752cd9f57d33972 | harshonyou/SOFT1 | /week7/week7_practical6a_6.py | 1,075 | 4.375 | 4 | '''
Exercise 6:
In Programming, being able to compare objects is important, in particular determining if two
objects are equal or not. Let’s try a comparison of two vectors:
>>> vector1 = Vector([1, 2, 3])
>>> vector2 = Vector([1, 2, 3])
>>> vector1 == vector2
False
>>> vector1 != vector2
True
>>> vector3 = vector1
>>> vector3 == vector1
True
As you can see, in the current state of implementation of our class Vector does not produce the
expected result when comparing two vectors. In the example above the == operator return
True if the two vectors are physically stored at the same memory address, it does not compare
the content of the two vectors.
Therefore, you need to implement a method equals(other_vector) that returns True
if the vectors are equals (i.e. have the same value at the same position), False otherwise.
'''
#Complete Answer Is Within Vector.py
def equal(self, matrix):
if not(isinstance(matrix,Vector)):
return 'TypeError'
if self._vector==matrix._vector:
return True
else:
return False | true |
13138f7e7f105cb917d3c28995502f01ace2c46a | harshonyou/SOFT1 | /week4/week4_practical3_5.py | 829 | 4.25 | 4 | '''
Exercise 5: Where’s that bug!
You have just started your placement, and you are given a piece of code to correct. The aim of
the script is to take a 2D list (that is a list of lists) and print a list containing the sum of each
list. For example, given the list in data, the output should be [6, 2, 10].
Modify the code below such that it gives the right result. In addition, you have been asked to
refactor the script into a function sum_lists(list_2D) that returns the list containing the
sums of each sub-list.
data = [[1,2,3], [2], [1, 2, 3, 4]]
output =[]
total = 0
for row in data:
for val in row:
total += val
output.append(total)
print(output)
'''
data = [[1,2,3], [2], [1, 2, 3, 4]]
output =[]
total = 0
for row in data:
for val in row:
total += val
output.append(total)
total=0
print(output) | true |
7209b64a1bfbca67fa750370a6b2a2f35f04085b | harshonyou/SOFT1 | /week3/week3_ex1_1.py | 870 | 4.125 | 4 | '''
Exercise 1: Simple while loopsExercise 1: Simple while loops
1. Write a program to keep asking for a number until you enter a negative number. At the end, print the sum of all entered numbers.
2. Write a program to keep asking for a number until you enter a negative number. At the end, print the average of all entered numbers.
3. Write a program to keep asking for a number until you enter a negative number. At the end, print the number of even number entered.
'''
Sum=0
total=0
evens=0
def printEXIT(a,b,c):
print("Sum of all the number entered:",a)
print("Average of all the number entered:",b)
print("Number of even number entered:",c)
exit()
while True:
x=input("Enter A Number: ")
total+=1
print("You have entered:", x if float(x)>=0 else printEXIT(Sum,Sum/total,evens))
Sum+=float(x)
evens+=1 if float(x)%2==0 else 0 | true |
ae485d7078b0a130d25f508fa3bbf2654b288fbd | carlosberrio/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/4-append_write.py | 312 | 4.34375 | 4 | #!/usr/bin/python3
"""Module for append_write method"""
def append_write(filename="", text=""):
"""appends a string <text> at the end of a text file (UTF8) <filename>
and returns the number of characters added:"""
with open(filename, 'a', encoding='utf-8') as file:
return file.write(text)
| true |
129c7dfb7e4704916d6a3c70c7b88de3f4ee5ab4 | carlosberrio/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,673 | 4.3125 | 4 | #!/usr/bin/python3
""" Module for matrix_divided method"""
def matrix_divided(matrix, div):
"""Divides all elements of a matrix by div
Args:
matrix: list of lists of numbers (int or float)
div: int or float to divide matrix by
Returns:
list: a new matrix list of lists
Raises:
TypeError: if div is not an int or float
ZeroDivisionError: if div is equal to 0
TypeError: if matrix or each row is not a list of lists
of int or floats
TypeError: if each row of the matrix is not of the same size
TypeError: if any element of the sublist is not an int or float
"""
if type(div) not in (int, float):
raise TypeError('div must be a number')
if div == 0:
raise ZeroDivisionError('division by zero')
if not isinstance(matrix, list) or len(matrix) == 0:
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
for row in matrix:
if not isinstance(row, list) or len(row) == 0:
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
if len(row) != len(matrix[0]):
raise TypeError('Each row of the matrix must have the same size')
for n in row:
if type(n) not in (int, float):
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
return [[round(n / div, 2) for n in row] for row in matrix]
if __name__ == "__main__":
import doctest
doctest.testfile("tests/2-matrix_divided.txt")
| true |
ac98781df6169c661443e347c22760b6a88fad1c | KamalAres/Infytq | /Infytq/Day8/Assgn-55.py | 2,650 | 4.25 | 4 | #PF-Assgn-55
#Sample ticket list - ticket format: "flight_no:source:destination:ticket_no"
#Note: flight_no has the following format - "airline_name followed by three digit number
#Global variable
ticket_list=["AI567:MUM:LON:014","AI077:MUM:LON:056", "BA896:MUM:LON:067", "SI267:MUM:SIN:145","AI077:MUM:CAN:060","SI267:BLR:MUM:148","AI567:CHE:SIN:015","AI077:MUM:SIN:050","AI077:MUM:LON:051","SI267:MUM:SIN:146"]
def find_passengers_flight(airline_name="AI"):
#This function finds and returns the number of passengers travelling in the specified airline.
count=0
for i in ticket_list:
string_list=i.split(":")
if(string_list[0].startswith(airline_name)):
count+=1
return count
def find_passengers_destination(destination):
#Write the logic to find and return the number of passengers traveling to the specified destination
#pass
#Remove pass and write your logic here
count=0
for i in ticket_list:
string_list=i.split(":")
if(string_list[2].startswith(destination)):
count+=1
return count
def find_passengers_per_flight():
'''Write the logic to find and return a list having number of passengers traveling per flight based on the details in the ticket_list
In the list, details should be provided in the format:
[flight_no:no_of_passengers, flight_no:no_of_passengers, etc.].'''
#pass
#Remove pass and write your logic here
pass_list=[]
for i in ticket_list:
flight_no=i[:5]
no_of_passengers=find_passengers_flight(i[:5])
flight_no=flight_no+":"+str(no_of_passengers)
pass_list.append(flight_no)
#print(pass_list)
return list(set(pass_list))
def sort_passenger_list():
#Write the logic to sort the list returned from find_passengers_per_flight() function in the descending order of number of passengers
#pass
#Remove pass and write your logic here
sort_list=find_passengers_per_flight()
new=[]
for i in sort_list:
i=i.split(":")
#print(i)
#new.append(i
l=i[::-1]
#print(l)
new.append(l)
new.sort(reverse=True)
sort_list=new
new=[]
for i in sort_list:
new.append(i[::-1])
temp=""
sort_list=[]
for i in new:
temp=i[0]+":"+i[1]
sort_list.append(temp)
#print(new)
return sort_list
#Provide different values for airline_name and destination and test your program.
#print(find_passengers_per_flight())
#print(find_passengers_flight("AI"))
#print(find_passengers_destination("LON"))
print(sort_passenger_list())
| true |
5a195c58bc440fce91c4a7ebc3a1f9eeb61d1ce1 | Wallabeee/PracticePython | /ex11.py | 706 | 4.21875 | 4 | # Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
# a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
# Take this opportunity to practice using functions, described below.
def isPrime(num):
divisors = []
for x in range(1, num + 1):
if num % x == 0:
divisors.append(x)
if num ==1:
print(f"{num} is not a prime number.")
elif divisors[0] == 1 and divisors[1] == num:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
num = int(input("Enter a number: "))
isPrime(num) | true |
02e8b295591e79c057481be775219e2143915e4f | SaidhbhFoley/Promgramming | /Week04/even.py | 370 | 4.15625 | 4 | #asks the user to enter in a number, and the program will tell the user if the number is even or odd.
#Author: Saidhbh Foley
number = int (input("enter an integer:"))
if (number % 2) == 0:
print ("{} is an even number".format (number))
else:
print ("{} is an odd number".format (number))
i = 0
while i > 0:
print (i)
else:
print ("This has ended the loop")
| true |
c158785cfd4d1ef3704194e7a1fea2d1a1210308 | tdchua/dsa | /data_structures/doubly_linkedlist.py | 2,805 | 4.34375 | 4 | #My very own implementation of a doubly linked list!
#by Timothy Joshua Dy Chua
class Node:
def __init__(self, value):
print("Node Created")
self.value = value
self.next = None
self.prev = None
class DLinked_List:
def __init__(self):
self.head = None
self.tail = None
def traverse(self):
curr_node = self.head
while(True):
if(curr_node != None):
print(curr_node.value)
curr_node = curr_node.next
else:
break
#For a doubly linked list the reverse traversal is much easier to implement
def reverse_traverse(self):
curr_node = self.tail
while(True):
if(curr_node != None):
print(curr_node.value)
curr_node = curr_node.prev
else:
break
return
def delete_node(self, value):
#The case for head removal
if(value == self.head.value):
self.head = self.head.next
else:
curr_node = self.head
while(True):
prev_node = curr_node
#If we have reached the end of the list
if(curr_node.next == None):
print("Node to delete...not found")
return
curr_node = curr_node.next
#The node to remove is curr_node
if(curr_node.value == value):
prev_node.next = curr_node.next
curr_node.next.prev = prev_node
return
def insert_node(self, value):
#In the DSA book, it was only mentioned that adding a node would be inserting it after the list's tail.
prev_node = None
if(self.head != None): #To check if there is no head
curr_node = self.head
while(True):
if(curr_node.next == None):
curr_node.prev = prev_node
curr_node.next = Node(value)
return
else:
prev_node = curr_node
curr_node = curr_node.next
else:
self.head = Node(value)
return
if __name__ == "__main__":
my_list = [i for i in range(10)]
#Here is where we instantiate a single linked list.
#We instantiate the head node first; we give it the first value
head = Node(my_list[0])
#We then instantiate the linked list
my_doubly_linked_list = DLinked_List()
#We connect the head pointer of the linked list to the first node
my_doubly_linked_list.head = head
for element in my_list[1:]:
my_doubly_linked_list.insert_node(element)
#We then traverse the link
print("Traversal")
curr_node = my_doubly_linked_list.head
my_doubly_linked_list.traverse()
#Reverse traversal
print("Reverse Traversal")
my_doubly_linked_list.reverse_traverse()
#Deleting a node
print("Node Deletion")
my_doubly_linked_list.delete_node(0)
my_doubly_linked_list.traverse()
#Inserting a node
print("Node Insertion")
my_doubly_linked_list.insert_node(16)
my_doubly_linked_list.traverse()
| true |
22aa6b4daeb05936eb5fd39b361e2945d02a5f64 | 786awais/assignment_3-geop-592-sharing | /Assignment 3 GEOP 592 | 2,512 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[50]:
#GEOP_592 Assigment_3
#Codes link: https://www.datarmatics.com/data-science/how-to-perform-logistic-regression-in-pythonstep-by-step/
#We are Provided with a data for 6800 micro-earthquake waveforms. 100 features have been extracted form it.
#We need to perform logistic regression analysis to find that if it is a micro-earthquake (1) or noise (0).
# In[1]:
#Import the module
from sklearn.datasets import make_classification
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np
# In[2]:
label = np.load('label.npy')
# In[3]:
features = np.load('features.npy')
# In[4]:
features.shape
# In[5]:
label.shape
# In[10]:
label[1:10]
# In[20]:
features[0:10,0:10]
# In[22]:
# Generate and dataset for Logistic Regression, This is given in the tutoriL, Not for our use in this assignmnet
x, y = make_classification(
n_samples=100,
n_features=2,
n_classes=2,
n_clusters_per_class=1,
flip_y=0.03,
n_informative=1,
n_redundant=0,
n_repeated=0
)
print(y)
# In[27]:
y.shape
# In[28]:
x.shape
# In[29]:
# Create a scatter plot
plt.scatter(x[:,1], y, c=y, cmap='rainbow')
plt.title('Scatter Plot of Logistic Regression')
plt.show()
# In[30]:
# Split the dataset into training and test dataset: Taking 5500 out of 6800 data points for training set, so 1300 will be used for test data points.
x_train, x_test, y_train, y_test = train_test_split(features, label, test_size = 1300, random_state=1)
# In[35]:
# Create a Logistic Regression Object, perform Logistic Regression
log_reg = LogisticRegression(solver='lbfgs',max_iter=500)
log_reg.fit(x_train, y_train)
# In[36]:
# Show to Coeficient and Intercept
print(log_reg.coef_)
print(log_reg.intercept_)
# In[37]:
# Perform prediction using the test dataset
y_pred = log_reg.predict(x_test)
# In[38]:
# Show the Confusion Matrix
confusion_matrix(y_test, y_pred)
# In[40]:
x_test.shape
# In[41]:
y_test.shape
# In[42]:
x_train.shape
# In[43]:
y_train.shape
# In[45]:
print(log_reg.score(x_test, y_test))
# In[49]:
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
# In[ ]:
# So, our classification for '0' and '1' is correct for 99% & 98% respectively with overall accuracy of 98%.
| true |
63b2b212b2e42f539fb802cc95633eae00c34a7f | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework1/problem2.py | 825 | 4.1875 | 4 | # jws2191
''' This program will, given an integer representing a number of years,
print the approximate population given the current population and the
approximate births, deaths, and immigrants per second. '''
# Step 1: store the current population and calculate the rates of births,
# deaths, and immigrations per year
current_population = 307357870
births_per_year = (60*60*24*365)/7
deaths_per_year = (60*60*24*365)/13
immigrants_per_year = (60*60*24*365)/35
#Step 2: take in number of years as input
s = input('Enter how many years into the future you would like to see the population?: ')
years = int(s)
# Step 3: adjust the population accordingly
new_population = current_population + years*(births_per_year - deaths_per_year + immigrants_per_year)
print("The new population is %d people." % new_population) | true |
773442a1cdd867d18af6c7578af1f5e208be9a7c | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework2/untitled.py | 552 | 4.28125 | 4 | '''
This is a basic dialog system that prompts the user to
order pizza
@author Joe Skimmons, jws2191
'''
def select_meal():
possible_orders = ["pizza" , "pasta" , "salad"]
meal = input("Hello, would you like pizza, pasta, or salad?\n")
while meal.lower() not in possible_orders:
meal = input("Sorry, we don't have " + meal + " today!\n")
def salad():
salad = input("Hello, would you like pizza, pasta, or salad?\n")
while salad.lower() != "salad":
salad = input("Sorry, we don't have " + meal + " today!\n")
select_meal()
salad() | true |
6210f2e37e1ce5e93e7887ffa73c8769fae0a35a | garg10may/Data-Structures-and-Algorithms | /searching/rabinKarp.py | 1,862 | 4.53125 | 5 | #Rabin karp algorithm for string searching
# remember '^' : is exclusive-or (bitwise) not power operator in python
'''
The algorithm for rolling hash used here is as below. Pattern : 'abc', Text : 'abcd'
Consider 'abc' its hash value is calcualted using formula a*x^0 + b*x^1 + c*x^2, where x is prime
Now when we need to roll( i.e. find hash of 'bcd'), which should be b*x^0 + c*x^1 + d*x^2,
instead of calculating it whole , we just subract first character value and add next character value.
Value of first character would be a*X^0 --> a, so we subract a and divide by prime so that new position becomes
b*x^0 + c*x^1, now we need to add next character, which would be 'd'*x^(patternLength-1), so here 'd'*x^2 so it becomes
b*x^0 + c*x^1 + d*x^2, which is what we need. It's O(1) so very useful for long strings.
Note:
Here it's recommended to use high value of text characters, therefore use ASCII value for text not just 0,1,2
Also use prime number greater than 100, so that the hash function is good and less collisions are there
See for more information --> https://en.wikipedia.org/wiki/Rolling_hash
'''
def hashValue(pattern, prime):
value = 0
for index, char in enumerate(pattern):
value += ord(char) * (pow(prime,index))
return value
def find(pattern , text):
prime = 3
m = len(pattern)
n = len(text)
p = hashValue(pattern, prime)
t = hashValue(text[:m], prime)
for i in range(n-m+1):
#if hashes are equal
if p == t:
#check for each character, since two different strings can have same hash
for j in range(m):
if text[i + j] != pattern[j]:
break
if j == m-1:
print 'Pattern found at index %s'%(i)
#calculate rolling hash
if i < n-m: # i.e. still some text of lenth m is left
t = ((t - ord(text[i])) / prime) + (ord(text[i + m]) * (pow(prime, (m - 1))))
find('abc', '***abc***111***abc***') | true |
e1be3b9664e172dc71a2e3038a1908c5e49dd57b | Fueled250/Intro-Updated-Python | /intro_updated.py | 881 | 4.1875 | 4 | #S.McDonald
#My first Python program
#intro.py -- asking user for name, age and income
#MODIFIED: 10/18/2016 -- use functions
#create three functions to take care of Input
def get_name():
#capture the reply and store it in 'name' variable
name = input ("what's your name?")
return name
def get_age():
#capture the reply, convert to 'int' and store in 'age' variable
age = int(input ("How old are you?"))
return age
def get_income():
#capture the reply, convert to 'float' and store in 'income' variable
income = float(input ("what's your income?"))
return income
#create a main function
def main():
#call the other functions by their names
name = get_name() #return the value from function
age = get_age()
income = get_income()
print(name, age, income)
#call the main() function
main()
| true |
1c60d291a1d02ee0ebefd3544843c918179e5254 | aiswaryasaravanan/practice | /hackerrank/12-26-reverseLinkedList.py | 956 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def add(self,data):
if not self.head:
self.head=Node(data)
else:
cur=self.head
while cur.next:
cur=cur.next
cur.next=Node(data)
def reverse(self):
pre=None
cur=self.head
foll=cur.next
while cur.next:
cur.next=pre
pre=cur
cur=foll
foll=cur.next
cur.next=pre
self.head=cur
def printList(self):
cur=self.head
while cur.next:
print(cur.data)
cur=cur.next
print(cur.data)
linkedList = LinkedList()
linkedList.add(1)
linkedList.add(2)
linkedList.add(3)
linkedList.add(4)
linkedList.add(5)
linkedList.printList()
linkedList.reverse()
linkedList.printList() | true |
781b93dd583dc43904e9b3d5aa4d6b06eaa5705b | spno77/random | /Python-programs/oop_examples.py | 1,399 | 4.625 | 5 | """ OOP examples """
class Car:
""" Represent a car """
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descritive name"""
long_name = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
print(f"this car has {self.odometer_reading} miles")
def update_odometer(self,mileage):
if(mileage >= self.odometer_reading):
self.odometer_reading = mileage
else:
print("You cant roll back the odometer")
def increment_odometer(self,miles):
if(miles < 0):
print("You cant assign negative values")
else:
self.odometer_reading += miles
class Battery:
def __init__(self,battery_size = 75):
self.battery_size = battery_size
def describe_battery(self):
print(f"this car has a {self.battery_size}-kWh batery")
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles"""
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
new_car = ElectricCar("tesla","model s",2019)
new_car.battery.describe_battery()
new_car.battery.get_range() | true |
052193ea7c43ccaf0406b3c34cf08b906d6c74fd | GitDavid/ProjectEuler | /euler.py | 812 | 4.25 | 4 | import math
'''
library created for commonly used Project Euler problems
'''
def is_prime(x):
'''
returns True if x is prime; False if not
basic checks for lower numbers and all primes = 6k +/-1
'''
if x == 1 or x == 0:
return False
elif x <= 3:
return True
elif x % 2 == 0 or x % 3 == 0:
return False
elif x < 9:
return True
else:
r = math.floor(math.sqrt(x))
f = 5
while f <= r:
if (x % f == 0) or (x % (f + 2) == 0):
return False
f += 6
return True
def primes_up_to(x):
'''
returns list of all primes up to (excluding) x
'''
primes_list = []
for i in range(x - 1):
if is_prime(i):
primes_list.append(i)
return primes_list
| true |
7bc09ed3640e3f0e32e2ea12725a65cb87d6d39f | SavinaRoja/challenges | /Rosalind/String_Algorithms/RNA.py | 2,275 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Transcribing DNA into RNA
Usage:
RNA.py <input> [--compare]
RNA.py (--help | --version)
Options:
--compare run a speed comparison of various methods
-h --help show this help message and exit
-v --version show version and exit
"""
problem_description = """Transcribing DNA into RNA
Problem
An RNA string is a string formed from the alphabet containing 'A', 'C', 'G',
and 'U'.
Given a DNA string, t, corresponding to a coding strand, its transcribed RNA
string, u, is formed by replacing all occurrences of 'T' in t with 'U' in u.
Given: A DNA string t having length at most 1000 nt.
Return: The transcribed RNA string of t.
Sample Dataset
GATGGAACTTGACTACGTAAATT
Sample Output
GAUGGAACUUGACUACGUAAAUU
"""
from docopt import docopt
from time import time
def get_string_from_dataset(inp_file):
#The dataset should be a file with a single line, containing no more than
#1000 characters of the ACGT alphabet
with open(inp_file, 'r') as inp:
data_string = inp.readline()
return data_string.strip()
def string_replace_method(data):
return data.replace('T', 'U')
def iterative_transcribe_method(data):
rna = ''
for char in data:
if char == 'T':
rna += 'U'
else:
rna += char
return rna
def main():
"""This will solve the problem, simply uses the string_replace_method"""
data_string = get_string_from_dataset(arguments['<input>'])
print(string_replace_method(data_string))
def compare():
"""
This will seek to compare the various solutions
"""
data_string = get_string_from_dataset(arguments['<input>'])
start = time()
for i in range(1000):
string_replace_method(data_string)
print('''It took the string_replace method {0} seconds to complete 1000 \
repetitions\n'''.format(time() - start))
start = time()
for i in range(1000):
iterative_transcribe_method(data_string)
print('''It took the string_replace method {0} seconds to complete 1000 \
repetitions\n'''.format(time() - start))
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.0.1')
if arguments['--compare']:
compare()
else:
main()
| true |
d122d93baa813af861b12346e82003bdc91e7d47 | Jessica-Luis001/shapes.py | /shapes.py | 1,042 | 4.46875 | 4 | from turtle import *
import math
# Name your Turtle.
marie = Turtle()
color = input("What color would you like?")
sides = input("How many sides would you like?")
steps = input("How many steps would you like?")
# Set Up your screen and starting position.
marie.penup()
setup(500,300)
x_pos = -250
y_pos = -150
marie.setposition(x_pos, y_pos)
### Write your code below:
answer = input("What color would you like?")
intanswer = int(answer)
answer = input("How many sides would you like?")
intanswer = int(answer)
marie.pendown()
marie.speed(10)
marie.pencolor(color)
def square():
marie.begin_fill()
marie.fillcolor(color)
for square in range(4):
marie.forward(50)
marie.right(90)
marie.end_fill()
print("This is a square.")
marie.penup()
square()
marie.pendown()
def large_square():
for large_square in range (4):
marie.forward(50)
marie.left(90)
marie.forward(50)
print("This is a large_square")
marie.penup()
large_square()
# Close window on click.
exitonclick()
| true |
14f15835a90bc85b84528f40622ee216d4bfd2a4 | GaloisGroupie/Nifty-Things | /custom_sort.py | 1,247 | 4.28125 | 4 | def merge_sort(inputList):
"""If the input list is length 1 or 0, just return
the list because it is already sorted"""
inputListLength = len(inputList)
if inputListLength == 0 or inputListLength == 1:
return inputList
"""If the list size is greater than 1, recursively break
it into 2 pieces and we will hit the base case of 1.
We then start merging upwards"""
return merge(merge_sort(inputList[:inputListLength//2]),
merge_sort(inputList[inputListLength//2:]))
"""Takes 2 sorted lists and combines them together to
return 1 sorted list"""
def merge(l1,l2):
l1Index = 0
l2Index = 0
#If either list is empty return the other
if len(l1) == 0:
return l2
if len(l2) == 0:
return l1
mergedSortedList = []
while True:
if l1[l1Index] <= l2[l2Index]:
mergedSortedList.append(l1[l1Index])
l1Index += 1
elif l2[l2Index] < l1[l1Index]:
mergedSortedList.append(l2[l2Index])
l2Index += 1
if not (l1Index < len(l1)):
mergedSortedList.extend(l2[l2Index:])
return mergedSortedList
elif not (l2Index < len(l2)):
mergedSortedList.extend(l1[l1Index:])
return mergedSortedList
print len(l1), l1Index, len(l2), l2Index
| true |
7fd5693cd6e035bb230eb535f4d9b0b0a5ce23bf | israel-dryer/Just-for-Fun | /mad_libs.py | 2,489 | 4.125 | 4 | # create a mad-libs | random story generator
# randomly select words to create a unique mad-libs story
from random import randint
import copy
# create a dictionary of the words of the type you will use in the story
word_dict = {
'adjective':['greedy','abrasive','grubby','groovy','rich','harsh','tasty','slow'],
'city name':['Chicago','New York','Charlotte','Indianapolis','Louisville','Denver'],
'noun':['people','map','music','dog','hamster','ball','hotdog','salad'],
'action verb':['run','fall','crawl','scurry','cry','watch','swim','jump','bounce'],
'sports noun':['ball','mit','puck','uniform','helmet','scoreboard','player'],
'place':['park','desert','forest','store','restaurant','waterfall']
}
# create a story and insert placeholders for the words you want to randomly select
story = (
"One day my {} friend and I decided to go to the {} game in {}. " +
"We really wanted to see the {} play the {}. " +
"So, we {} our {} down to the {} and bought some {}s. " +
"We got into the game and it was a lot of fun. " +
"We ate some {} {} and drank some {} {}. " +
"We had a great time! We plan to go ahead next year!"
)
# create a function that will randomly select a word from the word_dict by type of word
def get_word(type, local_dict):
''' select words based on type and then pop the selected word from the list
so that it isn't select more than once '''
words = local_dict[type]
cnt = len(words)-1 # used to set range of index
index = randint(0, cnt)
return local_dict[type].pop(index)
# create a function that will insert a random word into the story, based on word type
def create_story():
''' create a story with randomly selected words of certain type '''
local_dict = copy.deepcopy(word_dict) # deepcopy to prevent changes to word_dict
return story.format(
get_word('adjective', local_dict),
get_word('sports noun', local_dict),
get_word('city name', local_dict),
get_word('noun', local_dict),
get_word('noun', local_dict),
get_word('action verb', local_dict),
get_word('noun', local_dict),
get_word('place', local_dict),
get_word('noun', local_dict),
get_word('adjective', local_dict),
get_word('noun', local_dict),
get_word('adjective', local_dict),
get_word('noun', local_dict)
)
print("STORY 1: ")
print(create_story())
print()
print("STORY 2:")
print(create_story())
| true |
3dd09e91200b964ae1114bf6d655fcb9776816fd | EnricoFiasche/assignment1 | /scripts/target_server.py | 1,276 | 4.125 | 4 | #!/usr/bin/env python
import rospy
import random
from assignment1.srv import Target, TargetResponse
def random_target(request):
"""
Function that generates two random coordinates (x,y) given the range
(min,max)
Args:
request: The request of Target.srv
- minimum value of the random coordinate
- maximum value of the random coordinate
Returns:
Random point (x,y) between the minimum and maximum value
"""
# getting the target Response (target_x, target_y)
result = TargetResponse()
# choosing randomly the two coordinates of the target point
result.target_x = random.uniform(request.minimum, request.maximum)
result.target_y = random.uniform(request.minimum, request.maximum)
# display the random target
rospy.loginfo("Target position [%.2f,%.2f]",result.target_x,result.target_y)
return result
def main():
"""
Main function that init a node called target_server and create
a service called target, used to generate a random point
"""
rospy.init_node('target_server')
# create a service called target, type Target,
# using a function called random_target
s = rospy.Service('target',Target,random_target)
rospy.spin()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
| true |
a3af77c55562a3c70c9b1ee570086bc941b9bbee | Sidhved/Data-Structures-And-Algorithms | /Python/DS/Trees.py | 1,731 | 4.375 | 4 | #Program to traverse given tree in pre-order, in-order and post-order fashion
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = TreeNode(root)
def inorderTraversal(self, node, path):
if node:
path = self.inorderTraversal(node.left, path)
path += str(node.val) + " "
path = self.inorderTraversal(node.right, path)
return path
def preorderTraversal(self, node, path):
if node:
path += str(node.val) + " "
path = self.preorderTraversal(node.left, path)
path = self.preorderTraversal(node.right, path)
return path
def postorderTraversal(self, node, path):
if node:
path = self.postorderTraversal(node.left, path)
path = self.postorderTraversal(node.right, path)
path += str(node.val) + " "
return path
'''lets construct a binary tree as shown below to understand with help of an example
1
/ \
2 3
/ \ / \
4 5 6 7
'''
if __name__ == "__main__":
tree = Tree(1)
tree.root.left = TreeNode(2)
tree.root.right = TreeNode(3)
tree.root.left.left = TreeNode(4)
tree.root.left.right = TreeNode(5)
tree.root.right.left = TreeNode(6)
tree.root.right.left = TreeNode(7)
#In-Order Traversal : left -> root -> right
print(tree.inorderTraversal(tree.root, " "))
#Pre-order Traversal : root -> left -> right
print(tree.preorderTraversal(tree.root, " "))
#Post-order Traversal : left -> right -> root
print(tree.postorderTraversal(tree.root, " ")) | true |
c6899d11bbf0892f42b3b877bbe5f9a2a66bf757 | ben-coxon/cs01 | /sudoku_solver.py | 2,916 | 4.28125 | 4 | #!/usr/bin/python
# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.
# A valid sudoku square satisfies these
# two properties:
# 1. Each column of the square contains
# each of the whole numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the whole numbers from 1 to n exactly once.
# You may assume the the input is square and contains at
# least one row and column.
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(sud):
size = len(sud[0])
comp = []
lst = 0
a = 1
# Create list of numbers to check for
for n in sud[0]:
comp.append(a)
a += 1
# Create Vertical Numbers List
vert_list = []
n = 0
while n < size:
clist = []
for i in sud:
clist.append(i[n])
vert_list.append(clist)
n += 1
# Check horizontal numbers
while lst < size:
for i in comp:
if not i in sud[lst]:
print "\nhorizontal Fail!"
return False
lst += 1
# Check Vertical Numbers
lst = 0
while lst < size:
for i in comp:
if not i in vert_list[lst]:
print "\nvertical Fail!"
return False
lst += 1
print "\nThat's Sudoku!"
return True
### HERE IS THE SOLUTION FROM UDACITY, which is MUCH better!!!
def check_sudoku(p):
n = len(p) #extract size of grid
digit = 1 # start with 1
while digit <= n: # go through each digit
i = 0
while i < n: # go through each row and column
row_count = 0
col_count = 0
j = 0
while j < n: #for each entry in ith row/column
if p[i][j] == digit:
row_count += 1
if p[j][i] == digit:
col_count += 1
j += 1
if row_count != 1 or col_count != 1:
return False
i += 1 # next row/column
digit += 1 # next digit
return True # Sudoku was correct!
| true |
5421ce966d6b60ec40f9e43ece33809fe9576c84 | Ricky842/Shorts | /Movies.py | 1,404 | 4.40625 | 4 | #Empty list and dictionaries to store data for the movies and their ratings
movies = []
movie_dict = {'movie': '', 'rating': 0}
#Check validity of movie rating
def check_entry(rating):
while rating.isnumeric() is True:
movie_rating = int(rating)
if(movie_rating > 10 or movie_rating < 1):
rating = input("Please enter a rating between 1 and 10: ")
movie_rating = rating
else:
return movie_rating
movie_rating = input("Please enter an Integer between 1 and 10: ")
movie_rating = check_entry(movie_rating)
return movie_rating
#Calculates the highest rated movie
def rating():
numMovies = int(input("How many movies have you watched this year? "))
while len(movies) < numMovies:
movie_name = input("Please enter the name of the movie: ")
movie_rating = input(f"Please enter the rating of {movie_name} between 1 and 10: ")
movie_rating = check_entry(movie_rating)
movie_rating = int(movie_rating)
movie_dict = {'movie': movie_name, 'rating':movie_rating}
movies.append(movie_dict)
highest_rating = 0
for movie in movies:
if movie['rating'] > highest_rating:
highest_rating = movie['rating']
favMovie = movie['movie']
print(f"Your favorite movie was {favMovie} with a rating of {highest_rating}")
rating()
#Initial commit to Git | true |
5ed55cdbe3082ebcd87c8cc5ab40defff9542932 | anandavelum/RestApiCourse | /RestfulFlaskSection5/createdb.py | 605 | 4.125 | 4 | import sqlite3
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute("create table if not exists users (id INTEGER PRIMARY KEY,name text,password text)")
users = [(1, "Anand", "Anand"), (2, "Ramya", "Ramya")]
cursor.executemany("insert into users values (?,?,?)", users)
rows = list(cursor.execute("select * from users"))
print(rows)
connection.commit()
connection.close()
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute("Create table if not exists items(item_name primary key,price real)")
connection.commit()
connection.close() | true |
72994802e57e471f8cc14515072749eb35d79037 | LadyKerr/cs-guided-project-array-string-manipulation | /src/class.py | 657 | 4.21875 | 4 | # Immutable variables: ints; O(1) [to find new location for them is cheap]; string
# num = 1
# print(id(num))
# num = 100
# print(id(num))
# num2 = num
# print(num2 is num)
# num2 = 2
# print(num)
# print(num2 is num)
# Mutable Variables: arrays, dictionaries, class instances
arr = [1,2,3] #arrays are mutable
print(id(arr))
arr2 = arr
print(arr2 is arr)
arr2 = ['a', 'b'] # now assigning arr2 to something so this is a new array
print(arr)
arr2.append(4)
print(arr) # will return the original arr since arr2 was reassigned
# Mutable - Dictionaries
my_dict = {'hello': 'world'}
my_dict2 = my_dict
my_dict2['new_key'] = 'new value'
print(my_dict)
| true |
8c902651f21a4c5d25b384a3f73922c06eba74aa | gabefreedman/music-rec | /dates.py | 2,624 | 4.4375 | 4 | #!/usr/bin/env python
"""This module defines functions for manipulating and formatting date
and datetime objects.
"""
from datetime import timedelta
def get_month(today):
"""Format datetime to string variable of month name.
Takes in `today` and extracts the full month
name. The name is returned in all lowercase so
as to match the name of the URL.
Parameters
----------
today : datetime object
Returns
-------
month : str
Full name month extracted from datetime input.
"""
month = today.strftime('%B').lower()
return month
def get_previous_month(today):
"""Get full name of last month given datetime object.
Takes in `today` and finds the date of the last
day of the previous month. Formatted so as to
match the URL.
Parameters
----------
today : datetime object
Returns
-------
prev_month : str
Full name of last month extracted from datetime
input.
"""
first_of_month = today.replace(day=1)
prev = first_of_month - timedelta(days=1)
prev_month = prev.strftime('%B').lower()
return prev_month
def get_recent_monday(today):
"""Find the date of the nearest Monday.
Takes in `today` and and extracts the full month
name. The name is returned in all lowercase so
as to match the name of the URL.
Parameters
----------
today : datetime object
Returns
-------
recent_monday : date object
Date of nearest Monday to input datetime
"""
days_ahead = today.weekday()
if today.weekday() == 0:
recent_monday = today
elif today.weekday() <= 4:
recent_monday = today - timedelta(days=days_ahead)
else:
days_behind = 7 - days_ahead
recent_monday = today + timedelta(days=days_behind)
return recent_monday
def get_last_week_dates(today):
"""Retrieve the dates of the past 8 days.
Generates a list of dates in {month#}/{year#}
format from the past Monday to nearest Monday, inclusive.
Merges with full month name to form tuples.
Parameters
----------
today : datetime object
Returns
-------
full_week : list of 2-tuples
2-tuple of the form: (weekdate, full month name)
"""
week_end = get_recent_monday(today)
week_start = week_end - timedelta(days=7)
week_dates = [week_start + timedelta(days=i) for i in range(8)]
week_dates_fmt = [day.strftime('%#m/%#d') for day in week_dates]
months = [get_month(day) for day in week_dates]
full_week = list(zip(week_dates_fmt, months))
return full_week
| true |
3b2d9f12bcfee600b30eeb27e34788ae5c8ed4f9 | jc345932/sp53 | /workshopP1/shippingCalculator.py | 368 | 4.1875 | 4 | item =int(input("How many items:"))
while item < 0:
print("Invalid number of items!")
item = int(input("How many items:"))
cost =int(input("How much for item:"))
while cost < 0:
print("Invalid prices")
cost = int(input("How much for item:"))
total = cost * item
if total > 100:
total = total * 0.9
else:
total = total
print("Total is:$", total) | true |
1f45bdd57c3e4381ff05c668fadcb38bcaf589f8 | jc345932/sp53 | /workshopP4/numList.py | 322 | 4.15625 | 4 | list = []
for i in range(5):
num = int(input("Enter the number: "))
list.append(num)
print("The first number is: ",list[0])
print("the last number is: ", list[-1])
print("the smallest number is: ", min(list))
print("the largest number is: ",max(list))
print("the average of the numbers is: ",sum(list)/len(list))
| true |
c7443b333e6f8b64ca5e5d55c3cdaf0b64c8e291 | Necrolord/LPI-Course-Homework-Python-Homework- | /Exercise2-2.py | 1,123 | 4.53125 | 5 | #!/bin/usr/env python3.6
# This method is for reading the strings
def Input_Str():
x = str(input("Enter a String: "))
return x
# This method is for reading the number.
def Input_Num():
num = int(input("Enter a number between 1 and 3 included: "))
if ((num < 1) or (num > 3)):
print('The number you entered is not valid. Please enter another one.')
else:
return num
# This method comapres the length of the 2 strings.
def Compare_Str(str1,str2):
if len(str1) > len(str2):
print('The string ' , str1, 'Contains more letters than', str2)
elif len(2) > len(strr1):
print('The string' , str2, 'Contains more letters than', str1)
else:
print('Both strings contain the same amount of letters')
# This method is for checking if one string is inside the other string.
def Check_Str(str1,str2):
if str1 in str2:
print(str1, 'is inside' ,str2)
elif str2 in str1:
print(str2, 'is inside' ,str1)
else:
print(z, 'not inside at all', y)
num=Input_Num()
str1=Input_Str()
str2=Input_Str()
Compare_Str(str1,str2)
Check_Str(str1,str2)
| true |
23c4b91775a740a59ad4970b20935d3cfb50e768 | shafaypro/AndreBourque | /assignment1/mood2.py | 2,454 | 4.53125 | 5 | mood = input('Enter the mood of yours (angry,sad,happy,excited)') # we are taking an input in the form of a string
"""
if mood == "angry": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "happy": # ANGRY
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "sad":
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "excited":
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
"""
# if else statment used for multiple checking ---> (nested if-else condition)
if mood == "angry": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry
if mood == "sad": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry and the mood is not sad
if mood == "happy": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry nor the mood is sad nor the mood is happy -->
if mood == "excited": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry) | true |
30db7f2a89d91bdd140df331d0b039d896803ee1 | franciscomunoz/pyAlgoBook | /chap4-Recursion/C-4.19.py | 1,890 | 4.4375 | 4 | """Function that places even numbers before odd
if returns are removed in the else condition, the recursion
tree becomes messy as shown :
(0, 6, [2, 3, 5, 7, 9, 4, 8])
(1, 6, [2, 3, 5, 7, 9, 4, 8])
(2, 5, [2, 8, 5, 7, 9, 4, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(2, 5, [2, 8, 4, 7, 9, 5, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(1, 5, [2, 8, 4, 7, 9, 5, 3])
(2, 4, [2, 8, 4, 7, 9, 5, 3])
(3, 3, [2, 8, 4, 7, 9, 5, 3])
(4, 2, [2, 8, 4, 7, 9, 5, 3])
[2, 8, 4, 7, 9, 5, 3]
with the return statements in place gives a shorter recursion tree
(0, 6, [2, 3, 5, 7, 9, 4, 8])
(1, 6, [2, 3, 5, 7, 9, 4, 8])
(2, 5, [2, 8, 5, 7, 9, 4, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
[2, 8, 4, 7, 9, 5, 3]
"""
def move_even_odd(data,start,stop):
#print(start,stop,data)
if start > stop:
return
else:
if data[start] % 2 == 1 and data[stop] % 2 == 0:
data[start],data[stop] = data[stop],data[start]
move_even_odd(data,start+1,stop-1)
return
if data[start] % 2 == 0 and data[stop] % 2 == 0:
move_even_odd(data,start+1,stop)
return
if data[start] % 2 == 1 and data[stop] % 2 == 1:
move_even_odd(data,start,stop-1)
return
move_even_odd(data,start+1,stop-1)
if __name__ == '__main__':
tests=[]
tests.append([2,3,5,7,9,4,8])
tests.append([0,0,0,0,0,0,0])
tests.append([2,2,2,2,2,2,2])
tests.append([3,3,3,3,3,3,3])
tests.append([9,8,7,6,5,4,3,2,1])
tests.append([0,1,2,3,4,5,6,7,8,9])
tests.append([1,1,1,3,4,5,6,9,9,9])
for i in range(len(tests)):
move_even_odd(tests[i],0,len(tests[i])-1)
print(tests[i])
| true |
7981d8de44f4d1aaaab8aec30ea50b9fb1a87c48 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/C-5.13.py | 1,095 | 4.125 | 4 | """The output illustrates how the list capacity is changing
during append operations. The key of this exercise is to
observe how the capacity changes when inserting data to an
an array that doesn't start at growing from size "0". We
use two arrays, the original from 5.1 and another starting
to grow from a different value. Both arrays grow by the same
values
"""
import sys # provides getsizeof function
if __name__ == '__main__':
try:
n = int(sys.argv[1])
except:
n = 100
initial_size = 1000
data = []
data_init_size = [] * initial_size
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
a_l = len(data_init_size) + initial_size
b_l = sys.getsizeof(data_init_size)
print("Reference : Length: {0:3d}; Size in bytes: {1:4d}" \
" | | | Measured Array {2:3d}+ Length: {3:3d}; Size in bytes: {4:4d}:"\
.format(a,b,initial_size,a_l,b_l))
data_init_size.append(None)
data.append(None) # increase length by one
| true |
efd406bd5d1378e7d1d38e2329d5039fdd069730 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/P-5.35.py | 2,019 | 4.25 | 4 | """Implement a class , Substitution Cipher, with a constructor that takes a string
with 26 uppercase letters in an arbitrary order and uses that for the forward
mapping for encryption (akin to the self._forward string in our Caesar Cipher
class ) you should derive the backward mapping from the forward version"""
import string
from random import shuffle
class SubstitutionCipher:
"""Class for doing encryption and decryption using a Caesar cipher."""
def __init__(self, forward):
"""Construct Caesar cipher by calculating the decoder when encoder is given"""
decoder = [None] * 26
self._forward = (''.join(forward)) # will store as string
for i in range(len(forward)):
i_decoder = ord(forward[i]) - ord('A')
decoder[i_decoder] = chr( i + ord('A'))
self._backward = (''.join(decoder))
def encrypt(self, message):
"""Return string representing encripted message."""
return self._transform(message, self._forward)
def decrypt(self, secret):
"""Return decrypted message given encrypted secret."""
return self._transform(secret, self._backward)
def _transform(self, original, code):
"""Utility to perform transformation based on given code string."""
msg = list(original)
for k in range(len(msg)):
if msg[k].isupper():
j = ord(msg[k]) - ord('A') # index from 0 to 25
msg[k] = code[j] # replace this character
return ''.join(msg)
if __name__ == '__main__':
alpha_list = list(string.ascii_uppercase)
shuffle(alpha_list)
"""The encoding is donde using a random permutation of the alphabet and the
decoding array is calulated in the class ctor"""
cipher = SubstitutionCipher(alpha_list)
message = "THE Eagle IS IN PLAY; MEET AT JOE'S."
coded = cipher.encrypt(message)
print('Secret: ', coded)
answer = cipher.decrypt(coded)
print('Message:', answer)
| true |
7ed258a07a00f7092741efd7b9cef6dc69cdc4b8 | Marlon-Poddalgoda/ICS3U-Unit3-06-Python | /guessing_game.py | 980 | 4.25 | 4 | #!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program is an updated guessing game
import random
def main():
# this function compares an integer to a random number
print("Today we will play a guessing game.")
# random number generation
random_number = random.randint(0, 9)
# input
user_guess = input("Enter a number between 0-9: ")
print("")
# process
try:
user_guess_int = int(user_guess)
if user_guess_int == random_number:
# output
print("Correct! {} was the right answer."
.format(random_number))
else:
# output
print("Incorrect, {} was the right answer."
.format(random_number))
except Exception:
# output
print("That's not a number! Try again.")
finally:
# output
print("")
print("Thanks for playing!")
if __name__ == "__main__":
main()
| true |
b9862bf717d958e138ffeb6918d21f5fe164a780 | Lutshke/Python-Tutorial | /variables.py | 882 | 4.40625 | 4 | "This is where i will show you the basics ok?"
# to add comments to code you need to start with a hashtag like i did
# there are a few types of numbers
# there are "ints" and "floats"
# an int is a full number (10, 45, 100..)
# an float is (0.1, 1,5...)
# an int or float are variables so they save values
int1 = 1
float1 = 1.5
# to save text you use strings
# a string needs to be between " " or ' '
string1 = "This is an example"
# to save a value which is true or false we use booleans (bool)
bool1 = True
bool2 = False
# to store a lot of items in 1 variable we use lists, dicts or tuples
# but nobody i know uses tuples
List1 = ["String1", "String2"]
Dict1 = {"name" : "paul", "lastname" : "peters"} # be sure to use the right symboles
# you can also save multiple dicts in a list
"those are the basic datatypes of python"
| true |
231d905f24fa551c060748793eee07c9ce563edd | deepaparangi80/Github_pycode | /sum_numb.py | 254 | 4.21875 | 4 | # program to print sum of 1 to n
n = int(input('Enter n value'))
print('entered value',n)
sum = 0
for i in range(1,n+1):
'''print(i)'''
sum = sum + i
print('total sum of 1 to {} is {}'.format(n,sum))
'''print (range(1,n))''' | true |
d778b446a64b2a12c3cd521aa611ca71937d2381 | JYDP02/DSA_Notebook | /Searching/python/breadth_first_search.py | 1,263 | 4.40625 | 4 | # Python3 Program to print BFS traversal
from collections import defaultdict
class Graph:
# Constructor
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (len(self.graph))
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print(s, end=" ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
# Create a graph
grph = Graph()
grph.addEdge(0, 1)
grph.addEdge(0, 2)
grph.addEdge(1, 2)
grph.addEdge(2, 0)
grph.addEdge(2, 3)
grph.addEdge(3, 3)
print("Following is Breadth First Traversal"
" (starting from vertex 2)")
grph.BFS(2) | true |
8bf11d623899a8640bd99dc352518a2c562c9e87 | lingaraj281/Lingaraj_task2 | /q3.py | 317 | 4.15625 | 4 | print("Enter a text")
a=str(input())
letter = input("Enter a letter\n")
letter_count = 0
for x in a:
if x == letter:
letter_count = letter_count + 1
num_of_letters = 0
for x in a:
if(x != " "):
num_of_letters = num_of_letters + 1
frequency = (letter_count/num_of_letters)*100
print(frequency) | true |
2e7266efc9d0d28413d9b28053d49830f6c85834 | JatinR05/Python-3-basics-series | /17. appending to a file.py | 864 | 4.40625 | 4 | '''
Alright, so now we get to appending a file in python. I will just state again
that writing will clear the file and write to it just the data you specify in
the write operation. Appending will simply take what was already there, and add
to it.
That said, when you actually go to add to the file, you will still use
.write... you only specify that you will be appending instead of writing
when you open the file and specify your intentions.
'''
# so here, generally it can be a good idea to start with a newline, since
# otherwise it will append data on the same line as the file left off.
# you might want that, but I'll use a new line.
# another option used is to first append just a simple newline
# then append what you want.
appendMe = '\nNew bit of information'
appendFile = open('exampleFile.txt','a')
appendFile.write(appendMe)
appendFile.close()
| true |
a429e619657d092618f27c24cd0a30abfbda9e3c | JatinR05/Python-3-basics-series | /9. if elif else.py | 972 | 4.34375 | 4 | '''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to check multiple ifs?
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
Instead, you can use what is called the "elif" here in python... which is short for "else if"
'''
x = 5
y = 10
z = 22
# first run the default like this, then
# change the x > y to x < y...
# then change both of these to an ==
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')
else:
print('if and elif never ran...')
| true |
4ea711632c6a2bab41d0810384552a220d35eb7a | joe-bollinger/python-projects | /tip_calculator/tip_calculator.py | 1,703 | 4.25 | 4 | print('Tip Calculator')
print()
# TODO: Get the cost of the meal and print the results
get_cost = input('How much did your meal cost? (i.e. 45.67) ')
# Convert the input string to a float
get_cost = float(get_cost)
print(f"Food Cost: ${format(get_cost, '.2f')}")
# TODO: Calculate 10% sales tax for the bill and print the results.
def calc_tax():
return round(get_cost * 1.10, 2)
print(f"Your bill after tax: ${format(calc_tax(), '.2f')}")
print()
# TODO: Get the amount the customer would like to pay for a tip and print the results.
get_tip = input(
'What percentage of the bill would you like to pay as a tip? Please type in a number (i.e. 15) ')
# Convert the input string to a float.
get_tip = float(get_tip)
print(f'Customer wants to tip: {get_tip}%')
# TODO: Calculate the tip amount and print the results.
def calc_tip(tip):
if tip <= 0:
tip = 0
return round(get_cost * ((tip / 100)), 2)
else:
return round(get_cost * ((tip / 100)), 2)
print(f'Tip amount: ${calc_tip(get_tip)}')
def total_amount():
return calc_tip(get_tip) + calc_tax()
print(f'Total cost after tax and tip: ${total_amount()}')
print()
# TODO: Get number of people splitting the bill
get_diners = input('How many people will be splitting the bill? (i.e. 4) ')
# Convert the input string to a integer
get_diners = int(get_diners)
print('Diners:', get_diners)
# TODO: Calculate how much each person should pay (you can assume all people will split the bill evenly)
def split_amount(amount):
if amount <= 0:
amount = 1
return round(total_amount() / amount, 2)
print()
print(f"Each person should pay: ${format(split_amount(get_diners), '.2f')}")
| true |
f6717518f0fc59f794607f32ae3b2c33f8f88356 | sohel2178/Crawler | /file_test.py | 1,983 | 4.15625 | 4 |
# f= open('test.txt','r')
# print(f.mode)
# f.close()
# Context Manager
# with open('test.txt','r') as f:
# Read all the Content
# f_content = f.read()
# There is another method to read a file line by line
# f_content = f.readlines()
# print(f_content)
# Another way to read All of the Lines. Better Method then Above
# for line in f:
# print(line,end='')
# More Control Method to Read File
# if we pass 100 as an argument then it read 100 character from the file
# f_content = f.read(20)
# print(f_content,end='')
# f_content = f.read(20)
# print(f_content,end='')
# f_content = f.read(20)
# print(f_content,end='')
# size_to_read = 20
# f_content = f.read(size_to_read)
# If we reached the end of the file length of the f_content will be zero
# while len(f_content)>0:
# print(f_content,end='***')
# # print(f.tell())
# # print(f.seek())
# f_content = f.read(size_to_read)
# !!!! Wrinting a File !!!
# with open('test2.txt','w') as f:
# f.write('Hey Sohel How Are You')
# f.seek(0)
# f.write('Hey Sohel How Are You')
# f.seek(0)
# f.write('Hey Sohel How Are You')
# f.seek(0)
# !!! Copying Content of a File !!!
# with open('test.txt','r') as fr:
# with open('test_copy.txt','w') as fw:
# for line in fr:
# fw.write(line)
# !!! Copying Image File !!!
# with open('mobi.png','rb') as fr:
# with open('mobi_copy.png','wb') as fw:
# for line in fr:
# print(line)
# !!! Print Binary File and Examine !!!
# with open('mobi.png','rb') as fr:
# print(fr.read())
# !!! Read and Write Chunk by Chunk !!!
with open('mobi.png','rb') as fr:
chunk_size = 4096
with open('mobi_copy.png','wb') as fw:
chunk_data = fr.read(chunk_size)
while len(chunk_data) > 0:
fw.write(chunk_data)
chunk_data = fr.read(chunk_size)
| true |
80e00f4c0f308f8c361a884b08c56b60f3e6d4b3 | ishan5886/Python-Learning | /Decorators.py | 1,020 | 4.21875 | 4 | #Decorators - Function that takes function as an argument, performs some functionality and returns another function
# def outer_function(msg):
# def inner_function():
# print(msg)
# return inner_function
# def decorator_function(original_function):
# def wrapper_function():
# return original_function()
# return wrapper_function
#
# @decorator_function # Same as display = decorator_function(display)
#
# def display():
# print('Display function ran')
#
#
# display()
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function # Same as display = decorator_function(display)\
def display():
print('Display function ran')
@decorator_function # Same as display_args = decorator_function(display_args)\
def display_args(name, age):
print('Display function ran with arguments ({}, {})'.format(name, age))
display()
display_args('Ishan', 95) | true |
661627a12dc195ee9a2c9b26fc340d7e0a2099be | LavanyaBashyagaru/letsupgrade- | /day3assigment.py | 539 | 4.21875 | 4 | '''You all are pilots, you have to land a plane,
the altitude required for landing a plane is 1000ft,
if it is less than that tell pilot to land the plane,
or it is more than that but less than 5000 ft
ask the pilot to come down to 1000 ft,
else if it is more than 5000ft ask the pilot togo around and try later'''
altitude=int(input("ft:"))
if(altitude<=1000):
print("Land the plane")
elif(altitude>1000 and altitude<5000):
print("Come down to 1000ft")
elif(altitude>5000):
print("Go around and try later")
| true |
953b47f0be6a1c46f7c75b888dccf5d9e484f920 | MarsForever/python_kids | /7-1.py | 316 | 4.125 | 4 | num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 < num2:
print (num1, "is less than",num2)
if num1 > num2:
print (num2, "is more than",num2)
if num1 == num2:
print (num1,"is equal to",num2)
if num1 != num2:
print (num1,"is not equal to", num2)
| true |
6461becb3ef2198b34feba0797459c22ec886e4c | OrSGar/Learning-Python | /FileIO/FileIO.py | 2,953 | 4.40625 | 4 | # Exercise 95
# In colts solution, he first read the contents of the first file with a with
# He the used another with and wrote to the new file
def copy(file1, file2):
"""
Copy contents of one file to another
:param file1: Path of file to be copied
:param file2: Path of destination file
"""
destination = open(file2, "w")
with open(file1, "r") as source:
destination.write(source.read())
destination.close()
# Exercise 96
# In Colts code, he didnt save the reverse - He just reversed it when we passed it in
def copy_and_reverse(file1, file2):
"""
Copy contents of a file to another in reverse
:param file1: Path of file ot be copied
:param file2: Path of destination file
"""
with open(file1, "r") as source:
data = source.read()
with open(file2, "w") as destination:
reverse_data = data[::-1]
destination.write(reverse_data)
# Exercise 97
def statistics_2(file):
"""
Print number of lines, words, and characters in a file
:param file: Path of file
"""
with open(file) as source:
lines = source.readlines()
return {"lines": len(lines),
"words": sum(len(line.split(" ")) for line in lines),
# Split every line on a space and count how many elements there are
"characters": sum(len(line) for line in lines)} # Count number of chars in each line
def statistics(file):
""" My original version of statistics_2 """
num_lines = 0
num_char = 0
num_words = 1
with open(file) as source:
line = source.readlines()
num_lines = len(line)
source.seek(0)
data = source.read()
num_char = len(data)
for char in data:
if char == " ":
num_words += 1
return {"lines": num_lines, "words": num_words, "characters": num_char}
# Exercise 98
# In Colts implementation, he just read the whole thing and replaced it
def find_and_replace(file, target, replacement):
"""
Find and replace a target word in a file
:param file: Path to the file
:param target: Word to be replaced
:param replacement: Replacement word
"""
with open(file, "r+") as source:
for line in source:
print(line)
if line == "":
break
elif line.replace(target, replacement) != line:
source.write(line.replace(target, replacement))
def f_n_r(file, target, replacement):
""" Another version of find_and_replace """
with open(file, "r+") as source:
text = file.read()
new_text = text.replace(target, replacement)
file.seek(0)
file.write(new_text)
file.truncate() # Delete everything after a certain position
find_and_replace("fileio.txt", "Orlando", "Ligma")
copy("fileio.txt", "fileio_copy.txt")
copy_and_reverse("fileio.txt", "fileio_copy.txt")
print(statistics_2("fileio.txt"))
| true |
60ce089cbbc612632e6e249227e3cac374e59ad1 | MNJetter/aly_python_study | /diceroller.py | 1,396 | 4.15625 | 4 | ##################################################
## Begin DICEROLLER. ##
##################################################
## This script is a d20-style dice roller. It ##
## requires the user to input numbers for a ##
## multiplier, dice type, and modifier, and ##
## displays relevant information on the screen, ##
## including the result of each roll. ##
##################################################
## (c) 2015 Aly Woolfrey ##
##################################################
import random
random.seed()
rollnums = []
def roll_the_dice(d_mult, d_type, d_mod):
print "Rolling %dd%d + %d." % (d_mult, d_type, d_mod)
while d_mult > 0:
rollnums.append(random.randint(1, d_type))
d_mult -= 1
totalroll = sum(rollnums)
print "Your raw rolls are: %s" % (rollnums)
print "Your total unmodified roll is: %d" % (totalroll)
print "Your final number is %d" % (totalroll + d_mod)
mult_num = int(raw_input("Input multiplier (_DX + X): "))
type_num = int(raw_input("Input dice type (XD_ + X): "))
mod_num = int(raw_input("Input your modifier. Type 0 if there is no modifier. (XDX + _): "))
roll_the_dice(mult_num, type_num, mod_num)
##################################################
## End DICEROLLER. ##
##################################################
| true |
a425af412c404ebbef4e634ce335c58b75b7cee1 | RhettWimmer/Scripting-for-Animation-and-Games-DGM-3670- | /Python Assignments/scripts(old)2/Calculator.py | 2,452 | 4.21875 | 4 | '''
Enter a list of values for the calculator to solve in "Values"
Enter a value in to "Power" to calculate the power of "Values"
Define "userInput" to tell the calculator what function to solve for.
1 = Add
2 = Subtract
3 = Multiply
4 = Divide
5 = Power
6 = Mean
7 = Median
8 = Mode
'''
import maya.cmds as mc
Values = [1,10,50,50,100]
Power = 3
class Calculator:
def __init__(self):
pass
# Addition input 1 #
def Add(self, Vals):
total = 0
for i in Vals:
total += i
print 'Adding ' + str(Values) + ' = '
print total
return total
# Subtraction input 2#
def Sub(self, Vals):
total = Vals[0]
for i in Vals[1:]:
total -= i
print 'Subtracting ' + str(Values) + ' = '
print total
return total
# Multiplication input 3 #
def Multi(self, Vals):
total = 1
for i in Vals:
total *= i
print 'Multiplying ' + str(Values) + ' = '
print total
return total
# Division input 4 #
def Divi(self, Vals):
total = Vals[0]
for i in Vals[1:]:
total /= i
print 'Dividing ' + str(Values) + ' = '
print total
return total
# Power input 5#
def Pow(self, Vals, PowerVal):
import math
print 'The powers of ' + str(Values) + " to the power of " + str(Power) + ' = '
for i in Vals:
print math.pow(i, PowerVal)
# Mean input 6 #
def Mean(self, Vals):
import statistics
total = Vals
print 'The mean of ' + str(Values) + ' = '
print statistics.mean(total)
return statistics.mean(total)
# Median input 7 #
def Median(self, Vals):
import statistics
total = Vals
print 'The median of ' + str(Values) + ' = '
print statistics.median(total)
return statistics.median(total)
# Mode input 8 #
def Mode(self, Vals):
import statistics
total = Vals
print 'The mode of ' + str(Values) + ' = '
print statistics.mode(total)
return statistics.mode(total)
calc = Calculator()
calc.Add(Values)
calc.Sub(Values)
calc.Multi(Values)
calc.Divi(Values)
calc.Pow(Values, Power)
calc.Mean(Values)
calc.Median(Values)
calc.Mode(Values) | true |
db95ed4eccce222cea4b4326ab5e4586f2916ac3 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /17_mode/mode.py | 856 | 4.28125 | 4 | def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
2
"""
# mode_out will hold the number that occurred the most
mode_out = ""
# greatest_frequency will hold the largest total times a number occured.
greatest_frequency = 0
num_frequency = {num: 0 for num in nums}
for num in nums:
num_frequency[num] += 1
# did the amount of times num occur exceed the amount in greatest_frequency?
if (num_frequency[num] >= greatest_frequency):
# yes, we have a new most common number
mode_out = num
return mode_out
| true |
90707b2e54d15dcf7ecdcf4286a2409b271968a4 | ibrahimuslu/udacity-p0 | /Task4.py | 1,555 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
count =0
textPhoneDict = {}
callingPhoneDict = {}
receiveingPhoneDict = {}
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
for text in texts:
if text[0] not in textPhoneDict :
textPhoneDict[text[0]]=1
else:
textPhoneDict[text[0]]+=1
if text[1] not in textPhoneDict:
textPhoneDict[text[1]]=1
else:
textPhoneDict[text[1]]+=1
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
for call in calls:
if call[0] not in callingPhoneDict:
callingPhoneDict[call[0]]=1
else:
callingPhoneDict[call[0]]+=1
if call[1] not in receiveingPhoneDict:
receiveingPhoneDict[call[1]]=1
else:
receiveingPhoneDict[call[1]]+=1
print("These numbers could be telemarketers: ")
for phone in sorted(callingPhoneDict):
if phone not in receiveingPhoneDict and phone not in textPhoneDict:
print(phone)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
| true |
35c53757e5669ad24a4b61aa6878b722de8636e1 | martinee300/Python-Code-Martinee300 | /w3resource/Python Numpy/Qn3_PythonNumpy_CreateReshapeMatrix.py | 508 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 14:24:51 2018
@author: dsiow
"""
# =============================================================================
# 3. Create a 3x3 matrix with values ranging from 2 to 10.
# Expected Output:
# [[ 2 3 4]
# [ 5 6 7]
# [ 8 9 10]]
# =============================================================================
import numpy as np
listing = list(range(2,11))
# Use the reshape method to change it into a 3x3 matrix
array = np.array(listing).reshape(3,3)
| true |
cb0ae7e3a71550c42711351027a21917668560ba | robinrob/python | /practice/print_reverse.py | 441 | 4.125 | 4 | #!/usr/bin/env python
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def ReversePrint(head):
if head is not None:
if head.next is not None:
ReversePrint(head.next)
print head.data
head = Node(data=0)
one = Node(data=1)
head.next = one
two = Node(data=2)
one.next = two
three = Node(data=3)
two.next = three
ReversePrint(head) | true |
237a9ccbbfa346ff3956f90df5f52af4272b9291 | robinrob/python | /practice/postorder_traversal.py | 727 | 4.1875 | 4 | #!/usr/bin/env python
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
"""
lr = Node(data=4)
ll = Node(data=1)
l = Node(data=5, left=ll, right=lr)
rl = Node(data=6)
r = Node(data=2, left=rl)
tree = Node(data=3, left=l, right=r)
import sys
def postOrder(root):
#Write your code here
node = root
if node.left is not None:
postOrder(node.left)
if node.right is not None:
postOrder(node.right)
sys.stdout.write(str(node.data) + ' ')
postOrder(tree) | true |
1c047ac76bcb2fa3e902d3f5b6e0e145cc866c5d | KyleLawson16/mis3640 | /session02/calc.py | 871 | 4.21875 | 4 | '''
Exercise 1
'''
import math
# 1.
radius = 5
volume = (4 / 3 * math.pi * (radius**3))
print(f'1. The volume of a sphere with radius {radius} is {round(volume, 2)} units cubed.')
# 2.
price = 24.95
discount = 0.4
copies = 60
cost = (price * discount) + 3 + (0.75 * (copies - 1))
print(f'2. The total wholesale cost of {copies} copies is ${round(cost, 2)}.')
# 3.
easy_pace = 8 + (15/60)
tempo = 7 + (12/60)
total_time = (easy_pace * 2) + (tempo * 3)
start_time_min = (6*60) + 52
end_time_min = start_time_min + total_time
end_time = '{hours}:{minutes}'.format(hours=(round(end_time_min // 60)), minutes=(round(end_time_min % 60)))
print(f'3. You will get home for breakfast at {end_time} am.')
# 4.
start = 82
end = 89
difference = end - start
percent_change = difference / start * 100
print('4. Your average grade rose by {:04.1f}%'.format(percent_change))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.