def fill_walk(self): """计算随机漫步包含的所有点""" #不断漫步,直到列表到达指定的长度 while len(self.x_values) < self.num_points: #决定前进方向以及沿这个方向前进的距离 x_direction = choice([1,-1]) print([1,-1]) # x_distance = choice([0,1,2,3,4]) x_distance = choice([0,1,2,3,4,6,7,8]) x_step = x_distance * x_direction y_direction = choice([1, -1]) # y_distance = choice([0, 1, 2, 3, 4]) y_distance = choice([0,1,2,3,4,6,7,8]) y_step = y_distance * y_direction #拒绝原地踏步 if x_step == 0 and y_step == 0: continue #计算下一个点的x和y值 next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step if next_x > 0 and next_y > 0: self.x_values.append(next_x) self.y_values.append(next_y)
MAX_COLUMN_WIDTHS = { 'desc': 50, 'name': 20,} output_option = click.option('-o', '--output', type=click.Choice(['text', 'json', 'tsv', 'yaml']), default='text', help='Use alternative output format')json_output_option = click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json', help='Use alternative output format')watch_option = click.option('-w', '--watch', type=click.IntRange(1, 300), metavar='SECS', help='Auto update the screen every X seconds') def watching(watch: int): if watch: click.clear() yield 0 if watch: while True: time.sleep(watch) click.clear() yield 0 def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo('ClickClick Example {}'.format(__version__)) ctx.exit() @click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS)@click.option('-V', '--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True, help='Print the current version number and exit.')def cli(): pass @cli.command('list')@output_option@watch_optiondef list_dummy_states(output, watch): '''Example for Listings''' states = ['ERROR', 'FINE', 'WARNING'] i = 0 for _ in watching(watch): i += 1 rows = [] for y in (1, 2, 3): id = i * y - i rows.append({'id': id, 'name': 'Column #{}'.format(id), 'state': states[id % len(states)], 'creation_time': 1444911300, 'desc': 'this is a ve' + 'r' * 50 + 'y long description', 'without_title': 'column without title', 'missing_column': 'Column are not in output'}) with OutputFormat(output): print_table('id name state creation_time desc without_title'.split(), rows, styles=STYLES, titles=TITLES, max_column_widths=MAX_COLUMN_WIDTHS) @cli.command()@output_optiondef output(output): '''Example for all possible Echo Formats You see the message only, if the Output TEXT ''' with OutputFormat(output): action('This is a ok:') ok() action('This is a ok with message:') ok('all is fine') action('This is a warning:') warning('please check this') with Action('Start with working..') as act: # save_the_world() act.progress() act.progress() act.progress() act.progress() print_table('id name'.split(), [{'id': 1, 'name': 'Test #1'}, {'id': 2, 'name': 'Test #2'}]) info('Only FYI') action('This is a error:') error('this is wrong, please fix') action('This is a fatal error:') fatal_error('this is a fuckup') info('I\'am not printed, the process a dead') @cli.command()def localtime(): '''Print the localtime''' print('Localtime: {}'.format(get_now())) @cli.command('work-in-progress')def work_in_progress(): '''Work untile working is done''' with Action('do anything..'): pass try: with Action('create an excption..'): raise except: pass with Action('Start with working..') as act: # save_the_world() act.progress() act.progress() act.progress() act.progress() with Action('Calc 1 + 1..') as act: # save_the_world() act.ok(1+1) with Action('Oh, I make an error..') as act: # clear_the_oceans() act.error('work not complete done') with Action('Oh, I make a warning..') as act: # clear_the_air() act.warning('work is complicated') try: with Action('Start an exception..') as act: function_not_found() # noqa act.progress() except: pass with Action('Make a final error..') as act: act.fatal_error('this is the end..') with Action('This should not run..'): pass @cli.command()@click.argument('percentage', type=FloatRange(0, 100, clamp=True), required=True)def work_done(percentage): '''Work done in ?? %''' state = choice('Please select the state of your work', ['Done', 'In Progress', 'unknown', 'lost'], default='lost') print('Your work is {}% {}'.format(percentage, state)) if __name__ == "__main__": cli()
def send_event_notification(recipient_name, relatp_name, recipient_email, recommendation): """Send an email to the user reminding them to reach out to their friends.""" content = content1, content2, content3 content1 = """From: Relationship Manager App <*****@*****.**> To: {} Subject: {} misses you! Hiya, {}! It's been a while since {} has heard from you. {}. Relationships require time and care to nurture. Stay happy, Relationship Manager App """.format(recipient_email, relatp_name, recipient_name.first_name, relatp_name, recommendation) content2 = """From: Relationship Manager App <*****@*****.**> To: {} Subject: Re-connect with {} {}! {} understands that you're busy but would love to see how you're doing. {}. Warmly, Relationship Manager App """.format(recipient_email, relatp_name, recipient_name.first_name, relatp_name, recommendation) contact3 = """From: Relationship Manager App <*****@*****.**> To: {} Subject: Re-connect with {} Hi {}! Remember {}? If it's been a while since you've reached out to {}, remind them of a memory you shared with them or how you know each other. Don't expect them to remember exactly who you are (overselling yourself), but don't start with "You probably don't remember me but.." and undersell yourself either, as you'll trick them into somehow thinking that the two of you don't know each other that well. {}. What's the worst that could happen? Happy networking, Relationship Manager """.format(recipient_email, relatp_name, recipient_name, relatp_name, relatp_name, recommendation) # Create an SMTP object that specifices the server & port (465 or 587 for Gmail). mail = smtplib.SMTP('smtp.gmail.com', 587) # Identify yourself to server by helo (regular) or ehlo (esmtp server). mail.ehlo() # Start TLS mode (transport layer security). # Any smtp command that comes after this code will be encrypted. mail.starttls() # Log in to the account that email will come from. mail.login(YOUR_EMAIL_ADDRESS, YOUR_EMAIL_PASSWORD) # Specify sender, receiver and content of email. mail.sendmail(YOUR_EMAIL_ADDRESS, recipient_email, choice(content)) # Disconnect from teh SMTP server mail.quit()
'''Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome escolhido.''' import random import choice n1 = str(input('Primeiro aluno: ')) n2 = str(input('Segundo aluno: ')) n3 = str(input('Terceiro aluno: ')) n4 = str(input('Quarto aluno: ')) lista = [n1,n2,n3,n4] escolhido = choice(lista) print(escolhido)
import random import choice questions = [ "Why is the sky blue? ", "Why is Python so ez? ", "Where is mom? " ] question = choice(questions) answer = input(question).strip().lower() while answer != "just because": answer = input("why?: ").strip().lower() print("Oh...okay")
2 +''' 3 +Напишите программу, которая бы при запуске случайным образом 4 +отображала имя одного из трех племянников Скруджа МакДака. 5 +''' 6 +# SHEIKO R.V. 7 +# 10.03.2016 8 + 9 +from random import choice 10 + 11 +phrase = 'Билли, Вилли и Дилли' 12 + 13 +nephews = [''.join(filter(str.isalpha, name)) 14 + for name in phrase.split(' ') 15 + if len(name) > 2] 16 + 17 +stats = [0, 0, 0] 18 + 19 +k = 1 20 +while True: 21 + c = choice(nephews) 22 + stats[nephews.index(c)] += 1 23 + k -= 1 24 + if k <= 0: 25 + print('\n' + c) 26 + print('Статистика ' + str(stats)) 27 + try: 28 + k = int(input('Повторить n раз: ')) 29 + except: 30 + continue 31 +
def spawn(self): new_element =4 if randrange(100)>89 else 2 # When random number is 100 get 4 else 2 (i,j)=choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] ==0]) self.field[i][j] =new_element