text stringlengths 37 1.41M |
|---|
num=int(input())
b=1
c=[]
for i in range(1,6):
b=i*num
c=b.append(b)
print(*c)
|
num1,num2,num3 =[float(x) for x in input().split()]
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print(int(largest))
|
n,m,o=[x for x in input().split()]
if(m=="%"):
print(int(n)%int(o))
else:
print(int(int(n)/int(o)))
|
#!/usr/bin/env python
# coding: utf-8
# # List Methods
# In[1]:
# append(x)
# Adds an item to the end of the list. It's equivalent to var[len(var):] = [x]
var = ['car','bicycle']
print(var)
var.append('train')
print(var)
# In[2]:
# extend(iterable)
# Extends the lis by appendingall the items from iterable. Thi... |
#!/usr/bin/env python
# coding: utf-8
# # Complex Numbers
# ## Syntax
# In[1]:
# complex([real[, imag]])
# ## Creating a complex number
# In[2]:
c = 2 + 3j
print(type(c))
# In[3]:
c1 = complex(2, 3)
print(type(c1))
# In[4]:
print(c1)
# ## Atributes and Functions
# In[5]:
# Conjugate: 4 + 9j
# re... |
#!/usr/bin/env python
# coding: utf-8
# # Whitespace Formatting
# In[1]:
for i in [2]:
print(i) # first line in "for i" block
for j in [15]:
print(j) # first line in "for j" block
print(i + j) # last line in "for j" block
print(i + 1) # last line in "f... |
from datetime import date
date1 = date(2014, 7, 2)
date2 = date(2021, 7, 11)
print("Days between %s and %s are: " % (date1.strftime("%x"), date2.strftime("%x")))
print(date2 - date1) |
filename = input("Enter filename: ")
extn = filename.split(".")[1]
print("The file is %s type" % extn) |
import math
from collections import Counter
def all_factors(num):
l = list()
for i in range(1, num+1):
if num % i == 0:
l.append(i)
return l
def factors(num):
orig_num = num
l = list()
l.append(1)
i = 2
while num > 1:
if num % i == 0:
num = num/i... |
class Calculator(object):
# https://www.codewars.com/kata/5235c913397cbf2508000048
def evaluate(self, string):
interval_string = string.split(' ')
interval_string = self.calculate(interval_string, ['*','/'])
return float(self.calculate(interval_string, ['+','-'])[0])
@staticmet... |
from ..Board.Row import Node
class StrategyLiftshift:
def executeStrategy(board):
for value in [val for row in reversed(board.solved_board[1:]) for val in reversed(row)]:
StrategyLiftshift.liftshift(board, value)
def liftshift(board, value):
"""first stage solving algorithm, solve... |
from collections import deque # just to have a heap convention
from Sudoku.util import timeit, count_calls
class Tracker:
def __init__(self, sudoku):
self.unvisited = deque(sudoku.zeros)
self.remaining_choices = dict()
def nextzero(self):
"""yield the next zero to choose from."""
... |
"""
You are given given task is to print whether array is ‘majestic’ or not.A ‘majsetic’ array is an array whose sum of first three number is equal to last three number.
Input Description:
You are given a number ‘n’,Next line contains ‘n’ space separated
Output Description:
Print 1 if array is majestic and 0 if it is... |
"""
Alternate sorting:Given a number N followed by array of N elements,sort the array in such a way that the first number is the first maximum and second number is the 1st minimum 3rd number isthe 2nd maximum and so on.
Input Size : N <= 100000
Sample Testcase :
INPUT
8
7 623 19 10 11 9 3 15
OUTPUT
623 3 19 7 15 9 11 1... |
"""
A number is given as input. Find the odd digits in the number, add them and find if the sum is odd or not. If even print E, if odd print O.
Input Size : N <= 10000000000
Sample Testcase :
INPUT
413
OUTPUT
E
"""
n=int(input())
# print(n.split())
arr=[]
sum=0
while(n>0):
d=n%10
arr.append(d)
n=int(n/10)
... |
"""
Given a string S, print 2 strings such that first string containing all characters in odd position(s) and other containing all characters in even position(s).
Sample Testcase :
INPUT
XCODE
OUTPUT
XOE CD
"""
v=input()
o=[]
e=[]
for i in range(len(v)):
if(i%2==0):
e.append(v[i])
else:
o.appe... |
# Title: Photogrammetric Study Site Coordinate Calculator
# Created by: R. Allen Gilbert Jr.
# Created on: 20161130
# Purpose: This program calculates the approximate intervals images were taken at a study sites used during a Colorado Water Institute funded research project that used photogrammetry to derive snow ra... |
import random
import math
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# Monte Carlo Methods Presentation
# Example 1 - Pi Estimation
def single_estimate_pi(points=100000):
"""
Estimates Pi value using Monte Carlo method
Formula:
Estimated Pi = 4 * Number o... |
import tkinter as tk
class GuiMain():
"""Classe que define a interface gráfica da aplicação
"""
x_pad = 5
y_pad = 3
width_entry = 30
#Criando a janela...
window = tk.Tk()
window.wm_title("Torneio - Poker")
#Criando os objetos que estarão na janela...
btnJogador... |
#!/usr/bin/env python3
import sys
PRIMES = {
0: False,
1: False,
2: True,
3: True,
}
def is_prime(number):
if number in PRIMES:
return PRIMES[number]
if number % 2 == 0:
PRIMES[number] = False
return False
for i in range(3, int(number ** 0.5) + 1, 2):
i... |
#!/usr/bin/env python
import urllib
import sys
import re
import subprocess
"""
Scrapes a webpage for YouTube links and outputs to file.
Example formats for Reddit's URLs
http://www.reddit.com/r/listentothis/top/?t=day
http://www.reddit.com/r/listentothis/top/?t=week#page=2
Usage: python getMusicReddit.py... |
class Solution:
def numSquares(self, n: int) -> int:
level = 0
solution_set = {n}
while True:
level+=1
new_solution_set = set()
for item in solution_set:
for minus_item in range(int(n**0.5),0... |
class Solution:
def averageWaitingTime(self, customers: List[List[int]]) -> float:
wait_time = 0
time_start = 0
for ix, [x,y] in enumerate(customers):
time_start = max(time_start,x)
wait_time += y + time_start - x
... |
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
pos=[-1,-1]
for ix,i in enumerate(nums):
if i==target:
#for first position : only recorded for once
if pos[0]<0:
pos[0]=ix
#for last posi... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
ix = 2
while ix < len(nums):
if nums[ix] == nums[ix - 2]:
nums.pop(ix - 2)
else:
ix += 1
return le... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class CBTInserter:
def __init__(self, root: Optional[TreeNode]):
self.r = root
self.dict = {0: []}... |
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.magic = []
def buildDict(self, dictionary: List[str]) -> None:
self.dict = dictionary
def search(self, searchWord: str) -> bool:
if searchWord in self.magic... |
class Solution:
def findNumbers(self, nums: List[int]) -> int:
def check(t):
n=0
while t:
t//=10
n+=1
return 0 if n%2 else 1
return sum([check(i) for i in nums])
#Runtime: 52 ms, faster than 80.41% of Python3 online... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_dgree=hour%12*30+minutes*0.5
minutes_degree=minutes*6
return min( abs(hour_dgree-minutes_degree),360-abs(hour_dgree-minutes_degree))
#Runtime: 24 ms, faster than 91.04% of Python3 online submissio... |
class Solution:
def numberOfSteps (self, num: int) -> int:
step=0
while num!=0:
# for even => divided by 2
if num%2==0:
num=num/2
# for odd => minus 1
else:
num-=1
step+=1
... |
def name():
name = input("enter your name : ")
age = input ("enter your age : ")
print("hey! {} you'r wellcome you'r {} Year old" .format(name, age))
name()
|
from being import *
from functions import *
from random import *
def Zombies():
human = Human("Protag",40,False,'Human')
human.givestats()
tiles = {'ZB': 0.04,'zom': 0.2,'HP': 0.06,'WP': 0.08}
tilenum = tiles
#length = int(input("Enter the length (east to west distance) you want ... |
from board import Board
from ship import Ship
from os import system, name
from time import sleep
def clear_screen():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def ordinary_battleships(player_1_board, player_2_board, player_1_guess_board, player_2_guess_board):
has_play... |
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser(description="Sort the input file and return a sorted output file ")
parser.add_argument('-i', '--input', type=str, metavar='', required=True, help="Path to the input file")
parser.add_argument('-o', '--output', type=str, metavar='', required=True, hel... |
# http://www.careercup.com/question?id=15542726
import string
rows = 6
cols = 5
def rec(target, cursor):
trow, tcol = target / cols, target % cols
crow, ccol = cursor / cols, cursor % cols
if trow < crow:
print 'U'
return rec(target, cursor - cols)
elif trow > crow:
print 'D'... |
words = [
'abacus',
'deltoid',
'gaff',
'giraffe',
'microphone',
'reef',
'qar'
]
letters = [
'a',
'e',
'f',
'f',
'g',
'i',
'r',
'q',
]
def find_longest_word(words, letters):
# Maintain a global map of letter counts to check against
table = {}
fo... |
import random
def getdigit(num, pos):
return num / 10 ** pos % 10
def rsort(L, dindex=0):
buckets = {}
for digit in range(10):
buckets[digit] = []
finished = True
for number in L:
digit = getdigit(number, dindex)
buckets[digit].append(number)
if digit > 0:
... |
# This will be the cipher's dictionary, from which it will pull random words to mask the message's words
dictionary = ["this", "that", "those", "these", "them", "those", "they",
"though", "thought", "threw", "tough", "tease", "temptation", "tickle", "tackle"]
while True:
choice = input("Would you lik... |
# max heap
class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
pass
def delete(self):
pass
def get_max(self):
pass
def get_size(self):
pass
def _bubble_up(self, index):
# keep bubbling up intil we've either reached the t... |
my_list= [2.70, 3.14 , 5.92, 9.26, 12.48, 30.40, 55.55 ]
#Normal search
def search(my_list, element):
answer= False
for i in my_list:
print(i)
if element== i:
answer= True
break
return answer
print(search(my_list, 55.55))
#recursive binary search
#... |
print("This program will calculate the volume of a pyramid.\n You have to enter the length and width of the base, and height of the pyramid.\nEnter i or c after on the next prompt to indicated inches or centimeter.")
length= float(input("Enter length:"))
c_i = input("c or i:")
if c_i=="c":
length= length/2.54
... |
pH= float(input("Enter pH:"))
if pH<0 or pH>14:
print("Error")
elif pH==7:
print("Neutral")
elif pH<7:
print("Acidic")
else:
print("Basic") |
S=1
X= float(input("Input X:"))
Y= float(input("Input Y:"))
while X>0:
S= S*Y
X=X-1
print(S)
#Algorithm calculates Y to the power of X |
"""
-------------------------------------------------------------------------------
Name: days_hours.py
Purpose: convert hours to days and hours
Author: Yao.T
Created: 08/02/2021
------------------------------------------------------------------------------
"""
#get hours
hours = int(input("Enter hours: "))
#... |
class ComparableModelMixin:
def equals(self, obj, comparator):
"""
Use comparator for evaluating if objects are the same
"""
return comparator.compare(self, obj)
class Comparator:
def compare(self, a, b):
"""
Return True if objects are same otherwise False
... |
# -*- coding: UTF-8 -*-
from Tkinter import *
root = Tk()
li = ['c','python','php','html','sql','java']
movie = ['css','jquery','bootstrap']
listb = Listbox(root)
listb2 = Listbox(root)
for item in li :
listb.insert(0,item)
for item in movie :
listb2.insert(0,item)
def callback():
print "click!"
button ... |
#!/usr/bin/python
#Faca um Programa que peca 2 numeros inteiros e um numero real.
#Calcule e mostre:
#O produto do dobro do primeiro com metade do segundo .
#A soma do triplo do primeiro com o terceiro.
#O terceiro elevado ao cubo.
int1 = input("Digite o primeiro valor inteiro. ")
int2 = input("Digite o segundo val... |
#!/usr/bin/python
metros = input("Informe a quantidade de metros que serao pintados.")
litros = metros/6
totallata = litros/18.0
totalgalao = litros/3.6
precolata = totallata*80.0
precogalao = totalgalao*25.0
print("O total de tinta necessario e de ",litros,"litros de tinta.")
print("O total de latas necessario e d... |
"""
Created by Bede Kelly.
An implementation of the unix commandline tool 'cowsay'.
Usage: cow.py <message>
"""
import sys
def print_base_cow():
"""Prints the cow's body after the speech bubble."""
# Slightly odd python, but much more readable.
cow_list = [r" \ ^__^",
r" ... |
import numpy as np
import matplotlib.pyplot as plt
def show_data(ax, x0, x1, t):
for i in range(len(x0)):
ax.plot([x0[i], x0[i]], [x1[i], x1[i]], [120, t[i]], color='grey')
ax.plot(x0, x1, t, 'o', color='cornflowerblue', markeredgecolor='black',
markersize=6, markeredgewidth=0.5)
... |
def mergeSort(input_array):
if len(input_array) > 1:
mid = len(input_array)//2
left = input_array[:mid]
right = input_array[mid:]
mergeSort(left)
mergeSort(right)
left_index=0
right_index=0
input_index=0
while left_index < len(left) and right_index < len(right):
if left[... |
def human():
"""Inputs a word from user1 and returns it."""
a = input("Enter the word that user2 should guess: ")
return a
def hangman(humanWord, max_mistakes=8):
"""The function that initiates the hangman game
Keyword arguments:
humanWord -- The word given by user1, as captured in human().
... |
# https://www.hackerrank.com/challenges/s10-normal-distribution-1/problem
# In probability theory, a normal distribution is a type of continuous probability distribution for a real-valued random variable.
# The normal distribution is a probability distribution.
# It is also called Gaussian distribution because it w... |
# https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem
# In probability theory and statistics, the binomial distribution with parameters n and p
# is the discrete probability distribution of the number of successes in a sequence of n independent experiments,
# each asking a yes–no question, and e... |
# https://www.hackerrank.com/challenges/s10-poisson-distribution-1/problem
# This is a discrete probability distribution that expresses the probability of a given number of events occurring
# in a fixed interval of time or space if these events occur with a known constant mean rate and independently of the time since... |
"""
@ Schwinn Zhang
This file provides an object called Scheduler that utilizes the Min Queue data structure to schedule tasks
"""
import heapq
class Scheduler(object):
def __init__(self):
self.schedule = []
self.size = 0
self.table = {} # table hashes rank to task; rank is unique key; task can be repeated
#... |
import random
import time
def selection_sort(vector):
# runs through inversed array searching for the greater number
for fillslot in range(len(vector)-1, 0, -1):
max_pos = 0
# finds position of greater number
for locale in range(1, fillslot + 1):
if vector[locale] > vector[m... |
#!/usr/bin/python3
""" Lekce #4 - Uvod do programovani, Nakupni kosik """
kosik = {}
ODDELOVAC = "=" * 40
POTRAVINY = {
"mleko": [30, 5],
"maso": [100, 1],
"banan": [30, 10],
"jogurt": [10, 5],
"chleb": [20, 5],
"jablko": [10, 10],
"pomeranc": [15, 10]
}
print(
"VITEJTE V NASEM VIRTUALNIM OBCHODE".cente... |
"""
beautiful-days-at-the-movies
"""
def beautiful_days(i, j, k):
return sum([1 for day in range(i, j + 1) if abs(day - int((str(day)[::-1]))) % k == 0])
if __name__ == '__main__':
ijk = input().split()
i = int(ijk[0])
j = int(ijk[1])
k = int(ijk[2])
result = beautiful_days(i, j, k)
prin... |
"""
acm-icpc-team
"""
def acm_team(n, m, topic):
max_skills = 0
max_skill_teams = 0
for i in range(n - 1):
for j in range(i + 1, n):
skill_sets = str(bin((int(topic[i], 2) | int(topic[j], 2))))[2:].count('1')
if skill_sets > max_skills:
max_skill_teams = 1
... |
"""
strong-password
"""
def minimum_number(n, password):
count = [0, 0, 0, 0]
for c in password:
if c in "0123456789":
count[0] = 1
elif c in "abcdefghijklmnopqrstuvwxyz":
count[1] = 1
elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
count[2] = 1
elif... |
"""
compare-the-triplets
"""
def compareTriplets(a, b):
r = [0, 0]
for i in range(3):
if a[i] > b[i]:
r[0] += 1
elif b[i] > a[i]:
r[1] += 1
return r
if __name__ == '__main__':
a = list(map(int, input().rstrip().split()))
b = list(map(int, input().rstrip()... |
#!/bin/python3
"""
diagonal difference
"""
def diagonalDifference(arr):
ln = len(arr)
l_diag = sum([arr[i][i] for i in range(ln)])
r_diag = sum([arr[i][ln - i - 1] for i in range(ln)])
return abs(l_diag - r_diag)
if __name__ == '__main__':
n = int(input().strip())
arr = []
for _ in rang... |
"""
the-love-letter-mystery
"""
def the_love_letter_mystery(s):
return sum([abs(ord(s[i]) - ord(s[-(i + 1)])) for i in range(len(s) // 2)])
if __name__ == "__main__":
q = int(input())
for q_itr in range(q):
s = input()
result = the_love_letter_mystery(s)
print(result)
|
"""
modified-kaprekar-numbers
"""
def kaprekar_numbers(p, q):
k_nums = []
for i in range(p, q + 1):
num = str(i)
d = len(num)
squared_num = str(i ** 2)
sd = len(squared_num)
right = int(squared_num[sd - d:])
left = int("0" if sd - d == 0 else squared_num[:sd - d... |
"""
migratory-birds
"""
from collections import Counter
def migratoryBirds(arr):
c = Counter(arr)
mx = max(c.values())
return [i for i in range(1, 6) if c[i] == mx][0]
if __name__ == '__main__':
arr_count = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = migrator... |
from tkinter import Tk, Frame, Label, Button, Entry, BOTTOM
from tkinter import ttk
from main import inserir_dados, retornar_valores_bd
"""
Aplicação em Python utilizando Tkinter para a criação da Interface Grafíca para o Usuário, onde será exibida a pontuação da temporada
"""
class AppDesafio_Inserir(object):
"... |
import numpy as np
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {}
self.lis = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the spe... |
class Solution(object):
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
self.word_path = []
self.shortest_path_len = 9999999
self.end_word = ... |
# 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 dfs(self, node, target, ans):
if node.left:
self.dfs(node.left, target, ans)
if node.val ... |
class LinkNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.nxt = None
self.prev = None
class AllOne:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = LinkNode("", 0)
self.head.nxt = LinkN... |
class Solution(object):
def isPali(self, s):
return s == s[::-1]
def reverse(self, s):
return s[::-1]
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
ans = set()
dict = {}
for i in range(len(wo... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sort(self, head):
if head.next == None: return head
slow = fast = head
while True:
if fast == None or fast.next == None or fas... |
class Solution(object):
def binary_search(self, pre, num):
l = -1
r= len(pre)-1
while l+1<r:
mid = (l+r)/2
if pre[mid]>=num:
r = mid
else:
l = mid
return r
def lengthOfLIS(self, nums):
"""
:type n... |
# -*- coding: utf-8 -*-
# written by Thane
import pandas as pd
# Define these global variables before running.
SPACING_INTERVAL = 5
DATA_FILE = "python-forthane.csv" # Make sure this file is in the same folder as this script.
MINIMUM_VALUE = None
MAXIMUM_VALUE = None
#come back and define these later
AGE... |
class CEO:
# object properties are shared in static variable
__shared_state = {
'name': 'steve',
'age': 55
}
def __init__(self):
# every new object is assigned the same shared properties
# copying not just data but the REFERENCE to the entire dict
self.__dict... |
class Car:
def __init__(self, driver):
self.driver = driver
self.age =
def drive(self):
if self.age < 16:
else:
print(f'Car is being driven by {self.driver.name}')
# PROXY
class CarProxy:
def __init__(self, driver):
self.driver = driver
... |
# Event -> notification for that event
# Doctors want to know when person is ill
class Event(list):
# list of functions to invoke when the event happens
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
# Anyone can subscribe to event class
# For ex. doctor will ... |
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Size(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
class Product:
def __init__(self, name, color, size... |
import time
average_list = []
t0 = int(time.time())
def timefy(x):
print ('''Your Expected Waiting Time is''')
s = x%60
print(str(s)+" sec")
if x//60 >= 1:
m = (x//60)%60
print(str(m)+" min")
if (x//60)//60 >=1:
h = ((x//60)//60)%60
... |
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
listEven =[]
listOdd=[]
for el in A:
if el%2 == 0:
listEven.append(el);
else:
listOdd.append(el);
retur... |
class Animal(object):
def run(self):
print('Animal is running..')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
def run_twice(animal):
animal.run()
animal.run()
a = Animal()
b = Dog()
c = Cat()
print('a is An... |
"""
The energy distance test of homogeneity
=======================================
Example that shows the usage of the energy distance test.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import dcor
# %%
# Given samples (of possible different sizes) of several random vectors with
# th... |
import sys
colour=red
inputclr = raw_input('Please Enter colour: ')
enter singal colour = red
signal = {}
signal['red']='stop'
signal['yellow']='about to red'
signal['green']='go'
signal = {'red' : 'stop', 'yellow' : 'about to red', 'green' : 'go'}
/
Things to do in this script
ask for input as a prompt
if green ... |
# perform arithmetic operations with string
msg = 'Firstname Lastname'
print((msg + '\n')* 3)
# using slices, remove affixes in the following wordforms: dish-es, run-ning, nation-ality, un-do, pre-heat
affixes = ['dishes', 'running', 'nationality', 'undo', 'preheat']
dishes = affixes[0][0:4]
running = affixes[1][0:3]
... |
#Fonction permettant de déterminer si oui ou non un point de calcul se situe dans un mur
def isinwall(walls,x,y):
#Il existe deux cas possible, soit le point se trouve dans un mur horizontal soit vertical
res = False
for wall in walls:
#Mur horizontal
if y == wall.y1 ... |
inp = input("Enter the numbers to be added separated by spaces : ")
operands = inp.split(' ')
sum = 0.0
for i in operands:
sum += int(i)
print (i + ' + ', end='')
print (' = %.3f' %sum)
|
'''
Write a calculator program using try except blocks
'''
print("""
1-addition
2-subtraction
3-multiple
4-devide
""")
while True:
count = input("choose a process: ")
first = input("First Number (q for exit): ")
second = input("Second Number: ")
if first == "q": break
if count == "1":
try:... |
""" Grid Based Snake Game """
"""
TODO:
-Create nested lists to form a grid and put a starting position in it
-Create pygame window to represent that grid graphically with the snake (Black and White)
-Add player controls to the snake
-Snake continues moving in the same direction the playe... |
import string
import unicodedata
SLUG_CHARS_DISPLAY = '[a-z0-9-]'
_SLUG_CHARS = string.ascii_lowercase + string.digits + '-'
_SLUG_SIZE = 50
def slugify(text):
'''Returns the slug of a string (that can be used in an URL for example.'''
slug = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
... |
food = ["Cherry", "Strawberry", "Raspberry"]
description = ["Snack", "Tasty", "Red", "Healthy"]
for x in food:
for y in description:
print(x, y) |
#displays a list of numbers
num1 = 13
num2 = 6
num3 = 11
num4 = 3
print(num1, num2, num3, num4) |
# Python program to print list
# using for loop
fruit = ["Apple", "Pear", "Watermelon", "Orange", "Kiwi" "\n"]
# printing the list using loop
for x in (fruit):
print(x)
color = ["Red", "Blue", "Green", "Pink" "\n"]
for x in (color):
print(x)
states = ["California", "Texas", "Virginia", "Utah" "\n"]
for x... |
#//imports new commands
import requests
import json
from Tkinter import *
import tkFont
import tkMessageBox
#//window is referred to as "root"
root = Tk()
root.title("Weather")
#//prints two questions, in which the answer will decide where the weather report is from
stateLabel = Label(root, text = "What state are you... |
#creates a formula to add "a" and "b" numbers
print("What's the first number you would like to add?")
a = int(raw_input())
print("What would you like %s to be added with?" % (a))
b= int(raw_input())
def add (a,b):
c = a + b
print("%s + %s = %s" % (a,b,c))
print(add(a,b))
|
from functions import isvalid, score_G, getChildren, next_play
def minimax(data,depth, maximizing):
if depth <= 0 or not isvalid(data): return score_G(data)
if maximizing:
sc = float('-inf')
for child in getChildren(data.copy(), True): #will run 4 times at max
sc = max(sc, minimax(c... |
"""
Kata - Longest alphabetical substring
Find the longest substring in alphabetical order.
Eg: the longest alphabetical substring in asdfaaaabbbbcttavvfffffdf is aaaabbbbctt.
There are tests with strings up to 10000 characters long so your code will need to be efficient.
The input will only consis... |
from __future__ import print_function
def date_to_unix(date_string, date_format = '%Y-%m-%dT%H:%M:%S'):
import datetime, calendar
## Make datetime object from time_string
date = datetime.datetime.strptime(date_string, date_format)
time_tuple = date.timetuple()
## Get unix time (this assumes that time_tuple... |
# 开发时间:2021/5/22 0:34
print('本程序将对输入的整数进行绝对值输出')
b=0
while b==0:
a = int(input('请输入一个整数:'))
print('输入的数为', a)
if a>=0:
print('绝对值为',a)
else:
print('绝对值为',(-a))
judge=input('是否要再一次执行程序(y/n)')
c=0
while c==0:
if judge=='y':
b=0
c=1
elif j... |
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
def createData(n=1000):
random.seed(42)
np.random.seed(42)
#randomize ages
ages = []
for ii in range(n):
ages.append(rand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.