text
stringlengths
37
1.41M
#Written by Allif Izzuddin bin Abdullah #github : allifizzuddin89 import matplotlib.pyplot as plt import numpy as np import urllib.request import matplotlib.dates as mdates #refer https://pythonprogramming.net/converting-date-stamps-matplotlib-tutorial/ def bytespdate2num(fmt, encoding='utf-8'): #FMT IS FORM...
import keras.backend as K def recall(y_true,y_pred): """Calculates the recall of the prediction. This was copied from keras before they removed it from their default metrics. Parameters ---------- y_true : np.array The true output for the given input y_pred : np.array The pre...
x = 2 print(x == 2) print(x == 3) print(x < 3) name = "John" if name in ["John", "Rick"]: print("Your name is either John or Rick.") if x == 3: print("three") else: print("not three") x = [2] y = [2] if x is y: print("x is y") y = x if y is x: print("y is x") print() print() print() # Exercis...
import numpy as np import torch from torch.autograd import Variable import matplotlib.pyplot as plt import pandas as pd #df = pd.read_csv('cancer_data.csv') #print(df.head) #/Users/dionelisnikolaos/Downloads df = pd.read_csv('/Users/dionelisnikolaos/Downloads/cancer_data.csv') # binary classification, M is malig...
# we use Keras from keras import layers # we use keras layers # use keras models from keras import models # Data Science, Programming # use: https://www.springboard.com/blog/data-science-interview-questions/#programming # NLP and sentiment analysis # Twitter data => webscraping, we examine Twitter data # NLP: https:...
import anagram def methathesis(d): for anagram_sets in d.values(): anagram_sets.sort() for word1 in anagram_sets: for word2 in anagram_sets: # '<' operation to ensure each word is compared with the rest of words so as to avoid #repetetion ...
def is_sorted(ls): for i in range(len(ls)-1): if ls[i]<=ls[i+1]: return True else: return False a=[[1,2,3,4,5],['a','d','n','m'],[5,4,4,3],[1,1,2,2,3,3],['z','a','b','c','d']] for i in a: if is_sorted(i): print(True) else: print(False)
"""Module containing search algorithms.""" __all__ = ['binary_search'] from typing import Sequence from python_algorithms.typing import Comparable def binary_search(array: Sequence[Comparable], item: Comparable) -> int: """ Search for an item in a sorted array using binary search algorithms. Binary sea...
# + plus #- minus #/ slash #* asterik #% percent #< less-than #> greater-than #<= less-than-equal #>= greater-than-equal print "I will now count my chickens:" #Adds then divides print "Hens", 25.0 + 30.0 / 6.0 #Subtracts then multiplies then gives percentage? print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 #Counts eggs? p...
''' Input Description You will first input a number N. You will then accept N lines of input in the format: f:force This is a short-form definition; this particular example denotes that the flag -f is equivalent to the flag --force. Lastly you are to accept one further line of input containing the flags and other param...
import networkx as nx import numpy as np import periodictable def fill_hydrogens(graph): """ Function to add hydrogens to a molecular graph. Requires the connectivity matrix, which is used to calculate the number of bonds on each atom. The function loops over each atom, and adds hydrogens until t...
i = 0 while i<10: if(i % 2 == 0): i += 1 continue print(i) i += 1 else: print("Executed else of while")
n = eval(input("Enter number : ")) y = 1 for x in range(2,n+1): y = y * x print(y)
#WAP to accept number of donuts as an input, if no of donuts are gt than 10 then print "No of donuts: many" else print "No of donuts: count" --- actual count noDonuts = int(input("Enter number of donuts : ")) if(noDonuts > 10): print("No of donuts: many") else: print("No of donuts : ", noDonuts)
def lambda_sample(): x = lambda x : x*x print(x(3)) x = lambda y,z: y*z print(x(3,4)) x = lambda y, z : [y*y, z*z] print(x(3,4)) def generator(x): return lambda n:n+x def main(): lambda_sample() generator_of_5 = generator(5) print("generator of 5 : ", generator_of_5(10)) ...
''' wap to accept a string which has repetative characters consecutively and optimize the storage space for the same.. eg. aaabbcccccddddddaaa =>> o/p -> a3b2c5d6a3 ''' def count_chars(str1): cntr = 0 str11 = str1[0:1] cntr = str1.count(str11) return cntr def main(): str1 = input("Enter the string ...
# write a function to add 2,3,4,5 numbers def add(a=0,b=0,c=0,d=0,e=0): print(a+b+c+d+e) def multiply(a=1,b=1,c=1,d=1,e=1): print(a*b*c*d*e) def main(): add(1,2) add(2,4,6) add(1,2,3,4) add(1,2,3,4,5) multiply(2,3) multiply(2,3,4) multiply(2,3,4,5) multiply(2,3,4,5,6) if __name__ == '...
count = 0 string = 'Pushparaj' for letter in string : if letter == 'a' : count += 1 print("Letter 'a' found ", count, " times in '"+string+"'")
''' 1. **** *** ** * 2. **** *** ** * 3. ******* *** *** ** ** * * 4. * *** ***** *** * ''' def pattern1(n): while n: for _ in range(1,n+1): print("*", end='') print() n-=1 def pattern2(n): i = 0 while n: for _ in range(1,i+1): print(" ", end...
# wap to read columns from an excel and create a VCF out of columns import openpyxl from openpyxl import load_workbook def createVCF(row): fd_vcf = open("contacts.vcf",'w') row[0].value def readExcel(filename1): wb = load_workbook(filename = filename1) sheet_ranges = wb[wb.get_sheet_names()[0]] ...
#!/usr/bin/python3 import os import sqlite3 import chegg DB_LOC = "books.db" def insert_book(book): db_connection = sqlite3.connect(DB_LOC) db_cursor = db_connection.cursor() query_string = "insert into books (isbn13, isbn10, isbn, title, edition, author) values (?, ?, ?, ?, ?, ?)" book_data = (book...
import re from utils import is_string def uppercase(string): """ Return a string in uppercase :param string: :return string: Examples:: >>> uppercase("zenofpython") >>> ZENOFPYTHON """ is_string(string) return string.upper() def lowercase(string): """ Return a s...
#!/usr/bin/env python # Author: Christopher Segale # Date: 3/3/2013 def is_divisible_by(n, divisor): return n % divisor == 0 def smallest_multiple(low, high): smallest_multiple = 1 is_loop = True divisor = low while is_loop: while divisor < high + 1: if not is_divisible_by(sma...
#! PAGE 53 #* Working with Lists #* Looping Through an Entire List # You'll often want to run through all entries in a list, performing the same task with each item. # When you want to do the same action with every item in a list, you can use Python's for loop # Let's say we want to print out each name in a list # T...
#* Organizing a List # Often your lists will be created in an unpredictable order # You will often want to present your data in a predictable order # Python provides a number of ways to organize your lists #* Sorting a list permanently with the sort() Method # Pythons sort() method makes it relatively easy to sort a ...
''' Created on 11-May-2021 @author: sumitpuri ''' '''Adding operation''' x = 2+2 print(x) '''Concatenate operation''' name = 'sumit' name = name + ' puri' print(name) '''Print by position''' char = name[3] print(char) char = name[-4] print(char) char = name[0:3] print(char) char = name[-4:-1] print(char) char =...
import sys sys.stdin=open("input.txt","rt") a=input() stack=[] answer='' for x in a: if x.isdecimal(): answer+=x else: #x가 연산자임 if x=='(': stack.append(x) elif x=='*' or x=='/': while stack and (stack[-1]=='*' or stack[-1]=='/'): ...
import sys sys.stdin=open("input.txt","rt") n=int(input()) a=list(map(int,input().split())) def reverse(x): result=0 while x>0 : t=x%10 result=result*10 + t # 앞자리에 0이 올 때를 무시하게 하는 부분 x=x//10 return result def isPrime(x): if x==1: return Fals...
def solve(s): return ' '.join(word.capitalize() for word in s.split(" ")) if __name__ == "__main__": print(solve(input()))
def stairs(n): for x in range(n): n1 = x + 1 print((n - n1) * ' ' + n1 * '#') stairs(6)
def frac(input): pos = 0 neg = 0 zero = 0 for v in input: if v < 0: neg+=1 elif v == False: zero+=1 else: pos+=1 l = len(input) return str(round(pos/l, 5)) + str(round(neg/l, 5)) + str(round(zero/l, 5)) print(frac([5,...
import numpy as np def question2(): a = np.arange(25).reshape(5,5) b = np.array([1., 5, 10, 15, 20])[np.newaxis] c = [] for i in range(0,5): c.append(a[:,i]/b) c = np.array(c).reshape((5,5)).T print 'Question 2: \n', c
n=int(input()) x = n // 5 y = x while x > 0: x /= 5 y += int(x) print(y)
import sys import random import time import matplotlib.pyplot as plt class BFS: def __init__(self, initial_state, n_states): self.OPEN = [] self.CLOSED = [] self.initial_state = initial_state self.n_states = n_states def run(self): """ Main routine of the BFS algorithm....
import sys sys.stdin = open("input.txt", 'r') def quicksort(start, end): if start >= end: return pivot = arr[end] i = start - 1 for j in range(start, end): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[end] = arr[end], arr[i + 1]...
import sys sys.stdin = open("input.txt", 'r') def check_babygin(id, hands): global result hand_size = len(hands) if hand_size >= 3: for num in range(0, 10): if hands.count(num) >= 3: result = id return for num in range(0, 8): if hands...
class Tree: class Position: def element(self): raise NotImplementedError('Must be implemented by subclass') def __eq__(self,other): raise NotImplementedError('Must be implemented by subclass') def __ne__(self,other): return not (self == other) def root(self): raise NotImplementedError('Must be imp...
# Classes and Object-Oriented Programming # Defining Class print("\nSample OOP\n") class SampleClass: # Class Var sample_class_var1 = "Hi" # Initialization Method def __init__(self, sample_var1, sample_var2): # Instance Var self.sample_var1 = sample_var1 self.sample_var2 = sam...
def passwordgen(passwordlength=8): from random import randrange lowercase = "abcdefghijklmnopqrstuvwxyz" uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers = "0123456789" symbols = "!@#$%^&*()?" chars = lowercase + uppercase + numbers + symbols while True: pw = "" lowc_bool = F...
""" A class used to represent the search algorithm for Dots and Boxes Attributes ------- self.descendants: List A list containing the unique descendants of the board position passed into getMove Methods ------- swapSides(self, box, swap_type=0) Code used to swap...
#!/usr/bin/python import operator class TablePrinter(object): "Print a list of dicts as a table" def __init__(self, fmt, sep='', ul=None, tl=None, bl=None): """ @param fmt: list of tuple(heading, key, width) heading: str, column label key: dictio...
from code.algorithms.astar import Astar import copy import random class HillClimber(): """ Tries to improve current solution, by taking a random wire and laying it again differently. """ def __init__(self, chip, output_dict, heuristic): self.chip = chip self.heuristic = heuristic self.output_dict = copy.dee...
# https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1 import sys def Factorial(x): f=1 if x==0: f=1 elif x==1: f=1 else: for i in range(1,x+1): f=f*i return f x=14 print(Factorial(x)) def LargeFactorial(n): res=[None]*500 res...
# https://leetcode.com/problems/reverse-string/ def reverseString(arr): n=len(arr) l=0 r=len(arr)-1 while l<r: arr[l],arr[r]=arr[r],arr[l] l+=1 r-=1 return arr a1=['h','e','l','l','o'] print(reverseString(a1))
# https://leetcode.com/problems/find-the-duplicate-number/ def Duplicate(arr): arr.sort() n=len(arr) i=0 for i in range(n): if arr[i]==arr[i+1]: return arr[i] arr=[1,3,4,2,2] print(Duplicate(arr)) # Floyd cycle def twoPointerApproach(arr): fast=arr[0] slow=arr[0] ...
def MergeIntervals(intervals) : intervals.sort() result=[] curr=intervals[0] for next in intervals: if max(curr)>=min(next): curr=[curr[0],max(curr[1],next[1])] else: result.append(curr) curr=next result.append(curr) return resul...
class Node: def __init__(self,data): self.data=data self.next=None self.prev=None class DoubleLinkedList: def __init__(self): self.head=None # insert at front def Push(self,key): new_node=Node(key) new_node.next=self.head if self.head is not Non...
# https://practice.geeksforgeeks.org/problems/minimize-the-heights3351/1 def MinimiseMaxHts(arr,k): x=min(arr) y=max(arr) y=y-k x=x+k diff=y-x return diff arr=[3,9,12,16,20] k=3 print(MinimiseMaxHts(arr,k))
""" Longest Path Approximation """ import data_structure as ds import copy import utility import time import dag def modified_bfs(graph, s): """take in a graph and the index of the starting vertex; return a list of longest distance to every vertex and path""" vertices = graph.vertices dist = [] path = [] queue...
a=int(input("number1")); b=int(input("number2")); print(a,"+",b,"=",a+b); print(a,"-",b,"=",a-b); print(a,"*",b,"=",a*b);
# Решение задачи "Time Converter (24h to 12h)" в пайчекио # Автор - M. Batanov, 11.09.19 def time_converter(time): hours = int(time[0] + time[1]) result = time[2:5] if hours > 11: if hours != 12: hours = hours - 12 result = str(hours) + result + ' p.m.' else: if hou...
# Решение задачи "Digits Multiplication" в пайчекио # Задача: py.checkio.org/ru/mission/digits-multiplication/ # Автор: M. Batanov, 14.09.19 def checkio(number: int) -> int: multiplication, numb = 1, list(str(number)) for element in numb: if int(element) != 0: multiplication = multiplicati...
# Решение задачи "Friends" в пайчекио # Задача: py.checkio.org/mission/friends/ # Автор: M. Batanov, 26.09.19 class Friends: def __init__(self, connections): self.connections = list(connections) def add(self, connection): if connection in self.connections: return False el...
from random import randint options = ["Piedra", "Papel", "Tijeras"] # El resultado de salida son las siguientes String #'Empate!' #'Ganaste!' #'Perdiste!' def quienGana(p_player, p_ai): resultados = ['Empate!', 'Ganaste!', 'Perdiste!'] player = p_player.lower ai = p_ai.lower if player == ai: ...
# naiveBayes.py # ------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klein (kle...
import random def fact(n: int): """A recursive implementation of factorials. Calculates factorial of n. Precondition: n is a positive integer or 0. """ if n == 0: return 1 else: return n * fact(n - 1) def main(): num = random.randint(1, 10) print(f'The factorial of {nu...
num = input() if num%2==0: print "Even" else : print "Odd"
import pandas as pd df = pd.DataFrame({"A": [1,2,3,5,6,7,7,8], "B": [2,4,8,8,8,9,9,9]}) def add_square(df, col): df = df.assign(C = df[col]**2) # a function that adds a squared version of a specific column to a dataframe return df
#!/usr/bin/python3.6 class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def print(self): print("<%d>" % self.val, end='') class BinaryTree: def __init__(self): self.root = None def buildTree(self, preOrder, inOrder): def build...
#Anthony Jordan import random number = random.randint(1,15) chances = 0 print("Pick a number between 1-15:") while chances < 5: guess = int(input("Enter your number:")) if guess == number: print("Yay! you picked the correct number.") exit() elif guess< number: prin...
""" Perform required operation based on number of digits """ # Implement the helper functions here def reminder(num): if num<10: return (num) elif num>=10: num_rem=num%10 return (num_rem) def do_1digit_oper(num): oper_number=num+7 print("After adding 7 to 1 digit number, resul...
""" Using the starting and ending values of your car’s odometer, calculate its mileage """ def sub(num1, num2): diff=float(num1-num2) return diff def divide(num1, num2): division=float(num1/num2) return division def multiplication(num1, num2): product=float(num1*num2 ) return prod...
def run_statistics(ball_face_result , total_ball): dot_count = 0 total_run = 0 boundaries = 0 sixes = 0 for i in range (total_ball): if ball_face_result[i] == ".": dot_count = dot_count+1 continue total_run = total_run + int(ball_face_result[i]) if bal...
''' Write a program that generates a HTML webpage. Prompt the user for webpage title and webpage body contents. The webpage body should contain - one main header, - one sub header, and - at least 2 paragraphs. ''' template = ''' Webpage.html <html> <head> <title> {MyWebpagetitle} </title> </head> ...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] print (class_1) class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] print (class_2) new_class = class_1 + class_2 print (new_class) new_class.append('Peter Warden') print (new_class) new_class.r...
import itertools import fractions from utils import digit def e_sequence(): for n in itertools.count(1): yield 1 yield 2 * n yield 1 def build_frac(seq, depth): if depth == 1: return 0 a = next(seq) f = build_frac(seq, depth - 1) return fractions.Fraction(1, a + f)...
from utils import prime from utils import digit def rotate_digits(digits): digits.append(digits.pop(0)) def is_circular_prime(p): digits = digit.split(p) for _ in range(len(digits) - 1): rotate_digits(digits) if not prime.contains(digit.join(digits)): return False ...
from utils.general import * def is_pythagorean_triplet(a, b, c): return a * a + b * b == c * c def find_triplet_from_sum(n_sum): for c in range(1, n_sum + 1): for b in range(1, n_sum + 1): a = n_sum - b - c if is_pythagorean_triplet(a, b, c): return a, b, c pri...
def sum_squares(n): return sum(i * i for i in range(1, n + 1)) def square_sum(n): n_sum = sum(range(1, n + 1)) return n_sum * n_sum def sum_square_diff(n): return square_sum(n) - sum_squares(n) print(sum_square_diff(100))
import itertools def t(n): return (n * (n + 1)) // 2 def p(n): return (n * (3 * n - 1)) // 2 def h(n): return n * (2 * n - 1) def contains_func(f): largest = -1 i = -1 known = set() def contains(val): nonlocal largest, i while val > largest: i += 1 ...
from utils import cache from utils import digit def sum_digit_squares(n): return sum(d * d for d in digit.split(n)) def chain_end(n): if n == 1 or n == 89: return n else: return cached_chain_end(sum_digit_squares(n)) cached_chain_end = cache.deterministic(chain_end) def count_89s(upper_b...
zero_to_nineteen_str = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ] tens_str = [ "twenty", "thirty", "forty", "fifty", ...
kisiler = [] class Person: firstname = "", lastname = "", phone = "", mail = "", id = "", def __str__(self): return "{} {}".format(self.firstname ,self.lastname) def Bul(self,kelime): if kelime in self.firstname or kelime in self.lastname or kelime in self....
arr=[];arr2=[] n=int(input()) for i in range(n): s=input() sc=float(input()) arr.append([s,sc]) arr2.append(sc) m=max(arr2) for i in range(len(arr2)): try: arr2.remove(m) except: arr2=arr2 x=max(arr2) for i in range(n): if arr[i][1]==x: print(arr[...
#한줄 for #students = [1,2,3,4,5] #print(students) #students = [i+100 for i in students]#i에다가 100을 더한 값을 students에 있는 값을 불러와 students에 넣음 #print(students) students = ["Iron man", "Thor", "I am groot"] students = [len(i) for i in students] print(students)
for i in [0,1,2,3,4,5]: #loop through a small iteration using list print(i) for i in range(6): #if say we have to loop through many iterations say 100 or 1000 then defining a list is cumbersome print(i) names = ["Honey", "Seena", "Anu", "Shiva"] #loop through a list to print items in alist for na...
helpText=''' <html> <head> <title>Help</title> </head> <body> <h1>About this program</h1> <p>This program provides you with a general graphical user interface for your python program. Specifically,it takes charge of displaying measured values to LCD displays, drawing graphs,creating a data file and writ...
from tkinter import * root = Tk() root.title("Ejemplo") # Inicializando variables playa = IntVar() montana = IntVar() turismoRural = IntVar() # Funcion para indicar cuales se han seleccionado def opcionesViaje(): opcionesEscogida = "" if playa.get() == 1: opcionesEscogida += " playa" if monta...
# POLIMORFISMO --> Sirve para comunicarse con clases diferentes # y dependiendo de la clase, su comportamiento sera diferente # CLASE 1 class Coche: def desplazamientos(self): print("Me desplazo utilizando 4 ruedas") # CLASE 2 class Moto: def desplazamiento(self): print("Me ...
# SINTAXIS DE LA EXCEPCION RAISE PARA CREAR NUESTRAS PROPIAS EXCEPCIONES PARA LAS CLASES, HERENCIAS, ETC... def evaluarEdad(edad): if edad < 0: raise TypeError("No se permite edades negativas") # Para lanzar una excepcion propia if edad < 20: return "eres muy joven" elif edad < 40: ...
# ------------------------------------------------------ # reads the speeds in the specified file (filename) # and returns them as a list of integers # ------------------------------------------------------ def readData(filename): file = open(filename) speedlimit = [] for line in file: num = int(li...
#!/usr/bin/python3 while True: enter = float(input("入场价: ")) isLong = input("开多输入y,其它都是空: ") risk = float(input("风险率,建议2.0以下: ")) rr = [3,5,8,10]#Reward/Risk tp = []#Take Profit if isLong == "y": for i in rr: tp.append(enter*(1.0+i*risk*0.01)) sl = enter*(1-0.01*risk) print("开多: {:9.3f}$".format(ente...
# tutaj napisz funkcję z zadania 1 def multiply(subject,times): return subject * times # poniższe linijki przetestują Twoją funkcję: print("100 * 100 =", multiply(100, 100)) # 10000 print("2 razy 2 to", multiply(2, 2)) # 5? ;-) print("15 * 10 =", multiply(15, 10)) # 150 print("10 * Małpa =", multiply( 10,"Ma...
import random size = random.randint(3,9) print(size) for x in range(size): for x in range(x+1): print("*",end="") print("\n",end="") print("--------------------------") for x in range(size): for x in range(size-x): print("*", end="") print("\n", end="")
import random rows = random.randint(5,15) columns = random.randint(5,15) print("Wartość zmiennej rows:",rows) print("Wartość zmiennej columns:",columns) for item in range(rows): for item in range(columns): print("*",end="") print("\n",end="")
from tkintertable import TableCanvas, TableModel from tkinter import * import tkinter as tk # Class in charge of creating, displaying and manipulating table class App(Frame): """Basic test frame for the table""" data = {} table = TableCanvas def __init__(self, parent=None): self.table = Table...
import time import datetime import random while True: time.sleep(random.randint(1, 5)) t = datetime.datetime.now() # == int(time.time) print(t.second, '초 - ', sep='', end='') print("짝수 초" if t.second % 2 == 0 else "홀수 초") # random, time, calendar 모듈 3개를 모두 활용한 예제 프로그램
def calc(): x = 0 while True: w = (yield x) a, oper, b = w.split(' ') if oper == '+': x = int(a) + int(b) elif oper == '-': x = int(a) - int(b) elif oper == '/': x = int(a) / int(b) elif oper == '*': x = int(a) * int...
""" 블로그포스팅 : https://bodhi-sattva.tistory.com/62 """ a = 10 b = 6 print(a + b, a - b, a * b, a / b, a ** b, a // b, a % b) """산술연산자 사칙연산(+,-,/,*)말고도 제곱(**), 몫(//), 나머지(%)연산자도 있다. """ a += 10 print(a) a -= 10 print(a) a *= 2 print(a) a /= 2 print(a) a **= 2 print(a) a //= 10 print(a) a %= 2 print(a) """대입연산자 익히 쓰는 단순대...
# for x1, x2, y in [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)]: # print(x1, x2, '|', y) # """ # == for x1, x2 in [(0,0), (0,1), (1,0), (1,1)]: # print(x1, x2, '|', x1 and x2) # 의 코드로도 같은 실행 결과를 볼 수 있다. (리스트 안의 값이 두 변수의 and 연산 결과를 가지고 있다.) # """ test = [[1, 2], [3, 4], [5, 6]] print([n2-n1 for n1, n2 in test...
# 별찍기 문제 (직각삼각형 상하좌우대칭) n = int(input("높이를 입력하시오 : ")) for i in range(n, 0, -1): print(f"{'*'*i : >10}")
def lock_(a): for i in range(len(a)): if 91 > ord(a[i]) > 64: a[i] = chr(ord(a[i])+n) if 96 < ord(a[i]) < 123: a[i] = chr(ord(a[i])+n) def unlock_(b): for i in range(len(b)): if 91 > ord(b[i]) > 64: print(chr(ord(b[i])-n), end='') if 123 > or...
import sys print("뭔""차이여") print("뭔", "차이야") print("뭔" + "차인겨") """print()함수: c언어의 printf()함수 처럼, 파이썬에서 화면에 뭔가를 띄우려면 반드시 사용하는 함수는 print()다. 여기서 프린트에서 같은 따옴표로 묶은 문자열을 연달아 놓거나, +로 문자열 결합을 해준채로 출력하면 공백없이 나온다. (+로 숫자, 문자를 더하면 에러난다) 아니면 ,을 사용해서 한칸의 공백으로 다른 요소를 같이 출력할 수 있다. (문자열을 입맛에 맛게 출력하려면 문자열자료형에 붙인 설명을 참고해라) """ num = ...
data = [1, 2, 3, 4] print(data, [n+1 for n in data], [n for n in data if n % 2 is 0], sep='\n', end="\n"*2) """ 리스트 내포: 리스트 컴프리헨션(list comprehension), 리스트 내장, 리스트 축약, 리스트 해석이라고도 하는데, 리스트 안에 for 반복문이나 if 조건문을 사용하는 파이썬만의 리스트 표현식이다. * [n+1 for n in data] for 반복문을 복습하자면, 반복되는 여러가지 요소들(data)에서 요소를 하나하나 차례대로 변수(n)에 가져와서 반복...
# 별찍기 문제 (정삼각형) n = int(input("폭을 입력하시오 : ")) for i in range(1, n+1, 2): print(f"{'*'*i : ^10}") # print(f"{format('*'*(i), '^10'}") 과 같다.
from 中文分词 import IMM from 中文分词 import MM # 双向最大匹配(将选取词数切分最小) if __name__ == '__main__': text = '南京市长江大桥!' path_dic = 'data/1-imm_dic.utf8' tokenizer_IMM = IMM.IMM(path_dic) tokenizer_MM = MM.MM(path_dic) # 逆向最大分词 result_IMM = tokenizer_IMM.cut(text) # 正向最大分词 result_MM = tokenizer_MM....
class Auth: def __init__(self, username, password): self.__username = username self.__password = password @staticmethod def login(data): if data['username'] == "root" and data['password'] == "secret": self.__username = data['username'] self.__password = data...
# -*- coding: utf-8 -*- """ Created on Tue Jan 19 13:18:44 2016 @author: s621208 """ """ To improve score : - Use a better machine learning algorithm. - Generate better features. - Combine multiple machine learning algorithms. """ """ # Implimenting Random Forest """ from sklearn import cross_valida...
class time: def __init__(self,hrs,mins): self.hrs = hrs self.mins = mins def addTime(t1,t2): t3 = time(0,0) if t1.mins + t2.mins > 60: t3.hrs = (t1.mins + t2.mins)/60 t3.hrs = t1.hrs + t2.hrs + t3.hrs t3.mins = (t1.mins + t2.mins) - ((t1.mins + t2.min...
#-------4. Break and Continue Game----------- print("Enter Positive Number to play and Negative Number for End game ") while True: userEnter = int(input("Enter your Number: ")) if (userEnter > 0): print("Good Going!") continue elif (userEnter < 0): print("It's Over!") break ...