text
stringlengths
37
1.41M
""" Huffman Algorithm: Huffman algorithm is used to compress data. It is a lossless compression algorithm. So no data is lost between compression and decompression. Heart of the algorithm relies on using less bits to represent most frequent letters, and more bits to represent less frequent letters. Below is the genera...
#!/usr/bin/env python class xml_block_iterator: '''looping over a big file, generate xml block''' def __init__(self, inf): self.inf = inf self.xml_block = '' def __iter__(self): return self def next(self): self.read() return self.xml_block def read(self): self.xml_block = '' line = self.inf.readli...
# จะแก้ไข main.py ให้ใช้ไฟล์ main_playground.py ก่อน # copy main.py แล้วเล่นตามสบาย import time import calendar from tkinter import * from tkinter import ttk # ตรวจสอบเวลา class Setday(): # เช็คเวลาปัจจุบัน timer = time.localtime() # แปลงเป็นปี year = timer.tm_year # แปลงเป็นเดือน month = time...
# import image utilities import os import numpy as np import cv2 images_path = './images/temp' # define a function that rotates images in the current directory # given the rotation in degrees as a parameter def rotateImages(): for f_name in os.listdir(images_path): file_path = os.path.normpath(os.path.join(ima...
import random class Point: def __init__(self, initX, initY): """ Create a new point at the given coordinates. """ self.x = initX self.y = initY def getX(self): return self.x def getY(self): return self.y def distance(self, p2X, p2Y): x...
from __future__ import annotations from typing import List from random import shuffle EPSILON = 1e-4 class Point: def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, p: object) -> bool: return isinstance(p, Point) and self.x == p.x and self.y == p.y def __sub__...
#!/usr/bin/python3 from queue import Queue, Empty from intcode import IntcodeProgram from exceptions import WaitingForInput, ProgramHalted class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'({self.x},{self.y})' def __repr__(self): re...
#!/usr/bin/python3 import math def parse_input(): """ Parse input.txt to list of masses """ masses = [] with open('input.txt', 'r') as input: for mass in input: masses.append(mass.strip()) return masses def calculate_fuel(masses): """ Calculat...
# Exercise 15: Reverse Word Order string = input('Please input a sentence: ') def reverser(arg): splitter = string.split() result = [] for item in splitter: result = splitter[::-1] return ' '.join(result) print(reverser(string))
# Exercise 32: Hangman import random with open('sowpods.txt', 'r') as open_file: content = open_file.read().lower().split() line = random.choice(content) lst = list(line) print(line) hangman = '*' * len(line) print(hangman) print(str(len(line)) + ' letters') turn = 0 last_guess = '' def handsomema...
# Exercise 07: List Comprehensions a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]; # Target is to get the even elements in ONE line. lst = [x for x in a if x % 2 == 0]; # Syntax of list comprehension print(lst)
# Exercise 28: Max Of Three print('[Enter break,, to break]') a, b, c = input('Input three numbers, followed by comma: ').split(',') if a > b and a > c: print(str(a) + ' is the largest number of the three') elif b > a and b > c: print(str(b) + ' is the largest number of the three') elif c > a and c > b...
# Exercise 18: Cows And Bulls import random num = str(random.randint(1,9)) while len(num) < 4: rand = str(random.randint(0,9)) if rand not in num: num += rand print(num) ### Must delete later def cow_and_bull(ans,gue): cow_count = 0 bull_count = 0 for i in an...
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 11:24:42 2014 @author: YOUR NAME HERE """ # you may find it useful to import these variables (although you are not required to use them) from amino_acids import aa, codons, aa_table import random from load import load_seq def shuffle_string(s): """ Shuffles the ...
'''Day14-1_02-MajorElement''' #Pumpsama def majorelement(value): '''Find most many numbers.''' value = value.split(",") answer = "" for loop in xrange(len(value)): if not value[loop] in value[:loop]: if value.count(value[loop]) > len(value)/2.0: answer = va...
'''Day14-1_03-SentenceAnalyze''' #Pumpsama. def sentenceanalyze(word): '''Sort dictionary and print how many of splited words''' word = word.split() word.sort() for loop in range(len(word)): if not word[loop] in word[:loop]: print word[loop] + ":" + str(word.count(word[loop...
p = input() if p >= 0 and p <= 49: print "F" elif p >= 50 and p <= 59: print "D" elif p >= 60 and p <= 69: print "C" elif p >= 70 and p <= 79: print "B" elif p >= 80 and p <= 100: print "A" else: print "Error"
'''Graderrrrrrrrrrr''' #Comment def grader(point): ''' score >= 80 : A score 70-79 : B score 60-69 : C score 50-59 : D score < 50 : F ''' if point >= 80: return "A" else: if point >= 70 and point <= 79: return "B" else: if point >= 60...
"""Training_sord""" def num_sorr(num): """Return Sord number""" num_list = [input() for _ in xrange(num)] num_sord = quicksord(num_list) for number in num_sord: print number def quicksord(lst): """return List already sord""" if not lst: return [] return (quicksord([x for x in...
"""Nokia Legends 3310""" def sms3310(number): """Change word to a phone number clicker.""" nokia = {"a" : "2", "d" : "3", "g" : "4","j" : "5", "m" : "6", \ "p" : "7", "t" : "8", "w" : "9", " " : "0"} nokia2 = {"b" : "22", "e" : "33", "h" : "44", "k" : "55", \ "n" : "66", "q" : "77", "u" : ...
'''integerORfloat''' #Comment def check(value): '''Check int of float''' if type(value) == int: return "integer" elif type(value) == float: return "float" print check(input())
x1 = input() y1 = input() r1 = input() x2 = input() y2 = input() r2 = input() ra = r1 + r2 compar = ((x1 - x2)**2 + (y1 + y2)**2)**0.5 if compar <= ra: print "overlapping" elif compar > ra: print "no overlapping"
"""Total Circular Prime""" def cirprime(number): """Check is it Circular Prime""" numchecker = str(number) for _ in xrange(len(numchecker)): if not isprime(int(numchecker)): return 0 numchecker = numchecker[1:] + numchecker[0] return number def isprime(numcheck): """Chec...
"""Palindome""" ##Comment def palin(number): """Palindome""" for string in xrange(number): string = raw_input() if string[::1] == string[::-1]: print string palin(input())
"""Factorial_ial_ial""" ####Commnet def factor(number, fac): """Find Factorial sum""" numbersum = number for i in reversed(xrange(1, number, len(fac)): if i <= 0: pass else: count = i numbersum = numbersum * count print numbersum factor(abs(input()), raw_i...
""" This program find number of battery that need to charge""" def volt_check(n_batt, v_target): """ int -> int """ i = 1 volt = [] vbatt = input() while i<= n_batt : volt.append(input()) i = i+1 print volt total = 0 for x in xrange(1,len(volt)): if volt[x] < volt...
day1 = raw_input().lower() day2 = raw_input().lower() if day1 == true: if day2 == true: print "True" if day2 == false: print "False" if day1 == false: print "True"
"""SimpleSort""" ###Comment def sort(word): """Print sort number""" wordlist = map(float, word.split()) wordlist.sort() for i in wordlist: print "%.3f" % i, sort(raw_input())
"""TEST WRITer""" def writer(sen): """Return Money to get back in thai bath""" lensen = len(sen) if lensen <= 10: print "Pr!ze:=> 0 bAtH" elif lensen >= 11 and lensen <= 30: print "Pr!ze:=> " + str(lensen*1.23) + " bAtH" elif lensen >= 31 and lensen <= 50: print "Pr!ze:=> " +...
"""Check 90 Triangle""" def triangle(side1, side2, side3): if long1 + long2 < long3: return "NO" elif long1 + long3 < long2: return "NO" elif long2 + long3 < long1: return "NO" else: return "YES" triangle(int(raw_input()), int(raw_input()), int(raw_input()))
'''Collatz''' ###comment num1 = input() print num1 while num1 != 1: if num1 % 2 != 0: num1 = 3*(num1)+1 print num1 else: num1 = num1/2 print num1
"""MEOW PAT""" def patland(number): for loo in xrange(1 ,number+1): city = raw_input() casenum = str(loo) text = city[len(city)-1:] while True and text != 'a' or text != 'e' or text != 'i' or \ text != 'o' or text != 'u' or text != 'y': print "Case #" ...
"""Line Sort""" def sortline(number): """SORTED""" lsit = [] for i in xrange(number): word = raw_input() lsit.append(word) lsit.sort(key=len) for i in xrange(len(lsit)): print lsit[i] sortline(input())
"""Multiply|Recursion""" #COMMENT def multiply(number1, number2): """Multiply Number""" if number1 >= 0 and number2 >= 0: #+,+ if number1 > 0: return multiply(number1-1, number2) + number2 elif number1 < 0 and number2 > 0: #-,+ if number1 < 0: return multiply(number1+...
"""HW_HPS""" def hps(): """Return Winner of this games""" condition_type = [["H - H", "P - P", "S - S"], ["H - S", "P - H", "S - P"]] a_win, b_win, draw, round_att = 0, 0, 0, 1 while True: atttempt = raw_input() if atttempt in condition_type[0]: draw += 1 if draw ...
"""Quiz_ChristmasTree""" def tree(leaf, stem): """ Return ChristmasTree With tall(leaf+stem) """ for i in xrange(leaf): print " "*(leaf-i-1) + "*"*(2*i+1) for tall in xrange(stem): tall = leaf print " "*(tall-2)+"-"*3 tree(input(), input())
# fibonacci function import time def fib(): n = int(input("How many Fibonacci numbers you want: ")) result = [] fib1 = fib2 = 1 if n == 0: print("Incorrect value") elif n == 1: result.append(fib1) else: result.append(fib1) result.append(fib2) for i in ra...
import time # def timer(func): # def wrapper(*args): # start = time.time() # print('start time', start) # target = func(*args) # end = time.time() # print('end time', end) # print('timer.Function execution time in seconds:', round(end - start, 6)) # print('t...
"""Un empresa paga a sus vendedores de la siguiente manera: Sueldo fijo $ 360.40 más un porcentaje de las ventas realizadas en el mes. Si las ventas fueron menores o iguales a $ 500, el porcentaje es de 5% Si las ventas fueron mayores a $ 500 y menores o iguales a $1000, el porcentaje es de 8% Si las ventas fueron mayo...
# -*- coding: utf-8 -*- """ author: Emre Mutlu Date: Sat Feb 22 22:06:51 2020 """ def fibonacci(n): liste=[1,1] while len(liste)<n: liste.append(liste[-1]+liste[-2]) return liste[-1] def fibrecursion(n): if n==1 or n==2: return 1 else: return fibrecursion(n-...
"""Drawing forests in a loop.""" __author__ = "123456789" # The string constant for the pine tree emoji TREE: str = '\U0001F332' depth = int(input("Depth: ")) s: str = "" i: int = 0 while depth > i: trees = i while trees == i: s = s + (TREE) trees = trees - 1 i = i + 1 print(s)
counter: int = 0 maximum: int = int(input("count up to what?")) while counter <= maximum: counter_sqaured: int = counter ** 2 print("The square of " + str(counter) + " is " + str(counter_sqaured)) counter = counter + 1 print("Done")
# coding=utf-8 # @Time : 2020/8/12 9:21 # @Author : 胡泽勇 # 概念对象,通过Class Level构建自己的数据体系 import inspect from data import Data class Property(Data): def __init__(self, pt, default=None, required=False): """ 属性对象,为Concept对象在Class Level声明字段 @param pt: 属性对象的类型,如果设置为None,则直接将设置的值不通过任...
# coding=utf-8 # @Time : 2020/8/8 9:50 # @Author : 胡泽勇 # 数据对象 class Data(object): """ 数据对象,主要是为子类提供转化字符串的方法 """ def __repr__(self): return '<{0}>{1}'.format(type(self).__name__, str(self.__dict__)) __str__ = __repr__ class Prototype(object): def __init__(self, dic=None, **kwargs): ...
def median(l): a = sorted(l) # if odd length list, return middle index if len(a) % 2 != 0: return a[int((len(a)/2.0)-0.5)] # if even length list, return average of middle 2 indexes else: return (a[int((len(a)/2.0)-1)] + (a[int((len(a)/2.0))])) / 2.0
# citibike_populate.py # Andrew Maner # Pull data from citibike, create a reference table for all stations, and # create a table of available bikes keyed on execution time (time of pull) # insert reference info and insert available bikes # repeat every 60 seconds for an hour (last part) import requests from pandas.io....
class Person(object): def __init__(self,name): self.name = name self.pet = None class Employee(Person): def __init__(self,name,salary): super(Employee,self).__init__(name) self.salary = salary hh = Employee('hihi',110) print hh.salary
import random import time import datetime def Do_again(): Use=str(input("Do you want to use the program again? (Yes/No) ")) if Use=="No": return False return True def Enter_dateagain(): Newdate=str(input("Do you wish to enter a new date? (Yes/No) ")) if Newdate=="No": retu...
import random bal = random.randint(10000,90000) balreal = bal debt = random.randint(900,1000) debtreal = debt class Atm(object): def __init__(self,card,pin,): self.card = card self.pin = pin def getattributes(self): print(self.card, self.pin) def check_balance...
import nacl.pwhash from nacl import pwhash, encoding p = open("passwords.txt", "r") # open the file with the users and the hashed passwords, for read count1 = 0 salt = bytes(32) # setting salt for hash function size = pwhash.scrypt.BYTES_MIN #setting size for hash function us = '' for line1 in p: # rea...
class Solution: def connect(self, root: 'Node') -> 'Node': old_root = root prekid = Node(0) kid = prekid # Let kid point to prekid while root: while root: if root.left: kid.next = root.left kid = kid.next ...
from typing import List class Solution: def maxProduct(self, nums: List[int]) -> int: res = small = big = nums[0] print("n:", nums[0], "small:", small, "big:", big, "res:", res) for n in nums[1:]: big, small = max(n, n * big, n * small), min(n, n * big, n * small) ...
from typing import List class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: self.res = [] subset = [] # self.res.append(subset) self._subsets(nums, subset) return self.res def _subsets(self, nums: List[int], subset: List[int]): # print("[star...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None while head: current = head head = head.next current.next = prev prev = current ...
from typing import List class Solution: def distributeCandies(self, candies: int, num_people: int) -> List[int]: people = num_people * [0] give = 0 while candies > 0: people[give % num_people] += min(candies, give + 1) give += 1 candies -= give r...
from queue import Queue # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root queue = [] ...
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: inor_map = {} for i, n in enumerate(i...
from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: return self._sm(matrix, 0, 0, target) def _sm(self, matrix, i, j, target): if len(matrix) - 1 < i or len(matrix[0]) - 1 < j or matrix[i][j] is None or matrix[i][j] > target: ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head): if head is None: return True fast = slow = head while fast and fast.next: slow = slow.next ...
from itertools import permutations from math import ceil from typing import (Iterator, Collection) from utils import (digits_to_number, number_to_digits) def pandigital_multiples(digits: Collection[int]) -> Iterator[int]: position_stop = ceil(len(digits) / 2) for digits...
from itertools import combinations from typing import (Union, Iterable, Tuple) from utils import (prime_numbers, number_to_digits) def prime_digit_replacements(stop: int) -> Iterable[int]: numbers = list(prime_numbers(stop)) numbers_digits = map(tupl...
from fractions import Fraction from itertools import (count, islice) from typing import Iterable from utils import number_to_digits def continued_fraction() -> Iterable[int]: yield 2 for index in count(1): yield 1 yield 2 * index yield 1 def convergent(index: ...
with open("namelist.txt") as file: print("All Students") print() print("Name\t\tYear\t\tAge\tGPA") print("====================================================") for line in file: print(line.strip()) file.close() print("\n\n") with open("namelist.txt") as file: print("Freshman Students"...
import Attribute class Structure: def __init__(self,path): self.classAttribute = None self.attributes = [] self.readFile(path) if len(self.attributes) == 0: raise Exception("There must be attributes") if self.classAttribute is None: raise Exception("...
""" py thread """ import threading import time counter = 2 counter_lock = threading.Lock() def do_it() -> None: """ do it """ global counter with counter_lock: x = counter #time.sleep(1) x = x - 1 counter = x def run() -> None: """ run """ print(f"start coun...
"""Provides the History class. The History class is the primary data structure of the Calc App program. It stores the history of math operations performed with the calculator. Typical usage example: history = History(calc_ops)<br> history.append("add", 2.0) """ from functools import reduce from mixins.json_m...
#!/usr/bin/env python3 import sys def ints(itr): return [int(i) for i in itr] with open(sys.argv[1], "r") as f: lines = [l for l in f.read().split("\n") if l] ilist = [] imap = {} total = 0 result = 0 other = 0 while True: lcs = {} tiles = [] for l in lines: x = 0 y = 0 ...
from tkinter import * def aparecer(): root = Tk() label_1 = Label(root, text='texto') entry = Entry(root) Button1=Button(root, text='boton') label_1.place(x=10, y=10) entry.place(x=0, y=2) Button1.place(x=0, y=4) root.mainloop() mainRoot=Tk() boton= Button(mainRoot, text='click', ...
class Folder: #Birth format: '01/01/1994' and we can work with it just by splitting the / def __init__(self, name=''): self.name = name #self.rootFolder = rootFolder #self.date = date #self.description = description def getJSONforFolder(self): data = { ...
import numpy as np import math from tensorflow.examples.tutorials.mnist import input_data import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np from PIL import Image import PIL.ImageOps as ImageOps # The input layer has 784 nodes # The output layer has 10 nodes # 3 layers: Input layer, h...
def quickSort(alist,blist): quickSortHelper(alist,0,len(alist)-1,blist) def quickSortHelper(alist,first,last,blist): if first<last: splitpoint = partition(alist,first,last,blist) quickSortHelper(alist,first,splitpoint-1,blist) quickSortHelper(alist,splitpoint+1,last,blist) def partiti...
import pytest def rotate(string, n): """Rotate characters in a string. Expects string and n (int) for number of characters to move. """ if type(n) != int: return "Not an integer" if n == 0: return string if n > 0: s_new = string[0:n] l = list(s...
from RPS_Classes import Roll, Player import random def main(): print_header() #rolls = build_the_three_rolls() # TODO: figure out what this function should do name = get_players_name() player1 = Player(name) player2 = Player("computer") game_loop(player1, player2) def pr...
#2-1 message = "Hello world!" print(message) #2-2 message = "Hello new world!" print(message) #2-3 name = "Eric" print("Hello "+name+", would you like to learn some Python today?") #2-4 name = "zeng yin" print(name.lower()) print(name.upper()) print(name.title()) #2-5&2-6 name = 'Albert Einstein' word = ' once said, "A...
import re numregex = r'[-+]?[0-9]{0,3}(?:(?:\.[0-9]+)|(?:[0-9]+))' class PointHelper: @staticmethod def validate_latlng(lat, lon): is_valid = True # if lat is None: # print("lat is None: {lat}".format(lat=lat)) if not re.search(numregex, str(lat)): ...
a=0 b=1 x=int (input("enter the number")) print('0') for i in range (0,x): c=a+b a=b b=c print(c)
x = int(input("enter the number")) y = int(input("enter the second number")) if x>y: min=y else: min=x for i in range(min,1,-1): if x%i == 0 and y%i == 0: gcd = i break print(gcd)
#!/usr/bin/python for x in range(1,10): if x == 1: print("one") elif x == 2: # notice this is elif not else if print("two") else: print("not one or two")
def func( a ): return a * 10 def do_stuff( b ): c = func( b ) print( b, c ) x = 0 while x < 10: do_stuff( x ) x = x + 1
""" A double ended linklist is a linklist that has information both of its previus and next objects A <--> B <--> c <--> D Its mostly used in creating double ended queue""" ## ------------------------- ## Author : - Abhishek Hazra ## ------------------------- ## A class that can represents a node in the link ...
from .helpers import test_runtime def bubble_sort(a_list): number_of_passes = len(a_list) - 1 is_sorted = False while number_of_passes > 0 and not is_sorted: is_sorted = True for pos in range(number_of_passes): if a_list[pos] > a_list[pos+1]: is_sorted = False ...
from stack import Stack def sym_checker(symbol_str): """takes string with returns true if symbols balanced""" syms = {'(': ')', '[': ']', '{': '}'} s = Stack() for sym in symbol_str: if sym in syms.keys(): s.push(sym) elif sym in syms.values(): if syms[s.peek()]...
def binary_search(alist, item): found = False while not found and len(alist) > 0: mid_point = len(alist) // 2 if alist[mid_point] == item: found = True elif alist[mid_point] < item: alist = alist[mid_point + 1:] else: alist = alist[:mid_point]...
""" Write two Python functions to find the minimum number in a list. The first function should compare each number to every other number on the list. O(n2). The second function should be linear O(n). """ # O(n2) def min1(thelist): for i in thelist: for j in thelist: if j < i: ...
lista_initiala = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6 ] print(f'Lista intitiala este: {lista_initiala}') crescator = lista_initiala.copy() crescator.sort() print(f"Lista aranjata ascendent: {crescator}") descrescator = lista_initiala.copy() descrescator.sort(reverse=True) print(f"Lista ananjata descrescator: {descresc...
height = float(input("enter the height of person in inches")) weight = float(input("enter the weight of person in pounds")) bmi=(weight*(703/(height*height))) print("your bmi is:", bmi) if(bmi>=18.5 and bmi<=25): print("you have optimal bmi") elif(bmi<18.5): print("you are underweight") else: pri...
#!/usr/local/bin/python3 # Author: Jansen Lefever # Class: 301D2 Ops Challenge 13 # Purpose: Processes HTTP requests import requests site = str(input("Enter a website. Exsample: https://api.github.com:")) print(site) x = int(input('What HTTP request would you like to preform: 1)Get 2)Post 3)Put 4)Delete 5)Head...
# https://www.hackerrank.com/challenges/sets def raw_input_to_set(raw_input): return set(map(int, raw_input.split())) input() a_set_raw_input = input() input() b_set_raw_input = input() a_set = raw_input_to_set(a_set_raw_input) b_set = raw_input_to_set(b_set_raw_input) symmetric_difference = sorted([elem for ...
def sum_two_numbers(a, b): return a + b; first_number = int(input()) second_number = int(input()) result = sum_two_numbers(first_number, second_number) print (result)
""" A common use of decorators is to time the execution of functions. `timeit` decorator in below example, when applied to functions, prints out the execution time of every invocation. """ import functools import random import time # !!! TODO: think about how it could be reimplemented as a class # decorator...
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets import sklearn.metrics iris = datasets.load_iris() print('x shape is {}'.format(iris.data.shape)) print('y shape is {}'.format(iris.target.shape)) # ===YOU SHOULD EDIT THIS FUNCTION...
n = int(input()) for i in range(0,n): diff = 6 if (i+1)%2!=0: j = i+1 for i in range(n-i): print(j,end=" ") j += diff diff -= 1 print() else: j = i+1 for i in range(n-i): print(j,end=" ") ...
import numpy as np def sample_log(min_value, max_value, n): """ Samples logarithmically between min_value and max_value. :param min_value: minimum value of log random sampling :param max_value: maximum value of log random sampling :param n: how many samples do you want? :return: n logarithmaic...
# -*- coding: utf-8 -*- import pandas as pd data = { "year" : [2017, 2018, 2019], "GDP Rate" : [2.8, 3.1, 3.0], "GDP" : ['1.637M', '1.859M', '2.237M'] } df = pd.DataFrame(data) # 각 열의 데이터에 접근하기 위해서 # 열의 이름을 사용 # 데이터프레임변수명.열의이름 print(df.year) print(df.GDP) # 만약 열의 이름에 공백이 존재하는 경우 # [] 연산을 사용하여 접근 # 데이터...
# -*- coding: utf-8 -*- import numpy as np python_list = list(range(1,11)) numpy_array_1 = np.array(python_list) print(f"numpy_array_1.shape -> {numpy_array_1.shape}") print(f"numpy_array_1 -> {numpy_array_1}") # 배열의 형태를 수정할 수 있는 reshape() 메소드 # 1차원 배열을 2차원 배열로 형태를 변환하는 예제 numpy_array_2 = numpy_array_1.reshape(-1, ...
# -*- coding: utf-8 -*- import pandas as pd data = { "year" : [2017, 2018, 2019], "GDP Rate" : [2.8, 3.1, 3.0], "GDP" : ['1.637M', '1.859M', '2.237M'] } df = pd.DataFrame(data) # 데이터프레임의 앞 부분의 데이터 추출 # 기본값 = 5개 print(df.head(2)) # 데이터프레임의 뒷 부분의 데이터 추출 # 기본값 = 5개 print(df.tail())
n = int(input('Enter the number of subjects')) d =[] sum = 0 for i in range(n): m =float(input('Enter marks of the Subject')) d.append(m) sum+=m avg = sum/n print('Average marks of the Student is ',avg)
# a = None # b = None # c = None import time flag = -1 while flag==-1: a = input("Enter the first operand : ") a = int(a) b = input("Enter the second operand : ") b = int(b) print("\n Choose operation from the following menu => ") print("\n 1.ADDITION \n 2.SUBTRACTION \n 3.MULTIPLICATION \n 4.D...
for i in [1,2,3,4,5,6,7]: if i%2==0: print("Hola") continue
from tkinter import * window = Tk() def grams(): print(val.get()) grams=float(val.get())*1000 t1.insert(END,grams) def pounds(): print(val.get()) pounds=float(val.get())*2.20462 t2.insert(END,pounds) def ounces(): print(val.get()) ounce=float(val.get())*35.274 t3.insert(END,ou...