blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
6a29cb24698e9390ac9077d431d6f9001386ed84
|
lakshay-saini-au8/PY_playground
|
/random/day26.py
| 1,164
| 4.28125
| 4
|
# Write a program to find a triplet that sums to a given value with improved time complexity.
'''
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24;
Output: 12, 3, 9
Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
'''
# brute force apporach
def triplet(arr, sums):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j]+arr[k] == sums:
print(arr[i], arr[j], arr[k])
# triplet([12,3,4,1,6,9],24)
# triplet([1,2,3,4,5],9)
# Write a program to find a triplet such that the sum of two equals to the third element with improved time complexity
def triplet_sum(arr):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j] == arr[k] or arr[j]+arr[k] == arr[i] or arr[k]+arr[i] == arr[j]:
print(arr[i], arr[j], arr[k])
triplet_sum([5, 32, 1, 7, 10, 50, 19, 21, 2])
# triplet_sum([5,32,1,7,10,50,19,21,0])
| true
|
fce872e76b3da0255f503a85d718dc36fd739dd6
|
Niraj-Suryavanshi/Python-Basic-Program
|
/7.chapter/12_pr_03.py
| 224
| 4.125
| 4
|
num=int(input("Enter a number: "))
prime=True
for i in range(2,num):
if(num%i==0):
prime=False
break
if prime:
print("Number is prime")
else:
print("Number is not prime")
| true
|
8d15cc01aa2db01da9ea285fc234cae188e5c0cf
|
Niraj-Suryavanshi/Python-Basic-Program
|
/3.chapter/06_pr_02.py
| 210
| 4.40625
| 4
|
letter='''Dear <|Name|>
you are selected
date: <|date|>'''
name=input("Enter your name:")
date=input("Enter a date:")
letter=letter.replace("<|Name|>",name)
letter=letter.replace("<|date|>",date)
print(letter)
| false
|
69f491abbf9b757d6dc5b7fe6d5e7cd925785389
|
flerdacodeu/CodeU-2018-Group8
|
/cliodhnaharrison/assignment1/question1.py
| 896
| 4.25
| 4
|
#Using Python 3
import string
#Input through command line
string_one = input()
string_two = input()
def anagram_finder(string_one, string_two, case_sensitive=False):
anagram = True
if len(string_one) != len(string_two):
return False
#Gets a list of ascii characters
alphabet = list(string.printable)
if not case_sensitive:
#Case Insensitive so making sure only lowercase letters in strings
string_one = string_one.lower()
string_two = string_two.lower()
for char in alphabet:
if anagram:
#Counts occurences of a character in both strings
#If there is a difference it returns False
if string_one.count(char) != string_two.count(char):
anagram = False
else:
return anagram
return anagram
#My Testing
#print (anagram_finder(string_one, string_two))
| true
|
c425fd70a75756fa84add2f21f7593b8e91b1203
|
flerdacodeu/CodeU-2018-Group8
|
/aliiae/assignment3/trie.py
| 2,519
| 4.40625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Optional follow-up:
Implement a dictionary class that can be constructed from a list of words.
A dictionary class with these two methods:
* isWord(string): Returns whether the given string is a valid word.
* isPrefix(string): Returns whether the given string is a prefix of at least one
word in the dictionary.
Assumptions:
The dictionary is a trie implemented as node objects with children stored in
a hashmap.
"""
from collections import defaultdict
class Trie:
def __init__(self, words=None):
"""
Implement a trie node that has trie children and bool if it ends a word.
Args:
words: A list of words that can be inserted into the trie.
"""
self.children = defaultdict(Trie)
self._is_word_end = False
if words:
self.insert_words(words)
def __str__(self):
return ' '.join(self.children)
def insert_words(self, words):
"""
Insert a list of words into the trie.
Args:
words: A list of words to be inserted into the trie.
Returns: None
"""
for word in words:
self.insert_word(word)
def insert_word(self, word):
"""
Insert a word into the trie.
Args:
word: A word to be inserted into the trie.
Returns: None
"""
current = self
for letter in word:
current = current.children[letter]
current._is_word_end = True
def is_word(self, word):
"""
Return whether the given string is a valid word.
Args:
word: The word to look for.
Returns: True if the word is found, else False.
"""
current = self
for letter in word:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return current._is_word_end
def is_prefix(self, prefix):
"""
Return whether the given string is a prefix of at least one word.
Args:
prefix: Prefix to search for in the trie.
Returns: True if the string is a prefix of a word, else False.
"""
current = self
for letter in prefix:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return True
| true
|
6ddf930b444a33d37a4cc79308577c45cf45af96
|
Saraabd7/Python-Eng-54
|
/For_loops_107.py
| 1,117
| 4.21875
| 4
|
# For loops
# Syntax
# for item in iterable: mean something you can go over for e.g: list
# block of code:
import time
cool_cars = ['Skoda felicia fun', 'Fiat abarth the old one', 'toyota corola, Fiat panda 4x4', 'Fiat Multipla']
for car in cool_cars:
print(car)
for lunch_time in cool_cars:
print(car)
time.sleep(1)
print('1 -', cool_cars[0])
Count = 0 # first number being used ( to do the count for points.
for car in cool_cars:
print(Count + 1, '-', car)
Count += 1
# For Loop for dictionaries:
boris_dict = {
'name': 'boris',
'l_name': 'Johnson',
'phone': '0784171157',
'address': '10 downing street'}
for item in boris_dict:
print(item)
# this item is the key so we change it to key:
for key in boris_dict:
print(key)
# I want each individual values
# for this i need, dictionary + key
print(boris_dict[key])
print(boris_dict['phone'])
# for key in boris_dict:
# print(boris_dict['phone'])
# print(boris_dict['name'])
for value in boris_dict.values():
print(value)
print('Name:', 'Boris Johnson')
print('phone:', '0784171157')
| true
|
933c9d74c3dee9ac64fefe649af9aba3dcffce02
|
dmonzonis/advent-of-code-2017
|
/day24/day24.py
| 2,809
| 4.34375
| 4
|
class Bridge:
"""Represents a bridge of magnetic pieces.
Holds information about available pieces to construct the bridge, current pieces used
in the bridge and the available port of the last piece in the bridge."""
def __init__(self, available, bridge=[], port=0):
"""Initialize bridge variables."""
self.available = available
self.bridge = bridge
self.port = port
def strength(self):
"""Return the strength of the current bridge."""
return sum([sum([port for port in piece]) for piece in self.bridge])
def fitting_pieces(self):
"""Return a list of pieces that can be used to extend the current bridge."""
return [piece for piece in self.available if self.port in piece]
def add_piece(self, piece):
"""Return a new bridge with the piece added to it and removed from the available list."""
new_bridge = self.bridge + [piece]
# The new port is the unmatched port in the added piece
new_port = piece[0] if piece[1] == self.port else piece[1]
new_available = self.available[:]
new_available.remove(piece)
return Bridge(new_available, new_bridge, new_port)
def find_strongest(pieces):
"""Find strongest bridge constructable with a given list of pieces."""
max_strength = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def find_strongest_longest(pieces):
"""Find strongest bridge from the longest bridges constructable with a list of pieces."""
max_strength = max_length = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
length = len(bridge.bridge)
if length > max_length:
max_length = length
max_strength = bridge.strength()
elif length == max_length:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
max_length = length
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def main():
with open("input") as f:
pieces = [[int(x), int(y)] for x, y in [p.split('/') for p in f.read().splitlines()]]
# print("Part 1:", find_strongest(pieces))
print("Part 2:", find_strongest_longest(pieces))
if __name__ == "__main__":
main()
| true
|
a68e2b0be94ba93bb4e9d123c55af80297ddc5d6
|
dmonzonis/advent-of-code-2017
|
/day19/day19.py
| 1,866
| 4.34375
| 4
|
def step(pos, direction):
"""Take a step in a given direction and return the new position."""
return [sum(x) for x in zip(pos, direction)]
def turn_left(direction):
"""Return a new direction resulting from turning 90 degrees left."""
return (direction[1], -direction[0])
def turn_right(direction):
"""Return a new direction resulting from turning 90 degrees right."""
return (-direction[1], direction[0])
def get_tile(roadmap, pos):
"""With a position in the form (x, y), return the tile in the roadmap corresponding to it."""
x, y = pos
return roadmap[y][x]
def follow_roadmap(roadmap):
"""Follow the roadmap and return the list of characters encountered and steps taken."""
direction = (0, 1) # Start going down
valid_tiles = ['-', '|', '+'] # Valid road tiles
collected = []
steps = 1
pos = (roadmap[0].index('|'), 0) # Initial position in the form (x, y)
while True:
new_pos = step(pos, direction)
tile = get_tile(roadmap, new_pos)
if tile == ' ':
# Look for a new direction left or right
if get_tile(roadmap, step(pos, turn_left(direction))) != ' ':
direction = turn_left(direction)
continue
elif get_tile(roadmap, step(pos, turn_right(direction))) != ' ':
direction = turn_right(direction)
continue
else:
# We got to the end of the road
return collected, steps
elif tile not in valid_tiles:
collected.append(tile)
pos = new_pos
steps += 1
def main():
with open("input") as f:
roadmap = f.read().split('\n')
collected, steps = follow_roadmap(roadmap)
print("Part 1:", ''.join(collected))
print("Part 2:", steps)
if __name__ == "__main__":
main()
| true
|
73521ec81d51bc78eeda2c636402f9be0e796776
|
mahidhar93988/python-basics-nd-self
|
/difference_sum_even_odd_index.py
| 539
| 4.125
| 4
|
# difference_sum_even_odd_index
# You should name your function as difference_sum_even_odd_index
# It should take a list of integers
# Return an integer
def difference_sum_even_odd_index(arr):
e = 0
o = 0
for i in range(len(arr)):
if i % 2 == 0:
e += arr[i]
else:
o += arr[i]
return e-o
# Do not change anything below this line
if __name__ == "__main__":
numbers = [int(i) for i in input().split(' ')]
print(difference_sum_even_odd_index(numbers))
| false
|
e140bd8915d97b4402d63d2572c056e61a0d9e5a
|
presstwice/Python-
|
/data_camp/simple_pendulum.py
| 487
| 4.1875
| 4
|
# Initialize offset
offset = -6
# Code the while loop
while offset != 0 :b # The goal is to get offset to always equal 0
print("correcting...") # Prints correcting to clearly state the loop point
if offset > 0: # You start the if statement by checking if the offset is positive
offset = offset - 1 # If so bring the offset closer to 0 by -1
else:
offset = offset + 1 # if its not positive then it must be negative bring it closer to 0 + 1
print(offset)
| true
|
d22f5a9a6851525504cc7e4f1952a2bbb8ab27ae
|
BalaRajendran/guvi
|
/large.py
| 336
| 4.21875
| 4
|
print ("Find the largest number amoung three numbers");
num=list()
arry=int(3);
a=1;
for i in range(int(arry)):
print ('Num :',a);
a+=1;
n=input();
num.append(int(n))
if (num[0]>num[1] and num[0]>num[2]):
print (num[0]);
elif (num[1]>num[0] and num[1]>num[2]):
print (num[1]);
else:
print(num[2]);
| true
|
ca0409110b5846759427529b9a487ea95a84dadc
|
Sandhya-02/programming
|
/0 Python old/09_sandeep_milk_using_list.py
| 504
| 4.15625
| 4
|
"""
mummy and sandeep went for shopping
sandeep trolley lo [eggs , meat,small milk packet, bread,jam,] teskocchadu
mummy said get big milk packet
sandeep small milk packet ni teesesi big milk packet bag lo pettukunnadu
"""
list = ["eggs","meat","small milk packet","bread","jam"]
print(list)
if "small milk packet" in list:
list.remove("small milk packet")
""" del(4) pop(3)"""
list.append("big milk packet")
""" insert """
print("after removing small milk packet =",list)
| false
|
5e0c461e5b4d1f9e6c328dcc78d88b5c8a08d410
|
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
|
/students/AndrewMiotke/lesson04/class_work/generators.py
| 466
| 4.21875
| 4
|
"""
Generators are iterators that returns a value
"""
def y_range(start, stop, step=1):
""" Create a generator using yield """
i = start
while i < stop:
"""
yield, like next(), allows you to increment your flow control
e.g. inside a loop
"""
yield i
i += step
it = y_range(12, 25)
next(it) # this returns 12
next(it) # this returns 13
# Generators in a list comprehension
[y for y in y_range(12, 25)]
| true
|
bb0828b74f6eb99c20ffc39e3cae82f0816ada65
|
droidy12527/AlgorithmsInPythonandCpp
|
/anargrams.py
| 409
| 4.125
| 4
|
def findAnargrams(arr):
answers = []
m = {}
for elements in arr:
make = ''.join(sorted(elements))
if make not in m:
m[make] = []
m[make].append(elements)
for hello in m.values():
answers.append(hello)
return answers
arr = [ "eat", "tea", "tan", "ate", "nat", "bat" ]
answer = findAnargrams(arr)
print('The anargrams are {}'.format(answer))
| false
|
2948bcec98743ca4b12feb2828c6337ce22673ae
|
ishmatov/GeekBrains-PythonBasics
|
/lesson03/task_03_03.py
| 840
| 4.1875
| 4
|
"""
3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших
двух аргументов.
"""
def check_num(value):
try:
return True, int(value)
except ValueError:
print("Не число. Попробуйте ещё раз")
return False, -1
def sum_doble_max(num1, num2, num3):
return max(num1 + num2, num1 + num3, num2 + num3)
i = 0
list_num = []
while True and i < 3:
check, num = check_num(input(f"{i + 1} - Введите целое число: "))
if check:
list_num.append(num)
i += 1
print(f"Сумма из двух максимальных числе из {list_num} = ", sum_doble_max(list_num[0], list_num[1], list_num[2]))
| false
|
6c3c8bbae37317462a202481c0474008869186c5
|
ishmatov/GeekBrains-PythonBasics
|
/lesson01/task_01_06.py
| 1,914
| 4.1875
| 4
|
"""
6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который
общий результат спортсмена составить не менее b километров. Программа должна принимать значения параметров a и b и
выводить одно натуральное число — номер дня.
Например: a = 2, b = 3.
Результат:
1-й день: 2
2-й день: 2,2
3-й день: 2,42
4-й день: 2,66
5-й день: 2,93
6-й день: 3,22
Ответ: на 6-й день спортсмен достиг результата — не менее 3 км.
"""
while True:
begin = input("Введите результат начальной пробежки. (Целое положительное число): ")
if begin.isdigit() and int(begin) > 0:
break
while True:
finish = input("Введите желаемый результат (км). (Целое положительное число): ")
if finish.isdigit() and int(finish) > 0:
if int(finish) <= int(begin):
print(f"Конечный результат должен быть больше начального результата - {begin} км.")
continue
else:
break
result = int(begin)
day = 1
while True:
print(f"{day}-й день: {result:.2f}")
if result >= int(finish):
break
result += result * 0.1
day += 1
print(f"Ответ: на {day}-й день спортсмен пробежит - не менее {finish} км")
| false
|
603e12a667b8908776efbfef8d015c5e12b390c8
|
Super1ZC/PyTricks
|
/PyTricks/use_dicts_to_emulate_switch_statements.py
| 761
| 4.375
| 4
|
def dispatch_if(operator,x,y):
"""This is similar to calculator"""
if operator == 'add':
return x+y
elif operator == 'sub':
return x-y
elif operator == 'mul':
return x*y
elif operator == 'div':
return x/y
else:
return None
def dispatch_dict(operator,x,y):
"""Using anonymous function lambda to display."""
return{
'add':lambda: x+y,
'sub':lambda: x-y,
'mul':lambda: x*y,
#dict.get function,return None when the operator
#is not key in dict
'div':lambda: x/y,}.get(operator,lambda:None)()
print(dispatch_if('mul',2,8))
print(dispatch_dict('mul',2,8))
print(dispatch_if('unknown',2,8))
print(dispatch_dict('unknown',2,8))
| true
|
1af51d9ed56217484ab6060fc2f36ee38e9523df
|
rgvsiva/Tasks_MajorCompanies
|
/long_palindrome.py
| 560
| 4.21875
| 4
|
#This was asked by AMAZON.
#Given a string, find the longest palindromic contiguous substring.
#if there are more than one, prompt the first one.
#EX: for 'aabcdcb'-->'bcdcb'
main_St=input("Enter the main string: ")
st=main_St
palindrome=[st[0]]
while len(st)>1:
sub=''
for ch in st:
sub+=ch
if (sub==sub[::-1]) and (sub not in palindrome) and (len(sub)>len(palindrome[-1])):
palindrome=[sub]
st=st[1:]
print ('Longest palindromic substring: "',palindrome[0],'" at index-',main_St.index(palindrome[0]))
| true
|
78c17dc8b972e01ea7641e37fdcd4d35222ae513
|
GandT/learning
|
/Python/season2/p015-016/p016.py
| 987
| 4.28125
| 4
|
# coding: UTF-8
"""
2018.4.13
指定された月の日数を返す(閏年を考慮)
"""
def day_of_month(year, month):
# 不正な月が指定された場合Noneを返す
if type(year) != int or type(month) != int or not(1 <= month <= 12):
return None
# 2月を除くハッシュテーブル(辞書)の作成
table = {
1: 31, 2: -1, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
}
# 年から2月の値を確定
table[2] = 29 if (year % 400 == 0) or ((year % 100 != 0) and (year % 4 == 0)) else 28
# テーブルから結果を返す
return table[month]
print( day_of_month( 1, 1) )
print( day_of_month(87346894238473687461, 3) )
print( day_of_month(1000,13) )
print( day_of_month(2001, 2) )
print( day_of_month(2004, 2) )
print( day_of_month(2100, 2) )
print( day_of_month(2000, 2) )
print( day_of_month(100.4, 3) )
print( day_of_month(1999, "アポカリプス") )
| false
|
b6aca7b55b08724d2a922f3788cc2b15c4465f8e
|
webclinic017/davidgoliath
|
/Project/modelling/17_skewness.py
| 1,280
| 4.125
| 4
|
# skewness python
# https://www.google.com/search?q=skewness+python&oq=Skewness+python&aqs=chrome.0.0l4j0i22i30l6.3988j0j4&sourceid=chrome&ie=UTF-8
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
# https://www.geeksforgeeks.org/scipy-stats-skew-python/
''' Statistical functions
In simple words, skewness is the measure of how much the
probability distribution of a random variable deviates
from the normal distribution.
# https://www.investopedia.com/terms/s/skewness.asp
skewness = 0 : normally distributed.
skewness > 0 : more weight in the left tail of the distribution.
skewness < 0 : more weight in the right tail of the distribution.
'''
# part 1 ----------------------------------
import numpy as np
from scipy.stats import skew
import pandas as pd
arr = np.random.randint(1, 10, 10)
arr = list(arr)
# print(arr)
# # more weight in the right when skew>0,
# # determine skew close enough to zero
# print(skew(arr))
# print(skew([1, 2, 3, 4, 5]))
# part 2 ----------------------------------
# df = pd.read_csv('Data/nba.csv')
df = pd.read_csv('Data/XAUNZD_Daily.csv')
# print(df.tail())
# skewness along the index axis
print(df.skew(axis=0, skipna=True))
# skewness of the data over the column axis
# print(df.skew(axis=1, skipna=True))
| true
|
920fbc4957ec799af76035cbb258f2f41392f030
|
Reskal/Struktur_data_E1E119011
|
/R.2.4.py
| 1,096
| 4.5625
| 5
|
''' R-2.4 Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value
of each type. '''
class Flower:
def __init__(self, name, petals, price):
self._name = name
self._petals = petals
self._price = price
def get_name(self):
return self._name
def get_petals(self):
return self._petals
def get_price(self):
return self._price
def set_name(self, name):
self._name = name
def set_petals(self, petals):
self._petals = petals
def set_price(self, price):
self._price = price
# f = Flower('sunflower', 24, 1.25)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
# f.set_name('rose')
# f.set_petals(32)
# f.set_price(1.45)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
| true
|
de037860649e57eab88dc9fd8ae4cdab26fcb47a
|
sahilqur/python_projects
|
/Classes/inventory.py
| 1,720
| 4.28125
| 4
|
"""
Simple python application for maintaining the product list in the inventory
"""
class product:
price, id, quantity = None, None, None
"""
constructor for product class
"""
def __init__(self, price, id, quantity):
self.price = price
self.id = id
self.quantity = quantity
"""
update price function
"""
def update_price(self, price):
self.price = price
"""
update quantity function
"""
def update_quantity(self,quantity):
self.quantity = quantity
"""
print product function
"""
def print_product(self):
print "id is %d\nprice is %.2f\nquantity is %d\n" % (self.id, self.price, self.quantity)
class Inventory:
"""
constructor for inventory class
"""
def __init__(self):
self.product_list = []
"""
add product function
"""
def add_product(self,product):
self.product_list.append(product)
"""
remove product function
"""
def remove_product(self,product):
self.product_list.remove(product)
"""
print inventory function
"""
def print_inventory(self):
total= 0.0
for p in self.product_list:
total+= p.quantity * p.price
print p.print_product()
print "total is %.2f" % total
"""
main function
"""
if __name__ == '__main__':
p1 = product(1.4, 123, 5)
p2 = product(1, 3432, 100)
p3 = product(100.4, 2342, 99)
I = Inventory()
I.add_product(p1)
I.add_product(p2)
I.add_product(p3)
I.print_inventory()
| true
|
7279f2f62f5fab795ab14c5eaa8959fc8b1a1226
|
gdgupta11/100dayCodingChallenge
|
/hr_nestedlist.py
| 2,031
| 4.28125
| 4
|
"""
# 100daysCodingChallenge
Level: Easy
Goal:
Given the names and grades for each student in a Physics class of
students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
[["Gaurav",36], ["GG", 37.1], ["Rob", 42], ["Jack", 42]]
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
The first line contains an integer,
, the number of students.
The subsequent lines describe each student over
lines; the first line contains a student's name, and the second line contains their grade.
Constraints: 2 <= N <= 5
There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
"""
if __name__ == "__main__":
main_list = []
for _ in range(int(input())):
name = input()
score = float(input())
main_list.append([name, score])
# using lambda function here to sort the list of lists by second value
main_list.sort(key = lambda main_list: main_list[1])
tmpList = [lst[1] for lst in main_list]
# Taking the all the scores and making set of it to get unique values
tmpList = set(tmpList)
name_list = []
testList = []
for l in tmpList:
testList.append(l)
# sorting that unique list to get second lowest score
testList.sort()
# checking in main list for all the students who matches the second lowest score (Note: There might be more than 1 students with second lowest score)
for lst in main_list:
if lst[1] == testList[1]:
name_list.append(lst[0])
# sorting those names by alphabetically and printing them
name_list.sort()
for name in name_list:
print(name)
"""
Learnings:
using lambda Function to sort the list of list using value at second [1] position.
"""
| true
|
c93d362cfdbb5d7ff952181b68dda9d2b378d0c5
|
Berucha/adventureland
|
/places.py
| 2,813
| 4.375
| 4
|
import time
class Places:
def __init__(self, life):
'''
returns print statements based on the user's input (car color)
and adds or takes away life points accordingly
'''
#testing purposes:
# print('''In this minigame, the user has been walking along to Adventurland.
# However, the user has stumbled across three cars. This car will take you to a mysterious location!
# The user must select a car. Which color car do you choose.. Red, Blue, or Green?
time.sleep(3)
print('')
self.life = life
print("* Some time later *...") #introduction to the game of places
time.sleep(2)
print()
print('You have been walking through Adventurland trying to reach the castle. It seems forever away.')
time.sleep(2.75)
print()
print("Luckily you have stumbled across three cars. Each car will take you to a mysterious location!")
self.car_colors()
time.sleep(2.5)
def car_colors(self):
'''
evaluates which color the user picks and returns the according print statements and life points
:param self: object of the places class
:return:none
'''
print()
time.sleep(2)
self.user_color = input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ").lower() #user must select a car
while self.user_color != ("red") and self.user_color != ("green") and self.user_color != ("blue"):
self.user_color = (input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ")).lower()
if self.user_color == "red":
print() #if user chooses red then it is a bad choice and they lose life points
time.sleep(1.75)
print('''Uh-Oh! Your car takes you to the home of a troll who is one of the wicked ruler's minions!
You are forced to become his prisoner.''')
self.life -= 3
print('* 2 years later you escape and continue on with your journey *')
elif self.user_color == "blue":
print() #if user chooses blue then it is a good choice and they gain life points
time.sleep(1.75)
print(
"Yayyy! Your car takes you to the home of the Leaders of the Adventurer Revolution, where they feed and shelter you for the night.")
self.life += 2
elif self.user_color == "green": #if user chooses green then it is a okay choice and they dont gain life points nor lose them
print()
time.sleep(1.75)
print(
"Your car takes you to Adventureland's forest and then breaks down, you must continue your journey from here.")
#
# Places()
| true
|
d0d009499f6dd7f4194f560545d12f82f2b73db8
|
starlinw5995/cti110
|
/P4HW1_Expenses_WilliamStarling.py
| 1,358
| 4.1875
| 4
|
# CTI-110
# P4HW1 - Expenses
# William Starling
# 10/17/2019
#
# This program calculates the users expenses.
# Initialize a counter for the number of expenses entered.
number_of_expenses = 1
# Make a variable to control loop.
expenses = 'y'
# Enter the starting amount in your account.
account = float(input('Enter starting amount in account? '))
print()
#Make a variable for the total of the expenses.
total_expenses = 0
# Begin the loop.
while expenses == 'y':
# Get the expenses.
expenses = float(input('Enter expense ' + str(number_of_expenses) + ' : '))
#Calculate the total of expenses.
total_expenses = total_expenses + expenses
# Add 1 to the expense line everytime.
number_of_expenses = number_of_expenses + 1
# Ask if you want another expense.
expenses = input('Do you want to enter another expense? (y/n) ')
print()
# Display amount in account to begin with.
if expenses == 'n':
print('Amount in account before expense subtraction $',
format(account,'.0f'))
# Display number of expenses used.
print('Number of expenses entered:', number_of_expenses - 1 ,'')
print()
#Calculate and display amount left in account.
print('Amount in account AFTER expenses subtracted is $',
format(account - total_expenses,'.0f'))
| true
|
3a0f1e27326226da336ceb45290f89e83bb1f781
|
dosatos/LeetCode
|
/Easy/arr_single_number.py
| 2,254
| 4.125
| 4
|
"""
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Clarification questions:
How big is N?
Solution:
The easiest solution would be to use a dictionary:
- add to the dict each value seen with a value of 1
- and set the value to zero if the integer was seen twice
- after looping once, find a value with a value of 1
"""
import collections
class Solution:
def singleNumber(self, nums):
"""
using XOR operator
:type nums: List[int]
:rtype: int
"""
res = 0
for num in nums:
res ^= num
return res
# def singleNumber(self, nums):
# """
# using Counter instead
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = collections.Counter(nums)
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 1:
# return k # Total complexity is O(N) in the worst case
# return 0 # in case the list is empty
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = {}
# for num in nums:
# try: # increase by one if seen already
# container[num] += 1
# except: # add the number to the container otherwise
# container[num] = 0
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 0:
# return k
# return 0
# # total complexity is O(N)
| true
|
2fc808a248480a8840944c8e927ebdb2f23e854a
|
dosatos/LeetCode
|
/Easy/ll_merge_two_sorted_lists.py
| 2,574
| 4.125
| 4
|
"""
Percentile: 97.38%
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
Change "pointers" as in merge sort algorithm.
Time Complexity = O(N+M)
Space complexity = O(1)
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# node1, node2 = l1, l2
# head = ListNode(0)
# node = head
# while node1 and node2:
# if node1.val <= node2.val:
# tmp = node1.next # save tmp
# node.next = node1 # append
# node = node.next # increment
# node.next = None # clean up node
# node1 = tmp # use tmp
# else:
# tmp = node2.next
# node.next = node2
# node = node.next
# node.next = None
# node2 = tmp
# if node1:
# node.next = node1
# else:
# node.next = node2
# return head.next
# def mergeTwoLists(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# if not l1:
# return l2
# if not l2:
# return l1
# if l1.val < l2.val:
# l1.next = self.mergeTwoLists(l1.next, l2)
# return l1
# else:
# l2.next = self.mergeTwoLists(l2.next, l1)
# return l2
# def mergeTwoLists(self, a, b):
# if not a or b and a.val > b.val:
# a, b = b, a
# if a:
# a.next = self.mergeTwoLists(a.next, b)
# return a
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1: return l2
if not l2: return l1
if l1.val < l2.val:
l3, l1 = l1, l1.next
else:
l3, l2 = l2, l2.next
cur = l3
while l1 and l2:
if l1.val < l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return l3
| true
|
066769bf25ea46c40333a8ddf2b87c35bfed4fae
|
arvindsankar/RockPaperScissors
|
/rockpaperscissors.py
| 1,646
| 4.46875
| 4
|
import random
def correct_input(choice):
while choice != "Rock" and choice != "Scissors" and choice != "Paper":
# corrects rock
if choice == "rock" or choice == "R" or choice == "r":
choice = "Rock"
# corrects scissors
elif choice == "scissors" or choice == "S" or choice == "s":
choice = "Scissors"
# corrects paper
elif choice == "paper" or choice == "P" or choice == "p":
choice = "Paper"
else:
print ("Sorry, didn't get that.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
return choice
print ("\nTo play, select one of the following choices: Rock, Paper, or Scissors.\n")
print ("Rock beats Scissors and loses to Paper.")
print ("Paper beats Rock and loses to Scissors")
print ("Scissors beats Paper and loses to Rock\n")
# prompt player for choice
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
# CPU randomly selects from this list of choices
CPUChoices = ["Rock", "Paper", "Scissors"]
# CPU
CPU = CPUChoices[random.randrange(0,3)]
while choice == CPU:
print ("You and the Computer both picked " + CPU + " so we'll try again.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
CPU = CPUChoices[random.randrange(0,3)]
print ("\nYou chose: " + choice)
print ("Computer choses: " + CPU + "\n")
# Player choses Rock
if ( choice == "Rock" and CPU == "Paper"
or choice == "Paper" and CPU == "Scissors"
or choice == "Scissors" and CPU == "Rock"
):
print (CPU + " beats " + choice + ". You lose!")
else:
print (choice + " beats " + CPU + ". You win!")
print ("\nThanks for playing!")
| true
|
fd2236eaf9f68b84c79bc5ea679231c8d1678210
|
charuvashist/python-assignments
|
/assigment10.py
| 2,992
| 4.34375
| 4
|
'''Ques 1. Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is
inheriting Animal and access the base class method.'''
class Animal:
def animal_attribute(self):
print("This is an Animal Class")
class Tiger(Animal):
def display(self):
print("This is the Lion Class")
a= Tiger()
a.animal_attribute()
a.display()
#Mr.Hacker
'''Ques 2. What will be the output of following code.'''
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print a.f(), b.f()
print a.g(), b.g()'''
# Solution
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print(a.f(), b.f())
print(a.g(), b.g())
#Mr.SINGH
'''Ques 3. Create a class Cop. Initialize its name, age , work experience and designation. Define methods to add,
display and update the following details. Create another class Mission which extends the class Cop. Define method
add_mission _details. Select an object of Cop and access methods of base class to get information for a particular
cop and make it available for mission.'''
class Cop:
def add(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
def display(self):
print("\n\nDetails Will be:")
print("\nName is: ",self.name)
print("\nAge is: ",self.age)
print("\nWork_Experience: ",self.work_experience)
print("\nDestination: ",self.designation)
def update(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
class Mission(Cop):
def add_mission_details(self,mission):
self.mission=mission
print(self.mission)
m=Mission()
m.add_mission_details("Mission detail Assigned to HP :")
m.add("Bikram",18,8,"Hacker\n")
m.display()
m.update("Faizal",21,2,"Hacker")
m.display()
#Hacker
#MR.SINGH@
'''Ques 4. Create a class Shape.Initialize it with length and breadth Create the method Area.
Create class rectangle and square which inherits shape and access the method Area.'''
class Shape:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
self.area = self.length * self.breadth
class Rectangle(Shape):
def area_rectangle(self):
print("Area of Rectangle is :", self.area)
class Square(Shape):
def area_square(self):
print("Area of Square is :", self.area)
length = int(input("Enter the Length:"))
breadth = int(input("Enter the Breadth:"))
a = Rectangle(length,breadth)
b = Square(length,breadth)
if length == breadth:
b.area()
b.area_square()
else:
a.area()
a.area_rectangle()
| true
|
a336d3cc2a6067b7716b502025456667631106d5
|
joemmooney/search-text-for-words
|
/setup.py
| 1,437
| 4.5625
| 5
|
# This file is the main file for running this program.
import argparse
from fileReader import read_file
# The main function that is run when starting the program.
# It sets up argument parsing for the file name to read, the number of most common words to print,
# whether to return a json file, and the name for the json file that is being returned.
# Then it sends these arguments to the function that reads and processes the file.
def main():
parser = argparse.ArgumentParser(description="Arguments being passed to the word count program")
parser.add_argument("file_name", help="Name of the .txt file to count words in")
parser.add_argument("--number_of_words_to_print", type=int, default=10, help="The number of words to print " +
"when showing the top n most common words (defaults to 10)")
parser.add_argument("--return_json", action="store_true", help="If this flag is present, " +
"a json file with word counts will be returned")
parser.add_argument("--json_name", type=str, default="word_counts", help="Part of the name of the json file " +
"that the word counts will be saved to (naming convention is \"{file_name}_{json_name}.json\") " +
"(defaults to word_counts)")
args = parser.parse_args()
read_file(args.file_name, args.number_of_words_to_print, args.return_json, args.json_name)
if __name__ == "__main__":
main()
| true
|
cb8844bcac1c3fa02a35fbab9c6e8fd5c993cb74
|
MysticSoul/Exceptional_Handling
|
/answer3.py
| 444
| 4.21875
| 4
|
# Program to depict Raising Exception
'''
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not
'''
'''Answer2.=> According to python 3.x
SyntaxError: Missing parentheses in call to print
According to python 2.x
The output would be:
NameError: Hi there
'''
| true
|
9aff241bff636fa31f64cc83cb35b3ecf379738a
|
devhelenacodes/python-coding
|
/pp_06.py
| 621
| 4.125
| 4
|
# String Lists
# Own Answer
string = input("Give me a word:\n")
start_count = 0
end_count = len(string) - 1
for letter in string:
if string[start_count] == string[end_count]:
start_count += 1
end_count -= 1
result = "This is a palindrome"
else:
result = "This is not a palindrome"
print(result)
# Learned def reverse, more effective way
def reverse(word):
x = ''
for position in range(len(word)):
x += word[len(word)-1-position]
return x
word = input('Give me a word:\n')
wordReversed = reverse(word)
if wordReversed == word:
print('This is a palindrome')
else:
print('This is not a palindrome')
| true
|
5ae27ed7ccb33a62bbb98ff56f51952d43eaaed6
|
sergiofagundesb/PythonRandomStuff
|
/qualnome.py
| 320
| 4.125
| 4
|
n1 = int(input('Digite um número'))
n2 = int(input('Digite mais um número'))
s=n1+n2
p=n1*n2
di=n1//n2
d=n1/n2
pot=n1**n2
mod=n1%n2
print('A soma é {},\n o produto é {},\n a divisão inteira é {},\n a divisão é {:.3f},\n a potência é {}\n e o resto {}'.format(s,p,di,d,pot,mod), end='====')
print('Cu é bom')
| false
|
a176dbc8191e0cb82f1e2d93434a87327dfaaad6
|
litojasonaprilio/CP1404-Practicals
|
/prac_01/extension_2.py
| 520
| 4.125
| 4
|
print("Electricity bill estimator 2.0", '\n')
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input("Which tariff? 11 or 31: "))
while not (tariff == 11 or tariff == 31):
print("Invalid number!")
tariff = int(input("Which tariff? 11 or 31: "))
if tariff == 11:
price = TARIFF_11
else:
price = TARIFF_31
use = float(input("Enter daily use in kWh: "))
bill_days = int(input("Enter number of billing days: "))
total = price * use * bill_days
print()
print("Estimated bill: ${:.2f}".format(total))
| false
|
26fb03d7961e7a2d1c34fd0ef19b5ef2f6293061
|
emeryberger/COMPSCI590S
|
/projects/project1/wordcount.py
| 839
| 4.28125
| 4
|
# Wordcount
# Prints words and frequencies in decreasing order of frequency.
# To invoke:
# python wordcount.py file1 file2 file3...
# Author: Emery Berger, www.emeryberger.com
import sys
import operator
# The map of words -> counts.
wordcount={}
# Read filenames off the argument list.
for filename in sys.argv[1:]:
file=open(filename,"r+")
# Process all words.
for word in file.read().split():
# Get the previous count (possibly 0 if new).
count = wordcount.get(word, 0)
# Increment it.
wordcount[word] = count + 1
file.close();
# Sort in reverse order by frequency.
sort1 = sorted(wordcount.iteritems(), key=operator.itemgetter(0))
sort2 = sorted(sort1, key=operator.itemgetter(1), reverse = True)
for pair in sort2:
print ("%s : %s" %(pair[0] , pair[1]))
| true
|
4cccd10c95689842e2fba8d256bd086bec47e32e
|
tkruteleff/Python
|
/6 - String Lists/string_lists.py
| 295
| 4.125
| 4
|
word = str(input("Type in a word "))
word_list = []
reverse_word_list = []
for a in word:
word_list.append(a)
print("One letter " + a)
reverse_word_list = word_list[::-1]
if(word_list == reverse_word_list):
print("Word is a palindrome")
else:
print("Word is not a palindrom")
| false
|
84533ee76a2dc430ab5775fa00a4cc354dfc2238
|
tkruteleff/Python
|
/16 - Password Generator/password_generator.py
| 1,239
| 4.3125
| 4
|
import random
#Write a password generator in Python.
#Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
#The passwords should be random, generating a new password every time the user asks for a new password.
#Include your run-time code in a main method.
#Extra:
#Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list.
chars = list(range(ord('a'),ord('z')+1))
chars += list(range(ord('A'),ord('Z')+1))
chars += list(range(ord('0'),(ord('9')+1)))
chars += list(range(ord('!'),ord('&')+1))
dictionary = ["word", "input", "list", "end", "order", "rock", "paper", "scissors"]
password = ""
password_strength = str(input("Do you want a weak or strong password? "))
def generate_weak(list):
generated = random.choices(dictionary, k=2)
return (password.join(generated))
def generate_strong(keys):
key = []
for i in range(16):
key.append(chr(keys[random.randint(0,len(keys)-1)]))
return (password.join(key))
if password_strength == "weak":
print(generate_weak(dictionary))
elif password_strength == "strong":
print(generate_strong(chars))
else:
print("sigh")
| true
|
9777a2a85ad74c0cad75352fcded12ef838f3eb0
|
echang19/Homework-9-25
|
/GradeReport.py
| 987
| 4.15625
| 4
|
'''
Created on Mar 12, 2019
@author: Evan A. Chang
Grade Report
'''
def main():
studentList={'Cooper':['81','86', '90', '97'],'Jennie':['98', '79','99', '87', '82'], 'Julia':['87', '80','75', '10', '78']}
student=''
read=input("Would you like to access a student's grades?")
read.lower()
if read== "no":
student= input("Please enter the name of a student")
student.str
grades=''
while grades.lower !='done':
grades=input('please enter the students grades when done type "done" ')
grades.str
studentList[student]=grades
elif read=="yes":
name=input("Please enter the name of the student you want to see")
print(studentList[name])
again=input("would you like to see another's students grades?")
while again.lower()=='yes':
name=input("Please enter the name of the student you want to see")
print(studentList[name])
| true
|
2a1846f1de7daa7957dfbf272e16b185c344cfc2
|
mittal-umang/Analytics
|
/Assignment-2/MultiplyMatrix.py
| 1,194
| 4.3125
| 4
|
# Chapter 11 Question 6
# Write a function to multiply two matrices
def multiply_matrix(left, right):
result = []
for i in range(len(left)):
innerMatrix = []
for j in range(len(left)):
sum = 0
for k in range(len(left)):
sum += left[i][k] * right[k][j]
innerMatrix.append(sum)
result.append(innerMatrix)
return result
def print_matrix(sqMatrix):
for i in range(len(sqMatrix)):
for j in range(len(sqMatrix)):
print('%0.2f' % sqMatrix[i][j], end="\t", sep="\t")
print()
def list_matrix(size, alist):
i = 0
result = []
while i < len(alist):
result.append(alist[i:i + size])
i += size
return result
def main():
size = eval(input("Enter size of both Matrices: "))
print("Enter Matrix 1:", end="\t")
left = [float(x) for x in input().split()]
left = list_matrix(size, left)
print("Enter Matrix 2:", end="\t")
right = [float(x) for x in input().split()]
right = list_matrix(size, right)
print("Product of Matrices are : ")
print_matrix(multiply_matrix(left, right))
if __name__ == "__main__":
main()
| false
|
ed4293c4fcc473795705f555a305a4ee7c7a2701
|
mittal-umang/Analytics
|
/Assignment-2/VowelCount.py
| 977
| 4.25
| 4
|
# Chapter 14 Question 11
# Write a program that prompts the user to enter a
# text filename and displays the number of vowels and consonants in the file. Use
# a set to store the vowels A, E, I, O, and U.
def main():
vowels = ('a', 'e', 'i', 'o', 'u')
fileName = input("Enter a FileName: ")
vowelCount = 0
consonantsCount = 0
try:
with open(fileName, "rt") as fin:
fileContents = fin.read().split(" ")
except FileNotFoundError:
print("File Not Found")
except OSError:
print("Cannot Open File")
finally:
fin.close()
while fileContents:
word = fileContents.pop().lower()
for i in word:
if i.isalpha():
if i in vowels:
vowelCount += 1
else:
consonantsCount += 1
print("There are ", vowelCount, "vowels and", consonantsCount, "consonants in", fileName)
if __name__ == "__main__":
main()
| true
|
67593b7fcb04e87730e87066e587576fc3a88386
|
mittal-umang/Analytics
|
/Assignment-1/PalindromicPrime.py
| 1,189
| 4.25
| 4
|
# Chapter 6 Question 24
# Write a program that displays the first 100 palindromic prime numbers. Display
# 10 numbers per line and align the numbers properly
import time
def isPrime(number):
i = 2
while i <= number / 2:
if number % i == 0:
return False
i += 1
return True
def reverse(number):
reverseNumber = ""
while number > 0:
reverseNumber += str(number % 10)
number = number // 10
return int(reverseNumber)
def isPalindrome(number):
if reverse(number) == number:
return True
else:
return False
def main():
maxNumber = eval(input("Enter the a number of palindromic prime numbers are required: "))
count = 0
primeNumber = 2
while count < maxNumber:
# Evaluating isPalindrome first to reduce the computational time of prime number.
# since number of iterations in isPrime Functions are more.
if isPalindrome(primeNumber) and isPrime(primeNumber):
print(format(primeNumber, '6d'), end=" ")
count += 1
if count % 10 == 0:
print()
primeNumber += 1
if __name__ == "__main__":
main()
| true
|
ab73985f340bdcafff532a601e84d268f849a7db
|
mittal-umang/Analytics
|
/Assignment-1/RegularPolygon.py
| 1,258
| 4.25
| 4
|
# Chapter 7 Question 5
import math
class RegularPolygon:
def __init__(self, numberOfSide=3, length=1, x=0, y=0):
self.__numberOfSide = numberOfSide
self.__length = length
self.__x = x
self.__y = y
def getNumberOfSides(self):
return self.__numberOfSide
def getLength(self):
return self.__length
def getXCoordinate(self):
return self.__x
def getYCoordinate(self):
return self.__y
def getPerimeter(self):
return self.getNumberOfSides() * self.getLength()
def getArea(self):
return (self.getNumberOfSides() * (self.getLength() ** 2)) / (4 * math.tan(math.pi / self.getNumberOfSides()))
def main():
triangle = RegularPolygon()
hexagon = RegularPolygon(6, 4)
decagon = RegularPolygon(10, 4, 5.6, 7.8)
print("The Perimeter of the triangle is ", triangle.getPerimeter(), "and area of the triangle is",
triangle.getArea())
print("The Perimeter of the hexagon is ", hexagon.getPerimeter(), "and area of the hexagon is",
hexagon.getArea())
print("The Perimeter of the decagon is ", decagon.getPerimeter(), "and area of the decagon is",
decagon.getArea())
if __name__ == "__main__":
main()
| false
|
cea462ca0b7bf4c088e1a2b035f26003052fcef2
|
mittal-umang/Analytics
|
/Assignment-2/KeyWordOccurence.py
| 1,328
| 4.40625
| 4
|
# Chapter 14 Question 3
# Write a program that reads in a Python
# source code file and counts the occurrence of each keyword in the file. Your program
# should prompt the user to enter the Python source code filename.
def main():
keyWords = {"and": 0, "as": 0, "assert": 0, "break": 0, "class": 0,
"continue": 0, "def": 0, "del": 0, "elif": 0, "else": 0,
"except": 0, "False": 0, "finally": 0, "for": 0, "from": 0,
"global": 0, "if": 0, "import": 0, "in": 0, "is": 0, "lambda": 0,
"None": 0, "nonlocal": 0, "not": 0, "or": 0, "pass": 0, "raise": 0,
"return": 0, "True": 0, "try": 0, "while": 0, "with": 0, "yield": 0}
filename = input("Enter a Python source code filename: ").strip()
try:
with open(filename) as fin:
text = fin.read().split()
except FileNotFoundError:
print("File Not Found")
finally:
fin.close()
keys = list(keyWords.keys())
for word in text:
if word in keys:
keyWords[word] += 1
for i in range(len(keys)):
if keyWords.get(keys[i]) < 1:
print(keys[i], "occurs", keyWords.get(keys[i]), "time")
else:
print(keys[i], "occurs", keyWords.get(keys[i]), "times")
if __name__ == "__main__":
main()
| true
|
49837fed1d537650d55dd8d6c469e7c77bc3a4c6
|
mittal-umang/Analytics
|
/Assignment-1/ReverseNumber.py
| 502
| 4.28125
| 4
|
# Chapter 3 Question 11
# Write a program that prompts the user to enter a four-digit integer
# and displays the number in reverse order.
def __reverse__(number):
reverseNumber = ""
while number > 0:
reverseNumber += str(number % 10)
number = number // 10
return reverseNumber
def main():
number = eval(input("Enter an integer: "))
reversedNumber = __reverse__(number)
print("The reversed number is", reversedNumber)
if __name__ == "__main__":
main()
| true
|
4bdeb3a2c137e5fa69998ca4503538302082cef0
|
mittal-umang/Analytics
|
/Assignment-1/SineCosWave.py
| 977
| 4.3125
| 4
|
# Chapter 5 Question 53
# Write a program that plots the sine
# function in red and cosine in blue
import turtle
import math
def drawLine(x1, y1, x2, y2):
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
turtle.penup()
def main():
drawLine(-360, 0, 360, 0)
drawLine(0, -150, 0, 150)
drawLine(-20, 125, 0, 150)
drawLine(0, 150, 20, 125)
drawLine(340, -25, 360, 0)
drawLine(360, 0, 340, 25)
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtle1.penup()
turtle2.penup()
turtle1.goto(-360, 50 * math.sin(math.radians(-360)))
turtle2.goto(-360, 50 * math.cos(math.radians(-360)))
turtle1.pendown()
turtle2.pendown()
turtle1.pencolor("red")
turtle2.pencolor("blue")
i = -360
while i < 361:
turtle1.goto(i, 50 * math.sin(math.radians(i)))
turtle2.goto(i, 50 * math.cos(math.radians(i)))
i += 1
turtle.done()
if __name__ == "__main__":
main()
| false
|
c86efaf3ce656c67a47a6df3c036345d6e604001
|
mittal-umang/Analytics
|
/Assignment-2/AccountClass.py
| 1,428
| 4.1875
| 4
|
# Chapter 12 Question 3
class Account:
def __init__(self, id=0, balance=100, annualinterestrate=0):
self.__id = id
self.__balance = balance
self.__annualInterestRate = annualinterestrate
def getMonthlyInterestRate(self):
return str(self.__annualInterestRate * 100) + "%"
def getMonthlyInterest(self):
return "$" + str(self.__annualInterestRate * self.__balance / 12)
def getId(self):
return self.__id
def getBalance(self):
return "$" + str(self.__balance)
def withdraw(self, amount):
if self.__balance < amount:
raise Exception("Balance Less than withdrawal Amount")
else:
self.__balance -= amount
def deposit(self, amount):
self.__balance += amount
def main():
account = Account(1122, 20000, 0.045)
print("Current account balance is ", account.getBalance())
account.withdraw(2500)
print("Account balance after withdrawal is ", account.getBalance())
account.deposit(3000)
print("Account balance after deposit is ", account.getBalance())
print("Account Details are as below: ")
print("\tAccount ID : ", account.getId())
print("\tCurrent Balance is ", account.getBalance())
print("\tAnnual Interest rate is ", account.getMonthlyInterestRate())
print("\tAnnual Interest is ", account.getMonthlyInterest())
if __name__ == "__main__":
main()
| true
|
692505ec86ff96fe6e96802c2b2cf6306e11e2e0
|
mfnu/Python-Assignment
|
/Functions-repeatsinlist.py
| 554
| 4.1875
| 4
|
''' Author: Madhulika
Program: Finding repeats in a list.
Output: The program returns the number of times the element is repeated in the list.
Date Created: 4/60/2015
Version : 1
'''
mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"]
def count_frequency(mylist):
result = dict((i,mylist.count(i)) for i in mylist)
return result
print(count_frequency(mylist))
'''
O/P:
C:\Python34\Assignments>python Functions-repeatsinlist.py
{'eleven': 3, 'seven': 1, 'one': 2, 'two': 2, 'three': 2}
'''
| true
|
013cb916d56e94c09e5d0451ceff7c532c3a85cd
|
rustyhu/design_pattern
|
/python_patterns/builder.py
| 1,028
| 4.125
| 4
|
"Personal understanding: builder pattern emphasizes on the readability and user convenience, the code structure is not quite neat."
class BurgerBuilder:
cheese = False
pepperoni = False
lettuce = False
tomato = False
def __init__(self, size):
self.size = size
def addPepperoni(self):
self.pepperoni = True
return self
def addLecttuce(self):
self.lettuce = True
return self
def addCheese(self):
self.cheese = True
return self
def addTomato(self):
self.tomato = True
return self
# builder
def build(self):
return Burger(self)
class Burger:
def __init__(self, builder):
self.size = builder.size
self.cheese = builder.cheese
self.pepperoni = builder.pepperoni
self.lettuce = builder.lettuce
self.tomato = builder.tomato
if __name__ == '__main__':
# call builder
b = BurgerBuilder(14).addPepperoni().addLecttuce().addTomato().build()
print(b)
| true
|
4cc5e4aa3463e07ce239339aac99d5821ec786a1
|
ashok148/TWoC-Day1
|
/program3.py
| 423
| 4.34375
| 4
|
#Program to swap two variable without using 3rd variable....
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
print("Before swaping")
print("num1 = ",num1)
print("num2 = ",num2)
print("After swapping")
#LOGIC 1:- of swapping
# num1 = num1 + num2
# num2 = num1 - num2
# num1 = num1 - num2
#LOGIC 2:- of swapping
num1,num2 = num2,num1
print("num1 = ",num1)
print("num2 = ",num2)
| true
|
9878feed23238d5a152e08b2547b8db64d616a35
|
send2manoo/All-Repo
|
/myDocs/pgm/python/ml/04-PythonMachineLearning/04-MatplotlibCrashCourse/01-LinePlot.py
| 547
| 4.25
| 4
|
'''
Matplotlib can be used for creating plots and charts.
The library is generally used as follows:
Call a plotting function with some data (e.g. plot()).
Call many functions to setup the properties of the plot (e.g. labels and colors).
Make the plot visible (e.g. show()).
'''
# The example below creates a simple line plot from one-dimensional data.
# basic line plot
import matplotlib.pyplot as plt
import numpy
myarray = numpy.array([1, 2, 3])
plt.plot(myarray)
plt.xlabel('some x axis')
plt.ylabel('some y axis')
plt.show()
| true
|
849647385e43448924aa7108a5f4986015c0c88a
|
send2manoo/All-Repo
|
/myDocs/pgm/python/ml/03-MachineLearningAlgorithms/1-Baseline machine learning algorithms/2-Zero Rule Algorithm Classification.py
| 1,166
| 4.125
| 4
|
from random import seed
from random import randrange
# zero rule algorithm for classification
def zero_rule_algorithm_classification(train, test):
output_values = [row[-1] for row in train]
print 'output=',output_values
print "set=",set(output_values)
prediction = max(set(output_values), key=output_values.count)
'''
The function makes use of the max() function with the key attribute, which is a little clever.
Given a list of class values observed in the training data, the max() function takes a set of unique class values and calls the count on the list of class values for each class value in the set.
The result is that it returns the class value that has the highest count of observed values in the list of class values observed in the training dataset.
If all class values have the same count, then we will choose the first class value observed in the dataset.
'''
print "prediction-",prediction
predicted = [prediction for i in range(len(train))]
return predicted
seed(1)
train = [['0'], ['0'], ['0'], ['0'], ['1'], ['1']]
test = [[None], [None], [None], [None]]
predictions = zero_rule_algorithm_classification(train, test)
print(predictions)
| true
|
57a99993916020b5c5780236c8efb052974c51b0
|
wuxu1019/1point3acres
|
/Google/test_246_Strobogrammatic_Number.py
| 908
| 4.15625
| 4
|
"""
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Output: false
"""
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
same = '018'
diff = '69'
l, r = 0, len(num) - 1
while l < r:
s = num[l] + num[r]
if s[0] in same and s.count(s[0]) == len(s):
l += 1
r -= 1
elif s == diff or s[::-1] == diff:
l += 1
r -= 1
else:
return False
if l == r:
return num[r] in same
return True
| true
|
a59fc3330c0cb851e43252c9f54c47f2ce2c175e
|
mennanov/problem-sets
|
/dynamic_programming/palindromic_subsequence.py
| 2,379
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
A subsequence is palindromic if it is the same whether read left to right or right to left. For
instance, the sequence
A, C, G, T, G, T, C, A, A, A, A, T, C, G
has many palindromic subsequences, including A, C, G, C, A and A, A, A, A (on the other hand,
the subsequence A, C, T is not palindromic).
Goal: compute the longest palindromic subsequence.
"""
from graph_shortest_path import memoize
class Palindrome(object):
"""
Palindrome object
"""
def __init__(self, middle=None):
self.left = []
self.middle = middle
self.right = []
def __len__(self):
return len(self.left) + len(self.right)
def __cmp__(self, other):
if len(self) > len(other):
return 1
elif len(self) < len(other):
return -1
else:
return 0
def __str__(self):
return str(self.left[::-1] + [self.middle] + self.right if self.middle else self.left[::-1] + self.right)
def copy(self):
c = self.__class__()
c.left = self.left[:]
c.middle = self.middle
c.right = self.right[:]
return c
class PalindromicSubsequence(object):
"""
Longest palindromic subsequence: dynamic programming approach.
Running time is O(N^2)
"""
def __init__(self, iterable):
self.iterable = iterable
@memoize
def run(self, lo=None, hi=None):
if lo is None:
lo = 0
if hi is None:
hi = len(self.iterable) - 1
if lo == hi:
# 1 letter is also a palindrome
return Palindrome(self.iterable[lo])
elif lo > hi:
# empty palindrome
return Palindrome()
if self.iterable[lo] == self.iterable[hi]:
# first and last letters are equal - find a palindrome between these boundaries
p = self.run(lo + 1, hi - 1).copy()
# wrap the palindrome with the current letters
p.left.append(self.iterable[lo])
p.right.append(self.iterable[hi])
return p
else:
return max(self.run(lo + 1, hi), self.run(lo, hi - 1))
if __name__ == '__main__':
sequence = 'A, C, G, T, G, T, C, A, A, A, A, T, C, G'.split(', ')
pl = PalindromicSubsequence(sequence)
assert pl.run() == ['G', 'C', 'A', 'A', 'A', 'A', 'C', 'G']
| false
|
bcb7788af7663d0e9c52057795c5f62acc349ba1
|
mennanov/problem-sets
|
/other/strings/string_all_unique_chars.py
| 1,371
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Implement an algorithm to determine if a string has all unique characters.
"""
def all_unique_set(string):
"""
Running time and space is O(N).
"""
return len(string) == len(set(string))
def all_unique_list(string):
"""
Running time is O(N), space is O(R) where R is a length of an alphabet.
"""
# assume we have an ASCII string
r = 65535 if isinstance(string, unicode) else 255
if len(string) > r:
return False
chars = [0] * r
for i, char in enumerate(string):
chars[ord(char)] += 1
if chars[ord(char)] > 1:
return False
return True
def all_unique_bit(string):
"""
Running time is O(N), required space is 1 byte only for ASCII string and 2 bytes for a Unicode string.
Space usage is optimized using a bit vector.
"""
# bit vector
chars = 0
for i, char in enumerate(string):
# check if we have already seen this char
if chars & (1 << ord(char)) > 0:
return False
else:
chars |= (1 << ord(char))
return True
if __name__ == '__main__':
s = 'abcdefghatyk'
assert not all_unique_set(s)
assert not all_unique_list(s)
assert not all_unique_bit(s)
s = 'abcdefghtlk'
assert all_unique_set(s)
assert all_unique_list(s)
assert all_unique_bit(s)
| true
|
24a138a887902e511570cb744aae827d3b19409d
|
vatsaashwin/PreCourse_2
|
/Exercise_4.py
| 969
| 4.4375
| 4
|
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
# find middle and divide the array into left and right
m = len(arr) //2
L = arr[:m]
R = arr[m:]
# print(L, R)
# recursively sort the left and right halves
mergeSort(L)
mergeSort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i]< R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i<len(L):
arr[k] = L[i]
i+=1
k+=1
while j <len(R):
arr[k] = R[j]
j+=1
k+=1
# Code to print the list
def printList(arr):
arrlen = len(arr)
for i in range(arrlen):
print(arr[i])
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
| false
|
367e5bcdd755649dbedac19066b4f77e3a1293d7
|
suminb/coding-exercise
|
/daily-interview/binary_tree_level_with_minimum_sum.py
| 1,516
| 4.125
| 4
|
# [Daily Problem] Binary Tree Level with Minimum Sum
#
# You are given the root of a binary tree. Find the level for the binary tree
# with the minimum sum, and return that value.
#
# For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10,
# and 4 + 1 + 2 = 7. So, the answer here should be 7.
#
# class Node:
# def __init__(self, value, left=None, right=None):
# self.val = value
# self.left = left
# self.right = right
#
# def minimum_level_sum(root):
# # Fill this in.
#
# # 10
# # / \
# # 2 8
# # / \ \
# # 4 1 2
# node = Node(10)
# node.left = Node(2)
# node.right = Node(8)
# node.left.left = Node(4)
# node.left.right = Node(1)
# node.right.right = Node(2)
#
# print minimum_level_sum(node)
from collections import deque
import pytest
from common import build_binary_tree
def minimum_level_sum(root):
queue = deque()
queue.append((root, 0))
sums = {}
while queue:
node, level = queue.popleft()
if node:
sums.setdefault(level, 0)
sums[level] += node.val
queue.append((node.left, level + 1))
queue.append((node.right, level + 1))
return min(sums.values())
@pytest.mark.parametrize("values, expected", [
([1], 1),
([1, 2], 1),
([1, None, 3], 1),
([10, 2, 8, 4, 1, 2], 7),
([10, 9, 8, 7, 6, 5, 4], 10),
])
def test_minimum_level_sum(values, expected):
actual = minimum_level_sum(build_binary_tree(values))
assert expected == actual
| true
|
7cd442736a1d68ef5e38bdb4927f7b02f2180c3f
|
zgaleday/UCSF-bootcamp
|
/Vector.py
| 2,932
| 4.53125
| 5
|
class Vector(object):
"""Naive implementation of vector operations using the python list interface"""
def __init__(self, v0):
"""
Takes as input the two vectors for which we will operate on.
:param v0: A 3D vector as either a python list of [x_0, y_0, z_0] or tuple of same format
"""
self.v0 = v0
def get(self, index):
"""
Gets the desired x, y, z coordinate
:param index: 0 == x, 1 == y, 2 == z (int)
:return: the value of the specified dimension
"""
if (index > 2 or index < 0):
raise ValueError("Please input a valid index [0-2]")
return self.v0[index]
def add(self, other):
"""
Adds two Vector objects.
:param other: Another Vector object
:return: A Vector equal to the vector sum of the current vector and other
"""
return Vector([self.v0[i] + other.get(i) for i in range(3)])
def subtract(self, other):
"""
Subtract two Vector objects
:param other: Another vector object to be subtracted
:return: A Vector equal to the vector subtraction of the current vector and other
"""
return Vector([self.v0[i] - other.get(i) for i in range(3)])
def normalize(self):
"""
Returns the unit vector of the current vector
:return: A new vector object == the unit vector of the current vector
"""
magnitude = self.dot_product(self) ** .5
return Vector([self.v0[i] / magnitude for i in range(3)])
def dot_product(self, other):
"""
Returns the dot product of the current vector and the other Vector
:param other: Another instance of the vector class
:return:
"""
return sum([self.v0[i] * other.get(i) for i in range(3)])
def cross_product(self, other):
"""
Returns the cross product of the current vector and other
:param other: A Vector object
:return: The cross product of the two Vectors as a new Vector object
"""
x0, y0, z0 = self.v0
x1, y1, z1 = other.get(0), other.get(1), other.get(2)
# Calculate the new vector componants for readability
x2 = y0 * z1 - z0 * y1
y2 = z0 * x1 - x0 * z1
z2 = x0 * y1 - y0 * x1
return Vector([x2, y2, z2])
def __str__(self):
return self.v0.__str__()
if __name__ == "__main__":
v0 = Vector([1, 2, 3])
v1 = Vector([3, 4, 5])
print("Adding " + str(v0) + "and " + str(v1) + "yields: " + str(v0.add(v1)))
print("Subtracting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.subtract(v1)))
print("Normalizing " + str(v0) + "yields: " + str(v0.normalize()))
print("Dotting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.dot_product(v1)))
print("Crossing " + str(v0) + "and " + str(v1) + "yields: " + str(v0.cross_product(v1)))
| true
|
bf320a4a3eb4a61dbc1f485885196c0067208c94
|
cs-fullstack-2019-fall/python-classobject-review-cw-LilPrice-Code-1
|
/index.py
| 1,852
| 4.28125
| 4
|
def main():
pro1()
pro2()
# Problem 1:
#
# Create a Movie class with the following properties/attributes: movieName, rating, and yearReleased.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Movie class
#
#
# Assign a value of your choosing for each property/attribute
#
# Print all properties to the console.
#
def pro1():
class Movie:
def __init__(self, movieName, rating,yearReleased):
self.movie = movieName
self.rating = rating
self.year = yearReleased
def __str__(self):
mystr = (f"self.movie = {self.movie}\n"
f"self.rating = {self.rating}\n"
f"self.year = {self.year}")
return mystr
my1 = Movie("A Silent Voice", "9,7/10", "2018")
# !! : create *two* instances
print(my1)
#
# Problem 2:
#
# Create a class Product that represents a product sold online.
#
# A Product has price, quantity and name properties/attributes.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Product class
#
# In your main function create two instances of the Product class
#
# Assign a value of your choosing for each property/attribute
#
# Print all properties to the console.
def pro2():
class Product:
def __init__(self,price,quantity,name):
self.price = price
self.quan = quantity
self.name = name
def __str__(self):
mystr = (f"self.price = {self.price}\n"
f"self.quan = {self.quan}\n"
f"self.name = {self.name}")
return mystr
p1 = Product(15, 3, 'apple')
# !! : create *two* instances
print(p1)
main()
| true
|
1591a5a8e525549a24ed11f49346c6b207b2ef7c
|
Anthncara/MEMO
|
/python/coding-challenges/cc-001-convert-to-roman-numerals/Int To Roman V2.py
| 896
| 4.28125
| 4
|
print("### This program converts decimal numbers to Roman Numerals ###",'\nTo exit the program, please type "exit")')
def InttoRoman(number):
int_roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),\
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
if not number.isdigit():
return "Not Valid Input !!!"
number = int(number)
if (number > 3999) or (number < 1):
return "Not Valid Input !!!"
result = ""
while number > 0:
for i, roman in int_roman_map:
while number >= i:
result += roman
number -= i
return result
while True:
number = input("Please enter a number between 1 and 3999, inclusively : ")
if number == "exit":
print("Exiting the program... Good Bye")
break
print(InttoRoman(number))
| true
|
f0eb2a695f110c0f81777d0d6c64b60a003fcc51
|
chetan113/python
|
/moreprograms/rightangletriangle.py
| 270
| 4.21875
| 4
|
"""" n = int(input("enter a number of rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(" * ",end ="")
print()"""
"""one for loop statement"""
n =int(input("enter the number of rows:"))
for i in range(1,n+1):
print(" $ "*i)
| false
|
eebd301ffac344f8fe7bdf16a8cf9677bb542d3a
|
G00398275/PandS
|
/Week 05 - Datastructures/prime.py
| 566
| 4.28125
| 4
|
# This program lists out the prime numbers between 2 and 100
# Week 05, Tutorial
# Author: Ross Downey
primes = []
upto = 100000
for candidate in range (2, upto):
isPrime = True # Required only to check if divisible by prime number
for divisor in primes: # If it is divisible by an integer it isn't a prime number
if (candidate % divisor == 0):
isPrime = False
break # No reason to keep checking if not prime number
if isPrime:
primes.append(candidate) # If it is a prime number, append it to the list
print (primes)
| true
|
75a5d8161498d62cbdce415742715a9baac22543
|
G00398275/PandS
|
/Week 02/hello3.py
| 235
| 4.21875
| 4
|
# Week 02 ; hello3.py, Lab 2.2 First Programs
# This program reads in a person's name and prints out that persons name using format
# Author: Ross Downey
name = input ("Enter your name")
print ('Hello {} \nNice to meet you'.format (name))
| true
|
a0986698fa2430008eb4d33ebf02b50e933fc09c
|
G00398275/PandS
|
/Week 03/Lab 3.3.1-len.py
| 270
| 4.15625
| 4
|
# Week 03: Lab 3.3.1 Strings
# This program reads in a strings and outputs how long it is
# Author: Ross Downey
inputString = input ('Please enter a string: ')
lengthOfString = len(inputString)
print('The length of {} is {} characters' .format(inputString, lengthOfString))
| true
|
8ff8959b62adcc0f3455ca00c1e9108a16fbf97e
|
G00398275/PandS
|
/Week 03/Lab 3.3.3 normalize.py
| 575
| 4.46875
| 4
|
# Week 03: Lab 3.3.2 Strings
# This program reads in a string and removes any leading or trailing spaces
# It also converts all letters to lower case
# This program also outputs the length of the original string
# Author: Ross Downey
rawString = input("Please enter a string: ")
normalisedString = rawString.strip().lower()
lengthOfRawString = len(rawString)
lengthOfNormalised = len(normalisedString)
print("That string normalised is: {}" .format(normalisedString))
print("We reduced the input string from {} to {} characters" .format (
lengthOfRawString, lengthOfNormalised))
| true
|
59fc57e8d10d9f71c59999d297edfaf310676efd
|
G00398275/PandS
|
/Week 04-flow/w3Schools-ifElse.py
| 1,257
| 4.40625
| 4
|
# Practicing ifElse loops, examples in https://www.w3schools.com/python/python_conditions.asp
# Author: Ross Downey
a = 33
b = 200
if b > a: # condition is IF b is greater than a
print("b is greater than a") # Ensure indentation is present for print, i.e. indent for condition code
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b: # condition is ELSE/IF a and b are equal
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else: # Condition is ELSE, when the preceding if/elif conditions aren't met
print("a is greater than b")
a = 200
b = 33
if b > a:
print("b is greater than a")
else: # same above without the elif condition, can use just IF and ELSE if needed
print("b is not greater than a")
if a > b: print("a is greater than b")
# shorthand if, can do on one line if only one simple condition needed
a = 2
b = 330
print("A") if a > b else print("B")
# shorthand if / else, done on one line
a = int(input("Please enter integer a:"))
b = int(input("Please enter integer b:")) # changing code to inputs, ensure integer is used
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
| true
|
2e60abd703a5013e8ee5f7d2ce30b066833a7872
|
arnavgupta50/BinarySearchTree
|
/BinaryTreeTraversal.py
| 1,155
| 4.3125
| 4
|
#Thsi Program traverses the Binary Tree in 3 Ways: In/Post/Pre-Order
class Node:
def __init__ (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val==key:
return root
elif root.val<key:
root.right=insert(root.right, key)
else:
root.left=insert(root.left, key)
return root
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
print("Pre-Order Traversal: ")
preorder(r)
print("In-Order Traversal: ")
inorder(r)
print("Post-Oder Traversal: ")
postorder(r)
| true
|
e6657c32a76d198d60ad812ef1fc5587e8a74465
|
subham-paul/Python-Programming
|
/Swap_Value.py
| 291
| 4.1875
| 4
|
x = int(input("Enter value x="))
y = int(input("Enter value y="))
print("The value are",x,"and",y)
x = x^y
y = x^y
x = x^y
print("After the swapping value are",x,"and",y)
"""Enter value x=10
Enter value y=20
The value are 10 and 20
After the swapping value are 20 and 10
"""
| true
|
eafda40ba1154d3f8d02c01d9b827f93f3d7edc6
|
audflexbutok/Python-Lab-Source-Codes
|
/audrey_cooper_501_2.py
| 1,788
| 4.3125
| 4
|
# Programmer: Audrey Cooper
# Lab Section: 502
# Lab 3, assignment 2
# Purpose: To create a menu driven calculator
# set calc equal to true so it runs continuously
calc = True
while calc == True:
# adds two numbers
def add(x, y):
return x + y
# subtracts two numbers
def subtract(x, y):
return x - y
# multiplies two numbers
def multiply(x, y):
return x * y
# divides two numbers
def divide(x, y):
return x / y
# menu driven portion that allows user to select operation
print("Select operation.")
print("1. Add ")
print("2. Subtract ")
print("3. Multiply ")
print("4. Divide ")
print("5. Exit ")
# user input for operation choice
choice = input("Enter choice(1/2/3/4/5):")
# user input for number choice to perform operation
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# statements to perform the correct operations and print their results
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
break
else:
# input validation
print("Invalid input")
'''
IDLE Output
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):4
Enter first number: 2
Enter second number: 2
2 / 2 = 1.0
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):
'''
| true
|
71c813eeaea12d9f0b3791bbbf7c2c92fcaf391f
|
dedx/PHYS200
|
/Ch7-Ex7.4.py
| 797
| 4.46875
| 4
|
#################################
#
# ThinkPython Exercise 7.4
#
# J.L. Klay
# 30-Apr-2012
#
# Exercise 7.4 The built-in function eval takes a string and evaluates
# it using the Python interpreter. For example:
# >>> eval('1 + 2 * 3')
# 7
# >>> import math
# >>> eval('math.sqrt(5)')
# 2.2360679774997898
# >>> eval('type(math.pi)')
# <type 'float'>
# Write a function called eval_loop that iteratively prompts the user,
# takes the resulting input and evaluates it using eval, and prints the
# result.
# It should continue until the user enters 'done', and then return the
# value of the last expression it evaluated.
#
#
import math
def eval_loop():
while True:
line = raw_input('> ')
if line == 'done':
break
last = eval(line)
print last
print last
eval_loop()
| true
|
2f319d09ef1183f75623fdc10fe226c371eba85f
|
stuffyUdaya/Python
|
/1-9-17/strings.py
| 305
| 4.15625
| 4
|
name = "hello world!"
lname = "This is Udaya"
print "Welcome",lname
print "Welcome"+lname
print "Hi {} {}".format(name,lname)
print name.capitalize()
print name.lower()
print name.upper()
print name.swapcase()
print name.find("l")
print lname.replace("Udaya","UdayaTummala")
print name.replace("o","0",1)
| false
|
690805257154a3d610f72d0fa777a0196b9e07fb
|
sathishmepco/Python-Basics
|
/basic-concepts/for_loop.py
| 1,005
| 4.28125
| 4
|
#for loop
print('------Looping through string list')
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x,len(x))
print('------Looping through String')
str = 'Python'
for x in str:
print(x)
print('-----Range() function')
for x in range(10):
print(x)
print('-----Range() function with start and end value')
for x in range(2,5):
print(x)
print('-----Range() function with start, end, step')
for x in range(1,10,2):
print(x)
print('-----Range() with negative numbers')
for x in range(-10, -100, -30):
print(x)
print('-----for with else block')
for x in range(5):
print(x)
else:
print('For block is over')
print('-----nested for loops')
for i in range(3):
for j in range(3):
print(i,j)
print('-----print list items using range()')
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i,fruits[i])
print('-----print(range(5))')
print(range(5))
print('-----sum(print(range(5)))')
print(sum(range(5)))
print('-----list(range(5))')
print(list(range(5)))
| false
|
8617d6b008e47ed734b1ecaf568ae94dfc7db835
|
sathishmepco/Python-Basics
|
/basic-concepts/collections/dequeue_demo.py
| 1,329
| 4.34375
| 4
|
from collections import deque
def main():
d = deque('abcd')
print('Queue of : abcd')
for e in d:
print(e)
print('Add a new entry to the right side')
d.append('e')
print(d)
print('Add a new entry to the left side')
d.appendleft('z')
print(d)
print('Return and remove the right side elt')
print(d.pop())
print('Return and remove the left side elt')
print(d.popleft())
print('Peek of leftmost item')
print(d[0])
print('Peek of rightmost item')
print(d[-1])
print('Reverse of deque')
l = list(reversed(d))
print(l)
print('Search in the deque')
bool = 'c' in d
print(bool)
print('Add multiple elements at once')
d.extend('xyz')
print(d)
print('Right rotation')
d.rotate(1)
print(d)
print('Left rotation')
d.rotate(-1)
print(d)
main()
'''
Queue of : abcd
a
b
c
d
Add a new entry to the right side
deque(['a', 'b', 'c', 'd', 'e'])
Add a new entry to the left side
deque(['z', 'a', 'b', 'c', 'd', 'e'])
Return and remove the right side elt
e
Return and remove the left side elt
z
Peek of leftmost item
a
Peek of rightmost item
d
Reverse of deque
['d', 'c', 'b', 'a']
Search in the deque
True
Add multiple elements at once
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
Right rotation
deque(['z', 'a', 'b', 'c', 'd', 'x', 'y'])
Left rotation
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
'''
| true
|
c5e31c20a1a55cec683250a8d64ebc8836c3f5b6
|
JKodner/median
|
/median.py
| 528
| 4.1875
| 4
|
def median(lst):
"""Finds the median of a sequence of numbers."""
status = True
for i in lst:
if type(i) != int:
status = False
if status:
lst.sort()
if len(lst) % 2 == 0:
num = len(lst) / 2
num2 = (len(lst) / 2) + 1
avg = float(lst[num - 1] + lst[num2 - 1]) / 2
median = {"median": avg, "positions": [lst[num - 1], lst[num2 - 1]]}
elif len(lst) % 2 != 0:
num = (len(lst) + 1) / 2
median = {"median": lst[num - 1], "position": num}
return median
else:
raise ValueError("Inappropriate List")
| true
|
33487b5cd6e069e72cbe686724143ba1eb16979e
|
Tayuba/AI_Engineering
|
/AI Study Note/List.py
| 1,895
| 4.21875
| 4
|
# original list
a = [1, 2, 3, 4, "m", 6]
b = ["a", "b", "c", "d", 2, 9, 10]
# append(), add an item to the end of already existing list
c = 8
a.append(c) # interger append
print(a) # [1, 2, 3, 4, 'm', 6, 8]
d = "Ayuba"
b.append(d)
print(b) # ['a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# extend(), add all items to the to end of already existing list
a.extend(b)
print(a) # [1, 2, 3, 4, 'm', 6, 8, 'a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# insert(), insert an item at the a given position, first argument is the index and second argument is what is what to be inserted
first_names = ["ayuba", "zsuzsanna"]
first_names.insert(1, "tahiru")
first_names.insert(2, "imri")
print(first_names) # ['ayuba', 'tahiru', 'imri', 'zsuzsanna']
# remove(x), removes the first item from the list whose values is equal to the "x". raise ValueError if no such item
first_names.remove("ayuba")
print(first_names) # ['tahiru', 'imri', 'zsuzsanna']
# pop([i]), removes the item at the given position in the list, if no position is given, it removes and return the last item
index_zero_pop = first_names.pop(0)
print(index_zero_pop) # tahiru
no_index_pop = first_names.pop()
print(no_index_pop) # zsuzsanna
# clear(), remove all item from the list. equivalent to del a[:]
a.clear()
print(a) # []
del b[:]
print(b) # []
# index(x[,start[,end]]), return zero_base index in the list of the first item whose value is equal to x, Raise a ValueError if there is no such item
b = ["w", "a", "b", "c", "d","d", 2, 9, 10, 10]
indexed_value = b.index(2)
print(indexed_value) # 6
# count(x), returns the number of times x appears in a list
count_value = b.count("d")
print(count_value) # 2
c = ["w", "a", "b", "c", "d","d", "z", "q", "l"]
c.sort()
print(c) # ['a', 'b', 'c', 'd', 'd', 'l', 'q', 'w', 'z']
# reverse(), reverse the element of the list
c.reverse()
print(c) # ['z', 'w', 'q', 'l', 'd', 'd', 'c', 'b', 'a']
| true
|
4f340717ec34d4d1ee5dc79b1bcac29c8be02600
|
OliverMathias/University_Class_Assignments
|
/Python-Projects-master/Assignments/Celsius.py
| 367
| 4.3125
| 4
|
'''
A script that converts a user's celsius input into farenheight by using
the formula and prints out an temp in farenheight
'''
#gets user's temp Input
temp_c = float(input("Please enter the current temperature in celsius: "))
# turns it into farenheight
temp_f = temp_c*(9/5) + 32
#prints out farenheight
print("The current temp in farenheight is "+str(temp_f))
| true
|
10ea306fedbee3cff2ce63c97add2561c9f2b54a
|
mbkhan721/PycharmProjects
|
/RecursionFolder/Practice6.py
| 2,445
| 4.40625
| 4
|
""" Muhammad Khan
1. Write a program that recursively counts down from n.
a) Create a recursive function named countdown that accepts an
integer n, and progressively decrements and outputs the value of n.
b) Test your function with a few values for n."""
def countdown(n): # def recursive_function(parameters)
if n <= 0: # countdown stops at 1 since the parameter is 0
return n # return base_case_value
else:
print(n)
countdown(n - 1) # countdown decrements by 1
countdown(5)
print()
""" 2. Write a function called numEven that returns the number of even
digits in a positive integer parameter.
For example, a program that uses the function numEven follows.
print(numEven(23)) # prints 1
print(numEven(1212)) # prints 2
print(numEven(777)) # prints 0 """
def numEven(n): # defining numEven Function
even_count = 0 # making initial count=0
while (n > 0): # checking input number greater than 0 or not
rem = n % 10 #slashing up inputted number into digits
if (rem % 2 == 0): #verifing digit is even or odd by dividing with 2.if remainder=0 then digit is even
even_count += 1 #counting the even digits
n = int(n / 10)
print(even_count) #printing the even number count
if (even_count % 2 == 0): #exits the function
return 1
else:
return 0
numEven(23)
numEven(1212)
numEven(777)
print()
""" 3. Write a function called lastEven that returns the last even digit
in a positive integer parameter. It should return 0 if there are no
even digits.
For example, a program that uses the function lastEven follows.
print(lastEven(23)) # prints 2
print(lastEven(1214)) # prints 4
print(lastEven(777)) # prints 0 """
def lastEven(x):
if x == 0:
return 0
remainder = x % 10
if remainder % 2 == 1:
return lastEven(x // 10)
if remainder % 2 == 0:
return remainder + lastEven(x // 10)
print(lastEven(23))
print(lastEven(1212))
print(lastEven(777))
print()
class Vehicle:
def __init__(self, t ="unknown"):
self.type = t
def print(self):
print("type =", self.type)
x1 = Vehicle()
x1.print()
x2 = Vehicle("abcde")
x2.print()
print()
class Car(Vehicle):
def __init__(self, name="Unknown"):
#super().__init__()
self.name = name
self.type = "Car"
def print(self):
print(self.type, self.name)
x1 = Car()
x1.print()
x2 = Car("Audi")
x2.print()
print()
| true
|
3a21120c6e8e9814b6dad06431ec73beaeee9ff2
|
Roha123611/activity-sheet2
|
/prog15.py
| 366
| 4.1875
| 4
|
#prog15
#t.taken
from fractions import Fraction
def addfraction(st_value,it_value):
sum=0
for i in range(st_value,it_value):
sum=sum+Fraction(1,i)
print('the sum of fractions is:',sum)
return
st_value=int(input('input starting value of series:'))
it_value=int(input('enter ending value of series'))
addfraction(st_value,it_value)
| true
|
4a917541eaf35c7e398ec8a4bb6acd1774541c9e
|
helgurd/Easy-solve-and-Learn-python-
|
/differBetw_ARR_LIST.py
| 978
| 4.4375
| 4
|
# first of all before we get into Python lists are not arrays, arrays are two separate things and it is a common mistakes that people think that lists are the same arrays.
#in array if we append different data type will return typeerror which that is not case in the list.
# ARRAY!=LIST
###example 1 python list
import array
#LIST....................................
aList= [1,2,'monkey' ]
print(aList)
#Appending to the LIST.
bList= [1,2,3,5,6,7,8,'limon' ]
bList.append('Name')
print(bList,end='')
print('')
#extra list, in this exersice the program only print the numbers that can be devided by 2:
bList= [1,2,3,5,6,7,8 ]
for x in bList:
if x % 2==0:
print([x],end='')
print(' ')
#ARRAY...................................
num= array.array('i',[1,2,3,4])
num.append(5)
print(num)
#### this code will not work as we add a different data type to the arry which it is string monkey.
# num= array.array('i',[1,2,3,4])
# num.append('monkey')
# print(num)
| true
|
bfa347e6247121c5cd10b86b7769eb368d5ae487
|
helgurd/Easy-solve-and-Learn-python-
|
/open_and_read _string.py
| 1,310
| 4.6875
| 5
|
#write a program in python to read from file and used more than method.
# read from file --------------------------------------------------------------------
#write a program in python to read from file and used more than method.
# method1
# f=open('str_print.txt','r')
# f.close()
#---------
# method2 called context manager where we use (With and as) and in this method we don't need to write close() method.
with open('str_print.txt', 'r') as f:
f_contents = f.read()
print (f_contents)
#print in format -------------------------------------------------------
# Write a Python program to print the following string in a specific format (see the output). Go to the editor
# Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twinkle, twinkle, little star,
# How I wonder what you are!
# Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star,
# How I wonder what you are.add()
f='Twinkle, twinkle,\n little star,\n How I wonder what you are!\n Up above the world so high,\n Like a diamond in the sky.\n Twinkle, twinkle, little star,\n How I wonder what you are'
print (f)
| true
|
75964cfe90c20dbed87347908b79b899f45b593a
|
sachi-jain15/python-project-1
|
/main.py
| 1,206
| 4.1875
| 4
|
# MAIN FILE
def output(): #Function to take user's choice
print "\nWhich script you want to run??\n Press 1 for students_to_teacher\n Press 2 for battleship\n Press 3 for exam_stats"
choice=int(raw_input('Your choice: ')) # To take users input of their choice
if (choice==1):
print "\n STUDENTS_TO_TEACHER\n"
import students_to_teacher # It will import the code written in students_to_teacher.py
elif (choice==2):
print "\n BATTLESHIP\n"
import battleship # It will import the code written in battleship.py
elif (choice==3):
print "\n EXAM STATISTICS\n"
import exam_stats # It will import the code written in exam_stats.py
else:
print # To print blank line
print "Invalid choice" # To inform user that he/she has entered a wrong number
output() #Function call to start the program
print "\n If you want to continue to run any script once again type yes" # To ask user one more time whether he want to run the code again or not
user_input=raw_input().lower() # This statement will take the input in lower case
if(user_input=='yes' or user_input=='y'):
output() #Function Call
print "\n END"
| true
|
25246d0e0e2cb0ed366a2e778d1b3385fb1bd2db
|
Quetzalcoaltl/Cobra_2
|
/OOP_P3.py
| 2,735
| 4.53125
| 5
|
"""
aula 2 de orientação ao objeto,
Professor Corey Schafer
Tema Aula: Python OOP Tutorial 2: Class Variables
https://www.youtube.com/watch?v=BJ-VvGyQxho
"""
class Empregado:
aumento_salario= 1.04
numero_empregado=0
def __init__(self, primeiro_nome, ultimo_nome, pagamento):
self.primeiro_nome= primeiro_nome
self.ultimo_nome= ultimo_nome
self.pagamento=pagamento
self.email=primeiro_nome+'.'+ultimo_nome+"@empresa.com"
Empregado.numero_empregado +=1 #essa conta foi adicionada aqui porque toda vez que um objeto
# "funcionario" for criado __init_ roda, então podemos manter o controle de quantos foram
# criados
def NomeCompleto(self):
return ("{} {} ".format(self.primeiro_nome, self.ultimo_nome))
#operar um aumento na classe
def AplicaAumento(self):
#self.pagamento=int( self.pagamento*Empregado.aumento_salario)
self.pagamento=int(self.pagamento*self.aumento_salario)
"""operar dentro da classe com self é util quando a informaçãoa ser manipulada é importante ao objeto,
self.variavel_intancia
apesar disso, quando precisamos de uma variavel de controle para a classe, por exemplo ṕara contar quantas
vezes a classe foi chamada, então utilizamos a nomeclatura:
classe.variavel_instancia
"""
emp_1=Empregado("Jonas", "Souza", 10000)
emp_2=Empregado("Marcel", "Schunteberg", 12000)
#print("\n",emp_1.__dict__,"\n")
#notação para exibir detalhes intrisecos ao objeto, é importante notar que a variavel aumento salario
# não é exibida, isso porque ela é relativa a classe Empregado, não ao objeto, entretanto, caso eu realize
# uma alteração nessa variavel, aumenta salario essa ira ser mostrada quando esse comando acima for executado
# isso porque a auteração foi relativa ao objeto, a variavel da classe Empregado continua a msm,
#
"""
print("\n o email de ", emp_1.primeiro_nome,"eh", emp_1.email)
print("\n o email de ", emp_2.primeiro_nome,"eh", emp_2.email)
print("\n", Empregado.NomeCompleto(emp_1))
print("\n", emp_1.NomeCompleto() )
"""
print("\n", emp_1.pagamento)
emp_1.AplicaAumento()
print("\n", emp_1.pagamento)
"""pergunta=input("voce quer alterar o aumento? (sim/não):")
if pergunta == "sim":
#funcionario=input("qual funcionario (sim/não):")
inovo=float(input("qual o aumento :" ))
emp_1.pagamento=emp_1.pagamento/emp_1.aumento_salario
emp_1.aumento_salario=inovo
emp_1.AplicaAumento()
print("\n", emp_1.pagamento)
"""
print("\n foram cadastrado(s):", Empregado.numero_empregado, " funcionario(s)")
'''
print(emp_1.numero_empregado)
print(emp_2.numero_empregado)'''
| false
|
bb3f60122c2ecc63b78c98572cb05cffa6c4f72e
|
jaebradley/project_euler
|
/problems/pe44.py
| 1,410
| 4.25
| 4
|
"""
Find the pair of pentagonal numbers for which their sum and difference are pentagonal
"""
import time
def is_pentagonal(number):
#inverse function for pentagonal number
return not (1 + (1 + 24 * number) ** 0.5)/6 % 1
def return_pentagonal(n):
return n * (3 * n - 1) / 2
def is_sum_and_difference_of_two_pentagonal_numbers_pentagonal(pentagonal1, pentagonal2):
if is_pentagonal(pentagonal1 + pentagonal2) and is_pentagonal(abs(pentagonal1 - pentagonal2)):
return True
else:
return False
def return_first_pentagonal_number_pentagonal_difference():
found_pentagonal = False
pentagonals = list()
n = 1
while not found_pentagonal:
next_pentagonal = return_pentagonal(n=n)
for previous_pentagonal in pentagonals:
if is_sum_and_difference_of_two_pentagonal_numbers_pentagonal(pentagonal1=next_pentagonal, pentagonal2=previous_pentagonal):
return next_pentagonal, previous_pentagonal
pentagonals.append(next_pentagonal)
n += 1
def main():
start_time = time.time()
pentagonal_number_1, pentagonal_number_2 = return_first_pentagonal_number_pentagonal_difference()
end_time = time.time()
execution_seconds = end_time - start_time
print "pentagonal pair is {0}, {1}; execution took {2} seconds".format(pentagonal_number_1, pentagonal_number_2, execution_seconds)
main()
| false
|
91e7da83b03fe16d65782809e07e397a41aabb72
|
TheNathanHernandez/PythonStatements
|
/Unit 2 - Introductory Python/A1/Comments_Outputs_Errors.py
| 1,379
| 4.65625
| 5
|
print('Welcome to Python!')
# Output: Welcome to Python
# Why: String says "Welcome to Python
print(1+1)
# Output: 2
# Why: Math sum / 1 + 1 = 2
# print(This will produce an error)
# Output: This will produce an Error
# Why: The text doesn't have a string, it's invalid
print(5+5-2)
# Output: 8
# Why: 5 + 5 - 2
print(3*3+1)
# Output: 10
# Why: 3 x 3 + 1
print(10+3*2)
# Output: 16
# Why: 10 + 3 x 2
print((10 + 3) *2)
# Output: 26
# Why: 10 + 3 x 2
print(10/5)
# Output: 2
# Why: 10 divided by 5
print(5<6)
# Output: True
# Why: 6 is greater than 5. So, the Boolean statement is true.
print(5>6)
# Output: False
# Why: 5 is not over 6. So, the Boolean statement is false.
print(3==3)
# Output: True
# Why: 3 is the same as 3. So, the Boolean statement is true.
print(3==4)
# Output: False
# Why: 3 is not the same as 4. So, the Boolean statement is false.
print(4!=4)
# Output: False
# Why: != < means not equal. But 4 is equal to 4. So, the Boolean statement is false.
print("The secret number is", 23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The secret number is",23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The sum is ",(5+2))
# Output: The sum is 7
# Why: "The sum is" after that, a mathematical statement was added. Which equalled 7.
| true
|
bbed8da2e0837f77df6ae36a03ef73ac25e172fd
|
TheNathanHernandez/PythonStatements
|
/Unit 2 - Introductory Python/A4 - Conditional Expressions/programOne.py
| 403
| 4.15625
| 4
|
# Program One - Write a number that asks the user to enter a number between 1 and 5. The program should output the number in words.
# Code: Nathan Hernandez
from ess import ask
number = ask("Choose a number between 1 and 5.")
if number == 1:
print("One.")
if number == 2:
print("Two.")
if number == 3:
print("Three.")
if number == 4:
print("Four.")
if number == 5:
print("Five.")
| true
|
5077815f19f7bd1d729650704069e64e448cd89c
|
Souravdg/Python.Session_4.Assignment-4.2
|
/Vowel Check.py
| 776
| 4.15625
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Problem Statement 2:
Write a Python function which takes a character (i.e. a string of length 1) and returns
True if it is a vowel, False otherwise.
"""
def vowelChk(char):
if(char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u'):
return True
else:
return False
# Take user input
char = input("Enter character: ");
# If Invalid input, exit
if (len(char) > 1):
print("string Length must be one")
exit();
else:
# If Invalid input, exit
if (char.isalpha() == False):
print("Invalid entry")
else:
# Invoke function
if (vowelChk(char)):
print(char, "is a vowel.");
else:
print(char, "is not a vowel.");
| true
|
fb6ac747fcf5d0fc4fc360cdfbb7e146f9e099e4
|
sharyar/design-patterns-linkedin
|
/visitor.py
| 1,285
| 4.25
| 4
|
class House(object):
def accept(self, visitor):
''' The interface to accept a visitor '''
# Triggers the visiting operation
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, 'worked on by', hvac_specialist)
# This creates a reference to the HVAC specialist within the house object.
def work_on_electricity(self, electrician):
print(self, 'worked on by', electrician)
def __str__(self) -> str:
return self.__class__.__name__
class Visitor(object):
''' Abstract Visitor '''
def __str__(self) -> str:
'''Simply returns the class name when visitor object is printed'''
return self.__class__.__name__
class HVACSpecialist(Visitor):
# Concrete class fro HVACSpecialist
def visit(self, house):
house.work_on_hvac(self)
# now the visitor has a reference to the house object
class Electrician(Visitor):
'''Concrete visitor: electrician'''
def visit(self, house):
house.work_on_electricity(self)
hvac1 = HVACSpecialist()
elec1 = Electrician()
h1 = House()
# House accepting visitors
h1.accept(hvac1)
h1.accept(elec1)
# The visitors visiting the house.
hvac1.visit(h1)
elec1.visit(h1)
| true
|
9dd9050ffca4e9c67628c713695472613b6ef5bd
|
mas254/tut
|
/String methods.py
| 349
| 4.125
| 4
|
course = "Python for Beginners"
print(len(course))
print(course.upper())
print(course.find("P"))
# You get 0 here as this is the position of P in the string
print(course.find("z"))
# Negative 1 is if not found
print(course.replace("Beginners", "Absolute Beginners"))
print(course)
print("Python" in course)
# All case sensitive
print(course.title())
| true
|
132d54605b7b373f7d8494dce66665cf80cd9373
|
mas254/tut
|
/creating_a_reusable_function.py
| 935
| 4.28125
| 4
|
message = input('>')
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
print(output)
def emojis(message):
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
return output
message = input('>')
result = emojis(message)
print(result)
# An explanation: add the def at the start. The parameter is what we've called message, which is what
# the user inputs (taken from previous code). You don't include the first or last lines (the ones which
# ask for or print input) into your function). Add return output into the function as the function has to
# return a value, which can then be stored into a separate variable.
message = input('>')
print(emojis(message))
# Can make it shorter like so.
| true
|
cda3560dfafcb1c358ea0c6ff93477d6e868bb68
|
sabach/restart
|
/script10.py
| 540
| 4.375
| 4
|
# Write a Python program to guess a number between 1 to 9.
#Note : User is prompted to enter a guess.
#If the user guesses wrong then the prompt appears again
#until the guess is correct, on successful guess,
#user will get a "Well guessed!" message,
#and the program will exit.
from numpy import random
randonly_selected=random.randint(10)
guessed_number=input("Type your number to Guess: ")
while randonly_selected == int(guessed_number):
guessed_number=input("Type your number to Guess: ")
print (randonly_selected, guessed_number)
| true
|
713773b1c5d7b50b23270a1ac5f7ca2aa62ac58b
|
VelizarMitrev/Python-Homework
|
/Homework1/venv/Exercise6.py
| 343
| 4.34375
| 4
|
nand = input("Choose a number ")
operator = input("Input + OR * for either computing a number or multiplying it ")
sum = 0
if operator == "+":
for x in range(1, int(nand) + 1):
sum = sum + x
if operator == "*":
sum = 1
for x in range(1, int(nand) + 1):
sum = sum * x
print("The final number is " + str(sum))
| true
|
b44c3fcdf3aa99d88f9d5a03c7d12cb64e9715d6
|
VelizarMitrev/Python-Homework
|
/Homework2/venv/Exercise10.py
| 387
| 4.34375
| 4
|
def fibonacci(num): # this is a recursive solution, in this case it's slower but the code is cleaner
if num <= 1:
return num
else:
return(fibonacci(num-1) + fibonacci(num-2))
numbers_sequence = input("Enter how many numbers from the fibonacci sequence you want to print: ")
print("Fibonacci sequence:")
for i in range(int(numbers_sequence)):
print(fibonacci(i))
| true
|
02d3f469da092a1222b12b48327c61da7fc1fea3
|
mvargasvega/Learn_Python_Exercise
|
/ex6.py
| 903
| 4.5
| 4
|
types_of_people = 10
# a string with embeded variable of types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
# assigns a string to y with embeded variables
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
# printing a string with variable y
print(f"I also said: '{y}'")
# assign the boolean value of false to hilarious
hilarious = False
# assigns a string with an empty curly brace, which allows us to print something in
joke_evaluation = "Isn't that joke so funny?! {}"
# prints thet variable joke_evaluation and plugs in False into the two curlry braces
print(joke_evaluation.format(hilarious))
# a variable that stores a string
w = "This is the left side of..."
# a variable that stores a string
e = "a string with a right side."
# Conncatintes two variables that are holding strings
print(w + e)
| true
|
b13dd7edaf3c6269f3d3fa90682eeeb989d78571
|
TigerAppsOrg/TigerHost
|
/deploy/deploy/utils/click_utils.py
| 586
| 4.1875
| 4
|
import click
def prompt_choices(choices):
"""Displays a prompt for the given choices
:param list choices: the choices for the user to choose from
:rtype: int
:returns: the index of the chosen choice
"""
assert len(choices) > 1
for i in range(len(choices)):
click.echo('{number}) {choice}'.format(
number=i + 1,
choice=choices[i]
))
value = click.prompt('1-{}'.format(len(choices)), type=int) - 1
if value < 0 or value >= len(choices):
raise click.ClickException('Invalid choice.')
return value
| true
|
702a6a7a507adab77dd080f235544229d6c219b6
|
MrZhangzhg/nsd_2018
|
/nsd1809/python2/day01/stack.py
| 1,102
| 4.28125
| 4
|
"""
列表模拟栈结构
栈:是一个后进先出的结构
"""
stack = []
def push_it():
data = input('data to push: ').strip()
if data: # 如果字符串非空
stack.append(data)
def pop_it():
if stack: # 如果列表非空
print('from stack, popped \033[31;1m%s\033[0m' % stack.pop())
else:
print('\033[31;1mEmpty stack\033[0m')
def view_it():
print('\033[32;1m%s\033[0m' % stack)
def show_menu():
cmds = {'0': push_it, '1': pop_it, '2': view_it} # 将函数存入字典
prompt = """(0) push it
(1) pop it
(2) view it
(3) quit
Please input your choice(0/1/2/3): """
while True:
choice = input(prompt).strip()
if choice not in ['0', '1', '2', '3']:
print('Invalid choice. Try again.')
continue
if choice == '3':
break
cmds[choice]() # choice=0 => cmds[0]() =>pushit()
# if choice == '0':
# push_it()
# elif choice == '1':
# pop_it()
# else:
# view_it()
if __name__ == '__main__':
show_menu()
| false
|
ea790c65632f47dd6d0e78d0f366b8b042d0b3ad
|
MrZhangzhg/nsd_2018
|
/nsd1807/python1/day03/fibs_func.py
| 819
| 4.15625
| 4
|
# def generate_fib():
# fib = [0, 1]
#
# for i in range(8):
# fib.append(fib[-1] + fib[-2])
#
# print(fib)
#
# # generate_fib() # 调用函数,即将函数内的代码运行一遍
# # generate_fib()
# a = generate_fib()
# print(a) # 函数没有return语句,默认返回None
##############################
# def generate_fib():
# fib = [0, 1]
#
# for i in range(8):
# fib.append(fib[-1] + fib[-2])
#
# return fib
#
# alist = generate_fib()
# print(alist)
# blist = [i * 2 for i in alist]
# print(blist)
##############################
def generate_fib(n):
fib = [0, 1]
for i in range(n - 2):
fib.append(fib[-1] + fib[-2])
return fib
a = generate_fib(10)
print(a)
b = generate_fib(20)
print(b)
x = int(input('length: '))
c = generate_fib(x)
print(c)
| false
|
2609c2b1f06d647b086493c1294a1652787cefd8
|
FranciscoValadez/Course-Work
|
/Python/CS119-PJ 6 - Simple Calculator/PJ 6 - Simple Calculator/PJ_6___Simple_Calculator.py
| 1,900
| 4.5
| 4
|
# Author: Francisco Valadez
# Date: 1/23/2021
# Purpose: A simple calculator that shows gives the user a result based on their input
#This function is executed when the user inputs a valid operator
def Results(num1, num2, operator):
if operator == '+':
print("Result:", num1, operator, num2, "=", (num1 + num2))
elif operator == '-':
print("Result:", num1, operator, num2, "=", (num1 - num2))
elif operator == '*':
print("Result:", num1, operator, num2, "=", (num1 * num2))
elif operator == '/':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 / num2))
elif operator == '**':
print("Result:", num1, operator, num2, "=", (num1 ** num2))
elif operator == '%':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 % num2))
else:
print("Sorry,", operator, "is not a valid operator!")
#Prints the welcom message
print("Welcome to use the Simple Calculator of Francisco Valadez!")
counter = 0
operator = ''
#The while loop below will not stop until the user enter '@' for the operator
while operator != '@':
counter +=1
print (counter, "="*40)
num1 = float(input("Enter your first number: "))
operator = input("Enter your operator(@ to stop): ")
num2 = float(input("Enter your second number: "))
#If the user does not want to exit then this bit of code is run
if operator != '@':
Results(num1, num2, operator) #sends the user's input to a function
else: #Prints the goodbye message
print(counter + 1, "="*40)
print("Thank you for playing this Simple Calculator of Francisco Valadez!")
print(counter + 2, "="*40)
| true
|
f5617054ec164da96fe6c2d4b638c9889060bbf0
|
hirani/pydec
|
/pydec/pydec/math/parity.py
| 2,695
| 4.15625
| 4
|
__all__ = ['relative_parity','permutation_parity']
def relative_parity(A,B):
"""Relative parity between two lists
Parameters
----------
A,B : lists of elements
Lists A and B must contain permutations of the same elements.
Returns
-------
parity : integer
The parity is 0 if A differs from B by an even number of
transpositions and 1 otherwise.
Examples
--------
>>> relative_parity( [0,1], [0,1] )
0
>>> relative_parity( [0,1], [1,0] )
1
>>> relative_parity( [0,1,2], [0,1,2] )
0
>>> relative_parity( [0,1,2], [0,2,1] )
1
>>> relative_parity( ['A','B','C'], ['A','B','C'] )
0
>>> relative_parity( ['A','B','C'], ['A','C','B'] )
1
"""
if len(A) != len(B): raise ValueError("B is not a permutation of A")
# represent each element in B with its index in A and run permutation_parity()
A_indices = dict(zip(A,range(len(A))))
if len(A_indices) != len(A): raise ValueError("A contains duplicate values")
try:
perm = [A_indices[x] for x in B]
except KeyError:
raise ValueError("B is not a permutation of A")
return permutation_parity(perm, check_input=False)
def permutation_parity(perm, check_input=True):
"""Parity of a permutation of the integers
Parameters
----------
perm : list of integers
List containing a permutation of the integers 0...N
Optional Parameters
-------------------
check_input : boolean
If True, check whether the input is a valid permutation.
Returns
-------
parity : integer
The parity is 0 if perm differs from range(len(perm)) by an
even number of transpositions and 1 otherwise.
Examples
--------
>>> permutation_parity( [0,1,2] )
0
>>> permutation_parity( [0,2,1] )
1
>>> permutation_parity( [1,0,2] )
1
>>> permutation_parity( [1,2,0] )
0
>>> permutation_parity( [2,0,1] )
0
>>> permutation_parity( [0,1,3,2] )
1
"""
n = len(perm)
if check_input:
rangen = range(n)
if sorted(perm) != rangen:
raise ValueError("Invalid input")
# Decompose into disjoint cycles. We only need to
# count the number of cycles to determine the parity
num_cycles = 0
seen = set()
for i in range(n):
if i in seen:
continue
num_cycles += 1
j = i
while True:
assert j not in seen
seen.add(j)
j = perm[j]
if j == i:
break
return (n - num_cycles) % 2
| true
|
e3f3da252345a8e54f3e7bff4d6c695d379b5e42
|
grupy-sanca/dojos
|
/039/2.py
| 839
| 4.53125
| 5
|
"""
https://www.codewars.com/kata/55960bbb182094bc4800007b
Write a function insert_dash(num) / insertDash(num) / InsertDash(int num)
that will insert dashes ('-') between each two odd digits in num.
For example: if num is 454793 the output should be 4547-9-3.
Don't count zero as an odd digit.
Note that the number will always be non-negative (>= 0).
>>> verificaImpares(23543)
'23-543'
>>> verificaImpares(2543)
'2543'
>>> verificaImpares(454793)
'4547-9-3'
>>> verificaImpares(353793)
'3-5-3-7-9-3'
"""
def verificaImpares(numero):
impar = "13579"
res = ""
anterior_impar = False
for letter in str(numero):
if letter in impar:
if anterior_impar:
res += "-"
anterior_impar = True
else:
anterior_impar = False
res += letter
return res
| true
|
4fd23931962dd3a22a5a168a9a49bc68fd8eadd6
|
grupy-sanca/dojos
|
/028/ex2.py
| 1,416
| 4.40625
| 4
|
"""
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name.
They are now trying out various combinations of company names and logos based on this condition.
Given a string, which is the company name in lowercase letters, your task is to find the top three most common characters in the string.
-> Print the three most common characters along with their occurrence count.
-> Sort in descending order of occurrence count.
-> If the occurrence count is the same, sort the characters in alphabetical order.
-> ordena a string inicial -> garante que o dicionário tá ordenado
-> cria outra função que roda 3 vezes, e antes do for chama letter_count_func
Example:
* input:
aabbbccde
* output:
[("b": 3), ("a": 2), ("c": 2)]
>>> main('aaabbc')
[('a', 3), ('b', 2), ('c', 1)]
>>> main('aaabbcdef')
[('a', 3), ('b', 2), ('c', 1)]
>>> main('aaabbbcccdef')
[('a', 3), ('b', 3), ('c', 3)]
>>> main('abcccdddeffff')
[('f', 4), ('c', 3), ('d', 3)]
"""
def letter_count_func(string):
letter_count = {}
for letter in string:
letter_count[letter] = letter_count.get(letter, 0) + 1
return letter_count
def sort_values(x):
return [-x[1], x[0]]
def main(string):
letter_count = letter_count_func(string)
letter_count = sorted(letter_count.items(), key=sort_values, reverse=True)
return letter_count[-1:-4:-1]
| true
|
f17e7bc0acc2e97393a392ffb15e96a3f9f805f2
|
ayust/controlgroup
|
/examplemr.py
| 645
| 4.28125
| 4
|
# A mapper function takes one argument, and maps it to something else.
def mapper(item):
# This example mapper turns the input lines into integers
return int(item)
# A reducer function takes two arguments, and reduces them to one.
# The first argument is the current accumulated value, which starts
# out with the value of the first element.
def reducer(accum, item):
# This example reducer sums the values
return accum+item
# You'd run this via the following command:
#
# some_input_cmd | ./pythonmr.py --auto=examplemr | some_output_command
#
# or...
#
# ./pythonmr.py --in=infile.txt --out=outfile.txt --auto=examplemr
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.