blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0c6ae5e9838277d51beeb15f9c4182c056b855ba | macraiu/software_training | /leetcode/py/405_Convert_a_Number_to_Hexadecimal.py | 1,080 | 4.46875 | 4 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
def toHex(num):
d = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'}
h = []
if num == 0:
return '0'
if num < 0:
num = 2**32 + num
while num > 0:
h.append(d[num % 16])
num = num // 16
h.reverse()
return "".join(h)
num = -17
print(toHex(num))
print(hex(num))
| true |
11afb9ec2ea1e51b41ce266c5291a050007d45d1 | srosenfeld/MyFirstRepo | /personality_survey_SR.py | 903 | 4.15625 | 4 | print("What's your favorite sport?")
sport = input()
if sport == "Hockey":
print("That's my favorite sport too!")
elif sport == "Tennis":
print("Tennis is my other favorite sport to play!")
elif sport == "Crew":
print("Woah I love crew! You do too? Awesome!")
else:
print(sport + " sounds fun to play.")
print("What's your favorite subject?")
subject = input()
if subject == "Art" or subject == "Math":
print("I love art and math!")
else:
print(subject + " is a great class too.")
print("What's your fav food?")
food = input()
if food == "candy":
print("Oh boy")
elif food == "crepe":
print("What's your favorite kind of crepe?")
favfood = input()
if favfood == "nutella and banana":
print("Yum!")
else:
print("That's nice.")
elif food == "orange":
print("Orange ya glad I didn't say banana?")
| true |
6cffbd0e660b40e36060e86846f91ed1936a5168 | oscartoomey/starwarsGame | /gameparser.py | 663 | 4.3125 | 4 | # TODO: Add skip_words list
from string import ascii_lowercase
skip_words = []
def normalise_input(input):
lowercase_input = input.lower()
words = []
next_word = ""
# Cycle through characters in the input, storing sequences of letters as words.
for char in lowercase_input:
if char in ascii_lowercase:
next_word += char
elif next_word != "":
if next_word not in skip_words:
words.append(next_word)
next_word = ""
# If a word was being read at the end of the string, add it to the list.
if next_word != "":
words.append(next_word)
return words | true |
0ce51c53e01cebc7515677ef78c04fda785a5564 | treinmund/test | /functions.py | 1,178 | 4.375 | 4 | from datetime import date
def main():
# define today's date
y_today = int(date.today().year)
m_today = int(date.today().month)
d_today = int(date.today().day)
# get user input on their date of birth
y_born = int(input('Enter year born as yyyy: \n'))
m_born = int(input('Enter month born as mm: \n'))
d_born = int(input('Enter day born as dd: \n'))
age = calculate_age(y_today, m_today, d_today, y_born, m_born, d_born)
if age > 50:
print("You're old")
elif age < 21:
print("You're too young")
else:
print('Have a drink')
#your main code goes here - this is where you call functions
def calculate_age(y_today, m_today, d_today, y_born, m_born, d_born):
if m_born > m_today:
age = y_today - y_born - 1
elif m_born == m_today:
if d_born > d_today:
age = y_today - y_born - 1
elif d_born == d_today:
age = y_today - y_born
print('Happy birthday!')
else:
age = y_today - y_born
else:
age = y_today - y_born
return age
if __name__ == "__main__":
main()
| false |
365eeeae7268ac95dc200963c894cf73e2292686 | ashschwartz/remote_projects | /python/practice problems/collatz.py | 429 | 4.28125 | 4 | def collatz(inputNumber):
if inputNumber % 2 == 0:
newNumber = inputNumber // 2
else:
newNumber = 3 * inputNumber + 1
print(newNumber)
return newNumber
validInput = False
while not validInput:
print('Pick an integer and watch the Collatz Sequence in action')
number = input()
try:
number = int(number)
validInput = True
except:
print('You must enter an integer')
while number != 1:
number = collatz(number) | true |
9737d8cf1776dd2d7d8f26d27706ac717afe3c9a | pktolstov/Lesson4 | /task_6_2.py | 1,393 | 4.21875 | 4 | """
6. Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
что создаваемый цикл не должен быть бесконечным. Необходимо предусмотреть условие его завершения.
Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл.
Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
"""
from itertools import cycle
from random import randint
new_list = [randint(1, 30) for i in range(5)]
cycle_limit = int(input("Введите число повторений списка: "))
print(new_list)
count = 0
for el in cycle(new_list):
if count > (cycle_limit*len(new_list))-1:
break
else:
print(el, end=" ")
count += 1
| false |
88578d4e8c9ee1faa0438bfcda0a58c25c7a147b | jeffmay/haikuwriters | /haikuwriters/utils.py | 364 | 4.125 | 4 | import string
punkt_table = str.maketrans(string.punctuation, " " * len(string.punctuation))
def convert_punctuation_to_space(text):
return text.translate(punkt_table)
def remove_punctuation(words):
"""
Filter all words that are punctuation.
"""
for word in words:
if convert_punctuation_to_space(word) != " ":
yield word | true |
7f450fd6ec3ab73ec6ca210f47fbe55805ec4231 | rfael5/Exercicios-Python-Curso-em-Video | /ex083.py | 1,104 | 4.28125 | 4 | '''EXERCÍCIO 83
Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá
analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.'''
'''MINHA SOLUÇÃO - ESTÁ ERRADA. CONTA O NÚMERO DE PARENTESES CERTO MAS NÃO A ORDEM CERTA.
a = str(input('Digite a expressão: '))
p1 = a.count('(')
p2 = a.count(')')
print(f'{p1} parenteses abrindo e {p2} parenteses fechando.')
if p1 == p2:
print('Sua expressão está correta.')
else:
print('Sua expressão está errada.')'''
'''SOLUÇÃO DO PROFESSOR'''
expressão = str(input('Digite uma expressão: '))
parenteses = []
for p in expressão:
if p == '(':
parenteses.append('(')
elif p == ')':
if len(parenteses) > 0:
parenteses.pop() #ESSE COMANDO EXCLUI O ÚLTIMO ELEMENTO DA LISTA.
else:
parenteses.append(')')
break
print(parenteses)
if len(parenteses) == 0:
print('Sua expressão está correta.')
else:
print('Sua expressão está errada.')
| false |
e522014e2f9b809f7d14050b98eb649f82e7566b | rfael5/Exercicios-Python-Curso-em-Video | /ex028.py | 572 | 4.28125 | 4 | '''EXERCÍCIO 28
Escreva um programa que faça o computador "pensar" em um número entre 0 e 5 e peça para o
usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá
escrever na tela se o usuário venceu ou perdeu.'''
from random import randint
computador = randint(0,5) #randint faz escolher um número inteiro randomicamente.
print('Vou pensar em um número. Tente adivinhar.')
jogador = int(input('Qual número eu pensei?'))
if jogador == computador:
print('Você venceu! Muito bom.')
else:
print('Eu venci.')
| false |
f29c9054c38f4eca0dba292a61b6b2c603d31b74 | rfael5/Exercicios-Python-Curso-em-Video | /ex022.py | 849 | 4.40625 | 4 | '''EXERCÍCIO 22
Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas e minúsculas.
- Quantas letras ao todo (sem considerar espaços).
- Quantas letras tem o primeiro nome.'''
#Usa-se o '.strip()' para excluir espaços no inicio ou final da digitação.
nome = str(input('Qual é o seu nome? ')).strip()
dividido = nome.split()
print('Analisando seu nome')
print('Seu nome em maiúsculas é {}'.format(nome.upper()))
print('Seu nome em minúsculas é {}'.format(nome.lower()))
#Usou 'len(nome) - nome.count(" ") para não contar os espaços entre o nome. Faz uma subtração, a contagem de caracteres menos a contagem de espaços.
print('Seu nome tem ao todo {} letras.'.format(len(nome) - nome.count(" ")))
print('Seu primeiro nome tem {} letras.'.format(len(dividido[0])))
| false |
a3af14b7157c2f885e967d9af8eb077174cfe2d0 | rfael5/Exercicios-Python-Curso-em-Video | /ex037.py | 970 | 4.34375 | 4 | '''EXERCÍCIO 37
Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual
será a base de conversão.
1 para binário
2 para octal
3 para hexadecimal
'''
num = int(input('Digite um número: '))
print('''CONVERTER PARA
[ 1 ] BINÁRIO
[ 2 ] OCTAL
[ 3 ] HEXADECIMAL''')
conversao = int(input('Base de conversão: '))
if conversao == 1:
print('{} em binário é igual a {}.'.format(num,bin(num)[2:]))
elif conversao == 2:
print('{} em octal é igual a {}.'.format(num, oct(num)[2:]))
elif conversao == 3:
print('{} em hexadecimal é igual a {}.'.format(num, hex(num)[2:]))
#^ esse '2:' no final é pra mostrar só do 3º caracter pra frente
else: #Sem o '2:' ele mostra aqueles dois caracteres que serve pra identificar a base numérica
print('OPÇÃO NÃO DISPONÍVEL.') | false |
0ed973f1e958bbde21095581b33e3b2932059f42 | khemosh/Python_stuff | /shinners_homework.py | 2,202 | 4.1875 | 4 | def get_word_count(file_name):
handler = open(file_name) # your file
word_count_dict = {} # your dictionary
for line in handler: # go through each line in the file
words = line.split() # split the line into a list of words
for word in words: # go through each word in the list
if word not in word_count_dict: # if the word is not in the your dictionary..
word_count_dict[word] = 1 # put it there and give it a count value of 1
else: # if it is in the dictionary already..
word_count_dict[word] += 1 # add one to its count value
return word_count_dict
def get_word_count_first_line(file_name):
handler = open(file_name).readline() # get the first line of the file
word_count = {} # your dictionary
for word in handler.split(): # split the line into words and go through each word
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
return word_count
def get_word_count2(file_name):
handler = open(file_name)
word_count_dict = {}
for line in handler:
words = line.split()
for word in words:
"""get() is a built in python function for dictionaries that does
the same thing as lines 7 to 10 above in one line of code.
It says "if you dont find it give it a value of 0, but either way
add 1 to its value".
"""
word_count_dict[word] = word_count_dict.get(word, 0) + 1
return word_count_dict
# print "Count from first line: \n", get_word_count_first_line('news.txt')
# print "Count of all words in file: \n", get_word_count2('news.txt')
dd = get_word_count2('news.txt')
for key in dd:
print "key, value: ", key, dd[key]
print "list of tuples: ", dd.items() # gives back tuples
print "list of keys: ", dd.keys()
print "list of values: ", dd.values()
bigword = 0
bigcount = 0
for word, count in dd.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print "Most common word is: ", bigword, "at", bigcount, "times"
stuff = dict()
print stuff.get('candy', -1)
| true |
a3061d650197f0669d03bc5954445b199b6cc17b | xiaogy0318/coding-exercises | /python/AdditionWithoutArithmatic/solution.py | 659 | 4.28125 | 4 | def add_without_plus(n1, n2):
# Add can be split into 2 steps
# 1. use xor so that two numbers are added without considering carrying
# 2. Then handle the carrying by and and then << by 1 digit
if (n2 == 0):
return n1
sum = n1 ^ n2
#print n1, " xor ", n2, " is: ", n3
carry = (n1 & n2) << 1
#print n1, " and ", n2, " and then shift left by 1 is: ", n4
# Repeat the process. Each time the carry would move up, until it's 0
return add_without_plus(sum, carry)
#add_without_plus(2, 3)
print add_without_plus(9, 3)
print add_without_plus(2432, 213)
print add_without_plus(68762, 342)
print add_without_plus(3, 5758565)
| true |
60f1264ded09b81c7109410a77c44f8614f41f85 | cgarcia101015/Python_Full_Stack_Training | /Python/Level_Two/war_project.py | 2,297 | 4.40625 | 4 | #####################################
### WELCOME TO YOUR OOP PROJECT #####
#####################################
# For this project you will be using OOP to create a card game. This card game will
# be the card game "War" for two players, you an the computer. If you don't know
# how to play "War" here are the basic rules:
#
# The deck is divided evenly, with each player receiving 26 cards, dealt one at a time,
# face down. Anyone may deal first. Each player places his stack of cards face down,
# in front of him.
#
# The Play:
#
# Each player turns up a card at the same time and the player with the higher card
# takes both cards and puts them, face down, on the bottom of his stack.
#
# If the cards are the same rank, it is War. Each player turns up three cards face
# down and one card face up. The player with the higher cards takes both piles
# (six cards). If the turned-up cards are again the same rank, each player places
# another card face down and turns another card face up. The player with the
# higher card takes all 10 cards, and so on.
#
# There are some more variations on this but we will keep it simple for now.
# Ignore "double" wars
#
# https://en.wikipedia.org/wiki/War_(card_game)
from random import shuffle
# Two useful variables for creating Cards.
SUITS = 'Hearts Diamond Spades Clubs'.split()
RANKS = '2 3 4 5 6 7 8 9 10 Joker Queen King Ace'.split()
class Deck:
def __init__(self):
self.cards = []
self.build()
def build(self):
for s in ["Spades", "Clubs","Hearts","Diamonds"]:
for v in range(1, 14):
self.cards.append(s, v)
def show(self):
for c in self.cars:
c.show()
deck = Deck()
deck.show()
class Hand:
'''
This is the Hand class. Each player has a Hand, and can add or remove
cards from that hand. There should be an add and remove card method here.
'''
pass
class Player:
"""
This is the Player class, which takes in a name and an instance of a Hand
class object. The Payer can then play cards and check if they still have cards.
"""
pass
######################
#### GAME PLAY #######
######################
print("Welcome to War, let's begin...")
# Use the 3 classes along with some logic to play a game of war!
| true |
18b21f77c2ec4c1557d2cdb8e14fa2d12cd0f710 | ericachang018/Algorithms | /hanoi/model.py | 1,669 | 4.21875 | 4 | # how do i create a model!!! >__< gah
# Game model - There are 3 towers all of which have unique names and how to solve the hanoi problem
class Hanoi(object):
def __init__(self, num_disks):
self.tower1 = Tower("Tower Of Doom")
self.tower2 = Tower("Tower Of Power")
self.tower3 = Tower("Tower of Life")
for i in range(num_disks-1, -1, -1):
self.tower1.add( Disk(i+1) )
self.moves = []
def solve(self):
self._solve_towers(len(self.tower1.disks), self.tower1, self.tower2, self.tower3)
# private function which can only be used in this method.
def _solve_towers(self, n, start, holder, end):
if n > 0:
self._solve_towers(n-1, start, end, holder)
if start.has_disks():
disk = start.remove()
self.moves.append("Moving disk of size %d from %s to %s"%(disk.size, start.name, end.name))
end.add(disk)
self._solve_towers(n-1, holder, start, end)
#build a tower class that has a name and can hold disks and the functions to add remove them.
class Tower(object):
def __init__(self, name):
self.disks = []
self.name = name
def remove(self):
disk = self.disks.pop()
return disk
def add(self, disk):
self.disks.append(disk)
def has_disks(self):
return len(self.disks) > 0
# build a disk class that specifies size.
class Disk(object):
def __init__(self, size):
self.size = size
# def main():
# hanoi = Hanoi(5)
# hanoi.solve()
# print hanoi.moves
# if __name__ == "__main__":
# main() | true |
918a0031d6abd459958327067d4d7e11be06999d | Jasc94/thebridge | /0_AWS/eda_project/src/utils/folder_tb.py | 677 | 4.15625 | 4 | import sys, os
def path_to_folder(up, folder = ""):
'''
Function that calculates the path to a folder
args :
up -> how many levels you want to go up
folder -> once you've gone up "up" levels, the folder you want to open
'''
# to better use the function
dir = os.path.dirname
# I start the way up
path_up = dir(__file__)
# Loop "up" times to reach the main folder
for i in range(up): path_up = dir(path_up)
# go down to the folder I want to pull the data from
if folder:
path_down = path_up + os.sep + folder + os.sep
else:
path_down = path_up + os.sep
# return the path
return path_down | true |
54057d92d40de9dd6bf35007cb1d63a9e5f63f95 | rodrigo-arenas/complete_python_guide | /Section_02_Errors/1.Common_Errors.py | 941 | 4.15625 | 4 |
class Car:
def __init__(self,make,model):
self.make = make
self.model = model
def __repr__(self):
return f'<Car {self.make} {self.model}>'
class Garage:
def __init__(self):
self.cars =[]
def __len__(self):
return len(self.cars)
def add_car(self,car):
#NotImplementedError Error para especificar que este método aún no se ha implementado
raise NotImplementedError("We can't add cars to garage yet")
def add_cars(self,cars):
#isinstance(x,y) mira si x es de la clase de Y
if not isinstance(cars,Car):
raise TypeError(f'Tried to add a {cars.__class__.__name__} to garage, but you can only add \'Cars\' objects')
self.cars.append(cars)
ford = Garage()
#ford.add_car('Fiesta') <-NotImplementedError
print(len(ford))
#ford.add_cars('Volvo') <- TypeError
car= Car('Ford','Fiesta')
ford.add_cars(car)
print(len(ford))
| false |
3e7373d0ca5aadd9e09817dc6f7ec5181851439f | minielectron/coding-interview-problems | /algorithms/sorting/1insertion-sort.py | 472 | 4.15625 | 4 | import numpy as np
arr = np.array([2,5,3,7,9,8,0])
def sort(a):
j = 0
size = len(a)
while(j < size ):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a [i]
i = i - 1
j= j + 1
a[i+1] = key
return a
print(sort(arr))
# Worst case: When array is reverse sorted - Time complexity will be O(n^2)
# Best case: When array is already sorted - Time complexity will be O(n) | true |
a1f422645495f98ba551f17d1817ccd9d94655b5 | wclermont/Python | /mycalc.py | 1,933 | 4.375 | 4 | # Coder: Woody Clermont
# Simple Python Calculator
def validator (x,z): #this function validates the input of the first or second number
while True:
print ('\nEnter input number', x)
try:
y = float(input('Type a positive or negative rational number: '))
except ValueError:
print ('Input number', x, 'must be a real number.')
continue
if z=='4' and y == 0: #this condition prevents division by 0
print ('Division by 0 not permitted, type a different number.')
continue
else:
break
return (y)
def calculator (x,y,z): #this function performs the calculation
global operator
if z == '1':
operator = '+'
a = x + y
elif z == '2':
operator = '-'
a = x - y
elif z == '3':
operator = '×'
a = x * y
else:
operator = '÷'
a = x / y
return (a)
def operation(): #this function validates that a proper operator has been selected
while True:
b = input('What is the operator? (1-add (+), 2-subtract(-), 3-multiply (×), 4-divide (÷))\n')
if b == '1' or b == '2' or b == '3' or b == '4':
return (b)
else:
print('You can only choose 1-4 as options.')
continue
calc_cont = 0
while True: #this while statement is the main program
oper = '0'
first_number = validator(1,oper)
oper = operation()
second_number = validator(2,oper)
answer = calculator(first_number,second_number,oper)
print ('\n', first_number, operator, second_number, '=', answer, '\n')
calc_cont = input('Do you want to end the calculator? (Type 1 to end the program, or else it will continue.)\n')
if calc_cont == '1':
break #if the user presses 1 the program terminates
else:
continue #else the calculator will ask for new input and keep going
| true |
c6f41114982b101c52f0e2759745c6b23c3415c6 | rbryce90/learn-python | /strings.py | 1,061 | 4.375 | 4 | name = "bryce"
age = 29
# concatnate
# print('Hello, my name is ' + name + ' and I am ' + str(age))
# arguments by position
# print("My name is {name} and I am {age}".format(name=name, age=age))
# f-strings
# print(f'Hello, my name is {name} and I am {age}')
# string methods
s = 'hello world'
# string methods
print("started with", s)
print("capitalize", s.capitalize())
print("upper", s.upper())
print("lower", s.lower())
print("swapcase", s.swapcase())
print("replace", s.replace('world', 'everyone'))
sub = 'h'
print("count --> how many of a letter", sub.count(sub))
print("startswith returns bullion, for weather it starts with paramater ===>",
s.startswith("hello"))
print("endswith, boolean if it ends with paramater ===>", s.endswith('d'))
print("split, turns all words into a list", s.split())
print("find, finds index of character", s.find('r'))
# check to see if types of characters are particular type
print("isalpha, false because of space", s.isalpha())
print("isalnum", s.isalnum())
print("isalnumeric", s.isnumeric())
| true |
5a5921eea3270f777cf36b9736fe622192931d8b | tremax222/RaspArm-S-Tutorials-and-Code | /code/adeept_rasparms/CourseCode/08linkageM/linkageM.py | 859 | 4.375 | 4 | import numpy as np
'''
This program runs on the computer
pip install matplotlib
Install matplotlib
'''
'''
Import matplotlib
'''
from matplotlib import pyplot as plt
'''
matplotlib itself has a library for drawing line segments. Enter a set of X and then enter a set of Y to draw the line
This routine is mainly used to test whether the library is installed successfully, and to understand the most basic operations of matplotlib
'''
def drawLine(pos1, pos2):
'''
Enter the coordinates pos1 of the initial point of the line segment and pos2 of the end point
'''
x = [pos1[0], pos2[0]] # Array of X points
y = [pos1[1], pos2[1]] # Array of Y points
plt.plot(x, y) # Draw this line segment
drawLine([0,0], [2,2]) # Call the function and draw a line segment starting at (0,0) and ending at (2,2)
plt.show() # show result | true |
77978067eac1fba4193f9eba150f01d6e98e848a | 40586/Assignment | /assignment_improvement_exercise.py | 337 | 4.125 | 4 | #john bain
#05-09-12
#variable improvement exercise
import math
Radius = int(input("please enter the radius of the circle: "))
Cir = 2*math.pi*Radius
Cir = round(Cir,2)
Area = math.pi * Radius**2
Area = round(Area,2)
print("The circumference of this circle is: {0}.".format(Cir))
print("The area of this circle is: {0}.".format(Area))
| true |
d58701d3b488adc28fd59e23cd22c95ef90af4cf | kevinvervloet/Make1.2.1 | /Aantal tekens van een string.py | 506 | 4.46875 | 4 | #!/usr/bin/env python
"""
This program will display the amount of characters in a string
"""
__author__ = "Kevin Vervloet"
__email__ = "kevin.vervloet@student.kdg.be"
__status__ = "Development"
def main():
Word = input('Type your word here: ') # This is your input
print('Here are the amount of characters: ', len(Word)) # the amount of characters from a word will be printed
if __name__ == '__main__': # run tests if called from command-line
main()
| true |
544a9f68c6a22365337439657d29af118208deb7 | ktburns214/python_sandbox | /python_sandbox_starter/files.py | 561 | 4.375 | 4 | # Python has functions for creating, reading, updating, and deleting files.
#open a file
myFile = open("myfile.txt", "w")
# get info on the file
print("name: ", myFile.name)
print("is closed: ", myFile.closed)
print("opening mode: ", myFile.mode)
# write to file
myFile.write("Hello world!")
# can keep appending to file, as above
myFile.close()
# append to file
myFile = open("myfile.txt", "a")
myFile.write(" This is part of the Python crash course")
myFile.close()
# read from file
myFile = open("myfile.txt", "r+")
text = myFile.read(100)
print(text)
| true |
a93a07f96bd96ff25a3c62bc9f42729a96c3476b | alexReshetnyak/pure_python | /1_fundamentals/17_functions.py | 2,325 | 4.53125 | 5 | print('---------------------------FUNCTIONS--------------------------------')
# ? we can run functions only after it was defined
# say_hello() # ! NameError: name 'say_hello' is not defined
def say_hello():
phrase = 'Hello'
print(":", phrase)
say_hello() # Hello
# print(":", phrase) # ! NameError: name 'name' is not defined
print('---------------------------ARGUMENTS VS PARAMETERS--------------------')
def say_hello1(name): # name - parameter
phrase = 'Hello'
print(":", f'{phrase} {name}')
say_hello1('Alexey') # Hello Alexey , 'Alexey' is argument
print('---------------KEYWORD ARGUMENTS AND DEFAULT PARAMETERS---------------')
def say_hello2(name, second_name):
phrase = 'Hello'
print(":", f'{phrase} {name} {second_name}')
# ? Keyword arguments
# ! Bad practice
say_hello2(second_name='Reshetnyak', name='Alexey') # Hello Alexey Reshetnyak
# --------------------------------------------------------------------------------
# ? Default parameters
def say_hello3(name='Darth', second_name='Vader'):
phrase = 'Hello'
print(":", f'{phrase} {name} {second_name}')
say_hello3() # Hello Darth Vader
# say_hello2() # ! Error missing 2 required
# ! positional arguments: 'name' and 'second_name'
print('---------------------------RETURN--------------------------------')
def sum(num1, num2):
num1 + num2
print("sum(1,4):", sum(1, 4)) # None
# ---------------------------------------------------
def sum1(num1, num2):
return num1 + num2
total = sum1(2, 3) # 5
print("sum1(1,total):", sum1(1, total)) # 6
# ---------------------------------------------------
def sum2(num1, num2):
def another_func(num1, num2):
return num1 + num2
total = sum2(1, 2)
print("sum2(1,2):", sum2(1, 2)) # None
# ----------------------------------------------------
def sum3(num1, num2):
def another_func(num1, num2):
return num1 + num2
return another_func
total = sum3(1, 2)
# <function sum3.<locals>.another_func at 0x7fb8315ef950>
print("sum3(1,2):", sum3(1, 2))
# ----------------------------------------------------
def sum4(num1, num2):
def another_func(n1, n2):
return n1 + n2
return another_func(num1, num2)
total = sum4(1, 2)
print("sum4(1,2):", sum4(1, 2)) # 3
print(":", )
print(":", )
print(":", )
print(":", )
| false |
87d0d9647c567b628442fd02538f2872a2dbaa38 | alexReshetnyak/pure_python | /1_fundamentals/14_range .py | 587 | 4.40625 | 4 | print('---------------------------RANGE--------------------------------')
# ? Object that produce a sequence of integers from start to stop
print("range(100):", range(100)) # range(0, 100)
for number in range(0, 5):
print("number:", number) # 0,1,2,3,4,5
print(":", ) #
for _ in range(0, 5):
print(":", 'send email') # use _ if you don't need variable
print(":", ) #
for number in range(0, 10, 2):
print("number:", number) # 0,2,4,6,8
print(":", ) #
for number in range(10, 0, -2): # back count
print("number:", number) # 10, 8, 6, 4, 2
print(":", ) #
| false |
9b50351c78e856e6467112619f1780d49f07bd32 | Acentari/python-ds | /data_structures/array/max_product.py | 646 | 4.1875 | 4 | #function for log(a)
i = int(input("please give a number: "))
def power(a,b):
res = 1
while(b):
if(b & 1):
res = res * a
a = a * a
b >>= 1
return res
#function for max product
def max_product(x):
if(x == 2):
return 1
if(x == 3):
return 2
maxProduct = 0
if(x % 3 == 0):
maxProduct = power(3, int(x/3))
return maxProduct
elif(x % 3 == 1):
maxProduct = 2 * 2 * power(3,int(x/3)-1)
return maxProduct
elif(x % 3 == 2):
maxProduct = 2 * power(3,int(x/3))
return maxProduct
max = max_product(i)
print(max)
| true |
f2c48d779e3059135e4561f5b93e3228ab8c5baa | Liu-Maria/ISAT252 | /lec6.py | 1,288 | 4.375 | 4 | """
Week 2, day 6, lec 6
"""
# demo_string = 'this is my string'
# for str_item in demo_string: #for loop
# print(str_item)
# for word_item in demo_string.split():
# print(word_item.upper())
# print(word_item.title())
# for word_item in demo_string.split(): #split by each word
# if word_item is 'my': #print 'my' if there is one
# print(word_item)
# if word_item != 'my': #leave out 'my'
# print(word_item)
# for word_item in demo_string.split(): #split by each word
# print(word_item)
# for str_item in demo_string:
# print(str_item)
# print(range(4)) #will print range(0, 3) #will not print each number
# print(range(1, 3)) #not a list
# print(range(1, 6, 2))
# for each_num in range(5): #combine with for loop to get each number
# print(each_num)
'''
Use of breakpoint and debugging mode
Click on line number to add breakpoint
The weird green bush is for debugging
'''
num_list = [213, 321, 123, 312]
max_item = num_list[0] #use the first item as a placeholder for the max value
'''
#Finding the max value
num_list.sort()
print(num_list[-1])
'''
for num in num_list:
if max_item <= num:
max_item = num
print(max_item)
# print(max(num_list)) | true |
1e4421147318a041b3a64304758c07521037e40d | tlnguyen2018/holbertonschool-higher_level_programming | /0x08-python-more_classes/9-rectangle.py | 2,712 | 4.25 | 4 | #!/usr/bin/python3
"""
Same as the previous task
ADDING:
Class method def square(cls, size=0): that returns a new Rectangle instance
with width == height == size
"""
class Rectangle:
"""
define class Rectangle with public attribute
number_of_instances
"""
number_of_instances = 0
print_symbol = "#"
def __init__(self, width=0, height=0):
self.width = width
self.height = height
Rectangle.number_of_instances += 1
"""
setter -getter for private instance width
"""
@property
def width(self):
return (self.__width)
@width.setter
def width(self, value):
if not isinstance(value, int):
raise TypeError("width must be an integer")
if value < 0:
raise ValueError("width must be >= 0")
self.__width = value
"""
setter - getter for private instance height
"""
@property
def height(self):
return (self.__height)
@height.setter
def height(self, value):
if not isinstance(value, int):
raise TypeError("height must be an integer")
if value < 0:
raise ValueError("height must be >=0")
self.__height = value
"""
Public instance Area
"""
def area(self):
return (self.__width * self.__height)
"""
Public instance Perimeter
"""
def perimeter(self):
perimeter = (self.__width + self.__height) * 2
if self.__width is 0 or self.__height is 0:
return 0
return (perimeter)
"""
use str
"""
def __str__(self):
if self.__width is 0 or self.__height is 0:
return ""
for row in range(self.__height - 1):
print(str(self.print_symbol) * self.__width)
return str(str(self.print_symbol) * self.__width)
"""
use repr
"""
def __repr__(self):
return ("Rectangle({:d}, {:d})".format(self.__width, self.__height))
"""
use del
"""
def __del__(self):
print("Bye rectangle...")
Rectangle.number_of_instances -= 1
"""
static method
"""
@staticmethod
def bigger_or_equal(rect_1, rect_2):
if not isinstance(rect_1, Rectangle):
raise TypeError("rect_1 must be an instance of Rectangle")
if not isinstance(rect_2, Rectangle):
raise TypeError("rect_2 must be an instance of Rectangle")
if rect_1.area() > rect_2.area():
return (rect_1)
if rect_1.area() < rect_2.area():
return (rect_2)
return (rect_1)
"""
class method
"""
@classmethod
def square(cls, size=0):
return (Rectangle(size, size))
| true |
9826132233780fc2a261e3347b057778f2173548 | Rudedaisy/CMSC-201 | /Homeworks/hw3/hw3_part5.py | 1,041 | 4.53125 | 5 | # File: hw3_part5.py
# Written by: Edward Hanson
# Date: 9/19/15
# Lab Section: 18
# UMBC email: ehanson1@umbc.edu
# Description: Determines the day of the week using a day of the month.
def main():
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
dayOfMonth = int(input("Please enter the day of the month: "))
if (dayOfMonth <1) or (dayOfMonth > 31):
print("Invalid day.")
else:
dayOfWeek = dayOfMonth % 7
if dayOfWeek == SUNDAY:
print("Today is Sunday!")
if dayOfWeek == MONDAY:
print("Today is Monday!")
if dayOfWeek == TUESDAY:
print("Today is Tuesday!")
if dayOfWeek == WEDNESDAY:
print("Today is Wednesday!")
if dayOfWeek == THURSDAY:
print("Today is Thursday!")
if dayOfWeek == FRIDAY:
print("Today is Friday!")
if dayOfWeek == SATURDAY:
print("Today is Saturday!")
main()
| true |
56aaa43f34135a432fca631663269e9b7f1ff2ac | Sayali224/Python-Assignment | /Task2.py | 2,261 | 4.1875 | 4 | # Python-Assignment
1)
x = input ("Enter a value:")
x = int(x)
if (x%3 == 0) and (x%5 == 0):
print("Consultadd Python Training:")
if (x%3 == 0):
print("Consultadd")
if (x%5 ==0):
print("C")
if result <0 :
print("Negative")
# 2)
y = input("Select a value:")
y = int(y)
if y == 1:
x1,x2 = input("Enter the two values:").split()
result= int(x1)+int(x2)
print("Addition:", result)
if result <0 :
print("Negative")
if y == 2:
x1,x2 = input("Enter the two values:" ).split()
result= int(x1)-int(x2)
print("Subtraction:",result)
if result <0 :
print("Negative")
if y == 3:
x1,x2 = input("Enter the two values:" ).split()
result= int(x1)*int(x2)
print("Multiplication:",result)
if result <0 :
print("Negative")
if y == 4:
x1,x2 = input("Enter the two values:" ).split()
result= int(x1)/int(x2)
print("Division:",result)
if result <0 :
print("Negative")
if y == 5:
x1,x2,x3 = input("Enter three values:").split()
result= (int(x1)+int(x2)+int(x3))/3
print("Average:",result)
if result <0 :
print("Negative")
#3)
a = 10
b = 20
c = 30
avg = (a+b+c) / 3
print("avg:",avg)
if ( avg > a) and (avg > b) and (avg > c):
print("Avg is higher than a,b,c:")
elif(avg > a) and (avg > b):
print("avg is higher than a,b,c:")
elif(avg > a) and (avg > c):
print("avg is higher than a,c:")
elif(avg > b) and (avg > c):
print("avg is higher than b,c:")
elif(avg > a):
print("avg is just higher than a:")
elif(avg > b):
print("avg is just higher than b:")
elif(avg > c):
print("avg is just higher than c:")
#5)
n1=[]
for x in range (2000,3200):
if (x%7==0) and (x%5!=0):
n1.append(str(x))
print(','.join(n1))
#6)
x=123
for i in x:
print(i)
i = 0
while i<5:
print(i)
i+=1
if i==3:
break
else:
print("error")
count = 0
while True:
print(count)
count+=1
if count>=5:
break
#7)
for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
print("\n")
#8)
s = input("Input a string")
d=l=0
for a in s:
if a.isdigit():
d=d+1
elif a.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
| true |
4225ab2c4fa3eab9479549fd90df1fbeb202d78f | KoeusIss/holbertonschool-machine_learning | /math/0x00-linear_algebra/6-howdy_partner.py | 489 | 4.4375 | 4 | #!/usr/bin/env python3
""" Arrays concatenation """
def cat_arrays(arr1, arr2):
"""Concatenates two array of ints/floats
Args:
arr1 (list): the first given list
arr2 (list): the second given list
Returns:
(list): A new list contains the two given arrays concatenated in
single list
Example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [6, 7, 8]
cat_arrays(arr1, arr2) -> [1, 2, 3, 4, 5, 6, 7, 8]
"""
return arr1 + arr2
| true |
bf586db79392a7a659adaf04722a6edae3cffb71 | KoeusIss/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/12-learning_rate_decay.py | 828 | 4.125 | 4 | #!/usr/bin/env python3
"""Optimization module"""
import tensorflow as tf
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""Creates the learning rate decay operation in tensorflow using inverse
time decay
Args:
alpha (float): Is the original learning rate
decay_rate (float): Is the weight used to determine the rate at which
alpha will decay.
global_step (int): Is the number of passes of gradient descent that
have elapsed.
decay_step (int): Is the number of passes of gradient descent that
occur before alpha is decayed further.
Returns:
tf.operation: The learning rate decay operation
"""
return tf.train.inverse_time_decay(
alpha, global_step, decay_step, decay_rate, staircase=True
)
| true |
d7deb0d03a46300c34779fea83c25cf6c7e880da | KoeusIss/holbertonschool-machine_learning | /supervised_learning/0x0D-RNNs/1-rnn.py | 648 | 4.34375 | 4 | #!/usr/bin/env python3
"""RNN module"""
import numpy as np
def rnn(rnn_cell, X, h_0):
"""Performs forward propagation for a simple RNN
Arguments:
rnn_cell {RNNCell} -- RNNCell instance
X {np.ndarray} -- Contains the data to be used
h_0 {np.ndarray} -- Contains the initial hidden state
Returns:
tuple(np.ndarrat) -- Contains all the hidden states, and the
outputs
"""
T, m, i = X.shape
h, o = rnn_cell.Wy.shape
H = np.zeros((T + 1, m, h))
Y = np.zeros((T, m, o))
for t in range(1, T + 1):
H[t], Y[t - 1] = rnn_cell.forward(H[t - 1], X[t - 1])
return H, Y
| true |
d85ef43c8b137ee54aac058c5232115b7e3a788d | KoeusIss/holbertonschool-machine_learning | /math/0x02-calculus/9-sum_total.py | 426 | 4.1875 | 4 | #!/usr/bin/env python3
"""Sigma notation"""
def summation_i_squared(n):
"""Finds the summation of i squared where i goes from 1 to n
Args:
n (int): the stopping condition integer
Returns:
(int|None): The integer value of the sum, if n is not a valid number
return None
"""
if n < 1 or not isinstance(n, int):
return None
return int((n * (n + 1) * (2 * n + 1)) / 6)
| true |
8b791bedb7fcbbb0a0f1d9bf75a6eebae56e7772 | KoeusIss/holbertonschool-machine_learning | /math/0x00-linear_algebra/14-saddle_up.py | 708 | 4.5625 | 5 | #!/usr/bin/env python3
"""Matrix multiplication"""
import numpy as np
def np_matmul(mat1, mat2):
"""Performs matrices multiplication
Args:
mat1 (numpy.ndarray): the first given matrix
mat2 (numpy.ndarray): the second given matrix
Returns:
(numpy.ndarray): returns a new numpy.ndarray where performs matrices
multiplication
Example:
mat1 = [[1, 2],
[3, 4],
[5, 6]]
mat2 = [[1, 2, 3, 4],
[5, 6, 7, 8]]
np_matmul(mat1, mat2) -> [[11, 14, 17, 20],
[23, 30, 37, 44],
[35, 46, 57, 68]]
"""
return np.matmul(mat1, mat2)
| true |
35441e8c0805c1525c05e5b7c877075012d74124 | AngB0l/Python-for-Everybody | /exChapter6.py | 1,922 | 4.40625 | 4 | #Ex1. Write a while loop that starts at the last character in the string and works its way backwards
# to the first character in the string, printing each letter on a separate line, except backwards.
text = input('Type something to print backwards:\n')
i=len(text)
while i >= 1:
letter = text[i-1]
print(letter)
i=i-1
print('#############')
######################################
#Ex3. Ask the user for a character and a text.
#Create a function that counts the times that the character appears in the string
def count(searchTerm,text):
occurrences = 0
for i in text:
if i ==searchTerm:
occurrences+=1
return occurrences #saved in: found
searchTerm = input('What do you want to search for?\n') #has to be ONE letter or number
text = input('And now the text to search in \n')
found = count(searchTerm,text)
print(found)
print('#############')
######################################
#Ex4. Rewrite the previous exersise but use the STR method: count
#NOTE. if the search term is 11 in 111 it will find 1
searchTerm = input('What do you want to search for?\n') #go wild with letters or numbers
text = input('And now the text to search in \n')
occurrences = text.count(searchTerm)
print(occurrences)
print('#############')
######################################
#Ex5. Take the following Python code that strores a string: str = 'X-DSPAM-Confidence:0.8475'
#Use find and string slicing to extract the portion of the string after thecolon character
# and then use the float function to convert the extracted string into a floating point number.
text = 'X-DSPAM-Confidence:0.8475'
beg = text.find(':') # beg = 18, the possision of the ':'
number = text[beg+1:] # in the 'text' string [from possision(18+1) : end possision(NULL)]
print(float(number)) #print the number and transform it to float at the same time
print('#############')
######################################
| true |
91ac777d073bb8da46d6ecb153b68a200d57881a | vigneshmoha/python-100daysofcode | /day003_treasure_island/pizza_order.py | 1,149 | 4.21875 | 4 | currency = "$"
small_pizza = 15
medium_pizza = 20
large_pizza = 25
extra_pepperoni_small = 2
extra_pepperoni_medium_large = 3
extra_cheese = 1
print(f'''
Welcome to Python Pizzeria
**************************
Pizza Menu
**********
* Small Pizza: {currency}{small_pizza}
* Medium Pizza: {currency}{medium_pizza}
* Large Pizza: {currency}{large_pizza}
* Extra Pepperoni (Small pizza): +{currency}{extra_pepperoni_small}
* Extra Pepperoni (Medium/Large Pizzas): +{currency}{extra_pepperoni_medium_large}
* Extra cheese (Any size): +{currency}{extra_cheese}
''')
size = input("Enter the pizza size(S/M/L): ")
add_extra_pepperoni = input("Do you want toadd extra pepperoni? Please enter (Y/N): ")
add_extra_cheese = input("Do you want toadd extra cheese? Please enter (Y/N): ")
amount = 0
if add_extra_cheese == "Y":
amount += 1
if size == "S":
amount += small_pizza
elif size == "M":
amount += medium_pizza
else:
amount += large_pizza
if add_extra_pepperoni == "Y":
if size == "S":
amount += extra_pepperoni_small
else:
amount += extra_pepperoni_medium_large
print(f"You final bill is {currency}{amount}.")
| true |
3d0571c644beaf6579c4356aa33d7347aada8de1 | QiliWu/Udacity_code_02 | /triangle_pattern_2.py | 2,191 | 4.125 | 4 | import turtle
def single_triangle(some_turtle):
some_turtle.fillcolor('green') # move the filling code from draw_triangle_pattern, fill the triangle one by one
some_turtle.begin_fill() # start color fill , just before starting drawing
for j in range(3):
some_turtle.forward(30)
some_turtle.left(120)
some_turtle.end_fill() # end color fill when the drawing finished
def nine_triangles(some_turtle):
#line one
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.right(120)
some_turtle.forward(30)
some_turtle.left(120)
some_turtle.pendown()
#line two
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.forward(30)
some_turtle.pendown()
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.backward(30)
some_turtle.right(120)
some_turtle.forward(30)
some_turtle.left(120)
some_turtle.pendown()
#line three
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.forward(60)
some_turtle.pendown()
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.backward(60)
some_turtle.right(120)
some_turtle.forward(30)
some_turtle.left(120)
some_turtle.pendown()
#line four
for i in range(3):
single_triangle(some_turtle)
some_turtle.penup()
some_turtle.forward(30)
some_turtle.pendown()
single_triangle(some_turtle)
def triangle_pattern(some_turtle):
nine_triangles(some_turtle)
some_turtle.penup()
some_turtle.backward(90)
some_turtle.right(120)
some_turtle.forward(30)
some_turtle.left(120)
some_turtle.pendown()
nine_triangles(some_turtle)
some_turtle.penup()
some_turtle.forward(30)
some_turtle.left(60)
some_turtle.forward(90)
some_turtle.right(60)
some_turtle.pendown()
nine_triangles(some_turtle)
def draw_triangle_pattern():
window = turtle.Screen()
window.bgcolor('white')
brad = turtle.Turtle()
brad.shape('turtle')
brad.color('blue')
brad.speed(5)
brad.width(2)
triangle_pattern(brad)
window.exitonclick()
draw_triangle_pattern()
| true |
abded89bd7f5174390b77854610dcd8015492aa5 | Kellysmith7/Module-7 | /fun_with_collections/sort_and_search_array.py | 825 | 4.25 | 4 | """
Program: sort_and_search_array.py
Author: Kelly Smith
Last date updated: 10-8-19
Program to search and sort arrays
:param c: array to be sorted
:param f: array to search
:return The sorted array c and the searched value in array f or -1 if it is not found
"""
import array as arr
def sort_array(c):
c = arr.array('d', [1.2, 6.3, 5.4])
d = c.tolist()
d.sort()
e = arr.array('d', d)
return e # Included a return so the sorted array will be the array that is the output of the function
def search_array(f, value):
f = arr.array('d', [8.2, 4.3, 6.4])
try:
return f.index(value)
except ValueError:
return -1
if __name__ == '__main__':
c = arr.array('d', [1.2, 6.3, 5.4])
f = arr.array('d', [8.2, 4.3, 6.4])
print(sort_array(c))
print(search_array(f, 6.3))
| true |
07dbb495e7352e9db8db23faf35b70bd23370829 | fabiano-palharini/python_codes | /Set Mutations.py | 929 | 4.3125 | 4 | We can use the following operations to create mutations to a set:
.update() or |=
Update the set by adding elements from an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.update(R)
>>> print H
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
.intersection_update() or &=
Update the set by keeping only the elements found in it and an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.intersection_update(R)
>>> print H
set(['a', 'k'])
.difference_update() or -=
Update the set by removing elements found in an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.difference_update(R)
>>> print H
set(['c', 'e', 'H', 'r'])
.symmetric_difference_update() or ^=
Update the set by only keeping the elements found in either set, but not in both.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.symmetric_difference_update(R)
>>> print H
set(['c', 'e', 'H', 'n', 'r', 'R']) | true |
f09108e9869d81c73418e56475a4a15cdd36d385 | Gabriel300p/Computal_Thinking_Using_Python_Exercicios | /Exercicios Extras/exercicio02.py | 284 | 4.125 | 4 | num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
divisao = num1 % num2
if divisao >= 1:
print("O primeiro número não é divisível pelo segundo número")
else:
print("O primeiro número é divisível pelo segundo número")
| false |
b9261fa4fb3a4c4fa4240be7563350420378c702 | Showbiztable/Pense_Python | /exercicio5_2.py | 671 | 4.4375 | 4 | """
Escreva uma função chamada check_fermat que receba quatro parâmetros -a, b, c, n - e verifique se o teorema de
Fermat se mantém.
Escreva uma função que peça ao usuário para digitar valores para a, b, c e n, e os conveta em números inteiros e
use check_fermat para verificar se violam o teorema de Fermat.
"""
def check_fermat(a, b, c, n):
fermat = a**n + b**n
if n > 2 and fermat == c**n:
print('Holy smokes, Fermat was wrong!')
else:
print("No, that doesn't work")
a, b, c, n = input('Digite os valores de - a, b, c e n - nesta ordem e com espaço: ').split(' ')
check_fermat(int(a), int(b), int(c), int(n))
| false |
7ec319e58c79d8ea1195759670e7fe87a8e8dd69 | juiceinc/devlandia | /jbcli/jbcli/utils/format.py | 1,672 | 4.15625 | 4 | """Provides standardized methods and colors for various console message
outputs.
"""
from click import secho
from datetime import datetime, timedelta
from humanize import naturaltime
def echo_highlight(message):
"""Uses click to produce an highlighted (yellow) console message
:param message: The message to be echoed in the highlight color
:type message: str
"""
return secho(message, fg='yellow', bold=True)
def echo_warning(message):
"""Uses click to produce an warning (red) console message
:param message: The message to be echoed in the warning color
:type message: str
"""
return secho(message, fg='red', bold=True)
def echo_success(message):
"""Uses click to produce an success (green) console message
:param message: The message to be echoed in the success color
:type message: str
"""
return secho(message, fg='green', bold=True)
def human_readable_timediff(dt):
""" Generate a human readable time difference between this time and now
:param dt: datetime we want to find the difference between current time
:type dt: datetime
"""
return naturaltime(datetime.now() - dt)
def compare_human_readable(old, new):
""" Compare the difference in age between 2 human readable times
:param new: human readable diff sliced into list to be [ number, date operand ]
:param old: same as param new but older
"""
now = datetime.now()
if new[1] == 'months':
new[1] = 'weeks'
new[0] = int(new[0])/4
old_date = now - timedelta(**{old[1]:int(old[0])})
new_date = now - timedelta(**{new[1]: int(new[0])})
return abs(old_date - new_date)
| true |
97771cbe16d508d94be0453859c8886e824a085e | Reikon95/PythonPracticeDump | /RangesAndLists.py | 262 | 4.21875 | 4 | list1 = range(5, 15, 3)
#creates a range where you start from 5 (first param), end at 14 (one less than second param) and only count every third number (third param)
print(list(list1))
#prints it as a list, otherwise it'll just print range(5, 15, 3) literally
| true |
a2d5a7f8e1f5a912fcc9f07ec80e4f76f806abe9 | AcnoAamir/MyCap_Python | /MyCap_Python/area.py | 542 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Acno-Aamir
"""
r=float(input("Enter the radius of the circle to find area for "))
# pi=3.14159265358979323846
# area=pi*r*r
while(r<=0):
print("Error, radius is incorrect please try again")
r=float(input("Enter the radius of the circle to find area for "))
print("The area of circle with radius ",r," is ",(3.14159265358979323846*r*r)," sq units")
#Additional, perimeter of the circle
print("The perimeter of circle with radius ",r," is ",(2*3.14159265358979323846*r)," units")
| true |
fb3853db8268cd92ea29dd899008c958d4b46bbe | Newton-Figueiredo/PluralsightClass | /Cap 3,4/tipos_operadores_controlesdefluxo01.py | 1,840 | 4.3125 | 4 | #------OVERVIEW---------
#inteiro
10
#chamando um numero binario (0b)
0b10
#chamando um numero hexadecimal (0x)
0x10
#covertendo variavel em inteiro (int()):
int(3.5)
#covertendo variavel em decimal (float()):
float(3)
#escrevendo em notação cientifica (e):
3e8
1.61e-5
#operador none:
a = None
a == None
a
#operadores logicos: True e False
bool(0) #apenas zero é considerado falso
bool(10)
bool(-10)
bool(0.0)
bool(0.225)
bool("") #apenas strings vazias é considerado falso
bool([]) #apenas listas vazias é considerado falso
bool([1,2,3])
bool("False")
#--------RELATIONAL OPERATOR --------
"""
== igualdade:
!= diferente:
< menor que:
> maior que:
<= menor e igual a que:
>= maior e igual a que:
"""
g=20 # atribuindo
g == 20 # verdade
g ==13 # falso
g != 13 # verdade
g < 30 # verdade
g <= 20 # verdade
g > 30 # falso
#-------------- CONTROL FLOW ---------------
# if expressao:
# bloco com comando
if True:
print("é verdadeiro!")
if bool("ovos"):
print("sim, por favor !")
h=42
if h > 50:
print("Maior que 50")
else:
print("50 ou menor")
if h > 50:
print("Maior que 50")
else:
if h < 20:
print("Menor que 20")
else:
print("entre 20 e 50")
if h > 50:
print("Maior que 50")
elif h < 20:
print("Menor que 20"))
else:
print("entre 20 e 50")
# --------------------- WHILE-LOOPS ---------------
# while expressao:
# bloco de codigo
#obs : a expressao que fica no while se torna numa condição booleana e enquanto verdadeira roda o codigo
c=5
while c != 0:
print(c)
c -= 1
# outra forma de fazer o loop devido a expressao ser booleana
c=5
while c :
print(c)
c -= 1
# chegaremos no mesmo resultado porque a variavel só se torna falsa quando ela chega a "zero"
while True:
r=input()
if int(r)%7==0:
break
| false |
bd4ac597c89160b8206bb86a7ed39b70b56a9103 | Newton-Figueiredo/PluralsightClass | /Cap 3,4/for-loop.py | 820 | 4.15625 | 4 | '''
esse loop é maravilhoso ele precisa de um item e um iteravel para funcionar
exemplo:
for "item" in "iteravel":
print(item)
#essas ("") nao sao usadas no laço é so pra diferenciar o comando da variavel.
vamos ver na pratica varios exemplos:
'''
a=["laranja","maça","abacaxi"]
b=[1,3,7]
contatos={"danielle":"998455653","larissa":"987856365","joyce":"985842210"}
for iten in a:
print(iten)
for itens in b:
print(itens*3)
for pessoas in contatos:
print(pessoas,contatos[pessoas])
#------------------ Botando Tudo Junto !!!!! ---------------------
from urllib.request import urlopen
story=urlopen("http://sixty-north.com/c/t.txt")
story_words=[]
for line in story:
line_words=line.decode("utf8").split()
for word in line_words:
story_words.append(word)
story.close()
| false |
0d1fcbc15f8aacfe4e30b09a5bebfaade8d025e5 | Newton-Figueiredo/PluralsightClass | /Cap 3,4/lists.py | 488 | 4.3125 | 4 | #-------------- listas --------------------
'''
- listas sao mutaveis
- trabalham como uma sequencia de objetos
'''
a=["laranja","maça","abacaxi"]
b=[1,3,7]
print(a[0])
print(a[1])
a[0]=5
print(a)
#-----------------------------------------------------------------------
print(100*"-")
#metodo para adicionar iteins a uma lista: append()
print(b)
b.append(50)
print(b)
#ciando listas de formas rapidas, metodo: list()
c=list("newtoncarvalho")
print(c)
d=list(range(1,6,1))
print(d)
| false |
51e53eed8df0fc1958acabec97ea37cd10efd3df | Shubhranshu-Malhotra/Learning-Python | /Oops_ex_1.py | 1,192 | 4.25 | 4 | # OOPS EXERCISE 1
# Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1) Instantiate the cat object with 3 cats.
cat1 = Cat('tin', 1)
cat2 = Cat('pin', 0.5)
cat3 = Cat('lin', 2)
# WAY 1
# 2) Create a function that finds the oldest cat
def get_oldest(cats):
oldest_cat = ''
highest_age = -1
for cat in cats:
if cat.age > highest_age:
highest_age = cat.age
oldest_cat = cat.name
return oldest_cat, highest_age
# 3) Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
oldest_cat, highest_age = get_oldest([cat1, cat2, cat3])
print(f"The oldest cat is {oldest_cat} and she is {highest_age} years old.")
# WAY 2
# 2) Create a function that finds the oldest cat
def get_oldest_2(*args):
# return max(args) # if taking just the ages as input
return max( e.age for e in args)
# 3) Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
highest_age = get_oldest_2(cat1, cat2, cat3)
print(f"The oldest cat is {highest_age} years old.") | true |
85f9d315c13b8afab24917580f16bd95145c94fe | SaretMagnoslove/learn_programming-Derek | /Python/video06/random_bubble.py | 504 | 4.21875 | 4 | import random
length_list = int(input('Enter length of random list: '))
random_list = []
for ii in range(length_list):
random_list.append(random.randint(1,9))
def bubble_sort(the_list):
size = len(the_list)
while size > 0:
for ii in range(size-1):
if the_list[ii]>the_list[ii+1]:
the_list[ii],the_list[ii+1] = the_list[ii+1],the_list[ii]
size -= 1
return the_list
def main():
print ('The sorted list is: ',bubble_sort(random_list))
main() | true |
1c6cb1a7b865b358fad69e47358cb61bdea256c5 | bruntime/Portfolio | /Challenges/Coder Byte/Python/Easy Difficulty/time_convert (CB).py | 409 | 4.15625 | 4 | # Convert number to time
# Example: if num = 63 then the output should be 1:3
# Separate the number of hours and minutes with a colon
def TimeConvert(num):
time = num/60
extra_minutes = num - (time * 60)
colon = ":"
zeros = ":00"
if extra_minutes > 0:
print "%d%s%d" %(time, colon, extra_minutes)
else:
print "%d%s" %(time, zeros)
user_time = int(raw_input("Number: "))
TimeConvert(user_time) | true |
a1fe137f75ea6b82d4f5920a66a1102f75094b77 | bruntime/Portfolio | /Challenges/Coder Byte/Python/Medium Difficulty/fibonacci_checker (CB).py | 828 | 4.34375 | 4 | # Program Name: Fibonacci Checker
# Task Description: If num is in Fibonacci sequence, return the string yes if the number given is part of the Fibonacci sequence. If num is not in the Fibonacci sequence, return the string no.
# Parameter: N/A
# Example: The first two numbers are 0 and 1, then comes 1, 2, 3, 5 etc.
def Fibonacci_Check(num):
#Starting numbers of Fibonacci series
list_nums = [0, 1]
a = -1
b = 0
while list_nums[-1] <= num:
a += 1
b += 1
#Fibonacci sequence produced
sum = list_nums[a] + list_nums[b]
list_nums.append(sum)
print list_nums
if num not in list_nums:
print 'no'
else:
print 'yes'
user_num = int(raw_input("Check if what number is in Fibonacci series: "))
Fibonacci_Check(user_num)
#http://www.coderbyte.com/CodingArea/Editor.php?ct=Fibonacci%20Checker&lan=Python | true |
241ef70837cc2ccbc6769f67f170faa6bb1d3a5a | GuilletThomas/csi2_tp12 | /ex1.py | 220 | 4.15625 | 4 | def modulo(x,y):
"""Computes x % y recursively """
if x < y:
return x
else:
return modulo(x - y, y)
print(modulo(6,13)) #6
print(modulo(37,10)) #7
print(modulo(8,2)) #0
print(modulo(50,7)) #1 | false |
4398a2c7860ad339951c1c63d46d0ec37533c856 | kmcrayton7/python_coding_challenges | /programmr/variables/more_user_input_of_data.py | 409 | 4.3125 | 4 | # The user is asked for several pieces of information. Display it on the screen as a summary.
name = raw_input("What's your name?: ")
age = raw_input("How old are you?: ")
college = raw_input("What college do you attend?: ")
major = raw_input("What's your major?: ")
print "Hello %s, you told me that you are %s years old. You are currently attending %s and your major is %s." % (name, age, college, major)
| true |
ea181390b113ed045dc3024d869434d67ab23d61 | chadat23/learn_tkinter | /entry_widget.py | 361 | 4.28125 | 4 | from tkinter import *
root = Tk()
# e = Entry(root)
e = Entry(root, width=50, bg='blue', fg='white', borderwidth=5)
e.pack()
e.insert(0, 'Enter your name:')
def when_clicked():
my_label = Label(root, text=f'Hello {e.get()}!')
my_label.pack()
my_button = Button(root, text='Enter your name', command=when_clicked)
my_button.pack()
root.mainloop()
| true |
8240d8106d20da4411813a6d92feeaf3e366b910 | jfidelia/python_master | /exercises/11-Swap_digits/app.py | 266 | 4.1875 | 4 | #Complete the fuction to print the swapped digits of a given two-digit-interger.
def swap_digits(num):
a = num // 10
b = num % 10
c = (b * 10) + a
print(c)
#Invoke the function with any two digit interger as its argument
swap_digits(92)
| true |
a03d6f7d1d954d85a2d4a3162f3d26961b1052b2 | jfidelia/python_master | /exercises/15-Digit_after_decimal_point/app.py | 252 | 4.15625 | 4 | #Complete the function to print the first digit to the right of the decimal point.
#Hint: Import the math module.
def first_digit(num):
print(int(float(num * 10) % 10))
#Invoke the function with a positive real number. ex. 34.33
first_digit(1.79) | true |
220157a1e6b7faf4481ad20aee50a1b53ff47083 | rajeswari-namana/PythonCSAssignments | /Lab4/Source/OrderedDict.py | 310 | 4.15625 | 4 | #Initialising a dictionary
d={1:'raji',2:'swetha',3:'jo',4:'lv'}
#converting dictionary items into list to make it an oreder dictionary.
d1=list(d.items())
#Accesing dictionary items by index.
print("1st item is:", d1[0])
print("2nd item is:", d1[1])
print("3rd item is:", d1[2])
print("4th item is:", d1[3])
| false |
5ee9eafcf1322858031bc9ecb4b0cb822ece3946 | derrickmstrong/python_fcc | /basics/smallestnum.py | 225 | 4.15625 | 4 | # Find smallest num in loop using None and is
smallest = None
for num in [2,5,8,1,89,34,11,6,7]:
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print('Smallest num:', smallest) | true |
4fea34d2bf912c8f54752812c3c14755e08c9242 | dchlebicki/tgm-assignments | /16-17/thread_sync_queue/queuesync.py | 2,608 | 4.15625 | 4 | import threading
import queue
import math
class Producer(threading.Thread):
"""
Producer searches for prime numbers in a certain range and writes them into a queue.
"""
def __init__(self, queue, start_num, end_num):
"""
Initializes the super class and some variables
:param queue: the queue
:param start_num: the start number of the number range
:param end_num: the end number of the number range
"""
threading.Thread.__init__(self)
self.queue = queue
if start_num < 3:
print("Start number can't be smaller than 3, starting from 3")
self.start_num = 3 # starting from the smallest possible prime number
else:
self.start_num = start_num
self.end_num = end_num
def run(self):
"""
Searches for prime numbers and writes them into a queue
:return: None
"""
count = self.start_num
while True:
is_prime = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
is_prime = False
break
if is_prime:
self.queue.put(count)
self.queue.join()
if count >= self.end_num:
break
count += 1
self.queue.join()
self.queue.put("eof") # tells the Consumer that no more numbers are coming
class Consumer(threading.Thread):
"""
Reads numbers out of the queue, prints them in the console and writes them in a simple text file.
"""
def __init__(self, queue, file):
"""
Initializes the super class and some variables
:param queue: the queue
:param file: the writable text file
"""
threading.Thread.__init__(self)
self.queue = queue
self.file = file
def run(self):
"""
Reads numbers out of a queue, prints them in the console and writes then in a simple text file.
:return: None
"""
while True:
number = self.queue.get()
if number == "eof":
self.file.close()
break
print(str(number))
self.file.write(str(number) + "\n")
self.queue.task_done()
queue = queue.Queue()
file = open("prime.txt", "w")
start_num = int(input("start: "))
end_num = int(input("end: "))
producer = Producer(queue, start_num, end_num)
consumer = Consumer(queue, file)
producer.start()
consumer.start()
producer.join()
consumer.join()
| true |
2ffebf442a3bfef0f36b62278374dd1d19348627 | nagula-ritvika/Algorithms-Practice | /Arrays/Sorting/sort_colors.py | 954 | 4.34375 | 4 | #__author__ = ritvikareddy2
#__date__ = 2019-02-16
def sortColors(nums):
"""
Given an array with n objects colored red, white or blue, sort them in-place so that objects
of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
red, white, blue = 0, 0, len(nums) - 1
while white <= blue:
# if there is red in white's place
if nums[white] == 0:
nums[white], nums[red] = nums[red], nums[white]
white += 1
red += 1
elif nums[white] == 1:
white += 1
else:
nums[white], nums[blue] = nums[blue], nums[white]
blue -= 1
return nums
if __name__ == '__main__':
print(sortColors([1, 2, 0]))
| true |
e3a498a5d01e079a0f411b39d211fe1cb16bf728 | nagula-ritvika/Algorithms-Practice | /Arrays/Sorting/BubbleSort.py | 370 | 4.125 | 4 | #__author__ = ritvikareddy2
#__date__ = 2019-01-24
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j+1] < arr[j]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
if __name__ == '__main__':
A = [3, 45, 7, 8, 1]
print(bubbleSort(A)) | false |
c43c9816ec84915bfaac1199dc8326550379d841 | Vakicherla-Sudheethi/19A91A0559_II-CSE-A_IVSem_Python-lab_1-to-5 | /6)data structure-continued-(6.2) | 676 | 4.1875 | 4 | """
Implement a Python script to rotate list of elements towards right up to given number of times.
Example: Input: [23,34,9,45,19] and 2 (Hint: 2 indicates No. of times to rotate) Output: [45,19,23,34,9]
"""
n1=int(input("Enter how many list of values"))
list_number=[]
n=int(input("enter the no of rotations"))
#read list of values from user
for i in range(n1):
num=int(input())
#append number to list data structure
list_number.append(num)
print(list_number)
list_number = (list_number[-n:] + list_number[:-n])
print(list_number)
#output
"""Enter how many list of values5
enter the no of rotations2
14
15
75
10
25
[14, 15, 75, 10, 25]
[10, 25, 14, 15, 75]"""
| true |
22645adfaae5f7a86e28aa938dd07a6cd1f2f275 | RajatPrakash/Python_Journey | /oop_class_question.py | 607 | 4.5625 | 5 | # 1 Instantiate the Cat object with 3 cats
# 2 Create a function that finds the oldest cat
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
obj1 = Cat('minks', 2)
obj2 = Cat('ryalie', 3.5)
obj3 = Cat('Mandrine', 5)
print(obj1.name, obj1.age)
print('\n')
print(obj2.name, obj2.age)
print('\n')
print(obj3.name, obj3.age)
print('\n')
def old_cat(*args):
return max(args)
print(f'Oldest cat is {old_cat(obj1.age, obj2.age, obj3.age)} year old')
| true |
55ab46eea597a18ca59ae69b38b4f82fec8ab9d1 | RajatPrakash/Python_Journey | /Query 4.py | 594 | 4.1875 | 4 | # Question: write a code that takes an input from the user and indicates its number of digits
user_input = int(input('Enter your number: '))
# there are may ways to solve this problem
# first way converting it into string and then using a flag
# user_input = str(user_input)
# count = 0
# for i in user_input:
# count += 1
# print(count)
#
# # second way using length funtion on string
#
# print(len(user_input))
# third way
flag = 0
while user_input > 0:
if user_input > 0:
user_input = int(user_input / 10)
flag +=1
print('Number of digits in your input', flag)
| true |
e4148a9d2c119fe296df91315c1eabe16795007a | likhitha477/Learning_Python | /Array_using_NumPy.py | 924 | 4.25 | 4 | #Python Tutorial for Beginners - Telusko
from numpy import *
arr = array([1,2,3,4,5])
print(arr.dtype) #in array, all the elements are of same type.
#linspace
arr1 = linspace(0,16,10) #16 would be included and 10 is the number of elements printed.
print(arr1)
arr2 = linspace(0,15) #creates 50 elements as default.
#arange
arr3 = arange(1,15,3) #3 is the step size
print(arr3)
#logspace
arr4 = logspace(1,40,5) #the spacing between 1 and 50 depends on log of 5.
print(arr4)
print('%.2f' %arr4[4])
#zeros
arr5 = zeros(5)
print(arr5) #prints float values.
#ones
arr6 = ones(5)
print(arr6)
#copying an array
arr9 = array([2,6,8,1,3])
arr10 = arr9.copy() #deep copy. 2 different arrays with different addresses.
arr9[1] = 7
print(arr9)
print(arr10)
print(id(arr9))
print(id(arr10))
#adding an array
arr = arr + 5
print(arr)
arr7 = array([5,1,2,8,4])
arr8 = arr + arr7
print('arr8',arr8)
print('max of arr8',max(arr8))
| true |
1a9615b2f20d3586d52c5517267bd78fee422e99 | paulnguyen/code | /python/introduction/07.funcs.py | 1,172 | 4.75 | 5 |
# https://pythonprogramming.net/introduction-to-python-programming
# Here we've called our function example. After the name of the function, you
# specify any parameters of that function within the parenthesis parameters
# act as variables within the function, they are not necessary to create a
# function, so first let's just do this without any parameters.
def example():
print('this code will run')
z = 3 + 9
print(z)
example()
# The idea of function parameters in Python is to allow a programmer who is
# using that function, define variables dynamically within that function. For
# example:
def simple_addition(num1,num2):
answer = num1 + num2
print('num1 is', num1)
print(answer)
simple_addition(5,3)
# When using defaults, any parameters with defaults should be the last ones
# listed in the function's parameters.
def simple(num1, num2=5):
pass
# This is just a simple definition of a function, with num1 not being pre-
# defined (not given a default), and num2 being given a default.
def basic_window(width,height,font='TNR'):
# let us just print out everything
print(width,height,font)
basic_window(350,500)
| true |
1b049676c8a9eacd667d08621abfabd342b32784 | paulnguyen/code | /python/introduction/18.dicts.py | 907 | 4.1875 | 4 |
# https://pythonprogramming.net/introduction-to-python-programming
# Dictionaries are a data structure in Python that are very similar to
# associative arrays. They are non-ordered and contain "keys" and "values."
# Each key is unique and the values can be just about anything, but usually
# they are string, int, or float, or a list of these things. Dictionaries are
# defined with {} curly braces.
# Dictionary of names and ages.
exDict = {'Jack':15,'Bob':22,'Alice':12,'Kevin':17}
print(exDict)
# How old is Jack?
print(exDict['Jack'])
# We find a new person that we want to insert:
exDict['Tim'] = 14
print(exDict)
# Tim just had a birthday though!
exDict['Tim'] = 15
print(exDict)
# Then Tim died.
del exDict['Tim']
print(exDict)
# Next we want to track hair color
exDict = {'Jack':[15,'blonde'],'Bob':[22, 'brown'],'Alice':[12,'black'],'Kevin':[17,'red']}
print(exDict['Jack'][1])
| true |
5604d436bd487b63fc1aeae1bbfb8c7b75e2b139 | paulnguyen/code | /python/introduction/21.mathplot4.py | 2,439 | 4.59375 | 5 |
# https://pythonprogramming.net/introduction-to-python-programming
# https://pythonprogramming.net/matplotlib-python-3-basics-tutorial/
# https://pythonprogramming.net/matplotlib-graphing-series/
# https://pythonprogramming.net/matplotlib-intro-tutorial/
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
# Up to this, everything is about the same, but now you can see we've added
# another parameter to our plt.plot(), which is "label." Just to clarify, for
# those who are not yet totally comfortable with the notion of default
# parameters in functions, some people may be curious about why we are able to
# plot the x, y, and color variable without any sort of assignment, but then
# we have to assign label and linewidth. The main reason here is because there
# are many parameters to pyplot.plot(). It is really easy to forget their
# order. X, y, and color is fairly easy to remember the order, people are good
# at remembering orders of three. After that, the chances of forgetting the
# proper order get quite high, so it just makes sense. There are also many
# parameters to edit, so we just call them specifically. Anyway, we can see
# here that we added a "label," so matplotlib knows what to call the line.
# This doesn't quite yet give us a legend, however. We need to call
# plt.legend(). It's important to call legend AFTER you've plotted what you
# want to be included in the legend.
plt.plot(x,y,'g',label='line one', linewidth=5)
plt.plot(x2,y2,'c',label='line two',linewidth=5)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.legend()
plt.grid(True,color='k')
plt.show()
# Okay, well that's good enough for linear charts I'd say. Keep in mind what I
# was saying about how matplotlib first "draws" things to a canvas, then
# finally shows it. Things like legends are drawn when you call them, so, if
# you are using, say, subplots, and call legends at the very end, only the 2nd
# subplot would have a legend. If you wanted a legend on each subplot, then
# you would need to call it per subplot. This is the same with titles! But
# hey, I didn't even cover subplots (multiple graphs on the same "figure,"
# which just means the same window)... if you are curious about those, check
# out the in-depth Matplotlib tutorial series, or the specific matplotlib
# subplots tutorial.
| true |
5c5e8a9f21e47923c021835db50639e0730497ea | dannyhsdl/mypython | /ex16.py | 2,638 | 4.71875 | 5 | # coding=utf-8
# what this program do is to creat a text file and write something into it just like we do it directly
# But here we do it by a program (or codes)
# So,let's get started.
from sys import argv # import argv module
script,filename=argv #unpack Two arguments one is script name the another is file name.
print("We're going to erase %r."% filename) # print the name of the file.
print("If you don't want that,hit Ctrl-C(^C).") # you can type Ctrl-C to stop the procedur
print("If you do want taht, hit RETURN.") # recomemd you to type RETURN if want to continue
input("?") # here you can type Ctrl-C or RETURN, it's up to you.
print("Opening the file...") # recomemd you that the program s opening the file.
target= open(filename,'w') # this is a opreation to open the file by writing. And then save the option
print("Truncating the file. Goodbye!")
target.truncate() # no return value
print("Now I'm going to ask you for three lines.") # recomemd you to input some information
line1= input("line 1: ") # this is a option, which means you gotta input something,then you input something
line2= input("line 2: ") # remember you do this thing in a terminal window, instead of a notebook.
line3= input("line 3: ") # by the way this option will be saved.
print("I am going to write these to the file.") # recomemd you that the program will write there stuff to
# the file, just like you write it down on the notebook. Hopefully, the program helps you to write it to
# the file, not you
target.write(line1) # a option, which writes the stuff to the file.
target.write("\n") # return
target.write(line2) # here the same way
target.write("\n") # return
target.write(line3) # same way
target.write("\n") # return
print("And finally, we close it.") # the program recomemds you the file is gonna be closed
target.close() # close the file.
# it seems confusing,huh. But here I am gonna tell you the details.
# we imported a module call argv
# we created a script called ex16.py, and we created text file called test.txt(but there wassn't a file
# called test.txt) ex16.py and text.txt are 2 arguments which are invovel in the argv, import them to argv
# then unpack
# recomemd you erase the file.
# recomemd you that it's your choice to stop or continue(the procedur)
# type Ctrl-C to stop or RETURN to continue
# Open the file by writing, and then save it.
# Then truncating the file
# Ask you to input information
# ......
# Write the information to the file
# And finally, we close the file.
# So, this is the steps
# You can check the text file which in the floser | true |
c3694333da00d4da80763ae61f85a5ce64ba3c27 | kcmeehan/Algorithms1 | /exampleKaratsuba.py | 1,603 | 4.25 | 4 | #!/usr/bin/python
# This example is from https://pythonandr.com/2015/10/13/karatsuba-multiplication-algorithm-python-code/
import sys
def exampleKaratsuba(x,y):
"""Function to multiply 2 numbers in a more efficient manner than the grade school algorithm"""
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
n = max(len(str(x)),len(str(y)))
nby2 = n / 2
a = x / 10**(nby2)
b = x % 10**(nby2)
c = y / 10**(nby2)
d = y % 10**(nby2)
ac = exampleKaratsuba(a,c)
bd = exampleKaratsuba(b,d)
ad_plus_bc = exampleKaratsuba(a+b,c+d) - ac - bd
# this little trick, writing n as 2*nby2 takes care of both even and odd n
prod = ac * 10**(2*nby2) + (ad_plus_bc * 10**nby2) + bd
return prod
#***********************************************************************************************************
#-----------------------------------------------------------------------------------------------------------
# Starting Program that accepts two numbers and returns their product calculated via the Karatsuba algorithm
#-----------------------------------------------------------------------------------------------------------
#***********************************************************************************************************
if len(sys.argv) != 3:
print "ERROR: Incorrect number of arguments! Please pass two numbers. Try again."
else:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
product = exampleKaratsuba(num1, num2)
if product >= 0: print str(num1)+" * "+str(num2)+" = "+str(product)
| false |
a1156aaf2406e9cf47d1655f182d703567a6e33a | rkildea1/bi-and-tri-gram-builder | /tokenizor.py | 1,641 | 4.15625 | 4 |
f = open('Moby_dick.txt', 'r+')
words1 = f.read()
q3_words_list = words1.split()
def bigram(file,n=2,i=0):
while len(file[i:i+n]) == n:
yield file[i:i+n]
i += 1
bigrams_lists = list(bigram(q3_words_list, n=2)) #this is my bigram list. list inside a list
#print(bigrams_lists)
bigrams_2 = []
for il in bigrams_lists: #for inner list in
bigrams_2.append((il[0],il[1]))
#print(bigrams_2)
my_dict_il = {} #create a blank dictionary to write the word list to
for item in bigrams_2:
if item in my_dict_il.keys(): #if the word in the wordlist is already a key in the dictionary then...
my_dict_il[item]+=1 #increase the count by one
else:
my_dict_il[item]=1 #add to dictionary and make count 1
#print(my_dict_il)
def top_word_BOW(n):
bow_list = [] #making the dictionary a list so create a blank list
for key, value in n.items(): #for every key/ value in the dictionary..
vk = (value, key) #store each value and key in opposite order in a variable
bow_list.append(vk) #write each value and key to the new list
bow_list = sorted(bow_list) #sort the list
#bow_list = sorted(bow_list, reverse=True) #reverse sort
top_word = bow_list[-1] #create varviable from the last item in the list (which is the now highest dict item)
top_word = list(top_word) #make that pair a list type
print ("The most frequent word occuring in the text is: ", top_word[1]) #print the second item in the ist (i.e., the word)
print ("The most frequent word occurs the following number of times:", top_word[0])
top_word_BOW(my_dict_il) #call the function
| true |
ad224c3e64b61f267b4b93c5a17523138112effd | theperson60/Script-Programming | /Week 10 Projects/Project #1.py | 1,104 | 4.90625 | 5 | #Define a function drawCricle. This function should expect a Turtle object,
#the coordinates of the circle's center point, and the circle's radius as arguments.
#The function should draw the specified circle. The algorithm should draw the circle's
#circumference by turning 3 degrees and moving a given distance 120 times. Calculate
#the distance moved with the formula 2.0 * pi * radius / 120.0
import turtle
import math
def drawCircle(t, x, y, radius):
#Calculate distance
distance = 2.0 * math.pi * radius / 120.0
#Move pointer to x and y coordinates
t.penup()
t.setposition(x, y)
#Pen back down so it can draw
t.pendown()
for k in range(120):
#Go forward distance and turn 3 degrees each iteration
t.forward(distance)
t.right(3)
def main():
#Get info from user
x = int(input("Enter the x coordinate: "))
y = int(input("Enter the y coordinate: "))
radius = int(input("Enter the radius: "))
t = turtle.Turtle()
#Call drawCircle function
drawCircle(t, x, y, radius)
main()
| true |
7a899058ba2e1b5fa313867a03162dd69fd4f45f | patLoeber/python_practice | /data_structures/linked_list_circular.py | 2,073 | 4.15625 | 4 | class Empty(Exception):
pass
class LinkedListQueueCircular():
# queue implementation using a circular linked list for storage
# use a tail pointer that points to the first element in the queue
# implement a rotate method that rotates the front element to the back of the queue
class _Node():
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._tail = None
self._size = 0
def __len__(self):
return self._size
def __repr__(self):
if self.is_empty():
return '[]'
string = ''
current = self._tail._next
for i in range(self._size):
string += str(current._element) + ' '
current = current._next
string = string[:len(string)-1]
return '[' + string + ']'
def is_empty(self):
return self._size == 0
def first(self):
if self.is_empty():
raise Empty('queue is empty')
head = self._tail._next
return head._element
def dequeue(self):
if self.is_empty():
raise Empty('queue is empty')
old_head = self._tail._next
if self._size == 1:
self._tail = None
else:
self._tail._next = old_head._next
self._size -= 1
return old_head._element
def enqueue(self, e):
new = self._Node(e, None)
if self.is_empty():
new._next = new
else:
new._next = self._tail._next
self._tail._next = new
self._tail = new
self._size += 1
def rotate(self):
# rotate front element to the back of the queue
if self._size > 0:
self._tail = self._tail._next
q = LinkedListQueueCircular()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
print(q)
d = q.dequeue()
print('dequeue:', d)
print(q)
print('rotate...')
q.rotate()
print(q)
q.enqueue(5)
print(q)
d = q.dequeue()
print('dequeue:', d)
f = q.first()
print('first:', f)
print(q)
| true |
133f112f0e7a20568e753c19fc61bfa9aef7b12f | Alexander-Cardona-Herrera/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 476 | 4.125 | 4 | #!/usr/bin/python3
"""
For this funtion you can't use any type of characters bisides str.
last_name is empty by default.
"""
def say_my_name(first_name, last_name=""):
"""
Print the string <first_name> and <last_name>.
"""
if type(first_name) != str:
raise TypeError("first_name must be a string")
if type(last_name) != str:
raise TypeError("last_name must be a string")
print("My name is {:s} {:s}".format(first_name, last_name))
| true |
7cdcbbac0bb4e372627c3f8409a36984c0b36a7b | JoshuaPedro/python-1.4 | /triangle.py | 898 | 4.125 | 4 | #triangle.py
#1/18/19
#by Josh Pedro
import math
from math import *
from graphics import *
def main():
win = GraphWin('rectangle',400,400)
print("click the window three times")
p1 = win.getMouse()
p2 = win.getMouse()
p3 = win.getMouse()
x1 = p1.getX()
y1 = p1.getY()
x2 = p2.getX()
y2 = p2.getY()
x3 = p3.getX()
y3 = p3.getY()
l1 = Line(Point(x1,y1), Point(x2,y2))
l2 = Line(Point(x2,y2), Point(x3,y3))
l3 = Line(Point(x3,y3), Point(x1,y1))
dx1 = x2-x1
dx2 = x3-x2
dx3 = x1-x3
dy1 = y2-y1
dy2 = y3-y2
dy3 = y1-y3
a = sqrt(dx1**2 + dy1**2)
b = sqrt(dx2**2 + dy2**2)
c = sqrt(dx3**2 + dy3**2)
s = (a + b + c)/2
area = sqrt(s*(s-a)*(s-b)*(s-c))
print("the area of the Trihangle is",area)
print(p1)
print(p2)
print(p3)
print(s)
l1.draw(win)
l2.draw(win)
l3.draw(win)
main()
| false |
0f3e0c8a8243c886764e0b487561d5bc9336e73e | snehaltandel/generic_code | /square_root.py | 1,164 | 4.1875 | 4 | '''
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example,
if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
import math
def square_root(a):
for i in range(len(a)):
n = math.sqrt(a[i])
return round(n,2)
def agg(d, C=50, H=30):
final_result = []
for j in range(len(d)):
D = d[j]
final_result.append(square_root([(2*C*D)/H]))
j+=1
return final_result
''' Yet to make it accept value from console.
On doing that, the add method doesn't return results.
Working on it'''
# This way works
a = [12,34,23]
print(agg(a))
| true |
028050c5ae4c2e9d824d67732e8596cf0a4b915a | jordanmd/pythonthehardway | /ex4.py | 847 | 4.375 | 4 | #!/usr/bin/python
#set how many cars we have
cars = 100
# Each car can hold this many passengers
space_in_a_car = 4.0
# We have this many drivers todau
drivers = 30
# ...and this many passengers.
passengers = 90
# Calculate how many cars won't be driven today
cars_not_driven = cars - drivers
# The number of drivers equals the number of cars driven
cars_driven = drivers
# Calulate the total carpool capacity
carpool_capacity = cars_driven * space_in_a_car
# Calculate average passengers per car
average_passengers_per_car = passengers / cars_driven
print "There are:", cars , "cars available."
print "There are only", drivers ,"drivers available."
print "There will be", cars_not_driven ,"empty cars today."
print "We can transport", carpool_capacity ,"people today."
print "We need to put about", average_passengers_per_car , "in each car." | true |
9e31e11b2e81967f3e5460d969d99b2f8a673bbf | sudiptog81/ducscode | /YearII/SemesterIII/ProgrammingInPython/Practicals/letterFreq/main.py | 734 | 4.3125 | 4 | '''
Write a function that takes a sentence as input from the
user and calculates the frequency of each letter. Use a
variable of dictionary type to maintain the count.
Written by Sudipto Ghosh for the University of Delhi
'''
def frequencies():
'''
Prints the frequency of each letter in a sentence.
'''
freq = dict()
sentence = input('Enter a Sentence: ')
for letter in sentence:
if not letter.isalpha():
continue
if letter not in freq:
freq[letter] = 1
else:
freq[letter] += 1
print('Frequencies: ')
for letter in freq:
print(f'{letter} => {freq[letter]}')
if __name__ == "__main__":
frequencies()
| true |
46a29d9a375613ab67af92c1604240deb0773e6c | sudiptog81/ducscode | /YearII/SemesterIII/ProgrammingInPython/Practicals/salesRemarks/main.py | 2,130 | 4.1875 | 4 | '''
Consider a showroom of electronic products, where there are various salesmen.
Each salesman is given a commission of 5%, depending on the sales made per
month. In case the sale done is less than 50000, then the salesman is not
given any commission. Write a function to calculate total sales of a salesman
in a month, commission and remarks for the salesman. Sales done by each
salesman per week is to be provided as input. Use tuples/list to store data
of salesmen.
Assign remarks according to the following criteria:
Excellent: Sales >=80000
Good: Sales>=60000 and <80000
Average: Sales>=40000 and <60000
Work Hard: Sales < 40000
Written by Sudipto Ghosh for the University of Delhi
'''
def calculateRenumeration(n):
'''
Calculates sales, commission and determines
the remarks for n salesmen
Accepts:
n {int} -- number of salesmen
'''
s = 0
salesmen = []
for i in range(1, n + 1, 1):
salesman = [0, 0, '']
print(f'\nSalesman {i}')
print('============')
for j in range(1, 5, 1):
s = float(input(f'Enter Sales in Week {j}: '))
assert s >= 0, 'invalid entry'
salesman[0] += s
if salesman[0] > 50000:
salesman[1] = 0.05 * salesman[0]
if salesman[0] >= 80000:
salesman[2] = 'Excellent'
elif salesman[0] >= 60000:
salesman[2] = 'Good'
elif salesman[0] >= 40000:
salesman[2] = 'Average'
elif salesman[0] < 40000:
salesman[2] = 'Work Hard'
salesmen.append(salesman)
print()
for i in range(1, n + 1, 1):
print('''
Salesman %d Summary
================================
Total Sales: %10.2f
Total Commission: %10.2f
Remarks: %10s
''' % (i,
salesmen[i - 1][0],
salesmen[i - 1][1],
salesmen[i - 1][2]))
def main():
n = 0
n = int(input('Enter Number of Salesmen: '))
calculateRenumeration(n)
if __name__ == '__main__':
main()
| true |
c0deef545641d3cf3d332ff244e6ddc1ecac9a4c | subho781/MCA-python-assignment-6 | /Q2.py | 306 | 4.25 | 4 | '''Write a function that takes a sentence as an input
parameter and displays the number of words in the
sentence'''
test_string = "This is Python Programming assignment"
print ("The original string is : " + test_string)
res = len(test_string.split())
print ("The number of words : " + str(res))
| true |
36068833d8b3ee210d026e595637c21b6fce3f07 | vyasriday/Python | /beginner-programs/sets.py | 1,695 | 4.5625 | 5 | # IN THIS MODULE WE WILL STUDY sets.
t = set(tuple([1,2,3,4,4,4,4]))
print(t)
# sets in python works in the same way as sets in Math works
# Each element in set is immutable
p = {1,2,3,4,5,6,7,8,8}
print("Set p is ",p)
p.add(12)
print(p)
print(type(p))
p.remove(1)
print(p)
# remove produces key error if the element is not present in the list
# So we can also use dicard() methos which will silently ignore the keyerror
p.discard(12)
p.discard(12)
print(p)
# How to create an empty set . This can be done using set() constructor
empty_set = set()
print(empty_set)
for i in range(0,100,7):
empty_set.add(i)
print(empty_set) # Sets are unordered collections of elements
for i in empty_set:
print(i)
# Update Method can be used to add multiple elements from another set or tuple oe a list
t = (1,2,3,4,5)
print(type(t))
empty_set.update(t)
print(empty_set)
new_Set = empty_set.copy()
print(new_Set)
print(new_Set is empty_set)
# SET ALGEBRA
''' WE CAN USE SET UNION SET INTERSECTION METHODS ON SETS'''
x = {1,'Harry','Levester',0,10}
print(empty_set.union(x)) # Set operation is commutative
print(x.union(empty_set))
print(x.union(empty_set) == empty_set.union(x))
print(x.difference(empty_set)) # To find A-B OR B-A use difference method
print(x.intersection(empty_set))
# Use symmetric_difference() to explicitly find differece i.e elements in either A or B but not both
p = {1,2,3,4,5,6,7}
q = {2,3,10,11,12,15,0,0}
print(p.symmetric_difference(q))
# Using issubset() method to check whether one set is subset of another, issuperset() to check superset and isdisjoint() method to check disjoint sets
print(p.issubset(q))
print(p.issuperset(q))
print(p.isdisjoint(q)) | true |
8d9d8fe4835446b03d3fcb6f1dcba2009967279a | Prakashchater/Daily-Practice-questions | /Practice DS/Array/Max and MIn.py | 1,065 | 4.125 | 4 | def maxmin(array,left,right):
arr_max= left
arr_min= left
# array having only 1 number
if left==right:
arr_max=array[left]
arr_min=array[left]
return (arr_max,arr_min)
# array having 2 numbers
elif right==left+1:
if array[left]>array[right]:
arr_max=array[left]
arr_min=array[right]
else:
arr_max=array[right]
arr_min=array[left]
return (arr_max,arr_min)
# array having more than 2 number
else:
mid = int((left + right) / 2)
arr_max1, arr_min1 = maxmin(array,left,mid)
arr_max2, arr_min2 = maxmin(array,mid+1,right)
return (max(arr_max1, arr_max2), min(arr_min1, arr_min2))
if __name__ == '__main__':
array=[]
n=int(input("Enter the size of the array: "))
left=0
right=n-1
print("Enter the numbers:")
for i in range(n):
array.append(int(input()))
arr_max, arr_min = maxmin(array,left,right)
print("largest number: ", arr_max)
print("Smallest number: ",arr_min)
| true |
6a6eceedc276d49763f9a5c975c59e151daa88b9 | Prakashchater/Daily-Practice-questions | /Arrays/Waveform.py | 733 | 4.125 | 4 | def waveformarr(arr,n):
arr.sort()
for i in range(0,n-1,2):
arr[i],arr[i+1]=arr[i+1],arr[i]
arr=[10, 90, 49, 2, 1, 5, 23]
waveformarr(arr,len(arr))
for i in range(0,len(arr)):
print(arr[i],end=" ")
#
# # Python function to sort the array arr[0..n-1] in wave form,
# # i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
# def sortInWave(arr, n):
# # sort the array
# arr.sort()
#
# # Swap adjacent elements
# for i in range(0, n - 1, 2):
# arr[i], arr[i + 1] = arr[i + 1], arr[i]
#
# # Driver program
#
#
# arr = [10, 90, 49, 2, 1, 5, 23]
# sortInWave(arr, len(arr))
# for i in range(0, len(arr)):
# print (arr[i],end=" ")
#
# # This code is contributed by __Devesh Agrawal__
| false |
afbb07c93f59a636840b2db4e1caa46d0de55787 | Prakashchater/Daily-Practice-questions | /AlgoExpert/findThreeLargest.py | 760 | 4.125 | 4 | def find3largest(array):
threelargests=[None, None, None]
for num in array:
updateLargest(threelargests,num)
return threelargests
def updateLargest(threelargets,num):
if threelargets[2] is None or num > threelargets[2]:
updateAndShift(threelargets,num,2)
elif threelargets[1] is None or num > threelargets[1]:
updateAndShift(threelargets,num,1)
elif threelargets[0] is None or num> threelargets[0]:
updateAndShift(threelargets,num,0)
def updateAndShift(array,num,idx):
for i in range(idx+1):
if i == num:
array[i]=num
else:
array[i]=array[i+1]
if __name__ == '__main__':
array=[78,12,96,254,45,265,852,897,789,361,665]
print(find3largest(array))
| true |
5fb6963bace45e4c259f2671c4bff043f3b83424 | Prakashchater/Daily-Practice-questions | /Searching/Exponential_search.py | 2,123 | 4.15625 | 4 | # def binary(arr,target,left,right):
# if right >= 1:
# mid = (left + right-1) // 2
# if arr[mid] == target:
# return mid
# elif arr[mid] > target:
# return binary(arr,target,left,mid - 1)
# else:
# return binary(arr,target,mid+1,right)
# else:
# return -1
#
# def exponential(arr,target,n):
# if target == arr[0]:
# return 0
# i = 0
# while i < n and arr[i] <= target:
# i = i * 2
#
# return binary(arr,target,i/2,min(i,n-1))
#
# if __name__ == '__main__':
# arr = [2, 3, 4, 10, 40]
# n = len(arr)
# target = 10
# print(exponential(arr, n, target))
# Python program to find an element x
# in a sorted array using Exponential Search
# A recurssive binary search function returns
# location of x in given array arr[l..r] is
# present, otherwise -1
def binarySearch(arr, l, r, x):
if r >= l:
mid = l + (r - l) / 2
# If the element is present at
# the middle itself
if arr[mid] == x:
return mid
# If the element is smaller than mid,
# then it can only be present in the
# left subarray
if arr[mid] > x:
return binarySearch(arr, l,mid - 1, x)
# Else he element can only be
# present in the right
return binarySearch(arr, mid + 1, r, x)
# We reach here if the element is not present
return -1
# Returns the position of first
# occurrence of x in array
def exponentialSearch(arr, n, x):
# IF x is present at first
# location itself
if arr[0] == x:
return 0
# Find range for binary search
# j by repeated doubling
i = 1
while i < n and arr[i] <= x:
i = i * 2
# Call binary search for the found range
return binarySearch(arr, i / 2,min(i, n - 1), x)
# Driver Code
arr = [2, 3, 4, 10, 40]
n = len(arr)
x = 10
result = exponentialSearch(arr, n, x)
if result == -1:
print("Element not found in thye array")
else:
print("Element is present at index %d" % (result))
# This code is contributed by Harshit Agrawal
| false |
f736cd88349f9ce6c1e8be681871699116fcb549 | Prakashchater/Daily-Practice-questions | /Linked List/Singly linkedlist/delete at last.py | 1,704 | 4.21875 | 4 | """
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to push node at head
def push(head, data):
if not head:
return Node(data)
temp = Node(data)
temp.next = head
head = temp
return head
# Function to remove the last node
# of the linked list
def removeLastNode(head):
if head == None:
return None
if head.next == None:
head = None
return None
second_last = head
while(second_last.next.next):
second_last = second_last.next
second_last.next = None
return head
# Driver code
if __name__=='__main__':
# Start with the empty list
head = None
# Use push() function to con
# the below list 8 . 23 . 11 . 29 . 12
head = push(head, 12)
head = push(head, 29)
head = push(head, 11)
head = push(head, 23)
head = push(head, 8)
head = removeLastNode(head)
while(head):
print("{} ".format(head.data), end ="")
head = head.next
# This code is contributed by Vikash kumar 37
"""
# import sys
# import math
#
# class node:
# def __init__(self,data):
# self.data=data
# self.next=None
# def push(head,data):
# if not head:
# return node(data)
# temp=node(data)
# temp.next= head
# head=temp
# return head
#
# def removelastNode(head):
# if head==None:
# return None
# if head.next==None:
# head=None
# return None
# sec_last=head
# while(sec_last.next.next):
# sec_last=sec_last.next
# sec_last.next=None
# return head
# if __name__ == '__main__':
# head=None
# head=push(head, 12)
# head=push(head, 15)
# head=push(head, 16)
# head=push(head, 17)
# head=push(head, 18)
# head=removelastNode(head)
# while(head):
# print("{}".format(head.data),end=" ")
# head=head.next
| true |
addd10a2eefff346f388eecc246792107b14dd41 | HarukiOgawa1/turtle | /turtle1.py | 761 | 4.125 | 4 | import turtle
import tkinter as tk
my_turtle = turtle.Turtle()#タートルを生成
screen = turtle.Screen()#スクリーンを取得
screen.setup(800,800)#スクリーンのサイズを設定(幅,高さ)
screen.title("タートル")#ウィンドウのタイトルを設定
my_turtle.shape("turtle")#タートルの形を設定(亀のアイコン)
my_turtle.pensize(5)#ペンの太さを設定
#my_turtle.hideturtle()#アイコンを隠す
for i in range(4):
my_turtle.forward(100)#前方へ100ピクセル進む
my_turtle.left(90)#左に90度回転
my_turtle.forward(100)
my_turtle.right(90)#右に90度回転
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.back(200)
screen.mainloop()#イベントループして入力待ちになるメソッド
| false |
f03f4449be435bc2df795f479c35a9a48bcbaefc | PhoebeGarden/python-record | /廖雪峰 notes/list and tuple.py | 1,002 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#list
classmates = ['Pheobe', 'Bob', 'Tracy']
print(classmates)
print(len(classmates))
for x in range(len(classmates)) :
print('classmates[%d] = ' % x, classmates[x])
print('classmates[%d] = ' % -x, classmates[-x])
classmates.append('Cherry')
print(classmates)
classmates.insert(1, 'Jack')
print(classmates)
classmates.pop(2) #classmates.pop()就是指的只删除最后一个
print(classmates)
classmates[2] = 'Sarah'
print(classmates)
#list里面元素类型也可以是不同的
#tuple tuple一旦定义了之后不可变
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
t =()
print(t)
t = (1)
print(t)
t = (1,)
print(t)
#可变'tuple',需要借助list
t = ('a', 'b', ['A', 'B'])
print(t)
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)
#练习
L = [
['Apple', 'Google', 'Microsofg'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[2][2]) | false |
fb5108173f3734f222c3d1bfb4784dec83d0d88c | edwardhallett/ProjectEuler | /Problem1.py | 398 | 4.125 | 4 | # -*- coding: utf-8 -*"-
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def Prob1(amount):
lst = [i for i in range(1, amount) \
if i % 3 == 0 or i % 5 == 0 \
]
sum_lst = sum(lst)
return sum_lst
print(Prob1(1000))
| true |
55f438487c733c3fe520fb8ca3f06edf3a108c7c | VictorArce04/PracticasEDD | /Push.py | 920 | 4.21875 | 4 | pila = []#se crea el arreglo
tam = 5#se le asigna un tamano
def push(Valor):#Metodo push con el cual se agrega un numero a la pila
if len(pila) < tam:#Aqui el programa identifica que el tamano de la pila no se mas grande al que asignamos
pila.append(Valor)#en esta linea se agrega el numero que el usuario desea
else:#Si el tamano excede al que asignamos lanza el siguiente mensaje
print("Pila llena")
def Menu():#Metodo para el menu
print("Menu de pila")
print("Ingrese numero(ejemplo: 1)")
print("1-.push")
opc = int(input())#Se ingresa el numero para seleccionar la opcion del menu
if (opc==1):#aqui si el numero ingresado es igual a "1" se ejecuta la siguiente parte del codigo que hace qu ele push funcione
print("Ingrese el numero para apilar")
i = input()
push(i);
print("Valor ingresado")
Menu()
Menu()
| false |
e6d3cb7c84ebedfd560af5aab7494cf06293f7e2 | yograjsk/selenium_python | /OOP_Demo/abstraction_example/calculator.py | 725 | 4.34375 | 4 | from abc import abstractmethod, ABC
class calculator(ABC):
@abstractmethod
def add(self):
# def add(self, a, b):
# def add(self):
pass
@abstractmethod
# def multiply(self, a, b):
def multiply(self):
pass
# abstract class: the class which has at least one abstract method
class stringCalculator(calculator):
def add(self,a,b):
print(str(a)+str(b))
def multiply(self, a, b):
print(str(a)*b)
class numberCalculator(calculator):
def add(self, a, b, c):
print(a + b + c)
def multiply(self, a, b):
print(a * b)
sc = stringCalculator()
sc.add(2,4)
# sc.multiply("abc ",2)
nc = numberCalculator()
nc.add(2,4,6)
# nc.multiply(2,4) | true |
4e7b6dbcfe6f119319d21838821c703210dcc341 | Alexladin/Game_Design | /challenge.py | 369 | 4.125 | 4 | stars= int(input(" Enter number of stars: "))
line= stars
space= 0
for i in range (line):
for counter in range(stars):
print("* ", end=" ")
for j in range(space):
print (" ", end=" ")
space+= 2
for counter in range (stars):
print ("* ", end= " ")
print( )
stars-= 1
print ("thank you")
| true |
e34e2cf10d846639a797ec8356ff5fcfe4b2c8e2 | cmoore95/VSA-Projects | /proj04/proj04.py | 371 | 4.28125 | 4 | # Name:
# Date:
"""
proj04
Asks the user for a string and prints out whether or not the string is a palindrome.
"""
#shortcut
phrase=raw_input('Enter a word or phrase. ')
length=len(phrase)
end=phrase[1:]
phrase=phrase.lower()
if phrase==phrase[::-1]:
print phrase[0].upper()+end,'is a palindrome'
else:
print phrase[0].upper()+end,'is not a palindrome'
| true |
f6a662413b7f87cec966c1a65c42246d76858c2d | bopopescu/dojo_assignments | /Python/python fundamentals/making_and_reading_dict.py | 429 | 4.15625 | 4 | ##### Making and Reading from Dictionaries
user = {
'name': 'Victor',
'age': '30',
'country of birth': 'USA',
'favorite language': 'Python'
}
def user_info(dit):
print 'My name is {}'.format(dit['name'])
print 'My age is {}'.format(dit['age'])
print 'My country of birth is {}'.format(dit['country of birth'])
print 'My favorite language is {}'.format(dit['favorite language'])
user_info(user) | true |
1780b42158cc9fc53f9961e992f7a8e0da1e06e9 | ramonjunquera/GlobalEnvironment | /Python/standard/curso/07 Programación orientada a objetos/03 métodos mágicos - operaciones.py | 2,705 | 4.34375 | 4 | #Autor: Ramón Junquera
#Fecha: 20221221
# Métodos mágicos. Operaciones
# Son aquellos métodos que comienzan y terminan por doble guión
# bajo.
# En inglés se llaman dunders, de double underscores.
# Hasta ahora sólo hemos conocido el método __init__ como constructor
# Se utilizan para métodos con funcionalidades especiales que no
# se pueden representar con métodos regulares
# Método __add__
# Se llamará a este método cuando se pretenda utilizar el símbolo +
# para sumar dos clases
# En el siguiente ejemplo creamos la clase Vector, representando un
# vector de dos dimensiones.
# El constructor almacena en variables de instancia las coordenadas
# horizontal y vertical del vector
# Añadimos el método show para que muestre las coordenadas del
# vector.
# Y para finalizar la clase añadimos el método mágico __add__
# En este tipo de métodos están involucradas dos clases
# Por conveniencia llamamos self a la primera y other a la segunda
# Realmente podríamos ponerles cualquier nombre
# La suma de dos vectores da un nuevo vector con cuya coordenada
# horizontal es la suma de las coordenadas horizontales de los
# vectores sumados. Lo mismo ocurre con la vertical.
# Después instanciamos dos vectores, los sumamos y guardamos el
# resultado en una tercera variable (instancia) de la que usamos
# el método show para mostrar sus coordenadas
class Vector:
def __init__(self,x,y):
self.x=x
self.y=y
def show(self):
print("x={},y={}".format(self.x,self.y))
def __add__(self,other):
return Vector(self.x+other.x,self.y+other.y)
vector1=Vector(3,2)
vector2=Vector(4,6)
vectorResultado=vector1+vector2
vectorResultado.show()
# Hay más métodos mágicos cuyo funcionamiento es idéntico
# Lo único que cambia es el símbolo utilizado
# Este es el listado:
# __add__ +
# __sub__ -
# __mul__ *
# __truediv__ /
# __floordiv__ //
# __mod__ %
# __pow__ **
# __and__ &
# __xor__ ^
# __or__ |
# Creamos otro ejemplo. Esta vez con palabras
# Queremos que cuando se dividan dos palabras se muestre la
# primera en una línea, se dibuje una línea de guiones debajo
# y la segunda palabra por debajo de la línea de guiones
# Para que quede bien a la vista, la línea de guiones debería ser
# tan larga como la palabra más larga.
# Para ello creamos una lista de dos elementos con las longitudes
# de las dos palabras involucradas y calculamos el valor máximo
# que es número de veces que se repite el caracter guión
class Palabra:
def __init__(self,texto):
self.texto=texto
def __truediv__(self,other):
print(self.texto)
print("-" * max([len(self.texto),len(other.texto)]))
print(other.texto)
palabra1=Palabra("hola")
palabra2=Palabra("adios")
palabra1/palabra2
| false |
9fb9f1509d3f6d4fb13e4570c5c31cb0f722ea6c | VincentCheruiyot/python-basics | /Task14.py | 1,126 | 4.53125 | 5 | #Shopping list app as per video no. 23
#run the script
#put new things into the list
#enter the word done in all caps to quit the program
#on quiting, let the app show all the items in the list
#have the HELP command
#have the SHOW command
#clean code up in general
#make a list to hold onto our items
shopping_list=[]
def show_help():
print("what should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""")
def show_list():
#print out the list
print("Here's your list: ")
for item in shopping_list:
print(item)
def add_to_list(new_item):
# add new items to our list
shopping_list.append(new_item)
print("Added {}. List now has {} items.".format(new_item, len(shopping_list)))
show_help()
while True:
# ask for new items
new_item = input("> ")
if new_item=='DONE':
break
elif new_item=='HELP':
show_help()
continue
elif new_item=='SHOW':
show_list()
continue
add_to_list(new_item)
show_list()
#be able to quit the app
| true |
c46590d03120954df3a873232131df2f825ece01 | dwiberg4/comm_progs | /triangle_area.py | 1,102 | 4.46875 | 4 | # A program to calculate the area of a Triangle in 3D space
# The initial input is 3, 3D coordinates
import numpy as np
A = [4,1,3]
B = [6,6,1]
C = [-3,3,2]
#A = [0,0,0]
#B = [4,0,0]
#C = [0,3,0]
def distance_3D(A,B):
dist = np.sqrt( ((B[0]-A[0])**2)+((B[1]-A[1])**2)+((B[2]-A[2])**2) )
return dist
#print("The distance between the points A and B is: ",distance_3D(A,B))
#print("The distance between the points B and C is: ",distance_3D(B,C))
#print("The distance between the points C and A is: ",distance_3D(C,A))
def area_3D(A,B,C):
a = distance_3D(B,C)
b = distance_3D(C,A)
c = distance_3D(A,B)
angle_C = np.arccos( ( (c**2)-(a**2)-(b**2) ) /(-2*a*b) )
h = a*np.sin(angle_C)
area = .5*b*h
return area
def herons_area(A,B,C):
a = distance_3D(B,C)
b = distance_3D(C,A)
c = distance_3D(A,B)
s = (a+b+c)/2
area = np.sqrt(s*(s-a)*(s-b)*(s-c))
return area
area = area_3D(A,B,C)
herons = herons_area(A,B,C)
print("The area of the Triangle is: ",area)
print("According to Heron's Formula, the area of the Triangle is: ",herons)
| false |
362b167aa2f0d94627f754b5fda469ee7219ea4d | JoshCLWren/python_stuff | /decorators.py | 1,364 | 4.34375 | 4 | # # what's a decorator?
# # decorators are functions
# # decorators wrap other functions and enhace their behavior
# # decorators are examples of higher order functions
# # decorators have their own sytax using @ (sytactic sugar)
# # decorators as functions
# # def be_polite(fn):
# # def wrapper():
# # print("What a pleasure to meet you!!")
# # # exececutes passed function
# # fn()
# # print("have a nice day")
# # return wrapper
# # def greet():
# # print("My name is Colt.")
# # greet = be_polite(greet)
# # greet()
# def rage():
# print("I hate you")
# polite_rage = be_polite(rage)
# polite_rage()
# # decorator syntax
# # syntactic sugar
# def please_be_polite(fn):
# def wrapper():
# print("What a pleasure to meet you!")
# fn()
# print("have a nice day!")
# return wrapper
# @please_be_polite # eliminates the need to assign the function to a variable and pass it the function
# def yeet():
# print("My anem is Matt.")
# yeet()
# deocorators with different signatures
def shout(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
return f"Hi, I'm {name}."
@shout
def order(main, side):
return f"Hi, I'd like the {main}, with a side of {side}, please."
@shout
def lol():
return "Lol"
print(order("burger", "fries"))
print(lol()) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.