text
stringlengths
37
1.41M
n = int(input("Enter Number : ")) counter = 0 for i in range(1,(n+1)) : if (i % 7 == 0) : counter = counter + 1 print(counter)
Solution = '42' guess = input ('Enter Your Guess: ') guess = int(guess) print(guess) if guess == Solution: print('You are a winer!') print ('Here is another statement') else: print('You are a non-winner') print('so sorry') print('The game is over')
# coding: utf-8 # In[ ]: import numpy as np def total_profit(input_price,beg ,stock_data,quarterly_price_data,stocks): """ finds the total profit and number of quarters and returns a list Parameters ---------- input_price : amount to buy the stocks beg : variable to loop through ...
#! /usr/bin/python # -*- coding: utf8 -*- a= input ("Digite un entero ") b=0 while a> (b+1): b=b+1 print b
#! /usr/bin/python # -*- coding: utf8 -*- def factorial(x): a=1 b=2 while a<=x: a=a*b b=b+1 return a print factorial(5)
import turtle as t import random as r color=[] def LerpColor(c1,c2,t): return (int(c1[0]+(c2[0]-c1[0])*t),int(c1[1]+(c2[1]-c1[1])*t),int(c1[2]+(c2[2]-c1[2])*t)) #color generator입니다. def genTree(length,level): if level != 0: t.pensize(level) #level 값에 따라 Pensize가 바뀝니다. t....
# Filter Function is one of the functional programing primitives in python programs. # Lets use the scientists dataset and let's play with filtering! """ filter() is one of the functional programming primitives (or building blocks) available in Python and that it’s useful in a number of contexts. filter() takes anothe...
# coding: utf-8 # In[ ]: import random def game(): sjb = ['shitou','jiandao','bu'] count_equal = 0 count_computer = 0 count_human = 0 def ask_input(message): while True: value= input(message) try: value = str(value) if value in sjb:...
def dirname(my_path, full_path=False): """Return the name of the last directory in the path: /x/y/ ==> y ; /x/y ==> x \\ if full_path: /x/y/z ==> /x/y/ ; /x/y/ ==> /x/y/""" list_dir = [] directory = "" for character in my_path: if character == "/": list_dir.append(directory) ...
# A majority of this code is taken from example code posted by Dr. Omari # The test code was created by Carter Burzlaff # The timing and list generation was added by Carter Burzlaff import time import random class Heap: def __init__(self): self._heap = [] def _swap(self, i, j): se...
def findMinimum(array): if len(array) == 0: return None if len(array) == 1: return array[0] return min(array[0], findMinimum(array[1:])) def findMaximum(array): if len(array) == 0: return None if len(array) == 1: return array[0] return max(array[0], f...
def isEqual(num1,num2): if num1<num2: print '%d is too small!' %num1 return False; elif num1>num2: print '%d is too large!' %num1 return False; elif num1==num2: print '%d is the correct answer!' %num1 return True; from random import randint num = randint(1,10...
sum =0 i=1 while(i<=100): sum+=i i=i+1 print '1+2+3+...+100=' print sum
str1 = 'boring' str2 = 'day' num = 18 #print 'My age is'+num ֱֲַ+ print 'My age is '+str(18) #str()תΪַ print 'My age is '+str(num) print 'My age is %d' %num #%תַ print 'Price is %f' %4.99 #%dֻС%f print 'Prince is %.2f' %4.99 #λС day = 'Today' print '%s is a boring day.' %day #%sһַ print '%s is a boring da...
def sort_words(y): x=y.lower() word_list=x.split("-") word_list.sort() str="" for i in range(len(word_list)): if i==0: str += word_list[i] else: str+=("-"+word_list[i]) return str txt=input("Please enter the text with hypent(-):\n") print(sor...
# you can write to stdout for debugging purposes, e.g. # print "this is a debug message" def solution(N): """ lessons test by codility https://codility.com/programmers/lessons/1-iterations/binary_gap/ :param N:integer :return: binary gap """ # change integer to string bin_str = bin(N).r...
def solution(K, A): """ https://codility.com/programmers/lessons/16-greedy_algorithms/tie_ropes """ n = len(A) sum_ropes = 0 max_num = 0 for i in xrange(n): sum_ropes += A[i] if sum_ropes >= K: max_num += 1 sum_ropes = 0 return max_num if __na...
#coding=utf-8 ##下面这种是新式类 class Man(object): def __init__(self): self.legs = 25 def get_legs(self): return self.legs class Yinshuai(Man): def __init__(self): super(Yinshuai,self).__init__() self.eyes = 2 def get_eyes(self): return self.eyes print Yinshuai().get_eyes() print Yinshuai().get_legs() ...
#coding=utf-8 import operator new_list = sorted([5,2,3,1,4]) print new_list #[1, 2, 3, 4, 5] 当然也可以使用list.sort() 但是会改变原始list ## user_info = [{'username':'yinshuai','age':25,'sex':'man'},{'username':'yinkai','age':18,'sex':'man'},{'username':'yinna','age':19,'sex':'woman'}] ##key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技...
from tkinter import* # configuracion ventana principal ventana = Tk() ventana.geometry("240x240") ventana.title("CALCULADORA") ventana.configure(bg="light blue") #widget de entrada de datos y salida numero_a = IntVar() numero_1 = Entry(ventana, textvariable = numero_a,width=18) numero_b = IntVar() numero_2 = Entry(v...
def letters_range(start, end, step=1): letrange = list() for one in range(ord(start), ord(end), step): letrange.append(chr(one)) return letrange
def MultipleSummer(maxVal): retSum = 0 i = 1 while i < maxVal: if i % 5 == 0: retSum += i elif i % 3 == 0: retSum += i i += 1 return retSum
# x = [1, 2, 3] # def test(some_list): # some_list.append(100) # test(x) # print(x) # def test(some_list): # some_list = [3] # return some_list # a = test(x) # print(a) # x = [1, 2, 3, 4] # # for number in x.copy(): # print(number) # x.remove(number) # print(x) # a = [1, 2, 3, 4] # b = a.copy()...
from Tkinter import * def getValue(): num1 = int(e1.get()) num2 = int(e2.get()) print num1 + num2 root = Tk() v1 = StringVar() v2 = StringVar() e1 = Entry(root, textvariable = v1) e2 = Entry(root, textvariable = v2) b = Button(root, command = getValue, text="Test") e1.pack() e2.pack() b.pack() v1.set("T...
nome = str(input('Qual o nome do(a) funcionário(a)? ')) si = float(input('Qual o salário inicial do(a) funcionário(a) {}? R$'.format(nome))) p = si + (si * 15 / 100) print('O salário inicial do(a) funcionario(a) {} era de {:.2f} e com o aumento de 15% foi para R${:.2f}!'.format(nome, si, p))
l = float(input('Qual a largura total da parede a ser pintada? :')) h = float(input('Qual a altura total da parede a ser pintada? :')) area = l * h tinta = area/2 print('A área total do cômodo é de {:.2f}m² e será necessário {:.1f} litros de tinta para pintar tudo!!!'.format(area, tinta))
""" author: fangren """ class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.dict = [] def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ ...
""" author: fangren """ class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): left = nums[:i] right = nums[i+1:] #print nums[i], rest ...
""" author: fangren """ from collections import defaultdict class Solution(object): def repaceWord(self, dict, word): found = False i = 1 while not found and i <= len(word): short_word = word[:i] if short_word in dict[i]: found = True ...
""" author: Fang Ren (SSRL) 9/5/2017 """ """ WAP to modify the array such that arr[I] = arr[arr[I]]. Do this in place i.e. without using additional memory. example : if a = {2,3,1,0} o/p = a = {1,0,3,2} Note : The array contains 0 to n-1 integers. """ import numpy as np a = np.array([2,3,1,0]) #print a[a] print...
""" author: fangren """ class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ zero_count = 0 for num in nums: if num == 0: zero_count += 1 if zero_count > 1: return [0...
from math import sqrt from time import sleep from random import uniform import pygame CAPTION = "~~~" SCREEN_W = 800 SCREEN_H = 600 ACCURACY = 5 MIN_SPEED = 1 MAX_SPEED = 2 class Point: def __init__(self, x, y): self.x = x self.y = y self.dx = uniform(MIN_SPEED, MAX_SPEED) self....
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline(), end='') # Open the variable file and assign it to a variable current_file = open(input_file) print("First let's print the whole...
# Assign value to the variable with data type integer cars = 100 # Assign value to the variable with data type float space_in_a_car = 4.0 # This makes the number a float type. Not necessary # Assign value to the variable with data type integer drivers = 30 # Assign value to the variable with data type integer passenger...
# valores de triangulo maiores que zero # comprimento de um lado tem que ser menor que a soma dos dois lados base = float(input(f'Digite o valor da base: ')) if base <= 0: print(f'valor de {base} inválido! digite novamente ') base = float(input(f'Digite o valor da base: ')) hipotenusa = float(input(f'Digite ...
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums[0:] = sorted( nums[0:], reverse = False) global Result Result = [] self.copyResult(nums) while self.nextPermutation(nums)==True: self.copyResult(nums) return Result ...
class Solution(object): def reverseString(self, s): stringLength = s.__len__() stringList = list(s) for charIndex in range(stringLength/2): tmp = stringList[charIndex] stringList[charIndex] = stringList[stringLength - charIndex - 1] st...
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None CurrentDepth = 0 NodeDepth = -1 Node = None class Solution: # @param root, a tree link node # @return nothing ...
class Solution(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if (num<0): return False oddBit = False bitCount = 0 while (num!=0): print num," ", num&1 ...
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates = sorted(candidates) Stack = [] global Result_Combination Result_Combination = [] for i in range(target / candidates[0] + 1): ...
import os import math def PushHashTable(x): global HashTable HashTable[ord(x)] = 1 return 0 def PopHashTable(x): global HashTable HashTable[ord(x)] = 0 return 0 def CheckHashTable(x): # if exists, return True # if not exists, return False global HashTable if HashTable[ord(x)] == 1: re...
# -*- coding:utf-8 -*- # 计算回测指标 重写 用已经计算好的年化收益率来计算 import pandas as pd import numpy as np from scipy import stats class GetIndex(object): # data: 策略每天的年化收益率 # 有两列数据, # 一列为市场,市场的基准收益, # 一列为策略,为我们的策略收益 def __init__(self, data): self.data = data #每天的年化收益率 self.MD = 0.0 #最大回撤 ...
#! python3 # itemRotator.py - Rotates items into and out of a temporary holding queue following a specified amount of time required in the queue # # Usage: Run program twice per day to determine what items can be removed from the waiting queue and what should be added. # The user must enter the itemIDs of those ...
import pygame from node import Node from node_type import NodeType from constants import NODE_SIZE, BORDER, PADDING HORIZONTAL = 0 VERTICAL = 1 class Graph: """Represents a Graph as a grid (2d list).""" def __init__(self, rows, collumns, start=(0, 0), end=None): """Construct a new Graph.""" ...
import random a = [1,3,5,6,8,9] for i in range(10): chose1 = random.choice(a) print(chose1)
import math class Vector(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __float__(self): return math.hypot(self.x, self.y) # 平方根函数 def __mul__(self, beish...
print(list(range(10))) print([x*x for x in range(1,11)]) print([m+n for m in 'ABC' for n in 'XYZ']) for m in 'abc': for j in 'def': for k in 'hij': print(m+j+k) print([x * x for x in range(1, 11) if x % 2 == 0]) print([x * x for x in range(1, 11)[1::2]]) import os print([d for d in os.listd...
print(dict(a='ad',b=2)) print(dict([('1',2),('a',3)])) print(dict(zip(['a','b'],[1,2]))) print(["data{}".format(i) for i in range(100) if i % 2 == 0]) print([f"data{i}" for i in range(100) if i % 2 == 0]) print([f"data{i}" if i % 2 == 0 else f"lemon{i}" for i in range(100)]) a = ([f"data{i}" if i % 2 == 0 else f"le...
# _*_coding:utf-8_*_ choose = input('输入s或者p:') if choose == 's': class Student(object): # 将方法变成属性 @property def score(self): return self._score @score.setter def score(self,value): if (not isinstance(value,int)) or value<0 or value>100: ...
import tkinter as tk window = tk.Tk() window.title("my win") window.geometry('400x400') l = tk.Label(window, bg='yellow', width=20, text=None) l.pack() var1 = tk.StringVar() def print_selection(e): l.config(text='you have selected ' + var1.get()) # HORIZONTAL 横向,tickinterval 标签单位长度 resolution 保留两位小数 s = tk.S...
# Linear Regression with Gradient Descent # Import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt # Set parameters for figure plt.rcParams['figure.figsize'] = (12.0, 9.0) # Preprocessing input data # Read the file with pandas data = pd.read_csv('linear_regression_data.csv', header=N...
print("1. Arithmetic") print("2. Comparision") c=int(input("Enter your choice (1,2 or 3) ")) if(c==1): print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") o=int(input("Enter the operation(1,2,3 or 4) ")) a=int(input("Enter first number")) b=int(input("Enter second numbe...
''' Find longest palindromic substring Manacher's Algorithm ''' def longest_palondromic_substring(s): mid = len(s) // 2 # initialize s[i][i] = False T = [[False for i in range(0, len(s))] for i in range(0, len(s))] for i in range(0, len(T)): T[i][i] = False mx = 1 for l in range(2,...
''' Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. O(n) solution exits with O(1) space. ''' # S = lst[i] + ls...
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ intervals.sort(key= lambda x:x[0]) merged=[] for interval in intervals: if not me...
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ isPalindrome = lambda x: x == x[::-1] left, right = 0, len(s) -1 while left <= right: if s[left] == s[right]: ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ row = [set(range(1,10)) for _ in range(9)] col = [set(range...
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 left,right = 0, len(nums)-1 while left < right: ...
class LinkedList: def __init__(self, head): node = Node(head, None) self.head = node self.tail = None self.length = 1 def insert_at_beginning(self, value): node = Node(value, self.head) self.head = node self.tail = node self.length += 1 def i...
import numpy as np import random from scipy import linalg as la import pdb def random_chain(n): """Create and return a transition matrix for a random Markov chain with 'n' states. This should be stored as an nxn NumPy array. plan: create a random matrix, use scipy to normalize the columns, then return it ...
import numpy as np a = input("Enter string : ") nth = int(input("Enter nth: ")) if len(a)<nth: print("Not Possible") else: f=np.array([a[:nth]]) l=np.array([a[nth+1:]]) print(np.concatenate((f,l),axis=0))
# Day05 # The first line contains an integer, N (the size of our array).\ # The second line contains N space-separated integers that describe array A's elements # Print the elements of array A in reverse order as a single line of space-separated numbers # The code starts here: N = int(input()) A = list(map(int,input()...
answer = 'yes' print "guess a number between 1 and 1000" while answer == 'yes': numoftry = 10 numtoguess = 500 limitlow = 1 limithigh = 1000 while numoftry != 0: try: print numtoguess print "type 1 if guess is too high" print "type 2 if guess is too low" print "type 3 if guess is right" humananswe...
#High low guessing game. def show_instructions(): print '''pick a number between 1 and 1000 and I will try to guess it. I can do this in no more then 10 guesses. After each guess, enter: 0 - if I got it right -1 - if I guessed too high 1 - if I guessed too low.''' def take_guess(): low = 1 high = 1000
# Given two sorted list. We need to merge these two list such that the initial numbers (after complete sorting) # are in the first list and the remaining numbers are in the second list. Extra space allowed in O(1). # # Example: # # Input: ar1 = [10] # ar2 = [2, 3] # Output: ar1 = [2] # ar2 = [3, 10] # # ...
import random as rn def noReplacementSimulation(numTrials): ''' Runs numTrials trials of a Monte Carlo simulation of drawing 3 balls out of a bucket containing 3 red and 3 green balls. Balls are not replaced once drawn. Returns the a decimal - the fraction of times 3 balls of the same color we...
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 00:46:34 2018 @author: Shilpi """ N = int(input()) myList = [] for i in range(0,N): i = input() myList.append(i) for j in myList: j_eve = "" j_odd = "" for k in range(0, len(j)): if k%2 == 0: j_eve+=j[k] else: ...
def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ ### TODO noWords=0 bestShift=0 Shift=0 while Shift<26: decodedMessage = applyShift(text,Shift) words = decodedMessa...
class BankAccount: all_accounts = [] def __init__(self, int_rate, balance = 0): self.int_rate = int_rate self.balance = balance def make_deposit(self, amount): self.balance += amount return self def make_withdrawal(self, amount): if self.balance < 0: ...
a=1 for i in range(0, 5): a=1 for j in range(0,i+1): print(a, end = ' ') a = a + 1 print('\r')
# Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. # You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. # Example 1: # Inpu...
# Given a binary array, find the maximum number of consecutive 1s in this array. # # Example 1: # Input: [1,1,0,1,1,1] # Output: 3 # Explanation: The first two digits or the last three digits are consecutive 1s. # The maximum number of consecutive 1s is 3. ###########################################################...
# You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. # Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shor...
from numpy import diff def pairedMovement(a, b): """If both klines go up, go up.""" output = [1] for i in range(0, len(a)): if i == 0: continue elif a[i - 1] < a[i] and b[i - 1] < b[i]: # Go up output.append(output[i - 1] + 1) elif a[i - 1] > a[i...
nome=input('Qual é o seu nome?') idade=input('Qual é a sua idade?') hobbie=input('Qual é o seu Hobbie?') print('Meu nome é: ' + nome,'e minha idade é: ' + idade,'e gosto de: ' + hobbie)
import re patterns = ['term1', 'term2'] text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print('Searching for "%s" in: \n"%s"'%(pattern,text)) if re.search(pattern, text): print('\n') print('Match was found. \n') else: print('\n') print('No Mat...
#Tuplas t = (1,2,3) print(len(t)) #Variação tipos de dados t = ('one', 2) print(t) #indexação print(t[0]) #corte de dados print(t[-1]) #Métodos basicos da Tupla #use .index() com o valor de parâmetro para retornar o indice do mesmo print(t.index('one')) #use .count() com o valor de parâmetro para retornar ...
a = [8, 1, 2, 3, 0, 0, 0, 0] for i in range(7, 0): print(a[i]) print(range(0,7)) print(range(7, -1, -1))
dia = input('Dia?') mês = input('Mês?') ano = input('Ano?') print('Você nasceu no dia',dia,'de',mês,'de',ano,',Correto?')
from syntax import * import sys def main(): if len(sys.argv) < 2: print("Too few arguments in function main. A Starlet script should be passed as an argument.") exit(0) elif len(sys.argv) > 2: print("Too many arguments in function main. A Starlet script should be passed as an argument.") exit(...
# -*- coding: utf-8 -*- """ Created on Thu Nov 22 21:27:09 2018 @author: V510 """ import numpy as np import tensorflow as tf import random as rn import os os.environ['PYTHONHASHSEED'] = '0' np.random.seed(36) rn.seed(777) tf.set_random_seed(89) from keras import backend as K sess = tf.Session(graph = tf.ge...
# -*- coding: utf-8 -*- ponoviVajo = 'da' print "Pozdravljeni. Sem pretvornik enot, kilometrov v milje. " \ "\nVpiši željene kilometre in pretvoril jih bom v kilometre." while ponoviVajo == "da": try: kilometri = float(raw_input("\nVpiši kilometre: ")) milje = round(kilometri * 0.621371192, ...
#Q.1- Write a Python program to read n lines of a file from itertools import islice n = int(input("Enter how much lines of file you want to read? ")) try: f = open('Ques1.txt','r') lines = f.readlines(n) for i in islice(f,n): print(i) f.close() except FileNotFoundError: print("File...
# coding=utf-8 # Py从小喜欢奇特的东西,而且天生对数字特别敏感,一次偶然的机会,他发现了一个有趣的四位数2992, # 这个数,它的十进制数表示,其四位数字之和为2+9+9+2=22,它的十六进制数BB0,其四位数字之和也为22, # 同时它的十二进制数表示1894,其四位数字之和也为22,啊哈,真是巧啊。 # Py非常喜欢这种四位数,由于他的发现,所以这里我们命名其为Py数。 # 现在给你一个十进制4位数n,你来判断n是不是Py数,若是,则输出Yes,否则输出No。 # 如n=2992,则输出Yes; n = 9999,则输出No。 n = 2992 def SumBase(a,b): res = 0...
# coding=utf-8 # 给你一个整数a,数出a在二进制表示下1的个数,并输出。 a = 34 res = 0 while a: if a%2: res += 1 a //= 2 print res
''' The votes.csv consists of the data as is. votes for each law and each member. 7057 laws X 143 members. values represents: 1 - for the law, 2 - opposed to the law, 0 - didn't attend. Here, we would like to convert this data to an input for a cooperative game. That is, sets of players (members) and theirs values. ...
nums = [] for a in range(2, 101): for b in range(2, 101): if a**b not in nums: nums.append(a**b) nums.sort() print(len(nums))
#Artificial Intelligence: A Modern Approach # Search AIMA #AIMA Python file: mdp.py """Markov Decision Processes (Chapter 17) First we define an MDP, and the special case of a GridMDP, in which states are laid out in a 2-dimensional grid. We also represent a policy as a dictionary of {state:action} pairs, and a Uti...
def suma(a,b): #archivo de FUNCIONES print ("la suma de ",a," y ",b," es-> ",a+b) def resta(a,b): print ("la resta de ",a," y ",b," es-> ",a-b) def multiplicacion(a,b): print ("la multiplicacion de ",a," y ",b," es-> ",a*b) def division(a,b): print ("la division de ",a," y ",b," es-> ",a/b) def ...
def main(): #variables numero = 15 decimal = 12.56 caracter = 'a' cadenas = "hola mundo" booleano = True #entrada y salida de informacion print ("hola mundo", numero ,"-", decimal) dato = input() #como el cin print (dato) #operaciones basicas print ("introduce el valor ...
import os import random import cherrypy import math import time # added """ This is a simple Battlesnake server written in Python. For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md """ # Rules: 0=available space, 1=snake body, 2=Food, 3=head, 4= Bigger enemy's head # 5 = sm...
usernameinput = input("username : ") passwordinput = input("password : ") if usernameinput == "admin" and passwordinput == "1234": item = "" print("------------MAX SHOP------------") print("-------เลือกรายการสินค้าที่ต้องการ------") print("1.น้ำดื่ม ขวดละ 10 บาท") print("2.แล็คตาซอย กล่องละ 15 บาท"...
def vatcalculate(totalprice): result = totalprice + (totalprice * 0.07) return result print(vatcalculate(int(input("ใส่ราคาสินค้าที่ต้องการ : "))))
from typing import List from enum import Enum import operator class State(Enum): FLOOR = 1 EMPTY = 2 OCCUPIED = 3 def __repr__(self): if self.value == self.FLOOR.value: return '.' elif self.value == self.OCCUPIED.value: return '#' else: retur...
# -*- coding: utf-8 -*- class Calculator: def add(self, a, b): if (type(a)!= int and type(a)!=float) or (type(b) != int and type(b)!=float): return "请输入数字" return a + b def sub(self,a,b): if (type(a)!=int and type (a)!=float) or (type(b)!=int and type(b)!=float): ...
# -*- coding: utf-8 -*- class person: name : str = None age : int = 0 gen : str = "男" __money : float = 20000 def __init__(self,name,age,gen,money): print('这是一个构造函数') self.name = name self.age = age self.gen=gen self.__money=money def get_money(self): ...
''' Create the below pattern using nested for loop in Python. * * * * * * * * * * * * * * * * * * * * * * * * * ''' for i in range(1,6): for j in range(i): print("*",end=" ") print() for m in range(5,1,-1): for n in range(m-1,0,-1): ...
#number guessing game from random import randrange def hidden_number(): random_generated_numer = randrange(1,1000) str_random_number = str(random_generated_numer) r_g_n_len = len(str_random_number) hint_count = 0 print("\nWELCOME TO NUMBR GUESSING GAME....\n") start_game ...
def bubblesort(nlist): i=0 n=len(nlist) while i<n-1: j=0 sw=0 while j<n-i-1: if nlist[j]<nlist[j+1]: x=nlist[j] nlist[j]=nlist[j+1] nlist[j+1]=x sw=1 j=j+1 if sw==0: break ...
a=int(input("Enter the value of a:")) b=int(input("Enter the value of b:")) c=int(input("Enter the value of c:")) i=b**2-(4*a*c) d=i**0.5 f1=(-b+d)/2*a f2=(-b-d)/2*a print("The value of x1=",f1) print("The value of x2=",f2)