blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
3865e404fdf198c9b8a6cb674783aa58af2c8539
|
rehul29/QuestionOfTheDay
|
/Question8.py
| 561
| 4.125
| 4
|
# minimum number of steps to move in a 2D grid.
class Grid:
def __init__(self, arr):
self.arr = arr
def find_minimum_steps(self):
res = 0
for i in range(0, len(self.arr)-1):
res = res + self.min_of_two(self.arr[i], self.arr[i+1])
print("Min Steps: {}".format(res))
def min_of_two(self, first, second):
x1, y1 = first
x2, y2 = second
return max(abs(x2-x1), abs(y2-y1))
if __name__ == "__main__":
arr = [(0,0),(1,1),(1,2)]
sol = Grid(arr)
sol.find_minimum_steps()
| true
|
b24b8cb5a6a7200c99bc112b9d5812eb9726bc60
|
ywtail/leetcode
|
/35_58.py
| 616
| 4.125
| 4
|
# coding:utf-8
# Length of Last WordLength of Last Word 最后一个词的长度
s=raw_input()
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
t=s.split()
if len(t)==0:
return 0
else:
return len(t[-1])
print lengthOfLastWord(s)
"""
题目:
给定一个字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个字的长度。
如果最后一个字不存在,返回0。
注意:单词定义为仅由非空格字符组成的字符序列。
例如,
给出s =“Hello World”,
返回5。
注意:仅当s仅由空格组成时返回0,‘a ’返回1
"""
| false
|
5b13b24acbbc286305aa9cda7adc9afd7709104f
|
sjNT/checkio
|
/Elementary/Fizz Buzz.py
| 1,288
| 4.15625
| 4
|
"""
"Fizz buzz" это игра со словами, с помощью которой мы будем учить наших роботов делению. Давайте обучим компьютер.
Вы должны написать функцию, которая принимает положительное целое число и возвращает:
"Fizz Buzz", если число делится на 3 и 5;
"Fizz", если число делится на 3;
"Buzz", если число делится на 5;
"""
def checkio(number: int) -> str:
msg = ''
if number % 3 == 0:
msg += 'Fizz '
if number % 5 == 0:
msg += 'Buzz'
elif msg == '':
msg = str(number)
return msg.rstrip()
# Some hints:
# Convert a number in the string with str(n)
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(checkio(15))
assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
assert checkio(6) == "Fizz", "6 is divisible by 3"
assert checkio(5) == "Buzz", "5 is divisible by 5"
assert checkio(7) == "7", "7 is not divisible by 3 or 5"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
| false
|
1e30e88c79c0941f93ce4239a74eb38d4dcd02f5
|
dtekluva/first_repo
|
/datastructures/ato_text.py
| 1,616
| 4.125
| 4
|
# sentence = input("Please enter your sentence \nWith dashes denoting blank points :\n ")
# replacements = input("Please enter your replacements in order\nseperated by commas :\n ")
# ## SPLIT SENTENCE INTO WORDS
# sentence_words = sentence.split(" ")
# print(sentence_words)
# ## GET CORRESPONDING REPLACEMENTS
# replacement_words = replacements.split(',')
# replacement_index = 0
# # search and replace dashes with replacement words
# for i in range(len(sentence_words)):
# ## FIND DASHES IN WORDS OF GIVEN SENTENCE
# if sentence_words[i].find("_") != -1:
# ## REPLACE DASHES WITH CORRESPONDING REPLACEMENT WORDS.
# sentence_words[i] = sentence_words[i].replace("_", replacement_words[replacement_index])
# replacement_index+=1
# full_sentence = " ".join(sentence_words)
# print(full_sentence)
# prices = [200, 300, 400, 213, 32 ]
# marked = 1.5
# for i in range(len(prices)):
# prices[i] = prices[i]*marked
# print(prices)
x = 20
# def do_somthing():
# global x
# x = 30
# print(x)
# return 23
# do_somthing()
# print(x)
# def numbers(one, two, three):
# print("One : ",one, "Two : ", two, "Three : ", three)
# numbers(2,3,1)
# numbers(two = 2, three = 3, one = 1)
def greet(name, gender):
if gender == "male":
print(f"Hello Mr {name}..!")
else:
print(f"Hello Mrs {name}..!")
greet("Bolu", "female")
people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)]
# for person in people:
# greet(person[0], person[1])
for name, gender in people:
greet(name, gender)
| true
|
b9a6f5dfa9f184d24f941addd3aa219dcc16a1bd
|
harrylb/anagram
|
/anagram_runner.py
| 2,436
| 4.3125
| 4
|
#!/usr/bin/env python3
"""
anagram_runner.py
This program uses a module "anagram.py" with a boolean function
areAnagrams(word1, word2)
and times how long it takes that function to correctly identify
two words as anagrams.
A series of tests with increasingly long anagrams are performed,
with the word length and time to identify output to a file in the
same directory, anagram_results.csv, for easy import into a spreadsheet
or graphing program.
@author Richard White
@version 2017-02-20
"""
import random
import time
import anagram
def create_anagrams(word_length):
"""
Creates a random collection of lowercase English letters, a-z, of a
specified word_length, as well as a randomized rearranging of those
same letters. The strings word1 and word2 are anagrams of each other,
and returned by this function.
"""
baseword = []
for i in range(word_length):
baseword.append(chr(int(random.random()*26) + 97)) # random letter
word1 = ''.join(baseword) # Convert list to string
# Now go through baseword and pop off random letters to create word2.
word2 = ""
while len(baseword) > 0:
word2 += baseword.pop(int(random.random() * len(baseword)))
return word1, word2
def main():
"""
This main program includes some timed pauses and timed countdowns to
give the user some sense of the time it takes to sort the words.
"""
MAX_WORD_LENGTH = 10000
print("ANAGRAM RUNNER")
results = []
for word_length in range(int(MAX_WORD_LENGTH/10), MAX_WORD_LENGTH, int(MAX_WORD_LENGTH/10)):
word1,word2 = create_anagrams(word_length)
print("Comparing",word1,"and",word2)
print("Starting test")
start = time.time()
result = anagram.areAnagrams(word1,word2)
stop = time.time()
print("Stopping test")
if result:
print("The two words are anagrams")
else:
print("The two words are not anagrams")
print("Time elapsed: {0:.4f} seconds".format(stop - start))
results.append((word_length, stop-start))
outfile = open("anagram_results.csv","w")
outfile.write("Anagram length in letters,time to verify(seconds)\n")
for result in results:
outfile.write(str(result[0]) + "," + str(result[1]) + "\n")
outfile.close()
print("anagram_results.csv successfully written")
if __name__ == "__main__":
main()
| true
|
7008f73c39d0cffbb93e317e2e4371b16e4a1152
|
ozgecangumusbas/I2DL-exercises
|
/exercise_01/exercise_code/networks/dummy.py
| 2,265
| 4.21875
| 4
|
"""Network base class"""
import os
import pickle
from abc import ABC, abstractmethod
"""In Pytorch you would usually define the `forward` function which performs all the interesting computations"""
class Network(ABC):
"""
Abstract Dataset Base Class
All subclasses must define forward() method
"""
def __init__(self, model_name='dummy_network'):
"""
:param model_name: A descriptive name of the model
"""
self.model_name = model_name
@abstractmethod
def forward(self, X):
"""perform the forward pass through a network"""
def __repr__(self):
return "This is the base class for all networks we will use"
@abstractmethod
def save_model(self, data=None):
""" each model should know what are the relevant things it needs for saving itself."""
class Dummy(Network):
"""
Dummy machine
"""
def __init__(self, model_name="dummy_machine"):
"""
:param model_name: A descriptive name of the model
"""
super().__init__()
self.model_name = model_name
def forward(self, x):
"""
:param x: The input to the network
:return: set x to any integer larger than 59 to get passed
"""
########################################################################
# TODO #
# Implement the dummy machine function. #
# #
########################################################################
pass
########################################################################
# END OF YOUR CODE #
########################################################################
return x
def __repr__(self):
return "A dummy machine"
def save_model(self, data=None):
directory = 'models'
model = {self.model_name: self}
if not os.path.exists(directory):
os.makedirs(directory)
pickle.dump(model, open(directory + '/' + self.model_name + '.p', 'wb'))
| true
|
a477f9345fcd496943a6543eba007b5a883bc1d0
|
Ayaz-75/Prime-checker-program
|
/pime_checker.py
| 267
| 4.125
| 4
|
# welcome to the prime number checker
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
return "not prime"
else:
return "prime"
num = int(input("Enter number: "))
print(prime_checker(number=num))
| true
|
52230fa21f292174d6bca6c86ebcc35cc860cb69
|
kisyular/StringDecompression
|
/proj04.py
| 2,900
| 4.625
| 5
|
#############################################
#Algorithm
#initiate the variable "decompressed_string" to an empty string
#initiate a while True Loop
#prompt the user to enter a string tocompress
#Quit the program if the user enters an empty string
#Initiate a while loop if user enters string
#find the first bracket and convert it into an integer
#find the other bracket ")"
#find the comma index and convert it to an integer
#find the first number within the parenthesis and convert it to integer
#find the index of the second number within the comma and the last parenthesis
#get the string within the first index and the second index numbers
#find the decompressed string. Given by the string entered plus string within
#update the new string entered to a newer one
#replace the backslash with a new line during printing
#print the decompressed string
Backslash = "\\"
#initiate the variable "decompressed_string" to an empty string
decompressed_string =""
print()
#initiate a while True Loop
while True:
#prompt the user to enter a string tocompress
string_entered=input ("\nEnter a string to decompress (example 'to be or not to(13,3)' \
will be decompressed to 'TO BE OR NOT TO BE' see more examples in the pdf attached \
or press 'enter' to quit: ")
#Quit the program if the user enters an empty string
if string_entered=="" :
print("There is nothing to decompress. The Program has halted")
break
#Initiate a while loop if user enters string
while string_entered.find("(") != -1:
#find the first bracket and convert it into an integer
bracket_1st=int(string_entered.find("("))
#find the other bracket nd convert to an integer ")"
sec_bracket=int(string_entered.find(")"))
#find the comma index and convert it to an integer
comma=int(string_entered.find(",", bracket_1st, sec_bracket))
# find the first number within the parenthesis and convert it to integer
index_1st = int(string_entered[bracket_1st+1: comma])
# find the index of the second number within the comma and the last parenthesis
sec_indx=int(string_entered[comma+1 : sec_bracket])
#get the string within the first index and the second index numbers
string_within=string_entered[bracket_1st - index_1st \
: bracket_1st - index_1st + sec_indx]
#find the decompressed string. Given by the string entered plus string within
decompressed_string=(string_entered [ : bracket_1st] + string_within)
#update the new string entered to a newer one
string_entered=decompressed_string + string_entered[sec_bracket+1: ]
#replace the backslash with a new line during printing
decompressed_string=string_entered.replace(Backslash, "\n")
#print the decompressed string
print("\nYour decompressed string is:" "\n")
print(decompressed_string)
| true
|
e3e8af1efd0adbca06cba83b769bc93d10c13d69
|
jalalk97/math
|
/vec.py
| 1,262
| 4.125
| 4
|
from copy import deepcopy
from fractions import Fraction
from utils import to_fraction
class Vector(list):
def __init__(self, arg=None):
"""
Creates a new Vector from the argument
Usage:
>> Vector(), Vector(None) Vector([]) creates empty vector
>> Vector([5, 6, 6.7, Fraction(5, 6)]) creates vector with elements as list
"""
if arg is None:
super().__init__()
elif isinstance(arg, list):
super().__init__(to_fraction(arg))
elif isinstance(arg, Vector):
self = deepcopy(arg)
else:
raise TypeError('Invalid argument type:', arg)
def __getitem__(self, arg):
"""
Uses the basic list indexing
Usage:
>> v[0] returns the firt element
>> v[-1] returns the last element
>> v[:] shallow copy of vector elements
>> v[4:8] returns a sclice of the vectors element from 4 to 8
"""
return super().__getitem__(arg)
def __setitem__(self, arg, value):
"""
Uses the basic list indexing to set values
Usage:
>>
>>
>>
>>
"""
value = to_fraction(value)
super().__setitem__(arg, value)
| true
|
a84f6776548484ef96ab81e0107bdd36385e416e
|
DasVisual/projects
|
/temperatureCheck/tempCheck2.py
| 338
| 4.125
| 4
|
#! python 3
# another version of temperature checker, hopefully no none result
print('What is the current temperature of the chicken?')
def checkTemp(Temp):
if Temp > 260:
return 'It is probably cooked'
elif Temp < 260:
return 'More heat more time'
Temp = int(input())
Result = checkTemp(Temp)
print(Result)
| true
|
2d8d833c7ef4ea7411848251e673088c3ea18c88
|
GauravKTri/-All-Python-programs
|
/calculator.py
| 334
| 4.28125
| 4
|
num1=float(input("Enter the first number"))
num2=float(input("Enter the second number"))
num3=input("input your operation")
if num3=='+':
print(num1+num2)
if num3=='+':
print(num1+num2)
if num3=='-':
print(num1-num2)
if num3=='/':
print(num1/num2)
if num3=='*':
print(num1*num2)
if num3=='%':
print(num1%num2)
| false
|
cd3b288dc03da30a69439727191cb18e429d943a
|
olympiawoj/Algorithms
|
/stock_prices/stock_prices.py
| 1,934
| 4.3125
| 4
|
#!/usr/bin/python
"""
1) Understand -
Functions
- find_max_profit should receive a list of stock prices as an input, return the max profit that can be made from a single buy and sell. You must buy first before selling, no shorting
- prices is an array of integers which represent stock prices and we need to find the max, the min, and subtract
- TO solve this, we need to find out the max profit and minimum
[1, 3, 2]
Max profit = 2
3-2 = 1
[4, 8, 1]
I have to buy 4
Sell 8
Max profit = 4
So we start with the maxProfit = arr[1] - arr[0]
We need to track the min price arr[0]
TO DO
- Iterate through array prices
- For each current_price, if that price - min price > maxProfit, then define a new max
- For each current price, if that cur price is less than the min price, define a new min
- Update variables if we find a higher max profit and/or a new min price
"""
import argparse
def find_max_profit(prices):
# Tracks min price and current max profit
minPrice = prices[0]
maxProfit = prices[1] - minPrice
# could also do
# for currentPrice in prices[1:]
for i in range(1, len(prices)):
print('loop', prices[i])
print('i', i)
maxProfit = max(prices[i] - minPrice, maxProfit)
minPrice = min(prices[i], minPrice)
print('min', minPrice)
print('maxProfit', maxProfit)
return maxProfit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(
description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(
profit=find_max_profit(args.integers), prices=args.integers))
# print(find_max_profit([1050, 270, 1540, 3800, 2]))
| true
|
0affe2658592fab3415002287c348ef24ae372bb
|
Swaraajain/learnPython
|
/learn.python.loops/calc.py
| 384
| 4.1875
| 4
|
a= int(input("provide first number : "))
b= int(input("provide second number : "))
sign= input("the operation : ")
def calc(a,b):
if sign == '+':
c= a+b
elif sign== '-':
c= a-b
elif sign=='*':
c= a*b
elif sign=='/':
c= a/b
else:
print("This option is not available")
return c
print("the answer is : ",calc(a,b))
| false
|
17209e6ac514e763706e801ef0fb80a88ffb56b7
|
Swaraajain/learnPython
|
/learn.python.loops/stringQuestions.py
| 457
| 4.1875
| 4
|
# we have string - result must be the first and the last 2 character of the string
name = "My Name is Sahil Nagpal and I love Programming"
first2index = name[:2]
last2index = name[len(name)-2:len(name)]
print(first2index + last2index)
#print(last2index)
#string.replace(old, new, count)
print(name.replace('e','r',2))
# question - find the longest word and print the word and length of the z
# question - remove the nth index element from the string
| true
|
8d895964bd49c9b70d02da96c01d1fa5e935caa3
|
Swaraajain/learnPython
|
/learn.python.loops/lisOperations.py
| 729
| 4.125
| 4
|
# list1, list2 = [123, 'xyz'], [456, 'abc', 'ade', 'rwd', 'ghhg']
#
# print(list1[1])
# print(list2[2:4])
# list2[2]=123
# print(list2)
# #del list2[2]
# print(list2)
# print(len(list2))
# print(list1+list2)
# print(456 in list2)
# for x in list2:
# print(x)
# def cmp(a,b):
# return (a > b) - (a < b)
#
# list1 = [1, 2, 4, 3,8,5,6]
# list2 = [1, 2, 5, 8,'5']
# list3 = [1, 2, 5, 8, 10]
# list4 = [1, 2, 4, 3]
#
# # Comparing lists
# print("Comparison of list2 with list1 :")
# print(cmp(list2, list1))
# print(len(list1))
# print(max(list1))
# print(min(list1))
# print(tuple(list1))
# list1[7]=10
# print(list1)
# write a program to swap the last element with first element
# example [1,2,3,4,5] --> [5,2,3,4,1]
| false
|
fbc2b174ff0abcb78531105634d19c6ec9022184
|
40309/Files
|
/R&R/Task 5.py
| 557
| 4.28125
| 4
|
checker = False
while checker == False:
try:
user_input = int(input("Please enter a number between 1-100: "))
except ValueError:
print("The value entered was not a number")
if user_input < 1:
print("The number you entered is too low, Try again")
elif user_input > 100:
print("The number you entered is too high, Try again")
else:
print()
print("The Number you entered is good")
print(user_input)
checker = True
print()
print()
print("End of Program")
| true
|
aad05d66c26fa07d7b9ea7b59ca719af4f456248
|
Marinagansi/PythonLabPractice
|
/practiceq/pythonProject1/fucntion/q1.py
| 225
| 4.1875
| 4
|
''' to print multipliacation table of a given number by using fuction'''
def multi(a):
product=1
for i in range(11):
product=a*i
print (f"{a}*{i}={product}")
a=int(input("enter the nnumber"))
multi(a)
| false
|
707681af05d6cb4521bf4f729290e96e6c347287
|
Dirac26/ProjectEuler
|
/problem004/main.py
| 877
| 4.28125
| 4
|
def is_palindromic(num):
"""Return true if the number is palindromic and false otehrwise"""
return str(num) == str(num)[::-1]
def dividable_with_indigits(num, digits):
"""Returns true if num is a product of two integers within the digits range"""
within = range(10 ** digits - 1)
for n in within[1:]:
if num % n == 0:
if num / n <= 10 ** digits - 1:
return True
return False
def largest_mult(digits):
"""Returns the largest palindromic number that is the product of two numbers with certain digits number"""
num = (10 ** digits - 1) ** 2
found = False
while not found:
if is_palindromic(num):
if dividable_with_indigits(num, digits):
return num
num -= 1
def main():
"""main funtion"""
print(largest_mult(3))
if __name__ == "__main__":
main()
| true
|
774edd572b1497b9a8bc9e1c0f6107147626f276
|
max-moazzam/pythonCoderbyte
|
/FirstFactorial.py
| 541
| 4.1875
| 4
|
#Function takes in a number as a parameter and returns the factorial of that number
def FirstFactorial(num):
#Converts parameter into an integer
num = int(num)
#Creates a factorial variable that will be returned
factorial = 1
#While loop will keep multipying a number to the number 1 less than it until 1 is reached
while num > 1:
factorial = factorial * num
num = num - 1
return factorial
#May need to change to raw_input to just input depending on which version of Python used
print(FirstFactorial(raw_input()))
| true
|
4fdd9b3423f94460b3faad5262229e374ca3518c
|
indeyo/PythonStudy
|
/algorithm/insertion_sort.py
| 720
| 4.125
| 4
|
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author : indeyo_lin
# @Time : 2020/5/28 4:20 下午
# @File : insertion_sort.py
"""
def insertion_sort(arr):
if not arr:
return -1
for i in range(1, len(arr)):
current = arr[i]
# 有序区的索引
pre_index = i - 1
while pre_index >= 0 and arr[pre_index] > current:
# 遇到比当前元素大的就往后挪
arr[pre_index + 1] = arr[pre_index]
pre_index -= 1
arr[pre_index + 1] = current
return arr
if __name__ == '__main__':
# for i in range(0, -1, -1):
# print(i)
arr = [2, 8, 49, 4, 21, 0, 45, 22, 91, 5, 10]
print(insertion_sort(arr))
| false
|
1f29fed056ccc1691b630acc4ffbc33526a29276
|
lcantillo00/python-exercises
|
/2-SimplePythonData/ex11.py
| 227
| 4.40625
| 4
|
deg_f = int(input("What is the temperature in farengeigth? "))
# formula to convert C to F is: (degrees Celcius) times (9/5) plus (32)
deg_c = (deg_f -32)*5/9
print(deg_f, " degrees Celsius is", deg_c, " degrees Farenheit.")
| false
|
681ec03bc494256d93fd8e6482a2aea210cf94d2
|
lcantillo00/python-exercises
|
/4-ModuleTurtle/ex5.py
| 772
| 4.15625
| 4
|
# draw an equilateral triangle
import turtle
wn = turtle.Screen()
norvig = turtle.Turtle()
for i in range(3):
norvig.forward(100)
# the angle of each vertice of a regular polygon
# is 360 divided by the number of sides
norvig.left(360/3)
wn.exitonclick()
# draw a square
import turtle
wn = turtle.Screen()
kurzweil = turtle.Turtle()
for i in range(4):
kurzweil.forward(100)
kurzweil.left(360/4)
wn.exitonclick()
# draw a hexagon
import turtle
wn = turtle.Screen()
dijkstra = turtle.Turtle()
for i in range(6):
dijkstra.forward(100)
dijkstra.left(360/6)
wn.exitonclick()
# draw an octogon
import turtle
wn = turtle.Screen()
knuth = turtle.Turtle()
for i in range(8):
knuth.forward(75)
knuth.left(360/8)
wn.exitonclick()
| false
|
d9fbdc7310218e85b562a1beca25abe48e72ee8b
|
lcantillo00/python-exercises
|
/randy_guessnum.py
| 305
| 4.15625
| 4
|
from random import randint
num = randint(1, 6)
print ("Guess a number between 1 and 6")
answer = int(raw_input())
if answer==num:
print ("you guess the number")
elif num<answer:
print ("your number is less than the random #")
elif num>answer:
print("your number is bigger than the random #")
| true
|
7b692f7ea4d8718261e528d07222061dc3e35de8
|
michelmora/python3Tutorial
|
/BegginersVenv/dateAndTime.py
| 757
| 4.375
| 4
|
# Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch
# time. To get the date or time in Python we need to use the standard time module.
import time
ticks = time.time()
print("Ticks since epoch:", ticks)
# To get the current time on the machine, you can use the function localtime:
timenow = time.localtime(time.time())
print("Current time :", timenow)
# You can access each of the elements of the array:
timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])
# and use a combination for your own formatting. One alternative is to use the asctime function:
timenow = time.asctime(time.localtime(time.time()))
print(timenow)
| true
|
4dd9a591648531943ccd60b984e1d3f0b72a800c
|
michelmora/python3Tutorial
|
/BegginersVenv/switch(HowToSimulate).py
| 2,519
| 4.21875
| 4
|
# An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
# OPTION No.1
def dog_sound():
return 'hau hau'
def cat_sound():
return 'Me au'
def horse_sound():
return 'R R R R'
def cow_sound():
return 'M U U U'
def no_sound():
return "Total silence"
switch = {
'dog': dog_sound,
'cat': cat_sound,
'horse': horse_sound,
'cow': cow_sound,
}
# value = input("Enter the animal: ")
# if value in switch:
# sound = switch[value]()
# else:
# sound = no_sound()
# # default
#
# print(sound)
# OPTION No.2
# define the function blocks
def zero():
print("You typed zero.\n")
def sqr():
print("n is a perfect square\n")
def even():
print("n is an even number\n")
def prime():
print("n is a prime number\n")
# map the inputs to the function blocks
options = {0: zero,
1: sqr,
4: sqr,
9: sqr,
2: even,
3: prime,
5: prime,
7: prime,
}
# options[10]()
# OPTION NO. 3
# A very elegant way
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
print(numbers_to_strings(2))
# OPTION NO. 4
# Dictionary Mapping for Functions
def zero():
return "zero"
def one():
return "one"
def numbers_to_functions_to_strings(argument):
switcher = {
0: zero,
1: one,
2: lambda: "two",
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "nothing")
# Execute the function
return func()
print(numbers_to_functions_to_strings(3))
# OPTION NO. 5
# Dispatch Methods for Classes
# If we don't know what method to call on a class, we can use a dispatch method to determine it at runtime.
class Switcher(object):
def numbers_to_methods_to_strings(self, argument):
"""Dispatch method"""
# prefix the method_name with 'number_' because method names
# cannot begin with an integer.
method_name = 'number_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "nothing")
# Call the method as we return it
return method()
def number_2(self):
return "two"
def number_0(self):
return "zero"
def number_1(self):
return "one"
tes = Switcher()
print(tes.numbers_to_methods_to_strings(4))
| true
|
8dee8c987a27474de2b12a4a783dddc7aa142260
|
darrengidado/portfolio
|
/Project 3 - Wrangle and Analyze Data/Update_Zipcode.py
| 1,333
| 4.21875
| 4
|
'''
This code will update non 5-digit zipcode.
If it is 8/9-digit, only the first 5 digits are kept.
If it has the state name in front, only the 5 digits are kept.
If it is something else, will not change anything as it might result in error when validating the csv file.
'''
def update_zipcode(zipcode):
"""Clean postcode to a uniform format of 5 digit; Return updated postcode"""
if re.findall(r'^\d{5}$', zipcode): # 5 digits 02118
valid_zipcode = zipcode
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{3}$', zipcode): # 8 digits 02118-029
valid_zipcode = re.findall(r'(^\d{5})-\d{3}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{4}$', zipcode): # 9 digits 02118-0239
valid_zipcode = re.findall(r'(^\d{5})-\d{4}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'CA\s*\d{5}', zipcode): # with state code CA 02118
valid_zipcode =re.findall(r'\d{5}', zipcode)[0]
return valid_zipcode
else: #return default zipcode to avoid overwriting
return zipcode
def test_zip():
for zips, ways in zip_print.iteritems():
for name in ways:
better_name = update_zipcode(name)
print name, "=>", better_name
if __name__ == '__main__':
test_zip()
| true
|
3177bc787712977e88acaa93324b7b43c25016f9
|
sudharsan004/fun-python
|
/FizzBuzz/play-with-python.py
| 377
| 4.1875
| 4
|
#Enter a number to find if the number is fizz,buzz or normal number
n=int(input("Enter a number-I"))
def fizzbuzz(n):
if (n%3==0 and n%5==0):
print(str(n)+"=Fizz Buzz")
elif (n%3==0):
print(str(n)+"=Fizz")
elif (n%5==0):
print(str(n)+"=Buzz")
else:
print(str(n)+"=Not Fizz or Buzz")
fizzbuzz(n)
#define a function
| true
|
bf90882a0af31c4272a9fee19aa2716760847bbc
|
krishna-kumar456/Code-Every-Single-Day
|
/solutions/piglatin.py
| 1,060
| 4.375
| 4
|
""" Pig Lating Conversion
"""
def convert_to_pig_latin(word):
""" Returns the converted string based on the
rules defined for Pig Latin.
"""
vowels = ['a', 'e', 'i', 'o', 'u']
char_list = list(word)
""" Vowel Rule.
"""
if char_list[0] in vowels:
resultant_word = word + 'way'
""" Consonant Rule.
"""
if char_list[0] not in vowels:
resultant_word = ''.join(char_list[1:]) + str(char_list[0]) + 'a'
""" Consonant Cluster Rule.
"""
if char_list[0] == 'c' and char_list[1] == 'h':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
elif char_list[0] == 's' and char_list[1] == 'h' or char_list[1] =='t' or char_list[1] == 'm':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
elif char_list[0] == 't' and char_list[1] == 'h':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
return resultant_word
if __name__ == '__main__':
word = input('Please enter the word for conversion ')
print('Post conversion ', convert_to_pig_latin(word))
| false
|
da04ab784745cdce5c77c0b6159e17d802011129
|
sclayton1006/devasc-folder
|
/python/def.py
| 561
| 4.40625
| 4
|
# Python3.8
# The whole point of this exercise is to demnstrate the capabilities of
# a function. The code is simple to make the point of the lesson simpler
# to understand.
# Simon Clayton - 13th November 2020
def subnet_binary(s):
""" Takes a slash notation subnet and calculates the
number of host addresses """
if s[0] == "/":
a = int(s.strip("/"))
else:
a = int(s)
addresses = (2**(32-a))
return addresses
s = input("Enter your slash notation. Use a number or a slash (/27 or 27): ")
x = subnet_binary(s)
print(x)
| true
|
bbfa62e0a73aa476ff8c7a2abd98c021c956d20e
|
Zeonho/LeetCode_Python
|
/archives/535_Encode_and_Decode_TinyURL.py
| 1,708
| 4.125
| 4
|
"""
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your
encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny
URL and the tiny URL can be decoded to the original URL.
"""
class hashMap:
def __init__(self):
self.mapping = [[]]*25
def put(self, key, val):
hash_key = hash(val) % len(self.mapping)
bucket = self.mapping[hash_key]
key_exists = False
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket.append((hash_key, val))
else:
self.mapping[hash_key] = [(hash_key,val)]
return key
def get(self, key):
hash_key = hash(key) % len(self.mapping)
bucket = self.mapping[hash_key]
for i, kv in enumerate(bucket):
k,v = kv
return v
raise KeyError
class Codec:
def __init__(self):
self.urlShortener = hashMap()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
return self.urlShortener.put(hash(longUrl), longUrl)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urlShortener.get(shortUrl)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
| true
|
4af8683399a7344690ba6e7a3ba749d10852c993
|
aparecidapires/Python
|
/Python para Zumbis/3 - Atacando os tipos basicos/Comentarios e Resolucao de Exercicios/Lista III/1.py
| 398
| 4.375
| 4
|
'''
Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.
'''
nota = float(input("Digite uma nota entre '0' e '10': "))
while nota < 0 or nota > 10:
print ('Digite uma nota válida!')
nota = float(input("Digite uma nota entre '0' e '10': "))
print ('Nota: %2.f' %nota)
| false
|
ad6c9704c7f09a5fa1d1faab38eb5d43967026a4
|
fagan2888/leetcode-6
|
/solutions/374-guess-number-higher-or-lower/guess-number-higher-or-lower.py
| 1,199
| 4.4375
| 4
|
# -*- coding:utf-8 -*-
# We are playing the Guess Game. The game is as follows:
#
# I pick a number from 1 to n. You have to guess which number I picked.
#
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
#
# You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
#
#
# -1 : My number is lower
# 1 : My number is higher
# 0 : Congrats! You got it!
#
#
# Example :
#
#
#
# Input: n = 10, pick = 6
# Output: 6
#
#
#
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
low=1
high=n
num=(low+high)/2
while guess(num)!=0:
if guess(num)<0:
high=num
num=(low+high)/2
else:
low=num
num=(low+high)/2
if guess(num)!=0:
if num==low:
num=high
elif num==high:
num=low
return num
| true
|
6a097f9f7027419ba0649e5017bc2e17e7f822d3
|
fagan2888/leetcode-6
|
/solutions/557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py
| 773
| 4.1875
| 4
|
# -*- coding:utf-8 -*-
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is separated by single space and there will not be any extra space in the string.
#
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl=[]
for word in s.split(' '):
wordl=[]
for i in xrange(len(word)-1,-1,-1):
wordl.append(word[i])
sl.append(''.join(wordl))
rs=' '.join(sl)
return rs
| true
|
6f4b3f90db0be1ccc197aacca9b625642c498aee
|
Raziel10/AlgorithmsAndMore
|
/Probability/PowerSet.py
| 267
| 4.34375
| 4
|
#Python program to find powerset
from itertools import combinations
def print_powerset(string):
for i in range(0,len(string)+1):
for element in combinations(string,i):
print(''.join(element))
string=['a','b','c']
print_powerset(string)
| true
|
da7bd9d5abbdd838c1110515dde30c459ed8390c
|
Smita1990Jadhav/GitBranchPracticeRepo
|
/condition&loops/factorial.py
| 278
| 4.25
| 4
|
num=int(input("Enter Number: "))
factorial=1
if num<1:
print("Factorial is not available for negative number:")
elif num==0:
print("factorial of 1 is zero: ")
else:
for i in range(1,num+1):
factorial=factorial*i
print("factorial of",num,"is",factorial)
| true
|
9f0b7ec7c45ed53ae0c7141eb88d50e04c62a868
|
silasbispo01/todosOsDias
|
/Todos os dias/dia41/Exércicio3.py
| 832
| 4.1875
| 4
|
# Importação do random
import random
# Criação da lista de sorteios vazia
listaSorteio = []
# For para cadastro de 3 pessoas
for p in range(3):
# Inputs para nome da pessoa e quantia doada.
nome = input('Insira seu nome: ')
valorDoado = int(input('Insira o valor doado: R$'))
# Calculo de quantas vezes a pessoa tem direito a aparecer na lista "quantidade de chances"
chances = (int(valorDoado/10))
#For para adicionar pessoa na lista de acordo com as "chances"
for x in range(chances):
listaSorteio.append(nome)
# Método utilizado para embaralhar nomes na lista e print dos nomes embaralhados.
random.shuffle(listaSorteio)
print(listaSorteio)
# Sorteio do ganhador utilizando o método .choice + print do nome da pessoa.
print('O ganhador foi {}'.format(random.choice(listaSorteio)))
| false
|
a3e1eadfdf24f44dc353726180eee97269844c45
|
jjspetz/digitalcrafts
|
/py-exercises3/hello2.py
| 517
| 4.34375
| 4
|
#!/usr/bin/env python3
# This is a simple function that says hello using a command-line argument
import argparse
# formats the arguments for argparse
parser = argparse.ArgumentParser()
# requires at least one string as name
parser.add_argument('username', metavar='name', type=str, nargs='*',
help="Enter a name so the computer can say hello")
def hello(name):
print("Hello, {}!".format(name))
if __name__ == "__main__":
args = parser.parse_args()
hello(' '.join(args.username))
| true
|
c46f2637edea6f94adff6a8e93f78bd858d94fc1
|
jjspetz/digitalcrafts
|
/py-exercises2/make-a-box.py
| 327
| 4.15625
| 4
|
# makes a box of user inputed hieght and width
# gets user input
height = int(input("Enter a height: "))
width = int(input("Enter a width: "))
# calculate helper variables
space = width - 2
for j in range(height):
if j == 0 or j == height - 1:
print("*" * width)
else:
print("*" + (" "*space) + "*")
| true
|
5c9ff36d6710c334e72abc5b9b58abc8a94758bd
|
jjspetz/digitalcrafts
|
/dict-exe/error_test.py
| 343
| 4.125
| 4
|
#!/usr/bin/env python3
def catch_error():
while 1:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Enter an integer!")
except x == 3:
raise myError("This is not an integer!")
else:
x += 13
if __name__ == "__main__":
catch_error()
| true
|
4bdd9011b451281cdd9b3c8d4c3abbe730f9358f
|
kusaurabh/CodeSamples
|
/python_samples/check_duplicates.py
| 672
| 4.25
| 4
|
#!/usr/bin/python3
import sys
def check_duplicates(items):
list_items = items[:]
list_items.sort()
prev_item = None
for item in list_items:
if prev_item == item:
return True
else:
prev_item = item
return False
def create_unique_list(items):
unique_list = list()
for item in items:
if item not in unique_list:
unique_list.append(item)
return unique_list
if __name__ == "__main__":
items = ["Hello", "rt", "st", "lt", "lt"]
result = check_duplicates(items)
unqList = create_unique_list(items)
print(items)
print(result)
print(unqList)
| true
|
a5a46c8dbaaf4c4ceee25803e0cca585d74eb883
|
pseudomuto/sudoku-solver
|
/Python/model/notifyer.py
| 1,164
| 4.125
| 4
|
class Notifyer(object):
"""A simple class for handling event notifications"""
def __init__(self):
self.listeners = {}
def fireEvent(self, eventName, data = None):
"""Notifies all registered listeners that the specified event has occurred
eventName: The name of the event being fired
data: An optional parameter to be passed on listeners
"""
if eventName in self.listeners:
for responder in self.listeners[eventName]:
responder(data)
def addListener(self, eventName, responder):
"""Registers responder as a listener for the specified event
eventName: The name of the event to listen for
responder: A callback method that will be notified when the event occurs
"""
if not eventName in self.listeners:
self.listeners[eventName] = []
self.listeners[eventName].append(responder)
def removeListener(self, eventName, responder):
"""Removes the specified listener from the set of observers
eventName: The name of the event to stop listening for
responder: The callback method to remove
"""
if eventName in self.listeners:
if responder in self.listeners[eventName]:
self.listeners[eventName].remove(responder)
| true
|
3e925a8f0736eec9688f3597502d77f249c05e08
|
annapaula20/python-practice
|
/functions_basic2.py
| 2,510
| 4.4375
| 4
|
# Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(num):
nums_list = []
for val in range(num, -1, -1):
nums_list.append(val)
return nums_list
# print(countdown(12))
# print(countdown(5))
# Print and Return - Create a function that will receive a list with two numbers.
# Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
def print_and_return(nums_list):
print(nums_list[0])
return nums_list[1]
# print(print_and_return([10,12]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(nums_list):
return nums_list[0] + len(nums_list)
# print(first_plus_length([13,2,3,4,5]))
# Values Greater than Second - Write a function that accepts a list and
# creates a new list containing only the values from the original list that are greater than its 2nd value.
# Print how many values this is and then return the new list.
# If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
def values_greater_than_second(orig_list):
new_list = []
# get the second value in the original list
second_val = orig_list[1]
# scan through the original list, find values greater than second value and add them to the new list
for idx in range(len(orig_list)):
if orig_list[idx] > second_val:
new_list.append(orig_list[idx])
print(len(new_list))
return new_list
# print(values_greater_than_second([5,2,3,2,1,4]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value.
# The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def length_and_value(size, value):
new_list = []
for num_times in range(size):
new_list.append(value)
return new_list
# print(length_and_value(4,7))
| true
|
607e0ba035eaa2dc9216f0884c1562036797ba79
|
Jagadeesh-Cha/datamining
|
/comparision.py
| 487
| 4.28125
| 4
|
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6,7,8,9,10]
# corresponding y axis values
y = [35,32,20,14,3,30,6,20,2,30]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('busiest places in descending-order')
# naming the y axis
plt.ylabel('# of important customers')
# giving a title to my graph
plt.title('important_customers')
# function to show the plot
plt.show()
| true
|
b4816526ef6cc323464ac3e9f787a6032e32072f
|
lilimonroy/CrashCourseOnPython-Loops
|
/q1LoopFinal.py
| 507
| 4.125
| 4
|
#Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n // 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
| true
|
0ca00b26b0774c6e0d1891fca4567889cc657a01
|
Mmingo28/Week-3
|
/Python Area and Radius.py
| 263
| 4.28125
| 4
|
#MontellMingo
#1/30/2020
#The program asks if the user can compute the area of an circle and the radius.
radius = int(input("what is the radius"))
#print("what is the number of the radius"+ )
print("what is the answer")
print(3.14*radius*radius)
| true
|
8fbfcc3bcd13f2db5c6178cd7ed40f9eade923fc
|
xywgo/Learn
|
/LearnPython/Chapter 10/addition.py
| 372
| 4.1875
| 4
|
while True:
try:
number1 = input("Please enter a number:(enter 'q' to quit) ")
if number1 == 'q':
break
number1 = int(number1)
number2 = input("Please enter another number:(enter 'q' to quit) ")
if number2 == 'q':
break
number2 = int(number2)
except ValueError:
print("You must enter a number")
else:
results = number1 + number2
print(results)
| true
|
d025ef9b5f54fb004dc8ed67b652469566c92754
|
davidadamojr/diary_of_programming_puzzles
|
/arrays_and_strings/has_zero_triplets.py
| 1,089
| 4.1875
| 4
|
"""
Given an array of integers that do not contain duplicate values,
determine if there exists any triplets that sum up to zero.
For example,
L = [-3, 2, -5, 8, -9, -2, 0, 1]
e = {-3, 2, 1}
return true since e exists
This solution uses a hash table to cut the time complexity down by n.
Time complexity: O(n^2)
Space complexity: O(n)
Hint: a+b+c = 0 => c = -(a+b)
Once we know the first two elements of the triplet, we can compute the third
and check its existence in a hash table.
"""
# @param arr the list of integers to be checked for zero triples
# @return true if three elements exist that sum up to zero
def has_zero_triplet(arr):
if not arr:
return False
numbers = set([])
for number in arr:
numbers.add(number)
for i in range(0, len(arr) - 1):
for j in range(i, len(arr)):
first = arr[i]
second = arr[j]
third = -first - second
if third in numbers:
return True
return False
if __name__ == '__main__':
print(has_zero_triplet([-3, 2, -5, 8, -9, -2, 0, 1]))
| true
|
31966a029427f2de3759a8af889481c05e30339a
|
davidadamojr/diary_of_programming_puzzles
|
/arrays_and_strings/three_sum_closest.py
| 1,284
| 4.34375
| 4
|
"""
Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest
to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2)
"""
def three_sum_closest(nums, target):
if not nums:
return 0
nums.sort()
difference = float('inf')
target_sum = 0
for i in range(0, len(nums)-2):
j = i + 1
k = len(nums) - 1
while j < k:
first_num = nums[i]
second_num = nums[j]
third_num = nums[k]
element_sum = first_num + second_num + third_num
if element_sum < target:
j += 1
elif element_sum > target:
k -= 1
else:
return element_sum
current_difference = abs(element_sum - target)
if current_difference < difference:
difference = current_difference
target_sum = element_sum
return target_sum
assert three_sum_closest([-1, 2, 1, -4], 1) == 2
assert three_sum_closest([], 1) == 0
print("All tests passed successfully.")
| true
|
a7ad18871194654ee4d1cf04e1264b670df3d204
|
davidadamojr/diary_of_programming_puzzles
|
/arrays_and_strings/toeplitz_matrix.py
| 1,212
| 4.46875
| 4
|
"""
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix,
return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]", "[5, 5]', "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"
Note:
1. matrix will be a 2D array of integers
2. matrix will have a number of rows and columns in range [1, 20]
3. matrix[i][j] will be integers in range [0, 99]
https://leetcode.com/problems/toeplitz-matrix/description/
"""
def is_toeplitz_matrix(matrix):
for row_idx, row in enumerate(matrix):
for col_idx, value in enumerate(row):
if col_idx == 0 or row_idx == 0:
continue
if value != matrix[row_idx - 1][col_idx - 1]:
return False
return True
assert is_toeplitz_matrix([[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]]) is True
assert is_toeplitz_matrix([[1, 2, 3, 4],
[5, 5, 5, 5],
[9, 9, 9, 9]]) is False
print("All tests passed successfully.")
| true
|
895e80acf9eed3e1b580a9ac4dec51eb295e7319
|
davidadamojr/diary_of_programming_puzzles
|
/sorting_and_searching/find_in_rotated_array.py
| 1,653
| 4.21875
| 4
|
"""
Given a sorted array of n integers that has been rotated an unknown number of times,
write code to find an element in the array. You may assume that the array was originally
sorted in increasing order.
"""
def find_in_rotated(key, rotated_lst, start, end):
"""
fundamentally binary search...
Either the left or right half must be normally ordered. Find out which
side is normally ordered, and then use the normally ordered half to figure
out which side to search to find x.
"""
if not rotated_lst:
return None
if end < start:
return None
middle_idx = (start + end) / 2
middle_elem = rotated_lst[middle_idx]
leftmost_elem = rotated_lst[start]
rightmost_elem = rotated_lst[end]
if middle_elem == key:
return middle_idx
if leftmost_elem < middle_elem:
if leftmost_elem <= key < middle_elem:
return find_in_rotated(key, rotated_lst, start, middle_idx - 1)
else:
return find_in_rotated(key, rotated_lst, middle_idx + 1, end)
else:
if middle_elem < key <= rightmost_elem:
return find_in_rotated(key, rotated_lst, middle_idx + 1, end)
else:
return find_in_rotated(key, rotated_lst, start, middle_idx - 1)
if __name__ == '__main__':
assert find_in_rotated(1, [4, 5, 6, 1, 2, 3], 0, 5) == 3
assert find_in_rotated(5, [1, 2, 3, 4, 5, 6], 0, 5) == 4
assert find_in_rotated(5, [6, 6, 6, 6, 6, 6], 0, 5) == None
assert find_in_rotated(7, [6, 6, 6, 7, 7, 7, 7], 0, 6) == 3
assert find_in_rotated(6, [6, 6, 6, 6, 6, 6], 0, 5) == 2
print("All test cases passed.")
| true
|
46a081380aa96ceaf062d72e0101881f8d57a08c
|
davidadamojr/diary_of_programming_puzzles
|
/bit_manipulation/hamming_distance.py
| 1,025
| 4.3125
| 4
|
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers num1 and num2, calculate the Hamming distance.
https://leetcode.com/problems/hamming-distance/
"""
# @param num1 integer
# @param num2 integer
def hamming_distance(num1, num2):
distance = 0
while num1 > 0 and num2 > 0:
xor = num1 ^ num2
if xor % 2 == 1:
distance = distance + 1
num1 = num1 >> 1
num2 = num2 >> 1
while num1 > 0:
xor = num1 ^ 0
if xor % 2 == 1:
distance = distance + 1
num1 = num1 >> 1
while num2 > 0:
xor = num2 ^ 0
if xor % 2 == 1:
distance = distance + 1
num2 = num2 >> 1
return distance
if __name__ == '__main__':
assert hamming_distance(1, 4) == 2
assert hamming_distance(0, 0) == 0
assert hamming_distance(8, 4) == 2
assert hamming_distance(4, 8) == 2
print("All test cases passed successfully.")
| true
|
1ebdbdafcc3dadabe48676ca0dbda76cdb3181d8
|
davidadamojr/diary_of_programming_puzzles
|
/misc/convert_to_hexadecimal.py
| 1,658
| 4.75
| 5
|
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is
used.
Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
character '0'; otherwise, the first character in the hexadecimal string will not be zero character.
3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
4. You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
# @param num the number to convert to hexadecimal
# @return the hexadecimal representation of the number
def to_hex(num):
if num == 0:
return "0"
hex_digits = {
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f"
}
hex_num = ""
is_negative = False
if num < 0:
magnitude = abs(num)
mask = ((1 << 32) - 1) + (1 << 32)
inverted = magnitude ^ mask
num = inverted + 1
is_negative = True
while num != 0:
remainder = num % 16
num = num / 16
if remainder in hex_digits:
hex_num = hex_digits[remainder] + hex_num
else:
hex_num = str(remainder) + hex_num
if is_negative:
return hex_num[1:]
return hex_num
if __name__ == '__main__':
assert to_hex(0) == "0"
assert to_hex(-1) == "ffffffff"
assert to_hex(26) == "1a"
print("All test cases passed successfully.")
| true
|
a6673418628269bdac32de4aaa469fc9ea6b8239
|
davidadamojr/diary_of_programming_puzzles
|
/arrays_and_strings/integer_to_string.py
| 952
| 4.6875
| 5
|
"""
Write a routine to convert a signed integer into a string.
"""
def integer_to_string(integer):
"""
Writes the string backward and reverses it
"""
if integer < 0:
is_negative = True
integer = -integer # for negative integers, make them positive
else:
is_negative = False
integer_string = ""
while integer != 0:
new_digit = integer % 10
# "ord" returns the character code of its argument
ascii_code = ord('0') + new_digit
# "chr" returns the string representation of its argument
integer_string = integer_string + chr(ascii_code)
integer = integer / 10
# in python, the easiest way to reverse a string is "string[::-1]"\
integer_string = '-' + integer_string[::-1] if is_negative else integer_string[::-1]
return integer_string
if __name__ == "__main__":
print(integer_to_string(-1234))
print(integer_to_string(54321))
| true
|
e114ca362bb69f5298c5137696ee4aaffec569ad
|
davidadamojr/diary_of_programming_puzzles
|
/mathematics_and_probability/intersect.py
| 931
| 4.125
| 4
|
"""
Given two lines on a Cartesian plane, determine whether the two lines would
intersect.
"""
class Line:
def __init__(self, slope, yIntercept):
self.slope = slope
self.yIntercept = yIntercept
def intersect(line1, line2):
"""
If two different lines are not parallel, then they intersect.
To check if two lines intersect, we just need to check if the slopes are
different (or if the lines are identical)
Note: Due to the limitations of floating point representations, never check
for equality with ==. Instead, check if the difference is less than an
epsilon value.
"""
epsilon = 0.000001 # used for floating point comparisons
return abs(line1.slope - line2.slope) > epsilon \
or abs(line1.yIntercept - line2.yIntercept) < epsilon;
if __name__ == '__main__':
line1 = Line(0.5, 1)
line2 = Line(0.5, 2)
print(intersect(line1, line2))
| true
|
76e8af6b3ef66bce39724bd917d84150361c139e
|
davidadamojr/diary_of_programming_puzzles
|
/arrays_and_strings/excel_sheet_column_title.py
| 662
| 4.15625
| 4
|
"""
Given a positive integer, return its corresponding column title as it appears
in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
def convert_to_title(num):
integer_map = {}
characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
for i in range(0, 26):
integer_map[i] = characters[i]
column_title = ""
while num != 0:
remainder = num % 26
num = num - 1
num = num / 26
column_title = integer_map[remainder] + column_title
return column_title
if __name__ == '__main__':
print(convert_to_title(703))
print(convert_to_title(27))
print(convert_to_title(26))
| true
|
e6d847fbca7e196b13b3da94080a760656626497
|
CindyWei/Python
|
/ex41.py
| 1,295
| 4.15625
| 4
|
#coding=utf-8
'''
2014-2-11
习题41:类
'''
class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called"
def add_me_up(self, more):
self.number += more
return self.number
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print a.add_me_up(20)
print b.add_me_up(30)
print a.number
print b.number
class TheMultiplier(object):
def __init__(self, base):
self.base = base
def do_it(self, m):
return m * self.base
x = TheMultiplier(a.number)
print x.base
print x.do_it(30)
class Dog(object):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None #定义了类的两变量 name 和pet
#类的继承
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
print rover.name
mary = Person("Mary")
print mary.name
print mary.pet
employee = Employee('Cindy', 5000)
print employee.name
print employee.salary
'''
学习总结:
创建的类都要加上(object)参数
类的继承,用父类super(Employee, self).__init__(name)来初始化
'''
| false
|
332acd1b09be1ad4bdea876a5f3f82633319c7bc
|
cryojack/python-programs
|
/charword.py
| 402
| 4.34375
| 4
|
# program to count words, characters
def countWord():
c_str,c_char = "",""
c_str = raw_input("Enter a string : ")
c_char = c_str.split()
print "Word count : ", len(c_char)
def countChar():
c_str,c_char = "",""
charcount_int = 0
c_str = raw_input("Enter a string : ")
for c_char in c_str:
if c_char is not " " or "\t" or "\n":
charcount_int += 1
print "Character count : ", charcount_int
| true
|
28d38ddd8f5cf86011e785037ef891a338810b23
|
Daywison11/Python-exercicios-
|
/ex014.py
| 252
| 4.25
| 4
|
# Escreva um programa que converta uma temperatura digitando
# em graus Celsius e converta para graus Fahrenheit.
gc = float(input('infoeme a temperatra em °C :'))
fr = ((9*gc)/5) + 32
print('a temeratura de {}°C conrresponde a {}° F'.format(gc,fr))
| false
|
c08e6a357ee5cd58f4a171dc81b001df5a8f487a
|
rPuH4/pythonintask
|
/INBa/2015/Serdehnaya_A_M/task_5_25.py
| 1,494
| 4.25
| 4
|
# Задача 5. Вариант 28.
# Напишите программу, которая бы при запуске случайным образом отображала название одной из пятнадцати республик, входящих в состав СССР.
# Serdehnaya A.M.
# 25.04.2016
import random
print ("Программа случчайным образом отображает название одной из пятнадцати республик, входящих в состав СССР.")
x = int (random.randint(1,15))
print ('\nОдна из Республик - ', end = '')
if x == 1:
print ('РСФСР')
elif x == 2:
print ('Украинская ССР')
elif x == 3:
print ('Белорусская ССР')
elif x == 4:
print ('Узбекская ССР')
elif x == 5:
print ('Казахская ССР')
elif x == 6:
print ('Грузинская ССР')
elif x == 7:
print ('Азербайджанская ССР')
elif x == 8:
print ('Литовская ССР')
elif x == 9:
print ('Молдавская ССР')
elif x == 10:
print ('Латвийская ССР')
elif x == 11:
print ('Киргизская ССР')
elif x == 12:
print ('Таджикская ССР')
elif x == 13:
print ('Армянская ССР')
elif x == 14:
print ('Туркменская ССР')
else:
print ('Эстонская ССР')
input("\nДля выхода нажмите Enter.")
| false
|
bbaf1dec6b370ba832181e6b33f6e0f18a8490fb
|
ElianEstrada/Cursos_Programacion
|
/Python/Ejercicios/ej-while/ej-14.py
| 476
| 4.21875
| 4
|
#continuar = input("Desea continuar? [S/N]: ")
continuar = "S"
while(continuar == "S"):
continuar = input("Desea continuar? [S/N]: ")
print("Gracias por usar mi sistema :)")
'''
con ciclo while
pedir al usuario una cantidad númerica a ahorrar
y luego que le pregunten a al usuario si desea agregar otra cantidad
si la respuesta es SI, pedir la cantidad y volver ha preguntar si quiere ingresar otra
y si la respuesta es NO mostrar el total ahorrado y salir.
'''
| false
|
2c12b700e72b2cd155a8dca90a3e2389106eed3f
|
koenigscode/python-introduction
|
/content/partials/comprehensions/list_comp_tern.py
| 311
| 4.25
| 4
|
# if the character is not a blank, add it to the list
# if it already is an uppercase character, leave it that way,
# otherwise make it one
l = [c if c.isupper() else c.upper()
for c in "This is some Text" if not c == " "]
print(l)
# join the list and put "" (nothing) between each item
print("".join(l))
| true
|
22e20f3364f8498766caf17e4dc8b967ef217f5b
|
BMariscal/MITx-6.00.1x
|
/MidtermExam/Problem_6.py
| 815
| 4.28125
| 4
|
# Problem 6
# 15.0/15.0 points (graded)
# Implement a function that meets the specifications below.
# def deep_reverse(L):
# """ assumes L is a list of lists whose elements are ints
# Mutates L such that it reverses its elements and also
# reverses the order of the int elements in every element of L.
# It does not return anything.
# """
# # Your code here
# For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]
# Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements.
def deep_reverse(L):
for i in L:
i.reverse()
L.reverse()
return L
# Test: run_code([[0, -1, 2, -3, 4, -5]])
# Output:
# [[-5, 4, -3, 2, -1, 0]]
# None
| true
|
73e4c51440c5d6da38f297556843c0173f0153ee
|
alexhong33/PythonDemo
|
/PythonDemo/Day01/01print.py
| 1,140
| 4.375
| 4
|
#book ex1-3
print ('Hello World')
print ("Hello Again")
print ('I like typing this.')
print ('This is fun.')
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
print ('你好!')
#print ('#1')
# A comment, this is so you can read your program later.
# Anything after this # is ignored by python
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print("This will run.")
# this is the first Comment
spam = 1 # and this is the second Comment
# ... and now a third!
text = " # This is not a comment because it's inside quotes."
print (2 + 2)
print (50 - 5 * 6)
print ((50 - 5 * 6) / 4)
print (8/5) #division always returns a floating point number
print (8//5) #获得整数
print (8%5) #获得余数
print (5 * 3 + 2)
print (5 ** 2) #5 squared
print (2 ** 8)
print (2.5 * 4 / 5.0)
print(7.0/2) #python完全支持浮点数, 不同类型的操作数混在一起时, 操作符会把整型转化为浮点型
| true
|
41af103a812a599e376b79251c7f1c76a01fe914
|
KevinOluoch/Andela-Labs
|
/missing_number_lab.py
| 787
| 4.4375
| 4
|
def find_missing( list1, list2 ):
"""When presented with two arrays, all containing positive integers,
with one of the arrays having one extra number, it returns the extra number
as shown in examples below:
[1,2,3] and [1,2,3,4] will return 4
[4,66,7] and [66,77,7,4] will return 77
"""
#The lists are checked to ensure none of them is empty and if they are equal
if list1 == list2 or not (list1 or list2):
return 0
#If list1 is the larger one, the process of checking for the extra number is reversed
if len(list1) > len (list2):
return [ x for x in list1 if x not in list2 ][0]
return [ x for x in list2 if x not in list1 ][0]
print find_missing ( [66,77,7,4], [4,66,7] )
print find_missing ( [1,2,3], [1,2,3,4] )
| true
|
b2875d7737c5fd6cc06a5299f9f8c888c93bebb8
|
byhay1/Practice-Python
|
/Repl.it-Practice/forloops.py
| 1,856
| 4.71875
| 5
|
#--------
#Lets do for loops
#used to iterate through an object, list, etc.
# syntax
# my_iterable = [1,2,3]
# for item_name in my_iterable
# print(item_name)
# KEY WORDS: for, in
#--------
#first for loop example
mylist = [1,2,3,4,5,6,7,8,9,10]
#for then variable, you chose the variable
print('\n')
for num in mylist:
print(num)
#or you can print whatever you want, flexible
print('\n')
for num in mylist:
print ('Hi')
#ctrl flow with for loops
print('\n')
for num in mylist:
if num % 2 == 0:
print (num, 'even')
else:
print (num, 'odd future')
#get the sum of everything using loop
listsum = 0
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#show all by putting it in the for loop through indentation
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#do for strings
print('\n')
mystring = 'Hello World'
for letter in mystring:
print (letter)
#can use the underscore when you are not assigning variables '_'
print('\n')
for _ in mystring:
print("don't you dare look at me")
#tuple stuffs, tuple unpacking
print('\n')
mylist2 = [(1,2),(3,4),(5,6),(7,8)]
print(len(mylist2))
#return tuples back using a for loop
for item in mylist2:
print(item)
#Or you can do the following
#(a,b) does not need '()'
print('\n', 'unpacking the tuples!')
for (a,b) in mylist2:
print(a)
print(b)
#------------
#iterating through a dictionary
#------------
d = {'k1':1,'k2':2,'k3':3}
#only iterating the Key... not the value
#if you want only the value use .values()
print('\n')
for item in d:
print(item)
#------------
#If you want to iterate the value use the .items()
#This will give you the full item tuple set.
#------------
for item in d.items():
print(item)
#use unpacking to get the dictionary values
for key, value in d.items():
print(key, '=', value)
| true
|
29d08b7acb73e2baeb8a2daf67be103e1ad302fc
|
byhay1/Practice-Python
|
/Repl.it-Practice/tuples.py
| 828
| 4.1875
| 4
|
#------------
#tuples are immutable and similar to list
#FORMAT of a tuple == (1,2,3)
#------------
# create a tuple similar to a list but use '()' instead of '[]'
#define tuple
t = (1,2,3)
t2 = ('a','a','b')
mylist = [1,2,3]
#want to find the class type use the typle function type(PUTinVAR)
print('',"Find the type of the var 't' by using type(t): ", type(t), '\n', "Find the other type using type(mylist): ", type(mylist),'\n')
#can use other identifiers like a len(PUTinVar) and splice it how you want VAR[start:stop:step]
#find how many times a value occurs in a tuple or list
#do so by using the .count method
print('','There are only two methods you can use to get the count and the index position \n',"So t2.count('a') = ")
print(t2.count('a'))
#get the index num
print("and t2.index('b') = ")
print(t2.index('b'))
| true
|
4f3e7af26400a2f4c309cffa69d5a6f874819731
|
byhay1/Practice-Python
|
/Repl.it-Practice/OOPattributeClass.py
| 2,069
| 4.5
| 4
|
#----------
# Introduction to OOP:
# Attributes and Class Keywords
#
#----------
import math
mylist = [1,2,3]
myset = set()
#built in objects
type(myset)
type(list)
#######
#define a user defined object
#Classes follow CamelCasing
#######
#Do nothing sample class
class Sample():
pass
#set variable to class
my_sample = Sample()
#see type using built-in object
type(my_sample)
#######
#Give a class attributes
#######
#do something Dog class
class Dog():
def __init__(self,breed,name,spots):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
#Expect boolean True/False
self.spots = spots
#because attribute is used, must pass expected attribute or it will return an error
my_dog = Dog(breed='Mutt',name='Ruby',spots=False)
#Check to see type=instance of the dog class.
my_dog.breed
my_dog.name
my_dog.spots
#######PART TWO#######
#######
#Using Class object attribute and more...
#Using Methods within class
#######
######################
class Doggy():
# CLASS OBJECT ATTRIBUTE
# SAME FOR ANY INSTANCE OF A CLASS
clss = 'mammal'
# USER DEFINED ATTRIBUTE
def __init__(self,breed,name):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
# OPERATIONS/Actions ---> Methods
def bark(self, number):
print("WOOF! My name is {} and I am {} years old".format(self.name, number))
#because attribute is used, must pass expected attribute or it will return an error
my_dog2 = Doggy(breed='whtMutt',name='Rita')
#Methods need to be executed so they need '(' ')'
my_dog2.bark(2)
#######
#Create a new class called 'Circle'
#######
class Circle():
# CLASS OBJECT ATTRIBUTE
pi = math.pi
def __init__(self, radius=1):
self.radius = radius
self.area = radius*radius*Circle.pi
# METHOD
def get_circumference(self):
return self.radius*2*Circle.pi
my_circle = Circle(33)
print(my_circle.get_circumference)
print(my_circle.area)
print(my_circle.pi)
| true
|
eef86cb4c54bf7d0b38ced84acff83220b0304e3
|
jongwlee17/teampak
|
/Python Assignment/Assignment 5.py
| 988
| 4.34375
| 4
|
""" Exercise 5: Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
Extras:
1. Randomly generate two lists to test this
2. Write this in one line of Python (don't worry if you can't figure this out at this point - we'll get to it soon)
"""
import random
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# random_a = range(1, random.randint(1,30))
# random_b = range(1, random.randint(1,40))
print("Random_a list consists of: ", random_a)
print("Random_b list consists of: ", random_b)
def findCommonValues(a, b):
final_list = []
for num in a:
if num in b:
if num not in final_list:
final_list.append(num)
return final_list
print(findCommonValues(a, b))
| true
|
3061d9515b321d746e69674f44b9550ae0e6f151
|
ankitoct/Core-Python-Code
|
/40. List/6. AppendMethod.py
| 222
| 4.125
| 4
|
# Append Method
a = [10, 20, -50, 21.3, 'Geekyshows']
print("Before Appending:")
for element in a:
print (element)
# Appending an element
a.append(100)
print()
print("After Appending")
for element in a:
print (element)
| true
|
0a064e70245373690e15b0a00b36ee1f2ba76c8d
|
ankitoct/Core-Python-Code
|
/45. Tuple/6. tupleModification.py
| 585
| 4.125
| 4
|
# Modifying Tuple
a = (10, 20, -50, 21.3, 'GeekyShows')
print(a)
print()
# Not Possible to Modify like below line
#a[1] = 40 # Show TypeError
# It is not possible to modify a tuple but we can concate or slice
# to achieve desired tuple
# By concatenation
print("Modification by Concatenation")
b = (40, 50)
tup1 = a + b
print(tup1)
print()
# By Slicing
print("Modification by Slicing")
tup2 = a[0:3]
print(tup2)
print()
# By Concatenation and Slicing
print("Modification by Concatenation and Slicing")
c = (101, 102)
s1 = a[0:2]
s2 = a[3:]
tup3 = s1+c+s2
print(tup3)
print()
| true
|
a673f44d42f7a6ee67fa74814afac52099634358
|
ankitoct/Core-Python-Code
|
/38. Function/28. TwoDecoratorFunction.py
| 642
| 4.1875
| 4
|
# Two Decorator Function to same function
# Example 1
def decor(fun):
def inner():
a = fun()
add = a + 5
return add
return inner
def decor1(fun):
def inner():
b = fun()
multi = b * 5
return multi
return inner
def num():
return 10
result_fun = decor(decor1(num))
print(result_fun())
# Example 2
def decor(fun):
def inner():
a = fun()
add = a + 5
return add
return inner
def decor1(fun):
def inner():
b = fun()
multi = b * 5
return multi
return inner
@decor
@decor1
def num():
return 10
# result_fun = decor(decor1(num))
# print(result_fun()) instead of this directly call num function
print(num())
| false
|
74b872c0cdaec66aa6e378aed100b87079b91f6d
|
ankitoct/Core-Python-Code
|
/54. Nested Dictionary/3. AccessNestedDict1.py
| 375
| 4.40625
| 4
|
# Accessing Nested Dictionary using For loop
a = {1: {'course': 'Python', 'fees':15000},
2: {'course': 'JavaScript', 'fees': 10000 } }
# Accessing ID
print("ID:")
for id in a:
print(id)
print()
# Accessing each id keys
for id in a:
for k in a[id]:
print(k)
print()
# Accessing each id keys -- value
for id in a:
for k in a[id]:
print(id,'=',k,'=',a[id][k])
| false
|
bbf0d85066f85fae9f77a1a91d43237aaa3a1f57
|
ankitoct/Core-Python-Code
|
/9. if elif else Statement/1. ifelifelseStatement.py
| 472
| 4.40625
| 4
|
# If elif else Statement
day = "Tuesday"
if (day == "Monday"):
print("Today is Monday")
elif (day == "Tuesday"):
print("Today is Tuesday")
elif (day == "Wednesday"):
print("Today is Wednesday")
else:
print("Today is Holiday")
# If elif else with User Input
day = input("Enter Day: ")
if day == "Monday":
print("Today is Monday")
elif day == "Tuesday":
print("Today is Tuesday")
elif day == "Wednesday":
print("Today is Wednesday")
else:
print("Today is Holiday")
| false
|
7457008cab91ec66f819dcaec3f2b4bd4e69c627
|
ankitoct/Core-Python-Code
|
/36. Formatting String/7. FStringExample3.py
| 897
| 4.125
| 4
|
# Thousand Separator
price = 1234567890
print(f"{price:,}")
print(f"{price:_}")
#Variable
name = "Rahul"
age= 62
print(f"My name is {name} and age {age}")
# Expression
print(f"{10*8}")
# Expressing a Percentage
a = 50
b = 3
print(f"{a/b:.2%}")
# Accessing arguments items
value = (10, 20)
print(f"{value[0]} {value[1]}")
# Format with Dict
data = {'rahul': 2000, 'sonam': 3000}
print(f"{data['rahul']:d} {data['sonam']:d}")
# Calling Function
name= "GeekyShows"
print(f"{name}")
print(f"{name.upper()}")
# Using object created from class
#print(f"{obj.name}")
# Curly Braces
print(f"{10}")
print(f"{{10}}")
# Date and Time
from datetime import datetime
today = datetime(2019, 10, 5)
print(f"{today}")
print(f"{today:%d-%b-%Y}")
print(f"{today:%d/%b/%Y}")
print(f"{today:%b/%d/%Y}")
# Datetime Directive https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior
| false
|
a60165af0986981ea6097e34278a844d9b9b2f70
|
MirandaTowne/Python-Projects
|
/grade_list.py
| 754
| 4.46875
| 4
|
# Name: Miranda Towne
# Description: Creating a menu that gives user 3 choices
# Empty list
grade = []
done = False
new_grade = ''
# Menu options
menu = """
Grade Book
0: Exit
1: Display a sorted list of grades
2: Add a grade to the list
"""
# Display menu at start of a while loop
while not done:
print(menu)
# Ask for users choice
option = int(input('\nPlease enter an option: '))
# Respond to users choice
if option == 0:
done = True
print("Good bye!")
elif option == 1:
grade.sort
print(grade)
elif option == 2:
new_grade = input('\nPlease add a new grade to the list: ')
grade.append(new_grade)
print("\nGrade added to the list")
print(grade)
| true
|
ec40f68419b2a7c639bb9614cf1447f02927f529
|
kimalaacer/Head-First-Learn-to-Code
|
/chapter 12/dog4.py
| 1,205
| 4.34375
| 4
|
# this is an introduction to object oriented programming OOP
# dog class has some attributes (state) such as name, age, weight,and behavior ( or method) bark
class Dog:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def bark(self):
if self.weight > 29:
print(self.name, 'says "WOOF WOOF"')
else:
print(self.name, 'says "woof woof')
def human_years(self):
human_age = self.age * 7
return human_age
def __str__(self):
return "I'm a dog named " + self.name
def print_dog(dog):
print(dog.name+"'s",'age is', dog.age,'and weight is', dog.weight)
# all ServiceDog objects are Dog objects
#not all Dogs are Service Dogs.
class ServiceDog(Dog):
def __init__(self, name, age, weight, handler):
Dog.__init__(self, name, age, weight)
self.handler = handler
def walk(self):
print(self.name,'is helping its handler', self.handler, 'walk')
codie = Dog('Codie', 12, 38)
jackson = Dog('Jackson', 9, 12)
rody = ServiceDog('Rody', 8, 38, 'Joseph')
print(codie)
print(jackson)
print(rody)
| false
|
bffb8076b777e4962c687e0f9c790b5fafc93041
|
Silentsoul04/2020-02-24-full-stack-night
|
/1 Python/solutions/unit_converter.py
| 697
| 4.25
| 4
|
def convert_units(data):
conversion_factors = {
'ft': 0.3048,
'mi': 1609.34,
'm': 1,
'km': 1000,
'yd': 0.9144,
'in': 0.0254,
}
value, unit_from, unit_to = data
converted_m = conversion_factors[unit_from] * value
return round(converted_m / conversion_factors[unit_to], 2)
def main():
user_input = input('\nenter the distance: ')
convert_to_unit = input('\nenter units to convert to: ')
user_input_split = user_input.split(" ")
value = float(user_input_split[0])
unit = user_input_split[1]
print(f'\n{value} {unit} is {convert_units((value, unit, convert_to_unit))} {convert_to_unit}.\n')
main()
| true
|
63756dbda9070dd378118718383a7dbebcc469d9
|
haaks1998/Python-Simple
|
/07. function.py
| 1,011
| 4.1875
| 4
|
# A function is a set of statements that take inputs, do some specific computation and returns output.
# We can call function any number of times through its name. The inputs of the function are known as parameters or arguments.
# First we have to define function. Then we call it using its name.
# format:
# def func_name(arg1,arg2,..,argN):
# function statements
# return result
def add(a,b): #Function defination
c = a+b
return c
# Indentation shows that which statements are the part of functions.
# The indented statements are considered to be the part of function. Non indented statements are not part of function
# The code which is indented is in the body block and double indented code creates a block within a block
x = int(input("Enter first number "))
y = int(input("Enter second number "))
ans = add(x,y) #Function call
print(ans)
input("\nPress any key to exit")
| true
|
3dd22a089fd49714b6cd36abbd3e5a6a3c6a4d2b
|
rakipov/py-base-home-work
|
/py-home-work/tasks/horoscope.py
| 1,961
| 4.1875
| 4
|
# Простая задача из первых лекий для определения знака зодиака
day = int(input('Введите день: '))
month = (input('Введите месяц: ')).lower()
if day <= 31:
if (21 <= day <= 31 and month == 'март') or (1 <= day <= 20 and month == 'апрель'):
zodiac = 'Овен'
elif (21 <= day <= 30 and month == 'апрель') or (1 <= day <= 20 and month == 'май'):
zodiac = 'Телец'
elif (21 <= day <= 31 and month == 'май') or (1 <= day <= 21 and month == 'июнь'):
zodiac = 'Блезнецы'
elif (22 <= day <= 30 and month == 'июнь') or (1 <= day <= 22 and month == 'июль'):
zodiac = 'Рак'
elif (23 <= day <= 31 and month == 'июль') or (1 <= day <= 23 and month == 'август'):
zodiac = 'Лев'
elif (24 <= day <= 31 and month == 'август') or (1 <= day <= 23 and month == 'сентябрь'):
zodiac = 'Дева'
elif (24 <= day <= 30 and month == 'сентябрь') or (1 <= day <= 23 and month == 'октябрь'):
zodiac = 'Весы'
elif (24 <= day <= 31 and month == 'октябрь') or (1 <= day <= 22 and month == 'ноябрь'):
zodiac = 'Скорпион'
elif (23 <= day <= 30 and month == 'ноябрь') or (1 <= day <= 21 and month == 'декабрь'):
zodiac = 'Стрелец'
elif (22 <= day <= 31 and month == 'декабрь') or (1 <= day <= 20 and month == 'январь'):
zodiac = 'Козерог'
elif (21 <= day <= 31 and month == 'январь') or (1 <= day <= 18 and month == 'февраль'):
zodiac = 'Водолей'
elif (19 <= day <= 29 and month == 'февраль') or (1 <= day <= 20 and month == 'март'):
zodiac = 'Рыбы'
print(f'Ваш знак зодиака: {zodiac}')
else:
print('Введите корретные дату и месяц!')
| false
|
2d95625294be5907d014ea1c2c0a5c7c30640d34
|
feixuanwo/py_bulidinfunc
|
/myreverse_reversed.py
| 241
| 4.15625
| 4
|
#!:coding:utf-8
#reversed与reverse不同。前者是内置函数,后者是列表、字典的方法。前者返回一个新列表。
i = [x for x in range(-5,6)]
for x in reversed(i):
print x,
print
print i
print i.reverse()
print i
| false
|
1520b9faa5b957da64ea48e158adacc0e5987adf
|
pixeltk623/python
|
/Core Python/Datatypes/string.py
| 478
| 4.28125
| 4
|
# Strings
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
# 'hello' is the same as "hello".
# You can display a string literal with the print() function:
# print("Hello")
# print('Hello')
# a = "hello"
# print(a)
# a = """cdsa
# asdasdas
# asdasdassdasd
# asdasdsa"""
# print(a)
a = 'Hello, World'
# print(a[1])
# for x in a:
# print(x)
# print(len(a))
# print("Hello" in a)
# print("hello" not in a)
print(a[1:2])
| true
|
4b3f9e149707817aefa696ce2d336453cd93f34a
|
undergraver/PythonPresentation
|
/05_financial/increase.py
| 766
| 4.125
| 4
|
#!/usr/bin/env python
import sys
# raise in percent
raise_applied=6
raise_desired=40
# we compute:
#
# NOTE: the raise is computed annually
#
# 1. the number of years to reach the desired raise with the applied raise
# 2. money lost if the desired raise is applied instantly and no other raise is done
salary_now=100
desired_salary=salary_now*(1+raise_desired/100.0)
year_count=0
money_lost=0
while salary_now < desired_salary:
year_count+=1
salary_now=salary_now*(1+raise_applied/100.0)
money_lost += (desired_salary-salary_now)*12.0
print("You will reach desired salary in:%d years" % (year_count))
print("By that time you will lose:%f" % (money_lost))
if year_count > 0:
print("Average year loss is:%f" % (money_lost/year_count))
| true
|
6a293c64aabc496cc4e1669935d1659dc1042c39
|
Kjartanl/TestingPython
|
/TestingPython/Logic/basic_logic.py
| 368
| 4.21875
| 4
|
stmt = True
contradiction = False
if(stmt):
print("Indeed!")
if(contradiction):
print("Still true, but shouldn't be! Wtf?")
else:
print("I'm afraid I'm obliged to protest!")
print("------- WHILE LOOP ---------")
number = 0
while(number < 5):
print("Nr is %s" %number)
number = number+1
print("Finally, number is %s" % number)
| true
|
f4f9ba1982577f908487115093736c315f4a2c8c
|
aanantt/Sorting-Algorithms
|
/InsertionSort.py
| 253
| 4.21875
| 4
|
def insertionSort(array):
for i in range(len(array)):
j=i-1
while array[j] > array[j+1] and j >=0:
array[j], array[j+1] = array[j+1], array[j]
j -= 1
return array
print(insertionSort([1,5,8,2,9,0]))
| false
|
db4b2589fced75a64c6b55331dd7bbec12836441
|
Cary19900111/G7Cary
|
/Learn/crdataStrcuture/Array/dict/copycr.py
| 1,696
| 4.15625
| 4
|
from copy import copy,deepcopy
def copy_tutorial():
'''
第一层的id不一样,但是第二层的id是一样的,指向的是同一块地址
修改copy1,就会修改copy2
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = copy(dict_in)
dict_copy2 = copy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Before copy2:{}".format(dict_copy2))
print(f"dict_in id is {id(dict_in)}")
print("dict_copy1 id is %d" %id(dict_copy1))
print("dict_copy2 id is %d" %id(dict_copy2))
dict_copy1["favor"].append("footb")
print("After copy1:{}".format(dict_copy1))
print("After copy2:{}".format(dict_copy2))
print("dict_copy1.favor id is %d" %id(dict_copy1["favor"]))
print("dict_copy2.favor id is %d" %id(dict_copy2["favor"]))
def deepcopy_tutorial():
'''
第一层的id不一样,并且第二层的id也是不一样的,所以一般我们的复制都用deepcopy
返回一个完全独立变量
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = deepcopy(dict_in)
dict_copy2 = deepcopy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Before copy2:{}".format(dict_copy2))
print(f"dict_in id is {id(dict_in)}")
print("dict_copy1 id is %d" %id(dict_copy1))
print("dict_copy2 id is %d" %id(dict_copy2))
dict_copy1["favor"].append("footb")
print("After copy1:{}".format(dict_copy1))
print("After copy2:{}".format(dict_copy2))
print("dict_copy1.favor id is %d" %id(dict_copy1["favor"]))
print("dict_copy2.favor id is %d" %id(dict_copy2["favor"]))
if __name__=="__main__":
deepcopy_tutorial()
| false
|
fc2e497f6a4df5ed6002bb92dbcf4c5b3af8b393
|
2292527883/Learn-python-3-to-hard-way
|
/ex39/ex39.py
| 1,962
| 4.1875
| 4
|
# 字典
# create a mapping of state to abbreviation
statse = { # 定义字典
'Oregon': 'OR',
'Floida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some citise in them
cites = {
'CA': 'san Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more citise
cites['NY'] = 'New york' # 向字典cites 添加 'NY'对应'New york'
cites['OR'] = 'Oregon'
# 打印元素的对应元素
print('-' * 10 * 10)
print("Michigan's abbreviation is :", statse["Michigan"])
print("Floida's abbreviation is :", statse["Floida"])
# do it by using the state then cities dick
print('-' * 100)
# 查找states字典中的michigan对应的元素'MI' 来对应cites 的'Detroit'
print("Michigan has :", cites[statse['Michigan']])
print("Floida's abbreviation is :", cites[statse['Floida']])
# print ever state abbreviation
print('-' * 100)
for state, abbrev in list(statse.items()):
"""
在该循环中
state接受 key (密匙/键盘?)的值
abbrev接受 value(值)的值
字典(key:value)
item遍历字典用法:
for key , value in list#list(dic.items())
"""
print(f"{state} is abbrevuated {abbrev}")
# print every city in states
print('-' * 100)
for key, value in list(cites.items()):
print(f"{key} has the city {value}")
# now do both an the same time
print('-' * 100)
for key, value in list(statse.items()):
print(f"{key} state is abbreviated {value}")
print('-' * 100)
print(f"and has city {cites[value]}")
print("-" * 100)
# safely get a abbreviation by state that might not be thers
# get() 函数返回指定键的值,如果值不在字典中返回默认值None。
# 格式:get(指定值,返回值)
statse = statse.get('Texas')
if not statse: # statse为空值
print("sorry , no Texas")
# get a citu with a default value
city = cites.get('TX', 'Dose NOt Exist')
print(f"The city for the state 'TX' is {city}")
| false
|
134bf3bc84a1f0b67781d6f27656f24b81eef683
|
simonvantulder/Python_OOP
|
/python_Fundamentals/numberTwo.py
| 979
| 4.28125
| 4
|
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
#iterateDictionary(students)
# should output: (it's okay if each key-value pair ends up on 2 separate lines;
# bonus to get them to appear exactly as below!)
# first_name - Michael, last_name - Jordan
# first_name - John, last_name - Rosales
# first_name - Mark, last_name - Guillen
# first_name - KB, last_name - Tonel
def iterate_dictionary(some_list):
for x in some_list:
#print("%s and %s" %(key,value))
print("first_name - {}, last_name - {} ".format(first_name[x], last_name[x]))
# for x in range(len(some_list)):
# print(students[x])
iterate_dictionary(students)
first_name="Simon"
last_name="van Tulder"
age=24
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age))
| false
|
dd9dca4f015cb790227af5eb427850a1c8823202
|
PramodSuthar/pythonSnippets
|
/generator.py
| 670
| 4.15625
| 4
|
"""
def squence_num(nums):
result = []
for i in nums:
result.append(i*i)
return result
squared_list = squence_num([1,2,3,4,5])
print(squared_list)
"""
def squence_num(nums):
for i in nums:
yield(i*i)
##squared_list = squence_num([1,2,3,4,5])
"""
print(squared_list)
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
"""
## list comprehension
##squared_list = [x*x for x in [1,2,3,4,5]]
## generator
squared_list = (x*x for x in [1,2,3,4,5])
for num in squared_list:
print(num)
| false
|
0e07914cfa997c6ee2bef28123972e089f49b454
|
montaro/algorithms-course
|
/P0/Task4.py
| 1,234
| 4.125
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
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.
"""
callers = set()
non_telemarketers = set()
telemarketers = set()
for call in calls:
caller = call[0]
callee = call[1]
callers.add(caller)
non_telemarketers.add(callee)
for text in texts:
sender = text[0]
receiver = text[1]
non_telemarketers.add(sender)
non_telemarketers.add(receiver)
telemarketers = callers.difference(non_telemarketers)
sorted_telemarketers = sorted(telemarketers)
print('These numbers could be telemarketers: ')
for telemarketer in sorted_telemarketers:
print(telemarketer)
| true
|
d3eb57ca3377dcb7462afd86e43997a1f220e940
|
shivanshutyagi/python-works
|
/primeFactors.py
| 566
| 4.3125
| 4
|
def printPrimeFactors(num):
'''
prints primeFactors of num
:argument: number whose prime factors need to be printed
:return:
'''
for i in range(2, num+1):
if isPrime(i) and num%i==0:
print(i)
def isPrime(num):
'''
Checks if num is prime or not
:param num:
:return: true if num is prime, else false
'''
for i in range(2, int(num/2)+1):
if num % i == 0:
return False
return True
if __name__ == "__main__":
n = int(input('Enter the number: '))
printPrimeFactors(n)
| true
|
a89ba3ea381c392845379d369981fca1a0a16d1b
|
roberg11/is-206-2013
|
/Assignment 2/ex13.py
| 1,150
| 4.4375
| 4
|
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
## Combine raw_input with argv to make a script that gets more input
## from a user.
fruit = raw_input("Name a fruit: ")
vegetable = raw_input("Name a vegetable: ")
print "The name of the fruit: %r. The name of the vegetable: %r." % (fruit, vegetable)
#### Study drills
## Try giving fewer than three arguments to your script.
## See that error you get? See if you can explain it.
## Answer: ValueError: need more than 3 values to unpack.
# Because the script assigns four values to pass the
# ArgumentValue the program won't run with less or more.
## Write a script that has fewer arguments and one that has more.
## Make sure you give the unpacked variables good names.
# Answer: 'python ex13.py apple orange' gives the error:
# ValueError: need more than 3 values to unpack
## Remember that modules give you features. Modules. Modules.
## Remember this because we'll need it later.
| true
|
c232410e848da610102a0a08b4077aa2295847b0
|
roberg11/is-206-2013
|
/Assignment 2/ex20.py
| 1,803
| 4.53125
| 5
|
from sys import argv
script, input_file = argv
# Definition that reads a file given to the parameter
def print_all(f):
print f.read()
# Definition that 'seeks' to the start of the file (in bytes) given to parameter
# The method seek() sets the file's current position at the
# offset. The whence argument is optional and defaults to 0,
# which means absolute file positioning, other values are 1
# which means seek relative to the current position and 2 means
# seek relative to the file's end.
def rewind(f):
f.seek(0)
# Definition taking two parameters that counts the lines in the file
# and reads each line and prints them.
def print_a_line(line_count, f):
print line_count, f.readline()
# Variable assigned to the method of opening the file given to argument variable
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
## Each time print_a_line is run, you are passing in a variable
## current_line. Write out what current_line is equal to on
## each function call, and trace how it becomes line_count in
## print_a_line.
current_line = 1
# Current line is 1 in this function call
print_a_line(current_line, current_file)
# Current line is 1 + 1 = 2 in this function call
current_line = current_line + 1
print "This is line nr: %r\n" % current_line
print_a_line(current_line, current_file)
# Current line is 2 + 1 = 3 in this function call
current_line = current_line + 1
print "This is line nr: %r\n" % current_line
print_a_line(current_line, current_file)
## Research the shorthand notation += and rewrite the script to use that.
## current_line += 1 is the equivalent of saying current_line = current_line + 1
| true
|
676817b23e15e5368746b750f48e518427c937ae
|
onerbs/w2
|
/structures/w2.py
| 1,914
| 4.28125
| 4
|
from abc import ABC, abstractmethod
from typing import Iterable
from structures.linked_list_extra import LinkedList
class _Linear(ABC):
"""Abstract linear data structure."""
def __init__(self, items: Iterable = None):
self._items = LinkedList(items)
def push(self, item):
"""Adds one item."""
self._items.push(item)
@abstractmethod
def pop(self):
"""Removes one item.
:returns: The removed item.
"""
pass
def is_empty(self):
return self._items.is_empty()
def __contains__(self, item):
return item in self._items
def __iter__(self) -> iter:
return iter(self._items)
def __len__(self) -> int:
return len(self._items)
def __str__(self) -> str:
return str(self._items)
class Stack(_Linear):
def push(self, item): # O(1)
"""Adds one item to the stack."""
super().push(item)
def pop(self): # O(n)
"""Removes the oldest item from the stack."""
return self._items.pop() # LIFO
class Queue(_Linear):
def push(self, item): # O(1)
"""Adds one item to the queue."""
super().push(item)
def pop(self): # O(1)
"""Removes the most resent item from the queue."""
return self._items.shift() # FIFO
class Deque(_Linear):
def push(self, item): # O(1)
"""Adds one item to the end of the deque."""
super().push(item)
def pop(self): # O(n)
""" Removes the last item from the deque.
:returns: The removed item.
"""
return self._items.pop()
def unshift(self, value): # O(1)
"""Adds one item to the beginning of the deque."""
self._items.unshift(value)
def shift(self): # O(1)
"""Removes the first item from the deque.
:returns: The removed item.
"""
return self._items.shift()
| true
|
7f7b411883c7f6985a354f163a11da1a879b0cac
|
nishaagrawal16/Datastructure
|
/Python/decorator_for_even_odd.py
| 1,363
| 4.21875
| 4
|
# Write a decorator for a function which returns a number between 1 to 100
# check whether the returned number is even or odd in decorator function.
import random
def decoCheckNumber(func):
print ('Inside the decorator')
def xyz():
print('*************** Inside xyz *********************')
num = func()
print(num)
if num %2 != 0: # Odd
print('number is odd')
else:
print('number is Even')
return xyz
@decoCheckNumber
def random_number():
return random.randrange(1, 100)
for i in range(10):
random_number()
# Output:
# ------
#
# Inside the decorator
# *************** Inside xyz *********************
# 17
# number is odd
# *************** Inside xyz *********************
# 3
# number is odd
# *************** Inside xyz *********************
# 6
# number is Even
# *************** Inside xyz *********************
# 32
# number is Even
# *************** Inside xyz *********************
# 66
# number is Even
# *************** Inside xyz *********************
# 84
# number is Even
# *************** Inside xyz *********************
# 96
# number is Even
# *************** Inside xyz *********************
# 45
# number is odd
# *************** Inside xyz *********************
# 14
# number is Even
# *************** Inside xyz *********************
# 64
# number is Even
| true
|
aa5bc400ed332b046f45db6233975294afa48494
|
nishaagrawal16/Datastructure
|
/Linklist/partition_a_link_list_by_a_given_number.py
| 2,555
| 4.125
| 4
|
#!/usr/bin/python
# Date: 2018-09-17
#
# Description:
# There is a linked list given and a value x, partition a linked list such that
# all element less x appear before all elements greater than x.
# X should be on right partition.
#
# Like, if linked list is:
# 3->5->8->5->10->2->1 and x = 5
#
# Resultant linked list should be:
# 3->2->1->5->8->5->10
#
# Approach:
# Maintain 2 linked list 'BEFORE' and 'AFTER'. Traverse given linked list, if
# value at current node is less than x insert this node at end of 'BEFORE'
# linked list otherwise at end of 'AFTER' linked list.
# At the end, merge both linked lists.
#
# Complexity:
# O(n)
class Node:
def __init__(self, value):
self.info = value
self.next = None
class LinkList:
def __init__(self):
self.start = None
def create_list(self, li):
if self.start is None:
self.start = Node(li[0])
p = self.start
for i in range(1,len(li)):
temp = Node(li[i])
p.next = temp
p = p.next
def traverse(self):
p = self.start
while p is not None:
print('%d ->' % p.info, end='')
p = p.next
print ('None')
def partitionList(self, x):
before_start = None
before_end = None
after_start = None
after_end = None
p = self.start
present = 0
while p is not None:
if p.info == x:
present = 1
if p.info < x:
if before_start is None:
before_start = p
before_end = p
else:
before_end.next = p
before_end = before_end.next
else:
if after_start is None:
after_start = p
after_end = p
else:
after_end.next = p
after_end = after_end.next
p = p.next
if not present:
print('Element %d is not present in the list.' % x)
return False
# May be possible that before list is empty as no numebr is less than x.
# so check the before end is not None otherwise make the after_start as
# starting point of the list.
after_end.next = None
if before_end is None:
self.start = after_start
return True
# merge both link lists
before_end.next = after_start
self.start = before_start
return True
def main():
print ('*************** LIST ***********************')
link_list_1 = LinkList()
link_list_1.create_list([3, 5, 8, 5, 10, 2, 1])
link_list_1.traverse()
print ('\n***** LIST AFTER PARTITIONS BY A NUMBER *****')
if link_list_1.partitionList(5):
link_list_1.traverse()
if __name__ == '__main__':
main()
| true
|
bf13df5bf072797b535624bca57f87f5f5c7b39c
|
nishaagrawal16/Datastructure
|
/sorting/bubble_sort.py
| 1,314
| 4.6875
| 5
|
# Date: 20-Jan-2020
# https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# Bubble Sort is the simplest sorting algorithm that works by
# repeatedly swapping the adjacent elements if they are in wrong order.
# Once the first pass completed last element will be sorted.
# On next pass, we need to compare till last-1 elements and in next pass
# last-2,...so on
# Example:
# list: [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
# Pass1: [5, 6, 8, 1, 4, 9, 3, 2, 7, 10]
# ---- Sorted
# Pass2: [5, 6, 1, 4, 8, 3, 2, 7, 9, 10]
# -------- Sorted
# .... So on
# Time Complexity: O(n2)
# Space Complexity: O(1)
def bubble_sort(un_list):
n = len(un_list)
for i in range(n):
for j in range(n-1-i):
if un_list[j] > un_list[j+1]:
un_list[j+1], un_list[j] = un_list[j], un_list[j+1]
def main():
unsorted_list = [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
print('************ UNSORTED LIST **************')
print(unsorted_list)
bubble_sort(unsorted_list)
print('************** SORTED LIST **************')
print(unsorted_list)
if __name__ == '__main__':
main()
# Output:
# -------
# ************ UNSORTED LIST **************
# [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
# ************** SORTED LIST **************
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
| true
|
da785b4c17fbed0a35787f7db82ee578ffaf07bf
|
nishaagrawal16/Datastructure
|
/Python/overriding.py
| 2,643
| 4.46875
| 4
|
# Python program to demonstrate error if we
# forget to invoke __init__() of parent.
class A(object):
a = 1
def __init__(self, n = 'Rahul'):
print('A')
self.name = n
class B(A):
def __init__(self, roll):
print('B')
self.roll = roll
# If you forget to invoke the __init__()
# of the parent class then its instance variables would not be
# available to the child class.
# The self parameter within super function acts as the object of
# the parent class
super(B, self).__init__()
# OR
# A.__init__(self)
b = B(23)
print(b.roll)
print(b.name)
print(b.a)
# Output:
# -------
# B
# A
# 23
# Rahul
# 1
# Python program to demonstrate private members of the parent class
class C(object):
def __init__(self):
self.c = 21
# d is private instance variable
self.__d = 42
class D(C):
def __init__(self):
self.e = 84
self.__f = 99
C.__init__(self)
object1 = D()
print(dir(object1))
# This is the way to call the private variables
print(object1._C__d)
print(object1._D__f)
# produces an error as d is private instance variable
# print D.d
# Output:
# ------
# ['_C__d', '_D__f', '__class__', '__delattr__', '__dict__', '__doc__',
# '__format__', '__getattribute__', '__hash__', '__init__', '__module__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'c', 'e']
# 42
# 99
# Python code to demonstrate multiple inheritance
# we cannot override a private method of a superclass, which is the one having
# double underscores before its name.
# Base Class
class A(object):
def __init__(self):
constant1 = 1
def __method1(self):
print('method1 of class A')
class B(A):
def __init__(self):
constant2 = 2
A. __init__(self)
def __method1(self):
print('method1 of class B')
def calling1(self):
self.__method1()
self._A__method1()
b = B()
# AttributeError: 'B' object has no attribute '__method1'
# b.__method1()
# How to call the private methods of a class.
b._B__method1()
b._A__method1()
print('******* Calling1 **************')
b.calling1()
# Output:
# ------
# method1 of class B
# method1 of class A
# ******* Calling1 **************
# method1 of class B
# method1 of class A
| true
|
fee51facfda5df96e5aa73eaf6f7d3962df39c2c
|
cherkesky/urbanplanner
|
/city.py
| 762
| 4.59375
| 5
|
'''
In the previous Urban Planner exercise, you practices defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods.
Name of the city.
The mayor of the city.
Year the city was established.
A collection of all of the buildings in the city.
A method to add a building to the city.
Remember, each class should be in its own file. Define the City class in the city.py file.
'''
class City:
def __init__ (self, name, mayor, year_established):
self.name = name
self.mayor = mayor
self.year_established = year_established
self.city_buildings = list()
def addBuildings(self, building):
self.city_buildings.append(building)
| true
|
8da1b3e55c7d3c0f941d28d2395c1e1d353be217
|
spikeyball/MITx---6.00.1x
|
/Week 1 - Problem 3.py
| 1,002
| 4.125
| 4
|
# Problem 3
# 15.0/15.0 points (graded)
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print
#
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print
#
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart. If
# you've spent more than a few hours on this problem, we suggest that you move on
# to a different part of the course. If you have time, come back to this problem
# after you've had a break and cleared your head.
lstring = s[0]
cstring = s[0]
for char in s[1::]:
if char >= cstring[-1]:
cstring += char
if len(cstring) > len(lstring):
lstring = cstring
else:
cstring = char
print(lstring)
| true
|
776a2822e9a89368babe21c0289fa93e4f1b6e55
|
CaptainMich/Python_Project
|
/StartWithPython/StartWithPython/Theory/OOP/Class.py
| 2,994
| 4.25
| 4
|
# -------------------------------------------------------------------------------------------------
# CLASS
# -------------------------------------------------------------------------------------------------
print('\n\t\tCLASS\n')
class Enemy: # define a class;
# group similiar variables and function togheter
life = 3 # ...
def attack(self): # ...
print('\tOuch -> life -1') # ...
self.life -= 1 # ...
def checkLife(self): # ...
if self.life <= 0: # ...
print('\tI am dead') # ...
else: # ...
print('\t' + str(self.life) + ' life left') # ...
firstEnemy = Enemy() # how to access to the class
print('Enemy_One:') # ...
firstEnemy.checkLife() # ...
firstEnemy.attack() # ...
firstEnemy.checkLife() # ...
print('')
secondEnemy = Enemy() # access again to the class and discover that
print('Enemy_Two:') # each object is indipendent of one another
secondEnemy.checkLife() # ...
secondEnemy.attack() # ...
secondEnemy.attack() # ...
secondEnemy.attack() # ...
secondEnemy.checkLife() # ...
# -------------------------------------------------------------------------------------------------
# CLASS __INIT__
# -------------------------------------------------------------------------------------------------
print('\n\n\t\tCLASS __INIT__\n')
class Character:
def __init__(self, x): # __init__ = initialize --> pass a value to them and use
self.energy = x # it in a different way for the object that we'll create
def get_energy(self): # ...
return self.energy # ...
Pippo = Character(5) # initialize Pippo's energy to 5
Pluto = Character(18) # initialize Pluto's energy to 18
print('Pippo energy is ' + str(Pippo.get_energy()))
print('Pluto energy is ' + str(Pluto.get_energy()) + '\n')
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.