text
stringlengths
37
1.41M
""" Triangulates 2D image points to create 3D object/world points. """ import cv2 import numpy as np def from_ip(ip, E=None, F=None): """ Calculates the distance from cam center to each point in IP. """ l_cam_mat = [np.eye(3, 3), np.zeros(1, 3)] if E: rx, ry, rz, _ = cv2.triangulatePoints...
# for loop understands the lists paranoid_android = 'Marvin, the paranoid android' letters = list(paranoid_android) # for loop automatically detects the lists and works accordingly for alph in letters: print(alph) #for loop also detects the slices of the lists for alph in letters[:6]: print('\t',alph) print...
# sets don't allow duplicates, order is not guaranteed vowels = {'a','a','e','e','i','o','u','u'} # duplicates will be removed {'a', 'i', 'e', 'u', 'o'} print(vowels) # set from string vowels1 = set('aeeeeeeeiou') print(vowels1) # set operations word = 'hello' vowels2 = set('aeiou') # union {'e', 'l', 'o', 'h', 'i'...
class Bill: period_str: str bill_nbr: int customer_nickname: str customer_name: str customer_address: str customer_zip_place: str nbr_of_eggs: int price_per_egg: float = 0.6 def __init__(self, period_str: str, bill_nbr: int, customer_nickname: str, information_path: str, nbr_of_eggs...
# -*- coding: utf-8 -*- """ Created on Wed Sep 9 11:06:30 2020 @author: zorian Time to scramble some words? """ # user sees : ysk # goal: unscramble the word to sky words_to_scramble = ['man', 'woman', 'person', 'camera', 'television'] #import random from numpy import random #randomly choose a word from list word...
class Person(object): def __init__(self, first_name, last_name, *args, **kwargs): self.first = first_name self.last = last_name def __str__(self): return "{} {}".format(self.first, self.last) def eat(self, food): print('eating ' + food) class Student(Person): def __ini...
""" composition ---- has a --> part of a whole relationship one object owns / contains --> another object MultipleChoiceQuestion Quiz --> has many MultipleChoiceQuestions Survey --> has many MultipleChoiceQuestions Code reuse FTW!!!! self.attribute_name = other_object ducktyping ----- * regardless of type, if object ...
""" web_server.py ===== This file is both a web server and a web application in one. We'll consider a web server as a long running program that handles client connections, accepts requests and sends back responses. The web application is some program that works on the request and constructs a response. The server and t...
""" The purpose of this code is to show how to work with plant.id API. You'll find API documentation at https://plant.id/api """ import base64 import requests from time import sleep secret_access_key = "-- ask for one at business@plant.id --" class SendForIdentificationError(Exception): def __init__(self, m): ...
#!/usr/bin/env python """ info about project here """ __author__ = "Johannes Coolen" __email__ = "johannes.coolen@student.kdg.be" __status__ = "development" def plus(x, y): try: print(x + y) except Exception as e: print(e) main() def min(x, y): try: print(x - y) exc...
import json import csv import io filepath = input("Enter Path to your Json File: ") csv_filepath = input("Enter Name of your Csv File:") csv_filepath_format = csv_filepath + '.csv' json_file = io.open(filepath, 'r+', encoding="utf-8") csv_file = io.open(csv_filepath_format, 'w+', encoding="utf-8") json_parsed = json...
class TV: modelo: "" cor: "" fabricante: "" tamanho = 0 estado_tv = "Desligada" canal_atual = 0 volume_atual = 0 def mudarCanal(self, valor): self.canal_atual = valor def aumentarVolume(self, valor): self.volume_atual = valor def printTV(self): ...
usuarios = {} usuarios_media = {} menor_media = 0 nome_menor_media = '' maior_media = 0 nome_maior_media = '' while (len(usuarios)) != 4: nome = input('Digite seu nome: ') foto1 = int(input('Digite a quantidade de curtdas da primeira foto: ')) foto2 = int(input('Digite a quantidade de curtdas da se...
import sys class ExtendedList(list): @property def reversed(self): return list(reversed(self)) @property def first(self): return self[0] @first.setter def first(self, value): self[0] = value @property def last(self): return self[len(self) - 1] @l...
#Latihan #Akses List list_a = [10, 20, 30, 40, 50] print(list_a) print(list_a[2]) print(list_a[1:4]) print(list_a[-1]) #Ubah Element List list_a[3] = 45 print(list_a[3]) list_a[3:4] = 48, 55 print(list_a[3:5]) #Tambah ELement List list_b = list_a[0:2] print(list_b) list_b.append(25) print(list_b) list_b.extend([35...
message = "Hello Python world!" print(message) message = "Hello Python Crash Course world" print(message) # print('I told my friend, "Python is my favorite language"') print("The language 'Python' is named after Monty Python, not the snake") print("One of Pyhon's strength is its diverse and supportive comunity") # ...
"""This module provides functionality for using the DataFrame widget like for example custom styling""" from typing import Dict import pandas as pd from bokeh.models.widgets.tables import NumberFormatter INT_DTYPE = "int64" INT_FORMAT = "0,0" INT_ALIGN = "right" FLOAT_DTYPE = "float64" FLOAT_FORMAT = "0,0....
class SLLNode: def __init__(self,data): self.data = data self.next = None def __repr__(self): return "SLLNode object: data={}".format(self.data) def get_data(self): """"Return the self.data attribue""" return self.data def set_data(self,new_data): """"R...
# -*- coding: utf-8 -*- """ Created on Sun Feb 7 15:08:35 2021 @author: kalya """ user1 = input("Player 1,Enter your choice rock/paper/scissor: ") user2 = input("Player2,Enter your choice rock/paper/scissor:") def rock_paper_scissor(player_1, player_2): a_list = ["rock","paper","scissor"] whil...
import string def test(): """Here code reads,breaks the file(whitespace) and convertingwords to lowercase""" fin = open("file.txt","r") pun_char = string.punctuation for i in fin: i = i.strip().replace(" ","\n") for char in pun_char: i = i.replace(char,"") i = i.lower(...
class Test: """this class shows time""" time=Test() time.hour=9 time.minute=35 time.second=25 def print_time(t): print('the time is:','%.2d:%.2d:%.2d'%(t.hour,t.minute,t.second)) print_time(time)
# 使用字典 ab = {'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org' , 'Spammer' : 'spammer@hotmail.com'} print("Larry's address is %s" % ab['Larry']) # 使用索引操作符可以增加一个新的键值对 ab['Gundo'] = 'guido@python.org' print('now the new dictionary is :', ab) del ab['Spamm...
def double(x): return 2 * x x = double(2) for x in range(10): for y in range(10): print(x, y)
import datetime import operator import os EMPTY_LIST_MESSAGE = "\nNothing to do yet, add some items to the list.\n" ITEM = "item" DEPT = "department" grocery_list = [] run_date = datetime.datetime.today() class GroceryItem: def __init__(self, item, department): self.item = item se...
import sys # part one: create the length-to-words dictionary contents = open("sonnets.txt").read() words = contents.split() by_length = {} for item in words: if len(item) not in by_length: by_length[len(item)] = [] by_length[len(item)].append(item) #part two: read in standard input and perform the replacements ...
# # Worksheet #4 # # This worksheet is also a Python program. Your task is to read the # task descriptions below and then write one or more Python statements to # carry out the tasks. There's a Python "print" statement before each # task that will display the expected output for that task; you can use # this to ensure ...
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ This file defines the most important class DimQuant, which is a child of BaseDimQuant. The difference with respect to BaseDimQuant is the ability to initialize a DimQuant instance using a string representation of a dimensional quantity. In BaseDimQuant the user has to pr...
# happy2.py # Happy Birthday using value returning functions def happy(): return "Happy birthday to you!\n" def verseFor(person): lyrics = happy()*2 + "Happy birthday, dear " + person + ".\n" + happy() return lyrics def main(): for person in ["Fred", "Lucy", "Elmer"]: print(verseFor(perso...
## program to extract Strings between HTML import re test_str = '<b>Reddy Prasad</b> is <b>Best</b>. I love <b>Technology Enabler Machine Learning Algorithm</b> <b>Reading CS</b> from it.<b>Machine Learing Researcher</b>' print("The original string is : " + str(test_str)) tag = "b" # brack tag in html #...
""" Python does not have the private keyword, unlike some other object oriented languages, but encapsulation can be done. Instead, it relies on the convention: a class variable that should not directly be accessed should be prefixed with an underscore. """ class Robot(object): def __init__(self): self.a = ...
for row in range(6): for col in range(4): if col==1 and row>0 or row==3 and col<3 or col==2 and row==0 or col==3 and row==1: print('*', end = ' ') else: print(' ', end = ' ') print()
for row in range(4): for col in range(4): if col%3==0 and row<3 or row==3 and col>0: print('*', end = ' ') else: print(' ', end = ' ') print()
i=1 j=3 for row in range(5): for col in range(5): if(row==0)or(row==4): print('*',end='') elif (row==i and col==j): print('*', end='') i+=1 j-=1 else: print(end=' ') print()
for row in range(8): for col in range(5): if ((col==0 or col==4) and (row>0 and row<6)) or ((row==0 or row==6)and (col>0 and col<4))or (row==5 and col==1)or (row==7 and col==3): print("*",end="") else: print(end=" ") print()
for row in range(7): for col in range(5): if col==0 or (col==4 and (row==1 or row==2)) or ((row==0 or row==3) and (col>0 and col<4)): print("*",end="") else: print(end=" ") print()
# printfile.py # Prints a file to the screen. def main(): fname = input("Enter filename: ") infile = open(fname,"r") data = infile.read() print(data) main()
# Shape of reverse left angle triangle using fucntions def for_reverse_left_angle_triangle(): """ *'s printed in the shape of Reverse Left Angle Triangle """ for row in range(9): for col in range(9): if col >= row: print('*',end=' ') else: ...
for row in range(6): for col in range(4): if col==2 and row!=1 and row!=5 or row==5 and col==1 or col==0 and row==4 or col==1 and row==2: print('*', end = ' ') else: print(' ', end = ' ') print()
for row in range(7): for col in range(5): if row%3==0 and col>0 and col<4 or col==0 and row in (1,4,5) or col==4 and row>0 : print('*', end = ' ') else: print(' ', end = ' ') print()
# text2numbers.py # A program to convert a textual message into a sequence of # numbers, utilizing the underlying Unicode encoding. def main(): print("This program converts a textual message into a sequence") print("of numbers representing the Unicode encoding of the message.\n") #...
a = raw_input("Enter a word No spaces please:") if a[::-1] == a and len(a)>0: print "yes" else: print "no"
n = int(raw_input("enter:")) z =[] Mlist =[] for x in range(0,n): a = raw_input("enter a:").split(" ") for y in a: z.append(y) a = raw_input("enter a:").split(" ") for y in a: z.append(y) a = raw_input("enter a:").split(" ") for y in a: z.append(y) Mlist = sorted(z) pri...
"""Base classes and helper functions for data handling (dataset, dataloader).""" import abc from typing import Iterator from typing import List from typing import Optional from typing import Union import numpy as np class Dataset(abc.ABC): """ An abstract class representing an `iterable dataset <https://pyt...
def reverter(entrada): return print(entrada[::-1]) ent = str(input('Digite um numero ou texto: ')) reverter(ent)
lista = [] def numero(): for i in range(5): numeros = int(input('Digite o %d° número: ' % (i + 1))) lista.append(numeros) maior = max(lista) return print(f'O maior número é: {maior}') numero()
def salrio(hora, hMes): salario = hora * hMes ir = salario * 0.11 inss = salario * 0.08 sind = salario * 0.05 sLiquido = salario - ir - inss- sind return salario, ir, inss, sind, sLiquido h = float(input('Qual o seu salário hora: ')) m = float(input('Quantas horas trabalhou neste mês: ...
class No: """ Estruturação da arvore, para cada nó dou um dado, e tendo um filho esquerdo um filho direito e um pai """ def __init__(self, dado): self.dado = dado self.filhoesq = None self.filhodir = None self.pai = None def getDado(self): re...
import datetime #classes-------------------------------- class Employee: def __init__(self,name,age,salary,employment_year, **kwargs): self.name = name.capitalize() self.age = age self.salary = int(salary) self.employment_year = int(employment_year) for key, value in kwargs.items(): setattr(self, key...
from collections import namedtuple # added in Python 2.6 # immutable Person = namedtuple('Person',['person_id','name','gender']) if __name__ == '__main__': person_n1 = Person(100,'Guido','M') print(person_n1) # nice __repr__ method print(person_n1.name) # access by name person_id,name,gender = pers...
#the format of each algorithm will be a list of integers def swap(a, i, j): tmp = a[i] a[i] = a[j] a[j] = tmp #end swap def bubble(arg): end = len(arg) - 1 while end > 0: high = arg[0] highpos = 0 for i in range(end): if high < arg[i]: high = arg...
from collections import Counter my_list = [1, 1, 1, 1, 2, 2, 2, 4, 4, 6, 6, 8] print(Counter(my_list)) print(Counter('Python')) # Counter the number of words in this sentence! my_str = "How many times does each word show up in this sentence with a word" print(Counter(my_str.split())) # Returns most common items (m...
def add(num1, num2): try: result = num1 + num2 # Specific error except TypeError: print('Type error occurred!') except OSError: print('An OS error occurred!') except: print('Other exception occurred!') else: print('Add went well!') finally: pri...
def new_decorator(original_func): def wrap_func(): print('Some extra code, before the original function') original_func() print('Some extra code, after the original function') return wrap_func def fun_needs_decorator(): print('I want to be decorated!') # This is what actually ha...
def add(num1, num2): try: result = num1 + num2 # Generic error except: print('Something went wrong!') else: print('Add went well!') print(result) add(1, 2)
# Given a non-empty array N, of non-negative integers. The degree of this array is defined as # the maximum frequency of any one of it's elements. Your task is to find the smallest possible # length of a (contiguous) subarray of N, that has the same degree as N. For example, in the array # [1 2 2 3 1], integer 2 occurs...
age = 24 print("My age is " + str(age) + " years") print("My age is {0} years".format(age)) print( """ January: {2} February: {0} April: {1}""".format(28,30,31) ) print("My age is %d years" % age) #old for i in range(1, 12): print("No. {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i *...
# ages={} # print(type(ages)) # ages["himanshu"]=45 # ages[71]="tkr" # print(ages) # print(ages.keys()) # print(ages.values()) hg='himanshu' k=[print(i) for i in hg if i not in "aeiou"] print(k)
def firstLast(u): return u[0] == 6 or u[-1] == 6 #function to create a new list in ascending order def ascending(list, new_list): min_n = list[0] while len(list) != 0: min_n = list[0] for i in range(len(list)): if list[i] <= min_n: min_n = list[i] new_list.append(min_n) list.remove(min_n...
# File: GuessingGame.py # Description: Create a program that will "guess" a number that the user chooses between 1 and 100 (using binary search) # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 4/11/2016 # Date Last Modi...
# File: PalindromicSum.py # Description: Given a range of numbers, figure out which one has the longest cycle until it becomes a palindromic number # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 2/19/2016 # Date Last...
# File: Goldbach.py # Description: Given a range of even numbers greater than or equal to 4, print out all the unique sum combinations of prime numbers # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 2/25/2016 # Date L...
# File: htmlChecker.py # Description: Create a program that will check if an html file has matching tags throughout # Student's Name: Jonathan Zhang # Student's UT EID: jz5246 # Course Name: CS 313E # Unique Number: 50940 # # Date Created: 9/30/2016 # Date Last Modified: 9/30/2016 #Implement the...
#Time complexity O(n) and space complexity O(1) class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: l=len(nums) # creating product array with same size as nums p=[0]*l p[0]=1 #Traversing from left and finding product for i in range(1,l): ...
#!/usr/bin/env python # Credit to: # # http://www.improbable.com/news/2012/Optimal-seating-chart.pdf # https://github.com/perrygeo/python-simulated-annealing from __future__ import division import math import random from .anneal import Annealer #### Plans and Tables #### # A Plan is a list of Tables. # A Table is ...
import datetime import math import numbers import re import sys PY3 = sys.version_info[0] == 3 if PY3: string_types = str else: string_types = basestring def luhn(s): """ Calculates the Luhn checksum of a string of digits :param s: :type s: str :return: """ sum = 0 for i in ...
# # Compute the top ten most frequently occurring hashtags in the twitter data. # import sys import json from collections import Counter def main(): tweet_file = open(sys.argv[1]) # Load the tweets lines = tweet_file.readlines() results = {} # a list of tweets as dictionaries ...
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) def insert(self): # consider the balancing act # think about powers of 2 pass def ...
# -*- coding: utf-8 -*- """ Created on Sat Apr 10 10:24:22 2021 @author: Sofii """ import random from collections import Counter def tirada_conv(): #Tiro los 5 dados por primera vez tirada1= Counter([random.randint(1,6) for i in range(5)]) #Veo cual es el maximo de veces que se repite algún...
# HackerRank SHerlock and anagrams # find number of anagramic substrings in each string #anagramic -> which are built of exactly same letters (order of letters isnt important) # i. e. kkkk has 10 pairs # k,k,k,k -> six pairs (combinations of 2 letters in diferent positions) # kk,kk -> 2 pairs # kkk,kkk -> 2 pairs impo...
# example of quicksort implemetation in python usin Hoares partition import logging logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO) def partition(arr,l,h,comp): logging.info(f'current pivot {arr[0]}') pivot=arr[l] i=l+1 j=h while i<=j: # repeat process while pointers i and j dont 'pass ...
#python module which provides heapsort with #adjustable comparator function #it relies on max-heap sorting principle #so elements with higher priority are in higher #indexes in sorted iterable from singleton import singleton_decorator @singleton_decorator class parent_child(object): #object that stores comparator fun...
#!/usr/bin/env python3 #import modules import os import sys import shutil import re #store the directory where the files to be renamed are located directory = sys.argv[1] #make a list of the files to be renamed article_list = os.listdir(directory) #create a new directory to save the renamed files new...
#!/usr/bin/python # -*- coding: UTF-8 -*- # 题目:统计 1 到 100 之和。 tmp = 0 for i in range(1,101): tmp += i print 'The sum is %d' % tmp
#!/usr/bin/env python # -*- coding: utf-8 -*- # 题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同, # 十位与千位相同。 # ___________________________________________________________________ # 程序分析:同29例 # ___________________________________________________________________ # 程序源代码: # main( ) # { # long ge,shi,qian,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 题目:一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2 # +3.编程找出1000以内的所有完数。 # ___________________________________________________________________ # 程序源代码: # void main() # { # int a=0,i; # for(i=1;i<1000;i++) # int j,a=0; # for(j=1;j<i;j++) # if((i%j)==0) # a+=j;...
import pygame BLACK = (0,0,0) WHITE = (255,255,255) GREY = (200,200,200) class TextButton(): def __init__(self,size,position,colour=WHITE,rollover_colour=GREY,text="",text_size=14,text_colour=BLACK,font="Arial",action=None): """ size: tuple, (width,height) position: tuple, (x,y of the top left corner of the bu...
# # Programming Assignment 2 # # Problem 2 (15 Points) # # For Dictionary ADT implemented with open hash tables the average number of probes # required to make either a deletion or an insertion is O(1+a). # Find best numerical constants for deletion and insertion. # class Dictionary: 'Dictionary ADT implemented usin...
#!/usr/bin/env python from array import * from list_array import * def makeTrie(): allWords = [] f = open("AliceInWonderland.txt","r"); lines = f.readlines(); for i in lines: thisline = i.split(" "); for j in thisline: if j!="": allWords.append(j.strip()) x=ListArray() for word in allWords: for ...
#!/usr/bin/python3 """Module and function must be documented""" def island_perimeter(grid): """returns perimeter""" if len(grid) == 0 or grid is None: return 0 height = len(grid) lenght = len(grid[0]) perimeter = 0 for lists in grid: for items in lists: if type(i...
print('''Day3 List \n \n ''') example = [1, 2, 3] print(example) xample1 = ['cat', 'bat', 'rat', 'elephant'] print(example1) example2 = ['hello', 3.4452, True, None, 42] print(example2) spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0]) print(spam[1]) print(spam[2]) print(spam[3]) print('Hello ' + spam[0]) ...
#! ============================================================================== #! NEW SECTION - Lab 1 #! ============================================================================== english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"]...
#!/usr/bin/python __author__ = 'pythonspot.com' l = [ "Drake", "Derp", "Derek", "Dominique" ] print(l) # prints all elements print(l[0]) # print first element print(l[1]) # prints second element
# A program that plots 3 different lines on one line plot. # Each line has similar x values however they have a different equation to solve for y value of each line. # Author: Ryan Cox # Importing numpy and matplotlib. import numpy as np import matplotlib.pyplot as plt minRange = 0 # Defining the minimum paramet...
import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, MaxAbsScaler, MinMaxScaler def stats(raw_data): """Computes statistics useful for reverse scaling of predictions. :param raw_data: pandas.DataFrame - original DataFrame :return: pandas.DataFrame - DataFrame of co...
def list_recursion(number): numbers = [] if number > 0: numbers.append(number) return numbers + list_recursion(number - 1) else: return [] print(list_recursion(5)) list_recursion(5) [5] + list_recursion(4) [5] + ([4] + list_recursion(3)) [5] + ([4] + ([3] + list_recursion(2))) ...
import argparse import cProfile, pstats, sys import logging from typing import List logging.basicConfig() logging.root.setLevel(logging.DEBUG) """ leetcode 877. stone game https://leetcode.com/problems/stone-game/ https://github.com/labuladong/fucking-algorithm/blob/master/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E7%B3%B...
""" YZ_IMPORT try to understand python compiler! """ import os import re def main(): """ MAIN tests module ex.1 >>> path = './file01.txt' >>> tree = Tree(path) >>> print(tree) >>> print(tree.is_valid(path)) def('a') call('a') { call('a') def('b') } call('...
import sqlite3 class UserModel: #class for initiating a user, finding the user and retrieving it (sign in) def __init__(self, _id, username, password): #id because id is a python keyword, but self.id is okay self.id = _id self.username = username self.password = password @classmethod #t...
import math def circumference(r): """Calculate the surface of a circle of radius r This does not compute the surface though :D""" return 2*math.pi*r def area(r): """ Function calculating area of circle of radius r """ return math.pi*r**2 def area_triangle(base, height): """ Calcul...
import sys def get_score(array): ans = 0 for k in array: if k%2 == 0: ans+=2 else: ans+=1 return ans def get_numbers(array): vowels = ( 'a', 'e', 'i', 'o', 'u', 'y' ) counts = [] temp = 0 for i in...
def percentage(arr, n): x=sum(arr) y=n*100 return "%.12f" %(x*100/y) def main(): n=int(input()) d=list(map(int,input().split())) print(percentage(d,n)) if __name__ == '__main__': main()
def math(number_x, number_y): s='' for i in range(len(number_x)): if int(number_x[i])+int(number_y[i])==2: s+='0' elif int(number_x[i])+int(number_y[i])==1: s+='1' else: s+='0' return s def main(): x=input() y=input() ...
import sys def get_lowest(bird_dict, ans): lowest_birds = [] for bird in bird_dict: if bird_dict[bird] == ans: lowest_birds.append(bird) return min(lowest_birds) def get_count(arr): counts = {} ans = 0 for birds in arr: counts[birds] = counts.get(bir...
n=int(input("enter number of terms required")) n1=0 n2=1 c=0 if n<0: print("enter positive integers") elif n==1: print("0") else : print("the series is:") while c<n: print(n1) temp=n1+n2 n1=n2 n2=temp c+=1
i= int(input("enter a number")) num=(i+(10*i+i)+(110*i+i)) print(num)
#函数 #print() #a = 2.23232323 #print(round(a,3)) #2.23 ''' 函数内部执行了return , 后面的代码不会执行 import sys sys.setrecursionlimit(29) def add(x, y): print(x + y) result = x-y return result a = add(2,3) print(a) ''' ''' 提高阅读性,接收函数结果方式,用名称代替damage[0]使接受的参数简单明了 def damage(skill1, skill2): damage1 = skill1+skill2 ...
# 문제4 # 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 # 출력해보세요. 1부터 99까지만 실행하세요. for i in range(1, 100): if (str(i).find('3') != -1 or str(i).find('6') != -1 or str(i).find('9') != -1): print(i, '짝')
#!/bin/python3 # https://www.hackerrank.com/challenges/2d-array/problem import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): hgSum = -63 for x in range (len(arr) - 2): for y in range(len(arr) -2): num = arr[x][y] + ar...
from itertools import islice def evolution(island): ''' Infinite generator for evolution of some population. This generator yields population: population - tuple together containing tuples/individuals population_0 = create() population_1 = evolve(population_0, info_0) . . popu...
import random import functools as fcn def get_number_permutation_generator(start, end): ''' Closure around elements (start, start + 1, ..., end - 1) ''' return get_random_permutation_generator(range(start, end)) def get_random_permutation_generator(elements): ''' Generates closure around elements = ...