text stringlengths 37 1.41M |
|---|
# find all divisible numbers of user input and push to array
number = int(raw_input("choose a number to see what is divisible: "))
divsibleNum = list(range(2, number+1))
divisorList = []
for elem in divsibleNum:
if number % elem == 0:
divisorList.append(elem)
print (divisorList) |
data_box = [2, 4, 5, 1,"Cat", "Asset"]
# You can input from user to check.
def liner_Search(databox, target):
for loop1 in range(len(data_box)):
if databox[loop1] == target:
return True
else:
return False
print(liner_Search(data_box,"Asset"))
|
#first_no = input("Enter the first number: ")
#second_no = input("Enter the second number: ")
#operation = input("Choose the operation (+, -, *, /): ")
while True:
try:
first_no = int(input("Enter the first number: "))
second_no = int(input("Enter the second number: "))
except ValueError:
... |
# -*- coding: utf-8 -*-
import sys
import numpy as np
import cv2
###donne de nos questions
class Question:
def __init__(self, question,choices, correct):
self.question = question
self.choices = choices
self.correct = correct
from collections import namedtuple
q = [None] * 10
Question = name... |
import pandas as pd
import numpy as np
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import math
def get_reports_data(creditrecordcsv):
'''
The function takes in the credit_record.csv and creates a data frame for:
... |
from login_register import *
os.system("clear")
system_print("Welcome to the online Library!")
while True:
print_menu("MAIN MENU:\n1.Login\n2.Register\n3.Quit")
while True:
choice = int(input("Please give your option: "))
if choice != 1 and choice != 2 and choice != 3:
print("\tWr... |
#by Lucas and Siddhant
#loading library
from datetime import datetime
# Set a variable birthday = "1-May-12".
birthday="1-May-12"
date_format = "%d-%B-%y"
# Parse the date using datetime.datetime.strptime.
parsed_date = datetime.strptime(birthday,date_format)
# Use strftime to output a date that looks like "5/1/20... |
from constant.constant import Constant
class Character:
"""
class used for MacGyver's moves and items pick up logic
"""
def __init__(self, icon, level):
self.icon = icon
self.level = level
self.item_count = 0
self.item = ['N', 'E', 'S', 'T']
def move(self, x, y, d... |
class Solution:
def isPalindrome(self, x: int) -> bool:
#apparently, negatives can't be palindromes :/
if x<0: return False
#remember the slice syntax: LIST[start:end:position... -1 reverse, 1 forward, 2, skip 1 each round]
return int(str(x)[::-1]) == x |
# thanks to Nicholas Swift and his blog post explaining the a* code
class Cl_Node():
def __init__(self, parent = None, position = None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.positio... |
# Faça uma função que recebe três números por
# parâmetro e imprime na tela em ordem crescente.
def ImprimeOrdenado(a, b, c):
if (a < b) and (a < c):
if (b < c):
print(a, b, c)
else:
print(a, c, b)
elif (b < a) and (b < c):
if (a < c):
print(b, a, c)
... |
def FazerBolo():
print("Separar os ingredientes")
print("Misturar os ingredientes em um recipiente")
print("Deixar no forno por 30 minutos")
print("Retirar do forno")
print("")
def AtravesarRua():
print("Parar na borda da calçada")
print("Olhar para direita")
print("Olhar para esquerda"... |
# 2. Во втором массиве сохранить индексы чётных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо
# заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля),
# т.к. именно в этих позициях первого массива стоят чётные числа.
import random
SIZE = ... |
values = {
a:b}
a= int(input("enter num:"))
b= input("enter name:")
x=int(input("enter choice: 1.get name,2.get number,3.display dictionary,4.insert:::"))
if x == 1:
print values[input("enter num:")]
elif x==3:
print values
|
########################################################################
# Define a Convolution Neural Network
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 2. Change the code to have only a single fully connected layer.
# The model will have a single layer that connects the input to the output.
import torch.nn as nn... |
from algorithms.base_algorithm import BaseAlgorithm
class FordBellman(BaseAlgorithm):
def __init__(self, name):
super().__init__(name)
def find_path(self, graph, start, end):
return self.ford_bellman(graph, start, end)
@staticmethod
def ford_bellman(graph, start, end):
count ... |
from abc import ABCMeta, abstractmethod, abstractproperty
class BaseModel(object):
__metaclass__ = ABCMeta
@abstractproperty
def model(self):
""" Return Model
:return: obj model
"""
@abstractmethod
def reset(self):
""" Reset model with base structure
:r... |
"""
Task. Given two integers a and b, find their greatest common divisor.
Input Format. The two integers a, b are given in the same line separated by space.
Constraints. 1<=a,b<=2·109.
Output Format. Output GCD(a, b).
"""
def EuclidGCD(a, b):
if b == 0:
return a
else:
a = a%b
return Euc... |
#!/usr/bin/env python3
import sys
import os
from threading import Thread
from queue import Queue, LifoQueue
from functools import cache
from operator import itemgetter
from collections import Counter
from rectangle import Rectangle
# Keep a count of each area a rectangle might have
rect_areas = Counter()
rect_queue = ... |
# 5. Реализовать класс Stationery (канцелярская принадлежность).
# Определить в нем атрибут title (название) и метод draw (отрисовка).
# Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних
# класса Pen (ручка), Pencil (карандаш), Handle (маркер).
# В каждом из классов реализовать переопределение метода dra... |
# 3. Реализовать программу работы с органическими клетками.
# Необходимо создать класс Клетка. В его конструкторе инициализировать
# параметр, соответствующий количеству клеток (целое число). В классе
# должны быть реализованы методы перегрузки арифметических операторов:
# сложение (__add__()), вычитание (__sub__()), у... |
# 7. Продолжить работу над заданием. В программу должна попадать
# строка из слов, разделённых пробелом. Каждое слово состоит
# из латинских букв в нижнем регистре. Нужно сделать вывод
# исходной строки, но каждое слово должно начинаться с заглавной
# буквы. Используйте написанную ранее функцию int_func().
def is_asci... |
# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать
# дату в виде строки формата «день-месяц-год». В рамках класса реализовать
# два метода. Первый, с декоратором @classmethod, должен извлекать число,
# месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором
# @staticmethod, д... |
# 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.... |
# Python wih X starting point Y end Point and D as fix Jump distance.
def solution(X, Y, D):
# Use Case 1: Jump Distance 0
# Through exeption
if Y < X or D <= 0:
raise Exception("Invalid arguments")
# Use case 2: Y in multiplication of D
# Use case 3: Y in Not in multiplecaiton of D
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 09:59:26 2015
@author: akond
"""
from swampy.TurtleWorld import *
def drawTriangle(turtleParam, length, angle):
'''
This module draws a triangle
'''
import math
legLen = length * math.sin(angle * math.pi / 180)
#for i in range(3):
rt(... |
#Autores: Esteban Andres Flores Gutierrez y Camila Fernanda Guzman Lara
import base
def ConvertirAbase(bf):
fin= 'Fin de la funcion '+str('ConvertirAbase')
basef=bf
bi= input('Base inicial: ')
if basef==bi or bi < 2 or bi > 10:
print 'Ingrese base correcta.'
else:
nu... |
# %%
import matplotlib.pyplot as plt
import numpy as np
print("Hello python")
x = np.linspace(0, 2*np.pi, 10000)
y = np.sin(x)
print(np.pi)
plt.plot(x, y)
plt.show()
|
##############################################################################
# #
# A game by Louis Sugy for Ludum Dare #39 #
# Theme: Running out of power #
... |
UNDERCOVER_OPTIONS = '''
You decide to go undercover on Planet Earth as a human. Where do you decide
to go first
1) Harvard University
2) Visit the circus
3) Go to the mall
4) Visit a peanut butter factory... logically ;)
'''
VISIT_CIRUS = '''
You see a sentient peanut butter jar performing circus trucks. What do ... |
'''
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
'''
unconfimed_users = ["alice","brian","candance"]
confimed_users = []
while unconfimed_users:
current_user = unconfimed_user... |
"""
let n = 18
Ask user to guess a number.
If he guess greater than 18 than tell to reduce his guess
If he guess smaller than 18 than tell to grow up his guess
If he entered 18 then he wins game
Max no of guesses are 9
If he can't guess 18 either in 9 guesses then he lose the game
Print no of guesses left at each term
... |
"""
Take two numbers a & b as input.
Then swap their values & print.
"""
print("Enter number a = ", end="")
a = input()
print("Enter number b = ", end="")
b = input()
a, b = b, a
print("After swapping")
print("a = " + str(a))
print("b = " + str(b))
|
alfabe = "abcdefghijklmnopqrstuvwxyz"
text = input("Metninizi girin:")
result = ""
for i in text:
#Kullanıcı saçma karakterler girebilir.
try:
sayi = alfabe.index(i)
result+=alfabe[(sayi+13)%len(alfabe)]
except:
result+=str(i)
print(result)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode... |
#!/usr/bin/python
class Node:
def __init__(self, key=None, val=None, count=0):
self.key = key
self.val = val
self.left = None
self.right = None
self.count = count
class BST:
def __init__(self):
self.root = None
def size(self):
return self._size(se... |
class Parent1(object):
def __init__(self):
super().__init__()
print("is Parent1")
print("goes Parent1")
class Parent2(object):
def __init__(self):
super().__init__()
print("is Parent2")
print("goes Parent2")
class Child1(Parent1):
def __init__(self):
... |
class Node(object):
def __init__(self, value=None, next=None, previous=None):
self.value, self.next, self.previous = value, next, previous
class CircularDoubleLinkedNode(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.root.next = self.r... |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
n=''
a=''
for i in line:
if i!=n:
n=i
a=a+','+i
else :
a=a+i
b=a.strip(',').split(',')
sum=0
for i in b:
if sum<len(i):
... |
from collections import Counter
def checkio(text: str) -> str:
a = list(filter(nonum, text))
b = []
for i in a:
b.append(i.lower())
x = sorted(Counter(b).most_common(), key=lambda x: x[1], reverse=True)
def p(n):
if n[1] < x[0][1]:
return False
else:
... |
def health_calculator(age, apples_ate, cigs_smoked):
answer = (100-age) + (apples_ate * 2.5) - (cigs_smoked * 3)
print(answer)
my_data = [26, 1, 0]
# Unpacking an argument list
health_calculator(*my_data) |
# 3.4 = Pillow, 2.7 = PIL (PIL is 3.4 compatible, use it)
from PIL import Image
# Open image
img = Image.open("sampleImage1.jpg")
# Print image size, format
print(img.size)
print(img.format)
# Crop image
area = (100, 100, 200, 200) # (left, top, right, bottom)
cropped_img = img.crop(area)
# Display image
crop... |
import timeit
# Timing performances
print("List performance: ", end="")
l = timeit.timeit(stmt='10**6 in a', setup='a = range(10**6)', number=100000)
print(l, end="")
print("\nSet performance: ", end="")
s = timeit.timeit(stmt='10**6 in a', setup='a = set(range(10**6))', number=100000)
print(s, '\n')
# Printing ou... |
# The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.
import module
# Pros:
# Less maintenance of your import statements. Don't need to add any additional imports to start using a... |
# Printing binary and hex values
print("binary:", bin(8))
print("hex: ", hex(10))
# AND
a = 50 # 110010
b = 25 # 011001
c = a & b
print('\n', "AND: ", bin(c),' ',c, sep='')
# OR
d = a | b
print('\n',"OR: ", bin(d),' ',d, sep='')
# Shift
x = 240 # 11110000
y = x >> 2
print('\n',"Shift: ", bin(y),' ',y, sep='') |
import unittest
from Testing import main
class TestMain(unittest.TestCase):
def setUp(self):
print('about to test a function')
def test_do_stuff(self):
"""You can add docstrings within test functions"""
test_param = 10
result = main.do_stuff(test_param)
self.assertEqua... |
numbers = [number for number in range(1,21)]
print(numbers)
numbers2 = [number for number in range(1,10000001)]
number_min = min(numbers2)
number_max = max(numbers2)
number_sum = sum(numbers2)
print(number_min,number_max,number_sum)
numbers3 = []
for number in range(1,21,2):
numbers3.append(number)
for number in nu... |
def make_shirt(size, font='I love Python'):
print("This T-shirt'size is " + size + " and the font is " + font)
make_shirt('BIG')
make_shirt(size='middle')
make_shirt('small', font='ABCD') |
class ListInfo:
"""定义一个列表的操作类"""
def __init__(self, list_info):
self.list = list_info
def add_key(self, info):
# 添加的key必须是字符串或数字
if isinstance(info, (str, int)):
self.list.append(info)
return self.list
else:
return "str or int"
def g... |
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
class Line:
def __init__(self, p1, p2):
self.x = p1.get_x() - p2.get_x()
self.y = p1.get_y() - p2.get_y()
... |
import random
import math
from c1_1 import *
"""
输入一个三位数与程序随机数比较大小
1 如果大于程序随机数,则分别输出这个三位数的个位、十位、百位
2 如果等于程序随机数,则提示中奖,记100分
3 如果小于程序随机数,则将120个字符输入到文本文件中
(规则是每一条字符串的长度为12,单独占一行,并且前四个是字母,后8个是数字
"""
# 输入函数
while True:
num = input("请输入一个三位数:")
random_number = random.randint(100, 999)
# 检测输入是否是纯数字
if nu... |
import math
def comparison_small(num):
"""小于比较"""
print("这是一个小于")
def comparison_big(num):
"""大于比较"""
num = int(num)
num_one = num//100
num_two = num%100//10
num_three = num%100%10
print("百位是{}".format(num_one))
print("十位是{}".format(num_two))
print("个位是{}".format(num_three)... |
alien_color = 'red'
if alien_color == "green":
print("You get 5 points")
elif alien_color == "red":
print("You get 10 points")
else:
print("You get 15 points") |
name_invented = ['xuweicheng', 'zhangbo', 'zhuyifan', 'daipaiyu']
for i in name_invented:
print("Congralution! You are invented in this party, " + i.title())
print("It's shame that " + name_invented[0].title() + " can't come with us")
del name_invented[0]
name_invented.insert(0,'wangluodan')
print(name_invented)
na... |
import argparse
import os
import sys
parser = argparse.ArgumentParser(description="Create code project templates for C++, HTML and Python")
parser.add_argument("-t", "--template", help="Defines the template that you want to make", required=True)
parser.add_argument("-asrc", "--addsrc", action="store_true", help="Cho... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-03-14 20:16:01
# @Author : Damon Chen (Damon@zhenchen.me)
# @Link : www.zhenchen.me
# @Version : $Id$
# @Description:
import os
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do n... |
x = "there are %d types of people." % 10
# variable with string inside
# Defining decimal variable %d at end of string
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
# variable with strings inside
# defining multiple string variables %s
print x
# print varible x
pri... |
print "How old are you?",
age = raw_input()
# comma prevents new line
# variable asking for data raw_input()
# You can put any kind of data in raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "so, you're %r old, %r tall and %r heavy." % (
age, ... |
"""
Given a array/list , return a randomly shuffle array/list
this is implementation of "Fisher–Yates shuffle Algorithm",time complexity of this algorithm
is O(n) assumption here is, function rand() that generates random number in O(1) time.
Examples:
Given [1,2,3,4,5,6,7], [5, 2, 3, 4, 1]
Given [1,2,3,4,5,6,7], [1,2,... |
"""
4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
Количество элементов (n) вводится с клавиатуры.
Пример:
Введите количество элементов: 3
Количество элементов - 3, их сумма - 0.75
ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ
"""
try:
N = int(input('Введите число елементов в последовательност... |
import sys
sys.stdin = open("args1.txt")
def answer():
f, s = list(map(int, input().split()))
ans = 0
return " ".join( str(a) for a in sorted(ans))
def main():
ncases = int(input())
for i in range(ncases):
print("Case #{0}: {1}".format(i + 1, answer()))
if __... |
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total % 2: return False
target = total // 2
# * Sort the array -> NlogN
# * Create a current sum set for all possible (deduped) sums
# * Check if the target is in the total
... |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
## Start from the finish line
## Only move to left and up
## Every position is the sum of its right and down
grid = [[0]*(n+1) for _ in range(m+1)]
for row in reversed(range(m)):
for c... |
# -*- coding: utf-8 -*-
# @Time : 2017/10/5 15:43
# @Author : Yulong Liu
# @File : p0005_M_LongestPalindromicSubstring.py
"""
题号:5
难度:medium
链接:https://leetcode.com/problems/longest-palindromic-substring/description/
描述:找出一个长度不大于1000的字符串中的最长回文子串(非子序列)
"""
class Solution(object):
def longestPalindrome(self... |
x = 1
total = 0
for x in range(1,10):
total = total + x
x = x + 1
print("x=",total)
|
#!/usr/bin/env python
'''
Leetcode: Search in Rotated Sorted Array
Leetcode: Search in Rotated Sorted Array II
http://leetcode.com/2010/04/searching-element-in-rotated-array.html
'''
from __future__ import division
import random
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1... |
#!/usr/bin/env python
'''
Leetcode: Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, ... |
#!/usr/bin/env python
from __future__ import division
class Node(object):
def __init__(self, value, next=None, prev=None):
self.prev = prev
self.next = next
self.value = value
def __str__(self):
if self.next is None:
return str(self.value)
else:
... |
#!/usr/bin/env python
'''
Leetcode: Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html
http://... |
#!/usr/bin/env python
'''
Leetcode: Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of t... |
#!/usr/bin/env python
'''
Leetcode: Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer
which could point to any node in the list or null. Return a deep copy of the list.
'''
from __future__ import division
import random
import LinkedList
class Node(LinkedL... |
#!/usr/bin/env python
'''
Leetcode: Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
'''
from __future__ import division... |
#!/usr/bin/env python
'''
Leetcode: Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note... |
#!/usr/bin/env python
'''
Leetcode: Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example: Given the below binary tree,
1
/ \
2 3
Return 6.
2-1-3
'''
from __future__ import division
import random
from BinaryTree ... |
#!/usr/bin/env python
from __future__ import division
import random
from BinaryTree import Node, root, root_with_id
'''
Leetcode: Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example: Given the below b... |
#!/usr/bin/env python
'''
Leetcode: Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
... |
#!/usr/bin/env python
'''
Leetcode: Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For exam... |
#!/usr/bin/env python
from __future__ import division
import random
'''
Leetcode: Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
def func()... |
from game import Game
from layout import Layout
choice = str(input("Do you want to play? (Y/N)"))
player1 = Game.play(choice)
print("You choosed {}".format(player1))
Layout.layout()
print("")
index = int(input("Enter position:"))
Layout.index(index, player1)
Layout.layout()
|
# coding: utf-8
import urllib2
import math
# question 1
def lit_fichier():
# le principe est le m�me que pour le chargement d'un fichier
# le programme lit directement les informations depuis Internet
f = urllib2.urlopen(
"http://www.xavierdupre.fr/enseignement" "/examen_python/restaurant_paris.t... |
# coding: utf-8
from functools import reduce
def recherche(li, c):
"""
Retourne l'index d'un élément ou -1 si non trouvé.
:param li: liste
:param c: élément à trouver
:return: position
.. exref::
:tag: Base
:title: recherche avec index
Lorsqu'on cherche un élément ... |
# coding: utf-8
# �nonc� 1, exercice 1, recherche dichotomique
# question 1
def recherche_dichotomique(element, liste_triee):
"""
premier code: http://www.xavierdupre.fr/blog/2013-12-01_nojs.html
"""
a = 0
b = len(liste_triee) - 1
m = (a + b) // 2
while a < b:
if liste_triee[m] =... |
import os
import zipfile
from typing import List
from urllib.request import urlopen
def decompress_zip(filename, dest: str, verbose: bool = False) -> List[str]:
"""
Unzips a zip file.
:param filename: file to process
:param dest: destination
:param verbose: verbosity
:return: return the list ... |
import math
import unittest
class TestFunctions(unittest.TestCase):
# 1st Task
def calculateMpg(miles_int, gallons_int):
return miles_int / gallons_int
miles_string = input("Enter the amount of miles you went.")
gallons_string = input("Enter the number of gallons you consumed.")
miles_int= int(miles_string)
gal... |
import time
# dict mit sprechenden Stundenbezeichnungen
STUNDEN = { 0: "zwölf",
1: "eins",
2: "zwei",
3: "drei",
4: "vier",
5: "fünf",
6: "sechs",
7: "sieben",
8: "acht",
9: "neun",
10: "zehn",
... |
dict = {} # empty dictionary
dict[0] = 0
dict[1] = 3
dict[2] = 3
dict[3] = 5
dict[4] = 4
dict[5] = 4
dict[6] = 3
dict[7] = 5
dict[8] = 5
dict[9] = 4
dict[10] = 3
dict[11] = 6
dict[12] = 6
dict[13] = 8
dict[14] = 8
dict[15] = 7
dict[16] = 7
dict[17] = 9
dict[18] = 8
dict[19] = 8
dict[20] = 6
dict[30] = 6
dict[40] = 5
... |
#!/usr/bin/env python3
###################################
# WHAT IS IN THIS EXAMPLE?
#
# This example shows using the bot framework to build non-bot functionality.
# Here, the currently logged in user will send a message to the channel and
# then loop through rotating the message by moving the first character to
# th... |
class Clock(object):
def __init__(self,hours=0,minutes=0,seconds=0):
self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds
def set(self,hours,minues,seconds=0):
self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds
def tick... |
from Logica import Logica
print ("""Ingrese la figura de la cual va a calcular su volumen:
1) Esfera
2) Cilindro
3) Cono de con formula
4) Cono mediante cálculo con cilindros
5) Cubo""")
opc = int(input())
log = Logica(opc)
print ("El volumen es "+str(log.mostrar_volumen())+" u^3")
|
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
class TextBlock(BoxLayout):
def __init__(self,container, **kwargs):
super(TextBlock, self).__init__(**kwargs)
self.width = container.width
self.height = container.height
self.size_hint_max_y = 200
self... |
dict1 = dict()
def staircase(n):
if n in dict1:
return dict1[n]
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
else:
a = staircase(n-1)
dict1[n-1] = a
b = staircase(n-2)
dict1[n-2] = b
c = staircase(n-3)
... |
T = int(input())
for _ in range(T):
n = int(input())
str1 = input()
if(str1 == "".join(reversed(str1))):
print("Yes")
else:
print("No") |
a = input("Enter the string:\t")
list1 = []
for i in a.split(" "):
list1.append("".join(reversed(i)))
print(" ".join(list1)) |
# This is simply to learn about the MD5 Hash
"""
MD5 is hash function accepts sequence of bytes and returns 128 bit hash value,
usually used to check data integrity but has a lot of security issues.
This basically has 3 functions.
1. Encode(): converts the string into bytes to be acceptable by the hash function.
2.... |
class TrieNode(object):
#Trie Node class.
def __init__(self,char=None):
#This represents all the nodes of the trieNode.
self.children = [None]*26
#isEndOfWord is true if node represents end of the word,
self.character = char
self.isEndOfWord = False
class Trie(object):... |
import sys
from collections import defaultdict
def printSolution(shortest_distance,start):
ans = sorted(shortest_distance.items())
for i in ans:
if i[0] == start:
continue
elif i[1] >= 100000000000:
print(-1,end=" ")
else:
print(i[1],end=" ")
prin... |
def deep_reverse(arr,res):
'''
Base case: Here, as soon as the list is over, we return,
'''
if(len(arr) == 0):
return
else:
'''
1. We take the element from the end of the list
i). If it is a list, we recursively call the same function on this element... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
We will simply use the Binary search algorithm to find the square root, and we will be done in O(log(n))
"""
i... |
str1 = input("Enter the string:\t")
#In-place means that you should update the original string rather than creating a new one
n = len(str1)
str1 = list(str1)
for i in range(n//2):
temp = str1[i]
str1[i] = str1[n-i-1]
str1[n-i-1] = temp
print("".join(str1))
|
import sys
def get_min_max(ints):
if (len(ints) == 0):
print("Array is empty!")
return -1
maximum = -sys.maxsize
minimum = sys.maxsize
for i in ints:
if i > maximum:
maximum = i
if i < minimum:
minimum = i
print("Maximum minimum pair i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.