blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
db1143e720d5235473f01ca94cc39b6ef14e92fd | UnsupervisedDotey/Leetcode | /栈/155.py | 1,464 | 4.5625 | 5 | # 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self._the_min = []
self._data = []
def push(self, x: int) -> None:
self._data.append(x)
if len(self._the_min) == 0:
self._the_min.append(x)
else:
if x < self._the_min[-1]:
self._the_min.append(x)
else:
self._the_min.append(self._the_min[-1])
def pop(self) -> None:
self._the_min.pop()
return self._data.pop()
def top(self) -> int:
return self._data[-1]
def getMin(self) -> int:
return self._the_min[-1]
minStack = MinStack()
minStack.push(-2)
print(minStack._data, minStack._the_min)
minStack.push(0)
print(minStack._data, minStack._the_min)
minStack.push(-3)
print(minStack._data, minStack._the_min)
# minStack.push(0)
# print(minStack._data, minStack._the_min)
# minStack.getMin()
# print(minStack._data, minStack._the_min)
minStack.pop()
print(minStack._data, minStack._the_min)
minStack.getMin()
print(minStack._data, minStack._the_min)
# minStack.pop()
# print(minStack._data, minStack._the_min)
# minStack.getMin()
# print(minStack._data, minStack._the_min)
# minStack.pop()
# print(minStack._data, minStack._the_min)
# minStack.getMin()
# print(minStack._data, minStack._the_min) | false |
32969801992fefeeb0f6d49ce23b1cd6defc67ea | imcdonald2/Python | /9-7_admin.py | 1,193 | 4.125 | 4 | class User():
"""User info"""
def __init__(self, first_name, last_name, age):
"""User first name, last name, and age"""
self.first = first_name
self.last = last_name
self.age = age
def describe_user(self):
print('First name: ' + self.first.title())
print('Last name: ' + self.last.title())
print('Age : ' + str(self.age))
def greet_user(self):
print("How are you doing today " + self.first.title()
+ " " + self.last.title() + "?")
class Admin(User):
"""A class for describing an Admin"""
def __init__(self, first_name, last_name, age):
super().__init__(first_name, last_name, age)
self.first = first_name
self.last = last_name
self.age = age
self.privileges = ['can add post',
'can delete post',
'can ban user',]
def show_privileges(self):
print("Admins have the following privileges:")
for privilege in self.privileges:
print("\t-" + privilege)
new_user = Admin('ian', 'mcdonald', 30)
new_user.show_privileges()
new_user.greet_user()
new_user.describe_user()
| false |
209880bc58394e1b26637a150f957699452642e9 | gabcruzm/Basis-Python-Projects | /loops/loop_through.py | 493 | 4.40625 | 4 | #Loop through a string with For
def run():
# name = input("Write your name: ")
# for letter in name: #For letters in the name it will print each letter in each loop.
# #letter is the variable that will represent each character in each repetition in the for loop. The characters are taken from the name wich is a str.
# print(letter)
frase = input("Write a phrase: ")
for caracter in frase:
print(caracter.upper())
if __name__ == "__main__":
run() | true |
e471cb0845e9550d954db99e807ac0adebd115c0 | maimoneb/dsp | /python/q8_parsing.py | 1,295 | 4.3125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
from csv import reader
with open('football.csv', 'rb') as csvfile:
csv_reader = reader(csvfile, delimiter=',')
header = next(csv_reader) # skip first(header) row
data = [row for row in csv_reader]
def min_score_difference(data, goals_index, goals_allowed_index):
goals = [x[goals_index] for x in data]
goals_allowed = [x[goals_allowed_index] for x in data]
differences = [int(x) - int(y) for x, y in zip(goals, goals_allowed)]
minimum, min_index = min((val, index) for (index, val) in enumerate(differences))
return min_index
goals_index = header.index('Goals')
goals_allowed_index = header.index('Goals Allowed')
team_name_index = header.index('Team')
result_index = min_score_difference(data, goals_index, goals_allowed_index)
print data[result_index][team_name_index]
| true |
72e7171a13387c6fcd77caf8c2c3b03ddf82c155 | pratikv06/python-tkinter | /Entry.py | 520 | 4.1875 | 4 | from tkinter import *
root = Tk()
# Define a function for button4 to perform
def myClick():
msg = "Hello, " + e.get() + "..."
myLabel = Label(root, text=msg)
myLabel.pack()
# Create a entry i.e. input area
# setting width of the entry
# changing border width of the entry
e = Entry(root, width=50, borderwidth=10)
e.pack()
# Setting a default value of entry
e.insert(0, "Enter Something:")
myButton = Button(root, text="Click Me!", command=myClick)
myButton.pack()
root.mainloop() | true |
21cae5cdc5b43d27e62d161e20d46712ae3d7282 | mdelite/Exercism | /python/guidos-gorgeous-lasagna/lasagna.py | 1,467 | 4.34375 | 4 | """Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(elapsed_bake_time):
"""Calculate the bake time remaining.
:param elapsed_bake_time: int - baking time already elapsed.
:return: int - remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME'.
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""
return EXPECTED_BAKE_TIME - elapsed_bake_time
def preparation_time_in_minutes(layers):
"""Calculate the preperation time
:param layers: int - the number of layers to prepare
:return: int - time (in minutes) to prepare the lasagna
Function that the number of layers and returns how many minutes to prepare
based on the 'PREPARATION_TIME'.
"""
return layers * PREPARATION_TIME
def elapsed_time_in_minutes(layers, time):
"""Calculate the time elapsed.
:param layers: int - the number of layers in hte lasagna.
:param time: int
:return: int - time (in minutes) that has elapsed.
Function that calculates the total time that has elapsed in the preperation of
the lasagna.
"""
elapsed = preparation_time_in_minutes(layers) + time
return elapsed
| true |
1216602668067d9a17e4dd59c896d8fe2250be54 | sssmrd/pythonassignment | /38.py | 238 | 4.28125 | 4 | #program to add member(s) in a set.
l=input("Enter some elements=").split();
s=set(l);
print(s)
c=int(input("How many elements to enter="))
for i in range(0,c):
n=input("Enter the element to be added in set=")
s.add(n);
print(s) | true |
ca6341a13308ff63dc68f4546802e8f70b3db014 | shreeyamaharjan/AssignmentIII | /A_a.py | 534 | 4.125 | 4 | def bubble_sort(nums):
for i in range(n - 1):
for j in range((n - 1) - i):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
print(nums)
else:
print(nums)
print("\n")
lst = []
n = int(input("Enter the size of the list : "))
for i in range(n):
x = int(input())
lst.append(x)
print("The unsorted list is : ", lst)
bubble_sort(lst)
print("The sorted list is : \n", lst)
| false |
55b8617e66a268c69ef5e2e14861dcc494034b11 | edwardyulin/sit_project | /sit_il/utils/moving_average.py | 623 | 4.15625 | 4 | import numpy as np
def moving_average(data: np.ndarray, window_size: int) -> np.ndarray:
"""Return the moving average of the elements in a 1-D array.
Args:
data (numpy.ndarray): Input 1-D array.
window_size (int): The size of sliding window.
Returns:
numpy.ndarray: Moving average of the elements in `data`.
Examples:
>>> data = np.array([10,5,8,9,15,22,26,11,15,16,18,7])
>>> moving_average(data, 4)
array([ 8. , 9.25, 13.5 , 18. , 18.5 , 18.5 , 17. , 15. , 14. ])
"""
return np.convolve(data, np.ones(window_size), "valid") / window_size
| true |
b5aa438957ab34145e3e8228f28ffddc91251e80 | joshisujay1996/OOP-and-Design-Pattern | /oop/employee_basic.py | 1,049 | 4.3125 | 4 | """
Basic OOD Example
In python everything is derived from a class and they have their own methods, like List, tuple, int, float, etc
Everything is an Object in PY and they have there own methods and attributes
we create instance out of the list class or tuple or etc
pop, append,__str__, remove are methods of th list class
"""
class MyEmployee:
def __int__(self):
pass
MyEmployee.branch = "NY" # will be attached to all the objects fo the class
my_emp = MyEmployee()
my_emp.name = "sujay"
my_emp.age = 23
print(my_emp.branch) # the branch data is attached to all the objects fo the MyEMployee class
print("printing my_emp", my_emp)
print("printing in dic format \t", my_emp.__dict__) # See branch data is not shown on the dic output;
# since its a class instance var not a obj instance var, its same for every object of MyEmployee
print("Printing the MyEmployee class dic \n", MyEmployee.__dict__)
"""
__str__ : used to give string representation of the object
similarly __repr__; read about it for more detail
"""
| true |
9d8d92fc2e55c20249dd984394faac14af74064e | TusharKanjariya/python-practicles | /8.py | 252 | 4.15625 | 4 | str1 = input("enter string")
str2 = input("enter string")
if len(str1) != len(str2):
print("Length Not Equal")
print(tuple(zip(str1, str2)))
for x, y in zip(str1, str2):
if x != y:
print("Not Equal")
else:
print("Equal")
| false |
5b0d75ecbaebe98998a91200d2cb95d667a7d8d6 | dhobson21/python-practice | /practice.py | 1,794 | 4.1875 | 4 | # 11/19/19--------------------------------------------------------------------------------
"""Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
"""
# My Solution
def toJadenCase(string):
words = string.split()
finish = []
for word in words:
new = word.capitalize()
finish.append(new)
s = " "
return s.join(finish)
"""
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
"""
# My Solution
def spin_words(sentence):
words = sentence.split()
final_words = []
for word in words:
if len(word) > 4:
# Slice word and reverse if word is more than 4 characters long
rev = word[::-1]
final_words.append(rev)
else:
final_words.append(word)
s = " "
last = s.join(final_words)
return last | true |
5654828bd965177fc7ef341aecaf1fb897e59a1e | weekswm/cs162p_week8_lab8 | /Car.py | 1,291 | 4.25 | 4 | #Car class
class Car:
'''Creates a class Car
attributes: make, color, and year
'''
def __init__(self, make = 'Ford', color = 'black', year = 1910):
'''Creates a car with the provided make, color, year.
Defaults to Ford black 1910.
'''
self.make = make
self.color = color
self.year = year
'''Getters and Setters for make, color, and year
'''
#Getter and Setter for make
def getMake(self):
return self.make
def setMake(self, newMake):
self.make = newMake
#Getter and Setter for color
def getColor(self):
return self.color
def setColor(self, newColor):
self.color = newColor
#Getter and Setter for year
def getYear(self):
return self.year
def setYear(self, newYear):
self.year = newYear
# Overloading equality operator
def __eq__(self, differentCar):
'''Overloaded equality operator.
Returns True if color, year, and make match
'''
return (self.make == differentCar.make and self.color == differentCar.color and self.year == differentCar.year)
def __str__(self):
#Returns string of color, year, and make of Car
return ("%s %s %s" % (self.color, self.year, self.make)) | true |
2034276de5f99ed60e9ab3fd0d3e8d667c3e5ba0 | mugwch01/Trie | /Mugwagwa_Trie_DS.py | 2,267 | 4.21875 | 4 | #My name is Charles Mugwagwa. This is an implementation of a Trie data structure.
class Trie:
def __init__(self):
self.start = None
def insert(self, item):
self.start = Trie.__insert(self.start, item+"$")
def __contains__(self,item):
return Trie.__contains(self.start,item+"$")
#using this function because the node can be None and recursion on self complicated
def __insert(node,item):
if item == "":
return None
if node == None:
node = Trie.TrieNode(item[0])
node.follows = Trie.__insert(node.follows,item[1:])
elif item[0] == node.item:
node.follows = Trie.__insert(node.follows, item[1:])
else:
node.next = Trie.__insert(node.next, item)
return node
def __contains(node,item):
if node == None:
return False
elif item[0] == node.item:
if node.item == "$" and len(item) == 1:
return True
return Trie.__contains(node.follows,item[1:])
elif item[0] != node.item:
if node.next != None:
return Trie.__contains(node.next,item)
else:
return False
class TrieNode:
def __init__(self,item,next = None, follows = None):
self.item = item
self.next = next
self.follows = follows
def main():
trie = Trie()
file = open('wordsEn.txt','r')
for line in file:
line = line[:-1]
trie.insert(line)
file.close()
file = open('declaration_of_independence.txt','r')
lineCount = sum(1 for line in file) #includes blank lines
file.seek(0)
for t in range(lineCount):
line = file.readline()
if line != "":
splitLine = line.split()
for word in splitLine:
if word[-1]==',' or word[-1]=='.' or word[-1]==';' or word[-1]==':':
word = word[:-1]
word = word.lower()
if word not in trie:
print(word)
if __name__ == '__main__':
main() | true |
c1940693fd3eface908ff33ad53698b00bccba0a | patrickbucher/python-crash-course | /ch07/pizza-toppings.py | 294 | 4.125 | 4 | prompt = 'Which topping would you like to add to your pizza?'
prompt += '\nType "quit" when you are finished. '
topping = ''
active = True
while active:
topping = input(prompt)
if topping == 'quit':
active = False
else:
print(f'I will add {topping} to your pizza.')
| true |
05a6e73545aba94442b52eb8cfcced8225292cad | qmisky/python_fishc | /3-3 斐波那契数列-递归.py | 372 | 4.21875 | 4 | def factorial(x):
if x==1:
return 1
elif x==2:
return 1
elif x>2:
result=int(factorial(x-1))+int(factorial(x-2))
return result
elif x<0:
print ("WRONG NUMBER!")
number=int(input("please enter a positive number:"))
result=factorial(number)
print("the %d'th month,the amount of the rabbits is:%d"%(number,result))
| true |
905976bf6c4a48cb5e3a9a10f8bf8dd4179f17da | AKArrow/AllPracticeProblemInPython | /week.py | 289 | 4.15625 | 4 | n=input("Enter A Week Day:")
if n==1:
print "monday"
elif n==2:
print "tuesday"
elif n==3:
print "wednesday"
elif n==4:
print "thursday"
elif n==5:
print "friday"
elif n==6:
print "saturday"
elif n==7:
print "sunday"
else:
print "There Is No Such Week Day!" | false |
35dd288697bfe404b8f069973f4ca4e79091d445 | Shivanshu17/DS-Algo | /Insertion_Sort.py | 291 | 4.1875 | 4 | def insertionsort(arr):
l = len(arr)
for i in range(1,l):
j= i-1
key = arr[i]
while(j>=0 and key<arr[j]):
arr[j+1] = arr[j]
j = j-1
arr[j+1] = key
arr = [3,5,1,6,3,8,2,9]
insertionsort(arr)
for k in arr:
print(k) | false |
0165c1a06718db569cd1f53a94956a1508b5959e | DanWade3/belhard_8_tasks | /tasks/easy/inheritance_polimorphism/duck_typing.py | 745 | 4.34375 | 4 | """
Создать 3 класса:
Cat, Duck, Cow
в каждом классе определить метод says()
Cat.says() - кошка говорит мяу
Duck.says() - утка говорит кря
Cow.says() - корова говорит муу
Написать функцию animal_says(), которая принимает объект и вызывает метод says
"""
class Cat:
def says(self):
print("кошка говорит мяу")
class Duck:
def says(self):
print("утка говорит кря")
class Cow:
def says(self):
print("корова говорит муу")
def animal_says(animal):
animal.says()
animal_says(Duck())
animal_says(Cat())
animal_says(Cow()) | false |
5e86d3968b563d852e0dd68b67f48d12b37036d3 | psgeisa/python_eXcript | /Excript - Aula 01 - Concatenar.py | 698 | 4.28125 | 4 | # Concatenando numero inteiro e str
num_int = 5
num_dec = 7.3
val_str = "qualquer texto"
# %d é um marcador padrão
print("1ª forma - o valor é:", num_int)
print("2ª forma - o valor é:%i" %num_int) # %i de "inteiro"
print("3ª forma - o valor é:" + str(num_int)) # Essa concatenação necessita de conversão int > str
print("1ª forma - o valor é:", num_dec)
print("2ª forma - o valor é: %f" %num_dec) # %f de "float"
print("2ª forma - o valor é: %.4f" %num_dec)
print("3ª forma - o valor é:" + str(num_dec))
print("1ª forma - o valor é:", val_str)
print("2ª forma - o valor é: %s" %val_str) # %s de "string"
print("2ª forma - o valor é: %.4f" + val_str)
| false |
3c647ea21a894256099a43bf1835c741ca6aea32 | bhuiyanmobasshir94/haker-rank | /Problem-Solving/stair_case.py | 341 | 4.15625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
def staircase(n):
for i in range(1,n+1):
str=''
for k in range(1,((n-i)+1)):
str +=' '
for j in range(1,i+1):
str += '#'
print(str)
if __name__ == '__main__':
n = int(raw_input())
staircase(n)
| false |
c3fbdb921f822e4d6ebfeeeb8c11459af4f8af50 | jasonwsvt/Python-Projects | /db_sub.py | 1,389 | 4.375 | 4 | """
Use Python 3 and the sqlite3 module.
Database requires 2 fields: an auto-increment primary integer field and a field with the data type “string.”
Read from fileList and determine only the files from the list which end with a “.txt” file extension.
Add those file names from the list ending with “.txt” file extension within your database.
Print the qualifying text files to the console.
Provide good comments.
"""
import sqlite3
fileList = ('information.docx', 'Hello.txt', 'myImage.png', 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
def commit(stmt):
with sqlite3.connect('db_sub.db') as conn:
cur = conn.cursor()
try:
cur.execute(stmt)
conn.commit()
except:
print(stmt + ' is not a valid query.')
conn.close()
def fetchall(stmt):
with sqlite3.connect('db_sub.db') as conn:
cur = conn.cursor()
try:
cur.execute(stmt)
result = cur.fetchall()
except:
result = stmt + ' is not a valid query.'
print(result)
conn.close()
return result
commit("create table if not exists tbl_strings(id integer primary key autoincrement, col_string string)")
for file in fileList:
if file.endswith('.txt'):
commit("insert into tbl_strings('col_string') values('{}')".format(file))
print("{} inserted into database.".format(file))
print("\nAll records in database:")
for record in fetchall("select * from tbl_strings"):
print(record) | true |
bdf21e232926951c456a4ddbbb11799289ea3f27 | osho-sunflower/python_session_snippets | /console_io.py | 489 | 4.15625 | 4 | # Python2 ----> Python3
# input() ----> eval(input())
# raw_input() ----> input()
# Python3
string = input('Enter a string: ')
print('Got:', string)
number = int(input('Enter a number: '))
print('Got:', number)
expression = eval(input('Enter an expression: '))
print('Evaluated:', expression)
# # Python2
# string = raw_input('Enter a string: ')
# print('Got:', string)
#
# expression = input('Enter an expression: ')
# print('Evaluated:', expression)
| false |
c526f0b569465e0e1a3cd10674793bff1debd6bf | luzap/intro_to_cs | /cs013/lab.py | 1,389 | 4.21875 | 4 | import random
import helpers
#
# Each of the following functions have an arbitrary return value. Your
# job is to edit the functions to return the correct value. You'll
# know it's correct because when you run test.py, the program will
# print "PASS" followed by the function name.
#
# Any code you add outside of these functions (in the global
# namespace) should be commented out before running test.py
#
def exponentiate(base, power):
"""Recursively obtain the result of an exponentiation operation."""
if power > 0:
return base * exponentiate(base, power - 1)
else:
return 1
def get_nth(list_of, n):
"""Get nth element of a list without slicing."""
if n:
# Why does this need a return statement?
return get_nth(helpers.tail(list_of), n - 1)
else:
return helpers.head(list_of)
def reverse(list_of):
if len(list_of) == 2:
return helpers.tail(list_of) + [helpers.head(list_of)]
else:
return reverse(helpers.tail(list_of)) + [helpers.head(list_of)]
def is_older(date_1, date_2):
if len(date_1):
if helpers.head(date_1) < helpers.head(date_2):
return True
else:
return is_older(helpers.tail(date_1), helpers.tail(date_2))
else:
return False
def number_before_reaching_sum(total, numbers):
pass
def what_month(day):
return 0
| true |
05f02174029e72f410f52517576d655cd297e8ab | chin269/proyectos-ie | /cli/cli_simple.py | 1,572 | 4.4375 | 4 | """
Argumentos de linea de comandos
Modulo recibe argumentos de linea de comandos
Módulo sys proporciona funciones y variables que se usan
para manipular diferntes partes de Runtime de python y
acceso a ciertas partes del interprete.
"""
import sys
class Calc:
"""Provee metodos para operaciones basicas"""
def sumar(self, a, b):
return int(a) + int(b)
def restar(self, a, b):
return int(a) - int(b)
def multiplicar(self, a, b):
return int(a) * int(b)
def dividir(self, a, b):
return int(a) / int(b)
print('Parametros recibidos -------------------------')
# sys.argv[0] siempre devuelve el nombre del script
print(f'nombre de este modulo sys.argv[0] = {sys.argv[0]}')
print('Todos los argumentos recibidos:', sys.argv[1:])
calculadora = Calc()
argumentos = sys.argv[1:]
if sys.argv[1] == 'sumar':
resultado = calculadora.sumar(sys.argv[2], sys.argv[3])
print(resultado)
elif sys.argv[1] == 'restar':
resultado = calculadora.restar(sys.argv[2], sys.argv[3])
print(resultado)
elif sys.argv[1] == 'multiplicar':
resultado = calculadora.multiplicar(sys.argv[2], sys.argv[3])
print(resultado)
elif sys.argv[1] == 'dividir':
resultado = calculadora.dividir(sys.argv[2], sys.argv[3])
print(resultado)
elif sys.argv[1] == '-h' or sys.argv[1] == '--help':
print("""
Programa de línea de comandos. Operaciones basicas.
Parámetros
#####################
sumar: a + b
restar: a - b
multiplicar: a * b
dividir: a / b
#####################
""") | false |
ecddeb829aa78cd91843859c3e72093580f00279 | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Count_occurrences.py | 485 | 4.28125 | 4 | """ Program to count number of occurrences of each element in a list.
Asked in Precisely interview for Software Engineer-I """
def count_occurrences(ourlist):
# return dict((i, ourlist.count(i)) for i in ourlist) # List comprehension approach
dicx = {}
for j in ourlist:
dicx.__setitem__(j, ourlist.count(j))
return dicx
if __name__ == '__main__':
ourlist = [5, 3, 9, 3, 1, 6, 6, 6, 1, 2, 2, 6, 9, 2]
print(count_occurrences(ourlist))
| true |
1838b979bbf1c1b6ee4f1e872367325f2e3ea6da | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Bubble_sort.py | 516 | 4.3125 | 4 | """ Bubble sort. Time complexity-
Worst case = O(n^2) , when the array is in descending order.
Average case = O(n^2) , when the array is jumbled.
Best case = O(n) , when the array is already sorted. """
def bubblesort(list):
for i in range(len(list)):
for j in range(len(list) - i - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
if __name__ == '__main__':
list = [31, 9, 5, 10, 6, 12, 8, 1]
bubblesort(list)
print(list)
| true |
aba880ab4100a7c30c4b9fe8dbc5fd52da08a225 | vkhalaim/pythonLearning | /tceh/lection2/list_task_2.py | 359 | 4.15625 | 4 | objectList = ["Pokemon", "Digimon", "Dragon", "Cat", "Dog"]
# first method
for i in objectList:
print("Element of list -> " + i + "[" + str(objectList.index(i)) + "]"
+ "(in square braces index of element)")
# enumarate
print("-------------------")
for index, element in enumerate(objectList):
print(str(element + "[" + str(index) + "]"))
| true |
94a22ec4cf15613bf3ccce939d29bf6ba89f4a51 | J-Gottschalk-NZ/Random_String_generator | /main.py | 721 | 4.21875 | 4 | import string
import random
# Function to check string length is an integer that is > 0
def intcheck(question):
error = "Please enter an integer that is more than 0 \n"
valid = False
while not valid:
try:
response = int(input(question))
if response < 1:
print(error)
else:
return response
except ValueError:
print(error)
# Create string including letters, digits and symbols
random_characters = string.ascii_letters + string.digits + string.punctuation
how_many = intcheck("How many characters? ")
random_string = ""
for item in range(0,how_many):
random_char = random.choice(random_characters)
random_string += random_char
print(random_string) | true |
07c883f8fc0c761e210688b095c5c0e0d5cd82c8 | MMGroesbeck/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 2,097 | 4.1875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
i = 0
a = 0
b = 0
while i < elements:
if a >= len(arrA):
merged_arr[i] = arrB[b]
b += 1
elif b >= len(arrB):
merged_arr[i] = arrA[a]
a += 1
else:
if arrA[a] < arrB[b]:
merged_arr[i] = arrA[a]
a += 1
else:
merged_arr[i] = arrB[b]
b += 1
i += 1
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
import math
def merge_sort(arr):
# Your code here
if len(arr) < 2:
return arr
else:
mid = math.floor(len(arr) / 2)
return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
arr_end = len(arr)
a = start
b = mid
while a < mid or b < end:
if a < mid:
if b < end:
if arr[a] < arr[b]:
arr.append(arr[a])
a += 1
else:
arr.append(arr[b])
b += 1
else:
arr.append(arr[a])
a += 1
else:
arr.append(arr[b])
b += 1
for i in range(end - start):
arr[start + i] = arr[arr_end + i]
del arr[arr_end:]
def merge_sort_in_place(arr, l, r):
# Your code here
if arr == []:
return
if l >= r:
return
else:
mid = math.floor((l+r)/2)
if l < r-1:
merge_sort_in_place(arr, l, mid)
merge_sort_in_place(arr, mid, r)
merge_in_place(arr, l, mid, r + 1) | true |
c0fdd5f8b40a8bce1db3e6808c3a9341789b6292 | mazoko/python | /14_もっとオブジェクト指向/test14-1.py | 1,222 | 4.1875 | 4 | # 図形クラス
class Shape:
def __init__(self):
pass
def what_am_i(self):
print("I am a shape!!")
# 正方形クラス(図形クラスを継承)
class Square(Shape):
# 作成済み正方形リスト
square_list = []
def __init__(self, s):
self.side = s
# リストにインスタンスを追加
self.square_list.append(self)
# 外周計算メソッド
def calculate_perimeter(self):
return self.side * 4
# 値変更メソッド
def change_side(self, s):
self.side = self.side + s
#
def __repr__(self):
return "{0} by {0} by {0} by {0}".format(self.side)
# 正方形のインスタンス生成
square1 = Square(2)
square2 = Square(3)
square3 = Square(4)
print(Square.square_list)
# 渡されたふたつのパラメータが同じものだったらTrue、そうでなければFalseを返す関数
def equals(obj1, obj2):
if obj1 is obj2:
return True
else:
return False
square11 = square1
square21 = Square(3)
print(equals(square1, square11)) # コピーなのでTrue
print(equals(square2, square21)) # 同じ値を渡した別のオブジェクトなのでFalse | false |
a6079ca9dd18ad71ea9a3aee7159e14985c90d63 | serereg/homework-repository | /homeworks/homework7/hw2.py | 2,154 | 4.3125 | 4 | """
Given two strings. Return if they are equal when both are typed into
empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Examples:
Input: s = "ab#c", t = "ad#c"
Output: True
# Both s and t become "ac".
Input: s = "a##c", t = "#a#c"
Output: True
Explanation: Both s and t become "c".
Input: a = "a#c", t = "b"
Output: False
Explanation: s becomes "c" while t becomes "b".
"""
from itertools import zip_longest
from typing import Generator
def get_char_in_reserved_string(string: str) -> Generator[str, None, None]:
"""Generate sequence of chars from the given string.
Sequence of chars return in a backward order.
The '#' symbol means 'backspace'.
Example:
'asdfff##gh' -> 'h', 'g', 'f', 'd', 's', 'a'.
Args:
string: string, from which generates sequence
of symbols.
Returns:
str: symbol from string without 'backspaces'.
"""
string_reversed = reversed(string)
counter_deletes = 0
for s in string_reversed:
if s == "#":
counter_deletes += 1
continue
if counter_deletes > 0:
counter_deletes -= 1
continue
yield s
def backspace_compare(first: str, second: str) -> bool:
"""Compare two strings, with # as backspace symbol.
Args:
first: string for a comparison.
second: string for a comparison.
Returns:
bool: True, if strings are equal, False otherwise.
Examples:
if first is "ab#c" and second is "ad#c", then
output is True.
Both first and second become "ac".
If first is "a##c" and second is "#a#c", then
output is True.
Both become "c".
If first is "a#c" and second is "b", then
output is False.
First becomes "c" while second becomes "b".
"""
first_and_second = zip_longest(
get_char_in_reserved_string(first), get_char_in_reserved_string(second)
)
for f, s in first_and_second:
if f != s:
return False
return True
| true |
e10d7fa1b2457d129396d35cc6885d03f4dee095 | serereg/homework-repository | /homeworks/homework4/task_1_read_file.py | 1,784 | 4.1875 | 4 | """
Write a function that gets file path as an argument.
Read the first line of the file.
If first line is a number return true if number in an interval [1, 3)*
and false otherwise.
In case of any error, a ValueError should be thrown.
Write a test for that function using pytest library.
You should create files required for the testing inside the test run
and remove them after the test run.
(Opposite to previous homeworks when you reused files created manually
before the test.)
Definition of done:
- function is created
- function is properly formatted
- function has positive and negative tests
- tests do a cleanup and remove remove files generated by tests
You will learn:
- how to test Exceptional cases
- how to clean up after tests
- how to check if file exists**
- how to handle*** and raise**** exceptions in test. Use sample from
the documentation.
* https://en.wikipedia.org/wiki/Interval_(mathematics)#Terminology
** https://docs.python.org/3/library/os.path.html
*** https://docs.python.org/3/tutorial/errors.html#handling-exceptions
**** https://docs.python.org/3/tutorial/errors.html#raising-exceptions
"""
def read_magic_number(path: str) -> bool:
"""
Reads the first line of the file (path).
If first line is a number return true if number in an interval
[1, 3)*
and false otherwise.
In case of any error, a ValueError should be thrown.
"""
try:
with open(path) as fi:
line = fi.readline()
return 1.0 <= float(line) < 3.0
except FileNotFoundError:
raise ValueError("File not found")
except OSError:
raise ValueError(f"Error in opening {path}")
except ValueError:
raise ValueError(f"Exception in converting {line}")
# finally:
# return False
| true |
c91cea964cc5f6b8931497a93c6ac1b37cf8ca62 | serereg/homework-repository | /homeworks/homework2/hw5.py | 1,611 | 4.15625 | 4 | """
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
import string
assert = custom_range(string.ascii_lowercase, 'g') ==
['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(string.ascii_lowercase, 'g', 'p') ==
['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) ==
['p', 'n', 'l', 'j', 'h']
"""
def custom_range(iter, *args):
"""function that accept any iterable of unique values and then
it behaves as range function
Args:
iter (iterable, start_elemeng):
iter (iterable, start_elemeng, stop_element):
iter (iterable, start_elemeng, stop_element, step):
Example:
assert = custom_range(string.ascii_lowercase, 'g') ==
['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(string.ascii_lowercase, 'g', 'p') ==
['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) ==
['p', 'n', 'l', 'j', 'h']
"""
if len(args) == 1:
start_element, stop_element, step = None, args[0], None
if len(args) == 2:
start_element, stop_element, step = args[0], args[1], None
if len(args) == 3:
start_element, stop_element, step = args
begin = 0
if start_element:
begin = iter.index(start_element)
end = iter.index(stop_element)
return [element for element in iter[begin:end:step]]
| true |
c312bb50572e8260c13796c143961aa68d2cb8f8 | serereg/homework-repository | /homeworks/homework2/hw3.py | 752 | 4.125 | 4 | """
Write a function that takes K lists as arguments and
returns all possible
lists of K items where the first element is from the first list,
the second is from the second and so one.
You may assume that that every list contain at least
one element
Example:
assert combinations([1, 2], [3, 4]) == [
[1, 3],
[1, 4],
[2, 3],
[2, 4],
]
"""
import itertools
from typing import List, Any
def combinations(*args: List[Any]) -> List[List]:
"""
Returns all combinations of given lists in a list
"""
return [list(item) for item in itertools.product(*args)]
if __name__ == "__main__":
all_combinations = combinations([1, 2], [4, 3])
for i in all_combinations:
print(i, type(i))
print(all_combinations)
| true |
764e06c119d1690a26a80ed11f51c517bf2fc6de | MohitSojitra/PythonExcersise | /Forloop.py | 402 | 4.1875 | 4 | # here i will show ypu a how we use a for loop
list1 = ["mohit" , "parth" ,"manoj " , "mamu" , "kinjal" , 34, 54, 456]
dictionary1 = {"mohit" : "moylo" , "parth" : "vando" , "manoj" : "bahubally"}
for i, j in dictionary1.items():
print(i,j)
list2 = ["mohit" , "mamu" , 45 ,54 , 23, 234, 2, 1, 3, 4, 5,6]
for item in list2:
if str(item).isnumeric() and item > 6:
print(item + " ")
| false |
d9085475d79d664153e73818e7a07fe628910a06 | DonCastillo/learning-python | /0060_sets_intro.py | 2,661 | 4.25 | 4 | farm_animals = {"sheep", "cow", "hen"} # sets are unordered, can set the order randomly every time the code is ran
print(farm_animals) # sets only contains one copy of each element
for animal in farm_animals:
print(animal)
print("=" * 40)
wild_animals = set(["lion", "tiger", "panther", "elephant", "hare"]) # converting list to set
print(wild_animals)
for animal in wild_animals:
print(animal)
farm_animals.add("horse") # adding an element
wild_animals.add("horse")
print(farm_animals)
print(wild_animals)
empty_set = set() # this is an empty set, should be specificied explicitly
empty_set_2 = {} # this is an empty dictionary not an array
empty_set.add("a")
# empty_set_2.add("a")
even = set(range(0, 40, 2))
print(even)
print(len(even))
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(squares)
print(len(squares))
# gets all the union
# adds all the elements of the two sets together
print(even.union(squares))
print(len(even.union(squares)))
print(squares.union(even))
print("-" *40)
# gets all the intersection
# add only the common elements from each set
print(even.intersection(squares))
print(even & squares)
print(squares.intersection(even))
print(squares & even)
# set operation
print("-" * 40)
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(sorted(squares))
# removes all the elements in squares from even set
print("even minus squares")
print(sorted(even.difference(squares)))
print(sorted(even - squares))
print("squares minus even")
print(sorted(squares.difference(even)))
print(sorted(squares - even))
print("=" * 40)
print(sorted(even))
print(squares)
even.difference(squares)
print(sorted(even))
print("-" * 40)
print("symmetric even minus squares")
print(sorted(even.symmetric_difference(squares)))
print("symmetric squares minus even")
print((squares.symmetric_difference(even)))
print()
print(squares)
squares.discard(4)
squares.remove(16) # throws an error if the element does not exist
squares.discard(8) # no error, does nothing if the element does not exist
print(squares)
try:
squares.remove(8)
except KeyError:
print("The item 8 is not a member of the set")
print("-" * 40)
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuple = (4, 6, 16)
squares = set(squares_tuple)
print(sorted(squares))
if squares.issubset(even):
print("squares is a subset of even")
if even.issuperset(squares):
print("even is a superset of square")
print("-" * 40)
even = frozenset(range(0, 100, 2)) # just like set but is constant, cannot add or manipulate
print(even)
even.add(3)
| true |
c67e8738b515c6f514123d1b27e57bdbee27a628 | mnovak17/wojf | /lab01/secondconverter.py | 497 | 4.125 | 4 | #secondconverter.py
#Translates seconds into hours, minutes, and seconds
#Mitch Novak
def main():
print("Welcome to my Second Converter! \n")
print("This program will properly calculate the number of \n minutes and seconds under 60 from a given number of seconds")
n = eval(input("How many seconds have you got?"))
total = n
h = n//3600
n = n%3600
m = n//60
s = n%60
print (total, " seconds is equal to ", h ," hours, ", m ," minutes, and ", s ,"seconds.")
main()
| true |
5c8c994d67629eec2aade0b86e8b4a1ad3d807ae | mnovak17/wojf | /lab02/fibonacci.py | 370 | 4.25 | 4 | #fibonacci.py
#prints the fibonacci number at a given index
#Mitch Novak
#1/7/13
def main():
print("My incredible Fibonacci number generator!")
n = eval(input("Plaese enter an integer:"))
f0 = 1
f1 = 1
for i in range(3, n+1):
temp = f0 + f1
f0 = f1
f1 = temp
print("The", n,"th number in the Fibonacci sequence is", f1)
main() | false |
4a0738f39e7d517d81903dd7a63f76b7f6b8d7a5 | RinkuAkash/Python-libraries-for-ML | /Numpy/23_scalar_multiplication.py | 426 | 4.1875 | 4 | '''
Created on 21/01/2020
@author: B Akash
'''
'''
problem statement:
Write a Python program to create an array of (3, 4) shape, multiply every element value by 3 and display the new array.
Expected Output:
Original array elements:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
New array elements:
[[ 0 3 6 9]
[12 15 18 21]
[24 27 30 33]]
'''
import numpy as np
array=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]])
print(array*3) | true |
0ac549f8f324ddc0246cc9a6227ed0ddb715ffde | sabgul/python-mini-projects | /guess_the_number/main.py | 1,110 | 4.28125 | 4 | import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = input(f'Guess a number between 1 and {x}: ')
guess = int(guess)
if guess < random_number:
print('Guess was too low. Try again.')
elif guess > random_number:
print('Guess was too high. Guess again.')
print(f'Congrats, you have guessed the right number {random_number} correctly! ')
# letting the computer guess any number we are thinking of
def computer_guess(x):
low = 1
high = x
feedback = ''
while feedback != 'c': # c -- correct
if low != high:
guess = random.randint(low, high)
else:
guess = low
feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?').lower()
if feedback == 'h':
high = guess - 1
elif feedback == 'l':
low = guess + 1
print(f'Yes, the computer guessed the number you were thinking of ({guess}) correctly.')
#guess(10)
computer_guess(10)
| true |
5f215b292c15000d73a2007e8ed8e81d32e536a5 | OmarKimo/100DaysOfPython | /Day 001/BandNameGenerator.py | 465 | 4.5 | 4 | # 1. Create a greeting for your program.
print("Welcome to My Band Name Generator. ^_^")
# 2. Ask the user for the city that they grow up in.
city = input("What's the name of the city you grow up in?\n")
# 3. Ask the user for the name of a pet.
pet = input("Enter a name of a pet.\n")
# 4. Combine the name of their city and pet and show them their band name.
print(f"Your band name could be {city} {pet}")
# 5. Make sure the input cursor shows on a new line.
| true |
ebca9d6de69c7539774b2a57852d492ab0d7295d | Nicodona/Your-First-Contribution | /Python/miniATM.py | 2,703 | 4.25 | 4 | # import date library
import datetime
currentDate = datetime.date.today()
# get name from user
name = input("enter name : ")
# create a list of existing name and password and account balance
nameDatabase = ['paul', 'peter', 'emile', 'nico']
passwordDatabase = ['paulpass', 'peterpass','emilepass', 'nicopass']
accountBalance= [ 20000, 20000, 20000, 20000] # an example of initial accountbalance of various persons
# comparing name with name in list
if(name in nameDatabase):
passoword = input('enter password: ')
# nesting if condition to check for password if valid name is used and also making sure the existing n
# ame correspond to the index of the passwordDatabse list so that existing user uses only their password to login
realPass = nameDatabase.index(name)
if passoword == passwordDatabase[realPass]:
# print the date after successful login
currentBalance = accountBalance[realPass]
print(currentDate.strftime('%d %b, %Y'))
# output the user with options to do either withdraw deposit or complain
try: #this line is used to catch errors for example if the user enters a character instead of an interger
option = int(input('enter\n 1: withdraw\n 2:deposit\n 3:complaint\n'))
# this option checks the option input and deducts the withdraw cash from accountBalance
if option == 1:
withdraw = int(input('how much will you like to withdraw'))
currentBalance = currentBalance - withdraw
accountBalance[realPass] = currentBalance
print('take your cash %d' % withdraw)
print(f'ACCOUNT BALANCE is {currentBalance}')
# this block checks the option input and add the deposit to the accountBalance
elif option == 2:
deposit = int(input('how much will you like to deposit?'))
currentBalance = currentBalance + deposit
accountBalance[realPass] = currentBalance
print('successfully deposit into accountbalance is')
print(currentBalance)
# this option ask checks the option input and produce a complaint for users having issues
elif option == 3:
complaint = input('what issue will you like to report?')
print('thank you for contacting us')
except ValueError: # this is an alternative message if an error ValueError occurs
print('error please try again, enter an interger in option')
else:
print('wrong password please try again')
else:
print('user does not exit please input a valid username')
#for index in accountBalance:
# print(index)
| true |
6614083932d6659190d7eb0dc5ba9693d2faa44e | jeremyosborne/python | /iters_lab/solution/itools.py | 816 | 4.28125 | 4 | """
Lab
---
Using the iterutils, figure out the number of permutations possible when
rolling two 6-sided dice. (Hint: Think cartesian product, not the
permutations function.)
Print the total number of permutations.
Make a simple ascii chart that displays the count of permutations for
a particular combination (i.e. sum of a permutation).
Example:
3 *
4 **
... etc...
"""
from itertools import product
from collections import Counter
rolls = Counter()
for roll in product(range(1, 7), repeat=2):
rolls[sum(roll)] += 1
print "Total permutations:", sum(rolls.values())
print "Distribution of rolls"
# Since the dataset is small, we don't normalize.
for total, numperms in rolls.items():
print "{:2}".format(total), "*" * numperms
| true |
edc84c8a30911e7bd2d8c82fbdcac975cd3a1f40 | Deathcalling/Data-Analysis | /pythonData/pythonPandas/pandasBasics1.py | 1,529 | 4.125 | 4 | import pandas as pd #Here we import all necessary modules for us to use.
import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style #This simply tells python that we want to make matplotlib look a bit nicer.
style.use('ggplot') #Here we tell python what kind of style we would like to use for matplotlib
#Now I just made a dictionary to represent a dataframe type of datastructure
web_stats = {'Day' : [1,2,3,4,5,6],
'Visitors' : [43,56,76,46,54,34],
'Bounce_Rate' : [65,23,34,45,87,65]}
stats = pd.DataFrame(web_stats) #Turned our dictionary into a dataframe
print(stats) #Head and tail display the first five and last five of a dataframe
print(stats.head(2))
print(stats.tail(2))
print(stats.set_index('Day')) #Another way to get the same result, telling python we want stats to show the index of Day.
stats2 = stats.set_index('Day')
print(stats2.head())
print(stats['Bounce_Rate']) #more ways to display data
print(stats.Visitors)
print(stats[['Bounce_Rate','Visitors']]) # One way to get two or more different columns.
print(stats.Visitors.tolist()) #Here we told python to turn this column of data into a list.
print(np.array(stats[['Bounce_Rate','Visitors']])) # Using numpy we can make a dataset into an array!
stats3 = pd.DataFrame(np.array(stats[['Bounce_Rate','Visitors']])) # And just like we can turn dataframes to arrays, we can also turn arrays to dataframes!!!
print(stats3)
stats.plot()
plt.show()
| true |
ef5ad01f85285601321ec6fa246a16e6f07b775b | siddharth456/python_scripts | /python/add_elements_to_a_list.py | 251 | 4.34375 | 4 | # add elements to an empty list
testlist=[]
x=int(input("enter number of elements to be added to the list:"))
for i in range(x):
e=input("enter element:")
testlist.insert(i,e)
print() # adds an empty line
print("Your list is",testlist)
| true |
911040a477c107f353b3faace1d688dafde3064d | siddharth456/python_scripts | /python/create_user_input_list.py | 209 | 4.375 | 4 | # We will create a list using user input
userlist = [] # this is how you initialize a list
for i in range(5):
a=input("Enter element:")
userlist.append(a)
print ("your created list is:",userlist)
| true |
b32a498930d2701520f45965a56d65fa09e533ad | SergioG84/Python | /weight_converter.py | 1,113 | 4.15625 | 4 | from tkinter import *
window = Tk()
# define function for conversion
def convert_from_kg():
grams = float(entry_value.get()) * 1000
pounds = float(entry_value.get()) * 2.20462
ounces = float(entry_value.get()) * 35.274
text1.insert(END, grams)
text2.insert(END, pounds)
text3.insert(END, ounces)
# set labels for units
# add text box for conversion answers
label = Label(window, text="Kg")
label.grid(row=0, column=0)
entry_value = StringVar()
entry = Entry(window, textvariable=entry_value)
entry.grid(row=0, column=1)
button = Button(window, text="Convert", command=convert_from_kg)
button.grid(row=0, column=2)
label = Label(window, text="Grams")
label.grid(row=1, column=0)
text1 = Text(window, height=1, width=20)
text1.grid(row=2, column=0)
label = Label(window, text="Pounds")
label.grid(row=1, column=1)
text2 = Text(window, height=1, width=20)
text2.grid(row=2, column=1)
label = Label(window, text="Ounces")
label.grid(row=1, column=2)
text3 = Text(window, height=1, width=20)
text3.grid(row=2, column=2)
window.mainloop() | true |
04b9e2a82aa79e2aaba97531d8cb36e21ccc1983 | MHSalehi/Programming | /Lecture1Repeat_Strings.py | 2,130 | 4.28125 | 4 | #Introduction, Printing Strings
print ("Hello, Python!")
spch = "Greetings!"
print (spch + " What is your name?")
#Class Task 1
print ("\n")
g = 14
t = 0.12
tg = g+g*t
print ("£ " + str(tg))
#Class Task 2
print ("\n")
fg = 20
s = 0.4
#Calculate sale price to 2 d.p.
sg = '{:.2f}'.format(fg-fg*s)
print ("£ " + str(sg))
#Practicing with .upper() and .lower() functions
print ("\n")
t = "Barry ProgrammeR"
print (t[-3].upper() + t[-2] + t[2:5] + (" ") + t[7].upper() + t[8] + t[-5:-3] + t[-2] + t[-1].lower())
#Print Character Count
print ("Number of characters in " + "'" + str(t) + "'" + " = " + str(len(t)))
#Strip Function Experimentation
print ("\n")
a = " Stripping a sentence. "
print ("No stripping:" + "'" + a + "'")
print ("After stripping white space: " + "'" + a.strip() + "'")
print ("After stripping words: " + "'" + a.strip(" Stripping" "sentence. ") + "'" )
#Testing for alphabet/digit/space-only character strings
print ("\n")
b = "Alpha"
print (b.isalpha())
c = "Alpha1"
print (c.isdigit())
d = "\n "
print (d.isspace())
#Testing for strings beginning and ending in specific strings
print ("\n")
e = "All aboard the typing train."
print (e.startswith("All"))
print (e.endswith("train."))
print (e.endswith("in", -7, -1))
print (e.endswith("in", -12, -8))
#Searching for a specific string within another string
print ("\n")
print (e.find("aboard"))
print (e.find("abort"))
#Substituting portions of a string
print ("\n")
print (e.replace("All aboard", "Expedite"))
#User inputs
name = input("what is your name? ")
age = int(input("What is your age? "))
#Conditional Checks
print("\n")
if age >= 35:
print("With age comes wisdom.")
elif age >= 25:
print("The tip of the iceberg.")
elif age >= 15:
print("So much to learn.")
else:
print("Just getting started.")
#Class Task 3
print("\n")
playernum = int(input("Choose a number: "))
if playernum <= 100:
print ("That's a small number.")
elif playernum <= 1000:
print ("That's an adequately huge number!")
#Class Task 4
n = playernum % 2
if n == 0:
print ("This an even number.")
else:
print ("This is an odd number.")
| false |
02b0d355297a05752f11a1f18b81e542b849ed01 | Zyjqlzy/PythonStudyNotes | /Algorithm/select_sort.py | 808 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
选择排序
"""
def create_list():
user_input = input("请输入数据,逗号分隔:\n").strip()
user_list = [int(n) for n in user_input.split(',')]
print(user_list)
return user_list
def find_smallest_item(lst):
smallest_item = lst[0]
smallest_index = 0
for i in range(1, len(lst)):
if smallest_item > lst[i]:
smallest_item = lst[i]
smallest_index = i
return smallest_index
def select_sort(lst):
newlst = []
for i in range(len(lst)):
smallest = find_smallest_item(lst)
newlst.append(lst.pop(smallest))
return newlst
if __name__ == "__main__":
array = create_list()
new_array = select_sort(array)
print("排序后的序列为:", new_array)
| false |
8aece43ba3fef62e3bd9b1f2cead27608995c2c4 | SHASHANKPAL301/Rock-Paper-and-Scissor-game | /game.py | 1,311 | 4.25 | 4 | import random
print(''' Welcome to the Rock,Paper and Scissor game. THe rule of the game is shown below:-
1. rock vs scissor---> rock win
2. scissor vs paper---> scissor win
3. paper vs rock---> paper win''')
def game(computer, player):
if computer == player:
return None #tie
elif computer == 'R':
if player == 'P':
return True #winner
elif player == 'S':
return False #lose
elif computer == 'P':
if player == 'S':
return True
elif player == 'R':
return False
elif computer == 'S':
if player == 'R':
return True
elif player == 'P':
return False
computer = print("Computer turn: Rock(R), Paper(P) and Scissor(S)")
randomNum = random.randint(1, 3)
# print(randomNum)
# 1-->rock
# 2-->Paper
# 3-->scissor
if randomNum == 1:
computer = 'R'
elif randomNum == 2:
computer = 'P'
elif randomNum == 3:
computer = 'S'
player = input("Player turn: Rock(R), Paper(P) and Scissor(S) ")
i=game(computer,player)
if i==None:
print("game is tie!")
elif i==True:
print("You win")
elif i==False:
print("computer Win!")
print(f"computer choose { computer}")
print(f"player choose { player}") | true |
a43a0d590b70294442e9d92916cad822be961d3e | ohlemacher/pychallenge | /3_equality/equality.py | 2,339 | 4.34375 | 4 | #!/usr/bin/env python
'''
Find lower case characters surrounded by exactly three upper case
characters on each side.
'''
import pprint
import re
import unittest
def file_to_string():
'''Read the file into a string.'''
strg = ''
with open('equality.txt', 'r') as infile:
for line in infile:
for cha in line:
if cha != '\n':
strg += cha
return strg
def find_guarded_matches(strg):
'''
Use a regex to find the guarded chars.
'''
guard_re = re.compile(r"""
(^|[^A-Z]{1}) # Beginning or 3 non-uppercase
[A-Z]{3} # Three uppercase (guard)
([a-z]{1}) # One lowercase
[A-Z]{3} # Three uppercase (guard)
($|[^A-Z]{1}) # End or 3 non-uppercase
""",
re.VERBOSE)
matches = guard_re.findall(strg)
# Since three groups are used in the regex, tuples are returned.
# We only want the middle one.
answer = ''
for tup in matches:
answer += tup[1]
return answer
def explore():
'''Find the solution. Run iteractively.'''
strg = file_to_string()
print find_guarded_matches(strg)
class EqualityTest(unittest.TestCase):
'''Unit test set.'''
def test_start_match(self):
'''Test match at start of strg.'''
strg = "AAAxBBBooCCCyDDDo"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_middle_match(self):
'''Test match in middle of strg.'''
strg = "mNoAAAxBBBooCCCyDDDmNo"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_end_match(self):
'''Test match at end of strg.'''
strg = "ooAAAxBBBooCCCyDDD"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_no_match(self):
'''Test no matches in strg.'''
strg = "ooAaAxBBBooCCCyDdD"
answer = ''
result = find_guarded_matches(strg)
self.failUnless(result==answer)
if __name__ == '__main__':
# A real app would use argparse to optionally exec the unit tests.
unittest.main()
| true |
ee05faf9992dcd4041a0cacc10844f0e8f7ba000 | fhossain75/CS103-UAB | /lab/lab08/lab08_19fa103.py | 2,296 | 4.40625 | 4 | # 19fa103; john k johnstone; jkj at uab dot edu; mit license
# lab08 on recursion
# ------------------------------------------------------------------------------
def sum (n):
"""Compute the sum of the first n positive integers, recursively.
>>> sum (10)
55
Params: n (int) n >= 1
Returns: (int) sum from 1 to n (1 + 2 + ... + n)
"""
assert n >= 1
if n == 1:
return 1
else:
return n + sum(n-1)
print(sum(10))
print(sum(5))
# ------------------------------------------------------------------------------
def reverse1 (s):
"""Reverse a string, recursively.
>>> reverse ('garden')
nedrag
Params: s (str)
Returns: (str) reversal of s
"""
assert len(s) >= 1
if len(s) == 1:
return s
else:
return reverse1(s[1:]) + s[0]
print(reverse1("garden"))
# ------------------------------------------------------------------------------
# use another way to implement it recursively
def reverse2 (s):
"""Reverse a string, recursively.
>>> reverse ('garden')
nedrag
Params: s (str)
Returns: (str) reversal of s
"""
return
# ------------------------------------------------------------------------------
def sumMtoN (M, N):
"""Recursive sum from M to N.
Params:
M (int):
N (int): M <= N
Returns: M + ... + N
"""
assert M <= N
if N == M:
return M
else:
return N + sumMtoN(M, N-1)
print(sumMtoN(0, 3))
print(sumMtoN(2, 3))
print(sumMtoN(0, 10))
# ------------------------------------------------------------------------------
def lint (L):
"""Is L a list of integers? Solved recursively.
>>> lint ([0, 2, 3.1, 'joe'])
False
>>> lint ([123, 234, 345])
True
Params: L (list)
Returns: is every element of L an integer?
"""
return
# ------------------------------------------------------------------------------
def argmax (L):
"""Index of the max element of a nontrivial list of integers, recursively.
>>> argmax ([42,-3,101,100])
2
Params: L (int list) a nontrivial list of integers (len(L) > 0)
Returns: (int) index of the largest element (first if many ties);
use a nonnegative index
"""
return
| false |
3fbe28eaf7e972df0dc5c38e6adcc6857769fccd | fhossain75/CS103-UAB | /lab/lab07/reverse_stubbed.py | 441 | 4.375 | 4 | # 19fa103; john k johnstone; jkj at uab dot edu; mit license
# reverse1 iterates over the element;
# this is the one to remember, since it is the most natural and clear;
# so this is the one to practice
def reverse1 (s):
"""Reverse a string, iteratively using a for loop (by element).
>>> reverse1 ('garden')
nedrag
Params: s (str)
Returns: (str) reversal of s
"""
return
s = 'garden'
print (reverse1 (s))
| true |
d347240883041f719822fcbf4fed052a3741829d | ParrishJ/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 2,239 | 4.1875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
#test_arr = [1, 5, 3, 2]
#test_arr_b = [5, 6]
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
count = 0
while arrA or arrB:
if len(arrA) != 0 and len(arrB) == 0:
merged_arr[count] = arrA[0]
arrA.pop(0)
count += 1
elif len(arrB) != 0 and len(arrA) == 0:
merged_arr[count] = arrB[0]
arrB.pop(0)
count += 1
elif arrA[0] < arrB[0]:
merged_arr[count] = arrA[0]
arrA.pop(0)
count += 1
elif arrB[0] < arrA[0]:
merged_arr[count] = arrB[0]
arrB.pop(0)
count += 1
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
def merge_sort(arr):
#base case
if len(arr) <= 1:
return arr
#if len(arr) > 1:
first = 0
last = int(len(arr) - 1)
middle_index = (first + last) // 2
left = arr[:middle_index + 1]
right = arr[middle_index + 1:]
#sorted_arr = merge(left, right)
return merge(merge_sort(left), merge_sort(right))
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
count = 0
while arrA or arrB:
if len(arrA) != 0 and len(arrB) == 0:
merged_arr[count] = arrA[0]
arrA.pop(0)
count += 1
elif len(arrB) != 0 and len(arrA) == 0:
merged_arr[count] = arrB[0]
arrB.pop(0)
count += 1
elif arrA[0] < arrB[0]:
merged_arr[count] = arrA[0]
arrA.pop(0)
count += 1
elif arrB[0] < arrA[0]:
merged_arr[count] = arrB[0]
arrB.pop(0)
count += 1
return merged_arr
def merge_sort_in_place(arr, l, r):
# Your code here
pass
| false |
8393ddf1ce183849578b732960aab84cd2f36d86 | A-FLY/pyton8 | /反恐精英.py | 2,229 | 4.15625 | 4 | """
演示反恐精英案例
对一个匪徒
分析:
1.定义人类,描述公共属性 life:100 name:姓名要传参
2.定义出英雄与恐怖分子类
3.定义主函数描述枪战过程 main,创建两个对象
4.定义开枪方法,分成两个方法,Hero Is都有
定义的方法要传入被射击的对象
被射击对象的生命值要进行减少
5.主程序中调用开枪操作
6.开枪操作后,要在主程序中显示每个人的状态信息
7.定义Person类的__str__方法,用于显示每个人的状态
8.设置开枪操作为反复操作
再设置停止条件:一方生命值<=0
停止循环使用break
-----------------------修复版-----------------------
9.修复英雄的信息显示模式
状态描述 0 - 1- 70 - 99- 100
if..elif.. and组合条件
10.修复生命值为负的问题
射击时如果生命值<伤害值,生命值 = 0,否则正常减生命
"""
class Human:
def __init__(self, name):
self.name = name
self.life = 100
def fire(self, o, x):
if self.life - x >= 0:
print("%s 向 %s 射击,造成伤害值 %d" % (self.name, o.name, x))
o.life -= x
else:
print("%s 向 %s 射击,打死了%s" % (self.name, o.name, o.name))
def __str__(self):
return "%s 生命值为 %d" % (self.name, self.life)
class Police(Human):
def __str__(self):
if self.life == 100:
print("%s无伤" % self.name)
elif 70 < self.life < 100:
print("%s轻伤" % self.name)
elif 1 <= self.life <= 70:
print("%s重伤" % self.name)
elif self.life < 1:
print("%s挂了" % self.name)
class Bandit(Human):
pass
def main_i():
p = Police("成龙")
ban = Bandit("001匪")
while True:
if p.life > 0:
p.fire(ban, 40)
if ban.life > 0:
ban.fire(p, 10)
ban.__str__()
p.__str__()
print("------------")
if ban.life <= 0:
print("%s 被 %s 打死了" % (ban.name, p.name))
break
if p.life <= 0:
print("%s 被 %s 打死了" % (p.name, ban.name))
break
main_i()
| false |
c18382f6f82bd6d98f293d08ac885a5d78fad773 | sqhl/review | /坑向/range的加深理解.py | 264 | 4.15625 | 4 | x = 4
# for i in range(x):
# print(i, x)
# x = 2
# print(x)
# print("------------")
for i in range(x):
for j in range(x):
print(j, x)
x = 2
# range(2) 返回一个对象 当每次range完了之后 会重新创建对象
| false |
4c278680c7c2edd60a3435a9aa424a0a1ac1de6d | diksha16017/fcs_assignment1 | /assignment/CipherToPlain.py | 1,523 | 4.28125 | 4 |
cipher1 = "slnpzshabylzohssthrluvshdylzwljapunhulzahispzotluavmylspnpvuvywyvopipapunaolmylllelyjpzlaolylvmvyh"
cipher2 = "iypknpunaolmyllkvtvmzwlljovyvmaolwylzzvyaolypnoavmaolwlvwslwlhjlhisfavhzzltislhukavwlapapvuaolnvcl"
cipher3 = "yutluamvyhylkylzzvmnyplchujlz"
alphabets_frequency = dict()
def find_frequency(text1,text2,text3):
global alphabets_frequency
for alphabet in text1:
# print alphabet
if alphabet not in alphabets_frequency:
alphabets_frequency[alphabet] = 1
else:
alphabets_frequency[alphabet] += 1
for alphabet in text2:
# print alphabet
if alphabet not in alphabets_frequency:
alphabets_frequency[alphabet] = 1
else:
alphabets_frequency[alphabet] += 1
for alphabet in text3:
# print alphabet
if alphabet not in alphabets_frequency:
alphabets_frequency[alphabet] = 1
else:
alphabets_frequency[alphabet] += 1
#for key in alphabets_frequency:
#print key,alphabets_frequency[key]
# after seeing the frequencies one can easily figure out the less possibility of using transposition technique.
def substitution_cipher_direct(text1,text2,text3):
cipher = text1+text2+text3
cipher_new = ""
for i in range(27):
print "*** "+ str(i)+" ***"
for j in range(len(cipher)):
val = (ord(cipher[j])+i)
if val>122:
val = (val%122)+96
cipher_new += str(chr(val))
print cipher_new
print "\n"
cipher_new = ""
# 19th iteration is giving some meaningful text
find_frequency(cipher1,cipher2,cipher3)
substitution_cipher_direct(cipher1,cipher2,cipher3) | false |
8385b7cca4d9d2e2a7d25209233d5462ab8af24c | ErenBtrk/Python-Exercises | /Exercise21.py | 723 | 4.15625 | 4 | '''
Take the code from the How To Decode A Website exercise
(if you didn’t do it or just want to play with some different code, use the code from the solution),
and instead of printing the results to a screen, write the results to a txt file. In your code,
just make up a name for the file you are saving to.
Extras:
Ask the user to specify the name of the output file that will be saved.
'''
import random
fileName = input("Please enter the file name : ")
number_list = [random.randrange(1, 100, 1) for i in range(10)]
number_list_str = [ str(item) for item in number_list]
print(number_list_str)
with open(fileName,"w") as file:
for item in number_list_str:
file.write(item+' ')
file.close()
| true |
f99df6b2eabb591210ef8a18b648deaf198a9ef8 | ErenBtrk/Python-Exercises | /Exercise5.py | 1,280 | 4.25 | 4 | '''
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists
(without duplicates). Make sure your program works on two lists of different sizes.
Extras:
1-Randomly generate two lists to test this
2-Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
'''
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
new_list = []
for item in a:
if(not item in new_list):
new_list.append(item)
for item in b:
if(not item in new_list):
new_list.append(item)
new_list.sort()
print(new_list)
################################################################
import random
randomList = range(30)
list1 = random.sample(randomList,random.randint(5,20))
list2 = random.sample(randomList,random.randint(5,20))
print(list1)
print(list2)
new_list2 = []
for item in list1:
if(not item in new_list2):
new_list2.append(item)
for item in list2:
if(not item in new_list2):
new_list2.append(item)
new_list2.sort()
print(new_list2)
| true |
8b53226541e87eaee9b5ad490c425a35d84e3ab6 | Dinesh-Sivanandam/LeetCode | /53-maximum-subarray.py | 1,083 | 4.25 | 4 | #Program to find the maximum sum of the array
def maxSubArray(A):
"""
:type nums: List[int]
:rtype: int
"""
#length of the variable is stored in len_A
len_A = len(A)
#if the length of the variable is 1 then returning the same value
if 1 == len_A:
return A[0]
"""
Else we are taking the element one by one and adding the elements
if the value is less then zeor we are storing sum = 0
else if sum > max we are placing max value is equal to sum
else leaving the sum value and continue the process
after the process returning the max value
"""
max = None
sum = 0
for n in range(0, len_A):
sum += A[n]
if None == max or sum > max:
max = sum
if sum < 0:
sum = 0
continue
return max
#Starting the main
if __name__ == "__main__":
#declaring the values
nums = [-2,1,-3,4,-1,2,1,-5,4]
#storing the result in the variable
result = maxSubArray(nums)
#printing the result
print(result)
| true |
71929d852440e9767bed7adf6cb2d1deb9ed93b3 | ul-masters2020/CS6502-BigData | /lab_week2/intersection_v1.py | 349 | 4.1875 | 4 | def intersection_v1(L1, L2):
'''This function finds the intersection between
L1 and L2 list using in-built methods '''
s1 = set(L1)
s2 = set(L2)
result = list(s1 & s2)
return result
if __name__ == "__main__":
L1 = [1,3,6,78,35,55]
L2 = [12,24,35,24,88,120,155]
result = intersection_v1(L1, L2)
print(f"Intersection elements: {result}")
| true |
e22b8b0118602f46eeb6d10ece21836a7878a806 | Olishevko/home_work2 | /day_of_week.py | 427 | 4.25 | 4 |
day_of_week = int(input('enter the serial number of the day of the week: '))
if day_of_week == 1:
print('monday')
elif day_of_week == 2:
print('tuesday')
elif day_of_week == 3:
print('wednesday')
elif day_of_week == 4:
print('thursday')
elif day_of_week == 5:
print('friday')
elif day_of_week == 6:
print('saturday')
elif day_of_week == 7:
print(sunday)
else:
print('there is no such day of the week') | false |
8b2ec04aef80d96e472eaf2592d180f41c0b06a2 | ABDULMOHSEEN-AlAli/Guess-The-Number | /Guess-The-Number.py | 2,895 | 4.25 | 4 | from random import randint # imports the random integer function from the random module
computer_guess = randint(1, 50) # stores the unknown number in a variable
chances = 5 # sets the chances available to the user to 5
def mainMenu(): # defines the main menu function, which will be prompted to the user every now and then
global chances
print('-' * 55)
print("Guess the number from 1 up to 50, You have %d chances..." % chances)
print('OR enter 404 to give up and show the answer...')
print('-' * 55)
user_value = int(input()) # stores the user's value
return user_value
def hotCold(num,unknown): # defines the hot or cold function that will assist the user in guessing the number
if num > unknown:
if (num - 5) < unknown:
result = 'Hotter'
elif (num - 10) < unknown:
result = 'bit hotter'
else:
result = 'Colder'
elif num < unknown:
if (num + 5) > unknown:
result = 'Hotter'
elif (num + 10) > unknown:
result = 'bit hotter'
else:
result = 'Colder'
else:
result = 'Colder'
return result
choice = mainMenu() # stores the choice made by the user from the main menu function into a variable
# Computation Section
while computer_guess != choice and choice != 404: # this while loop will be executed till the specified condition
# validates the range
if choice > 50 or choice < 1:
print('Be careful mate... Your guess is out of range')
choice = mainMenu()
else:
# deducts the counter with each valid guess
chances -= 1
# if there are no more chances available, the loop gets interrupted and the code proceeds to the next lines
if chances == 0:
break
tip = hotCold(choice, computer_guess) ## stores the result of the hot or cold function in a variable
print('Try again... \"Hint: You are getting %s \"' % tip) ### prints the result of it
choice = mainMenu() # prompts the user for another guess
# Check for the result based on the above computations
if computer_guess == choice and chances == 5: # If the user wins from the first time
print("\nYOU WIN")
print('You guessed the number successfully!!!')
print("CASINO")
elif computer_guess == choice:
print("\nYOU WIN")
print('You guessed the number successfully!!!')
elif choice == 404: # if the user gives up and wants to see the unknown number
print('Sorry mate...')
print('The unknown number was %d' % computer_guess)
print('Thanks for your time')
else: # if the user failed to guess the number
print("YOU LOSE GG MAN")
print('The unknown number was %d' % computer_guess)
print("\nThanks for your time, and I hope you have fun")
# developer's message to the user
print("Feel free to contact me if you face any issues.") | true |
7906bb35b5f7c0c0acb8730ff7ccc6423fdd1623 | LesroyW/General-Work | /Python-Work/Loops.py | 470 | 4.4375 | 4 | #Looping over a set of numbers
# For number in numbers:
# print(number) examples of for loop
# For loops can also loop of a range
#e.g for x in range(5):
# print(x)
#While loops can also be used within it
#Break and continue statements can be used to skip the current block or return to the for/whil statement
# else clause can be used at the end after a while/for loop but won't be executed if a break function is reached in the loop but will if continue is used. | true |
9b3267d9488f10a980a2935d77bf906c4468f281 | adityagith/pythonprograms | /prime number.py | 278 | 4.15625 | 4 | a = int(input("Enter a number to check its prime or not\n"))
if(a<=0):
print("No")
elif(a==2):
print("Yes")
elif(a>2):
for i in range(2,a):
if(a%i==0):
print("Not a prime")
break
else:
print("Prime")
| true |
3fe6eb252a60edfa06b9c96e8bdc4728bb0537a7 | zhenningtan/DataStructure_Algorithms | /mergesort_inversion.py | 1,462 | 4.15625 | 4 | ############################################################
# Count inversion
# merge sort function
def merge_inversion(arr1, arr2, inversion):
n1 = len(arr1)
n2 = len(arr2)
n = n1 + n2
marray = [0] * n
k = 0
i = 0
j = 0
#compare arr1 and arr2 and add the smaller number to the sorted array
while i < n1 and j < n2:
if arr1[i] <= arr2[j]:
marray[k] = arr1[i]
i +=1
else:
marray[k] = arr2[j]
j +=1
inversion += (n1-i)
k +=1
# add the remaining elements of arr1 or arr2 to the sorted array if any
while i < n1:
marray[k] = arr1[i]
i+=1
k+=1
while j < n2:
marray[k] = arr2[j]
j+=1
k+=1
#print marray, inversion
return marray, inversion
def mergeSort_inversion(arr, inversion = 0):
n = len(arr)
if n <=1:
return arr, inversion
else:
left, inversion = mergeSort_inversion(arr[0:n/2], inversion)
right, inversion = mergeSort_inversion(arr[n/2:n], inversion)
#print merge_inversion(left, right, inversion)
return merge_inversion(left, right, inversion)
'''
#test case
output = mergeSort_inversion(c,0)
print output[1]
'''
array = []
with open("IntegerArray.txt", "r") as f:
for line in f:
array.append(int(line.strip()))
output =mergeSort_inversion(array)
print output[1]
print "length of array:", len(array)
| false |
379a96400b033254a0ddd01c9a477882d16adfd0 | odecay/CS112-Spring2012 | /hw04/sect1_if.py | 992 | 4.25 | 4 | #!/usr/bin/env python
from hwtools import *
print "Section 1: If Statements"
print "-----------------------------"
# 1. Is n even or odd?
n = raw_input("Enter a number: ")
n = int(n)
x = n % 2
if x == 0:
print "1.", n, "is even"
else:
print "1.", n, "is odd"
# 2. If n is odd, double it
if x > 0:
dub = 2 * n
print "2.", n,"doubled is", dub
else:
print "2.", n,"is even, so no function was performed"
# 3. If n is evenly divisible by 3, add four
toAdd = n % 3
if toAdd == 0:
toAdd = n + 4
print "3.", n, "is devisible by three.", n,"+ 4 =", toAdd
else:
print "3.", n,"is not divisible by three"
# 4. What is grade's letter value (eg. 90-100)
grade = raw_input("Enter a grade [0-100]: ")
grade = int(grade)
if grade > 89:
print "4.", grade, "is an A"
elif grade > 79:
print "4.", grade, "is a B"
elif grade > 69:
print "4.", grade, "is a C"
elif grade > 64:
print "4.", grade, "is a D"
else:
print "4.", grade, "is a F"
| false |
2584097aff364d6aeb60030eda2117628cbceda9 | siva4646/DataStructure_and_algorithms | /python/string/longest_word_indictioary_through_deleting.py | 986 | 4.15625 | 4 | """
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
"""
class Solution:
def findLongestWord(self, s: str, d: list[str]) :
print (s,d)
def check(s,s1):
i=0
j=0
while(i<len(s) and j<len(s1)):
if s[i]==s1[j]:
i=i+1
j=j+1
continue
i=i+1
return j==len(s1)
res=""
for word in d:
if check(s,word) and (len(res)<len(word) or (len(res)==len(word) and res>word)):
res=word
return res
findLongestWord(self,"abpcplea",["ale","apple","monkey","plea"])
| true |
9b90a92ae8019fb0f7b7ea91381269abc8df48dc | brahmaniraj/Python_BM | /Datatypes/Strings/capitalize.py | 428 | 4.6875 | 5 | #!/usr/bin/python
# 1. capitalize() Method :
# Note: string with only its first character capitalized.
a01 = "welcome to python world"
a02 = "python world"
a03 = "to python world"
print ("a01.capitalize() : ", a01.capitalize(),id(a01),type(a01),len(a01))
print("")
print ("a02.capitalize() : ", a02.capitalize(),id(a02),type(a02),len(a02))
print("")
print ("a03.capitalize() : ", a03.capitalize(),id(a03),type(a03),len(a03)) | false |
2e274a24f93f81017686ad4c5ceabfaece95d419 | sebasbeleno/ST0245-001 | /laboratorios/lab02/codigo/laboratorio2.py | 1,610 | 4.15625 | 4 | import random
import sys
import time
sys.setrecursionlimit(1000000)
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
"""
Mohit Kumra (2020) Insertion Sort. [Source code] https://www.geeksforgeeks.org/python-program-for-insertion-sort/.
"""
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
"""
Mayank Khanna(2021) Merge Sort. [Source code] https://www.geeksforgeeks.org/merge-sort/.
""" | true |
38bd89e50954a7421eee5662d019fc303fa1b172 | nerincon/Python-Exercises | /week2/Thurs/phonebook_app/phonebook_json.py | 2,283 | 4.15625 | 4 | import json
while True:
print("Electronic Phone Book")
print("=====================")
print("1. Look up an entry")
print("2. Set an entry")
print("3. Delete an entry")
print("4. List all entries")
print("5. Save entries")
print("6. Restore saved entries")
print("7. Quit")
phonebook = {}
def app():
lookup()
quest = int(input("What do you want to do (1-7)? "))
if 0 < quest < 8:
if quest == 1:
specific_lookup()
elif quest == 2:
set_entry()
save_entry()
elif quest == 3:
delete_entry()
elif quest == 4:
lookup()
for k, v in phonebook.items():
print ('Name: {} Phone Number: {}'.format(k, v.get("Phone Number")))
elif quest == 5:
save_entry()
elif quest == 6:
lookup()
else:
print("Until Next Time!")
quit()
else:
print("Please pick a number from 1-7")
def lookup():
global phonebook
with open('phone_list.json', 'r') as f:
phonebook = json.load(f)
def specific_lookup():
person = input("Person Name: ")
lookup()
if person in phonebook:
for n in range(1):
print("Phone Number: " + phonebook[person]["Phone Number"])
else:
print("Person not in phonebook")
def set_entry():
name = input("Person's Name: ")
phone = input("Person's Phone: ")
phonebook[name] = {}
phonebook[name]["Phone Number"] = phone
print("An Entry has been created for {}".format(name))
def save_entry():
with open('phone_list.json', 'w') as f:
json.dump(phonebook, f, indent=4)
def delete_entry():
person = input("Person Name: ")
lookup()
if person not in phonebook:
print("{} not in phonebook!".format(person))
else:
del phonebook[person]
save_entry()
print("Deleted: {}".format(person))
app()
| false |
afd31e371feaed5fdf84e4372460b931416b3284 | karankrw/LeetCode-Challenge-June-20 | /Week 3/Dungeon_Game.py | 1,918 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 01:25:32 2020
@author: karanwaghela
"""
"""
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon.
The dungeon consists of M x N rooms laid out in a 2D grid.
Our valiant knight (K) was initially positioned in the top-left room and
must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer.
If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons,
so the knight loses health (negative integers) upon entering these rooms;
other rooms are either empty (0's) or contain magic orbs that increase
the knight's health (positive integers).
In order to reach the princess as quickly as possible,
the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below,
the initial health of the knight must be at least 7
if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2(K) -3 3
-5 -10 1
10 30 -5(P)
Note:
The knight's health has no upper bound.
Any room can contain threats or power-ups,
even the first room the knight enters and the bottom-right room where the princess is imprisoned.
"""
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
m, n = len(dungeon), len(dungeon[0])
dp = [[float("inf")]*(n+1) for _ in range(m+1)]
dp[m-1][n], dp[m][n-1] = 1, 1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
dp[i][j] = max(min(dp[i+1][j],dp[i][j+1])-dungeon[i][j],1)
return dp[0][0] | true |
65c2f70ca2dae1538060ac49c894702961d52e91 | Python-lab-cycle/Swathisha6 | /2.fibopnnaci.py | 214 | 4.15625 | 4 | n =int(input("enter the number of terms:"))
f1,f2=0,1
f3=f2+f1
print("fibonacci series of first" , n, "terms")
print(f1)
print(f2)
for i in range (3, n+1):
print(f3)
f1=f2
f2=f3
f3=f1+f2
| true |
899cccdd60ddcb83f56c18966562d82d0f77703e | LowerDeez/grasp-gof-patterns | /abstract-factory/main.py | 1,864 | 4.3125 | 4 | from abc import ABC, abstractmethod
from typing import List
class TraditionalDish(ABC):
"""Base class for traditional dish"""
name = "traditional dish"
class Lunch(ABC):
"""Base class for lunch"""
name = "lunch"
class Cafe(ABC):
"""Abstract Factory. Base class for specific country food"""
name = "cafe"
traditional_dishes: List[TraditionalDish] = []
@abstractmethod
def cook_lunch(self) -> Lunch:
pass
class JapanDish(TraditionalDish):
name = "japan traditional dish"
class AmericanDish(TraditionalDish):
name = "american traditional dish"
class UkrainianDish(TraditionalDish):
name = "ukrainian traditional dish"
class JapanLunch(Lunch):
name = "japan lunch"
class AmericanLunch(Lunch):
name = "american lunch"
class UkrainianLunch(Lunch):
name = "ukrainian lunch"
class JapanFood(Cafe):
name = "cafe's japan food"
traditional_dishes: List[JapanDish] = [JapanDish, ]
def cook_lunch(self) -> JapanLunch:
return JapanLunch()
class AmericanFood(Cafe):
name = "cafe's american food"
traditional_dishes: List[AmericanDish] = [AmericanDish, ]
def cook_lunch(self) -> AmericanLunch:
return AmericanLunch()
class UkrainianFood(Cafe):
name = "cafe's ukrainian food"
traditional_dishes: List[UkrainianDish] = [UkrainianDish, ]
def cook_lunch(self) -> UkrainianLunch:
return UkrainianLunch()
if __name__ == '__main__':
# Client's code:
SETTINGS = {
'japan': JapanFood,
'american': AmericanFood,
'ukrainian': UkrainianFood,
}
for country_food in list(SETTINGS.values()):
country_food = country_food()
print('*' * 30)
print([dish.name for dish in country_food.traditional_dishes])
lunch = country_food.cook_lunch()
print(lunch.name)
| false |
c40bb2fd8c2d832b63fc1cd49c3718f6d8b96a87 | ipcoo43/pythonone | /lesson145.py | 758 | 4.21875 | 4 | print('''
[ 범위 만들기 ]
range(<숫자1>) : 0부터 (<숫자1>-1)까지의 정수 범위
range(<숫자1>,<숫자2>) : <숫자1>부터 (<숫자2>-1)까지의 정수의 범위
ringe(<숫자1>,<숫자2>,<숫자3>) : <숫자1>부터 <숫자3> 만큼의 차이를 가진 (<숫자2>-1)까지 범위
[ 범위와 반복문 ]
for <범위 내부의 숫자를 담을 변수> in <범위>:
<코드>
''')
print(range(5))
print(list(range(5)))
for i in range(5):
print('{}번째 반복문입니다.'.format(i))
print()
print(range(5,10))
print(list(range(5,10)))
for i in range(5,10):
print('{}번째 반복문입니다.'.format(i))
print()
print(range(0,10,2))
print(list(range(0,10,2)))
for i in range(0,10,2):
print('{}번째 반복문입니다.'.format(i)) | false |
6fca883d665e990214b2d41c54de0a598dbff80b | kruart/coding_challenges | /hackerRank/python3_/string-formatting.py | 337 | 4.125 | 4 | # https://www.hackerrank.com/challenges/python-string-formatting/problem
def print_formatted(num):
maxWidth = len(format(num, 'b'))
for i in range(1, num+1):
print("{0:>{width}} {0:>{width}o} {0:>{width}X} {0:>{width}b}".format(i, width=maxWidth))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
| false |
ee934da6f5e0eee00050b8ed0845a2a9f70dd3e7 | katherfrain/Py101 | /tipcalculator2.py | 810 | 4.125 | 4 | bill_amount = float(input("What was the bill amount? Please don't include the dollar sign! "))
service_sort = input("What was the level of service, from poor to fair to excellent? ")
people_amount = int(input("And how many ways would you like to split that? "))
service_sort = service_sort.upper()
if service_sort == "POOR":
tip_amount = (bill_amount*.1)
elif service_sort == "FAIR":
tip_amount = (bill_amount*.15)
elif service_sort == "EXCELLENT":
tip_amount = (bill_amount*.2)
else:
bill_amount = float(input("I didn\'t understand your first statement. What amount did you owe, sans dollar sign? "))
total = bill_amount + tip_amount
perperson = float(total/people_amount)
print(f"Your tip is ${tip_amount:.2f}, and your total is ${total:.2f}, which splits to ${perperson:.2f} per person.") | true |
2efd2878071e1534f85d45a7c3f36badb42c7a96 | katherfrain/Py101 | /grocerylist.py | 447 | 4.125 | 4 | def want_another():
do_you_want_another = input("Would you like to add to your list, yes/no? ")
if do_you_want_another == "yes":
grocery = input("What would you like to add to your list? ")
grocery_list.append(grocery)
print("You have added ", grocery, "to the list")
print("Your current list is: ", grocery_list)
do_you_want_another = input("Would you like to add another item? Yes or no?") | true |
15cba18ee92d82bf0f612e96ece1dc4a2911d9fc | ghimire007/jsonparser1 | /jsonparser.py | 1,111 | 4.1875 | 4 | # json parsor
import csv
import json
file_path = input("path to your csv file(add the name of your csv file as well):") # takes file path
base_new = "\\".join(file_path.split("\\")[:-1])
file_name = input(
"name of th file that you want to save as after conversion(no extension required):") # takes name of file you want to save as
file_name = base_new + "\\" + file_name + ".json" # adds extension to file name
with open(file_path, "r") as qna: # opens g n fileive
with open(file_name, "w") as qnajson: # makes new file as you entered
final_json = []
reader = csv.reader(qna)
headings = next(reader) # reads header of csv file
for line in reader:
x = {}
for i in range(len(headings)):
x[headings[i]] = line[i]
ready_json = json.dumps(x)
final_json.append(ready_json)
new_json = ",".join([str(elem) for elem in final_json])
last_json = "[" + new_json + "]"
qnajson.write(last_json)
print("your json file has been created at " + base_new)
| true |
84e0a3ba3678e6e5bc8618871e8d7a2eb6cebfe1 | himala76/Codding_Lesson_1 | /Lectures_Note_Day_1/Cancat.py | 352 | 4.4375 | 4 | # This is the result we want to have in the console
#print "Hello, world! My name is Josh."
# Create a variable to represent the name and introduction statement to print
name = "Josh"
# Comment out this line for the moment
# intro_statement = "Hello, world! My name is "
# print the concatenated string
print "Hello, world! My name is " + name + "." | true |
4b02cf096cd437659968330d1e2fed228fd2036f | asenath247/COM404 | /1-basics/4-repetition/3-ascii/bot.py | 212 | 4.15625 | 4 | print("How many bars should be charged.")
bars = int(input())
chargedBars = 0
while chargedBars < bars:
print("Charging "+"█" * chargedBars)
chargedBars += 1
print("The battery is fully charged.")
| true |
4b3fd151726e2692179e72be9fb71e4b3fb632a3 | vishal-B-52/Documentation_of_Python | /GuessTheNumberModified.py | 1,693 | 4.25 | 4 | # Guess the number :-
print("This is a 'Guess the Number Game'. You have 10 Life(s) to guess the hidden number. You have to win in 10 Life(s) "
"else You lose!!! ")
Life = 10
while True:
N = int(input("Enter the number:- "))
Life -= 1
if 0 <= N < 18:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are too close to the number. Try to focus!!")
elif N == 18:
print("Hurray You won the game !!!")
print("You won with", Life, "life(s) still left\n")
break
elif 19 <= N <= 36:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are close to the number, Please concentrate!!")
elif 37 < N <= 100:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are going too far. You need to come back")
elif N > 100:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("Number is smaller than 100, Please Try again!!!")
if Life == 9:
print("You lost one life,", Life, "life(s) left\n")
elif Life == 8:
print("You lost another life,", Life, "life(s) left\n")
elif 1 < Life <= 7:
print("You lost another life again,", Life, "life(s) left\n")
elif Life == 1:
print("You have the last life. Best of Luck.", Life, "Life(s) left\n")
| true |
b15d153e861eeed43c8b9c77c6a4f00198580892 | Kaiquenakao/Python | /Coleções Python/Exercicio58.py | 1,433 | 4.125 | 4 | """
58. Faça um programa que leia uma matriz de 4 linhas e 4 colunas contendo as seguintes informações
sobre alunos de uma disciplina, sendo todas as informações do tipo inteiro:
º Primeira coluna: Número de matrícula (use um inteiro)
º Segunda coluna: Média das prova
º Terceira coluna: Média dos trabalhos
º Quarta coluna: Nota final
Elabore um programa que:
(a) Leia as três primeiras informações de cada aluno
(b) Calcule a nota final como sendo a soma da média das provas e da média dos trabalhos
(c) Imprima a matrícula do aluno que obteve a maior nota final (assuma que só existe uma maior nota)
(d) Imprima a média aritmética das notas finais
"""
soma = 0
maior = 0
matricula = 0
matriz = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(0, 3):
for j in range(0, 4):
matriz[i][j] = int(input(f'Linha: {j} - Coluna: {i} Insira um número: '))
for j in range(0, 4):
if j == 0:
maior = matriz[1][j]
x = matriz[1][j] + matriz[2][j]
matriz[3][j] = x
if matriz[3][j] > maior:
maior = matriz[3][j]
matricula = matriz[0][j]
soma = soma + matriz[3][j]
print(matriz)
for i in range(0, 4):
for j in range(0, 4):
print(f'[{matriz[j][i]}]', end=' ')
print()
print(f'A matricula: {matricula} teve a maior nota final: {maior}')
print(f'A média aritmetica: {soma/4}')
| false |
ac95c2666c923119653f31376e715f7d2b233d59 | Kaiquenakao/Python | /Coleções Python/Exercicio57.py | 762 | 4.375 | 4 | """
57. Faça um programa que permita ao usuário entrar com uma matriz de 3 x 3 números inteiros. Em seguida,
gere um array unidimensional pela soma dos números de cada coluna da matriz e mostrar na tela esse
array. Por exemplo, a matriz:
[5 -8 10]
[1 2 15]
[25 10 7]
[31 4 3]
"""
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
soma = 0
somacolunas = []
for i in range(0, 3):
for j in range(0, 3):
matriz[i][j] = float(input(f'[{[i]}] [{[j]}] Insira um número: '))
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]}]', end=' ')
print()
for i in range(0, 3):
soma = 0
for j in range(0, 3):
soma = soma + matriz[j][i]
somacolunas.append(soma)
print(somacolunas) | false |
b907811cd06f03f55b3df9afc7fbc9309cb1f96e | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio2.py | 358 | 4.21875 | 4 | """
2. Leia um número fornecido pelo usuário. Se esse número for positivo, calcule a raiz quadrada do número
Se o número for negativo, mostre uma mensagem dizendo que o número é inválido.
"""
import math
num = int(input('Insira um número:'))
if num >= 0:
print(f'A raiz do número:{math.sqrt(num)}')
else:
print('Número inválido') | false |
4a72a5656a63fbd3a14ec2bfe8b7656dbd69a76d | Kaiquenakao/Python | /Coleções Python/Exercicio30.py | 594 | 4.125 | 4 | """
30. Faça um programa que leia dois vetores de 10 elementos. Crie um vetor que seja a intersecção
entre 2 vetores anteriores, ou seja, que contém apenas os números que estão em ambos vetores.
"""
conjuntoA = []
conjuntoB = []
print('Conjunto A')
for i in range(0, 9+1):
n = float(input(f'Conjunto : {i+1} - Insira um número: '))
conjuntoA.append(n)
print('Conjunto B')
for i in range(0, 9+1):
n = float(input(f'Conjunto B: {i + 1} - Insira um número: '))
conjuntoB.append(n)
A = set(conjuntoA)
B = set(conjuntoB)
print(A.intersection(B)) | false |
7dbbdacbfd8ce304a0de43a175ec23f5088e7470 | Kaiquenakao/Python | /Coleções Python/Exercicio51.py | 719 | 4.21875 | 4 | """
51. Leia uma matriz de 3 x 3 elementos. Calcule e imprima a sua transporta
"""
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrizt = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range(0, 3):
matriz[i][j] = float(input(f'[[{i}] [{j}]] digite um valor: '))
print('-----------------Matriz------------------')
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]}]', end=' ')
print()
for i in range(0, 3):
for j in range(0, 3):
matrizt[j][i] = matriz[i][j]
print('------------Matriz transporta-------------')
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matrizt[i][j]}]', end=' ')
print() | false |
f3bc9942cf77b94e4e8c4f9136f1189699fc39bc | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio4.py | 371 | 4.34375 | 4 | """
4. Faça um programa que leia um número e, caso ele seja positivo, calcule e mostre:
* O número digitado ao quadrado
* A raiz quadrada do número digitado.
"""
import math
num = float(input('Insira o seu valor:'))
if num > 0:
print(f'O número digitado ao quadrado:{num ** 2}')
print(f'A raiz quadrada do número digitado:{math.sqrt(num)}') | false |
c740260a42fd2ecda2ccf6fc33e4c709160d8957 | Kaiquenakao/Python | /Coleções Python/Exercicio1.py | 1,023 | 4.3125 | 4 | """
1. Faça um programa que possua um vetor denominado A que armazene 6 números inteiros. O
Programa deve executar os seguintes passos
(a) Atribua os seguintes valores a esses vetor:1,0,5,-2 ,-5,7;
(b) Armazene em uma variável inteira(simples) a soma entre os valores da posições A[0], A[1]
e A[5] do vetor e mostre na tela esta soma;
(c) Modifique o vetor na posição 4, atribuindo a está posição o valor 100;
(d) Mostre na tela cada valor do vetor A, um em cada linha;
"""
#(a) Atribua os seguintes valores a esses vetor:1,0,5,-2 ,-5,7;
A = [1,0,5,-2,-5,7]
"""(b) Armazene em uma variável inteira(simples) a soma entre os valores da posições A[0], A[1]
e A[5] do vetor e mostre na tela esta soma;"""
soma = A[0] + A[1] + A[5]
print(f'A soma:{soma}')
"""
(c) Modifique o vetor na posição 4, atribuindo a está posição o valor 100;
"""
A[4] = 100
print(f'Posição 4 modificada:{A[4]}')
"""
(d) Mostre na tela cada valor do vetor A, um em cada linha;
"""
for num in A:
print(num) | false |
bbaa640f05c59ee9347ae2e708de6171d8c16c95 | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio35.py | 543 | 4.125 | 4 | """
35. Sejam a e b os catetos de um triangulo, onde a hipotenusa é obtida pela equação
hip = √a² + b². Faça um programa que receba os valores de a e b e calcule o valor da
hipotenusa através da equação. Imprima o resultado dessa operação.
"""
import math
try:
a = float(input('Insira o valor de a: '))
b = float(input('Insira o valor de b: '))
print(f'O valor da hipotenusa é {"%.2f" %(math.sqrt(pow(a, 2) + pow(b, 2)))}')
except ValueError:
print('ERRO!!! o valor de a ou b tem que ser um número') | false |
9790f37381a1455af2fbb10777525caa9b8d0ab0 | innovatorved/BasicPython | /x80 - Tuples.py | 541 | 4.3125 | 4 | #turple
#turple is immutable
#once u defined turple u cannot change its elements
bmi_cat = ('Underweight' , 'Normal', 'Overweight' ,'very Overweight')
#type
print('Type: ',type(bmi_cat))
#access element of turple
print(bmi_cat[1]) #we use positive value
print(bmi_cat[-2]) #and we also use negative value
print(bmi_cat[0:3])#indexing range
print(bmi_cat.index('Normal')) #searching index of value
#for searching any element was in turple or not
#it is Case sensitive
print('Very underweight' in bmi_cat) #it return Boolean value
| true |
43fd97252b25c653bfdbe8a1349cd89475d40e60 | HananeKheirandish/Assignment-8 | /Rock-Paper-Scissor.py | 876 | 4.125 | 4 | import random
options = ['rock' , 'paper' , 'scissor']
scores = {'user' : 0 , 'computer' : 0}
def check_winner():
if scores['user'] > scores['computer']:
print('Play End. User Win!! ')
elif scores['user'] < scores['computer']:
print('Play End. Computer Win!! ')
else:
print('Play End.No Win!! ')
exit()
print('Choose from this list: ' , options)
for i in range(10):
computer = random.choice(options)
user = input('Play the game: ')
if (computer == 'rock' and user == 'scissor') or (computer == 'paper' and user == 'rock')\
or (computer == 'scissor' and user == 'paper'):
print('Computer win! ')
scores['computer'] += 1
elif computer == user:
print('No win! Try again. ')
else:
print('User win! ')
scores['user'] += 1
check_winner() | true |
e2a0c342c90cd07b387b7739b9869aee46df4090 | luroto/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 761 | 4.15625 | 4 | #!/usr/bin/python3
"""
Function handbook:
text_identation("Testing this. Do you see the newlines? It's rare if you don't: all are in the code."
Testing this.
Do you see the newlines?
It's rare if you dont:
all are in the code.
"""
def text_indentation(text):
""" This function splits texts adding newlines when some separators are found"""
if type(text) != str:
raise TypeError("text must be a string")
i = 0
total = len(text)
while i < total:
if text[0] == ' ':
pass
if text[i] == '.' or text[i] == ':' or text[i] == "?":
print("{}{}".format(text[i],'\n'))
i += 2
print("{}".format(text[i]), end="")
i += 1
if text[total -1] == ' ':
pass
| true |
3b0fe27b3dc3448de0bdcdd034ff6220af9bad2d | mtocco/ca_solve | /Python/CA041.py | 2,774 | 4.28125 | 4 | ## Code Abbey
## Website: http://www.codeabbey.com/index/task_view/median-of-three
## Problem #41
## Student: Michael Tocco
##
##
##
## Median of Three
##
##
## You probably already solved the problem Minimum of Three - and it was
## not great puzzle for you? Since programmers should improve their logic
## (and not only skills in programming language), let us change the task to
## make it more tricky.
##
## You will be again given triplets of numbers, but now the middle of them
## should be chosen - i.e. not the largest and not the smallest one. Such number
## is called the Median (of the set, array etc).
##
## Be sure, this problem is not simply "another stupid exercise" - it is used
## as a part in powerful QuickSort algorithm, for example.
##
## Input data will contain in the first line the number of triplets to follow.
## Next lines will contain one triplet each.
## Answer should contain selected medians of triplets, separated by spaces.
##
## Example:
## data:
## 3
## 7 3 5
## 15 20 40
## 300 550 137
##
## answer:
## 5 20 300
## Note: if your program will have a lot of if-else-if-else statements, then you
## are probably doing something wrong. Simple solution should have no more
## than three of them.
##
def main():
userArray = []
print()
print()
yesOrNo = input("Would you like proceed with the calculation? (enter[y , n]): ")
if yesOrNo == "y":
buildArray()
else:
print("Thank you, come again")
def buildArray():
arrayPairs = int(input("Please enter in " + \
"a desired number of sets to analyze"))
print("Enter/Paste your content. Ctrl-D to save it.")
answer = ""
contents = []
for i in range(int(arrayPairs+1)):
try:
line = input().split(" ")
if len(line) > 1:
intSet = [int(i) for i in line]
median = [i for i in intSet if i != min(intSet) and i != max(intSet)]
answer = answer + str(median).replace("[","").replace("]","") + " "
except EOFError:
break
print(answer)
main()
## The result was correct - the author listed some notes as well:
##
## Author's Notes
## To select the middle of three elements A, B and C let us try to reorder them:
##
## if A > B swap A with B
## if B > C swap B with C
## if A > B swap A with B
## For swapping X and Y use the temporary variable T in three assignment,
## for example:
##
## T = X; X = Y; Y = T
##
## At the 2nd step the largest element of three would be moved to C.
## After 3rd step the smallest of the remaining two is moved to A.
## Therefore B contains the middle element.
| true |
fbec208c8dae08742e23d199f4a4debc8d125430 | unknownpgr/algorithm-study | /code-snippets/02. permutation.py | 724 | 4.15625 | 4 | '''
Recursive function may not be recommanded because of stack overflow.
However, permutation can be implemented with recursive function without warring about overflow.
That is because n! grows so fast that it will reach at time limit before it overflows.
'''
def permutation(array):
'''
This function returns the array of all available permutations of given array.
If the given array is sorted in ascending order, the result also will be sorted.
'''
l = len(array)
if l == 1:
return [array]
result = []
for i in range(l):
sub_array = array[:i]+array[i+1:]
for sub_result in permutation(sub_array):
result.append([array[i]]+sub_result)
return result
| true |
af800a84a2887a6cc0561a74b3a44215ac9e8457 | jhglick/comp120-sp21-lab09 | /longest_increasing_subsequence.py | 467 | 4.125 | 4 | """
File: longest_increasing_subsequence.py
Author: COMP 120 class
Date: March 23, 2021
Description: Has function for longest_increasing_subsequence.
"""
def longest_increasing_subsequence(s):
"""
Returns the longest substring in s. In case of
ties, returns the first longest substring.
"""
pass
if __name__ == "__main__":
s = input("Enter a string: ")
print(f"Maximum consecutive subsequence is {longest_increasing_subsequence(s)}")
| true |
0ead192ad5b4d5d7d2200c26a78eaed348933274 | rachit-mishra/Hackerrank | /String 10 formatting.py | 793 | 4.21875 | 4 | '''
def print_formatted(number):
for i in range(1,number+1):
binlen = len(bin(i)[2:])
print(str(i).rjust(binlen,' '),end=" "),
print(str(oct(i)[2:]).rjust(binlen,' '),end=" ")
print(str(hex(i)[2:].upper()).rjust(binlen,' '),end=" ")
print(str(bin(i)[2:]).rjust(binlen,' '), sep=' ')
'''
# lesson: Simply use plus to concatenate strings, no need for separate print statements
def print_formatted(number):
width = len(bin(number)[2:])## used to slice the first 2 characters
for i in range(1, number + 1):
print(str(i).rjust(width+1) +
str(oct(i))[2:].rjust(width + 1) +
str(hex(i))[2:].upper().rjust(width + 1) +
str(bin(i))[2:].rjust(width + 1))
# CHECK OUT OTHER SOLUTIONS AS WELL
| false |
5b17d6216a339ee9642c7d826ff468a2bdd99139 | rachit-mishra/Hackerrank | /Sets 1 intro.py | 681 | 4.25 | 4 | # Set is an unordered collection of elements without duplicate entries
# when printed, iterated or converted into a sequence, its elements appear in an arbitrary order
# print set()
# print set('HackerRank')
# sets basically used for membership testing and eliminating duplicate entries
array = int(input())
sumlist = 0
for i in range(array):
s = input()
num = map(int, s.split())
my_list = list(set(num))
for j in range(len(my_list)):
sumlist += (my_list[j])
avg=sumlist/len(my_list)
print(avg)
## num = map(int, s.split())
# in python 3, map no longer returns a list
# num was being stored as a list earlier
# so use map | true |
a5daff0eccc74862ba2f2cd962971a27f2ec7099 | tinybeauts/LPTHW | /ex15_mac.py | 1,197 | 4.375 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# Extra Credit 4
# from sys import argv
#
# script, filename = argv
#
# txt = open(filename)
#
# print "Here's your file %r:" % filename
# print txt.read()
# Extra Credit 5
# print "Type the filename again:"
# file_again = raw_input("> ")
#
# txt_again = open(file_again)
#
# print txt_again.read()
# A reason to get the file name as input rather than when you call the file
# would be if you have a lot of files you're calling
# Another reason is maybe you're calling multiple files, but the names of
# some of them are contained in other ones. So you might need to open them
# before you can call the next one.
# Extra Credit 8
# from sys import argv
#
# script, filename = argv
#
# txt = open(filename)
#
# print "Here's your file %r:" % filename
# print txt.read()
#
# txt.close()
#
# print "Type the filename again:"
# file_again = raw_input("> ")
#
# txt_again = open(file_again)
#
# print txt_again.read()
#
# txt_again.close() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.