text stringlengths 37 1.41M |
|---|
def gcd(a,b):
a = abs(int(a))
b = abs(int(b))
if b > a:
a, b = b, a
# @@@@@@ very good to know! a,b = b,a !!
while b != 0:
new_a = b
new_b = a % b
a = new_a
b = new_b
return new_a
def main():
a = (input("Enter your first value: "))
whi... |
def gcd(a,b):
if a < b:
a,b = abs(b),abs(a)
if b == 0:
return a
return gcd(b,a%b)
def main():
int1 = int(input("Enter first integer value: "))
int2 = int(input("Enter second integer value: "))
print("Your integers are {0} and {1}, and their GCD is {2}.".format(int1,int2,gcd(int... |
def mine_convert(s,numRows):
if numRows == 1:
return s
else:
keynum = 2 * numRows - 2
mystrings = [""] * numRows
myanswer = ""
rows = 1
while rows <= numRows:
for each_index, each_value in enumerate(s):
... |
"""
This is not my answer,
I tried, but I failed to pass this question.
I brought the best answer as future reference to learn.
The main explanation is provided as follow:
"""
"""
The main idea is to iterate every number in nums.
We use the number as a target to find two other numbers which make total zero.
For those... |
from FINAL.funciones_final import *
#main
print("\n ----------------------"
"\n -Welcome to the Game--"
"\n ----------------------")
#colocacion automatica de los barcos
user_tab.colocacion_automatica()
machine_tab.colocacion_automatica()
print("This is your board with your boats generated automatical... |
import unittest
# f(0) = [0]
# f(1) = [0,1]
# f(n+1) = duplicate(f(n))
class Solution:
# @param A, a list of integer
# @return an integer
def hasCycle(self, head):
node = head
node2 = head
while node != None:
node = node.next
if node2 == None:
return False
else:
node2 = node2.next
i... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
self.sum = 0
if root == None:
... |
import unittest
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
first = 0
second = 1
for i in range(n):
first, second = second, second + first
return second
class SolutionTest(unittest.TestCase):
"""docstring... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import unittest
class Solution:
# @param root, a tree node
# @return a list of integers
def levelOrder(self, root):
self.valMap ={}
... |
class Solution1(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
self.coins= sorted(coins, reverse=True)
maxCnt = amount/coins[-1] + 1
self.length = maxCnt
if amount == 0:
re... |
#Line 18: RuntimeError: maximum recursion depth exceeded in cmp
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if nums == []:
return True
self.travel = ['u'] * len(nums)
self.nums = nums
self.len... |
import random
def main():
dicerolls = int(input('How many dice would you like to roll? '))
dice_size = int(input('How many sides are the dice? '))
sum = 0
for i in range (0, dicerolls):
roll = random.randint(1, dice_size)
sum += roll
if roll == 1:
print(f'You rolled ... |
person = {"name": "Eli", "email": "a@ja.com", "number": 1234567}
all_contacts =[]
all_contacts.append(person)
print(all_contacts)
name = str(input("Enter name:"))
while len(str(name)) > 20 or len(str(name)) < 3 or len(str(name)) == 3:
name = str(input("Invalid name. Re-enter name(more than 2 letters): "))
email =... |
"""
Script to evaluate the predictions
(based on the code submission Text Mining Domains
Van der Ende, Buckens and Den Uijl 2020-2021 VU Amsterdam)
"""
import argparse
import sys
import os
import pandas as pd
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
def read_data... |
import random
#Selection sort is when you take the smallest element in an unsorted array and bring it over to the sorted side, then go back to the unsorted side and bring the next smallest element in the unsorted array and then keep repeating the process until the last index is reached in the unsorted array.
def sele... |
def hhmmss2sec( hours, minutes, seconds ):
"""Given a hour value in th eformat hh:mm:ss convert it to the amount of seconds"""
if checkHourRange( hours ) == False:
return -1
elif checkMinutesSecondsRange( minutes ) == False:
return -1
elif checkMinutesSecondsRange( seconds ) == False:
return -1
else:
resu... |
"""Graphs in python."""
# Author: Daniel Dahlmeier <ddahlmeier@gmail.com>
from abc import ABCMeta, abstractmethod
import numpy as np
import random
from itertools import chain
from operator import itemgetter
import heapq
def unique(iter):
"""Helper class to return list of unique items in iter"""
return list(... |
# split the string into two and count the total values. If they're equal return true else false
class Solution:
def halvesAreAlike(self, s: str) -> bool:
n = len(s)
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
l_count = 0
for i in range(0, int(n / 2)):
if s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 13:20:25 2021
@author: eshasharma
"""#
# import csv and random libraries
import csv
import random
# for random example
from datetime import datetime
# Introductin to csv library and dict reader
with open('BanditsData.csv', n... |
#https://www.codewars.com/kata/511f11d355fe575d2c000001/train/python
def two_oldest_ages(ages):
'''
oldest = []
oldest.append(max(ages))
ages.pop(ages.index(max(ages)))
if oldest[0] in ages:
oldest.append(max(ages))
else:
for a in ages:
if max(ages) not in oldes... |
import random
from .deck import Card
# Base Player
class Player:
# Who is sitting next to the player
left_player = None
right_player = None
# Card Chosen for the Round
card_chosen = None
# Is the player eliminated
eliminated = False
# Has the player won
is_winner = False
def __init__(self, win_threshold... |
N = int(input())
print('{:.3f}'.format(sum([i/(i*2-1) if i%2==1 else -i/(i*2-1) for i in range(1,N+1)])))
|
from random import randint
t = ["r","s","p"]
computer = t[randint(0,2)]
player = "y"
name = input("enter your name: ")
print("type reset if you want to reset the score: ")
you = 0
pc = 0
def win():
global you
you+=1
print(message)
print("computer:",pc,"\n",name,":",you)
def lose():
global pc
pc+=1
... |
import sqlite3
sqlite_file = 'sql_test.db'
table_name1 = 'my_table_1'
table_name2 = 'my_table_2'
new_field = 'my_first_column'
field_type = 'INTEGER'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute('CREATE TABLE {tn} ({nf} {ft})'\
.format(tn=table_name1, nf=new_field, ft=field_type))
c.execu... |
names = ['Demi', 'Victoria', 'Carmen', 'Myat', 'Nico']
boys = ['Shaun', 'Brian', 'Krishna', 'Patrick']
print(names+boys)
print(names.extend(boys)) #old list changes
print(names.append(boys))
def capitalize_all(t):
result = []
for word in t:
result.append(word.capitalize())
return result
names = ... |
class Sweetgreens:
"""
represents a sweetgreens list
attributes: vegetable, grain, protein, standard topping, premium topping, bread
"""
def __init__(self, vegetable = [], grain='wild rice', protein='chicken', standard='tomatoes', premium='corn', dressing='vinegar', bread='wheat'):
self.ve... |
import turtle
import math
#SHAPE 1
shape1 = turtle.Turtle()
print (shape1)
def polygon(t, length, n):
for i in range(n):
t.fd(length)
t.lt(360/n)
def circle(t, r):
circumference = 2 * math.pi * r
n = 100
length = circumference / n
polygon(t,length, n)
circle (shape1, 100)
def arc(t, ... |
# list of DNA combinaisons.
def mkstr(prefix):
if len(prefix) == 4:
return [prefix]
combs = []
combs.extend(mkstr(prefix + "A"))
combs.extend(mkstr(prefix + "T"))
combs.extend(mkstr(prefix + "G"))
combs.extend(mkstr(prefix + "C"))
return combs
letters = ""
ATGC_comb = mkstr(letters... |
my_name = 'Joe Shuttlewood'
my_age = 26
my_height = 6*12+2 #Hopefully this will put my height in to inches for me. Yep, it works!
my_weight = 200
my_eyes = 'blue'
my_hair = 'blonde'
is_heavy = my_weight > 3000 #when I use this variable further on this will return 'False'. Flattering.
my_height_in_cm = my_height * 2.5
m... |
annual_salary = float(input("Enter your annual salary: "))
monthly_salary = annual_salary / 12
total_cost = 1000000
portion_deposit = total_cost * 0.25
current_savings = 0
semi_annual_raise = 0.07
r = 0.04
epsilon = 100
months = 0
low = 0
high = 10000
limit = 36
savings_percent = (low + high) / 2.0
iterations = 0
for ... |
# Similar code for logistic regression
import torch
import torch.nn.functional as F
x_data = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y_data = torch.tensor([[0.0], [0.0], [1.0], [1.0]])
# Step 1. define network parameters and forward, it's still linear layer, but for regular NN logistic reguression, there is ac... |
dic = {'b':3, 'a':1, 'c':2}
sorted(dic.items())
# [('a', 1), ('b', 3), ('c', 2)]
sorted(dic.items(), key=lambda x:x[1])
# [('a', 1), ('c', 2), ('b', 3)]
sorted(dic.items(), reverse=True)
# [('c', 2), ('b', 3), ('a', 1)]
sorted(dic.items(), key=lambda x:x[1], reverse=True)
# [('b', 3), ('c', 2), ('a', 1)]
|
x = int(input("Enter an Integer: "))
if (x%2) != 0:
print ("Odd")
elif (x%2) == 0:
print("Even")
|
import math
h = float(input("Enter in Height(cm)"))
M = float(input("Enter in Mass(kg)"))
m = M
h = h / 100.0
V = M / 1000
r = math.sqrt(float(V/(h*math.pi)))
waist_line = 2*math.pi*r
waist_line_inch = 100 * waist_line * 0.39
print (waist_line_inch) |
"""
Program: investmentGUI.py
Alexa Caridi 4/28/2020
GUI-based investment program
1.Inputs:
starting investment amount
number of years
interest rate (an integer %)
2.The report is displayed in tabular format
3.Compute interst for each year and add it to the investment
4.Display the ending invest... |
#!/usr/bin/python
numbers=range(1,101)
def factorial (n):
fact = 1;
numbers = range(1,n+1)
for i in numbers:
fact = fact * i
if n == 1:
return 1
else:
return fact
N=factorial(100)
sum=0
while N>1:
dig=N % 10
sum = sum + dig
N = (N-dig)/10
print "ANSWER=",sum
|
human = 'choyeaeun'
age = 24
print('hello world', 'my name is', human, 'my age is', age)
human = 'ohhyunji'
age = 25
print('hello world', 'my age is', age, 'my name is', human)
#주석 처리는 이렇게
"""
긴 주석은 이렇게 처리
""" |
# 튜플은 소괄호로 선언하며, 값의 변경과 삭제가 불가능
# 튜플 선언
tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3, 4
print(tuple1)
print(tuple2)
# 리스트를 튜플에 넣을 수도 있음
list1 = [4, 5, 6, 7]
tuple3 = tuple(list1)
print(tuple3)
# packing, unpacking : 여러 개의 값을 한 번에 변수에 넣을 수 있다
c = (3, 4)
a, b = c
print(a) # 3
print(b) # 4
# temp없이 바로 두 개의 값 바꾸기 가능
amy = 10
b... |
#function to left rotate array of size s by n
def rotateArray(array, s, n):
for i in range(s):
rotateByOne(array, n)
#function to left rotate array of size s by 1
def rotateByOne(array, n):
tempArray = array[0]
for i in range(n - 1):
array[i] = array[i + 1]
array[n - 1] = temp... |
#python math
# arithmetic operators
# + plus addition
# - minus subtraction
# * times multiplication
# / divided by division
# ** power exponentiation
print 12, -3, 3.14159, -1.8 #prints 12 -3 3.14159 -1.8
print type(1), type(3.14159), type(2.0) # prints <type 'int'> <type 'float'> <type 'float'>
print ... |
users = {
"omer": {
"level": 7
},
"yusuf": {
"level": 4
},
"esra": {
"level": 1
}
}
name = "omer"
for i, j in users.items():
if i == name:
print(j["level"])
|
from .. import util
class Point:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def step(self):
self.x += self.dx
self.y += self.dy
def step_backwards(self):
self.x -= self.dx
self.y -= self.dy
def __... |
from tree import TreeNode
def search_name(root_node, goal_value, path=()):
path = path + (root_node,)
if root_node.value == goal_value:
return path
for child in root_node.children:
path_found = search_name(child, goal_value, path)
if not path_found == None:
retur... |
class Node(object):
def __init__(self,value = None):
self.value = value
self.left = None
self.right = None
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self,left):
self.left = lef... |
"""
The flag of the Netherlands consists of three colors: red, white and blue.
Given balls of these three colors arranged randomly in a line (the actual number of balls does not matter),
the task is to arrange them such that all balls of the same color are together
and their collective color groups ... |
def arraysIntersection(arr1, arr2, arr3):
"""Given three sorted arrays strictly increasing order, return a sorted array of only the integers
that appeared in all three arrays.
For example:
>>> arraysIntersection([1,2,3,4,5], [1,2,5,7,9], [1,3,4,5,8])
[1, 5]
"""
# i = 0
... |
"""
Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
(i.e., buy one and sell one share of the stock multiple times).
"""
def maxProfit(prices):
"""... |
import random
lista = ['piosenka1', 'piosenka2', 'piosenka3']
losowy_element = random.choice(lista)
print(losowy_element)
for i in range(2):
losowy_element = random.choice(lista)
print(losowy_element)
losowa_lista = random.sample(lista, 2)
print(losowa_lista)
|
def main():
from sys import stdin, stdout
t = int(input())
for i in range(0, t):
s = input()
mid = (len(s) + 1) // 2
first = ''.join(sorted(s[:mid - (len(s)%2)]))
second = ''.join(sorted(s[mid:]))
if first == second:
print('YES')
else:
... |
# 比较不同类别精灵属性值分布 查看双变量数据分布 查看变量间的关系
# seaborn 盒形图 双变量图 相关系数
# 如果有多个画图 运行程序时 每个图的show()不能少 不然容易最后都画到一张图上面
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data_path = 'C:\\Users\\shine小小昱\\Desktop\\data_pd\\pokemon.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'
def collect_... |
# 进程由进程创建 被创建的进程是子进程 每个进程执行自己的任务 互不干扰 进程有属于自己的进程编号 标示着从属关系
# 进程间的内存空间各自独立 比较稳定 消耗内存
from multiprocessing import Process, cpu_count, Queue
import os
import time
# 死循环任务1
def print_A(word, que):
i = 1
while True:
time.sleep(4)
print(word)
print(f'正在执行的子进程号:{os.getpid()}'... |
# 统计不同专业背景的员工的平均薪资,并用柱状图显示结果
import pandas as pd
import matplotlib.pyplot as plt
data_info_path = 'C:\\Users\\shine小小昱\\Desktop\\data_employee\\employee_info.csv'
data_edu_path = 'C:\\Users\\shine小小昱\\Desktop\\data_employee\\employee_edu.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'
def collect_... |
# Problem 21
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called
# amicable numbers.
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 4... |
def showOdds(last):
n = int(last) + 1
print("All odd numbers are given below:")
sumOfOdds = 0
for i in range(1, n, 2):
print(i, end = " ")
sumOfOdds += i
print()
return sumOfOdds
value = input("Enter a number: ")
result = showOdds(value)
print("Sum of the following numbers: " +... |
import random
def burbuja(A):
n = len(A)
for i in range(1, n):
for j in range(0, n - i):
if A[j] > A[j + 1]:
swap(A, j, j + 1)
def swap(A, i, j):
tmp = A[i]
A[i] = A[j]
A[j] = tmp
'''
def burbuja_optimizado2(A):#La optimizacion del algoritmo burbuja es que simple... |
"""
후위표기볍 연산하는 알고리즘 미리 생각해보기
인자 = '3+4*2-4/2'를 str으로 넣고 for문 돌려서 i가 연산자, 괄호가 아니면 int로 casting해서 answer.append(i)하기.
연산자 만났는데, 우선순위 비교하고 opStack.pop() 하는 곳에
if oper == '*':
K = answer.pop(-2) * answer.pop(-1)
answer.append(K)
elif oper == '/':
K = answer.pop(-2) / answer.pop(-1)
answer.append(K)
elif oper == '+':
K = an... |
import time
def rec(n):
if n <=1:
return n
else:
return rec(n-1) + rec(n-2)
def iter(n):
a = 0
b = 1
count = 0
if n<=1:
return n
else:
while count < n-1:
count +=1
c = b + a
a = b
b = c
return b #return... |
# 作业背景:在数据处理的步骤中,可以使用 SQL 语句或者 pandas 加 Python 库、函数等方式进行数据的清洗和处理工作。
# 因此需要你能够掌握基本的 SQL 语句和 pandas 等价的语句,利用 Python 的函数高效地做聚合等操作。
# 请将以下的 SQL 语句翻译成 pandas 语句:
import pandas as pd
import os
pwd = os.path.dirname(os.path.realpath(__file__))
data_file = os.path.join(pwd,'data.csv')
df = pd.read_csv(data_file)
# 1. SELE... |
# 区分以下类型哪些是容器序列哪些是扁平序列,哪些是可变序列哪些是不可变序列:
# list - 容器序列, 可变序列
list_a = [1, 'a']
list_b = list_a
print(list_b is list_a) # True
list_a[1] = 'b'
print(list_b is list_a) # True
# tuple - 容器序列, 不可变序列
tuple_a = tuple([1, 'a'])
try:
tuple_a[1] = 'b' # TypeError
except TypeError:
print('tuple object does not suppor... |
def raisetest():
try:
integer = int(input('2의 배수를 입력하세요 : '))
if (integer % 2) != 0:
raise Exception('2의 배수가 아닙니다.')
print(integer)
except Exception as e:
print('raisetest 함수에서 예외가 발생했습니다.', e)
raise
try:
raisetest()
except Exception as e:
... |
import time,multiprocessing
print('Multithreads thread')
start = time.perf_counter()
def dosomething():
print("funtion sleeping zzzzzZZZZ")
time.sleep(1)
print("woke up")
p1 = multiprocessing.Process(target= dosomething)
p2 = multiprocessing.Process(target= dosomething)
p1.start()
p2.start()
## Join... |
import re
string = "My name is John, Hi I'm John"
pattern =r"John"
newstring = re.sub(pattern,"Rob",string)
print(newstring)
|
# Create a dictionary
# Access the items in dictionary
# Changing the value of specific item in a dictionary
# Print all the key names in the dictionary
# print all the values in a dictionary, one by one
# Using the values() function return all the values of the dictionary
# Loop through both keys an value, by us... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def display_board(val):
print(val[1]+ '|' + val[2]+ '|' + val[3])
print("------")
print(val[4]+ '|' + val[5]+ '|' + val[6])
print("------")
print(val[7]+ '|' +val[8]+ '|' +val[9])
# In[2]:
test_board = ['#','X','O','X','O','X','O','X','O','X']
d... |
# Ingreso de datos de triangulo 1
print("Ingrese datos del triangulo 1:\n")
lado1 = float (input ("Ingrese lado 1 del triangulo:"))
lado2 = float (input ("Ingrese lado 2 del triangulo:"))
lado3 = float (input ("Ingrese lado 3 del triangulo:"))
ang1 = float (input ("Ingrese angulo 1 del triangulo:"))
ang2 = float (input... |
from coin import Coin
import matplotlib.pyplot as plt
import os.path
import pathlib
class Game:
def __init__(self):
self.coin = Coin(0.4)
self.goal = 100
self.discount_rate = 1
self.epsilon = 0.000001
self.value_archive = []
self.action_archive = []
@staticm... |
class SimActLocation:
"""
Structure-like class used to bundle the instruction address and statement index of a given SimAction in order to
uniquely identify a given SimAction
"""
def __init__(self, bbl_addr: int, ins_addr: int, stmt_idx: int):
self.bbl_addr = bbl_addr
self.ins_addr ... |
from typing import Set
from collections import defaultdict
import ailment
class Goto:
"""
Describe the existence of a goto (jump) statement. May have multiple gotos with the same address (targets
will differ).
"""
def __init__(self, block_addr=None, ins_addr=None, target_addr=None):
"""
... |
'''Example script to generate text from Nietzsche's writings.
At least 20 epochs are required before the generated text
starts sounding coherent.
It is recommended to run this script on GPU, as recurrent
networks are quite computationally intensive.
If you try this script on new data, make sure your corpus
has at le... |
# purpose is to find the 'stationary number'
# stationary number = number that will be the same regardless how many times it goes through loop
# div_13 sequence: [1, 10, 9, 12, 3, 4]
# eventually recursive calls should yield n = total = stationary number
def thirt(n):
total = 0
a = [int(x) for x in str(n)]
... |
# works for most cases, except case where there is inner solution
# example ([5,3,7,5], 10) returns [5,5] when [3,7] is solution
def sum_pairs(ints, s):
for i in range(0,len(ints)):
for j in range(i+1,len(ints)):
if ints[i] + ints[j] == s:
return [ints[i],ints[j]]
return None... |
nombre = int(input())
nombre += 1
print(nombre)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
import game
def saisieCoup(jeu):
""" jeu -> coup
Retourne un coup a jouer
"""
print("Les coups valides sont:")
print(str(game.getCoupsValides(jeu)))
i= int(input("Entrer la colonne du coup à jouer:... |
def WriteArrayToFile (array, filename = 'result.txt'):
''' This procedure takes a name of a file and writes to it an array of data'''
f = open(filename, 'w')
'''for revstep in array:
strarray = []
for pos in revstep:
sign = ''
if pos > 0:
sign = '... |
def ChromosomeToCycle(Chromosome):
'''Chromosome is a sequence of synteny blocks in format [-3, +1, +2]
Return its representation of nodes [6, 5, 1, 2, 3, 4]'''
nodes = []
for el in Chromosome:
if el > 0:
nodes.append(el*2-1)
nodes.append(el*2)
else:
... |
import HammingDistance as HD
def ApproximatePatternCount(Text, Pattern, dist):
'''Finds in Text all Patterns and similar patterns of distance <-dist'''
count = 0
k = len(Pattern)
for i in range(len(Text) - k + 1):
if HD.HammingDistance(Text[i: i + k], Pattern) <= dist:
count +=1
... |
#!/usr/bin/python
#coding:utf8
from algorithms.common.sortbase import Key, IntNode, SortBase
class SelectionSort(SortBase):
@staticmethod
def sort(a):
length = len(a)
for i in range(length):
#将首号元素标记位最小
min_index = i
#从下一个元素开始遍历记录最小的索引
for j in ... |
# Title: Computing Pi Using Archimedes' Method
# Author: Lisa Carpenter
'''Abstract: This program computes the value of pi to within 3 decimal places. The method used will be to calculate the perimeters of two polygons, one polygon circumscribed about the circle and the other inscribed in the circle. The number of s... |
# Chaotic Behavior of Pendula
# Author: Lisa Carpenter
'''Abstract: A driven and damped pendulum will exhibit chaotic behavior if
initial conditions are set appropriately. The chaotic behavior is investigated
by modeling the behavior of two pendula with slightly different initial
conditions. The value for theta as a f... |
"""
Rules of Life
- Death
If there is no surrounding unit alive then die
"""
import random
import time
import sys
from colorama import Fore, Style
size = None
spawn = None
def usage():
print("Usage: game.py size spawn")
def main():
global size
global spawn
if len(sys.argv) < 3:
usag... |
import time
num=input("Ramdeni Procentit Ginda Rom Ikos Kle( Es Sxvas Ar Anaxo Ubralod Utiteb ): ")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
name = input("Klis Procentis Damtvleli. Chaweret Saxeli: ")
print("Vitv... |
#Enter a 4-digit number and print its reverse.
n=int(input("Enter a no.(4-digit):"))
a=3
temp=0
ans=0
while a>=0:
temp=n%10
n=n//10
ans=ans+(10**a)*temp
#print("temp=",temp)
#print("n=",n)
#print("ans=",ans)
a=a-1
print("The reverse no.=",ans)
|
import sys
class stack:
def __init__(self):
self.stack =[None]*100
self.top=-1
def isFull(self):
if self.top==100:
return True
else:
return False
def isEmpty(self):
if self.top==-1:
return True
return Fa... |
def majorityElement(nums):
count = 0
count1 = 0
for i in range(len(nums)):
if(count ==0):
m = nums[i]
count += 1
else:
if m == nums[i]:
count += 1
else:
coun... |
# COMPULSORY TASK - JHB Metro Police Demerit
your_speed = int(input("What was your average speed in km/h: "))
average_speed = int(input("What was the allowed speed on the road: "))
diff = your_speed - average_speed
if your_speed <= average_speed:
print("Ok!")
else:
point = diff/5
point = int(point)
pri... |
class SymbolEntry:
def __init__(self, line, is_int, is_pointer = None, value = None):
self.is_int = is_int
self.is_pointer = is_pointer
self.values = []
self.values += [(line, value)]
# Returns corresponding type
def get_type(self):
return (self.is_int, self.is_pointer)
# Returns corresponding value
de... |
#!/usr/bin/python3
def max_integer(my_list=[]):
if len(my_list) == 0:
return None
max_value = my_list[0]
for i in my_list:
if i > max_value:
max_value = i
return max_value
|
#!/usr/bin/python3
"""
function that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
def text_indentation(text):
"""
function that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
if type(text) != str:
raise TypeError('text must b... |
#!/usr/bin/python3
def uniq_add(my_list=[]):
suma = 0
new_list = sorted(my_list[:])
for i in range(len(new_list)):
if i == 0:
suma += new_list[i]
elif new_list[i] != new_list[i - 1]:
suma += new_list[i]
return suma
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Tianyanfei
# @Mail : tyfdream@163.com
# @Data : 2016-11-24 16:17:48
# @Version : python 2.7
import os
# 判断一个unicode是否是汉字
def is_chinese(uchar):
if u'\u4e00' <= uchar<=u'\u9fff':
return True
else:
return False
# 判断一个unic... |
"""
Tasks
-------
Search and transform jsonable structures, specifically to make it 'easy' to make tabular/csv output for other consumers.
Example
~~~~~~~~~~~~~
*give me a list of all the fields called 'id' in this stupid, gnarly
thing*
>>> Q('id',gnarly_data)
['id1','id2','id3']
Observations... |
class Light(object):
def __init__(self,Direction,GreenTime):
self.Direction = Direction #there are 2 light objects, one for the horizontal lanes and one for the vertical lanes
self.GreenTime = GreenTime
self.YellowTime = 6
self.RedTime=GreenTime+6
#def DetermineState(StartsGreen,(x+1)%((self.GreenTime+6)*2)... |
class Lane(object):
def __init__(self):
print("Lane created.")
self.carqueue=[]
'''def MoveCar(self,LightStatus):
#cars follow one set of rules with a green light
#starting at the head of the queue and moving towards the tail, for each
for x,item in reversed(list(enumerate(self.car... |
# def permutations(items):
# n = len(items)
# if n == 0:
# yield []
# else:
# for i in range(len(items)):
# for cc in permutations(items[:i] + items[i + 1:]):
# yield [items[i]] + cc
# for p in permutations(['r', 'e', 'd']):
# print(''.join(p))
# for p in per... |
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 3000))
while True:
# prin... |
def bsearch(data,target):
if data!=[]:
top =0
bot=len(data)-1
while(top <=bot):
mid = ( top + bot )/2
if (data[mid]==target):
return mid
elif (data[mid]<target):
top=mid+1
... |
'''
11650 좌표 정렬하기
알고리즘 :
1. x, y를 하나의 리스트에 담고, 여러개의 x,y들을 coord라는 리스트에 담아서 sort() 함수 사용해 정렬
'''
N =int(input())
coord = []
for i in range(N):
a = list(map(int, input().split()))
coord.append(a)
coord.sort()
for i in range(len(coord)):
print(coord[i][0], coord[i][1])
|
'''
6549 히스토그램에서 가장 큰 직사각형
알고리즘:
(아직도 이해 잘 안간다. 나중에 다시 할 것)
1. 모든 직사각형의 높이들을 탐색
2. 스택에 자기의 높이보다 큰 높이가 없으면 stack 에 push
3. 스택의 top이 나보다 높거나 같으면, 그 높이 pop해서 최대 넓이 계산
4. 남은 것들을 pop해서 넓이 비교
'''
import sys
def maxArea():
max_area = 0
stack = []
for i in range(N):
index = i
... |
'''
15651 N과 M(3)
알고리즘 :
1. N개 중에 중복을 허용해서 M개를 순서를 고려해서 뽑는 중복순열의 알고리즘을 이용
2. itertools의 product를 이용
'''
from itertools import product
N, M = map(int, input().split())
num_list = []
for i in range(N):
num_list.append(i+1)
a = list(product(num_list, repeat = M))
for i in range(len(a)):
for j i... |
'''
1541 잃어버린 괄호
알고리즘:
1. 입력을 '-'를 기준으로 list에 넣어준다.
2. 각 리스트를 숫자로 바꾼다. 이때 +가 있으면, 숫자로 바꾸고 더한 결과값으로 저장
3. 최소로 만들기 위해서는 최종 list에 남은 숫자들끼리 빼면된다.
'''
s = input().split('-')
num_list =[]
for x in s:
total = 0
if '+' in x:
temp = x.split('+')
for num in temp:
total... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.