text
stringlengths
37
1.41M
total = mil = menor = 0 cont = 0 barato = ' ' print('-'*30) print('LOJA SUPER BARATÃO') print('-'*30) while True: nome = str(input('nome do produto: ')) preco = float(input('preço do produto: $')) cont +=1 total+= preco if preco > 1000: mil+=1 if cont == 1 or preco < menor: meno...
import math n = float(input('digite um numero: ')) t = math.trunc(n) print('o número {} tem a parte inteira {}'.format(n, t))
sexo = '' while sexo != 'm' and sexo != 'f': sexo = str(input('qual o sexo da pessoa? M/F?: ')).lower() if sexo != 'm' and sexo != 'f': print('sexo inexistente, SEU PORRA!') print('por favor, digite novamento o sexo') print('FIM')
def leiadinheiro(msg): """ formata um valor(em dinheiro) com as características do REAL :param msg: recebe a string :return: retorna o numero float """ valido = False while not valido: entrada = str(input(msg)).replace('.',',').strip() if entrada.isalpha() or entrada == '': ...
import math numero = float(input('digite o valor de um ângulo: ')) s = math.sin(math.radians(numero)) c = math.cos(math.radians(numero)) t = math.tan(math.radians(numero)) print('o seno de {} é {:.2f}'.format(numero,s)) print('o cosseno de {} é {:.2f}'.format(numero,c)) print('a tangente de {} é {:.2f}'.format(numero,t...
s = float(input('qual o seu salario?: ')) a = ((s*15)/100) + s print('o seu salrio era {} R$, com 15% de aumento fica {} R$'.format(s, a))
def main(): empId = int(input("Enter an employee id (00000):")) if (empId == 82500): empName = "Helene Mukoko" elif (empId == 92746): empName = "Raymond Kuomo" elif (empId == 54080): empName = "Henry Larson" else: empName = "Unknown" print("Id # ", empId," The em...
def main(): lines = readFile() writeFile(lines) def readFile(): fname = input("Enter a filename: ") fp = open(fname, 'r') lines = fp.readlines() fp.close() return lines def writeFile(data): fp = open('output','a') for i in range(0, len(data), 1): fp.write(str(i) + ' ' ...
from List import * def main(): numbers = ArrayToList(eval(input("Enter an array of numbers: "))) print(reverse(numbers)) def reverse(items): return rhelper(None,items) def rhelper(t,s): if (s == None): return t else: return rhelper(join(head(s),t),tail(s)) main()
import sys def main(): rows = int(sys.argv[1]) cols = int(sys.argv[2]) mode = sys.argv[3] # Mode = 'recursive' or 'iterative' mode = sys.argv[3] mat = createMatrix(rows,cols,mode) print(mat) def createMatrix(r,c,m): if (m == 'recursive'): return recursiveMatrix(r,c) ...
def main(): ` arr = [[1,2,3],[4,5,6],[7,8,9]] # Iterating over the rows for i in range(0,len(arr),1): # Iterating over the columns for j in range(0,len(arr[i]),1): print(arr[i][j], end= ' ') print() sums = sumOfColumns(arr) print("Sums:", sums) Diag = sumDiag(...
import sys def main(): matrix = eval(sys.argv[1]) compute(matrix) pi(matrix) def compute(matrix): count = sum(matrix[0]) for i in range( 1, len(matrix), 1): count += matrix[i][len(matrix[i]) - 1] print("The sum of the first row and last column is",count) def sum(items): ...
import sys from List import * def main(): strings = ArrayToList(sys.argv[1:]) print("The second longest string is, ",secondLongest(strings)) def secondLongest(data): longest = head(data) second = 0 while (data != None): if (len(head(data)) > len(longest)): second = longes...
ax=input() b=ax.isalpha() if(b==True): print("Alphabet") else: print("No")
n=int(input()) if(n>0): print("Positive") elif(n<0): print("Negative") elife(n==0): print("Zero") else: print("enter a valid number")
import sys import pyautogui import argparse from datetime import datetime # validate the given argument to ensure it is an integer. def numeric_val(duration): if not duration.isnumeric(): raise argparse.ArgumentTypeError('Input Error. Expected a numeric value for duration. Found "{}"' ...
''' Module handles and manipulates all requests that are sqlite specific List of methods: get_tables_names get_columns_names get_column_data ''' from data.dbhelpers.Sqlite import Sqlite import logging def get_tables_names(target, index_col=None, coerce_float=True, params=None, ...
from address import Address class Person: def __init__(self, first, last, dob, phone, address): self.first_name = first self.last_name = last self.date_of_birth = dob self.phone = phone self.addresses = [] # Using isinstance to check if the address entered is the co...
#!/usr/bin/env python import sys import sqlite3 class mySqlite: """ Constructor le paso el nombre de la base de datos """ def __init__ (self,baseDatos): self.con = None self.tabs = {"nombreTabs":[],"idTabs":[],"pathIcono":[]} self.programas = {"ejecucion":[],"descripcion":[],"pathIcono...
#importando bibliotecas necessárias para funcionamento do código import sys #modulo nativo do python para algumas variáveis usadas ou mantidas pelo interpretador from PyQt5 import QtCore, QtGui, QtWidgets #framework em C++ para o desenvolvimento da UI import random #gerador de números pseudo-aleatórios import time #us...
# Modules import os import csv # Path to collect data from the Resources folder poll_csv = os.path.join("Poll.csv") # Create lists and initialize variables total_votes = 0 candidate_list = [] vote_count = [] Winner_Vote_Count = 0 # Read in the CSV file with open(poll_csv, 'r') as csvfile: # Split the data ...
import gym import numpy as np env = gym.make("MountainCar-v0") #environment has 3 actions you can take # 0 = go left, 1 = no accel, 2 = go right env.reset() #resets the environment each time the program runs # to the agent, it does not matter what these values represent print(env.observation_space.high) #highest value...
#To find if the file exists, path of file, if given path is file or a directory. import os from os import path import datetime from datetime import date, time, timedelta import time def main(): print(os.name) #Prints the os name #Output: #nt #CHECKING FILE'S EXISTENSE, IF THE PATH IS A FILE PATH...
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that # tells them the year that they will turn 100 years old. #Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. class Age: d...
def main(): x=0 #while loop while(x<5): print(x) x=x+1 print("") for i in range(1,5): print(i) print("") #range(x) gives the values 0 to x-1 #range(x,y) gives the values x to y-1 #Now, for loop over collection days=["mon","tue","wed","thurs"...
# -*- coding: utf-8 -*- M, N = map(int, input().split()) graph = {} visited = {} for _ in range(N): name1, _, name2 = input().split() try: graph[name1].append(name2) except KeyError: graph[name1] = [name2] if not name2 in graph: graph[name2] = [] visited[name1] = False ...
# -*- coding: utf-8 -*- inversions = 0 def merge(arr1, arr2): global inversions mid = len(arr1) sz = len(arr1) + len(arr2) merged = [0 for _ in range(sz)] arr1.append(float('inf')) arr2.append(float('inf')) i = 0 j = 0 for idx in range(sz): if arr1[i] <= arr2[j]: ...
# -*- coding: utf-8 -*- _ = input() nums = sorted(map(int, input().split()), reverse=True) half = sum(nums) // 2 acum = 0 for coin, num in enumerate(nums, start=1): acum += num if acum > half: print(coin) break
import matplotlib.pyplot as plt import numpy as np def show_curve(ys, title): """ plot curlve for Loss and Accuacy Args: ys: loss or acc list title: loss or accuracy """ x = np.array(range(len(ys))) y = np.array(ys) plt.plot(x, y, c='b') plt.axis() plt.title('{} cur...
def find_fraction(summ): if summ < 3: return False if summ%2 != 0: a = summ/2 else: a = summ/2 - 1 b = summ - a flag = True while flag: if b % a == 0: break if a % (b % a) != 0 or (b % a) == 1: flag = False else: ...
def str_to_int(a): return [int(i) for i in list(a)] def read_input(): with open("input.txt", 'r') as f: algo_name = f.readline() n = int(f.readline().strip()) p = int(f.readline().strip()) data = list(map(str_to_int, f.read().split())) return (n, p, data)
#데이터 프레임에 함수적용 frame = pd.DataFrame(np.random.randn(4,3), columns = list('bde'), index = ['Utah', 'Ohio', 'Texas', 'Oregon']) frame np.abs(frame) print(frame) def f(x): return pd.Series([x.min(), x.max()], index=['min','max']) frame.apply(f) print(frame) format = lambda x:"%.2f"%x frame....
import matplotlib.pyplot as plt years = [1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2000, 2002, 2006, 2010, 2014] medals = [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 3, 2, 1, 5, 0, 13, 10, 3, 1] plt.plot(years, medals, color=(255/255,...
import random import quiz_common words = { } # ask the user for quiz type print("Quiz Types: sat, spanish") quiz_type = input("Enter quiz type: ") data_files_path = quiz_type + "/" # randomly select a file random_file_num = random.randrange(1,3) random_file_num = str(random_file_num) word_file = data_fi...
import cv2 import math import numpy import os from PIL import Image, ImageDraw def rotatePoints(origin, point, angle): """Rotate a point by a given angle around a given origin.""" # Taken from https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python angle = math.radians(an...
# _*_ coding: utf-8 _*_ """ LSTM prediction 考虑时间维度,以一天为周期输入分钟数 """ import math import numpy as np import time from keras.layers.core import Dense,Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from sklearn.metrics import mean_squared_error from lstm_pre import data_pre str=10 #设置时间...
import random import string from words import words from hangman_drawing import user_lives def get_valid_word(words): word = random.choice(words) while '-' in word or ' ' in word: word = random.choice(words) return word.upper() def hangman(): lives = 6 word = get_valid_word(words) ...
# BLOKUSFUNCTIONS.PY # Functions useful for the other classes import numpy as np def findExtremes(points): """Return the minimum and maximum x and y from a 2xn array of points.""" xmin = xmax = points[0,0] ymin = ymax = points[1,0] for i in range(0, points[0].size): curx = points[0,i] ...
from math import sin, cos import random class Polecart: # state variables theta = 0.00 thetaVel = 0.0 thetaAcc = 0.0 x = 0.0 #pole position. y = 0.0 xVel = 0.0 xAcc = 0.0 gravity = -9.81 massCart = 1.0 massPole = 0.1 totalMass = massCart+massPole poleLen = 0.5 ...
# One Time Pad encryption # an encrypting technique used to to shift every character of a message according to a one time pad (or just a radnom sequence) # I've encorporated my own random function into the algorithm import datetime alphabet = ['i', 'l', 'o', 'v', 'e', 'k', 'a', 'n', 'b', 'r', 'u', 'g', 'm', 'h', 'c...
__author__ = 'Ruslanas' from graphics.vector import Vec3 from tkinter import * root = Tk() canvas = Canvas(root, width=100, height=100) canvas.pack() vec = Vec3(0, 50, 0) origin = Vec3(50, 50, 0) for i in range(12): canvas.create_line(origin.x, origin.y, (origin + vec).x, (origin + vec).y) vec.rotate_z(30)...
a = 1 for i in range(9): a = (a + 1) * 2 print(a) for i in range(3): print(' ', end=' ') for a in range(i): print('*') sum= 0 for b in range(1, 20): sum = ((b+1)/b)+sum print(sum)
a = int(input("enter number1 :")) b = int(input("enter number2 :")) c = int(input("enter number3 :")) if(a>b and a>c): print(a," is largest") else: if(b>c): print(b," is largest") else: print(c," is largest")
''' Finds k-th smallest element in the array arr. ''' ######################################################################### from random import randrange def find_kth(arr, k, start=0, end=None): if not end: end = len(arr) -1 pivot_ridx = randrange(start, end) pivot = arr[pivot_ridx] pi...
import os import openpyxl def calculate_water_usage(work_book, work_sheet_names, row_num): """ 2か月ごとの水道使用量を取得 """ # 初期処理 work_sheet = work_book.get_sheet_by_name(work_sheet_names[0]) # 水道使用量リスト sum_of_water_usage_per_one_month = [] water_usage_per_one_month = [0] """ index 0 :...
import psycopg2 import time import serial def main(): banco = Banco('projects','arduinoproject','postgres','banco') # Cria conexao: banco.connection(); banco.insertDataInto(table='environment', description='soil') banco.selectAllDataFrom(table='environment') class Banco: """Database class. U...
def main(): hieght = int(input("Enter Hieght: ")) for i in range(0,hieght): for j in range(0,i+1): print("*",end= "" ) print("") if __name__ == "__main__": main()
class Solution(object): def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ """ They key to make this efficient as possible is to reduce the number of times we check if an integer is a factor of the input number. Number Theory: ...
#!/usr/bin/env python # HW04_ex08_11 # The following functions are all intended to check whether a string contains # any lowercase letters, but at least some of them are wrong. For each function, # describe what the function actually does (assuming that the parameter is a # string). # Do not merely paste the output...
#! usr/bin/env python3 # -*- coding:utf-8 -*- """ @Author:zhoukaiyin """ # n的阶乘 def getFactorial(n): if n==1: return 1 return n*getFactorial(n-1) # 求字符串所有子序列 def printAllSubsquence(test, i, res): if i == len(test): print(res) return printAllSubsquence(test, i+1, res) printA...
#! usr/bin/env python3 # -*- coding:utf-8 -*- """ @Author:zhoukaiyin """ #! usr/bin/env python3 # -*- coding:utf-8 -*- """ @Author:zhoukaiyin """ #时间复杂度太高 def lengthOfLongestSubstring(s: str) -> int: min = 0 string = "" for i in range(1,len(s)+1): for j in range(len(s)-i+1): lis = s[j:j...
# -*- coding: utf-8 -*- __author__ = "Anshul Kapoor(10456388)| " \ "Pranay Singh(10455251) | " \ "Himanshu Bishnoi(10451752)" """ J&M 3rd Exercise 11.1 """ from stat_parser import Parser import nltk moby_dick = nltk.corpus.gutenberg.raw('melville-moby_dick.txt') sent_tokenizer = nltk.data...
def sum(num): if(num==0): return 0 else: return (num%10) + sum(num//10) def main(): num=int(input("Enter the number : ")) ret=sum(num) print("Sum is : ",ret) if (__name__=="__main__"): main()
import math def area_triangle(side1, side2, side3): """Returns the area of a triangle with the given side lengths.""" # Uses Heron's formula s = (float(side1) + side2 + side3) / 2 return math.sqrt(s * (s - side1) * (s - side2) * (s - side3)) print area_triangle(3, 4, 5)
#-*-coding:utf-8-*- import pilas import piedra_espacial import random #import contador_de_vidas from grilla import Jeison class Estado: "Representa un estado dentro del juego." def actualizar(self): pass #tienes que sobrescribir este metodo... class Jugando(Estado): "Representa el estadop de ju...
1 - Faça um Programa que peça dois números e imprima o maior deles. 2 - Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido. 3 - Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se ...
# -*- coding: utf-8 -*- # Se listarmos os números menores que 10 e que são múltiplos de 3 e de 5, temos 3, 5, 6 e 9. # A soma desse múltiplos é 23 # Descubra a soma de todos os múltiplos de 3 e de 5 e que são menores que 1000 limite = 1000 total = 0 for i in range(0, limite): if i % 3 == 0: total = total ...
# -*- coding: utf-8 -*- # O código abaixo imprime o somatório dos números da lista # Por que ele está dando erro? # Como podemos corrigir? lista = [ "0", 1, 2, "3", 4 ] total = 0 for elemento in lista: total = total + elemento print(total)
numbers = [] def even(): for num in range(1,51): if num % 2 == 0: numbers.append(num) print(numbers) return numbers even()
import random # For generating random numbers import sys # We will use sys.exit to exit the program import pygame from pygame.locals import * # Basic pygame imports from tkinter import * # Global Variables for the game SCREENWIDTH = 320 SCREENHEIGHT = 560 GROUNDY = SCREENHEIGHT * 0.84 #base.png 84% height G...
a=int(input("Enter a: ")) b=int(input("Enter b: ")) c=int(input("Enter c: ")) if a+b>c and a+c>b and b+c>a: print(a, b, c) print("triangle exists") else: print("triangle does not exist")
#1 Task. #Вводится строка. # Если в строке больше символов в нижнем регистре - вывести все в нижнем, #если больше в верхнем - вывести все в верхнем, #если поровну - вывести в противоположных регистрах. s = input ("1. Enter a string: ") s1 = s * 2 template_1 = "Some string {0}\nSome edited string {1}" c...
year = int(input("year: ")) leap = 366 usual = 365 if year % 4 !=0: print("Quantity of days: ", usual) elif year % 4 == 0: print("leap year:", leap) elif year % 100 !=0: print("leap year:", leap) elif year % 400 != 0: print("leap year:", leap) else: pass
import copy a=[[1,2,3,4],[4,5,6,7]] b=copy.deepcopy(a) print("a and b before modify") print(a) print(b) a[0][1]=10 print("a and b after modify. b was obtain as a copy of a") print(a) print(b)
# 3. List - contain set of elements, defined in [], can be set of nums, strings or combination list_numbers = [12, 34, 23, 56, 45645, 234, 7862] list_language = ["English", "Malay", "Mandarin", "Tamil"] list_numbs_language = [34, 76, 54, "Python", "Java", "C++"] # Concatenation output = list_numbers + list_language p...
# 4) read using csv library # Advantage : each line will be converted to list automatically import csv # fobj is file object used for reading any kind of file with open("realestate.csv", "r") as fobj: # converting file object to csv object reader = csv.reader(fobj) for line in reader: print(line)
import os print("Current directory =", os.getcwd()) print("Current username :", os.getlogin()) # list all the files for file in os.listdir(): print(file) # files from D: for file in os.listdir("D:\\"): print(file) # delete file in the directory # os.remove("put the file name") # # delete extension files ...
def CurrentBoard(Board): print("\n", Board.get("0"),"|",Board.get("1"),"|",Board.get("2"), "\n---+---+---\n",Board.get("3"),"|",Board.get("4"),"|",Board.get("5"), "\n---+---+---\n",Board.get("6"),"|",Board.get("7"),"|",Board.get("8")) def NewBoard(): i = 0 Board = {} while...
#coding:utf-8 import urllib2,json import city def ctq(): name = raw_input('你想查询哪个城市的天气:') bianma = city.city.get(name) if bianma: try: url='http://www.weather.com.cn/data/cityinfo/%s.html' % bianma result=urllib2.urlopen(url) html=result.read() html=js...
from datetime import datetime def string_to_bool(string): if string in ('f', 'F', 'false', 'False', 0): return bool(False) elif string in ('t', 'T', 'true', 'True', 1): return bool(true) else: print("Please use true or false values.") class TestClass: """ test class to show effect of change attribute method...
def leaderof_array(arr): for i in range(len(arr)): flag = False for j in range(i+1,len(arr)): if arr[i] <= arr[j]: flag = True break if flag == False: print(arr[i],end=" ") arr = [7,10,4,10,6,5,2] print(leaderof_array(arr))...
import math def check_prime(number): if number <=1: return False if number == 2: return True for i in range(2,number): if number%i ==0: return False return True def check_prime1(number): if(number<=1): return False if number ==2: return T...
def middle_linkedlist(self): method 1 if self.head == None: print("No element") else: llist = self.head count = 0 while llist: count = count+1 llist = llist.next llist1 = self.head for i in ra...
def givensubarraySumzero(arr): for i in range(len(arr)): curry_sum = 0 for j in range(i,len(arr)): curry_sum += arr[j] if curry_sum == 0: return True return False def givensubarraySumzero1(arr): result = set() prefix_sum = 0 for i in ...
## GCD of the number of the navie approach. def gcd_number(num,num1): result = min(num,num1) while(result>0): if num%result ==0 and num1%result == 0: break; result = result-1 return result print(gcd_number(2,4)) ## Time complexitity = 0(min(num,num1)) ## GCD of the numbe...
def compute_power(number,number1): result =1 for i in range(number1): result = result*number return result def compute_power1(number,number1): if number1 == 0: return 1 temp = compute_power1(number,number1//2) temp = temp*temp if(number1 %2 ==0): return temp ...
def factorial(num): if num==0 or num==1: return 1 else: return num*factorial(num-1) print(factorial(5)) def fibonacci_number(num): if num == 0: return 0 if num ==1: return 1 return fibonacci_number(num-1)+fibonacci_number(num-2) print(fibonacci_number(3))
def peak_element(arr): low =0 high = len(arr)-1 n = len(arr)-1 while low <= high: mid = (low+high)//2 if (mid==0 or arr[mid-1]<arr[mid]) and (mid==n or arr[mid]> arr[mid+1]): return arr[mid] elif mid >0 and arr[mid-1] > arr[mid]: high = mid-1 else...
def transpose_matrix(arr,r,c): for i in range(0,r): for j in range(i+1,c): arr[i][j],arr[j][i] = arr[j][i],arr[i][j] return arr arr = [[1,2,3],[4,5,6],[7,8,9]] print(transpose_matrix(arr,3,3))
n=int(input("Enter the value :")) for i in range(1,6): m=n*i print(m)
n=[1,2,3,4,5] sum=0 k=2 for i in range(0,k): sum=sum+n[i] print(sum)
x=int(input("Enter the year :")) if(x%4==0): print(x,"is a leap year") else: print(x,"is not a leap year")
# # @lc app=leetcode.cn id=306 lang=python3 # # [306] 累加数 # # https://leetcode.cn/problems/additive-number/description/ # # algorithms # Medium (38.16%) # Likes: 374 # Dislikes: 0 # Total Accepted: 44.1K # Total Submissions: 115.6K # Testcase Example: '"112358"' # # 累加数 是一个字符串,组成它的数字可以形成累加序列。 # # 一个有效的 累加序列 必须 至...
# # @lc app=leetcode.cn id=81 lang=python3 # # [81] 搜索旋转排序数组 II # # https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/description/ # # algorithms # Medium (41.20%) # Likes: 639 # Dislikes: 0 # Total Accepted: 171.2K # Total Submissions: 415.4K # Testcase Example: '[2,5,6,0,0,1,2]\n0' # # 已知存在一个按非降序排...
# # @lc app=leetcode.cn id=590 lang=python3 # # [590] N叉树的后序遍历 # # https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/description/ # # algorithms # Easy (72.93%) # Likes: 61 # Dislikes: 0 # Total Accepted: 20.8K # Total Submissions: 28.5K # Testcase Example: '[1,null,3,2,4,null,5,6]' # # 给定一个 N 叉树,返...
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ length = len(nums) if not length: return -1 if target < nums[0]: i = length-1 while i > 0 and target < nums[...
# -- coding: utf-8 -- import string class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ unique_letters = [l for l in string.ascii_lowercase if s.count(l)==1] unique_index = [s.index(l) for l in unique_letters] return min(uniq...
# -- coding: utf-8 -- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int ...
# -- coding: utf-8 -- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def build_link_str(self, prefix, val): if prefix: return '%s->%s' % (prefix, va...
# -- coding: utf-8 -- class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ max_positive_value = 2**31-1 min_negative_value = -2**31 int_val = [] starrted = False for char in str: if char.isspace(): ...
# -- coding: utf-8 -- class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 3: return 0 result = [False] * 2 + [True] * (n - 2) for i in range(2, int(n ** 0.5) + 1): if result[i]: re...
#str=input("please provide any of the string:") #if ele in range len(str): #kindom king #k=str[0] #for ele in range(len(str)): #print(str.replace(str[0],'@',5)) def change_char(str1): char = str1[0] str1 = str1.replace(char, '$') str1 = char + str1[1:] return str1 print(change_char('restart'))
class User: __name = '' __email = '' def __init__(self, name, email): self.__name = name self.__email = email def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_email(self, email): self.__email = email def get_email(self): return self.__email def info(...
def merge_sort(s): if len(s)<2: return(s) else: left=merge_sort(s[:len(s)//2]) right=merge_sort(s[len(s)//2:]) return(merge(left,right)) def merge(left,right): i,j = 0,0 result=[] while i<len(left) and j<len(right): if left[i]<=right[j]: result.append(left[i]) i+=1 else: result.append(righ...
""" Forms.py: This will handle user authenticationagainst our DB """ from django import forms from django.contrib.auth.models import User from accounts.models import Profile # This class will be responsible for handling the registration of a new user class UserRegisterForm(forms.ModelForm): """ passwo...
# Author: Kishon Diaz # Date: 02/7/2014 # File: volume_and_surface.py # Description: This is a program to calculate the volume and surface area of a sphere """ ALGORITHM: The pseudocode description for how the program performs its tasks. Write as many lines as necessary in this space to describe the method selected t...
# Author: Kishon Diaz # Date: 02/16/2014 # File: futureValuehw4.py # Description: Brief This is a revised future vaule caluation program # just the required code for the homework """ ALGORITHM: """ # IMPORT STATEMENTS # GLOBAL VARIABLES # FUNCTIONS # MAIN FUNCTION def main(): print("This is a revised f...
''' Author: Catherine Boothman Student Number: D12127081 Graphical User Interface for user to input new inventory items to the system. ''' # --------------------------------------------------- First GUI --------------------------------------------------- # First screen allows the user to either load a ....
#lists def add_all(t): """Add all the numbers in t and return the sum""" total = 0 for x in t: total += x return total # Exercise 4 def is_anagram(s, t): """return True if s and t are anagrams""" u = list(s) v = list(t) return u.sort() == v.sort()
import random class Player(): def __init__(self,name): self.name = name self.wins = 0 self.losses = 0 self.ties = 0 def __str__(self): return f"\n{self.name}\n{self.wins} - {self.losses} - {self.ties}\n" def addResult(self, result): if result == 1: ...