text
stringlengths
37
1.41M
#!/usr/bin/env python # coding: utf-8 # In[2]: outcome = [x**2 for x in range(1,11)] #x**2 is the output expression #x is the variable #range(1,11) is the input sequence outcome # In[ ]:
filename = 'full_text_small.txt' def file_write(filename): with open(filename, 'r') as f: n = 0 for line in f: n += 1 if n <= 5: print(line) return(line) file_write(filename)
from numpy import sqrt def isPrime(n): if (n<0): return False if (n%2==0): return False for i in range(3, int(sqrt(n))+1, 2): if (n%i==0): return False return True def formulaCount(a, b): n = 0 while( isPrime(n*n+a*n+b) ): n += 1 return...
from functions import isPalindrom, binary solution = 0 for n in range(1, 10**6): if isPalindrom(n) and isPalindrom(binary(n)): solution += n print(solution)
# 팩토리얼 구현 # 5! = 120 num = int(input("자연수 입력 : ")) fac = 1 for i in range(1, num + 1): fac = fac * i print(f'{num} 팩토리얼은 {fac}입니다.')
import random arr = list() print(arr) for i in range(10): arr.append(random.randint(1, 100)) print("*" * 40) print(arr) print("*" * 40) # 이 리스트 안에서 가장 큰 값을 출력하시오 arr.sort() print(arr[-1]) # 2번째 값도 출력하깅 print(arr[1]) li = [] # 가수 세 명을 입력 받기 for i in range(0, 3, 1): li.append(input('가수 이름을 쓰세요 : ')) print...
def f_iter(n): r = 1 for i in range(1, n + 1): r *= i return r def f_rec(n): if n <= 1: return 1 else: return n * f_rec(n-1) print(f_iter(5)) print(f_rec(5)) # iter 1에서 올리며 팩토리얼 # rec 재귀적인 표현 팩토리얼 # 줄이고 줄이고
# for a in range(1,10): # for b in range(1,10): # if b == 9 : # print('{} x {} = {:0>2}'.format(a,b,a*b)) # else : # print ('{} x {} = {:0>2}'.format(a,b,a*b),end=', ') # for _ in range(5) : # for _ in range(5) : # print('*',end=' ') # print() ...
"""name='Mason' age=20 food='라멘' print('이름은:{},나이:{},음식:{}'.format(name,age,food)) price = 100 num = input('사탕 몇 개 줄까요? ') #str print('총 {}원입니다.'.format(int(num)*price)) #총 가격 """ # p_score = int(input ('파이썬 점수 입력 : ')) # c_score = int(input ('C언어 점수 입력 : ')) # j_score = int(input ('자바 점수 입력 : ')) # p...
# print(dir(list)) # print(help(list.reverse)) #list 추가하는 방법 st = [1,2,3,4,5] st[5:] = [6,7] print(st) # st.insert(5,6) # st.insert(6,7) # print(st) # del st[2] # print(st) st[2:4]=[4] print(st) # st.remove(3) # print(st) st[5:0]=[100] print(st) # st.insert(5,100) # print(st)
# st4 = [d for d in range(1,7)] # print(st4) # st1 = [1,2,3,4,5] # # st2 = [] # # for d in st1 : # # st2.append(d*3) # st2 = [d*3 for d in st1] #List comprehension # print(st2) # st = [1.2,3.4,5.6,7.8,9.9] # # for i in range(len(st)) : # # st[i] = int(st[i]) # st2 = [int(st[i]) for i in r...
# -*- coding:utf-8 _*- """ @file: test.py @time: 2021/03/01 @site: @software: PyCharm # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ...
def main (): number = 533 h_code = hamming_code(number) decoded_number = decode_from_hamming_code(h_code) print(f'Hamming code of input number({number}): {h_code}') print(f'Decodeding result: {decoded_number}') print('\n\nTest:\n') test_h_code = dec_to_bin(int(h_code, 2) ^ 1 << 4) print...
import numpy as np from game.Constants import NB_COLUMNS, NB_ROWS, COMPUTER from game.Game import Game MAX_SCORE = 1 SCORE_DECREASE_RATE = 0.9 # Generate a lot of games, feeding the results to the given learning strategy. # The playing strategy of the 2 players can be either the learning strategy, but also another ...
import math rediusString = raw_input("Enter the radius of your circle: ") radiusInteger = int(radiusString) circumference = 2 * math.pi * radiusInteger area = math.pi * (radiusInterger ** 2) print "The circumference is: ", circumference, ", and the area is :", area
""" AI agent that solves the n-sliding puzzle game through various search algorithms Starting the script ------------------- python driver.py <method> <board> Parameters ---------- The method argument will be one of the following. bfs (Breadth-First Search) dfs (Depth-First Search) ast (A-Star Search) ida (IDA-Star S...
#!/usr/bin/env python #A python function that takes #an ip_range ex: (192.168.1-254.0-255) or #192.168.1.0-255) and appends every ip #to a returned list for other uses. #Use it if you would like or email me with #a better one. #d3hydr8[at]gmail[dot]com import sys def getips(ip_range): lst = [] iplist = [] ip_r...
class LinkedList: class Node: def __init__(self,value,next=None,previous=None): self.value=value self.next=next self.previous=previous def __init__(self): self._first=None self._last=None self._count=0 def _old_add(self,value): ...
import threading as t import sys class CountDownTask: def __init__(self, max,min=0,name=None): self._min=min self._max=max self._name=name self._thread=t.Thread(target=self.count_down,name=name) self._thread.start() def count_down(self): name=self._name if self....
import threading as t import sys class CountDownThread(t.Thread): def __init__(self,max,min=0,**kwargs): name=kwargs.get('name') super(CountDownThread,self).__init__(name=name,kwargs=kwargs) self._max=max self._min=min def run(self): name=t....
n=input() if n==n[::-1]: print('是回文字符串') else : print('不是回文字符串')
""" To test Double linkedlist and Tree """ class Dlist: def __init__(self): self.val = [] self.left = None self.right = None class Node: def __init__(self, x): self.val = x self.left = None self.right = None def build_tree(): root = Node(0) root.left = Node(-1) root.right = Node(1) return root ...
#!/usr/bin/python3 from numpy import exp, arange, int32, array # The pre-computed factorial numbers. factorials = { 2 : array([1, 1, 2]), 3 : array([1, 1, 2, 6]), 4 : array([1, 1, 2, 6, 24]), 5 : array([1, 1, 2, 6, 24, 120]), 6 : array([1, 1, 2, 6, 24, 120, 720]), 7 : array([1, 1, 2, 6, 24, 120, 720, 5040]), 8...
import inline import numpy as np import matplotlib.pyplot as plt from numpy import number from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score seed =1 # seed for random number generation numInstances = 200 # number of data instances np.random.seed(seed) X = np.random.rand(numInstan...
from pandas import DataFrame cars = {'make': ['Ford','Honda','Toyota','Tesla'], 'model':['Taurus','Accord','Camry','Model S'], 'MSRP' : [27595,23570,23495,68000]} carData2 = DataFrame(cars,index = [1,2,3,4]) #change the row index carData2['year'] = 2018 #ad column with same value carData2['dealershi...
import numpy as np my2darr = np.arange(1,13,1).reshape(3,4) print(my2darr) divBy3 = my2darr[my2darr % 3 ==0] print(divBy3,type(divBy3)) divBy3LastRow = my2darr[2:, my2darr[2,:] % 3==0] print(divBy3LastRow)
def squared(x): """ Takes an int and returns it multiplied by 2. :param x: int. :return: x multiplied by 2. """ return x ** 2 print(squared(5))
class Horse: def __init__(self, weight, name, rider): self.weight = weight self.name = name self.rider = rider class Rider: def __init__(self, height, weight, name): self.height = height self.weight = weight self.name = name yutaka = Rider(170, 50, "Yutaka Take"...
def string_to_float(x): """ Converts passed in str to int. :param x: str. :return: string converted to int. """ try: return float(x) except ValueError: print("It can not convert 'string' to 'float'.") y = string_to_float("aaa") print(y)
# -*- coding: utf-8 -*- # @公众号 :Web图书馆 代码详解:http://t.cn/A6Ihdrxf # @Software: PyCharm 安装教程:https://mp.weixin.qq.com/s/a0zoCo9DacvdpIoz1LEN3Q # @Description: # Python全套学习资源:https://mp.weixin.qq.com/s/G_5cY05Qoc_yCXGQs4vIeg import pandas as pd students = pd.read_excel('C:/Temp/Students_Duplicates.xlsx') dupe = students...
# -*- coding: utf-8 -*- # @公众号 :Web图书馆 代码详解:http://t.cn/A6Ihdrxf # @Software: PyCharm 安装教程:https://mp.weixin.qq.com/s/a0zoCo9DacvdpIoz1LEN3Q # @Description: # Python全套学习资源:https://mp.weixin.qq.com/s/G_5cY05Qoc_yCXGQs4vIeg import pandas as pd import matplotlib.pyplot as plt students = pd.read_excel('C:/Temp/Students.x...
from bitarray import bitarray import bitstring def str_to_binary(s): """ Converts input string into binary. :param s: (str) input :return: (List[int]) list of bits """ bits = bitarray() bits.frombytes(s.encode('utf-8')) return bits.tolist(True) def binary_to_str(bits): """ ...
def chunk(L,x): x = int(x) chunked = [L[i:i+x] for i in range(0,int(len(L)),x)] #Divide the list of inputs into smaller lists equal in size to the time step x return chunked def consolidate(L,x): x = int(x) chunked_list = chunk(L,x) #Divide the list of inputs into smaller lists equal in size to the ...
# mode='a' (append): ファイルの最後尾に内容を追加 # with open("writing_file.txt", mode='a') as f: # f.write("mode=a appends text") # mode='r+': 読み書きどちらも可能 # with open("writing_file.txt", mode='r+') as f: # f.write("You can write and read with r+ mode!!") # print(f.read()) # f.write("This should be the last sentence....
import sys input = sys.stdin.readline def get_bin(N): if N == 0 or N == 1: return str(N) return get_bin(N//2) + str(N%2) if __name__ == '__main__': N = int(input().strip()) print(get_bin(N))
def check_pixel(pixel, n): check = pixel[0][0] temp = -1 for i in range(n): for j in range(n): temp = pixel[i][j] if temp != check: return -1 return check def slice_pixel(pixel, n, r, c): sliced_num = int(n/2) sliced_pixel = [] for i in range(...
''' 분해합 ''' def decomposite_num(num): answer = num while num > 0: answer += num % 10 num //= 10 return answer def find_creator(): n = int(input()) digit_n = int(len(str(n))) #n 자릿수 구하기 if n < 18: for test_num in range(1, n): if decomposite_num(test_num) ...
def cantor(n): if n == 0 : return '-' elif n >= 1 : return cantor(n-1) + ' '*(3**n-1) + cantor(n-1) while True : try : n = int(input()) answer = cantor(n) print(answer) except : break
def sugar_plz(sugar): count = 0 while sugar >= 0: if sugar % 5 == 0: count += (sugar // 5) print(count) return sugar -= 3 count += 1 print(-1) return if __name__ == "__main__": sugar = int(input()) sugar_plz(sugar)
n = int(input()) arr = [] for _ in range(n): arr.append(int(input())) def merge_arr(a, b): result = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 if i...
import math n = int(input()) base_star = [" * ", " * * ", "*****"] cnt = int(math.log(n/3, 2)) def make_triangle(base_star, n, cnt): if cnt == 0: return base_star new_star = [] space = ' ' * (int(n/2)) for i in range(len(base_star)): new_star.append(space + base_star[i] + space) ...
def hanoi(num, _from, tmp, to): if num == 1: print(_from, to, end = ' ') print() else: hanoi(num - 1, _from, to, tmp) print(_from, to, end = ' ') print() hanoi(num - 1, tmp, _from, to) hanoi_num = int(input()) print(pow(2,hanoi_num) - 1) hanoi(hanoi_num, 1, 2, 3)...
Q = int(input()) for _ in range(Q): n, m = map(int,input().split()) importance = list(map(int,input().split())) index = [0 for _ in range(n)] index[m] = 'point' cnt = 0 while True : if importance[0] == max(importance): cnt +=1 if index[0] == 'poin...
# 0개 이상의 문자를 추가해서 팰린드롬 만들기 # 출력: 만들 수 있는 가장 짧은 팰린드롬의 길이 # 체크할 조건 # len(S) <= 1000 # 1. 각 문자의 양 옆을 살핀다. # 양 옆 문자가 다르면 넘어간다. # 같으면 다른 문자가 나오거나 끝이 나올 때까지 ++, --하며 살핀다. # 서로 다른 문자가 나오면 넘어간다. # 2. 문자열의 첫 부분이나 끝에 다다르면 남아있는 부분의 길이를 더해준다. # 남은게 없으면 0을 더한다. # 가장 짧은 팰린드롬의 길이로 갱신한다. # def solution(string)...
def how(n, guess): n = str(n) guess = str(guess) strike = 0 ball = 0 for i in range(0, 3): if n[i] == guess[i]: strike += 1 else: if n[i] in guess: ball += 1 return (strike, ball) N = int(input()) guesses = list() for _ in range(N): ...
#!/usr/bin/python3 import sys def main(): if(len(sys.argv) == 2): filename = sys.argv[1] fo = open(filename,"r") readF = fo.read() readF = readF.lower() readF = readF.split() readF = [i.split('.',1)[0] for i in readF] readF = list(set(readF)) readF = sorted(readF,reverse=True) print("Hasil dari spli...
Height=float(input("Enter your height in centimeters: ")) Weight=float(input("Enter your Weight in Kg: ")) Height = Height/100 BMI=Weight/(Height*Height) print("Your Body Mass Index is: ",BMI) if(BMI<=18.5): print("Oops! You are underweight.") elif(BMI<=24.9): print("Awesome! You are healthy.") elif(BMI<=29....
num =int(input("Number please:")) def factorial(n): x = 1 for i in range(n): x = x * (n - i) return x print (factorial(num))
import random board = [''' >>>>>>>>>>Hangman<<<<<<<<<< +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' ...
from Homework6Regularization import getRawData, LinearRegression, nonLinearTransform, getTestError, getPredictions import numpy as np from random import randint from LinearRegression import get_target_function trainingPercent = 25 / 35 def splitTraining(trainingIndex=25, first=True): """helper function that takes...
class Solution: def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.output = list() self._permuteUnique(list(), nums) return self.output def _permuteUnique(self, curr_arr, nums): """ Help...
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ grid = list() # Initialize the 2D grid for i in range(n): temp = [0] * m grid.append(temp) # Topmost row are all ...
"""Grid class provides a template for data systems which implement grid structures where the individual cells within the grid contain information individual to the cell.""" class Grid: #init Provides a default set of traits to each cell in the grid provided by #the user. The grid is a two dimensional array a...
# 把以下程式放到 .py 上執行 # 執行後,伺服器會持續開著 # 到瀏覽器開啟 http://127.0.0.1:5000/ 就可以看到網頁 from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return """ <html> <head> <title>網頁標題</title> </head> <body> <div id="header"> <a class="logo" href="https://test.com.t...
# Reference File for Basic Plotting # You'll see similarities here to Matlab plotting with this library import numpy as np import matplotlib.pyplot as plt # generating 100 standard normally distributed random numbers as a NumPy ndarray np.random.seed(1000) y = np.random.standard_normal(100) x = range(len(y))...
import random # initial values # List = real value, suits, card player_cards = [] dealer_cards = [] MINIMUM = 17 # poker card as a dictionary poker_card = { 1: "Ace", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 1...
import numpy as np import matplotlib.pyplot as plt def compute_accel(desired_accel, desired_speed, duration, N): accel = np.zeros(int(N)) N1 = int(desired_speed / desired_accel * N / duration) N2 = int((duration - desired_speed / desired_accel) * N / duration) if N1 <= N2: accel[:N1] ...
''' 사회적 거리두기에 따른 영화관 좌석 예매 시스템 만들기 1~20번까지 총 20개의 좌석으로 구성 이 때 각 열에 대해 홀수(/짝수로 끝나는 좌석에 대해서만 출력 A, B, C, D열까지 있다고 가정하기 A, C열은 홀수만, B, D는 짝수만 있다고 가정 ''' def what_seat(alphabet): seat_list = [] ''' # 평상시 for i in range(1, 21): seat = alphabet + str(i) seat_list.append(seat) ''' #...
""" Program: employee_class.py Author: Ihsanullah Anwary Last date modified: 12/11/2020 This is program is an example employee management system which allows the user to choose one for option from the list of the selection.This program allows the user to save, find and delete the employee's id, first name, last name, d...
import Snake as S import os import time import random #size of grid nxn n = 16 grid = list() #For now food is a tuple. Could make a spearate object for a separate sprite if there is time. food = tuple() def checkCollision(snakeObject,otherSnakeObject = None): ''' Checks the collisions of the snake with the bounds...
FORWARD = 'forward' DOWN = 'down' UP = 'up' def pretty_print_answer(part, answer): print('Answer to part {num}: {ans}'.format(num=part, ans=answer)) def read_lines(file_name, is_strip=True): file = open(file_name) lines = [s for s in file.readlines()] file.close() if is_strip: lines = [s.s...
def main(): file_input = open('input.txt', 'r') lines = file_input.readlines() file_input.close() calories = [] current = 0 for line in lines: line = line.strip() if line.isdigit(): current += int(line) else: calories.append(current) c...
import copy import utils class Recipes: def __init__(self): self.recipe = [3, 7] self.current = 0 self.next = 1 self.processed = 0 def step(self): score = self.recipe[self.current] + self.recipe[self.next] score = [int(d) for d in str(score)] self.recip...
import utils TREE = '#' class Map: def __init__(self, file_name): self.grid = [] lines = utils.read_lines(file_name) for line in lines: self.grid.append(list(line)) def traverse(self, col_mod, row_mod): num_trees = 0 row = col = 0 while row < len(se...
import utils vowels = 'aeiou' forbidden = ['ab', 'cd', 'pq', 'xy'] def is_nice(input_string): return (has_three_vowels(input_string) and has_duplicate_letter(input_string) and not has_forbidden_pair(input_string)) def is_nice_pt2(input_string): return (two_pairs(input_string) ...
def snafu_to_decimal(value): total = 0 power = 0 for digit in value[::-1]: if digit.isdigit(): total += int(digit) * 5 ** power elif digit == '-': total += -1 * 5 ** power elif digit == '=': total += -2 * 5 ** power else: assert...
def coin_change(coins, m, n, mem): if n == 0: return 1 if n < 0: return 0 if m < 0: return 0 if (m, n) in mem: return mem[m, n] ans = 0 ans += coin_change(coins, m, n-coins[m], mem) ans += coin_change(coins, m-1, n, mem) ...
def smallestWindow(st): n = len(st) dic = {} setChars = set() count = 0 for c in st: setChars.add(c) count = len(setChars) start = 0 end = n-1 curr = 0 found = set() minl = n start_ind = 0 for i in range(n): c = st[i] ...
# -*- coding: utf-8 -*- """ Created on Sun Nov 29 16:17:42 2020 @author: Jill Wright This program takes information from an API program called Financial Prep and commits it to a SQL database. The information is from ticker symbol and includes Industry,CEO, and company description. Another segment is populat...
print("Welcome to the BMI calculator\n") height = float(input("Kindly Enter your height\n")) weight = int(input("Kindly Enter your weight\n")) bmi_data = int(weight) / float(height ** 2) # bmi = float(bmi_data,2) print(bmi_data) if bmi_data < 18.5: print(f"Your BMI is {bmi_data} You're underweight") elif bmi_data...
is_even = 0 total_evens = 0 for numbers in range(1, 100+1): is_even = numbers % 2 if is_even == 0: total_evens += numbers print(f"Total even numbers is {total_evens}")
from ListItem import ListItem class List: """ A simple linked list implementation. The list object contains the head, tail, and the length of the list. I keep track of the tail of the list so that I can append items to the list in O(1) time. """ def __init__(self): self._head = None ...
import unittest import random import functools from QuickSort import quick_sort from List import List from ListItem import ListItem class TestList(unittest.TestCase): def setUp(self): self.int_list = List() self.int_list.append(ListItem(0)) self.int_list.append(ListItem(15)) self.i...
# https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ # Jose Luiz Mattos Gomes class Solution: def solution(self, X, Y, D) -> int: # calculate number of jumps numJumps = (Y - X) // D if (Y - X) % D > 0: # add 1 jump if remainder is bigger than 0 numJumps +=1 # retur...
# https://leetcode.com/problems/fizz-buzz/ # Jose Luiz Mattos Gomes from typing import List class Solution: def fizzBuzz(self, n: int) -> List[str]: # define return list vReturn = [] # iteract from 1 to n for i in range(1, n+1): # test if is multiple of 3 if i%3==0: ...
# https://leetcode.com/problems/rotate-array/ # Jose Luiz Mattos Gomes from typing import List class Solution: def rotate(self, nums: List[int], k: int) -> None: # guarantee that k is between 0 and nums.length k = k % len(nums) # if k is zero than no rotation is needed if(k==0): return ...
import random wordlist = ["mouse", "banana", "grow", "king", "chalk", "clever", "sharan", "mindset", "munnar", "eraser"] choosen = random.choice(wordlist) print(choosen) chos_length = len(choosen) empty = [] for i in range(chos_length): empty.append("_") def guess(): for i in range(0, ...
#!/usr/bin/env python #resp : 72 verbos 19 verbos em primeira pessoa import sys verb = 0 verb1 = 0 foo = ['r','x','w','j','m'] fp = open(sys.argv[1], "r") line = fp.readline() words = line.split(' ') for wd in words: if len(wd) >= 8 and wd[-1] not in foo: verb = verb + 1 if wd[0] in foo: verb1...
# coding:utf-8 # O(n^2) # i 范围 0- (len-1) # j 范围 0- (i-1) j永远比i小1 def insertSort(relist): len_ = len(relist) for i in range(1,len_): for j in range(i): if relist[i] < relist[j]: relist.insert(j,relist[i]) # 首先碰到第一个比自己大的数字,赶紧刹车,停在那,所以选择insert relist.pop(i+1)...
# coding:utf-8 class BiNode(object): # 结点类 def __init__(self, element=None, left=None, right=None): self.element = element self.left = left self.right = right def get_element(self): return self.element def dict_form(self): dict_set = { "element": self...
from re import findall def is_isogram(string): temp = findall(r'\w', string.upper()) return len(set(temp)) == len(temp)
# Import libraries import os import csv smallval = 0 bigval = 0 bigdate = '' smalldate = '' maxchange = 0 minchange = 0 # open the file and EXCLUDE THE HEADER after printing it so I can see it csvpath = os.path.join('resources', 'bank.csv') with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimite...
""" Module for approximating square root More details """ def sqrt2(x): """ Function definition """ s = 1. kmax = 100 tol = 1.e-14 for k in range(kmax): print "Before iteration %s, s = %20.15f" % (k+1,s) s0 = s s = 0.5 * (s + x / s) delta_s = s - s0 if abs(delta_s / x) < tol: break print "After %...
"""Volume 1: The Drazin Inverse. <Timothy Norris> <MTH 420> """ import numpy as np from scipy import linalg as la # Helper function for problems 1 and 2. def index(A, tol=1e-5): """Compute the index of the matrix A. Parameters: A ((n,n) ndarray): An nxn matrix. Returns: k (int): The i...
class Board(object): def __init__(self): # Board spaces will be represented by a list. This list # shows where the players have a mark or a space is empty. # Indices relate to the board as follows: # # 0 | 1 | 2 # ---|---|--- # ...
dict1 = {} dict1['one'] = '1' dict1[2] = '2' tinydict = {'name':'bloodymandoo','code':1,'site':'www.bloodymandoo.com'} print(dict1['one']) print(dict1[2]) print(tinydict) print(tinydict.keys()) print(tinydict.values()) dict1 = dict([('Python',1),('Google',2),('Taobao',3)]) print(dict1) dict2 = {x:x**2 for x in (2,4,...
''' String to atoi 1. discards whitespace characters 2. optional intital plus and minus sign 3. string can contain additional characters Input: "42" Output: 42 Input: " -42" Output: -42 Input: "4193 with words" Output: 4193 Input: "words and 987" Output: 0 Input: "-91283472332" Output: -2147483648 Explanation: T...
''' Given a linked list change it in sorted order Merge sort 1. if head is null one element in the linked list then return 2. else divide linked list in two halves 3. Sort the two halves MergeSort(a) MergeSort(b) 4. Merge the sorted a and b and update the header pointer using headRef ''' class Node: def __init__(...
el = [10, 10, 53, 20, 30, 40, 59, 40] k = 2 def kth_largest(input_list, k): # initialize the top_k list to first k elements and sort descending top_k = input_list[0:k] top_k.sort(reverse = True) for i in input_list[k:]: if i > top_k[-1]: top_k.pop() # remove the lowest of the top k...
''' This is the return book module for the user to return a book. It imports booklist.py and datetime modules in order to access their main functions. It imports the 2D list of books from booklist.py for the user to return a book and see if it is present in the library or not. It then stores a record of the user in...
import string def get_word(file): d = dict() count = 0 #获取每一行 for f in file: word_list = f.split(" ") #取到单行的每个单词 for word in word_list: table = str.maketrans(string.punctuation," " * len(string.punctuation)) word = word.translate(table).strip() ...
class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __str__(self): return "(%g, %g)" % (self.x, self.y) def print_point(self): print("(%g, %g)" % (self.x, self.y)) def __add__(self, other): if isinstance(other, Point): self.x +...
# #01 - Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com essa formatação: # [ 1 ][ 2 ][ 3 ] # [ 4 ][ 5 ][ 6 ] # [ 7 ][ 8 ][ 9 ] # linha_1 = input("Linha 1: Escreva 3 números separados por espaço").split() # lin...
# Utilizando os conceitos aprendidos até dicionários, crie um programa onde 4 # jogadores joguem um dado e tenham resultados aleatórios. # O programa tem que: # • Perguntar quantas rodadas você quer fazer;X # • Guardar os resultados dos dados em um dicionário. # • Ordenar esse dicionário, sabendo que o vencedor tirou o...
# Faça um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL ou OBRIGATÓRIO nas eleições: def voto(ano): idade = 2021 - ano if idade < 16: return 'Voto negado' ...
#!/usr/bin/env python3 nums = [101,2,15,22,95,33,2,27,72,15,52] evens = [num for num in nums if num%2==0] print(evens)
#!/usr/bin/env python3 lines_num = 0 char_num = 0 with open("Python_05.fastq","r") as fastq_obj: for line in fastq_obj: print('This line length:', len(line)) line = line.rstrip() lines_num += 1 char_num = char_num + len(line) print('total lines:', lines_num) print('total chars:', char_num) print('Ave line le...
import csv fields = ['Name', 'Branch', 'Year', 'CGPA'] rows = [ ['Nikhil', 'COE', '2', '9.0'],['Sanchit', 'COE', '2', '9.1'],['Aditya', 'IT', '2', '9.3'] ] filename = 'record.csv' with open(filename, 'w') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(fields) csvwriter.writerows(rows) p...
# Getting Started Assignment 1: # Given the below list of dictionaries, write code to: # -- iterate through the list of dictionaries; # -- for each dictionary, check whether the make is a Honda; # -- if make is Honda, print the color year Honda model # -- Precede the list with text intro # Your output should look lik...
# Array of unique, consecutive natural numbers such that allow all rows, all columns, and both of the main diagonals have the same sum def verifysquare(square): sums = [] rowsums = [sum(square[i]) for i in range(0,len(square))] sums.append(rowsums) colsums = [sum([row[i] for row in square]) for i in...