blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9c93949912fc77ad1833f767013569f4c4ddc4f6 | ilante/exercises_python_lpthw | /ex11.py | 325 | 4.15625 | 4 | #software
# 1 takes input
# 2 does something with it
# prints out something to show how it changed
print("How old are you?", end=" ")
age = input()
print("How tall are you?", end='')
height = input()
print('How much do you weigh?', end='')
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.") | true |
35ff67f966de50a59ebe73912169f829ef41b71c | adam-weiler/GA-Reinforcing-Exercises-Functions | /exercise.py | 284 | 4.1875 | 4 | def word_counter(string): #Counts how many words in a string.
if string:
return(len(string.split(' ')))
else:
return(0)
print(word_counter("Hello world")) # returns 2
print(word_counter("This is a sentence")) # returns 4
print(word_counter("")) # returns 0
| true |
c65c1051989e32dbee0e7b0ab6a784c654ba9f78 | yummychuit/TIL | /homework/submit/homework05.py | 260 | 4.28125 | 4 | # 1
for sth in my_list:
print(sth)
# 2
for index, num in enumerate(my_list):
print(index, num)
# 3
for key in my_dict:
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(key, value)
# 4
None | true |
5f56e3b131b35a1367a22251f498aff54239f17b | beexu/testlearngit | /requests git/learnpy/learn1.py | 410 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
for i in range(1, 5):
# print(i)
for a in range(1, 5):
# print(a)
for d in range(1, 5):
# print(d)
if i != a and a != d and i != d:
print(i, a, d)
else:
print("double")
| false |
ae79fa9452ac79299955911627f82bf38ad08032 | lenngro/codingchallenges | /RotateMatrix/RotateMatrix.py | 1,279 | 4.15625 | 4 | import numpy as np
class RotateMatrix(object):
def rotate90(self, matrix):
"""
To rotate a matrix by 90 degrees, transpose it first, then reverse each column.
:param matrix:
:return:
"""
tmatrix = self.transpose(matrix)
rmatrix = self.reverseColumns(tmatrix)
return rmatrix
def transpose(self, matrix):
for i in range(matrix.shape[0]):
for j in range(i, matrix.shape[1]):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
return matrix
def reverseColumns(self, matrix):
"""
For every column:
swap elements from beginning to start, until the column is reversed.
:param matrix:
:return:
"""
for i in range(matrix.shape[0]):
j = 0
k = matrix.shape[0] - 1
while j < k:
tmp = matrix[j][i]
matrix[j][i] = matrix[k][i]
matrix[k][i] = tmp
j += 1
k -= 1
return matrix
if __name__ == "__main__":
matrix = np.array([
[1,2],
[4,5]
])
rm = RotateMatrix()
result = rm.rotate90(matrix)
print(result)
| true |
0d793adfea8dab3384fdde15731feaffd19cee28 | Mistik535/Zadachi | /zad/zad10.py | 803 | 4.1875 | 4 | # ZAD 1
# Создать массив N и заполнить его числами с клавиатуры.
# Вывести на консоль первый и последний элемент массива.
# Поменять местами первый и последний элемент в массиве.
# ZAD 2
# Программа должна переводить число, введенное с клавиатуры в метрах, в километры.
print("Input N:")
N = int(input())
list = []
for i in range(0, N):
print("Append item [", i, "]: ")
list.append(int(input()))
print(list[0])
print(list[N - 1])
x = list[N - 1]
list[N - 1] = list[0]
list[0] = x
print(list)
# def meters(a):
# return a * 0.001
#
# a = int(input())
# print("Kilometres =", meters(a))
| false |
5d7c61e72a8cf91579e0598dab6aa4ed365ed3b4 | MattMacario/Poly-Programming-Team | /Detect_Cycle_In_Linked_List.py | 1,001 | 4.125 | 4 | # Matthew Macario Detecting a Cycle in a Linked Lists
# For reference:
#class Node(object):
# def __init__(self, data=None, next_node=None):
# self.data = data
# self.next = next_node
def has_cycle(head):
# Creates a list to store the data that has already been passed over
dataList=[]
# if the first head is None then it is impossible to have a cycle
if head==None:
return False
# loops as long as the head is not None and checks the heads.data member
# if the data member is already stored in the list, true is returned to signify a cycle
while head:
if head.data in dataList:
return True
# If the data is not in the list, it is added and the head is incremented
else:
dataList.append(head.data)
head=head.next
# function reaches this point only if it has reached a None head before a cycle
#returns false to signify there is no cycle
return False
| true |
1211efb7146a21086cd036062ccd9ff04fbeebdd | Hardik12c/snake-water-gun-game | /game.py | 1,154 | 4.1875 | 4 | import random # importing random module
def game(c,y):
# checking condition when computer turn = your turn
if c==y:
return "tie"
#checking condition when computer chooses stone
elif c=="s":
if y=="p":
return "you win!"
else:
return "you loose!"
#checking condition when computer chooses paper
elif c=="p":
if y=="sc":
return "you win!"
else:
return "you loose!"
#checking condition when computer chooses scissor
elif c=="sc":
if y=="s":
return "you win!"
else:
return "you loose!"
#taking input from computer by random module
print("computer turn: stone(s) paper(p) scissor(sc):-")
rand=random.randint(0,2)
if rand==0:
c="s"
elif rand==1:
c="p"
else:
c="sc"
#taking input from user
y=input("your turn: stone(s),paper(p),scissor(sc):-")
#putting c,y value in game function
a=game(c,y)
#printing what computer chooses and what is choosen by you
print(f"computer chooses {c}")
print(f"you chooses {y}")
#printing final result whether u win or loose
print(a) | true |
dfe21c343e5740ccdb60d083f0c3dc9046eae1fd | ShaamP/Grocery-program | /Cart.py | 1,647 | 4.28125 | 4 | #####################################
# COMPSCI 105 S2 C, 2015 #
# Assignment 1 Question 1 #
# #
# @author YOUR NAME and UPI #
# @version THE DATE #
#####################################
from Item import Item
class Cart:
# the constructor
def __init__(self):
self.__items = []
# This function gets the number of items in the shopping cart.
def get_size(self):
return len(self.__items)
#################################################################################################
# The implementation of the above functions have already been given. #
# Please DO NOT MODIFY the content of the ABOVE functions, as they are used by other functions. #
# Please given the implementation of the following five functions to complete the program. #
#################################################################################################
# This function adds an item into the shopping cart.
def add_item(self, item):
self.__items += [item]
item.setQuantity(quantity - 1)
# This function finds an item on sale based on the item code.
def find_item(self, code):
## IMPLEMENT THIS METHOD
pass
# This function removes an item from the shopping cart.
def delete_item(self, item):
## IMPLEMENT THIS METHOD
pass
# This function clears everything in the shopping cart.
def discard_all(self):
## IMPLEMENT THIS METHOD
pass
# This function prints out the items bought and calculates the total amount due.
def check_out(self):
## IMPLEMENT THIS METHOD
pass | true |
84d1e9eca4618180e1c2ed5b23e153695322f930 | alexmontolio/Philosophy | /wikipedia_game/tree_node.py | 1,469 | 4.28125 | 4 | """
The Node class for building trees
"""
class Node(object):
"""
The basic Node of a Tree data structue
Basic Usage:
>>> a = Node('first')
>>> b = Node('second')
>>> a.add_child(b)
"""
def __init__(self, name):
self.name = name
self.children = []
def add_child(self, node):
"""
Adds a child node to the current node
:param node: the child node being added to the
current nod
:type node: Node
:return: None
"""
self.children.append(node)
def find(self, name):
"""
Searches the node's path for a given node by
the node's name
:param name: the name of the node to find
:type name: str
:return: Node or None
"""
if self.name == name:
return self
for node in self.children:
node_ = node.find(name)
if node_:
return node_
return None
def create_path(self, paths):
"""
Adds a series of nodes to a given node such that
each node forms a chain of nodes to a given
node
:param paths: a series of node names
:type paths: List<str>
:return: None
"""
current_node = self
for path in paths:
node = Node(path)
if current_node:
current_node.add_child(node)
current_node = node
| true |
64b5b695e053404803633ce7673e414b37dafb25 | thiagotato/Programing-Python | /decorators.py | 865 | 4.21875 | 4 | import functools
def trace_function(f):
"""Add tracing before and after a function"""
@functools.wraps(f)
def new_f(*args):
"""The new function"""
print(
'Called {}({!r})'
.format(f, *args))
result = f(*args)
print('Returing', result)
return result
return new_f
def memoize(f):
print('Called memoize({!r})').format(f)
cache = {}
@functools.wraps(f)
def memoized_f(*args):
print('Called memoized_f({!r})'.format(args))
if args in cache:
print('Cache hit!')
return cache[args]
if args not in cache:
result = f(*args)
cache[args] = result
return result
return memoized_f
@memoize
def add(first, second):
"""Return the sum of two arguments."""
return first + second
| true |
80df817700d692076b0583fd641fbf57afd69483 | Tommy8109/Tkinter_template | /Tkinter template.py | 2,779 | 4.28125 | 4 | "This is a template for the basic, starting point for Tkinter programs"
from tkinter import *
from tkinter import ttk
class gui_template():
def __init__(self):
"This is the init method, it'll set up all the variables needed in the app"
self.__title = "Test Application" #This sets the title of the app, which appears at the very top left
self.__screen_geometry = "1920x1080" #This sets up how big the screen will be
self.__mainScreenFile = "bacground_image.png" #This sets up an instance of the Tk libary
self.__MainWindow = Tk()
self.var1 = StringVar()
self.var2 = StringVar()
def screen(self):
mainScreen = self.__MainWindow #This loads the Tk instance
mainScreen.title(self.__title) #This sets the title to what was assigned in init
mainScreen.geometry(self.__screen_geometry) #This sets the geometry to what was assigned in init
mainScreen.attributes("-topmost", False) #This makes it so the app appears ontop of other open apps, False means it wont
mainScreen.resizable(False, False) #This decides if the user can change the size of the window
background = ttk.Label(mainScreen , text = "") #This adds a label to the screen, so a backing image can be applied
background.place(x=0, y=0) #Place is one of Tkinters 2 methods of placing something on the screen (other is "pack")
logo = PhotoImage(file = self.__mainScreenFile, master=mainScreen) #This assigns the image defined in init to a local variable
background.config(image = logo) #This applies the image to the previously declared label
background.img = logo
background.config(image = background.img)
txtCityName = ttk.Entry(mainScreen,textvariable= self.var1, width=40) #This sets up a text box and what where the entered text will be stored
txtCityName.place(x=748, y=217)
btnSearch = ttk.Button(mainScreen,command=self.var2,text=" Search ") #This sets up a button and assigns a command to run when clicked
btnSearch.place(x=828, y=257)
txtCityName.focus_set() #This makes it so the user doesn't have to click the text box to begin typing
mainScreen.option_add('*tearOff', False) #This disables the ability for the user to freely move anything put on the screen(buttons, menus, etc)
mainScreen.mainloop() #This begins the main loop, the app will now run till its closed, it will wait for events to happen and respond accordingly
| true |
53e768354e681a632924d599661e04d67790111a | austinthemassive/first-py | /lambda calculator.py | 840 | 4.34375 | 4 | #!/usr/bin/python
#This file is meant to demonstrate using functions. However since I've used functions before, I will attempt to use lamdas.
#add
add = lambda x,y: x+y
#subtract
subtract = lambda x,y: x-y
#multiply
multiply = lambda x,y: x*y
#divide
divide = lambda x,y: x/y
#while
while True:
try:
num1 = float(input("Enter a number: \n"))
num2 = float(input("Enter a second number: \n"))
function = str(input("Enter 'add', 'subtract', 'multiply', or 'divide': \n")).lower()
except ValueError:
print("Invalid entry... restarting \n")
continue
if function == "add":
print(add(num1,num2))
elif function == "subtract":
print(subtract(num1,num2))
elif function == "multiply":
print(multiply(num1,num2))
elif function == "divide":
print(divide(num1,num2))
else:
print("not a valid operation, restarting...") | true |
cae804a30e3de12689b0d2d4f33a1d237431d6cc | SekalfNroc/03_list_less_than_ten | /__main__.py | 358 | 4.1875 | 4 | #!/usr/bin/env python
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
try:
divider = int(input("Enter a number: "))
except:
print("That's silly")
exit()
less_than = []
for number in numbers:
if number < divider:
less_than.append(str(number))
print("The numbers in the list less than %d are %s" % (divider, ", ".join(less_than)))
| true |
093d43f6865f140f58654f6986a1ce3f5cd532dd | edwardjthompson/resilience_data | /keovonm/normalize.py | 1,397 | 4.15625 | 4 | import pandas as pd
import sys
import os
def normalize(filename, column_name):
'''
This method normalizes a column and places the normalized values
one column to the right of the original
:param filename: name of csv file
:param column_name: column that should be normalized
:return:
'''
try:
data = pd.read_csv(filename, delimiter=',')
except IOError as e:
print(e)
return
df = pd.DataFrame(data)
column_min = df[column_name].min()
column_max = df[column_name].max()
column_index = df.columns.get_loc(column_name)
new_column_name = "normalized_" + column_name
df.insert(column_index+1, new_column_name, True)
df[new_column_name]=(df[column_name]-column_min)/(column_max-column_min)
#Creates a new directory to store results
outdir = './result'
if not os.path.exists(outdir):
os.mkdir(outdir)
path_to_save = os.path.join(outdir, filename)
#Save to path listed above
df.to_csv(path_to_save, index=False)
# Only runs if this program is main
if __name__ == "__main__":
if ((len(sys.argv) < 3 or len(sys.argv) > 3)):
print ("arguments: [csv file name] [column name]")
sys.exit(0)
csv_name = sys.argv[1]
column_name = sys.argv[2]
normalize(csv_name, column_name) | true |
6f6b3ba920bd014fb03effa672fb7df7acaf8933 | zhubw91/Leetcode | /Add_and_Search_Word.py | 1,684 | 4.15625 | 4 | class TrieNode(object):
def __init__(self):
self.children = {}
self.is_word = False
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
for letter in word:
if letter not in node.children:
node.children[letter] = TrieNode()
node = node.children[letter]
node.is_word = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
q = [(self.root,0)]
head = 0
tail = 1
while head < tail:
node,i = q[head]
if i == len(word):
if node.is_word == True:
return True
else:
head += 1
continue
if word[i] == '.':
for key in node.children:
q.append((node.children[key],i+1))
tail += 1
elif word[i] in node.children:
q.append((node.children[word[i]],i+1))
tail += 1
head += 1
return False
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern") | true |
fe15490ff1fc0d6f78069083d9dcbd28df2a0c56 | ronliang6/A01199458_1510 | /Lab01/my_circle.py | 765 | 4.53125 | 5 | """Calculate area and radius of a circle with given radius, and compares to circumference and area of circle with
double that radius"""
Pi = 3.14159
radius = 0
print("Please enter a number for a radius")
radius = float(input())
radius_doubled = radius * 2
circumference = 2 * Pi * radius
circumference_doubled_radius = 2 * Pi * radius_doubled
print(circumference)
area = radius * radius * Pi
area_doubled_radius = Pi * radius_doubled * radius_doubled
print(area)
area_comparison = area_doubled_radius / area
circumference_comparison = circumference_doubled_radius / circumference
print("If you double the radius, the circumference becomes " + str(circumference_comparison) +
" times as big, and the area becomes " + str(area_comparison) + " times as big.")
| true |
67a6dec5b87cd0de6437d2c75c5970edc8e68eb9 | ronliang6/A01199458_1510 | /Lab07/exceptions.py | 2,111 | 4.5625 | 5 | import doctest
def heron(num: int):
"""
Return the square root of a given integer or -1 if that integer is not positive.
:param num: an integer.
:precondition: provide the function with a valid argument according to the PARAM statement above.
:postcondition: return an object according to the return statement below. If num is 0 or negative,
print a helpful warning message.
:raise ZeroDivisionError: if PARAM num is 0 or negative.
:return: a float that represents the square root of num with two or less decimal places or -1 if num is 0 or
negative.
>>> heron(0)
0.0
>>> heron(-50)
You have entered a negative integer, that is not valid.
-1
>>> heron(1)
1.0
>>> heron(0.25)
0.5
>>> heron(1000)
31.62
>>> heron(10000)
100.0
"""
try:
if num < 0:
raise ZeroDivisionError
else:
guess = num
tolerance = 0.00001
while abs(guess * guess - num) > tolerance: # continue finding a more accurate guess if the guess is not
# close enough to the true root, as defined by the tolerance
guess = (guess + num / guess) / 2 # this formula is a step towards finding the square root of a number
return float(round(guess, 2))
except ZeroDivisionError:
print("You have entered a negative integer, that is not valid.")
return -1
def find_an_even(input_list: list):
"""
Return the first even number in input_list.
:param input_list: a list of integers.
:precondition: input_list must be a list of integer.
:postcondition: return the first even number in input_list.
:raise ValueError: if input_list does not contain an even number.
:return: first even number in input_list.
>>> find_an_even([0])
0
>>> find_an_even([0, 2])
0
>>> find_an_even([1, 9, 0])
0
"""
for integer in input_list:
if integer % 2 == 0:
return integer
raise ValueError
def main():
doctest.testmod()
if __name__ == "__main__":
main()
| true |
05c8cd898bbe6e7a9bf754c4d7c45a373f6f9fbd | nia-ja/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,052 | 4.1875 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
smallest_index = i
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for e in range(i + 1, len(arr)):
if arr[e] < arr[smallest_index]:
smallest_index = e
# TO-DO: swap
arr[i], arr[smallest_index] = arr[smallest_index], arr[i]
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# number of iterations for range
iter = len(arr)
# starting from the secon number
for i in range(1, iter):
# starting from the first number
for j in range(0, iter - 1):
# if the second number (i) is smaller then first number (j)
if arr[i] < arr[j]:
# swap
arr[j], arr[i] = arr[i], arr[j]
return arr
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
return arr | true |
e69de86af9107c4b4d72a132b5b809bb64de7199 | HoldenCaulfieldRye/python | /functional/functional.py | 2,216 | 4.1875 | 4 | # http://docs.python.org/2/howto/functional.html
################################################################################
# ITERATORS #
################################################################################
# important foundation for functional-style programs: iterators
# iter() takes any object and tries to return an iterator on it
>>> data = 7,7,6,5,2,1,4,6,7,4,2
>>> it = iter(it)
>>> it
<tupleiterator object at 0x13ec4d0>
>>> it.next()
9
>>> it.next()
4
# use iterators for (exact) sequence unpacking
>>> data = 8,4,32,5
>>> a,b,c,d = iter(data)
>>> a
8
>>> d
5
>>> e,f,g = iter(data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
# common operations on an iterator's output:
# 1) Generator expression: performs an operation for every element
# 2) List comprehension: selects a subset of elements that meet some condition
# Generator expression - always surrounded by ()
# eg define an iterator that skips whitespace, using predefined line.strip()
>>> list = ' i', ' want', ' to', ' join', ' ef', 'and', ' launch'
>>> stripped_iter = (string.strip() for string in list) # notice '()' syntax
>>> stripped_iter.next() # notice nothing to def
'i'
>>> stripped_iter.next()
'want'
>>> stripped_iter.next()
'to'
# List comprehension - always surrounded by []
# eg define a list that is another list stripped of its whitespace
>>> stripList = [word.strip() for word in list] # notice '[]' syntax
>>> stripList # notice nothing to def
['i', 'want', 'to', 'join', 'ef', 'and', 'launch', 'my', 'startup']
# multiple for...in clauses
# cartesian product
>>> seq1 = ['cat', 'dog']
>>> seq2 = ['white', 'black']
>>> seq = [(x,y) for x in seq1 for y in seq2] # notice tuple needs '()'
>>> seq
[('cat', 'white'), ('cat', 'black'), ('dog', 'white'), ('dog', 'black')]
# CHECK OUT this LAMBDA FUNCTIONS TUTORIAL
# this will make you a badass
# http://www.secnetix.de/~olli/Python/lambda_functions.hawk
| true |
801e6955a7b89d863ac53f2fc3ea9ff21d241e83 | denamyte/Hyperskill_Python_06_Coffee_Machine | /Coffee Machine/task/previous/coffee_machine4.py | 1,434 | 4.1875 | 4 | from typing import List
buy_action, fill_action, take_action = 'buy', 'fill', 'take'
resources = [400, 540, 120, 9, 550]
coffee_costs = [[-250, 0, -16, -1, 4], # espresso
[-350, -75, -20, -1, 7], # latte
[-200, -100, -12, -1, 6]] # cappuccino
add_prompts = ['Write how many ml of water do you want to add:\n',
'Write how many ml of milk do you want to add:\n',
'Write how many grams of coffee beans do you want to add:\n',
'Write how many disposable cups of coffee do you want to add:\n']
def main():
show_resources()
branches[input_action()]()
print()
show_resources()
def show_resources():
print('''The coffee machine has:
{} of water
{} of milk
{} of coffee beans
{} of disposable cups
{} of money'''.format(*resources))
def input_action() -> str:
return input('\nWrite action (buy, fill, take):\n')
def buy_branch():
drink = -1 + int(input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:\n'))
costs = coffee_costs[drink]
for i in range(5):
resources[i] += costs[i]
def fill_branch():
for i in range(4):
resources[i] += int(input(add_prompts[i]))
def take_branch():
money, resources[4] = resources[4], 0
print(f'I gave you ${money}')
branches = {buy_action: buy_branch,
fill_action: fill_branch,
take_action: take_branch}
main()
| true |
61b7ba4f2ecb877a19a0b20ad22ce13cc02ac7db | bvishal8510/Coding | /python programs/List insertion.py | 1,733 | 4.40625 | 4 | print "Enter 1. to insert element at beginning."
print "Enter 2. to insert element at end."
print "Enter 3. to insert element at desired position."
print "Enter 4. to delete element from beginning."
print "Enter 5. to delete last element."
print "Enter 6. to delete element from desired position."
print "Enter 7. to display list contents."
print "Enter 8. to quit."
l=[]
while(1):
print"\n"*1
ch=input("Enter your choice.")
if(ch==1):
el=input("Enter the element to be inserted :")
l.insert(0,el)
elif(ch==2):
el=input("Enter the element to be inserted :")
l.append(el)
elif(ch==3):
el=input("Enter the element to be inserted :")
print "Your list is ",l
po=input("Enter the position where you want to enter the element :")
if(po>len(l)):
print "Your index is out of range."
else:
l.insert((po-1),el)
elif(ch==4):
if(l==[]):
print "List is empty."
else:
l.pop(0)
elif(ch==5):
if(l==[]):
print "List is empty."
else:
l.pop(-1)
elif(ch==6):
if(l==[]):
print "List is empty."
else:
print "Your list is ",l
po=input("Enter the position from where you want to delete the element :")
if(po>len(l)):
print "Index number does not exist."
else:
l.pop(po-1)
elif(ch==7):
print "List contents are ",l
elif(ch==8):
break
else:
print "Invalid choice.Please reenter your chioce"
| true |
b74ee930f04695da23898292ceceb21f3252979b | holmes1313/Leetcode | /746_Min_Cost_Climbing_Stairs.py | 1,437 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 15:13:03 2019
@author: z.chen7
"""
# un solved
# 746. Min Cost Climbing Stairs
"""
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
cost will have a length in the range [2, 1000].
Every cost[i] will be an integer in the range [0, 999]."""
def minCostClimbingStairs(cost):
"""
:type cost: List[int]
:rtype: int
"""
n = len(cost)
memo = {}
if n == 2:
memo[n] = min(cost[0], cost[-1])
return min(cost[0], cost[-1])
if n == 3:
memo[n] = min(cost[1], cost[0] + cost[2])
return min(cost[1], cost[0] + cost[2])
if n not in memo:
memo[n] = min(minCostClimbingStairs(cost[:-1]), minCostClimbingStairs(cost[:-2])) + cost[-1]
return memo[n]
test1 = [10, 15, 20]
test2 = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
minCostClimbingStairs(test1)
minCostClimbingStairs(test2)
| true |
9c5c513abd1c40791bdc1972f326f2a6e5a6e888 | holmes1313/Leetcode | /518_Coin_Change_2.py | 1,288 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 10:57:29 2019
@author: z.chen7
"""
# 518. Coin Change 2
"""
You are given coins of different denominations and a total amount of money.
Write a function to compute the number of combinations that make up that amount.
You may assume that you have infinite number of each kind of coin.
Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
"""
def coinChange(coins, amount, memo={}):
if (amount, len(coins)) in memo:
return memo[amount, len(coins)]
if amount == 0:
return 1
if not coins:
return 0
coin = coins[-1]
if coin == coins[0]:
return 1 if amount % coin == 0 else 0
numberOfWays = 0
for cn in range(0, amount+1, coin):
numberOfWays += coinChange(coins[:-1], amount-cn)
memo[amount, len(coins)] = numberOfWays
print(memo)
return numberOfWays
assert coinChange([1, 2, 5], 5) == 5
assert coinChange([2], 3) == 0
assert coinChange([10], 10) == 1
| true |
8af5c04d70fc72c4f0046e8da167e8ef8af2628e | holmes1313/Leetcode | /array_and_strings/500_Keyboard_Row.py | 1,196 | 4.15625 | 4 | """
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl", and
the third row consists of the characters "zxcvbnm".
Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Example 2:
Input: words = ["omk"]
Output: []
"""
from typing import List
class Solution:
mapping = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1,
'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2,
'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3}
def findWords(self, words: List[str]) -> List[str]:
ans = []
for word in words:
if self.is_same_row(word):
ans.append(word)
return ans
def is_same_row(self, word):
word = word.lower()
row = self.mapping.get(word[0])
for l in word:
if self.mapping.get(l) != row:
return False
return True
| true |
0bb1c537af47523a326c80b8776196b74b03fa11 | holmes1313/Leetcode | /array_and_strings/check_408_Valid_Word_Abbreviation.py | 1,621 | 4.40625 | 4 | """
lengths. The lengths should not have leading zeros.
For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n" ("s ubstitutio n")
"sub4u4" ("sub stit u tion")
"12" ("substitution")
"su3i1u2on" ("su bst i t u ti on")
"substitution" (no substrings replaced)
The following are not valid abbreviations:
"s55n" ("s ubsti tutio n", the replaced substrings are adjacent)
"s010n" (has leading zeros)
"s0ubstitution" (replaces an empty substring)
Given a string word and an abbreviation abbr, return whether the string matches the given abbreviation.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "internationalization", abbr = "i12iz4n"
Output: true
Explanation: The word "internationalization" can be abbreviated as "i12iz4n" ("i nternational iz atio n").
Example 2:
Input: word = "apple", abbr = "a2e"
Output: false
Explanation: The word "apple" cannot be abbreviated as "a2e".
"""
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
p1 = 0
p2 = 0
while p1 < len(word) and p2 < len(abbr):
if word[p1] == abbr[p2]:
p1 += 1
p2 += 1
elif abbr[p2] == "0":
return False
elif abbr[p2].isnumeric():
num = ""
while p2 < len(abbr) and abbr[p2].isnumeric():
num += abbr[p2]
p2 += 1
p1 += int(num)
else:
return False
return p1 == len(word) and p2 == len(abbr)
| true |
0667e42e73b0c4eb8a2f2e8752573ce40543cfb2 | liuhuipy/Algorithm-python | /greedy/lemonade-change.py | 2,146 | 4.28125 | 4 | """
柠檬水找零:
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。
顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
示例 1:
输入:[5,5,5,10,20]
输出:true
解释:
前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
由于所有客户都得到了正确的找零,所以我们输出 true。
示例 2:
输入:[5,5,10]
输出:true
示例 3:
输入:[10,10]
输出:false
示例 4:
输入:[5,5,10,10,20]
输出:false
解释:
前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。
对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。
对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。
由于不是每位顾客都得到了正确的找零,所以答案是 false。
"""
from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
m, n = 0, 0
for bill in bills:
need_p = bill - 5
if need_p >= 15 and n > 0:
need_p = 5
n -= 1
if m * 5 >= need_p >= 5:
m -= need_p // 5
need_p = 0
if need_p != 0:
return False
if bill == 5:
m += 1
elif bill == 10:
n += 1
return True
if __name__ == '__main__':
print(Solution().lemonadeChange([5,5,10,20,5,5,5,5,5,5,5,5,5,10,5,5,20,5,20,5]))
| false |
ec271a49ddd1d9d93989b0e1c913fb7c6fbeccf6 | liuhuipy/Algorithm-python | /array/flatten.py | 610 | 4.25 | 4 | # -*- coding:utf-8 -*-
"""
Implement Flatten Arrays.
Given an array that may contain nested arrays,
give a single resultant array.
function flatten(input){
}
Example:
Input: var input = [2, 1, [3, [4, 5], 6], 7, [8]];
flatten(input);
Output: [2, 1, 3, 4, 5, 6, 7, 8]
"""
def list_flatten(alist, res=None):
if res is None:
res = []
for lis in alist:
if isinstance(lis, (list, tuple)):
res = list_flatten(lis, res)
else:
res.append(lis)
return res
if __name__ == '__main__':
alist = [2, 1, [3, [4, 5], 6], 7, [8]]
print(list_flatten(alist)) | true |
47144145ecbd0966df05394ae6de495c07f62d8b | liuhuipy/Algorithm-python | /tree/validate-binary-search-tree.py | 1,391 | 4.15625 | 4 | """
验证二叉搜索树:
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
方法:
中序遍历,判断是否递增。
时间复杂度
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.temp_num = float("-inf")
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
def dfs(node: TreeNode):
if not node:
return True
r_left = dfs(node.left)
if node.val <= self.temp_num:
return False
self.temp_num = node.val
r_right = dfs(node.right)
return r_left and r_right
return dfs(root)
| false |
03cf9108fddb23e91a30d43ac9d985fb17fb4a88 | Navaneeth442000/PythonLab | /CO1/program03.py | 412 | 4.1875 | 4 | #List Comprehensions
list=[3,6,-2,0,-6,-2,5,1,9]
newlist=[x for x in list if x>0]
print(newlist)
N=int(input("Enter number of no:s "))
list=[]
for x in range(N):
x=int(input("Enter no: "))
list.append(x)
print(list)
squarelist=[x**2 for x in list]
print(squarelist)
word="umberella"
vowels="aeiou"
list=[x for x in word if x in vowels]
print(list)
word="flower"
list=[ord(x) for x in word]
print(list) | true |
5d2f4f8f8c2d6deadde1f35100cb56baf0158d80 | ximonsson/python-course | /week-5/main_input_from_file.py | 663 | 4.28125 | 4 | """
Description:
This script will read every line in 'sequence.txt' and factorize the value on it and then
print it out to console.
As an optional exercise try making the script take as a command line argument of the file
that it should read for input.
"""
from mathfuncs import fact
# Exercise: make the script read a command line argument that is the name of the file with data
# open the file - default mode is reading in text mode
f = open("sequence.txt")
# loop over each line and cast it to an int, then print the result of factorizing it to console
for line in f:
x = fact(int(line))
print(" >", x)
f.close() # !! IMPORTANT !!
| true |
c7a696d47b67e2e40a1e889ed646fb157c6dd0df | prathyushaV/pyalgorithm | /merge_sort.py | 1,753 | 4.28125 | 4 | from abstract import AbstractAlgorithm
class MergeSort(AbstractAlgorithm):
name = ""
o_notation = ""
def implement(self,array,start,stop):
"""
Merge sort implementation a
recursive one :)
"""
if start < stop:
splitter = (start+stop)/2
self.implement(array,start,splitter)
self.implement(array,(splitter+1),stop)
self.merge(array,start,splitter,stop)
def merge(self,array,start,splitter,stop):
"""
Merges two parts of an array into itself ...
"""
#split the array into a left and a right partition
left_array = array[start:splitter]
right_array = array[splitter:stop]
#print "The inner left :",left_array
#print "The inner right :",right_array
l_i=0
r_i=0
early_exit = None
#do the merging here
for main_index in xrange(start,stop):
if left_array[l_i] < right_array[r_i]:
array[main_index]=left_array[l_i]
l_i += 1
if l_i == splitter:
early_exit='left'
break
else:
array[main_index]=right_array[r_i]
r_i +=1
if r_i == (stop-splitter):
early_exit='right'
break
#print "The inner main :",array
if early_exit:
if early_exit=='left':
array[(l_i+r_i):stop] = right_array[r_i:len(right_array)]
elif early_exit=='right':
array[(l_i+r_i):stop] = left_array[l_i:len(left_array)]
#print array
if __name__ == "__main__":
pass
| true |
334faf370f8b54adde42f3e60c1f456e0b40ca19 | cnshuimu/classwork | /If statement.py | 1,331 | 4.125 | 4 | # Q34
try:
num = int(input("enter a number: "))
except ValueError:
print('Value must be an integer')
else:
if num % 2 == 0:
print("it is an even number")
elif num % 2 == 1:
print("it is an odd number")
# Q35
human_year = float(input("enter a human year: "))
if human_year <= 2 and human_year >= 0:
dog_year = human_year * 10.5
print(dog_year)
elif human_year > 2:
dog_year = 13 + 4 * human_year
print(dog_year)
else:
print("do not enter a neagtive number")
# Q36
vowel = ["a", "e", "i", "o", "u"]
letter = input("please enter a letter: ")
if letter in vowel:
print("it a a vowel")
elif letter == "y":
print("sometimes it is a vowel, sometimes it is a consonant")
else:
print("it is a consonant")
# Q37
shape = ["triangle","quadrilateral","pentagon","hexagon","heptagon","octagon","nonagon","decagon"]
sides = int(input("please enter the number of sides: "))
index = sides - 3
if sides >= 3 and sides <= 10:
print(shape[index])
else:
print("the sides are so many/few")
# Q48
zodiac = ["dragon","snake","horse","sheep","monkey","rooster","dog","pig","rat","ox","tiger","hare"]
year = int(input("enter a year: "))
index = (year + 4) % 12
if year >= 0:
print(year, "is the year of", zodiac[index] )
else:
print("do not enter a negative year number")
| true |
b77d47c301e45a7446d7e0785687194b4e6a47e3 | vvakrilov/python_basics | /03. Conditional Statements Advanced/02. Training/02. Summer Outfit.py | 902 | 4.40625 | 4 | outside_degrees = int(input())
part_of_the_day = input()
outfit = ""
shoes = ""
if part_of_the_day == "Morning" and 10 <= outside_degrees <= 18:
outfit = "Sweatshirt"
shoes = "Sneakers"
elif part_of_the_day == "Morning" and 18 < outside_degrees <= 24:
outfit = "Shirt"
shoes = "Moccasins"
elif part_of_the_day == "Morning" and outside_degrees >= 25:
outfit = "T-Shirt"
shoes = "Sandals"
elif part_of_the_day == "Afternoon" and 10 <= outside_degrees <= 18:
outfit = "Shirt"
shoes = "Moccasins"
elif part_of_the_day == "Afternoon" and 18 < outside_degrees <= 24:
outfit = "T-Shirt"
shoes = "Sandals"
elif part_of_the_day == "Afternoon" and outside_degrees >= 25:
outfit = "Swim Suit"
shoes = "Barefoot"
elif part_of_the_day == "Evening":
outfit = "Shirt"
shoes = "Moccasins"
print(f"It's {outside_degrees} degrees, get your {outfit} and {shoes}.")
| true |
7a5c7864f2e4be8b80c9fc1a8aeb90eade2c0715 | JEPHTAH-DAVIDS/Python-for-Everybody-Programming-for-Everybody- | /python-data-structures-assignment7.1.py | 478 | 4.59375 | 5 | ''' Write a program that prompts for a file name, then opens that file and reads through the file,
and print the contents of the file in upper case. Use the file, words.txt to produce to the output below. You
can download the sample data at https://www.py4e.com/code3/words.txt?PHPSESSID=88c95d597d36e3db919cbef32f4ce623 '''
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
line = line.rstrip()
print(line.upper())
| true |
23362101fcf09380b72fe260028c7b42d078577d | AnkitMitraOfficial/yash_friend_python | /4.py | 312 | 4.28125 | 4 | # Task:
# To check a given number is prime
prime_number = int(input('Write down a number to find whether it is prime or not!: '))
def find_prime(n=prime_number):
if n % 2 == 0:
print(f'Number {n} is a prime number :)')
else:
print(f'Number {n} is not a prime number :(')
find_prime() | true |
49b9f5b36a059a7681d0a43bb464d33c9a64f1cd | noodlles/pathPlaner-A- | /student_code.py | 2,644 | 4.125 | 4 | import math
import copy
def shortest_path(M,start,goal):
print("shortest path called")
path_list=[]
solution_path=[]
knownNode=set()
#init
path1=path(M,start,goal)
path_list.append(path1)
while(not(len(path_list)==0)):
#get the minimum total_cost path
path_pop=path_list.pop()
#check the path
if path_pop.current==goal:
insertPath(solution_path,path_pop)
return getPath(path_pop)
#add the node to knownNode
knownNode.add(path_pop.current)
#explore the path
for neighbour in M.roads[path_pop.current]:
if neighbour in knownNode:
continue
path_tmp=copy.deepcopy(path_pop)
path_tmp.add_node(M.intersections,neighbour)
insertPath(path_list,path_tmp)
#print_Paths_coor(path_list)
#print_Paths_coor(solution_path)
return None
#将路径按total_cost排序插入path_list
def insertPath(_path_list,path):
for i in range(len(_path_list)):
if path.total_cost >= _path_list[i].total_cost:
_path_list.insert(i,path)
return
_path_list.append(path)
#print the path
def print_Paths_coor(pathList):
for path in pathList:
print("route:",getPath(path),"\t cost:",path.total_cost)
#get route from path Object
def getPath(_path):
current=_path.current
whole_path=[current]
while current in _path.cameFrom.keys():
current=_path.cameFrom[current]
whole_path.append(current)
whole_path.reverse()
return whole_path
#measure the dist of 2 points
def distance(pt1,pt2):
return math.sqrt(pow(pt1[0]-pt2[0],2)+pow(pt1[1]-pt2[1],2))
class path:
def __init__(self,M,startNode,goalNode):
self.dist_soFar=0
self.est_dist=0
self.total_cost=0
self.startNode=startNode
self.goalNode=goalNode
self.cameFrom={}
self.current=startNode
def add_node(self,nodeData,node):
self.cameFrom[node]=self.current
self.current=node
self.get_total_cost(nodeData)
def cal_dist_soFar(self,nodeData):
self.dist_soFar+=distance(nodeData[self.current],nodeData[self.cameFrom[self.current]])
return self.dist_soFar
def est_dist_goal(self,nodeData):
self.est_dist=distance(nodeData[self.current],nodeData[self.goalNode])
return self.est_dist
def get_total_cost(self,nodeData):
self.total_cost=self.cal_dist_soFar(nodeData)+self.est_dist_goal(nodeData)
return self.total_cost
| true |
2332b026ad042a60a61c60e5b6420f564721290d | alexbarsan944/Python | /Lab1/ex9.py | 620 | 4.25 | 4 | # 9 Write a functions that determine the most common letter in a string. For example if the string is "an apple is
# not a tomato", then the most common character is "a" (4 times). Only letters (A-Z or a-z) are to be considered.
# Casing should not be considered "A" and "a" represent the same character.
def most_common(string: str()):
freq = {}
string = string.lower()
for i in string:
if 'a' <= i <= 'z':
if i not in freq:
freq[i] = 1
else:
freq[i] += 1
return sorted(freq.values())[-1]
print(most_common("an apple is not a tomato"))
| true |
22664285c944e3d570a041368bf0cbb82e320a38 | alexbarsan944/Python | /Lab1/ex5.py | 1,019 | 4.125 | 4 | # 5. Given a square matrix of characters write a script that prints the string obtained by going through the matrix
# in spiral order (as in the example):
def printRow(matrix):
size = len(matrix) - 1
k = 0
for i in matrix[k][0][size]:
print(i)
def five():
def ptrOuter(matrix, level):
size = len(matrix[0])
for i in range(level, size - level): # top
print(matrix[level][i], end='')
for i in range(level + 1, size - level): # right
print(matrix[i][size - 1 - level], end='')
for i in range(size - 1 - level, level, -1): # bottom
print(matrix[size - level - 1][i - 1], end='')
for i in range(size - level - 1, level + 1, -1): # left
print(matrix[i - 1][level], end='')
matrix = [['f', 'i', 'r', 's'],
['n', '_', 'l', 't'],
['o', 'b', 'a', '_'],
['h', 't', 'y', 'p'],
]
for i in range(0, len(matrix[0]) // 2):
ptrOuter(matrix, i)
| false |
1c35777a6133fb51eabc3120b51bfdedbd2a3edc | naresh2136/oops | /threading.py | 2,315 | 4.34375 | 4 | run() − The run() method is the entry point for a thread.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread.
Creating Thread Using Threading Module
=============================================================
Without creating a class
Multithreading in Python can be accomplished without creating a class as well. Here is an example to demonstrate the same:
Example:
from threading import *
print(current_thread().getName())
def mt():
print("Child Thread")
child=Thread(target=mt)
child.start()
print("Executing thread name :",current_thread().getName())
Output:
MainThread
Child Thread
Executing thread name : MainThread
==================================================
By extending the Thread class:
When a child class is created by extending the Thread class, the child class represents that a new thread is executing some task. When extending the Thread class, the child class can override only two methods i.e. the __init__() method and the run() method. No other method can be overridden other than these two methods.
Here is an example of how to extend the Thread class to create a thread:
Example:
import threading
import time
class mythread(threading.Thread):
def run(self):
for x in range(7):
print("Hi from child")
a = mythread()
a.start()
a.join()
print("Bye from",current_thread().getName())
Output:
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Bye from MainThread
====================================
Without Extending Thread class
To create a thread without extending the Thread class, you can do as follows:
Example:
from threading import *
class ex:
def myfunc(self): #self necessary as first parameter in a class func
for x in range(7):
print("Child")
myobj=ex()
thread1=Thread(target=myobj.myfunc)
thread1.start()
thread1.join()
print("done")
Output:
Child
Child
Child
Child
Child
Child
Child
done
The child thread executes myfunc after which the main thread executes the last print statement. | true |
6e4e62a52b16a9452437d2efa8ad94d4f1a6fbd1 | antadlp/pythonHardWay | /ex5_studyDrill_03.py~ | 957 | 4.28125 | 4 | #Search online for all of the Python format characters
print "%d : Signed integer decimal"
print "%i : Signed integer decimal"
print "%o : Unsigned octal"
print "%u : Unsigned decimal"
print "%x : Unsigned hexadecimal (lowercase)"
print "%X : Unsigned hexadecimal (uppercase)"
print "%e : Floating point exponential format (lowercase)"
print "%E : Floating point exponential format (uppercase)"
print "%f : Floating point decimal format"
print "%F : Floating point decimal format"
print "%g : Same as 'e' if exponent is grater than -4 or less than precision \
'f' otherwise"
print "%G : Same as 'e' if exponent is grater than -4 or less than precision, \
'F' otherwise"
print "%c : Single characters (accepts integer or single character string)"
print "%r : String (converts any python object using repr())"
print "%s : String (converts any python objetc using str())"
print "% : No arguments is converted, results in a '%' character in the \
result"
| true |
cf4a064e95f153869ea27f689877f86dbbcd1888 | ethan786/hacktoberfest2021-1 | /Python/ReplaceDuplicateOccurance.py | 808 | 4.15625 | 4 | # Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
Classes help understand better . '
# printing original string
print("The original string is : " + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print("The string after replacing : " + str(res))
| true |
c8492f83cf1ebd331aa4f3946324c9ecc4d727e9 | ethan786/hacktoberfest2021-1 | /Python/mathematical calculator.py | 461 | 4.4375 | 4 | # take two input numbers
number1 = input("Insert first number : ")
number2 = input("Insert second number : ")
operator = input("Insert operator (+ or - or * or /)")
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number2 * number1
elif operator == '/':
total = number1 / number2
else:
total = "invalid operator"
# printing output
print(total) | false |
412aa8efb5779739eed62eca2bf84d46dbd5da52 | ethan786/hacktoberfest2021-1 | /Python/VerticalConcatination.py | 626 | 4.21875 | 4 | #Python3 code to demonstrate working of
# Vertical Concatenation in Matrix
# Using loop
# initializing lists
test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]
# printing original list
print("The original list : " + str(test_list))
# using loop for iteration
res = []
N = 0
while N != len(test_list):
temp = ''
for idx in test_list:
# checking for valid index / column
try: temp = temp + idx[N]
except IndexError: pass
res.append(temp)
N = N + 1
res = [ele for ele in res if ele]
# printing result
print("List after column Concatenation : " + str(res))
| true |
6545a85e1e3a7a1f2791dc266483b559c824e4ed | Dakontai/-. | /cs/3/5.py | 376 | 4.21875 | 4 | num1 = int(input("Введите первое число: "))
num2 = int(input("Введите второе число: "))
num1 *= 5
print("Result:", num1 + num2)
print("Result:", num1 - num2)
print("Result:", num1 / num2)
print("Result:", num1 * num2)
print("Result:", num1 ** num2)
print("Result:", num1 // num2)
word = "Hi"
print(word * 2)
word = True | false |
98db41c342b502dadb0c1a41470f07b48a1557eb | qianjing2020/cs-module-project-hash-tables | /applications/crack_caesar/crack_caesar.py | 1,216 | 4.15625 | 4 | # Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Your code here
special = ' " : ; , . - + = / \ | [] {} () * ^ & '
def alphabet_frequency(filename):
#obtain text from txt file
f = open(filename, 'r')
s = f.read()
f.close
# list contains list of alphabets
lst = s.replace(" ", "")
# remove all special character
lst = [c for c in lst if c.isalnum()]
# creat an dictionary to count frequency
letter_count = {}
for letter in lst:
if letter not in letter_count:
letter_count[letter] = 0
letter_count[letter] += 1
# sort the dictionary by value frequency
list_sorted = sorted(letter_count.items(), key=lambda x: x[1], reverse=True)
# match the frequency to get cipher map!
list_sorted = list_sorted[:-1]
print(len(list_sorted))
frequent_english = ['E', 'T', 'A', 'O', 'H', 'N', 'R', 'I', 'S', 'D', 'L', 'W', 'U', 'G', 'F', 'B', 'M', 'Y', 'C', 'P', 'K', 'V', 'Q', 'J', 'X', 'Z']
cipher_map = zip(tuple(list_sorted.items[0], frequent_english))
deciphered = lst
return cipher_map
result = alphabet_frequency('applications/crack_caesar/ciphertext.txt')
print(result)
| true |
2b56d5789f94816a770ea759a6e3d5b336a70aba | luizfboss/MapRender | /main.py | 1,076 | 4.1875 | 4 | import folium
# A little help: add this code to a folder to open the map after running the code
a = float(input('x coordinate: ')) # Asks for the x coordinate
b = float(input('y coordinate: ')) # Asks for the y coordinate
city = str(input("Place's name: ")) # Asks for the city's name
# The city name won't change anything, just will keep the HTML more organized
# The following command will create the map.
# You should open this map as a browser tab.
# Go to the folder which contains this code and run the code
# After executing, you will see a "newmap.html". Just click on it.
new_map = folium.Map(
location=[a, b], tiles='Stamen Terrain',
zoom_start=16
)
# Location - Combination of both coordinates the user provided (a, b)
# Tiles - The "style" of the map. Highly recommend you to look at the documentation for more Tiles.
# Zoom Start - The zoom level after running the code. You can zoom in/out with your mouse's scroll button.
folium.Marker(
[a, b], popup=f'<i>{city}</i>',
tooltip='Click here'
).add_to(new_map)
new_map.save(r'.\newmap.html')
| true |
b806b42c533faa0c2cde79d4d067b53fb70abbcc | marcmatias/challenges-and-studies | /Edabit/python/Moving to the End.py | 420 | 4.3125 | 4 | '''
Flip the Boolean
Create a function that reverses a boolean value and returns the
string "boolean expected" if another variable type is given.
Examples
reverse(True) ➞ False
reverse(False) ➞ True
reverse(0) ➞ "boolean expected"
'''
def reverse(arg):
return not arg if type(arg) == bool else "boolean expected"
print(reverse(True)) | true |
4abd2567d26205e70109e9d2358c9869809850f3 | marcmatias/challenges-and-studies | /Edabit/python/Return the Factorial.py | 378 | 4.28125 | 4 | '''
Return the Factorial
Create a function that takes an integer and returns the factorial of that integer.
That is, the integer multiplied by all positive lower integers.
Examples
factorial(3) ➞ 6
factorial(5) ➞ 120
factorial(13) ➞ 6227020800
'''
def factorial(num):
return num * factorial(num-1) if num > 1 else 1
| true |
51f406d423ce8c6e7cdfc427f2025709d8656443 | ayamschikov/python_course | /lesson_3/2.py | 922 | 4.21875 | 4 | # 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой.
def user_info(name='', last_name='', year='', city='', email='', phone=''):
print(f"User {name} {last_name} was born in {year}, lives in {city}, email - {email}, phone - {phone}")
name = input('name: ')
last_name = input('last_name: ')
year = input('year: ')
city = input('city: ')
email = input('email: ')
phone = input('phone: ')
user_info(name=name, year=year, last_name=last_name, email=email, phone=phone, city=city)
| false |
2b4fcc0a88ba50f20630d7c6965714c275860e5b | ayamschikov/python_course | /lesson_3/3.py | 467 | 4.15625 | 4 | # 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
def my_func(a, b, c):
if a >= b and b >= c:
return a + b
elif a >= b and c > b:
return a + c
else:
return b + c
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
print(my_func(a, b, c))
| false |
d925271c57d03ecd51a1ae4633d6bf468a8a09ae | ayamschikov/python_course | /lesson_1/2.py | 501 | 4.28125 | 4 | # 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
seconds = int(input('enter number of seconds: '))
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
seconds = seconds - hours * 3600 - minutes * 60
print('formatted time - {}:{}:{}'.format(hours, minutes, seconds))
| false |
c2e2bc9e26a478b6df3944327769f7bf23c567d4 | ayamschikov/python_course | /lesson_1/5.py | 1,272 | 4.1875 | 4 | # 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
income = int(input('enter income: '))
expenses = int(input('enter expenses: '))
if income > expenses:
print('you earned money!')
print('income to expenses ratio = {}'.format(income / expenses))
employees_count = int(input('enter count of employees: '))
print('your income by employee = {}'.format((income - expenses) / employees_count))
elif income == expenses:
print('at least you have not lost money')
else:
print('you lost some money')
| false |
21ffdb0c183029ea8f2a7d7a1052fb4b2ea5947b | lemonella/Dogs_project | /nearest_cafe.py | 2,863 | 4.3125 | 4 | '''
Let's find the nearest cafe by given coordinates
'''
import csv
import math
def get_coordinates_from_user():
# Getting the longitude and latitude from the user
# lat_point = input("Введите широту: ")
# lng_point = input("Введите долготу: ")
lat_point = 37.230884
lng_point = 56.036111
try:
lat_point = float(lat_point)
lng_point = float(lng_point)
except ValueError:
print("Введены некорректные данные")
exit()
return lat_point, lng_point
def find_distance_by_coordinates (lat1, lng1, lat2, lng2):
'''
function finds the distance between 2 points by coordinates
'''
try:
lat1 = float(lat1)
lng1 = float(lng1)
lat2 = float(lat2)
lng2 = float(lng2)
except ValueError:
print("Введены некорректные данные")
return False
# Convert degrees to radians.
lat1 = math.radians(lat1)
lng1 = math.radians(lng1)
lat2 = math.radians(lat2)
lng2 = math.radians(lng2)
# Calculate delta longitude and latitude.
delta_lat = (lat2 - lat1)
delta_lng = (lng2 - lng1)
return round(6378137 * math.acos(math.cos(lat1) * math.cos(lat2) * math.cos(lng2 - lng1) + math.sin(lat1) * math.sin(lat2)))
def find_nearest_cafe(cafes_raw, lat_user, lng_user):
try:
lat_user = float(lat_user)
lng_user = float(lng_user)
except ValueError:
print('Введены некорректные данные')
return False
nearest_cafe = {'Distance':0, 'Name':'', 'Address':''}
for row in cafes_raw:
# coordinates = row['Coordinates'].split(',')
lat_raw = float(row['Lat'])
lng_raw = float(row['Lng'])
distance = find_distance_by_coordinates (lat_user, lng_user, lat_raw, lng_raw)
if not distance:
return False
# If this cafe is the nearest let's write it to nearest_cafe var
if (nearest_cafe['Distance'] == 0) or (distance < nearest_cafe['Distance']):
nearest_cafe = {'Distance': distance, 'Name':row['Name'], 'Address':row['Address']}
return nearest_cafe
def get_cafes_from_file(filepath):
# Read the file with cafes info
cafes_raw = list()
with open (filepath, "r", encoding = 'utf-8') as file:
fields = ['Name', 'Address', 'Lat', 'Lng', 'Description']
reader = csv.DictReader(file, fields, delimiter=',')
cafes_raw = list(reader)
return cafes_raw
if __name__ == "__main__":
user_lat, user_lng = get_coordinates_from_user()
cafes_raw = get_cafes_from_file('csv/placelist.csv')
nearest_cafe = find_nearest_cafe(cafes_raw, user_lat, user_lng)
# Printing the nearest cafe
print('Ближайшее кафе: ' + str(nearest_cafe)) | false |
0cc6b0e73b5b22af969492ec7001163552e0a513 | syedfarazhus/Beginner-programs | /3. is_even and is_odd.py | 213 | 4.40625 | 4 | def is_even(num:int) -> bool:
"""
Returns true if a number is even
"""
return num % 2 == 0
def is_odd(num:int) -> bool:
"""
returns true if a number is odd
"""
return num % 2 == 1
| false |
de78b70d84464edf5f136bafd10d98c9f3695773 | 112358Sean/Kalkulator-Sederhana | /Kalkulator Sederhana.py | 1,305 | 4.15625 | 4 | while True:
print("Note: Untuk pangkat, bilangan b adalah nilai pangkatnya.Untuk akar, bilangan b adalah nilai akarnya."
"Untuk hasil pengakaran agak sedikit error, sehingga untuk beberapa akar sempruna dibulatkan ke angka satuannya."
"Selamat Mencoba.")
a = input("Masukkan bilangan 1: ")
b = input("Masukkan bilangan 2: ")
print("1.Penjumlahan? 2.Pengurangan? 3.Perkalian? 4.Pembagian? 5. Sisa Pembagian? 6. Pangkat? 7. Akar? (Tulis Angka)")
answer = input()
if answer == "1":
print(a, "+", b, "=", float(a) + float(b))
elif answer == "2":
print(a, "-", b, "=", float(a) - float(b))
elif answer == "3":
print(a, "x", b, "=", float(a) * float(b))
elif answer == "4":
print(a, ":", b, "=", float(a) / float(b))
elif answer == "5":
print("sisa ", a, ":", b, "=", float(a) % float(b))
elif answer == "6":
print(a, "^", b, "=", float(a) ** float(b))
elif answer == "7":
print("Akar", b, "dari ", a, " adalah", float(a) ** (1 / float(b)))
else:
print("Invalid Input")
c = input("Ketik 'l' untuk melanjutkan atau 'b' untuk berhenti")
if c == "l" :
continue
elif c == "b":
break
else:
print("Invalid Input") | false |
772ebe0e48e44ce7f40861d41ebddad75e094c45 | JanhaviBorsarkar/Ineuron-Assignments | /Programming assignments/Programming Assignment 4.py | 1,825 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
# Q1. Write a Python Program to Find the Factorial of a Number
n = int(input("Enter a number: "))
fact = 1
if n < 0:
print("Please enter a positive integer")
elif n == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, n + 1):
fact = fact * i
print("Factorial of {0} is {1}" .format(n , fact))
# In[3]:
# Q2. Write a Python Program to Display the multiplication Table
n = int(input("Enter a number: "))
for i in range(1,11):
print(n * i)
# In[4]:
# Q3. Write a Python Program to Print the Fibonacci sequence
n = int(input("How many numbers? "))
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
# In[5]:
# Q4. Write a Python Program to Check Armstrong Number
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
# In[6]:
# Q5. Write a Python Program to Find Armstrong Number in an Interval
lower = 100
upper = 2000
for num in range(lower, upper + 1):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
# In[7]:
# Q6. Write a Python Program to Find the Sum of Natural Numbers
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
# In[ ]:
| false |
40f5bd514abcfb94d581ce838eebed35c176d427 | FarabiHossain/Python | /Python Program/5th program.py | 321 | 4.125 | 4 | #How to get input from the user
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
school = input("Enter your school name: ")
age = input("Enter your age: ")
name = fname +" "+ lname
print("my name is " +name)
print("my school name is "+school)
print("i am " ,age, "years old") | true |
4c35c58813cfb2697a8e00c7497b05f290aea394 | anniequasar/session-summaries | /Red_Hat/sess_10/10a_modules.py | 1,303 | 4.375 | 4 | """
Modules - Beginners Python Session 10
Demonstrates how program can tell if it has been run as script or imported as module
@author: Tim Cummings
Every python program file is a module.
A module is a group of python functions, classes, and/or a program which can be used from other python programs.
The module name is the file name less the .py suffix.
Other programs use the 'import' statement to use the module.
'import' runs the python program and makes available functions and classes
Note: make sure all code is in function definitions if you don't want it to run on import.
"""
# Challenge 1: Create a python program which prints the value of variable __name__
# Advanced challenge 1: print the value of variable __name__ using logging
print("__name__ has value {}".format(__name__))
# Challenge 2: Run the python program and see what value gets printed.
# Import as a module and see what gets printed
# script: __name__ has value __main__
# import: __name__ has value s10a_module
# Challenge 3: Detect whether program has been run as a script or imported as a module and
# display a different message for each case
if __name__ == "__main__":
print("I have been run as a script")
else:
print("I have been imported as a module and my name is {}".format(__name__))
| true |
a5063e58428fc5053b8248c9c684378d67713bdc | heggy231/final_coding_challenges | /practice_problems/non_repeat_substring.py | 334 | 4.15625 | 4 | """
Given a string as input, return the longest substring which does not return repeating characters.
"""
def non_repeat_substring(word):
"""
>>> non_repeat_substring("abbbbc")
'ab'
"""
start = 0
iterator = 0
maximum_substring = ""
# iterate through the string
# have an end counter.
| true |
55d4008280c22a62a031019d82ed0434c7ffdcec | sidkushwah123/pythonexamples | /calsi.py | 1,701 | 4.3125 | 4 | def calculator():
print("Hello! Sir, My name is Calculator.\nYou can follow the instructions to use me./n")
print("You can choose these different operations on me.")
print("Press 1 for addition(x+y)")
print("Press 2 for subtraction(x-y)")
print("Press 3 for multiplication(x*y)")
print("Press 4 for division(x/y)")
print("Press 5 for pover(x^y)")
while True:
a = int(input("Choose your operation:"))
if a>0 and a<6:
print(f"You choose {a}")
break;
else:
print("Invalid operation")
x = int(input("Enter the value of x:"))
y = int(input("Enter the value of y:"))
if a==1:
z = x+y
if (x==56 and y==9) or (x==9 and y==56):
print(f"The correct answer is:{77}")
else:
print(f"The correct answer is:{z}")
elif a==2:
z = x-y
print(f"The correct answer is:{z}")
elif a==3:
z = x*y
if (x==45 and y==3) or (x==3 and y==45):
print(f"The correct answer is:{555}")
else:
print(f"The correct answer is:{z}")
elif a==4:
z = x/y
if (x==56 and y==6):
print(f"The correct answer is:{4}")
else:
print(f"The correct answer is:{z}")
elif a==5:
z = x**y
print(f"The correct answer is:{z}")
else:
print("Invalid syntax")
again()
def again():
print("If you like to start me again then choose one of the operations.")
print("Choose 'y' for Yes and 'n' for No")
i = input()
if i=='y':
calculator()
else:
print("See You Later")
if __name__ == "__main__":
calculator() | true |
f42a13e83415ed2c2554365b31f8bb649fba64df | sidkushwah123/pythonexamples | /stone_paper.py | 2,662 | 4.21875 | 4 | # stone paper seaser game
import random
option = ["STONE","PAPER","SISER"]
user_score = 0
computer_score = 0
turn = 0
print("Let's play STONE PAPER SISER")
k="y"
while(k !="n"):
user_score = 0
computer_score = 0
for i in range(3):
if i != 2:
print("\n"+"*"*15+"Round"+str(i+1)+"*"*15)
else:
print("\n"+"*"*15+"FinalRound"+"*"*15)
turn += 1
print("\nSelect your choice: For quit press q")
for key in option:
print(key)
print()
user = input()
user_choice = user.upper()
computer_choice = random.choice(option)
if user_choice == "STONE" or user_choice == "PAPER" or user_choice == "SISER" :
print("\nYour choice is "+user_choice+" MY choice is "+computer_choice)
if user_choice == "STONE" :
if computer_choice == "STONE":
print("Ohhh its A tie")
elif computer_choice == "PAPER":
computer_score += 1
print("Yeaaa you lose")
else :
user_score += 1
print("aHH You win this time....")
elif user_choice == "PAPER":
if computer_choice == "STONE":
user_score += 1
print("aHH You win this time....")
elif computer_choice == "PAPER":
print("Ohhh its A tie")
else :
computer_score += 1
print("Yeaaa you lose")
elif user_choice == "SISER":
if computer_choice == "STONE":
computer_score += 1
print("Yeaaa you lose")
elif computer_choice == "PAPER":
user_score += 1
print("aHH You win this time....")
else :
print("Ohhh its A tie")
elif user_choice == "Q":
print("O shit You quit the game ")
break
else:
print("\nWrong input..! Try entering from the given option")
continue
print("\nYour score: " + str(user_score) +"\nMy score: " + str(computer_score) +"\n")
print("*"*40+"\n")
if user_score > computer_score:
print("Ohh.. Shits.. You WIN...but i bet you will not win again")
elif user_score < computer_score:
print("LOSER....I win and you LOSE")
else:
print("I am Shocked.. Ahhh... it's a TIE")
print("\nYour score: " + str(user_score) +"\nMy score: " + str(computer_score))
if user_choice != "Q" :
a = input("\nWant you play again? y/n\n")
else:
break
k=a | false |
5f6bba95c9799f4095c1f7e4db2d5f50e07da791 | mkseth4774/ine-guide-to-network-programmability-python-course-files | /TSHOOT/TSHOOT#2/higher.py | 237 | 4.125 | 4 | ##
##
number1 = int(input("Please enter your first number: "))
number2 = input("Please enter your first number: "
if number1 > number2
HIGHEST = nubmer1
else
HIGHEST = number2
print("The higher of the two numbers was" HIHGEST)
| false |
8ee3f7247112e5afb3efdc0c41d303b1426fa216 | prophecyofagod/Python_Projects | /mario_saiz_Lab4c.py | 1,451 | 4.15625 | 4 | #Author: Mario Saiz
#Class: COSC 1336
#Program: Lab 4c
#Getting grades that are entered, determining the letter grade, and
#then calculating the class average by adding all the grades up, and
#dividing by the number of entered grades
print("\n"*25)
name = input("What is your name?: ")
grade = float(input("Please enter a grade, " + str(name) + ", or a -1 to end the program: "))
totalgrades = 0
gradecount = 0
while (grade != -1):
if (grade >= 90 and grade <= 100):
print ("\nYou got an A! You're doing amazing!")
elif (grade >= 80 and grade <= 89):
print ("\nYou got a B! You're doing great, keep it up!")
elif (grade >= 70 and grade <= 79):
print ("\nYou got a C! You're doing okay, but you can do better.")
elif (grade >= 60 and grade <= 69):
print ("\nYou got a D! You're not doing so well in class. Try harder.")
elif (grade <= 59 and grade >= 0):
print ("\nYou got an F! You really need to get serious about class.")
print()
gradecount = (gradecount + 1)
totalgrades = (totalgrades + grade)
grade = float(input("Enter a grade or a -1 to end the program: "))
if (gradecount == 0):
print("\nNo grades found, " +str(name) + ". Class average cannot be calculated.")
elif (grade == -1):
classaverage = totalgrades/gradecount
print("\nThe class average is a(n) " + format(classaverage, ".2f") + ", " + str(name) + ".")
| true |
3bab3c4f57880b7fe63df4af07a62fc4f14531dc | BSN2000/SL_Lab | /selection_constructs.py | 254 | 4.1875 | 4 | a = int(input("enter the value of a "))
print("the value of a:",a)
b = int(input("enter the value of b "))
print("the value of a:",b)
if a>b:
print("a is greater than b")
elif b>a:
print("b is greater than a")
else:
print("both are equal")
| false |
c123862957de1163da3601eb2a5ccfb1fb0073ec | Yi-Hua/HackerRank_practicing | /Python_HackerRank/BasicDataTypes/Lists.py | 1,567 | 4.375 | 4 | # Lists
''' Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer e at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the list.
7. reverse: Reverse the list. '''
# Input 0
''' 12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print '''
# Output 0
''' [6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1] '''
if __name__ == '__main__':
N = int(input())
arr = []
for i in range(1,N+1):
s = input().split()
if s[0] == 'insert' :
a, b = int(s[1]), int(s[2])
arr.insert(a, b) # insert(a, b):第a的位置放b
elif s[0] == 'print' :
print(arr)
elif s[0] == 'remove':
a = int(s[1])
arr.remove(a) # remove(a):移除"一個"a
elif s[0] == 'append':
a = int(s[1])
arr.append(a) # append(a):增加a
elif s[0] == 'sort':
arr.sort() # sort():排序
elif s[0] == 'pop':
arr.pop() # pop():移除最後一項
elif s[0] == 'reverse':
arr.reverse() # reverse():倒敘
| true |
6742ecb3ce433a551fbe480c9de0b6cb40469489 | Yi-Hua/HackerRank_practicing | /Python_HackerRank/Sets/Set_DifferenceOperation.py | 1,233 | 4.125 | 4 | # Set .difference() Operation 差集
# ______
# | |
# | A __|.... A difference B : A.difference(B) or A-B
# |___| :
# : B :
# :......:
# Sample Input
'''
9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8 '''
# Sample Output
''' 4 '''
a = input()
A = set(input().split())
b = input()
B = set(input().split())
C = A.difference(B)
# C = A-B
print(len(C))
# ========== .difference() ==========
# The tool .difference() returns a set with all the elements from the set that are not in an iterable.
# Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set.
# Set is immutable to the .difference() operation (or the - operation).
'''
>>> s = set("Hacker")
>>> print s.difference("Rank")
set(['c', 'r', 'e', 'H'])
>>> print s.difference(set(['R', 'a', 'n', 'k']))
set(['c', 'r', 'e', 'H'])
>>> print s.difference(['R', 'a', 'n', 'k'])
set(['c', 'r', 'e', 'H'])
>>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'r', 'e', 'H', 'k'])
>>> print s.difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'r'])
>>> s - set("Rank")
set(['H', 'c', 'r', 'e']) ''' | false |
2b7d71339c21528b07b3af83ed06c15d013a2a01 | chrisdavidspicer/code-challenges | /is_prime.py | 617 | 4.1875 | 4 | # Define a function that takes one integer argument
# and returns logical value true or false depending on if the integer is a prime.
# Per Wikipedia, a prime number (or a prime) is
# a natural number greater than 1 that has no
# positive divisors other than 1 and itself.
def is_prime(num):
# print(range(num))
if num < 2: return False
div_list = []
for i in range(num):
if i > 1 and num % i == 0:
div_list.append(i)
if len(div_list) > 0:
return False
else:
return True
# if:
# # determine if integer is prime
# return True
# else:
# return False
print(is_prime(6))
| true |
616186ec59d49fbf3b4437a1ddaf8a40a2ab816a | parth04/Data-Structures | /Trees/symmetricTree.py | 1,574 | 4.375 | 4 | """
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
tempL = []
tempR = []
resL = []
resR = []
resL = self.dfsLeft(root.left, tempL)
resR = self.dfsRight(root.right,tempR)
if tempL == tempR:
return True
else:
return False
def dfsLeft(self,root, temp):
if root == None:
return temp.append('')
l = self.dfsLeft(root.left,temp)
r = self.dfsLeft(root.right,temp)
return temp.append(root.val)
def dfsRight(self,root, temp):
if root == None:
return temp.append('')
l = self.dfsRight(root.right,temp)
r = self.dfsRight(root.left,temp)
"""
Explanation:
1) Catch here is we need to store null value also.
2) First I stored the left subtree in a list. Then I stored right subtree in a list. Tweak here is while storing right subtree I recursively called right child first.
3) Atlast simply compared the two list and returned the result.
"""
| true |
d8f3d005639d4bf74738072c79381721c929a3a3 | parth04/Data-Structures | /misc/rotateImage.py | 1,456 | 4.4375 | 4 | """
48. Rotate Image
Medium
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:
Input: matrix = [[1]]
Output: [[1]]
Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
"""
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
m = len(matrix[0])
for i in range (n):
for j in range(i,m):
matrix[i][j], matrix[j][i] = matrix[j][i],matrix[i][j]
# matrix[i].reverse()
for item in matrix:
item[:] = item[::-1]
"""
Explanation:
Method 1:
1) In this we use 4 swaps. For explanation see youtube video 'https://www.youtube.com/watch?v=gCciKhaK2v8&t=1735s&ab_channel=FisherCoder'
Method 2:
1)I used this in above problem. Main idea is to take transpose of the give matrix then reverse the each row. Tricky part here is to set range for inner for loop. We set from outer loop till end.
"""
| true |
f1b39bf74c7844753d0a02832e73018cc344b11e | ZTcode/csc150Python | /convert3.py | 458 | 4.125 | 4 | # convert.py
# A program to convert Celsius to Fahreheit
def main():
print("Converting from celcius to fahrenheit")
celsius = eval(input("What is the Celsius Temperature? "))
fahrenheit = 9/5 * celsius + 32
if fahrenheit > 90:
print("It's hot as hell out!")
if fahrenheit < 30:
print("It cold as shit nigga, bundle up!")
print("The temperature is", fahrenheit, "degrees fahrenheit.")
main()
| true |
592fd0e7cefd02922163db3857875dc5b1be4b24 | pwang867/LeetCode-Solutions-Python | /1367. Linked List in Binary Tree.py | 2,089 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
if self.isRootPath(head, root):
return True
if root.left and self.isSubPath(head, root.left):
return True
if root.right and self.isSubPath(head, root.right):
return True
return False
def isRootPath(self, head, root):
if not head:
return True
if not root:
return False
if root.val != head.val:
return False
if self.isRootPath(head.next, root.left) or self.isRootPath(head.next, root.right):
return
"""
Given a binary tree root and a linked list with head as the first node.
Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
Example 1:
Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Explanation: Nodes in blue form a subpath in the binary Tree.
Example 2:
Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Example 3:
Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: false
Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.
Constraints:
1 <= node.val <= 100 for each node in the linked list and binary tree.
The given linked list will contain between 1 and 100 nodes.
The given binary tree will contain between 1 and 2500 nodes.
""" | false |
f92cf43577af65a94f924d83123734bf7eafbd20 | pwang867/LeetCode-Solutions-Python | /0874. Walking Robot Simulation.py | 2,330 | 4.3125 | 4 | # cartesian coordinate
# time O(n), space O(1)
class Solution(object):
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
dir = (0, 1) # current moving direction
pos = (0, 0)
obstacles = set(map(tuple, obstacles))
max_dist = 0
for command in commands:
if command < 0:
dir = self.getNextDirection(dir, command)
else:
while command > 0:
new_pos = (pos[0]+dir[0], pos[1]+dir[1])
if new_pos in obstacles:
break
else:
pos = new_pos
max_dist = max(max_dist, pos[0]**2 + pos[1]**2)
command -= 1
return max_dist # return maximum distance, not final position distance
def getNextDirection(self, cur, command):
# use z1 = z*e^(i*theta) to get rotation matrix
# or we can use two dictionaries to get next direction
# d={(1,0):(0,1), ...}
if command == -2: # rotate CCW
return (-cur[1], cur[0])
if command == -1: # CW
return (cur[1], -cur[0])
"""
A robot on an infinite grid starts at point (0, 0) and faces north.
The robot can receive one of three possible types of commands:
-2: turn left 90 degrees
-1: turn right 90 degrees
1 <= x <= 9: move forward x units
Some of the grid squares are obstacles.
The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
If the robot would try to move onto them, the robot stays on the previous
grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will
be from the origin.
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)
Note:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
The answer is guaranteed to be less than 2 ^ 31.
"""
| true |
902e5293b4ce676efe711da81d8015b9c383d4d1 | pwang867/LeetCode-Solutions-Python | /0225. Implement Stack using Queues.py | 2,197 | 4.5 | 4 | # rotate the queue whenever push a new node to stack
from collections import deque
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = deque()
def push(self, x): # time O(n)
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
self.queue.append(x)
for _ in range(len(self.queue)-1):
self.queue.append(self.queue.popleft())
def pop(self): # O(1)
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if not self.queue:
return None
return self.queue.popleft()
def top(self): # O(1)
"""
Get the top element.
:rtype: int
"""
if not self.queue:
return None
return self.queue[0]
def empty(self): # O(1)
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.queue
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
"""
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
Notes:
You must use only standard operations of a queue -- which means
only push to back, peek/pop from front, size, and is empty operations
are valid.
Depending on your language, queue may not be supported natively.
You may simulate a queue by using a list or deque (double-ended queue),
as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example,
no pop or top operations will be called on an empty stack).
"""
| true |
aa8393d6d5d39c4b48c6034fefecef226ca67c93 | pwang867/LeetCode-Solutions-Python | /0092. Reverse Linked List II.py | 1,201 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head or not head.next:
return head
# to solve m == 1 issue
dummy = ListNode(0)
dummy.next = head
# initialize
tail = dummy
for i in range(m-1):
tail = tail.next
pre = tail.next
cur = pre.next
pre.next = None # not mandatory
# reverse
for i in range(n-m):
copy = cur.next # to make sure cur.next is always valid !
cur.next = pre
pre, cur = cur, copy
# reconnect
copy = tail.next
tail.next = pre
copy.next = cur
return dummy.next
"""
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
"""
| false |
fec96f7d0cd28d6151e7d100a72597a178e2e67d | pwang867/LeetCode-Solutions-Python | /0543. Diameter of Binary Tree.py | 1,790 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# time O(n), space O(depth)
# same as method 1, but use attributes
# diameter: count of edges, not count of nodes
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.diameter = 0
self.depth(root)
return self.diameter
def depth(self, root):
if not root:
return 0
left = self.depth(root.left)
right = self.depth(root.right)
self.diameter = max(left + right, self.diameter)
return max(left, right) + 1
# method 1, recursion
class Solution1(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.depth(root)[1]
def depth(self, root):
if not root:
return (0, 0)
left = self.depth(root.left)
right = self.depth(root.right)
depth = max(left[0], right[0]) + 1
diameter = max(left[0] + right[0], left[1], right[1])
return (depth, diameter)
"""
Given a binary tree, you need to compute the length of the diameter
of the tree. The diameter of a binary tree is the length of the
longest path between any two nodes in a tree.
This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
| true |
7a5f58683cea86a8770142cf57c7b6fa2f420150 | eejay73/python-bootcamp | /ch20-lambdas-builtin-functions/main.py | 1,273 | 4.53125 | 5 | #!/usr/bin/env python3
"""
Chapter 20 - Lambdas and builtin functions
@author Ellery Penas
@version 2018.04.07
"""
import sys
def main():
"""main line function"""
# Normal function definetion
def square(x):
return x * x
# lambda version of the same function
# square2 = lambda num: num * num
print(square(4))
# print(square2(5))
# more lambda fun and using the map function to affect items in a list
nums = [1, 2, 3, 4, 5]
dubs = list(map(lambda x: x * 2, nums))
print(dubs) # [2, 4, 6, 8, 10]
# a look at the keyword 'all'; all items must be True to return True
print(all([0, 1, 2, 3])) # False
nums = [2, 4, 6, 8]
print(all([num for num in nums if num % 2 == 0])) # True
# a look at the keyword 'any'; at least 1 item in the collection must be
# true
names = ['Jill', 'Jen', 'Dave', 'Don']
print(any([name[0] == 'J' for name in names]))
# genex vs list comprehension
list_comp = sys.getsizeof([x * 10 for x in range(1000)])
genex = sys.getsizeof(x * 10 for x in range(1000))
print(f"This the size of a list comp element in memory: {list_comp} BYTES")
print(f"This the size of a genex element in memory: {genex} BYTES")
if __name__ == "__main__":
main()
| true |
590935d4f552690e09fb61e25da08a4c57befcf9 | Woosiq92/Pythonworkspace | /5_list.py | 1,124 | 4.15625 | 4 | #리스트
subway1 = 10
subway2 = 20
subway3 = 30
subway = [10, 20, 30]
print(subway)
subway = ["유재석", "조세호", "박명수"]
print(subway)
#조세호가 몇번 째 칸에 타고 있는가?
print(subway.index("조세호"))
# 하하씨가 다음 정류장에 탐
subway.append("하하") # 항상 맨뒤에 삽입
print(subway)
# 정형돈씨를 유재석과 조세호 사이에 태워봄
subway.insert(1, "정형돈")
print(subway)
# 지하철에 있는 사람이 한명씩 내림
print(subway.pop())
print(subway)
print(subway.pop())
print(subway)
print(subway.pop())
print(subway)
# 같은 이름의 사람이 몇 명 있는지 확인하기
subway.append("유재석")
print(subway)
print(subway.count("유재석"))
# 정렬도 할 수 있음
num_list = [ 5, 4, 3, 2, 1]
num_list.sort()
print(num_list)
# 뒤집기
num_list.reverse()
print(num_list)
# 모두 지우기
num_list.clear()
print(num_list)
# 다양한 자료형 함께 사용
num_list = [5, 4, 3, 2, 1]
mix_list = ["조세호", 20, True]
print(mix_list)
#리스트 확장( 병합)
num_list.extend(mix_list)
print(num_list) | false |
185ae423da8786ee4454391f2de6c9c216cb9d92 | matthew-t-smith/Python-Archive | /Merge-Sort.py | 1,464 | 4.125 | 4 | ## Merge-sort on a deck of cards of only one suit, aces high
import math
## We will assign a number value to face cards so the computer can determine
## which is higher or lower
J = 11
Q = 12
K = 13
A = 14
## Here is our shuffled deck
D = [4, 9, Q, 3, 10, 7, J, 5, A, 6, K, 8, 2]
## We define the mergeSort here; notice how it "recursively" calls itself
def mergeSort(deck, p, r):
if p < r:
q = (p + r)//2
mergeSort(deck, p, q)
mergeSort(deck, q + 1, r)
merge(deck, p, q, r)
return deck
## We now define the most important merge function
def merge(deck, p, q, r):
## the sizes of each sub-problem
N_1 = q - p + 1
N_2 = r - q
## create the left and right piles from the original deck
L = []
R = []
for i in range(1, N_1):
L[i] = deck[p + i - 1]
for j in range(1, N_2):
R[i] = deck[q + j]
## we will place a terminator card at the bottom of each pile so that
## we know when we've reached the bottom of a comparison pile
L[N_1 + 1] = math.inf
R[N_2 + 1] = math.inf
## reset our counters
i = 1
j = 1
## compare and either put the left card back into the deck or the right one
for k in range(p, r):
if L[i] <= R[j]:
deck[k] = L[i]
i += 1
else:
deck[k] = R[j]
j += 1
return deck
| true |
b9e10a145429022614da4426e4d461b77cb12007 | Raolaksh/Python-programming | /If statement & comparision.py | 466 | 4.15625 | 4 |
def max_num(num1, num2, num3):
if num1 >= num2 and num1>= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(300, 40, 5))
print("we can also compare strings or bulleans not only numbers")
print("these are comparision operators")
print("! sign means not equal and if we have to tell python that this "
"is equal to this we have to put double = like this == ") | true |
a0788ac07a593928ed83bcaee802c3459538022f | miquelsi/intro-to-python-livelessons | /Problems/problem_6_lucky_number_guess.py | 446 | 4.21875 | 4 | """
Guess the number between 1 and 10
"""
import random
answer = random.randint(1, 10)
guess = int(input("I'm thinking of a number between 1 and 10: "))
# If the number is correct, tell the user
# Otherwise, tell them if the answer is higher or lower than their guess
if answer == guess:
print("It is correct!")
elif guess < answer:
print("No, it's higher")
else:
print("No, it's lower")
print('The number was {}'.format(answer))
| true |
eebd61d9ea854d09ecdf645d594f949bcce30ee0 | ViniciusDanielpps/ViniciusDanielpps | /diferencas_divididas.py | 578 | 4.15625 | 4 | import matplotlib.pyplot as plt
from numpy import linspace as np
"""programa com a finalidade de objter um polinomio generico de grau n, a partir de seus coeficientes .
"""
def fu(x,coeficiente):
funcao=0
n=0
for i in coeficiente:
funcao+=i* x **n
n+= 1
return funcao
constantes=[1,2,-3,5,-5]
"""
for i in constantes:
print(i)
metodo no qual faz a funcao receber uma lista com cada elemento da lista sendo um parametro, melhor que utilizar o
def f(x,*args)
"""
#print("\n",fu(20,constantes))
x= np(1,10,30)
y=(fu(x,constantes))
plt.plot(x,y)
plt.show()
| false |
22b98de5c1195b2101bd649fed279cefbff98b67 | decadevs/use-cases-python-Kingsconsult | /static_methods.py | 899 | 4.21875 | 4 | # Document at least 3 use cases of static methods
# This method don't rely on the class attributes
# They are completely independent of everythin around them
# example 1
class Shape:
def __init__(self, name):
self.radius = name
@staticmethod
def calc_sum_of_angle(n):
return (2 * n - 4) * 90
a = Shape("triangle")
print(a.calc_sum_of_angle(4))
# example 2
class Vehicle:
def __init__(self, name):
self.name = name
@staticmethod
def fuel_consumed(num):
return num * 5
lexuz = Vehicle("lexuz")
print(lexuz.fuel_consumed(6))
# example 3
class Building:
def __init__(self, type, color):
self.type = type
self.color = color
@staticmethod
def number_of_occupants(a):
return a * 6
decagon = Building("storey Building", "brown")
print(decagon.number_of_occupants(3))
| true |
2dcf1f9b20227194ee543bf4d07fd10792fb9256 | RibRibble/python_june_2017 | /Rib/multiply2.py | 514 | 4.40625 | 4 | # Multiply:
# Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16])
# and returns a list where each value has been multiplied by 5. The function should multiply each value in the
# list by the second argument. For example, let's say:
# a = [2,4,10,16]
# Then:
# b = multiply(a, 5)
# print b
# Should print [10, 20, 50, 80 ].
def multiply(list):
new_list = []
for i in list:
new_list += [i*5]
if i >= len(list):
print new_list
multiply([1,2,3,4]) | true |
7b575dc10ab4460b380d40c6971fedd097f9cecc | RibRibble/python_june_2017 | /Rib/ave2.py | 241 | 4.21875 | 4 | # Average List
# Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
print 'For the following list: '
a = [1, 2, 5, 10, 255, 3]
print a
print 'The average of the values in the list is: ' ,sum(a)/2
| true |
6d3c76402feb77a15890b728883722196df4094a | Amertz08/ProjectEuler | /Python/Problem005.py | 519 | 4.15625 | 4 | '''
Takes in a value, start point, and end point
returns true if value is evenly divisible from start to end
'''
def eDiv(value, start, end):
for a in range(start, end + 1):
if (value % a != 0): return False
return True
#Prompt input
print('''
Program will find smallest number than can be evenly divisible
by all valuse in range 1 to whatever value entered by user
''')
end = int(input('Enter last value of range: '))
#Find value
n = 1
while(not eDiv(n, 1, end)):
n += 1
#Print answer
print(n)
| true |
e8c3afdb41c2b9f095f29a42f07b43140f309ba1 | maggie-leung/python_exercise | /02 Odd Or Even.py | 401 | 4.21875 | 4 | num = int(input('Input the number you want to check'))
if (num % 4 == 0):
print('This is a multiple of 4')
elif (num % 2 == 0):
print('This is an even number')
else:
print('This is an odd number')
check = int(input('Check for the multiple'))
if (num % check == 0):
print(str(num) + ' is a multiple of ' + str(check))
else:
print(str(num) + ' is NOT a multiple of ' + str(check))
| true |
e2e55c6c6561d91489e06f710835379e9cbc771e | cybersquare/G12_python_solved_questions | /files_exception/count_chars.py | 821 | 4.25 | 4 |
# Read a text file and display the number of vowels/ consonants/uppercase/ lowercase
# characters in the file.
file = open('hash.txt', "r")
vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
upper = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
lower = set('abcdefghijklmnopqrstuvwxyz')
text = file.read()
countV = 0
countC = 0
countU = 0
countL = 0
for c in text:
if c in vowels: # Check vowel
countV += 1
elif c in cons: # Check consonant
countC += 1
if c in upper: # Check upper case
countU += 1
elif c in lower: # Check lower case
countL += 1
print('The number of Vowels is: ',countV)
print('The number of consonants is: ',countC)
print('The number of uppercase letters is: ',countU)
print('The number of lowercase letters is: ',countL) | true |
a6bb1b1effc36daa8021e53a0a05a64c49a0274e | mikaelaberg/CIS699 | /Ch2_Work/Ch2_4.py | 1,048 | 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, petal, pricePer):
self.name = name
self.petal = petal
self.pricePer = pricePer
def __getName__(self):
return self.name
def __setName__(self, name):
self.name = name
def __getPetal__(self):
return self.petal
def __setPetal__(self, petal):
self.petal = petal
def __getPricePer__(self):
return self.pricePer
def __setPricePer__(self, name):
self.pricePer = pricePer
flw_1 = Flower('Rose', 5, 5.50)
flw_2 = Flower('Tulip', 3, 2.50)
print(flw_1.__getPetal__())
print(flw_2.__getPetal__()) | true |
7a9ea799d19d80b1c22d070ac2588905bcd91dd2 | thomaslast/Test | /Python/Codeacademy/dice_game.py | 1,118 | 4.15625 | 4 | from random import randint
from time import sleep
"""
Program that rolls a pair of dice and asks the user to guess the sum.
"""
number_of_sides = 6
def check_guess(guess):
if guess > max_val:
print ("Guess is too high, guess again")
guess = get_user_guess()
elif guess <= 0:
print ("Guess must be Valid")
guess = get_user_guess()
else:
print ("Valid Guess, rolling...")
rolled_val = roll_dice(number_of_sides)
print (rolled_val)
if guess == rolled_val:
print ("You Win!!!")
else:
print ("Sorry, Try again...")
def get_user_guess():
guess = int(input ("Enter a Guess: "))
check_guess(guess)
return guess
def roll_dice(number_of_sides):
first_roll = randint(1,number_of_sides)
sleep(1)
print ("First Dice roll is: %i" %first_roll)
second_roll = randint(1,number_of_sides)
sleep(1)
print ("Second Dice roll is: %i" %second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("Total is: %i" %total_roll)
return total_roll
max_val = number_of_sides * 2
print ("The max number is: %d" %(max_val))
guess = get_user_guess()
| true |
fe4c8c4e20eb92cacc4ae61803b7b2bda8b243f3 | mrpodkalicki/Numerical-Methods | /lab_1/tasks.py | 686 | 4.125 | 4 | #TASKS (4p)
#1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p)
#2 ask the user for a number and print its factorial (1p)
#3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p)
#4 looking at lab1-input and lab1-plot files create your own python script that takes a number and returns any chart of a given length.
#the length of a chart is the input to your script. The output is a plot (it doesn't matter if it's a y=x or y=e^x+2x or y=|x| function, use your imagination)
#test your solution properly. Look how it behaves given different input values. (1p)
| true |
6c8dfee1a9d82c98efb5ef9fd3379433bf68407f | LalithK90/LearningPython | /privious_learning_code/OS_Handling/os.readlink() Method.py | 708 | 4.15625 | 4 | # Description
#
# The method readlink() returns a string representing the path to which the symbolic link points. It may return an absolute or relative pathname.
# Syntax
#
# Following is the syntax for readlink() method −
#
# os.readlink(path)
#
# Parameters
#
# path − This is the path or symblic link for which we are going to find source of the link.
#
# Return Value
#
# This method return a string representing the path to which the symbolic link points.
# Example
import os
src = '/usr/bin/python'
dst = '/tmp/python'
# This creates a symbolic link on python in tmp directory
os.symlink(src, dst)
# Now let us use readlink to display the source of the link.
path = os.readlink(dst)
print(path)
| true |
72f57e54a9390cb5b076ea4cc409da0e7759713d | LalithK90/LearningPython | /privious_learning_code/OS_Handling/os.popen() Method.py | 1,048 | 4.21875 | 4 | # Description
#
# The method popen() opens a pipe to or from command.The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.The bufsize argument has the same meaning as in open() function.
# Syntax
#
# Following is the syntax for popen() method −
#
# os.popen(command[, mode[, bufsize]])
#
# Parameters
#
# command − This is command used.
#
# mode − This is the Mode can be 'r'(default) or 'w'.
#
# bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
#
# Return Value
#
# This method returns an open file object connected to the pipe.
# Example
import os, sys
# using command mkdir
a = 'mkdir nwdir'
b = os.popen(a, 'r', 1)
print(b)
| true |
5a1a68b0a693a534361db3206bceab00e68106fc | LalithK90/LearningPython | /privious_learning_code/String/String rfind() Method.py | 808 | 4.375 | 4 | str1 = "this is really a string example....wow!!!"
str2 = "is"
print(str1.rfind(str2))
print(str1.rfind(str2, 0, 10))
print(str1.rfind(str2, 10, 0))
print(str1.find(str2))
print(str1.find(str2, 0, 10))
print(str1.find(str2, 10, 0))
# Description
#
# The method rfind() returns the last index where the substring str is found, or -1 if no such index exists,
# optionally restricting the search to string[beg:end]. Syntax
#
# Following is the syntax for rfind() method −
#
# str.rfind(str, beg=0 end=len(string))
#
# Parameters
#
# str − This specifies the string to be searched.
#
# beg − This is the starting index, by default its 0.
#
# end − This is the ending index, by default its equal to the length of the string.
#
# Return Value
#
# This method returns last index if found and -1 otherwise. | true |
4a234927f0f6f3fb11abc4ae52f147ba59b197cb | LalithK90/LearningPython | /privious_learning_code/List/List extend() Method.py | 438 | 4.21875 | 4 |
# Description
#
# The method extend() appends the contents of seq to list.
# Syntax
#
# Following is the syntax for extend() method −
#
# list.extend(seq)
#
# Parameters
#
# seq − This is the list of elements
#
# Return Value
#
# This method does not return any value but add the content to existing list.
# Example
aList = [123, 'xyz', 'zara', 'abc', 123]
bList = [2009, 'manni']
aList.extend(bList)
print("Extended List : ", aList) | true |
98d84207ce7c25952584fcbfabad329cc4690d40 | LalithK90/LearningPython | /privious_learning_code/List/List max() Method.py | 491 | 4.40625 | 4 |
# Description
#
# The method max returns the elements from the list with maximum value.
# Syntax
#
# Following is the syntax for max() method −
#
# max(list)
#
# Parameters
#
# list − This is a list from which max valued element to be returned.
#
# Return Value
#
# This method returns the elements from the list with maximum value.
# Example
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2)) | true |
14c1c4bdd5817b28b1b758d5b3d3fe51bb959f95 | LalithK90/LearningPython | /privious_learning_code/QuotationInPython.py | 448 | 4.40625 | 4 | print("Quotation in Python")
# Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
# as long as the same type of quote starts and ends the string.
# The triple quotes are used to span the string across multiple lines.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
print(word)
print(sentence)
print(paragraph) | true |
14c050442a17bf7f8ffd71aa476d582735789d7d | LalithK90/LearningPython | /privious_learning_code/String/String isupper() Method.py | 509 | 4.53125 | 5 | str = "THIS IS STRING EXAMPLE....WOW!!!"
print(str.isupper())
str = "THIS is string example....wow!!!"
print(str.isupper())
# Description
#
# The method isupper() checks whether all the case-based characters (letters) of the string are uppercase.
# Syntax
#
# Following is the syntax for isupper() method −
#
# str.isupper()
#
# Parameters
#
# NA
#
# Return Value
#
# This method returns true if all cased characters in the string are uppercase and there is at least one cased
# character, false otherwise. | true |
367c5c5015d27b792d9c1e905dff7a72992ad186 | LalithK90/LearningPython | /privious_learning_code/String/String lower() Method.py | 400 | 4.21875 | 4 | str = "THIS IS STRING EXAMPLE....WOW!!!"
print(str.lower())
# Description
#
# The method lower() returns a copy of the string in which all case-based characters have been lowercased.
# Syntax
#
# Following is the syntax for lower() method −
#
# str.lower()
#
# Parameters
#
# NA
#
# Return Value
#
# This method returns a copy of the string in which all case-based characters have been lowercased.
| true |
65329c697810fa82fb33abcfcdf3d452ca4da93f | LalithK90/LearningPython | /privious_learning_code/Dictionary/dictionary update() Method.py | 467 | 4.1875 | 4 | # Description
#
# The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return anything.
# Syntax
#
# Following is the syntax for update() method −
#
# dict.update(dict2)
#
# Parameters
#
# dict2 − This is the dictionary to be added into dict.
#
# Return Value
#
# This method does not return any value.
# Example
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female'}
dict.update(dict2)
print("Value : %s" % dict)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.