text
stringlengths
37
1.41M
''' password validation in python code''' import re def check_valid_password(password): while True: if len(password) < 8: return "Make sure your password is at least 8 letters" elif re.search('[0-9]', password) is None: return "Make sure your password has a number in it" ...
# def my_repeat(data, times): # i = 1 # record = [] # while i <= times: # record.append(data) # # i += 1 # # return record # # # obj = my_repeat('admin', 10) def my_repeat(data, times): return data * times print(my_repeat('admin', 10))
# Программа отбирающая файлы с датой позже чем заданная import os # Запрос исходных данных: путь к корневой папке и дата после которой # были созданы файлы path = input("Введите путь к иследуемой папке с файлами: ") date_file = input("Дата последних изменений файлов: ") # Получаем перечень всех файло и папок list_file...
import heapq class ParkingSpot: def __init__(self, floor, spot): self.floor = floor self.spot = spot def __lt__(self, other): # For heapify if self.floor == other.floor: return self.spot < other.spot else: return self.floor < other.floor class ParkingLot: def __init__(self): l = [] # dummy data ...
#!/usr/bin/env python """circuits Hello World""" from circuits import Component, Event class hello(Event): """hello Event""" class App(Component): def hello(self): """Hello Event Handler""" return "Hello World!" def started(self, component): """ Started Event Handler ...
""" VirtualHost This module implements a virtual host dispatcher that sends requests for configured virtual hosts to different dispatchers. """ from urllib.parse import urljoin from circuits import BaseComponent, handler class VirtualHosts(BaseComponent): """ Forward to anotehr Dispatcher based on the Host h...
""" Session Components This module implements Session Components that can be used to store and access persistent information. """ from abc import ABCMeta, abstractmethod from collections import defaultdict from hashlib import sha1 as sha from uuid import uuid4 as uuid from circuits import Component, handler def who...
""" Author: Rajiv Malhotra Program: sort_and_search_array.py Date: 10/11/20 Search and Sort Array Assignment """ import array as arr def search_array(n_array, a_value): """ Function searches for a value in the Array and returns the index value. -1 if not found :param n_array: An Array :param a_value...
# Author: Dariush Azimi # Created: April 22, 2020 import matplotlib.pyplot as plt import matplotlib import os import pandas as pd import streamlit as st import seaborn as sns matplotlib.use('Agg') def main(): """ Machine Learning Dataset Explorer App """ st.title("Machine Learning Dataset Explorer App") ...
def do_flatten(iterable): nested_list = iterable[:] while nested_list: sublist = nested_list.pop(0) if isinstance(sublist, list): nested_list = sublist + nested_list elif sublist or sublist == 0: yield sublist def flatten(iterable): return [i for i in do_f...
import re while True: print("Voer je mobiele nummer in:") invoer = input("> ") patroon = '^06-?\d{8}$' matches = re.findall(patroon, invoer) if (len(matches) > 0): break print("Bedankt nummer in juiste formaat:", matches[0])
print("Introduceti un numar intreg: ", end="") n = int(input()) money_values = [1000, 500, 200, 100, 50, 20, 10, 5, 1] print("Suma introdusa poate fi descompusa in urmatoarele bancnote") while n > 0: for value in money_values: # operatoru // ia partea intreaga de la impartire if n//value > 0: ...
import math def show_if_not_prime(number): for x in range(2, number): if number % x == 0: return print('{} '.format(number), end='') print("Introduceti un numar intreg: ", end="") n = int(input()) for i in range(1, int(math.sqrt(n))): if n % i == 0: show_if_not_prime(i) ...
""" A program for calculating the number of units of each type of product from the purchased by each customer of the online store in lexicographic order, after the name of each product - the number of units of the product. Sample Input 1: 5 Руслан Пирог 1 Тимур Карандаш 5 Руслан Линейка 2 Тимур Тетрадь 12 Руслан Хлеб 3...
person = { 'name': '', 'money': 1000, 'cargo': {}, # 'level': 1, # 'experience': 0, 'skills': { 'luck': 4, 'eloquence': 7, 'agility': 0 } } goods = [{'type': "Техника", "price_in":1000, "price_out": 5000, "risk_precent": 10}, {'type': "Сигареты", "price_in":100, ...
import math def MuyuanC(T): if T > 0: print 'Hello Muyuan Chen' else: print 'Good bye Muyuan Chen' F = [1, 2] def fibNEven(N): if( N <= 0): print 'please input a valid number' return print F[0] while( N - 1 > 0 ): a = F[0]+F[1] if(a % 2 == 1): ...
import time def time_exc(s): start = time.clock() result = eval(s) run_time = time.clock() - start return result, run_time def spin_loop(n): i = 0 while i < n: i +=1 print time_exc('1+1') print time_exc('spin_loop(10000)') print time_exc('spin_loop(10 ** 7)')[1]
""" Authors: EYW and Addison Spiegel Allows you to have two modifiable colors and the ability to change the greyscale threshold Created: 10/1 """ import cv2 import numpy import os.path # this function does nothing, it is for the creation of the cv2 createTrackbar, it requires a function as an argument de...
#!/usr/bin/env python3 from lazylist import LazyList def fibonacci(a=0, b=1): while True: yield a a, b = b, a + b lazyfib = LazyList(fibonacci()) print(lazyfib[0], lazyfib[3], lazyfib[10]) # prints 0, 2, 55 print(lazyfib[8], lazyfib[7]) # prints 21, 13 for x in lazyfib[3:...
# # -*- coding: utf-8 -*- # ''' This program takes a excel sheet as input where each row in first column of sheet represents a document. ''' # # import pandas as pd # import numpy as np # # data = pd.read_excel('C:\\Users\medicisoft\Downloads\\data.xlsx',dtype=str) # Include your data file instead of data.xlsx # # id...
# a = input('숫자를 입력하시오! : ') # # if int(a)%2 == 0: # print('짝수') # # else: # print('홀수') # def mod(val): # if val%2 == 0: # print('짝수') # else: # print('홀수') # # print(mod(10)) # a = input('이름을 입력하시오! ') # # import pandas as pd # emp = pd.read_csv("d:\data\emp.csv") # salary = emp[['s...
import simplegui # Initialize globals WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 ball_pos = [WIDTH / 2, HEIGHT / 2] vel = [-120.0 / 60.0, 25.0 / 60.0] # define event handlers def draw(canvas): global BALL_RADIUS BALL_RADIUS = 20 # Update ball position ball_pos[0] += vel[0] ball_po...
# Mouseclick Handlers # Tic-Tac-Toe # This program allows two users to play tic-tac-toe using # mouse input to the game. import simplegui # Global Variables canvas_width = 300 canvas_height = 300 grid = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] turn = "X" won = False # Helper Functions ...
# Testing template for Particle class import random import simplegui ################################################### # Student should add code for the Particle class here WIDTH = 800 HEIGHT = 600 PARTICLE_RADIUS = 5 COLOR_LIST = ['Green', 'Red', 'Maroon', 'Aqua', 'White', 'Blue', ...
__author__ = 'darrell.skogman' def addemup(a, b, c): return a+b+c def divideandadd(a,b,c): return a/b+c def main(): a = int(input("first number ")) b = int(input("second number ")) c = int(input("third number ")) print(addemup(a, b, c)) main()
#Importing OS and File Type import os import csv #Creates Path to budget_data CSV File #Had trouble opening 'budget_data.csv so implemented os.getcwd() to help open filepath #https://www.tutorialspoint.com/python/os_getcwd.htm print(os.getcwd()) budget_data = os.path.join('PyBank', 'Resources', 'budget_data....
import trek import wander while True: print("Games") print("-----") print("0. Quit") print("1. Trek") print("2. Wander") choice = input("What do you want to play?") if choice == "0": break elif choice == "1": trek.start() elif choice == "2": wander.start()...
import re class GameController: """Maintains the state of the game.""" def __init__(self, WIDTH, HEIGHT, PLAYER_NAME, PLAYER_COLOR, file_name="scores.txt"): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.PLAYER_NAME = PLAYER_NAME assert PLAYER_COLOR in ["black", ...
"""A standard card deck with shuffling, sorting, and dealing features. This module contains the CardDeck() class. It is made to represent a standard deck of cards (4 suits, 13 cards per suit).The pull_card_from_deck() function returns the final card from the deck, as if the cards were upside down and the top card was ...
""" REVERSE OF A GIVEN NUMBER """ n=int(input(" enter the number to be reversed ")) rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 print("Reverse of the number ",rev) OUTPUT- enter the number to be reversed 21 Reverse of the number 12
import numpy as np import pandas as pd from pandasql import sqldf ##1. Create an sqlalchemy engine using a sample from the data set from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:', echo=False) #engine = create_engine('sqlite:///:memory:', echo=True) ## To Enable Logging from sqlalche...
tool_quantity = int(input()) tools = input().split(" ") [a, b] = input().split(" ") money = int(a) num = int(b) for i in range(num): [c, d] = input().split(" ") purchase_tool = int(c) - 1 purchase_quantity = int(d) total = int(tools[purchase_tool]) * int(d) if total < money: money -= t...
# 迭代 ''' Python的for循环抽象程度要高于c的for循环,因为Python的for 循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。 list这种数据类型虽然有下标,但是有很多数据类型是没有下 标的,但是,只要是可迭代对象,无论有无下标,都可以迭代, 比如dict就可以迭代。 ''' ''' d = {'a' : 1, 'b' : 2, 'c' : 3} for key in d: print(key) ''' # 如何判断一个对象是可迭代对象呢? # 方法是通过collections模块的Iterable类型判断: ''' from collections import Ite...
# print(100 + 200 +300) # print("hello world!") # print("100 + 200 =",100 + 200) # name = input() # name # name = input() # print("hello,",name) # name = input("please enter your name:") # print("hello,",name) print(1024 * 768)
def tail(iterable, n): if n <= 0: return [] items = [] for item in iterable: if len(items) == n: items.pop(0) items.append(item) return items from collections import deque def tail(iterable, n): if n <= 0: return [] return list(deque(iterable, max...
import math class Circle: def __init__(self, r=1): self.radius = r @property def radius(self): return self._radius @radius.setter def radius(self, r): if r < 0: raise ValueError('Radius cannot be negative') self._radius = r @property def diame...
def extract_word(token): start = 0 for idx, c in enumerate(token): if c.isalnum(): start = idx break else: return '' end = 0 for idx, c in enumerate(reversed(token)): if c.isalnum(): end = idx break else: assert Fal...
# Q. Rhezo and Prime Problems # Check Prime No. def checkPrime(num) : if num > 2: for i in range(2,num): if (num%i) == 0: break; else: return 1 else: return 0 #Find Max Prime def maxPrime(num): count = 0 for i in range(num,0,-1): if (checkPrime(i)): num = i break; count += 1 return num ...
#take name input name =input('What is your name ?') print(name) #take age input age=input ('What is yout age?') print(age) #take hobbies hobbies=[] hobbies=input('What are your hobies?') print(hobbies) #format all the info finalOut='Your name is {} at the age of {} your hobbies are {}' finalOut=fina...
from tkinter import* import math class Calc(): def __init__(self): self.total = 0 self.current = "" self.input_value = True self.check_sum = False self.op = "" self.result = False add_value = Calc() root = Tk() root.title("Project Casio") root.resiz...
#!/user/bin/python # 5 test, 25 real preambleCount = 25 allowedLowestIndex = 0 numbers = [] def isValid(value, amongNumbers): #print(amongNumbers) for first in amongNumbers: for second in amongNumbers: if first + second == value: return True return False with open...
#!/user/bin/python rules = {} class BagRule: def __init__(self, id, contains): self.id = id self.contains = contains def extractBagRule(line): print(line) splitted = line.split("contain") bagID = splitted[0].split("bag")[0].strip() rules = [x.strip() for x in splitted[1].spli...
#Try catch try: print(x) except: print("An exception occurred") else: print("Nothing went wrong") finally: print("The 'try except' is finished") #RegEx import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) # [] A set of characters "[a-m]" # \ Signals a special sequence ...
#!/usr/bin/python3 """ Teste de desenvolvimento criado para a empresa Keeggo Data: 2021-03-01 Autor: Marcos Thomaz da Silva """ import random from excecoes import * class Comportamento: tipo = 'ComportamentoGeral' def __init__(self, jogador): self.__jogador = jogador def pode_comprar(self,...
import random import string import time #greet the user print("\nhello, Welcome to Passwords Generator!") print("Let's generate some passwords ^^") nOfPasswd = int(input('\nHow many passwords you want to generate? (Default 10): ') or "10") print("") #asking the user the length of the password. length = i...
one = 'Learn' two = 'Python' def get_summ(one, two, delimiter='&'): return (str(one) + str(delimiter) + str(two)).upper() sum_string = get_summ(one, two) print(sum_string)
# -*- coding: utf-8 -*- import pandas as pd import sqlite3 '''#load csv file to create db with''' df = pd.read_csv('https://raw.githubusercontent.com/iesous-kurios/' 'DS-Unit-3-Sprint-2-SQL-and-Databases/master/' 'module1-introduction-to-sql/buddymove_holidayiq.csv') print(df...
import common def main() : dat = common.readFile('day9.dat') print(find_bad_number(dat)) def check_number(prev, number): i = 0 valid_number = False while i < len(prev) - 1: j = i + 1 while j < len(prev): if (int(prev[i]) + int(prev[j])) == int(number) : ...
from collections import namedtuple Point = namedtuple('Point',['x','y'],verbose=True) p=[1,2] d = Point._make(p) print(d) print(d._asdict()) print(d._replace(x=3))
# encoding:utf-8 # @Time : 2019/5/13 9:27 # @Author : Jerry Chou # @File : common.py # @Function : 公共方法 def show_cards(cards): """ 显示卡牌 :param cards: :return: """ for i, card in enumerate(cards): print("\t{0}-{1}({2})".format(i + 1, card.name, card.present_mana), end='') ...
a = int(input("Enter the number of steps: ")) b = input("Enter the symbol of steps: ") c = input("Which way will the stairs go (left, right): ") if c == "left": # Left for i in range(1, a+1): print(b * i) elif c == "right": # Right for i in range(1, a + 1): print((" " * (a - i)), b * i) ...
def posl(numbers): tmp = 0 maxim = 0 a = [numbers] while numbers != 0: numbers = int(input("Enter your number: ")) a.append(numbers) for i in range(1, len(a)): if a[i] == a[i - 1]: tmp += 1 if a[i] != a[i - 1]: if tmp > maxim: m...
# Quine McCluskey # Take in a logical expression # Go through and count the number of variables # num = 2^{varcount} - 1 # for i in range(num): # if checkTrue(i): # add to list # make varcount number of tables # loop through list values and put into tables sorting by number of 1s # combine values in each ...
import string # def encrypt(text,shift): # encrypted_text = list(range(len(text))) # alphabet = string.ascii_lowercase # # first_half = alphabet[:shift] # second_half = alphabet[shift:] # # shifted_alphabet = second_half+first_half # # for i,letter in enumerate(text.lower()): # if le...
import random mystring = "Secret agents are super good at staying hidden." # for word in mystring.split(): # first_letter = word.lower()[0] # # if first_letter =='s': # print(word) # for word in mystring.split(): # if len(word)% 2 == 0: # print(word) # word=[word[0] for word in mystring.s...
greetings = "Hi" name = "Touhid" message = greetings + " " + name print(message) age = 25 message = "Your age is: " + str(age) print(message) height = 5.10 message = "Your height is: " + str(height) + " feet." print(message) string_to_int = int("100") string_to_float = float("100.01") float_to_string = str(100.01...
# This is a comment of python # print is responsible for write/show something into console print("This is Bismillah Program") # We can add comment in same line of code execution """ Example of Multiline comments The sum method is responsible for addition of 2 number and return them """ def sum(first, second): ...
from tkinter import * from tkinter import messagebox #from gtts import gTTS root=Tk() root.title("Tic Tac Toe") global bclick bclick=True def close(): exit() def reset(): button1["text"]="" button2["text"]="" button3["text"]="" button4["text"]="" button5["text"]="" butto...
''' Daniel McNulty II Last Modified: 08/15/2018 The Monty Hall Problem This code: a) Creates and initializes five processes for never switching door simulations. b) Executes all five processes. Give each process 1/5 of the total simulations (2,000,000 each). c) Combines the five returned results lists ...
""" Get all text from csv files and extract the vocabulary The csv files have the following columns ['img_id', 'sent_id', 'split', 'asin', 'folder', 'sentence'] """ import pandas as pd import collections # Read in csv file and write vocabulary with_zappos = 'no_zappos' # with_zappos = 'with_ngrams' # only_zappo...
""" Kingsheep Agent Template This template is provided for the course 'Practical Artificial Intelligence' of the University of Zürich. Please edit the following things before you upload your agent: - change the name of your file to '[uzhshortname]_A1.py', where [uzhshortname] needs to be your uzh shortname - chang...
# Iterating multiple lists at the same time: # Zip method will work based on the size of the lists and it considers the list which has smaller size. # For example, list2 has smaller size and hence zip method will consider list2 size. # So zip iterates till '4534' in list2 and same length will be considered for list1 .S...
list1 = [] # Empty list print(list1) list1 = ["BMW", "AUDI", "FERRARI"] print(list1) # by Index print(list1[0]) print(list1[1]) print(list1[2]) # replacing the values in the list list1[1] = "HONDA" print(list1[1]) print(list1) # type casting range to list. print(list(range(0,10)));
# length of list list1 = ["BMW", "AUDI", "FERRARI"] print(len(list1)) # adding data to list list1.append("HONDA") list1.append("BUGAATI") list1.insert(2, "LAMBI") print(list1) # finding the index of a element List x = list1.index("LAMBI") print(x) # removing the elements from the list list1.pop() # By default it re...
# in Python, there are only two types of Inheritance. Multiple Inheritance and Multilevel Inheritance. class SuperClass(object): def __init__(self): print("From superclass constructor") def start(self): print("invoke Driving") def drive(self): print("Start Driving from super class...
from game.guess import Guess from game.hint import Hint from game.number import Number from game.player import Player from game.turn import Turn import random class Director: """A code template for a person who directs the game. The responsibility of this class of objects is to keep track of the score and con...
letter = 'ThiS is String with Upper and lower case Letters' split_letter = list(letter.lower()) letters = {} for chu in split_letter: letters[chu] = 0 for i in range(len(split_letter)): letters[split_letter[i]]+=1 for key in sorted(letters): print(key,letters[key])
numbers=[1,6,8,1,2,1,5,6] print('numbers =',numbers) find=int(input('nhap 1 so muon tim: ')) print(find,'appears',numbers.count(find),'times in my list')
weight=int(input('nhap so can nang cua ban(kg): ')) he=int(input('nhap chieu cao (cm): ')) hei=he/100 bmi=weight/(hei**2) print('chi so BMI cua ban la: ',bmi) if bmi<16: print('Severely underweight') elif bmi<18.5: print('underweight') elif bmi<25: print('normal') elif bmi<30: print('overweight') else: ...
numbers=[1,6,8,1,2,1,5,6] print('numbers =',numbers) find=int(input('nhap 1 so muon tim: ')) count=0 for i in range(len(numbers)): if numbers[i]==find: count+=1 print(find,'appears',count,'times in my list')
import sys import csv info = sys.stdin.readlines() info1 = csv.DictReader(info) for row in info1: column=row.get('YEAR') if column =="2016": print 1, "|",row['YEAR'],"|",row['Naics'],"|" ,row['Cip_name'],"|",row['Cip_code'],"|",row['Num_ppl'],"|",row['Avg_wage']
from os import stat import plotly.figure_factory as ff import statistics import pandas as pd import random import csv import plotly.graph_objects as go df=pd.read_csv("Temp.csv") data=df["temp"].tolist() def random_set_of_mean(counter): dataset=[] for i in range(0,counter): random_index=random.randint...
# Identify gender from first names # Adapted from https://www.nltk.org/book/ch06.html game_of_thrones = { 'male': [ 'Eddard', 'Robb',' Jon', 'Bran', 'Jaime', 'Joffrey', 'Tyrion', 'Theon', 'Varys', 'Viserys' ], 'female': [ 'Catelyn', 'Sansa', 'Arya', 'Cersei', 'Daenerys', 'Melisandre...
import pygame import time ''' LANDSCAPES = {".":(True, "graphics/tiles/grass.png"), \ ",":(True, "graphics/tiles/grass.png"), \ "G":(True, "graphics/tiles/grass.png"), \ "M":(False, "graphics/tiles/mountain.png"), \ "W":(False, "graphics/tiles/water.p...
import animal as animal from animal import * # ---------------------------------------------- class Beast(Animal): def __init__(self): super().__init__() self.type = 1 def read_str_array(self, strArray, i): # должно быт как минимум три непрочитанных значения в массиве if i >=...
def findMax(a,b,c): if a>b: bigt=a else: big=b if c>big: big=c return big a = int(input("첫번째숫자입력:")) b = int(input("두번째숫자입력:")) c = int(input("세번째숫자입력:")) biggest = findMax(a,b,c) print(a,b,c,"중가장큰수는",biggest,"입니다.")
print("Celsius\t | Fahrenheit") for celsius in range(0, 101, 10): fahrenheit = (celsius * 9/5) + 32 print(celsius,'\t','|' ,fahrenheit)
nombre = input('mi nombre es:') print('que tal buenos dias', nombre )
import random import copy class NQueen(object): #generates the board randomly for random restarts def GenerateRamdomBoard(self, a, n): i = 0 while( i < n): a[i] =random.randint(0,n-1) + 0 i += 1 def FillBoard(self, store, n): i = 0 while i < n: ...
import csv import random # Open the existing CSV file with open("whatever.csv", "r") as file: reader = csv.reader(file) # Store the rows in a list rows = list(reader) # Select 500 random rows selected_rows = random.sample(rows, 500) # Open a new file to save the selected rows with open("new.csv", "w", ne...
from typing import List from functools import reduce import numpy as np from fast_fourier_transform import fft, ifft def evaluate_polynomial(polynomial: List[float], value: float) -> int: total = 0 for power, coefficient in enumerate(polynomial): total += coefficient * (value ** power) return to...
from typing import List """ The sequence of values A[1], A[2], . . . , A[n] is unimodal: For some index p between 1 and n, the values in the array entries increase up to position p in A and then decrease the remainder of the way until position n. Find the index of the peak entry in O(log(n)) time. """ def peak_fi...
# -*- coding: utf-8 -*- import os from time import sleep from traceback import print_exc from distributors.RandomDistributor import RandomDistributor from strategies.RandomStrategy import RandomStrategy from constants import STATE, FIELD, MOVE, BOARD_SIZE, DEFAULT_SHIPS from Board import Board #TODO: board size, sh...
# -*- coding: utf-8 -*- from random import choice from game.constants import DIR from AbstractDistributor import AbstractDistributor class RandomDistributor(AbstractDistributor): """ This distributor simply puts boats on random positions. Thus it delivers a basic framework for ship deployment and a...
import tkinter as tk from tkinter import messagebox, simpledialog class UserInterface: USER_CHOICE = """ Enter: -'a' to add a new restaurant -'l' to list all restaurants -'r' tp mark a restaurant as visited -'d' to delete a restaurant -'q' to quit Your choice:""" def user_interf...
#var = 1 # for infinite loop constructs #while var == 1: #num = input("enter your number: ") #print("you entered the number is: ", num) #print("good bye") #Else statement in whileloop count = 0 while count < int(input("enter the number")): print(count, " is less then 5") count += 1 else: ...
#!/usr/bin/python def count_words(text, words): count = 0 for word in words: if word in text: count+=1 print "word ", word print "count is ", count return count assert count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3, "Example" assert count_w...
#!/usr/bin/python def checkio(str_number, radix): answer = 0 powers_list = [radix**y for y in range(0,10)] for i in range(0,len(str_number)): if str_number[len(str_number)-i-1].isalpha(): if (ord(str_number[len(str_number)-i-1]) - 55) >= powers_list[1] : return -1 sum =((or...
list1 = ['a','e','i','o','u','A','E','O','U','I'] def Translat_Word(word): s = '' i = 0 for i in word: if i not in list1 and i.isalpha(): s = s + i +"o"+ i else: s = s + i print s if __name__ == "__main__": word = raw_input("\nEnter word\n") Translat_Word(wo...
#Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) def FindLength(list1): c=0 for i in list1: c+=1 return c if __name__ == "__main__": list1 = raw_input("Ent...
def reverseFun(a,l,h): while(l < h): a[l],a[h] = a[h],a[l] l+=1 h-=1 def rightRotation(arr,n,k): print(arr) reverseFun(arr,0,n-1) reverseFun(arr,0,k-1) reverseFun(arr,k,n-1) print(arr) if __name__ == "__main__": arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arrlen...
def minReplacement(s1): if len(s1)>26: print("IMPOSSIBLE") else: char_freq = [0]*26 for i in range(len(s1)): char_freq[int(chr(s1[i])-chr(a))] count = 0 for i in range(len(s1)): if char_freq[int(chr(s1[i])-chr(a))] > 1: ...
def Reverse_Function(string): #first logic list2 = [] s = '' for i in range(len(string)-1,-1,-1): val = string[i] list2.append(val) list2 = ''.join(list2) print list2 #2 logic str = '' for s in string: str = s + str print str #3 logic if (len(string)) ...
def countFreq(str1): dict ={} for i in str1: key = dict.keys() if i in key : dict[i]+=1 else: dict[i] = 1 print(dict) str1 = "arati" countFreq(str1)
def Find_Max_Number(list1): Store_Max = 0 for Ele in list1: if Store_Max < Ele: Store_Max = Ele return Store_Max if __name__ == "__main__": list1 = [] L = int(raw_input("Enter Length")) print "Enter ele" for i in range(L): ele = raw_in...
from tests.unit.unit_base_test import UnitBaseTest from models.item import ItemModel class ItemTest(UnitBaseTest): def test_create_item(self): item = ItemModel('test', 11.11, 1) self.assertEqual(item.name, 'test', "The name of the item after creation does not equal the ...
from survey import AnonymousSurvey # 定义一个问题,创建关于这个问题的调查对象 question = "你最喜欢做什么事?" my_survey = AnonymousSurvey(question) # 显示问题并存储答案 my_survey.show_question() print("任何时候按下\"q\"退出程序。") while True: response = input("最喜欢做:") if response == "q": break my_survey.store_response(response) # 显示调查结果: print...
#Diffie Hellman q = 311 # q and root values are our base prime g = 2# our base root a = 9 # a and b values are our randomly generated key values b = 3 def diffieHellman(q,g,a,b): # Sender Sends Receiver A = g^a mod p keyA = (g**a)%q # 353 to the power of random value 1 modulus prime print("Share...
import random def print_board(board): print(board[7] + '|' + board[8] + '|' + board[9]) print('-+-+-') print(board[4] + '|' + board[5] + '|' + board[6]) print('-+-+-') print(board[1] + '|' + board[2] + '|' + board[3]) def player_symbol(): letter = ' ' while not (letter == 'X...
def break_loop(): for i in range(1, 5): if(i == 2): return (i) print(5)