text
stringlengths
37
1.41M
# 10001st prime # Problem 7 # Published on 28 December 2001 at 06:00 pm [Server Time] # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? def problem(): import eulertools prime_list = eulertools.primeseive(120000) return prime_...
# sql1.py """Volume 3: SQL 1 (Introduction). Adam Robertson Math 321 November 8, 2018 """ import csv import sqlite3 as sql import numpy as np from matplotlib import pyplot as plt # Problems 1, 2, and 4 def student_db(db_file="students.db", student_info="student_info.csv", student...
# numero_valido=False # while not numero_valido: # try: # a = input('Ingresá un número entero: ') # n = int(a) # numero_valido = True # except ValueError: # print('No es válido. Intentá de nuevo.') # print(f'Ingresaste {n}.') # numero_valido=False # while not numero_valido: # ...
# Import math Library from math import pi radio = 6 volumen = 4 / 3 * pi * radio ** 3 print ("El vomunen de la esfera es:", round(volumen, 2))
x = 5 print(type(x)) int z="Hello World" print(type(x)) str y = 20.5 print(type(y)) float
def palindrome(str): if len(str) < 1: return True else: if str[0] == str[-1]: return palindrome(str[1:-1]) else: return False a=str(input("aza")) print(palindrome('aza'))
from nltk.tokenize import word_tokenize from nltk.probability import FreqDist from nltk.corpus import wordnet from nltk.corpus import stopwords text = """Hi Mr. John, how are you, please? I hope you are fine. Tomorrow at 9 am a meeting suggested by Investors.""" # Remove the stop words from a text stop_words = set(st...
from nltk.stem import PorterStemmer from nltk.tokenize import sent_tokenize, word_tokenize text2 = """I have seen you drinking with your ex""" porterStemmer = PorterStemmer() stop_words2 = set(stopwords.words("english")) words2 = word_tokenize(text2) without_stop_words2 = [word for word in words2 if not word in stop_...
import numpy as np def powers(base,n): e = 2 num = base ** e while e <= n: yield num e=e+1 num = base ** e out= set() for i in range(2,101): print i out |= set(powers(i,100))
import numpy as np from collections import Counter def prime_sieve(n): upper = n candidates = np.arange(upper+1) for i in np.arange(2,upper): if candidates[i]!=0: candidates[2*i::i] = 0 c=[int(n) for n in candidates.tolist() if n not in [0,1]] return(c) def ispandigit(n): number = str(n) l = len(number...
#!/usr/bin/env python3 ''' Converts a decimal digit to its unsigned integer complement. Author: Alexander Roth Date: 2016-03-17 ''' import sys def main(args): filename = args[1] line_generator = read_file(filename) try: while True: line = next(line_generator) base_lis...
#########贪心算法################################### # 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi , # 这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i , # 这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 # 注意: # 你可以假设胃口值为正。 # 一个小朋友最多只能拥有一块饼干。 # 示例 1: # 输入: [1,2,3], [1,1] # 输出: 1 # 解释: # 你...
sehirler = ["Ankara", "İstanbul", "İzmir"] for sehir in sehirler: print(sehir) for sayi in range(10): # sayı 0dan başladı print(sayi) for sayi in range(1, 10): print(sayi) for sayi in range(1, 10, 2): print(sayi) for sayi in range(0, 10, 2): print(sayi) sayac = 1 while sayac <= 10: prin...
#!/usr/bin/env python import csv import datetime import requests FILE_URL = "https://storage.googleapis.com/gwg-hol-assets/gic215/employees-with-date.csv" def get_start_date(): """Interactively get the start date to query for.""" print() print('Getting the first start date to query for.') print() ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: lesson66_2.py # Author: peter.chen list_1 = [1,2,3,5,8,13,22] list_2 = [i for i in list_1 if i % 2 == 0] print list_2
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: lesson49.py # Author: peter.chen class Car: speed = 0 def drive(self,distance): time = distance /self.speed print time car1 = Car() car1.speed = 60.0 car1.drive(100.0) car1.drive(200.0) car2 = Car() car2.speed = 150.0 car2.drive(100.0)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: lesson61.py # Author: peter.chen import time starttime = time.time() print 'start:%f' % starttime for i in range(10): print i time.sleep(1) endtime = time.time() print 'end:%f' % endtime print 'total time:%f' % (endtime - starttime)
#字符串 strs = ['runoob.com','runoob','Aunoob'] for str in strs: print(str.isalnum(), # 判断所有字符都是数字或者字母 str.isalpha(), # 判断所有字符都是字母 str.isdigit(), #判断所有字符都是数字 str.islower(), # 判断所有字符都是小写 str.isupper(), # 判断所有字符都是大写 str.istitle(), # 判断所有单词都是首字母大写,像标题 str.isspa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 7 16:14:53 2018 @author: valen """ from turtle import * def branch(length, level): #print("step") if level <0: #base case return forward(length) left(45) branch(0.6 * length, level-1) # recursice case: left branch ...
def File1 (): file1 = open (input("PLease enter the right name of the file")) readFile1 = file1.readlines() count = 0 for line in readFile1: words = line.split() count = count+len(words) print(count) DummyLine = "Python is a language, I am learning it, my name i...
#Create a function that advances Fibonacci by one def fibonacci_sequence(): ''' helper function we're hooking you with a partial answer, just this first time! ''' fib_of_n, fib_of_n_plus1 = 1, 1 while True: fib_of_n, fib_of_n_plus1 = fib_of_n_plus1, fib_of_n + fib_of_n_plus1 yield fi...
#!/usr/bin/env python # coding: utf-8 """ date: 2017/7/25 冒泡算法的多个实现 """ class BubbleSortV1(object): """最原始的冒泡算法, 无论是最好最坏的情况下, 其复杂度都是: O(n^2)""" def __init__(self, array, length): self.array = array self.length = length def sort(self): """ 升序排序 :return: "...
import os import argparse import sys import re def mem_convert(input_file, output_file): """ Change mem initialization syntax """ with open(os.path.join(os.getcwd(), input_file), 'r') as f: input_file_data = f.read() input_mem_regex = r' reg \[(.*)\] (\S*) \[(.*)\];\n initial begin\n(( \S*\...
""" ----------------------------------------- Função: Informa qual dois números informados é maior Autor: Nicolas Florencio Alves. Data de criação: 09/08/2020. Data de modificação: 09/08/2020. ------------------------------------------- """ n1 = float(input("Informe o primeiro valor: ")) n2 = float(input("Informe o...
""" ----------------------------------------- Função: Informa se o número está entre 5 e 20, se estiver entre este intervalo calcula o cubo desse número Autor: Nicolas Florencio Alves. Data de criação: 09/08/2020. Data de modificação: 09/08/2020. ------------------------------------------- """ n = int(input("Infor...
""" The python script to generate the network plot Use list that contains the hashtags data in the time window that you want to plot """ import networkx as nx from itertools import combinations, permutations import matplotlib.pyplot as plt def edges(lst): """ Fucntion that return edges between all nodes ...
#Develop code that considers a given list and iterates it from the reverse direction. (Use iterator class for this problem). input_list = [0,1,2,3,4,5,6,7,8,9] my_list = input_list[::-1] value=my_list.__iter__() for i in my_list: try: item=value.__next__() print(item) except StopIter...
def main(student_list): print(student_list) name = input("Please input a student's name:") found = -1 for index in range(len(student_list)): # print(student_list[index]["name"]) if name in student_list[index]["name"]: found = index break if found == -1: ...
import random def main(): init_val = 0 end_val = 100 ans = guessing() correct_flag = True count = 0 while correct_flag: value = int(input('Please guess a number from:{} to {} : '.format(init_val,end_val))) if value < end_val and value > init_val: if value ...
class Node: def __init__(self, value, next_node): self.value = value self.next_node = next_node class Queue: def __init__(self): self.first = None self.last = None def add(self, value): new = Node(value, None) if self.is_empty(): self.first = ne...
#!/usr/bin/env python #-*- encoding:utf-8 -*- ''' stack.py: stack abstract data structure implementation used by python ''' class Stack: def __init__(self): self._items = [] def is_empty(self): return len(self._items) == 0 def push(self, item): self._items.append(ite...
import numpy ''' Strings ''' str = "It is String" b = "Hello, World!" #Slicing print(b[2:5]) print(b[:5]) #Negative Indexing print(b[-13:-8]) #Uppercase print(b.upper()) print(b.lower()) #Remove whitespace c = " Hello, World " print(c.strip()) ''' Use negative indexes to start the slice from the end of the string: ''' ...
import sys, pygame pygame.init() white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) gameDisplay = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Fun game!') gameExit = False char_x = 300 char_y = 300 char_x_change = 0 clock = pygame.time.Clock() while not gameExit: #gameloop for event i...
import sys import pygame import random def main(): pygame.init() white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) disp_width = 800 disp_height = 600 gameDisplay = pygame.display.set_mode((disp_width, disp_height)) pygame.display.set_caption('Fun game!') gameExit = False char_x = disp_width/...
#!/bin/python3 import re n,m=map(int,input().split()) l=list() for i in range(n): l.append(input()) l=list(zip(*l)) s='' for i in l: s=s+''.join(i) s='' for i in l: s=s+''.join(i) s=re.sub(r'\b[^a-zA-Z0-9]+\b',r' ',s) print(s) ''' Neo has a complex matrix script. The matrix script is a X grid of string...
#!/usr/bin/python import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) # set the board numbering system to BCM led = 17 #setup our output pins GPIO.setwarnings(False) GPIO.setup(led,GPIO.OUT) print ("Led On") GPIO.output(led, GPIO.HIGH) sleep(10) print ("Led Off") GPIO.output(led, GPIO.LOW)
for n in range(101): print "-------------------" print "This is Number %d" %n print "In Decimal : " + str(n) print "In Biner : " + str(bin(n)) print "In Octadecimal : " + str(oct(n)) print "In Hexadecima : " + str(hex(n))
import datetime # this is an example progame def birth_date(): year = int(input('Which year did u born?\n')) current_year = datetime.datetime.now() print(f"your age is {current_year.year - year}")
""""" Given a string of even length, return the first half. So the string "WooHoo" yields "Woo". first_half('WooHoo') → 'Woo' first_half('HelloThere') → 'Hello' first_half('abcdef') → 'abc' """ def first_half(str): strlen = len(str) if strlen>1: x = int(strlen/2) str = str[0:x] return str return st...
#if -else conditions a=5 # a icin 5 degerini atadik b=6 # b icin 6 degerini atadik if(a>b): # eger a > b ise ekrana alttaki ifadeyi yaz ve a ile b yi toplayip c ye at. print("a is greater than b ") c= a+b else: #eger a > b degilse, ekrana alttaki ifadeyi yaz ve b den a yi cıkarip, c ye at. pri...
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("30 days 30 hours challenge") 30 days 30 hours challenge >>> print('30 days 30 hours challenge') 30 days 30 hours challenge >>> Hours = ...
########################### # 6.0002 Problem Set 1a: Space Cows # Name: # Collaborators: # Time: from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ # Problem 1 def load_cows(filename): """ Read the conten...
#!/usr/bin/env python3 def prime_factors(n): i = 2 factors = {} while n > 1: if n % i: i += 1 else: n //= i if i not in factors: factors[i] = 1 else: factors[i] += 1 return factors def nr_divisors(n): d = prime_factors(n) nr = 1 for k in d: nr *= d[k...
def part1(): result = 0 with open('day1.txt', 'r') as file: for line in file: fuel = int(line) // 3 - 2 result += fuel print(result) def part2(): result = 0 with open('day1.txt', 'r') as file: for line in file: fuel = int(line) while ...
country = input('Please enter your country') age = input('How old are you?') age = int(age) if country == 'Taiwan': if age >= 18: print('You can drive ~~~~~' ) else: print('You can not QQ') elif country == 'USA': if age >= 16: print('You can drive ~~~~~' ) else: print('You can not QQ') else: print('You ca...
class replacing_decorator_class(object): def __init__(self, arg): # this method is called in the decorator expression print("in decorator init, %s" % arg) self.arg = arg def __call__(self, function): # this method is called to do the job print("in decorator call, %s" % self.arg) ...
number1=int(input("enter the number")) number2=int(input("enter the number")) print("Largest of two is %d"%max(number1,number2))
def replace(test_string="", replace_string=""): if replace_string == "": return test_string n = test_string.find(replace_string) return_string = "" if n == -1: return_string = test_string else: return_string = test_string[0:n] + "bodega" + \ test_string[n + len(repla...
from util import memoize, run_search_function, INFINITY def basic_evaluate(board): """ The original focused-evaluate function from the lab. The original is kept because the lab expects the code in the lab to be modified. """ if board.is_game_over(): # If the game has been won, we know that...
def add(*params): sumOfNumber = 0 for element in params: sumOfNumber += element print('sumOfNumber:', sumOfNumber) print('Enter two number for addition') number1 = int(input()) number2 = int(input()) add(number1, number2) print('Enter three number for addition') number1 = int(input()) number2 = in...
def printReverseWithSpace(firstName, lastName): return (' ').join([firstName[::-1], lastName[::-1]]) firstName = input('Enter first name:') lastName = input('Enter last name:') print(printReverseWithSpace(firstName, lastName))
def turnOffGivenBit(number, bit, numberOfBit): modifiedNumber = 1<<bit-1 numberOfBitToChange= 1<<bit - numberOfBit numberToCheck = modifiedNumber | numberOfBitToChange print(number & ~numberToCheck) number = int(input('Enter the number:')) bitPosition = int(input('Enter the bit-position to turned off:...
def checkNumberIn1000(inputNumber): return (abs(1000 - inputNumber) <= 100) or (abs(2000 - inputNumber) <= 100) print(checkNumberIn1000(int(input('Enter number:'))))
1- take words from textfile. DONE! 1- compare words one by one to a database of MyKnowledge. DONE! 1- show all text again with marked unknown words. DONE! 1- show unknows one by one to user, ask if he knows them or not. DONE! 3-send the known ones to MyKnowledge. DONE! 4- save the unknown ones to a StudyList TODO:...
def nota_quices(codigo: str, nota1: int, nota2: int, nota3: int, nota4: int, nota5: int) ->str: notas = (nota1, nota2, nota3, nota4, nota5) min = max = notas[0] for nota in notas: if nota < min: min = nota elif nota > max: max = nota ...
# Calculates number of days until april fool day # April 1st is april fool day from datetime import date def howmanydayuntilaf(): # Today's date today = date.today() # April fools date afdate = date(day = 1, month = 4, year = today.year) # if april fool has already passed if afdate < today: # Next april foo...
# importing specific class from module datetime from datetime import date from datetime import time from datetime import datetime def main(): # Date Object # Get today's date from today() method of class date today = date.today() print(today) # Date components print("Day: ", today.day, " Month: ", today.month...
#!/usr/bin/python from math import log, floor, ceil def make_tree(left, root, right): return (left, root, right) def make_leave(value): return make_tree(None, value, None) def get_left(tree): return tree[0] def get_root(tree): return tree[1] def get_right(tree): return tree[2] def get_height(tr...
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 21:28:31 2021 @author: manik """ class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.num_elements = 0 self.head = None def push(sel...
import turtle import random wn = turtle.Screen() wn.colormode(255) # so as to randomly assign colors to different branches of the fractal tree wn.title('Fractal Tree!') # give the title to the window myTurtle = turtle.Turtle() wn.setup(1200, 1200) wn.bgcolor('black') # for aesthetics wn.setup(1200, 1200) # set the scr...
from math import pi r=16 print("area of the circle is: ",pi*r**2) r=4 print("area of the circle is: ",pi*r**2)
import os import hashlib import itertools def getHashContent(path): """ Get hash of the content of a file :param path (string): the path to the file :return (string): the hash (hexadecimal) of the whole content """ chunk_size = 1024 with open(path, 'rb') as input_file: # md5 works ...
print('-- 성적 처리 프로그램 v1 --') name = input("이름을 입력하세요") kor = int(input("국어 점수를 입력하세요")) eng = int(input("영어 점수를 입력하세요")) mat = int(input("수학 점수를 입력하세요")) def getTotal(): tot = kor + mat + eng return tot def getAverage(): avg = getTotal() / 3 return avg def getGrade(): avg = getAverage() grd ...
#1 print()를 이용하여 다음 내용이 출력하라 from builtins import print print('* * ** **** **** * *') print('* * * * * * * * * *') print('**** * * **** **** * * ') print('* * ****** * * * * * ') print('* * * * * * * * * ') print(' +---+') print(' | |') pri...
while True: try: num = int(input('Digite um valor positivo: ')) if num < 0: raise ValueError('Valor Negativo') # print(f'--> {num} é um valor negativo, logo não é permitido.') elif num >= 0: print(f'--> {num} é um valor positivo.') else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Week 6. Conversions""" import decimal def convertCelsiusToKelvin(degrees): """Converting Celsium measurment to Kevins Args: degrees(int, float): number of degrees to convert Returns: conversion Example: >>> convertCelsiusToKelvi...
# Program to implement the Insertion Sort Algorithm. # Worst-Case Complexity of Insertion Sort is O(n^2). # Function to do the Insertion Sort: def insertion_sort(arr): # Traverse the array through 1 to len(arr): for i in range(1, len(arr)): value = arr[i] # Variable 'j' stores the index of th...
# -*- encoding: utf-8 -*- # Aqui escribe tu codigo import os import sys import random import platform class my_game(object): """docstring for ClassName""" def __init__(self): self.menu_option = {1:self.single_player, 2:self.multi_player, 3:self.exit_program} self.operative_system = platform.system() def creat...
# from Crypto.Cipher import DES # # key = 'abcdefgh' # # def pad(text): # while len(text) % 8 != 0: # text += ' ' # return text # # # des = DES.new(key.encode(), DES.MODE_ECB) # text = 'Python rocks!' # padded_text = pad(text) # encrypted_text = des.encrypt(text.encode()) # print(encrypted_text.decode()...
import numpy as np def activation_thr(x,thr=0.2): """"Treshold Activation Function""" return (x > thr).astype(int) def activation(x): """Sigmoid activation function""" return (1 / (1 + np.exp(-x))) class NNet: """Class of Neural Networks with variable number of layers""" def __init__(self, ...
# In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. # The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, # and retrieve the first place_id from the JSON. # A place ID is a textual identifier ...
# In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. # The program will use urllib to read the HTML from the data files below, # extract the href= vaues from the anchor tags, # scan for a tag that is in a particular position relative to the first name in the li...
def Fibo(n): for i in range(n): arr.append(arr[-2]+arr[-1]) arr = [1, 1] Fibo(10) print(arr)
def Factorial(num): result = 1 while num > 0: result *= num num -= 1 return result result3 = Factorial(3) result4 = Factorial(4) result5 = Factorial(5) print(result3, result4, result5)
#!/usr/bin/env python3 import sys import time # to calculate the estimated time taken to run an algorithm from collections import deque # for creating data structures and special lists such as stack and queue for the tree nodes management from queue import Queue, LifoQueue, PriorityQueue im...
#!/usr/bin/env python ''' ETL [Python] Ejemplos de clase --------------------------- Autor: Inove Coding School Version: 1.1 Descripcion: Programa creado para manipular la base de datos de productos ''' __author__ = "Inove Coding School" __email__ = "alumnos@inove.com.ar" __version__ = "1.1" import s...
from sys import stdout """Pywrite is a writes to command line in format that is more like a menu.""" def topline(title="", top='=', width=80): """topline repeats the character top across the width. Will put a title in the middle of the top line. Args: title: Text that is in the middle ...
from players import * import random class Territory: """Class Territory""" def __init__(self, name, title, player=None, armies=0, continent=None): """ Class constructor :param name: string :param title: string :param player: Player/None :param armies: int ...
# https://mathscholar.org/2019/02/simple-proofs-archimedes-calculation-of-pi/ # https://www.davidhbailey.com/dhbpapers/pi-formulas.pdf import math import numpy as np ###### Archimedes Method (1) def archimedes(): k = 0 A = 2*(3**0.5) B = 3 err = 1e-20 while A-B > err: A = 2*A*B/(A+B) ...
import unittest import numpy as np import pandas as pd ''' Course: Software Testing Team Number: 10 Author: Mette Nordqvist (meno5557@student.uu.se) Contributors: Martin Dannelind (mada0115@student.uu.se) Julia Ekman (juek2660@student.uu.se) Helena Frestadius (hefr3736@student.uu.se) ...
def main1(): file = "a.txt" infile = open(file,"r") sum=0 count=0 for line in infile: sum+=eval(line) count+=1 print("ave=",sum/count) print("ave=%.2f"%(sum/count)) def main2(): file = "a.txt" infile = open(file,"r") sum=0 count=0 line = infile.readline() ...
print('Hello World') name = 'Yoon Deockhee' season = 'winter' print('This is',season,'.') #annotation """ annotation """ a = 33 b = 3 summation = a+b multiply = a*b divide = a/b remainder = a%b power = a**b print ("Summation is {}.".format(summation)) print ("Multiply is {}.".format(multiply)) print ("Divide is ...
a = 5 b = 7 def add(): result = a+b print(result) add() # def add(a,b): result = a+b print("{}+{}={}".format(a,b,result)) add(10,5) # def add(a,b): result = a+b return result a=7; b=5; add(a,b)
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' ,'y', 'z', ' '] crypto_letters = [] s = [' ', '!', '?', '(', ')'] do = input('Зашифровать или разшифровать?(1/2):') if do == '1': cod = input('Введите код RОТ(1, 2, 3, 4...25):')...
def merge_sort(l): ''' l: list of integers returns: list, sorted in ascending order ''' def merge(fir, sec, new = None): if new == None: new = [] len_fir = len(fir) len_sec = len(sec) if len_fir == 0 and len_sec == 0: return new elif le...
def permutations(num): ''' num: length of a set to be permutated ''' if num == 0: return 1 return permutations(num - 1) * num def pow_set(num): ''' num: length of a set, int returns: list of all subsets, list of ints ''' result = {} for i in xrange(2 ** num): ...
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. import json import collections import functools recursive_dict = lambda: collections.defaultdict(recursive_dict) def setDeep(path,dictObj, value): retDict = recursive_dict() retDict.update(dict...
#To find factorial of number num = int(input('N=')) factorial = 1 if num<0: print('Number is not accepted') elif num==0: print(1) else: for i in range(1,num+1): factorial = factorial * i print(factorial)
""" python program for reverse a given number using recursion""" # initial value is 0. It will hold the reversed number sum=0 #logic for reverse a number def reverse_number(a): global sum if(a!=0): rem=a%10 sum=(sum*10)+rem reverse_number(a//10) return sum a=eval(inpu...
""""python program for find greatest of three numbers""" #take input from the user first_number=eval(input("enter first number")) second_number=eval(input("enter second numberr")) third_number=eval(input("enter third number")) #find largest of three number if first_number>second_number and first_number>third_...
""" python program for print all prime numbers in given interval """ #take input from the user a=eval(input("enter the number")) #check numberr is greater than 1 if a>1: print(1) #code for find prime number for i in range(0,a+1): b=0 for j in range(1,a+1): if i%j==0: b=b...
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 1, 51) y = [] for a in x: if a < 0: y.append(-a) else: y.append(a) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.grid(True) plt.show()
import threading class A(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for i in range(10): print('I am A') class B(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for i in range(10):...
def add_vectors(vector_1, vector_2): """Returns a list object representing the result of adding two vectors together. Arguments: vector_1 -- list representing first vector vector_2 -- list representing second vector Error checking: Both arguments must be of type list. B...
i = 0 grades = [] totalGrades = 0 #Program loops until the user enters -1, which ends the inputting of grades while i != -1: grade = float(input('Enter student grade: ')) # If value is out of bounds, the program will exit. if(grade == -1): i = -1 # Otherwise it will calculate the grade letter an...
from Algorithms import simulated_annealing from random import randint from copy import deepcopy class Graph: def __init__(self): self.graph_matrix = [[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], [0,...
menu_dict = { } while True: dish = raw_input("Enter meal:") price = raw_input("Enter price:") menu_dict[dish] = price new = raw_input("Would you like to enter new dish? (yes/no) ") if new == "no": break print "All dishes: %s" % menu_dict with open("menu.txt", "w+") as menu_file: # open...
import pygame from random import randint from string import ascii_lowercase wordlist = open('hangman.txt') smallest = None biggest = None secretwords = [] for word in wordlist: secretwords.append(word.strip()) if smallest is None: smallest = len(word.strip()) elif len(word.strip()) < ...
class Solution(object): def selfDividingNumbers(self, left, right): def self_dividing(n): for d in str(n): if d == '0' or n % int(d) > 0: return False return True ...
for i in range(1,3): print(str(i) + ' X 2 = ' + str(i*2)) for i in range(1,4): print(str(i) + ' X 3 = ' + str(i*3))