text
stringlengths
37
1.41M
class pointD: def __init__(self, point, label): self.point = point # null =- 1, top = 0, bottom = 1 self.label = label def getColor(self): if(self.label == -1): return 'grey' if(self.label == 0): return 'red' if(self.label == ...
a = int(input()) cnt = 0 for x in range(1,int(a**0.5)+1): if a % x == 0 and a / x == x: cnt=cnt+1 elif a%x==0: cnt=cnt+2 print(cnt)
import tkinter as tk from random import randrange root = tk.Tk() root.title("Guess the Right Number to Win") initial = tk.Label(root, text = "Guess A Number From 0 to 9") beginner = tk.Label(root, text = "# of Guesses: 0") maxguess = tk.Label(root, text = "Maximum # of Guesses: 3") options = tk.Label(root, text="What...
""" Provides a series of solutions to the challenge provided at the following link: https://therenegadecoder.com/code/how-to-check-if-a-key-exists-in-a-dictionary-in-python/#challenge """ def to_empty_or_not_to_empty_1(anime: list): has_duplicates = len(set(anime)) != len(anime) has_seventeen_shows = len(anim...
""" Tests the performance of all of the solutions listed in the following article: https://therenegadecoder.com/code/how-to-empty-a-list-in-python/ """ from test_bench import test_bench def control(anime: list[str]) -> None: """ Provides a control scenario for testing. In this case, all of the solutions ...
#cette fonction sert à définir les variables def entree(): a= int (input("Entrez une valeur de a:")) b= int (input("Entrez une valeur de b:")) c=0; return a,b,c ; #cette fonction sert a calculer def calcul(a,b,c): while(a<b): if (a%5==0): c=c+a a=a+1 return c #cette...
import random print(" Гра має імя - Камінь, Ножниці, Папір" \ "Приві, гравцю, давай познайомимось.\n \ Як тебе звати") name = input(' ') print(' Дуже приємно ' + name) ###Початок гри games_array = ['Камінь', 'Ножниці', 'Бумага'] print(' Умови гри: Камінь ломає ножниці, Папір - накриває камінь,\n Ножниці - ріжуть папір\...
#!/usr/bin/env python3 age = 26 name = 'kernel' print('Возраст {0} -- {1} лет'.format(name,age)) print('Почему {0} забаляэеться с этим Python?'.format(name))
#!/usr/bin/env python3 number = 23 guest = int(input('Введите целое число: ')) if guest == number: print('Поздравляю, вы угадали,') #Здесь начинаеться новый блок print('(хотя и не выиграли никакого приза!)') # Здесь заканчиваеться новий блок elif guest < number: print('Нет, загадочное число немного больше этого.') #...
chois = int(input('Вы решыли прогуляться в Южном бутово и наткнулись на спортивних ребят.\n 1. Попитатся убежать\n 2. Продолжить идти\n')) if chois == 1: quit ('Ребята без труда вас догнали и побили. Незнаю за что') else: print('Один из ребят вишел вперед и спросил \"Сиги есть?\"\n1. Да прикурить\n2. -- Не курю') c...
# -*- coding: UTF-8 -*- from tkinter import * root = Tk() root.title('我是计算机') root.geometry('320x420') result = Entry(root) # 用来显示结果的可变文本 result.pack() print(result) # equation = Tk().StringVar( ) # 用来显示算式的可变文本 # result.set(' ') # 赋初始值 # equation.set('0') # show_uresul...
""" File: best_photoshop_award.py Author: Jade Yeh ---------------------------------- This file creates a photoshopped image that is going to compete for the 2020 Best Photoshop Award for SC101P. Please put all the images you use in image_contest folder and make sure to choose which award you are aiming at """ from sim...
""" File: fire.py Author: Jade Yeh --------------------------------- This file contains a method called highlight_fires which detects the pixels that are recognized as fire and highlights them for better observation """ from simpleimage import SimpleImage # Control the degree of the R-value to be highlighted HURDLE_F...
# parent class class Rectangle: def __init__(self, height: int, length: int): self.height = height self.length = length def get_area(self) -> int: return self.length * self.height def get_name(self) -> str: return 'I am a rectangle' # child class -> a square is like a re...
def cube(x): cube_i=0 for i in str(x): z=int(i)**3 cube_i=z+cube_i if cube_i==x: print('{} is an Armstrong number'.format(x)) else: print('{} is not an Armstrong number'.format(x)) cube(371)
""" ------------------------- Created on Jul 13, 2018 @author: Prashant Gurung ------------------------- Doubly Linked List Implementation using Head and Tail pointers Methods: is_empty() => O(1) => returns whether the list is empty or not push_front(newNode) => O(1) => inserts a new node at the beginning of the lis...
""" ------------------------- Created on Jul 27, 2018 @author: Prashant Gurung ------------------------- Merge Sort Implementation """ # function to merge two sorted lists def merge_sorted_lists(list1, list2): assert type(list1) == list and type(list2) == list, "Arguments list1 and list2 must both be of type li...
def squr(): n = 1 while n>0 : n = int(input("Enter the number ")) if n>0: a=n**2 print(a) else: print("Enter the +ve number ") def sum_even_odd(): n = int(input("Enter a number :")) sumeve = 0 sumodd = 0 i=1 for i in range (1,n+1): if i%2==...
import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 print(f"host name is {host}") # connection to hostname on the port. print(f"connecting to {host}") s.connect((host, port)) while ...
try: file = open("sample.txt","w") text = input("enter the statements : ") file.write(text) file.close() except Exception as msg: print("Exception is",msg) try: file = open("sample.txt","r") text = file.read() file2 = open("ram.txt","a") text2 = input("enter the statements : ") ...
try: file_name = input("enter the file name : ") file_name2 = input("enter the file name2 : ") file = open(file_name,"w") file2 = open(file_name2,"w") text = input("enter the statements : ") text2 = input("enter the statements2 : ") file.write(text) file2.write(text2) file.close() ...
print print 'Welcome to uno.exe!' print 'This program was made by Ryan Curry using Python 2.7' print 'To find out more, read the README file' print print #creates README file READMEtext = 'This program was made by Ryan Curry using Python 2.7\nTo find an indepth discussion on the creation of this program, or th...
from dataclasses import dataclass, field from abc import ABC, abstractmethod from user_roles import RoleType @dataclass class BaseUser(ABC): name: str email: str @abstractmethod def describe_user(self): """this function describes the user""" def assign_role_to_a_user(self): """t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: pandian_krishna Recreated an Old Lab because I was bored """ import math import operator ops = {'+':operator.add, #take data from operator '-':operator.sub, '*':operator.mul, '/':operator.truediv} def Valid(s): #checks if it's vali...
""" Sample dictionary init from CSV in the simple case of the CSV being exactly key-value pairs """ import os import csv my_dict = dict() my_dir = os.path.dirname(os.path.realpath(__file__)) filename = 'dictionary_test.csv' # TODO: read the data from the csv file and put into dictionary with open(my_dir + '/' + fil...
from StringList import StringList ''' 对BF算法进行改进,即在匹配失败后,重新开始匹配时不改变主串S中的i,只改变模式串T中的j,从而减少匹配的次数 改变模式串T中的j,依据的则是模式串的next数组值 ''' class Indexkmp(StringList): #获取模式串next数组的函数 def GetListNext(self): ''' 求字符串next数组的方法,其实就是将字符串作为模式串与自己进行匹配,特殊的地方是:模式串要从主串第二个元素起开始匹配 ''' ListNext=[None for x...
#定义链栈节点 class StackNode: ''' 链栈的节点:包含一个数据域 self.data, 一个指针域 self.next 。 ''' def __init__(self): self.data=None self.next=None #定义链栈类 class LinkStack: ''' 带头节点链栈的初始化:即初始化一个栈顶节点,其数据域为None,指针域next始终指向栈顶元素,是不移动的。 元素入栈即:该指针next域改为指向该元素,而该元素next域接手指向self.top指向的入栈元素,即之前入栈的元素 ...
#!/usr/bin/env python3 # Requires PyAudio and PySpeech. import speech_recognition as sr from time import ctime import time import os from gtts import gTTS #Text_to_speech def speak(audioString): print(audioString) tts = gTTS(text=audioString, lang='bn') tts.save("audio.mp3") os.system...
# -*- coding: utf-8 -*- """ Created on Mon Nov 2 14:26:39 2020 @author: stein Kurs i Python, Oppgave 9 """ for x in range(0,5): print(f"Hei verden") for x in range(1,102): print(x) for x in range(1,101): print(x**2, end = ", ")
# coding=utf-8 """ http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-2/ """ import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from util.lib import computeCost, gradient_descent if __name__ == '__main__': path = os.getcwd() + "\data\ex1data2.txt" data2 = pd...
import pandas as pd class DataSave: """ 数据存储类 具体用法: 新建对象db = DataSave() 插入数据:db.update({...}) """ def __init__(self): self.data_frame = None def update(self, new_data): if self.data_frame is None: self.data_frame = pd.DataFrame([list(new_data.values())], co...
#Algorithm 1 ''' list = list(range(1,101,1)) for x in list: if x % 3 == 0 and x % 5 == 0: print('FizzBuzz') elif x % 3 == 0: print('Fizz') elif x % 5 == 0: print('Buzz') else: print(x) #Algorithm 2 list = list(range(1,1000,1)) sum = 0 for x in list: if x % 3 == 0 and...
#!/usr/bin/env python import argparse import sys def parse_cl_arguments(): parser = argparse.ArgumentParser(description="Reverse complement sequence") parser.add_argument( "sequence", help="Sequence to be reverse complemented (use - for stdin)" ) parser.add_argument( "-c", "--c...
""" technologies = ["AI", "hadoop", "android", "JEE"] technologies[1]= "mobile apps" #update operation/set operation print(technologies) #del(technologies[1]) print(technologies[1:3]) print(technologies[1:-2]) """ data = [1, 2, 3, 4, 5, "john", "jenny", "joe", "john"] #data.pop(3) #deletes data on the basis of i...
#assignment operator num1 = 10 #write operator / update operation num2 = 7 num2 = num1 #copy operation / reference copy #print(num2) #num1 = num1+10 #print(num1) #it can be written as num1 += 10 print(num1) # *=, /=, //=, **= """ num1 *= 2 print(num1) """ num1 **= 2 print(num1) num1 //= 7 print(num1)
#list of having only integers a= [1,2,3,4,5,6] print(a) #list of having only strings b=["hey","pravesh","google"] print(b) #list of having both integers and strings c= ["hi","yo",1,2,3,"yolo"] print(c) #index are 0 based. this will print a single character print(c[1]) #this will print "you" in list c
a = "string in quote a" b= 'string in quote b' print(a) print(b) # using ',' to concate the two or several strings print(a,"concated with",b) #using '+' to concate the two or several strings print(a+" concated with "+b)
str1 = "Hello" str2 = "World!" print("Strings Entered are"+" "+"str1="+str1+" "+"str2="+str2) print("3rd alphabet in str1"+" "+str1[3]) print("Index value of the letter 'o' in str2"+" "+str(str2.index('o'))) print("Length of str1 is"+" "+str(len(str1))) print("All Upper case of str1 is"+" "+str1.upper()) print("All Low...
import unittest # Importing the unittest module from credentials import User, Credentials # Importing the credentials class import pyperclip class TestUser(unittest.TestCase): def setUp(self): self.new_user = User("Celine", "Mmbone", "0723456789", "celinekerrine@gmail.com")...
from unittest import TestCase from . import circular_list class CircularArrayRotationTests(TestCase): sample_list = [8, 4, 6, 9, 1, 2] def test_rotate_1_time(self): rotated = circular_list.rotate(self.sample_list, 1) self.assertEqual(rotated[0], 2) def test_rotate_3_times(self): ...
# The Grid Search # https://www.hackerrank.com/challenges/the-grid-search def search(G, P): R = len(G) r = len(P) i = 0 j = 0 l = 0 m = -1 while i < R and j < r: try: k = G[i+j][l:].find(P[j]) except IndexError: break if m == -1: ...
#!/bin/env python # coding=utf-8 class Reponse(object): #Constructeur de la classe Personne def __init__(self): self.id = -1 self.reponse = None self.id_question = None self.id_questionnaire = None #Saisir un acces avec tout ses attributs d'un seul coup def set_reponse...
# Euler 231 - Binomial Prime Factorization Sum import Primes def Number_Ps_in_N_factorial(N,P): p = P num = 0 while P <= N: num += int(N/P) P *= p return num def Euler231(n,m): """ n choose m """ pList = Primes.MakePrimeList(n+1) summ = 0 for p in pL...
#--------------------------------------------------------------- # Divisibility Multipliers # # Key observation - # m must preserve divisibility by p under f(n). # In particular it must preserve divisibility of f(4p) # I use 4p instead of p to ensure that there are at least # two digit...
# Euler 262 # Kelvin Blaser 2019-02-20 # # Plotting this function in the specified area shows a few things. # The area is a 'volcano', there's a mountain with a depression in the middle. # The elevation is symmetric about the line y=x (Easily seen from the formula) # There are two paths from A to B. # 1. Through...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Одноклеточная амеба каждые три часа делится на 2 клетки. Определить, сколько будет # клеток через 6 часов if __name__ == '__main__': n = int(input("Введите количество амеб ")) n = n * 4 print("Через такое время амеб будет - ", n)
#!/usr/bin/env python3 #function defintion and input parameters def ytm(years): return int(round(years*12,0)) def calculateFutureValue(monthlyInvestment, monthlyRate, months): # iterator for length of calculation cycle futureValue = 0.0 for i in range(months): #business logic futureValue = ( ...
#!/usr/bin/env python3 import random from objects import Card, Deck, Hand def main(): print("Blackjack") print() while True: deck = Deck() deck.shuffle() dealer_hand = Hand() player_hand = Hand() # deal two cards to player and one to the dealer player_ha...
#list are not effective in stacks because of unwanted memory allocation so collections deque were used instead """from collections import deque s=deque() s.append("one") s.append("two") s.append("three") print(s) """ from collections import deque class Stack: def __init__(self): self.container ...
#!/usr/bin/env python3 import itertools def first_nonrepeating(string): ''' Find the first letter in a string that occurs only once in it. ''' badtypes = [list, tuple, int, dict, set] if type(string) in badtypes or len(string) == 0: return None letters = {} for i in string: i...
from typing import List def find_two_sum(nums: List, value: int) -> tuple: nums.sort() l = 0 r = len(nums) - 1 while l < r: if nums[l] + nums[r] < value: l += 1 elif nums[l] + nums[r] > value: r -= 1 else: return nums[l], nums[r] return t...
import pygame from pygame.locals import * from input import Input from utils import load_sound class Button(object): """ This is the Button class, which is used for handling a button. """ def __init__(self, text, callback, *args): """ @param text: The text that should be show...
""" Confirming a password entered by a User Password should not contain, Username, student id,"huddersfield","justin beiber", "cheese", "canalside" """ username = input("Enter username: ") student_id = input("Enter student id: ") password = input("Enter password: ") if len(password) in range(6,13) : if (passw...
""" Calculating Area of a Circle """ from math import pi radius = int(input("ENTER THE RADIUS IN CM: ")) Area = pi * radius * radius print("the area of the circle is {} cm^2".format(Area))
# utils.py from PIL import Image, ImageDraw, ImageFont, ImageOps def draw_rotated_text(image, text, position, angle, font, fill=(255,255,255)): # Get rendered font width and height. context = image.draw() width, height = context.textsize(text, font=font) # Create a new image with transparent background...
from tkinter import * win = Tk() ent = Entry(win).grid(row=0,column=0,columnspan=3) f='굴림', 10 btn1=Button(win,font=f,text='1-0',width=4,height=2) btn1.grid(row=1,column=0) btn2=Button(win,font=f,text='1-1',width=4,height=2) btn2.grid(row=1,column=1) btn3=Button(win,font=f,text='1-2',width=4,height=2) btn3.grid(row=1...
""" The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def sumOfPrimes(num): primeNumbers = [] for i in range(num+1): primeNumbers.append(i) primeNumbers[0] = 0 primeNumbers[1] = 0 p = 2 while(p * p <= num): if p != 0: ...
# https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn # KNN with multiple labels # this calculates Euclidean distance # but is sensitive to magnitudes; # data must be scaled accordingly # get the wine data set from sklearn import datasets wine = datasets.load_wine() ''' Just...
A = [1,2,3,4] B = [1,2,3,4] if A == B : print("True") else: print("False")
import threading import time import multiprocessing from lrthread import multiprocess def loop(): print('thread %s is running...' % threading.current_thread().name) n =0 while n <5: n = n+1 print('thread %s >>> %s' % (threading.current_thread().name,n)) time.sleep(1) print('...
import pygame import random import math # initalise the pygame pygame.init() # create a screen screen = pygame.display.set_mode((800,600)) # background background = pygame.image.load('level1bk.jpg') # title and icon pygame.display.set_caption("Hackerman Invaders") icon = pygame.image.load('ufo.png') pygame.display....
class Subjects(object): def __init__(self, subject_name, teacher): self.subject =+ subject_name self.teacher_inCharge = teacher def get_subject(self): return self.subject def teacher(self): return self.teacher_inCharge class Student(Subjects): def __init__(self, name, *...
#!/usr/bin/env python import scipy import re import sys def read_square_matrix(infile): ''' Read a matrix from infile which has been printed out in column- major form (ie like Fortran). Complain if the number of elements is not n**2 for some value of n. ''' try: f = scipy.loadtxt((...
import matplotlib.pyplot as plt from random import choice class RandomWalk(): # 一个生成随机漫步数据的类 def __init__(self, num_points=5000): #初始化随机漫步的属性 self.num_points = num_points # 所有的随机漫步都始于(0,0) self.x_values = [0] self.y_values = [0] def fill_walk(self): # 计算随机漫...
class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.name = restaurant_name self.type = cuisine_type self.number_served = 10 def describe_restaurant(self): print("The name of this restaurant is " + self.name.title() + '.') print("The type of this re...
'''list of 10 users with unique name''' name=[] for i in range(1,11): user=input(f"enter the name of the user {i}:") if user not in name: name.append(user) print(name) elif user in name: while user in name: print("the name is already taken") user =in...
# -*- coding: utf-8 -*- """ Created on Tue Dec 10 14:03:47 2019 @author: AARADHYA JAIN """ dict1={1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 225, 15: 225} set1=set([]) set1={j for j in dict1.values()} '''for j in dict1.values(): #set1 = (dict1[i] for i in r...
# -*- coding: utf-8 -*- """ Created on Tue Dec 10 23:01:09 2019 @author: AARADHYA JAIN """ n = int(input("Enter the number of strings")) for i in range(n): s = input("enter the string") j = len(s)-1 i = 0 flag = 1 while(j>=i): if(s[i]==s[j]): i=i+1 j=j-1 ...
from collections import namedtuple import random import itertools import copy from utils import argmax, vector_add inf = float('inf') inf = float('inf') GameState = namedtuple('GameState', 'to_move, utility, board, moves') class Game: """A game is similar to a problem, but it has a utility for each...
import pygame from GameStart import * class Tile: ''' Tile object: Each tile is 16 x 16 pixel legal space tile (tilechar = '1', 'D' or 'E') dead space tile (rest of tilechars) Input Argument: gameScreen: the gameScreen window from GameStart tilelocation:...
# coding: utf-8 # Face Recognition with OpenCV # To detect faces, I will use the code from my previous article on [face detection](https://www.superdatascience.com/opencv-face-detection/). So if you have not read it, I encourage you to do so to understand how face detection works and its Python coding. # ### Impor...
# %% import math def combination(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) def main(): length = int(input()) return combination(length - 1, 11) if __name__ == '__main__': message = main() print(message)
import unittest import leapYear class TestCase(unittest.TestCase): def test_isLeapYear(self): year = 2000 result = leapYear.leapYear(year) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: self.assertEqual(result, True) ...
#This is to open the file of names """ a_file = open("names.txt", "r") names = [] for line in a_file: stripped_line = line.strip() line_list = stripped_line.split() names.append(line_list) a_file.close() a_file = open("loggedin.txt", "r") logged = [] for line in a_file: stripped_line = line.strip() line_l...
''' fiz o algoritmo de euclides, mas não era suficiente foi preciso extender, material de consulta livro, wikipedia''' def euclidean_algo(m,n): if m%n==0: return n else: remainder = m%n m = n n = remainder return euclidean_algo(m,n) #print (euclidean_algo(...
import random def euclidean_algo(m,n): if m%n==0: return n else: remainder = m%n m = n n = remainder return euclidean_algo(m,n) #função para gerar pares de números def random_pairs(n): lista = [] for i in range(1,n): pairs = [] pairs.appen...
import argparse from sys import argv import socket parser = argparse.ArgumentParser(description="""This is a very basic server program""") parser.add_argument('-f', type=str, help='File to read the pairs words', default='Pairs.txt', action='store', dest='in_file') parser.add_argument('port', type=int, help='This is t...
from math_functions import * n = 1 while True: num_divisors = 0 # since n and n + 1 are coprime, number_of_factors is multiplicative and we need integer inputs if n % 2 == 0: num_divisors = number_of_factors(n / 2) * number_of_factors(n + 1) else: num_divisors = number_of_factors(n) * nu...
for i in range(1000): pass names = ["George", "Sohail", "Waad"] for name in names: print(name) if name not in ["George", "Sohail", "Waad"]: print("There is an impostor among us") break else: print("finished regularly") for (i, name) in enumerate(names): print(i, " ", name) def new_...
print("Hello, world!") func_call(7, 2, name, *arg, d=True, c=False, **kwrags) a = "My_string" if hasattr("str", "__len__"): print("a has attribute called __len__ ") else: print("a doesn't have __len__ attribute")
# # Tuple # EastAfrica= ("Somalia", "Kenya", "Uganda","Djabuti","Sudan","Rwanda") # print(EastAfrica) # accessing tuple EastAfrica= ("Somalia", "Kenya", "Uganda","Djabuti","Sudan","Rwanda") print(EastAfrica[5]) # # Negative Indexing # EastAfrica= ("Somalia", "Kenya", "Uganda","Djabuti","Sudan","Rwanda") # print(Eas...
#9. Write a Python program to combine two dictionary adding values for common keys. from collections import counter d1 = {'a':5, 'b':10, 'c':15} d2 = {'a':5, 'b':50, 'd':2} for key, value in d1.items(): if key in d2: d1[key] = value + d2[key] del d2[key] d1.update(d2) print(d1)
#10.Write a Python script to concatenate dictionaries and create a new one d1 = {1:2,2:3} d2 = {3:4,4:5} d3 = {5:6,7:8} d1.update(d2) d1.update(d3) print(d1)
def sequentsearch(target, lyst): """ :param target:目标值 :param lyst: 搜索列表 :return: 搜素成功返回位置下标 否则返回-1 """ position = 0 while position < len(lyst): if target == lyst[position]: return position position += 1 return -1 def binarysearch(target, lystlist): st...
#!/usr/bin/env python # encoding: utf-8 STRING,FUNCTION,INTEGER,EOF,END ="STRING","FUNCTION","INTEGER","EOF","." class Token(object): def __init__(self, type, value): self.type = type self.value = value def __str__(self): return 'Token({type}, {value})'.format( type=self.t...
#!/usr/bin/python from qpt_v2 import * def main(): while True: print('Enter following input in degrees...or q to quit') az = input('Enter azimuth: ') el = input('Enter elevation: ') if (az == 'q' or el == 'q'): shut_down() print('Program Terminated') ...
import sys metricValues = ['metric','Metric','METRIC'] imperialValues = ['imperial','Imperial','IMPERIAL'] acceptableUnits = metricValues + imperialValues try: #Check valid number of arguments if len(sys.argv) != 4: print "Your input is invalid!" sys.exit("Invalid number of arguments.\nUsage: ...
import sys def quit(message="Please enter valid integers."): print message sys.exit(message) def add(x,y): try: addSum = int(x) + int(y) return (addSum) except ValueError: quit("Please enter valid integers as separate arguments. Example: [10,20]") def subtraction(x,y): try...
""" author: aesavas Problem 10: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ """ This is the simplest way of solution but it is not good. Because it takes nearly 2 minutes. So this is lazy code. I share it because it is the first solution that comes to m...
""" author : aesavas A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is le...
""" author : aesavas The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and...
def fuel_recursion(l): fuel_req = int(l) // int(3) - 2 if fuel_req <= 0: return(0) else: return(fuel_req + fuel_recursion(fuel_req)) fuel_total = 0 with open("day1.in") as f: for l in f: this_fuel = fuel_recursion(int(l)) fuel_total += this_fuel print(fuel_total)
def reverse_sentace(str): revStr = "" for i in range(len(str)-1, -1, -1): revStr = revStr + str[i] return revStr def reverse_sentace_native(str): arr = list(str) arr.reverse() return "".join(arr) TST = "Some sentace for reversing!" print("Original sentance - ", TST) print("Reversed...
#~~~~~~ GAMES RULES ~~~~~~ #~~~~~~ DICTIONARIES ~~~~~~ #----- English ----- letters_english = [] #total length must be 100 for i in range(12): letters_english.append('E') for i in range(9): letters_english.append('I') letters_english.append('A') for i in range(8): letters_english.append('O') for i in range(6): ...
# -*- coding: utf-8 -*- class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def presearch(self, tree, res): if tree is None: return else: res.append(tree.val) self.pres...
import pandas as pd def explore_data(): """ Getting to know the dataset (to cleanup and set up models). """ df = pd.read_csv('DisasterDeclarationsSummaries.csv') print "-----------------------------------------" print "-----------------------------------------" print "TOTAL # OBSERVATIONS:", ...
# -*- coding: utf-8 -*- import numpy as np def Approx_Beta(vals,N): inter = .001 prop = 1./(len(vals))-inter b = True while b: prop+=inter vals2 = list(vals) #print prop try: Appel_calcul(vals2,N,prop) except: b = False return prop d...
def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' # Your code here if len(aStr) == 0: return False if len(aStr) == 1: if char == aStr[0]: return True else: ...
import math print("PLease think of a number between 0 and 100") low = 0 high = 100 computerGuess = math.floor((high + low) / 2.0) endGame = False while not endGame: print(f"Is your guess {computerGuess}?") userAnswer = input("Enter 'h' if this is too high. Enter 'l' if this is too low, and enter 'c' to s...
from random import randint class Creature: def __init__(self, health, min_attack, max_attack, min_defense, max_defense): self.health = health self.min_attack = min_attack self.max_attack = max_attack self.min_defense = min_defense self.max_defense = max_defense c...