text
stringlengths
5
121k
import matplotlib.pyplot as plt import numpy as np time = [i for i in range(0,19)] number = [9.6,18.3,29,47.2,71.1,119.1,174.6,257.3, 350.7,441.0,513.3,559.7,594.8,629.4,640.8, 651.1,655.9,659.6,661.8] plt.title('Relationship between time and number') plt.xlabel('time') plt.ylabel('number'...
number=input("Enter a number between 1-5 :") number=int(number) if number==1: print("number is one") elif number==2: print("number is two") elif number==3: print("number is Three") elif number==4: print("number is Four") elif number==5: print("number is Five") else: print("The number is...
class TvShow: def __init__(self, name, year, ): self._name = name.title() self.year = year self._likes = 0 def like(self): self._likes += 1 @property def name(self): return self._name @property def likes(self): return self._likes @name.sett...
def reverseBits(n): binary = '{0:032b}'.format(n) rev = "" for item in binary: rev = item + rev return int(rev, 2)
def containsDuplicate(nums): if not nums: return False values = {} for item in nums: values[item] = values.get(item, 0) + 1 for key, value in values.iteritems(): if value >= 2: return True ret...
import sys print("""hey player yu can enter your input by choosing a number from 1-9 1|2|3 ----- 4|5|6 ----- 7|8|9 """) board=[" "," "," "," "," "," "," "," "," "] def disp(): print(f"{board[0]}|{board[1]}|{board[2]}") print("_____") ...
L = [3, 6, 7, 4, -5, 4, 3, -1] if sum(L)>2: print(len(L)) if abs(max(L)-min(L))>10: print(sorted(L)) else: print("Ferq 10-dan kichik-beraberdir.")
import csv from contact import Contact class ContactBook: def __init__(self): self._contacts = [] self._load() def add(self, name, phone, email): self._contacts.append(Contact(name, phone, email)) self._save() def remove(self, name): try: self._contact...
import re def normalize(text: str) -> str: text = re.sub('\([^\s]*?\)', '', text) text = re.sub('\[[^\s]*?\]', '', text) text = re.sub('\{[^\s]*?\}', '', text) text = text.strip() text = re.sub(' +', ' ', text) text = re.sub(' ,', ',', text) text = re.sub(' ;', ';', text) text = re...
import csv class VDC(object): def __init__(self, district, name, number ,pop_male,pop_female): self.district = district self.name = name self.number = number self.pop_male = pop_male self.pop_female = pop_female def __str__(self): return str("District: %s, Name:...
import oauth2 import sys import time import settings def sign_oauth_request(url): consumer = oauth2.Consumer(key=settings.CONSUMERKEY, secret=settings.CONSUMERSECRET) token = oauth2.Token(key=settings.ACCESSTOKEN, secret=settings.ACCESSTOKENSECRET) params = {} params['oauth_version'] =...
""" An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours, plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours an...
def merge(lyst, copybuffer, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high + 1): if i1 > middle: copybuffer[i] = lyst[i2] i2 += 1 elif i2 > high: copybuffer[i] = lyst[i1] ...
""" File: die.py This module defines the Die class. """ from random import randint class Die: """This class represents a six-sided die.""" def __init__(self): """Creates a new die with a value of 1.""" self.value = 1 def roll(self): """Resets the die's value to a random number ...
""" File: testquicksort.py Tests the quicksort algorithm """ def quicksort(lyst): """Sorts the items in lyst in ascending order.""" quicksortHelper(lyst, 0, len(lyst) - 1) def quicksortHelper(lyst, left, right): """Partition lyst, then sort the left segment and sort the right segment.""" if left ...
""" File: counterdemo.py """ from breezypythongui import EasyFrame class CounterDemo(EasyFrame): """Illustrates the use of a counter with an instance variable.""" def __init__(self): """Sets up the window, label, and buttons.""" EasyFrame.__init__(self, title = "Counter Demo") sel...
""" Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. Use "The t...
""" Instructions for programming Exercise 9.10 Geometric shapes can be modeled as classes. Develop classes for line segments, circles, and rectangles in the shapes.py file. Each shape object should contain a Turtle object and a color that allow the shape to be drawn in a Turtle graphics window (see Chapter 7 for detai...
""" Instructions Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 ye...
""" Instructions for programming Exercise 4.7 Write a script that decrypts a message coded by the method used in Project 6. Method used in project 6: Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypt...
""" Instructions for programming Exercise 4.6 Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5 to code a new encryption algorithm. The algorithm should Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string on...
""" Instructions A local biologist needs a program to predict population growth. The inputs would be: The initial number of organisms The rate of growth (a real number greater than 1) The number of hours it takes to achieve this rate A number of hours during which the population grows For example, one might start wi...
""" Instructions for programming Exercise 5.9 In Case Study: Nondirective Psychotherapy, when the patient addresses the therapist personally, the therapist’s reply does not change persons appropriately. To see an example of this problem, test the program with “you are not a helpful therapist.” Fix this problem by repa...
import numpy as np size = 4 board = np.zeros((size, size)) def iter(board, column): for row in range(board.shape[0]): if is_stable(board, row, column): board[row][column] = 1 iter(board, column + 1) board[row][column] = 0 print(board) def is_stable(board, row, ...
import numpy as np from scipy.spatial.distance import pdist, squareform import matplotlib.pyplot as plt a = np.arange(1, 13).reshape(4, 3) print(a) b = np.array([0, 2, 0, 1]) print("----\n", a[np.arange(4), b]) a[np.arange(4), b] += 10 print("======\n", a) print("+++") x = np.array([[1, 2, 3], [...
def decodeNumber(s): if not s: return 0 prev, curr, prev_value = 0, 1, "" print(prev, curr, prev_value) for digit in s: prev, curr, prev_value = curr, (digit > '0') * curr + int(10 <= int(prev_value + digit) <= 26) * prev, digit return curr print("*" * 10) print(decodeNumber("1234"...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 condition = True l3 = ListNode(0...
print('Tablas ') for i in range(1,11): print('\nTABLA DEL ',i) for j in range(0,11): print(i,' x ',j,' = ',(i*j))
import math message = input('Ingresa el radio del circulo: ') r = int(message) area = math.pi * r**2 print('El area es: ',area)
function=input("enter string") name=input("enter string") def string(x,y): if len(x)>len(y): print(x) else: print(y) string(function,name)
""" https://www.hackerrank.com/challenges/balanced-brackets """ from stack import Stack def is_balanced(s): if len(s) % 2 == 1: return 'NO' else: stack = Stack() counterparts = {'{':'}', '[':']', '(':')'} for char in s: if char in counterparts: ...
""" Implements a stack with a O(1)-time operation to get the max of the stack. """ from stack import Node, Stack class StackWithMaxAPI(Stack): def __init__(self, node=None): super(StackWithMaxAPI, self).__init__(node) self.maxs = Stack(node) def push(self, data): super(StackWithMaxA...
class SinglyLinkedListNode(): """A node with a data and next attribute.""" def __init__(self, dat, next_node=None): self.data = dat self.next = next_node def __str__(self): return "| {} |".format(self.data) def __repr__(self): return self.__str__() class SinglyLink...
prompt = str.lower(input('What is the name of the file to read? ')) try: fhand = open(prompt) except: print('Please choose an existing file') exit() for line in fhand: line = line.upper() print(line)
prompt = str.lower(input('What is the name of the file to read? ')) try: fhand = open(prompt) except: print('Please choose an existing file') exit() count = 0 for line in fhand: if line.startswith('From:'): line = line.rstrip() count = count + 1 print('Total count in file: %s' ...
class Stack: def __init__(self): self.__stack = list() def __str__(self): return str(self.__stack) def push(self, value): self.__stack.append(value) return self.__stack[len(self.__stack) -1] def pop(self): if len(self.__stack) > 0: temp = self.__s...
import mis_funciones datos = [2, 3, 4, 7, 0, 1, 56, 6] mis_funciones.agregar(datos, 100) print(datos)
""" private protected economy memory slots """ class Client(object): """ Why client? """ __slots__=('__dict__','_id') def __init__(self, id, card_number): """ :param id: :param card_number: """ self._id = id self.__card_number = card_number ...
deckSize = 10007 checkValue = 2019 class Deck: def __init__(self, sizeOfDeck): self.deck = list(range(sizeOfDeck)) return def printDeck(self): print(self.deck) def reverseShuffle(self): print("Reversing Deck") self.deck.reverse() def cutN(self, n...
import sys class TicTacToeGame(object): board = [[None, None, None], [None, None, None], [None, None, None]] turn = True def reset_game(self): print('\n Game reset') self.turn = True for i in range(3): for j in range(3): self.board[i][j] = None def play(self): while 1: m...
""" Tuples are same as list. The diffferance between list and tuples. Tuples are unmutalble. Tuples add using parenthesis """ my_tuple=(1, 2, 3, 4,3, 3, 3) print(my_tuple) print(my_tuple[1]) print(my_tuple[1:]) print(my_tuple[::-1 ]) print(my_tuple.index(3)) print((my_tuple.count(3)))
""" Lists are orderder items witch comes with brackets and seperated with comma """ lst=['Rahul', 'Mahesh', 'Vishal'] print(lst) lst[1]="Gaurav" print(lst) print(lst[::-1]) print lst2=[1,4,5,6,7,8,] sum_lst=lst2[1]+ lst2[4] print(sum_lst) sum_lst2=lst[1]+lst[2] print(sum_lst2) print("**************") list=["b...
""" Object is a instace of class """ class car(object): def __init__(self, make,year): self.makeof_Car=make, self.year=year c2=car('Maruti', 2019) print(c2.makeof_Car) print(c2.year) c3=car("Innova", 2020) print(c3.makeof_Car) print((c3.year))
numero = eval(input("Informe o nmero:\n")) soma = 0 for i in range(1, numero + 1): soma = soma + i print("O resultado obtido foi:", soma)
import random class Solution: def GetLeastNumbers_Solution(self, tinput, k): result = [] if (len(tinput) == 0 or k <= 0 or k > len(tinput)): return result pos, start, end = -1, 0, len(tinput) - 1 while(pos != k - 1): if (pos > k - 1): end = pos - 1 e...
import face_recognition from PIL import Image, ImageDraw image_path = '../data/without_mask/0.jpg' mask_image_path = '../data/mask.png' face_image_np = face_recognition.load_image_file(image_path) face_locations = face_recognition.face_locations(face_image_np, model='hog') face_image = Image.fromarray(face_image_n...
import streamlit as st from PIL import Image from predict import model, tokenizer, maxlength from predict import extract_features, generate_description def get_caption(img): with st.spinner('Extracting features from image...'): img = extract_features(img) with st.spinner('Generating descri...
import turtle angle = 5 collist2 = ['red', 'crimson', 'orangered', 'darkorange', 'orange', 'gold', 'yellow', 'greenyellow', 'lawngreen', 'limegreen', 'springgreen', 'mediumspringgreen', 'aquamarine', 'turquoise', 'aqua', 'deepskyblue', 'dodgerblue', 'mediumslateblue', 'mediumpurple', 'blueviolet', 'darkviolet', 'purpl...
""" You have solar panels that are mounted on a pole in your front yard. They have three settings that tip the panels at different angles with respect to the horizontal. As the seasons change, the settings allow you to capture more solar energy by better aligning the tipping angle of the panels with the position of t...
def file1(): file1=open("delhi.txt","r") c=0 for i in (file1): c=c+1 print(i) file1.close() def file2(): file2=open("shimla.txt","r") d=0 for j in (file2): d=d+1 print(j) file2.close() def file3(): file3=open("others.txt","r") e=0 for k in (fil...
t=int(input()) for i in range (t): n=int(input()) a,b,sum=1,2,0 while b<=n: if b%2==0: sum+=b a , b = b , a+b print(sum)
num1 = int(input("Numero 1:")) num2 = int(input("Numero 2:")) valor = int((num1 - num2) * num1) print(valor)
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: pre, pre.next = self, head while pre.next and pre.next.next: a = pre.next b = a.next ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements1(self, head, val): dummy = ListNode(-1) dummy.next, prev = head, dummy while prev.next: if prev.next.val == val: prev.n...
class Solution: def maxArea_1(self, height): result = 0 for i in range(0, len(height)): for j in range(i + 1, len(height)): result = max(result, min(height[i], height[j]) * (j - i)) return result def maxArea_2(self, height): result, le...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getIntersectionNode(self, headA, headB): if not headA and not headB: return None a, b = headA, headB while a is not b: a = headB if a is None els...
def shipsPlacement(): return ( [4, [0, 0], 'right'], [3, [2, 0], 'right'], [3, [9, 2], 'top'], [2, [0, 5], 'bottom'], [2, [0, 9], 'bottom'], [2, [7, 9], 'left'], [1, [0, 7], 'right'], [1, [5, 3], 'right'], [1, [5, 7], 'right'], [1,...
def calc_interval(freq, word): low = 0 high = 1 for char in word: Range = high - low high = low + Range * freq[char]['higher'] low = low + Range * freq[char]['lower'] print(char, ':', low, high) return low, high def get_char_freq(word): freq = {} for char in...
import re n = input() if (re.match('.*7.*', n)): print("Yes") else: print("No")
import math import os import random import re import sys def migratoryBirds(arr): dict = {} for no in arr: if no not in dict.keys(): add = {no: arr.count(no)} dict.update(add) mvalue = 0 mkey = 0 print(dict) for key,value in dict.items(): if value > m...
print("enter your favorite number") n = int(raw_input()) while n != 14: print("i don't like that number- please try another number") else: n == 14 print("that is the best number")
""" Count the number of times a depth measurement increases """ def num_increases(report): depths = report.split() return sum(d2 > d1 for d1, d2 in zip(depths, depths[1:])) if __name__=="__main__": report = """ 199 200 208 210 200 207 240 2...
""" Program: lottery.py Anthor: Li Chan Project: Lottery Quick Pick This program generates 5 random numbers between 1 and 50. By clicking the Quick Pick button,the computer randomly selects the numbers for you. """ from tkinter import * import random def pickNum(): lottoNum = [] for i in range(5)...
class myClass(): def method1(self): print("myClass method 1") def method2(self, someString): print("myClass method 2 " + someString) def method3(self, someString=""): print("myClass method 3 " + someString) class childClass(myClass): def method1(self): myClass.method1...
def fact(n): return fact_iter(n, 1) def fact_iter(num, porduct): if num == 1: return porduct return fact_iter(num-1, num * porduct) print(fact_iter(1000,1))
name = input("Enter your name: ") age = input("Enter your age: ") print(name) print(age) print("") print("Hello World!")
""" Simulates a magic eight ball. Prompts the user to type a yes or no question and gives a random answer from a set of prefabricated responses. """ import random RESPONSES = ["As I see it, yes.", "Ask again later.", "Better not to tell you now." , "Cannot predict now.", "Concentrate and ask again.", "Don't count on i...
""" Example of using the index variable of a for loop """ def main(): pass def is_divisible(a, b): """ >>> is_divisible(20, 4) True >>> is_divisible(12, 7) False >>> is_divisible(10, 10) True """ return a % b == 0 def is_leap_year(year): """ Returns Boolean indicating ...
from karel.stanfordkarel import * """ File: Midpoint.py ------------------------ Place a beeper on the middle of the first row. """ def main(): """ Your code here """ paint_corner(CYAN) move_to_wall() paint_corner(CYAN) turn_around() move_if() while corner_color_is(BLANK): ...
import csv def write_data(): with open("data.csv", "w") as f: columns = ['x', 'y'] writer = csv.DictWriter(f, fieldnames=columns) writer.writeheader() writer.writerow({'x': 1, 'y': 2}) writer.writerow({'x': 2, 'y': 4}) writer.writerow({'x': 4, 'y': 6}) def main(): write_data() if __name__ == "__main...
from itertools import islice, chain def grouper_chunk(n, iterable): "grouper_chunk(3, '[1,2,3,4,5,6,7]') --> [1,2,3] [4,5,6] [7]" it = iter(iterable) while True: chunk = islice(it, n) try: first_el = next(chunk) except StopIteration: return yield cha...
def sum_up(filename): total = 0 with open(filename) as f: for line in f: total += int(line) return total def first_twice(filename): seen_freqs = {0} cur_freq = 0 while True: with open(filename) as f: for line in f: cur_freq += int(line) ...
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def findSum(arg1): a = arg1 arr3 = [] for i in range(1,x+1): if 3 * i > x: ...
veces = int (input("Cuantos numeros ingresa?: ")) par=0 impar=0 for x in range(veces): nume = int (input("ingrese un numero : ")) if (nume%2==0): par=par+1 elif(nume%2!=0): impar=impar+1 print("La cantidad de numero pares es: " + str(par)) print("La cantidad de numero impares es: " + str(...
__author__ = 'vivian' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ left = {}; if len(nums) < 2: return False for i in range(len(nums)): if nums[i] in ...
import re findout=re.compile("i*") print(findout.findall("Osman is a good boy")) print(re.split("[a-e]", "Hi this is Osman")) print(re.sub("shi", "dim", "I am Shirin. yes it is Shirin",flags=re.IGNORECASE)) regex=r"([a-zA-Z]+) (\d+)" match=re.search(regex, "I was born on June24") try: print(match.start(),mat...
def welcome(): print("Hello... Welcome to Python...") welcome() def sum(a, b): c = a + b print("Sum of 2 Numbers: - " + str(c)) sum(25, 25)
number = input("Pls enter number - ") for i in range(int(number)): print(i)
number = input("PLS enter number - ") for i in range(10,0,-1): print(int(number) *1)
num = input("Please enter your number - ") num = int(num) if(num != 100): print("This is Valid number ") else: print("This is INvalid number ")
""" Find the area of a circle. """ from math import pi radius = float (input ('Enter the radius of the circle: ')) print ('The area is', pi * radius * radius)
sweets = int (input ('How many sweets are there? ')) bag_size = int (input ('How many sweets fit in each bag? ')) full_bags = sweets // bag_size left_over = sweets % bag_size print ('You will get', full_bags, 'full bags.') print ('There will be', left_over, 'sweets spare.')
def hands_table_clear(table, said_cards): """ for some decisions clears table and say lists :param tuple player_hands_table_say not cleared table and say :return tuple player_hands_table_say cleared table and say """ table.clear() said_cards.clear() return table, said_cards def do_yo...
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_circles class NeuralLayer: def __init__(self, n_connections, n_neurons, act_fun): self.act_fun = act_fun self.bias = np.ones([1, n_neurons]) self.weight = np.random.rand(n_connections,...
import collections import re class SetElement: def __init__(self): self.parent = self def root(self): if self.parent is self: return self else: return self.parent.root() def union(self, other): self.root().parent = other.root() Building = coll...
""" Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cy...
import sys from pyspark import SparkContext if __name__ == "__main__": ''' Create a Spark program to read the first 100 prime numbers from in/prime_nums.text, print the sum of those numbers to console. Each row of the input file contains 10 prime numbers separated by spaces. ''' sc = SparkCont...
import random class Password: def __init__(self,sequence,limit): ''' No return initializes variables ''' self.sequence = sequence self.limit = limit def create_password(self): ''' Returns password Opens the text file for the word list an...
import unittest from src.main import Point class PointTestCase(unittest.TestCase): def test_point_validity(self): point = Point(7, -14) self.assertEqual(point.x, 7) self.assertEqual(point.y, -14) def test_point_equality(self): point1 = Point(0, 0) point2 = Point(0, 0...
from json import JSONDecodeError import requests import pandas as pd from flatten_json import flatten class APIParser: """Takes in url and json_format (flat, structured)""" def __init__(self, url, json_format): self.url = url self.json_format = json_format def parse(self): """Pa...
epsilon = 0.01 lower = balance / 12 upper = balance * ((1 + annualInterestRate / 12.0) ** 12) / 12.0 result = (lower + upper) / 2.0 def rest(monthlyPayment): rest_balance = balance for m in range(12): interest = (rest_balance - monthlyPayment) * annualInterestRate / 12.0 rest_balance = rest...
mbox = open('mbox-short.txt') count = dict() for line in mbox: newLine = line.find('From ') if newLine is not 0: continue else: amper = line.find('@') endspot = line.find(' ',amp...
class PartyAnimal: x = 0 name = '' def __init__(self, nam): self.name = nam print(self.name,'constructed') def party(self) : self.x = self.x + 1 print(self.name,'party count',self.x)
from threading import Thread import time count = 0 def timer(name, n): global count while True and count < 10: print("{} : {} ".format(name, time.strftime('%Y-%m-%d %X',time.localtime()))) time.sleep(n) count += 1 if __name__ == "__main__": t1 = Thread(target=timer, args=('Threa...
import sys def Find_minnum(list,sum,num): if len(list)==0: return -1 if sum in list: num+=1 if sum < list[0] and sum != 0: return -1 if sum>list[0] and sum<list[-1]: for i in range(len(list)): if list[i]>sum: list.pop(i) if ...
cars=['bmw','audi','toyuta'] cars_1='bmm' print(cars_1 in cars) alien={'color':'green','points':5} print(alien['color']) print(alien['points']) print(alien) alien['x']=1 alien['y']=2 print(alien) alien['color']='red' print(alien) for key,value in alien.items(): print('\nkey:'+key) print('val...
import threading a=0 lock=threading.Semaphore(1) def inc(): global a,lock lock.acquire() for x in range(1000000): a=a+1 lock.release() def main(): print('we start a = ',a) t1=threading.Thread(target=inc,name='t1') t2=threading.Thread(target=inc,name='t2') t1.start() t2.start() t1.join() t2.join()...
'''Lets a player make a move''' def Move(Master,Player_lst,Turn): from copy import copy from Message import Clear,Card_display Hand=Master[Player_lst[Turn]] Clear() print('Your current hand:\n') Card_display(Hand) if len(Master['Trash'])!=0: Top=Master['Trash'][-1] print(...
base = float(input("Ingrese la base de su figura: ")) altura = float(input("Ingrese la altura de su figura: ")) numero = 1 lM = 0 lm = 0 if base > altura: lM = base lm = altura else: lM = altura lm = base no_entran = [] si_entran = [] while numero > 0: radio = float(input("Ingrese un radio: ")) ...
numero_1 = int(input("Ingrese un numero entero: ")) numero_2 = int(input("ingrese un segundo numero entero: ")) if numero_1 % numero_2 == 0: print(f"La division es exacta") print(f"Cociente = {numero_1 / numero_2} ") print(f"Resto = 0") else: print(f"La division no es exacta") print(f"Cociente = {nu...