text stringlengths 37 1.41M |
|---|
########################################
#
# type() نوع
#
#
# صفة object جميع البيانات في بايثو هي
#
#
انواع البيانات
# int => Integer الرقمي او العدد الصحيح
# float => Floating Point Number العدد العشري
# s... |
# -----------------------------
# -- Tuple --
# -----------
# [1] Tuple Items Are Enclosed in Parentheses
# [2] You Can Remove The Parentheses If You Want
# [3] Tuple Are Ordered, To Use Index To Access Item
# [4] Tuple Are Immutable => You Cant Add or Delete
# [5] Tuple Items Is Not Unique
# [6] Tuple Can Have Differe... |
"""Module nature
Demonstrates how to connect objects.
"""
class Animal(object):
"""An animal"""
def __init__(self, name):
"""Constructor"""
self.name = name
def __repr__(self):
"""Returns string representation."""
return 'Animal: %s' % self.name
class Food(object):
... |
# coding: utf-8
"""Strings
"""
print __doc__
print 'H' 'e' 'l' 'l' 'o' '!'
print 'Hello', 'world!'
print 'Hello' + ' ' + 'world!'
print """This sentence
has multiple
lines."""
text = "Hello\nworld."
print text
text_raw = r"Hello\nworld."
print text_raw
print '-' * 40
print 'Hi %s!' % 'Guido'
print 'Hi %s! My name is %s... |
class Circle():
pi = 3.14
def __init__(self,radius=1):
self.radius = radius
def area(self):
return self.radius * self.radius * self.pi
def circumference(self):
return 2* self.pi * self.radius
mycircle = Circle()
print(mycircle.radius)
print(mycircle.area())
print(mycircle.ci... |
# Ask the user to write a number and print if this number is even or odd
number = input("Write a number: ")
if int(number) % 2 == 0:
print("This number is even")
else:
print("This number is odd") |
# Watching the 15 min of Python youtube video from Code Command
welcome = "Hello, "
print("Please enter your name: ")
name = input()
print(f"{welcome}{name}") |
def longestIncreasingSubSequence(arr):
res=[None]*len(arr)
ind=[None]*len(arr)
for i in range(len(arr)):
res[i]=1
ind[i]=i
maximum=0
for i in range(1,len(arr)):
for j in range(i):
if(arr[j]<arr[i]):
prev=res[i]
current=re... |
# Project Name: SleekWebBot
# Author: Kevin Bazira
# Descripttion: SleekWebBot is an internet robot that visits a website and clicks on a specified web element.
# How it works: Requests User Input,
# Function visit_web(): Opens Browser, Loads URL, Waits for some time, Finds Element, Clicks Element, Waits for some time... |
a = int(input())
b = int(input())
if a == 0:
if b == 0:
print ('x-любое')
else:
print ('решения нет')
elif c:= b / a:
if a > 0:
print ('x', '>', c)
else:
print ('x', '<', c)
|
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import sys
high=100
low=0
remaining_gusses100=7
remaining_gusses1000=10
# helper function to start and restart the game
def new_gam... |
#Solution 2 -- program to check whether a given Sudoku solution is valid
board_list = [[" " for x in range(9)] for y in range(9)]
value_list1 = [1,2,3,4,5,6,7,8,9]
board_index_map = {1:[(0,0), (0,1), (0,2),
(1,0), (1,1), (1,2),
(2,0), (2,1), (2,2)],
... |
#! /usr/bin/python
# euler-prob-001.py
# author: Ray Wach
# date: 2014-10-02
# info: Python script to find the solution for Project Euler problem 1.
import sys
if len(sys.argv) != 2:
print 'Usage:', sys.argv[0], '<ceiling>'
exit(1)
cap = int(sys.argv[1])
fives = range(5,cap,5)
threes = range(3,cap,3)
co... |
import math
class Vector2:
def __init__(self,x,y):
self.x = x
self.y = y
# Operators and smart build-ins
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def __add__(self,other):
return Vector2(self.x+other.x,self.y+other.y)
def __sub__(self,... |
#!/usr/bin/env python
print 'Welcome to the grade conversion tool!'
while True:
score = int(raw_input("Enter 999 to exit. Please enter score-->"))
if score == 999:
print 'Have a nice day!'
break
elif score > 100:
print 'Invalid score'
elif score < 0:
print 'Invalid score'
elif score>=90:
pr... |
# encoding: utf-8
import sys
import socket
CLIENT_NAME = sys.argv[1] # Nome do cliente
SERVER_ADDRESS = sys.argv[2] # Endereco IP do Servidor
SERVER_PORT = int(sys.argv[3]) # Porta que o Servidor esta
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Criacao do soquete
dest = (SERVER_ADD... |
#!usr/bin/env python
'''this is for basic file operations '''
FILE = 'file_operation.txt'
CODEC = 'utf-8'
intro = 'This is the basic file operation txt\n'
to_write = open(FILE, 'w')
to_write.write(intro)
main_part = ''' file is read by open()/file() operation
and open() built-in method recommended
... |
#!usr/bin/env python
def safe_float(obj):
try:
retval = float(obj)
except ValueError:
retval = 'could not convert non-number to float'
except TypeError:
retval = 'object type cannot be converted to float'
return retval
if __name__ == '__main__':
str1 = 'a is a not number'
print safe_float(st... |
"""
This module has a couple of functions
"""
def GetTheMovieData():
"""Reads the MontyPythonData.csv and returns
a list of dictionaries with the movie data"""
# Read the file
content = open("MontyPythonData.csv").read()
# Split the file into a list of lines
lines = content.splitlines()
... |
import sqlite3
from movie_client import get_movie_data
class MovieDatabase(object):
def __init__(self):
"Connects to the database or creates a new if needed."
self.connection = sqlite3.connect("test.sqlite")
def create_movie_table(self):
"Creates the movie table in the database."
... |
"""
Dictionaries are lists of key value pairs.
The key can be any object that doesn't change and the value can be any object.
The key and values have a colon ':' between them.
{ Key:Value, Key:Value, Key:Value}
"""
#
# Creating empty dictionaries
#
data = {}
data = dict()
#
# Dictionary with three pairs usin... |
"""
Methods for downloading movie data from http://omdbapi.com.
"""
import json
# Python 3
# import http.client
# from urllib.parse import quote
# Python 2.7
import httplib
from urllib import quote
def get_movie_data(title):
"""Downloads movie data from imdbapi.com.
Returns a dictionary with the movie's d... |
#Link- https://www.hackerrank.com/challenges/python-loops/problem
#Solution
if __name__ == '__main__':
n = int(input())
x=0
while x<n :
print(x*x)
x+=1
|
'''
Author: Ri Hong
Date AC'd: Feb 18, 2021
Problem: https://dmoj.ca/problem/ccc21s2
'''
#Explanation
'''
The ideology behind this solution is the same as the one in CCC '21 J4 - Arranging Books.py. If you did not read that solution first, I strongly recommend that you do. Also, this solution uses classes, but you can... |
'''
Author: Ri Hong
Date AC'd: Jan 10, 2021
Problem: https://dmoj.ca/problem/ccc05j1
'''
#--------Explanation-----------
#First we want to get the sequence of Hs and Vs
#Notice that the operations are commutative in that if you flip the mirror twice horizontally,
#you end up with the original mirror and the same is tr... |
'''
Author: Ri Hong
Date AC'd: June 19, 2020
Problem: https://dmoj.ca/problem/ccc11j4
'''
#Explanation
'''
Already drilled coordinates can be stored in a list. Don't forget to include the plan provided in the example. The starting
coordinate is (-1, -5), from there, we can process each command and calculate each posi... |
'''
Author: Ri Hong
Date AC'd: June 19, 2020
Problem: https://dmoj.ca/problem/ccc12s5
'''
#Explanation
'''
DFS can be used to find the number of paths it takes to reach the destination while avoiding car coordinates. The grid can be
represented by a 2D array and each cell we be set to -1 initially to represent that it... |
'''
Author: Ri Hong
Date AC'd: Mar 23, 2020
Problem: https://dmoj.ca/problem/ccc06j2
'''
#Explanation
'''
Try all the combinations of rolls and cound the number of combinations that add up to 10.
'''
#Code
a = int(input())
b = int(input())
aList = [] #Stores all the possible rolls on the first dice
bList = [] #Stores ... |
'''
Author: Ri Hong
Date AC'd: Jan 5, 2020
Problem: https://dmoj.ca/problem/ccc14j1
'''
#Explanation
'''
Get the three angles. If they add up to 180, then we have to further check if the triangle is isosceles, equalateral or scalene.
If the angles don't add up to 180, then output "Error"
'''
#Code
#Get side lengths
a ... |
'''
Author: Ri Hong
Date AC'd: Jan 18, 2020
Problem: https://dmoj.ca/problem/ccc19s2
'''
#----------Explanation----------
"""
For each test case, we want go from 1 to N(the test case number) to look for A and B (the two numbers
that when added together will equal the test case). Then for each number from 1 to N (let ... |
'''
Author: Ri Hong
Date AC'd: Aug 27, 2020
Problem: https://dmoj.ca/problem/ccc16s2
'''
#Explanation
'''
For the maximum total speed, we want to pair the fastest Dmojistan riders with the slowest Pegland riders, or vice versa.
For the minimum total speed, we want to pair the slowest Dmojistan riders with the slowest... |
'''
Author: Ri Hong
Date AC'd: Feb 27, 2021
Problem: https://dmoj.ca/problem/ccc21j4
'''
#Explanation
'''
Step 1
First, we have to split the bookshelf into three sections: the large, medium and small section, where the size of each section is the number of books of that size in the bookshelf.
For example, if the books... |
'''
Author: Ri Hong
Date AC'd: Mar 1, 2021
Problem: https://dmoj.ca/problem/ccc21s3
'''
#Explanation
'''
***Note that this solution only ACs when Pypy 3 is selected as the language on DMOJ instead of Python 3
SUBTASK 1
For the first subtask, we can use linear search to find our answer.
Step 1
Loop through all possibl... |
import unittest
import math
from exercise_06_13 import Main
from utils import Utils
class Test_06_13(unittest.TestCase):
def test1(self):
out=Main.get_random_permutations(10)
print(str(out))
def test2(self):
n=5
map={}
permutation_count = math.factorial(n)
f... |
import definitions as defn
import random
import data_methods as data
#the only thing that matters when initializing a dijkstra map is the goals and impassable objects
class Map:
def __init__(self, goals):
self.goals = goals
self.array = [[ 999999
for y in range(defn.MAP_HEIGHT)]
... |
arr1= [1 , 2, 4, 7, 9, 8, 2]
arr2= [3, 4, 1, 8 ,10, 3]
uniqDict = {}
for i in arr1:
if uniqDict.get(i):
pass
else:
uniqDict[i]=1
for j in arr2:
if uniqDict.get(j):
pass
else:
uniqDict[j]=1
res = list(uniqDict.keys())
print(res)
res.sort()
print(res)
|
print("""
Homebrew ABV Addition Tool
==========================
This tool is designed to calculate the final abv of a homebrew after adding other alcohol to it (e.g. adding whisky to porter to create a bourbon porter)
""")
abv1 = float(input("Enter the ABV (%) of the first item: "))
print(str(abv1) + "%")
volume1 = ... |
def hasNumber(inputString):
return any(char.isdigit() for char in inputString)
#Hello. to HELLO!
def shout(txt):
if txt[-1] == ".":
new_txt = txt.upper()
new_txt = new_txt[:-1]
new_txt = new_txt + "!"
return new_txt
elif hasNumber(txt) == True:
raise Exception, "Can... |
from math import*
def funct(x):
return x*x -1
def dif(x,difx = 0.000000001):
lf = funct(x+ difx)
rf = funct(x)
return (lf-rf)/difx
def newton(x,e):
i=0
while True:
df = dif(x)
f = funct(x)
x = x - f/df
i+=1
if(abs(f)<e and i>=2000):
break
return x
print(newton(3,0.0... |
x = int(input('enter a number: '))
a = dict()
def mf1(x):
for i in range(1,x+1):
a[i] = i * i
print(a)
mf1(x)
|
a = input('enter numbers :').split(',')
b = []
print(a)
for i in a:
if len(i)>=4 and int(i)%5==0:
b.append(i)
print(','.join(b)) |
from math import sqrt # import specific functions as importing all using *
# is bad practice
C,H = 50,30
"""
a = input("enter numbers: ")
for i in a:
d=int(i).split(',')
print(d)
"""
D = [int(i) for i in input().split(',')]
print(D)
"""
items = (input("enter numbers: "))
d = items.split(','... |
# takes a positive integer n as input and ...
# returns the sum of all that number's digits.
# Written while completing Codecademy Learn Python 2
def digit_sum(x):
x = str(x)
nums=[]
for i in x:
number = int(i)
nums.append(number)
total = 0
for num in nums:
total = total + num
re... |
# In this challenge, the user enters a string and a substring.
#You have to print the number of times that the substring occurs...
#...in the given string. String traversal will take place from left...
#...to right, not from right to left.
#NOTE: String letters are case-sensitive.
#Input Format:
#The first li... |
# I wrote this from scratch as part of the Codecademy Python tutorial
x = int(input("Enter a number: "))
nums =[]
if x < 2:
print("Not prime")
sys.exit()
elif x == 2:
print("Prime")
sys.exit()
elif x > 2:
for n in range(2,x):
rem = x%n
nums.append(rem)
... |
"""
Запись в файл
* .write(arg) - записывает строку arg
* .writelines(Lst[atg]) - записывает список строк arg
* 'w' - режим работы на перезапись
* 'a' - режим работы на дозапись
"""
file_handler = open("output.txt", "a")
file_handler.write("Hello world!" + '\n')
file_handler.write("Second line!" + '\n')
names = ["Ali... |
import sys
def user_input(init_key):
key = init_key
message = raw_input("Enter message to encode\n$ ")
c = 0
if key > 26:
c = key / 26
c = (key - (26 * c))
key = c
return key, message
def encrypt(key, message):
crypt_message = ""
for i in range(0, len(message))... |
#************* HELP *****************
# REMEMBER THAT YOU IF YOU EVER NEED ANY HELP AT ALL, EMAIL US ON HELP@HYPERIONDEV.COM, OR CREATE A NEW TEXT FILE IN THIS FOLDER CALLED 'HELP'
#*************************************
#REMINDER: OPEN THIS FILE IN IDLE.
#Congrats! You've made it to the next task.
#You've learnt the ... |
# Write a Python program called “disappear” to strip a set of characters from
# a string.
# Ask the user to input a string and then ask the user which characters they
# would like to make disappear.
# For example... |
# This example program is meant to demonstrate errors.
# There are some errors in this program, try run the program by pressing F5.
# Now look at the error messages, and find and fix the errors.
name = str("Tim")
surname = str("Jones")
age = int(21)
fullMessage = (name) + " " + (surname) + " is " + str(age) + " y... |
#Open file containing list of people details and sort
#Importing libraries
import os
#Open file in read & write mode
f = open("DOB.txt", "r+")
#Defining details
Fname = [] #4 characters after n/line chr
Lname = [] #4 characters after 1st w/space
Day = [] #2 integers after 2nd w/space
Month = [] #4 characters after 3rd ... |
# Welcome to example.py. You may open this file in EITHER notepad++ or IDLE.
# I recommend that you open it in IDLE so that you can run it (by pressing F5) to view the output of the commands below.
# ************* HELP *****************
# REMEMBER THAT YOU IF YOU EVER NEED ANY HELP AT ALL, EMAIL US ON HELP@HYPERIOND... |
import math
#Get user input:
side1, side2, side3 = input("Please enter the 3 side of your triangle: ").split()
#Define user input:
side1 = int(side1)
side2 = int(side2)
side3 = int(side3)
#Define Operations:
Sides = (side1 + side2 + side3) / 2
Triarea = math.sqrt(Sides * (Sides - side1) * (Sides - side2) * (Sides - sid... |
cleanCarRed = True
cleanCarBlue = True
cleanCarGreen = True
numOfCar = 0
Busy = False
print ("Welcome to the car wash")
redCheck = input("Is the Red car Dirty? (Yes or No)")
if redCheck == "Yes":
cleanCarRed = False
blueCheck = input("Is the Blue car Dirty? (Yes or No)")
if blueCheck == "Yes":
cleanCarBlue = Fals... |
def get_questions():
return [["What color is the daytime sky on a clear day? ", "blue"],
["What is the answer to life, the universe and everything? ", "42"],
["What is a three letter word for mouse trap? ", "cat"]]
def check_question(question_and_answer):
question = question_and_answer[... |
#Get user input:
friend_name = input("Enter your a friends full names: ")
friends_age = int(input("Enter your a friends age: "))
#Define operation variables:
friends_names = ["John Doe", "Doe Donald", "Donald Johnson"]
friends_names.append(friend_name)
friends_ages = [35,54,43]
friends_ages.append(friends_age)
#Out Ope... |
# Create a program called “alternative.py” that reads in a sting and makes
# each alternate character an Uppercase character and each other alternate
# character a lowercase character.
# Collecting user input
U_string = input("Please enter your sentence to convert: \n").lower()
U_string = list(U_string)
while len(U_s... |
# Welcome to example2.py. You may open this file in EITHER notepad++ or IDLE.
# I recommend that you open it in IDLE so that you can run it (by pressing F5) to view the output of the commands below.
# ============= Errors when running Python files ==========
# Now that you've learnt how to run a Python file, you sho... |
# K-Means clustering implementation
# Some hints on how to start have been added to this file.
# You will have to add more code that just the hints provided here for the full implementation.
# ====
import math
import pandas
import random as rand
import matplotlib.pyplot as plt
# Define a function that computes the di... |
noDays = int(raw_input("How many days did you work this month?"))
payPerDay = float(raw_input("How much is your pay per day?"))
salary = noDays * payPerDay
print "My salary for the month is R"+str(salary)
|
# ============ Basics ===================
#A list of Strings:
alphabet = ['a','b','c']
#A list of integers:
numbers = [1, 2, 3]
#A list of doubles:
real_numbers = [1.2, 2.4, 4.9]
#Image the type of data you could store in a list - names, phone numbers, file names, email messages.
#For each of these, think of the... |
import numpy as np
import scipy.stats
def random_points_in_triangle(p1,p2,p3,n):
"""Generate random points uniformly distributed in a triangle.
The points can be in any number of dimensions.
Params
------
p1: 1D array
Vector pointing to the first vertex
p2: 1D array
Vector po... |
#!/usr/bin/python3
"""
Function to return the perimeter of an island
"""
def island_perimeter(grid):
"""Calculating the island perimeter"""
k = 0
c = 0
for a in range(len(grid)):
for b in range(len(grid[a])):
if grid[a][b] == 1:
if a > 0 and grid[a - 1][b] == 1:
... |
def add(numstrings):
if len(numstrings) == 0:
return None
else:
total = 0
for s in numstrings:
total += int(s)
return total
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
# Need to tu... |
# N = 15 => 1,2,3....15
# print numbers % 3 - > Fizz, % 5 -> Buzz, % 3 % 5 -> FizzBuzz
n = 30
for i in range(1, n+1):
if (i % 3 == 0 and i % 5 == 0) or (i % 4 == 0 and i % 7 == 0):
print(i, 'FizzBuzz')
elif i % 3 == 0 or i % 4 == 0:
print(i, 'Fizz')
elif i % 5 == 0 or i % 7 == 0:
... |
vowels = 'AEIOUYaeiouy'
#vowels = ['A', 'E', 'I', 'O', 'U', 'Y', 'a', 'e', 'i', 'o', 'u', 'y']
text = ['Hello', 'my', 'NAME', 'is', 'Daniel']
# 2 1 2 1 3
slovo_max_golosni = ''
max_golosni = 0
for word in text:
amount_of_voewls_in_word = 0
for letters in word:
if letters in vowels:
... |
arr = [21, 23, 31, 34, 11, 111, 17, 12, 7, 5]
a = 2
b = 4
def find_count(n):
count = 0
while n > 0:
digit = n % 10
n = n // 10
count = count + 1
return count
for i in range(len(arr)):
count = find_count(arr[i])
if count > a and count < b:
print((arr[i]))
|
# n = 123 , kilkist = 3, suma = 6
n = 1234
def find_sum(n):
summ = 0
while n > 0:
digit = n % 10
n = n // 10
summ += digit
return summ
def find_count(n):
count = 0
while n > 0:
digit = n % 10
n = n // 10
count = count + 1
return count
print(f... |
n = 15
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
print("Fizz Buzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
"""
for i in range(1, 11):
parnist = 'neparne'
if i % 2 == 0:
parnist = 'parne'
print("%s %s" % (i, parnist))
"""
"""
i = 1
print("%s %s" % ... |
from string import ascii_lowercase, ascii_uppercase
text = 'dkghokdghopAAAAAAAfghgfbnvbnretwwquouipiuopAAAAdkhotkyr0k59-kk53gki53g53k5klk%^%^%_&)%_+)_+)$_+)%^$%$)(^+_)%(&_('
new_text = ''
for elem in text:
if elem in ascii_lowercase:
new_text += str(elem)
if elem in ascii_uppercase:
new_text += str(ele... |
array = [8, 7, 21, 54, 1, 56, 47, 421, 321]
def sort(number):
for i in range(len(array)):
first = array[i]
j = i - 1
while j >= 0 and array[j] < first:
array[j + 1] = array[j]
j -= 1
array[j + 1] = first
sort(array)
print(array) |
text = 'skueryiweruwoieuo'
substring = 'wer' # 7 - індекс початку підрядка
#substring = 'abc' # -1 - підрядка немає
#print(text.index(substring))
found = True
for i in range(len(text)):
if i > len(text) - len(substring):
break
found = True
for j in range(len(substring)):
if text[i+j] !... |
#assignment operator
x = 5
#Simple mathematical operators are +; -; *; /;
#modulus
x = 5%2
print(x) |
#assignment operator
x = 5
#Simple mathematical operators are +; -; *; /;
#modulus
x = -(5)%4
print(x)
#Self assignment
x = 5
x = x+3
print(x)
x = 5
x += 3
print(x)
x = 5
x = x + 5
a = 6
a += 3
b = 9
b -= 3
c = 15
c /= 3
print(x,a,b,c)
x = 5
x //= 2
print(x)
x = 4
x **= 2
print(x)
#Incrementing... |
class Stack:
def __init__(self):
self.el = []
# проверка стека на пустоту. Метод возвращает True или False.
def isEmpty(self):
if self.el:
return False
else:
return True
# добавляет новый элемент на вершину стека. Метод ничего не возвращает.
def push... |
from Arquivo import e_arquivo_vazio, le_arquivo, escreve_arquivo
from Proprietario import cadastrar_proprietario, adiciona_carro_a_proprietario
class Carro:
def __init__(self, placa, marca, modelo, ano, cpf_proprietario):
self.__placa = placa
self.__marca = marca
self.__modelo = modelo
... |
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
"""
soup=BeautifulSoup(html,'lxml')
print(soup.head.title)
print(type(soup.head.title))
print(soup.title.string) |
#!/usr/bin/python36
# Desafio 006
n = int(input('Insira um número: '))
print('O dobre de {} é {}'.format(n, (n*2)))
print('O triplo de {} é {}'.format(n, (n*3)))
print('A raiz quadrada de {} é {:.2f}'.format(n, (n**(1/2))))
|
#!/usr/bin/python36
pv = int(input('Primeiro valor: '))
sv = int(input('Segundo valor: '))
tv = int(input('Terceiro valor: '))
if pv < sv and pv < tv:
menorvalor = pv
if sv < pv and sv < pv:
menorvalor = sv
if tv < pv and tv < sv:
menorvalor = tv
print('O menor valor digitado é {}'.format(menorvalor))
if pv... |
#!/usr/bin/python36
peso = float(input('Qual é o seu peso (Kg)? '))
altura = float(input('Qual é a sua altura? '))
imc = peso / (altura ** 2)
print('Com {}Kg e {}m seu IMC é {:.1f}.'.format(peso, altura, imc))
if imc < 18.5:
print('Você está ABAIXO DO PESO normal!')
elif imc < 25:
print('Você está com o PESO ID... |
#!/usr/bin/python36
def voto(ano):
from datetime import date
anoatual = date.today().year
idade = anoatual - nasc
if idade < 16:
return f'Com {idade} anos: NÃO VOTA.'
elif 16 <= idade <= 17 or idade > 70:
return f'COM {idade} anos: VOTO OPCIONAL.'
else:
return f'Com {ida... |
#!/usr/bin/python36
def area():
a = largura * comprimento
print(f'A área de um terrano {largura}x{comprimento} é de {a}m².')
largura = float(input('LARGURA (m) :'))
comprimento = float(input('COMPRIMENTO (m) :'))
area()
|
#!/usr/bin/python36
import random
vitoria = 0
print('-'*30)
print('A brincadeira só acaba quando o computador vencer.')
print('-'*30)
while True:
jogador = int(input('Quantos dedinhos: '))
escolha = ' '
while escolha not in 'PI':
escolha = str(input('Par ou ímpar: [P/I] ')).upper().strip()[0]
co... |
#!/usr/bin/python36
numero = str(input('Informe um número: ')).zfill(4)
len(numero)
print('Analisando o número {}'.format(numero))
print('Unidade: {}'.format(numero[3]))
print('Dezena: {}'.format(numero[2]))
print('Centena: {}'.format(numero[1]))
print('Milhar: {}'.format(numero[0]))
|
#!/usr/bin/python36
from datetime import date
nasc = int(input('Ano de nascimento: '))
ano = date.today().year
idade = int(ano - nasc)
print('O atleta possui {} anos.'.format(idade))
if idade <= 9:
print('Está na categoria MIRIM.')
elif idade <= 14:
print('Está na categoria INFANTIL.')
elif idade <= 19:
pri... |
#!/usr/bin/python36
distancia = int(input('Qual é a distância da sua viagem? '))
if distancia <= 200:
print('Você viajou {}Km e será cobrado R${:.2f} nessa viagem.'.format(distancia, distancia * 0.50))
else:
print('\033[4;34mAndou muito e ganhou desconto!\nVocê viajou {}Km, seu custo foi R${:.2f}.\033[m'.format... |
#!/usr/bin/python36
maior = c = total = 0
cont = 'S'
while cont == 'S':
n = int(input('Digite um número: '))
if c == 0:
menor = n
elif n < menor:
menor = n
if n > maior:
maior = n
c += 1
total += n
cont = input('Continua? [S/N]').strip().upper()
while cont not in ... |
#!/usr/bin/python36
s = 0
v = 0
for c in range(3, 501, 3):
if c % 2 != 0:
s += c
v += 1
print('A soma dos {} valores é {}'.format(v, s))
|
#!/usr/bin/python36
from random import sample
print('-'*30)
print('{:^30}'.format('JOGA NA MEGA SENA'))
print('-'*30)
jogos = int(input('Quantos jogos você quer que sorteie? '))
print('-=' * 3, f' Sortenado {jogos} JOGOS ', '-=' * 3)
for c in range(1, jogos+1):
numeros = sorted(sample(range(1, 60), k=6))
print(... |
import math
class Line(object):
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2
def __repr__(self):
return repr(((self.x1, self.y1), (self.x2, self.y2)))
def __str__(self):
return str(((self.x1, self.y1), (self.x2, self.y2)))
d... |
# Find the sum of all the primes below two million.
# reusing code from problem 7
VERY_BIG_NUMBER = 2000000
primes = [True for i in range(VERY_BIG_NUMBER)]
p = 2
print ("generated array")
while p * p <= VERY_BIG_NUMBER:
if primes[p]:
for j in range(p*p, VERY_BIG_NUMBER, p):
primes[j] = False... |
# Find the difference between the sum
# of the squares of the first one hundred natural numbers and the square of the sum.
x = 0
y = 0
for i in range(1, 101):
x += i*i
y += i
y = y*y
print("sum of squares", x)
print("square of sum", y)
print("difference", y-x)
|
def manhattan_distance(board):
return board.evaluate()
def num_remaining_pieces(board):
return len(board.agent_pieces) - len(board.adversary_pieces)
def num_threats(board):
'''
This evaluates how many threats surround each of the agent's pieces in a radius of d/3
'''
d = board.grid.width
radius = d//3
n_thre... |
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 10, "normal")
class Message(Turtle):
def __init__(self):
super().__init__()
self.message = "Ahoj"
self.level = 0
self.color("white")
self.penup()
self.goto(0, -290)
self.hideturtle()
... |
# Save A Matplotlib Plot As A Vector
# Import Numpy and matplotlib.pyplot
import numpy as np
import matplotlib.pyplot as plt
# Create two new variables for mu and sigma
mu, sigma = 100, 15
# Create some simulated data of 10000 values
x = mu + sigma * np.random.randn(10000)
# Create a histogram of the simulated data... |
# String Operations
# Python 3 has three string types
# str() is for unicode
# bytes() is for binary data
# bytesarray() mutable variable of bytes
# Create some simulated text.
string = 'The quick brown fox jumped over the lazy brown bear.'
# Capitalize the first letter.
string_capitalized = string.capitalize()
prin... |
# Logical Operations
# Create some simulated variables
x = 6
y = 9
z = 12
# x or y
x or y
# x and y
x and y
# not x
not x
# x is equal to y
x == y
# x is not equal to y
x != y
# One is less than two.
print(1 < 2)
# Two is less than or equal to four.
print(2 <= 4)
# Three is equal to five.
print(3 == 5)
# Thre... |
#ITORQUE Compute the manipulator inertia torque
#
# TAUI = ITORQUE(ROBOT, Q, QDD)
#
# Returns the n-element inertia torque vector at the specified pose and
# acceleration, that is,
# TAUI = INERTIA(Q)*QDD
#
# ROBOT describes the manipulator dynamics and kinematics.
# If Q and QDD are row vectors, the result is a row ... |
import numpy as np
def angle_inside_range(angle, start, end):
'''Test whether angle in inside range [start, end).'''
# ensure that end value is within the range [start, start + 2*pi)
while end < start:
end += 2*np.pi
while end >= start + 2*np.pi:
end -= 2*np.pi
# add/subtract 2*pi... |
class Singleton(object):
'''Python implementation of the Singleton design pattern'''
__instance = None
@classmethod
def get_instance(cls):
instance_attr_name = '_%s__instance' % cls.__name__
if getattr(cls, instance_attr_name) is None:
cls()
return getattr(cls, insta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.