text
stringlengths
37
1.41M
from abc import ABC, abstractmethod class Piece: @property def opposite(self): raise NotImplementedError('Should be implemented by subclasses') class Board(ABC): @property @abstractmethod def turn(self): ... @abstractmethod def move(self, location): ... @prope...
from enum import Enum from board import Board, Piece class TicTacToePiece(Piece, Enum): X = 'X' O = 'O' E = ' ' @property def opposite(self): if self == self.__class__.X: return self.__class__.O elif self == self.__class__.O: return self.__class__.X ...
counter = 1 row = int(input("Input Row Number: ")) while row>26: row = row-26 counter += 1 print(chr(ord('A')+row-1)*counter)
print("Welcome to my program! If you put in 2 colors I will combine them for you!") def color(): color1 = input("What is the first color?: ").lower() color2 = input("What is the second color?: ").lower() colorlist = ["red","orange","yellow","green","blue","purple","white","black","brown","grey"] if color1 in colo...
#!/usr/bin/env python3.5.2 # -*- coding: utf-8 -*- from collections import Counter #结果分析: def resultType(result): count = 0 indexNum = list() for kk in range(len(result)): if(result[count][result[count].argmax()]>=0.5): index = result[count].argmax()+1 #判断最大值是否大于0.5,大于则统计,不大于则舍弃 ...
''' Faça um programa que leia um comprimento do cateto oposto e do cateto adjacente de um triângulo retangulo, calcule e mostre o comprimento da hipotenusa. 13/01/2020 ''' from math import hypot cateto_oposto = float(input('Digite o comprimento do cateto oposto: ')) cateto_adjacente = float(input('Digite o comprimento ...
''' Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos digitos separados. Ex: Digite um número: 1834 unidade: 4 dezena:3 centena:8 milhar:1 Rafael Bispo 14/01/2020 ''' numero = int(input('Digite um numero entre 0 e 9999: ')) unidade = numero // 1 % 10 dezena = numero // 10 % 10 centena = nu...
''' Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por Km Rodado. 13/01/2020 ''' km = float(input('Digite quantos Kms percorridos: ')) dias = int(input('Di...
''' Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80 Km/h. mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$ 7,00 por cada Km acima do limite. Rafael Bispo 14/01/2020 ''' velocidade = float(input('Informa a velocidade do carro: ')) if velocidade > 80: kmAcima = vel...
def positiveInt(value): vallist = list(range(10, 0, -1)) for num in vallist: if value % num == 0: print(num) else: print('Nope') print(positiveInt(10))
def returnThree(x): # define our function return x[0:3] # What do we want our function to do? ask = input("Please enter a long word: ") # User prompt value = returnThree(ask) # apply function to prompted value if len(ask) < 3: # conditions for printing print("too tiny") else: print("He...
''' write a function that excepts a parameter as a string and compute the average length of all the words in the string''' def average(string): table = str.maketrans(',.?!@#$%^&*', '***********') # replace all punctuation with one value string = string.translate(table) # applies the translate based on the tabl...
hours = eval(input("Enter hours driven (> 0): ")) avSpeed = eval(input("Enter average speed (> 0): ")) # Formula is d = x*t where x is speed & t is time if hours <= 0 or avSpeed <= 0: print("This is an invalid value, Please enter a positive value.") else: print("Hours driven: " , hours , ", ", "Average Speed: " ...
''' While - indefinite loop write a function that prompts the user to enter cities and appends to a list and stops when a null string is entered/just hiting enter ''' def cities(): lst = [] city = input("Enter a city (NULL to stop): ") while city != '': lst.append(city) city = input("Ente...
import math def perimeter(radius): return 2 * math.pi * radius # formula: 2*pi*r rad = eval(input("Enter a value: ")) print(perimeter(rad))
''' Rock - Paper - Scissors Function Rules: a. Rock always beats Scissors (rock dulls scissors) b. Scissors always beats Paper (scissors cut paper) c. Paper always beats Rock (paper covers rock) ''' def rps(choice1, choice2): if choice1 == 'R' and choice2 == 'S': print("Player 1 is th...
''' don't need address directory if both the .py program and the text file are in the same directory''' def numChars(filename): infile = open(filename, 'r') # 'r' is default & can be left off content = infile.read() # read the whole file to the console infile.close() # always close your file return len...
import pandas as pd from sklearn.preprocessing import MinMaxScaler """ General method for preprocessing any dataset in the best way posible in a generalized way. The steps done are: 1. Fix missing values 2. Normalize categorical data 3. Normalize all data to the same numerical domain """ def preprocess(dataset): ...
# name = input() # print('Enter name') # age = input() # print('Enter age') # if name == 'Alice': # print('Hi, Alice') # elif age < 12: # print('You are not Alice, kidddo') # else: # print('You are a nobody') # name = 'Bob' # age = 5 # if name == 'Alice': # print('Hi Alice') # elif age < 12: # print...
def printInvites(glist): print "--**--" for g in glist: print "Welcome "+ g print "--**--" guestList = ['Mike Butterworth','Mark Carson','Kiet Pham'] #print guestList printInvites(guestList) print "Kiet cant make it :(" del guestList[2] #print guestList printInvites(guestList) print "Sid will be...
# Understanding functions def print_student(salutation,fname,lname): print(salutation + ' ' + fname + ' ' + lname) def default_print_student(fname,lname,salutation='Mr.'): """Non-default parameter preceed default parameters""" print(salutation + ' ' + fname + ' ' + lname) #Positional arguements print_stu...
import sys ALPHABET_SIZE = 26 def getKey(keyword, count): """Calculating positions to shift in plain text for a particular letter according to""" """the KEYWORD and amount of alphabetical letters passed in the plain text (COUNT)""" count %= len(keyword) return ord(keyword[count]) - ord('a') if keywor...
import unittest def num_squares(n): squares = [] i = p = 1 while p <= n: squares.append(p) i += 1 p = pow(i, 2) squares.reverse() from collections import OrderedDict lasts = OrderedDict({n:0}) while lasts: last, c = lasts.popitem(last=False) #last = l...
# # def dfs(graph, s, t=None): """ :param graph: :param t: :return: """ stack = [s] visited = set() traversal = [] while stack: n = stack[-1] stack = stack[:-1] if n not in visited: traversal.append( n ) # you can ol...
# # #206 Reverse Linked List from leetcode import ListNode, linked_list_to_list, list_to_linked_list class Solution(object): def reverseList_mine(self, head): queue = [] n = head while n: queue.append(n) n = n.next i = 0 j = len(queue) - 1 h...
# 16. 3Sum Closest # class Solution(object): def threeSumClosest(self, nums, target): """ :param nums: List[int] :param target: int :return: int """ nums.sort() k = 0 closest = None len_nums = len(nums) while k < len_nums: ...
#1st #name = "Harry" #print(name[0]) # ---------------- # 2nd #names = ["Harry", "Ron", "Ahmed"] #print(names) #print(names [0]) # 3th cordinateX = 10.0 cordinateY = 20.0 cordinate = (10.0, 20.0) #------------------- # Data Structure # list --> sequence of mutable values # tuple --> sequence of immutable v...
# Uses python3 import sys def get_optimal_value(capacity, weights, values): value = 0. vwr = [] if max(values)*capacity == 0: return 0.0 for i in range(len(weights)): vwr.append([values[i],weights[i],float(values[i]/weights[i])]) sorted_vwr = sorted(vwr, key = lambda ratio: ratio[2], re...
# Uses python3 import sys def get_change(n): tens = n//10 fives = (n - tens*10)//5 ones = n%5 n = tens + fives + ones return n if __name__ == '__main__': n = int(sys.stdin.read()) print(get_change(n))
from sorting import Sorting k = 6 arr = [4,1,6,7,8,2,65,143,5] #arr = [1] print(arr) if k > len(arr): print("Error: k larger than array") exit() sort = 'qsel' #sort = 'merge' #-----------------test mergesort implementation------------------------ if sort == 'merge': print('\nMerge-sorting...') Sorting().me...
# Escrever o codigo aqui salaAtual = 1 contadorDeTentativas = 0 perdeu = False def Escolhercaminho(): global salaAtual global contadorDeTentativas global perdeu print("Voce esta na sala {}".format(salaAtual)) print("Escolha seu caminho:") print("[1] - Caminho Vermelho") print("[2] - Caminho Preto") ca...
import requests class IRCTC: def __init__(self): user_input=input("""how would you like to procde? 1. enter 1 to check live train status 2.enter 2 to check pnr 3.enter 3 to check train schedule""") if user_input=="1": self.live_status() elif us...
print("Hello!") #simple string printing print(5) #print a number; doesn't requires the double inverted commas{ " " } #defining integer variables and having matematical operations num1=10 num2=20 print(num1+num2) #defining float variable x=5.5 y=5.5 print(x+y) print(x*y) print(x*y+y*x) #defining stri...
'''---------------CS3A04: LAB 7--------------------''' '''---------------CODE------------------------------''' '''No user input should be done in this program''' # 1. Create a class called TripleString class TripleString: # Class level constants MIN_LEN = 1 MAX_LEN = 50 DEFAULT_STRING = "Ready, Stea...
# -*- coding: utf-8 -*- """ Created on Sun Sep 10 14:29:23 2017 @author: Nilton Junior """ def index_power(array, n): if n > len(array) - 1: return -1 else: return array[n]**n
def checkio(str_number, radix): result = 0 base = list(range(0, 10)) for i in range(0, len(base)): base[i] = str(base[i]) ordA = ord('A') ordZ = ord('Z') for i in range(ordA, ordZ + 1): base.append(chr(i)) base = base[0:radix] for i in range(0, len(str_number)): ...
def checkio(number): prod = 1 num_str = str(number) for i in num_str: if i != '0': prod *= int(i) return prod
import sys # sanity chekc the number of arguments def sanity_check(argv): if len(sys.argv) != 2: print "Please provide only the file name" sys.exit(0) # take a text file and extracts the word as well as their frequency def process_file(text_file): word_list = {} # read file and only keep alphabet and spaces ...
print("Welcome to Gabriel's Function Calculator") num1 = int(raw_input("Give me a number please: ")) num2 = int(raw_input("Give me another number please: ")) def myAddFunction(add1, add2): sum = add1 + add2 return sum print("Here is the sum: " + str(myAddFunction(num1, num2))) def mySubtractFunction(sub1,...
import sys class Point : def __init__(self, x_val, y_val): self.x = x_val self.y = y_val def __repr__(self): return "(%.2f, %.2f)" % (self.x, self.y) def Read_Points_From_Command_Line_File(): points = [] number_of_args = len(sys.argv) file = open(sys.argv[1],"r") for ...
name = input("What's your name?\n") print("hello, " + str(name))
# import modules to read csv file import os # module for path in different OS systems import csv # module for csv files # file path election_csv = os.path.join('Resources', 'election_data.csv') # create Lists and Dictionary to store data voters = [] # dictionary to store candidate name as key and votes as value ca...
from sys import argv def get_next(nums1, p1, nums2, p2): less_than = -1 if p1 < len(nums1) and p2 < len(nums2): if nums1[p1] < nums2[p2]: less_than = nums1[p1] p1 += 1 else: less_than = nums2[p2] p2 += 1 elif p1 < len(nums1): less_than...
# A password is considered strong if below conditions are all met: # It has at least 6 characters and at most 20 characters. # It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit. # It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa....
class Vertice_P: def __init__(self, n): self.nome = n self.vizinhos = list() self.tempo_descoberta = 0 self.tempo_fim = 0 self.cor = "preto" def add_vizinho(self, v): nset = set(self.vizinhos) if v not in nset: self.vizinhos.append(v)...
y=int(input("enter an integer 1\n")) x=int(input("enter an integer 2\n")) z=int(input("enter an integer 3\n")) if (y==x and x==z): print("Equal") else: print("Not Equal")
#Binary search Algorithm def BinarySearch(list1,key): #define the binary Search function lowindex=0 highindex= len(list1)-1 found =False while lowindex<=highindex and not found: midelement =(lowindex+highindex)//2 if key==list1[midelement]: #checking if key matches our ...
"""Functions used for processing the results of the optimisation runs and plotting them. """ import os import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter from scipy.stats import median_absolute_deviation, wilcoxon from statsmodels.stats.multitest import multipletests f...
#! /usr/bin/env python3 table_data = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'mouse', 'goose']] def print_table(tables): col_widths = [0] * len(tables) for i in range(len(tables)): for j in range(1, len(tables[0]))...
l1=[89,87,989,76,56] l2=[8,9800,0] def maxlist(l): m=max(l) print("largest number in the list: ",m) maxlist(l1) maxlist(l2)
l=[9,8,7,6,5,4,3,2,678] m=sum(l) print("the sum of elements of list is: ",m)
s=input("enter a non-empty string: ") n=int(input("enter the index number where deletion is to take place: ")) print(s.replace(s[n],""))
b=0 if b: print("value") else: print("falsey") n=0 while n<10: print(n) n+=1
print("1.farhenheit to celsius") print("2.celsius to farhenheit") n=int(input("enter your choice: ")) if n==1: m=int(input("enter temparature in farhenheit: ")) o=(m-32)/1.8 print("temparature in celcius: ",o) elif n==2: p=int(input("enter temparature in celcius: ")) q=1.8*p+32 print("temparatur...
n=int(input("enter the number of terms in fibonacci series: ")) print("the fibonacci series is: ") t1=0 t2=1 for i in range(0,n): print(t1) t3=t2+t1 t1=t2 t2=t3
import math class PriorityQueue: def __init__(self): self.elements = [] def is_empty(self): return self.size() == 0 def size(self): return len(self.elements) def swap_elements(self, index_first, index_last): aux = self.elements[index_first] self.elements[inde...
print ("\t\tThis is a python converter") """step one, determine what conversion to perform step two get user input on what conversions they want step three convert and display to ouput""" #How many pounds are in a kilogram? #How many miles is 1km? # what is xMbps in KB/s? def prompt(weight,dist,band_w): """this ...
import os #type hint for input parameters for python >3.5 def multiplyList(aList : list, n): j = 0 for i in aList: aList[j] = i * n j += 1 return aList # lambda programming # lbd essentially a function pointer def transform_to_newlist(aList: list,lbd): # apply lbd operator to each elem...
nome = input ('qual o seu nome?') print('ola',nome,'! Prazer em te conhecer') print(nome,'que dia vc nasceu?') dia = input() print('dia',dia,'jura, e qual mes?') mes = input() print(nome,',se vc me falar o ano te dou um presente') ano = input()//jgjgj print('vc nasceu dia',dia,'do mes',mes,'e do ano',ano) prin...
""" page: http://www.pythonchallenge.com/pc/def/map.html General tips: Use the hints. They are helpful, most of the times. Investigate the data given to you. Avoid looking for spoilers. Forums: Python Challenge Forums """ def solution(): text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc d...
from weapon import Weapon class Robot: def __init__(self, name, health): self.name = name self.health = health self.attack_power = 25 self.power_level = 50 self.weapon_names = ["laser cannon", "plasma rifle", "lightsaber"] self.set_weapon() def set_weapon(self):...
def add(a, b): """Add 2 numbers""" return a+b def sub(a, b): """Substract 2 numbers""" return a-b
import unittest from collections import deque def bfs(graph, start_node, end_node): if start_node not in graph: raise Exception("Start node not in graph!") if end_node not in graph: raise Exception("End node not in graph!") nodes_to_visit = deque() nodes_to_visit.append(start_...
def construct_dataset(x, f): n = len(x) s = [] for i in range(n): for j in range(f[i]): s.append(x[i]) s = sorted(s) return s def median(x): sz = len(x) if sz % 2 != 0: return x[sz // 2] else: return (x[sz // 2] + x[sz // 2 - 1]) / 2 def inter_quar...
# find a researcher's h-index # h-index: The largest number of papers h that have atleast h citations # Input: Papers(A, B, C, D, E) and Citations (2, 4, 1, 8, 7) # Output: 3 (corresponding to B, D, E) # How to think about this? # Given an array of n elements, Are there atleast h elements greater than or equal to h? ...
import unittest import math import numpy as np def hash_scores(scores_list, max_score): hash_array = [0] * (max_score+1) for score in scores_list: hash_array[score] += 1 return hash_array def sort_scores(scores_list, max_score): hash_array = hash_scores(scores_list, max_score) sorted_sc...
n = int(input()) zero = 0 while n >= 5: zero += n // 5 n = n // 5 print(zero)
from datetime import timedelta, date # Day of Week --> Date # DoW = day of week # Assumes the date only gets smaller. # e.g. querying about "Wed", "Tue", "Wed" means this Wednesday, this Tuesday... # and the Wednesday from last week. # Usage: # 1. Use the factory to create a function with starting date and the DoW o...
# from recommendations import critics from math import sqrt # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs, person1, person2): # get the list of shared_items si = {} # for every movie person1 rated, if person2 # also rated it, add to si for item in prefs[...
name = input('Enter your name: ') age = int(input('Enter your age: ')) if age > 19: print('Your name is',name,'and you are an Adult') elif age > 12: print('Your name is', name, 'and you are a teenager') else: print('Your name is', name, 'and you are a kid')
import threading import time # Define a function for the thread thread_signal = True def wait_for_other_thread(): """Thread needs a function to call in this example the thread executing this function simply waits for the global variable to change value. Which is done by the other thread""" whi...
#!/usr/bin/env python # comms.py # Alexander Looi # Last Modified: March 26rd, 2017 """COMMS This module has all the components to create, manipulate and analyze communities for a graph. In addition to manipulating and analyzing communities this module builds graphs. to associate with communities the user wishes to a...
#!/usr/bin/env python3 #_*_utf-8_*_ '''This script separates out the all the different finishing times of the Boston Marathon for every year there is data present. The resulting file is a text file called ParsedBoston{}.txt where the {} represents the specific year the marathon was run. ''' import os import numpy as ...
#Problem 743. Network Delay Time ''' Problem statement: There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target. Now, we send a sig...
#Problem 1792. Maximum Average Pass Ratio ''' There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of stud...
#Problem 1705. Maximum Number of Eaten Apples ''' There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does n...
from tkinter import * import random class Application(Frame): # Extend Frame's function globalnumber = 1 def division(): try: # Try to ...
""" O(n log n), or O(n + d) where d is the number of inversions """ import math #list = [-1,6,3,2,1,7,9,8,10,12,11,8,4,5] list = [-1,2,5,4,8,7,6,9,8,10,12,11,5,90,80,70,60,65,45,35,42] def insertion_sort(list): n = len(list) for i in range(1,n): # save value to be positioned value = list[i] pos...
import numpy as np # single dimentional array a = np.array([1,2,3]) # multi dimentional array b = np.array([(1,2,3),(4,5,6)]) print(a) print(b) # create a array of 1000 number d = np.arange(1000) print(d) print(d.itemsize) # to get a tupple having array dimensions print(a.shape) print(b.shape) # to reshap a array c =...
a = 10 b = 20 print("value of a is : ",a) print("value of b is : ",b) print("opeations examples: ") print("a + b : ",a+b) print("a - b : ",a-b) print("a * b : ",a*b) print("a / b : ",a/b) print("a // b : ",a//b) print("a % b : ",a%b) print("a ** b is a to power b : ",a**b)
# declaring class and using oops concepts class Employee: #declaring class varianble no_of_emps = 0 raise_amt = 1.04 def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first+last+'@testmail.com' Employee.no_of_...
a =5 b = 6 print(a) print(b) print("\n\n") a,b =b,a print("numbers after swaping") print(a) print(b)
x = input("enter first value") y = input("enter second value") a = int(x) b = int(y) z = a+b print(z) result = eval(input("input a math expression")) print(result)
def is_prime(num): for n in range(2,num): if num % n ==0: print('Not prime') else: print('Number is prime') is_prime(5)
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ l = [i.lower() for i in s if i.isalnum()] return l == l[::-1] s = Solution() print(s.isPalindrome('A man, a plan, a canal: Panama'))
#求两数的最大公约数 # c=a%b,c=0则b是最大公约数 ,否则a=b,b=c,继续计算a%b a = input("a=") b = input("b=") c = 0 while 1: c = int(a)%int(b) #print("输出",c) if c == 0: print("最大公约数:",b) break else: a = b b = c
# -*- coding: utf-8 -*- import sys import random import curses from itertools import chain class Action(object): ''' 游戏控制显示 ''' UP = 'up' LEFT = 'left' DOWN = 'down' RIGHT = 'right' RESTART = 'restart' EXIT = 'exit' letter_codes = [ord(ch) for ch in 'WASDRQwasdrq'] # 字母编码,o...
# https://leetcode.com/problems/two-sum/submissions/ # 1__2_Sum_problem # TimeComplexity # O(n) def twoSum(nums, target): arr = nums arr_inv_map = {} for i in range(len(arr)): if arr_inv_map.get(arr[i], 'X') == 'X': arr_inv_map[target-arr[i]] = i else: return arr_i...
#3__Merge_two_sorted_Linked_List from dataStructure.linkedList import singlyLinkedList, Node def mergeTwoLists(l1,l2): if l1 and l2: if l1.val < l2.val: newHead,l1 = l1,l1.next else: newHead,l2 = l2,l2.next cur = newHead while l1 and l2: if l1.v...
# https://leetcode.com/problems/copy-list-with-random-pointer/ #7__Clone_a_Linked_List_with_random_and_next_pointer_ from dataStructure.linkedList import singlyLinkedList as sLL, Node def copyRandomList(head): if not head: return head newhead = Node('-1') hmap = {} hmap[None]=None nh = ...
# https://leetcode.com/problems/rotate-list/ #6__Rotate_a_LinkedList from dataStructure.linkedList import singlyLinkedList as sLL, Node def rotateRight(head,k): if k and head: length = 0 cur = head while cur: length+=1 cur = cur.next k = k%length if ...
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ # Input: [7,1,5,3,6,4] # Output: 5 # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. # Not 7-1 = 6, as selling price needs to be larger than buying price. def maxProfitBrute(arr): # O(n^2) arr...
# https://www.interviewbit.com/problems/subarray-with-given-xor/ # 5__Count_number_of_subarrays_with_given_XOR(this_clears_a_lot_of_problems) from collections import defaultdict from functools import reduce def visualize(arr, m): print(f'Valid subarray with xor = {m}') for i in range(len(arr)): for ...
import timeit def sqrd_list(sqrd): for i in sqrd: print(i**2, end=" ") a=list(range(10)) sqrd_list(a) b=list(range(100)) sqrd_list(b) c=list() sqrd_list(c) mycode = ''' def sqrd_list(sqrd): for i in sqrd: print(i**2, end=" ") a=list(range(10)) sqrd_list(a) ''' print(timeit.timeit(stmt=m...
# *функция niter(iterable, n=2) # возвращает кортеж из "копий"-итераторов по переданному итератору, # каждый итератор должен предоставлять то же, что и итератор-источник. # Новые итераторы независимы в смысле их текущих позиций (в первом может вычитаться значение, # а в последующих они неизменны, возвращают перв...
# Класс “линейная функция”. # И основные ее операции: # -вычисление в точке, # -сложение с другой линейной функцией, # -умножение на константу, # -композиция с другой линейной функцией, - # строковое представление. # Нужно уточнить формулировку, но суть примерно такая. import numbers class Linear_funct...
# Read a file "mbox-short.txt and search for lines that start with From and a character # like "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008m" # followed by a two digit number between 00 and 99 followed by ':' # Then print the number if it is greater than zero import re filename = input("Enter a file name:...
import numpy as np from numpy import sin, cos, pi import matplotlib.pyplot as plt np.set_printoptions(precision=3, linewidth=200) def wrap(x, m, M): """ :param x: a scalar :param m: minimum possible value in range :param M: maximum possible value in range Wraps ``x`` so m <= x <= M; but unlike ``b...
#!/usr/bin/python #encoding=utf-8 import urllib2 import sys import re import base64 from urlparse import urlparse # The two normal authentication schemes are basic and digest authentication. # Between these two, basic is overwhelmingly the most common. # As you might guess, it is also the simpler of the two. # # A...
''' Pandas Homework with IMDb data ''' ''' BASIC LEVEL ''' import pandas as pd import matplotlib.pyplot as plt # read in 'imdb_1000.csv' and store it in a DataFrame named movies file_path = 'C:\Users\Matt\githubclones\GA-SEA-DAT1\data\\' movies_url = file_path + 'imdb_1000.csv' movies = pd.read_table(movies_url, sep...