text stringlengths 37 1.41M |
|---|
import random
def Name():
a = random.randint(0, 5)
Names = ["Bob", "Robert", "Roberto", "Roberta", "Robin", "Rose"]
print(Names[a])
def Menu():
s = random.randint(0, 2)
m = random.randint(0, 3)
d = random.randint(0, 1)
sides = ["salad", "soup", "bread"]
mainCourse = ["salmon", "pizza",... |
def factor(num1, num2):
if num2 % num1 == 0:
return True
else:
return False
def FizzBuzz(num):
if num == 0:
print("Bad number")
elif factor(15, num):
print("FizzBuzz")
elif factor(5, num):
print("Buzz")
elif factor(3, num):
print("Fizz")
else:
... |
import random
#reads file
def readFile(fileName):
f = open(fileName, "r")
content = f.readline()
return content
#writes file
def writeFile(fileName, content):
f = open(fileName, "w")
f.write(content)
f.close()
#interprets the file so that the file is put into a dictionary format, and returns ... |
roman_numerals = {"M":1000,"CM":900,"D":500,"CD":400,"C":100,"XC":90,"L":50,"XL":40,"X":10,"V":5,"IV":4,"I":1}
def roman_int(user_choice):
if user_choice == "1":
user_roman = input("What numeral would you like to convert?\n").upper()
resultI = 0
for k,v in roman_numerals.items():
... |
p = int(raw_input())
factorial = 1
for i in range(1,p+ 1):
factorial = factorial*i
print(factorial)
|
class stack_min:
num_of_stacks = 0
def __init__(self):
self.top = None
self.min_stack = []
stack_min.num_of_stacks+=1
class stack_node:
def __init__(self,data= None):
self.data = data
self.next = None
def push(self,data):
... |
from LinkedList import *
from math import *
#Stack approach.
def palindrome(LL):
sta = stack()
tmp = LL.head
while tmp!=None:
sta.push(tmp)
tmp = tmp.next
tmp = LL.head
while tmp != None and tmp == sta.peek():
tmp = tmp.next
sta.pop()
if sta.peek() == None and t... |
#Array ascii method no bit vector (original way I coded it).
def isUnique1(st):
if len(st) > 128:
return False
list = [0] * 128
for c in st:
list[ord(c)]+=1
if list[ord(c)] > 1:
return False
return True
#Sort method
def isUnique2(st):
st = sorted(st)
for i in range(1, len(st)):
if st[i] == st[... |
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self,name, position):
super(Employee, self).__init__(name) #this is better than the hard coding way of initialization, because the sub class may be inherited from more than one parent class
s... |
import tensorflow as tf
import numpy as np
import collections
#logistic = lambda x: 1.0/(1+np.exp(-x))
#print(logistic(3))
# Example 1:
#j = tf.constant(0)
#c = lambda i: tf.less(i, 9) # loop termination condition
#b = lambda i: tf.add(i, 1) # loop body: loop body that is executed in each loop
#r = tf.while_lo... |
"""
a class of stars is written in this module
"""
import const_and_inp
class Star:
def __init__(self, star_id, ra, dec, mag):
"""
the star object characterizes 5 attributes, id, ra, dec, mag and distance,
the distance we count as having ra and dec
"""
self.id = star_id
... |
import itertools
import copy
# Takes a list of integers shipments and an int capacity and returns a list of shipments that best fit the given capacity.
def get_optimal_load(capacity, shipments):
# Get all unique combinations of shipments that are less than or equal to the truck's capacity.
combinations = [el f... |
name_file = open("name.txt", "w")
user_name = input("Please enter your name:")
print(user_name, file=name_file)
name_file.close()
name_file = open("name.txt", "r")
name = name_file.read().strip()
name_file.close()
print(name)
|
# conditional
a = 10
if 0 < a < 11:
print('cool')
b = int(input('input number : '))
if (b > 10):
pass
elif (b < 10):
print(f'input number is {b}')
else:
print('input number is 10')
# loop
print('loop in list')
l = [1,2,3,4,5]
for i in l:
print(i)
print('loop in tuple')
t = (1,2,3,4,5)
for i in t... |
print ("put the measurements of you fish tankin cm centimeters" )
print ("hegiht")
heigth =eval(input())
h = heigth
print ("deep")
deep=eval(input())
d = deep
print ("large")
large= eval(input())
l = large
mileliters = d*l*h
liters = mileliters /1000
print ("liters of fish tank have ")
print(liters)
if d == h ==... |
"""Reactor with socket.select
First, instantiate a reactor.
Next, register a file descriptor integer and corresponding
object with the reactor.
Then, register read or write on the integer (and therefore object)
in order to have that object called on that read or write event
Implement the read_event / write_event in... |
'''
Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line... |
'''
Given two arrays X and Y of positive integers, find number of pairs such that xy > yx (raised to power of) where x is an element from X and y is an element from Y.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test consists of three lines. T... |
"""Weekdays in December"""
import sys
import datetime
def get_weekday(number):
return datetime.date(2017, 12, number).weekday()
for input in sys.stdin.readlines():
values = input.split(' ')
for i, value in enumerate(values):
if value == "end":
sys.exit(0)
elif value... |
import turtle
wn=turtle.Screen()
t1=turtle.Turtle()
def drawSquareAt(x,y,size):
t1.penup()
t1.goto(x,y)
t1.pendown()
for a in range(0,4):
t1.fd(size)
t1.rt(90)
def drawTriangleAt(x,y,size):
t1.penup()
t1.goto(x,y)
t1.pendown()
for a in range(0,3):
... |
# https://www.hackerrank.com/challenges/validating-credit-card-number/problem
# Those two lines make the code 1:1 compatiple with hackerrank
f = open('./input/test_case_5.txt')
input=f.readline
import re
def validate(cnum):
if re.match('\d{5}-', cnum)!=None:
return False
if re.match('-\d{5}', cnum)!... |
def iterativeFactorial(x):
if(x==0): return 1
factorial = 1
for i in range(1,x+1):
factorial*=i
return factorial
def recursiveFactorial(x):
if(x==0): return 1
return x * recursiveFactorial(x-1)
print(iterativeFactorial(5))
print(recursiveFactorial(5))
|
"""
Inheritance tools.
------------------
This sets up inheritance of the docstrings for use when we inherit
classes. This makes it simple to add further details to or replace the
docstring present on the base class.
"""
def update_docstring(method_name, content, append=True):
r"""
Update docstring of (an in... |
size = 8
a = [2 * n for n in range(size * size)]
Sums = [0 for i in range(3)]
def t():
for k in range(3):
Sum = 0
for i in range(size):
for j in range(size):
tmp = a[i * size + j]
Sum += tmp
Sums[0] += Sum
t()
print(Sums)
|
def t():
for j in range(len(a)):
for i in range(len(b)):
c[j] = b[i] + a[j]*2
a = [1., 2., 3.]
b = [4., 5., 6.]
c = [0., 0., 0.]
t()
print(c)
d = [10., 20., 30.]
for i in range(len(a)):
a[i] = d[i]
t()
print(c)
|
size = 8
a = [2 * n for n in range(size)]
Sums = [0]
def t():
for k in range(3):
Sum = 0
x = 0
for i in range(size):
x = i
Sum += a[i]
Sums[0] += Sum + x
t()
print(Sums)
|
#Object to be clustered
class DataObject:
def __init__(self, name, values):
self.name = name
self.values = values
def __str__(self):
return self.name
def __repr__(self):
return self.name
#Two clusters (from and to) and the distance between the two clusters
class DistanceMeasurement:
def __init__(self, fm... |
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить, является ли
# он разносторонним, равнобедренным или равносторонним.
side_a = int(input('Введите первую сторону треугольника: '))
s... |
#Задание 2
#По введенным пользователем координатам двух точек
#вывести уравнение прямой вида y = kx + b, проходящей через эти точки.
# Уравнение прямой имеет вид (y-y1) / (y2-y1) = (x - x1) / (x2 - x1)
# => k = (y1 - y2)/-c b = (x1*y2 - x2*y1) / -c c = (x2-x1)
#Точка 1
x1 = int(input('x1 = '))
y1 = int(input('y1 = '... |
def func(a, b) -> str:
if (a==b):
return f'{a}'
elif (a > b): #по возрастанию
return f'{a}, {func(a-1, b)}'
elif (a < b): #по убыванию
return f'{a}, {func(a+1, b)}' #f строки
print(func(8, 10000)) #глубина рекурсии 1000
|
class Point:
"""Point Model"""
def __init__(self, position):
self.__charge = -1
self.__position = position
self.__distance = []
def __str__(self):
return "Point: " + self.__position
@property
def charge(self):
return self.__charge
@charge.setter
de... |
graph = {
1:[2,3,4],
2:[],
3:[5],
4:[6],
5:[],
6:[]
}
visited = []
queue = []
def bfs( node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph:
if neighbour not in visited:#neigh... |
weather_tbl=[] #for weather
play_tbl=[] #for play
n=int(input("Enter number of dataset:"))
for i in range(n):
weather=input("Enter weather name:")
weather_tbl.append(weather.lower())
play=input("Enter paly or not:")
play_tbl.append(play.lower())
t_rainy_y=t_rainy_n=0
t_y=t_n=0
t_rainy=0
for i in ... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
openParen = '([{'
closeParen = ')]}'
parenStack = []
for p in s:
if p in openParen:
parenStack.append(p)
elif p in closeParen:
... |
import random
class Stack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.container == []
def push(self, item):
self.container.append(item)
def pop(self):
return self.container.pop()
def peek(self):
return self.cont... |
# Given a non negative integer number num.
# For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in
# their binary representation and return them as an array.
class Solution:
def countBits(self, num: int):
return [self.hammingWeight(n) for n in range(num + 1)]
def hammingWeight(x... |
for x in range(3):
user=input("Ingresa el usuario");
pas=input("ingresa paswors");
if(user=="alex" and pas=="3ct"):
print("Bienvenido" + user);
break;
else:
print("verificar datos");
|
numero = int(input("dame el numero de la taba "));
x=1;
while x<=10:
# print("el resultado de "+ str(numero) +" * "+str(x)+" es " +str(x*numero));
print(f'{x * numero}');# Epesiones
x+=1;
|
print('----------------------------------')
year=int(input("请输入年份:"))
month=int(input("请输入月份:"))
day=int(input("请输入日期:"))
monthlist=[31,28,31,30,31,30,31,31,30,31,30,31]
sum=day
if year % 4==0 and year % 100 !=0 or year % 400==0:# or 表示只要满足两方一个条件即可,即为闰年。
monthlist[1]=29
for i in range(month-1):# range(0)=[] r... |
sum=0
for i in range(100):
if i %2 !=0:
sum=sum+i
print(sum)#在这里打印就是每循环一次就打印一次
else:
continue
#倘若在这里打印,那么直接将所有循环后相加的和打印出来
|
'''x={'陈':1,'思':2,'未':3,'帅':4}
for i in x:
print(x[i])'''
x=[59,70,58,60,61]
a=[]
b=[]
for i in x :
if i>=60:
a.append(i)
else:
b.append(i)
print('不小于60的数组:',a)
print('小于60的数组:',b)
#print(a,end='@')
#print(b,end='@')
|
"""
Functions for ActivityLogger
Luke Fitzpatrick 2014
"""
import os.path
from datetime import *
ACTIVITYFILENAME = "activities.txt"
def loadActivities():
"""
Loads and returns a list of all activities in the activities.txt file.
"""
try:
f = open(ACTIVITYFILENAME, 'r')
lines ... |
#!/usr/bin/python
import sys
import lxml
from lxml import html
import urllib
import urllib2
# read page html
def get_page(url):
request = urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)')
response = urllib2.urlopen(request)
html = response.read()
response.... |
from contact_book.src.contacts_trie import Trie, insert_data, search_data
def deligator(choice):
deligator_map = {
1: insert_data,
2: search_data,
}
return deligator_map.get(choice)
class ContactBook:
def __init__(self):
self.name = Trie('')
self.surname = Trie('')
... |
lst=[1,2,3,4]
sq=[(i*i) for i in lst]
print(sq)
pairs=[(i,j) for i in lst for j in lst if i!=j]
print(pairs)
odd=[i for i in lst if i%2!=0]
print(odd) |
class Employee:
def __init__(self,eid,name,des,salary):
self.eid=eid
self.name=name
self.des=des
self.salary=int(salary)
def printValues(self):
print(self.eid,self.name,self.salary)
def __str__(self):
return self.name
f=open("edetails","r")
emplst=[]
for ... |
from re import *
pattern="a{2}" #two noes of a
pattern="a{2,3}" #min 2 noes max 3 noes of a
matcher=finditer(pattern,"abaaabaaaaa 05@x")
for match in matcher:
print(match.start())
print(match.group()) |
lst=['x','y','z','x']
for i in range(len(lst)-1):
for j in range(i+1,len(lst)):
if(lst[i]!=lst[j]):
print(lst[i], lst[j])
|
lst=[]
newlst=[]
n=int(input("enter the size of list"))
print("enter elements:")
for i in range(0,n):
ele=int(input())
lst.append(ele)
for i in lst:
if i not in newlst:
newlst.append(i)
print(newlst)
|
from re import *
pattern="\s" #spaces
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\d" #[0-9]
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\D" #[^0-9]
matcher=findit... |
#program to print star triangle
n=int(input("enter the number of rows"))
sp=2*n-2 #calculating the space needed
for i in range(1,n+1):
for j in range(0,sp):
print(end=" ")
sp=sp-1
for k in range(0,i):
print("*",end=" ")
print(" ")
|
#program to check whether a given sequence is palindrome or not
num=int(input("enter a number"))
temp=num
rev=0
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
#print(rev)
if(temp==rev):
print("palindrome")
else:
print("not palindrome")
|
# APPROACH 1: BRUTE FORCE (MY APPROACH)
# Time Complexity : O(n^3) - n is the length of nums
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : No (TIME LIMIT EXCEEDED)
# Any problem you faced while coding this : None
#
#
# Your code here along with comments explaining your approach
# 1. Consider... |
import random
class Card(object):
#constructor
def __init__(self,suite,face):
self._suite = suite
self._face = face
self._showCase = ''
#self._faceShowing = ''
#getter and setter
@property
def suite(self):
return self._suite
@property
def face(se... |
'''OOP NOTES'''
class Student(object):
#slots : restrict constructor: what attribute can user setup.
__slots__ = ("_name","_age","_email")
# constructor
def __init__(self, name, age, email):
self._name = name
self._age = age
self._email = email
#getter
@property... |
# Menu
from ram import ram
import Creacion_archivo
ram = ram()
def subir_archivo():
nombre_archivo = raw_input("introduzca el nombre del archivo a subir ")
espacio_suficiente, cant_bloques = Creacion_archivo.restriccion_archivo(nombre_archivo)
if espacio_suficiente:
ram.agregar_archivo(cant_bloques, nombre_arc... |
import json
import datetime
class MyEncoder(json.JSONEncoder):
'''
Usage, when you call a json.dumps(), call like
json.dumps(obj, cls = MyEncoder), to convert json
objects to str object
'''
def default(self, obj):
if isinstance(obj, datetime.datetime):
return ob... |
class ASTVisitor():
'''
Wrapper class to walk througha tree and visit each Node.
'''
def visit(self, astnode):
'A read-only function which looks at a single AST node.'
pass
def return_value(self):
return None
class ASTModVisitor(ASTVisitor):
'''
A visitor class th... |
import re
import phonenumbers
### Checks if a variable is empty or not ###
def is_empty(variable):
if variable:
return variable
else:
return None
# # An array of fields to be validated
# validation_list = [
# # Each element is made up of the field that is being validated
# # and the alias of the field t... |
'''
Created on 31/05/2012
@author: ultrazoid_
'''
def length(lists):
lengths = 0
for ind in lists:
lengths +=1
return lengths
x=[1,2,3,4,5,6,7,8,9,0]
print length(x) |
#hello python3
print("hello pyhon3")
j = 1
i = 5
print(f"i={i}")
print("i=",i)
i = i+1
print(f"after i++; i={i}")
def print_max(a,b):
print(f"a={a}, b={b}")
if(a>b):
print("max is", a)
else:
print("max is", b)
print_max(8,11)
def global_test():
global i
i = 11
print(f"in glo... |
##def count_adjacent_repeats (s):
## '''
## (str) -> int
##
## Return the number of occurrences of a character and an adjacent
## character being the same.
##
## >>>count_adjacent_repeats ('abccdeffggh')
## 3
## '''
## repeats = 0
##
## for i in range(len(s)-1):
## if s[i]... |
"""Frequent Words with Mismatches and Reverse Complements Problem
Find the most frequent k-mers (with mismatches and reverse complements) in a DNA string.
Given: A DNA string Text as well as integers k and d.
Return: All k-mers Pattern maximizing the sum Countd(Text, Pattern) + Countd(Text, Pattern) over all possibl... |
"""BA1_ba1b: Frequent Words Problem
Find the most frequent k-mers in a string.
Given: A DNA string Text and an integer k.
Return: All most frequent k-mers in Text (in any order)"""
import os
path=os.getcwd()
from BA1_ba1a import PatternCount
def CountDict(Text, k):
"""Generates a dictionary that count... |
from disjoint_set import DisjointSet
class UnionBySizeDisjointSet(DisjointSet):
def __init__(self, n):
self.n = n
self.parent = [-1 for _ in range(n)]
def find(self, x):
while not self.parent[x] < 0:
x = self.parent[x]
return x
def union(self, x, y):
x... |
def love(size):
for a in range(int(size/3),size,2):
for b in range(1, size - a, 2):
print(" ",end = "")
for b in range(1, a + 1):
print("*", end="")
for b in range(1, (size - a) + 1):
print(" ", end="")
for b in range(1,a):
print("*", e... |
def divisors(n):
i=1
while (i<n+1):
if(n%i==0):
print(i)
i+=1
print("please enter a number")
n=int(input())
divisors(n)
|
#IF ELSE STATEMENT
n1=20
n2=30
if n1>n2:
print("n1 is greater")
else:
print("n2 is greater") |
def sum(*n1):
sum=0
for i in n1:
sum=sum+i
print("Ans is ",sum)
sum(10,20)
sum(10,20,30) |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
from itertools import permutations, combinations
def find_shortest_path(board, start, end):
R = len(board)
C = len(board[0])
queue = [(start, 0)]
seen = set([start])
while queue:
(r, c), steps = queue.pop(0)
DR = [-... |
import sys
from collections import Counter
from typing import List
def prep(board: List[str]) -> set((int, int)):
return set([(x, y, 0)
for y, row in enumerate(board)
for x, c in enumerate(row)
if c == '#'
])
NEIGHBOURS = set([(1, 0), (-1, 0), (0, 1), (0, -1)])
def prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 07:47:15 2020
@author: KEV
"""
from marco import *
import tkinter as tk
from tkinter import Canvas
class ventana:
def __init__():
__marco__ = marco.__init__()
ln = tk.Label(__marco__, text ="A continución digíte el grado de ... |
import geojson
import parse as p
def create_map(data_file):
# Define the GeoJSON that we are creating
geo_map = {"type": "FeatureCollection"}
# make an empty list to collect the points for plotting
item_list = []
# Iterate through the input data to make the GeoJSON document The enumerate
# fu... |
"""
# Module 4- Example Plot of Weather Data
#### author: Radley Rigonan
In this module, I we will be using data from RadWatch's AirMonitor to create a plot that compares
counts per second (CPS) due to Bismuth-214 against the CPS of the lesser occurring isotope Cesium-137.
I will be using the following link:
ht... |
# -*- coding: utf-8 -*-
"""
#### Module 7- Data Sorting and Searching
Computer scripts excel at performing repetetive tasks that would normally be tedious or uninteresting to do by hand. Therer are many useful jobs that programs can perform, but in this module I will demonstrate three common data-processing techn... |
import random
from Trie import *
from HashTable import *
#Setting the student directory and hash table as global variables
directory = Trie()
Hash = HashTable()
#A function which adds new students to the directory
#The function also gives the students a slot in the HashTable
#The slot holds the student name and the s... |
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
n = len(board)
m = len(board[0])
for i in range(n):
for j in range(m):
visited = [[False] * m for i in range(n)]
if board[i][j]==word[0]:
if se... |
# we will calculate the darivative of an image
import numpy as np
import cv2
from matplotlib import pyplot as plt
def callMe():
# der()
test()
pass
def der():
img = cv2.imread("/home/hp/PycharmProjects/image/data/dog2.jpg", 0)
# cv2.imshow('Image', img)
print(img.shape)
print(img)
... |
import time
start_time = time.time()
def even(list1):
list1=[int(n) for n in str(list1)]
list2= [0,2,4,6,8]
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
return result
def candidate_range(n):
cur = 5
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = 'Ulises Olivares - uolivares@enesmorelia.unam.mx
import os
from collections import defaultdict
import csv
def readFiles():
'''
This function reads all the files contained in the data directory and returns
:return:
'''
files = []
for... |
# Suppose we had a list S and a number N. How can we find out whether there is a subset in S that
# adds up to N?
def f(N, S):
r = 0
if N == 0:
return 1
if not S:
return 0
for num in S:
print(f'{N} {S}')
r += f(N - num, remove(S, num))
return r
# Removes an element... |
def quicksort(a):
if len(a) <= 1:
return a
left = []
right = []
equal = []
pivot = a[-1]
for num in a:
if num < pivot:
left.append(num)
elif num > pivot:
right.append(num)
else:
equal.append(num)
return quicksort(left... |
__author__ = 'Sean Moore'
"""
Problem:
Run-length encoding is a fast and simple method of encoding strings. The basic
idea is to represent repeated successive characters as a single count and
character. For example, the string "AAAABBBCCDAA" would be encoded as
"4A3B2C1D2A".
Implement run-length encoding and decodin... |
__author__ = "Sean Moore"
"""
Problem:
Given a list of integers, write a function that returns the largest sum of
non-adjacent numbers. Numbers can be `0` or negative.
For example, `[2, 4, 6, 2, 5]` should return `13`, since we pick `2`, `6`,
and `5`. `[5, 1, 1, 5]` should return `10`, since we pick `5` and `5`.
Fo... |
__author__ = "Sean Moore"
"""
Problem:
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplicates and negative
numbers as well.
For example, the input [3, 4,... |
__author__ = "Sean Moore"
"""
Problem:
Compute the running median of a sequence of numbers. That is, given a stream of
numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two
middle numbers.
For example, given the sequence [2, 1... |
import random
def load_words(filename):
#with open(filename, 'r') as f:
# file_string = f.read()
#words = file_string.split()
words = ['hello', 'bye', 'world']
return words
def choose_secret_word(words):
word = random.choice(words)
return word
def is_secret_guessed(secret_word, letters_guessed):
all_gues... |
# created by jenny trac
# created on Nov 20 2017
# program lets user calculate average of marks
import ui
marks = []
def enter_touch_up_inside(sender):
# button to add marks to the array
global marks
try:
new_mark = int(view['input_textfield'].text)
if new_mark >= 0 and new_mark... |
from random import sample
print('Bem-Vindo ao sorteador de ordem!')
n1 = input('Informe o primeiro nome')
n2 = input('Informe o segundo nome')
n3 = input('Informe o terceiro nome')
n4 = input('Informe o quarto nome')
lista = [n1, n2, n3, n4]
sorteados = sample(lista, 4)
print('Os alunos que apresentaram na seguinte or... |
numeros = list()
escolha = ''
while True:
num = int(input('Informe um número para a lista'))
if not num in numeros:
numeros.append(num)
print('Valor \033[32madicionado\033[m.')
else:
print('Já existe esse valor na lista, \033[31mnão\033[m será adicionado.')
escolha = input('Você ... |
lista = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez',
'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezesete', 'dezoito', 'dezenove', 'vinte')
while True:
escolha = ' '
num = int(input('Informe o número entre 0 a 20 para ser escrito por extens... |
from random import randint
menor = maior = 0
lista = (randint(-100,100), randint(-100,100), randint(-100,100),
randint(-100,100), randint(-100,100))
print(f'Os valores da tupla são:', end = ' ')
for u in lista:
print(f'{u}', end = ' ')
for c in range(5):
if c == 0 or lista[c] < menor:
menor = ... |
import random
def jogar():
print("\n\nOla felipe vamos arrasar no python!!!!!!!")
print("***********************************************")
print("Bem-Vindo ao Jogo de Adivinhação!")
print("************************************************")
print("Nivel de dificuldade\n(1) facil numeros entre 1 a ... |
marcador = 30 * '\033[33m//\033[m'
while True:
try:
inteiro = input('Informe um número inteiro')
if inteiro.isnumeric():
inteiro = int(inteiro)
else:
inteiro = int('y')
except ValueError:
print('\033[31mERRO!!Digite o número correto\033[m')
else:
... |
frase: str = ' Olá felipe '
print(frase.replace('Olá', 'Oi'))
print(frase.upper())
print('w' in frase)
print(frase.find('ipe'))
print(frase.split('e'))
print(frase.strip())
print('+'.join(frase))
|
from datetime import date
atual = date.today().year
maior:int = 0
menor:int = 0
for y in range(7):
nasc = int(input('Informe o ano do nascimento da {} pessoa'.format(y+1)))
idade = atual - nasc
if idade >= 21:
maior += 1
else:
menor += 1
print('{} pessoas são maiores capazes\n{} pessoas ... |
from math import sqrt, ceil
n = float(input('Informe um número para tirar raiz quadrada'))
raiz = sqrt(n)
print('A raiz de {} é {}'.format(n, ceil(raiz)))
|
n = int(input('Informe um número inteiro'))
print('O número informado foi {}, seu sucessor é {}'.format(n, n+1), end=', ')
print('o antecessor do número é {}'.format(n-1))
|
from random import choice
print('Bem-Vindo ao sorteador de nomes')
n1 = input('Informe o nome do primeiro aluno')
n2 = input('Informe o nome do segundo aluno')
n3 = input('Informe o nome do terceiro aluno')
n4 = input('Informe o nome do quarta aluno')
lista = n1, n2, n3, n4
sorteado = choice(lista)
print('O sorteado fo... |
def voto(nasc):
from datetime import date
atual = date.today().year
idade = atual - nasc
if idade < 16:
return 'Sua idade é {} não pode votar'.format(idade)
elif 16 <= idade < 18 or 65 <= idade:
return f'Sua idade é {idade} seu voto é opcional'
else:
return f'Sua idade é ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.