text stringlengths 37 1.41M |
|---|
# Hangman
# Tejas Gokhale
# 2015-12-02
import string
import random
name = raw_input("Enter your name: ")
print "**** WELCOME TO HANGMAN, %s!" % name ," ****"
print "."
print "."
print "."
path = 'words.txt'
def load_words():
print "Loading words from dictionary ..."
wordFile = open(path, 'r', 0)
line = w... |
# CLASSES
# ****************************************
class parentClass:
var1 = "I'm Iron Man"
var2 = "Let's put a smile on that face"
class childClass(parentClass):
pass
# don't want to copy everything, aka laziness
parentObject = parentClass()
parentObject.var1
childObject = childClass()
childObject.va... |
__author__ = 'tmsbn'
a = [[0, 1],
[1, 2],
[4, 5]]
b = [[11, 1, 2],
[1, 12, 3]]
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# print(len(a[0]), len(b), a[0][1]) # len(a) give the row count, len(a[0] gives the column count of 1st column
# a[row][column])
for i in range(len(a)):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 10:33:28 2018
@author: Vijay
"""
cars = ['bmw','audi','honda']
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
squares = [value**2 for value in range(1,11)]
print(squares)
for car in cars:
if car == 'bmw':
prin... |
def replaceVowels(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
ans = ''
for c in word:
if c not in vowels:
ans = ans + '.' + c
return ans
x = input().lower()
print(replaceVowels(x))
|
# funcion len propia
def len(objeto):
contador=0
for i in objeto:
contador+=1
return contador
print (len([1, 2,3,4]))
print (len ("hola"))
|
phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
# newlist=plist[1:8]
'''newlist1=plist[4:8]
newlist1=newlist1.remove(" ")
newlist2=newlist1.insert(1,newlist1.pop())'''
# newlist.remove("'")
# # ['o', 'n', 't', ' ', 'p', 'a']
# newlist1 = newlist.insert(3,newlist.pop(5))
# print(newlis... |
sum = 2
for x in range(3, 101):
for i in range(2, x):
if x%i == 0 :
break
else:
sum += x
print('一百以内素数之和为',sum)
|
import math
def check_prime(num):
if num > 2 and num % 2 == 0:
return False
else:
# I tried using a generator here,
# but it is slower by a noticeable amount.
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True... |
# This is a single line comment
"""
This is a multiline comment,
that takes up,
multiple lines
"""
# Prints "Hello" to the terminal
print("Hello")
"""
PRIMITIVE DATA TYPES
- integer (1, 2, 3)
- float (1.0, 1.5)
- string ("Hello", "Hi!", "40", "4.5")
- boolean (True, False)
"""
firstVariable = 5
print(firstVariable... |
#!/usr/bin/python3
cigarros = int(input('Cigarros fumados por dia: ' ))
anos = int(input('Anos que fumou: '))
qntCigarros = anos*365*cigarros
dias = int((qntCigarros*10)/1440)
print('Redução do tempo de vida em ' + str(dias) + ' dias')
|
class Person(object):
def __init__(self,name):
self.name=name
def play_with_dog(self,Dog):
print("%s 在和 %s 玩耍——————" % (self.name,Dog.name))
Dog.play()
class Dog(object):
def __init__(self,name):
self.name=name
def play(self):
print("%s 在玩耍------" % self... |
class Gun:
#枪的属性需要从外部输入,但是如果默认每把枪初始子弹都为0,
# 都需要装填子弹,即可不需要外部输入
def __init__(self,model):
self.model=model
self.bullet_count=0
def add_bullet(self,count):
self.bullet_count+=count
def shoot(self):
#要判断子弹数量
if(self.bullet_count>0):
#发射子弹
... |
a = str(input())
#print(a)
#print("." in a)
if ("." in a) == True:
b ,_= a.split(".")
# print("True")
else:
b=a
print(b) |
pages = int(input())
pages_per_hour = int(input())
days = int(input())
hours_for_reading = pages / pages_per_hour / days
print(hours_for_reading)
|
# plot feature importance manually
from numpy import loadtxt
from xgboost import XGBClassifier
from matplotlib import pyplot
# load data
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",")
# split data into X and y
X = dataset[:,0:8]
y = dataset[:,8]
# fit model on training data
model = XGBClassifier()
model.... |
import os
import csv
import numpy as np
csvpath = os.path.join("election_data.csv")
output_path = os.path.join("election_data_output.txt")
month_total = 0
file_data = []
vote_values = []
cand_values = []
# NEED TO CREATE THE FUNCTION THAT ALLOWS YOU TO EXPORT AS A CSV
# Extract the information in a dictionary or l... |
<<<<<<< HEAD
def drawlines(screen,width,x1,x2,y):
byte_width = width//8
height = len(screen)//byte_width
if x1>x2:
x1,x2 = x2,x1
byte = y*byte_width+x1//8
byte_end = y*byte_width+x2//8
screen[byte] = (1<<(x1%8))-1
byte +=1
while byte<byte_end:
screen[byte]= 255
... |
def stack_boxes(boxes):
sorted_boxes = sorted(boxes,key=lambda x: x.height, reverse=True)
return stack_more_boxes(sorted_boxes,None,0)
def stack_more_boxes(boxes,base,index):
if index>=len(boxes):
return 0
without_box_height = stack_more_boxes(boxes,base,index+1)
box = boxes[index]
if n... |
def peaks_and_valleys(array):
if len(array)<3:
return
for ix in range(len(array)-1):
if ix%2:
if array[ix]<array[ix+1]:
array[ix],array[ix+1]=array[ix+1],array[ix]
else:
if array[ix]>array[ix+1]:
array[ix],array[ix+1]=array[ix+1],... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################################################
#
# Program name: traverse.py
# Created: Sun Jan 7 2018 13:03
# author: Stephen Flowers Chávez
#
########... |
# !/bin/python3
import math
import os
import random
import re
import sys
def solve(s):
# list1 = []
for _ in range(len(s)):
# list1.append(s[i].capitalize())
list1 = [word.capitalize() for word in s.split(' ')]
return (' '.join(list1))
if __name__ == '__main__':
with open(os.environ... |
import os
import conversions
import functions
import input_padding
import tkinter as tk
# CREATE FILES CONTAINING INITIAL VALUES #
"""
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,
67,71,73,79,83,89,97,101,103,107,109,113,127,131,
137,139,149,151,157,163,167,173,179,181,191,
193,197,... |
from typing import List, Optional
class View:
children: List["View"]
def __init__(self, name: str, cost: float, is_materialized=False):
self.name = name
self._cost = cost
self.parents: List["View"] = []
self.children: List["View"] = []
self.is_materialized = is_materia... |
"""This module provides an implementation of the Bag ADT.
The ADT is implemented in class Vector.
Author: Yue Hu
"""
from array import Array
class Vector:
def __init__ ( self, size ):
""" Constructs an empty vector with an initial capacity of two elements."""
size=2
self._theVect = Array( size )
sel... |
'''
https://codefights.com/arcade/intro/level-2/xskq4ZxLyqQMCLshr
Created on 2018年2月5日
@author: rocky.wang
'''
def matrixElementsSum(matrix):
total = 0
for w in range(len(matrix[0])): # width
for h in range(len(matrix)): # height
if matrix[h][w] == 0:
break
els... |
import time
file_name = input("Enter text file name => ") + ".txt"
try:
with open(file_name, "r") as file:
find_word = input("Enter word you want to replace => ")
replace_word = input("Enter word you want to replace with => ")
file_data = file.read()
while True:
word_index = file_data.... |
# -*- coding: utf-8 -*-
# @Time : 2021/4/24 下午6:14
# @Author : ShaHeTop-Almighty-ares
# @Email : yang6333yyx@126.com
# @File : 05.private_property_demo.py
# @Software: PyCharm
class A:
_y = '_y'
__y = '__y'
def _a(self):
print('_a')
def __a(self):
print('__a')
def get_y... |
# -*- coding: utf-8 -*-
"""
This is for Jon Snow using Uniform Cost Search
This is to find the quickest route to his goal.
John Snow's goal is to reach the white walkers as
they leave the wall
@author: Ashley
"""
import queue as que
def ucsJS(nodeMap, start, goal):
visited = set()
stack = [start]... |
"""
Factorial of a number (without using recursion)
"""
def fact_no_recursion(num):
fact = 1
if num == 0:
return fact
else:
for i in range(1,num+1):
fact = fact * i
return fact
x = 7000
y = fact_no_recursion(x)
print("Factorial of {} is {}".format(x, y)) |
a = 1 > 2 # Is 1 greater than 2?
print(a)
a = 1 < 2 # Is 1 less than 2?
print(a)
a = 1 >= 1 # Is 1 greater than or equal to 1?
print(a)
a = 1 <= 4 # Is 1 less than or equal to 4?
print(a)
a = 1 == 1 # is 1 equal to 1?
print(a)
a = 'hi' == 'bye' # is 'hi' equal to 'bye'
print(a)
|
"""
Using the Python map() function
"""
def my_square(x):
y = x * x
return y
numbers = (1, 2, 3, 4)
# First way
y = []
for num in numbers:
y.append(my_square(num))
print("Without using map function ", y)
# A better way
z = map(my_square,numbers) # map applies the my_square on the tuple numbers... |
# solution for https://www.hackerrank.com/challenges/icecream-parlor/problem
import sys
def icecreamParlor(m, arr):
arr = quickSort(m, arr)
for i in range(0,len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == m:
return [a[i], a[j]]
# Complete this function
... |
# solution for https://www.hackerrank.com/challenges/caesar-cipher-1/problem
def caesarCipher(s, k):
res = []
for char in s:
if char.islower():
res.append(rotate(char, 96))
elif char.isupper():
res.append(rotate(char, 64))
else:
res.append(char)
re... |
import math
def hourglassSum(arr):
maxSum = -math.inf
for i in range(0, len(arr) - 2):
for j in range(0, len(arr[i]) - 2):
sum = hourglass(arr, i, j)
if maxSum < sum:
maxSum = sum
return maxSum
def hourglass(arr, i, j):
return sum(arr[i][j:(j+3)]) + ar... |
'''
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário,
mostrando uma mensagem de erro e voltando a pedir as informações.
'''
usuario = input("Informe o nome: ")
senha = input("Informe a senha: ")
while (senha == usuario):
print("Erro!")
print("Digite uma ... |
'''
Faça um programa que receba dois números inteiros e gere os números
inteiros que estão no intervalo compreendido por eles.
'''
n1 = int(input("Informe o primeiro número: "))
n2 = int(input("Informe o segundo número: "))
for Nintervalo in range (n1, n2):
print(Nintervalo)
|
import random
chars = '012345uewuwoirjeiwuruwi54683959048Y489jroieury78o2349u9498yruieiikj4283wujuiy39jr9eijrh78w36789'
number = int(input('Ծածկագրերի քանակը․'))
lenght = int(input('Տողի երկարությունը․'))
for user_name in range(number):
password = ''
for per_user in range(lenght):
passwor... |
import numpy as np
import pandas as pd
class Optimizer:
"""
A class that performs general optimization
todo: list should be changed to numpy
todo: filter and criteria have to have 2 arguments each
todo: add store and load to documentation
Attributes
----------
accepted_choices : list
... |
import numpy as np
class FeatureExtractor:
"""
A base class for feature extraction classes
This class performs no extraction; it returns the dataset as it is. It should be overriden to create feature
extraction classes, in which case, at least fit method should be overriden.
Attributes
------... |
'''
For this assignment you should read the task, then below the task do what it asks you to do.
EXAMPLE TASK:
'''
#EX) Make a variable called name and assign it to your name. And print the variable.
from builtins import False, True
name = "Michael"
print(name)
'''
END OF EXAMPLE
'''
'''
START HERE
'''
name = "Laura"... |
# 앞에서부터 읽을 때나 뒤에서부터 읽을 때나 모양이 같은 수를 대칭수(palindrome)라고 부릅니다.
# 두 자리 수를 곱해 만들 수 있는 대칭수 중 가장 큰 수는 9009 (= 91 × 99) 입니다.
# 세 자리 수를 곱해 만들 수 있는 가장 큰 대칭수는 얼마입니까?
set_A = []
set_B = []
set_C = []
for i in range(100, 1000):
A = i
for k in range(100, 1000):
B = k
C = A * B
str_C = str(C)
... |
# 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.
# reference : http://projecteuler.net/problem=1
mul3_5 = [] # 3의 배수와 5의 배수를 포함한 리스트
for i in range(1,1001):
if i % 3 == 0 o... |
def mas_grande(num1, num2, num3, d):
menor = min(num1, num2, num3)
mayor = max(num1, num2, num3)
medio = (num1 + num2 + num3) - menor - mayor
if d == "N":
print("Los Valores Son: {}, {}, {}".format(mayor, medio, menor))
else:
print("Los Valores Son: {}, {}, {}".format(menor, medio,... |
def compute(x, y):
return x * y
def main():
x = int(input())
y = int(input())
result = compute(x, y)
print(result)
if __name__ == '__main__':
main()
|
def check(num1,num2):
return format(num1^num2,'b').count('1')
c = 0
for i in range(31):
if check(i,0) <= 3 and check(i,3) <= 3:
print(""+"0"*(5-len(format(i,'b')))+format(i,'b'))
c += 1
print(c)
|
S = input()
#print(S)
ans = []
for str in S:
if str == '0':
ans.append('0')
elif str == '1':
ans.append('1')
else:
if len(ans) > 0:
ans.pop()
for a in ans:
print(a,end ="")
print()
|
#import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#importing the dataset
df = pd.read_csv('50_startups.csv')
x = df.iloc[: , :-1].values
y = df.iloc[: , 4].values
#Convert categorical data by Label Encode/One-Hot Encoding
from sklearn.preprocessing import... |
# Import combinations from itertools
from itertools import combinations
# Create a combination object with pairs of Pokémon
combos_obj = combinations(pokemon, 2)
print(type(combos_obj), '\n')
# Convert combos_obj to a list by unpacking
combos_2 = [*combos_obj]
print(combos_2, '\n')
# Collect all possible combination... |
"""Determine if number is palindrome."""
def isPalindrome(x):
"""
Take integer number and determine if palindrome.
:type x: int
:rtype: bool
"""
if x < 0:
return False
# convert to string
x = str(x)
if x[-1] == '0' and len(x) > 1:
return False
if x == x[::-1]:... |
"""Reverse Linked List II."""
def reverse_between(head, m, n):
"""Reverse linked list between m and n."""
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
|
"""Append the sum of prior 3 elements into original 3 element list."""
def tribonacci(signature, n):
"""Render iterative solutions."""
res = signature[:n]
for i in range(n - 3):
res.append(sum(res[-3:]))
return res
"""
[:n], from start to n - 1.
In case n = 0, returns []
range(n - 3) ensure ... |
# encoding: utf-8
"""
@author: Liangzi Rong
@contact: 289770334@qq.com
"""
import copy
import time
def copy_deepcopy():
# copy is much more efficient
a = range(10000)
last_time = time.time()
for i in range(10000):
_ = copy.copy(a)
print('time(s) for copy: ', time.time() - last_time)
... |
# 1046. Last Stone Weight
"""
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x
and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the s... |
# 735. Asteroid Collision
"""
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents
its direction (positive meaning right, negative meaning left). Each asteroid moves
at the same speed.
Find out the state of th... |
# 394. Decode String(M)
"""
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the
square brackets is being repeated exactly k times. Note that k is guaranteed
to be a positive integer.
You may assume that the input string is always valid; No... |
#102. Binary Tree Level Order Traversal
"""
Given a binary tree, return the level order traversal of its nodes' values. (ie,
from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
"""
#-------------------------------------------------------------------------------
# Approach ... |
# 206. Reverse Linked List
# Reverse a singly linked list.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Array
"""
#----------------------------------------------------------------... |
# 234. Palindrome Linked List
"""
Given a singly linked list, determine if it is a palindrome.
"""
#-------------------------------------------------------------------------------
# Approach-
#-------------------------------------------------------------------------------
#----------------------------------------... |
# 127. Word Ladder
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed w... |
# 953. Verifying an Alien Dictionary
# In an alien language, surprisingly they also use english lowercase letters,
# but possibly in a different order. The order of the alphabet is some permutation of
# lowercase letters.
# Given a sequence of words written in the alien language, and the order of the alphabet,
# ret... |
#88. Merge Sorted Array
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# #-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
Two pointers, s... |
## 611. Valid Triangle Number
# Given an array consists of non-negative integers, your task is to count the number
# of triplets chosen from the array that can make triangles if we take them as side
# lengths of a triangle.
#-------------------------------------------------------------------------------
# Approach... |
#141. Linked List Cycle
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
# To represent a cycle in the given linked list, we use an integer pos which represents the position
#(0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in ... |
#298. Binary Tree Longest Consecutive Sequence
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
DFS
"""
#-------------------------------------------------------------------------------... |
#426. Convert Binary Search Tree to Sorted Doubly Linked List
#Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------... |
#!/usr/bin/python3
print('Hi how are you?')
feeling= input()
if feeling.lower()== 'great':
print('i feel great too')
else:
print('too bad!')
|
# name = "Srini"
# age = 23
print ("Hello world")
print("My name is " + name + "my age " + str(age))
print("My name is %s and my age %d" % (name,age))
print("My name is {name} and my age {age}".format(age=age,name=name))
# this syntc work only python 3.6
print(f'My name is {name} my age next year {age+1}')
... |
#codewars link
#https://www.codewars.com/kata/546d15cebed2e10334000ed9/train/python
def solve_runes(runes):
temp = runes
print(temp)
for i in "0123456789":
if i in temp or i == '0' and (temp[0] in '0?' and \
temp[1] in '?1234567890' or \
any([ True for i,s in enumerate(temp) \
... |
import datetime
class Logger:
def __init__(self, log_file_name, console):
self.logs = []
self.log_file_name = log_file_name
self.console = console
def get_formatted_time(self):
""" Returns the current time for use in the .log and console in day/month/year hour:minute.second fo... |
def main():
sentence = input("Introduce la frase que quieres ver al reves: ")
print("")
firstchar= input("Cambia la primera letra de lo que has introducido: ")
sentence_new= firstchar + sentence[1:]
print("")
print("Tu frase al reves es=", sentence_new[::-1])
if __name__ == "__main__":
main... |
def main():
a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40] # Declaramos la lista con los números.
b = list() # Creamos una lista vacía que guardara los números que no se repitan.
for i in a: # Dentro de la lista a.
if i not in b: # Validamos que no se repita ningún número.
b.append... |
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[L... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dfs(... |
# # Next Palindrome
# def np(num):
# count=1
# while(1):
# i=num+count
# if(str(i)==str(i)[::-1]):
# return f"The palindrome for {num} is: {i}"
# else:
# count+=1
# if __name__ == '__main__':
# a=int(input("Enter the number of cases:"))
# b=[]
... |
# -*- coding: utf-8 -*-
import urllib
import os
import sys
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def mkdir(path):
#判断参数
if len(sys.argv) < 2:
pass
else:
path = sys.argv[1]
#绝对路径
path = os.path.join(os.getcwd... |
# -*- coding: utf-8 -*-
#RF1:Obtener la mayor nota y la menor nota
#RF2:Imprimir la nota promedio del curso
#RF3:Cuántos estudiantes aprobaron y cuántos reprobaron
#RF4:imprimir el código y un mensaje de acuerdo con la nota:
#❖ Cuántos obtuvieron una nota Muy bien [ 4.0 5.0]
#❖ Cuántos obtuvieron una nota Bien ... |
k=str(input())
if "+" not in k:
print(k)
else:
s=k.split("+")
s.sort()
x='+'
print(x.join(s)) |
# Find the largest palindrome made from the product of two 3-digit numbers
def palindrome_count(n):
n = str(n)
if len(n) <= 1:
return 0
if n[0] == n[-1]:
return 1 + palindrome_count(n[1:len(n) - 1])
else:
return 0 + palindrome_count(n[1:len(n) - 1])
def main():
count = 0 ... |
# Solution to Project Euler #11
def hor_sum(num_list):
product = 1
for row in range (len(num_list)):
temp = 1
for column in range (len(num_list[row])):
temp *= num_list[row][column]
product = max(product, temp)
return product
def vert_sum(num_list):
product = 1
f... |
# task 1
def random_num(n):
for i in range(1, n, 2):
yield i
numb = random_num(16)
while (numbers := next(numb)) is not None:
print('my_generator_15')
print(numbers)
# task 2
#numb = iter(range(1, 16, 2))
|
import time
class Library:
def __init__(self, booksList, libraryName, lendDict = {}):
self.booksList = booksList
self.libraryName = libraryName
self.lendDict = lendDict
def displayBook(self):
for book in self.booksList:
print(book, "\n")
def donateBook(self)... |
# Health Management System #
import time
userinput = int(input("Press\n1 For Brock\n2 For Roman\n3 For Dean\n"))
if userinput == 1:
print("Do You Want Log Or Retrieve ?")
userinputforbrock = int(input("Press\n1 For Log\n2 For Retrieve\n"))
if userinputforbrock == 1:
print("What Do You Want To Lo... |
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
total = 0
for fruits in prices:
print(fruits)
print("price:", prices[fruits])
for n in stock:
if n == fruits:
print("stock:", sto... |
amount = int(input("entert the amount you want to make it change"))
print("number of 500 rupees notes u got are:",amount//500)
amount = amount%500
print("number of 200 rupees notes u got are:",amount//200)
amount = amount%200
print("number of 100 rupees notes u got are:",amount//100)
amount = amount%100
print("number o... |
import re
n = int(input())
for i in range(1, n + 1):
dias = ["SEGUNDA", "TERCA", "QUARTA", "QUINTA", "SEXTA"]
final = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
regex = r"^[A-Z]{3}-[0-9]{4}$"
placa = input()
if not re.match(regex, placa):
print('FALHA')
else:
finalplaca = int(plac... |
#if, else,elife.
nome = str(input('Qualo o seu nome: ')).title()
if nome == 'Mosiah':
print('Que nome bonito!')
elif nome == 'Pedro' or nome == 'Maria' or nome == 'João':
print('Seu nome é bem popular!')
elif nome in 'Ana Claudia Jessica':
print('Belo nome feminino')
else:
print('Seu nome é bem normal!... |
#xercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher,
# só que agora utilizando um laço for.
t = int(input("A tabuada de qual numero voce quer ver? "))
for c in range(0, 11):
print("| {:2} x {:2} = {:2} |".format(t, c, (c*t)))
|
#Exercício Python 039: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
# se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do
# alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.... |
#crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'santo'
#nome = str(input('Digite uma cidade: ')) .strip().upper().split()
#print('Essa cidade começa com santo? {}'.format('SANTO' in nome[0]))
cid = str(input('Digite uma cidade: ')).strip()
print('Essa cidade começa com santo? {... |
'''Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros
termos da progressão usando a estrutura while.'''
print('=' * 30)
print('{:^30}'.format('10 termos de uma PA'))
print('=' * 30)
x = int(input("Digite o primeiro termo: "))
y = int(input("Digiete a razão:... |
#!/usr/bin/python3
"""
created by alex on 2/2/18
Fits the GDP data into the Cobbs Discrete model using matrices
"""
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatc... |
#Author: Thy H. Nguyen
import turtle
wn = turtle.Screen()
wn.bgcolor("#E0FFFF")
mom = turtle.Turtle()
mom.color("#0000CD")
mom.shape("circle")
thy = int(input())
i=1
while i < thy:
mom.right(10)
mom.forward(100)
mom.stamp()
mom.backward(thy)
mom.dot()
i +=1
wn.exitonclick()
|
import time
from decorator import decorator
SLEEP_PENALTY = .0001 # penalty in second for sleeping / context switching, etc.
UPDATE_EVERY_N_SECONDS = 2
class safe(object):
"""
a decorator for keeping a function from
raising an exception to its caller
"""
def __init__(self, function_description):
... |
# Association Rules for Market Basket Analysis (Python)
# import package for analysis and modeling
from rpy2.robjects import r # interface from Python to R
r('library(arules)') # association rules
r('library(arulesViz)') # data visualization of association rules
r('library(RColorBrewer)') # color palettes... |
'to samo co ćw 4. tylko na sterydach'
def IsPrime(Number):
ListOfNumbers = range(2,Number)
Divisors = []
[Divisors.append(elements) for elements in ListOfNumbers if Number % elements == 0]
if len(Divisors) == 0:
return True
else:
return False
Liczba = int(input('Wprowadź liczb... |
def ReverseWordOrder(txt):
txt2 = " ".join(txt.split()[::-1])
return txt2
txt1 = input('Wprowadź długie zdanie\n')
txt2 = ReverseWordOrder(txt1)
print(txt2)
|
print('Pomyśl liczbę od 0 do 100, a ja spróbuję ją odgadnąć.')
Start = 0
End = 100
Counter = 0
answer = 'XD psie'
Oszust = False
ComputerGuess = []
while 1:
C = (Start + End)//2
Counter+=1
if C not in ComputerGuess:
ComputerGuess.append(C)
else:
Oszust = True
break
... |
print('Enter four names')
theNames=[]
for name in range(0,4):
theNames.append(input())
print('The name that is longest is\n')
print(max(theNames,key=len))
|
EMPTY_LINE = '\n'
def solution():
fields = {}
field_names = []
with open('input.txt') as file:
for line in file:
if line == EMPTY_LINE:
break
field, rules = line.strip().split(": ")
first_rule, second_rule = rules.split(" or ")
fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.