blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
daedde48bae6061778eb3a3153539d2f61374fb9 | Hrishikeshbele/Competitive-Programming_Python | /2 pointers technique.py | 496 | 3.796875 | 4 | '''
just loved this technique called 2 pointers technique in which we maintain the two pointers and interate through sorted list
to find pair having some perticular sum.
ex.
arr=[10,20,35,50,55,75,80]
x=70
ispairsum(arr,x) return True.
'''
def ispairsum(arr,x):
i=0
j=len(arr)-1
while(i<j):
if (arr[i... |
46cc90796f13ec7a9896b5bc33adac211a92f430 | Hrishikeshbele/Competitive-Programming_Python | /Generate all Parentheses II.py | 3,093 | 3.703125 | 4 | '''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n.
n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
'''
class Solution:
# @param A : integer
# @return a list of strings
def generateParenthesis(self, n):
#list t... |
4374cd09d9c7bcd8fdf700c7a47770b6982db258 | Hrishikeshbele/Competitive-Programming_Python | /4Sum.py | 1,442 | 3.734375 | 4 | '''
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[... |
224e2c2e3835534e75d9816249aaf06625e70ada | Hrishikeshbele/Competitive-Programming_Python | /Letter Case Permutation.py | 1,326 | 4.1875 | 4 | '''
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
approach:
let's see recursion ... |
1709b2ddd66afc9255099ccaec5c714ec5aa9589 | Hrishikeshbele/Competitive-Programming_Python | /Gray Code.py | 2,136 | 4.03125 | 4 | '''
he gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Approach:
For example, given n = 2, return [0,1,3,2]
For n=2: 00 01... |
afab2fe8f815cda591267691c0667a75a6182296 | Hrishikeshbele/Competitive-Programming_Python | /Leaf-Similar Trees.py | 767 | 4.25 | 4 | '''
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Input: root1 = [1,2], root2 = [2,2]
Output: true
approach : we find root nodes of both tree and compare them
'''
class Solutio... |
61487c706c0aeb27dad49b2a88a7026cc1223af6 | Hrishikeshbele/Competitive-Programming_Python | /Lychrel numbers.py | 888 | 4.0625 | 4 | '''
link: https://projecteuler.net/problem=55
How many Lychrel numbers are there below ten-thousand?
A number that never forms a palindrome through the reverse and add process is called a Lychrel number.
We know from the problem statement that the maximum number of iterations for all numbers below 10,000 is <50 to form... |
d9dbcef9234af631720b0e6d0ff76ffc9f5957fe | Hrishikeshbele/Competitive-Programming_Python | /MaximusumSubarray.py | 1,129 | 4.0625 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
class Solution(object):
def maxSubArray(self, nums):
"""
... |
0000c69455e235c02fe792ef58891c7f195c6317 | Hrishikeshbele/Competitive-Programming_Python | /Reverse integer.py | 369 | 3.984375 | 4 | '''
Reverse digits of an integer.
Example1:
x = 123,
return 321
'''
class Solution:
# @param A : integer
# @return an integer
def reverse(self, A):
if(A > 0):
k = int(''.join(reversed(str(A))))
return k*(k < 2**31)
else:
k = -1*int(''.join(reversed(str(A)[1:])))... |
34b090968b06ee05bd9ebfb94547b9ba63e32b2b | Hrishikeshbele/Competitive-Programming_Python | /Invert the Binary Tree.py | 1,079 | 4.3125 | 4 | '''
Given a binary tree, invert the binary tree and return it.
Look at the example for more details.
Example :
Given binary tree
1
/ \
2 3
/ \ / \
4 5 6 7
invert and return
1
/ \
3 2
/ \ / \
7 6 5 4
'''
### we exchange the left and right child recursively
# Definition f... |
3cf4054ef8c3b48e258dffec8d03a98675238987 | Hrishikeshbele/Competitive-Programming_Python | /Multiplication of all numbers in the list.py | 173 | 3.9375 | 4 | '''
Given a list, return the value obtained after multiplying all numbers in a list.
'''
def multiply(x):
prev=1
for i in x:
prev=prev*i
return prev
|
a53b136705af2cb07db3cde0a67f63d445fcc121 | Hrishikeshbele/Competitive-Programming_Python | /index of fibonacci sequance.py | 593 | 4.09375 | 4 | '''
given a number find the index of number if exist in fibonacci sequence else return -1.
Examples :
Input : 13
Output : 7
Input : 4
Output : -1
'''
#solution 1
def isfib(n):
if n<2:
return n
a = 0
b = 1
c = 1
res = 1
# iterate until generated fibonacci number
# is less th... |
10e13318a8978c67a0e2060a5eedbe9d384fc710 | Hrishikeshbele/Competitive-Programming_Python | /OOPS/shor_url_class.py | 1,452 | 3.71875 | 4 | # OOP: Easier to design, reuse components and build large software
# OOP for ML & DS roles: Should know the basics to use various modules and extend them when needed.
'''
Q. How would you build a TinyURL service?
approach:
Key = short-URL, Value = Long-URL
Key: random variable length alphabetic suffix [tinyurl.com/tg... |
9af9bc53e43238029d5c791bbc1cd37d26920e7a | Hrishikeshbele/Competitive-Programming_Python | /Jewels and Stones.py | 1,027 | 4.125 | 4 | '''
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a
type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. ... |
55975cca3658c25449c04034e95041ddaa0ff676 | jairSuarez/Ejercicios_Propios_Python3 | /primos.py | 255 | 3.5 | 4 | def esPrimo(num):
prim = False
divs = 0
for i in range(1,num+1):
if(num%i==0): divs+=1
if(divs==2): prim = True
return prim
for x in range(100):
if(esPrimo(x)==True): print(x)
|
b89895805ccf69dbc2a1ebf32832177485523f83 | emmaling27/social-distancing-simulation | /network.py | 2,814 | 3.59375 | 4 | import networkx as nx
import numpy as np
class Network():
""" Generate a network using Toivonen et al.'s social network model """
def __init__(self, n_0, n, mean_type, var_type):
"""
n_0: initial seed of nodes
n: number of nodes the network should have
"""
assert(n_0 <... |
108dedc3824783fe3ca2e84677966cb5d113f6d4 | Hyppogriff/python-project-lvl1 | /brain_games/games/calc.py | 954 | 4.03125 | 4 | import random
TASK = 'What is the result of the expression?'
MIN_RANDOM_NUMBER = 0
MAX_RANDOM_NUMBER = 10
def generate_question_and_answer():
number_1 = random.randint(MIN_RANDOM_NUMBER, MAX_RANDOM_NUMBER)
number_2 = random.randint(MIN_RANDOM_NUMBER, MAX_RANDOM_NUMBER)
operations = ['+', '-', '*']
o... |
a1f0706c96e98af1e902ccf94db1157c964a02af | Hyppogriff/python-project-lvl1 | /brain_games/cli.py | 134 | 3.53125 | 4 | import prompt
def get_user_name():
name = prompt.string('May I have your name? ')
name = "{}!".format(name)
return name
|
23275fede27675ba37f35a8e9117af1395c3aa72 | nirajkvinit/pyprac | /recursiveBinarySearch.py | 472 | 4.15625 | 4 | # Binary search using recursion
def binarySearchRecursive(arr, low, high, value):
mid = low + int((high + low) / 2)
if arr[mid] == value:
return mid
elif arr[mid] < value:
return binarySearchRecursive(arr, mid + 1, high, value)
else:
return binarySearchRecursive(arr, low, mid - 1, value)
def binarySearch(... |
b95a1a7a98cc227a5a9221363acf08d8496d2665 | nirajkvinit/pyprac | /reverse_letters.py | 275 | 4.09375 | 4 | def reverse_letters(word):
index = 0
reversed_word = ''
while index < len(word):
reversed_word = word[index] + reversed_word
index = index + 1
print(reversed_word)
reverse_letters('apple')
def reverse2(word):
for letter in word:
print(letter)
reverse2('test')
|
a4c94ed077075a01ef12f176fbccff19ef24a0fc | nirajkvinit/pyprac | /100skills/dictgen.py | 386 | 4.3125 | 4 | '''
With a given number n, write a program to generate a dictionary that
contains (i, i*i) such that i is an number between 1 and n (both included). and
then the program should print the dictionary.
'''
def dictgen():
n = int(input("Enter a number: "))
d = dict()
for i in range(1, n+1):
d[i] = i**... |
89cdd73ce9700472e869c9f9da632ca6acaad884 | nirajkvinit/pyprac | /convert_dec_to_any_base_rec.py | 577 | 3.953125 | 4 | def convert_dec_to_any_base_rec(number, base):
''' Convert an integer to a string in any base'''
convertString = '0123456789ABCDEF'
if number < base:
return convertString[number]
else:
return convert_dec_to_any_base_rec(number // base, base) + convertString[number % base]
def test_convert_dec_to_any_base_rec(... |
0fb037fb4b516306d29576c5f1adea0dbfd215d3 | nirajkvinit/pyprac | /binarySearch.py | 483 | 4.0625 | 4 | # Binary Search
def binarySearch(arr, value):
if arr:
arr.sort()
print(arr)
size = len(arr)
low = 0
high = size - 1
while low <= high:
mid = low + int((high - low) / 2)
if arr[mid] == value:
return True
else:
if arr[mid] < value:
low = mid + 1
else:
high = mid - 1
r... |
97d543a5289db82c175e0dbcd2f6e07d6d556d80 | Nigirimeshi/leetcode | /0179_largest-number.py | 1,459 | 4.09375 | 4 | """
最大数
链接:https://leetcode-cn.com/problems/largest-number
给定一组非负整数 nums,重新排列它们每个数字的顺序(每个数字不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
示例 1:
输入:nums = [10,2]
输出:"210"
示例 2:
输入:nums = [3,30,34,5,9]
输出:"9534330"
示例 3:
输入:nums = [1]
输出:"1"
示例 4:
输入:nums = [10]
输出:"10"
提示:
1 <= nums.length <= 100
0 <= nums[i... |
d47ef1a93a5a369786d84891ea39fd570f7f1c44 | Nigirimeshi/leetcode | /0103_binary-tree-zigzag-level-order-traversal.py | 5,383 | 3.796875 | 4 | """
二叉树的锯齿形层次遍历
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
给定一个二叉树,返回其节点值的锯齿形层次遍历。
(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
我的解题思路:
1.
设置交替标志位,用于每一层控制是左 -> 右,还是右 ->... |
bdbfa3600c7aff75d6a31d5078cc30cfec46ba23 | Nigirimeshi/leetcode | /structure/linked_list.py | 475 | 3.796875 | 4 | from typing import List
# 单链表的定义.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_to_list_node(arr: List) -> ListNode:
dummy = ListNode(0)
n = dummy
for v in arr:
n.next = ListNode(v)
n = n.next
return dummy.next
de... |
4f2487efd3bb2d56cb4e502bf08783ff5ef3f2a4 | Nigirimeshi/leetcode | /0021_merge-two-sorted-lists.py | 2,635 | 4.1875 | 4 | """
合并两个有序链表
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
将两个升序链表合并为一个新的升序链表并返回。
新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1 -> 2 -> 4, 1 -> 3 -> 4
输出:1 -> 1 -> 2 -> 3 -> 4 -> 4
官方解法:
1. 迭代法。
当两个链表都不为空时,判断哪个链表的头节点的值更小,将较小值添加到结果里,之后将链表中的节点向后移动一位。
时间复杂度:O(n+m),n 和 m 分别是两个链表的长度,因为每次迭代循环时,只会放入一个链表元素,因此 while 循环次数不... |
536652b7f54d9673410595607b0887f186cdab8f | Nigirimeshi/leetcode | /0059_spiral-matrix-ii.py | 2,204 | 4.09375 | 4 | """
螺旋矩阵 II
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
解法:
1. 模拟。
算法:
1)设 l, r, t, b = 0, n - 1, 0, n - 1。
2)按从左到右、从上到下、从右到左、从下到上的顺序遍历矩阵。
时间复杂度:O(N) N 为... |
d7fd82ab972ebdaef04c6892b2f7b6b21431883f | Nigirimeshi/leetcode | /0072_edit-distance.py | 3,290 | 3.859375 | 4 | """
编辑距离
链接:https://leetcode-cn.com/problems/edit-distance
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:
输入:word1 = "intention", word2 = ... |
f16a4c9924ac8328b019dd8caf797ae878c956a1 | Nigirimeshi/leetcode | /0301_remove-invalid-parentheses.py | 3,194 | 3.984375 | 4 | """
删除无效的括号
链接:https://leetcode-cn.com/problems/remove-invalid-parentheses
给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
返回所有可能的结果。答案可以按 任意顺序 返回。
示例 1:
输入: "()())()"
输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()"
输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")("
输出: [""]
示例 1:
输入:s = "()())()"
输出:["(())()","()()()"]
示例 ... |
ff4b94e05441616294f9b64596d0c6a8a5746427 | Nigirimeshi/leetcode | /0162_find-peak-element.py | 3,785 | 3.609375 | 4 | """
寻找峰值
链接:https://leetcode-cn.com/problems/find-peak-element
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞。
示例 1:
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返... |
faaed8a9df06a571ea196d787dcbfc6d964fd63d | Nigirimeshi/leetcode | /0337_house-robber-iii.py | 2,523 | 3.703125 | 4 | """
打家劫舍 III
链接:https://leetcode-cn.com/problems/house-robber-iii
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。
这个地区只有一个入口,我们称之为 “根”。
除了“根”之外,每栋房子有且只有一个“父“房子与之相连。
一番侦察之后,聪明的小偷意识到 “这个地方的所有房屋的排列类似于一棵二叉树”。
如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
... |
439445e18cb8260567be42e0e8df9eade0b3c9b5 | Nigirimeshi/leetcode | /1249_minimum-remove-to-make-valid-parentheses.py | 2,593 | 4.125 | 4 | """
移出无效的括号
链接:https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses
给你一个由 '('、')' 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 '(' 或者 ')'(可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下任意一条要求:
空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
示例 1:
输入:... |
020704dff945b381db894f4bbdb2d7bfb63bd68d | Nigirimeshi/leetcode | /0001_two-sum.py | 1,114 | 3.8125 | 4 | """
两数之和
链接:https://leetcode-cn.com/problems/two-sum
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
我的解题思路:
1. 暴力:遍历数组每个元素 x,并查找是否存在一个值与 target - x 相等。
时间复杂度:O(n^2)
空间复杂度:O(1)
""... |
ccee22d4925dce3e3c1777e0608ce1b0a1860467 | Nigirimeshi/leetcode | /0003_longest-substring-without-repeating-characters.py | 2,582 | 3.9375 | 4 | """
无重复字符的最长子串
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须... |
d8352a8e7b679ddf96237646a5208afbd8d3f931 | Nigirimeshi/leetcode | /0062_unique-paths.py | 2,270 | 4.03125 | 4 | """
不同路径
链接:https://leetcode-cn.com/problems/unique-paths
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start”)。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish”)。
问总共有多少条不同的路径?
示例 1:
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右
示例 2:
输入: m = 7, n = 3
输出: 28
提示:... |
6d38d7fb28e65289892b5df40553884525e3d46f | Nigirimeshi/leetcode | /0283_move-zeroes.py | 3,743 | 4.03125 | 4 | """
移动零
链接:https://leetcode-cn.com/problems/move-zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
我的解题思路:
1. 遍历数组,记录 0 的下标,删除所有 0,最后在数组尾部追加对应数量的 0。
官方解法:
1. 两次遍历(双指针)。
创建两个指针 i,j,第一次遍历时用 j 记录非 0 元素的数量。
遍历到非 0 元素时向左挪,并使 j + 1,遍历完后,j - 1... |
37f9b62a163f1645863f4ca50bf66eae3156adb2 | Nigirimeshi/leetcode | /0041_first-missing-positive.py | 2,584 | 3.734375 | 4 | """
缺失的第一个正数
链接:https://leetcode-cn.com/problems/first-missing-positive
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
进阶:你可以实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案吗?
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
提示:
0 <= nums.length <= 300
-231 <= nums[i] <= 231 - 1
解法:
1. 哈希表... |
5d888d2fdbe53d3ce2811d0aea97f98eb845ea48 | Nigirimeshi/leetcode | /0189_rotate-array.py | 3,505 | 3.5 | 4 | """
旋转数组
链接:https://leetcode-cn.com/problems/rotate-array
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 ... |
a6f3666caa66d1c8d3ceb7267e6613f9b4f96bd3 | Nigirimeshi/leetcode | /0468_validate-ip-address.py | 4,067 | 3.75 | 4 | """
验证 IP 地址
链接:https://leetcode-cn.com/problems/validate-ip-address
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
如果是有效的 IPv4 地址,返回 "IPv4" ;
如果是有效的 IPv6 地址,返回 "IPv6" ;
如果不是上述类型的 IP 地址,返回 "Neither" 。
IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 -255,用 (".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
I... |
7e6bb868bd107963f118061ef7a67891924d1750 | Nigirimeshi/leetcode | /0347_top-k-frequent-elements.py | 4,449 | 3.640625 | 4 | """
前 k 个高频元素
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n),n是数组的大小。
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
... |
5e312e8a1eea4968f113b45c5fadf805ee4b4f0a | Nigirimeshi/leetcode | /0718_maximum-length-of-repeated-subarray.py | 1,986 | 3.59375 | 4 | """
最长重复子数组
链接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray
给两个整数数组 A 和 B,返回两个数组中公共的、长度最长的子数组的长度。
示例:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出:3
解释:
长度最长的公共子数组是 [3, 2, 1] 。
提示:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
解法:
1. 动态规划。
状态:
- A 的下标 i,B 的下标 j。
- dp[i][j] 表示以 A[i] 和 B[j] 为尾元... |
9a0e481b5927b02ca89297bd81a0803af2ca9f8e | Nigirimeshi/leetcode | /0056_merge-intervals.py | 2,454 | 3.65625 | 4 | """
合并区间
链接:https://leetcode-cn.com/problems/merge-intervals
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: intervals = [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: intervals = [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
提示:
intervals[i][0] <= intervals[i][... |
8bf1ef6524c89c5fe541bb48c64640b60e3ea021 | Nigirimeshi/leetcode | /0051_n-queens.py | 3,171 | 3.96875 | 4 | """
N 皇后
链接:https://leetcode-cn.com/problems/n-queens
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例 1:
输入:n = 4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
解释:如上图所示,4 皇后问题存在两个不同的解法。
示例 2:
输入:n = 1
输出... |
24be0bae232d4d0cbc631eab2708e7f997b8daf8 | brianmego/Chat-Message-Parser | /chat_parser.py | 1,457 | 3.59375 | 4 | '''
This script will parse apart a chat string input into
mentions, links, and emoticons
'''
import argparse
import json
import re
from urllib2 import Request, urlopen
def parse_chat(message):
'''
Takes a message string and outputs json of
mentions, links, and emoticons
'''
output = {}
mentio... |
2ee84c47cddf8b6ec63dfc37d2c51f2ee3e006af | veryflying/ltcd | /82-Remove-Duplicates-from-Sorted-List-II/solution.py | 884 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def delete_next(node_i):
... |
2cef8c89d9d6c701b41c29e61134376b7b962f8d | Secaly/N-puzzle | /npuzzle.py | 14,473 | 3.625 | 4 | import pickle
import itertools
import generator
import argparse
MOVE = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
FILE = 'redundant_move_7_12.txt'
def array2d_to_array1d(array_2d, size):
array_1d = []
for x in range(size):
for y in range(size):
array_1d.append(array_2d[x][y]... |
dc7d73b3f8ecc4af1ca23f662eb6db8b24f33640 | kami-sa/python_lab3 | /24.4.py | 454 | 3.640625 | 4 | n = int(input())
words = [input().lower().strip() for i in range(n)]
sort_words = []
for word in words:
sort_words.append(sorted(word))
set_w = set()
for i in range(len(words)):
if words[i] not in set_w:
print(words[i], end=' ')
set_w.add(words[i])
for j in range(i+1, len(words)):
... |
ec680ad364ea3560c791fb435a5db1571c58835e | Padma-1/100_days-coding | /sum_of_diagonal_elements.py | 445 | 3.875 | 4 | ##Sum of Primary and Secondary diagonal elements that are not part in primary diagonal
n=int(input())
mat=[[int(input()) for i in range(n)]for j in range(n)]
diagonal_sum=0
for i in range(n):
for j in range(n):
if i==j:
diagonal_sum+=mat[i][j]
for i in range(n):
j=n-1
i... |
eca7b99471ef304eda470f901f21bf814149f71e | Padma-1/100_days-coding | /seive.py | 1,000 | 3.609375 | 4 | # to find a number is prime or not using seive array-->here once seive is generated and then checking whether that is prime or not based on 0 and 1 on seive array
"""def seivegen():
seive=[1 for i in range(m+1)]
i=2
while(i*i<=m):
if seive[i]==1:
for j in range(i*i,m+1,i):
... |
606fe3d50350078588bbbf2a1f07e3c46b9c66e9 | Padma-1/100_days-coding | /Abundant_number.py | 332 | 4.1875 | 4 | #A number is abundant if sum of the proper factors of the number is greater than the given number eg:12-->1+2+3+4+6=16-->16>12 i.e., 12 is Abundant number
n=int(input())
sum=0
for i in range(1,n//2+1):
if n%i==0:
sum+=i
if sum>n:
print("Abundant number")
else:
print("not Abundant number")... |
ef19ed873171d0c2a9f405b01114f2262926fe0e | Padma-1/100_days-coding | /2power.py | 481 | 3.96875 | 4 | #using logic
n=int(input())
for i in range(1,n//2+1):
if (2**i)==n:
print("true")
break
else:
print("false")
#using and-->if number of 1's is 1 we can represent that number in 2**
n=int(input())
res=0
while n:
n=n&(n-1)
res+=1
if res==1:
print("true")
else:
p... |
89bcd9ade685725d1013e0ec17d7520b9111bb79 | Padma-1/100_days-coding | /fibonacci.py | 605 | 3.828125 | 4 | #fibonacci upto n
n= 10
a = 0
b = 1
print(a,end = " ")
print(b,end = " ")
#i = 2#0,1 already printed
while True:
c = a+b
a,b = b,c#swapping
# i+=1
if c>n:
break
print(c,end=" ")#1 2 3 5 8
###fibonacci of n numbers
n= 10
a = 0
b = 1
print(a,end = " ")
print(b,end = " ")
... |
b63c5ad4a138de403ef34297f1e05d4668c20339 | Padma-1/100_days-coding | /sastry_and_zukerman.py | 674 | 4.15625 | 4 | ###Sastry number:A number N is a Sastry Number if N concatenated with N + 1 gives a perfect square.eg:183
##from math import sqrt
##def is_sastry(n):
## m=n+1
## result=str(n)+str(m)
## result=int(result)
## if sqrt(result)==int(sqrt(result)):
## return True
## return False
##n=int(input... |
539dfb7e29346e4c1ab4c5ae976e004a4f3f535f | aswanthkoleri/Competitive-codes | /Hackerrank/Graphs/Find the nearest clone.py | 2,254 | 3.703125 | 4 | import sys
from collections import defaultdict
def dfsutil(node,graph,color,shortestPathColor,visited):
val=sys.maxsize
step=0
# print("The node examined: " + str(node))
visited[node]=True
for adj in graph[node]:
if visited[adj]==False:
val=min(val,dfs(adj,graph,color,sh... |
85f723245ad481884a07e9e961c600ff08658b0c | aswanthkoleri/Competitive-codes | /Interviewbits/Level7-Linked-List/☗ ● Swap List Nodes in pairs - InterviewBit.py | 541 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def swapPairs(self, A):
p=prev=A
head=None
while p!=None and p.next !=None:
a=p
b=p.next
... |
e1b7f6b24852f1add12663025c7938b211b4c23b | aswanthkoleri/Competitive-codes | /Codeforces/Random problems/trailing_loves.py | 784 | 3.5625 | 4 | def gcd(a,b):
if a==0:
return b
else:
return gcd(b%a,a)
def main():
# enter n and b
[n,b]=list(map(int,input().split(" ")))
# factorial = fact(n)
# print(factorial)
# now find trailing zeros
# repeatedly divide factorial until its not divisible by b
# co... |
6dc059d668f1d09a245719f4f7cb8baddfb163ef | aswanthkoleri/Competitive-codes | /Codeforces/Contests/Codeforces contest #546 Div 2/c.py | 583 | 3.578125 | 4 | def main():
# accept n and m
[n,m]=list(map(int,input().split(" ")))
# accept the matrix
a=[input().split(" ") for j in range(n)]
b=[input().split(" ") for j in range(n)]
# print(a)
# print(b)
# traverse through the matrix
for i in range(0,n-1):
for j in range(0,m-1... |
2ffc6fbc036575bc9aa8b29c7bf40b325d0415dd | aswanthkoleri/Competitive-codes | /Disjoint sets/matrix.py | 1,476 | 3.890625 | 4 | def find(parent,i):
if parent[i]==-1:
return i
else:
return find(parent,parent[i])
def union(m,parent,v1,v2):
x=find(parent,v1)
y=find(parent,v2)
parent[x]=y
if m[x]==True or m[y]==True:
m[x]=True
m[y]=True
def main():
[cities,machines]=list(m... |
6361bbacd3b770bb8d3443f0937e6bd001ace510 | aswanthkoleri/Competitive-codes | /Hackerrank/Graphs/BFS Shortest Reach in a Graph.py | 1,627 | 3.671875 | 4 | from collections import defaultdict
import heapq
def main():
# queries
queries=int(input())
# create graph
for _ in range(queries):
graph=defaultdict(list)
[n,e]=list(map(int,input().split(" ")))
# for i in range(1,n+1):
for _ in range(e):
[item1,i... |
f9ccce6f37fa2a1dd5e4fac88f2482c26af977b8 | aswanthkoleri/Competitive-codes | /Interviewbits/Level3-Binary-Search/Matrix Search.py | 911 | 3.875 | 4 | def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)/2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ... |
96af38fcaf676e67b50112b713af0b4d4fa08022 | aswanthkoleri/Competitive-codes | /Codeforces/Contests/Codeforces_Global_Round_3/Quicksort.py | 2,073 | 4.34375 | 4 | def partition(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
# print("Pivot 1 = ",pivot)
# What we are basically doing in the next few steps :
# 1. Whenever we find an element less than the pivot element we swap it with the element starting from the 0th inde... |
42f3b02ce66d44798732848f4cb892edf9153060 | aswanthkoleri/Competitive-codes | /Interviewbits/Level4-Strings/Palindrome String.py | 463 | 3.890625 | 4 | import re
def isPalindrome(string):
# Refine the string to alphanumeric characters
refined="".join(re.findall(r'\w+',string.lower()))
# Now palindrome algo
l=0
h=len(refined)-1
rev=refined[::-1]
if refined==rev:
return 1
else:
return 0
def main():
# *****************Input********************
string=input(... |
e0ec5f6ac601fea0d860fcd0cad703a9e225317f | aswanthkoleri/Competitive-codes | /GeekForGeeks/dynamic_programming/basic/1_dyn.py | 897 | 3.953125 | 4 | # Ugly Numbers
# Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included.
# Given a number n, the task is to find n’th Ugly number.
UGLY=[0]*(10**4)
def ugly(n):
global UGLY
UGLY[0]=1
i... |
00a66a293f6989d91871e8998d82f260d66a3bda | aswanthkoleri/Competitive-codes | /Hackerrank/Mathematics/Is Fibo.py | 497 | 3.8125 | 4 | def isFibo():
t=int(input())
for i in range(t):
target=int(input())
prev1=0
prev2=1
current=prev1+prev2
flag=0
while current<=target:
if current==target:
flag=1
break
prev1=prev2
prev2=current
... |
44e4a22c1318e44f75e74af86558246f9acecd83 | lavish205/hackerrank | /time_conversion.py | 913 | 4.3125 | 4 | """PROBLEM STATEMENT
Given a time in AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM... |
13e534a96bf8c37d663032a74b037ed2566aac3d | mtaufiqaryadi/pemrograman-jaringan | /pengenalan/latihan.py | 157 | 4.09375 | 4 | #for i in range(1, 30, 2):
# print (i)
#for i in range (3, 27, 1):
# if (i%3 == 0):
# print (i)
for i in range(1, 6, 1):
print("*"*i)
|
600314d93d7fc8aad9752a3f1a6a497d798a7b27 | dsohum/detecting-malicious-urls | /NeuralNets.py | 4,720 | 3.578125 | 4 | import numpy as np
import math
import csv
# import ML
# import Dimentionality_Reduction
import os
import sys
def sigmoid(x):
return 1.0/(1.0+np.exp(-x))
#derivative of sigmoid wrt x
def sigmoid_prime(x):
return sigmoid(x)*(1-sigmoid(x))
class NeuralNetwork:
#constructor
def __init__(self, layers, act... |
67d4b33b1fe030f8b62b522efe97e0af54b90a78 | eric-meehan/MusicalAlgorithmsAndFundamentalStructures | /Main.py | 2,149 | 4.09375 | 4 | """
This is the main function that will run all of the algorithms needed to generate a counterpoint exercise in the style of Fux.
It is quite simple, and will simply run until stopped.
"""
# This file will need the Counterpoint class and the graphing function
from Counterpoint import Exercise
# The graphing function ... |
581091fe56a0b705db8ba71f8de61a800bb3cab9 | rocomenty/temporary | /minesweeper.py | 1,525 | 3.671875 | 4 | class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
def checkAdjacent(click):
nonlocal board
count = 0
for row in range(max(0, click[0] - 1), min(len(board), click[0] + 2)):
for col in range(max(0, click[1] ... |
c690367701dc910a615a3adc319207660dafd6c7 | seedy1/text_cleaning_functions | /remove_punctuations.py | 455 | 3.53125 | 4 | import string
import re
# pass it into your corpus and see the magic
def remove_punctuations(text):
text = text.lower()
text = re.sub('\[.*\]', '', text)
text = re.sub('[%s]' % re.escape(string.punctuation), ' ', text) # removes punctuation and other symbol
text = re.sub('\n\n\n', '', text)
text =... |
9aae3ac09e79ef5df31f0ca356490efa34083270 | isakura313/07_05_01 | /oop/Tesla.py | 808 | 3.765625 | 4 | from Car import Car
from Battery import Battery
class Tesla(Car):
"""Представляет из себя класс автомобиля с электродвигателем"""
def __init__(self, speed, marka="Tesla", condey=True):
super().__init__(marka, speed, condey)
#с помощью мы получаем доступ к атрибутам класса родителя
self.... |
6e6fafee2da6a120876ad46030b148e602fe38cf | isakura313/07_05_01 | /bench/cikl.py | 173 | 3.53125 | 4 | def cikl(n):
if n == 0 or n == 1:
return 1
else:
prod = 1
for i in range(1, n+1):
prod *= i
return prod
# print(cikl(5)) |
5c6961398b359fb9ba25f4e63a4f6b310e7f6c24 | AviBomb/Hill_Cipher | /Hill_Cipher.py | 4,918 | 3.59375 | 4 | import numpy as np
from egcd import egcd
import math
# Converts Plain Text to Numberical Array of size 1*n (ie: 1 row and n columns)
def lettonum(string):
numarray = []
i=0
for letter in string:
if(letter.isupper()==True):
number = ord(letter)-65
if(letter.islower()==True):
... |
db4ddabad4e06351428963d6bd8075415338cba1 | Zhenyaair/Praktika-Python | /Taks0/task.py | 526 | 3.609375 | 4 | from random import randint
x = []
y = []
maxnum = 0
for a in range(30):
x.append(randint(-100, 100))
print("\n Список 30 випадкових чисел: \n",x)
for a in x:
if a > maxnum:
maxnum = a
print("\n Максимальне число iз спискy:",maxnum)
print(" Індекс:",x.index(maxnum)+1)
for a in x:
if a % ... |
b23a7f2f49905d85a3c16c037effe817dcfe7078 | Hiep0701/Python_PythonFlask | /demo.py | 4,572 | 3.953125 | 4 | # Biến
a = 4
b = 5
print(a+b)
# Method
def plus(a,b):
return(a+b)
print(plus(3,4))
# List và Tuple
a = [1,2,3,4,5] # Tạo list a
b = (1,2,3,4) # Tạo tuple b
print(a)
print(b)
# xuất địa chỉ hex của a, b
print("Address a: ", hex(id(a)))
print("Address b: ", hex(id(b)))
# remove số ở vị trí 2... |
37d31bb95ba329fc44d55a1edd1e6b8b49b474d9 | tkamerman/pygame | /Assignment 1/textrpg_0_1.py | 3,351 | 3.734375 | 4 | # Source File Name: textrpg.py
# Author's Name: Trevor Kamerman
# Last Modified By: Trevor Kamerman
# Date Last Modified: Thursday May 23, 2013
"""
Program Description: This program is a roleplaying game conveyd through
text and played by imputting commands into the comsole
Version: 0.... |
deeea87693fe3f3cc9bfcc0d542544764b94028a | datpht/session2 | /session2_HW2.py | 116 | 3.9375 | 4 | n = int(input("nhap n: "))
factorial = 1
for i in range(1,n+1):
factorial = factorial * i
print(factorial) |
6e19b6a8bc213cb6ac4759418ae9d46e9cad2b84 | gmulholland/100daysofcode | /lovecal.py | 999 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Love Calculator app
"""
__author__ = 'GM'
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
name1_score = 0
name1.lower()
if name1.count("t"):
name1_score += 1
if name1.count("r"):
name1_sco... |
282181736069121b2ffc98713b47efc296cc0c13 | gmulholland/100daysofcode | /cointoss.py | 202 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Head and Tails random app
"""
__author__ = 'GM'
import random
toss = random.randint(1, 2)
if toss == "1":
print("Heads")
else:
print("Tails")
|
336462673f1eccec9e6b8cd938c8d9c5af4c8018 | alihasan01/CodingInterview_Python | /Chapter2/removeDuplicates.py | 1,503 | 4.3125 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
# Time Complexity O(n)
# Space complexity Complexity O(n)
class linkedList:
def __init__(self):
self.head = None
def insertAtStart(self,data):
node = Node(data , self.head)
self.hea... |
c10e368bc908fc21bf3942ba2183f3fb3d6b232b | alihasan01/CodingInterview_Python | /Chapter1/OneAway.py | 755 | 3.953125 | 4 | # Time Complexity O(n)
# Space complexity Complexity O(1)
def oneAway(string1 , string2):
count1 = 0
count2 = 0
check = False
print(len(string1))
print(len(string2))
while count1 < len(string1) and count2 < len(string2):
if string1[count1] == string2[count2]:
count1 += 1
... |
c7b26dd29739edb1e8aa671f1b7a41e03ad1134a | alihasan01/CodingInterview_Python | /Chapter2/Intersection.py | 1,855 | 4.1875 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
# Time Complexity O(n)
# Space complexity Complexity O(1)
class linkedList:
def __init__(self):
self.head = None
def insertAtStart(self,data):
node = Node(data , self.head)
self.head =... |
06deef41c28a2bb24074dfd42bc87f99495e4d3a | cob0013/Kattis-Problems | /Python/minspantree.py | 1,096 | 3.65625 | 4 | def find(x, parents):
if parents[x] == x:
return x
parents[x] = find(parents[x], parents)
return parents[x]
def union(x, y, p):
p[find(x, p)] = p[find(y, p)]
def kruskal(edges, n):
edges.sort()
mst = set()
dj = [i for i in range(n)]
for edge in edges:
w, u, v = edge
... |
9105f20452a550f2d6a4c86ef3ac35a0cfe123fb | cob0013/Kattis-Problems | /Python/keywords.py | 204 | 3.609375 | 4 | def main():
n = int(input())
words = set()
for i in range(n):
s = input().lower()
words.add(s.replace(" ", "-"))
print(len(words))
if __name__ == "__main__":
main()
|
a620d2436eee9c60cca4b0e7e4e8a20c836b7897 | cob0013/Kattis-Problems | /Python/UnionFind.py | 610 | 3.890625 | 4 | def find(parents, child):
if parents[child] == child:
return child
parents[child] = find(parents, parents[child])
return parents[child]
def union(parents, childX, childY):
parentX = find(parents, childX)
parentY = find(parents, childY)
parents[parentY] = parentX
def main():
n, q = map(int, input().sp... |
80cedc5db67856cf08169dea9328b358f2c49ac2 | cob0013/Kattis-Problems | /Python/DetailedDifferences.py | 307 | 3.53125 | 4 | def main():
n = int(input())
for i in range(n):
s1 = input()
s2 = input()
output = []
for i in range(len(s1)):
if s1[i] == s2[i]:
output.append('.')
else:
output.append('*')
print(s1)
print(s2)
print("".join(output))
print()
if __name__ == '__main__':
main() |
a339c95feff1e6810af3ecae569e2d69814bc990 | cob0013/Kattis-Problems | /Python/compass.py | 220 | 3.734375 | 4 | def main():
n1 = int(input())
n2 = int(input())
d = n2 - n1
if d > 180:
print(d - 360)
elif d <= -180:
print(d + 360)
else:
print(d)
if __name__ == "__main__":
main()
|
c35e5d9129c8f09a7cad6adfe22ebf7de585f855 | cob0013/Kattis-Problems | /Python/CrossCountry.py | 533 | 3.75 | 4 | from queue import PriorityQueue
# re wrote cleaner but slower dijkstra's
def main():
n, s, t = map(int, input().split())
graph = []
pq = PriorityQueue()
pq.put((0, s))
visited = set()
for i in range(n):
# adj matrix
graph.append(list(map(int, input().split())))
while pq:
weight, vert = pq.get()... |
08bb31abfd91f94822ca2fe0e3c965ec4f8a87a9 | cob0013/Kattis-Problems | /Python/AToweringProblem.py | 953 | 3.6875 | 4 | def main():
tower1 = []
tower2 = []
line = list(map(int, input().split()))
heights = line[:6]
h1 = line[-2]
h2 = line[-1]
found = False
for i in range(6):
for j in range(i + 1, 6):
for k in range(j + 1, 6):
height = line[i] + line[j] + line[k]
if height == h1:
tower1.append(li... |
a803e07081e9c2e4a5fa674842337e27983fdc26 | cob0013/Kattis-Problems | /Python/AboveAverage.py | 299 | 3.78125 | 4 | import statistics
n = int(input())
for i in range(n):
line = list(map(float, input().split()))
test = line[0]
line = line[1:]
average = statistics.mean(line)
count = 0
for x in line:
if x > average:
count += 1
output = (count / test * 100)
print(format(output, '.3f') + "%") |
21381af8f3a634dbe57731df697fe6a8c8e91d7e | cob0013/Kattis-Problems | /Python/textureanalysis.py | 372 | 3.578125 | 4 | def main():
i = 1
while 1:
line = input()
if line == "END":
return
pattern = []
prev = ""
count = 0
for s in line:
if s == ".":
count += 1
else:
if prev != "":
pattern.append
... |
b112df326c7837edca0642ef0b76e6e9c8786f4c | cob0013/Kattis-Problems | /Python/Shirotori.py | 411 | 3.671875 | 4 | n = int(input())
previous = input()
count = 1
words = set()
words.add(previous)
for i in range(n):
word = input()
if (word not in words) and (previous[len(previous) - 1] == word[0]):
words.add(word)
previous = word
count += 1
if (count == n):
print ("Fair Game")
break
else:
if i % 2 =... |
1bde0ccc4a3dbbf42614c2a9efd70bdb6bd12bce | cob0013/Kattis-Problems | /Python/AnotherBrick.py | 437 | 3.703125 | 4 | def main():
h, w, n = map(int, input().split())
bricks = map(int, input().split())
currentwidth = 0
currentheight = 0
for brick in bricks:
currentwidth += brick
if currentwidth > w:
print("NO")
return
if currentwidth == w:
currentheight += 1
if currentheight == h:
break
curre... |
f76b1e5dde090e07c0168143b4d5f31c17bdf1dc | cob0013/Kattis-Problems | /Python/NPuzzle.py | 534 | 3.5625 | 4 | def manhattandist(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1] )
def main():
board = []
desired = []
home = {}
distance = 0
desired.append("ABCD")
desired.append("EFGH")
desired.append("IJKL")
desired.append("MNO.")
for i in range(4):
for j in range(4):
home[desired[i][j]] = (i , j... |
d68049bd93c80b68640bcb623a34f015720dfb0b | cob0013/Kattis-Problems | /Python/erraticants.py | 1,551 | 3.703125 | 4 |
from collections import deque
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def bfs(grid, goalX, goalY):
q = deque()
visited = set()
visited.add((0, 0))
q.appendleft((0, 0, 0))
while q:
currX, currY, moves = q.pop()
if currX == goalX and currY == goalY:
return moves
... |
562ecf75fa96e397780e05075e5db5946515ce56 | madhuranga84/mean | /mean.py | 785 | 3.8125 | 4 | def mean(num_list):
#assert isinstance(num_list, list)
#if len(num_list)==0:
#raise Exception("The algebraic mean of an empty list is undefined...!, please provide a non-empty list.")
try:
return sum(num_list)/len(num_list)
#except ZeroDivisionError as detail: ... |
51235dc97bc9138b22b4477895d4ebcfc7d9fc4b | daniel-bogdoll/unknown_objects_roads | /mseg_semantic/mseg-api/mseg/utils/tsv_utils.py | 2,669 | 3.625 | 4 | #!/usr/bin/python3
import csv
import os
from typing import List, Mapping, Union
"""
Set of utilities for working with tab-separated values (tsv) files.
The tsv format is a convenient way to store a mapping, e.g. a
mapping between taxonomies.
"""
def download_tsv(tsv_fpath, spreadsheet_url) -> None:
"""Use a sy... |
a9b4c04fa8627f344a2baacc36b0121b7913760a | daniel-bogdoll/unknown_objects_roads | /mseg_semantic/mseg-api/mseg/utils/dictionary_utils.py | 1,368 | 3.859375 | 4 | #!/usr/bin/python3
from typing import Any, Mapping
def convert_dictionaries(source_to_middle_dict, middle_to_sink_dict):
""" """
source_to_sink_dict = {}
for source_key, middle_val in source_to_middle_dict.items():
sink_val = middle_to_sink_dict[middle_val]
source_to_sink_dict[source_key... |
289cf9ae13d197c0f2252242b7231b575042495e | daniel-bogdoll/unknown_objects_roads | /mseg_semantic/mseg-api/mseg/utils/csv_utils.py | 1,116 | 3.71875 | 4 | #!/usr/bin/python3
import copy
import csv
import collections
from typing import Any, List, Mapping
def read_csv(csv_fpath: str, delimiter="\t") -> List[collections.OrderedDict]:
"""Copy the data out of a csv file, as a list of OrderedDicts.
Args:
csv_fpath: string representing path to a csv file.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.