text
stringlengths
37
1.41M
# Создать класс File: # -он должен принимать любое количество уникальных имен файлов но не меньше 2-х # -создать метод который будет проверять существуют ли эти файлы, если нет то создать их # -создать метод который принимает текст и выводит список файлов (записать текст в выбранный файл) # -создать метод который вывод...
import re def tokenize_url_parameters(url): """ A function that tokenize parameters from the provided url. >>> tokenize_url_parameters("/test/{object_id}") [('{object_id}', 'object_id')] >>> tokenize_url_parameters("/tests/") [] """ pattern = re.compile("(\{([a-z-_]+)\})") return ...
#!/usr/bin/env python import sys def main(): edges = set() for line in sys.stdin: line = line[:-1] if not line: continue cols = map(int, line.split('\t')) from_ = cols[0] for to in cols[1:]: if from_ < to: edge = (from_, to) ...
from numpy import * # 数据集大小 m = 20 # X0 = ones((m,1)) # 生成一个m行一列的向量,全是1 print('x0:',X0) X1 = arange(1,m+1).reshape(m,1) print('x1:',X1) X = hstack((X0,X1)) # 按照列堆叠形成数组,样本数据 print('X:',X) # Y = array([ 3,4,5,5,2,5,7,8,11,8,12, 11,13,13,16,17,18,17,19,21 ]).reshape(m,1) print('Y:',Y) # 学习率 alpha = 0.01 # 定义代价...
import re from typing import List def string_to_caps_words(in_string: str) -> List[str]: """ Convert string to list of words in caps :param in_string: input string :return: word list (all caps) >>> string_to_caps_words("Svool, R'n z hgirmt!") ['SVOOL', ',', "R'N", 'Z', 'HGIRMT', '!'] """ ...
""" Python program to multiplies all the items in a list. """ # creating a sample list with random numbers list = [2,3,4,5,6] value = 1 # iterating through the loop and multiplying all the elements in the list for i in range(len(list)): value = value * list[i] # printing the final value print "multiplies of all i...
""" Python program to remove duplicates from a list. """ # declaring a sample list with repeated values list1 = [1,2,3,4,5,1,2,3,4,5] # removing duplicates by converting it into a set list1 = set(list1) # converting back to list after removing duplicates list1 = list(list1) print list1
""" program to find greater number between three number. """ # reading 3 numbers from the users num1 = int(raw_input("Enter first number : ")) num2 = int(raw_input("Enter first number : ")) num3 = int(raw_input("Enter first number : ")) if num1 > num2 and num1 > num3: print str(num1) + " is the greatest number of ...
class parent: employees = 0 def __init__(self,name,salary): self.name = name self.salary = salary self.email = name + "@gmail.com" parent.employees = parent.employees + 1 def empcount(self): print " emp name : ",self.name print " emp salary : ",self.salar...
fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) count = 0 for s in fh: if s.startswith('From'): sto=s.split() print(sto[1]) count=count+1 else: continue print ('There were',count,'lines int the file with From as the first word')
import sys a = int(input()) b = int(input()) print("{:d} \n{:d} \n{:d}".format((a + b), (a - b), (a * b)))
#!/usr/bin/env python class Vehicle : # constructor method definition to initialize # the variables # def __init__(self) : self.manufacturer = "" self.model = "" self.width = -1 self.length = -1 self.data = [] # store entire data from file self.temp = []...
"""Даны три стержня A, B, C, на один из которых нанизаны N колец, причём кольца отличаются размером и лежат меньшее на большем. Задача состоит в том, чтобы перенести пирамиду из N колец за наименьшее число ходов на другой стержень. За один раз разрешается переносить только одно кольцо, причём нельзя класть большее ко...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ num1 = num2 =...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if (n == 1): return 1 if (n == 2): return 2 else: first = 1 second = 2 while n > 2: third = first + s...
class Position(object): def __init__(self,x=0,y=0,z=0): self.x=x self.y=y self.z=z def __str__(self): return str((self.x,self.y,self.z)) def magnitude(self): return (self.x**2+self.y**2+self.z**2)**.5 def __add__(self,p): return Position(self.x+p.x, self.y...
#1. Write a Python program to create a tuple. # x =() # print(x) # fruits = ("apple", "banana", "cherry") # print(fruits[1]) #2. Write a Python program to create a tuple with different data types. # diffdatatype = (1,'ram', 50.5,True) # print(diffdatatype) #3. Write a Python program to create a tuple with...
''' #################### EN605.613 - Introduction to Robotics Assignment 2 Coordinate Transforms ------- For this assignment you must implement the all the functions in this file ================================== Copyright 2020, The Johns Hopkins University Applied Physics Laboratory L...
''' #################### EN605.613 - Introduction to Robotics Assignment 4 Kinematic Chains ------- For this assignment you must implement the following functions 1. axis_angle_rot_matrix 2. hr_matrix 3. inverse_hr_matrix 4. KinematicChain.pose 5. KinematicChain.jacobian ===...
import socket DEFAULT_IP = "192.168.1.52" DEFAULT_PORT = 1235 class ServerConnector(object): """ Represents server side of connection between Pi's. """ def __init__(self): self.s = None self.conn = None def __enter__(self): return self def __exit__(self, exc_type...
# Python 3.4 - sub-word search utility # See accompanying LICENSE and README.md files for more info import re from collections import defaultdict import sys import gc word_dict = defaultdict(set) def load_words(file): global word_dict f = open(file) for line in f: line = line.strip() matc...
date_1={'Как дела?': 'Хорошо', 'Что делаешь?': 'Программирую'} while True: question=input('Задайте свой вопрос: ') if question in date_1: print(date_1.get(question)) break else: print('Такого вопроса нет')
import requests import json # DOCUMENTATION : This is a basic program that manipulates the API according to user provided input. #------------------------------------------------------------------------------------------------------ # Since listing notes is so ubiquitously used - we define it as a separate function ...
from DiceRoll import diceRoll, EnemydiceRoll weapondmg = 5 enemyweapondmg = 3 charhealth = 15 enemyhealth = 15 enemyAC = 11 charAC = 10 def characterdmg(): enemyhealth = 15 if diceRoll.d20(diceRoll) >= enemyAC: enemyhealth -= weapondmg print(f'The Enemies health is now {enemyhealth}!') el...
import pygame class Ship(): def __init__(self, ai_settings, screen): """初始化飞船及其位置""" self.screen = screen self.ai_settings = ai_settings # 加载飞船图像并获取其外接矩形 self.image = pygame.image.load('ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.ge...
#counting charactor import re def countingwords(sample): remember = [] for i in sample: if (i not in remember): getTarget = re.findall(i,sample) print(i,len(getTarget)) remember.append(i) test = "abcdccaaddbkfdka" countingwords(test)
#Day093 - code challenge banknotes """ Suppose you are the manager of a bank and you have the problem of discriminating between genuine and counterfeit banknotes. You are measuring several distances on the banknote and the width and height of it. Measuring these values of about 100 genuine and 100 counterfeit ...
#Day089 - WCSS and Silhouette Method import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('xclara.csv') features = df.iloc[:,[0,1]].values from sklearn.cluster import KMeans #WCSS Method: To determine optimla number of clusters WCSS = [] for i in range(1,11): k...
#Day015 OOP code challenge: Book biblio class Book: def __init__(self,authorfirstname, authorlastname, booktitle, publish_place, publisher, publish_year): self.first = authorfirstname self.last = authorlastname self.title = booktitle self.place = publish_place self.pub...
#regex import re dir(re) """ sub findall search match compile """ mails = 'abc@gmail.com def@yahoo.com ghf@outlook.com' #ABC@gmail.com, DEF@yahoo.com, GHIO@outlook.com mail = re.sub(r'[abcdfeghi]+@','ABC@',mails) #re.sub needs pattern, then replacing character, then the string in which we are operating an...
#Day033 - linear regression model testing import pandas as pd df = pd.read_csv('student_scores.csv') """ features = df['Hours'].values #values added to give data in a list and to remove index labels = df['Scores'].values from sklearn.linear_model import LinearRegression #create an object regression = Li...
# OOPs (Object Oriented Programming) """ Code Challenge 1 Filename: radio.py Create a Radio class with characteristics and functionality discussed in class Create the object of the Radio class and start the radio and play a song Characteristics | Functionality ------------------------...
#Day024 - code challenge baby names import re from glob import glob import pandas as pd import matplotlib.pyplot as plt filenames = glob('*.txt') #reading data from 1880 t0 2010 and adding a column named year #concatenating all of the data into single dataframe baby_list = [] i=1 while i<(2011-1879): ...
#Day037, Day038, Day039 - categorical data to numeric representation import pandas as pd df = pd.read_csv('Salary_Classification.csv') df.shape df.columns.tolist() df.isnull().any(axis=0) df.dtypes #features and labels: features = df.iloc[:,0:4].values labels = df.iloc[:,-1].values #department columns...
#https://projecteuler.net/problem=3 #find the largest prime below a certain number '''def prim(x): i=x state = "f" while True: i-=1 j=2 while (j<=round(i**0.5+1)): if(i%j==0): if(i==3): print "3 is the largest prime below ",x state = "Found" break elif(i==2): print "2 is the larg...
#https://projecteuler.net/problem=9 #calculate the product of the Pythagorean triplet when a+b+c = 1000 . #Given the Triangle Inequality that the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side, the length of any side should never exceed 500. #Moreover, as the avera...
# 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요. def reverse(s): return s.__reversed__() in_str = input('입력 > ') print('결과>' + in_str[::-1])
import matplotlib.pyplot as plt import numpy as np # сделать, чтоб при приходе LIST[ [a] [b] ] рисовал графики а1б1 а2б2 а3б3 ... # ловит косяки с размерностями и диапазонами def PRINT_PLOT( LIST_Y = [1,3,2,6,8,2,6,8] , LIST_X = "NUMBER" , MARK="k" , PARAMS=["","","","",""] , POINTS_BEG = 0 , POINTS_END = "END" ): ...
''' Several useful functions for doing things with tuples''' def tup_value_w_kwargs( a_tup=(1,2,3), a_int=5 ): '''This returns the input tuple with a_int as the first item''' r = (a_int,) + a_tup[1:] return r
def size_of_list(list_a): return len(list_a) # return size of list def add_elem_to_list(list_a, elem): list_a.append(elem) return list_a # add elem to list and return the list def delete_elem_from_list(list_a, index=-1): list_a.pop(index) return list_a # delete element from list, such that its index is ind...
#!/usr/bin/env python3 # Pick out the single number that doesn't have duplicate number in the list # Way to go is to create another list, add if the number is not in the new list, delete if already in the new list def single_number(ls): new_list = [] for i in ls: if i in new_list: ...
# Created by Vinay Jakkali on 11/25/2019 """ -------------------------------------------------------------------------------------- Include code description here: -------------------------------------------------------------------------------------- """ import matplotlib.pyplot as plt from univariate import univaria...
# Created by Vinay Jakkali on 11/25/2019 """ -------------------------------------------------------------------------------------- The newton_raphson function defined here takes following parameters as input INPUT: f : It is defined as an anonymous function x0 : It is initial guess required for Newton Raphson metho...
""" Napisz program, który wczytuje liczbę całkowitą, a następnie na konsolę wypisuje w tylu liniach "choinkę" ze znaków `*`. Np. dla parametru 3 powinno się wypisać: ``` * * * * * * * * * ``` """ zmienna = '' liczba_calkowita = int(input('Podaj liczbe całkowitą: ')) j = 0 for i in range(1, liczba_calkowita +1...
""" # Zadanie #11Zaimplementuj klasy odpowiedzialne za tworzenie dokumentów w składni MarkDown. Stwórz klasę bazową `Element` zawierającą podstawową implementację metody `render()` oraz kilka jej klas pochodnych. Stwórz klasę `Document` umożliwiającą wyrenderowanie dodanych elementów. Przykład użycia: >>> document = Do...
""" --- Day 11: Seating System --- Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet!...
class Subscript(object): def __init__(self, begin=0, end=0, isWildcard=False, isSingle=False): self.begin = begin self.end = end+1 if (self.end == 0): self.end = None # No end == "until the array ends" self.isWildca...
""" Given an 3 x 3 array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. """ def snail_sort(arr): sorted_list = [] # get the top, right and bottom numbers for i in range(len(arr)): # if its the top layer, add it if i == 0: ...
def any7(nums): """Are any of these numbers a 7? (True/False)""" boolean = False for number in nums: if number == 7: boolean = True break return(boolean, nums) print("should be true", any7([1, 2, 7, 4, 5])) print("should be false", any7([1, 2, 4, 5]))
a = [1, 7, 2, 3, 5, 8, 13, 21, 34, 55, 89] new = [] for x in a: if (x < 5): new.append(x) print(new) # filter return those element which return true in lambda function other function are reduce and map #print(list(filter(lambda x: (x < 5) , a))) #no = int(input("enter a no: ")) #print(list(filter(lambda ...
def LongestWord(sen): from string import ascii_letters, digits sen = " ".join([ch for ch in sen if ch in (ascii_letters + string.digits)]) return sen # keep this function call here print LongestWord(raw_input())
import random import string def generate_password(length=8): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password # Usage example: # Generates a random password of length 12 password = generate_password(...
*** 20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty strin...
''' 1491. Average Salary Excluding the Minimum and Maximum Salary Given an array of unique integers salary where salary[i] is the salary of the employee i. Return the average salary of employees excluding the minimum and maximum salary. Example 1: Input: salary = [4000,3000,1000,2000] Output: 2500.00...
*** 1162. As Far from Land as Possible Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance. The distance used in this problem is the Manhattan distance: the dista...
*** 172. Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. *** class Solution: def trailingZeroes(self, n: int...
*** 268. Missing Number Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you impl...
*** 326. Power of Three Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Follow up: Could you do it without using any loop / recur...
*** 796. Rotate String We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. ...
*** 821. Shortest Distance to a Character Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] *** class Solution: def min_d...
*** 560. Subarray Sum Equals K Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 *** class Solution: def subarraySum(self, nums: List[int], k: int) -> int: l=0 ...
#!/usr/local/bin/python3 import smtplib import time ticket = "tnum.txt" def ticketnumber(): ''' This function simply retrieves the ticket number for the tnum.txt file this file is only supposed to be 1 line. ''' with open(ticket, 'r') as file: i = file.read() return i def updatenumbe...
def pl(count, one, few, many): count = str(count) if int(count) != 11 and int(count[len(count) - 1]) == 1: print(count, one) elif int(count[len(count) - 1]) >= 2 and int(count[len(count) - 1]) <= 4 and (int(count) < 5 or int(count) > 21): print(count, few) elif int(count[len(count)...
x = float(input('x ')) y = float(input('y ')) if x > y: z = x - y else: z = y - x + 1 print('z = ', z)
x = float(input('x ')) y = float(input('y ')) if x > y: print(x) else: print(x, y)
def LongestUniqueSubsequence2(s): st = set() res = 0 j = 0 for i in range(len(s)): while (s[i] in st): st.remove(s[j]) j+=1 st.add(s[i]) # 移除掉上一个之后,现在的这个元素也要加上 res = max(res,i-j+1) return res if __name__=='__main__': print(LongestUniqueSubsequence...
def lower_bound(array,first,last,value): while first < last: mid = first + (last-first)//2 if array[mid] <value: first = mid+1 else: last = mid return first def upper_bound(array,first,last,value): while first < last: mid = first + (last-first)//2 ...
#Sheila Robles #Assignment 1 Problem 2 #Python Version 3.0.1 start = int(input("Enter a start value: ")) print("exp res") print("1 ",start ** 1) print("2 ",start ** 2) print("3 ",start ** 3) print("4 ",start ** 4)
# Sheila Robles # Final Exam Summer 2016 # Python Version 3.0.1 import tkinter as tk import DBUpdater from tkinter import messagebox score_track = tk.Tk() def add_team_new(name): """Used with the modify_command in add team pane Args: name: the name of the team to add """ ...
#Sheila Robles #Assignment 1 Problem 5 #Python Version 3.0.1 message = input("Please enter the message: ") key = int(input("Please enter the key: ")) + 1 print(message[::key])
#Sheila Robles #Assignment 1 Problem 3 #Python Version 3.0.1 names = input("Enter three names: ").split() print(names[2]) print(names[1]) print(names[0])
#Sheila Robles #Assignment 3 Problem 3 #Python Version 3.0.1 class Actor(object): def __init__(self, name): self.name = name def act(self): raise NotImplementedError("Act method not implemented.") def act(self,actor): self.actor = actor class Robber(Actor): def __i...
#coding=utf-8 def demo1(): num = int(input("请输入一个整数")) return num def demo2(): return demo1() #利用异常的传递性,在主程序捕获异常 try: print(demo2()) except Exception as result: print("未知错误 %s" % result)
#coding=utf-8 num = 10 def demo1(): #不允许直接修改全局变量的值 num = 99 print("demo1 ==>%d" % (num)) def demo2(): print("demo2 ==>%d" % (num)) demo1() demo2()
# coding=utf-8 def sum_numbers(num): #1.出口 if num == 1: return 1 #2.数字的累加 num + (1....num-1) temp = sum_numbers(num-1) return num + temp result = sum_numbers(100) print(result)
#coding=utf-8 try: num = int(input("请输入一个整数:")) result = 8 / num print(result) except ValueError: print("请输入一个整数") #捕获未知错误 except Exception as result: print("未知错误 %s" %result) else: print("尝试成功") finally: print("不管是否成功都会去执行") print("*" * 50)
#coding=utf-8 from collections import namedtuple,Counter from random import randint import re def tuple_named(): '''命名''' Student = namedtuple('Student',['name','age','male','email']) s = Student('subiao','20','女','123@qq.com') return s def dict_count(): '''统计''' data = [randint(-10,10) for ...
#coding=utf-8 import threading import time #定义全局变量 num = 100 def test1(): global num num += 100 print("---in test1---%d" % num) def test2(): print("---in test2---%d" % num) def main(): t1 = threading.Thread(target=test1) t2 = threading.Thread(target=test2) t1.start() time.sleep(1...
# input = range(112233, 112234) # input = range(123444, 123445) # input = range(112111, 112112) # input = range(111122, 111123) input = range(152085, 670284) def check_mult_length(agg, x, candidate): if x and x[0] == candidate: return check_mult_length(agg + 1, x[1:], candidate) return agg def is_pa...
#Paulina Mendoza Iglesias #Programa que devuelve la cantidad a pagar por cierta cantidad de boletos #Función calcula el pago de acuerdo a la cantidad de boletos en cada zona def calcularPago(boletosA, boletosB, boletosC): numeroBoletosA = boletosA * 3250 numeroBoletosB = boletosB * 1730 numeroBoletosC = bo...
# Katie Krieger # 5/7/17 # https://www.rithmschool.com/courses/python-fundamentals-part-1/python-functions-exercises # Part 1 #1 def difference(a,b): return a-b def product(a,b): return a*b def print_day(num): if num < 1 or num > 7: return None dict = {1:"Sunday", 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"T...
# using for loop def linearSearch(array,item): for i in array: if i == item: return True break else: return False # using while loop def linearSearch(array,item): found = False index = 0 while index < len(array) and found is False: if array[...
def no_repeats(year_start, year_end): dates_list = range(year_start, year_end) numbers_list = [] final_list = [] for x in dates_list: for y in str(x): if y not in numbers_list: numbers_list.append(y) if len(numbers_list) == len(str(x)): final_list.append(x) numbers_list = [] return final_list ...
from time import perf_counter_ns from rich import print def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) else: return -1...
# =============== varcopy =============== a = 3 b = a print("a = %d, b = %d" % (a, b)) a = 5 print("a = %d, b = %d" % (a, b)) print(id(a), id(b)) # =============== listcopy =============== list1 = [ 1, 2, 3 ] list2 = list1 list2[1] = 100 print(list1) print(list2) print(id(list1),id(list2)) # =============== listcop...
import random grade = random.randint(1,6) if grade == 1 or grade == 2 or grade == 3: print(grade,"학년은 저학년입니다.") else: print(grade, "학년은 고학년입니다.")
import random pairNum1 = random.randint(1,6) pairNum2 = random.randint(1,6) while pairNum1 != pairNum2: if pairNum1 > pairNum2: print("pairNum1이 pairNum2 보다 크다.") else: print("pairNum1이 pairNum2 보다 작다.") pairNum1 = random.randint(1, 6) pairNum2 = random.randint(1, 6) print("게임 끝")
# =============== mathquiz =============== import random a = random.randint(1, 9) b = random.randint(1, 9) question = "%d + %d = ? " % (a, b) c = int(input(question)) if c == a + b: print("정답입니다.") else: print("틀렸습니다.") # =============== mathquiz2 =============== import random correct = 0 while True: ...
def myprint (*a, **args): deco = '**' s = ',' if 'deco' in args.keys(): deco = args['deco'] if 'sep' in args.keys(): s = args['sep'] '''deco = args.get("deco", "**") s = args.get("sep", ",")''' result = '' if len(a) == 0: print("Hello Python") else: re...
import random score = random.randint(0, 100) grade = "" if score >= 90: grade ="A" elif score >= 80 and score < 90: grade ="B" elif score >= 70 and score < 80: grade ="C" elif score >= 60 and score < 70: grade ="D" else: grade ="F" print(score,"점은",grade ,"등급입니다. ")
data = [1,2,3,4] print(data) print(*data) # 아규먼트에서도 *을 붙일 수 있음, 리스트가 가지고있는 요소값들을 쪼개서 야구먼트로 전달함!! print(data[0], data[1], data[2], data[3]) print("*"*30) a,b,c,d = [10,20,30,40] print(a) print(b) print(c) print(d) print("*"*30) x,*y,z = [10,20,30,40] print(x) print(y) # 처음, 마지막 뺴고 모두 y한테 할당 print(z) print("*"*30) p ...
a = 100 print(type(a)) #int print(a.bit_length()) print(bin(a)) # a. 했을 떄 뜨는 것들은 코드 어시스턴트, 객체에 속한 메서드 알려주는 것 b = 3.14 print(type(b)) #float print(b.real) print(b.is_integer()) c = 3+4j print(type(c)) #complex print(c.real) print(c.imag) d = False print(type(d)) # bool print(d.bit_length()) print(bin(d)) e = " " pri...
def print_gugudan(n): if type(n) == int: if 1<=n<=9: for i in range(1,10): print(n,"*",i,"=",n*i) else: pass else: pass print_gugudan(3) print_gugudan(5) print_gugudan(8) print_gugudan(10) print_gugudan("x") # else - pass 없어도 됨. 가독성 필요할 떄만 쓰기
numlist1 = [] numlist1.append(1) numlist1.append(2) numlist1.append(3) numlist1.append(4) numlist1.append(5) print("list1 = {}".format(numlist1)) numlist2 = [] for n in range(1,6) : numlist2.append(n) print("list2 = {}".format(numlist2)) numlist3 =[1,2,3,4,5] print("list3 = {}".format(numlist3)) numlist4 = [ num...
import random import numpy as np import matplotlib.pyplot as plt # ------------------------------------------------ # # this is the Robot class # class Robot(object): def __init__(self, length=20.0): """ Creates robot and initializes location/orientation to 0, 0, 0. """ self.x = 0...
# # Adversarial Indistinguishability Experiment # CSC507/609 Term 201 # # Write an adversary with an advantage in the # indistinguishability game for a vigenere cipher. # The key is generated according to the distribution # presented in problem 2.8 of the class text. # # template author: bjr # template date: 9 sept 201...
import sys from helpers import frequency from wav import Song NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def main(): if len(sys.argv) > 2: print("Usage: python notes.py OCTAVE") sys.exit(1) octave = int(sys.argv[1]) if len(sys.argv) == 2 else 4 if octave < 0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 12 14:46:47 2020 @author: macbook """ def get_batches(arr, batch_size, seq_length): '''Create a generator that returns batches of size batch_size x seq_length from arr. Arguments --------- arr: Array you want...
#Filename: Compare.py def maxi(a,b):#define maxi function if a>b: print(a,"is maximum") elif a==b: print("Both are Equal") else: print(b,"is Greater") #End of Function while True:#Loop Started g=int(input("What You Want to Do?\n1:Enter\n2:Exit\n="))#User Conformation ...
#FileName:Global_Statement.py #if you are uing global statement in the function then the value of the variable of same name will chnage globally. x = 50#local variable def funct(): global x print("value of local variable x is ",x) x=2 print('value change of x in function is ',x) #end of function ...