text
stringlengths
37
1.41M
def function1(): """simple function""" return 5 def function2(x): """square a number""" return x*x-3 def function5(x,y,z): """multiply and subtract""" return x*y*z-3 def main(): "print linear combination" print function1() - function2(5) + function5(1,2,3)
from colorama import * init() class Bank: """Bank class with method and attributes to use with different bank instances""" def __init__(self, bankname, ifcs_code, branch, location): self.bankname = bankname self.ifcs_code = ifcs_code self.branch = branch self.location = location...
#!/usr/bin/env python3 import random EMPTY = 0 FIRST_PLACE = 0 HALF = 2 ONE_RIGHT = 1 ONE_LEFT = 1 MOVE_ONE = 1 LAST_CELL = 1 class WordTracker(object): """ This class is used to track occurrences of words. The class uses a fixed list of words as its dictionary (note - 'dictionary' in...
#Data type notes splitter_length = 100 splitter_character = '*' section_splitter = '\n' + splitter_character * splitter_length + '\n' a=11.9 print('When casting with the int function:') print('int() will round down...') print('a = ' + str(a) + ' and then int(a) = ' + str(int(a)) + ',if you don\'t believe me? Check ...
import pygame import math X = 0 Y = 1 Z = 2 COLOR = 3 PLANE_X = X PLANE_Y = Y PLANE_Z = Z class PointCloud: """ A class responsible for loading, calculating and transforming point clouds """ def __init__(self, filename): """ Constructor loads point cloud from text file formatt...
# # @lc app=leetcode.cn id=104 lang=python3 # # [104] 二叉树的最大深度 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # def maxDepth(self, root: TreeNode) -> int: # ...
# # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): n = int(input()) if n <= 3 : print(n - 1) else: if n % 2 == 0: #one move make it to two and one susbtraction to make it 1 print(2) else: ...
# # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): d, k = map(int, input().split()) #we find game breaking point #observe that the player 2 can choose his point on y = x line #the last point of y = x line is the breaking point => player...
from sys import stdin, stdout # only need for big input def read_int_from_line(): return list(map(int, input().split())) def solve(): n = int(input()) a = read_int_from_line() #range_sum[i] = a[0] + ... + a[i] : the position robot ends up after i move range_sum = [0] * n #overshoot[i] the righ...
from sys import stdin, stdout # only need for big input def read_int_from_line(): return list(map(int, input().split())) def solve(): #since n is big, we read input n as string n = input() num_digit = len(n) #state in binary representation represents how we delete/keep digits #i-th digit of st...
#import programs import os import csv #set csvpath to open the csvfile csvpath = os.path.join("election_data.csv") #set the counts for all the candiates to 0, and as it scans through the row and sees the deligate it will count #alternatively I think a diction could be created as it scans through or the dict read coul...
import math # Basic logical statements x = int(input('Enter a number: ')) y = int(input('Enter another number: ')) areEqual = (x == y) if areEqual: print('The numbers are equal') else: print('The numbers are not equal') if x > y: print('The first is bigger') elif x < y: print('The second is bigger') else: prin...
class Node(object): def __init__(self, data=None): self.data = data self.next = None class Stack(object): def __init__(self): self.head = Node() def add(self,data): new_node = Node(data) ptr = self.head while ptr.next is not None: ptr = p...
import numpy as np # imports from pandas import read_csv import plotly.express as px # read data from disk faithful = read_csv('./data/faithful.csv') def hist(bins = 30): # calculate the bins x = faithful['waiting'] counts, bins = np.histogram(x, bins=np.linspace(np.min(x), np.max(x), bins+1)) bins = 0.5* (bi...
n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) media = (n1 + n2)/2 if media < 5.0: print('Sua média é {:.1f}, você foi REPROVADO!'.format(media)) elif media >= 5.0 and media < 6.9: print('Sua média é {:.1f} e você está em RECUPERAÇÃO!'.format(media)) elif media >= 7: print('Sua média é {:.1f} e...
import random aluno_1 = input('Digite o nome do primeiro aluno: ') aluno_2 = input('Digite o nome do segundo aluno: ') aluno_3 = input('Digite o nome do terceiro aluno: ') aluno_4 = input('Digite o nome do quarto aluno: ') lista = [aluno_1, aluno_2, aluno_3, aluno_4] escolhido = random.choice(lista) print('O escolhido ...
pt = int(input('Primeiro termo: ')) r = int(input('Razão: ')) t = pt cont = 1 total = 0 mais = 10 while mais != 0: total = total + mais while cont <= total: print('{} -> '.format(t), end='') t += r cont += 1 print('PAUSA') mais = int(input('Quantos termos vc quer mostrar a mais? ...
from random import randint computador = randint(0, 5) jogador = int(input("Vou pensar emum numero de 0 a 5, tente adivinhar: ")) if jogador == computador: print('Parabéns, você adivinhou! Eu pensei no número {}'.format(computador)) else: print('Não foi dessa vez! eu pensei no número {}!'.format(computador))
c = 1 for i in range(1, 11): for c in range(1, 11, 1): print('{} x {} = {}'.format(i, c, i*c)) #OU num = int(input('Digite um número para ver sua tabuada: ')) for c in range(1, 11): print('{} x {:2} = {}'.format(num, c, num*c))
dias = int(input('Você alugou o carro por quantos dias? ')) km = float(input('Quantos km foram rodados? ')) preco = (60*dias)+(0.15*km) print('O preço do aluguel será R${:.2f}'.format(preco))
#num = float(input('Digite um numero: ')) #num_int = int(num) #print('o numero {} tem a parte inteira {}'.format(num, num_int)) from math import trunc num = float(input('Digite um numero: ')) print('o numero {} tem a parte inteira {}'.format(num, trunc(num)))
import random Number = random.randint(1,9) chances = 0 while chances<5: Guess = int(input("enter your guess :- ")) if Guess==Number: print("You Won :) !") break elif Guess<Number: print("Guess higher than" + str(Guess)) elif Guess>Number: print("G...
import sklearn.linear_model def build_linear_model(current_obervations_values, current_decision_values): # it is a linear model current_regression = sklearn.linear_model.LinearRegression() # fit in the observation current_regression.fit( X = current_obervations_values, y = current_decis...
#*****CLASSES*************************************************************************# #*****USER****************************************************************************# class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {} def ge...
arr = [int(x) for x in input().split()] req = int(input()) n = len(arr) def LinearSearch(): for i in range(n): if(req == arr[i]): return i+1 return 0 b = LinearSearch() if(b!=0): print(b) else: print("The element is not found")
class Parser: """ Parser the file """ def __init__(self, inputF): """ init Parser :param inputF: file of input """ self.lines = inputF.readlines() self.lines = [' '.join(l.split()) if l.find("//") == -1 else ' '.join(l[:l.find("//")].split()) f...
class Student(object): role = "Stu" def __init__(self,name): self.name = name @staticmethod def fly(self): print(self.name,"is flying...") @staticmethod def walk(self): print("student walking...") s = Student("Jack") s.fly(s) # s.fly(s) s.walk()
class RelationShip: """保存couple之间的对象关系""" def __init__(self): self.couple = [] def make_couple(self,obj1,obj2): self.couple = [obj1,obj2] # 两个人就成了对象 print("[%s] 和 [%s] 确定了男女关系..." % (obj1.name,obj2.name)) def get_my_parter(self,obj): # p1 p2 #print("找[%s]的对象" % obj.n...
# Berikut contoh program Turunan (Inheritance) 1 : class Ayah: def methodAyah(self): print('Ini adalah Method Ayah') class Anak(Ayah): def methodAnak(self): print('Ini adalah Method Anak') # Deklarasi objek kelas Ayah p = Ayah() p.methodAyah() # Deklarasi objek kelas Aanak c = Anak() c.met...
# Program selisih jam # judul # mencari durasi dari 2 waktu # kamus # jamawaljam = int # jamakhirjam = int # jamawalmenit = int # jamakhirmenit = int # jamawaldetik = int # jamakhirdetik = int # deskripsi print(">>>>>>>>>>>>>>>>>>SELAMAT DATANG<<<<<<<<<<<<<<<<<<<<") print("Masukan dalam format 24jam") print("--------...
# Pencarian dengan Binary Search (Pencarian Biner) def binary_search(angka, listku): listku.sort() # Penyortiran List langkah = 0 ketemu = False awal = 0 akhir = len(listku)-1 while awal <= akhir and not ketemu: tengah = (awal+akhir)//2 if listku[tengah] == angka: k...
from numpy import * # 抽样工具 class Sampling: # 无放回随机抽样 def randomSampling(dataMat, number): dataMat = array(dataMat) try: #slice = random.sample(dataMat, number) sample = [] for i in range(number): index = random.randint(0, len(dataMat)) #包含low...
# # a,b = 25,"Neal" # # Déclarer une variable et lui attribuer un nombre. Afficher le résultat de la multiplication de cette variable par 4 # # Déclarer une variable et lui attribuer un nombre. trouver ensuite 2 syntaxes différentes pour ajouter "1" à ce nombre. Afficher ce nombre à chaque fois que vous ajoutez "1". ...
# -*- coding: utf-8 -*- # @Time : 2021/5/21 13:42 # @Author : lvzhimeng # @FileName: 华为面试题.py # @Software: PyCharm import itertools def test_list(n): if n < 1: return 1 else: vue = test_list(n - 1) char_list = list(str(vue)) count_list = [list(v) for k, v in itertools.groupb...
#!/usr/bin/env python ################################################################################ #Imports import random import sys #Body def determine_digits(): '''Retrieves the number of digits from an arg given in the command line. If an arg is not given, the number of digits defaults to 3. Function retu...
''' * @Author: csy * @Date: 2019-04-28 14:01:32 * @Last Modified by: csy * @Last Modified time: 2019-04-28 14:01:32 ''' requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if '...
def somaRecursivo(number): if len(number) == 1: return int(number) soma = str(sum([int(char) for char in number])) return somaRecursivo(soma) def proxMultiplo10(number): if number%10 == 0: return number number+=1 return proxMultiplo10(number) # Espera receber os campo1, 2 e...
# Jonas Claes - 02/06/2019 12:19 # Store exam results. examResults = [] # Get all the results. for i in range(0, 5): examResults.append(int(input("Exam %i result? " % (i + 1)))) # Sort exam results from low to high. examResults.sort() # Check if first two elements are below 50. if (examResults[0] < 50 and e...
#!/usr/bin/env python3 """Script for Tkinter GUI chat client.""" #followed tkinter module from socket import AF_INET, socket, SOCK_STREAM #initiate socket from threading import Thread #Threading import tkinter def receive(): """Looks at received messages.""" while True: ...
"""Gradient descent implementation.""" import numpy from sklearn.utils import shuffle def l2_regularization_gradient(l2, w): g = w.copy() g[0] = 0. # don't penalize intercept return 2 * g * l2 def adjust(x): """Prepends row filled with 1s to the vector, so that constant of a polynomial is eval...
import numpy as np from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier class Perceptron: def __init__(self, model=None): self.model = model def fit(self, X, y): """ this method learns the parameters of the mod...
def read_only_properties(*attrs): """ Decorator to make select attributes from a class read-only. Overrides _setattr_ to raise an AttributeError whenever any attributes listed in attrs is set. This results in attributes that are initially writable (during __init__ of the object), but immediately after...
import collections import six import time import re def is_iterable(arg): """ Returns whether an argument is an iterable but not a string From stackoverflow: "how to tell a varaiable is iterable but not a string" Args: arg: some variable to be tested Returns: (bool) """ ...
#!/usr/bin/env python # coding: utf-8 # In[1]: from IPython.display import clear_output def display_board(board): clear_output() print(board[7]+' |'+board[8]+' |'+board[9]) print('----') print(board[4]+' |'+board[5]+' |'+board[6]) print('----') print(board[1]+' |'+board[2]+' |'+board[3]) ...
# Jumping number is the number that All adjacent digits in it differ by 1. def jumping_number(number) : s, i = str(number), 1 for each in s : if i == len(s) : return 'Jumping!!' elif int(each) == int(s[i]) - 1 or int(each) == int(s[i]) + 1 : i = i + 1 re...
# Given an array/list [] of integers , Find The maximum difference # between the successive elements in its sorted form. def max_gap(numbers) : sorted_nums = sorted(numbers) lst, i, diff = [], 1, 0 for each in sorted_nums : if i == len(numbers) : break diff = sorted_nums[i] - each ...
def duty_free(price, discount, holiday_cost): # return int(holiday_cost / (price - (((100-discount)/100) * price))) # discount_percent = (100 - discount) / 100 # discount_price = price * discount_percent # savings = price - discount_price # how_many_bottles = int(holiday_cost / savings) # retur...
# Create a function named divisors/Divisors that takes an integer n > 1 # and returns an array with all of the integer's divisors(except for 1 and # the number itself), from smallest to largest. If the number is prime return # the string '(integer) is prime' (null in C#) (use Either String a in Haskell # and Result<Vec...
# In this Kata, you will be given an array of numbers in which two numbers # occur once and the rest occur only twice. Your task will be to return the # sum of the numbers that occur only once. # For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 # occur once, and their sum is 15. # first soluti...
def alternate_case(s) : st = '' for each in s : if each.isupper() : st += each.lower() elif each.islower() : st += each.upper() else : st += each return st # return s.swapcase() print(alternate_case('Hello World'))
states = { 'AZ': 'Arizona', 'CA': 'California', 'ID': 'Idaho', 'IN': 'Indiana', 'MA': 'Massachusetts', 'OK': 'Oklahoma', 'PA': 'Pennsylvania', 'VA': 'Virginia' } def by_state(str) : # long and convoluted but it works! new_str = '..... ' state_list = [] str_list = [] split = str.split('\n') for...
# Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight. # Your task is to make 'Past' function which returns time converted to milliseconds. def past(h, m, s) : return ((h * 36000) + (m * 60) + s) * 1000 print(past(0, 1, 1)) lst = ['one','two','three'] def count(x) : return len(x) y = map(cou...
# Name: Eric A Dockery # Section: 01 # Date: 1/27/2012 # Email: eric.dockery283@hotmail.com # Purpose: # Program to find the area of the face in the given picture. # Preconditions: # Given area is calculated. ## Design from math import * def main(): # 1. Measure the length of the given face...
# Prolog # Author: Eric Dockery # Section: 001 # Date: 1/18/2012 # Purpose: # Program to find the volume of a right cone given the length # of the radius of the base and the height # Preconditions: (input) # User supplies radius and height of the cone (as numbers, no error checking done) # Post...
# Names: Eric Dockery, Brent Dawson, George Grote # Lab 5 # Team:2 # Section:1 # Date 2/6/2012 #Preconditions: (input) #User will input three variables. #Postcondtions #Code will print the product of the numbers #Code will output the product in its individual digits #Code will output the produ...
# -*- coding:utf-8 -*- # 有如下面值的硬币 现在输入一个数值 求出与之匹配的硬币数 conins = [1, 5, 10, 50, 100, 500] def conins_list(A, input): for i in range(len(conins)-1, -1, -1): current_number = min(input[i], A/conins[i]) A -= current_number * conins[i] print "{0},{1}".format(conins[i], current_number) pa...
#!/usr/bin/env python3 """ #### # Taken from https://github.com/antoine-trux/regex-crossword-solver # All credit should go to original author # # - Changed 'xrange' to 'range' in this file to make it python3 compatible. # - Added python3 shebang # #### A program to solve regular expression crosswords like those fr...
class Node: def __init__(self, elem=-1, children=None): self.elem = elem self.children = children class Tree(object): def __init__(self, root=None): self.root = root def add(self, elem): node = Node(elem) if self.root is None: self.root = node ...
user_input = str(input("Enter the string:")) text = user_input.split() # creating list of words after splitting the user input # print(text) ac = "" # defining an empty string for x in text: ac = ac + str(x[0]).upper() print(ac) # printing the final acronymn
# Lists vs Tuples ''' Definition of Constant folding: the process of recognizing and evaluating constant expressions at compile time rather than computing them at runtime ''' from dis import dis (1, 2, 3) [1, 2, 3] dis(compile('(1, 2, 3, "a")', 'string', 'eval')) print('---------------------------------...
import unittest def running_sum(ls): '''Modify list so it contains the running sum of original elements''' for i in range(1, slen(ls)): ls[i] = ls[i-1] + ls[i] class TestRunningSum(unittest.TestCase): '''Tests for running_sum''' def test_running_sum_empty(self): '''Testing an empty list''' argument = [] ...
#functioms with outputs # use print or return same here def format_name(f_name, l_name): f_name_edited = f_name.title() l_name_edited = l_name.title() return f"{f_name_edited} {l_name_edited}" #however we need to save the function that trigger in a variable then print or just print the new function it ne...
#advanced python arguments not how to argument but how to specfify a large range of inputs u know keyword argument? it is better while you create the function u specfify paramter and argument together then u just clal function name easy though we can change it while declaring but yea it will always have defulte value ...
# some websites does not have api so we use webscarbing #or api does not let us do what we want to do #webscarbing = look in underline html code to get the information we want #so today we will learn how to make soup beautiful soup it is a library that help people like us make sense of websites like even webpage as ...
for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) #note if is paried with else that is why it print the else with the third else so please use elif
#we gonna create habit tracker using piexal api =japanese developer #shows intensity of how u did a day like high colored = read a lot of pages # we used get requests #there is 3 others than get request which are post put delete #the code looks pretty much the same #get = ask external system for particaluar p...
#turtle only work with .gif format import turtle from turtle import Turtle, Screen #coordinate = spelled like cowardinate = x,y postions = coor screen = Screen() screen.title("U.S States Game") image = "blank_states_img.gif" #epic storing path ways screen.addshape(image) # this add shape to turtle turtle.shape(image...
print("why " + input("how are you bro?")) #input wworks beforee print() # control / to change to comment and control z to undo use thonny program for step by step ing
#files dont just have names they also have pathes #on computers there is file and folders and files can live in folders #and you can navigate(go through) serveral folders to get to a particular file # the root is the main path of folder which is represented by / #then the main path which is usually c and the path c ...
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? \n")) #if and else should be at same indentional level to work and just #write comment here at top to preven future erros of thee spacing betwee lines in python or near to code == is equal and != is not equal # one = means assignign ...
def checkio(stones): ''' minimal possible weight difference between stone piles ''' print (stones) stones.sort() stones.reverse() print (stones) bag1, bag2 = 0, 0 for i in stones: # print('i:',i) if bag1 < bag2: bag1 += i else: bag2 += ...
# coding=utf-8 names=['Job','Favourite','Thinking'] print len(names) print names[-1] #打印倒数第一个 names.append('Append') print names[-1] names.pop() print names names.insert(0, 'First') print names[0] t = ('aaa', 'bbb', ['xx', 'yy']) t[2][0] = 'X' # t[0] = '111' # TypeError: 'tuple' object does not support item assignme...
#scape information from website import requests #use to get webpage libraries for now html from bs4 import BeautifulSoup #lib will be responsibe to pass html code oyo_url= "https://www.oyorooms.com/hotels-in-bangalore/" req= requests.get(oyo_url) #to get the accessed content content= req.content #need to pass co...
class View: def display(self, list_of_dictionaries): for dictionary in list_of_dictionaries: for key in dictionary: print("{0} = {1}".format(key, dictionary[key])) import plotly print(plotly.__version__) # version >1.9.4 required """ plotly.offline.plot({ "data"...
# NoteMaster # Prompts the user to create a journal entry - to track ideas and for later reference import datetime as dt from difflib import SequenceMatcher # Welcome text (colorized) # ANSI exit codes (\033) enable text color changing 1 for style (bold), 36 for color (cyan), 4 (black background), 0 to cancel, m to f...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Put your code into 'input' # I'll try not to use RegEx. It'll be hard! input = '''( ((pattern) ê (replacement)) (ê) )''' # ① Obliger GlobalScope # ② Obliger PatternScheme class LanghException(Exception): """ Langh's most basic Exception. """ ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 15:50:49 2020 @author: VIRUS """ """ stack = [] def Push(): element = input("Enter a number: ") stack.append(element) print("Element added: ",stack) def PopElement(): if not stack: print("stack underflow!") else: elem = stack.pop(...
def soma(x,y): print(x+y) soma (2,10) print() def soma(x,y, z=2): print(x+y+z) soma (2,10) print() # * siginifa uma lista ou tupla # ** significa um dicionário def funcaoDinamica(*args, **kwargs): print(args) print(kwargs) funcaoDinamica(1, 'a', texto = 'teste')
import math linha = input().split() A = float(linha[0]) B = float(linha[1]) C = float(linha[2]) areaTriangulo = (A*C)/2 areaCirculo = 3.14159*math.pow(C,2) areaTrapezio = (((A+B))*C)/2 areaQuadrado = math.pow(B,2) areaRetangulo = A*B print('TRIANGULO: {:.3f}'.format(areaTriangulo)) print('CIRCULO: {:.3f}'.format(area...
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches # how big is our world? SIZE = 100 def generate_circles(num, mean, std): """ This function generates /num/ random circles with a radius mean defined by /mean/ and a s...
import pandas as pd import numpy as np df_csv=pd.read_csv("nyc-east-river-bicycle-counts.csv") df_bridge=df_csv[df_csv.columns[6:8]] x=df_bridge[df_bridge.columns[0]] y=df_bridge[df_bridge.columns[1]] def gradient_descent(): w=0 b=0 lr=0.000000001 num_iter = 10000 n = len(x) for i in range(...
# Задача 2. Вариант 3. # Напишите программу, которая будет выводить на экран наиболее понравившееся вам # высказывание, автором которого является Нострадамус. # Не забудьте о том, что автор должен быть упомянут на отдельной строке. S = "Жизнь - это череда выборов.\n\n" Auth = "\t\tНострадамус" print(S,Auth) inp = input...
# Задача 1, Вариант 12 # Напишите программу , которая будет сообщать род деятельности и псевдоним под которым скрывается Мария Луиза Чеччарелли. # Послевывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода. # Лях А. А. # 21.05.2016 print("Мария Луиза Чечарелли, более известна как ита...
# 5. 49 ''' # , . ''' # Ametova M. M. # 31.03.2016 import random wifes = [" ", " ", " ", " ", " ", " ", " ", " ", " "] number = random.randint(0, 8) name = wifes[number] print(name, "- ") input("\n Enter .")
#Задача № 3. Вариант 28 # Программа вводит имя и запрашивает его псевдоним # Цкипуришвили Александр #25.05.2016 print("Анри Мари Бейль \nПод каким псевданимом он был известен?") psev=input("Ваш ответ:") if (psev)==("Стендаль"): print("Все верно! Анри Мари Бейль-Стендаль - " + psev) input("\n\n\nНажмите Enter дл...
#Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы #большее количество баллов за меньшее количество попыток. # Кодзоков М.М., 26.05.2016 import random pigs=("Ниф-ниф","Наф-наф","Нуф-нуф") choice=random.choice(pigs) pg=input("Угадайте одного из трех поросят: ") points=1000 w...
#Задача 7. Вариант 1. #Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток. import random guessesTaken=0 print('Компьютер загадал имя одного из трех мушкетеров - товарищей д`Артаньяна. \nТвоя цель отгадать имя загаданного ...
# Задача 12. Вариант 50 # Разработайте игру "Крестики-нолики". #(см. М.Доусон Программируем на Python гл. 6). # Alekseev I.S. # 20.05.2016 board = list(range(1,10)) def draw_board(board): print("-------------") for i in range(3): print( "|", board[0+i*3], "|", board[1+i*3], "|", board[2+i*3], "|") ...
# Задача 3. Вариант 27. # Напишите программу, которая выводит имя "Михаил Евграфович Салтыков", и #запрашивает его псевдоним. Программа должна сцеплять две эти строки и #выводить полученную строку, разделяя имя и псевдоним с помощью тире. # Denisenko A. N. # 02.06.2016 name = "Михаил Евграфович Салтыков" print(name)...
# Задача 7. Вариант 15. # Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее # количество баллов за меньшее количество попыток. # Чинкиров В.В. ИНБ-ДБ1 # 11.05.2016, 11.05.16 balls=7 import random print("Создайте игру, в которой компьютер загадывает имя одного из две...
# Задача 6. Вариант 7. # Создайте игру, в которой компьютер загадывает имя одного из двух сооснователей компании Google, а игрок должен его угадать. # Zorin D.I. #11.04.2016 import random a = random.randint(1,2) if a == 1: w="Сергей Брин" elif a ==2: w="Ларри Пейдж" print("Основатель компании google: ") otvet = in...
#Задача №3. Вариант 6 #Борщёва В.О #02.03.2016 print("Герой нашей сегодняшней программы-Самюэл Ленгхорн Клеменс") psev=input("Под каким же именем мы зтого человека? Ваш ответ:") if(psev)==(Марк Твен): print(Все верно:Самюэл Ленгхорн Клеменс-"+psev) else: print("Вы ошиблись. это ни его псевдоним.") input("Нажмите Ente...
#Задача 9. Вариант 32. #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. #Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо #буква в слове, причем программа может отвечать только "Да" и "Нет". #Вслед за тем игрок должен попробоват...
# -*- coding: UTF-8 -*- # Задача 5. Вариант 15. # Напишите программу, которая бы при запуске случайным образом отображала название одного из двенадцати городов, входящих в Золотое кольцо России. # Mochalov V. V. # 08.03.2016 import random x=random.randint(1, 12) if x == 1: print ('Сергиев Посад') elif x == 2: prin...
#Задача 10. Вариант 10. #1-50. Напишите программу "Генератор персонажей" для игры. Пользователю должно быть предоставлено 30 пунктов, которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но ...
POINT = 30 ochki = 30 person = {"Сила":"0","Здоровье":"0","Мудрость":"0","Ловкость":"0"} points = 0 choice = None while choice != 0: print(""" 0 - Выход 1 - Добавить пункты к характеристике 2 - Уменьшить пункты характеристики 3 - Просмотр характеристик """) choice = int(input("Выбор пункта меню: ")) if...
#Задача 9. Вариант 33 #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отга...
# Задача 6. Вариант 28. # Создайте игру, в которой компьютер загадывает название одного из шести континентов Земли, а игрок должен его угадать. # Cherniy F. Y. # 27.03.2016 import random print("Компьютер загадал название одного из шести континентов Земли, а Вы должны его угадать.\n") continents = ('Евразия','Африка...
#Задача 7. Вариант 46 #Создайте игру, в которой компьютер загадывает название одной из трех стран, входящих в #военно-политический блок "Антанта", а игрок должен его угадать. #Gryadin V. D. import random print("Попробуй угадать, каую страну входящих в Антанту я загадал") a = random.choice(['Англия','Франция','Росси...
# Задача 6. Вариант 22. # Создайте игру, в которой компьютер загадывает имена двух братьев, легендарных # основателей Рима, а игрок должен его угадать. # Щербаков Р.А. # 22.05.2016 import random print("Комп загадал имя одного из двух братьев основавшие рим, попробуй угадать что ли") name='Рем', 'Ромул' rand=random.r...