text
stringlengths
37
1.41M
#!/usr/bin/env python # We know that the lowest crime rate is 130. # This is the second column of the data. # We need to find the corresponding value in the first column -- the city with the lowest crime rate. # Let's load the csv file f = open('crime_rates.csv', 'r') data = f.read() rows = data.split('\n') full_data ...
#!/usr/bin/env python # We can count how many times items appear in a list using dictionaries. pantry = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"] # Create an empty dictionary pantry_counts = {} # Loop through the whole list for item in pantry: # If the list item is alrea...
#!/usr/bin/env python column_list = ['Fiber_TD_(g)', 'Sugar_Tot_(g)'] # Let's sum the amount of fiber and sugar in each of the foods. row_total = food_info[column_list].sum(axis=1) # This gives us a sum for each row in the data print(row_total) # Let's sum up the total amount of fiber and sugar across all the foods....
#!/usr/bin/env python # start by making a list of Pmfs to represent the dice: def make_die(num_sides): die = Pmf(range(1, num_sides+1)) die.name = 'd%d' % num_sides die.normalize() return die dice = [make_die(x) for x in [4, 6, 8, 12, 20]] print(dice)
#!/usr/bin/env python most_nutritious_foods = [] # Find the three most nutritious foods by sorting food_info using the "nutritional_rating" column. # Get the name of those foods (the "Shrt_Desc" column), and assign the names to most_nutritious_foods. # If most_nutritious_foods isn't a list at the end, use the list() ...
#!/usr/bin/env python import matplotlib.pyplot as plt # We can use the plt.plot() function to make a line plot. plt.plot(forest_fires["temp"], forest_fires["area"]) plt.show() # Hmm, the above plot looks really strange (check in the plots area to look for yourself) # The reason it does is because we didn't sort based ...
#!/usr/bin/env python # Cannot be parsed into an int with the int() function. invalid_int = "" # Can be parsed into an int. valid_int = "10" # Parse the valid int try: valid_int = int(valid_int) except Exception: # This code is never run, because there is no error parsing valid_int into an integer. valid_...
import datetime start_time=datetime.datetime.now().replace(microsecond=0) fishes=0 Eggs = 0 async def log_start(): print("Start date & time " + str(start_time)) async def log_fish(Fish_Catches): global fishes fishes += Fish_Catches async def log_eggs(EggsNum): global Eggs Eggs += Egg...
class Node: def __init__(self, info): self.info = info self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None self.queue = [] def create(self, value): if self.root == None: self.root = Node(value) queue ...
import math class Prime: def __init__(self): pass def generates_primes(self,num): not_prime = False for i in range(2,math.ceil(math.sqrt(num))): print(num , i) print(num % i) if num % i == 0: not_prime = True if not not_prime...
x= [1,2,3,4,5] y= ["a","b","c"] x_and_y = list(zip(x,y)) print(x_and_y) # it will print zipped but the length of the # longest will be lost import itertools another_x_y = list(itertools.zip_longest(x,y)) print(another_x_y)
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math import sys def init(): glClearColor(0.0,0.0,0.0,1.0) gluOrtho2D(0,100,0,100) def drawPixel(x,y): glColor3f(0.0,1.0,0.5) glPointSize(5.0) glBegin(GL_POINTS) glVertex2i(x,y) glEnd() glFlush() def ...
import time import ast from types import new_class def password_isvaid(password): if (len(password) < 6) or (len(password)>16): print("Password length should not be less than 6") isValid = False elif not any(char.isdigit() for char in password): print("Password should contain at least a...
import random import time import ast def write_to_file(type, data): if type == 'customer': file = 'bankapp_v3/customers.txt' elif type == 'transaction': file = 'bankapp_v3/transactions.txt' with open(file, 'w') as doc_file: doc_file.write(f'{data}') def read_file_data...
# # variabe = "Hello world" # # print(variabe) # # # set_a = {3,3,1,2, 4,5} # # # print(set_a) # # a = 2 # # b = 3 # # c = 7 # # x = (-b + (4*a*c)**0.5) / (2*a) # # print(x) # dollar = 30 # naira = 200 # convert_naira_to_dollar = naira * dollar # print(convert_naira_to_dollar) # x = 7 # solution = 2*(x**3) - 4*x ...
from argparse import ArgumentParser import requests; import os; import signal; def printNewLine(): print("--------------------------------------------"); def terminating(sig, frame): # a signal handler for ctrl+C (SIGINT) exit() signal.signal(signal.SIGINT, terminating); def printHelp():...
''' 두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. ''' def solution(a, b): # 파이썬에서는 다음과 같이 한 줄로 두 값을 바꿔치기할 수 있습니다. if (b > a): a, b = b, a return (a + b) * (a - b + 1) / 2 def adder(a, b): # 함수를 완성하세요 return sum(ran...
''' 1. sort 원본을 변형시켜 정렬한다. '변수. sort( )' 형태로 사용. 2. sorted 정렬된 결과를 반환. 원형을 변형시키지 않는다. 괄호( ) 안에 반복 가능한 iterable 자료형을 입력하여 사용한다. 정렬 기준은 문자열은 알파벳, 가나다순이고 숫자는 오름차순이 기본값이다. 3. Parameter sort, sorted 모두 key, reverse 매개변수를 갖고 있다. 3-1. reverse bool값을 넣는다. 기본값은 reverse=False(오름차순)이다. reverse=True를 매개변수로 입력하면 내림차순으로 정렬할 수 있...
#!/usr/bin/python3 """Module with the 'Base' class""" import json class Base: """Base class""" __nb_objects = 0 def __init__(self, id=None): """Initializes base class""" if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = sel...
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): try: for index in range(x): print(my_list[index], end='') return x except IndexError: return index finally: print()
#!/usr/bin/python3 """Module tahat provides a function 'matrix_divided' that divides a matrix by a number""" def matrix_divided(matrix, div): """Divide each element of a matrix by a number""" if not (matrix and isinstance(matrix, list) and all(isinstance(row, list) and ...
print("Give me five kinds of fruits:") fruits = [] index = 0 while index < 5: new_fruit = input() fruits.append(new_fruit) index += 1 print("Fruits that you entered:") print(fruits)
from utility.draw import draw_line print("Enter the number of rows:") num_rows = int(input()) print("Enter the number of columns:") num_columns = int(input()) print("Enter the symbol of the rectange:") symbol = input() for _ in range(num_rows): draw_line(num_columns)
fruits = ["apple", "orange", "banana", "strawberry"] fruits[1] = "mango" # Change the second item to mango print(fruits) fruits.append("cherry") # Add cherry to the end of the list print(fruits)
# TODO: Use for-loop to print 0 to 9. # Tip: range(n) starts from 0 and ends at n - 1 n = range(10) for x in n: print(x)
fruit_list = ["apple", "orange", "banana"] for fruit in fruit_list: print(fruit)
# TODO: Use while-loop to print the integers from 0 to 10 number = 0 while number <= 10: print(number) number += 1
# TODO: Complete the following program by completing the function lcm so that the lowest common multiple (LCM) of two # positive integers can be computed. # TODO: return the LCM of num1 and num2 def lcm(num1, num2): pass print("Input the first integer: ", end="") num1 = int(input()) print("Input the second...
""" An implementation of Minimum Spanning Tree functionality by Kruskal's algorithm """ from collections import OrderedDict """ Calculates the distance between 2 two-dimensional points in space """ def calculate_dist(a,b): return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5 """ The mst_kruskal dunction takes an nX2 n...
"""Task 1 - Enoch Leow 30600022 """ from math import pow from math import log from math import ceil def get_digit(integer, base, digit): """ Get_digit computes the value of the specified 'digit' in 'base' of the 'integer' :time complexity: O(1) :param integer: Any positive integer in rang...
"""Quick analysis pairs solution is O(N) space and time complexity triplets solutions is O(N^2) time and O(N) space complexity """ def get_nums(path="./input.txt"): """Read file for number input return: sorted array on numbers """ nums = [] with open(path, "r") as _f: for line in _f.read...
import time class User(object): username = 'liam' password = '123456' def printWelcome(self): print('********************') print('********************') print(' 欢迎光临 ') print('********************') print('********************') def p...
# This sets the variable `formatter` to the format string "%r %r %r %r" formatter = "%r %r %r %r" # This command tells python to print the output "1 2 3 4" print formatter % (1, 2, 3, 4) # This command tells python to print the output "'one', 'two', 'three', 'four'" print formatter % ("one", "two", "three", "four") ...
#miles = input("enter milage: ") #for miles in range(10, 70, 10): # km = miles * 1.609 # print("%d miles --> %3.2f kilometers"%(miles, km)) #print ("%3.2f "%(km)) #print (miles) #x = 25 #print("the number is " + str(x)) mylist = ["nice", "cool", "nice", "road", "trip", "cool"] print(set(mylist)) #to change a...
import platform from enum import Enum from typing import Self class Site(Enum): """Supported Recordpool websites.""" BANDCAMP = "Bandcamp" BEATJUNKIES = "Beatjunkies" BPMSUPREME = "BPMSupreme" DJCITY = "DJCity" # Not using StrEnum here since that will use the variable name in lowercase, ...
# pylint: disable-all # NOTE : Python 2.7 does not require parenthesis to print # Python 3 does however # Excercise 1 print (5/3) print 5%3 print 5.0 / 3 print 5/3.0 print 5.2%3 #Exercise 2 print 2000.3**200 print 1.0 + 1.0 - 1.0 print 1.0 + 1.0e20 - 1.0e20 #Exercise 3 print float(123) print float('123') print flo...
print("problema 05") nr= int(input("Dati numarul lui Ion: ")) print(nr-2, nr-1 , nr, nr+1, nr+2 , sep = "_")
# # if conditional # hasGoodCredit = True # price = 1000000 # if hasGoodCredit: # print(price * 0.1) # else: # print(price * 0.2) # # hasHighIncome = False # hasGoodCredit = True # # if hasGoodCredit and hasHighIncome: # print("Elegible for loan") # else: # print("Not Elegible for loan") # # # isMayorEd...
def divide(num1, num2): try: return num1/num2 except TypeError: print ("Please provide two integers or floats") except ZeroDivisionError: print ("Please do not divide by zero") divide(1, 0) try: age = int(input("Ingrese un numero ()")) print(age) except ValueError: pr...
# input an integer number number = int(input('input an integer number:')) if number == 0: factorial = 1 else: factorial = number while number > 1: factorial = factorial * (number - 1) number = number -1 print ('Factorial ', factorial)
from abc import ABC, abstractmethod import random class AI(ABC): '''Abstract AI class''' @abstractmethod def play(self, game): pass class RandomAI(AI): def play(self, game): '''An AI player that chooses a legal move at random out of all available legal moves in Tic-...
import string import unidecode from sentences import CONJUNCTION, NEGATION # format user entry (unaccented, no punctuation, lowercase) def formatText(text: str): unaccentedStr = ' '.join(unidecode.unidecode(text).split("'")) formattedStr = unaccentedStr.translate( str.maketrans('', '', string.punctuat...
print("{:=^20}".format(" 제어문 ")) print("{:-^20}".format(" if문 ")) # if 문 print("-" * 20) if 1 > 10: print("test") print("test") if 1 < 20: print("test") if True: print("aaa") # if - else 문 print("-" * 20) a = 10 if a % 2 == 0: print("짝수") else: print("홀수") #...
# problem 1 a = 20180123 year = int(a / 10000) month = int((a % 10000) / 100) day = a % 100 print("{:04d}.{:02d}.{:02d}".format(year, month, day)) # problem 2 input_str = input("insert your string : ") print(input_str[0] + "_" * (len(input_str) - 1)) # problem 3 input_str = input("insert your string : ") ...
tasklist = [23,"Jane",["lesson 23",560,{"currency":"KES",}],987,(76,"John")] #1.determine the type of variable in task list using an inbuilt function a = print(type(tasklist)) #2. print KES-said print(tasklist[2][2]["currency"]) #3. print 560- patricia print(tasklist[2][1]) #4. length of task list print(len(tasklist))...
m,n=map(int,input().split()) a,b=map(int,input().split()) s,d=map(int,input().split()) if(m==a==s): print("yes") elif(n==b==d): print("yes") elif(m==n and a==b and s==d): print("yes") else: print("no")
keycode = { 'a': 65, 'b': 66, 'c': 67, 'd': 68, 'e': 69, 'f': 70, 'g': 71, 'h': 72, 'i': 73, 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78, 'o': 79, 'p': 80, 'q': 81, 'r': 82, 's': 83, 't': 84, 'u': 85, 'v': 86, 'w': 87, 'x': ...
from functools import reduce from operator import mul def main(): max_x, max_y, trees = read() counts = [] for dx, dy in (1, 1), (3, 1), (5, 1), (7, 1), (1, 2): counts.append(count_trees(max_x, max_y, trees, dx, dy)) mul_count = reduce(mul, counts) print(mul_count) def count_trees(max_x,...
numCalls=0 def fib(n): global numCalls numCalls+=1 if n<=1: print('fib of',n) return 1 else: print('fib of',n) return fib(n-1)+fib(n-2) print(numCalls) memo={0:0,1:1} def fib1(n): global memo global numCalls numCalls+=1 if not n in me...
#合并排序法 def merge(left,right): """Assume left and right are sorted lists.Return a new sorted list containing the same elements as (left+right) would contain.""" result=[] i,j=0,0 while i<len(left) and j<len(right): if left[i]<=right[j]: result.append(left[i]) i=i+1...
#Demonstrating popen and popen2 import os #determine operating system, then set directory-listing and reverse-sort commands if os.name =="nt" or os.name == "dos": fileList = "dir /B" sortReverse = "sort /R" elif os.name =="posix": fileList = "ls -l" sortReverse = "sort -r" else: sys.exit("OS not supported by thi...
class Items(object): def __init__(self, name, type, price): self.itemName = name self.itemType = type self.unitPrice = price class Store(object): def __init__(self): self.itemInventory = dict() def buyItem(self, name, quantity): for i, j in self.itemInventory.items(): if name.lower() == i.itemName.lo...
# A traveler wants to start his/her journey from Pune # to Ahmedabad. Before starting the journey, he/she uses # the GPS system to find all the paths to reach from # the source to the destination. He/she will use the # smallest or the second smallest path to start the journey. # Write a logic to find the smallest and ...
class Passenger(object): def __init__(self, name, age, dist): self.passengerName = name self.passengerAge = age self.distanceTravelled = dist def calculateTicketFare(passengers, fare): total = 0 for i in passengers: if i.passengerAge >= 60 or i.passengerAge < 12: total += (i.distanceTravelled *...
N=int(input("Enter the limit:")) if N<0: print("Invalid input") else: print("Armstrong number between 0 and",N,"are:") for N in range(1,N+1): sum=0 i=N l=len(str(N)) while i>0: sum=sum+((i%10)**l) i//=10 if N==sum: prin...
# # Make a SQL database using `psycopg2` # # When you make a database in SQL, you have to execute the command from within a database that already exists. # By default every PgSQL cluster has a database named `postgres`, so in the code below we connect to that database # before issuing the command to create the new data...
import numpy as np #Array with Array #Array with Scalar #Universal Array Function arr = np.arange(0,11) print(arr) #Addition of 2 array elements add_arr = arr + arr print(add_arr) #Add 100 to each element of array arr_100 = arr + 100 print(arr_100) #Universal Array Functions #If you wantto take square root of eac...
''' Author: Christian Duncan Modification: David Lepore, Alex Hutman, Stephen Kern Date: Spring 2019 Course: CSC350 (Intelligent Systems) This sample code shows how one can read in our JSON image files in Python3. It reads in the file and then outputs the two-dimensional array. It applies a simple threshold test - i...
def move(f,t): print("move disk from {} to {}!".format(f,t)) #move("A","C") def moveVia(f,v,t): move(f,v) move(v,t) def hanoi(n,f,h,t): if(n==0): pass else: hanoi(n-1,f,t,h) move(f,t) hanoi(n-1,h,f,t) hanoi(8,"A","B","C")
""" Author: Alejandro Sanchez Uribe Date: 12 Dec 19 """ import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the d...
""" Author: Alejandro Sanchez Uribe Date: 19 Dec 2019 """ import random def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(list): Input array to search number(int): The target Returns: int: Index or -1 """...
import math import matplotlib.pyplot as plt import numpy.random as rand plt.rcParams['figure.dpi'] = 280 class Vector: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'Vector({self.x}, {self.y})' def magnitude(self): mag = math.hypot(self.x, s...
import os import sqlite3 import sys import masterScript def screen_Scripts() : ''' Show all the available operations that can be done on the bam files ''' pass def screen_Cancer() : ''' Show the cancers available to analyze. To do that, check on the database. After get the bams, ask if the bams should ...
import pickle import os class account(): def __init__(s): s.acno = 0 s.name = "" s.deposit = 0 s.type = "" def create_account(s): # function to get data from user name =input("\n\nEnter the name of the account holder: ") s.name = name.capitalize() type...
def sum_n(n): if n == 1: return 1 else: return n + sum_n(n-1) print(sum_n(5))
#define function chorus, which repeats many time in the song #We have to define function before it is called def chorus(duck_num): print("{} little ducks".format(duck_num)) print("Went out one day") print("Over the hill and far away") print("Mother duck said") print("\"Quack, quack, quack, quack.\"") print(...
my_name = 'Eric Yang' my_age = 42 # not a lie my_height = 1.71 # metre my_weight = 80 # kg my_eyes = 'black' my_teeth = 'white' my_hair_color = 'black' my_hair_style = 'short' print ('My name is',my_name,'and my age is:', my_age) print("Let's talk about %s." % my_name) print("He's %4.2f metres tall." % my_height) pri...
number=int(input()) tem=number re=0 while(number>0): dig=number%10 re=re*10+dig number=number//10 if(tem==re): print("yes") else: print("no")
import random SHIP_SIZE = 4 DIMENSION = 10 #Create a board board = [[0 for i in range(DIMENSION)] for x in range(DIMENSION)] #randomly generate a ship check = False while check != True: ship = [random.randint(0,DIMENSION-1),random.randint(0,DIMENSION-1),random.randint(0,1)] #The number represents row_num,co...
""" Day-1 (29/05/2021) Binary sort Author: Prajwal Prakash Time complexity: Process finished --- 2.8371810913085938e-05 seconds --- Data structures used: Result: Successful """ import time def linear_search(list, element): for i in range(len(list)): if element == list[i]: return i ########...
import math ######################## # PYTAGORAS ######################## def pytagoras(delta_x, delta_y) -> float: return math.sqrt(delta_x**2 + delta_y**2) def distance_to(pos1, pos2) -> float: """ Returns the distance between two object on a 2d plane (using the formula of Pytagoras) """ return pytagor...
#CLASS: Dinosaur #Author: Richard Fleming #Create Date: August 10, 2021 from attacks import Attacks class Dinosaur: #Constructor def __init__(self, name): #, attack_power): self.name = name #self.attack_power = attack_power self.health = 100 self.attack_types = [] se...
#!/usr/bin/env python3 # coding: utf-8 # Teste si le caractère c est une lettre minuscule. def is_alpha_min(c): return (ord(c) >= ord('a') and ord(c) <= ord('z')) # Teste si le caracère c est une lettre majuscule. def is_alpha_maj(c): return (ord(c) >= ord('A') and ord(c) <= ord('Z')) # Teste si le caractère...
from sqlalchemy import* db = create_engine('sqlite:///tutorial2.db') # The create_engine() function takes a single parameter that's a URI, of the form: # "engine://user:password@host:port/database" # Most of these options can be omitted, db.echo = False metadata = MetaData(bind=db) #Before creating our table definiti...
import string word='and' n=1 s=list(string.ascii_lowercase) s1=[i for i in s if i!=word[0]] def sub(s1,w): substitute=[] s2=[i for i in s if i!=word[w]] for i in s2: for j in s1: substitute.append(j+i) return substitute s3=[] for i in range(n-1): s1=sub(s1,w=i+1) for i in s1: s3.append(i+word[n:]) print(s3)...
""" Day 23: BST Level-Order Traversal test """ from hackT import bst_traversal def test_1(): a = [3, 5, 4, 7, 2, 1] myTree = bst_traversal.Solution() root=None for i in a: data = i root=myTree.insert(root,data) res = myTree.levelOrder(root) assert res == [3, 2, 5, 1, 4, 7] ...
""" Day 22: Binary Search Trees test """ from hackT import bin_trees def test_1(): a = [3, 5, 2, 1, 4, 6, 7] myTree = bin_trees.Solution() root=None for i in a: data = i root=myTree.insert(root,data) height=myTree.getHeight(root) assert height == 3
"""Day 11: 2D Arrays""" def getHourglassSum(arr, startRow, startCol): """ Returns sum of hourglass in arr matrix stating at [startRow, startCol] position (zero based indices) Return value is None where hourglass is not possible to construct """ retVal = 0 if startRow > 3 or startCol > 3: ...
#This script gets job posting from github # IMPORTS #Make Python understand how to read things on the Internet import urllib2 #Make Python understand the stuff in a page on the Internet is JSON import json # Make Python understand csv import csv # Make Python know how to take a break so we don't hammer API and exceed r...
import math class turtle(): def __init__(self, obj): self.Interface = obj self.Y = 100 self.X = 100 self.Pen = True self.Angle = 0 def parseCode(self): code = str(self.Interface.getCode()) code = code.split('\n') for f in code: ...
s=0 for x in range(0,1000): if x%3==0 or x%5==0: s=s+x print (s)
# -*- coding: utf-8 -*- """ Clever iterative solution Like a two box kernel moving forward one number at a time """ def fib5(n: int) -> int: """ Time complexity = O(N-1) Space complexity = O(2) we just accumulate the two previous numbers nifty """ if n == 0: return n last: in...
is_foodie = False do_cook = False if is_foodie and do_cook: print("Are you a foodie!") elif is_foodie and not(do_cook): print("You are not a foodie.") else: print("You are not a foodie and don't cook?!") # >, <, >=, <=, !=, == if 1 > 3: print("number omparison was true") if "dog" == "cat": print("string ...
#Syntax #lambda arguments : expression #A lambda function is a small anonymous function. #A lambda function can take any number of arguments, but can only have one expression. x = lambda a: a + 15 print(x(5))
import sqlite3 import Main as Main from abc import ABC, abstractmethod ConDb = sqlite3.connect('manajementoko.db') Cursor = ConDb.cursor() class Masuk: def LoginManager(self): pass def login_karyawan(self): pass class Login(Masuk): def LoginManager(self): print("Selamat Datang Koh...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: ARAVINTHAN # # Created: 07/02/2018 # Copyright: (c) ARAVINTHAN 2018 # Licence: <your licence> #--------------------------------------------------------------------------...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Aravinthan # # Created: 30/01/2018 # Copyright: (c) Aravinthan 2018 # Licence: <your licence> #---------------------------------------------------------------------------...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Aravinthan # # Created: 11/02/2018 # Copyright: (c) Aravinthan 2018 # Licence: <your licence> #--------------------------------------------------------------------------...
import tkinter as tk from student import Student from student import StudentListUtilities class StudentGui: DEFAULT_NAME = "" DEFAULT_GRADE = 9 DEFAULT_ADDRESS = "123 Main St, 456" DEFAULT_PHONE = "123 456 7890" def __init__(self): """Constructor for a GUI for Student.""" self._ro...
hastag = int(input("Please enter the number")) if hastag == 1: print("#") else: print("#" * hastag) for i in range(hastag-2): print("#" + " " *(hastag-2) + "#") print("#" * hastag)
text = list(input("Please enter the text :").lower()) vowels = ["a","e","i","u","o"] result=False if len(text) <= 1: result = False else: for i in range(len(text)-1): if text[i] in vowels and text[i+1] in vowels: result = True break if result: print("positive") else...
# linear search algorithm class LinearSearch: def linear_search(self,lis,find): found=0;count=0 for a in lis: if a==find: found=a else: found=None count=count+1 index=count-1 return found,index if __name__=='__main__': li=[];count=0 # [6,5,4,3,2,1] print "Enter any 6 numbers (Insertion So...
to_find=[12,23,54,56,67,78,95,99] count=0 key=67 b=0 e=len(to_find)-1 while b<=e: m=(b+e)/2 count=count+1 if to_find[m] < key: b=m+1 else: e=m-1 if b== len(to_find) or to_find[b]!=key: print "Index of the element not found: Element not in the list",-1 else: print "Index ...
if number > 1: for itr in range(2, int(number/2)+1): if (number % itr) == 0: print(number, "is NOT a PRIME number") break else: print(number, "is a PRIME number") else: print(number, "is NOT a PRIME number")
#Question4 def even(list): a=[] for i in list: if (i % 2) == 0: a.append(i) return a def odd(list): b=[] for i in list: if (i % 2) != 0: b.append(i) return b #Main #l1=[30,40,22,33,22,11] #l2=[40,30,10,99,53] l1=[] n = int(...
__author__ = 'claireopila' import string import random import math import numpy as np """Make passwordswithout files""" def makePassword1(password): ## this algorithm breaks up inputs into vowels and consonants by ## uppercase and lowercase, and numbers and punctuation ## inputs defined here vowels = ['a', '...
# -*- coding: utf-8 -*- # @Author: mithril from __future__ import unicode_literals, print_function, absolute_import def is_cjk(character): """" Checks whether character is CJK. >>> is_cjk(u'\u33fe') True >>> is_cjk(u'\uFE5F') False :param character: The character that ne...
#CALCULANDO OPERACIONES BASICAS from tkinter import * from tkinter import messagebox from math import* app = Tk() app.title("OPERACIONES BASICAS") app.geometry("600x200+200+200") app.config(bg="pink") def show_entry_fields(): print("REALIZADO POR: %s" % (e1.get())) #PIDIENDO NUMEROS PARA LAS OPERACIONES AL ...
import numpy as np import math #iteration counter: to count how many steps to reach the threshold value i=0 def randompostive(x): return np.multiply(np.random.random(),x) # here iter(x) is x - f(x)/f'(x) def iter(x): f_x = math.tan(x)-math.cos(x); df_x = 1+math.pow(math.tan(x),2)+math.sin(x); return x...
ans=True while ans: print ("""============================= PROGRAM SEDERHANA 1.Menghitung Waktu Tempuh 2.Delete a Student 3.Look Up Student Record 0.Exit/Quit =============================""") ans = input("Pilih pilihanmu: ") if ans == "1": waktutempuh=0.0 j...