text stringlengths 37 1.41M |
|---|
'''Crie um programa que leia varios numeros inteiros pelo teclado.
O programa só vai parar quando o usuario digiitar o valor 999. que é a condiçao de parada.No final mostre quantos numeros foram digitados e qual foi a soma entre eles'''
total = 0
n2 = 0
while True:
total = total+1
n = int(input('Digite um numer... |
'''faça um programa que calcula a soma entre todos os numeros impares que são multiplos de três e que se encontram no intervalo de 1 até 500'''
soma = 0
cont = 0
for c in range(1,501,2):
if c %3 == 0:#se divisivel por 3 é multiplo de 3 sendo resto =0 então é multiplo de 3
soma += c # no caso aqui é um acumu... |
from math import floor,ceil,sqrt
cateto_op = float(input('entre com o valor do cateto oposto'))
cateto_ad = float(input('entre com o valor do cateto adjacente'))
soma_dos_lados_do_triangulo_retangulo_ao_quadrado = ((cateto_op**2)+(cateto_ad**2))
Raiz_quadrada_da_soma_dos_Lados_ao_quadrado = sqrt(soma_dos_lados_do_trian... |
import matplotlib.pyplot as plt
#create lists of x and y values
x = [1,2,3,4]
y = [5,7,4,6]
plt.plot(x,y) # plot x and y using default line style and color
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Default Arguments\nLine Style & Color')
# everything is drawn in the background, call show to see i... |
# lesson 5c - arbitrary number of arguments
# arbitrary arguments, *args
def some_function(*names):
print('there are ' + str(len(names)) + ' names')
for n in names:
print(n)
# call some_function.
some_function('Bart', 'Homer', 'Marge', 'Lisa')
|
import matplotlib.pyplot as plt
#create lists of x and y values
x = [1,2,3,4]
y1 = [5,7,4,6]
y2 = [-1, -2, 3, 0]
plt.plot(x,y1, 'r+-') # color='red', marker='+', linestyle='-'
plt.plot(x, y2, 'bo--') # color='blue', marker='o', linestyle='--'
plt.xlabel('x')
plt.ylabel('y')
plt.title('Multiple Lines with ... |
"""
University of Liege
ELEN0062 - Introduction to machine learning
Project 1 - Classification algorithms
"""
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import argparse
import sys
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.m... |
from os import name
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("studentMarks.csv")
data = df["Math_score"].tolist()
mean = statistics.mean(data)
std_deviation = statistics.stdev(data)
def random_set_of_mean(coun... |
a=int(input("Enter The value of a"))
b=int(input("Enter The value of b"))
c=int(input("Enter The value of c"))
if a>b:
print(f'The value of a is {a} is > value of b {b}')
elif b>c:
print(f'The value of b is {b} is > value of c {c}')
else:
print(f'The value of c is {c} is > value of a {a}') |
import numpy as np
import pandas as pd
# 从列表创建,指定行、列索引
df = pd.DataFrame([10, 20, 30, 40],
columns=['numbers'],
index=['a', 'b', 'c', 'd'])
print(df)
# 添加新的列数据
df['floats'] = (1.5, 2.5, 3.5, 4.5)
df['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc')
print(df)
# 以列为单位修改数据
df['float... |
import numpy as np
import pandas as pd
df = pd.DataFrame([10, 20, 30, 40],
columns=['numbers'],
index=['a', 'b', 'c', 'd'])
df['floats'] = (1.5, 2.5, 3.5, 4.5)
df['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc')
df['names2'] = pd.DataFrame(['Yv', 'Gu', 'Fe', 'Fr'],
... |
def linha1():
print('=' * 60)
def linha2():
print('*' * 80)
linha1()
print('O LIVRO DE TOT')
linha1()
# Ambientação do jogo.
print('''Uma pequena arca que contem um livro e uma adaga de ouro está em algum lugar do Egito.
O deus Seth é capaz de qualquer coisa pelo livro, que pode torná-lo o Senhor do Mund... |
'''利用BuildTree, 进行Depth_First_Search: Preoder; inorder; postorder'''
from 树.BuildTree import BinaryTree
class BinaryTree2(BinaryTree):
def preorder(self,root): #先序遍历
node = root
if node == None:
return
print(node.data)
self.preorder(node.lchild)
self.preorder... |
'''给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
'''
'''粗略解释:矩阵要求两条垂直线的距离越远越好,垂直线的长度越长也好。故,比较
左右两端的高度,将较短高度的那条线像前/后移动一位'''
class Solution:
def maxArea(self,height):
ma... |
# 姓名排序
# 输入
stopword = ''
str = []
i = input()
while i != stopword:
str.append(i)
i = input()
print ('str是:', str ) #一维数组
# 提取姓氏
for j in range(len(str)):
str[j]=str[j].split() #转为二位数组;注:二维数组的创建方式,见Two-dimensional.py
print ('str is: ', str)
str2 = []
for j in range(len(str)):
str2.... |
'''给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807 '''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# ... |
A = [1,3,2,4,10]
for elem in A:
h = elem * elem
A.append(h)
A.reverse()
print(A) |
a = input('Введите палиндром на проверку ');
def is_palindrome(string):
return string == ''.join(reversed(string))
print(is_palindrome(a))
|
cities=["İzmir","Antalya","Ankara","İstanbul","Sakarya"]
print(cities[3])
print(cities[-1]) ##Sondan başlar
print(cities[:2])
print(cities[:-1])
cities[1]="Eskişehir"
print(cities)
cities.append("Ordu") ##Sona ekler
print(cities)
cities.insert(0,"Kars")
print(cities)
del cities[0] ##Silinen şeye ulaşılamaz
print(citie... |
def kare(x):
return x**2
x= int(input("Karesini istediğiniz sayıyı giriniz : "))
print(f"Girilen {x} sayısının karesi {kare(x)}")
x=int(input("Lütfen sayı giriniz: "))
y=int(input("Lütfen bir sayı daha griniz: "))
top = lambda x,y:x+y
çarp = lambda x,y : x*y
print(f"Girilen sayıların toplamı : {top(x,y)} , ça... |
class Car:
def __init__(self,brand,model,year):
self.brand = brand
self.model = model
self.year = year
def brandmodel(self):
return f"Araba markası {self.brand} ve modeli {self.model}"
car_1 = Car("BMW","i5",2010)
car_2 = Car("Audi","x6",2012)
print(car_1)
print(car_1.brand)
p... |
#!/usr/bin/python
#!enconding:UTF-8
def aproximacion (n):
sumatorio = 0.0
for i in range (1, n+1):
xi = (i-0.5)/float(n)
fxi = 4/(1 + (xi**2))
sumatorio += fxi
c = sumatorio/float(n)
return c
from math import pi
print 'El valor de PI con 35 decimales: %.35f\n' % pi
import sys
veces = int (sys.... |
import pprint # In order to print matrices prettier
import scipy as sc
import scipy.linalg # Linear Algebra Library contained in Scipy
matrix_A = sc.array([[7,4],[3,5]]) # given matrix A
P, L, U = scipy.linalg.lu(matrix_A) # returns the result of LU decomposition to the variables P, L, and U
print("Original matrix ... |
#Factorial test
def calculateFactorial(factorial):
num = 1
for x in range(factorial, 1, -1):
num = num * x
return num
val = input("Enter your value: ")
print ('Factorial of ' + str(val) + ' is: ' + str(calculateFactorial(int(val)))) |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
############
# Alphabet #
############
# we will use alphabet for text cleaning and letter counting
def define_alphabet():
base_en = 'abcdefghijklmnopqrstuvwxyz'
special_chars = ' !?¿¡'
german = 'äöüß'
italian = 'àèéìí... |
#!/usr/bin/env python3
import string
import sys
import re
def read_input(file):
for line in file:
line = line.lower()
line = re.sub('[^a-zA-Z0-9 \n]','',line)
yield line.split()
def main(separator='\t'):
data = read_input(sys.stdin)
for words in data:
for wo... |
n=input()
count=0
for x in range (0,len(n)):
if (n[x]==" "):
count=count+1
else:
count=count
print (count)
|
s=str(input())
if (s=='Monday' or s=='Tuesday' or s=='Wednesday' or s=='Thursday' or s=='Friday'):
print("no")
elif (s=='Saturday' or s=='Sunday'):
print("yes")
else:
print("invalid")
|
i=int(raw_input())
for x in range(1,i+1):
print("Hello")
|
h=int(input())
y=input().split()
l=input().split()
if(sorted(l)==y):
print("yes")
else:
print("no")
|
#!/usr/bin/env/python
# This is a typing test application created in python
# Created by Raymond Ho on Aug 4, 2014
import time
import sys
# Open file, and store each line into list.
List = []
total_words = 0
with open(sys.argv[1], 'r') as f:
List = f.read().splitlines()
# Count the words in the list.
for line in... |
def collatz_steps(number):
assert isinstance(number, int), "The input should be an integer"
assert number > 0, "The input should be larger than 0"
steps = 0
while number > 1:
steps += 1
if number % 2:
number = number*3 + 1
else:
number /= 2
... |
a="Hello"
print(a*3)
print(a[0])
## String negative index
print(a[-1])
##String Slicing- Works with index only.
##output is ell as starts with 1, ends at 3. Last index is not inclusive
print(a[1:4])
print(a[2:5])
## Comparison Operator
## Compares Ascii value, Starts with first chartacter.. Expect result at fi... |
## Accepting a number from user
num= input("Please enter number ")
print(num)
#Input will accept only number or float
## To accept strig use raw_input
string= raw_input("Please enter a string ")
print("Hello "+string)
|
for a in ['abc','def','xyz']:
message="Hi "+a+" How are you?"
print(message)
for i in range(5):
print('i is at',i)
print(range(4))
print(range(2,4))
print(range(2,11,5))
######################################################################
number=0
while number != 42:
number=input("Plz input number")
... |
import pygame
pygame.init()
win=pygame.display.set_mode( (500,500))
pygame.display.set_caption("First Game")
x=50
y=50
w=40
h=60
vel =5
run =True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
keys=pygame.k... |
Attack = input("Are we being Attacked!!??").lower()
if(Attack == "yes") or (Attack == "y"):
print("We are being attaked!!!Attack Back!!!")
elif (Attack == "no") or (Attack == "n"):
print("They are friendly invite them for tea!")
else:
print("You must answer us!!! Or we will be attacked!!")... |
from datetime import *
import time
#hello
class DifferenceTimes():
def __init__(self, tasks):
self.startTimes = []
self.endTimes = []
self.differenceTimes = []
self.tasks = int(tasks)
self.create_array_length()
def create_array_length(self):
for i in range(self.tasks):
self.startTimes.append(0)
self... |
'''O arquivo Controller terá as requisições do usuário'''
import mysql.connector
conexao = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database = "loja"
)
def mostrarAoUsuario():
acao = conexao.cursor()
comando = input("O que deseja fazer no Banco de Dados: "... |
class max_heap2:
def __init__(self, capacity):
self.data = [0] * (capacity + 1)
self.capacity = capacity
self.count = 0
def is_full(self):
return self.count == self.capacity
def insert(self, v):
assert not self.is_full()
print("insert", v)
... |
#!/usr/bin/env python
from enum import Enum, unique
@unique
class Colour(Enum):
black=0
red=1
class Postion():
def __init__(self,xAxis,yAxis):
self.xAxis = xAxis
self.yAxis = yAxis
class Chess():
def __init__(self,colour,xAxis,yAxis):
self.colour = colour
self.xAxis =... |
from typing import List
import csv
from ipaddress import IPv4Address
from event_parser.event import Event
from event_parser.gender import Gender
from event_parser.person import Person
def ip_anonymization(ip: IPv4Address) -> IPv4Address:
'''
This function will anonymize a given IPV4 adress by setting the las... |
# A Command Line dynamic TIC TAC TOE GAME.
# Requirements:- Python3.
# TIC TAC TOE Board is dynamic can be of any size.
# 2 Player game Player1 will choose 'X' position and Player2 will choose 'O' position on the game board.
# A winner s chosen if all the input('X'/'O') in a row/column/diagonal are same.
# Program give... |
def createBoard():
board = [0, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4]
return board
#prints out the currentboard
def printBoard(board):
print('\n')
print(' 13 12 11 10 9 8 7')
print('\n')
secondLine = ''
for x in range(8, 14):
secondLine = ' ' + str(board[x]) + secondLine
secondLine = ' ' + secondLine
... |
import re
# 1. For simple literal patterns,
text = 'yeah, but no, but yeah, but no, but yeah'
text1 = text.replace('yeah', 'yep')
print(text1)
# --->Output: yep, but no, but yep, but no, but yep
# 2.For more complicated patterns, use the sub()
# functions/methods in the re module.
# if you want to convert 11/05/202... |
from datetime import datetime
from datetime import datetime, timedelta
weekdays = ['monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday', 'sunday']
def getPrevious_byDay(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekd... |
#===============#
# 1.Time Delta #
#===============#
from datetime import datetime
from datetime import timedelta
a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
c = a+b
print(c)
# ---> Output: 2 days, 10: 30: 00
# print days in c
print(c.days)
# ---> Output: 2
# print hours in c
print(c.seconds/3600)
# -... |
import string
# 1. interpolate string using format method
message = '{name} has {n} messages...'
new_message = message.format(name='Avinash', n=20)
print(new_message)
# ---> Avinash has 20 messages...
# 2. interpolate string using format_map() and vars()
message = '{student} has unique id : {id}'
student = 'Avinash... |
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Instead of doing manually we can set qa slic options
print(items[2:4])
# ---> [2, 3]
# slice(start,end,step)
# a sile [2:4]
a = slice(2, 4)
# b slice [4: ]
b = slice(4, 8, 2)
print(items[a])
# ---> [2, 3]
print(items[b])
# ---> [4, 6]
# here b is an instance of slice so we ... |
import random
#1.定级
# s= []
# s= input('Enter scores:').split()
# def score(s):
# bests = sorted(s)
# best = bests[-1]
# best = int(best)
# for _ in s:
# i=int(_)
# if i>=best-10:
# print(i,' is A')
# elif i>=best-20:
# print(i,' is B')
# ... |
"""
初版:2018-12-30
Flaskのパッケージをインストールしておきます
pip install Flask
"""
# pipでインストールするもの
from flask import Flask, render_template, url_for, request, redirect
# はじめから入っているもの
import sys
import os
import sqlite3
# データベースファイルのパス
DB_PATH = "../notes.db"
# データベースファイルのサイズ
file_size = 0
# Pythonのバージョンを確認、表示
ve... |
from matplotlib import pyplot as plt
from graph import Greengraph
def plotGraph(start, end, steps, out=None):
""" Generate a greeting string for a person.
Parameters
----------
start: str
Start city.
end: str
End city.
steps: int
Gives number of images to process between start and e... |
import tkinter
import tkinter.messagebox
from tkinter import Tk,Label,Entry,Button,END,LEFT,RIGHT
from tkinter import *
import math
root = Tk()
l1=Label(root,text="Enter per day saving amount: ").pack()
e1=Entry(root,bd=10)
e1.pack()
l2=Label(root,text="How Many Years you want to Save ? : ").pack()
... |
Python 2.7.6 (default, Jun 22 2015, 18:00:18)
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> x = 5
>>> if x<10:
print('Smaller')
Smaller
>>> if x>20:
print('Bigger')
>>> if x>20:
print('Bigger')
print('Finis')
>>>
>>> x=5
>>> if x==5:
print("Equals 5")
Equa... |
zodiac_animals = ["Bear", "Cat", "Dog", "Dolphin", "Antelope", "Gila Monster",
"Orangutan", "Rat", "Rooster", "Sheep", "Giraffe", "Puffin"]
print ("In which year were you born?")
year = None
while year == None:
try:
year = int(input())
except:
print ("Please enter an integer ... |
def answer(food, grid):
if len(grid) == 0 or len(grid[0]) == 0:
raise Exception("Invalid grid. Don't do this to me, man.")
if (food > 200):
raise Exception("That's too much food. 200 max")
best_path = best_path_from(0, 0, food, grid)
if best_path == 201:
return -1
els... |
import math
def n_choose_m(n, m):
return math.factorial(n)/(math.factorial(n-m)*math.factorial(m))
class TreeNode():
def __init__(self, value, left, right):
self.left = left
self.right = right
self.value = value
def build_order_possibilities(self):
#one side of the tree do... |
import math
def answer(N, K):
return str(recursive_answer(N, K))
#memoized recursive method will perform similarly to tabular method
memoized_calls = {}
def recursive_answer(N, K):
if (N, K) in memoized_calls:
return memoized_calls[N, K]
if K == N-1:
memoized_calls[N, K] = int(math.po... |
def answer(numbers):
seen_pirates = []
current_pirate = 0
while current_pirate not in seen_pirates:
seen_pirates.append(current_pirate)
current_pirate = numbers[current_pirate]
return len(seen_pirates[seen_pirates.index(current_pirate):])
|
def answer(heights):
if len(heights) <= 1:
return 0
divide = max(heights)
divide_index = heights.index(divide)
left = heights[:divide_index]
right = heights[divide_index+1:]
right.reverse()
return held_water(left) + held_water(right)
def held_water(heights):
#cons... |
import numpy as np
class NaiveBayes(object):
def __init__(self,num_class,feature_dim,num_value):
"""Initialize a naive bayes model.
This function will initialize prior and likelihood, where
prior is P(class) with a dimension of (# of class,)
that estimates the empirical frequen... |
import random
list = [random.randint(1, 9999) for _ in range(10)]
print("before sorted:", list)
list.sort()
print("after sorted:", list)
list.reverse()
print("after reversed:", list)
|
import random
import time
from typing import List
def shell_sort(a: List[int]) -> None:
n = len(a)
h = n // 2
while h > 0:
for i in range(h, n):
tmp = a[i]
j = i - h
while j >= 0 and a[j] > tmp:
a[j + h] = a[j]
j -= h
a... |
def change_string(strn: str) -> str:
strn = strn * 5
return strn
strn = "keio"
print("before function, strn ==", strn)
strn2 = change_string(strn)
print("after function, strn ==", strn)
print(" strn2 ==", strn2)
|
from backend_dij import *
import numpy as np
import math
import sys
'''
print("The start and end coordinates should lie between 200 x 300 area.")
startRow = int(input("Enter the x-coordinate for start node: "))
startCol = int(input("Enter the y-coordinate for start node: "))
goalRow = int(input("Enter the x-coo... |
# All of the utility classes, methods, and functions are contained here. Where most of the math actually happens.
# ---DISCLAIMER---
# Most of the things in this file are formulas I Googled, code that was part of the example bot (like Vector3), or from
# the RLBot community. That being said, I did put a lot of time int... |
# Definitions
def show():
print()
print(f" 0 1 2 ")
print("--------------")
for i, row in enumerate(field):
row_str = f"{i}| " + " | ".join(row) + " |"
print(row_str)
print("__")
print()
#---------------------------
# Делаем ход
def ask():
while True:... |
# Copyright (c) 2021 D.Damian
# Released under the MIT license
# ************************************************************************************************
# check if range of numbers contains any palindrome (number which look the same when read forward and backward)
# Example numbers: 59395
# *******************... |
import os
os.system("cls")
i=5
for j in range(i):
x=int(input("Wpisz liczby, którą chciałbyś podnieść do kwadratu: "))
print(x*x) |
from Tkinter import *
root= Tk()
labelframe= LabelFrame(root,text="This is a Labelframe")
labelframe.pack(fill="both", expand="yes")
left= Label(labelframe,text="Inside the LabelFrame")
left.pack()
root.mainloop()
#also try expand="no" and see
|
from Tkinter import *
root=Tk()
frame= Frame(root)
frame.pack()
bottomframe= Frame(root)
bottomframe.pack(side= BOTTOM)
redbutton= Button(frame,text="Red", fg="red")
redbutton.pack(side= RIGHT)
brownbutton= Button(frame,text="Brown", fg="Brown")
brownbutton.pack(side= LEFT)
bluebutton= Button(frame,text="Blue", f... |
from itertools import imap
from random import uniform
def monte_carlo_integrate(func, xmin, xmax, num_points=100):
"""Performs definite integration on :param func:.
The range is specified by the range :param xmin: < :param xmax:
:param num_points: defines the resolution of the grid. Higher numbers
... |
# Dictionaries and sets are both data collections in python
## Dicts?
### sets?
# dicts are another way to manage data but can be a little more dynamic
# Dict works as a JEY and VALUE
# KEY = the refernce of the object
# VALUE = What is the data storage mechanism you need to use
# Dynamic as it we have lists, and ano... |
import matplotlib.pyplot as plt # pyplot is used to plot a chart
from sklearn import datasets # datasets are used as a sample dataset, contains set that has number recognition data
from sklearn import svm # for the sklearn Support Vector Machine
digits = datasets.load_digits() # digits variable loaded with digit d... |
#Day 19 of 100 days of code
#Removing Loops
"""
This method is also dependent on Floyd’s Cycle detection algorithm.
Detect Loop using Floyd’s Cycle detection algorithm and get the pointer
to a loop node.
Count the number of nodes in loop. Let the count be k.
Fix one pointer to the head and another to a kth node from t... |
#Day 21 of 100 days of code
#Circular LinkedList
"""
Circular linked list is a linked list where all nodes are connected to form
a circle. There is no NULL at the end. A circular linked list can be a singly
circular linked list or doubly circular linked list.
"""
"""
Advantages of Circular Linked Lists:
1) Any node ... |
#DAY 10 OF 100 DAYS OF CODE
#Dates
import datetime
"""
A date in Python is not a data type of its own,
but we can import a module named datetime to work with dates as date objects.
"""
x= datetime.datetime.now()
print(x,"\n")
print(x.year,"\n") #getting year
print(x.strftime("%A"),"\n") #getting day
#Creating Date... |
#DAY 14 0F 100 DAYS OF CODE
#Linked List Continue
class Node:
def __init__(self, data=None):
self.data =data
self.next= None
class LinkedList:
#initalizing head
def __init__(self):
self.head = None
#Inserting at Begining
def push(self, newData):
newNode = Node(... |
#DAY 9 OF 100 DAYS OF CODE
#Inheritance
"""
Inheritance allows us to define a class that inherits all the methods and properties
from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
"""
class P... |
#Day 16 of 100 days of code
#Linked List Continue
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
#Rev... |
class Dino:
@staticmethod
def exe1():
print("al carajo 1")
def exe2(self):
print("al carajo 2")
class Car(Dino):
wheels = 0
def __init__(self, color, x, func):
self.color = color
self.f = func
Car.wheels = x
while (True):
print("yey")
Dino.exe1()
din = Dino()
din.exe2()
f = lambda x: x+1
#print(f(2... |
# -*- coding: utf-8 -*-
"""
@author: Michał Worsowicz
"""
import requests
from http.server import HTTPServer, BaseHTTPRequestHandler
from sys import argv
from urllib.parse import urlparse
import json
class Server_Application(BaseHTTPRequestHandler):
"""
Class to represent a server application w... |
from math import radians, cos, sin, asin, sqrt
class Location:
"""
Object representation of latitude and longitude in Decimal Degrees format
Decimal Degrees format:
(+|-)degree where (+) indicates N and E, (-) indicates S and W
degree° (N|S|E|W)
Degrees and Decimal M... |
numero = int(input("Digite um número : "))
sucessor = numero + 1
antecessor = numero - 1
print("Sucessor do número {} é {} ".format(numero, sucessor))
print("Antecessor do número {} é {} ".format(numero, antecessor))
|
km = float(input("Quantos km você rodou com o carro alugado ? "))
dias = float(input("Por quantos dias você alugou o carro ? "))
km2 = ( km * 0.15 )
dias2 = dias * 60
total = km2 + dias2
print(" Você deve pagar R${:.2f} pelo dias que alugou, e R${:.2f} pelos kilometros rodados com o carro ! \n O total a pagar é {:.2f} ... |
n1 = int(input("Digite um número para ver sua tabuada : "))
n11 = n1 * 1
n12 = n1 * 2
n13 = n1 * 3
n14 = n1 * 4
n15 = n1 * 5
n16 = n1 * 6
n17 = n1 * 7
n18 = n1 * 8
n19 = n1 * 9
n110 = n1 * 10
print('-' * 12)
print("{} x 1 = {:2} ".format(n1, n11))
print("{} x 2 = {:2} ".format(n1, n12))
print("{} x 3 = {:2} ".format(n1... |
# GENERATE Bilangan Prima
# Bil Prima : Hanya Bisa di bagi 1 dan dirinya sendiri, Contoh : 5 hanya bisa dibagi 1 dan 5
# Bukan Prima : Contoh 6 : bisa dibagi 1 ,2 ,3, 6
# Definisikan Fungsi sederhana untuk cek apakah bilangan tersebut prima contoh : is_prime(4)
def is_prime(num):
for i in range(2, num):
i... |
# Umur 0 - 5 -> Terlalu kecil untuk Sekolah
# Umur 6 - 12 -> Pergi ke SD print => SD Kelas 1 - SD Kelas 6
# Umur 13 - 15 -> Pergi ke SMP print => SMP Kelas 1 - SMP Kelas 3
# Umur 16 - 18 -> Masuk SMA
# Jika Mampu selesaikan tidak kurang dari 14 baris
umur = eval(input("Masukkan Umur : "))
if umur <= 5:
print("Ter... |
import math
import random
# Generate random list with value between 1 - 9
# Create initial List
# use forloop
# use list append and random module to the initial list
# Print Result |
# for x in range(1,1001):
# if x%2 == 1:
# print x
# for x in range(5,1000001):
# if x%5 == 0:
# print x
# sum = 0
# for count in a:
# sum += count
# print sum
# print sum/len(a)
def counting():
for x in range(1,2001):
if x%2 == 1:
y = "odd"
else:
y = "even"
print "number is {}. This is an {} num... |
# Given a positive integer num, write a function which returns True if num is a perfect square else False.
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
sqrt = 0
x = 0
while sqrt < num:
x += 1
... |
def bubblesort(array):
swaps = True ### Short Bubble: breaks if no swaps
for i in range(len(array)):
swaps = False
for x in range(len(array)-i-1):
if array[x+1]<array[x]:
swaps = True
temp = array[x+1]
array[x+1] = array[x]
array[x] = temp
return array |
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have... |
def main():
'''
Objective : To display percentage of marks scored by the student
Input Parameters: None
Return Value : None
'''
totalMarks = 0
nSubjects = 0
while True:
marks = input('Marks for subject ' + str(nSubjects + 1) + ':')
if marks == '': #End of input
... |
a=3
def f():
def g():
global a
a=4
print('inside g, global a=',a)
g()
a=5
print('inside f, local a=',a)
f()
print('outside of all functions definitions a=',a)
|
nums = list(range(1, 5))
doubled = [ y * 2 for y in nums ]
print(nums)
print(doubled)
# need a square root function
from math import sqrt
# generate numbers for "o" (opposite of a right triangle) in range 1-13 inclusive
# for each of those, generate values for "a" (adjacent side) in range 1 - one-less-than opposite s... |
def mypower(x,n):
if n==0:
return 1
temp = mypower(x,n/2)
if n%2==1:
return temp*temp*x
else:
return temp*temp
def power(x,n):
if n==0:
return 1
neg = False
if x<0:
neg = True
x *= float(-1)
if n<0:
x = float(1)/x
n *= (-1)... |
name = input('Qual seu nome? ').strip()
name_list = name.split()
print(name_list[0])
print(name_list[len(name_list)-1]) |
print('=====Desafio 2=====')
month = input('Qual seu mês de nascimento ?')
day = input('Qual seu dia de nascimento ?')
yaer = input('Qual seu ano de nascimento ?')
print('Tu nasceu em', day, 'de', month,'de', yaer) |
# =========Desafio 20==========
# Embaralhando nomes
import random
name1 = str(input("Infome o primeiro aluno: "))
name2 = str(input("Infome o segundo aluno: "))
name3 = str(input("Infome o terceiro aluno: "))
name4 = str(input("Infome o quarto aluno: "))
names = [name1,name2,name3,name4]
sort = random.shuffle(name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.