text stringlengths 37 1.41M |
|---|
from typing import List
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
W, R, B = range(3)
N = len(graph)
colors = [W] * N
for vertex in range(N):
if colors[vertex] != W:
continue
stack = [vertex]
colors[ve... |
"""
T: O(N)
S: O(N)
Just do as the description says. Python's split correctly handles leading
and trailing whitespace and properly splits on multiple whitespace chars.
"""
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(reversed(s.split())) |
"""
T: O(N)
S: O(N)
Process every character, check if it is the same as the previous one. If so -
don't put it into the stack and pop the last character in the stack. This way,
our algorithm will work even when we have to do multiple removals in one go,
i.e. for abba, because bb will never be added to the stack.
"""
... |
"""
T: O(N)
S: O(N)
The gist of the solution is to determine a correct index for each node.
Since we are doing BFS, also known as level traversal, we can simply put
the node to the appropriate bucket with the nodes of the same vertical index.
In the end, we use recorded minimum and maximum indices to get a proper orde... |
from typing import List
class Solution:
def colorBorder(self,
grid: List[List[int]],
r0: int,
c0: int,
color: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
bfs, component, border = [[r0, c0]], set([(r0, c0)]... |
from typing import List
class Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
target_count = 0
for num in nums:
if num == target:
target_count += 1
elif num > target:
break
return target_count > len(nums)... |
import collections
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
result = []
if not root:
return result
values_count... |
from typing import List
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
ax_min, ay_min, ax_max, ay_max = rec1
bx_min, by_min, bx_max, by_max = rec2
right = min(ax_max, bx_max)
left = max(ax_min, bx_min)
if not right > left:
... |
import requests
print("""
____ _
| _ \ ___ __ _ _ _ ___ ___| |_ ___ _ __
| |_) / _ \/ _` | | | |/ _ \/ __| __/ _ \ '__|
| _ < __/ (_| | |_| | __/\__ \ || __/ |
|_| \_\___|\__, |\__,_|\___||___/\__\___|_|
|_|
------------------------------------------
| De... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 17 21:15:36 2017
@author: ranko
"""
import os
import pandas as pd
stats = pd.DataFrame(columns = ("language", "author", "title", "length","unique"))
text = "This is my test text. We're keeping this text short to keep things managable."
def count_wo... |
# 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 printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
s... |
# 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 largestBSTSubtree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.... |
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
ret = []
num = []
for i in strs:
ret.append(i)
num.append(',' + str(len(i)))
if len(num) > 0:
... |
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
self.reverse(0, n-1, nums)
self.reverse(0, k-1, nums)
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return []
... |
class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
count = 0
nums.sort()
for i in range(len(nums)):
left, right, t = i + 1, len(nums) - 1, target - nums[i]
... |
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.dic = dict()
for w in dictionary:
if len(w) >= 3:
tmp = w[0] + str(len(w[1:-1])) + w[-1]
... |
# 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.dic = dict()
l = len(words)
self.max = l
for i in xrange(l):
word = words[i]
if word in self.dic: se... |
# 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 longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if n... |
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 2:
return nums[0]
nums.sort()
print
left, right = 0, len(nums) - 1
while left < right:
if lef... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
# 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 rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
#Python program to solve the leetcode count-and-say sequence problem
# Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
# You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
#Functio... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import *
from statistics import *
from collections import *
def roulette_wheel_bad():
'''using choice()
return:
list: ['black', 'black', 'black', 'red', 'red', 'red']
counter = Counter({'black': 3, 'red': 3})
'''
popul... |
# array can also be used in this way but data type is not defined
X = [5, 6, 8, 10, -11]
n = len(X)
for i in range(n):
print(X[i], end=' ') |
width = input("Podaj dł. podstawy: ")
height = input("Podaj dł. wysokości: ")
triangle_area = (width * height) / 2
print("Pole trójkąta wynosi {triangle_area} cm^2")
print(f"Pole trójkąta wynosi {triangle_area} cm^2")
print("Pole trójkąta wynosi", triangle_area, "cm^2")
|
birth = int(input("Podaj rok urodzenia: "))
age = 2021 - birth
if age % 2 == 0:
print("Twój wiek jest parzysty.")
else:
print("twój wiek jest nieparzysty.")
if age > 60:
print("Możesz się szczepić Pfizerem.")
elif age > 70:
print("Astra jest dla ciebie")
elif age > 18:
print("W ogóle to Sputnik 8")... |
import time
import math
import matplotlib as plt
import numpy as np
# Starting function for script.
# Prints options for user input and runs another option.
# Returns result to caller.
def start():
print("Which formula would you like to use? ")
print("1. Quadratic")
print("2. Direct Proportions")
... |
# Clase de ejercicio 0003
import json
from pprint import pprint
class Ejercicio0003:
"""Esta es la clase del ejercicio 3"""
def __init__(self, archivo):
with open(archivo) as data_file:
data = json.load(data_file)
self.numeroevaluar = data['numeroevaluar']
self.resto = ... |
def solution(xs):
''' Finds the maximum product of a non empty subset of the array xs
Args: a list of integers with 1 to 50 elements whose absolute values are no greater than 1000.
Returns: the maximum product as a string '''
def remove_zeros_from_list(xs):
return [i for i in xs if i != 0]
... |
""""
题号 127 单词接龙
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","l... |
#compreensao de listas
x = [1,2,3,4,5]
y = []
#metodo basico
for i in x:
y.append(i**2)
print(x)
print(y)
print("Ideal")
z = [i**2 for i in x]
print(z)
a = [i for i in x if i%2==1]
print(a) |
nota1 = int(input("Digite a nota 1: "))
nota2 = int(input("Digite a nota 2: "))
if nota1 and nota2 >= 6:
print("Aprovados")
else:
print("reprovado") |
#grafico de dispersao
import matplotlib.pyplot as plt
x = [1,3,5,7,9]
y = [2,3,7,1,0]
titulo = "scatterplot: grafico de dispersao"
eixox = "Eixo X"
eixoy = "Eixo Y"
plt.title(titulo)
plt.xlabel(eixox)
plt.ylabel(eixoy)
plt.scatter(x, y, label="Meus pontos", color="r",marker = ".", s = 200)
plt.plot(x... |
#visualizacao de um grafico simples
import matplotlib.pyplot as plt
x = [1,2,5]
y = [2,3,7]
#titulo
plt.title("Grafico simples em python")
#eixos
plt.xlabel("Eixo X")
plt.ylabel("Eixo Y")
plt.plot(x, y)
plt.show()
|
# 列表去重
def get_unique_list(origin_list):
result = []
for item in origin_list:
if item not in result:
result.append(item)
return result
origin_list = [10, 20, 30, 10, 20]
print(
f"origin_list: {origin_list}, unique_list: {get_unique_list(origin_list)}")
# 利用 set
print... |
# 复杂列表排序
students = [
{"sno": 101, "sname": "小赵", "sgrade": 88},
{"sno": 104, "sname": "小钱", "sgrade": 77},
{"sno": 102, "sname": "小孙", "sgrade": 99},
{"sno": 103, "sname": "小李", "sgrade": 66},
]
result = sorted(students, key=lambda x: x["sgrade"], reverse=False)
print(f"students: {students}... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Module of tasks Hackerrank
# Copyright (C) 2021
# Salavat Bibarsov <Bibarsov.Salavat@gmail.com>
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# https://www.... |
#!/bin/python3
# Day 4: Class vs. Instance
# https://www.hackerrank.com/challenges/30-class-vs-instance/problem
"""
Objective
In this challenge, we're going to learn about the difference between a class and an instance;
because this is an Object Oriented concept, it's only enabled in certain languages. Check
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 15 12:59:50 2021
@author: Robert Morton
"""
from enum import Enum
class CoordPair:
"""
A single coordinate pair.
"""
def __init__(self, x, y):
self.x = x
self.y = y
self._hash = x<<16 ^ y
def __eq__(self, other):... |
class Car(object):
def __init__(self, color, make, speed_limit):
self.color = color
self.make = make
self.speed_limit = speed_limit
def accelerate(self, speed):
if speed <= self.speed_limit:
return "now driving at " + str(speed) + " MPH"
else:
re... |
from Person import Person
class Student(Person):
def __init__(self, name, age, year):
super().__init__(name, age)
self.year = year
self.courses = []
def introduce_self(self):
"""This method prints out the name and age attributes"""
print(
f"My name is {se... |
from random import randint
import copy
import string
import queue
class Map():
"""
The map
search(self); searchit(self, x, y, next); searchback(self); findback(self, x, y)
are used for the finding
show(self)
print actuall state of map
sector(self, x, y)
does nothing, yet
... |
a=[0]
b=a[:]
b[0]+=1
print(a)
print(b)
print()
x=[0]
y=x
y[0]+=1
print(x)
print(y)
|
def ctverec(velky,maly):
x,y=[0]*2
if velky < 3:
x+=3*velky
elif velky < 6:
x+=3*(velky-3)
y+=3
else:
x+=3*(velky-6)
y+=6
if maly < 3:
x+=maly
elif maly < 6:
x+=maly-3
y+=1
else:
x+=maly-6
y+=2
return x,y
def... |
from socket import *
import threading
import argparse
def scan_TCP_port(ip, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.settimeout(0.5)
try:
sock.connect((ip, port))
print(f"TCP Port: {port} Open")
except:
print(f"TCP Port: {port} CLOSED")
def scan_UDP_port(ip, port):
... |
def can_make_note(note, mag):
note = list(note.replace(" ", ""))
mag = list(mag.replace(" ", ""))
for c in note:
if c in mag:
mag.remove(c)
else:
return False
return True
def main():
note = "He old"
mag = "Hllo World"
print(str(can_make_note(note, ma... |
# -*- coding: UTF-8 -*-
import geopandas as gpd
from shapely.geometry import Point, Polygon
shapefile = '/home/tudor/Documents/GitHub/building_resilience/models/top_to_bottom/resources/data_resources/shapes/ne_110m_admin_0_countries.shp'
#Read shapefile using Geopandas
gdf = gpd.read_file(shapefile)[['ADMIN', 'ADM0_A... |
from tkinter import ttk
from tkinter import *
class Desk:
def _init_(self, window):
# Initializations
#ancho
ancho = 800
#alto
alto = 600
# asignamos la ventana a una variable de la clase llamada wind
self.wind = windo... |
#!/usr/bin/python2.7
#pokerdice.py
import random
from itertools import groupby
nine = 1
ten = 2
jack = 3
queen = 4
king = 5
ace = 6
names = { nine: "9", ten: "10", jack: "J", queen : "Q", king = "K", ace = "A" }
player_score = 0
computer_score = 0
def start():
print "Let's play a game of Poker Dice."
while game... |
n1,n2,n3=int(input('Enter your first number')),int(input('Enter your second number')),int(input('Enter your third number'))
smaller=('first number is smaller'if n2>n1<n3 else'second number is smaller'if n1>n2<n3 else'third number is smaller'if n1>n3<n2 else
'all are equal'if n1==n2==n3 else'first and second ar... |
southheros=['Rajini','Naga Arjun','Chiranjiv','Mahesh Babu','Junior NTR','Ram Charan','Allu Arjun','Naga Chaitanya','Gopi Chand','Pavan Kalyan','Yash','Ravi Teja','Ram Pothenin']
n=input('Enter the name of your favorite south hero :')
if n in southheros:
print('It was there in the list')
southheros.remove(n)
... |
"""
This set of classes is going to be used for easy HTML generation
for Watson to read. Syntax is as follows:
<html>
<body>
<div class="Story" id="Game Name">
<div class="Page" value=0>
TEXT OR SOMETHING
<div class="Choice" value=0> Go to Castle </div>
<div class="Choice" value=1> Go Home <... |
'''
Author:Israel Flannery
Date:15/10/2020
Description:right Room 2
Version:6.0
'''
#--------Libraries-------#
import sqlite3
from sqlite3 import Error
import random
#------Functions--------#
def introduction():
conn = None
db_file = "quiz.db"
try:
conn = sqlite3.connect(... |
#自分が何日間いきているか計算
import datetime
import math
#今日
today = datetime.date.today()
#誕生日
birthday = datetime.date(1998,2,25)
life = today - birthday
print(str(life.days) + "日間生きています!")
#現在の年齢
age = math.floor(life.days / 365)
print(str(age) + "歳です")
#曜日ごとにメッセージを変える
#0は月曜日、6は日曜日
# 月曜日
if today.weekday() == 0:
print(... |
from multiprocessing import Pool, Manager
def get_word(que):
word_list = ["Life", "is", "short"]
for word in word_list:
que.put(word)
def print_word(que):
for i in range(3):
print(que.get(), end=" ")
def main():
process_pool = Pool(2)
word_que = Manager().Queue()
process_p... |
words = "Life is short"
def print_before(func):
# it is almost a trap to print here, words will be printed while decorating instead of calling foo
# Be aware that @ is just syntactic sugar, decorating is equivalent to `print_before(foo)`
print(words)
def wrapper(*args, **kw):
return func(*ar... |
word_list = ["Life", "is", "short"]
it = iter(word_list)
while True:
try:
print(next(it), end=" ")
except StopIteration:
break
|
quantApl = int(input("How many apple do you want to buy? \n> "))
quantOrng = int(input("How many orange do you want to buy? \n> "))
aplPrice = quantApl * 20
orngPrice = quantOrng * 25
overallTtl = aplPrice + orngPrice
print(f'Apple: 20 pesos * {quantApl} piece/s = {aplPrice}')
print(f'Orange: 25 pesos * {quantOrng} ... |
# Source: https://leetcode.com/problems/swap-nodes-in-pairs/
#
# Level: Medium
#
# Date: 29th July 2019
"""
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the... |
# Source: https://leetcode.com/problems/rotting-oranges/
#
# Date: 23rd August 2019
"""
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (... |
# Source: https://leetcode.com/problems/subarrays-with-k-different-integers/
#
# Date: 19th August 2019
"""
Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the
number of different integers in that subarray is exactly K.
(For example, [1,2,3,1,2] has 3 differe... |
# Source: https://leetcode.com/problems/search-in-a-binary-search-tree/
# Level: Easy
#
# Date: 07th August 2019
"""
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the
node's value equals the given value. Return the subtree rooted with that node. If such node... |
# Source: 2020 Goldman Sachs Engineering Code test
# Level: Medium
# Date: 17th July 2019
def analyzeInvestments(stringInput): # O(n^2)
hashMap = {}
count = 0
for index, value in enumerate(stringInput):
if index + 3 > len(stringInput):
break
hashMap[value] = index
for... |
# Source: https://leetcode.com/problems/powx-n/submissions/
#
# Level: Easy
#
# Date: 30th July 2019
"""
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanat... |
# Source: https://leetcode.com/problems/reverse-words-in-a-string/
#
# Level: Medium
#
# Date: 31st July 2019
"""
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: " hello world! "
Output: "world! hello"
Explanation: Your rev... |
# Source: https://leetcode.com/problems/intersection-of-two-arrays-ii/
#
# Date: 22nd August 2019
"""
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each e... |
# Source: https://leetcode.com/problems/can-place-flowers/
# Level: Easy
# Date: 12th July 2019
# Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot
# be planted in adjacent plots - they would compete for water and both would die.
#
# Given a flowerbed ... |
# Source: https://leetcode.com/problems/search-insert-position/
# Level: Easy
# Date: 13th July 2019
# Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
#
# You may assume no duplicates in the array.
#
# Example ... |
# Source: https://leetcode.com/problems/odd-even-linked-list/
# Level: Medium
# Date: 24th July 2019
# Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are
# talking about the node number and not the value in the nodes.
#
# You should try to do it in place. Th... |
'''
Source: https://leetcode.com/problems/longest-palindrome/
Level: Easy
Date: 06th July 2019
'''
'''
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palin... |
# Source: https://leetcode.com/problems/set-mismatch/
# Level: Easy
# Date: 13th July 2019
# The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in
# the set got duplicated to another number in the set, which results in repetition of one number and loss of ... |
# Source: https://leetcode.com/problems/ugly-number/
#
# Date: 17th August 2019
"""
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: 8
Output: tru... |
# Source: https://leetcode.com/problems/average-of-levels-in-binary-tree/
# Level: Easy
# Date: 28th July 2019
"""
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The averag... |
# Source: https://leetcode.com/problems/brick-wall/
# Level: Medium
# Date: 21st July 2019
# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the
# same height but different width. You want to draw a vertical line from the top to the bottom and cross the ... |
#!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function named uses_all that takes a word and a string of required
# letters, and that returns True if the word uses all the required letters at
# least once.
# - write uses_all
# (2)
# How many words are there that use all the vowels aeiou? How about
# aeiouy?... |
# -*- coding: utf-8 -*-
# @Time : 2021/10/19 14:33
# @Author : Ruby
# @FileName: 603random.py
# @Software: PyCharm
price = 12 # 每次乘车票价
days = 22 # 每月乘车天数
times = 2 # 每天乘车次数
MountCost = 0 # 累计消费
# range 会产生从1开始到 days*times + 1 之间的连续整数
for i in range(1, days*times + 1):
# f+{} 打印变量
print(f'第{i}天')
... |
from random import randint
my_crazy_list = [randint(10, 20) for i in range(10)]
print(my_crazy_list)
for i in range(1, len(my_crazy_list)):
if my_crazy_list[i] > my_crazy_list[i - 1]:
print(my_crazy_list[i]) |
#!/usr/bin/python3
"""test the airbnb project"""
import unittest
from models.place import Place
A = Place()
class TestClassMethods(unittest.TestCase):
"""test the Airbnb project"""
def test_State_Place(self):
self.assertEqual(type(A.city_id), str)
self.assertEqual(type(A.user_id), str)
... |
'''
Created on Mar 1, 2013
@author: Jimmy
'''
def countall(words):
firstLetters = [w[0].lower() for w in words]
print firstLetters
alliterations = 0
for i in range(0,len(firstLetters)):
if len(firstLetters) == 1:
return 0
if i > 0 and i !=... |
'''
Created on Feb 23, 2012
@author: ola
'''
import Tools, random, operator, copy
_DEBUGisON = False
def change_knowledge(guess, secret, knowledge):
""" Changes the knowledge that is shown to the player
For example changes _ e _ _ e to t e _ _ e when t is guessed.
"""
for i, ch i... |
'''
Created on Jan 31, 2013
@author: Jimmy
'''
def reverse(dna):
reverselist = []
result = ""
for i in range(0,len(dna)):
reverselist.append(dna[i])
reverselist.reverse()
for i in range(0,len(reverselist)):
result += reverselist[i]
return result
|
def get_second_lowest_score(sorted_records):
idx = 0
for _ in sorted_records:
if idx > 0:
if sorted_records[idx - 1][1] != sorted_records[idx][1]:
return sorted_records[idx][1]
idx += 1
return 0
studentRecords = []
for _ in range(int(input())):
name = input(... |
##################################################
# This script shows an example of a header section. This sections is a group of commented lines (lines starting with
# the "#" character) that describes general features of the script such as the type of licence (defined by the
# developer), authors, credits, versions... |
# mean
# The mean tool computes the arithmetic mean along the specified axis.
# import numpy
# my_array = numpy.array([ [1, 2], [3, 4] ])
# print numpy.mean(my_array, axis = 0) #Output : [ 2. 3.]
# print numpy.mean(my_array, axis = 1) #Output : [ 1.5 3.5]
# print numpy.mean(my_array, axis = None) ... |
import random
def rolls ():
counter = 1
all_rolls = []
while counter == 1:
var1 = random.randint(1,6)
var2 = random.randint(1,6)
var3 = random.randint(1,6)
all_rolls += [((var1 , var2, var3))]
if var1 > var2 > var3 or var2 > var3 > var1 or var3 > ... |
from __future__ import print_function
import random
def guess():
secret = random.randint(1, 20)
print('I have a number between 1 and 20.')
while True:
guess = int(raw_input('Guess: '))
if guess != secret:
print('Wrong, not my number')
if guess > secre... |
"""
Advent of Code 2020 - Day 10
Pieter Kitslaar
"""
from pathlib import Path
from collections import Counter
from functools import reduce
example_a = """\
16
10
15
5
1
11
7
19
6
12
4"""
def parse(txt):
values = list(map(int, txt.splitlines()))
values.sort()
return values
def compute_diffs(txt):
val... |
"""
Advent of Code 2020 - Day 21
Pieter Kitslaar
"""
from pathlib import Path
example="""\
mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
trh fvjkl sbzzf mxmxvkd (contains dairy)
sqjhc fvjkl (contains soy)
sqjhc mxmxvkd sbzzf (contains fish)"""
def parse(txt):
foods = []
for line in txt.splitlines():
... |
import random
x=22/7
print(x)
suit = ("hearts" , "diamonds" , "spades" , "clubs")
value = ("two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" , "ten" , "jack" , "queen" , "king" , "ace")
val = {"two" : 2 , "three" : 3 , "four" : 4 , "five" : 5 , "six" : 6 , "seven" : 7 , "eight" : 8 , "nine" : ... |
# ---------------------------------------------------PROBLEM STATEMENT------------------------------------------------------------------
#
#
# You visit a doctor on a date given in the format yyyy:mm:dd. Your doctor suggests you to take pills every alternate day
# starting from that day. You being a forgetful ... |
'''
This program let one compute all different parameters of the credit. This program calculate the annuity payment
which are fixed during the whole credit term, and the differentiated payment where the part of reducing the credit
prinsipal is constant. Also the interest repayment part of the credit calculator, it re... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
data = pd.read_csv('C:/Users/nikhil.goyal/Desktop/itbodhi/LinerarRegdataset/student.csv')
print(data.shape)
data.head()
math = data['Math'].values
re... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def toint(self, node):
return node.val + 10 * self.toint(node.next) if node else 0
def addTwoNumbers(self, l1, l2):
"""
:type l... |
"""
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
import random
class ListNode(object):
def __init__(self, x):
... |
#PARA EXECUTAR O PROGRAMA NO TERMINAL BASTA DIGITAR: python3 main.py
'''
Para o entendimento da lógica do programa é necessário que entenda-se o que está atribuido a algumas variáveis:
"dicionario_pontuacao": associa as letras a seus valores;
"banco_palavras": inicialmente é uma lista que representa o banco de ... |
from typing import List
import random
import sys
def menu(entries : List) -> int:
maxLen = len(entries) + 1
while True:
print('\nMENU')
print('----')
for num, label in enumerate(entries):
print(f'{num + 1:2} - {label}')
print(' 0 - Quitter')
try:
... |
import sqlite3
def schema(dbpath = "schema_designer.db"):
with sqlite3.connect(dbpath) as connection:
c = connection.cursor()
#drop tables if they exist
dropsql = "DROP TABLE IF EXISTS {};"
for table in ["snacks", "students", "teachers", "classes", "class1"]:
c.execute... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.