text
stringlengths
37
1.41M
"""Task 2 The birthday greeting program. Write a program that takes your name as input, and then your age as input and greets you with the following: “Hello <name>, on your next birthday you’ll be <age+1> years” """ user_name, user_age = input("Enter your name, please!\n"), input("And enter your age, please!\n") ...
"""Task 2 Exclusive common numbers. Generate 2 lists with the length of 10 with random integers from 1 to 10, and make a third list containing the common integers between the 2 initial lists without any duplicates. Constraints: use only while loop and random module to generate numbers""" from random import randint ...
"""Task 1 Extend UnorderedList Implement append, index, pop, insert methods for UnorderedList. Also implement a slice method, which will take two parameters `start` and `stop`, and return a copy of the list starting at the position and going up to but not including the stop position.""" from node import Node class ...
"""Task 1 The Guessing Game. Write a program that generates a random number between 1 and 10 and lets the user guess what number was generated. The result should be sent back to the user via a print statement.""" import random guessed_number = random.randint(1, 11) entered_number = int(input('Enter number, please. ...
# 字符串 a = 'hello word'; b = 'python 你好'; print("a[0]", a[0]) print('b[0]', b[8]); # 字符串运算符 ''' + 字符串连接 * 重复输入字符串 [] 通过索引获取字符串中字符 [:] 截取字符串中的一部分 in 成员运算符-如果包含该字符返回Ture not in 成员运算符-如果不包含改字符返回True r/R 原始字符串-原始 ''' print("a + b 输出结果:", a + b) print( "a * 2 输出结果:", a * 2) print( "a[1] 输出结果:", a[1]) print...
suma=0 while 1: x=int(input("ingrese el numero a sumar ")) suma+=x if x==0: break print("la sumatoria de los numeros es",suma)
import math print("ingrese el radio de la esfera") radio=float(input()) area=4*math.pi*math.pow(radio,2) volumen=4/3*math.pi*math.pow(radio,3) print("el area de la esfera es: "+str(area)) print("el volumen de las esferas: "+str(volumen))
def crearlista(): num=int(input("ingrese la cantidad de numeros que desea ingresar")) suma=0 nums=[] for i in range(1,num+1): nuevo=float(input("ingrese el valor "+str(i)+":")) nums.append(nuevo) suma+=nuevo promedio=suma/num for i in range(1,num): desviacion=(abs...
seleccion=0 def Cargar_Valores(): nom=input("ingrese el nombre del libro :") auto=input("ingrese el nombre del autor :") editorial=input("ingrese la editorial :") with open("biblioteca.txt","r+") as file : file.write(nom+", "+auto+", "+editorial+"\n") def Mostrar_Valores(): with open("...
""" Sample Model File A Model should be in charge of communicating with the Database. Define specific model method that query the database for information. Then call upon these model method in your controller. Create a model using this template. """ from system.core.model import Model import re ...
# Written by RF import math a = float(input("a = ")) T = float(input("T = ")) B = float(input("B = ")) aT = (a/T) aTB = (aT+B) print("aTB = ", aTB) print("R = ", math.log(aTB, 10))
# Written by RF while True: answer = str(input("Is it a right triangle? (y/n) : ")) if answer in ('y', 'n'): print("invalid input") break if answer == 'y': continue else: # skip to other code # Calculation of Right Triangle def loopfunc(1) answer = str(i...
# Written by RF while True: s1=float(input("What is the length of side one in cm?")) s2=float(input("What is the length of side two in cm?")) A=(s1*s2) print("The area is", A, "cm^2") while True: answer = str(input('Anything else? (y/n): ')) if answer in ('y', 'n'): brea...
def contained(elem, list) : """ return true if the element is contained in the list """ if elem in "\n".join(list) : return True return False def mass_category(mass) : """ return the mass category depending on the value of mass. Currently we will have only one mass category for...
# -*- coding: utf-8 -*- """ Created on Tue Oct 24 19:39:39 2017 @author: nbt264 Introduction to plotting in Python """ import numpy as np, numpy.random as randn, matplotlib.pyplot as plt #Just to begin plt.plot(np.arange(10,21)) """ For most charts, we need to begin with a figure object - that's just a container f...
import numpy as np def power_method(A, iter_num=1): """ Calculate the first singular vector/value of a target matrix based on the power method. Parameters ---------- A : numpy array Target matrix iter_num : int Number of iterations Returns ------- u : numpy ...
''' You are teaching kindergarten! You wrote down the numbers from 1 to n, in order, on a whiteboard. When you weren’t paying attention, one of your students erased one of the numbers. Can you tell which number your mischievous student erased? Input The first line of input contains a single integer n (2≤n≤100), whi...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Oct 26 10:58:07 2018 @author: Mac """ #Question 1: Plotting sports data import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('UWvMSU_1-22-13.txt', sep = '\t') out = pd.DataFrame(columns=['time','scoreMSU','scoreUW']) scoreMSU = 0 s...
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ """ 复杂度:O(n^2) """ for i in range(len(nums)): temp=nums[i] for j in range(i): if nums[j] == temp: retur...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ pairs={ ")":"(", "]":"[", "}":"{" } listStack=[] for i in s: if i not in pairs: listStack.append(i) ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """...
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ """ 先确定行数,然后二分查找 """ if matrix == [] or matrix == [[]]:return False if target > matrix[-1][-1] or targe...
class Solution(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ """ 将整数转换为二进制数,若整数是4的指数,则满足: 1.最高位为1,其余位为0(num & (num) ==0) 2.0的个数为偶数(num & 0x55555555 > 1) """ return num & (num-1) ==0 and num & 0x55555555 > 0 ...
from leetcode.structures.singly_linked_list import ListNode class Solution: def __call__(self, l1, l2): def gen_add(a, b): """generator based solution""" carry = 0 while a and b: lsum = a.val + b.val + carry carry = lsum // 10 ...
import pandas as pd from datetime import datetime, timedelta class TimeZoneConvertor: def __init__(self, input_file, output_file): self.input_file = input_file self.output_file = output_file def convert(self): pd_A = pd.read_csv(self.input_file,delimiter=',') output = open(se...
#------------------------------------------------------------------------------- # Name: calender.py # Purpose: print the calender of the given year # # Author: Akshay # # Created: 11-06-2015 #------------------------------------------------------------------------------- DAYS_OF_THE_WEEK = ('Sun',...
# newton's method to find roots of any function dx = 1e-8 EPSILON = 1e-8 def deriv(g): """Return a function f such that f(x) is approximately dg/dx(x)""" return lambda x: (g(x+dx) - g(x))/dx def fixed_point(f, start, max): """ Find x such that f(x) is approximately x. start is the initial guess. max is the ma...
def insert(ls, pos): """ Insert ls[pos] into ls[:pos]. ASSUME: pos >= 1, ls[:pos] is sorted, len(ls) > pos""" if pos == 0: return ls assert pos >= 1 elem = ls.pop(pos) j = pos - 1 while j >= 0 and ls[j] > elem: j -= 1 ls.insert(j + 1, elem) #WHY j+1? The prev loop...
from battalion_types import BattalionType from typing import List from collections import defaultdict class Army: """Army holds all the battalions along with their strength. Army can update, add new battalions and their strength """ def __init__(self, **battalions): self.battalion_strength = d...
class Address: def __init__(self, address, apt, state, city, zip_code): self.__address = address self.__apt = apt self.__city = city self.__state = state self.__zip_code = zip_code @property def full_address(self): return f'{self.__address} {self.__apt} {sel...
import random class Food: def __init__(self): self.x_coordinate = random.randint(0,60) self.y_coordinate = random.randint(0,20) type = random.randint(0,40) if type <=5 : self.type_food = 0 #0 == bad food (*) else: self.type_food = 1 #1 == good food (+...
import turtle as t # 写了一个移动画笔的函数 def GoTo(x,y): t.up() t.goto(x, y) t.down() # 准备工作 GoTo(-100,100) #设置起点 可直接调用之前写的移动画笔的函数 #t.pencolor() #设置画笔颜色 t.pensize(40) #设置画笔粗细 # 画左边的小人 #============================== # 画小人的头 t.circle(13) # 画小人的身体 GoTo(-130,50)...
words = [] for _ in range(int(input())): word = input() l = len(word) words.append((word, l)) words = list(set(words)) # set 으로 만들기위해 () 이형태로 좌표를 넣어주고 # 중복 없애기 위해 set -> 다음 list words.sort(key= lambda x: (x[1], x[0])) # 길이, 단어 순 for w in words: print(w[0])
arr = ['a','b','c','d','e'] n = len(arr) # 5C3 for i in range(n-2): # 3개 뽑기 for j in range(i+1, n-1): # 2 for k in range(j+1, n): # 1 print(arr[i], arr[j], arr[k])
from itertools import permutations n=int(input()) number=list(map(str,range(1,n+1))) a=list(map(' '.join,permutations(number,n))) for i in a: print(i) # for i in range(1,n+1): # number+=[i] # # a=list(permutations(number,n)) # for j in a: # print(*j)
def maketree(i): #4 2 6 1 3 5 global count if i<=N: #중위 maketree(i*2) #왼 맨밑부터 matrix[i]=count count+=1 maketree(i*2+1) t=int(input()) for tc in range(1,t+1): N=int(input()) tree=[i for i in range(1,N+1)] matrix=[0]*(N+1) count=1 #트리를 만들어준다 제일 낮은 순서부터 make...
# 시간복잡도 nlonn -> 힙정렬, 병합정렬, 퀵정렬 등으로 풀어야함. # sys.stdin... 이거 차이큼 # 시간초과는 안나지만 효율성은 좀 떨어짐 import sys n = int(sys.stdin.readline()) li = [] for _ in range(n): li.append(int(sys.stdin.readline())) li.sort() print("\n".join(list(map(str, li)))) # 하나씩 출력해줌 # for a in li: # print(a)
arr=[3,6,7,1,5,4] n=len(arr) for i in range(1<<n): for j in range(n+1): if i & (1<<j): print(arr[j],end=', ') print() print()
#최소힙만 지원한다 (heapq) import heapq heap=[7,2,5,3,4,6] #list print(heap) heapq.heapify(heap) #최소힙으로 만들어줌 print(heap) heapq.heappush(heap,1) #삽입 print(heap) while heap: print(heapq.heappop(heap),end=' ') #오름차순으로 뽑혀서 만들어줌 print() ##################################### #최대힙은 ? temp=[7,2,5,3,4,6] heap2=[] for i in rang...
while True: num = input() if num == '0': break elif num[::-1] == num: print('yes') else: print('no') ''' def check(str): length = len(str) for i in range(0, length): if (str[i] != str[length -i -1]): return 'no' return 'yes' '''
def check(n, s): global minv if n > 12: # 12달 이상은 없으니깐 ! if s < minv: minv = s else: check(n+1, s+ month[n]*d) check(n + 1, s+m) check(n + 3, s+three_m) # 완전 탐색 for tc in range(1, int(input())+1): d, m, three_m, y = map(int, input().split()) month = [0] ...
def check_blank(string): for i in range(len(string)): if string[i] == '{' or string[i] == '(': check.append(string[i]) elif string[i] == '}' or string[i] == ')': if len(check) == 0: return 0 tmp=check.pop() if string[i]=='}' and tmp=='{...
# print("abc" in "abcba") # # print("cabcd".find("abc", 1)) # индекс первого вхождения или -1 # print("cabcd"[1:].find("abc")) # # print("cabcd".index("abc")) # индекс первого вхождения или ValueError # print("cabcd".index("abe")) # s = "The man in black fled across the desert," # print(s.startswith(("The woman", "T...
#============SCIENTIFIC CALCULATOR=========================================================== from tkinter import* import math import parser from tkinter import messagebox root = Tk() root.title("Scientific Calculator") root.geometry("480x568+0+0") root.configure(background="powder blue") calc = Frame(root) calc.gri...
#==============4TH SCRIPT================================= import sqlite3 as lit db = lit.connect('employee.db') with db: cur = db.cursor() selectquery = "SELECT * FROM users" cur.execute(selectquery) rows = cur.fetchall() for data in rows: print (data)
from src.heap import Heap def test_initialize_empty_heap(): heap = Heap() expected = [0] output = heap.heap assert output == expected def test_heapify_empty_list(): list_to_heapify = [] heap = Heap(list_to_heapify) expected = [0] output = heap.heap assert output == expected def ...
class Heap: def __init__(self, from_list=None): self.heap = [0] if from_list: self.heap.extend(from_list) self.heapify() def heapify(self): if len(self.heap) > 2: current_sub_heap_index = (len(self.heap) - 1) // 2 while current_sub_heap_in...
#!/usr/bin/env python #-*-coding=utf-8-*- ''' @author jdpdyx@126.com (jiangdapeng) @date 2014-10-14 @from netease interview problem ''' ''' problem: calculate f(a,b) = f(a-1,b) + f(a,b-1) given: f(0,b) = b f(a,0) = 1 for a >=0 , b>=0 ''' # using closure def gen_calculator(a,b): table = [[0 for j ...
class ListNode: def __init__(self, val=None, next=None): if val is None: val = 0 self.val = val self.next = next def reverse(self): if self.next is None: return self first = self prev = None while first is not None: _...
#Program berikut menggunakan Tkinter Widget GUI #Source code yang digunakan adalah Python #Source code berikut digunakan untuk mengecek informasi memori (RAM) from tkinter import * #memanggil library Tkinter import subprocess as sub #memanggil library subprocess dan dinyatakan sebagai sub p = sub.Popen(('cat', '...
class SNode: def __init__(self, value): self.value = value self.next = None class SList: def __init__(self): self.head = None def add_to_front(self, val): new_node = SLNode(val) current_head = self.head new_node.next = current_head ...
class BankAccount: def __init__(self, balance=0.00 ,int_rate=0.01): # don't forget to add some default values for these parameters! self.accountBalance = balance self.accountInterestRate =int_rate # increases the account balance by the given amount def deposit(self, amount): se...
def mergesort(arr, start, end): if end - start > 1: mid = (start + end)//2 mergesort(arr, start, mid) mergesort(arr, mid, end) merge_arr(arr, start, mid, end) def merge_arr(arr, start, mid, end): left = arr[start:mid] right = arr[mid:end] k = start i = 0 j ...
class Node(object): def __init__(self, val, parent, color): self.val = val self.left = None self.right = None self.color = color self.parent = parent class RB_tree(object): #RR rotation: def RR(self,node): t = node.left parent = node.parent...
from random import randint def start(): user_numbers = get_lottery_numbers() randomized_numbers = randomize_lottery_numbers() print(f"\nUser numbers {user_numbers}") print(f"\nRandomized numbers {randomized_numbers}") result = set.intersection(user_numbers, randomized_numbers) print(f"\nYou ...
data = {"name": "Demo", "marks": [10, 20, 30]} #print(len(["Demo"])) print(len(data["marks"])) print(sum(data["marks"])) marks_sum = sum(data["marks"]) marks_added = len(data["marks"]) print(marks_sum / marks_added) def print_data(data): print({data["name"], data["marks"]}) print_data(data)
from calc import Calculadora from geo import Geometria menup = ('''SUB - Linguagem de Programação - Menu Inicial [1] - Menu Calculadora [2] - Menu Geometria [0] - Sair do programa ''') menuc = ('''SUB - Linguagem de Programação - Menu Calculadora [1] - Somar [2] - Subtrair [3] - Multiplicar [4] - Dividir [0] - Retorna...
# coding=utf-8 """ __Arthur Marble__ This is the game manager class. It includes the main game loop and runs until the program ends. It is a parent class to GameView classes. """ import pygame from . import ResourceLoader class GameManager: """ GameManager Class """ def __init__(self): pygam...
import turtle my_turtle = turtle.Turtle() my_turtle.pencolor("red") for i in range(50): my_turtle.forward(50) my_turtle.right(123) my_turtle.pencolor("blue") for i in range(50): my_turtle.forward(100) my_turtle.right(123) turtle.done()
#!/usr/bin/env python """The data structures to store a schedule (task system), along with all the job releases and other events that have occurred for each task. This gives a high-level representation of a schedule that can be converted to, say, a graphic.""" from graph import * import util import copy EVENT_LIST ...
#!/usr/bin/python """Miscellanious utility functions that don't fit anywhere.""" def format_float(num, numplaces): if abs(round(num, numplaces) - round(num, 0)) == 0.0: return '%.0f' % float(num) else: return ('%.' + numplaces + 'f') % round(float(num), numplaces)
"""Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million. """ if __name__ == "__main__": sum = ...
# 29 Feb 2020 # CopyRight: WANG Hongru if __name__ == '__main__': a = int(input("please input a:")) hire, salary, fired = map(int, input("Please input the cost, salary, fired cost of individual person: ").strip().split()) needed = list(map(int, input("Please input the minimum person needed per month: ").s...
""" 定义LCS(S,T)为字符串S和字符串T最长公共子序列的长度,即一个最长的序列W既是S的子序列也是T的子序列的长度。 小易给出一个合法的括号匹配序列s,小易希望你能找出具有以下特征的括号序列t: 1、t跟s不同,但是长度相同 2、t也是一个合法的括号匹配序列 3、LCS(s, t)是满足上述两个条件的t中最大的 因为这样的t可能存在多个,小易需要你计算出满足条件的t有多少个。 """ s = input().strip() class Solution: def __init__(self): self.res = [] def reset(self): self.re...
# 리스트 : 많은 양의 데이터를 한꺼번에 다루기 위해서! # 순서를 가지고 있음. name = ['홍길동', '박길동', '송길동'] print(name[0]) #리스트 중 첫번째 값, 위치값 print(name[1]) print(name[2]) print(type(name[0])) #위치값: index는 0부터 시작, 마지막 위치는 전체개수-1
# 극장 예매시스템 # 1. 화면을 만든다. # --0이 10개 들어간 리스트 필요! seat = [0] * 10 # print(seat) count = 0 # 예매 상황을 카운트 name = input('고객님의 성함을 입력해주세요.>> ') while True: # 자리 번호 프린트 print('-----------------------------') for x in range(0, len(seat)): print(x, end=" ") print('\n-----------------------...
# 극장 예매시스템 # 1. 화면을 만든다. # --0이 10개 들어간 리스트 필요! seat = [0] * 10 # print(seat) while True: # 자리 번호 프린트 print('-----------------------------') for x in range(0, len(seat)): print(x, end=" ") print('\n-----------------------------') # 자리 예약 상태 프린트(0=>예약x, 1=>예약o) for x in s...
class SortedList(list): def __init__(self,lista,sorttype=False): self.sorttype=sorttype lista.sort(reverse=self.sorttype) super().__init__(lista) def _sort(self): self.sort(reverse=self.sorttype) return self def __setitem__(self, key, value): super().__setitem...
def volume(length): if(isinstance(length, int) or isinstance(length, float)): if(not length > 0): print("Length of edge must be greater than 0") return None return length**3 else: print("Invalid input") return None
#!/usr/bin/python3 if __name__ == "__main__": import sys lenght = len(sys.argv) if lenght == 1: print("0 arguments.") elif lenght == 2: print("1 argument:\n1: {}".format(sys.argv[1])) elif lenght > 2: print("{} arguments:".format(lenght - 1)) for x in range(1, len(sys...
#!/usr/bin/python3 """ function that reads a text file (UTF8) and prints it to stdout """ def read_file(filename=""): """ myfile: the variable use to store the open file """ with open(filename, mode="r", encoding="UTF8") as my_file: print(my_file.read(), end="")
valeur = 1 for loop in range(100): print(valeur) valeur = valeur +1 print("J'arrive !")
from listnode import ListNode class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if not head: return head dummy = ListNode(-1) dummy.next = head left...
class MissingNumber(object): ''' Solution: 1. Use binary search as the array is sorted. Calculate low, mid and high as usual. Calculate the differences of array[low] - low and array[mid] - mid. 2. If first one is smaller, reject the second half else reject the first half and update mid until low...
class Student(): # class variable # the number of students # all changes amde by other objects and instances, # can be seen pop = 0 def __init__(self, name, avg): self.name = name self.avg = avg print('Hi, how are you? My name is', self.name) # remember to b=put ...
#!/usr/bin/python # coding: utf-8 import argparse import sys import time my_parser = argparse.ArgumentParser( description='Slowly output the lines of a text file.', epilog='Parameters can be in a file, one per line, using @"file name"', fromfile_prefix_chars='@') my_parser.add_argument( 'fileNames', ...
seq = [1,2,3,4,5] print(1 in seq) for item in seq: print(item) for x in range(0,11,2): print(x) i = 1 while i<5: print("i is currently: {}".format(i)) i = i + 1
from Disk import * # import disk from Core import * def print_inventory(inventory): for item in inventory: print(inventory) def load_inventory(inventory): for item in inventory: car = inventory[item] print(item) print(' rental:', car['rental']) print(' in-stock:',...
x = 'Carro' print(x.lower()=='carro') # Vai dar True porque eu converti a variavel com a letra maiuscula para colocar todas as #letras minusculas
s = 'Sorte' if s != 'sorte': print('Sua string é diferente da string comparada') # Se string s, for diferente de 'sorte' ele vai exibir a mensagem
import random choice = ["paper", "scissor", "rock"] tie = 0 win = 0 lose = 0 while True: q = str(input("Paper,Scissor,or Rock? ")).lower() c = random.choice(choice) # good info...here it get overwritten everytime the loop start over while (q != "paper" and q != "scissor" and q != "rock"): ...
import heapq # def heapify(i): # sp = swap(i, min(2 * i + 1, 2 * i + 2)) # if (sp != -1): # heapify(sp) # def buildHeap(arr, n): # for i in range(n / 2, -1, -1): # heapify(i) # # def delete_min(arr): # # elt = arr[0] # # swap(arr, 0, h.size) # # h.size -= 1 # # heapify(0) # # return elt # # todo # # i...
from node import Node class LinkedList: def __init__(self): self.length = 0 self.head = None # adds to end def add(self, data): n = Node(data) if self.head is None: self.head = n self.length += 1 return tmp = self.head while tmp.next: tmp = tmp.next tmp.next = n self.length += 1 ...
import tensorflow as tf import pickle import numpy as np import matplotlib.pyplot as plt """ You have to implement an image classification neural network for the same dataset as before. Feel free to reduce the number of examples for each class in your dataset, if it takes too long to train on your hardware. For this ...
from Hashtable import Hashtable import random # The objective of this program is to determine the efficiency of the simple hash function # by inserting a random string of random length into a hashtable of a given size and determining # the number of collisions in each spot SIZE = 1000 MAX_WORD_LENGTH = 10 AMMOUNT_WO...
def cells(): from sympy import * init_printing() %matplotlib notebook import matplotlib.pyplot as mpl from util.plot_helpers import plot_augmat, plot_plane, plot_point, plot_line, plot_vec, plot_vecs Vector = Matrix # define alias Vector so I don't have to explain this during video ...
#https://selftaught.blog/python-tutorial-build-hangman/ def hangman(word): wrong = 0 stages = ["", "__________ ", "| ", "| | ", "| 0 ", "| /|\ ", "| / \ ", "| "] rletters = list(word) board = ["_"] * len(word) win = False print("Welcome to HANGMAN!") while wrong < len(stages)-1: print("\n") msg = "...
## Problem3 (https://leetcode.com/problems/search-a-2d-matrix-ii/) #Time Complexity : O(m+n), m=number of rows and n=number of columns # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No class Solution: def searchMatrix(self, matrix, target):...
import tkinter as tk import math from random import randint, choice WIDTH = 800 HEIGHT = 600 class Ball: #def __init__(self, r, x, y, dx, dy): def __init__(self): """ self.r = r self.x = x self.y = y self.dx = dx self.dy = dy """ self.r = randin...
import tkinter as tk import math def calc_angle(ddx, ddy): if ddx > 0 and ddy > 0: return math.atan(ddy / ddx) + 3 * math.pi / 2 elif ddx > 0 and ddy < 0: return -(math.atan(ddy / ddx)) elif ddx < 0 and ddy < 0: return math.atan(ddy / ddx) + math.pi / 2 elif ddx < 0 and ddy > 0...
# author: Grechnev Sergey """Module for test """ class FirstClass: def __init__(self, age, name): self.__age = age self.name = name assert type(age) == str, "Переменная равна строке" def __str__(self): return f"IPAddress: {self.name}" def modyfy(self): self.__age...
__author__ = 'ManiKanta Kandagatla' import sqlite3 mails = {} conn = sqlite3.connect('D:\Languages\python\SQLite\emaildb.sqlite') cur = conn.cursor() cur.execute(''' DROP TABLE IF EXISTS Counts''') cur.execute(''' CREATE TABLE Counts (org TEXT, count INTEGER)''') fname = raw_input('Enter file name: ') if ( len(fnam...
import pygame ''' Class that defines the squares on the board of the Checker GUI ''' class Square(): def __init__(self, root, area, color, x, y): self.root = root self.area = area self.color = color self.x = x self.y = y self.is_selected = False def draw(self, square_edge): if self.is_...
from __future__ import division from piece import * """ Class that determines the rules and structure of the Checkers game """ class Game(): def __init__(self, rows=8, columns=8, set_board=True): # Set structure of the board self.rows = rows self.columns = columns # Reset board...
from collections import defaultdict def vocab(df): dictionary = df.to_dict(orient='index') all_names = set() for k in dictionary: all_names.add(k[0]) return all_names def counts_dict(df, name_list): dictionary = df.to_dict(orient='index') names_vals = defaultdict(int) for k in d...
import statistics as st count=int(input(" ")) array=list(map(int,input().split())) result=False for i in range(1,count): list1=array[:i] list2=array[i:] if st.mean(list1)==st.mean(list2): result=True if result==True: print("yes") else: print("no")
from models.blog import Blog class Menu(object): def __init__(self): self.user_blog = None self.user = input("Enter your author name: ") if self._user_has_account(): print("Welcome back {}".format(self.user)) else: self._setup_new_user() def _user_has_...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def middle_node(head): if not head: return fast_ptr = head slow_ptr = head while fast_ptr.next and fast_ptr.next.next: fast_ptr = fast_ptr.n...
def get_next_greater_element_list(nums1, nums2): next_greater_element_list = [] next_greater_element_list = [] for num in nums1: found_flag = False nums_2_index = nums2.index(num) if nums_2_index == len(nums2)-1: next_greater_element_list.append(-1) contin...
from collections import defaultdict import math def majority_element(nums): count_dict = defaultdict(int) arr_length = math.floor(len(nums)/2) for element in nums: count_dict[element] += 1 if count_dict[element] > arr_length: return element if __name__ == '__main__': pr...