text stringlengths 5 121k |
|---|
import numpy.random as random
def partition(arr, l, h):
ptr=l
pivot=h
for i in range(l,h):
if arr[i]<arr[pivot]:
arr[i], arr[ptr] = arr[ptr],arr[i]
ptr += 1
arr[ptr] , arr[pivot] = arr[pivot], arr[ptr]
return ptr
def quickSortIterative(arr, l, h):
stack... |
from collections import deque
def Palimdrome(s: str) ->bool:
"""
strs = []
for char in s :
if char.isalnum():
strs.append(char.lower())
while len(strs)>1:
if strs.pop(0) != strs.pop():
return False
return True
"""
strs =deque()
... |
""" A collection of all appliances available. Each appliance has a consumption mean
and standard deviation, as well as a list of houses containing the appliance. """
appliance_data = {
"kettle": {
"mean": 700,
"std": 1000,
"houses": [2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 19, 20],
"channe... |
def remove_space(string):
return string.replace(" ","") |
import sqlite3
conn=sqlite3.connect('answer.db')
c=conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS answer (
asked_on text,
answered_on text,
answer text,
photo text,
answerd_by text,
answer_by_email text
... |
import csv
import os
import sys
import inspect
import getopt
def read_key_value_pair_from_csv(file, key, value):
values = None
if value is not None:
values = [value]
results = []
with open(file, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:... |
while (1):
import random
arr=['p','s','sc']
c=random.choice(arr)
v=str(input("enter the your choice form -- s, sc, p:"))
b=str(v)
n=str(c)
print(b)
print(n)
if(c==v):
print("match draw")
elif(b=="s" and n=="sc"):
print("vijay is win")
elif(b=="s" and n=="p"):
print("computer is win")
elif(b=="p" a... |
def translateMessage(do, message, key):
if do == "d":
key = -key
transMessage = ""
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
if symbol.islower():
if num > ord("z"):
... |
import datetime
import calendar
import sys
def get_day(day, month, year):
date = datetime.datetime(int(year), int(month), int(day))
print(calendar.day_name[date.weekday()])
if __name__ == '__main__':
get_day(sys.argv[1], sys.argv[2], sys.argv[3]) |
import reminder
import user_notes
import calendar
import datetime
import os
Help = """
Make your planning more efficient with the use of calendar.
You won't miss your favourite events like watching movies,
plan tours, mark birthdays, manage datewise to-do lists and
other benefits by using it in the best poss... |
Limit = input("Enter Limits >> ")
try:
Limit = int(Limit)
n1,n2 = 0,1
count = 0
if Limit < 0 :
print("Fibonacci Series is 0 !")
elif Limit==1:
print("Fibonacci Series is :", n2)
else:
print("Fibonacci Series >> ")
while co... |
class Product:
def __init__(self, price, name, weight, brand):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = 'For Sale'
def sell(self):
self.status = 'Sold'
return self
def add_tax(self, tax):
total =... |
class Banking():
def __init__(self, balance=100):
self.balance = balance
print("\nWelcome to the ATM Deopsit and Withdrawal Machine!")
def machine(self):
data=self.usage()
if data == True:
self.deposit()
self.display()
else:
self.withd... |
'''
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
'''
'''
要注意特殊输入,如果输入是空链表,不能崩溃。
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def Merge(self, p_head1, p_head2):
if p_head1 == None:
return p_head2
elif p_head2... |
'''
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
'''
需要两个栈Stack1和Stack2,push的时候直接push进Stack1。
pop需要判断Stack1和Stack2中元素的情况,Stack1空的话,直接从Stack2 pop,Stack1不空的话,把Stack1的元素push进入Stack2,然后pop Stack2的值。
'''
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, ... |
print('hello world')
a = input('write your ... something: ')
if len(a) % 2 == 0:
b = a[:len(a)//2]
c = a[len(a)//2:][::-1]
print(b + c)
else:
print('ты неправильно ввел')
|
data = [1, 2, 3, [2, 3, '12'], [123], 22, [1, 2]]
answer = []
for i in data:
if isinstance(i,list):
answer.extend(i)
else:
answer.append(i)
print(answer)
|
def countpolindroms(a):
a += ' '
word_or_number = ''
answ = ''
for i in a:
if i != ' ':
word_or_number += i
elif i == ' ':
if word_or_number == word_or_number[::-1] and len(word_or_number) > 1:
answ += word_or_number + ' '
word_or_n... |
class Solution(object):
def removeDuplicates(self, nums):
"""
nums= [1,1,2,2,3,4]
create and index of all unique chars in the list
then remove all the rest
return the new index list we make
+ the len of them
"""
if len(nums) == 0:... |
class Solution:
def twoSum(self,nums,target):
comp_map = dict()
for i in range(len(nums)):
num = nums[i]
comp = target - nums[i]
if num in comp_map:
return [comp_map[num], i]
... |
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
vw_tuple = [(values[i], weights[i], 1. * values[i] / weights[i]) for i in range(len(values))]
vw_tuple.sort(key=lambda x: x[2], reverse=True)
for v, w, v_over_w in vw_tuple:
if w < capacity:
... |
import sys
sys.setrecursionlimit(200000)
def toposort(adj):
visited = [False] * len(adj)
post_order = []
def explore(_x):
visited[_x] = True
for _neighbor_of_x in adj[_x]:
if not visited[_neighbor_of_x]:
explore(_neighbor_of_x)
post_order.append... |
from sys import stdin
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current * current
return sum % 10
def get_fibonacci_huge_fast(n, m):
... |
i = 0
total = 0
while True:
total = total + i
if i == 100:
break
i = i + 1
print(total)
|
list = [0, 1, 2, 3, 4, 5]
def length(list):
return len(list)
|
def calculator(grade):
if grade > 90:
return 'A'
elif 80<grade <= 90 :
return 'B'
elif 70<grade <= 80 :
return 'C'
elif 60<grade <= 70 :
return 'D'
def calculate(grade):
if grade > 90:
return 'A'
elif 80 < grade <= 90:
return 'B'
elif... |
import sys
def print_header(file):
file.write("<!DOCTYPE html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title>periodic table</title>\n\t</head>\n\t<body>\n")
def print_end(file):
file.write("\t</body>\n</html>")
def print_line(out_file, periodic_table, space_1=0, nb_elem_1=0, spac... |
import turtle
turtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.forward(50)
turtle.pendown()
turtle.forward(100)
turtle.backward(... |
from sqlite.interfaces import ToSQLInterface
import sqlite3
import pandas
class SetUpSQL(ToSQLInterface):
'''this class initializies sqlite connection to sqlite3 and creates database if none exists, it has convert_to_sql method which opens csv files and converts it sql'''
def __init__(self):
self.conne... |
l = [1,1]
ll = []
s = sorted(l)
print(s)
for x in s:
if x > len(s):
break
if len(s) == 1:
ll.append(s+1)
else:
for y in range(1,len(s)+1):
if y not in s:
ll.append(y)
print(ll)
|
l = [2,0,2,1,3,1,0]
mini = l.count(min(l))
print(mini)
maxi = l.count(max(l))
print(maxi)
print(str(min(l))*mini)
print(str(max(l))*maxi)
|
ll = []
def list_of_multiples(x,y):
for z in range(1,y+1):
ll.append(x*z)
print(list_of_multiples(7,5))
print(ll)
|
if __name__=='__main__':
a = 1
s ='1221121221221121122'
one = ''
for x in range(0,len(str(a))):
one+=s[x]
print(one.count('1'))
|
l = [4,3,2,1]
z = ''
l1 = []
for x in l:
z = str(z)+str(x)
print(z)
add = int(z)+1
for y in str(add):
l1.append(y)
print(l1)
|
if __name__=='__main__':
s = 'aacabdddd23'
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
lo = ''
up = ''
num = ''
move = 0
if len(s)>=6 and len(s)<=20:
for x in s:
if x in lower_case:
... |
if __name__ == '__main__':
a = str(13)
c=0
for i in range(1,int(a)+1):
if '1' in str(i):
c+=1
print(i)
print(c)
|
s = 'LRUD'
y = 0
z = 0
for x in s:
if x == 'U':
y+=1
elif x == 'D':
y-=1
elif x == 'L':
z+=1
elif x == 'R':
z-=1
if y == z:
print('True')
else:
print('False')
|
if __name__ == "__main__":
l = (1,0,1,0,0)
z=0
m =0
last_index = -1
while True:
try:
last_index = l.index(z, last_index + 1)
print(last_index)
if last_index> l.index(1):
m = m +1
print("Max = "+str(m))
except ValueError:... |
'''
A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N.
There are M sweets that must be distributed to the prisoners.
The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending S),
and then, starting with some random S, dis... |
import sys
import re
def getInput():
inputString = input('Please enter the string to process')
if not inputString:
inputString='(id,created,employee(id,firstname,employeeType(id),lastname),location)'
return inputString
def isValid(inputString):
if inputString.count('(') != inputString.coun... |
""" was a[i] before?"""
a = input()
a = a.split()
before = set([])
for i in range(len(a)):
if set([a[i]]) & before != set([]):
print('yes')
else:
before.add(a[i])
print('no')
"""print (bool(a[0] == '1'))
print(before & '1')
a = [1, 2, 3, 1, 2, 3]
before = set([])
for i in range(len(a... |
import sys
"""
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
Find the second largest number in a list
"""
junk = input()
def secondLargest(arg):
dat = []
for line in arg:
dat.append(line)
dat = dat[0].split(' ')
i = 0
while i < len(dat... |
"""CIS 189
Author: Alex Rickels
Module 4 Topic 3 Assignment"""
def calculate_order(price, cash_coupon, percent_coupon):
if price < 10.00:
if (price - cash_coupon)*(1 - (percent_coupon / 100)) < 0:
return 5.95
else:
return round((((price - cash_coupon)*(1 - (per... |
import random
people_num = 7
number = random.randint(1,people_num)
print(number)
people_num = 6
number = random.randint(1,people_num)
print(number)
input("Press <Enter>") |
"""Player class which represents in game character"""
class player:
"""Initialize name attribute"""
def __init__(self, name, id):
self.name = name
self.id = id
self.location = ""
self.description = ""
self.isPlayer = true
def do_say(self, args):
pass
def... |
adj = input("Adjective: ")
verb1 = input("Verb: ")
verb2 = input("Verb: ")
famous_person = input("Famous Person: ")
noun1 = input("Noun: ")
noun2 = input("Noun: ")
place = input("Make a name for a place: ")
number = input("Number : ")
madlib = f"My time on earth is absolutely {adj}! All i want to do is {verb... |
a = [0, 0, 0]
a[0] = int(input())
a[1] = int(input())
a[2] = int(input())
a.sort()
if (a[2] < a[0] + a[1]):
print("YES")
else:
print("NO")
|
'''
projecteuler.net/problem=6
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of t... |
user_number = int(input('Введите число>>>'))
max_number = 0
while user_number > 0:
comparing_number = user_number % 10
if max_number < comparing_number:
max_number = comparing_number
user_number //= 10
else:
user_number //= 10
comparing_number = user_number % 10
print(max_number)... |
a,b,c=map(int,input().split())
if a>=b and a>=c:
print(a)
elif b>=c and b>=-a:
print(b)
else:
print(c)
|
n=int(input(""))
fact=1
if(n<=0):
print(fact)
elif(n==1):
print(fact)
if(n>1):
for i in range(1,n+1):
fact=fact*i
print(fact)
|
string=input("")
count1=0
for i in string:
if(i.isdigit()):
count1=count1+1
print(count1)
|
n=int(input(""))
sum1=0
for i in range(1,n+1):
sum1=sum1+i
print(sum1)
|
events = [i for i in dir(cv2) if 'EVENT' in i]
print(events)
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print(x, ', ' ,y)
font = cv2.FONT_HERSHEY_SIMPLEX
strXY = str(x) + ', ' + str(y)
cv2.putText(img, strXY, (x,y), font, 1, (255,0,0), 2)
cv... |
import re
string = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', string)
if match:
print('found', match.group())
else:
print('did not find')
match = re.search(r'pi+', 'piiig')
match = re.search(r'i+', 'piigiiii')
match = re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx')
match = re.search(r'\... |
import shelve, pyperclip, sys
mcb_shelf = shelve.open('mcb')
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
mcb_shelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 2:
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcb_shelf.keys())))
elif sys.argv[1] in m... |
import unittest
from collatz_conjecture import (
steps,
)
class CollatzConjectureTest(unittest.TestCase):
def test_zero_steps_for_one(self):
self.assertEqual(steps(1), 0)
def test_divide_if_even(self):
self.assertEqual(steps(16), 4)
def test_even_and_odd_steps(self):
se... |
"""
Depth First Search implementation on a binary Tree in Python 3.0
Working -
recursion calls associated with printing the tree are in the following order -
- print(1, "")
|- traversal = "1"
|- print(2, "1")
| |- traversal = "12"
| |- print(4, "12")
| | ... |
"""
Queues Implementation in Python 3.0 using deque module.
For implementations from scratch, check out the other files in this repository.
"""
from collections import deque
q = deque()
q.append(20)
q.append(30)
q.append(40)
print(q)
print(q.popleft())
print(q.popleft())
|
def solution(n, computers):
answer = 0
enumerated_link = enumerate(computers)
queue = []
current_queue = [enumerated_link.next()]
while len(current_queue) > 0:
queue += current_queue
return answer
count = [
solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]),
solution(3, [[1, 1, 0... |
def sum_of_array(arr1, arr2):
"""두 행렬의 덧셈을 구하라.
시간 복잡도:
arr1가 M x N 크기의 행렬이라고 할 떄 O(NM)
"""
return [sum_of_rows_in_arrays(arr1[row], arr2[row]) for row in range(len(arr1))]
def sum_of_rows_in_arrays(row1, row2):
return [row1[row] + row2[row] for row in range(len(row1))]
def test_sum_of_arra... |
import re
exponents = {'S': 1, 'D': 2, 'T': 3}
def dart_game(dart):
"""다트게임의 문자열이 주어지면 총점수를 반환하라.
"""
return mathematical_expression_to_score(
make_mathematical_expression(game_to_token(split_dart_game(dart))))
def mathematical_expression_to_score(mathematical_expressions):
total = 0... |
def welcome():
print('Welcome to the Calculator.')
def again():
again_input = input('''
Do you want to calculate again?
Press Y for YES and N for NO
''')
if again_input == 'Y':
calculate()
elif again_input == 'N':
print('Thank You for using Calculator')
else:
again()
def calculate():
opera... |
from pieces import *
class Board:
def __init__(self, white_type, black_type):
self.white = Player(1, white_type)
self.black = Player(-1, black_type)
self.board = self.init_board()
def __str__(self):
board_string = ''
for row in self.board:
board_string += ' '.join([str(c) for c in row])
board_st... |
import turtle
import os
wn = turtle.Screen()
wn.title("Pong version ..::HC::..")
wn.bgcolor("red")
wn.setup(width=1000, height=700)
wn.tracer(0)
score_a = 0
score_b = 0
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("black")
paddle_a.shapesize(stretch_len=1, stretch_w... |
"""
Programa para obtener serie Fibonacci usando recursividad
CLUB ALGORITMIA UPIITA
Aaron Merlos
"""
def fibonacci(posicion):
if posicion==0:
return 0
elif posicion==1:
return 1
return fibonacci(posicion-1)+fibonacci(posicion-2)
if __name__ == '__main__':
... |
a_candi = [x for x in range(-1000, 1000) if x % 2 != 0]
b_candi = [x for x in range(-1000, 1000) if x % 2 != 0]
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
else:
return True
else:
return False
number_pr... |
import random
import itertools
class Card:
def __init__(self, name, color):
self.name = name
self.color = color
class Deck:
def __init__(self):
self.newDeck = []
self.colors = ['C', 'D', 'H', 'S']
self.numbers = [i for i in range(1,14)]
def MakeNewDeck(self):
... |
"""
This is to handle the games enemies
"""
import pygame
class enemies(object):
def __init__(self, pos):
from config import mobs
self.position = (pos[0], pos[1])
self.rect = pygame.Rect(self.position[0], self.position[1], 32, 32)
mobs.append(self)
self.health = 100
... |
def ant_time(locs, wood_len,speed):
"""
求所有蚂蚁都离开木杆的最短时间和最长时间
:param locs: 蚂蚁的初始位置
:param wood_len: 木杆的长度
:param speed: 蚂蚁爬行速度,厘米/秒
:return: 最短时间 最长时间
"""
min_distance = []
max_distance = []
for loc in locs:
min_distance.append(min(loc, wood_len - loc))
max_di... |
from pydantic import BaseModel, ValidationError, validator
class UserModel(BaseModel):
name: str
username: str
password1: str
password2: str
@validator('name')
def name_must_contain_space(cls, v):
print('name_must_contain_space-v:', v)
if ' ' not in v:
raise ValueE... |
import math
class Solution:
@classmethod
def judge_square_sum(cls, target):
if target < 0:
return False
i, j = 0, int(math.sqrt(target))
while i < j:
res = i * i + j * j
if res == target:
print(i, j)
return True... |
"""
问题定义
有如下 8 x 8 格子,机器人需要从开始位置走到结束位置,每次只能朝右或朝下走,粉色格子为障碍物,机器人不能穿过,
问机器人从开始位置走到结束位置最多共有多少种走法?
"""
from pprint import pprint
mat = [
[0] * 8,
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0... |
from threading import Thread, Lock
class Singleton(type):
def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
cls.__instance = None
def __call__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__call__(*args, **kwargs)
r... |
import time
from threading import Thread, Condition
li = list(range(1, 101))
cond = Condition()
class Consumer01(Thread):
def __init__(self, name, nums, con):
Thread.__init__(self)
self.name = name
self.nums = nums
self.con: Condition = con
def consumer(self):
self.co... |
"""
Though the interface of the two modules is similar, the two modules have very different implementations.
All the threads share global variables, whereas processes are completely separate from each other.
Hence, killing processes is much safer as compared to killing threads. The Process class is provided a metho... |
my_list = ["apple", 5.2, "dog", 8]
def combiner(my_list):
strlist = ""
numlist = 0
for items in my_list:
if isinstance(items, str):
strlist += items
else:
numlist += items
print(strlist + str(numlist) )
return strlist + str(numlist)
... |
import random
import os
WORDS = (
"treehouse",
"python",
"learner")
def prompt_for_words(challenge):
guesses = set()
print("What words can you find in the word '{}'".format(challenge))
print("(Enter Q to Quit)")
while True:
guess = input("{} words >. ".format(len(guesses)))
... |
a = b = c = d = 12
print(c)
a, b = 12 , 13
print(a, b)
a, b = b, a
print(" a is {}".format(a))
print("b is {}".format(b)) |
import random
highestNumber = 10
answer = random.randint(1, highestNumber)
print("Enter the number betweeen 1 and {}".format(highestNumber))
guess = 0
while guess != answer:
guess = int(input())
if guess > answer:
print("please Select Lower Number")
elif guess < answer:
print("Pl... |
from item import Item
class Player:
def __init__(self, name, current_room, items):
self.name = name
self.current_room = current_room
self.items = items
def move(self, d):
if d == 'n' and self.current_room.n_to:
self.current_room = self.current_room.n_to
... |
from random_word import RandomWords
def guessing_game():
'''returns a random integer between 1 and 100'''
r = RandomWords()
return r.get_random_word()
if __name__ == '__main__':
print('Hmmmm.... let me pick a word')
word = guessing_game()
guess = input(f"Guess the word ({len(word)}... |
import time
running=True
start_time=time.time()
print("start_time{}".format(start_time))
while running:
now_time=time.time()
print("now_time{}".format(now_time))
second_depends=now_time-start_time
print("second_depends{}".format(second_depends))
if second_depends==3:
start_time=now_time
... |
print ("hurry makes a bad curry")
print("{1} makes a bad {0}".format("curry","hurry"))
print("The {e} rotates {a} a {s}".format(e="Earth",a="around",s="Sun"))
result=9/5
print(result)
result=100/3
print(result)
print("the result is {r:1.4f}".format(r=result))
celsius=((132-32)*5)/9... |
sum =0
for n in range (1, 1000):
if(n%3==0 or n%5==0):
sum += n
print("Sum is", sum)
|
class Player:
def __init__(self,name,age,height):
self.age=age
self.name=name
self.height=height
def IncreaseAge(self):
self.age+=1
def PrintInformation(self):
print("This is {0}, he is {1} years old and {2} cm.".format(self.name,self.age,self.height))
player1=Player("Jhon",20,170)
player1.IncreaseAge(... |
l=['hola','Hello','konnitiwa','hallo']
for element in reversed(l):
print(element)
quit()
for i in range(len(l)-1,-1,-1):
print(l[i])
|
'''
Connection data to MongoDB using pymongo lib
'''
import os
from pymongo import MongoClient
def connect_mongo(data, collection, content):
myclient = MongoClient("mongodb://localhost:27017/")
db = myclient[data]
Collection = db[collection]
if isinstance(content... |
import csv
with open('names.csv','r') as csv_file:
csv_reader=csv.DictReader(csv_file)
with open('new_file.csv','w') as new_file:
fieldnames = ['first_name','last_name']
csv_writer=csv.DictWriter(new_file,fieldnam... |
lst_1 = [1, 2, 3, [1, 2], 2, [1, [1, 3]], 20]
print(lst_1)
str_1 = str(lst_1)
str_2 = str_1.replace('[', '')
str_3 = str_2.replace(']', '')
str_4 = str_3.replace(',', '')
str_5 = str_4.replace(' ', '')
lst_3 = []
for elem in str_5:
elem = int(elem)
lst_3.append(elem)
prin... |
num_of_rows = int(input('Enter the quantity of rows(colums) :'))
player_1 = input('Player 1, Please, enter your name: ')
player_2 = input('Player 2, Please, enter your name: ')
game_board_coord = {}
GBC = game_board_coord
max_number_way = num_of_rows**2
ways_counter = 0
def game_board_init(num_of_rows):
for x in ra... |
def main():
x1 = 5
y1 = 6
x2 = 8
y2 = 9
slope = (y2 - y1)/(x2 - x1)
print("Slope is ", round(slope))
main() |
my_list=["192.168.0.5", 5060, "UP"]
print("The first item in the list (IP): " + my_list[0])
print("The second item in the list (port): " + str(my_list[1]))
print("The last item in the list (state): " + my_list[2])
iplist= [5060, "80", 55, "10.0.0.1", "10.20.30.1", "ssh"]
print("IPs are as follows:" , iplist[3... |
items = ['biscuit', 'bed', 'desk', 'biscuit', 'books', 'computer', 'biscuit']
for i in items:
if i == 'biscuit':
print("SLAP!")
|
class Freq:
"""
频率
"""
def __init__(self, value=0.0):
self.value = value
def change_freq(self):
new = self.value
if self.value == 1700:
new = 2300
elif self.value == 2000:
new = 2600
elif self.value == 2300:
new = 1700... |
def chunkify(lst, n):
"""Given a list of a number n, yield consecutive chunks of size n."""
for pos in range(0, len(lst), n):
yield lst[pos:pos + n]
def hex_to_ints(hex_string):
"""Converts the hex string to a list of ints by converting chunks of 2 chars to int."""
return [int(chars, 16) for c... |
def area_of_rectangle(length, width):
"""
This function calculate the area of a rectangle
:param length: length of long side of rectangle
:param width: length of small side of rectangle
:return: area
"""
area = length * width
return area
|
import tensorflow as tf
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b
"""
Constants are initialized when you call tf.constant, and their value can never change. By contrast, variables are not
initialized when you call tf.Variable... |
n=int(input())
def arms(n):
sum = 0
temp = n
while temp > 0:
digit=temp % 10
sum+=digit ** 3
temp //= 10
if (n == sum):
print(n,"is Armstrong number")
else:
print(n,"is not Armstrong number")
arms(n)
|
rec={}
n=(int(input('enter no of students:')))
i=1
while i<=n:
name=input('enter the student name:')
marks=input('enter the %of the student')
rec[name]=marks
i=i+1
print('name of student','\t','% of marks')
for x in rec:
print('\t',x,'\t\t',rec[x])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.