text
stringlengths
37
1.41M
import numpy as np arr = np.arange(0, 3*4) a = arr.reshape([3,4]) print(a) b = np.array([0,1,2,3,4]) print(b[2]) print(b[-1]) print(a) #콤마를 기준으로 앞,뒤:행 열 print(a[0,1]) print(a[-1,-1]) #인덱싱: 행 지정 후, 슬라이싱: 콤마 뒤 추출열 지정 print(a[0,: ]) #첫번째 행 전체를 추출 print(a[ :,1]) #두번째 열 전체를 추출 print(a[1, 1:]) # 두번째 행의 두번째 열부터 끝열까지 추출 print...
for i in range(10): print(i, end=" ") print() for i in range(0, 10): print(i, end=" ") print() for i in range(0, 10, 1): print(i, end=" ") print() for i in range(10-1, -1, -1): print(i, end=" ") print() for i in reversed(range(10)): print(i, end=" ") print() s = 0 for i in range(5): s+=i...
# 이벤트 처리 1 from tkinter import * from tkinter import messagebox # 함수 선언부 def clickLeft(event): xCor = event.x yCor = event.y mButton = event.num txt = "" #빈 문자열 준비 if mButton == 1: txt += '왼쪽' elif mButton == 2 : txt += '가운데' else: txt += '오른쪽' txt += '를' + str(x...
import numpy as np print(np.__version__) list1 = [1,2,3,4] a = np.array(list1) print(a) # [1 2 3 4] print(a.shape) # shape:(4,)=> rank:1 b = np.array([[1,2,3],[4,5,6]]) print(b) print(b.shape) # shape:(2, 3) 2행 3열, rank:2 print(b[0,0]) print(a[2]) print(type(b)) #<class 'numpy.ndarray'> 자료구조 print(type(list1)) #<class...
numStr = '', '' numStr = input("숫자를 입력하세요") print('') i=0 ch=numStr[i] while True: heartNum = int(ch) heartNum = "" for k in range(0, heartNum) : heartStr +="\u2665" k += 1 print(heartStr) i+= 1 if(i > len(numStr)-1) : break ch =
import random dice = input('What side dice are you rolling? ') number = input('How many are you rolling? ') print('You rolled ' + number + 'd' + dice + ' and got: ') for i in range(1, int(number) + 1): print(random.randrange(1, int(dice) + 1))
first = input('Enter first word') second = input('Enter second word') lst = [first, second] word = '-'.join(lst) print(word)
"""Make it rain""" import operator import urllib.request from bs4 import BeautifulSoup def read_in_file(file): f = open(file, 'r') unformatted_file = f.readlines() return unformatted_file def make_table(file): table = [line.split() for line in file] return table def strip_headers(unformatted...
# write a program that reads the length of the base and the height of a right angled triangle and prints the area. every number is given on a separate line. length = int(input('enter the length of the base of right angled trianlgle')) height = int(input('enter the height of the right angled triangle')) area = 1/2 * len...
#4.Given threeintegers, print the smallestone.(Threeintegers should be user input) num1 = int(input("enter first number")) num2 = int(input("enter second number")) num3 = int(input("enter third number")) if num1<num2 and num1<num3: print(f'{num1} is smallest') elif num2<num1 and num2<num3: print(f'{num2} is the...
# 1. Найти функцию которая принимает несколько аргументов. # - С помощью partial передать часть (не все) аргументы в найденную функцию создав новую. # - Передать остаток аргументов получив результат вычисления from functools import partial def t66(a, b): return a + b fn2 = partial(t66, 4) print(fn2) pri...
import streamlit as st import pandas as pd def app(): datafile = "bostoncrime2021.csv" df = pd.read_csv(datafile) datafile2 = "BostonPoliceDistricts.csv" df2 = pd.read_csv(datafile2) st.title('Analysis of Boston reported Crime Data') st.subheader("Hello! Welcome to the ...
print('----小天使----') temp=input('猜一猜我的小天使是谁:') guess = temp if guess=="周 ": print("猜对了啦") print("猜对了也没奖励") else: print("猜错了") print("猜错了要请客吃饭") print("游戏结束")
''' 循环为多个客户端服务器 ''' import socket def main(): #1. 创建套接字 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #2. 绑定本地信息bind tcp_server_socket.bind(("127.0.0.1", 10000)) #3. 让默认套接字由主动改为被动listen tcp_server_socket.listen(128) while True: #4. 等待客户端的链接accept new_client_socket, client_addr = ...
# Python file to test reading files. # Chp 5 last line exercises, Python Workbook. # Date: 8/5/2020 f = open('demofile.txt', 'rt') blob = f.read() print(blob) f.close() # Printed whole file with correct line spacing, # and without \n tags f = open('demofile.txt') lines = f.readlines() # read all lines into ...
""" Copy of book code, with my comments. """ from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y # x, y values passed in when class constructor is called def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) # returns x...
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1/(1+np.exp(-x)) def deriv_sigmoid(x): fx = sigmoid(x) return fx * (1 - fx) def mse_loss(y_true,y_pred): return ((y_true - y_pred) ** 2).mean() class neural_network: def __init__(self): self.w1 = np.random...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 15:54:50 2018 @author: user """ low = int(input("enter the lowest number of range:")) high = int(input("enter the highest number of range:")) """ def perfectSq(num): if num/math.sqrt(num) == math.sqrt(num): print("Sq root:", math.sqrt(num)) ...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 14:21:06 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] list2 = [int(x) for x in input("enter the elements of the list2:").split()] mergedList = list1 + list2 print("Merged list:", mergedList) mergedLi...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 14:48:07 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] print("Element 3: ", list1[2]) print("Element 6: ", list1[5]) print("First 5 elements: ") for i in range(0,5): print(list1[i]) length =...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 17:29:26 2018 @author: user """ string=input("Enter string:") list1=[] list1 = string.split() wordfreq=[list1.count(p) for p in list1] print(dict(zip(list1,wordfreq)))
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 16:17:05 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] list2 = [] for i in range(0,len(list1)): total = 0 for j in range(0,i+1): total += list1[j] list2.append(total) print(...
# -*- coding: utf-8 -*- """ Created on Thu Jul 26 14:31:51 2018 @author: user """ a = [['Rhia',10,20,30,40,50], ['Alan',75,80,75,85,100], ['Smith',80,80,80,90,95]] #print(type(a)) list1 = [] for i in a: list1.append(i[0:2]) print("the original list is: ", a) print("the sliced list is: ", list1) ...
import types class Strategy: def __init__(self, Instance="Default", function=None): self.name = Instance def execute(self): print("{} is used!".format(self.name)) def strategy_one(self): print("{} is used to execute method".format(self.name)) def strategy_two(self): print("{} is used to execute method".form...
""" [[1,3], [], [2], [4,5], [], [], []] moveCamel(3,1) return [[1], [3], [2], [4,5]] moveCamel(1,1) return [[], [1, 3], [2], [4,5]] moveCamel(2,1) return [[1], [3], [], [4,5,2]] [1 ,2] + [3] = [1, 2, 3] [0,1,2,3,4] [startind : endind : spacing] """ class Board(object): def __init_...
st=input('enter string').split(' ') if st[0]=='Is': s='' for i in st: s+=i print(s) else: st.insert(0,'Is') s='' for i in st: s+=i print(s)
str1=input('Enter ') print(str1) str2=input('Enter ') print(int(str2)+10)
num=int(input('Enter the number: ')) if num<17: diff=17-num print(diff) else: diff=abs(17-num)*2 print(diff)
a=int(input('enter number: ')) n1=int('%s'%a) n2=int('%s%s' %(a,a)) n3=int('%s%s%s'% (a,a,a)) print(n1+n2+n3)
string_value='1234' # here 1234 is a string print(int(string_value)+10) # you can convert int to a string but you cannot convert a string value as a string
# Parent class class Pets: dogs = [] def __init__(self, dogs): self.dogs = dogs # Parent class class Dog: # Class attribute species = 'mammal' # Initializer / Instance attributes def __init__(self, name, age): self.name = name self.age = age # Instance method ...
""" 543. 二叉树的直径 https://leetcode-cn.com/problems/diameter-of-binary-tree/ 时间 O(N) 遍历每一个节点 空间 O(height) 不需要DP """ class Solution: ans = 0 def get_d(self, root): def depth(root): if not root: return -1 depth_l = depth(root.left) + 1 depth_r = depth(...
from random import choice cpu = choice(["ROCK","PAPER","SCISSOR"]) print("ROCK..") print("PAPER>>") print("Scissor") player = input("enter ur move") for i in range(1,3): if player.upper()==cpu.upper(): print("TIE") player = input("enter ur move") else: if player.upper()=="ROCK": ...
def is_leap(year): leap = False # Write your logic here if year%4==0: if year%100==0 and year%400==0: leap=True elif year%100!=0 and year%400!=0: leap=True else: leap=False return leap year = input("Enter y...
from random import randint ran = randint(1,10) x = input("Enter the number") while(int(x)!=ran): if(int(x)<ran): print("Too low") x = input("Enter new guess") elif(int(x)>ran): print("too high") x = input("Enter new guess") print("{} yes u guessed it".format(int(x))) friend = ["Undertaker","John","Batista"]...
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.board = board self.siz = len(board) self.solve() def findSlot(self): for i in range...
# coding=utf-8 # The MIT License (MIT) # Copyright (c) 2016 mateor from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import unittest import random # best/average = O(n^2) # very slow - minimal to zero production v...
# coding=utf-8 # The MIT License (MIT) # Copyright (c) 2016 mateor from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) # ComplexityTheta(n log n) # A bit slower in practice than quicksort - but has a better # worst-ca...
def factorial_last_zero(number): fact=1 temp=1 while temp <= number: fact*=temp temp+=1 print(fact) count = 0 while fact%10 == 0: fact //= 10 count += 1 return count def fau(number): count=0 i = 5; while i <= number: count+=number//i ...
a=int(input("小明身上有幾元:")) b=int(input("有幾種飲料:")) t=0 for i in range(b): c=int((input("第"+str(i+1)+"種飲料:"))) if a>=c: t+=1 print("可以買的飲料:"+str(t))
a=int(input("國:")) b=int(input("英:")) c=int(input("數:")) d=int(input("體:")) e=int(input("程設:")) ans=(a+b+c+d+e)/5 t=[] t.append(a) t.append(b) t.append(c) t.append(d) t.append(e) t.sort() print("平均分數:"+str(round(ans,2))) print("最高分科目"+str(t[4])) print("最低分科目"+str(t[0]))
import random import _sqlite3 conn = _sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS card") create_table = 'create table if not exists card (id INTEGER, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);' insert_data1 = "insert into card(number, pin) values (?, ?);" insert_id ...
# Get test data for sample of target words to evaluate accuracy. # Similar to get-data-train.py, but more to do here as we have to ensure not to select those already in train # set, meaning there are fewer potential sentences. import lib.utility as u import config as c import random if __name__ == "__main__": #...
''' Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? ''' ''' Time Limit Exceeded class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): visitedNodes = [] if head == None: return False ...
''' Integer to Roman Total Accepted: 6260 Total Submissions: 19425 Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. ''' class Solution: # @return a string def intToRoman(self, num): dict = {1:"I", 2:"II", 3:"III", 4:"IV", 5:"V", 6:"VI", 7:"VII", 8:"VI...
''' Gas Station Total Accepted: 8759 Total Submissions: 36746 There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty t...
def chapter1(): p = (3,7) x,y = p print("x: " + str(x)) person = ["Mohamed","Developer",(1,1,1995)] name,job,birth = person print("name: " + name) # star expressions print("********* star expressions *************") data = ["somename", "many", "others", "information"] name, *ot...
class student: prof_name="Kamal Sir" def __init__(self,r,n,m): self.rno=r self.name=n self.marks=m def talk(self): print("rno =",self.rno) print("name =",self.name) print("marks =",self.marks) def find_grade(self): if self.marks>80: print("Grade A") else: print("Grade B") @staticmethod def ...
import random # Given a string s and an integer list indices of the same length. # The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. # Return the shuffled string. s = "odce" indices = [1, 2, 0, 3] ans = "" for i in range(len(indices)): ans += s[...
class Contato: #Contato telefonico def __init__(self, codigo): self.codigo = codigo self.nome = None self.telefone = None self.email = None self.proximo = None self.anterior = None """ self.contatos Lista com os contatos / implantar Fase 2""" ...
import sys def main(): n = len(sys.argv) if(n > 3): print("Error") command = sys.argv[1] value = int(sys.argv[2]) if(command == "ABC"): print(2*value) if(command == "XYZ"): print(5*value) if(command == "FOO"): print(10*value) sys.exit(0) if __name__ == '__main__': main()
# To print odd or even number. num = int(input("Number: ")) if num % 2 == 0: print(f"Given {num} is Even Number.") else: print(f"Given {num} is Odd Number.")
from basic_list import List, Node class IncresingOrderLinkList(List): def bulk_insert(self, values): for value in values: self.insert(value) def insert(self, value): new_node = Node(value) if self.head is None: self.head = new_node;return head = self.hea...
from math import sqrt class Vector: def __init__(self, a, b): self.a = a self.b = b def __add__(self, vector): return Vector(self.a + vector.a , self.b + vector.b) def __str__(self): return "Vector({},{})".format(self.a, self.b) ab= Vector(1,2) ac= Vector(5,8) print ab+a...
class Node(): def __init__(self, value): self.value = value self.next = None class List(): def __init__(self): self.head = None def printList(self): tmp = self.head while (tmp): print tmp.value, tmp = tmp.next print "\n" def add...
import threading import time # semaforo1 = threading.Semaphore(1) # semaforo2 = threading.Semaphore(1) # semaforo3 = threading.Semaphore(1) def threadRed(n): semaforo2.acquire() semaforo3.acquire() for i in range(n): if i%3==0: semaforo1.acquire() print(i, end =" ") ...
""" First Pass ( 5 1 4 2 8 ) --> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) --> ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) --> ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) --> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm d...
# Python program to understand # the concept of pool import multiprocessing import os ############################################################## ############################################################## ############################################################## def square(n): print("Worker process id...
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 06:22:09 2020 @author: RAMPRIYAN """ from array import* arr1=array('i',[12,34,54,32,11,76]) arr1.insert(6,79) arr1.remove(12) arr1[0]=98 print(arr1.index(32)) for i in arr1: print(i)
a=input("Enter a :") b=input("Enter b:") temp=a a=b b=temp print("The value of a after swapping:{}".format(a)) print("The value of b after swapping:{}".format(b))
import docx import unidecode import re import csv ellipses_char = "\u2026" left_quote = "\u201c" right_quote = "\u201d" def get_file_as_word_list(file_name: str): """ Get all the words in the file as a word list. Parameters ---------- file_name: str The file name to get the words from. ...
def BinarySearch(number_list,numbet_to_find): left_index = 0 right_index = len(number_list)-1 mid_index = 0 while left_index<=right_index: mid_index = (left_index+right_index)//2 mid_number = number_list[mid_index] if mid_number == numbet_to_find: return mid_index ...
# merging sort def mergingSort (arr): if (len(arr)> 1): mid = len(arr)//2 left = arr[:mid] right= arr[mid:] mergingSort(left) mergingSort(right) i=j=k=0 while (i < len(left) and j < len(right)): if left[i] < right[j]: arr[k]...
import OthelloLogic import action1 import util from copy import deepcopy from pprint import pprint def action(board, moves): """ Args: board ${1:arg1} moves ${2:arg2} Returns: move 選択したmove """ pprint(moves) # 確定マスではない辺はなるべく取りたい sidePos = len(board) - 1 fo...
import math # IMPORT TP2 def pgcd(a, b): while b != 0: r = a % b a = b b = r return a def bezout(a, b): (u0, u1) = (1, 0) (v0, v1) = (0, 1) while b != 0: r = a % b q = (a - r) / b (a, b) = (b, r) (u0, u1) = (u1, u0 - q*u1) (v0, v1) = ...
#!/usr/bin/python ''' This script returns the optimal path from one point to another on a 3D cost mask (e.g. brain mask). Note that this is a path and not an interpolation of electrodes along a path. It takes as inputs two sample voxel coordinates representing the starting and ending points on a mask surface as well...
# IA - Particle Swarm Optimization # By: Isaac Montes Jiménez # Created: 10/13/2019 # Modified: 10/15/2019 import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D import numpy as np import random as ran import math #Define the range of the values by the obje...
from util import is_prime def awesomeness(a, b): n = 0 while is_prime(n**2 + a * n + b): n += 1 return n ma, ans = 0, 0 # max awesomeness, answer for a in xrange(-999, 999+1): for b in xrange(-999, 999+1): ca = awesomeness(a, b) # current awesomeness if ca > ma: ma,...
from math import sqrt def is_pentagonal(n): t = (sqrt(1 + 24 * n) + 1) / 6 return int(t) == t j = 1 done = False while not done: j += 1 P_j = j * (3 * j - 1) / 2 for k in xrange(j - 1, 1 - 1, -1): P_k = k * (3 * k - 1) / 2 if is_pentagonal(P_j - P_k) and is_pentagonal(P_j + P_k): ...
#! /usr/bin/env python import functools from math import sqrt import numpy import operator def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False for x in xrange(3, int(sqrt(n)) + 1, 2): if n % x == 0: return False re...
from math import pi print('Введите два радиуса или длину хорды и ничего: ') t = int(input()) r2 = input() if r2 != '': r1 = t r2 = int(r2) del t radiuses_product = r1 * r2 else: radiuses_product = t ** 2 / 16 s = pi * 2 * radiuses_product print(round(s, 2))
def factorial(n): if n == 1: return 1 else: if n == 2: return 2 else: return n * factorial(n - 1) def count_end_nulls(res): res = str(factorial(n)) ind = len(res) - 1 count = 0 while res[ind] == '0': count += 1 i...
def is_prime(n, divider): if divider > n // 2: return True else: if n % divider != 0: return is_prime(n, divider + 1) else: return False for n in range(2, 1001): if is_prime(n, 2): print(n)
""" Задача: Если элемент матрицы равен 0, то всю строку и весь столбец нужно обнулить. """ from random import randint matrix = [[randint(0, 10) for i in range(0, 5)] for i in range(0, 4)] for inner_arr in matrix: for j in inner_arr: print(j, end=' ' * (5 - len(str(j)))) # хитрый способ настр...
# Uses python3 import sys def optimal_weight(W, w): # write your code here val = [[None] * (len(w) + 1) for _ in range(W + 1)] for u in range(W + 1): val[u][0] = 0 print(val) for i in range(1, len(w) + 1): for u in range(W + 1): val[u][i] = val[u][i-1] if u >...
from sys import setrecursionlimit def fibonacci(prev=1, cur=1): swap = cur cur += prev prev = swap print(cur) print() return fibonacci(prev, cur) setrecursionlimit(2600) fibonacci()
from random import random n = int(input("Enter number of flips: ")) history = {'eagle': 0, 'tails': 0} for i in range(0, n): rand_num = random() if round(rand_num) == 0: history['eagle'] += 1 else: history['tails'] += 1 print(history)
x1 = int(input("Type x1: ")) x2 = int(input("Type x2: ")) y1 = int(input("Type y1: ")) y2 = int(input("Type y2: ")) a = abs(x2 - x1) b = abs(y2 - y1) print(a) print(b) if a / b == a // b or b / a == b // a: if a >= b: print(b + 1) else: print(a + 1) else: print(2)
fans_num1 = int(input('Введите кол-во болельщиков 1: ')) fans_num2 = int(input('Введите кол-во болельщиков 2: ')) places = int(input('Введите кол-во мест в номерах: ')) if fans_num1 % places == 0: rooms1 = fans_num1 // places else: rooms1 = fans_num1 // places + 1 if fans_num2 % places == 0: roo...
""" Задача: Дана гистограмма, она представлена числовым массивом: [3, 6, 2, 4, 2, 3, 2, 10, 10, 4] Нужно посчитать объем воды (1 блок в гистограмме), ктр наберется внутри нее. """ from matplotlib import pyplot as plt arr = [3, 6, 2, 4, 2, 3, 2, 10, 10, 4, 5, 6, 4, 10] plt.bar(range(len(arr)), arr) plt.sh...
"""LAB1 CPE202 """ # import unittest #1 def get_max(int_list): """find the maximum in a list of integers Args: int_list (list): a list of integers Returns: int: max integer """ max_int = 0 if len(int_list) == 0: return None for i in range(len(int_list)): if ...
print("Please think of a number between 0 and 100!") low = 0 high = 100 inp = '' while inp != 'c': num = int((low + high)/2) print("Is your secret number %i?"% num) inp = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly...
''' Find all of the numbers from 1-1000 that are divisible by 7 Find all of the numbers from 1-1000 that have a 3 in them Count the number of spaces in a string Remove all of the vowels in a string Find all of the words in a string that are less than 4 letters Challenge: Use a dictionary comprehension to count th...
strToSearch = "This is a test string" pattern = "is" #create a function called match that takes two arguments, one the pattern, the other the string, returns true or false if the pattern is found or not found. lenStr = len(strToSearch) lenPattern = len(pattern) for i in xrange(0,lenStr): if (!pattern[0] == strToSea...
def is_even(): numbers = [1,56,234,87,4,76,24,69,90,135] print("The odd numbers are:",[number for number in numbers if not number%2==0]) # call fxn is_even()
#1a my_list = ["Amy", 1, "Beth", "Charlie", 6, "Daisy", 7, 2 ] #1b my_list[2] = "Sandy" print (my_list) #1c my_list [1] = 1**2 my_list [4] = 6**2 my_list [6] = 7**2 my_list [7] = 2**2 print(my_list) #1d my_list.count() #???
my_first_name = "Henrietta" print(my_first_name) x = "Blue" y = "Blue" z = "Blue" print(f"{x=} {y=} {z=}") print (f"{x.upper()}")
#3a question_list = ["q", "u", "e", "s", "t", "i", "o", "n"] print (question_list) #3b list_of_list = [[5,3,4], [1,3,2,1], [3,2,3], [10,1,5], [6,7,2]] def list_addition ()
#Python Item 40 exercises #This version was as instructed - but it prints age twice :-/ and seems sloppy print("This program determines how long you have lived in days, minutes and seconds") print(" ") name = input("What is your name?: ") print("Please enter your age: ") age = int(input("age: ")) days = age * 365...
#Python 2.7.14 #Sandy Glantz via Dan Christie TA video Nice or Mean print "Python Item 35" print "---------------------------------" print "---------------------------------" ''' def start(): print ("What\'s up {}?".format(get_number())) def get_number(): name = raw_input("What is your name? ") return na...
import time import sys import numpy as np import random # This function generates a random problem instance def make_random_problem(n_variables, n_clauses): # This is a helper function to check if a row occurs in a matrix def find_row(mx, row): for i in range(mx.shape[0]): if np.all(mx[i, :...
hours = 1 while hours <=12: minutes = 00 while minutes <60: print(f'{hours}:{minutes}') minutes = minutes + 1 hours = hours + 1
import random vidaLeptude = 3 vidaJaque = 3 vezJaque = True print("Bem vindo as aventuras matemáticas de Leptude o Mago de patinete") print("Leptude por algum motivo entra em batalha com o sapo mago professor de matemática interdimensional Jaque, para vencer dele você precisa acertar suas perguntas de matemática ou e...
#Range vs xrange ==================== #range() vs xrange() in Python #range() and xrange() are two functions that could be used to #iterate a certain number of times in for loops in Python. #In Python 3, there is no xrange , but the range function behaves #like xrange in Python 2.If you want to write code that wil...
import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3 from tkinter import * from PIL import Image, ImageTk class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send...
def addition(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None return num1 + num2 def subtraction(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None return num1 - num2 def multiplication(a,...
""" ====== Discount Sceme ====== Upto 1000 Rs. - No Discount 1000 to 1999 - 10% Discount 2000 to 4999 - 20% Discount 5000 and Above - 30% Discount """ """WAP to calculate total discount on final billing based on Above slabs""" Slab_20_Fix_Discount = 600 Sl...
a=int(input("enter the number")) rev=0 while a>0: rev=(rev*10)+(a%10) a=a//10 print(rev) # a=int(input("enter the number")) # rev=0 # while a>0: # rev=(rev*10)+(a%10) # a=a//10 # print(rev)
w=input() i=0 for a in range (len(w)): if(w[a].isdigit() or w[a].isalpha() or w[a]==' '): continue else: i+=1 print(i)
re = input() b = ["a","e","i","o","u","A","E","I","O","U"] c=len(re) for i in range(0,c): if(re[i] in b): print("yes") break else: print("no")