text stringlengths 37 1.41M |
|---|
input1=input("Enter a String: ")
def remove_odd_index(input1):
res=''
for i in input1[::2]:
res+=i
return res
val=remove_odd_index(input1)
print(val) |
import math
from queue import Queue
# Spatial distance between two positions
def distance(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
# Shortest path distance (BFS) between two positions on the board
def board_distance(pos1, pos2, board):
bfs_queue = Queu... |
import pickle
import struct
f = open('Stu.txt','w')
n = input('Please input the number of stus:')
s = struct.pack('i',n)
f.write(s)
s2 = 'Number Name High Level Maths Lineral Math Computer Introduction'
print len(s2)
f.write(s2)
i = 0
while i < n:
num = input('Please input No.' + str(i+1) + '... |
#yield2
rows = [3,17]
def cols():
yield 56
yield 2
yield 1
r = ((i,j) for i in rows for j in cols())
for e in r :
print e
#ļwri,''te
import os
f = open('h.txt','w+')
x = ['1\n','2\n','3\n','4\n','5\n','6\n']
#for e in x :
# f.write(e+os.linesep)
f.writelines(x)
... |
# -*- coding:utf-8 -*-
'''最短子数组
对于一个数组,请设计一个高效算法计算需要排序的最短子数组的长度。
给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的长度。(原序列位置从0开始标号,若原序列有序,返回0)。保证A中元素均为正整数。
测试样例:
[1,4,6,5,9,10],6
返回:2
'''
class Subsequence:
def shortestSubsequence(self, A, n):
# write code here
minA = 0
right = 0
... |
def sum(numbers):
total = 0
for x in range(0, len(numbers)):
total = total + numbers[x]
return total
def dot_product(A, B):
dot = []
if len(A) == len(B):
for x in range(0, len(A)):
num = A[x] * B[x]
dot.append(num)
else:
return None
return sum(dot) |
# 1B1.py
# Sandis Mālnieks 193RIC058
from numpy import * # Importē skaitlisko metožu bibliotēkas funkcijas
from matplotlib import pyplot as plt
x = linspace(0, 7, 70) # Trešais arguments ir ģenerējamo elementu skaits
y = sin(x)
plt.grid()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Funkcija $sin(x)$')
plt.plot(x... |
from numpy import exp,array,random,dot
def sigmoid(x,derivative=False):
if derivative==True:
return x*(1-x)
return 1/(1+exp(-x))
if __name__ == '__main__':
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
random.seed(1)
synaptic_weights0... |
"""
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode
"""
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single... |
"""
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "i... |
x = 0
def a():
x = 0
x +=1
print x
print "a"
x +=1
print x
yield 99
x +=1
print x
print "a2"
x +=1
print x
yield 98
x +=1
print x
b = a()
b
#print x
print "``````````"
print b.next()
#print x
#b.next()
#print x
print b
print "``````````"
for i in b:
p... |
import math
def odd(n):
return n % 2 == 1
def generate_odd():
n = 3
while True:
yield n
n = n + 2
count = 1
prime_list = [2,]
for candidate_prime in generate_odd():
is_prime = True
for test in prime_list:
if test > math.sqrt(candidate_prime):
break
... |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
i = 0
for num in nums:
n = target - num
if n not in h:
h[num] = i
i+=1
else:
return [h[n],i]
nums = [2, 7, 11, 15]
... |
'''
96. Unique Binary Search Trees
Question: https://leetcode.com/problems/unique-binary-search-trees/
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\... |
'''
394. Decode String
Question: Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.
Note that k is guaranteed to be a positive integer.
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", ... |
'''
Inorder traversal
def inorderTraversal(self, A):
if A is None:
return None
self.inorderTraversal(A.left)
self.inorderTraversal.append(A.val)
self.inorderTraversal(A.right)
return self.postorderList
Created on Jul 3, 2018
@author: smaiya
'''
# Definition for a... |
'''
3. Longest Substring Without Repeating Characters
Q: Longest Substring Without Repeating Characters
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution: Store the latest inde... |
'''
61. Rotate List
Given the head of a linked list, rotate the list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next =... |
'''
56. Merge Intervals
Question: Given a collection of intervals, merge all overlapping intervals.
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18]
Solution:
- Sort the interval based on the interval start
- Starting from the first interval, keep checking if it overlaps with the following inter... |
'''
Created on Jun 30, 2018
Given an array, find the nearest smaller element G[i] for every element A[i] in the array
such that the element has an index smaller than i.
Input : A : [4, 5, 2, 10, 8]
Return : [-1, 4, -1, 2, 2]
Input : A : [3, 2, 1]
Return : [-1, -1, -1]
@author: smaiya
'''
class Solution:
# @param ... |
'''
399. Evaluate Division
Question: Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number).
Given some queries, return the answers. If the answer does not exist, return -1.0
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ... |
'''
743. Network Delay Time
Question:
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node,
v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certa... |
'''
Sadhana Amazon Assessment: 6/1/2018
Question: find the most frequented word excluding words from 'ignore_list'
'''
import re
class Solution:
# @param A : integer
# @return an integer
def mostFrequentWord(self, A, B):
exclude_map = dict()
for words in B:
exclude_map[words.lower()] = 1
literature_map ... |
'''
Question: Number of inversions (swaps) required to make the array sorted
E.g., Input: [2, 4, 1, 3, 5] Output = 3
Solution: Dynamic Programming. O(nlogn) for sorting
- D(n) = D(n-1) + x
where D(n) = number of swaps required to make the first n array sorted
x = number of elements in the (n-1) elements th... |
'''
128. Longest Consecutive Sequence
# Uber Phone Interview 6/28/2018
Given an unsorted array of integers nums, return the length of the longest
consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements ... |
'''
871. Minimum Number of Refueling Stops
Question: A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the
starting position, and has station... |
'''
121. Best Time to Buy and Sell Stock
Question: What is the max profit you can make given the price array of a stock
E.g., A = [2, 1, 10, 9, 2, 6, 5] ==> Answer = 10-1 = 9
Solution: Dynamic Programming
Dn = max profit at time n
Dn+1 = max(Dn, x(n+1) - curr_min)
'''
class Solution:
def maxProfit(self... |
'''
2049. Count Nodes With the Highest Score
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1.
You are given a 0-indexed integer array parents representing the tree, where parents[i]
is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a s... |
'''
Preorder Traversal
def preorderTraversal(self, A):
if A is None:
return None
self.preOrderList.append(A.val)
self.preorderTraversal(A.left)
self.preorderTraversal(A.right)
return self.preOrderList
Created on Jul 3, 2018
@author: smaiya
'''
# Definition for a binary tree node
class Tre... |
'''
Created on Jul 7, 2018
shortest unique prefix to represent each word in the list.
Input: [zebra, dog, duck, dove]
Output: {z, dog, du, dov}
This is a tree question. Can be solved using Trie.
@author: smaiya
'''
class Solution:
# @param A : list of strings
# @return a list of strings
def prefix(self, ... |
'''
147. Insertion Sort List
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion so... |
'''
287. Find the Duplicate Number
Question: https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.
Assume that there is only one duplicate number, find the duplicate... |
'''
131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward as forward.
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Solution
- Us... |
'''
2265. Count Nodes Equal to Average of Subtree
Given the root of a binary tree, return the number of nodes where the value of the node
is equal to the average of the values in its subtree.
Note:
The average of n elements is the sum of the n elements divided by n and
rounded down to the nearest integer.
Input: r... |
'''
162. Find Peak Element
Question:
A peak element is an element that is greater than its neighbors. Idx 0 and n-1 have just 1 neighbor
Given an input array nums, where nums[i] != nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of th... |
from datetime import date
from datetime import datetime
today = date.today()
dateList = []
# User story 1 - all dates should be before current date
def DatebeforeCurrentDate(indi, fam):
print("User story 1 - All dates should be before current date")
print(" ")
for i in indi:
# Checking death date... |
import math
class Rectangle:
def __init__(self, a, b):
self.width = a
self.height = b
@property
def area(self):
return self.width * self.height
@area.setter
def area(self, value):
ratio = math.sqrt(value / self.area)
self.width = self.width * ratio
... |
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sub list
sub_list = lst[1:8] # lst[1:-1]
print(sub_list)
# sub list w/ steps
sub_list = lst[1:8:2] # lst[1:-1:2]
print(sub_list)
sub_list = lst[8:1:-1]
print(sub_list)
sub_list = lst[::]
print(sub_list)
|
import math
class Square:
def __init__(self, a):
self.side = a
self.__area = self.side * self.side
@property
def area(self):
return self.__area
@area.setter
def area(self, value):
self.side = math.sqrt(value)
self.__area = self.side * self.side
sq1 = Squ... |
import sqlite3
class Singleton:
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__new__(cls)
cls.instance.initialized = False
return cls.instance
def __init__(self):
if not self.initialized:
... |
text = "April is the cruelest month."
if len(text) % 2 == 0:
print(text.upper())
if len(text) % 2 == 1:
print(text.lower()) |
# Time complexity: O(n^2)
# Space Complexity: O(n)
# Algorithm: Sort the words and then for each word if the string upto previous character is in a set then place the word in the set.
# Sort the set and return max value (with min lexical order)
class Solution:
def longestWord(self, words: List[str]) -> s... |
#!/usr/bin/env python3
def word_stats(file_directory, num):
f = open(file_directory, "r")
contents = f.read()
list_of_things_in_txt = list(contents) #puts all the separate letters into a list
list_of_characters = []
for char in list_of_things_in_txt:
if char.isalnum() or char == " ": #if ... |
#programa que imprime todos os numeros pares de 0 a 20. Quando chegar no 5 parar o codigo
i= 0
while i <= 20:
print(i)
if (i == 5):
break
i += 1 |
h = ['head', 'body', 'left leg', 'right leg', 'left arm', 'right arm']
word = 'candy'
word_length = len(word)
dashes = ''
for i in word:
dashes += '- '
print(dashes)
u = input('Letter? ').lower()
while
if u.lower() in word:
print('True')
else:
print('You guessed wrong!')
print(h[0])
|
i=1
c=0
n=int(input("enter a number"))
while c<n:
f=0
j=1
while j<=i:
if i%j==0:
f=f+1
j=j+1
if f==2:
print(i)
c=c+1
i=i+1
|
#!/bin/env python
# Created on March 25, 2020
# by Keith Cherkauer
#
# This script serves as the solution set for assignment-10 on descriptive
# statistics and environmental informatics. See the assignment documention
# and repository at:
# https://github.com/Environmental-Informatics/assignment-10.git for more
# de... |
def sum(x, y):
# print(x+y)
return x + y
print(sum(4, 5))
# default Parameter
# keyword Argument
def more_num(a, b=7, c=10):
print("a is", a, "b is", b, "c is ", c)
more_num(2)
# pass statment
def dream_home():
pass
# varArgs parameter
def total_numbers(a=7, *numbers, **phonebook):
# th... |
from itertools import cycle
import tkinter as tk
class App(tk.Tk):
# TK window/label adjust to size of images
def __init__(self, image_file, x, y, delay):
tk.Tk.__init__(self)
self.geometry("+{}+{}".format(x, y))
self.delay = delay
self.pictures = cycle((tk.PhotoImage(file=i... |
# class Point:
# def draw(self):
# print("draw")
# point = Point()
# print(type(point))
# print(isinstance(point, Point))
# creating new constructure
class Point:
# class level attribute are accessinle all level of the class.
default_color = "red"
def __init__(self, x, y):
self.x =... |
import sqlite3
class DataCliente:
def __init__(self):
self.conn = sqlite3.connect('basedata.db')
self.cursor = self.conn.cursor()
def insertItems(self, code, name, supp, price, cant):
sql = "INSERT INTO clientes (name, phone, mail, adress, reference ) VALUES(?,?,?,?,?)"
params = (code, name, price, supp, ... |
"""
Validate national code method for Iranian national ID Codes
"""
# Standard library imports
import re
def validate(national_code):
if national_code is None:
return False
if type(national_code) != str:
return False
national_code = national_code.replace('_','').replace('-','').replace(... |
# Do relevant imports
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
from moviepy.editor import VideoFileClip
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as... |
import time
import pandas as pd
from datetime import timedelta
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
MONTHS = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6
}
DAYS = ... |
#!/usr/bin/env python
"""This program grabs a joke from the internet and if you like it, saves it in a file. You can look at the jokes you liked"""
__author__ = "Ken Vanden Branden"
__license__ = "GPL"
__version__ = "1.0.0"
__email__ = "kenvdb@gmail.com"
import requests # To make http requests
import sys # to exit the ... |
# Ex.4 - Variables and Names
# - Write a comment above each line explaining to yourself in English what it does.
# - Read the .py file backwardç
# - Read the .py file out loud, saying even the characters
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven =... |
trip = float(input())
puzzle_number = int(input())
doll_number = int(input())
teddy_bear_number = int(input())
minion_number = int(input())
truck_number = int(input())
puzzle_price = 2.60
doll_price = 3
teddy_bear_price = 4.10
minion_price = 8.20
truck_price = 2
total_toy_sum = (puzzle_number * puzzle_pr... |
first_number = int(input())
second_number = int(input())
for i in range(first_number, second_number + 1):
number = i
even_sum = 0
odd_sum = 0
for position in range(1, 7):
digit = number % 10
number = number // 10
if position % 2 == 0:
even_sum += digit
... |
n = int(input())
bus_price = 0
truck_price = 0
train_price = 0
total_weight = 0
total_weight_bus = 0
total_weight_truck = 0
total_weight_train = 0
average_weight = 0
for load in range(1, n + 1):
weight = int(input())
if weight <= 3:
bus_price = 200
total_weight_bus += weight
... |
number_dogs = int(input())
number_animals = int(input())
dog_food_price = 2.5
animal_food_price = 4
result = number_dogs * dog_food_price + number_animals * animal_food_price
print(f'{result} lv') |
import math
number_magnolii = int(input())
number_zumbuli = int(input())
number_roses = int(input())
number_cactus = int(input())
gift_price = float(input())
price_magnolii = 3.25
price_zumbuli = 4
price_roses = 3.50
price_cactus = 8
total_sales = (number_magnolii * price_magnolii) + (number_zumbuli * p... |
n = int(input())
numbers_sum = 0
for i in range(n):
current_number = int(input())
numbers_sum += current_number
print(numbers_sum)
|
days_count = int(input())
bakers_count = int(input())
cakes_count = int(input())
waffles_count = int(input())
pancakes_count = int(input())
cake_price = 45
waffles_price = 5.80
pancakes_price = 3.20
money_per_day = ((cake_price * cakes_count) + (waffles_count * waffles_price) + (pancakes_count * pancakes_pr... |
exam_hour = int(input())
exam_minutes = int(input())
arrival_hour = int(input())
arrival_minutes = int(input())
exam_time = exam_hour * 60 + exam_minutes
arrival_time = arrival_hour * 60 + arrival_minutes
diff = arrival_time - exam_time
state = ''
if diff < -30:
state = 'Early'
elif diff <= 0:
st... |
season = input()
distance = float(input())
price_per_km = 0
if distance <= 5000:
if season == 'Spring' or season == 'Autumn':
price_per_km = 0.75
elif season == 'Summer':
price_per_km = 0.90
else:
price_per_km = 1.05
elif 5000 < distance <= 10000:
if season == 'S... |
import math
days = int(input())
available_food = int(input())
dog_food = float(input())
cat_food = float(input())
turtle_food = float(input())
total_dog = days * dog_food
total_cat = days * cat_food
total_turtle = days * turtle_food / 1000
total_food_needed = total_dog + total_cat + total_turtle
diff ... |
pages_count = int(input())
pages_per_hour = int(input())
days_count = int(input())
total_time = pages_count / pages_per_hour
total_hours = total_time / days_count
print(total_hours)
|
money = float(input())
months = int(input())
interest_rate = float(input())
interest = money * interest_rate / 100
interest_per_month = interest / 12
total_money = money + (months * interest_per_month)
print(total_money)
|
budget = float(input())
video_cards = int(input())
processors = int(input())
ram_memory = int(input())
price_video_card = 250
total_video_card = price_video_card * video_cards
price_processor = total_video_card * 0.35
total_processor = price_processor * processors
price_ram_memory = total_video_card * 0.1
to... |
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
x = float(input())
y = float(input())
if (x == x1 or x == x2) and (y1 <= y <= y2):
print(f'Border')
elif (y == y1 or y == y2) and (x1 <= x <= x2):
print(f'Border')
else:
print(f'Inside / Outside') |
name = input()
sum_grades = 0
average_grade = 0
level = 0
while True:
annual_grade = float(input())
if annual_grade < 4:
grade = float(input())
if annual_grade < 4:
level += 1
print(f'{name} has been excluded at {level} grade')
break
else:
... |
#This class models a board for the game. Includes the functionality
#for making moves
class PentagoBoard:
def __init__(self, newState = []):
if newState == []:
self.state = [["-" for x in range(6)] for y in range(6)]
else:
self.state = [[newState[y][x] for x in range(0, 6)]... |
'''
* Python program to use contours to count the objects in an image.
*
* usage: python Contours.py <filename> <threshold>
'''
import cv2, sys
# read command-line arguments
filename = sys.argv[1]
t = int(sys.argv[2])
# read original image
image = cv2.imread(filename = filename)
# create binary image
gray = cv2.c... |
"""
* Program to practice with skimage drawing methods.
"""
import random
import numpy as np
import skimage
from skimage.viewer import ImageViewer
# create the black canvas
image = np.zeros(shape=(600, 800, 3), dtype="uint8")
viewer = ImageViewer(image)
viewer.show()
# mask = np.ones(shape=image.shape[0:2], dtype="b... |
'''
* Python script to demonstrate Laplacian edge detection.
*
* usage: python LaplacianEdge.py <filename> <kernel-size> <threshold>
'''
import cv2
import numpy as np
import sys
# read command-line arguments
filename = sys.argv[1]
k = int(sys.argv[2])
t = int(sys.argv[3])
# load and display original image
img = cv... |
import re
def validating_name(name):
regex_name=re.compile(r'^(Mr\.|Mrs\.|Ms\.) (?P<First>[A-Z][A-Za-z]+)(?P<Second> [A-Z][A-Za-z]+)*( [A-Z][A-Za-z]+)*$')
res=regex_name.fullmatch(name)
if res:
print(res.group())
print(res.group("First"))
print(res.group('Second'))
else:
print("Invalid")
validating_name(... |
def list_less_than_ten():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
for element in a:
if element < 5:
b.append(element)
print b
def divisors():
number = int(raw_input("Enter a number: "))
divisor_list = []
divisor_range = list(range(1,number+1))
... |
import numpy as np
"""
This entire code base has been developed
by Baijayanta Roy at Medium-Article. The code
can be found at {https://github.com/BaijayantaRoy/Medium-Article}.
I do NOT claim any rights for this code as it has NOT been developed by me.
However, the code is under the GNU GENERAL PUB... |
# На вход программе подается последовательность чисел, заканчивающихся нулем.
# Сам ноль не входит в последовательность. Найти среднее значение последовательности.
# Для округления использовать функцию round(x, n). Где x - число, n - количество знаков после запятой.
# Формат входных данных
# Последовательность чисел, ... |
def sum_numbers(n: int):
"""
Отдает сумму цифр входящего числа.
:param n:
:return:
"""
num_str = str(n)
num_sum = 0
for char in num_str:
num_sum += int(char)
return num_sum
def test_sum_numbers():
assert sum_numbers(123) == 6, 'Not pass'
assert sum_numbers(963) == ... |
# Ограничение по времени работы программы: 1 секунда.
# Ограничение по памяти: 32 мегабайта.
# Ввод из стандартного потока ввода(с клавиатуры).
# Вывод в стандартный поток вывода(на экран).
# Вычислите XOR от двух чисел.
# Входные данные
# Два целых шестнадцатеричных числа меньших FF.
# Выходные данные
# Побитовый XO... |
def cipher(text, shift, encrypt=True):
"""
Each letter is replaced by a letter some fixed number of positions down the alphabet.
Parameters
---
text: string value that you wish to encrypt or decrypt
shift: integer value of how many number positions down the alphabet you would like to shift the ... |
from store_data import data as store_data
from view import show_stocks
def update_product_detail():
pass
def remove_products():
pass
def add_products_to_store(*args, category=None):
if category is None:
category = input("Enter the product category(fruits, grocery, stationary): ")
item = {}... |
#!/usr/bin/env python
def day_1(file) -> int:
diff1 = diff3 = 0
input_list = []
with open(file, "r") as f:
for line in f:
line = line.strip("\n")
input_list.append(int(line))
input_list.sort()
previous = 0
for i in input_list:
if i - previous == 1:
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
cur_node = head
while cur_node and cur_node.next:
pre_node = cur_n... |
# Sum square difference
# ------------------------------------------------- #
# First square all the numbers from 1 to 100. Then
# sum all the numbers and square them. Then
# substract the two results from each other.
# ------------------------------------------------- #
squared, result, sum = 0,0,0
for i in range(1,... |
# Summation of primes
# ------------------------------------------------- #
# Reuse isPrime from Euler_7. While number is less
# than 2000000 check if the number is prime, if it is
# then add it to result.
# ------------------------------------------------- #
num, result=1,0
def isPrime(n):
if n==1: return False
... |
import pygame
import random
import sys
import math
from pygame.locals import *
gridSize = 10
letters = ['A', 'B', 'C', 'D', 'E' ,'F', 'G', 'H' ,'I','J']
class Grid():
def __init__(self):
self.size = gridSize
self.pieces = []
self.grid = self.gridMe()
self.coord = []... |
"""
OpenCV中图像像素读写操作
Python中的像素遍历与访问
- 数组遍历
"""
import cv2 as cv
src = cv.imread("../images/beauty.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
cv.imshow("image",src)
# 获取彩色图片的高 宽 通道数
h,w,ch = src.shape
# 遍历像素值,对像素取反
for row in range(h):
for col in range(w):
b,g,r = src[row,col]
b = 255 - b
... |
t = int(input())
for _ in range(t):
n = int(input())
grid = []
for i in range(n):
l = list(input())
l = sorted(l)
grid.append("".join([x for x in l]))
flag = 0
for i in range(len(grid[0])):
temp = []
for j in range(n):
temp.append(grid[j][i])
... |
from tkinter import *
from PIL import Image, ImageTk
imagenary_tech_root = Tk() #create a basic gui
#gui logic
#width x height - gemetory
imagenary_tech_root.geometry("700x334")
#imagenary_tech_root.minsize(300,100) #minimize- width,height
#imagenary_tech_root.maxsize(566,300) #maxsize-width,height
a... |
from tkinter import *
import tkinter.messagebox as tmsg
root= Tk()
root.geometry("450x300")
root.title("Slider Gui")
def getdollar():
print(f"we have credited{myslider2.get()} dollars to your bank account")
a=tmsg.showinfo("Amount credited ",f"{myslider2.get()} dollars to your bank account")
#myslid... |
'''
devolver los indices de dos numeros que sumados entre si son iguales a un target.
suponer que solo hay una respuesta.
suponer que no se va a usar el mismo numero.
ejemplo:
nums = [2,7,11,15]
target = 9
if nums[0] + nums[1] == target
return --> [0,1]
'''
def twoSum(nums, target):
for i in range(len(nums)):
... |
from sys import exit
from random import shuffle
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def getRandomKey()-> str:
key = list(LETTERS)
shuffle(key)
return "".join(key)
def checkValidKey(key: str)-> None:
key_list = list(key)
key_list.sort()
if key_list != list(LETTERS):
... |
from copy import deepcopy
import numpy as np
import pandas as pd
import sys
'''
In this problem you write your own K-Means
Clustering code.
Your code should return a 2d array containing
the centers.
'''
# Configure the path to data
data_dir = 'data/data/iris.data'
# Import the dataset
df = pd.read_table(data_dir, d... |
# Expanding circle by timer
###################################################
# Student should add code where relevant to the following.
import simplegui
WIDTH = 200
HEIGHT = 200
radius = 1
# Timer handler
def tick():
global radius
radius += 1
# Draw handler
def draw(canvas):
... |
present_value = 1000
annual_rate = 7
years = 10
future_value = present_value * (1 + 0.01 * annual_rate) ** years
print "The future value of $" + str(present_value) + " in " + str(years),
print "years at an annual rate of " + str(annual_rate) + "% is $" + str(future_value) + "." |
def circle_circumference(radius):
return 2 * 3.14 * radius
def test(radius):
print "A circle with a radius of " + str(radius),
print "inches has a circumference of",
print str(circle_circumference(radius)) + " inches."
test(8)
test(3)
test(12.9)
|
def rectangle_perimeter(width,height):
return 2*(width+height)
def test(width, height):
print "A rectangle " + str(width) + " inches wide and " + str(height),
print "inches high has a perimeter of",
print str(rectangle_perimeter(width, height)) + " inches."
test(4, 7)
test(7, 4)
test(10, 10)... |
# Compute the circumference of a circle, given the length of its radius.
###################################################
# Circle circumference formula
# Student should enter statement on the next line.
r=8
circumf=2*3.14*r
print circumf
###################################################
# Expected o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.