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 |
|---|---|---|---|---|---|---|
773bfaecd14ea6f4835042c5de9993e6c8138381 | wadi19-meet/y2s18-python_review | /exercises/for_loops.py | 126 | 3.515625 | 4 | # Write your solution for 1.1 here!
a = 0
for i in range (100):
if i % 2 == 0:
a= a + i
print(a)
|
ccdecbba4d8e0891418182ca641ba395d835dd83 | digant0705/Algorithm | /LeetCode/Python/143 Reorder List.py | 1,509 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Reorder List
============
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
'''
class ListNode(object):
def __init__(self, x):
... |
299443de038fdfe90e3e5e831b25f2caafa621d1 | digant0705/Algorithm | /LeetCode/Python/146 LRU Cache.py | 3,291 | 4 | 4 | # -*- coding: utf-8 -*-
'''
LRU Cache
=========
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists
in the cache, otherwise return -1.
set(key, v... |
562b403f9b863332949ed22748f4077e2bb4bb2d | digant0705/Algorithm | /LeetCode/Python/029 Divide Two Integers.py | 1,590 | 3.921875 | 4 | # -*- coding: utf-8 -*-
'''
Divide Two Integers
===================
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
'''
def getA(x):
'''
任何整数都能够用 a0*2^0 + a1*2^1 + a2*2^2 + ...... an*2^n 来表示,随便给出一个
数,因此计算出来 a0, a1, ..., an,也就计算出来 x 了
'... |
ccee97b325a717c7031159ee1c4a7569ff0675d6 | digant0705/Algorithm | /LeetCode/Python/274 H-Index.py | 1,647 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
H-Index
=======
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h
if h of his/her N papers have at least h citations eac... |
6d047bc382edd279d64793b778e04754c1cca423 | digant0705/Algorithm | /LeetCode/Python/267 Palindrome Permutation II.py | 1,526 | 3.78125 | 4 | # -*- coding: utf-8 -*-
'''
Palindrome Permutation II
=========================
Given a string s, return all the palindromic permutations (without duplicates)
of it. Return an empty list if no palindromic permutation could be form.
For example:
Given s = "aabb", return ["abba", "baab"].
Given s = "abc", return [].... |
693e40ea5d10dbba79140af157db16dcf335edc8 | digant0705/Algorithm | /LeetCode/Python/189 Rotate Array.py | 2,276 | 4.09375 | 4 | # -*- coding: utf-8 -*-
'''
Rotate Array
============
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to
[5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
[sho... |
24c938d94e8c5dacadc4edde1e99bae904cc412e | digant0705/Algorithm | /LeetCode/Python/273 Integer to English Words.py | 2,695 | 3.890625 | 4 | # -*- coding: utf-8 -*-
'''
Integer to English Words
========================
Convert a non-negative integer to its english words representation. Given input
is guaranteed to be less than 2^31 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Mil... |
58c305a71f8c84999b2842c36928b576685297c0 | digant0705/Algorithm | /LeetCode/Python/237 Delete Node in a Linked List.py | 1,008 | 4.03125 | 4 | # -*- coding: utf-8 -*-
'''
Delete Node in a Linked List
============================
Write a function to delete a node (except the tail) in a singly linked list,
given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node
with value 3, the linked list should become ... |
e8163d4faddd7f6abeacdea9c6ebbb86a57dd195 | digant0705/Algorithm | /LeetCode/Python/328 Odd Even Linked List.py | 1,532 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Odd Even Linked List
====================
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. The program should run in O(1) space
compl... |
f43f14fe47b99787333551c200df24d211f2f466 | digant0705/Algorithm | /LeetCode/Python/156 Binary Tree Upside Down.py | 823 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Binary Tree Upside Down
=======================
Given a binary tree where all the right nodes are either leaf nodes with a
sibling (a left node that shares the same parent node) or empty, flip it upside
down and turn it into a tree where the original right nodes turned into left
leaf nodes... |
bb74d28eb5e2fae422a278a02c920d856bd11b5d | digant0705/Algorithm | /LeetCode/Python/059 Spiral Matrix II.py | 1,968 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Spiral Matrix II
================
Given an integer n, generate a square matrix filled with elements from 1 to n^2
in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
'''
class Solution(object):
'''算法思路:
... |
292ff2aabed4d1ade5efce00ea203b575f24eefc | digant0705/Algorithm | /LeetCode/Python/310 Minimum Height Trees.py | 3,259 | 4.40625 | 4 | # -*- coding: utf-8 -*-
'''
Minimum Height Trees
====================
For a undirected graph with tree characteristics, we can choose any node as the
root. The result graph is then a rooted tree. Among all possible rooted trees,
those with minimum height are called minimum height trees (MHTs). Given such a
graph, wri... |
59443ad47a189e168d67e178f4442c0c3f204b9b | digant0705/Algorithm | /LeetCode/Python/242 Valid Anagram.py | 1,603 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Valid Anagram
=============
Given two strings s and t, write a function to determine if t is an anagram
of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if... |
422aa7064b6f08b428a782685507ecd3d6b8b98a | digant0705/Algorithm | /LeetCode/Python/117 Populating Next Right Pointers in Each Node II.py | 1,611 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Populating Next Right Pointers in Each Node II
==============================================
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution
still work?
Note:
- You may only use constant ... |
6199c6bfaf4f031f9310e90d01694b0340d1781a | digant0705/Algorithm | /LeetCode/Python/038 Count and Say.py | 1,032 | 3.859375 | 4 | # -*- coding: utf-8 -*-
'''
Count and Say
=============
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth seque... |
8118e40253720530ba3d45baea3e962054218e3e | digant0705/Algorithm | /LeetCode/Python/304 Range Sum Query 2D - Immutable.py | 6,034 | 3.765625 | 4 | # -*- coding: utf-8 -*-
'''
Range Sum Query 2D - Immutable
==============================
Given a 2D matrix matrix, find the sum of the elements inside the rectangle
defined by its upper left corner (row1, col1) and lower right corner
(row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defi... |
05d03545ebf50ff4b10fab028e49b3823929e74d | digant0705/Algorithm | /LeetCode/Python/089 Gray Code.py | 1,258 | 3.859375 | 4 | # -*- coding: utf-8 -*-
'''
Gray Code
=========
The 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.
For example, given n... |
49948daded2dd54ec0580b90f49602a9f109b623 | digant0705/Algorithm | /LeetCode/Python/114 Flatten Binary Tree to Linked List.py | 903 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Flatten Binary Tree to Linked List
==================================
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
... |
f70831de914e8e30bc7d5b585d604621b153d989 | digant0705/Algorithm | /LeetCode/Python/044 Wildcard Matching.py | 2,354 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Wildcard Matching
=================
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function pr... |
5ef4eea963d52347fe3fb3d14333c96529b490e3 | digant0705/Algorithm | /LeetCode/Python/091 Decode Ways.py | 3,875 | 3.96875 | 4 | # -*- coding: utf-8 -*-
'''
Decode Ways
===========
A message containing letters from A-Z is being encoded to numbers using the
following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways
to decode it.
For example,
Given encoded message "12", it... |
388bb8ca1be4390e813459e675ad97decdd7df66 | digant0705/Algorithm | /Sort/counting_sort.py | 505 | 3.640625 | 4 | # -*- coding: utf-8 -*-
'''
计数排序
=======
设取值范围为 [start, end],长度为 k = end - start + 1, 数组长度为 n
时间复杂度:O(n + k)
空间复杂度:O(k)
是否稳定:是
'''
def counting_sort(array, start=0, end=100):
count = [0] * (end - start + 1)
for num in array:
count[num - start] += 1
i = 0
for v, n in enumerate(count):
... |
059e307b28c0802e22169c32e0dcadb7725360f5 | digant0705/Algorithm | /LeetCode/Python/233 Number of Digit One.py | 2,116 | 3.890625 | 4 | # -*- coding: utf-8 -*-
'''
Number of Digit One
===================
Given an integer n, count the total number of digit 1 appearing in all
non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
'''
class Solution(obj... |
4877878702e050d463e5bf529c4624c191c2fdd0 | digant0705/Algorithm | /LeetCode/Python/151 Reverse Words in a String.py | 1,061 | 4.0625 | 4 | # -*- coding: utf-8 -*-
'''
Reverse Words in a String
=========================
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
'''
class Solution(object):
... |
21a697c1de6c91860e07070e868dd40b2ac73b59 | digant0705/Algorithm | /LeetCode/Python/222 Count Complete Tree Nodes.py | 2,958 | 3.9375 | 4 | # -*- coding: utf-8 -*-
'''
Count Complete Tree Nodes
=========================
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees
In a complete binary tree every level, except possibly the las... |
676462bbeb65b4c86a49a3e15fda440170e117cb | digant0705/Algorithm | /LeetCode/Python/281 Zigzag Iterator.py | 1,770 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Zigzag Iterator
===============
Given two 1d vectors, implement an iterator to return their elements
alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements
returned by next shoul... |
34cba023d6c006885539c141592334de82eace2f | digant0705/Algorithm | /LeetCode/Python/215 Kth Largest Element in an Array.py | 3,238 | 3.9375 | 4 | # -*- coding: utf-8 -*-
'''
Kth Largest Element in an Array
===============================
Find the kth largest element in an unsorted array. Note that it is the kth
largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is al... |
df8486fa5e3b1bf76fb496b4e7d30666f502e400 | digant0705/Algorithm | /LeetCode/Python/188 Best Time to Buy and Sell Stock IV.py | 1,559 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Best Time to Buy and Sell Stock IV
==================================
Say you have an array for which the ith element is the price of a given stock
on day i.
Design an algorithm to find the maximum profit. You may complete at most k
transactions.
Note:
You may not engage in multiple tran... |
5229ef9e95890d4e4cb6970ef00aeb1f9c6a91c5 | digant0705/Algorithm | /LeetCode/Python/094 Binary Tree Inorder Traversal.py | 1,623 | 4.09375 | 4 | # -*- coding: utf-8 -*-
'''
Binary Tree Inorder Traversal
=============================
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
'''... |
f0a86e62cf0ddcab3602dad2afb48c12ae0defe5 | digant0705/Algorithm | /LeetCode/Python/210 Course Schedule II.py | 2,010 | 3.984375 | 4 | # -*- coding: utf-8 -*-
'''
Course Schedule II
==================
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a l... |
1b1ae8b841a23ef9411a169a2e41d7702ad2d7c3 | digant0705/Algorithm | /LeetCode/Python/048 Rotate Image.py | 1,873 | 4.15625 | 4 | # -*- coding: utf-8 -*-
'''
Rotate Image
============
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
'''
class Solution(object):
'''算法思路:
- o = (length - 1) / 2.0 旋转的中心为 (o, o)
- 可以根据 当前点 (row, col) 算出 将要翻转的点为... |
c7731d232c8a19ee8a5a62c6f095c7ef69f12e99 | digant0705/Algorithm | /LeetCode/Python/224 Basic Calculator.py | 2,347 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
Basic Calculator
================
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus
+ or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is alwa... |
3affb20448382ec198dd02902cb3806a46893fbf | digant0705/Algorithm | /LeetCode/Python/285 Inorder Successor in BST.py | 972 | 3.578125 | 4 | # -*- coding: utf-8 -*-
'''
Inorder Successor in BST
========================
Given a binary search tree and a node in it, find the in-order successor of
that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
'''
class Solution(object):
'''算法思路:
线索二叉树
'''
... |
b1d4c792fa5bed9318d6b06ef5040f8033da7b92 | digant0705/Algorithm | /LeetCode/Python/371 Sum of Two Integers.py | 663 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Sum of Two Integers
===================
Calculate the sum of two integers a and b, but you are not allowed to use the
operator + and -.
Example:
Given a = 1 and b = 2, return 3.
"""
class Solution(object):
def add(self, a, b):
for _ in xrange(32):
a, b = a ^ b, ... |
88a04c8ef23064bf13ff3d8a884e87f827ad0178 | digant0705/Algorithm | /LeetCode/Python/047 Permutations II.py | 1,838 | 3.921875 | 4 | # -*- coding: utf-8 -*-
'''
Permutations II
===============
Given a collection of numbers that might contain duplicates, return all
possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
'''
class Solution(object):
'''算法思路:
用 set 去掉重复的序列
... |
0a75d610e2057ba3de810b44e5a8f9503eea8526 | digant0705/Algorithm | /LeetCode/Python/201 Bitwise AND of Numbers Range.py | 1,680 | 3.546875 | 4 | # -*- coding: utf-8 -*-
'''
Bitwise AND of Numbers Range
============================
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND
of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
'''
class Solution(object):
'''算法思路:
最直接的做法
... |
eea376cdc85781a8324b55a52c42fcbfc9f6bd1a | digant0705/Algorithm | /LeetCode/Python/230 Kth Smallest Element in a BST.py | 1,409 | 3.875 | 4 | # -*- coding: utf-8 -*-
'''
Kth Smallest Element in a BST
=============================
Given a binary search tree, write a function kthSmallest to find the kth
smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operati... |
9b501b254e6c49c6b39990ebcab69c7230efd544 | digant0705/Algorithm | /LeetCode/Python/013 Roman to Integer.py | 915 | 3.859375 | 4 | # -*- coding: utf-8 -*-
'''
Roman to Integer
================
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
'''
class Solution(object):
'''算法思路:
从维基百科得到罗马数字的表示方式 https://en.wikipedia.org/wiki/Roman_numerals
只有 I, X, C 可以作为前缀
'''
de... |
dc5fa176d9352e14c8fa39630b37eb845d551cc7 | digant0705/Algorithm | /LeetCode/Python/260 Single Number III.py | 1,447 | 3.828125 | 4 | # -*- coding: utf-8 -*-
'''
Single Number III
=================
Given an array of numbers nums, in which exactly two elements appear only once
and all the other elements appear exactly twice. Find the two elements that
appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order o... |
33802317ca0b2112d7d8bd552349dba81a42089b | digant0705/Algorithm | /LeetCode/Python/077 Combinations.py | 771 | 3.890625 | 4 | # -*- coding: utf-8 -*-
'''
Combinations
============
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
'''
class Solution(object):
'''算法思路:
暴力递归
'''
d... |
a7f54a8d8b11030b98a8e47676358a3a2a807bb2 | digant0705/Algorithm | /LeetCode/Python/275 H-Index II.py | 748 | 3.859375 | 4 | # -*- coding: utf-8 -*-
'''
H-Index II
==========
Follow up for H-Index: What if the citations array is sorted in ascending
order? Could you optimize your algorithm?
'''
class Solution(object):
'''算法思路:
从右往左,找到最后一个使得 num[mid] >= n - mid,返回长度 n - mid
'''
def hIndex(self, citations):
n = len(... |
64e825375b5a1ada878be6c862d5bc1b05d5cd5c | digant0705/Algorithm | /LeetCode/Python/272 Closest Binary Search Tree Value II.py | 4,191 | 3.921875 | 4 | # -*- coding: utf-8 -*-
'''
Closest Binary Search Tree Value II
===================================
Given a non-empty binary search tree and a target value, find k values in the
BST that are closest to the target.
Note:
- Given target value is a floating point.
- You may assume k is always valid, that is: k ≤ total... |
aef52ff69877fd5eb64e95154fef3b30441766e7 | Derfies/nodebox-opengl | /examples/02-transform/01-spiral.py | 2,132 | 3.578125 | 4 | # Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
def draw(canvas):
canvas.clear()
# The origin point of the canvas is in the bottom-left corner.
# That means if you draw a shape or image at ... |
8de6fa814facca8c47c5af4889fca2a44d8d73f0 | jordiori/aoc-2020 | /day16/exercise_part2.py | 3,067 | 3.8125 | 4 | import argparse
from typing import List, Dict
from itertools import permutations
def parse_ticket(line_ticket: str) -> List[int]:
"""Parse a string ticket."""
return [int(x) for x in line_ticket.split(',')]
def parse_restrictions(lines_restrictions: List[str]) -> Dict[str, List[int]]:
"""Parse restricti... |
a0f3158544d02af5bbec94b618e9903202173932 | jordiori/aoc-2020 | /day08/exercise_part1.py | 1,052 | 3.640625 | 4 | import argparse
def solve(input_txt: str) -> int:
"""Solve exercise."""
instructions = input_txt.splitlines()
accumulator = 0
idx = 0
visited_instructions = []
while idx not in visited_instructions:
visited_instructions.append(idx)
ins, offset = instructions[idx].split()
... |
3506f5d6c7592bc781ea62213c305b0447f6246e | jordiori/aoc-2020 | /template/exercise_part2.py | 430 | 3.953125 | 4 | import argparse
def solve(input_txt: str) -> int:
"""Solve exercise."""
# write your magic solution here!
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('input_file')
args = parser.parse_args()
if not args.input_file:
raise ValueError('Missing input_file!'... |
f6e694f065538b7656454d0d5cf37cbc95003014 | jordiori/aoc-2020 | /day06/exercise_part1.py | 688 | 3.796875 | 4 | import argparse
def solve(input_txt: str) -> int:
"""Solve exercise."""
answers = input_txt.split('\n\n')
total_sum = 0
for answer in answers:
diff_answers = set()
for one_answer in answer.split():
for question in one_answer:
diff_answers.add(question)
... |
3d932a1f99d2dc012434a3bc9bc0ff8c285d90c4 | TheWildMonk/automated-birthday-wisher-project | /main.py | 1,247 | 3.578125 | 4 | import os
import random
import smtplib
import datetime as dt
import pandas as pd
# Emails & password
email = "demo@email.com"
password = "##########"
# Create a dictionary from birthdays.csv
df_birthdays = pd.read_csv("birthdays.csv")
birthday_dict = df_birthdays.to_dict(orient="records")
# Check whether any birthda... |
52c040daa48d3430bf264bf53aa3b373579af2c1 | amanvyas1/python-projects-for-beginners | /calendar-gui/main.py | 1,064 | 3.734375 | 4 | from tkinter import *
import calendar
def showCal():
new_gui = Tk()
new_gui.config(background="white")
new_gui.title("CALENDER")
new_gui.geometry("550x600")
fetch_year = int(year_field.get())
cal_content = calendar.calendar(fetch_year)
cal_year = Label(new_gui, text=cal_content, fo... |
7b1aaf61fb16beb8675a9d04f54c1c947e58e452 | percyelbis/least_squares | /matriz.py | 663 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
####### Digitado por usuario
def crear_matriz(f, c):
'''f:filas, c:columnas-->retorna filas
y digitado por el usuario'''
m = [] # Lista vacia
for i in range(f):
# crea una linea i
flinea = [] # lista vacia
for j in range(c... |
45a8cb97e8e8184fec35acf8be8e10e1a086c673 | anatulea/codesignal_challenges | /Python/13_Picturing the Parsibilities/92_weirdEncoding.py | 906 | 3.578125 | 4 | '''
You've been actively exchanging email with one of your colleagues and noticed that you can't open his attachments. Unfortunately, he's just went on a vacation and you need these attached files right now.
You've spent some time studying his emails and discovered that your colleague used the buggy email client which... |
35131f3bff52c30cf0ca3f99445ec08a53f020f6 | anatulea/codesignal_challenges | /Intro_CodeSignal/07_Through the Fog.py/31_depositProfit.py | 953 | 4.25 | 4 | '''
You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold.
Example
For deposit = 100, rate = 20, and ... |
2257eeef7bf514b374f68e233903a2e09e8e6ed8 | anatulea/codesignal_challenges | /Python/01_meetPython/01_truthness.py | 177 | 3.640625 | 4 | xs =[()]
res = [False]*2
# print(res)
if xs:
res[0]=True
if xs[0]:
res[1]=True
# print(res) # [True, False]
def division(x,y):
return x/y
print(division(15,-4) ) |
40da9655f1ceb1450d203efa31a6bfc9a3748220 | anatulea/codesignal_challenges | /Intro_CodeSignal/01_The Jurney Begins/02_centuryFromYear.py | 1,220 | 4.1875 | 4 | '''
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
centuryFromYear... |
b53108845db209df609b3fdf78dbb573fa0d9224 | anatulea/codesignal_challenges | /Intro_CodeSignal/12_Land of Logic/59_spiralNumbers.py | 1,742 | 3.96875 | 4 | '''
Construct a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.
Example
For n = 3, the output should be
spiralNumbers(n) = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]'''
def spiralNumbers(n):
... |
67801342d06b60b610ee909bf60712796894cbad | anatulea/codesignal_challenges | /Python/11_Higher Order Thinking/73_tryFunctions.py | 1,391 | 4.40625 | 4 | '''
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extreme... |
5aad9e93a5ea31881ae22ab18d3944a1d60b966d | anatulea/codesignal_challenges | /Intro_CodeSignal/11_Rainbow of Clarity/50_chessKnight.py | 1,346 | 3.8125 | 4 | '''
Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.
The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like ... |
7d95aafc8e3b783c05196c5ba11e448578bf5a9e | anatulea/codesignal_challenges | /Python/08_Itertools Kit/48_cyclicName.py | 1,147 | 4.71875 | 5 | '''
You've come up with a really cool name for your future startup company, and already have an idea about its logo. This logo will represent a circle, with the prefix of a cyclic string formed by the company name written around it.
The length n of the prefix you need to take depends on the size of the logo. You haven... |
e83daa2475d8a6d6b52b729a9efd90426da429a7 | anatulea/codesignal_challenges | /Intro_CodeSignal/11_Rainbow of Clarity/51_deleteDigit.py | 524 | 3.828125 | 4 | '''
Given some integer, find the maximal number you can obtain by deleting exactly one digit of the given number.
Example
For n = 152, the output should be
deleteDigit(n) = 52;
For n = 1001, the output should be
deleteDigit(n) = 101.
'''
def deleteDigit(n):
str_num = str(n)
nums = []
for i in range(l... |
ae12622ea7ab0959a7e0896b504f683487cac457 | anatulea/codesignal_challenges | /isIPv4Address.py | 1,229 | 4.125 | 4 | '''
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
Given a string, find out ... |
93a720d3f28962640b125a474dd939af8b9bbd7b | anatulea/codesignal_challenges | /Practice tests/03_meanGroups.py | 2,452 | 3.9375 | 4 | '''
You are given an array of arrays a. Your task is to group the arrays a[i] by their mean values, so that arrays with equal mean values are in the same group, and arrays with different mean values are in different groups.
Each group should contain a set of indices (i, j, etc), such that the corresponding arrays (a[i... |
79efe0f71e3216d25af3d67500a29423af62a35f | anatulea/codesignal_challenges | /Intro_CodeSignal/03_Smooth Sailing/13_reverseInParentheses.py | 1,577 | 4.21875 | 4 | '''
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
Example
For inputString = "(bar)", the output should be
reverseInParentheses(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
reve... |
0f30ab84f246ce8c842d54dd760106bcb464304e | anatulea/codesignal_challenges | /Python/02_SlitheringinStrings/19_newStyleFormatting.py | 1,234 | 4.125 | 4 | '''
Implement a function that will turn the old-style string formating s into a new one so that the following two strings have the same meaning:
s % (*args)
s.format(*args)
Example
For s = "We expect the %f%% growth this week", the output should be
newStyleFormatting(s) = "We expect the {}% growth this week".
'''
d... |
36d4e3c31c4e4381a873bd2d55a8de00fa7ab3c3 | anatulea/codesignal_challenges | /Python/11_Higher Order Thinking/77_mergingVines.py | 2,848 | 4.0625 | 4 | '''
One summer Felicia was visiting her granny's summer house. There were several old and withered vines growing in the garden, that no longer produced grapes. Felicia found it sad, and decided to decorate the vines with wooden grapes she carved out herself. She also watered them with cola, since cola makes everything ... |
a31a68973b5fed0408081240d7ae19bb5973c152 | edcs960/python | /교양/6주차 실습4.py | 77 | 3.796875 | 4 | n = int(input())
sum = 0
for x in range(1,n+1,2):
sum += x*x
print(sum)
|
897b57c1fdda9166b3fe965a462964b1d4d4353f | edcs960/python | /교양/9주자 실습1.py | 292 | 3.734375 | 4 | import random
print("4자리 정수를 출력합니다.")
digits = []
digits.append(random.randrange(1,10))
for i in range(3):
while True:
m = random.randrange(10)
if not m in digits:
digits.append(m)
break
for x in digits:
print(x,end="")
|
cedd9e3ec7b4e58fa0847b8d0ba94f99519e845e | edcs960/python | /교양/2주차 실습10.py | 309 | 3.9375 | 4 | num1 = input("첫 번째 정수를 입력하시오: ")
num2 = input("두 번째 정수를 입력하시오: ")
num3 = input("세 번째 정수를 입력하시오: ")
Inum1 = int(num1)
Inum2 = int(num2)
Inum3 = int(num3)
print(Inum1, Inum2, Inum3, "의 평균은 ", (Inum1 + Inum2 + Inum3) / 3, "입니다.")
|
efb904d6d4c0a0e17aeaf6b403d843d5d09764e4 | edcs960/python | /교양/6주차 실습9.py | 171 | 3.5 | 4 | L=[35,23,19,15,81]
for x in L:
prime = True
for k in range(2,x):
if x % k == 0:
prime = False
break
if prime:
print(x)
|
5ef35cd82d9d5428fd4277db7190f95159b9c306 | tessadvries/DSF | /dsf-exercise12-snacknames-refactored.py | 344 | 4.28125 | 4 | friends = {
"Tessa" : " ",
"Manon" : " ",
"Stijn" : " ",
}
for key in friends:
length = len(key)
print(f'Hi {key}! Your name has {length} characters.')
friends[key] = input(f'{key}, what is your favorite snack? ')
value = friends[key]
print(friends)
for key, value in friends.items():
print(f'The favorite sna... |
5998669e825b8cb23bc3efca62c965253c3ec7a5 | tessadvries/DSF | /dsf-exercise01-myfitnesspal.py | 820 | 4 | 4 | calories = 189
fat = 7.7
carbs = 13.4
sugar = 14.7
fiber = 0.6
salt = 0.26
protein = 1.5
amount = input("how many stroopwafels have you had today?")
print("You had " + amount + " stroopwafels today")
amount = float(amount)
user_calories = calories * amount
user_fat = fat * amount
user_carbs = carbs * amount
user_su... |
2ed7b7c71329613c171f81b1e6cffc6edca91925 | rsibiet/computorv1 | /computorv1.py | 4,864 | 3.703125 | 4 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
import sys
import os
from check_arg import *
from format_eq import *
""" - parse l'equation passee
- prend en compte les equations sous forme naturelle (ex: 5 + 4 * X + X^2 = X^2)
- donne la forme reduite sous forme naturelle
- affichage des etapes de resolution
... |
0be2cd20fbd5d270a676683c51aa824826e39d41 | tscizzle/IPD_Morality | /tournament_results.py | 7,394 | 3.859375 | 4 | ########
##
## Wrapper to hold results of a tournament
##
########
class TournamentResults(object):
"""
Calculates and wraps results of tournaments
"""
def __init__(self, botList, interactions, payoffs):
"""
Calculate the scores of the interactions and the total scores for the
... |
a44226e20b14b2d85893f3468fe584af04fb30a7 | gambastian/pythonFibonacci | /fibonacci.py | 768 | 3.84375 | 4 | user_input = input("Ingrese el limite para la serie de fibonacci:")
try:
limit = int(user_input)
print "Calculando serie de fibonacci inferior a " + str(limit)
serie = []
index = 0
current = 0
message = ""
while current <= limit:
if index == 0:
current = 0
elif in... |
ba71af6bb051c7267108636c14fd0e45ad6f4f18 | jo-tez/ML-From-Scratch | /mlfromscratch/examples/genetic_algorithm.py | 1,333 | 3.75 | 4 |
from mlfromscratch.unsupervised_learning import GeneticAlgorithm
def main():
target_string = "Genetic Algorithm"
population_size = 100
mutation_rate = 0.05
genetic_algorithm = GeneticAlgorithm(target_string,
population_size,
... |
ff4a5d265963d3e2f198c5324d0fcfd8abbfd864 | jitske4me/nobel_project | /Corsetti_Day3 | 781 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 11:55:09 2018
@author: leacaterinacorsetti
"""
#to change a header in a csv file for a column
import csv
import os
inputFileName = "processed_countries_1.csv" #file you wanna open
outputFileName = os.path.splitext(inputFileName)[0] + "processed... |
f5f2400b07c3155e4f4710e105434ad7438633bf | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Lab/01. abs_values.py | 178 | 3.875 | 4 | def turn_nums_to_absolute(nums):
return [abs(num) for num in nums]
nums = [float(el) for el in input().split()] #turn elements into floats
print(turn_nums_to_absolute(nums)) |
c9680e5c9c774a74bf435a4c09ba52a1f0374acf | ivn-svn/Python-Advanced-SoftUni | /Stacks-Queues/Lab/02. matching_brackets.py | 440 | 3.734375 | 4 |
OPEN_BRACKET = "("
CLOSE_BRACKET = ")"
def find_match_brackets():
expression = [ch for ch in input()]
opening_brackets = []
for i in range(len(expression)):
if expression[i] == OPEN_BRACKET:
opening_brackets.append(i)
elif expression[i] == CLOSE_BRACKET:
start = ... |
d4d9a9ae96ebf4a33a9758802b9acdfeb555ccdc | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Exercises/12. recursion_palindrome.py | 401 | 4.25 | 4 | def palindrome(word, index=0, reversed_word=""):
if index == len(word):
if not reversed_word == word:
return f"{word} is not a palindrome"
return f"{word} is a palindrome"
else:
reversed_word += word[-(index + 1)]
return palindrome(word, index + 1, reversed_word)
... |
ace6ed6643240ce0f1a66d1234a198535bd4fd3d | ivn-svn/Python-Advanced-SoftUni | /Multidimensional-Lists/Exercises/07.bombs.py | 1,710 | 3.5 | 4 | dead_cell = 0
deltas = [
(0, -1), (-1, -1), (-1, 0), (-1, +1),
(0, +1), (+1, +1), (+1, 0), (+1, -1)
]
# matrix = [
# [8, 3, 2, 5],
# [6, 4, 7, 9],
# [9, 9, 3, 6],
# [6, 8, 1, 2]
# ]
def create_matrix(size):
result = []
for _ in range(size):
line = input().s... |
2aba40daf6215c8e78df77b83b3d211c5ea53671 | ivn-svn/Python-Advanced-SoftUni | /Exam/Problem1..py | 2,122 | 4.03125 | 4 | from collections import deque
def divisible(sum_values, firework_types):
is_divisible = True
if sum_values % 3 == 0 and sum_values % 5 == 0:
firework_types["Crossette"] += 1
elif sum_values % 3 == 0:
firework_types["Palm"] += 1
elif sum_values % 5 == 0:
firework_types["Willow"]... |
b203a5382d2f7f3ae890a6485f9cfcfae6651148 | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Lab/08. expressions.py | 577 | 3.59375 | 4 |
def recur_expression(nums, current_sum=0, result=""):
if not nums:
return result, current_sum
result_plus = recur_expression(nums[1:], current_sum + nums[0], f"{result}+{nums[0]}")
result_minus = recur_expression(nums[1:], current_sum - nums[0], f"{result}-{nums[0]}")
return result_plus + resu... |
6f6018b330b3628272a4dba51c38f363bb2d03ca | ivn-svn/Python-Advanced-SoftUni | /Multidimensional-Lists/Lab/04. symbol_in_matrix.py | 742 | 3.9375 | 4 | def create_matrix(size):
result = []
for n in range(size):
result.append(list(map(str, input())))
return result
def search_symbol(matrix, size, symbol):
is_found = False
location = []
for r in range(size):
if is_found:
break
for c in range(size):
... |
4473191b48b90a9576f654df44a01ac1cfbef05d | ivn-svn/Python-Advanced-SoftUni | /Exam/Problem2..py | 2,053 | 3.78125 | 4 | from math import floor
PLAYER = "P"
WALLS = "X"
def create_matrix(size):
return [input().split() for line in range(size)]
def find_player_position(matrix, PLAYER):
for row in range(len(matrix)):
for col in range(len(matrix)):
if matrix[row][col] == PLAYER:
return (row, col... |
a08a6e158d778ca35b48bb34f8c39030f895f598 | ivn-svn/Python-Advanced-SoftUni | /Comprehensions/Lab/04. flat_matrix.py | 287 | 3.84375 | 4 | def create_matrix():
rows = int(input())
result = [[int(x) for x in input().split(", ")] for _ in range(rows)]
return result
def flatten_matrix(matrix):
result = [n for row in matrix for n in row]
return result
matrix = create_matrix()
print(flatten_matrix(matrix)) |
011343941c9fb81bf4e4523c8e8d6559650e1918 | hangnew/python_studies | /210711 day01/08.py | 328 | 3.703125 | 4 | coffee_Price = input('커피값 입력')
coffee_Count = input('인원수')
sum = int(coffee_Price) * int(coffee_Count)
if sum >= 20000:
print('2000원을 할인해드립니다.')
print(sum - 2000, '원 결제하세요')
else:
print('계산값을 다 지불하셔야합니다')
print(sum, '원 결제하세요')
|
04a0de18186df4d15882d400fa2301d6a2f98183 | hangnew/python_studies | /210805 day50:51:52/class02.py | 1,149 | 3.75 | 4 | # 클래스의 상속, 메서드 오버라이딩
class FourCal:
# 생성자
def __init__(self, first, second):
self.first = first
self.second = second
# 메서드 첫 번째 매개변수 : self
# 호출한 객체 자신이 전달된다.
def setdata(self, first, second):
# 객체에 생성되는 객체만의 변수를 객체변수라고 부른다.
self.fisrt = first
self.second =... |
370c99e1cd146cf011a19b05a9b77433446e7d58 | chetanpant11/HackerRankCompetitiveProgramming | /Taum and Bday.py | 792 | 3.5 | 4 | t = int(input().strip())
for t_itr in range(t):
first_multiple_input = input().rstrip().split()
b = int(first_multiple_input[0])
w = int(first_multiple_input[1])
second_multiple_input = input().rstrip().split()
bc = int(second_multiple_input[0])
wc = int(second_multiple_input[1])
z = ... |
8c4dd6b4f43c3047bcdc057c3c8037f9ed4f71ef | guilhermeborges84/Programacao | /Curso JLCP/Exercícios/Exercicio2.py | 701 | 4.15625 | 4 | #Definino as variáveis
nome = str(input("Digite o seu nome: "))
cargo = str(input("Digite o seu cargo: "))
concatenado = 'Nome:' + nome + ' ,' + ' Cargo:' + cargo
#Concatenando manualmente
print(f'Valores concatenados manualmente: {nome} {cargo}')
print(f'Juntando string usando variáveis: {concatenado}')
inserir = in... |
a4f6b048383dcd7592a1f5859d1c504ef429b93c | guilhermeborges84/Programacao | /Curso JLCP/Tupla Lista Dicionários/Enumarate.py | 535 | 3.984375 | 4 | cardapio =['Carne','Queijo','Pizza']
for indice,recheio in enumerate(cardapio): #O enumerate colocou indice no cardapio [0]Carne,[0]Queijo,[0]Pizza
print(f'O indice é: {indice} e o recheio é: {recheio}')
opcao = int(input('Digite o valor desejado: '))
'''if opcao < 0 or opcao >indice:
print("Escolha opção d... |
d989002af2c4e04daf8f53664f37297698df151e | SuYuxi/yuxi | /Algorithms/Stack/20. Valid Parentheses.py | 321 | 3.609375 | 4 | class Solution(object):
def isValid(self, s):
stack = list()
Mapping = {'}': '{', ']': '[', ')': '('}
leftBracket = ['{', '[', '(']
for char in s:
if(char in leftBracket):
stack.append(char)
elif(char in Mapping):
if(not stack or stack.pop() != Mapping[char]):
return False
return not stack... |
8ec9085fed00aa316025c1c88669a9249ce37e3b | SuYuxi/yuxi | /Algorithms/Backtracking/77. Combinations.py | 499 | 3.515625 | 4 | #combinations
from itertools import combinations
class Solution(object):
def combine(self, n, k):
return list(combinations(list(range(1, n+1)), k))
#backtrack
#super fast!
class Solution(object):
def combine(self, n, k):
def backtrack(pre, k, left):
if(not k):
L.append(pre)
return
for inx in range(... |
4fae5fc937078b1428be503736ea698b26cb0622 | SuYuxi/yuxi | /Program Contest/AtCoder/Grand Contest 004/A.Divide a Cuboid.py | 146 | 3.5625 | 4 | str = input()
num = list(map(int,str.split(' ')))
if ((num[0]%2)and(num[1]%2)and(num[2]%2))==0:
print(0)
else:
num.sort()
print(num[0]*num[1])
|
2d3c311f61d0864c3205ed7f50618e712dbd8658 | SuYuxi/yuxi | /Algorithms/Math/504. Base 7.py | 224 | 3.515625 | 4 | class Solution(object):
def convertToBase7(self, num):
if(not num):
return '0'
if(num < 0):
return '-' + self.convertToBase7(-num)
res = ''
while(num):
res = str(num % 7) + res
num //= 7
return res
|
f3946cde9b458f7e24e47188ce809f6bcead79bf | satish3366/PES-Assignnment-Set-2 | /37_dist_operations.py | 791 | 4.3125 | 4 | dict1={'Empid':12,'Ename':'Vijay','Band':'B1'}
dict2={'Rollno':11,'Name':'Arshiya','Class':7}
dict3={'Kname':'Ashu','Kage':8,'Bgroup':'B+'}
if dict1>dict2 and dict1>dict3:
print ("dict1 is th biggest",dict1)
elif dict2>dict1 and dict2>dict3:
print ("dict2 is the biggest",dict2)
else:
print ("dict3 is the ... |
3d7c284cdc7983c91d2259017ef5681da3a21a19 | gustingonzalez/ml-it-challenge-2017 | /South Africa/resolution.py | 607 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 02/09/17
def challenge_hash(s):
h = 7
letters = "acdegilmnoprstuw"
for i in range(0, len(s)):
h = (h * 37 + letters.index(s[i]))
return h
# Reverse de hash
def challenge_hash_reverse(h):
s = ""
letters = "acdegilmnoprstuw"
while(h/... |
e9c0c9c90d85a0f8d0da8ca272c5e171c0d3906c | jducuara42/estructurasDeDatos | /Proyecto/principal.py | 3,299 | 3.5625 | 4 | from manejarXML import *
def main():
"""
lat2 = math.radians(9.366429043)
lon2 = math.radians(-67.9766140)
lat1 = math.radians(9.483648265)
lon1 = math.radians(-67.4801781)
print("lat2: ", lat2, " lat1: ", lat1)
print("lon2: ", lon2, " lon1: ", lon1)
#lat2, lon2, lat1, lon1 = map(radia... |
8f825bfa9e66b6e466119d271afb5a9e371d3a30 | NickCrews/CP215-ApplicationDesign | /Tweets/tweet.py | 1,391 | 3.65625 | 4 | '''
tweet.py
Holds the implementation of the Tweet Class
Nick Crews
2/19/16
'''
import csv
class Tweet:
def __init__(self, usr, txt, date, polarity):
# username string of author
self.usr = usr
# string of actual Tweet text
self.txt = txt
# all dates are represented as strings in format "Mon Apr 06 22:19:49... |
6555d3380ba72594cc3f8543658ecc1acfb98bd8 | rgp5043/python | /a1/loanPayments.py | 892 | 4 | 4 | #Author: Brian Stamm
#Assignment: loanPayments.py
#Date: 12.21.15
#Notes: None.
import math
def main():
print()
loan = float(input('Amount of loan: $'))
rate = float(input('Monthly interest rate: '))
pay = int(input('Number of payments: '))
c = (rate / 100) + 1
d = math.pow(c, pay)
a ... |
fdbc53e35a59d822757929ae58167a938c485dda | rgp5043/python | /pastHW/madLips.py | 2,492 | 3.8125 | 4 | #Brian Stamm
#CSC 110
#HW 1 - Mad Lips
#9.29.14 v2
#Original story
#The other day, I was walking with my dog, and then the most amazing thing happened!
#We were in the middle of Discovery Park, and then a leprechaun jumped out of the bushes!
#“Hello, my name is Patrick! And I will grant you 1 wish(es)!”
#“... |
3a7baad4cf891fe0d8bb6a7b5fa11ce938cbfda8 | om-100/assignment2 | /11.py | 519 | 4.6875 | 5 | """Create a variable, filename. Assuming that it has a three-letter
extension, and using slice operations, find the extension. For
README.txt, the extension should be txt. Write code using slice
operations that will give the name without the extension. Does your
code work on filenames of arbitrary length?"""
def filen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.