text
stringlengths
37
1.41M
def demo01(): print("hello python") print("我是汉字") f = open('./demo01.txt', 'rb') for line in f: print(line.decode('utf-8')) def fibonacci(): a, b = 0, 1 while b < 1000: print(b, end=',') a, b = b, a+b if __name__ == "__main__": demo01() fibonacci()
# 9-3 Users: Make a class called User") class User: def __init__(self, first_name, last_name, occupation, address, phone): self.first_name = first_name self.last_name = last_name self.occupation = occupation self.address = address self.phone = phone def describe_user(...
# 03/11/2021 cars = ['bugatti', 'ferrari', 'tesla', 'lexus'] # making numerical list # SYNTEX: range ([start], stop, [step]) for num in range(4): print(num) nums = range(4) nums2 = list(range(4)) print(nums) print(nums2) for num in nums2: print(f"number: {num}") print() print('range with start and stop') fo...
# ind1 ind2 favorite_places = {'Alex': 'Spain', 'Jen': ['Arizona', 'Florida'], 'Bob': 'Thailand', 'Anna': 'India'} for name, details in favorite_places.items(): if name == 'Jen': print(f"{name}'s favorite places are" f"\n {favorite_places['Jen']...
print("++++++++++++++++++++++++++++7.1++++++++++++++++") ''' Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.''' number = input("What kind of rental car they would like?: ") print(f"Let me see if i can find you...
from turtle import Turtle, Screen import random # Screen setup screen = Screen() screen.setup(width=500, height=400) # Make bet user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race?") # Create turtles colors = ["red", "blue", "pink", "orange"] coordina...
""" -------------------------------------------------------------------------- PROJECT EULER - PROBLEM 96 Copyright (c) Eduardo Ocampo, All Rights Reserved ...
inp = input("Введите фамилию, имя и отчество").split() print("ФИО:"+inp[2], inp[0][0]+"."+inp[1][0]+".")
# ===================================== # --*-- coding: utf-8 --*-- # @Author : TRHX # @Blog : www.itrhx.com # @CSDN : itrhx.blog.csdn.net # @FileName: 【11】Pawn Brotherhood.py # ===================================== def safe_pawns(pawns: set) -> int: num = 0 for i in pawns: left_paw...
# ============================================ # --*-- coding: utf-8 --*-- # @Author : TRHX # @Blog : www.itrhx.com # @CSDN : itrhx.blog.csdn.net # @FileName: 【15】Date and Time Converter.py # ============================================ def date_time(time: str) -> str: month = ['January', 'Februa...
def alphabet_position2(text): text = text.lower() alph = [] text_pos = "" for x in range(97, 123): alph.append(chr(x)) for char in text: if char.isalpha(): text_pos += str(alph.index(char)+1) + " " return text_pos def alphabet_position(text): x = ' '.join...
def get_middle(s): i = len(s) // 2 if len(s) % 2 == 0: return s[i-1]+s[i] return s[i] def get_middle(s): return s[len(s)//2 - 1:len(s)//2 + 1] if len(s) % 2 == 0 else s[len(s) // 2] # assert get_middle("test") == "es" # assert get_middle("testing") == "t" # assert get_middle("A") == "A" def ...
# Hash Generator def generate_hashtag(s): s = s.strip() result = '' if s != '' and len(s) < 140: words = s.strip().split(' ') for word in words: if word != '': word = word.lower() word = word[0].upper() + word[1:] result += word return '#' + result return False def generate_hashtag(s): p...
from tkinter import * from tkinter import * from PIL import Image, ImageTk import random window = Tk() window.title("ball") text = Label(window, text = "shake the ball!", font= ("Helvetica", 25)) text.grid(column = 0, row = 0) window.geometry('220x300') # the switching function goes here ball = PhotoImage(file = "...
from random import randint #引入随机整数函数 arr=[] #初始化数组 for i in range(20): arr.append(randint(1,100)) #读入数组 print('排序前的列表为:{}'.format(arr)) arr.sort() #排序 print('排序后的列表为:{}'.format(arr))
# Pokemon class class Pokemon: def __init__(self, name, type, level = 5): self.name = name self.level = level self.health = level * 5 self.max_health = level * 5 self.type = type self.is_knocked_out = False def lose_health(self, health_lost): ...
#!/usr/bin/python2.7 #-*- coding: utf-8 -*- message = "hello python" print(message) print("hello everyone.") #将首字母大写 print(message.title()) #将字符串全部大写 favorite_language=' python ' favorite_language.rstrip() print(favorite_language) print(favorite_language.strip()) print(favorite_language.lstrip()+favorite_language.str...
def matrix_transpose(A): result = [[0 for i in range(len(A))] for j in range(len(A[0]))] for i in range(len(A)): for j in range(len(A[0])): result[j][i] = A[i][j] return result print(matrix_transpose(A))
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None #Insert a node into BST def insert(self, key): if self.root == None: self.root = Node(key) else: ...
def matrix_multiplication(A, B): Arow, Acol = len(A), len(A[0]) Brow, Bcol = len(B), len(B[0]) #print(Arow, Acol, Brow, Bcol) def multiply(x, y): result = [[0 for i in range(y)] for j in range(x)] #print(result) for i in range(len(A)): for j in range(len(B[0])): ...
def mergeSort(arr): if len(arr) < 2: return arr else: a = arr[:len(arr)//2] b = arr[len(arr)//2:] a = mergeSort(a) b = mergeSort(b) c = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: c.append(...
import ast lst = input() lst = ast.literal_eval(lst) def selection_sort(lst): for i in range(len(lst)): minimum = i for j in range(i, len(lst)): if lst[j] < lst[minimum]: minimum = j lst[i], lst[minimum] = lst[minimum], lst[i] print(lst) selection_sort...
import ast lst = input() lst = ast.literal_eval(lst) column = int(input()) def sort_matrix_by_columnNumber(lst, column): for i in range(len(lst)): minimum = i for j in range(i, len(lst)): if lst[j][column] < lst[minimum][column]: minimum = j lst[i], lst[minimum]...
import argparse import sys class Node(object): def __init__(self,data=None,next=None): self.data = data self.next = next def ParseArgs(): #desc = 'usage:' parser = argparse.ArgumentParser() parser.add_argument('-i',action='store',dest='list',help='The input list') parser.add_argu...
''' A program that returns any two numbers from a list which adds up to a target. @params arr: a list @params target_value: an integer @returns: a boolean. True returns a tuple with result. ''' from itertools import permutations def find_sum(arr, target_value): '''Using permutations. Loops through the list only o...
#!/usr/bin/python import math class StatisticsAccumulator: """Accepts one value at a time and keeps track of the associated statistics""" def __init__(self): self.__welford_mean__ = 0.0 self.__welford_i_var__ = 0.0 self.i = 0 # Maintain the statistics for each estimate ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 10 14:05:16 2016 @author: LeviZ """ # implementation of card game - Memory import simplegui import random # helper function to initialize globals def new_game(): global state, turns, cards, exposed, click_1, right_guess state = 0 turns = 0 ...
class Car: def __init__(self, speed=None, color='', name='', is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print(f'{self.color} машина марки {self.name} поехала') def stop(self): print(f'{se...
def f(x): return x * x * x + 3 * x - 5 def RegulaFalsi(a, b, ACCURACY): x1 = a - f(a) * (b - a) / (f(b) - f(a)) if abs(f(x1)) < ACCURACY: return x1 if f(x1) * f(a) < 0: x0 = a else: x0 = b while abs(x1 - x0) > ACCURACY: x1 = x1 - f(x1) * (x0 - x1) /...
# -*- coding: utf-8 -*- # This script describes how truncated and fully compounded fiscal multiplier # scenarios can be consider to be equivalent. It is described in the accompanying # iPython Notebook and at # # http://misunderheard.org/monetary_economics/2017/04/10/modelling_the_fiscal_multiplier/ # # %% import m...
#РЕАЛИЗАЦИИ МАССИВОВ #В Python существует 2 реализации массивов: списки и кортежи #Списки --- list() my_list = [10, 20, 30, 40, 5, -1, 20] print(my_list[0], my_list[1]) print("Last element of my_list is: ", my_list[6]) print("Last element of my_list is: ", my_list[-1]) print(my_list[-3]) print(my_list[-0]) #Empty lis...
def my_function(a, b): result = a ** 2 + b ** 3 / (a * b) return result q = my_function(4,10) w = my_function(10,2000) e = my_function(1,1) print(q + w + e) # y(x,z) = 5*x + 3*z # y(2,1) = 5*2 + 3*1 = 13 # y(7,1) = 5*7 + 3*1 = 38
def add(a :int, b :int) -> int: return a + b def sub(a :int, b :int) -> int: return a - b def mult(a :int, b :int) -> int: return a * b def div(a:int, b:int) -> float: if ( b != 0): return a / b else: return 0 a = 10
def add(a :int, b :int) -> int: return a + b + 1 def sub(a :int, b :int) -> int: return a - b def mult(a :int, b :int) -> int: return a * b def div(a:int, b:int) -> float: if ( b != 0): return a / b else: return 0 a = 109 print("Hi from another module!") ...
my_list = [1,2,3,4,5,6,7,8,9,10] my_tup = (1,2,3,4,5,6,7,8,9,10) print(type(my_list),my_list.__sizeof__(), my_list ) print(type(my_tup),my_tup.__sizeof__(), my_tup ) print(my_tup[0:-1:3])
#猜单词游戏,在实际应用中把输入的单词从文件读取或者在源码中修改直接写好。 #定义函数 def guessWord(word): print("play the game:") wrong=0 getWords=list(word) bind=["_"]*len(word) win= False gragh=["————————————————————", "| |", "| |", "| o", "| |", "| /|\ ", "| ...
import pygame as pg pg.init() # Iniciar pygame pantalla = pg.display.set_mode((800, 600)) # Crear pantalla # Bucle principal game_over = False while not game_over: # = "Mientras game_over sea falso" ó "while True" , se mete en el bucle. Para salir, game_over a True: eventos = pg.event.get() # Procesar eventos. ...
# INHERITANCE class Animal(): def __init__(self): print('ANIMAL CREATED') def whoAmI(self): print('ANIMAL') def eat(self): print('EATING') mya = Animal() mya.whoAmI() mya.eat() class Dog(Animal): def __init__(self): print('DOG CREATED') def bark(self): ...
# prompt: # A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well. ...
from random import shuffle SUITE = 'H D S C'.split() RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() class Deck(): ''' This is the Deck class. This object will create a deck of cards to initiate play. You can then use this Deck List of cards to split in half and give to the players. It will use SUITE and...
""" Demo of the histogram (hist) function with a few features. In addition to the basic histogram, this demo shows a few optional features: * Setting the number of data bins * The ``normed`` flag, which normalizes bin heights so that the integral of the histogram is 1. The resulting histogram is a proba...
from typing import List n = 4 def small_square(tu, line_list): counter = 0 if [tu[0], tu[1]] in line_list: counter += 1 elif [tu[0], tu[0] + n] in line_list: counter += 1 elif [tu[1], tu[1] + n] in line_list: counter += 1 elif [tu[0] + n, tu[1] + n] in line_list: counter +...
from linkedlist import * node1 = Node(3) node2 = Node(4) print(node1.data) print(node2.data) node1.data = 5 print (node1.data) node1.nextNode = node2 print(node1.nextNode.data) print("\nLL TEST\n") myLL = LinkedList() myLL.add2Front(4) myLL.add2Front(3) myLL.add2Back(6) myLL.addinOrder(5) print(myLL.isIn(5)) print(my...
# Erich Eden # SY301 # Dr. Mayberry # Lab 2 class Node: def __init__(self, data): self.data = data self.nextNode = None class LinkedList: def __init__(self): self.head = None self.tail = None def printAll(self): print ("list contains: \n") current ...
# Assigment: CoinFlips # Name: Akhmadjon Kurbanov import random # by flipping the coin get H (heads) or T (tails) def flipCoin(): return random.choice(['T','H']) # Return true of flips result has at least two heads, otherwise false def gotMatch(n): counter = 0 for i in range(n): if flipCoin() == ...
# Assigment: CoinFlips pt2 # Name: Akhmadjon Kurbanov import random import matplotlib.pyplot as plt # by flipping the coin get H (heads) or T (tails) def flipCoin(): return random.choice(['T','H']) # Return true of flips result has at least two heads, otherwise false def gotMatch(n, k): result = '' for i...
#!/usr/bin/env python #importing the library required, topics and mathematical functions import rospy #the main library for ROS functions in python from geometry_msgs.msg import Twist #the (node_turtle_revolve) node will publish velocities to this Twist from turtlesim.msg import Pose #the (node_turtle_...
#Arrays in python are called lists x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in x: print(i)
# # This is my work regarding a problem in Chapter 2 of Spraul's "Think Like a Programmer": # # Write a program that takes an identification number of arbitrary length and # determines whether the number is valid under the Luhn formula. The program must # process each character before reading the next one. # ...
import math class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ max = math.pow(2,31) if x >= 0: flag = 1 else: flag = -1 _ = str(abs(x)) reverse = _[::-1] result = int(reverse) if flag == -1: ...
n = int(input("plase enter n: ")) m = int(input("enter m: ")) for i in range(n): for j in range(m): if (i+j) %2==0: print('*', end=" ") else: print('#', end=" ") print()
"""CPU functionality.""" import time import sys class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.reg = [0] * 8 self.pc = 0 self.reg_pc = 0 self.sp = 6 self.flag = [0] * 8 def ram_read(self, ...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: node = ListNode(0) dummy = node while...
""" Valid Starting City Imagine you have a set of cities that are laid out in a circle, connected by a circular road that runs clockwise. Each city has a gas station that provides gallons of fuel, and each city is some distance away from the next city. You have a car that can drive some number of mil...
""" This module colects the weather information that will be used in the main module """ import requests import json def get_weather(): """ This function colects and process al the data and returns a string with the content of the weather notifications of the main module """ #Read configuration file and...
import requests from bs4 import BeautifulSoup import csv from jumia_db import * ##To crawl in disguise headers = requests.utils.default_headers() headers.update( { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" } ) ## F...
def getPath(start, hierarchy): if start in hierarchy: l = getPath(hierarchy[start], hierarchy) l.append(start) return l else: return [] def travelUpTree(obj, hierarchy): if obj in hierarchy: #print("found parent for",obj,":",hierarchy[obj]) re...
RIGHT = (0,1) DOWN = (1,0) UP = (-1,0) LEFT = (0,-1) DIRECTIONS = [UP,RIGHT,DOWN,LEFT] TURNS = [-1, 0, 1] LEFTTURN = "\\" LEFTTURNS = {0:3,1:2,2:1,3:0} RIGHTTURN = "/" RIGHTTURNS = {0:1,1:0,2:3,3:2} INTERSECTION = "+" area = [] #cart : y,x,direction,nextTurn carts = [] def printArea(area, carts): areaC...
with open('data.txt') as file: positions = [int(x) for x in file.readline().split(',')] def findFuelCost(positions, target): cost = 0 for x in positions: cost += sum(range(abs(x-target)+1)) return cost def findMinimumFuelCost(positions, guess): neighborhood = {guess:findFuelCost(positi...
from collections import namedtuple targetX = [85,145] targetY = [-163,-108] #targetX = [20,30] #targetY = [-5,-1] targetArea = set((x,y) for x in range(targetX[0],targetX[1]+1) for y in range(targetY[0],targetY[1]+1)) Velocity = namedtuple('Velocity',['x','y']) def simulate(x,y, vel, path): #print(x,y,vel) ...
from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bets", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] def create_turtle(num)...
from builders import * def numberToWords(number): try: number = int(number) if number < 0: return 'Expresión inválida' except: return 'Expresión inválida' if number == 0: return 'cero' if number >= 1 and number < 1000: return hundredBuilder(number) if number >= 1000 and number < 1000000: return...
# # The Vector class represents a position, a force or a direction. # class Vector: def __init__(self, x, y): ### Test if arguments are of correct type if not isinstance(x, int) and not isinstance(x, float) and x != None: raise TypeError(f"unsupported type(s) for Vector.x: '{type(x)}'")...
print('Введите число') a=input() summa=0 m=0 while a !="": a=int(a) summa=summa+a m+=1 print(summa, a) print('Введите число') a=input() if a =="": average=summa/m print('Среднее арифметическое=', average)
# Group Anagrams # Given an array of strings, group anagrams together. # Example: # Input: ["eat", "tea", "tan", "ate", "nat", "bat"], # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] # Note: # All inputs will be in lowercase. # The order of your output does not matter. cla...
def is_number_correct(number): # Votre code ici result = number >= 10 and number <= 20 diff = 0 if result == False: if number < 10: diff = 10 - number elif number > 20: diff = 20 - number return (result, diff) def run(): assert is_number_correct(0) == (Fa...
def NEWTON_METHOD(number): number=float(number) ε=10**-10 num_old=number num_new=number/2 while abs(1-num_old/num_new)>ε: num_old=num_new num_new=(num_old+number/num_old)/2 return num_new
from sympy import * from tkinter_math.calculation.common.STR import STR x = Symbol('x') def taylor(formula,dimension,center): try: f=sympify(formula) center=float(center) A=f.subs(x,center) for number in range(1,int(dimension)+1,1): f=diff(f) D=f.subs(x,cen...
import tkinter from tkinter_math.calculation import * def sub_window_7(): def sub_window_7_1(): def calc_7_1(): try: a=int(txt_7_1_1.get()) root_7_1.destroy() sub_window_7_2(a) except: lbl_7_1_2=tkinter.Label(root_7_1,t...
# Keep these 2 lines text_to_translate = input("Text to translate: ") VOWELS = "aeiouyAEIOUY" # ...add your code here text_list = text_to_translate.split() translation = "" for word in text_list: if word[0] in VOWELS: word = word + "yay" translation = translation + word + " " elif word[0] not in...
a = bool(int(input("A"))) b = bool(int(input("B"))) c = bool(int(input("C"))) d = int((a and not b)or(not b and c)) # compute d print("D is", d)
# is_prime function definition goes here def is_prime(number): for x in range(2, number): if number % x == 0: return False else: pass if number % number == 0 and number % 1 == 0: return True max_num = int(input("Input an integer greater than 1: ")) for x...
#Algorithm #1 make loop that loops n time #2 make variables and get the sum of them n = int(input("Enter the length of the sequence: ")) # Do not change this line count = 0 sequence1 = 1 sequence2 = 2 sequence3 = 3 while count < n: if sequence1 < sequence2: print(sequence1) sequence1 = sequence3 +...
secs_str = input("Input seconds: ") # do not change this line hours = int(secs_str) // 3600 minutes = (int(secs_str) % 3600) // 60 seconds = (int(secs_str) % 3600) % 60 print(hours,":",minutes,":",seconds) # do not change this line
num = int(input("Input a number: ")) # Do not change this line # Fill in the missing code below print("Negative") # Do not change this line print("Positive") # Do not change this line print("Zero") # Do not change this line
''' ANKIT KHANDELWAL 15863 Exercise 4 Square Wave ''' from math import floor import matplotlib.pyplot as plt import numpy as np def f(t): if floor(2 * t) % 2 == 0: return 1 else: return -1 xv = np.linspace(0, 1, 1000) values = [] for i in range(1000): values.append(f(xv[i])) plt.plot(...
''' ANKIT KHANDELWAL 15863 Exercise 9 ''' import math prime = [2] for n in range(3, 10000): low_i = int(math.sqrt(n)) for i in prime: if n % i == 0: break if i > low_i: prime.append(n) break print('Prime numbers upto 10000 are:') print(prime)
''' ANKIT KHANDELWAL 15863 Exercise 1 ''' import math def altitude(T): R_Earth = 6378100 g_Earth = 9.803 R_sat = ((T * R_Earth * math.sqrt(g_Earth)) / 2 / math.pi) ** (2 / 3) return R_sat - R_Earth # 1a T = int(input('Enter period of rotation in seconds: ')) print('The altitude of satellite above ...
''' ANKIT KHANDELWAL 15863 Exercise 2 ''' import math def polar(x, y): r = math.sqrt(x ** 2 + y ** 2) if x == 0: if y > 0: theta_degrees = 90 elif y == 0: theta_degrees = 0 else: theta_degrees = 270 else: theta = math.atan(abs(y / x)) ...
""" Ankit Khandelwal 15863 Exercise 2 """ from math import sqrt a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) [x1, x2] = [(-b + sqrt(b ** 2 - 4 * a * c)) / 2 / a, (-b - sqrt(b ** 2 - 4 * a * c)) / 2 / a] print('Solutions of ', a, 'x^2 +', b, 'x +', c, '= 0 is by first for...
import statistics import json class TestResultContainer: """ This is a class for holding test results and calculating statistics on the values Attributes: results (dictionaty): holds input values with key as type of input and value as list of values avgMeans (dictionary): holds calculated mean statstic fo...
import string alphabet = string.ascii_letters def is_pangram(phrase): import pdb; pdb.set_trace() words = phrase.split() count = 0 for word in words: letters = word.split() count += letters.count() return count >= 26
def feets_to_meters(a): return (a*0.3048) def meters_to_feet(b): return(b/0.3048) c=50 d=10 print("{0} feets are {1} meters.".format(c,feets_to_meters(c))) print("{0} meters are {1} feets.".format(d,meters_to_feet(d)))
#from: https://realpython.com/python3-object-oriented-programming/ import dog_father dog = dog_father.Dog # Instantiate the Dog ob# Class Attribute philo = dog("Philo", 15) mikey = dog("Mikey", 16) # Access the instance attributes print("{} is {} and {} is {}.".format( philo.name, philo.age, mikey.name, mikey...
""" Algorithm to categorize elements into equivalence classes http://code.activestate.com/recipes/499354-equivalence-partition/ """ def equivalence_partition( iterable, relation, verbose=False ): """ Partitions a set of objects into equivalence classes\n", Args:\n", iterable: collection of objects t...
def arithmetic_arranger(problems: list, result=False): if len(problems) > 5: return "Error: Too many problems." line1 = "" line2 = "" line3 = "" line4 = "" for idx, problem in enumerate(problems): first, op, second = problem.split() if op not in ["+", "-"]: ...
############ # Pecoraro Cyril # Design and Analysis of Algorithms - Week 1 # Merge-sort algorithm # August 2016 ############ from Week1.functions import merge_sort import numpy as np input_Array = np.loadtxt("test1.txt", dtype="int") n = len(input_Array) #Largest possible number of inversion max_inversion = n*(n-1)...
#!/bin/env python2.7 # !Important! # To execute the program, in your commandline prompt, type in the following command: # python clockAngles.py <test file name> > ClockAngles.txt # replace <test file name> with your own file name import sys times = [] class Time: def __init__(self, time_str): times_list = time_str...
''' A program to test hash function variations ''' from collections import Counter import statistics as stats from Hash import * def testHash(radix, modulus, fName): print() print("Using radix " + str(radix) + " and modulus " + str(modulus) + ".") print() print(" Input | hash value") ...
### 汉诺塔问题 # def hannoi(n,from_tower,mid_tower,to_tower): # if n==1: # print('Move {} to {}'.format(from_tower,to_tower)) # else: # hannoi(n-1,from_tower,to_tower,mid_tower) # print('Move {} to {}'.format(from_tower,to_tower)) # hannoi(n-1,mid_tower,from_tower,to_tower) # # try : ...
""" Global function is used when we want to make the variable outside the function to behave as global variable which is declared inside function.It can also change the value of global variable. Global keyword is used when we want global variable which is present inside the function.(function body) Date-2nd Nov 2020 ""...
""" Class is a blue print(design) of an object(thing). To define attributes(variables),we need __init__method. To define behaviours,we need methods(function). Date-10th Nov 2020 """ class Computer: def __init__(self,a,b): self.a=3 self.b=b def config(self): print("config is",self.a,self....
""" 4 types of argument-1.Position 2.Default 3.Keyword 4.Varibale length 5.Keyword variable length Date-1st Nov 2020 """ #position def sum(a,b): return a+b print(sum(5,6))#11 #default def info(name,age=16): print(name,age)#Yash 16 info("Yash") #or info("yash",age=20) #Keyword def infor(name,age): age-=2 ...
# A turtle draws a fractal that is a circle with squares # derived from Programming Foundations with Python on Udacity.com import turtle import webbrowser def draw_square(some_turtle): for i in range(0, 4): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor...
def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y): return x/y if __name__== "__main__": print(add(1,2)) print(sub(400, 1000)) print(mul(100, 2300)) print(div(8,2))
mydict = { } mydict['홍길동'] = '010-111-1111' mydict['이순신'] = '010-222-2222' print(mydict) del mydict['이순신'] print(mydict) #딕셔너리에 포함된 값들은 keys, values, items 함수들을 사용하여 리스트의 형태로 얻을 수 있다.' mydict2 = {'kim':'111', 'park':'2222', 'lee':'3333'} for k in mydict2.keys() : v = mydict2[k] print("{0:10s} {1:10s}".forma...
dictionary = { "name": "7D 건조 망고", "type": "당절임", "ingradient": ["망고", "설탕", "메타중아황산나트륨", "치자황색소"], "origin": "필리핀" } print("name: ", dictionary["name"]) print("type: ", dictionary["type"]) print("ingradient: ", dictionary["ingradient"]) print("origin: ", dictionary["origin"]) print() di...
# 리스트와 튜플의 차이점은 "자료가 변경될 수 있는가? " # 튜플은 한번 생성되면 그 항목들이 추가되거나 삭제될 수 없다. # 튜플은 리스트보다 빠른 사용속도를 지원 mylist = [10,20,30,40,50] mytuple = (10,20,30,40,50) print(mylist) print(mytuple) len(mytuple) 30 in mytuple mytuple[0] for x in mytuple : print(x) mylist2 = list(mytuple) mylist2.append(60) mylist2.remove(20) n...
guess = input("Guess a number between 1 and 10: ") guess = int(guess) if guess == 5: print("Your guess was correct.") else: print("Your guess was incorrect")
#Que1-->Write a python script to create a databse of students named Students. import pymongo client=pymongo.MongoClient() database=client['Studentdb'] print("database created") collection=database['studenttbl'] print("table created") print() #Que2-->Take students name and marks(between 0-100) as input from user 10 tim...