text stringlengths 37 1.41M |
|---|
def pattern(n):
for i in range(1,10):
for i in range(0,i):
print("*")
print("\r")
pattern(10)
#not completed |
#a function its self is called recursion
#fibnocci series using recursion
#call afunction inside the same function
#important
def recur_fibo(n):
if n<=1:
return n
else:
return recur_fibo(n-1)+recur_fibo(n-2)
nterms=10 #nterms=int(input("enter number))
if nterms<=0:
print("please enter a pos... |
#for loop same
#initialization
#condition
#inc or dec
#inc 1 ,bt not using;no need of 1,loop default the inc
for i in range(1,10): #upp-1
print(i)
|
list=[1,53,4,96,46]
print(list)
oddset=set()
evenset=set()
for i in list:
if(i%2==0):
evenset.add(i)
else:
oddset.add(i)
print("even set",evenset)
print("odd set",oddset) |
#program to accept three integers and print the largest of the three. make use of
#only if statement.
x=float(input("enter the first number:"))
y=float(input("enter the second number:"))
z=float(input("enter the third number:"))
max=x
if(y>max):
max=y
if(z>max):
max=z
print("largest number is", max) |
sal=int(input("enter ur salary"))
year=int(input("enter num of yr of service"))
bonus=(5/100)*sal
if(year>=5):
newsal=sal+bonus
print(newsal)
else:
print("experience lessthan 5")
|
#Create an Animal class using constructor and build a child class for Dog?
class Animal:
def __init__(self,name,age):
self.name=name
self.age=age
def print(self):
print("i'am",self.name)
print(self.age,"years old")
class Dog(Animal):
def __init__(self,name,age,type):
... |
# to add odd and even elemnts to different set
s={1,8,5,9,4,7,11,100,5,}
print(s)
odd=set()
even=set()
for i in s:
if(i%2==0):
even.add(i)
else:
odd.add(i)
print("even set",even)
print("odd set",odd)
|
#reduce
# import functools
from functools import *
arr=[1,2,3,4,5,6]
total=reduce(lambda num1,num2:num1+num2,arr)
print(total)
#print highest number
highest=reduce(lambda num1,num2:num1 if num1>num2 else num2,arr)
print(highest)
|
#using forloop odd to even number and check sum
low=int(input("enter the low limit"))
upp=int(input("enter the upp limit"))
evensum=0
oddsum=0
for i in range(low,upp+1):
if(i%2==0): #1%2==0
evensum+i
else:
oddsum+i
print(evensum)
print(oddsum) |
#write a program to input a value in kilometers and convert it into miles (1km=0.621371miles)
km=int(input("enter the kilometers:"))
miles=km*0.621371
print(miles) |
#odd or even
def odd():
num1=int(input("enter the num"))
if(num1%2==0):
print("even")
else:
print("odd")
odd() |
# 1. PRINT STATEMENT: [syntax: print()]
print("hello world")
# 2. PRINT BLANK LINES:
print(4 * "\n") # it's print 4 blank lines
""" NOTE:
1. print("\n\n\n\n") this is another print statement to print 4 blank lines """
# 3. PRINT END COMMAND: [syntax : print("", end ="")]
""" NOTE:
1.... |
# import libraries
# -*- coding: utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
# specify the url
quote_page = "http://www.bloomberg.com/quote/SPX:IND"
# query the website and return the html to the variable ‘page’
page = urllib2.urlopen(quote_page)
# parse the html using beautiful soup and store in variable `... |
# Normal library imports
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
# importing requisite information from create_data.py
# 1. show_images(): to display the images so it may be verified if Canny Edge detection worked fine
# 2. grey_images: which is a
from create_data i... |
def check_index(key):
if not isinstance(key,int):raise TypeError
if key<0:raise IndexError
class ArithmeticSequence:
def __init__(self,start=0,step=1):
self.start = start
self.step = step
self.changed = {}
def __getitem__(self,key):
check_index(key)
try:return ... |
#!/usr/bin/env python
# list = [num*num for num in range(1,11)]
# print(list)
# list1 = [num*num for num in range(1,11) if num%2 == 0]
# print(list1)
# list2 = [char+num for char in ['a','b','c'] for num in['1','2','3']]
# print(list2)
# list3 = (num*num for num in range(1,6))
# print(list3)
# for li in list3... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
class MyClass(object):
message="hello, developer!"
def show(self):
print(self.message)
print("Here is %s in %s!" % (self.name,self.color))
@staticmethod
def printMessage():
print("printMessage is called")
print(MyClass.message)... |
import random
import time
nahodne_cislo = []
zadane_cislo = []
def main():
print("Ahoj, vitej ve hre bulls and cows!")
print("Generuji nahodne ctyrciferne cislo (muze zacinat nulou).")
vytvor_nahodne_cislo()
t0 = time.time()
pokus = 0
while nahodne_cislo != zadane_cislo:
pokus += 1
... |
"""
This project was created by the right honorable sir Alexander de Poyen-Brown, in
the year of Our Lord two thousand and twenty one for the purpose of being silly.
"""
def sillyText(word, num):
"""
Purpose: To duplicate each character in a string
Parameters: word - the string in question, num -... |
# Pograma que da um desconto de 12 porcento de um produto
produto = 'Video Game'
valor = float(input('Entre com o valor do produto: R$'))
desc = (valor * 12) / 100
print(f'Produto: {produto}.\nValor: R${valor}\nDesconto: R${desc}\nTotal a pagar: R${valor - desc}') |
# Peça ao usuario para digitar 3 numero e retorne a somas de ambos
"""num1 = int(input('Entre com um numero: '))
num2 = int(input('Entre com um numero: '))
num3 = int(input('Entre com um numero: '))
soma = num1 + num2 + num3
print(soma)"""
nums = []
cont = 0
while cont < 3:
numeros = int(input('Entre com um num... |
# Convertendo Km/h para milhas
km_h = float(input('Entre com a distancia em KM/h: '))
milhas = km_h / 1.62
print(milhas) |
import sys
import click
#(1)Source: https://stackoverflow.com/questions/20063/whats-the-best-way-to-parse-command-line-arguments
#(2)Source: https://www.youtube.com/watch?v=SDyHLG2ltSY (click watch)
#(3)Source: https://www.youtube.com/watch?v=gR73nLbbgqY (tools for cli)
#(4)Source: https://www.youtube.com/watch?v=hJhZ... |
import sys
# total arguments
print("Total arguments passed: " + str(len(sys.argv)))
assert len(sys.argv)==3, "Expected 2 arguments."
s1 = sys.argv[1]
s2 = sys.argv[2]
print("No of characters in both strings: (" + str(len(s1)) + "," + str(len(s2)) + ")")
print("Are they equal? " + str(s1==s2))
counter=0
for char1,ch... |
# 第一步 以像素为单位,进行带角度的坐标转换 像素相对坐标系
# 第二步 将坐标转化为以毫米为单位 毫米绝对坐标系
# 第三步 加上平移的毫米偏移量,最终毫米绝对坐标系下的坐标
import numpy as np
# a = np.arange(10)
# print(a)
# print(a.shape)
a = np.arange(100).reshape(10, 10)
print(a)
print(a.shape)
a_index = []
for i... |
###############################
# python imports
###############################
from time import time
###############################
# Timing Class
###############################
class Timer:
def __init__(self, precision=3):
'''
(Timing, int) -> (None)
:constructor function for the Timing class, will... |
def show_magicians(list):
# while list:
# print(list)
# 不能自动跳出去
for person in list:
print(person)
personlist = ["linlin","linna","nana"]
show_magicians(personlist)
|
##Codifica strings ao transformá-las em binário, de binário para gray e de gray de volta para string.
#Encodes strings by transforming them into binary, from binary to gray and from gray into string again.
print('Bem-vindo ao Codificador.') #'Welcome to the encoder.'
print('O codificador usa os caracteres dentro da li... |
# Recebe o número de itens em uma lista e o valor de cada item e imprime o dobro do valor deles na ordem inversa
# Receives the number of items in a list and each item value, then prints their double in the reverse order
lista = []
n = int(input('Insira o número de itens da lista: '))
for cont in range (1, n + 1):
... |
import random
import numpy as np
from operator import itemgetter
class RandomSampling(object):
"""This class is used to implement different types of random sampling techniques
"""
def __init__(self,data,num):
print ("Initialzing Random Sampling Class")
self.data=data
self.num=num
... |
import numpy as np
from .layers import Layer
from tqdm import tqdm
# Neural Network API inspired by sequential model
def batch_iterator(X, y=None, batch_size=64):
"""
Simple batch iterator
From https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/utils/data_manipulation.py
... |
if __name__ == '__main__':
s = raw_input()
alphanum = 0
alpha = 0
digit = 0
lower = 0
upper = 0
for i in range(len(s)):
if(s[i].isalnum()):
alphanum+=1
if(s[i].isalpha()):
alpha+=1
if(s[i].isdigit()):
digit+=1
... |
# High order functions
# son funciones que reciben como prametro a otra funcion
# Existen 3 principales:jilter, map, reduce
from functools import reduce
def run():
my_list = [1,4,5,6,9,13,19,21]
odd = [i for i in my_list if i % 2 != 0]
print(odd)
# Filter: filtra los valores de una lista
odd = list... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 00:05:02 2020
@author: Akshat Jain
"""
class Node(object):
def __init__(self , character):
self.character = character
self.leftchild = None
self.rightchild = None
self.middlechild = None
self.value = 0
class ... |
str = "Hello man, how are you babe?"
print(str[3])
print(str[3:5])
print(str.split(","))
print(str.lower())
print(str.upper())
print(len(str))
print("What is your name?")
name = input()
print("Your name is " + name)
|
class Person:
def __init__(self,name, family):
self.name = name
self.family = family
def full_name(self):
return(self.name + " "+ self.family)
class Student(Person):
def __init__(self, fname , lname , year_of_birth):
Person.__init__(self,fname, lname)
self.year_of_b... |
n1 = float(input('Digite a nota 1 '))
n2 = float(input('Digite a nota 2 '))
print('A média entre suas notas "{}" "{}" é "{}"'.format(n1, n2, ((n1 + n2) / 2))) |
a = input("enter value of a")
b = input("enter value of b")
val_a = int(a)
val_b = int(b)
y = (val_a + 4 * val_b) * (val_a + 3 * val_b) + val_a*val_a
print(y)
|
#! /usr/bin/env python3
#
# Take a file, extract all trees, midpoint root, calculate height, print
# heights
import argparse
from parsers import Tree
from midpointRoot import midpoint_root
from describe import print_descriptive_statistics
def get_height(tree):
tree = midpoint_root(tree)
return tree.avg_dist(tree.... |
#https://www.hackerrank.com/challenges/np-arrays/problem?h_r=next-challenge&h_v=zen
import numpy
def arrays(arr):
# complete this function
# use numpy.array
arrnp = numpy.array(arr,float)
return arrnp[::-1]
arr = input().strip().split(' ')
result = arrays(arr)
print(result) |
#!/bin/python3
import math
import os
import random
import re
import sys
def keyFunc(item,k):
return item[k]
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
# print(arr[::... |
# https://www.hackerrank.com/challenges/py-collections-ordereddict/problem
from collections import OrderedDict
n = int(input())
ordered_dictionary = OrderedDict()
for _ in range(n):
items = input().rpartition(' ')
item_name = items[0]
net_price = int(items[2])
if item_name in ordered_dictionary:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 11 12:08:22 2017
@author: yazar
"""
import numpy as np
import pandas as pd
from scipy import linalg
from sklearn import preprocessing
from matplotlib import pyplot as plt
from scipy import optimize
def sigmoid(x):
return 1 / (1 + np.exp(-x))
... |
import socket
def draw_board(content):
if len(content) != 9:
# board content len error
return
print('Current board:\n')
print(f'|{content[0]}|{content[1]}|{content[2]}|\n')
print(f'|{content[3]}|{content[4]}|{content[5]}|\n')
print(f'|{content[6]}|{content[7]}|{content[8... |
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
N = len(nums)
for i in range(N - 1):
# print(output[i])
if nums[i] == nums[i + 1]:
del nums[i]
else:
i += 1
return nums
number_l... |
import math
import sys
testlist = [(1, 3), (2, 5), (10, 6), (14, 15), (13, 14), (45, 81)]
min_distance = sys.maxsize
closest_points = [testlist[0], testlist[1]]
for point in testlist:
i = testlist.index(point) + 1
for second_point in testlist[i:]:
y_length = second_point[1] - point[1]
x_lengt... |
def list_vertices(g):
# Your code here
vertices = []
for i in g:
vertices.append(i)
return vertices
l = {1:[2, 4], 2:[3, 4], 3:[4], 4:[5], 5:[1]}
print(list_vertices(l)) |
import json
import os
import crypt
import getpass
#Constants
file_name = "data.json"
def login_validation(database_name, user_dict):
'''
returns True if account is found in the database,
and False otherwise.
'''
# account_exists = False
with open(database_name, 'r') as file:
data = file... |
from collections import defaultdict
from heapq import *
def dijkstra(edges, f, t): #edges = lista dei link | f = nodo di partenza (from) | t = nodo di arrivo (to)
g = defaultdict(list) #dizionario dove ad ogni nodo viene fatto corrispondere un nodo raggiungibile da esso e il peso per raggiungerlo
for link in... |
#1. Write a code to verify if the string is a palindrome
str1=input("Enter a string:")
if(str1==str1[::-1]):
print("The string is a palindrome")
else:
print("The string is not a palindrome") |
# -*- coding: utf-8 -*-
print "medio de tres numeros"
def entra():
a = int(raw_input("numero 1:"))
b = int(raw_input("numero 2:"))
c = int(raw_input("numero 3:"))
sale(a, b, c)
def sale(a, b, c):
if a < b:
if b < c:
print "el medio es %d" % b
elif a < c:
print "el medio es %d" % c
else:
print "el... |
# -*- coding: utf-8 -*-
import math
print "ecuacion cuadratica"
def entra():
a = int(raw_input("numero 1:"))
b = int(raw_input("numero 2:"))
c = int(raw_input("numero 3:"))
x = b ^ 2 - 4 * a * c
return calcula(a, b, c, x)
def calcula(a, b, c, x):
if a == 0:
print "no se puede dividir"
else:
x = (-b) + ma... |
#interpolation module
#takes 2 two-dimensional points and interpolates for a point in between them
#author: shulkasr
def interpolate(two_dim_array,interpPoint):
x1 = two_dim_array[0][0] if two_dim_array[0][0] <= two_dim_array[1][0] else two_dim_array[1][0]
y1 = two_dim_array[0][1] if two_dim_array[0][0] <= two... |
from random import randint
from time import sleep
def hallway():
inventory = []
lockedDoor=5
hallDoors =[1,2,3,4]
doorOption = [ 'N','n','Y','y']
deathDoor = hallDoors.pop(randint(0,len(hallDoors)-1))
keyDoor = hallDoors.pop(randint(0,len(hallDoors)-1))
coinDoor = hallDoors.pop(r... |
def merge_sort(data_list):
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
del left[0]
else:
result.append(right[0])
del right[0]
... |
"""A class for creating a timer widget."""
from kivy.clock import Clock
import kivy.properties as props
from kivy.uix.widget import Widget
class Timer(Widget):
"""Used to dynamically display the current time elapsed on the screen."""
# initializes a timer with 0 seconds.
timeText = props.NumericProperty(... |
import turtle
'''
turtle.showturtle()
turtle.color("red")
turtle.forward(120)
turtle.write("1", font=('adobe garamond', 20, 'normal'))
turtle.right(90)
turtle.color("yellow")
turtle.forward(50)
turtle.write(" 2", font=('adobe garamond', 20, 'normal'))
turtle.right(90)
turtle.color("green")
turtle.... |
from tkinter import *
import tkinter
master = Tk()
master.title("AUTOMATED MACHINE LEARNING")
#creating a text label
Label(master, text="AUTOMATED MACHINE LEARNING SYSTEM",font=("times new roman",20),fg="white",bg="maroon",height=2).grid(row=0,rowspan=2,columnspan=8,sticky=N+E+W+S,padx=5,pady=5)
location=StringV... |
def run():
def crea_diccionario(diccionario):
nuevo_diccionario = {}
for asignatura, nota in diccionario.items():
asignatura = asignatura.upper()
if nota >= 7:
nota = 'Aprobado'
nuevo_diccionario[asignatura] = nota
return nuevo_diccionario
asignaturas_notas = {
'Español... |
def contar_palabras(cadena):
cadena = cadena.split()
palabras = {}
for palabra in cadena:
if palabra in palabras:
palabras[palabra] += 1
else:
palabras[palabra] = 1
return palabras
#print(palabras)
def mas_repetida(cadena):
palabra_mas_repetida = ''
maxima_frecuencia = 0
for palabr... |
from functools import reduce
def run():
#map -> map(funcion, objeto_iterable)
""" def elevar_al_cuadrado(numero):
return numero * numero
lista = [1,2,3,4,5]
resultado = list(map(elevar_al_cuadrado, lista))
print(resultado) """
#filter -> filter(funcion, objeto_iterable)
""" def mayor_a_cinco(numero... |
numeros = [50, 75, 46,100, 22, 80, 65, 8,1]
numeros.sort()
print(f'El número más pequeño de {numeros} es {numeros[0]}')
print(f'El número más grande de {numeros} es {numeros[-1]}') |
n = float(input("Ingresa un numerador: ")) #numerador es el de arriba
m = float(input("Ingresa un denominador: ")) #denominador es el de abajo
c = n/m
r = n%m #módulo -> regresa el residuo de una división
print(f"El resultado de dividir {n} entre {m} es {c} y su residuo es {r}") |
def run():
inmuebles = [
{'año': 2000, 'metros': 100, 'habitaciones': 3, 'garaje': True, 'zona': 'A'}, # 0
{'año': 2012, 'metros': 60, 'habitaciones': 2, 'garaje': True, 'zona': 'B'}, # 1
{'año': 1980, 'metros': 120, 'habitaciones': 4, 'garaje': False, 'zona': 'A'}, # 2
{'año': 2005, 'metros': 75, 'ha... |
monto = float(input("Monto: "))
interes = float(input("Interés: "))
anios = int(input("Años: "))
for i in range(anios):
monto = monto * (1+interes)**anios
print(f"Cantidad de dinero después de {i+1} años $ {monto}") |
print("\n\t Welcome to the Gusess Game\n\n\t You have only three atemps")
import random
for i in range(3):
ran=random.randint(1,6)
number=int(input("enter number > "))
if number==ran:
print("you Guess the number.. Congrats ")
break
else:
print("bad luck")
|
# https://blog.csdn.net/sinat_38321889/article/details/80390238
#selectSort which is a time-consuming sort algorithm.Its Time-complexity is O(N**2)
#1、we just use the simple sort algorithm to get the smallest number per loop,which the time-consuming is O(n)
#2、next we can define a function that a loop to get the small ... |
def first_double_string(mot):
dict_char = dict()
for letter in mot:
if letter in dict_char:
dict_char[letter]+=1
print(letter)
return letter
else:
dict_char[letter]=1
return dict_char
first_double_string('abcdefa')
first_double_string('j... |
# encoding=utf-8
# -,- 回头理解清楚一下
class Solution(object):
def recur_search(self, left, right, nums, target):
if left == right:
if nums[left] == target:
return left
else:
return -1
mid = (left + right) / 2
if nums[mid] == target:
... |
import pandas as pd
import numpy as np
dfx = pd.read_csv("data.csv")
dataset = dfx.values
print(dataset)
res = []
n = dataset.shape[1]-1
for i in range(n):
res.append('Φ')
print("The initial value of hypothesis:")
print(res)
print()
for i in dataset:
if i[-1] == 'Yes':
for j in range(len(i)-1):
... |
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
s = "a b c d e f"
# split adds individual characters to a list
z = s.split()
print(z)
if 'a' in z:
print("A is in z")
else:
print("A is not in z")
for i in z:
print(i)
# sort sorts by ascending order
g = [4, 5, 3, 2, 7]
g.sort()
print(g)
g.reverse()
prin... |
"""
This example shows how to use the Mesh class in order
to generate a geometry similar to those that may define
a lifting surface planform.
X ^ B This geometry is positioned in space
| +---+ with two chords simulating the root
| / | and tip chords, usin... |
# Translate one language to the other using the translate library!
from translate import Translator
def trans():
global user_statement
user_statement =input('Type the statement you want to translate: ')
print()
langauge_type = input('Which language will you like to translate it to? ')
m = langauge_... |
# Write a python program to find sum of the first n positive integers.
# sum = ( n * ( n + 1)) / 2
list=[1,2,3,4,5,6,7,8,9,10]
total=sum(list)
print(f"The sum of the give integer is {total}") |
# 3. BMI 指数测试
weight = float(input('请输入体重(公斤):'))
height = float(input('请输入身高(米):'))
height_square = height ** 2
bmi = weight / height_square
min_weight = height_square * 18.5
max_weight = height_square * 24
print('您的BMI指数为: %.2f ' % bmi)
print('正常体重范围是%.2f公斤 - %.2f公斤 之间' %(min_weight, max_weight))
if bmi < 18.5:
... |
"""
Program: NumPy_array_math.py
Author: Daniel Meeker
Date: 9/17/2020
This program demonstrates using NumPy in Python.
"""
import numpy as np
if __name__ == '__main__':
array_1 = np.array([[10, 15, 20], [2, 3, 4], [9, 14.5, 18]])
array_2 = np.array([[1, 2, 5], [8, 0, 12], [11, 3, 22]])
array_1_even = arr... |
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
print(f"I received {my_votes / total_votes * 100}% of the total votes.")
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What ... |
#!/usr/bin/env python
# coding: utf-8
"""
A simple VM interpreter.
Code from the post at http://csl.name/post/vm/
This version should work on both Python 2 and 3.
"""
from __future__ import print_function
from collections import deque
from io import StringIO
import sys
import tokenize
def get_input(*args, **kw):
... |
#!/usr/bin/env python
"""
nn.py
Implements feedforward complete artifical neural networks.
Python 2.7.12
A 'from scratch' implementation + a few code snippets from grad school coursework.
"""
import math
import random
def sigmoid(dblX):
"""The sigmoid function. Given input dblX, sigmoid(dblX)... |
'''
Write a Python class to find the three elements that sum to zero
from a list of n real numbers.
Input array: [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
'''
from itertools import combinations
def sumToZero(inArray):
comb = combinations(inArray, 3)
posibOutComes = list(comb)
... |
'''
Write a Python class to find validity of a string of parentheses, '(', ')', '{',
'}', '[' and ']'. These brackets must be close in the correct order, for example
"()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid
'''
def bra(string):
dis = {'[': ']', '{': '}', '(': ')'}
stack = []
... |
'''
Create a function, is_palindrome, to determine if a supplied word is
the same if the letters are reversed.
'''
def is_palindrome(word1):
word2 = word1[-1::-1]
return "It is palindrome" if word1 == word2 else "It is not palindrome"
word1 = input("Enter the word: ")
word1.lower()
print(is_palindrome(wor... |
'''
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
def for_n_digit_numbers(n=3):
limit = calculate_limit(n)
multipliers = []
largest = 0
... |
for i in range(0, 10):
print("In the iteration with the value", i)
for i in range(0, 10):
print("perfect square", i, "is", i*i)
for j in range(1,11):
print(i, "x", j, "=", i*j)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
count = raw_input("Vpiši cifro do katere želiš prešteti: ")
count = int(count)
for num in xrange(1, count):
if num % 3 == 0 and num % 5 == 0:
print "FizzBuzz"
elif num % 3 == 0:
print "Fizz"
elif num % 5 == 0:
print "Buzz"
else:
print num
|
def clean_dict(d):
"""Remove all key, value pairs whose key is "tooltip" or whose value is either None or empty"""
clean = {}
for k, v in d.items():
if isinstance(v, dict):
nested = clean_dict(v)
if len(nested.keys()) > 0 and k != "tooltip":
clean[k] = nested
... |
# 1b qns 4
import math
import tensorflow as tf
import numpy as np
import pylab as plt
seed = 10
tf.set_random_seed(seed)
# Same implementation as question 1
def get_admission_data(small = None):
np.random.seed(seed)
#read and divide data into test and train sets
admit_data = np.genfromtxt('admission_p... |
name = input("What's your name?\n")
print("Hi " + name + " How are you?")
user = input() #for saving useres answers
print("Thanks," + name + " Good bye.") |
class Person():
def __init__(self, name, age, idNum):
self.name = name
self.age = age
self.idNum = idNum
def output(self):
print("Your name is " + self.name + " your age is " + self.age + " Your ID num is " + self.idNum)
ana = Person("Ana", "28", "23225655")
class Man(): #N... |
myvarable = 10
if myvarable == 5:
print("This is true, myvariable = 10")
else:
print("this is false myvariable is NOT 10")
print("Lession for Greater, less than, and aqual operator")
enyvar = 150
othervar = 5000
if enyvar >= othervar:
print("enyvar is greater than othervar")
else:
print("No") |
print("This program checks if you are eligbe for loan or not")
salary = int(input("How much is your salary"))
if(salary>1000):
amount = 200
print("You are eligbe to get a bank loan py paying", amount, "monthly")
elif(salary == 1000):
amount=500
print("you are eligbe to get bank loan with higher monthl... |
n = int(input("Введите числo: "))
z = 0
for i in range (1, n+1):
y = 1 / i
if i % 2 ==0:
y = -y
elif i % 2 !=0 or y ==1:
y = y
z += y
print(z)
|
n = int(input("Введите число от 1 до 9 "))
x = n * 10
for i in range (n, x, n):
print(i, end=" ")
|
y = int(input("Введите угол в градусах: "))
x = 30 #Градусы
hours = y // 30
min = y % 30 * 2 # 30gr - 60min, 15gr - xmin => x = 15 * 60 / 30
print(min)
|
x = int(input("Введите число "))
max = x
while x != 0:
x = int(input("введите число "))
if x > max:
max = x
print(max)
|
import math
def area():
a = float(input("Введите a "))
b = float(input("Введите b "))
c = float(input("Введите c "))
d = float(input("Введите d "))
e = float(input("Введите e "))
f = float(input("Введите f "))
g = float(input("Введите g "))
S1 = (a * b) // 2
S2 = (e * d) // 2
x... |
a=(input("ведите число a "))
b=(input("ведите число b "))
c=(input("ведите число c "))
x=b
z=a
a=x
b=c
c=z
print(a,b,c)
|
a = input("Введите число: ")
length = len(a)
x =""
for i in range(length):
y = a[length -1 - i]
x = x + y
print(int(x)) |
n = int(input("Введите натуральное число n: "))
m = int(input("Введите число m: "))
p = int(input("Введите число p: "))
sum = 0
for i in range(n):
d = int(input("Введите число d: "))
if d <= m:
sum += d
if sum % p == 0:
print("Сумма чисел 'd' кратна числу p")
else:
print("Сумма чисел 'd' не кр... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.