blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
359b1f4d28ca3238a2c91373735629256c0bcdc6 | kingpipi/rock-paper-scissors | /rps.py | 2,751 | 4.125 | 4 | from random import randint
#intro
print("Rock...")
print("Paper...")
print("Scissors...")
player_name = str(input("New player, choose your nickname:")).capitalize()
#Interact with user
comp_react = randint(0,2)
if comp_react == 0:
greeting = f"Welcome {player_name} to Rock, Paper, Scissors!"
elif comp_react == 1:
greeting = f"What a funny name {player_name} is, did your parents hate you?"
else:
greeting = f"Alas! I've finally found a {player_name} to beat at Rock, Paper, Scissors"
print(greeting)
#Define initial variables
computer_score = 0
player_score = 0
winning_score = 3
active_game = "y"
#Actual Game start
while active_game == "y":
while computer_score < winning_score and player_score < winning_score:
player = input(f"{player_name} make your move:").lower()
if player == "q" or player == "quit":
print(f"{player_name} quit game")
computer_score = 0 #reset scores to cancel winners
player_score = 0
break
if player not in ['rock','paper','scissors']:
print("something went wrong :|")
computer_score = 0 #reset scores to cancel winners
player_score = 0
break
rand_num = randint(0,2)
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print(f"Computer plays {computer}")
if player == computer:
print("It's a draw!")
elif player == "rock":
if computer == "paper":
print("Computer wins!")
computer_score += 1
else:
print(f"{player_name} wins!")
player_score += 1
elif player == "paper":
if computer == "scissors":
print("Computer wins!")
computer_score += 1
else:
print(f"{player_name} wins!")
player_score += 1
elif player == "scissors":
if computer == "rock":
print("Computer wins!")
computer_score += 1
else:
print(f"{player_name} wins!")
player_score += 1
print(f"{player_name} score: {player_score} | Computer score: {computer_score}")
print("Game over")
if computer_score > player_score:
print("Computer wins game!")
elif player_score > computer_score:
print(f"{player_name} wins game!")
active_game = str(input("Do you want to play again? y/n:")).lower()
#reset scores so game can restart
computer_score = 0
player_score = 0
print(f"Thanks for playing {player_name}, we'll soon meet again...")
| true |
991fea54251d20bc2692341536bb60739384fdf5 | fabianmroman/python | /IBM Cognitive Classes/Python2DS/strings.py | 1,188 | 4.1875 | 4 | mike = 'Michael Jackson'
print (mike[0]) # First character
print (mike[-1]) # Last character
print (len(mike)) # Lenght of string
print (mike[-len(mike)]) # First character
# Print the string forward
for i in range(len(mike)):
print (mike[i], end = '') # " end = '' " Prints everything in a single line
print('')
# Print the string backwards
for i in range(1, len(mike)+1): # Range specifying beginning and end
print (mike[-i], end = '') # "-i" represents the negative values of string index
print('')
print (mike[::2]) # Stride - Zancada, paso largo
print (mike[::3])
print (mike[0:mike.find(' ')]) # Print the first name - Slicing
# Prints from the first "el", if exists
if mike.find('el') != -1:
for i in range(mike.find('el'), len(mike)):
print (mike[i], end = '') # " end = '' " Prints everything in a single line
print('')
print (mike.upper())
mike = mike + ' ' # Concatenate an space
mike3 = 3*mike
print (mike3)
G = "Mary had a little lamb Little lamb, little lamb Mary had a little lamb \
Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go"
H = G.replace("Mary", "Bob")
print (H) | false |
295326313450fc889ee9506753e6a14c698f48d8 | busrabek/Python-Tasks | /fizzbuzz.py | 239 | 4.15625 | 4 | number = int(input("Please enter a number: "))
if 1 <= number <= 100:
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number) | false |
03c56238131336fc92e230f52d2e744dc9fb63f3 | KiranBahra/PythonWork | /PythonTraining/Practice/6.StringLists.py | 484 | 4.65625 | 5 | #Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
varInput = input("Enter Text:")
#this reverses the text as a string is a list
varReverse=varInput[::-1]
print(varReverse)
if (varInput== varReverse):
print("This is a palindrome")
else:
print("This is not a palindrome")
#reversed is a set word in python that will reverse the string
for i in reversed(varInput):
print(i)
| true |
65ffd09d4d2d792f58d772e43a8253587a66813c | anupamnepal/Programming-for-Everybody--Python- | /3.3.py | 621 | 4.46875 | 4 | #Write a program to prompt the user for a score using raw_input. Print out a letter
#grade based on the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit.
#For the test, enter a score of 0.85.
score = raw_input("Enter you score")
try:
score = float(score)
except Exception, e:
print "Enter a valid float Value"
quit()
if score >= 0.9 :
letter = 'A';
elif score >= 0.8 :
letter = 'B';
elif score >= 0.7 :
letter = 'C';
elif score >= 0.6 :
letter = 'D';
elif score < 0.6 :
letter = 'E';
print letter | true |
6d9960c8e6239326706f88c882ff21e9d0116b20 | ad002/LPTHW | /ex39_Notes.py | 1,709 | 4.3125 | 4 | things = ['a', 'b', 'c', 'd']
print(things[1])
#= b
things[1]='z'
print(things[1])
#=z
print(things)
#output:['a', 'z', 'c', 'd']
#lists = you can only use numbers to get items out of a list
#e.g. things[1]
#dict = lets you use anything, not just numbers. It associates one thing
#to another, no matter what it is
stuff = {'name' : 'Zed', 'age' : 39, 'height' : 6*12+2}
print(stuff['name'])
#Output: Zed
print(stuff['age'])
#Output: 39
print(stuff['height'])
#Output: 74
stuff['city'] = "SF"
#Wird das Element einfach hinten angehängt??????????
#Ja, wird es. Es folgt auf 'height'
print(stuff)
#Out: {'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF'}
print(stuff['city'])
#Output: SF
#As you see we use strings to say what we want from the stuff dictionary
#The syntax is:
# name = { 'element' : 'associated value' , 'next element' : 'assoc. value'}
#You dont have to use only strings. You can also do stuff like this:
stuff[1] = "Wow"
stuff[2] = "Neato"
#Zu beachten: Mit diesen Befehlen wird hinten angehängt: (!!!)
# [...], 'SF', 1: 'Wow', 2: 'Neato'}
print(stuff)
#Output also:
#{'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF', 1: 'Wow', 2: 'Neato'}
#Also ganz anders als bei den Listen, wo jetzt das 2. Element mit List[1] durch
#"Wow" ersetzt werden würde!
print(stuff[1])
#Output: Wow
print(stuff[2])
#Output: Neato
print(stuff)
#-> You see: You can use numbers or strings as keys to the dict
#Here's how you delete Stuff:
del stuff['city']
del stuff[1]
del stuff[2]
print(stuff)
#output: {'name: 'Zed', 'age': 39, 'height': 74}
#Also wurden hier das Element mit der Bez. City, sowie das Element mit dem
# Namen (!!) 1 und das Element mit dem "Namen" 2 ! Siehe z.39 bis 47!
| true |
b763e434e634b62133f12244cc3112eb8987b930 | ad002/LPTHW | /ex25.py | 2,132 | 4.21875 | 4 | def break_words(stuff):
#Gespannt, ob das hier beim Aufrufen der Funktion mit gedruckt wird
#Die Dinger heißen "documentation comments" und wenn wir die Funktionen
#über die Console aufrufen und z.b. help(ex25) eingeben, könenn wir
#Sie über den Funktionsdefinitionen sehen als Hilfestellung
"""This function will break up words for us"""
#Die Eingangsworte werden mit .split geteilt und in words gespeichert
words=stuff.split(' ')
return words
#Werden hier wohl die vorher ausgegebenen, bereits "gebrochenen"/gesplitteten
#Worte verwendet (Line 6)oder ist words nur eine neue, lokale variable für
#genau diese eine Funktion?
def sort_words(words):
"""Sort the words"""
#anscheinened gibt es eine funktion die sorted heißt??
return sorted(words)
def print_first_word(words):
"""Print the first word after popping it off"""
#Die Eingangsworte werden "gepoppt", an Stelle 0? und in einer Variable
#word gespeichert -> Gut, den code rückwärts zu lesen
word=words.pop(0)
#Hier wird mal "geprinted", anstatt nur zu "returnen". Ob das einen Unter-
#schied macht?
print(word)
def print_last_word(words):
"""This is the last word after popping it off."""
#Hier "poppen" wir an einer anderen Stelle, an -1
word=words.pop(-1)
print(words)
def sort_sentence(sentence):
"""Takes in a full sentence and returns sorted words"""
#Wir rufen die vorher definierte Funktion auf (Zeile 1) und speichern
#das Ergebnis in der Variablen words
#Der Satz wird also in einzelne Wörter zerbrochen
words=break_words(sentence)
#Wir nutzen die print_first_word Funktion, um das erste Element auszugeben
print_first_word(words)
print_last_word(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence"""
words=break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one"""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
| false |
8e94a7d2a71ea6b2de0cb595ff79e2cfb36d5120 | jnkg9five/Python_Crash_Course_Work | /Styling_Python_Code.py | 1,833 | 4.375 | 4 | #Python_List_Exercise
#PYTHON CRASH COURSE Chapter#3
#When changes will be made to the Python language, they write a Python Enhancement Proposal (PEP)
#The oldest PEPs is PEP8 which instructs programmers on how to style their code.
#Code will be read more often then its written.
#You will write your code and then read it to debug. The idea is that you should be able to read and understand others code.
#Choice between code that is easier to write or code that easier to read, you will be encouraged to write code that's easier to read.
#TO OPEN UP A HYPERLINK to PEP8, see the code below at python.org .
import webbrowser
webbrowser.open('https://www.python.org/dev/peps/pep-0008/#code-lay-out')
#########################
#Indentations
#########################
#PEP8 recommends that you use 4 space per indentation
#In a word processing doc or text editor the tab uses the 4 spaces.
#The Python interpreter will throw errors if tabs are mixed with spaces.
#You can convert tabs into spaces in most editors to debug.
#########################
#Line Length
#########################
#Programmers recommends aht each line should be less than 80 characters.
#This guideline comes because most computers could only fit 79 characters on a single line.
#PEP 8 recommends to limit comments to 72 characters per line since some tools that generate auto documentation will add characters at the beginner of each commented line.
#You can set up a visual cue, usually a vertical line on your screen to show the character limits.
#########################
#Blank Lines
#########################
#To group parts of your programs, use blank lines.
#Blank lines do not effect how the code runs. They affect the readability.
#The Python interpreter uses horizontal indentation to interpet the code, but disregards vertical spacing.
| true |
36e177cc82bfb45369922fbcad512fd334f7d56d | gabrielyap/early-works-python | /32ahw2/part3.py | 376 | 4.15625 | 4 | one = int(input("Enter first number: "))
two = int(input("Enter second number: "))
three = int(input("Enter third number: "))
if (one <= two):
if (one <= three):
print("Lowest number:", one)
elif (two <= one):
if(two <= three):
print("Lowest number:", two)
elif (three <= one):
if (three <= two):
print("Lowest number:", three)
| false |
1f9426a958a249bb01f48035782704ebc906e27e | saisai/tutorial | /python/python_org/library/data_types/itertools/product.py | 360 | 4.1875 | 4 | from itertools import product
def cartesian_product(arr1, arr2):
# return the list of all the computed tuple
# using the product() method
return list(product(arr1, arr2))
if __name__ == '__main__':
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
print(cartesian_product(arr1, arr2))
# https://www.geeksforgeeks.org/python-itertools-product/
| true |
853bb4c8af140d5d7b6ce04b19708b23446c1f9f | saisai/tutorial | /python/techiedelight_com/stack/check-given-expression-balanced-expression-not.py | 1,501 | 4.28125 | 4 | '''
https://www.techiedelight.com/check-given-expression-balanced-expression-not/
'''
from collections import deque
# function to check if given expression is balanced or not
def balance_parenthesis(exp):
# base case: length of the expression must be even
if len(exp) & 1:
return False
# take an empty stack of characaters
stack = deque()
# traverse the input expression
for ch in exp:
# if current in the epxression is an opening brace,
# push it to the stack
if ch == '(' or ch == '{' or ch == '[':
stack.append(ch)
# if current in the expression is a clsoing brace
if ch == ')' or ch == ']' or ch == '}':
# return false if mismatch is found (i.e. if stack is empty,
# the number of opening braces is less than number of closing
# brace, so expression cannot be balanced)
if not stack:
return False
# pop character from the stack
top = stack.pop()
# it the topped characeter if not an opening brace or does not
# pair with current character of the expression
if (top == '(' and ch != ')') or (top == '{' and ch != '}') \
or (top == '[' and ch != ']'):
return False
# expression is balanced only if sack is empty at this point
return not stack
if __name__ == '__main__':
exp = "{()}[{}]"
print(balance_parenthesis(exp))
| true |
16759348c64f450a463cd8c1ad363bd51675995b | saisai/tutorial | /python/python_org/tutorial/introduction.py | 1,563 | 4.15625 | 4 |
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
print()
# 3 times 'un', followed by 'ium'
print(3 * 'un' + 'ium')
print(40 * '-' + 'end')
print()
print("Py" "thon")
print()
text = ('Put several strings within parentheses '
'to have them joined together.')
print(text)
print()
'''
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
'''
word = 'Python'
print(word[0]) # character in position 0
print(word[5]) # character in position 5
print()
print(word[-1]) # last[]character
print(word[-2]) # second-last character
print()
#Note that since -0 is the same as 0, negative indices start from -1.
print(word[0:2]) # characters from position 0 (included) to 2 (excluded)
print(word[2:5]) # characters from position 2 (included) to 5 (excluded)
print()
# Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:
print(word[:2] + word[2:])
print(word[:4] + word[4:])
print()
# Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
print(word[:2]) # character from the beginning to position 2 (excluded)
print(word[4:]) # characters from position 4 (included) to the end
print(word[-2:]) # characters from the second-last (included) to the end
# https://docs.python.org/3/tutorial/introduction.html | true |
49f37fcc2b6474a9e8eb03eb4de38ffb9e0213fb | Issaquah/NUMPY-PYTHON | /EDX_DATA-SCIENCE/NUMPY/Sorting/sorting.py | 1,226 | 4.375 | 4 | import numpy as np
random_array = np.random.rand(10) # generate array of random values
unsorted_array = np.array(random_array)
print("Unsorted array=\n", unsorted_array)
print("")
sorted_array = np.sort(unsorted_array) # use sort to arrange array elements in ascending order
print("Sorted array=\n", sorted_array)
print("")
unsorted_array.sort() # call sort() on unsorted array to do as stated in above comment
print("Sorted array by calling sort() on unsorted_array=\n", unsorted_array)
print("")
# pull out only unique values from arrays
first_array = np.array([1, 11, 3, 4, 5, 2, 11, 19, 5, 1, 2, 13, 7, 19])
print("Unique elements from 1st array=", np.unique(first_array))
print("")
# find out unique elements from 1st and 2nd array
# use intersectId() and pass 1st and 2nd array to find unique values
second_array = np.array([1, 11, 23, 14, 5, 12, 11, 9, 5, 19, 22, 13, 3, 7, 19])
print("Unique elements from 1st and 2nd array=", np.intersect1d(first_array, second_array))
print("")
# you can clearly understand what's executing below this comment. Hail NumPy!!!
print("Sum of all elements of 1st array=", first_array.sum())
print("")
b = 1
print(first_array + b)
| true |
2185d6e49b8f3909d05e18bbe27fb3e0eea6be58 | simrangrover5/Advance_batch2020 | /t3.py | 362 | 4.46875 | 4 |
import turtle
rad = int(input("\n Enter the radius : "))
pen = turtle.Pen()
pen.right(90)
pen.up() #it will not show anything that will be drawn on the interface
pen.forward(50)
pen.down()
pen.color('red','blue') #color(foreground,background)
pen.begin_fill()
pen.circle(rad)
pen.end_fill() #fill the background color into your circle
turtle.exitonclick()
| true |
e5da9a08bf869df6258aa66149a1835d082b78ea | 18zgriffin/AFP-Work | /Test Python.py | 289 | 4.1875 | 4 | print("Hello World")
name = input("You?: ")
age = int(input("Age: "))
print("Hello", name, age)
print("Hello " + name + " " + str(age))
#the comma simply outputs the result
#the plus tries to output the variables as they are
#therefore we must convert the integer to a string outselves
| true |
5fc0397b2c2934f177f857aca178db27d28e43e4 | bedralin/pandas | /Lesson4/slicedice_data.py | 1,886 | 4.3125 | 4 | # Import libraries
import pandas as pd
import sys
print 'Python version ' + sys.version
print 'Pandas version: ' + pd.__version__
# Our small data set
d = [0,1,2,3,4,5,6,7,8,9]
# Create dataframe
df = pd.DataFrame(d)
print d
print df
# Lets change the name of the column
df.columns = ['Rev']
print "Lets change name of column"
print df
# Lets add a column
df['NewCol'] = 5
print "Lets add a column"
print df
# Lets modify our new column
df['NewCol'] = df['NewCol'] + 1
print "Lets modify our new column"
print df
# We can delete columns
del df['NewCol']
print "We can delete columns"
print df
# Lets add a couple of columns
df['test'] = 3
df['col'] = df['Rev']
print "Lets add a couple of columns"
print df
# If we wanted, we could change the name of the index
i = ['a','b','c','d','e','f','g','h','i','j']
df.index = i
print "We can change name of index"
print df
print "We can now start to select pieces of the dataframe using loc"
print df.loc['a']
# df.loc[inclusive:inclusive]
print "df.loc[inclusive:inclusive]"
print df.loc['a':'d']
# df.iloc[inclusive:exclusive]
# Note: .iloc is strictly integer position based. It is available from [version 0.11.0] (http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#v0-11-0-april-22-2013)
print "df.iloc[inclusive:exclusive] but integer position based"
print df.iloc[0:3]
print "df['Rev']"
print df['Rev']
print "df[['Rev', 'test']]"
print df[['Rev', 'test']]
# df['ColumnName'][inclusive:exclusive]
print "df['ColumnName'][inclusive:exclusive]"
print df['Rev'][0:3]
print "df['col'][5:]"
print df['col'][5:]
print "df[['col', 'test']][:3]"
print df[['col', 'test']][:3]
# Select top N number of records (default = 5)
print "df.head() to select top N number of records"
print df.head()
# Select bottom N number of records (default = 5)
print "df.tail() to select bottom N number of records"
print df.tail()
| true |
f0836493a5aabd316d71a60b2478c108aa442040 | bedralin/pandas | /Lesson2/create_data.py | 1,070 | 4.28125 | 4 | # Import all libraries needed for the tutorial
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
import sys #only needed to determine Python version number
# Enable inline plotting
#matplotlib inline
print 'Python version ' + sys.version
print 'Pandas version ' + pd.__version__
print "\nCreate Data!"
# The inital set of baby names
names = ['Bob','Jessica','Mary','John','Mel']
random.seed(500)
random_names = [names[random.randint(low=0,high=len(names))] for i in range(1000)]
# Print first 10 records
print random_names[:10]
# The number of births per name for the year 1880
births = [random.randint(low=0,high=1000) for i in range(1000)]
print births[:10]
print len(births)
print type(births)
BabyDataSet = zip(random_names,births)
print BabyDataSet[:10]
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
print "Creating DataFrame (pandas) object in a format similar to a sql table or excel spreadsheet:\n",df[:10]
print "Export DataFrame object to txt file"
df.to_csv('births1880.txt',index=False,header=False)
| true |
113f1e6b37f3cdf9e0fee294b24af7b359fac917 | abegpatel/LinkedList-Data-Structure-Implementation | /DataStructure/linkedlist/SinglyLinkedlist.py | 2,298 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 20:28:33 2021
@author: Abeg
"""
#singly Linkedlist Implementation
# Create a node
class Node:
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# Insert at the beginning
def insertAtBeginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# Insert after a node
def insertAfter(self, node, data):
if node is None:
print("The given previous node must inLinkedList.")
return
new_node = Node(data)
new_node.next = node.next
node.next = new_node
# Insert at the end
def insertAtEnd(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last = self.head
while (last.next):
last = last.next
last.next = new_node
# Deleting a node
def deleteNode(self, position):
if self.head == None:
return
temp_node = self.head
if position == 0:
self.head = temp_node.next
temp_node = None
return
# Find the key to be deleted
for i in range(position - 1):
temp_node = temp_node.next
if temp_node is None:
break
# If the key is not present
if temp_node is None:
return
if temp_node.next is None:
return
next = temp_node.next.next
temp_node.next = None
temp_node.next = next
def printList(self):
temp_node = self.head
while (temp_node):
print(str(temp_node.item) + " ", end="")
temp_node = temp_node.next
if __name__ == '__main__':
llist = LinkedList()
llist.insertAtEnd(1)
llist.insertAtBeginning(2)
llist.insertAtBeginning(3)
llist.insertAtEnd(4)
llist.insertAfter(llist.head.next, 5)
print('Linked list:')
llist.printList()
print("\nAfter deleting an element:")
llist.deleteNode(3)
llist.printList()
| true |
4c2a3fa7101263b3a820397fe9b54f2c11e956ee | NunoTomas83/Python | /lists_functs.py | 494 | 4.28125 | 4 | """ Script to use several python list functions"""
my_list = [5, 2, 9, 1]
second_list = list(range(5))
print("Length :", len(my_list))
print("1st Index :", my_list[0])
print("1st 3 Values :", my_list[0:3])
print("9 in List :", 9 in my_list)
print("Index for 2 :", my_list.index(2))
print("How Many 2s :", my_list.count(2))
my_list.remove(1)
my_list.pop(0)
my_list.insert(0, 10)
my_list.sort()
print("Sorted : {}".format(my_list))
my_list.reverse()
print("Sorted : {}".format(my_list))
| true |
83825e787a8d45bed32f76904a68446f733dc183 | NunoTomas83/Python | /elevevator.py | 1,409 | 4.15625 | 4 | """ Simulates the an elevator """
class Elevator:
def __init__(self, bottom, top, current):
"""Initializes the Elevator instance."""
self.bottom = bottom
self.top = top
self.current = current
pass
def __str__(self):
return "The elevator is in the {}th floor".format(self.current)
def up(self):
"""Makes the elevator go up one floor."""
if self.current < 10:
self.current += 1
#print(self.current)
pass
def down(self):
if self.current >-1:
self.current -= 1
#print(self.current)
pass
def go_to(self, floor):
"""Makes the elevator go to the specific floor."""
if self.current < 10 and self.current > -1 :
self.current = floor
#print(self.current)
pass
"""instanciate the elevator class"""
elevator = Elevator(-1, 10, 0)
elevator.up()
elevator.current #should output 1
elevator.go_to(10)
elevator.current #should output 10
# Go to the top floor. Try to go up, it should stay. Then go down.
elevator.go_to(10)
elevator.up()
elevator.down()
print(elevator.current) # should be 9
# Go to the bottom floor. Try to go down, it should stay. Then go up.
elevator.go_to(-1)
elevator.down()
elevator.down()
elevator.up()
elevator.up()
print(elevator.current) # should be 1
elevator.go_to(5)
print(str(elevator))
| true |
b493d9f16771f592ca6e7a4e0d41f10e61f056c9 | gmkerbler/Learn-Python-the-hard-way-Tutorial | /ex10_1.py | 794 | 4.25 | 4 | print "ASCII backspace, deletes a single space before it"
print "** blabla \b blabla" #\b is an ASCII backspace, which deletes a single space before it
print "ASCII bell, puts a single space before it"
print "** blabla \a blabla" #\a is an ASCII bell, which puts a single space before it
print "ASCII formfeed, puts a new line and a tab after it"
print "** blabla \f blabla"
print "ASCII linefeed, puts a new line after it"
print "** blabla \n blabla"
print "ASCII %r tab, puts a new line and tab after it" % "vertical"
print "** blabla \v blabla"
print "ASCII %s tab, puts a tab without new line after it" % "horizontal"
print "** blabla \t blabla"
print "Carriage %r" % 'return'
print "** blabla \r blabla"
print "If i want to print a backslash i just write two like this: 6 \\ 3 = 2"
| true |
36574929054c1d21c46a45bb0f04d1f1de1ea1bc | nathantau/YouuuuRL | /flask/string_utils/string_utils.py | 354 | 4.21875 | 4 | def get_6_digit_representation(code: str) -> str:
'''
Given a code, it fills it up with 0s to make it 6-digits.
Parameters:
code (str): The code to add 0s to.
'''
num_zeroes_needed = 6 - len(code)
zeroes_str = ''
for _ in range(num_zeroes_needed):
zeroes_str = str(0) + zeroes_str
return zeroes_str + code | true |
9fbe9cf530242d1065d9fa5c2e973c99c80fd1c7 | venkunikku/exercises_learning | /PycharmProjects/HelloWorldProject/inheritance_polymorphism.py | 1,251 | 4.28125 | 4 | #Inheritance and polymorphism example
class Animal:
""" Example of poly."""
"""More comments about this class."""
def quack(self):
return self.strings['quack']
def bark(self): return self.strings['bark']
def talk(self): return self.strings['talk']
def mcv_pattern(self): return self._doaction('talk')
def _doaction(self,action):
if action in self.strings:
return self.strings[action]
else:
return "Does not have this in the dictionary {0} from class {1}".format(action,self.get_class_name())
def get_class_name(self):
return self.__class__.__name__.lower()
class Duck(Animal):
strings = dict(quack = 'Duck Quacking', bark = 'duck cannot bark', talk = 'Duck cannot talk too')
class Dog(Animal):
strings = dict(quack = 'Dog no Quacking', bark = 'Dog barks', talk = 'Dog cannot talk too')
class Huma(Animal):
strings = dict(quack = 'Human no Quacking', bark = 'Human cannot bark', talkk = 'Human can talk too')
if __name__ == '__main__':
duck = Duck()
print(duck.quack())
human = Huma()
print(human.bark())
dog=Dog()
print(dog.bark())
print(dog.quack())
print('trying mvc patter****')
print(human.mcv_pattern()) | true |
264736c4a5eac5a0d7fc36c8180ec640ccb7a792 | andyskan/26415147 | /python/array.py | 942 | 4.28125 | 4 | #!/usr/bin/python3
#this is a list, that looks like an array, just say that this is array
list = [ 'John', 1998 , 'Cena', 70.2,4020 ]
list2 = ['ganteng', 91]
print (list) # print complete list
print (list[0]) # print element n
print (list[1:3]) # print element on a range
print (list[2:]) # prints elements starting from n th element
print (list2 * 2) # prints list n times
print (list + list2) # print two tuples
#this is tuple, like a list but cannot modify the value
tuple = ( 'John', 1998 , 'Cena', 70.2, 4020 )
tuple2 = ('ganteng',91)
print (tuple) # prints complete tuple
print (tuple[0]) # prints element n
print (tuple[1:3]) # prints element on a range
print (tuple[2:]) # prints elements starting from n-th element
print (tuple2 * 2) # prints tuple n times
print (tuple + tuple2) # print two tuples
list[0]='Meong'
print (list)
#tuple cannot be modified unlike list
| true |
f467112e148356b0fb35020bd7ca4a0a16356370 | andyskan/26415147 | /python/time.py | 462 | 4.15625 | 4 | #!/usr/bin/python
#Learning time in python
import calendar;
import time;
#unformatted time
localtime=time.localtime(time.time())
print "Sekarang waktunya :",localtime
#timeformatting
localtime= time.asctime( time.localtime(time.time()))
print localtime
tanggalan=calendar.month(2016,10)
print "Calendar bulan oktober ini :"
print tanggalan
#leap year
print "Is 2016 a leap year?",calendar.isleap(2016)
print time.asctime(time.localtime(time.clock()))
| false |
df2b5d7c681a944cbe9e4998ef149a5a14737c92 | onionmccabbage/advPythonMar2021 | /my_special.py | 609 | 4.21875 | 4 | # special operators
# for example the asterisk can mean mathematical multiply or repeat a string
# __mult__
# overriding the __eq__ built-in operator
class Word():
def __init__(self, text):
self.text = text
def __eq__(self, other_word):
return self.text.lower() == other_word.text.lower()
def __add__(self, other_word):
return '{}{}'.format(other_word.text, self.text)
if __name__ == '__main__':
w1 = Word('ha')
w2 = Word('Ha')
print('ha' == 'Ha') # False
print(w1 == w2) # True - uses our own __eq__ method
print(w1+w2) # Haha
| true |
4e9e6fd0802da69251fda87b6e8d87a16ec64370 | onionmccabbage/advPythonMar2021 | /using_functions.py | 933 | 4.125 | 4 | # args and kwargs allow handling function parameters
# we use args for positionl/ordinal arguments and kwargs for keyword arguments
def myFn(*args): # *args will make a tuple containing zero or more arguments passed in
# one-arg outcome
if(len(args)== 1):
return 'one argument: {}'.format(args[0])
# two-arg outcome
if(len(args)== 2):
return 'two arguments: {} {}'.format(args[0], args[1])
# else
return 'more than two arguments: {}'.format(args)
def otherFn(*args, **kwargs): # the keyword arguments will be in a dictionary called kwargs
print(args) # see the tuple
print(kwargs)# see the dict
if __name__ == '__main__':
print( myFn('weeble') )
print( myFn('weeble', 'wooble') )
print( myFn('weeble', True, False, [4,3,2], {'name':'value'}) )
otherFn('a', False, [], k=(1,), n={})
otherFn(n=True, x=4, diddledoo=True, result=myFn('coffee')) | true |
1e6eda8ef2ccf528295680be48a94c61ac7a9184 | AmruthaRajendran/Python-Programs | /Counting_valleys.py | 1,551 | 4.59375 | 5 | # HackerRank Problem
''' Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps.
For every step he took, he noted if it was an uphill,U, or a downhill, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms:
A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.
For example, if Gary's path is s=[DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.'''
# Program Code:
import math
import os
import random
import re
import sys
def countingValleys(n, s):
h=0
valley=0
for ch in s:
if(ch=='U'):
h+=1
elif(ch=='D'):
if(h==0):
valley+=1
h-=1
return(valley)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
# Reference: HackerRank Discussion Forum
| true |
701792debbb3529c73a5f97fa159f0cbbd594bc6 | AmruthaRajendran/Python-Programs | /Cats_and_Mouse.py | 2,111 | 4.21875 | 4 | # Hackerrank Problem
''' Question:
Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first,
assuming the mouse doesn't move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight.
You are given q queries in the form of x, y, and z representing the respective positions for cats A and B, and for mouse C. Complete the function catAndMouse to return the
appropriate answer to each query, which will be printed on a new line.
If cat A catches the mouse first, print Cat A.
If cat B catches the mouse first, print Cat B.
If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes.
For example, cat A is at position x=2 and cat B is at y=5. If mouse c is at position z=4, it is 2 units from cat A and 1 unit from cat B. Cat B will catch the mouse.
Function Description
Complete the catAndMouse function in the editor below. It should return one of the three strings as described.
catAndMouse has the following parameter(s):
x: an integer, Cat A's position
y: an integer, Cat B's position
z: an integer, Mouse C's position
Input Format
The first line contains a single integer, q, denoting the number of queries.
Each of the q subsequent lines contains three space-separated integers describing the respective values of x(cat A's location), y(cat B's location), and z(mouse C's location).
Output Format
For each query, return Cat A if cat A catches the mouse first, Cat B if cat B catches the mouse first, or Mouse C if the mouse escapes.
Sample Input 0
2
1 2 3
1 3 2
Sample Output 0
Cat B
Mouse C
# Program Code:
def catAndMouse(x, y, z):
d1 = abs(x-z)
d2 = abs(y-z)
if(d1 == d2):
return("Mouse C")
elif(d1<d2):
return("Cat A")
else:
return("Cat B")
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
x,y,z = map(int,input().split())
result = catAndMouse(x, y, z)
print(result)
| true |
608807c992a9013012f15cc155633e8b5c4914f0 | AmruthaRajendran/Python-Programs | /Password_Problem.py | 1,549 | 4.21875 | 4 | # This was asked on the SAP Labs online preplacement test.
# Question: you are given two strings from which you have to create a new string which is considered as a password.
# The password should be made by combining the letters from each string in alternate fashion.
# eg: input: abc, def output: adbecf
#Program:
def FindPassword(a,b):
n1 = len(a)
n2 = len(b)
n = n1 + n2
newpassword = ' '
l = 0
k = 0
for i in range(0,n):
if(n1 == n2): # For equal length strings we can directly append alternatively.
if(i%2 == 0): # The first string letters will be in positions 0,2,4,etc that is on even number positions.
newpassword += a[l]
l += 1
else:
newpassword += b[k]
k += 1
elif(n1 > n2): # For different lengths remaining length is filled with the largest strings remaining letters.
if(i%2 == 1 and k < n2): # The second string letters will be in odd numbered positions.
newpassword += b[k]
k += 1
else:
newpassword += a[l]
l += 1
elif(n2 > n1):
if(i%2 == 0 and l < n1):
newpassword += a[l]
l += 1
else:
newpassword += b[k]
k += 1
return(newpassword)
# main program
a = input()
b = input()
ans = FindPassword(a,b)
print(ans)
| true |
062f2c51748e40ea410c1c6fd8fbe436fd93d164 | vechaithenilon/Python-learnings | /MORNINGPROJECTRemovingVowels.py | 409 | 4.375 | 4 | VOWEL = ('a','e','i','o','u') #Tuple
message = input('Enter your message here: ')
new_message = ''
for letter in message:
if letter in VOWEL:
print(letter, 'is a vowel') #the latter part is used to print the end of line with a space in between
if letter not in VOWEL:
# new_message = new_message + str(letter)
new_message += letter
print (new_message)
| true |
f5bfd1699b1d9dba71f41840add964af2209b890 | nanodoc2020/Physics | /timeDilator.py | 1,249 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 31 20:15:48 2019
timeDilator calculates the relativistic time dilation between two reference
frames. This is an application of Einstein's special relativity and can be used
to compute the time passed in either frame of reference, moving or stationary.
No units necessarry for the time input. The velocity input must be in meters
per second to give correct answers.
@author: Erik Larsen
"""
import numpy as np
import scipy.constants
def timeDilator():
t=float(input("Please input the time passed: "))
framer=str(input("Is this time the proper time? Y/N: "))
c=scipy.constants.c
v=float(input("What is the speed, v(m/s)? "))
if v>=c:
v=0
print('Einstien shames you. You must choose a value lower than',c)
v=float(input("Please enter your speed: "))
if v>=c:
quit()
gamma=np.round(1/np.sqrt(1-(v/c)**2),3)
print("The Lorentz transformation factor \u03B3=",gamma)
if framer=='Y':
temp=np.round(gamma*t,6)
print("t'=",temp,"\nThe stationary frame's clock shows more time passed.")
else:
temp=np.round(t/gamma,6)
print("tproper=",temp,"\nThe moving clock shows less time passed.")
| true |
6b03b117630c9ee39ad2f472b0a530a66c0d0d76 | jordanNewberry21/python-practice | /lesson20-string-methods.py | 2,534 | 4.5 | 4 | # string methods return a new value rather than modifying in place
# this is because strings as a data type are immutable
spam = 'Hello world!'
print(spam.upper())
print(spam.lower())
answer = input()
if answer == 'yes':
print('Playing again.')
answer.lower()
# lower() and upper() methods return the string as lower or uppercase, respectively
# a useful scenario for these methods could be making a case-insensitive comparison
# isupper() and islower() returns a boolean value
# methods are checking to see if there are upper or lower case values in a string
spam = 'Hello world!'
print(spam.islower()) # returns false because of the capital H
spam = 'HELLO WORLD!'
print(spam.isupper()) # returns true because all characters in the string are uppercase
spam = ''
print(spam.isupper())
print(spam.islower())
# both methods here return false because there needs to be one character
# of the method type to return true
# isalpha() -- checks if string is letters only
# isalnum() -- checks if string is letters and numbers only
# isdecimal() -- checks if string is numbers only
# isspace() -- checks if string is whitespace only
# istitle() -- titlecase only
# startswith() -- checks if string starts with whatever argument is passed in
# endswith() -- checks if string ends with whatever argument is passed in
print(','.join(['cats', 'rats', 'bats']))
print(''.join(['cats', 'rats', 'bats']))
print(' '.join(['cats', 'rats', 'bats']))
print('\n\n'.join(['cats', 'rats', 'bats']))
print('My name is Simon'.split())
# rjust() and ljust() methods will return a padded version of a string
print('Hello'.rjust(10))
# the first argument is an integer that is telling the method how many spaces
# of padding to add to the string, on the right or left side as specified
print('Hello'.rjust(20, '@'))
# the second argument is a 'fill character' where instead of white space
# it adds in whatever character is specified, this can only be one character long
print('Hello'.center(20, '%'))
# center() does the same thing as rjust and ljust but center aligns it
spam = 'Hello'.center(20)
print(spam)
print(spam.strip())
# strip() removes characters from a string
# it's default behavior is to remove white spaces
# but any characters can be passed in as an argument
# and strip() will look through the string from the beginning and end
# until no matching characters are found
# there are also lstrip() and rstrip() methods to strip away from one side of the string
spam = 'Hello there.'
print(spam.replace('e', 'XYZ'))
| true |
c4444916d978830857d3471c73a7ba4258c760f3 | kshiv29/PandasEx | /Udemy python/String1.py | 692 | 4.15625 | 4 | String="This is the string"
String1="this is 1 string"
print(String)
# print(len(String))
# print(String[::-1])
# print(String*2)
# print("hello" " guys")
# word="Ford"
# word= "L"+word[1:]
# print(word)
formatstarting= "Today I will Learn {0} hours {1}".format(2,"python")
formatstarting2 ="Today I will Learn {x} hours {y}".format(x=3,y="python")
print(formatstarting2)
print('{:<20}'.format("shiv kumar yadav"))
print('{:>20}'.format("shiv kumar yadav"))
print('{:o}'.format(10))
print('{:b}'.format(10)) #for binary
print('I\'m a "python learner"')
print(r'this is path C:\number\nan') #raw string
print("""\
Hello:
user Defined Look
hallo ihr seid junge
""") | false |
552940c34e423babaf52f2c62449d29bc3850db8 | robwa10/pie | /python/unpacking-function-arguments.py | 1,342 | 4.71875 | 5 | # Unpacking Function Arguments
"""
## Function params
- args passes in a tuple
- *args unpacks the tuple before passing them in
"""
def multiply(*args):
total = 1
for arg in args:
total = total * arg
return total
# print(multiply(1, 3, 5))
"""
## Passing multiple arguments
"""
def add(x, y):
return x + y
nums = [3, 5]
# Destructures the list into the variables
# i.e. add(3, 5)
# print(add(*nums))
# You must have same number of arguments and params
# Destructuring dicts as names args
dict_nums = {"x": 15, "y": 25}
# print(add(**nums)) # Passes key/value pairs as named keyword args
def apply(*args, operator): # This turns operator into a required keyword arg
pass
"""
## Unpacking Keyword arguments
- '**' collects keyword arguments
"""
def named(**kwargs):
print(kwargs)
# named(name='Jane', age=25)
# You can also unpack a dict into named arguments
details = {'name': 'Bob', 'age': 25}
# named(**details)
def print_nicely(**kwargs):
named(**kwargs)
for arg, value in kwargs.items():
print(f'{arg}: {value}')
# print_nicely(**details)
def both(*args, **kwargs):
print(args)
print(kwargs)
both(1, 3, 5, **details)
# Example he talks about
def post(url, data=None, json=None, **kwargs):
return request('post', url, data=data, json=json, **kwargs) | true |
51a029659882714adb03b696cd70e4f38353a1d2 | VisheshSingh/Get-to-know-Python | /stringformatting.py | 877 | 4.28125 | 4 | # STRING FORMATTING
radius = int(input("Enter the radius: "))
area = 3.142 * radius ** 2
print('The area of circle with radius =', radius,'is', area)
num1 = 3.14258973
num2 = 2.95470314
#PREVIOUS METHOD
print('num1 is', num1, 'and num2 is', num2) # num1 is 3.14258973 and num2 is 2.95470314
#FORMAT METHOD
print('num1 is {0} and num2 is {1}'.format(num1, num2))
print('num1 is {0:.2} and num2 is {1:.3}'.format(num1, num2))
print('num1 is {0:.2f} and num2 is {1:.3f}'.format(num1, num2))
# num1 is 3.14258973 and num2 is 2.95470314
# num1 is 3.1 and num2 is 2.95
# num1 is 3.14 and num2 is 2.955
#USING f-STRINGS
print(f'num1 is {num1} and num2 is {num2}')
print(f'num1 is {num1:.4} and num2 is {num2:.3}')
print(f'num1 is {num1:.4f} and num2 is {num2:.3f}')
# num1 is 3.14258973 and num2 is 2.95470314
# num1 is 3.143 and num2 is 2.95
# num1 is 3.1426 and num2 is 2.955 | true |
433db8f06cf604fd9e95cbce266bd315bbdc7cdf | orikhoxha/itmd-513 | /hw4/hw4-1.py | 1,607 | 4.1875 | 4 | '''
fn: get_user_input(message)
Gets the user input.
Parameters
----------
arg1 : string
message for the console
Returns
---------
string
returns the input of the user
'''
def get_user_input(message):
return input(message)
'''
fn: validate_input_blank(message)
Validate the user input basic case. Checks for the blank input.
Parameters
----------
arg1 : string
message for the console
Returns
---------
string
returns the input of the user after validation.
'''
def validate_input_blank(message):
# Runs until the user inputs a non-blank value.
while True:
user_input = get_user_input(message)
if user_input == '':
print("Please do not leave the input blank")
else:
break
return user_input
'''
fn: main()
Opens the file to generate the html for the data input by a user.
'''
def main():
name = validate_input_blank("Enter your name:")
description = validate_input_blank("Describe yourself:")
html_tags = "<html> \n" \
"<head> \n" \
"</head> \n" \
"<body> \n" \
"\t<center> \n" \
"\t\t<h1> " + name + "</h1> \n" \
"\t</center> \n" \
"\t<hr /> \n" \
"\t" + description + "\n" \
"\t<hr/> \n" \
"</body> \n" \
"<html>"
file = open("home.html", "w")
file.write(html_tags)
file.close()
if __name__ == '__main__':
main()
| true |
0f2b90e06bd55e069eb02f6e90e6206c5c43a9af | Acrelion/various-files | /Python Files/ex34.py | 648 | 4.34375 | 4 | # Looping through a list, printing every item + string.
# In the last line we print index of the elements and then the element itself.
# The element is being selected/called by using its index:
# Give me the element from list animals with index i.
animals = ['bear', 'python', 'peacock', 'kangaroo',
'whale', 'platypus']
"""
print animals[1], "python"
print animals[2], "peacock"
print animals[0], 'bear'
print animals[3], 'kangaroo'
print animals[4], 'whale'
print animals[2], "peacock"
print animals[5], 'platypus'
print animals[4], 'whale'
"""
for i in range(len(animals)):
print "Index %d in the list is %s" % (i, animals[i])
| true |
f1dcc3ab3be3fc15b4f3ef9cad8269e3d3f6aa6e | amitsng7/Leetcode | /Multiply number without using operator.py | 207 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 7 18:38:11 2017
@author: Amit
"""
def multiple(x,y):
if (y==0):
return 0
if(y>0):
return (x + (multiple(x,y-1)))
print(multiple(2,3)) | false |
159e9cfd8bc0e50f2cd0a8d699b29ca71c906fa1 | emilyvroth/cs1 | /homework/homework3/hw3Part3.py | 787 | 4.125 | 4 | name=input("Name of robot => ")
print(name)
x=int(input("X location => "))
print(x)
y=int(input("Y location => "))
print(y)
energy=10
command=''
while command !='end':
print("Robot {} is at ({},{}) with energy: {}".format(name,x,y,energy))
command=input("Enter a command (up/left/right/down/attack/end) => ")
print(command)
command=command.lower()
valid_commands=['up','down','left','right','attack']
if command in valid_commands:
if energy>=1:
if command=='up':
y-=10
elif command=='down':
y+=10
elif command=='right':
x+=10
elif command=='left':
x-=10
elif command=='attack':
if energy>=3:
energy-=4
else:
continue
energy+=1
y=max(y,0)
y=min(y,100)
x=max(x,0)
x=min(x,100)
energy=min(energy,10)
energy=max(energy,0)
| true |
ed00f211b21e7c0c4d7f991ef5f07c03f1d8369e | kamran1231/INHERITENCE-1 | /inheritance1.py | 887 | 4.125 | 4 | # INHERITANCE METHOD
class Mobile:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
def display_all(self):
return f'MOBILE: {self.brand}, MODEL: {self.model} and PRICE: {self.price}'
class Smartphone(Mobile):
# two ways we use the inheritance:
def __init__(self, brand, model, price, ram, internal_memory, rear_camera):
# 1st method:
# Mobile.__init__(self,brand,model,price)
# 2nd Method:
super().__init__(brand, model, price)
self.ram = ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
mob1 = Mobile('nokia', 1108, 3000)
mob2 = Smartphone('samsung', 'qeqwq', 40000, '16GB', '30GB', '25megaPIxcel')
print(mob1.display_all())
print(mob2.price)
print(mob2.display_all())
| true |
1a901ca15f4d9254980157bbd2a0ef07e8e31d69 | SaiPranay-tula/DataStructures | /PY/Da.py | 427 | 4.25 | 4 | #generators
def prints(ran):
for i in range(1,ran):
yield(i*i)
a=prints(10)
print(next(a))
for i in a:
print(i)
g=(i for i in range(10))
print(list(g))
#generator dont until they are called
#they are effecient than list when dont want to store the values
#generator adds functionality to funtion that it returns value at each step
#when we call the function or encloses yield it returns the value | true |
238367ef3065bb99512044a89bd1c61bd85defdf | J040-M4RC0S-Z/first-programs | /Player text/Condições para triângulos.py | 1,733 | 4.15625 | 4 | print("\033[1;35mTriângulo type\033[m")
r1 = float(input("Digite a primeira medida do triângulo: "))
r2 = float(input("Digite a segunda medida do triângulo: "))
r3 = float(input("Digite a terceira medida do triângulo: "))
if r1 < (r2+r3) and r2 < (r1+r3) and r3 < (r1+r2):
if r1 == r2 and r2 == r3 and r3 == r1:
print("Com essas medidas é possível formar um triângulo Equilátero.")
if r1 < (r2+r3) and r2 < (r1+r3) and r3 < (r1+r2):
if r1 == r2 != r3 or r2 == r3 != r1 or r3 == r1 != r2:
print("É possível formar um triângulo isóceles !")
if r1 < (r2+r3) and r2 < (r1+r3) and r3 < (r1+r2):
if r1 != r2 and r2 != r3 and r3 != r1:
print("É possível formar um triângulo Escaleno")
else:
print("Não é possível formar um triângulo com essas medidas de retas. ")
#Outro código
print("\033[1;36mClassificador de triângulos\033[m")
res = 'S'
while res == "S":
r1 = int(input("Digite o tamnho da primeira reta: "))
r2 = int(input("Digite o tamanho da segunda reta: "))
r3 = int(input("Digite o tamanha da segunda reta: "))
if r1 < (r2 + r3) and r2 < (r1 + r3) and r3 < (r1 + r2) and r1 > (r2 - r3) and r2 > (r3 - r2) and r3 > (r2 - r3):
print("Nessas condições podemos formar um triângulo e ele ", end="")
if r1 == r2 == r3:
print("será EQUILÁTERO !")
elif r1 == r2 != r3 or r2 == r1 != r3 or r3 == r2 != r1 or r3 == r1 != r2 :
print("será ISÓCELES !")
elif r1 != r2 != r3 != r1:
print("será ESCALENO ! ")
else:
print("Nessas condições não podemos ter um triângulo !")
res = str(input("Você deseja fazer outro teste ? [S/N]")).strip().capitalize()[0]
print("Fim") | false |
457a30dc984dc1f9d23b3af76eab9e79ae8dfe68 | kyrienguyen5701/LeetCodeSolutions | /Medium/ZigZagConversion.py | 738 | 4.1875 | 4 | '''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows
'''
def convert(s: str, numRows: int) -> str:
if numRows == 1:
return s
orders = [''] * numRows
for i in range(len(s)):
if i // (numRows - 1) % 2 == 0:
orders[i % (numRows - 1)] += s[i]
else:
orders[numRows - 1 - i % (numRows - 1)] += s[i]
return ''.join(orders)
'''
Runtime: 60ms - 80.11%
Memory Usage: 13.6MB - 99.46%
''' | true |
b860e390ffe1908ea53b1ce7ce41bde96dae4726 | kyrienguyen5701/LeetCodeSolutions | /Hard/ShortestPalindrome.py | 588 | 4.21875 | 4 | '''
You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
'''
def shortestPalindrome(s):
def isPalindrome(word, i, j):
while i < j:
if word[i] != word[j]:
return False
i += 1
j -= 1
return True
for i in reversed(range(len(s))):
if isPalindrome(s, 0, i):
furthest = i + 1
break
return s if furthest == len(s) else s[furthest:][::-1] + s
# currently TLE | true |
11d1a81c923da796cf20d053f9b3e7c678102d65 | kyrienguyen5701/LeetCodeSolutions | /Medium/MergeInBetweenLinkedLists.py | 847 | 4.125 | 4 | '''
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeInBetween(self, list1, a, b, list2):
list2_head = list2_tail = list2
while list2_tail and list2_tail.next:
list2_tail = list2_tail.next
list1_head = list1
for _ in range(a - 1):
list1_head = list1_head.next
nxt = list1_head.next
list1_head.next = list2_head
list1_head = nxt
for _ in range(a, b):
list1_head = list1_head.next
list2_tail.next = list1_head.next
list1_head.next = None
return list1
'''
Runtime: 432ms - 93.39%
Memory: 19.9MB - 92.11%
''' | true |
017a603f8be512c3564cb9d72db5e61e0063c7ab | dylcruz/Automate_The_Boring_Stuff | /chapter2/guessTheNumber.py | 662 | 4.15625 | 4 | #This is a guess the number game. The player has 6 tries to guess a random number between 1 and 20
import random
import sys
number = random.randint(1,20)
guess = 0
tries = 0
print('I\'m thinking of a number between 1 and 20.')
while guess != number:
if tries > 5:
print("You lose! My number was " + str(number) + ".")
sys.exit()
print ('Take a guess:')
guess = input()
guess = int(guess)
tries = tries + 1
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
print("You got it! You guessed my number in " + str(tries) + ' tries!') | true |
13a94688618057631f760685cfb529e03499ed95 | akavenus/Calculator | /Calculater.py | 1,242 | 4.25 | 4 | print('Welcome to the vennus calculater')
print('Addition is +')
print('Subtraction is -')
print('Multiplication is *')
print('Division is /')
xe=input('Enter a operater ')
num_1=float(input('Enter your first number: '))
num_2=float(input('Enter your second number: '))
if xe == '+':
print('Your answer is', num_1 + num_2,)
elif xe == '-':
print('Your answer is', num_1 - num_2,)
elif xe == '/':
print('Your answer is', num_1 / num_2,)
elif xe == '*':
print('Your answer is', num_1 * num_2,)
else:
print('You entered a invalid operator')
while True:
yz = input("Would you like to complete another equation? ").lower()
if yz == 'yes':
xe=input('Enter a operater ')
num_1=float(input('Enter your first number: '))
num_2=float(input('Enter your second number: '))
if xe == '+':
print('Your answer is', num_1 + num_2,)
elif xe == '-':
print('Your answer is', num_1 - num_2,)
elif xe == '/':
print('Your answer is', num_1 / num_2,)
elif xe == '*':
print('Your answer is', num_1 * num_2,)
else:
print('You entered a invalid operator')
elif yz == 'no':
print('Thanks so much for usuing venus calculater')
quit()
| true |
e941ba4379ca69ed4a8a76bc6cbe66f20101e419 | abhigun1234/jsstolearnpython | /weekendbatch/sequence/chapter1/operators.py | 749 | 4.21875 | 4 | #aretemetic operators
# + - / * ** %
# print('enter a no and check the no is even or odd')
# a=int(input('enter a no '))
# reminder=a%2
# print("result",reminder)
# if(reminder==1):
# print('it is a odd no')
# else :
# print("it is a even no ")
# result=a+b
# print(result)
# result=a*b
# print(result)
#if
'''
docstring
'''
'''
elif logical operators
'''
name=input('enter user name')
age=int(input('enter user age'))
city=(input('enter your city'))
ticketPrice=2000
discount=0
if age<5:
discount=ticketPrice*10/100
if city=='pune':
print('you are not eligible for the discount')
elif age>5 and age <55:
discount=ticketPrice*5/100
elif age>70:
discount=ticketPrice*20/100
print('discount ',discount)
| true |
00b3ff2a9e3e8e13011c9999524622db10856ef9 | kidexp/91leetcode | /array_stack_queue/380InsertDeleteGetRandomO(1).py | 1,789 | 4.15625 | 4 | import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.num_index_dict = {}
self.value_list = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.num_index_dict:
return False
self.value_list.append(val)
self.num_index_dict[val] = len(self.value_list) - 1
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val not in self.num_index_dict:
return False
val_index = self.num_index_dict[val]
last_element = self.value_list[-1]
self.value_list[val_index], self.value_list[-1] = (
self.value_list[-1],
self.value_list[val_index],
)
self.value_list.pop()
self.num_index_dict.pop(val)
if last_element != val:
self.num_index_dict[last_element] = val_index
return True
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
return self.value_list[random.randint(0, len(self.value_list) - 1)]
if __name__ == "__main__":
random_set= RandomizedSet()
print(random_set.insert(1))
print(random_set.remove(2))
print(random_set.insert(2))
print(random_set.num_index_dict, random_set.value_list)
print(random_set.remove(1))
print(random_set.insert(2))
print(random_set.num_index_dict, random_set.value_list)
print(random_set.remove(2))
print(random_set.num_index_dict, random_set.value_list)
| true |
b5435b55106086b7ef25eda59668ef25ae2565ba | apisitse/workshop2 | /string/modifystring.py | 304 | 4.25 | 4 | string = "Hello, World!"
print (string.upper()) #output: "HELLO,WORLD!"
print (string.lower()) #output: "hello,world!"
print (string.strip()) #output: "Hello,World!"
print (string.replace("H", "J")) #output: Jello,World!
print (string.split(",")) #output: [" Hello" , "World! "]
print (len(string)) # 15 | false |
360e24dfc79fdf12562cbad8fc8075c087d3ba71 | yashasvi-goel/Algorithms-Open-Source | /Sorting/Quick Sort/Python/QuickSort.py | 1,202 | 4.15625 | 4 | #Implementation of QuickSort in Python
def partition(arr,low,high):
# index of smaller element
i = (low-1)
# Pivot is the last element in arr
pivot = arr[high]
print("Pivot is: " + str(pivot))
for j in range(low,high):
# Checks if the current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# Increment index of smaller element
i +=1
# Swap the values at the high index and the smaller index
arr[i],arr[j] = arr[j],arr[i]
# Swap the values
arr[i+1],arr[high] = arr[high],arr[i+1]
return (i+1)
# arr is the array to be sorted
# low is the starting index
# high is the ending index
def QuickSort(arr,low,high):
if len(arr) == 1:
return arr
if low < high:
# p is partitioning index, arr[p] is at the right place
p = partition(arr,low,high)
# Sperately sort elements before partition and after partition
QuickSort(arr,low,p-1)
QuickSort(arr,p+1,high)
if __name__=='__main__':
arr = [10,7,8,9,1,5]
n = len(arr)
QuickSort(arr,0,n-1)
print("Sorted array is:")
for i in range(n):
print(arr[i]) | true |
864b1739ea38bb0e8578ae5d89844e56f978b19d | mrdebator/171-172 | /DrawingARightTriangle.py | 925 | 4.5625 | 5 | # This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
#
# (1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character. (1 pt)
#
#
#
# (2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character. (2 pts)
#
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
triangle_char += ' '
for i in range(triangle_height+1):
print(triangle_char * i)
| true |
1edcd3b9b6474bea839131948277d7540f49baaf | mrdebator/171-172 | /FileIntro.py | 1,116 | 4.34375 | 4 | # In this lab, you will experiment with opening an reading files.
#
# A file has been attached to this lab called english.txt. It contains a selection of random english words. There is one word on each line.
#
# Open the file by using the command
#
# f = open("english.txt","r")
# Ask the user for a single letter. Loop through the file and print any word that starts with that letter. Your letter match should be case insensitive. If the user enters A, you should print words that start with a.
#
# Remember to close your file once you have completed the task.
#
# You are not required to do any error checking in this part of the lab.
#
# Enter First Letter:
# A
# agouties
# amphora
# allotropy
# anguses
# auroras
# assuring
# anesthetics
# arrant
# averments
# autopsied
# anastomoses
# alpaca
# anthropoids
# addicting
# absconder
# answers
# abbe
# aggressors
# armband
# abjuratory
letter = input('Enter First Letter:\n')
with open("english.txt", 'r') as f:
wordList = f.read().split()
for word in wordList:
if word[0] == letter.lower() or word[0] == letter.upper():
print(word)
| true |
a7cd36032fd5b60aa3d163e0d59824addfd84c12 | orel1108/hackerrank | /practice/data_structures/linked_lists/reverse_doubly_linked_list/reverse_doubly_linked_list.py | 586 | 4.15625 | 4 | """
Reverse a doubly linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
return the head node of the updated list
"""
def Reverse(i_head):
if not i_head:
return i_head
while i_head.next:
cp = i_head.next
i_head.prev, i_head.next = i_head.next, i_head.prev
i_head = cp
i_head.prev, i_head.next = i_head.next, i_head.prev
return i_head
| true |
4d831645a79f5e033d17666419695bf3679de4e1 | tkachyshyn/move_in_json | /move_in_json.py | 1,210 | 4.25 | 4 | '''
this module helps the user to move
in the json file
'''
import json
def open_file(path):
'''
open file and convert data into
dictionary
'''
f = open(path)
data = json.load(f)
return data
lst = []
def keys(data):
'''
help the user to choose keys and to
move within them in the dictionary
'''
for key in data:
print(key)
choice = str(input())
lst.append(choice)
try:
new_data = data[lst[-1]]
try:
if type(new_data) == dict or\
type(new_data[0]) == dict:
if type(new_data[0]) == dict:
new_data = new_data[0]
print("This is a dictionary. Do you want to continue?(y/n):")
yes_no_option = str(input())
if yes_no_option == 'y':
try:
keys(new_data)
except TypeError:
return new_data[lst[-1]]
except TypeError:
return new_data
return new_data
except KeyError:
print("That is a wrong key. Please, enter the right one:\n")
keys(data)
print(keys(open_file('move_in_json/friends.json')))
| true |
f185cf0f7b3352771916dc9ab3a2a936ee6751ee | sharvarij09/LMSClub | /Find_Monday | 933 | 4.6875 | 5 | #!/usr/bin/env python3
#
#This is my code which includes a function that will check if i have "Monday" in my calender and prints it in Uppercase
#
def find_monday(mycalender1):
mycalendar1 = """Day Time Subject
Monday 9:10 AM - 10:15 AM LA
10:35 AM - 11:40 AM SS
12:10 PM - 1:15 PM S
Friday 9:10 AM - 10:15 AM Math
10:35 AM - 11:40 AM Exploratory Wheel
12:10 PM - 1:15 PM PF"""
#This is my calender for school
If "Monday" in mycalendar1:
print "Monday is written in this schedule."
else:
print "Monday is not written in this schedule."
#This is my Function
return
def main():
print find_monday()
print mycalendar.upper()
#This is where i will print my schedule in Uppercase
| true |
fabe66fb9a56ea0cef30df8dc94fa5d05ebf2274 | erlaarnalds/TileTraveller | /int_seq.py | 660 | 4.34375 | 4 | num=int(input('Enter an integer: '))
cumsum=0
maxnum=0
odd=0
even=0
while num>0:
cumsum=cumsum+num
print('Cumulative total: ', cumsum)
#finding the maximum number
if num>maxnum:
maxnum=num
#counting odd and even numbers
if num%2==0:
even+=1
else:
odd+=1
num=int(input('Enter an integer: '))
#print info after integer intake has stopped
#maxnum is zero only if the while loop has not been entered,
#so we use that to control whether info is printed or not
if maxnum!=0:
print('Largest number: ', maxnum)
print('Count of even numbers: ', even)
print('Count of odd numbers: ', odd) | true |
e9c6dcf015e432639e1a23cf06fa24968b1336ca | krailis/hackerrank-solutions | /Python/Strings/capitalize.py | 577 | 4.28125 | 4 | def capitalize(string):
words = string.split(" ")
upper = []
for item in words:
if (item.isalnum()):
if (item[0].isalpha()):
str_list = list(item)
str_list[0] = str_list[0].upper()
item_new = "".join(str_list)
upper.append(item_new)
else:
upper.append(item)
else:
upper.append(item)
return " ".join(upper)
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string)
| false |
fcc48fbf44c772f1a894bc4a79afbb21f90eff89 | Pav-lik/Maturita-CS | /Programy/06 - Eratosthenovo síto/sieve.py | 533 | 4.28125 | 4 | limit = int(input("The limit under which to look for primes: "))
# create a boolean array
sieve_list = [True] * limit
primes = []
for i in range(2, limit):
# if the number hasn't been crossed out, cross out all its multiplicands and add it to the list
if sieve_list[i]:
primes.append(i)
# start at i^2 -- every smaller multiple has been crossed-out already
for j in range(i * i, limit, i):
sieve_list[j] = False
input("Primes under " + str(limit) + ": " + str(primes))
| true |
9f90c56bc44c827e75a879f8e343865dc3a7fc7f | amberheilman/info636 | /3BHeilmanCODE.py | 2,655 | 4.125 | 4 | """
Name: Assignment 2B
Purpose:
- read out one number at a time from a file
- User may (A) Accept (R) Replace (I) Insert or (D) Delete the number shown
- User may (S) Save file with remainder of numbers unchanged
- User may (W) Rename file and leave original file undisturbed
Error Conditions:
-Reach end of file
-Improper mode selection -> repeat mode selection
-Improper data entry -> repeat data entry
"""
"""
Main function prompt()
Return: void
Parameters: none
Notes: Main function; uses command line raw_input
"""
def prompt():
#prompt user to enter file name
global filename
filename = raw_input("What is the file name (ie /home/filename.txt) ? ")
#open file for read
global file
file = open(filename, "r+") #above is old
#save an array to keep track of changes
global temp_file
temp_file = file.readlines()
file.close()
display()
def display():
global index
index = 0
while index < len(temp_file):
#print the number
print "Here is your number %s" % (temp_file[index])
#prompt user for mode
mode = raw_input("What would you like to do? Type (A)Accept (R) Replace (I) Insert (D) Delete (S) Save (W) Write new File: ")
if mode == "R":
replace(index)
if mode == "I":
insert()
if mode == "D":
delete(index)
if mode == "A":
pass
if mode == "S":
destroy(file)
break
if mode == "W":
write()
break
elif mode not in ["A", "R", "I", "D", "S", "W"]:
index = index-1
error()
index = index + 1
def replace(index):
#replaces temp array
new_num = raw_input("What is the new number? ")
if check_data(new_num):
temp_file[index] = new_num + "\n"
else:
pass
def insert():
#inserts to temp array
new_num = raw_input("What is the new number? ")
if check_data(new_num):
try:
temp_file[index+1] = new_num + "\n"
except:
temp_file.append(new_num + "\n")
else:
pass
def delete(index):
#delete removes from global temp array
del temp_file[index]
def write():
#if mode is (W) Write, then prompt and save and quit
new_filename = raw_input("New file name (ie file.py): ")
destroy(new_file)
def error():
print "Incorrect Entry.Please try again!"
def check_data(num):
try:
num = int(num)
except:
error()
def destroy(file_name):
file = open(filename, "w")
for num in temp_file:
file.write(num)
file.close()
prompt()
| true |
b5cfe70801789f94d65dc8fb1e4bde1068edc486 | ndanielsen/intro-python | /class_two/01_data_types.py | 504 | 4.25 | 4 | ## Learn More Python with Automate the Boring Stuff:
## https://automatetheboringstuff.com/chapter1/
# Your First Program
#
# print('hello world')
#
# # Comments in python use a '#'
## WARM UP QUIZ
# PART I
a = 5
b = 5.0
c = a / 2
d = b / 2
# What is type(a)?
# What is type(b)?
# What is c?
# What is d?
# EXERCISES
e = [a, b]
f = list(range(0, 10))
# What is type(e)?
# What is len(e)?
# What is type(f)?
# What are the contents of f?
# What is 'list' called? # hint: google it
| false |
a8e42771a2f2a89fd53f18b05c19f9de68ad1108 | ndanielsen/intro-python | /class_two/04_exercise.py | 1,136 | 4.59375 | 5 | """
Extracting city names from a list of addresses
Exercise: Modify `extract_city_name()` to get the city name out of the address_string
"""
list_of_addresses = [
"Austin, TX 78701",
"Washington, DC 20001",
"Whittier, CA 90602",
"Woodland Hills, CA 91371",
"North Hollywood, CA 91601"
"Baltimore, MD 21201",
"Woodland Hills, CA 91365",
"Brea, CA 92821",
"Whittier, CA 90601",
"Studio City, CA 91604",
"Woodland Hills, CA 91364",
"Reseda, CA 91335"
]
def get_list_cities(addresses):
"""Gets a list of the cities from the addresses given to it.
"""
cities = []
for address in list_of_addresses:
city_name = extract_city_name(address)
cities.append(city_name)
return cities
def extract_city_name(address_string):
"""A helper function used in get_list_cities to extract the city name from the address_string.
Look at "02_strings" for hints
"""
#### EXERCISE: Implement extract city from string here
return address_string
if __name__ == "__main__":
cities = get_list_cities(list_of_addresses)
print(cities)
| true |
4e0a986a6af063585625103bfb54940e483610e0 | faisalsetiawan14/praktikum-apd | /konversi suhu.py | 565 | 4.25 | 4 | print("cara konversi suhu")
print("konversi suhu celcius ke fahrenheit, kelvin, dan reamur")
print(" berikut hasilnya")
suhu = ("fahrenheit", "kelvin", "reamur")
suhu_celcius = float(input("masukan suhu dalam celcius"))
suhu_fahrenheit = (9./5) * suhu_celcius+32
suhu_kelvin = suhu_celcius + 273
suhu_reamur = (4./5) * suhu_celcius
print(suhu)
print("hasil perhitungan konversi suhu:")
print("1. suhu fahrenheit adalah: %f" %(suhu_fahrenheit))
print("2. suhu kelvin adalah: %f" %(suhu_kelvin))
print("3. suhu reamur adalah: %f" %(suhu_reamur)) | false |
64bd846c948d790a2870d7a84465b090730a8abf | datazuvay/python_assignments | /assignment_1_if_statements.py | 249 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
name = input("Please enter your name: ")
user_name = "Joseph"
if name == user_name:
print("Hello, {}! The password is: W@12".format(name))
else:
print(f"Hello {name}! See you later!")
| true |
b324e1c6fc51aa01ce6567a7ef9cc60dfaae23be | RajanIsBack/Python_Codes | /Bank_ATM_simulation.py | 941 | 4.28125 | 4 | '''ATM Simulation
Check Balance Make a Withdrawal Pay In Return Card
'''
bank_pin =5267
entered_pin = int(input("Enter your bank pin"))
if(entered_pin != bank_pin):
print("Wrong pin.Exiting and returning card")
else:
print("WELCOME USER !!. Choose from below options")
print("1.Check Balance")
print("2.Withdraw Money")
print("3.Pay in")
print("4.Return Card")
user_option=int(input("Enter an option number"))
if(user_option==1):
print("Balance is 55,283.00")
elif(user_option==2):
withdrawn_amount=int(input("Enter the amount to be withdrawn"))
elif(user_option==3):
pay_in_amount=int(input("Enter the amount of money you want to Pay In"))
print("Press OK to confirm")
elif(user_option==4):
print("Press CANCEL to return your Card")
else:
print("Invalid Input")
print("Thanks for Banking with EDUREKA BANK. Visit Again!!")
| true |
52aba9b05d89481b5ef529a911c7e4e1bb7d8e78 | davkandi/MITx-6.00.1x | /ps6/test.py | 1,582 | 4.71875 | 5 | import string
def build_shift_dict(shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
dict = {}
for i in string.ascii_lowercase:
dict[i] = string.ascii_lowercase[(string.ascii_lowercase.index(i) + shift) % 25]
for i in string.ascii_uppercase:
dict[i] = string.ascii_uppercase[(string.ascii_uppercase.index(i) + shift) % 25]
return dict
print(build_shift_dict(3))
message_text = 'bonjouR'
def apply_shift(shift):
'''
Applies the Caesar Cipher to self.message_text with the input shift.
Creates a new string that is self.message_text shifted down the
alphabet by some number of characters determined by the input shift
shift (integer): the shift with which to encrypt the message.
0 <= shift < 26
Returns: the message text (string) in which every character is shifted
down the alphabet by the input shift
'''
message = ''
for i in message_text:
if i in string.ascii_letters:
message += str(build_shift_dict(shift)[i])
else:
message += i
return message
print(apply_shift(3)) | true |
95c22214e2e788540f942e9bf8380852fa33d23e | anikahussen/algorithmic_excercises | /functions/check_answer.py | 506 | 4.25 | 4 |
def check_answer(number1,number2,answer,operator):
'''processing: determines if the supplied expression is correct.'''
expression = True
if operator == "+":
a = number1 + number2
if answer == a:
expression = True
elif answer != a:
expression = False
elif operator == "-":
a = number1 - number2
if answer == a:
expression = True
elif answer != a:
expression = False
return expression
| true |
ee8969f29c4e9f16093c5b50bee0ad0d38f4ed94 | thphan/Nitrogen-Ice-cream-Shop-Monte_Carlo_Simulation | /Distribution.py | 2,450 | 4.40625 | 4 | # Distribution needed in simulation
import random
class RandomDist:
# RandomDist is a base abstract class to build a Random distribution.
# This class contains an abstract method for building a random generator
# Inherited class must implement this method
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def random(self):
"""
This class is an abstract method for implementation class
should return a random value
:return:
"""
pass
class NormalDist(RandomDist):
def __init__(self, mu: float, sigma: float, low: float, high: float):
"""
To use this class we must provide mu (mean), sigma (standard deviation), low value, and high value
:param mu: mean, in which the normal gaussian will have most distribution
:param sigma: a standard deviation for a random normal distribution parameter
:param low: the lowest value this random generator must provide
:param high: the highest value this random generator must provide
"""
RandomDist.__init__(self, "Normal")
self._mu = mu
self._sigma = sigma
self._low = low
self._high = high
def random(self):
"""
This will return a random gaussian generator by checking the low value and highest value
:return:
"""
while True:
x = random.gauss(self._mu, self._sigma)
if self._low <= x <= self._high:
return x
class GaussianDiscrete(NormalDist):
"""
A random Gaussian Discrete generator
This will include all the feature that gaussian has but will return a discrete value using round
"""
def __init__(self, mu: float, sigma: float, low: float, high: float):
"""
To use this class we must provide mu (mean), sigma (standard deviation), low value, and high value
:param mu: mean, in which the normal gaussian will have most distribution
:param sigma: a standard deviation for a random gaussian parameter
:param low: the lowest value this random generator must provide
:param high: the highest value this random generator must provide
"""
NormalDist.__init__(self, mu, sigma, low, high)
RandomDist.__init__(self, "GaussianDiscrete")
def random(self):
return round(NormalDist.random(self))
| true |
e7c3d7830475a09f733725e064046f2fa72c2a0a | menezesfelipee/exercicios-python | /Aula12/dicionarios_ex03.py | 628 | 4.1875 | 4 | '''3. Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela. A média para aprovação é 7. Se o aluno tirar entre 5 e 6.9 está de recuperação, caso contrário é reprovado.'''
aluno = dict()
aluno['nome'] = input('Digite o nome do aluno: ').strip().capitalize()
aluno['media'] = float(input(f'Digite a média do(a) {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['situacao'] = 'aprovado'
elif 5 <= aluno['media'] < 7:
aluno['situacao'] = 'recuperação'
else:
aluno['situacao'] = 'reprovado'
print(aluno) | false |
d985f4eca97864fbd75db0654c0120564b339e2c | menezesfelipee/exercicios-python | /Aula14/funcoes_ex06.py | 590 | 4.25 | 4 | '''Escreva uma função que, dado um número nota representando a nota de um estudante, converte o valor de nota para um conceito (A, B, C, D, E e F).
Nota Conceito
>=9.0 A
>=8.0 B
>=7.0 C
>=6.0 D
>=5.0 E
<=4.0 F '''
def conceito(nota):
if nota >= 9:
return 'A'
elif nota >= 8:
return 'B'
elif nota >= 7:
return 'C'
elif nota >= 6:
return 'D'
elif nota >= 5:
return 'E'
else:
return 'F'
nota = float(input('Digite a nota do aluno: '))
print(f'O conceito do aluno nessa prova foi {conceito(nota)}')
| false |
0d1c478f529b2ec27f98f77c0b03e799c12e0479 | trejp404/FileWritingProgram | /week10program.py | 2,831 | 4.21875 | 4 | # Prepedigna Trejo
# Assignment 10.1
import os #imports OS library
import time #imports time
# print() for cleaner output
print()
# welcome message
print("---Welcome---")
# print() for cleaner output
print()
# sleep for 2 seconds
time.sleep(2)
print("---To create and store a new file, follow the directions below.---")
# print() for cleaner output
print()
# sleep for 2 seconds
time.sleep(2)
flag1 = 0
# targeted statement (directoryName) will be executed repeatedly as long as the given condition is true
while flag1 == 0:
# Ask user for directory name
directoryName = input("Please enter the name of the directory where you would like to save your \nfile (Ex:'/Users/Alice/Desktop/python_work/'): ")
# print() for cleaner output
print()
print("Verifying directory exists...")
# sleep for 2 seconds
time.sleep(2)
# print() for cleaner output
print()
# if directory exists program will then ask user for file name
if os.path.isdir(directoryName):
flag1 = 1
print("Success! Directory found.")
# loop iterates if directory is not found
else:
flag1 = 0
print("Oops...that directory does not exist. ")
# print() for cleaner output
print()
# sleep for 2 seconds
time.sleep(2)
# user inputs their preferred file name
fileName = input("Please enter the name of your file (Ex: test.txt): ")
# print() for cleaner output
print()
# user inputs their name
name = input ("Please enter your name (Ex: Alice): ")
# print() for cleaner output
print()
# user inputs their address
address = input( "Please enter your home address (Ex: 111 Home Ave): ")
# print() for cleaner output
print()
# user inputs their phone number
phone = input ("Please enter your phone number (Ex: 123-456-7890): ")
# main program
def main():
try:
# open file for writing
with open(fileName, 'w') as fileHandle:
# write data to file
fileHandle.write(name + "," + address + "," + phone)
# print() for cleaner output
print()
# sleep for 2 seconds
time.sleep(2)
# confirmation statement that file was saved and stored in requested directory
print("Success! The file, "+ fileName + ", is now stored in the requested directory.")
except:
# Handle unexpected error
print("Oops...we seem to have run into a problem while attempting to store the file in the requested directory.")
try:
# print() for cleaner output
print()
# sleep for 3 seconds
time.sleep(3)
print("Loading file contents...")
# print() for cleaner output
print()
# sleep for 3 seconds
time.sleep(3)
# open file for reading
with open(fileName, 'r') as fileHandle:
# read data from file
data = fileHandle.read()
# prints data saved to file
print(data)
# print() for cleaner output
print()
except:
# Handle unexpected error
print("Oops...we seem to have run into a problem while trying to read the stored file.")
main() | true |
291638d0af06b1379f39c69a86a9290d0607607d | sapnajayavel/FakeReview-Detector | /features/edit_distance.py | 2,264 | 4.15625 | 4 | #!/usr/bin/env python2.7
#encoding=utf-8
"""
Code about implementing calculate min edit distance using Dynamic Programming. Although the method is used for compare similariy of two strings,it can also be used to compare two vectors
Code from http://blog.csdn.net/kongying168/article/details/6909959
"""
class EditDistance():
def __init__(self):
pass
def levenshtein(self,first,second):
"""
Compute the least steps numver to convert first to second by insert,delete,replace(like comparing first with second)
In information theory and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertion, deletion, substitution) required to change one word into the other. The phrase edit distance is often used to refer specifically to Levenshtein distance.
(str/list of int, str/list of int) -> int
return the mininum distance number
>>> ed = EditDistance()
>>> ed.levenshtein("abc","abec")
1
>>> ed.levenshtein("ababec","abc")
3
In Chinese, distance of each word is 3 times than English
"""
if len(first) > len(second):
first,second = second,first
if len(first) == 0:
return len(second)
if len(second) == 0:
return len(first)
first_length = len(first)+1
second_length = len(second)+1
distance_matrix = [range(second_length)for x in range(first_length)]
for i in range(1,first_length):
for j in range(1,second_length):
deletion = distance_matrix[i-1][j]+1
insertion = distance_matrix[i][j-1]+1
substitution = distance_matrix[i-1][j-1]
if first[i-1]!=second[j-1]:
substitution+=1
distance_matrix[i][j]=min(insertion,deletion,substitution)
#print distance_matrix
return distance_matrix[-1][-1]
if __name__ == '__main__':
import doctest
doctest.testmod()
ed = EditDistance()
print ed.levenshtein('可能是灯光的原因','因为有光的原因')
| true |
37791833300839c3b45d050783b9f00db6be3ded | JuanRojasC/Python-Mision-TIC-2021 | /Lambda Functions/Ejercicio 0 - Experimentacion.py | 874 | 4.125 | 4 | # FUNCIONES LAMBDA O ANONIMAS
funcion = lambda parametro : parametro
funcionSuma = lambda parametro1,parametro2 : parametro1 + parametro2
funcionResta = lambda parametro1,parametro2 : parametro1 - parametro2
funcionMultiplicacion = lambda parametro1,parametro2 : parametro1 * parametro2
funcionDivision = lambda parametro1,parametro2 : parametro1 / parametro2
funcionModulo = lambda parametro1,parametro2 : parametro1 % parametro2
print(funcion(5))
print(funcionSuma(5,5))
print(funcionResta(5,5))
print(funcionMultiplicacion(5,5))
print(funcionDivision(5,5))
print(funcionModulo(5,5))
# METODOS DE ARRAYS (filter-map)
numeros = '123456789'
# METODO FILTER
numerosImpares = list(filter(lambda elemento: (int(elemento) % 2 == 1), numeros))
print(numerosImpares)
# METODO MAP
numerosPotencia = list(map(lambda numero: int(numero) ** 2, numeros))
print(numerosPotencia)
| false |
fc46624c8d57c289ea99c4efdb5cc0de0c6d8e71 | namnhatpham1995/HackerRank | /findthepositionofnumberinlist.py | 559 | 4.28125 | 4 | #Given the participants' score sheet for your University Sports Day,
#you are required to find the runner-up score. You are given scores.
#Store them in a list and find the score of the runner-up.
# in put n=5, arr= 2 3 6 6 5 => output 5
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
print(sorted(list(set(arr)))[-2])
#set() method is used to convert any of the iterable to sequence of iterable elements with "distinct elements"
#sorted()[-2] => sorted increasing and take the runner-up position
| true |
64234ee7f6d0b26f6a512e3da1526a4a82835b77 | dyrroth-11/Information-Technology-Workshop-I | /Python Programming Assignments/Assignemt2/18.py | 633 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Created on Thu Apr 2 10:49:02 2020
@author: Ashish Patel
"""
"""
Define a function reverse() that computes the reversal of a string.
For example, reverse(“I am testing”) should return the string ”gnitset ma I”.
LOGIC:In this we take a string as input and define a empty string rev_string
then iterated through the characters of the string and concatenated them
in front of the rev_string, finally printed the rev_string.
"""
input_string = str(input("Enter a string : \n"))
rev_string=''
for x in input_string:
rev_string = x + rev_string
print("Reversed string is: " + rev_string)
| true |
0a3fdbe0b48cedd0c706d38fd17273080ef34e43 | dyrroth-11/Information-Technology-Workshop-I | /Python Programming Assignments/Assignemt1/7.py | 884 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Created on Wed Mar 25 07:34:41 2020
@author: Ashish Patel
"""
"""
# Write a Python function that prints out the first ‘n’ rows of Pascal's triangle. ‘n’ is user input.
LOGIC:1)As we know pascals triange consist of the binomial coefficient of (1+x)^(n-1) for nth row.
2)Therefore we computed coefficent and printed then in the order that we are suppose to do.
"""
def NCR(n, r):
x = 1
if (r > n - r):
r = n - r
for i in range(r):
x = x * (n - i)
x = x // (i + 1)
return x
def Pascal_triangle(n):
y=2*(n-1)
for x in range(n):
for j in range(y):
print(" ",end="")
for i in range(x + 1):
print(NCR(x, i),
" ", end="")
print()
y=y-2
n=int(input("Enter number of rows of Pascal's triangle to be printed: "))
Pascal_triangle(n) | true |
1c36f2fee1cdbb19c9a4bc35467bb10216776c70 | dyrroth-11/Information-Technology-Workshop-I | /Python Programming Assignments/Assignemt4/13.py | 642 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Created on Thu Apr 16 09:46:08 2020
@author: Ashish Patel
"""
"""
Write a NumPy program to find the number of elements of a given array, length of one array element in bytes,
and the total bytes consumed by the elements of the given array.
Example: Array = [1,2,3]
Size of the array: 3
Length of one array element in bytes: 8
Total bytes consumed by the elements of the array: 24
"""
import numpy
A = numpy.array([1,2,3])
print("Size of the array: ", A.size)
print("Length of one array element in bytes: ", A.itemsize)
print("Total bytes consumed by the elements of the array: ", A.nbytes) | true |
3f4871250a9a6d56f16f5ada8afd808db44b83c8 | tanjased/design_patterns | /04. prototype/prototype.py | 896 | 4.34375 | 4 | import copy
class Address:
def __init__(self, street_address, city, country):
self.street_address = street_address
self.city = city
self.country = country
def __str__(self):
return f'{self.street_address}, {self.city}, {self.country}'
class Person:
def __init__(self, name, address):
self.name = name
self.address = address
def __str__(self):
return f'{self.name} lives at {self.address}'
john = Person('John', Address('123 ndflb', 'Bogota', 'CU'))
print(john)
# Take a look at OOP course for instance references. How to create a copy
jane = copy.deepcopy(john)
# when we perform a shallow copy copy.copy(<instance>), the reference instance inside this instance will still refer to one object and can be overwritten
# while with a deep copy copy.deepcopy(<instance>) a completely independent object will be created. | true |
a18155b85b4e0e3c27707d4c6691c57d3070277e | mkatkar96/python-basic-program | /all python code/file handing.py | 832 | 4.1875 | 4 | '''file handling -1.file handing is very important for accessing other data.
2.there are three modes in file hanling as read , write and append.
3.in read you can red only
4.in write you can write a data but when you write new line old one gets deletd
5.append adds new data and keeps olds data as it is.
6.if you open a file but that file doesnt exist it creates a new file with that name but mode
must be append.
7. we also can acess image using this
..for eg we are aceesed a demo file below'''
#EG-
f1 = open("abc.txt",'a')
f1.write("encryptt side support encrypted communication, an eavesdropper snooping ...")
f1 = open("abc.txt",'r')
for data in f1:
print(data) | true |
fc428bc197e2fd2d8f7312d5c3f5255278fd09ee | gamladz/LPTHW | /ex16.py | 1,208 | 4.53125 | 5 | from sys import argv
script, filename = argv
# Takes the filename arguments and tells user its is liable to deletion
print "We're going to erase %r." % filename
print "if you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
#Takes input of RETURN or CTRL-C to determine the users next action
print "Opening the file..."
# target is a variable which opens the filename in writable formati
target = open(filename, 'w')
# Truncate empties the target variable, not actually necessary as the file
# is opened in writable format, so when you begin writing you will automatically overlap
print "truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
# Assignes raw string input from users into 3 different variables, line 1, line 2, line 3
line1 = raw_input ("line 1: ")
line2 = raw_input ("line 2: ")
line3 = raw_input ("line 3: ")
print "I'm going to write these to the file"
# Writes line1, line2 and line3 to the file
target.write(line1, "\n", line2, "\n", line3)
#target.write("\n")
#target.write(line2)
#target.write("\n")
#target.write(line3)
#target.write("\n")
print "And finally we close it"
target.close() | true |
a0b89a3cd0583036d7a6bbf23c8db205b77df95c | Astrolopithecus/SearchingAndSorting | /Searching & Sorting/binarySearch2.py | 1,219 | 4.34375 | 4 | #Program to search through a sorted list using a binary search algorithm
#Iterative version returns the index of the item if found, otherwise returns -1
def binarySearch(value, mylist):
low = 0
high = len(mylist)-1
while (low <= high):
mid = (low + high) // 2
if (mylist[mid] == value):
#Found it
return mid
if (mylist[mid] < value):
#Search in upper half
low = mid + 1
else:
high = mid - 1
return -1
#Recursive version returns the index of the item if found, otherwise returns -1
##def binarySearchRecursive(mylist, value):
## if len(mylist) = 0:
## return -1 #Base case
## else:
## #Check midpoint
## mid = len(mylist) // 2
## if (mylist[mid] == value):
## #Found it
## return mid
## else: #Figure out which half to explore next
## if (mylist[mid] < value):
## #Search in upper half
## return binarySearchRecursive(mylist[mid + 1:], value)
## else:
## #Search in lower half
## return binarySearchRecursive(mylist[:mid], value)
| true |
2d4c8c7933257b9cc535082659548d04061bbe6d | GBoshnakov/SoftUni-OOP | /Polymorphism and Abstraction/vehicles.py | 1,265 | 4.125 | 4 | from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, fuel_quantity, fuel_consumption):
self.fuel_quantity = fuel_quantity
self.fuel_consumption = fuel_consumption
@abstractmethod
def drive(self, distance):
if distance * self.fuel_consumption <= self.fuel_quantity:
self.fuel_quantity -= distance * self.fuel_consumption
@abstractmethod
def refuel(self, fuel):
self.fuel_quantity += fuel
class Car(Vehicle):
extra_consumption = 0.9
def drive(self, distance):
if distance * (self.fuel_consumption + Car.extra_consumption) <= self.fuel_quantity:
self.fuel_quantity -= distance * (self.fuel_consumption + Car.extra_consumption)
def refuel(self, fuel):
self.fuel_quantity += fuel
class Truck(Vehicle):
extra_consumption = 1.6
def drive(self, distance):
if distance * (self.fuel_consumption + Truck.extra_consumption) <= self.fuel_quantity:
self.fuel_quantity -= distance * (self.fuel_consumption + Truck.extra_consumption)
def refuel(self, fuel):
self.fuel_quantity += 0.95 * fuel
truck = Truck(100, 15)
truck.drive(5)
print(truck.fuel_quantity)
truck.refuel(50)
print(truck.fuel_quantity)
| true |
d3e7620455bf6813e1d7ad372f114f9196c9a0f8 | Tong-Wuu/Technical-Questions | /simple-dp-fib-example.py | 739 | 4.21875 | 4 | # find the nth fib number using dynamic programming
# Solution 1: Memoization with top down approach
def memoi(n):
memo = [None] * (n + 1)
return fib(n, memo)
def fib(i, memo):
if memo[i] is not None:
return memo[i]
if i == 1 or i == 2:
result = 1
else:
result = fib(i - 1, memo) + fib(i - 2, memo)
# Cache the result in a list based on the nth fib number
memo[i] = result
return result
# Solution 2: Bottom up approach
def fib_bottom_up(n):
if n == 1 or n == 2:
return 1
res = [None] * (n + 1)
res[1] = 1
res[2] = 1
for i in range(3, n + 1):
res[i] = res[i - 1] + res[i - 2]
return res[n]
print(memoi(100))
print(fib_bottom_up(100))
| false |
bc4c750579fbe676caa0b2360af236cff60f0d73 | rogeriog/dfttoolkit | /structure_editing/rotate.py | 2,081 | 4.28125 | 4 | #####################################################
### THIS PROGRAM PERFORMS SUCCESSIVE ROTATIONS IN A GIVEN VECTOR
### FOR EXAMPLE:
### USE $> python rotate.py [vx,vy,vz] x=30 y=90
### TO ROTATE VECTOR V=[vx,vy,vz] 30 degrees in X and 90 degrees in Y
#####################################################
import numpy as np
import sys
def unit_vector(vector):
""" Returns the unit vector of the vector."""
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
"""Finds angle between two vectors"""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
def x_rotation(vector,theta):
"""Rotates 3-D vector around x-axis"""
R = np.array([[1,0,0],[0,np.cos(theta),-np.sin(theta)],[0, np.sin(theta), np.cos(theta)]])
return np.dot(R,vector)
def y_rotation(vector,theta):
"""Rotates 3-D vector around y-axis"""
R = np.array([[np.cos(theta),0,np.sin(theta)],[0,1,0],[-np.sin(theta), 0, np.cos(theta)]])
return np.dot(R,vector)
def z_rotation(vector,theta):
"""Rotates 3-D vector around z-axis"""
R = np.array([[np.cos(theta), -np.sin(theta),0],[np.sin(theta), np.cos(theta),0],[0,0,1]])
return np.dot(R,vector)
#print("This is the name of the script: ", sys.argv[0])
#print("Number of arguments: ", len(sys.argv))
#print("The arguments are: " , str(sys.argv))
# input must be in format n,n,n or [n,n,n]
v = np.fromstring(sys.argv[1].strip("[]"), dtype=float, sep=',')
for n in range(2, len(sys.argv)) :
if sys.argv[n].startswith('x=') :
dummy, angle = sys.argv[n].split('=')
angle=float(angle)*np.pi/180
print(angle)
v = x_rotation(v, float(angle))
elif sys.argv[n].startswith('y=') :
dummy, angle = sys.argv[n].split('=')
angle=float(angle)*np.pi/180
v = y_rotation(v, float(angle))
elif sys.argv[n].startswith('z=') :
dummy, angle = sys.argv[n].split('=')
angle=float(angle)*np.pi/180
v = z_rotation(v, float(angle))
else:
print('ERROR, no axis defined.')
print(v)
| true |
d4d730739527523f773b5a69b26792bc503215e4 | Akshaya-Dhelaria-au7/coding-challenges | /coding-challenges/week03/day5/counting_sort.py | 465 | 4.15625 | 4 | '''Counting Sort'''
def countingSort(array):
n = len(array)
output = [0] * n
count = [0] * 100
for i in range(0, n):
count[array[i]] += 1
for i in range(1, 100):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
output[count[array[i]] - 1] = array[i]
count[array[i]] -= 1
i -= 1
for i in range(0, n):
array[i] = output[i]
list = [23,55,12,65,35,24]
countingSort(list)
print("Sorted Array in Ascending Order: ")
print(list)
| false |
6456b274762f583c97fa7862acd1afc27ceaf9af | Akshaya-Dhelaria-au7/coding-challenges | /coding-challenges/week03/day5/index.py | 602 | 4.28125 | 4 | '''Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.'''
element=7
list=[1,3,5,6,8]
n=len(list)
#Index is used to find the position of the value within the list
index=list.index(6)
print("Position of index in list is",index)
#Insert element at beginning
if element < list[0]:
list.insert(element)
elif element > list[n-1]:
#Insert element at the end of list
list.append(element)
for i in range(n-1):
if list[i]<=element<=list[i+1]:
list.insert(i+1,element)
break
print (list)
| true |
7d9b01e16bdf914a9727fa6d7899fe8df96e5800 | dawidpacia/python-selenium | /python_tests/src/fibonacci_primary.py | 888 | 4.125 | 4 | def fibonacci(n_element):
"""
Calculating fibbonacci value
:param n_element: number of fibbonacci sequence
:return:
"""
a_1, a_2 = 0, 1
try:
if n_element == 1:
return a_1
if n_element == 2:
return a_2
if n_element <= 0:
return False
num_of_element = 0
while True:
if if_primary(a_2):
num_of_element += 1
a_1, a_2 = a_2, a_1 + a_2
if num_of_element == n_element:
return a_1
except (TypeError, MemoryError) as err:
print(err)
return False
def if_primary(value):
if value >= 2:
for i in range(2, value//2):
if value % i == 0:
return False
return True
return False
if __name__ == "__main__":
print(fibonacci(10))
print(if_primary(21))
| false |
d9aabbc9a3e63ec8d48091ab8f49ce9a49f1f799 | Ashish-Surve/Learn_Python | /Training/Day5/Functional Programming/1_map_demo_in_python3.py | 1,232 | 4.21875 | 4 |
nums = [1,2,3]
squareelemnts = [i**2 for i in nums if i<3] #list comprehension
print("Original nums list = ", nums)
print("List of square elemnts = ", squareelemnts) #[1, 4]
def sq_elem(x):
return x**2
squareelemnts2 = [sq_elem(i)for i in nums]
print("List of square elemnts = ", squareelemnts2)#[1, 4, 9]
print("sq_elem(5) = ", sq_elem(5))
#2)alternative solution in map() function call:
map_obj = map(sq_elem, nums) #sq_elem is a func functional programming
print("map_obj = ", map_obj) #<map object at 0x0410AE30> 1,4,9
newlist1 = list(map_obj)
print("List of square elemnts = ",newlist1)
print ("---------------------------------------------------")
print("Output of map with lambda = ",list(map(lambda x : x**2,nums)))
print("filter and map = ",list(map(lambda x : x**2,list(filter(lambda x: x<3,nums)))))
print ("---------------------------------------------------")
#in python 3
words =["abc", "xyz", "lmn"]
upper_words = []
map_ob = map(lambda w :w.upper() , words)
print( "Return value of map in Python 3 = ", map_ob)
upper_words = list(map_ob)
print ("Original sequence list = ", words)
print("Upper words = ", upper_words)
#in Python3 map() function returns map object so pass that as parameter to list
| true |
9489322aa60c348a7da1c9d6f2b10fe94533578a | sarahmarie1976/CS_Sprint_Challenges | /src/Sprint_1/01_csReverseString.py | 838 | 4.4375 | 4 | """
Given a string (the input will be in the form of an array of characters), write a function that returns the reverse of the given string.
Examples:
csReverseString(["l", "a", "m", "b", "d", "a"]) -> ["a", "d", "b", "m", "a", "l"]
csReverseString(["I", "'", "m", " ", "a", "w", "e", "s", "o", "m", "e"]) -> ["e", "m", "o", "s", "e", "w", "a", " ", "m", "'", "I"]
Notes:
Your solution should be "in-place" with O(1) space complexity. Although many in-place functions do not return the modified input, in this case you should.
You should try using a "two-pointers approach".
[execution time limit] 4 seconds (py3)
[input] array.char chars
[output] array.char
"""
def csReverseString(chars):
# return [ele for ele in reversed(chars)]
return list(reversed(chars))
print(csReverseString(["l", "a", "m", "b", "d", "a"])) | true |
e4379a3d7a2b92cc140decd99c5568c960f504b3 | ruancs/Python | /ordenacao.py | 237 | 4.125 | 4 | num1 = int(input("digite o primeiro número: "))
num2 = int(input("digite o segundo número: "))
num3 = int(input("digite o terceiro número: "))
if num1 < num2 < num3 :
print("crescente")
else:
print("não está em ordem crescente")
| false |
7eb2d3d1f9dec31542a2ff7c1c948c73f5394b31 | nishant-sethi/HackerRank | /DataStructuresInPython/sorting/MergeSort.py | 919 | 4.21875 | 4 | '''
Created on Jun 4, 2018
@author: nishant.sethi
'''
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the middle point and devide it
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res | true |
491560323401dca9ab3d8e5af49e516842bc5f1b | EduardoPNK/atividadesdiversas | /9.py | 584 | 4.1875 | 4 | #Crie um programa que declare uma matriz de dimensão 3x3
#e preencha com valores lidos pelo teclado.
#No final, mostre a matriz na tela, com a formatação correta.
matriz = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
for i, valor in enumerate(matriz):
for j , valor in enumerate(matriz[i]):
matriz[i][j] = input(f'Informe algum valor para linha {i} e coluna {j}: ')
print('-'*30)
for linha in matriz:
for coluna in linha:
print('[ {} ]'.format(coluna), end='')
print()
print('-'*30) | false |
855da4aad48c1bdcef773f0b768a6469fe90e948 | gtr25/python-basic | /Favorite Character Line Formation.py | 1,340 | 4.21875 | 4 | # This code gets a Maximum Characters per line, Favorite Character and words separated by commas
# From all the possible combinations of the words,
# After excluding the "Favorite Character" and white space,
# if the total number of characters is less than the "Maximum Characters" given by the user,
# That specific combination of words is printed along with the number of characters other than fav char and whitespace
import itertools
def all_combinations(input_list):
combinations = []
for r in range(1, len(input_list) + 1):
combinations += list(itertools.combinations(input_list, r))
def join_tuple_string(strings_tuple) -> str:
return ' '.join(strings_tuple)
return list(map(join_tuple_string, combinations))
max_char = int(input("Max char per line: "))
fav_char = (input("Favorite character: ")).lower()
words = input("Words: ")
word_list = words.split(",")
result_list = []
for word in word_list:
result_list.append(("".join([x for x in word if x.isalnum() is True])).lower())
combinations_list = all_combinations(result_list)
for combo in combinations_list:
combo_count = 0
for char in combo:
if char != fav_char:
combo_count += 1
if combo_count <= max_char:
print("{} ({})".format(combo, combo_count))
| true |
bc3987ef3958064f976a273c125b83f9f03f51a9 | Dirtytrii/data-visualization | /randomWalk/randomWalk.py | 834 | 4.125 | 4 | from random import choice
class RandomWalk:
"""一个可以生成随机步数的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性。 """
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""实现随机漫步"""
# 不断漫步直到列表达到指定长度
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
def get_step(self):
direction = choice([1, -1])
distances = choice(range(10))
step = distances * direction
return step
| false |
5e06d754b4b7553f56d4a2350eba508fc50c8de4 | ponka07/pythoncalc | /calculator.py | 865 | 4.21875 | 4 | print("this will only work with 2 numbers")
print('what do you want to calculate?')
print("1: add")
print("2: subtract")
print('3: multiply')
print('4: divide')
while True:
choice = input('add:1, subtract:2, multiply:3, divide:4, which one do you want? ')
if choice in ('1', '2', '3', '4'):
num1 = float(input('first number: '))
num2 = float(input('second number: '))
if choice == '1':
print(num1, 'plus', num2, 'equals', num1 + num2)
elif choice == '2':
print(num1, 'minus', num2, 'equals', num1 - num2)
elif choice == '3':
print(num1, 'multiplied by', num2, 'equals', num1 * num2)
elif choice == '4':
print(num1, 'divided by', num2, 'equals', num1 / num2)
break
else:
print('enter a proper number') | true |
c18d0e7c99f628c2c5503881b86eac33473c5502 | frankhinek/Deep-Learning-Examples | /tf-max-pool.py | 1,450 | 4.15625 | 4 | '''
A simple max pooling example using TensorFlow library tf.nn.max_pool.
tf.nn.max_pool performs max pooling on the input in the form (value, ksize,
strides, padding).
- value is of shape [batch, height, width, channels] and type tf.float32
- ksize is the filter/window size for each dimension of the input tensor
- strides of the sliding window for each dimension of the input tensor
- padding is the padding algorithm (either 'VALID' or 'SAME')
Reference: https://www.tensorflow.org/api_docs/python/tf/nn/max_pool
'''
import tensorflow as tf
import numpy as np
# `tf.nn.max_pool` requires the input be 4D (batch_size, height, width, depth)
# (1, 4, 4, 1)
x = np.array([
[0, 1, 0.5, 10],
[2, 2.5, 1, -8],
[4, 0, 5, 6],
[15, 1, 2, 3]], dtype=np.float32).reshape((1, 4, 4, 1))
X = tf.constant(x)
def maxpool(input):
# The ksize (filter size) for each dimension (batch_size, height, width, depth)
ksize = [1, 2, 2, 1]
# The stride for each dimension (batch_size, height, width, depth)
strides = [1, 2, 2, 1]
# The padding, 'VALID'
padding = 'VALID'
return tf.nn.max_pool(input, ksize, strides, padding)
out = maxpool(X)
# Initializing the variables
init = tf. global_variables_initializer()
# Launch the graph
with tf.Session() as session:
session.run(init)
# Print session results
print("Output shape: " + str(out.shape))
print("\nMax Pool result:")
print(session.run(out))
| true |
4a1e8de9890faa7ab037b47ff1dc503fea90e772 | goremd/Password-Generator | /pswd_gen.py | 846 | 4.25 | 4 | # Generate pseudo-random numbers
import secrets
# Common string operations
import string
# Defines what characters to use in generated passwords.
# String of ASCII characters which are considered printable.
# This is a combination of digits, ascii_letters, punctuation, and whitespace.
characters = string.ascii_letters + string.digits + string.punctuation
# Defines total number of passwords requested
number = int(input("How many passwords? "))
# Defines length of passwords
length = int(input("Password length: "))
# Calls number variable
for i in range(number):
# What the password will be
password = ''
# Calls length variable
for p in range(length):
# Adds new characters to password
password += secrets.choice(characters)
# Prints generated passwords
print(password)
| true |
dc7d96836d73a18a2b1fe086b92f525889675762 | EduardoPessanha/Git-Python | /exercicios/utilidades/numero/__init__.py | 2,620 | 4.21875 | 4 | # from utilidades import cor
from Exercícios.utilidades.cor import corletra
def leiaint(texto):
"""
-> Lê um valor de entrada e faz a validação
para aceitar apenas um valor numérico.
:param texto: recebe o valor a ser validada.
:return: retorna um valor Inteiro.
"""
while True:
try:
num = int(input(texto))
except (ValueError, TypeError):
print(
f'{corletra("vm")}ERRO! Digite um número \"Inteiro\" válido!.{corletra()}')
continue
except (KeyboardInterrupt, EOFError):
print(
f'\n{corletra("az")}O usuário preferiu não digitar esse valor!{corletra()}')
return 0
else:
return num
def leiafloat(texto):
"""
-> Lê um valor de entrada e faz a validação
para aceitar apenas um valor Real.
:param texto: recebe o valor a ser validado.
:return: retorna um valor Real.
"""
while True:
try:
num = str(input(texto)).replace(',', '.')
num = float(num)
except (ValueError, TypeError):
print(
f'{corletra("vm")}ERRO! Digite um número \"Real\" válido!.{corletra()}')
continue
except (KeyboardInterrupt, EOFError):
print(
f'\n{corletra("az")}O usuário preferiu não digitar esse valor!{corletra()}')
return 0
else:
return num
def leiaintold(texto):
"""
-> Lê uma string de entrada e faz a validação
para aceitar apenas um valor numérico.
:param texto: String a ser validada.
:return: retorna um valor Inteiro.
"""
while True:
n = str(input(texto))
if n.isnumeric(): # Retorna True se houver apenas caracteres numéricos (inteiros),
# caso contrário retorna False
n = int(n)
break
else:
print(
f'{corletra("vm")}ERRO: Digite um número \"Inteiro\" válido. Tente outra vez!{corletra()}')
return n
def leiafloatold(texto):
"""
-> Lê uma string de entrada e faz a validação
para aceitar apenas um valor Real.
:param texto: Recebe o valor a ser validado.
:return: retorna um valor Real.
"""
while True:
valor = str(input(texto)).strip().replace(',', '.')
if valor.isalpha() or valor == '' or valor.isnumeric():
print(
f'{corletra("vm")}ERRO! Digite um número \"Real\" válido! Tente outra vez!{corletra()}')
else:
break
return f'{float(valor):.2f}'
| false |
6787874265e6425437fb1a2b47c9843eef4fe587 | EduardoPessanha/Git-Python | /exercicios/ex113.py | 830 | 4.1875 | 4 | from utilitarios import titulo
from utilidades.numero import leiaint, leiafloat
# ************************ Desafio 113 ************************* #
# Funções aprofundadas em Python #
# Reescreva a função leiaInt() que fizemos no desafio 104, #
# incluindo agora a possibilidade da digitação de um número de #
# tipo inválido. Aproveite e crie também uma função leiaFloat() #
# com a mesma funcionalidade. #
# ************************************************************** #
titulo('Funções aprofundadas em Python')
# ************************************************************** #
nI = leiaint('Digite um número: ')
nR = leiafloat('Digite um número Real: ')
print(f'O número \"Inteiro\" digitado foi {nI} e o número \"Real\" foi {nR}')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.