text
stringlengths
37
1.41M
import pandas as pd df1_title = ['name','id','phone'] df2_title = ['name','sex','age'] df3_title = ['name','grade','score'] count = 101 writer = pd.ExcelWriter('file_name.xlsx') def generate_df1(): df1 = pd.DataFrame({df1_title[0]:[], df1_title[1]:[], df1_title[2]:[]}) for i in range (1, count): df1 =...
#Задание №1 # Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. print("Как тебя зовут?") name = input() print("Привет,", name) print("Сколько тебе лет?") age = int(input()) print("Когда у тебя день рождения?...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv import time with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务0: 短信记录的第一条记录是什么?通话记录最后一条记录是什么? 输出信息: "First record of t...
#Required Packages from nltk import sent_tokenize from spacy.lang.en import English nlp = English() tokenizer = nlp.Defaults.create_tokenizer(nlp) #Split and Tokenize def split_and_tokenize(text): """ Goal: Create a list of list of tokens from sentence(s). Input: - text: String containing >= 1 senten...
from string import ascii_lowercase # "I have no special talent I am only passionately curious" # ~ Albert Einstein def TabulaRecta(): mat =[[l for l in ascii_lowercase[i:]] + [' '] + [l for l in ascii_lowercase[:i]] for i in range(len(ascii_lowercase)+1) ] def encrypt(text): s...
from string import ascii_lowercase """ "DON’T WORRY ABOUT THE WORLD ENDING TODAY, IT’S ALREADY TOMORROW IN AUSTRALIA." ~ CHARLES M. SCHULZ """ class PlayfairCipher(): def __init__(self, key=None): self.mat = [[]] if key: alpha = key else: alpha = "" ...
class Catraca: def cod(self): return "XPTO" def __init__(self, clube): self.__clube = clube def identificarPessoa(self, pessoa): if pessoa.getVinculo() == "Sócio": if pessoa in self.__clube.consultarSocio(): return self.cod() +""+ str(pessoa) else: return str(pesso...
def sum_digits(d1, d2): if (d1 == d2): return int(d1) return 0 def sum_neighbor(numbers): if len(numbers) <= 1: return 0 sum = 0 for i in range(0, len(numbers)): if i < len(numbers) - 1: sum += sum_digits(numbers[i], numbers[i+1]) if len(numbers) > 2: ...
def check(expected, actual): if actual == expected: print(actual, 'OK') else: print(f'{actual} != {expected} ERROR') def open_files(): with open('day09.input') as f: in_lines = f.read().splitlines() with open('day09.output') as f: out_lines = f.read().splitlines() ...
# CSCI3180 Principles of Programming Languages # # --- Declaration --- # # I declare that the assignment here submitted is original except for source # material explicitly acknowledged. I also acknowledge that I am aware of # University policy and regulations on honesty in academic work, and of the # disciplinar...
listval = [1,2,3,4,5,6] print ("value at idx 1 %d " % listval[1]) somenum =2**4 lst = [1, [20,21,somenum],3,4] print(lst[1][2]) #16 lst[1][2] = somenum**2 print(lst[1][2]) #256 (16^2) frstList = [4,3,2,1] secondList = [10,9,8] print (frstList + secondList) # adds both the list print (secondList *2) # prints the...
################## IMPORTATN : OBJECT ORIENTED PROGRAMMING CONCEPT ####### # imperative programming (using statements, loops, and functions as subroutines), # functional programming (using pure functions, higher-order functions, and recursion). # Objects in python are created using classes. # once class is created li...
w=input(" ") if(w=='Monday' or w=='Tuesday' or w=='Wednesday' or w=='Thrusday' or w=='Friday'): print("no") elif(w=='Saturday' or w=='Sunday'): print("yes") else: print("invalid")
# O(n^2)T | O(1)S def TwoNumberSum(array, TargetSum): for i in range(len(array)): Firstnum = array[i] for j in range(i + 1, len(array)): Secondnum = array[j] if Firstnum + Secondnum == TargetSum: print(Firstnum, Secondnum) array = [1, 2, 3, 8, 5] TargetSum...
#KONSTRUKSI DASAR PYTHON #SEQUENTIAL : EKSEKUSI BERURUTAN print('Hello World!') print("by Yakub") print("tanggal 4 Juli 2021") print("-"*10) #PERCABANGAN : Eksekusi Terpilih ingin_cepat=False if ingin_cepat: print('jalan lurus aja ya!') else: print('jalan lain!') #PERULANGAN jumlah_anak = 4 for index_anak in...
from Game import * game = Game() # This module functions as the driver for the game. while game.gamestatus() is False: print("\n\n\n\n\n\n\n\n\n\n\n\n\n") game.displaymap() print("\n What would you like to do? ") print(" You can move up 'u', down 'd', left 'l', and right 'r'") ui = input("\n\tEnter...
def hello(): print("Hello!") hello() name=["たんじろう","ぎゆう","ねずこ","むざん"] name.append("ぜんいつ") def namae(name1): if name1 in name: print(name1, "は含まれます") else: print(name1, "は含まれません") namae("ぜんいす")
""" Sklearn中的make_circles方法生成训练样本 并随机生成测试样本,用KNN分类并可视化。 """ from sklearn.datasets import make_circles from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt import numpy as np import random fig = plt.figure(1, figsize=(10, 5)) x1, y1 = make_circles(n_samples=400, factor=0.4, noise=0.1) # 模...
import numpy as np class BoardReader: """ ~ Class BoardReader represents single board reader from picture. Arguments: :param picture: picture from which board will be created :type picture: pil.Image """ def __init__(self, picture): """ ~ Class BoardReader constructor. ...
def findSublists(A): for i in range(len(A)): for j in range(i, len(A)): print(A[i:j + 1]) def rotate(arr, n): x = arr[n - 1] #last element for i in range(n - 1, 0, -1): arr[i] = arr[i - 1] arr[0] = x print(arr) if __name__ == '__main__': A ...
# -*- coding: utf-8 -*- """ Created on Sun Sep 1 15:30:27 2019 @author: prash """ def process(line: str) -> str: # Return 'VALID' or 'INVALID' checksum=line[0:2] try: acc_num=int(line[2:len(line)],16) except (ValueError): return "INVALID" sum=0 while(acc_num>0): dig=ac...
if __name__ == "__main__": # 입력 string = input() # 입력받은 문자열을 탐색하면서 따로 구현한 문자열 배열에 문자를 삽입하고, 숫자는 누적해서 더한다. sort_string = [] total = 0 for i in string: if i.isalpha(): sort_string.append(i) else: total += int(i) result = sorted(sort_string) if tot...
from tkinter import * import tkinter.messagebox as tmsg root=Tk() root.geometry("455x233") root.title("Slider") def getdollar(): print(f"We have credited {myslider2.get()} dollars to your bank account") tmsg.showinfo("Amount Credited",f"We have credited {myslider2.get()} dollars to your bank account") # mysl...
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/bubble', methods=['POST']) def bubbleSort(arr): # import user input bubble = request.form['bubble'] n = len(arr) # Filter through array for i in range(n): # Last i elements are already in place ...
import random booklist1 = ["The Great Gatsby,", "To Kill a Mockingbird", "Catch-22", "Pride and Prejudice", "The Scarlet Letter", "War and Peace", "One Hundred Years of Solitude", "The Sun Also Rises"] booklist2 = ["To Kill a Mockingbird,", "The Scarlette Letter", "War and Peace"] #1: setting up the class class ...
# nested loops listA = list(range(6)) listB = list(range(6)) product1 = [(a, b) for a in listA for b in listB] product2 = [(a, b) for a in listA for b in listB if a % 2 == 1 and b % 2 == 0] ''' print(product1) print(product2) ''' ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ', 'LU...
import os import os.path import time def user_dir_file(): user_dir = input("Please enter a directory to save a file in: ") user_file = None if os.path.exists(user_dir): user_file = input("Please enter the name of the file you want to save in the specified directory: ") else: os.makedir...
import math def calentropy(dict): entropy={} for i in dict.keys(): entropy[i]=0 for j in dict[i]: if j!=0: entropy[i]-=(j*(math.log(j, 2))) print(entropy) calentropy({'A':[0.5, 0, 0, 0.5],'B':[0.25, 0.25, 0.25, 0.25],'C':[0, 0, 0, 1],'D':[0.25, 0, 0.5, 0.25]})
""" CMPS 2200 Assignment 1. See assignment-01.pdf for details. """ # no imports needed. def foo(x): if x <= 1 : return x else: return foo(x-1)+foo(x-2) ### TODO pass def longest_run(mylist, key): tracker = 0 longest_count = 0 for i in mylist: if (i > 0 and i==key):...
def soma(numero1, numero2): return numero1 + numero2 def validador(numero): return type(numero) == int def test_soma(): assert soma(2,2) == 4 def test_soma_numero_negativo(): assert soma(2,-2) == 0, "a função soma() não está somando corretamente números negativos" def test_valida_numero(): asser...
print("mario sergio".replace('a', 'b').startswith('m')) meses = {'01': 'janeiro', '02': 'fevereiro', '03': 'março', '04': 'abril'} data = '26/04/2018'.split('/') mes = meses[data[1]]
# import numpy as np # np = numpy lista1 = [1,2,3] lista2 = list(lista1) print(lista2, lista1) print(lista1 == lista2) print(lista1 is lista2) lista1.append(10) print(lista2, lista1) print(lista1 == lista2) print(lista1 is lista2) def soma(num1, num2): return num2 + num1 class Calculadora(): def soma(se...
import numpy as np def getH(x): return x[1] - x[0] def getForwardDifferences(g): out = [g[0]] temp = [each for each in g] for i in range(len(temp)-1): temp2 = [temp[i+1]-temp[i] for i in range(len(temp)-1)] out.append(temp2[0]) temp = temp2 return out def factorial(n): ...
# -*- coding: utf-8 -*- import numpy as np import xlrd import pandas as pd #read the data from the excel file def read(file): wb = xlrd.open_workbook(filename=file)#open the file sheet = wb.sheet_by_index(0) #obtain the table data from the index rows = sheet.nrows # calculate the number of rows all_con...
from queue import Queue def bfs(start_state, goaltest): """ Find a sequence of moves through a state space by breadth first search. This function returns a policy, i.e. a sequence of actions which, if applied to `start_state` in order, will transform it to a state which satisfies `goaltest`...
""" Solve a Sudoku puzzle using logic constraints. """ # This exercise uses Microsoft's Z3 SMT solver (https://github.com/Z3Prover/z3). # You can install it for python using e.g. pip: `pip install z3-solver` # or see the github page for more option.s # # z3 is an SMT - Satisfiability Modulo Theories - solver, and isn't...
import random from math import inf # Evaluate a state # Monte Carlo search: randomly choose actions def mc_trial(player, state, steps_left): """ Recursively perform Monte Carlo Trial randomly choosing among available actions for next state. Performs at most steps_left moves, if steps_left = 0 or if t...
#27 Process Class in python class Process: def __init__(self,slice,input_output,waiting,arrival,burst): self.slice=slice self.input_output=input_output self.waiting=waiting self.arrival=arrival self.burst=burst self.remainingQuantum=0 self.comming_back_time=0 def showProcess(self): print(...
class Coordenada: def __init__(self,x,y): self.x, self.y = x, y def move(self, delta_x, delta_y): return Coordenada(self.x + delta_x, self.y + delta_y) def dist(self, other_coor): dif_x = self.x - other_coor.x dif_y = self.y - other_coor.y return(dif_x**2 + dif_y**...
class Employee: company = 'Google' def getSalary(self): print (f'Salary for {self.name} working in {self.company} is {self.salary}') nirmit = Employee() nirmit.name = 'Nirmit' nirmit.salary = 100000 nirmit.getSalary() # Employee.getSalary(nirmit) # actually nirmit.getSalary() converts to Empl...
# fizbuzz test def fizzbuzz(start, end): fizzbuzz = [] for i in range(start,end): if i % 3 == 0 and i % 5 == 0: fizzbuzz.append('fizzbuzz') elif i % 3 == 0: fizzbuzz.append('fizz') elif i % 5 == 0: fizzbuzz.append('buzz') else: fizzbuzz.append(str(i)) return fizzbuzz print(fizzbu...
# coding=utf-8 c = int(input("请您输入当前的摄氏温度")) f = 9*c/5+32 print("当前的华氏温度为: " + str(f))
# coding=utf-8 successed = "no" #这是个开关 while successed == "no": username = input("Please input your username/请输入你的用户名") pw = input("Please input your password/请输入你的密码") if username == "will": if pw == "1234": print("欢迎登陆, "+ username) successed = "yes" else: ...
# coding=utf-8 score = 0 print("来参加这个小测试,试验一下你有多了解我吧!") print("题目1:我喜欢什么颜色?") print("a:黑色black?") print("b:白色white?") print("c:粉红色pink?") ans = input("please input your answer ") if ans == "a": print("恭喜你选对啦!") score = score +10 else: print("你猜错啦!") print("题目2:我喜欢吃什么?") print("a:蔬菜vegetables?") print("b:汉堡...
# Time Complexity : O(NlogN) for sorting # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach # sort the numbers at add all numbers at even positions # to get the maximum sum of the min...
class Track: def __init__(self, trackname, tracklength): self.name = trackname self.length = tracklength def __str__(self): return f'Name: \"{self.name}\" | Length: {self.length} minutes' def __lt__(self, other): return print(self.length < other.length) def __gt__(self...
from enum import Enum class Suit(Enum): spades = 1 clubs = 2 diamonds = 3 hearts = 4 def __str__(self): suit_names = { 1: "spades", 2: "clubs", 3: "diamonds", 4: "hearts" } return suit_names[self.value]
""" This is an example to show how usefull (or not!) is to create objects by reference in python """ # Lets create a dictionary like this one: # a = { # "dog" : { # "name" : "Boobis", # "eats" : ["meat", "treats", "anything that smells great"] # }, # "cat" : { # "name" : "Logan", # ...
def insert(self, val): if self.root== None: self.root= Node(val) root= self.root while True: if val > root.info: if root.right: root= root.right else: root.right=Node(val) break elif val < root.info: ...
## Module Car ## This is the main module of this project. # It observes the reaction of the solution and # controls the move and stop of the motors according # to the timing reaction. from motor import Motor from timer import Timer class Car: def __init__(self): self.timer = Timer() self.motor =...
# -*- coding: utf-8 -*- """ Created on Fri May 8 19:54:20 2020 @author: Carlos Henrique """ for a in range(1,1000): for b in range(1,1000): for c in range(1,1000): if (a**2 + b**2 == c**2 and a < b and b < c): if a + b + c == 1000: print(a*b*c)
# -*- coding: utf-8 -*- """ Created on Sun Jun 7 16:19:04 2020 @author: Carlos Henrique """ circ = [] primes = [] def prime(n): if n == 2: return True if n > 2: if any(n%i == 0 for i in range(2,n)): return False else: return True ...
# -*- coding: utf-8 -*- """ Created on Tue May 19 18:07:36 2020 @author: Carlos Henrique """ collatz_sequence = [] collatz_sequence_2 = [] def start(): global collatz_sequence global collatz_sequence_2 global i collatz_sequence_2.append(i) if i%2 == 0: while i%2 == 0: ...
# -*- coding: utf-8 -*- """ Created on Tue Jun 23 12:16:53 2020 @author: Carlos Henrique """ fibonacci = [1,1] for i in fibonacci: a = fibonacci[-1] + fibonacci[-2] b = str(a) fibonacci.append(a) if len(b) == 1000: print(len(fibonacci)) break
# -*- coding: utf-8 -*- """ """ import itertools ''' Dada la lista L de longitudes de las palabras de un código q-ario, decidir si pueden definir un código. ''' def kraft1(L, q=2): acum = 0 for lon in L: acum += 1/(q**lon) return acum <= 1 ''' Dada la lista L de longitudes de las palabras de un código q-...
from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache_size = capacity self.length = 0 self.cache = OrderedDict() def get(self, key: int) -> int: #print(f'trying to get key: {key}') try: if self.cache[key] >...
import sys import math while True : text = input() if text =="" : break num = long(text) if num <= 1: print(num) else : print(2*(num-1))
import trig def add(a, b): return a+b def subtract(a, b): return add(a, -b) def multiply(a, b): return a*b def divide(a, b): if b == 0: return "Undefined" else: return multiply(a, power(b, -1)) def factorial(a): x = 1 if a < 0: return("Undefined") else: fo...
from typing import Union def naive_exponentiation(a: int, b: int) -> Union[int, float]: r = 1 if b < 0: a = 1 / a b *= -1 for i in range(b): r *= a return r def power_of_two_with_multiplication(a: int, b: int) -> Union[int, float]: r = a pwr = 1 previous = 0 i...
def gcd_subtraction(a: int, b: int) -> int: while a != b: if a > b: a = a - b else: b = b - a return a def gcd_division(a: int, b: int) -> int: while b != 0: t = b b = a % b a = t return a def gcd_bitwise(a: int, b: int) -> int: # ...
from cs1graphics import * ################################# # Global variables index_list = [ ( 0, (0, 0) ), ( 1, (0, 2) ), ( 2, (2, 0) ), ( 3, (2, 4) ), ( 4, (4, 2) ) ] word_list = [ ( 'ACROSS', 0, (0, 0), 3, 'BAA' ), ( 'ACROSS', 2, (2, 0), 5, 'SOLID' ), ( 'ACROSS', 4, (4, 2), 3, 'WIT' ), ( 'DOWN', 0, (...
remainder = [] list1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"] def deci_to_any(n, rad): a1 = n/rad r1 = n%float(rad) remainder.append(list1[int(r1)]) while a1 > rad: r1 = a1%float(rad) a1 /= rad remainder.append(list1[int(r1)]) ...
# ver1 from abc import abstractmethod class Calc: def __init__(self, x, y): self.x = x self.y = y def add(self): return self.x + self.y def subtract(self): return self.x - self.y class Calc2: def __init__(self, x, y): self.x = x self.y = y ...
#coding:utf-8 from Tkinter import * def calcular(): print "VALORES" lb["text"] = "VALORES" tela = Tk() lb = Label(tela, text="Bem Vindo!") # Isso é um componente lb.place(x=120, y=150) #Gerenciador é o place. () bt = Button(tela, width=20, text="CALCULAR", command=calcular) bt.place(x=50, y=180) lb = Label(te...
import random import itertools from termcolor import cprint from gameactions import play_card def sort_hand_value(card_list): return card_list.sort(key=lambda x: x.run_value) class Game: # environment for the game, global var/objects should be available here def __init__(self, first_player, second_player,...
def addition(x, y): return x + y def substraction(x, y): return x - y def division(x, y): return x / y def multiplication(x, y): return x * y PI = 3.1415 def print_text(): print("Module mathematics")
# Funkcie v Pythone sú takzvané funkcia prvej triedy 'First class functions' def hello_world(): print("helllo world") print(type(hello_world)) # Aj funkcia je len objekt (pre tych co videli moj kurz OOP) # To znamená že ich napríklad vieme priradiť do premenných x=hello_world # vsimni si ze nepouzivam okruhle zat...
# Video https://youtu.be/VH_YaAI-BKI numbers = [1, 2, 3, 4, 5, 10] # Pomocou for cyklu vieme prechadzat cez polia for number in numbers: print(number) # Alebo cez retazce. for letter in "Michal Hucko": print(letter) # Funkcia range nam pomaha vytvorit pocitadlo, alebo pole cisel <dolnyny interval; horny int...
import datetime from random import randint long_list = [randint(0, 3000) for element in range(1000000)] # Przeszukiwanie liniowe (bez przygotowania) t1 = datetime.datetime.now() for i in long_list: if i == -1: print("Znaleziono!") t2 = datetime.datetime.now() - t1 print("Czas trwania algorytmu: ", t2) ...
""" Для даного імені виводить ім'я та по-батькові Вхідні дані очікуються з аргумент стрічки (1 строковий параметр). При відсутності імені в базі, виводить відповідне повідомлення """ import sys import argparse def createParser(): parser = argparse.ArgumentParser() parser.add_argument('name', narg...
# Hamming def distance(strand_a, strand_b): strand_length = len(strand_a) hamming_distance = 0 if len(strand_a) != len(strand_b): raise ValueError('Strand lengths are not equal') for x in range(strand_length): if strand_a[x] != strand_b[x]: hamming_distance += 1 retur...
#print "Hello WOrld" #var = int(raw_input("")) #var2 = int(raw_input("")) #print (var+var2) #print (var-var2) #print (var*var2) #if var2!=0: # print (var/var2) # print (var%var2) print ":)" o = 0 while ( o != 3 ): o = int(raw_input("1. Calculadora \n2. Par o impar\n3. Salir")) if o == 1: st = raw_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 13 03:40:08 2018 @author: star """ """ Deletion of elements in python dictionary is quite easy. You can just use del keyword. It will delete single element from Python Dictionary. But if you want to delete all elements from the dictionary. You c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 13 19:56:07 2018 @author: star """ One of the first cautions programmers encounter when learning Python is the fact that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted b...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 13 10:18:04 2018 @author: star """ """ Traversing 2D-array using for loop The following code print the elements row wise then the next part prints each element of the given array. """ arrayElement2D = [ ["Four", 5, 'Six' ] , [ 'Good', 'Food' , 'W...
import random from classes import Prints out = Prints(False) def Battle(p1,p2): global out, p1damage,p2damage p1damage = 0 p2damage = 0 IQcheck(p1,p2) STRcheck(p1,p2) CHAcheck(p1,p2) Critical(p1,p2) p1.hp = p1.hp- p2damage p2.hp = p2.hp- p1damage return p1.hp,p2.hp def IQcheck(p1,p2): global p1dam...
#사전 속 자료 찾기 # values 메소드 사용 my_number = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } print(my_number.values()) for value in my_number.values(): #my_number.values 안에 들어있는 녀석들을 순차적으로 불러옴. print(value) print(my_number.keys()) for key in my_number.keys(): #my_number.keys 안에 들어있는 녀석들을 차례대로 불러옴 print(...
# 빈 리스트 만들기 numbers = [] print(numbers) # numbers에 값들 추가 numbers.append(1) numbers.append(7) numbers.append(3) numbers.append(6) numbers.append(5) numbers.append(2) numbers.append(13) numbers.append(14) print(numbers) # numbers에서 홀수 제거 index = 0 while index < len(numbers): if numbers[index] % 2 != 0: del(...
#1 # in을 이용하면 boolean을 통해 찾고자 하는 값이 있는지 아닌지 확인할 수 있어요! primes = [2, 3, 5, 7, 11, 13, 17, 19, 23] print(13 in primes) print(1 in primes) print(13 not in primes) print(1 not in primes) print() #2 #nested list : list 안에 또 리스트가 있지용 a = [62, 75, 77] b = [78, 81, 86] c = [85, 91, 89] grades = [] grades.append(a) grades....
# 화씨 온도에서 섭씨 온도로 바꿔 주는 함수 def fahrenheit_to_celsius(fahrenheit): global Celcius # Celcius를 글로벌 변수로 선언. count = 0 length = len(fahrenheit) Celcius = [] while count < length: temp_F = fahrenheit[count] temp_C = (temp_F - 32) * 5 / 9 temp_C = round(temp_C, 1) Celcius.a...
#while 과 for 사이 차이? ''' for문은 리스트의 내역을 반복할 시에 좋음 my_list = [2, 3, 5, 7, 11] for numbers in my_list: print(numbers) 여기서 numbers는 다르게 지정되어도 괜춘해! ''' #for 반복문을 이용해서 1~10까지 출력하는 프로그램 제작해보자. for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: pass #근데.. 1~ 100이면? 1000이면? 귀찮슴다.. #Sol. range 함수 : 리스트 슬라이싱이랑 비슷혀! #장점 : ...
year = 2019 month = 10 day = 29 #format classmethod ''' 1. 우리가 쓰고 싶은 문장을 우선 작성한다. 2. 원하는 값을 넣어야하는 공간을 {}로 대체해준다. ''' date_string = "오늘은 {}년 {}월 {}일 입니다." #문자열을 계속 반복해서 사용할 것이면 선언을 미리 해주자. print(date_string.format(year, month, day)) #그냥 그자리에 그대로 숫자를 대입할거면 굳이 중괄호에 번호 안적어도 괜춘해요 #.format의 괄호 안에서 연산을 해도 괜춘! num_1 = 1 num...
def ToPigLatin(a): word = "" for i in range(0, len(a)): a[i] = a[i].lower() a[i] = a[i][1:] + a[i][0] + "ay" for i in a: word += i + " " word = word.capitalize() return word def ToEnglish(b): word = "" for i in range(0, len(b)): b[i] = b[i].lower() b[...
def median(arr): l=len(arr) if(l%2!=0): return arr[l//2] else: return (arr[(l//2)-1]+arr[l//2])//2 n=int(input()) x=[int(i) for i in input().split(' ')] x.sort() #Q2 Q2=median(x) #Q1 Q1=median(x[:n//2]) #Q3 if(n%2!=0): Q3=median(x[((n//2)+1):n]) else: Q3=median(x[n//2:n]) print(Q1)...
total = 0 for a in range(1,11): #print(a) total = total + a a = a + 1 print(total)
str_N = input("Please enter a number to find summation of 1..N: ") N = int(str_N) + 1 total = sum(range(1,N)) print(total)
def binary_search(array, value_to_be_searched): left_bound = 0 right_bound = len(array) - 1 found = False while left_bound <= right_bound and not found: middle = (left_bound + right_bound) // 2 if array[middle] == value_to_be_searched: return middle else: ...
from itertools import cycle import itertools Name_1 = list(''.join(I1 for I1 in input("Enter Your Name :").lower())) Name_2 = list(''.join(e for e in input("Enter Your Partner Name :").lower())) Flames_List = ["Friendship","Love","Affection","Marriage","Enemy","Siblings"] Flames_Dict = {Output_List_1[x]:Flames_Lis...
def Sum_Of_Intergers(Arg_1): Temp_Var = 0 for Loop_Var in Arg_1: Temp_Var += int(Loop_Var) if(len(str(Temp_Var)) == 1): return Temp_Var else: return Sum_Of_Intergers(str(Temp_Var))
# https://projecteuler.net/problem=4 #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. n = 0 for i in range(999, 100, -1): for j in range(999, 100, -1): ...
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/112444173 def hit(base, occupied = None): """ >>> hit(2) (0, [2]) >>> hit(0, [1, 3]) (0, [1, 3]) >>> hit(1, (1, 3)) (1, [1, 2]) >>> hit(2, occupied=[1, 3]) (1, [2, 3]) >>> hit(3, occupied=(1, 3)) (2, [3]) >>>...
# https://dodona.ugent.be/nl/courses/359/series/3489/activities/1266098554 def splitsing(soort): """ Splitst de parameter (str) in een prefix en een suffix, waarbij de prefix bestaat uit alle medeklinkers aan het begin van de gegeven string. >>> splitsing('schaap') ('sch', 'aap') >>> splitsing...
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/1158810383 def serial_number(serial): """ >>> serial_number(834783) '00834783' >>> serial_number('47839') '00047839' >>> serial_number(834783244839184) '834783244839184' >>> serial_number('4783926132432*') Traceback (mos...
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/1652372190 def next_letter(v, w): """ >>> next_letter('e', 'HERDSMAN') 'R' >>> next_letter('LC', 'sepulchre') 'H' >>> next_letter('onf', 'Teleconference') 'E' >>> next_letter('EURO', 'DOLLAR') '' >>> next_letter('LF'...
# https://dodona.ugent.be/nl/courses/359/series/3488/activities/2009241681 # input the separator and number of lines separator = input() line_number = int(input()) for _ in range(line_number): # 循环的东西在loop中用不到 line = input() sep_index = line.index(separator) # exchange place and combine new_line = line[...
# https://dodona.ugent.be/nl/courses/359/series/3486/activities/56374393 # give the input start = str(input()) end = str(input()) move = '' # process start1, start2 = start end1, end2 = end if ord(start1) == ord(end1) or int(start2) == int(end2): # should be L shape move = 'cannot' elif abs(ord(start1)-ord(end1)) +...
# https://dodona.ugent.be/nl/courses/359/series/3487/activities/1898834779 # https://dodona.ugent.be/nl/courses/359/series/3486/activities/182880102 first = input() while first != 'stop': sum = int(first) for index in range(2, 10): next_digit = int(input()) sum += index * next_digit sum %= 1...
import random choices = ['rock','paper','scissors'] # let the computer choose def compChoice(): cChoice = random.randint(1,3) if cChoice == 1: cChoice = 'rock' elif cChoice == 2: cChoice = 'paper' else: cChoice = 'scissors' return cChoice # get the users choice ...
import numpy as np import pandas as pd from problem2 import * # Note: please don't import any new package. You should solve this problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 3: (Moneyball) Data Preprocessing in Baseball Dataset (24 ...
#zasieg zmiennych, zmienne lokalne i globalneabs #precyzja liczby(zaokrąglenie do 3 miejsc po przecinku) x="{0:.3f}".format(5) print(x) def plnToChf(value): kursChf=3.7536 iloscChf=value / kursChf iloscChf="{0:.0f}".format(iloscChf) print(f'Ilosc CHF: {iloscChf}') plnToChf(100) Ile=input("Podaj ile...