text stringlengths 37 1.41M |
|---|
def printRepeating(arr):
print("The repeating elements are: ")
size = len(arr)
for i in range(0, size):
print(abs(arr[i]))
# print(arr[abs(arr[i])])
if arr[abs(arr[i])] >= 0:
arr[abs(arr[i])] = -arr[abs(arr[i])]
else:
print("Duplicate")
# p... |
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) == 0 or len(p) == 0:
return 0
# initialise
s = {}
indexs_array = []
substring_map = {}
i = 0
# get the substring map
for char in p:
if char in substring_map.keys():
substring_map[char] += 1
... |
class Solution(object):
def shortestPalindrome(self,s):
n=len(s)
longest=1
for length in range(n,1,-1):
rev=s[0:length]
if rev==rev[::-1]:
longest=length
break
print longest
suffix=s[longest:]
print suffix
... |
def readint(prompt, min, max):
val=int(input(prompt))
assert val<=max and val>=min
return val
try:
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
except ValueError:
print("Error: wrong input")
except AssertionError:
print("Error: the value is n... |
class StudentsDataException(Exception):
pass
class BadLine(StudentsDataException):
def __init__(self):
print("Bad line in the file")
class FileEmpty(StudentsDataException):
def __init__(self):
print("This file is empty!")
fileName = input("Enter the file name: ")
students={}
try:
fil... |
#This is the User class that contains the user's information
class User:
def __init__(self,name, age, bio):
self.name = name
self.age = age
self.bio = bio
self.connections = []
def set_age(self, age):
self.age = age
def set_bio(self, biography):
self.bio = (... |
import random
from typing import Optional
import a2_game_tree
import a2_minichess
def generate_complete_game_tree(root_move: str, game_state: a2_minichess.MinichessGame,
d: int) -> a2_game_tree.GameTree:
"""Generate a complete game tree of depth d for all valid m... |
'''
kata : https://www.codewars.com/kata/565f448e6e0190b0a40000cc
'''
def actually_really_good(foods):
sentence = "You know what's actually really good? "
if not foods:
return sentence + "Nothing!"
return sentence + '{} and {}.'.format(foods[0].capitalize(), foods[1].lower() if len(foods) > 1... |
var_A = input('Variable A')
var_B = input('Variable B')
try:
var_A = int(var_A)
var_B = int(var_B)
if var_A<var_B:
print('mas pequeño')
elif var_A>var_B:
print('mas grande')
else:
print('igual')
except ValueError:
print('String involucrado')
|
import re
def reggex(string):
match = re.search(r'[A-Z]{1}[a-z]+\s\d+', string)
if match :
print(match.group())
else:
print('no result found')
reggex("Kampakkers 52")
reggex("5503 LL Veldhoven") |
import sys
input = sys.stdin.readline
## 집합 개념으로 이해하면 쉽다.
# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x):
# 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(pare... |
#Michael McPhee, 05/09/21, fraction math practice program
import random
#gcd function using eucludian algorithm
def gcd(numeranswer, denomanswer):
while denomanswer:
numeranswer, denomanswer = denomanswer, numeranswer % denomanswer
return numeranswer
#addition function
def add(numer1, n... |
#Michael McPhee, 03/05/21, develops equation of linear graph from 2 points
x1 = int(input("Enter x1 "))
y1 = int(input("Enter y1 "))
x2 = int(input("Enter x2 "))
y2 = int(input("Enter y2 "))
#calculate numerator and denominator of the slope
slopenumerator = int(y2-y1)
slopedenominator = int(x2-x1)
#calcul... |
import matplotlib.pyplot as plt
import numpy as np
l = input("Ingrese la longitud de la varilla: ")
x=np.linspace(0,l/2,1000)
y=np.sqrt(-(2*x)**2+l**2)/2
plt.plot(x,y, label = "Pos. Centro de masa")
plt.legend()
plt.title("Posicion centro de masa varrilla", fontsize=16, fontweight='bold')
plt.xlabel("m")
plt.ylabel("... |
square= lambda num:num**2
i=square(5)
print(i)
mynum=[1,2,3,4,5,6]
mylist=list(map(lambda num:num**2,mynum))
print (mylist) |
# Convolutional Neural Network
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initializing the CNN
classifier = Sequential()
# Step 1: Convolution
classifier.add(Convolution2D(filters=32... |
import pygame
import math
import random
"""Colors"""
white = [255,255,255]
black = [0,0,0]
red = [255,0,0]
blue = [0,0,255]
green = [0,255,0]
"""Initializing and setup pygame"""
pygame.init()
pygame.display.set_caption("Double Pendulum Simulation")
screen_width = 600
screen_height = 600
screen = pygame.display.set_mo... |
# In this problem, you'll create a program that guesses a secret number!
#
# The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will g... |
import os
import re
def is_alphanumeric(input_string, exact_length=0):
"""Return True if input is a valid alphanumeric, False otherwise
Keyword arguments:
input_string -- string value to check
exact_length -- strict string length check, if 0, it's omitted (default 0)
"""
if exact_length > 0 an... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# @Author : shiqi.chang
# @Email : shiqi.chang@carrobot.com
# @Time : 2019/6/17 上午10:18
# @Filename : palindrome_number.py
# @Software : PyCharm
class Solution:
def is_palindrome(self, x: int) -> bool:
"""回文数
解题思路:
int 转换成 str, 利用 [:... |
# coding: utf-8
# In[ ]:
a = {'那堤' : '$105',
'冰那堤' : '$105',
'焦糖瑪奇朵' : '$125',
'冰焦糖瑪奇朵' : '$125',
'摩卡' : '$120',
'冰摩卡' : '$120',
'卡布奇諾' : '$105',
'美式咖啡' : '$85',
'冰美式咖啡' : '$85',
'濃粹那堤' : '$120',
}
print('選單:')
print('那堤, 冰那堤, 焦糖瑪奇朵, 冰焦糖瑪奇朵, 摩卡, 冰摩卡, 卡布奇諾, 美式咖啡, 冰美式咖啡, 濃粹... |
# board = [-1] * 9
# 1 -> cross
# 0 -> circle
def checkFree(ind1, ind2, board):
if(board[ind1]==-1 and board[ind2]==-1):
return True
else:
return False
def checkBlocked(ind1, ind2, ind3, value, board):
if(board[ind1]==value and board[ind2]==value):
if(board[ind3]==-1):
... |
import random
import time
chosenPath =
correctPath = 0
def displayIntro():
print("North Korea, The USA, one giant war")
print("North Korea has 11 nuclear weapons")
print("USA hsa over 750,000 soldiers ")
print("USA also has 35,000 troops on the border between South Korea")
print("Perks on the way ar... |
#!/usr/bin/env python
#
# Raspberry Pi Robot Costume
'''
In this project, we're making a Raspberry Pi Robot Costume. The costume will count candy placed in a bin, and speak out loud to the giver.
Well use the GrovePi, with an Ultrasonic Sensor, an LED Bar graph, 4 Chainable LED's, and the RGB LCD Display. We'll also ... |
#!/usr/bin/python3
work_hours = [('Abby',100), ('Billy', 4000), ('Cassie',800)]
def employee_check(work_hours):
current_max = 0
employee_of_month = ''
for employee,hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month = employee
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 11:02:24 2018
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
i=1
count=0
c=int(input("In the series of prime numbers, which term do you want?"))
while c... |
''' TO FIND THE SUM OF DIGITS OF A NUMBER'''
number = int(input("Enter a number: "))
def sumdigits(number):
if number==0:
return 0
return (number%10) + sumdigits(number//10)
print(sumdigits(number)) |
# Given a sorted array of numbers, find if a given number ‘key’ is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates.
# Write a function to return the index of the ‘key’ if it is present in ... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'rpg' function below.
#
# The function is expected to return a DOUBLE.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER m
# 3. INTEGER k
#
def rpg(n, m, k):
if k==0 or m==0:
return 0
... |
from heapq import *
def minimum_cost_to_connect_ropes(ropeLengths):
result = 0
min_heap = []
for i in ropeLengths:
heappush(min_heap, -i)
n = len(min_heap)-1
for itr in range(n):
rope1 = -min_heap.pop()
rope2 = -min_heap.pop()
combined_rope = rope1+rope2
hea... |
def search_min_diff_element(arr, key):
if key < arr[0]:
return arr[0]
if key > arr[len(arr) - 1]:
return arr[len(arr) - 1]
l, h = 0, len(arr)-1
while l <= h:
mid = (l+h)//2
if arr[mid] == key:
return arr[mid]
elif key < arr[mid]:
h = mid -... |
def find_first_k_missing_positive(nums, k):
n = len(nums)
i = 0
while i < len(nums):
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
nums[i], nums[j] = nums[j], nums[i] # swap
else:
i += 1
missingNumbers = []
extraNumbers = s... |
# Given an array of intervals representing ‘N’ appointments, find out if a person can attend all the appointments.
def can_attend_all_appointments(intervals):
start, end = 0, 1
for i, interval in enumerate(intervals):
iterator = i + 1
while iterator < len(intervals):
if interval[star... |
# We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space.
def find_all_duplicates(nums):
duplicateNumbers = []
itr = 0
while itr < len(nums):
if nums[itr] != itr+1:
... |
from collections import deque, defaultdict
def is_scheduling_possible(tasks, prerequisites):
if tasks <= 0:
return False
dependency_map = defaultdict(list)
no_of_prerequisites = defaultdict(int)
schedule = deque()
ans = []
for prerequisite, task in prerequisites:
no_of_prerequi... |
class Solution:
def frequencySort(self, s: str) -> str:
if not s:
return s
freq = collections.defaultdict(int)
for char in s:
freq[char] += 1
li = []
for char in freq.keys():
li.append((freq[char], char))
li.sort(key=lambda x: -x[0]... |
from __future__ import print_function
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(temp.value, end=" ")
temp = temp.next
print()
def rotat... |
# Given an array arr of unsorted numbers and a target sum, count all triplets in it such that arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices. Write a function to return the count of such triplets.
def triplet_with_smaller_sum(arr, target):
arr.sort()
count = 0
for first in r... |
class ParenthesesString:
def __init__(self, str, openCount, closeCount):
self.str = str
self.openCount = openCount
self.closeCount = closeCount
def generate_valid_parentheses(num):
result = []
return result
def main():
print("All combinations of balanced parentheses are: " +... |
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# 0=x1, 1=x2, 2=y1,3=y2
if (rec1[0] == rec1[2] or rec1[1] == rec1[3] or
rec2[0] == rec2[2] or rec2[1] == rec2[3]):
return False
return rec1[0] < rec2[2] and rec2[0] < rec1[2] a... |
from heapq import *
from collections import defaultdict
def reorganize_string(str, k):
if k <= 1:
return str
max_heap = []
feq_map = defaultdict(int)
for char in str:
feq_map[char] += 1
for key in feq_map.keys():
heappush(max_heap, [-feq_map[key], key])
# [prev_char_fr... |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
dic = {}
if not head:
... |
def backspace_compare(str1, str2):
idx = 0
slow = 0
str1 = list(str1)
str2 = list(str2)
while idx < len(str1):
if str1[idx] == '#':
slow -= 1
else:
str1[slow] = str1[idx]
slow += 1
idx += 1
idx2 = 0
slow2 = 0
while idx2 < len(st... |
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
... |
'''Crea un programa que sea capaz de contar la cantidad de letras mayúsculas en una string introducida por el usuario.'''
frase_del_usuario = input('Escribe una frase: ')
mayusculas = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','V','W','X','Y','Z']
n_mayusculas = 0
for numero in f... |
'''Crea un programa que encuentre el número más pequeño de una serie de números introducidos por el usuario'''
usser_numbers = []
added_number = ''
while len(usser_numbers) < 10:
added_number =input('Elige un numero:')
while not added_number.isdigit():
added_number = input('Elige un numero:')
print... |
mi_lista = []
input_usuario = input('Que quieres comprar?')
while input_usuario != 'FIN':
mi_lista.append(input_usuario)
input_usuario = input('Que quieres comprar?')
for item in mi_lista:
print('Tengo que comprar {}'.format(item))
print('Esta es la lista de compra')
|
import random
import string
data= dict()
listname=list()
lowerLetters=string.ascii_lowercase
print(" please enter passcode ")
name = input()
lowercase_letters = [c for c in name if c.islower()]
# print (lowercase_letters)
# print (name)
# print (listname[:10])
if lowercase_letters != [] :
passcode=' '.join(lowercase_... |
class MovieNode:
def __init__(self, movie_dict):
self._type = "movie" # cannot be changed
self._neighbors = [] # preset, will not included if transfer to json format
# set other fields by an actor_dict
for key, value in movie_dict.items():
if key ==... |
print('-'*20)
print('LOJA BARATÃO')
print('-'*20)
fim = 'a'
totalpreço = contadorpreço = menor = contador = 0
menorproduto = ''
while True:
produto = str(input('Nome do produto:'))
preço = float(input('Preço: R$'))
totalpreço += preço
contador += 1
if preço > 1000:
contadorpreço += 1
if ... |
j = 'João'
v = 'Vitória'
idade = 33
i = 'john'
n = 987.3
print(f'{i:^20} ESPAÇO') #DÁ PARA ALIAR(CENTRALIZAR)
print(f'{i:-^20} ESPAÇO') #DÁ PARA COMPLEMENTAR
print(f'{i:->20} ESPAÇO') #DÁ PARA ALIAR À DIREITA
print(f'{i:-<20} ESPAÇO') #DÁ PARA ALIAR À ESQUERDA
print(f'{i:20} ESPAÇO') #DÁ PARA MODIFICAR O ESPAÇ... |
n = int(input('Digite um número para ver sua tabuada:'))
#print('===========\n6 x 1 = 6 \n6 x 2 = 12 \n6 x 3 = 18 \n6 x 4 = 24 \n6 x 5 = 30 \n6 x 6 = 36'
#'\n6 x 7 = 42 \n6 x 8 = 48 \n6 x 9 = 54 \n6 x 10 = 60\n===========')
#r1 = n*1
#r2 = n*2
#r3 = n*3
#r4 = n*4
#r5 = n*5
#r6 = n*6
#r7 = n*7
#r8 = n*8
#r9 = n*9
... |
m = 0
conta = 0
contam = 0
for c in range(1, 8):
n = int(input('Digite o ano de nascimento da {}° pessoa:'.format(c)))
m = 2019 - n
if m >= 21:
conta += 1
else:
contam += 1
print('Existem {} pessoas maior de idade.'.format(conta))
print('E existem {} pessoas menor de idade'.format(contam... |
#print('='*20)
#print('DEZ TERMOS DE UMA PA')
#print('='*20)
#pt = int(input('Primeri Termo:'))
#raz = int(input('Razão:'))
#for c in range(pt, 11):
# print(pt+ raz + c)
print('='*20)
print('DEZ TERMOS DE UMA PA')
print('='*20)
pt = int(input('Primeri Termo:'))
raz = int(input('Razão:'))
pa = pt + (11 - 1) * raz
for... |
n1 =int(input('Digite sua idade:'))
n2 =int(input('Digite em que ano nós estamos:'))
n3=n2-n1
print('você nasceu em',n3) |
print('\033[1;7;35;40m#'*5+'\033[1;7;35;40mConfederaçao Nacional De Nataçao'+'\033[1;7;35;40m#'*5)
a = int(input('Digite o ano do seu nascimento: '))
m = 2019 - a
print(m)
if m <= 9:
print('O atleta tem {} anos e sua categoria é mirim.'.format(m))
elif m <= 14:
print('O atleta tem {} anos e sua categoria é infa... |
n1 = int(input('Digite um número:'))
n2 = int(input('Digite outro número:'))
n3 = n1 + n2
n4 = n1 - n2
n5 = n1 * n2
n6 = n1 ** n2
n7 = n1 / n2
n8 = n1 // n2
n9 = n1 % n2
print('A soma é: {}. A diminuição é: {}.'.format(n3, n4))
print('A multiplicação é: {}. A potência é: {}.'.format(n5, n6))
print('A divisão é: {}. A d... |
#o metodo estatico de classe também recebi um decorador --> @staticmethod
from random import randint
class Pessoa:
ano_atual = 2020
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def get_ano_nascimento(self):
print(self.ano_atual - self.idade)
@classmethod... |
print('Digite uma medida para as retas')
reta1 = float(input('Reta 1:'))
reta2 = float(input('Reta 2:'))
reta3 = float(input('Reta3'))
if (reta1 + reta2) > reta3 and (reta3 + reta2) > reta1 and (reta3 + reta1) > reta2:
print('Dá para fazer um triangulo.')
else:
print('Não dá para fazer um triangulo.') |
n = int(input('digite: '))
print('Digite 1 para converter em binário.')
print('Digite 2 para converter em octal')
print('Digite 3 para converter em hexadécimal')
m = int(input('Digite 1, 2 ou 3: '))
if m == 1:
print('O número {} em binário é {}.'.format(n, bin(n)))
elif m == 2:
print('O número {} em octal é {}.... |
n1 = float(input('Digite a nota do aluno: '))
n2 = float(input('Digite outra nota do aluno: '))
media = (n1 + n2) / 2
print('Média: {}.'.format(media))
if media >= 7.0:
print('Aluno aprovado.')
elif media < 5.0:
print('Aluno reprovado.')
elif media <= 6.9:
print('Aluno em recuperação.')
|
class Carro:
def __init__(self, marca, tipo, modelo):
self.marca = marca
self.tipo = tipo
self.modelo = modelo
def Parado(self):
print('Está parado.')
def Deslocando(self):
print('Esta se deslocando.')
def Informações_do_veiculo(self):
print(self.marca,... |
valor = list()
impar = list()
par = list()
n = 1
numero = 0
while n < 8:
valor.append(int(input(f'Digite o {n}° valor ')))
n += 1
for c in valor:
if c % 2 == 0:
par.append(c)
else:
impar.append(c)
print(f'Número impar: {impar}')
print(f'Número par{par}') |
from random import randint
sorteio = (randint(1, 10), randint(1, 10), randint(1, 10),randint(1, 10), randint(1, 10))
print(f'VALOR SORTEADO: {sorteio}')
print(f'O MAIRO VALOR FOI: {max(sorteio)}')
print(f'O MENOR VALOR FOI: {min(sorteio)}')
'''contador = maior = menor = 0
while contador < 5:
número = (1, 2, 3, 4, ... |
adição = 0
for c in range(1, 8):
n = int(input('Digite um número:'))
adição += n
print('A adição do número {}, 7 vez é {}'.format(n, adição)) |
"""Module for undertaking data transformation operations."""
from typing import List, Dict
import pandas as pd
import numpy as np
def count_error_code_occurrences(errors: List[Dict[str, int]]) -> List[Dict[str, int]]:
"""Return the number of occurrences for each distinct error code."""
# Load the errors into... |
def collatz(number):
if number % 2 == 0:
print(number/2)
return number / 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
print('Enter a number')
while True:
try:
num = int(input())
break
except ValueError:
print("Invalid inpu... |
#!/bin/python
# Source: https://www.hackerrank.com/challenges/non-divisible-subset
# Given a set, S, of n distinct integers, print the size of a maximal subset
# S', of S where the sum of any 2 numbers in S' is not evenly divisible by k.
from collections import defaultdict
def max_non_divisible_subset(n, k, a):
... |
#this program is used to find whether the inputted year is leap year or not
def checkyear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return Fa... |
'''
this is my first day on the 100 days python challenge.
wish me luck
'''
print("hello python world")
message = "would you like to learn some python today"
print("hello," +(message))
clientName = "nimah abdulkarim"
print(clientName.title())
print(clientName.lower())
print(clientName.upper())
'''
let us ... |
import numpy as np
#Definicion de dimensiones de la matriz
num_filas = int(input("Ingrese el numero de filas de la matriz "))
num_col = int(input("Ingrese el numero de columnas de la matriz "))
#Ingresar los valores de la matriz R
print("Si su matriz se ve así")
print("1 2 3")
print("4 5 6")
print("7 8 9")
print("Ingre... |
import random
def check_valid_input(s):
"""
Check the input (valid or not)
Args:
s (str): The parameter, which is the input from the player.
Returns:
bool: The return value. True for valid input, False for invalid.
>>>check_valid_input("GUN")
False
>>>check_valid_input("... |
def check_valid_input(s):
"""Check that input is wrong or not
>>> check_valid_input("rock")
True
>>> check_valid_input("paper")
True
>>> check_valid_input("scissors")
True
>>> check_valid_input("stand")
False
>>> check_valid_input("spock")
True
>>> check_valid_input("liz... |
#number 1
def ll_sum(t):
"""function that add up all the number in the lists and nested lists
>>> ll_sum([[1,2],[3],[4,5,6]])
21
>>> ll_sum([[1,2,3,4,5]])
15
>>> ll_sum([[3,5,4,7,8]])
27
>>> ll_sum([[111,2],[4,3]])
120
>>> ll_sum([[2,3,4,5]])
14
"""
total = 0
fo... |
import random
import sys
def convert_to_num(s):
"""This function convert your choice into number.
>>> convert_to_num('rock')
0
>>> convert_to_num('paper')
1
>>> convert_to_num('scissors')
2
"""
if s == "rock":
return 0
elif s == "paper":
return 1
elif s == "... |
#1
def ll_sum(num):
"""this function takes a list of lists of integers and adds up the elements from all of the
nested lists.
>>> t = [[1, 2], [3], [4, 5, 6]]
>>> ll_sum(t)
21
>>> u = [[1, 3], [3], [4, 5, 6]]
>>> ll_sum(u)
22
>>> v = [[1, 2], [5], [4, 5, 6]]
>>> ll_sum(v)
... |
import random
# list = ["rock", "scissors", "paper", "Spock", "lizard", "gun", "zombie"]
# player = random.choice(list)#input("Play chooses: ")
# com = random.choice(list)
# print(f"Computer choose {com}")
def strnum(player):
'''
:param player: [str]
:return: [int]
'''
if player == "Scissors":
... |
def check_valid_input(s):
"""
>>> check_valid_input("rock")
True
>>> check_valid_input("spock")
True
>>> check_valid_input("scissors")
True
>>> check_valid_input("paper")
True
>>> check_valid_input("lizard")
True
"""
if s == "rock":
return True
if s == "... |
# Chanathip Thumkanon
# 6210546650
import random
NUMOFSYM = 7
def check_valid_input(s):
return convert_to_num(s) >= 0
def convert_to_num(s):
if s == 'rock':
return 0
elif s == 'gun':
return 1
elif s == 'Spock':
return 2
elif s == 'paper':
return 3
elif s == '... |
if __name__ == "__main__":
import doctest
doctest.testmod()
def this_check_valid_input(t):
""" this function will check that if the input is True or False """
if t == "rock":
return True
elif t == "paper":
return True
elif t == "scissors":
return True
elif t == "l... |
def ll_sum(t):
'''
:param t:[int] list of numbers
:return:[int] sum of numbers in the list
>>> ll_sum([[1,2],[3],[5,6]])
17
>>> ll_sum([[2,7],[1,2,3]])
15
>>> ll_sum([[3,6,8],[1,2,3]])
23
>>> ll_sum([[1,3,4],[5],[8,2]])
23
>>> ll_sum([[2,8,4,3],[2,1]])
20
'''
... |
def ll_sum(list_in_list):
'''
This function will gonna sum all the inlist member that is
list in list and return the value in int by using only one parameter
'list_in_list'(list that have list inside)
>>> ll_sum([[1,2],[3],[4,5,6]])
21
>>> ll_sum([[3,4],[7],[8,1,9]])
32
>>> ll_sum... |
import random
def computer_check(n):
"""
>>> computer_check(0)
Computer chooses: rock
>>> computer_check(1)
Computer chooses: paper
>>> computer_check(2)
Computer chooses: scissors
>>> computer_check(3)
Computer chooses: spock
>>> computer_check(4)
Computer chooses: lizard
... |
def ll_sum(t):
"""
this function is used to calculate the sum of number in each list combined.
>>> t = [[1],[1,2],[1,2,3]]
>>> ll_sum(t)
10
>>> t = [[3],[1,2],[4,5,6]]
>>> ll_sum(t)
21
>>> t = [[0],[1,2,4],[10,2,3]]
>>> ll_sum(t)
22
>>> t = [[1],[1,2],[4,4,0]]
>>> ll_sum(t)
... |
import random
choice = ['scissors', 'paper', 'rock', 'lizard', 'spock']
scissors_win = [1, 3]
paper_win = [2, 4]
rock_win = [3, 0]
lizard_win = [4, 1]
spock_win = [0, 2]
def check_win(x, y):
"""Check if x win y.
>>> check_win(0,0)
False
>>> check_win(0,1)
True
>>> check_win(0... |
# 1
def ll_sum(t):
''' make the sum of all number in list
>>> t = [[1,2],[3],[4,5,6]]
>>> ll_sum(t)
21
>>> a = [[1,2],3,[4]]
>>> ll_sum(a)
10
>>> b = [[5,6],[5,7]]
>>> ll_sum(b)
23
>>> c = [1,2,3]
>>> ll_sum(c)
6
>>> d = []
>>> ll_sum(d)
0
'''
b ... |
import random
# n = number of integers you want to generate, x ** y denotes x^y
n =10**5
u = 10**1
# minimum and maximum possible value of random number generated
minn = 1
maxx = 10 ** 7
# first line containing the value of n
# print "n,q"
print(n)
l=n
choices = list(range(maxx))
random.shuffle(choices)
# print(choic... |
"""
Temporary memory database
get_all() - returns a list of unanswered questions. Return list()
get(id) - by the id of the user who asked the question, the question itself is returned. Return String
delete(id) - delete the questions, when answered
add(id, quest) - adding quest in the main list.
"""
class BD:
def ... |
# first
a=-5
if a>0:
if a%2==0:
print(str(a) + " is positive even number")
else:
print(str(a) + " is negative number")
# Output is : -5 is negative number because the outer if statement is evaluated
# and the condition is false so the else statement gets executed.
# second
a=5
if a>0:
if a%2==0 :
... |
# Check the output of following code and justify your answer:
x = 50
def func(x):
print('x is',x)
x = 2
print('Changed local x to',x)
func(x)
print('x is now',x)
# Justification : the function did not changed the value of x because
# their are 2 scopes for variable x:
# i. in... |
def maximum(x,y,z):
if x > y and x > z:
return x
if y > x and y > z:
return y
if z > x and z > y:
return z
n1 = int(input("Enter num 1 :"))
n2 = int(input("Enter num 2 :"))
n3 = int(input("Enter num 3 :"))
print(maximum(n1,n2,n3)) |
# Write a program to combine following dictionaries by averaging values for
# common keys.
# D1 = {‘ram’:60, ‘shyam’:70, ‘radha’:70}
# D2 = {‘ram’:70, ‘shyam’:80, ‘gopi’:60}
# output : {‘ram’:65, ‘shyam’:75, ‘radha’:70, ‘gopi’:60}
D1 = {'ram':60, 'shyam':70, 'radha':70}
D2 = {'ram':70, 'shyam':80, 'gopi':60}
output =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 12:21:55 2019
@author: damienrigden
This program crates a graphical window of a clock drawn using sofdot numbers.
It takes as an argument the desired clock face size
"""
from graphics import GraphWin, Point, Circle, Rectangle
from time import ... |
l = eval(input("Enter the length: "))
w = eval(input("Enter the width: "))
h = eval(input("Enter the heigth: "))
result = l*w*h
print(result) |
# Autor: Ithan Alexis Pérez Sanchez, A01377717
# Descripcion: Calcular la distancia de 2 tiempos de determinados y el tiempo necesario para llegar a un kilometraje determinado
# Escribe tu programa después de esta línea.
Velocidad = int(input("Los Km/h de carro son: "))
Distancia1 = 7 * Velocidad
Distancia2 = 4.5 * V... |
class MyIterator(object):
def __init__(self, step):
self.step = step
def next(self):
if self.step == 0:
raise StopIteration
self.step -= 1
return self.step
def __iter__(self):
return self
def test_simple_iterator():
simple_iter = MyIterator(4)
... |
class TeamMembers:
team_members = {}
def add_team_member(self, team_member):
self.team_members[team_member.id] = team_member
def get_team_member_names(self):
names = []
for person in self.team_members.values():
names.append(person.name)
return names
def get... |
def larger_sum(lst1, lst2):
sum1 = 0
sum2 =0
for item in lst1:
sum1+=item
for item in lst2:
sum2+=item
if sum1>sum2:
return lst1
elif sum1==sum2:
return lst1
else:
return lst2
print(larger_sum([1, 9, 5][2, 3, 7])) |
# На входной двери подъезда установлен кодовый замок, содержащий десять кнопок с цифрами от 0 до 9.
# Код содержит три цифры, которые нужно нажать одновременно.
#Какова вероятность того, что человек, не знающий код, откроет дверь с первой попытки?
from math import factorial
A = int(factorial(10) / factorial(10 - 3))
p... |
calif1 = float(input("Ingrese la primera calificación: "))
calif2 = float(input("Ingrese la segunda calificación: "))
calif3 = float(input("Ingrese la tercera calificación: "))
prom = (calif1 + calif2 + calif3)/ 3
if prom > 70:
print("Alumno aprobado")
else:
print("Alumno reprobado") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.