blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
570b3042c709303cf71132f27f692335df9b1b7e | euxuoh/leetcode | /python/str/integer-to-roman.py | 958 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
12. Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/1/4
"""
cl... |
76e277daa49402a437f21d46980fca3681fa86dc | euxuoh/leetcode | /python/str/add-binary.py | 890 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/1/9
"""
class Solution(object):
def addBinary(self, a, b):
... |
68649e9bdb190a46d2bdf404ed7abaf379d3e1ff | euxuoh/leetcode | /python/hashtable/longest-substr-without-repeat.py | 1,628 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
... |
e9f883f815bf3fc0a3e39f9683090717e88071b0 | euxuoh/leetcode | /python/str/compare-version-numbers.py | 2,002 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
165. Compare Version Numbers
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
Th... |
99bc8daf7079174da095c364e8177346188eb4a5 | euxuoh/leetcode | /python/two-pointer/partition-list.py | 1,264 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
86. Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2-... |
865052e19bac38e3ef36184137e351c210582d11 | euxuoh/leetcode | /python/tree/next-node.py | 1,800 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
剑指offer:58
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/9/23
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
... |
a0e4213256f92ae1b9196220d974d8e76b9d128a | euxuoh/leetcode | /python/sort/count-sort.py | 737 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
doc string
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/3/5
"""
class CountSort(object):
def count_sort(self, nums):
if len(nums) <= 1:
return nums
_min, _max = min(nums), max(nums)
count, res = [0]... |
b3ef8e0a6c4c486ddc7e9f85ed4c2f5d11ff8dee | euxuoh/leetcode | /python/hashtable/word-pattern.py | 1,954 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
290. Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" shoul... |
4f073b5f1a4d0a1803361d589f3e804e48761c3a | euxuoh/leetcode | /python/hashtable/number-boomerangs.py | 1,217 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
447. Number of Boomerangs
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k)
such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerang... |
4500182a151902292a99c23e1ce5dfce1cf85088 | euxuoh/leetcode | /python/hashtable/island-perimeter.py | 2,187 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
463. Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally).
The grid is completely surrounded by water, and there is exactly one i... |
4026c770a87752553a127017e8364f244b257846 | euxuoh/leetcode | /python/hashtable/bulls-and-cows.py | 1,580 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
299. Bulls and Cows
You are playing the following Bulls and Cows game with your friend:
You write down a number and ask your friend to guess what the number is.
Each time your friend makes a guess, you provide a hint that indicates
how many digits in said guess match y... |
85316282d2a10d23ceb47b90c4299ab9dbcd4394 | euxuoh/leetcode | /python/hashtable/count-primes.py | 705 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
204. Count Primes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2016/12/29
"""
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return 0
... |
1893d12d390ebb0cd9edec4519899cddce5873a5 | euxuoh/leetcode | /python/graph/graph.py | 3,915 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
doc string
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/3/22
"""
from collections import defaultdict
class Graph(object):
def __init__(self, node_list):
self.graph = defaultdict(list)
self.visited = {}
self.add_... |
52af0f9fad277a1377abd34991137d5d5ae4a65e | euxuoh/leetcode | /python/bin-search/sqrtx.py | 1,775 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
doc string
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/3/7
"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x < 2:
return x
left, right =... |
6419d21ed2f6c9ddb9cc87e4ecdc9579291536b3 | bgramson/python_projects | /ooexercise.py | 214 | 3.875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Joe", 23)
p2 = Person("Jimmy", 32)
p3 = Person("Ben", 40)
print(p1.name)
print(p2.age)
print(p3.name) |
572f9633fcfd54fbf1c636da5585d38e9710e468 | xanderdunn/aalgopy | /aalgo/ud120_naive_bayes/nb_author_id.py | 4,489 | 3.859375 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project of Udacity 120 Introduction to Artificial Intelligence.
Use a Naive Bayes Classifier to identify emails by their authors.
Sara has label 0, Chris has label 1.
"""
import numpy
import sys
class SolutionClass(object):
"... |
bf95fffa7f04cfb7c3c172a8f3f2712d76b11d0b | Strijkerr/BachelorThesis | /Scripts/CSV_scripts/most_common_anchors.py | 1,252 | 3.828125 | 4 | #!/usr/bin/python3
from csv import reader
import sys
from collections import Counter
def main () :
file = sys.argv[1]
total_count = 0
empty_count = 0
else_count = 0
anchors = []
anchors2 = []
with open(file, 'r') as total :
csv_reader = reader(total)
next(csv_reader) # Skip ... |
3b41c6fd42567847fe1d5a63dca8cdcd732050ad | Gopalakrishnan1995/python-contact-prog | /contactdetalis/deletecontact.py | 1,407 | 3.984375 | 4 | from tkinter import *
from tkinter import messagebox
import sqlite3
class DeleteContactDetails:
def display(self):
self.delete=Tk()
self.delete.title("DELETE CONTACT DETAILS")
self.delete.geometry("300x300+500+100")
self.namelabel=Label(self.delete,text="Name:").grid(ro... |
e135dd2df77dc18404b81fdc7ac16869464a726c | marofmar/TIL | /2019_09_25_Wed.py | 1,756 | 3.640625 | 4 | '''
Logistic Regression without sklearn library
Soley depending on Numpy
Credits to Codebasics
'''
# Load dependent libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
# Generate dataset
df = pd.DataFrame({"age": [22,25,47,52, 46,56,55,60,62,61,18,28,27,29,49,55,25,58,19,... |
c29521e553530804b3a0ba41a6b8eedf6e5d1e32 | madaniel/IntroToDataStructures | /maman14/main.py | 559 | 3.65625 | 4 |
from maman14.parser import Parser
def main():
parser = Parser()
# Generating random input of list of number, based on the defined number in Parser (for testing purpose)
# user_data_list = parser.user_data_generator()
# Getting the numbers from the user
user_data_list = parser.read_user_data()
... |
207479c5c4f563a011dd4e74669fe6650ed0102f | Kp2442priv/israel.cython | /pig_latin_coder.py | 467 | 3.609375 | 4 |
#coder
def pig_latin(word):
first_letter=word[0]
if first_letter in('aeiou'):
pig_word = word + 'ay'
else:
pig_word = word[1:] + first_letter + 'ay'
return pig_word
#decoder
def pig_latin_decode(word):
last_letter=word[-3]
... |
82a40c181035b4d28692dcc16e53ef9cf0a3f492 | Osmel1999/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,951 | 4.1875 | 4 | #!/usr/bin/python3
"""Module matrix_mul
Multiplies two matrices and returns the result.
"""
def matrix_mul(m_a, m_b):
"""Return the matrix resulting of
the multiplication of m_a and m_b."""
if type(m_a) is not list:
raise TypeError("m_a must be a list")
if type(m_b) is not list:
raise... |
5db62dd302d84796d8d51c712599babb9ceb93a8 | Osmel1999/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 225 | 3.640625 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
new_tuple = ()
tuple_1 = tuple_a + (0, 0)
tuple_2 = tuple_b + (0, 0)
new_tuple = tuple_1[0] + tuple_2[0], tuple_1[1] + tuple_2[1]
return new_tuple
|
46129ccb790e3d564b19a79bf61768dd39fd4a58 | Osmel1999/holbertonschool-higher_level_programming | /0x0B-python-input_output/9-add_item.py | 567 | 3.8125 | 4 | #!/usr/bin/python3
"""Module 9-add_item.
Adds all arguments to a Python list,
and then save them to a file.
"""
import sys
import json
import os.path
save_to_json_file = __import__("7-save_to_json_file").save_to_json_file
load_from_json_file = __import__("8-load_from_json_file").load_from_json_file
my_file = 'add_it... |
cd9cb205d307160644cc8468a14316b86f321e5f | Osmel1999/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 391 | 4.1875 | 4 | #!/usr/bin/python3
"""Module 1-number_of_lines.
Counts number of lines in a file.
"""
def number_of_lines(filename=""):
"""Counts lines in filename.
Args:
- filename: name of the file
Returns:
- number of lines
"""
count = 0
with open(filename) as f:
text = f.readline... |
2527d3c83ad86840fa46393229f23e4fb8015465 | MannyIOI/Competitive-Programming | /Week-1/Day-2/Contest/repeated-string.py | 306 | 3.59375 | 4 | # Complete the repeatedString function below.
def repeatedString(s, n):
total = 0
for i in range(n):
if i >= len(s):
break
if s[i] == 'a': total += 1
other = total * (n // len(s))
for i in range(n % len(s)):
if s[i] == 'a': other += 1
return other |
f80ec113334932db420aef80d0412e3ab3ea44ce | MannyIOI/Competitive-Programming | /Week-1/Day-2/division.py | 744 | 3.65625 | 4 | import math
def longDivision(number, divisor):
ans = ""
idx = 0
temp = ord(number[idx]) - ord('0')
while (temp < divisor):
temp = (temp * 10 + ord(number[idx + 1]) - ord('0'))
idx += 1
idx += 1
while ((len(number)) > idx):
ans += chr(math.floor(temp //... |
4bac3b5b38cc043310489af53161364f5e94f318 | MannyIOI/Competitive-Programming | /Week-2/Day-5/circular-deque.py | 3,004 | 4.1875 | 4 | class Node:
def __init__(self, value):
self.val = value
self.next: Node = None
self.prev: Node = None
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.max_size... |
f23b6a70c1f3712465548806506e0302477968f0 | MannyIOI/Competitive-Programming | /Week-3/Day-4/graph-max-depth.py | 432 | 3.578125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node', count = 0) -> int:
if root == None:
return count
print(root.val)
mx = count + 1
... |
b346ba2e37dcc2bacb29c85997d5f8bf97b3dadb | MannyIOI/Competitive-Programming | /Week-3/Day-2/validate-bst.py | 524 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode, mn = -sys.maxsize - 1, mx=sys.maxsize) -> bool:
if not root:
... |
d3355220dc274a70f2cf58904af722df4fceb8d5 | allisonkoran/Celestia | /GameLoop.py | 7,685 | 3.53125 | 4 |
import game as gm
def playerLeaves(player):
prize=Game.dealTreasure()
if prize ==0:
player.setSpyglass(player.getSpyglass()+1)
print("treasure dealt: %d" %(prize))
prize=player.getTreasure()+prize
player.setTreasure(prize)
def doesCaptainHaveResources(roll, capHand):
capHasResour... |
d41041e312357e8f6eaa6032faca378ec8b3e7ff | gautam20197/SURA-2016 | /FeatureExtractor.py | 8,288 | 3.625 | 4 | import nltk
import string
import re
import math
import operator
import sys
import numpy as np
import os
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.corpus import cmudict
# cmudict stands for Carnegie Mellon Pronouncing Dictionary
# vowels are marked by arithmetic digits in the... |
02d43deb060817dcc1f5ef72243b8608c5bf4751 | katono254/Password_Locker | /credential.py | 1,469 | 3.859375 | 4 | import random
import string
class UserCredential:
credentials_list = [] #empty array for the credential section.
def __init__(self,media,email,p_code,u_name):
"""
__init__ method that helps us define properties for our objects.
Args:
media: New credential media.
email :... |
e967738840b29d833906a43f63a45f6b1139cae8 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_51.py | 279 | 3.96875 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 8: Estrutura de Dados - Aula: 51 """
# 51. Looping dentro de uma lista
valores = [50, 80, 10, 150, 170]
for x in valores:
print(f'O valor final do produto é de R$ {x}')
|
8d491e66352f6aeae79059a8a231bf55e0e22a04 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_42.py | 439 | 3.90625 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 7: Funções - Aula: 42 """
# 42. Print ou Return em Funções
# Functions (Funções):
# DRY - Don't repeat yourself (Não se repita)
# Calcula e retorna uma valor.
def cliente1(nome):
print(f'olá {nome}')
... |
e3b275f9e719178b0118e1763def11b31c97812b | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_47.py | 536 | 3.953125 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 8: Estrutura de Dados - Aula: 47 """
# 47. Manipulando Listas
# listas
# armazenar mais de uma informação em variaveis
# manter a sequencia dos dados em uma variavel
cidade1 = "rio de janeiro"
cidade2 = "São... |
00240591f36d1890ed27e4baf9528ed79f80b639 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_66.py | 422 | 4.46875 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 8: Estrutura de Dados - Aula: 66 """
# 66. Função Map em uma lista
# google: built-in functions in python
# map function
# muito utilizado com listas
# aplicar um função iterable, por item. (list, tuple, dic... |
b6e163e29c7cad4883abe7d84fbd8011e143f059 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_81.py | 1,232 | 4.6875 | 5 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 10: OOP (Python Object-Oriented Programming) - Aula: 81 """
# 81. Calculando a idade do funcionário
# classes
# utilizamos para criar objetos (instances)
# objetos sao partes dentro de uma class (instancias)
... |
6b4120f56077f58c56822f2c2b83667150cc4ed1 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_82_main.py | 633 | 3.515625 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 11: Modulos (Arquivos) - Aula: 82 """
# 82. Criando seu primeiro Modulo - main
# 83. Importando um Modulo
# 85. Aplicando um Modulo
# formar de importar modulos com import e/ou from
# import ppybaAndreIacono_82_func... |
c32b94f00d5b028b957907b19165d2c7a6d68002 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_57.py | 728 | 4.28125 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 8: Estrutura de Dados - Aula: 57 """
# 57. Criando Sets
# set (listas)
# similar a listas
# evita itens duplicados
# nao utiliza index
lista1 = [10, 20, 30, 40, 50, 80, 90]
lista2 = [10, 20, 60, 70]
nu... |
3951796c6c8bbb02f00625966887e208154d21cb | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_29.py | 531 | 3.84375 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 6: Controle de Fluxo - Aula: 29 """
# 29. For Loop - Utilizando Strings
palavra = "google"
palavra = "espetacular"
palavra = "fantastico"
palavra = "inconstitucionalissimamente"
palavra = "pneumoultramicroscopicossil... |
e4c6d686119d6842514599d2db02a648ac1d401c | roblivesinottawa/INT-Python | /list-comprehension/app.py | 157 | 3.765625 | 4 | list_ = [3, 34, 56, 75, 98, 13, 45]
odds = [x for x in list_ if x%2 != 0]
print(list(reversed(odds)))
evens = [y for y in list_ if y % 2 == 0]
print(evens) |
caa814cc029a756b61281854cc51a517912918f8 | smahamkl/ScalaSamples | /sep2020challenge/FindDifference.py | 927 | 3.84375 | 4 | from typing import List
'''
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter... |
e545e9f4640de7f2d4d2852fe9c62f945e19f665 | smahamkl/ScalaSamples | /oct2020challenge/BinaryTreeMinDepth.py | 1,380 | 3.546875 | 4 | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findDepth(self, root:TreeNode, depth:int) -> int:
if root.left == None and root.right == None:
return dep... |
38f13e862e698d8248bca4364cb3f42572cf49c6 | smahamkl/ScalaSamples | /jan2021challenge/RemoveDupsSortedList2.py | 1,426 | 3.828125 | 4 |
'''
Given the head of a sorted linked list, delete all nodes that have duplicate numbers,
leaving only distinct numbers from the original list. Return the linked list sorted as well.
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
... |
68916bd4222690ff73dd9f3283043035199b09ad | smahamkl/ScalaSamples | /ReverseLinkedList2.py | 1,205 | 3.875 | 4 | from os import TMP_MAX
from typing import List, Optional
import sys
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
dummy = ListNode(... |
bd4d79fd58b44009c98a10c88ed75da8c0fd8333 | smahamkl/ScalaSamples | /sep2020challenge/LastWord.py | 552 | 3.5 | 4 | from typing import List
import copy
from itertools import combinations
import re
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if s is None:
return 0
s = re.sub(' +', ' ', s)
strList = s.strip().split(' ')
#strList = [lambda x: x.strip() for x in strLis... |
de80d666282a51872a5cd9c6035339e304ce6140 | smahamkl/ScalaSamples | /CombinationSum4.py | 931 | 3.78125 | 4 | from typing import List
'''
LeetCode 377
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The test cases are generated so that the answer can fit in a 32-bit integer.
'''
class Solution:
def combinationSum4(self, nums: List[int... |
8980a9a682f2c2afe652ead63aec574286a94d17 | smahamkl/ScalaSamples | /ZigZagArr.py | 606 | 3.828125 | 4 | from typing import List
'''
https://practice.geeksforgeeks.org/problems/convert-array-into-zig-zag-fashion1638/1/?page=1&company[]=Amazon&curated[]=1&sortBy=submissions
'''
class Solution:
def zigZag(self,arr, n):
for i in range(1, n):
if i % 2 == 1:
if arr[i] - arr[i-1] < 0:
... |
fa7c67bea2c70e876745e131413cb39c603fd80b | smahamkl/ScalaSamples | /oct2020challenge/LinkedListCycle2.py | 3,201 | 3.875 | 4 | from typing import List
'''
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.
Internally, pos is used to denote the index of the node... |
f2ee11bf035f026186fb825acb79b15db91a2d3c | smahamkl/ScalaSamples | /oct2020challenge/132Pattern.py | 813 | 3.5 | 4 | from typing import List
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) >= 3:
n1 = nums[0]
for i in range(1, len(nums)-1):
n1 = min(n1, nums[i-1])
if nums[i] > n1:
n2 = [num for num in nums[i+1:] i... |
681df783cfbdeb91aa632106bfdcf7bb3dbad9d5 | smahamkl/ScalaSamples | /GroupAnagrams.py | 730 | 3.71875 | 4 | from typing import List
'''
Leetcode - 49
https://leetcode.com/problems/group-anagrams/
'''
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = {}
ans = []
for i in range(len(strs)):
tmp = "".join(sorted(strs[i]))
if tmp not in res:
... |
df0c2dc3bd53a12caac2acc3d7d7abf8ed62590a | smahamkl/ScalaSamples | /SortArray2.py | 1,056 | 3.828125 | 4 | from typing import List
'''
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/1605178/Py3Py-Simple-solution-using-for-loop-and-del-on-list-w-comments
'''
from math import inf
class Solution:
def removeDuplicates(self... |
4abf750fdc6478d02908e0e4ece784d159159a35 | smahamkl/ScalaSamples | /oct2020challenge/Search2DMatrix.py | 2,212 | 3.984375 | 4 | from typing import List
'''
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
'''
class Solution:
def search_list... |
88c87d8e764447159e414031b641fa02653418ae | smahamkl/ScalaSamples | /WordSearch.py | 1,499 | 3.78125 | 4 | from typing import List
'''
LeetCode 79. Word Search
dfs with backtracking problem
'''
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rowlen, collen = len(board), len(board[0])
visited = set()
def wordsearch_backtrack(row:int, col:int, charPos:int)->bool:
... |
81cbe810cb5c54121f2ce9beb37dac5d1d3cf57c | smahamkl/ScalaSamples | /sep2020challenge/TreeLeafSum.py | 2,480 | 4.0625 | 4 | from typing import List
'''
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.
For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the ... |
a6f4c806afcd4051f0b9bbbeb789868a1ff33345 | smahamkl/ScalaSamples | /nov2020challenge/LinkedListBinToDec.py | 1,046 | 3.859375 | 4 | from typing import List
'''
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Expl... |
b86149a9826fe548c2a69caa9b07471b80d962c1 | smahamkl/ScalaSamples | /nov2020challenge/ListAddition.py | 2,902 | 4.09375 | 4 | from typing import List
'''
You are given two non-empty linked lists representing two non-negative integers.
The most significant digit comes first and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, excep... |
0dfbb695e9a8fea406966145b8f4ed5bf88aff9d | smahamkl/ScalaSamples | /sep2020challenge/SeqientialDigits.py | 576 | 3.53125 | 4 | from typing import List
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
digitySeq="123456789"
l = len(str(low))
r = len(str(high))
res = []
for i in range(l, r+1):
for j in range(len(digitySeq)-i+1):
num = int(digityS... |
7c63012ec0828c4979dccbb4c21fa02acfa198a7 | smahamkl/ScalaSamples | /oct2020challenge/RotateArray.py | 1,326 | 3.9375 | 4 |
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,... |
c74842306884b9adc70795fa43971de6bb0d0622 | smahamkl/ScalaSamples | /sep2020challenge/HouseRobber.py | 2,444 | 3.828125 | 4 | from typing import List
'''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping
you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjac... |
1ed1215d619adcbf39386001c3b3fa34df8e06d2 | smahamkl/ScalaSamples | /mar2021challenge/ListIntersection.py | 1,642 | 4.0625 | 4 | from typing import List
'''
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect.
If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
It is guaranteed that there are no cyc... |
36e2183b7d95b15b78ae1cee1c9451f4c65d2fa6 | smahamkl/ScalaSamples | /nov2020challenge/SmallDivisor.py | 3,441 | 3.921875 | 4 | from typing import List
import math
'''
Problem:
-----------
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to thr... |
d0ff205fe14a3be5a02f6c034381d508d025fc55 | tkokhing/kiddyPython | /pyInstiCse/loopsOfWhileFor.py | 1,890 | 4.65625 | 5 | # THIS IS A GOOD SUMMARY ON USAGE OF FOR AND WHILE ELSE LOOPS
# Create a for loop that counts from 0 to 10, and
# prints odd numbers to the screen. Use the skeleton below:
print('\n Print odd inside 0 to 10 using for loop')
for i in range(0, 11):
if i % 2 != 0:
print(i)
print('\n')
# Create... |
9b2ab3e96dae02b447399d9f3aa6789f2f418c87 | tkokhing/kiddyPython | /readWriteFile.py | 4,283 | 3.65625 | 4 | # This is Python for Data Science, Exercise 4-2, by Cognitiveclass.ai
"""
Your local university's Raptors fan club maintains a register
of its active members on a .txt document.
Every month they update the file by removing the members who are not active.
You have been tasked with automating this with your Pytho... |
29819b56dcc4ea25447f99d17f0c77d8c9b990d8 | tkokhing/kiddyPython | /pyInstiCse/test3test3.py | 3,187 | 3.96875 | 4 | # TEST 3 - tricky questions, strange ways of using the codes but it is a good test
# It covers Module 3 - Boolean values,
# conditional execution, loops, lists and list processing,
# logical and bitwise operationsExternal tool
# a = 1
# b = 0
# c = a & b
# d = a|b
# e = a^b
# print (c + d + e)
# my_... |
7e52cdfd8595adf5f8498d01a9934a8e35844a52 | Sonobe-br/mackenzie-python | /Mack_Progr09.py | 2,000 | 4.28125 | 4 | '''Lista de Exercícios Estrutura Sequencial.
Resolva os exercícios em Python -
EXERCÍCIO 1 – Escreva um programa em Python que permita ao usuário
digitar dois números inteiros e exibir o resultado para cada uma das
seguintes operações: soma, subtração, multiplicação, divisão, divisão
truncada, resto e exponenciação.... |
1a1e974b7222ad8f5c8cf0d02d38000ef583dd96 | Sonobe-br/mackenzie-python | /Mack_numInteiros.py | 491 | 4.1875 | 4 | print('Digite um numero inteiro:')
inteiroDigitado1 = int(input())
print('Digite outro numero inteiro:')
inteiroDigitado2 = int(input())
exibeQuadrado = (inteiroDigitado1*inteiroDigitado2) /2
print(exibeQuadrado)
'''soma = numero1+numero2
subtracao = numero1-numero2
multiplicacao = numero1*numero2
divisao = nu... |
9039d48e4fea53c62c851147e03004064b4a2ea8 | Sonobe-br/mackenzie-python | /Mack_Progr02.py | 257 | 4.09375 | 4 | '''Faça um programa que receba quatro números inteiros, calcule e mostre a soma desses números.'''
print('Digite quatro números: ')
n1= int(input())
n2= int(input())
n3= int(input())
n4= int(input())
soma= n1+n2+n3+n4
print(f'Soma dos números {soma}')
|
521672e33aba1ee63781dbae1f021d14755c3f62 | SidorovRKN/dz | /kontrlnaya_3_3_.py | 1,654 | 3.515625 | 4 | class Tomato:
states = {0: 'посажен', 1: "первые ростки", 2: "зацвел", 3: "зеленые плоды", 4: "красные плоды"}
def __init__(self, index):
self._index = index
self.s = 0
self._state = self.states[self.s]
def grow(self):
self.s += 1
self._state = self.states[self.s]
... |
a1012b9c1993c4ec1007561303b01d403428bb13 | nsyng/pythonKNUlabs | /Homework 1/Task11Force.py | 317 | 4.09375 | 4 | """
1.1. Обчислити силу притягання F між двома тілами, що мають маси
m1,m2 , на відстані r
"""
m1 = float(input('m1: '));
m2 = float(input('m2: '));
r = float(input('r: '));
y = 6.673*10**-11;
result = y*m1*m2/(r**2);
print('Result: ', result)
|
6dcccc450c6885d1c8ffd7b83a408d51cdb0a242 | mr-kkid/tensorflow | /test2.py | 866 | 3.640625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x=tf.placeholder(tf.float32,[None,784])
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,W)+b)
y_=tf.placeholder("float",[None,10... |
a4177a186a737ba20ae6272425ca34b2c1d0e8d4 | Giselii/Exercicios_Python | /045_PedraPapelTesoura.py | 1,774 | 3.953125 | 4 | #Crie um programa que faça o computador jogar Jokenpô com você.
from time import sleep
import random
from termcolor import colored
print(colored('=', 'red') * 8, colored('VAMOS JOGAR JOKENPÔ', 'blue'), colored('=', 'red') * 8)
usuario = str(input(colored('Qual sua jogada: ', 'green')))
sleep(1)
print(colored('JO..', '... |
71d43cd67d5de8b8a3af496446bd9559f32dfb18 | Giselii/Exercicios_Python | /004_TestandoTiposeOutros.py | 1,097 | 4.1875 | 4 | #Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo
# primitivo e todas as informaões possíveis sobre ele
#Usar os métodos .is
#OBSERVAÇÃO: Nos casos abaixo o 'a1' é um OBJETO e
#os ".is..." são os métodos.
a1 = input('Digite algo: ')
print('O tipo primitivo de {} é:'.format(a1), type(a1))
#prin... |
e8cf1556bbd03c5058abc0bfb9de6cb1e752bd34 | luiseduardiazc/holbertonschool-higher_level_programming | /0x11-python-network_1/8-json_api.py | 698 | 3.796875 | 4 | #!/usr/bin/python3
'''
Write a Python script that takes in a URL and an email address,
sends a POST request to the passed URL with the email as a parameter,
and finally displays the body of the response.
'''
import requests
import sys
if __name__ == '__main__':
letter = ""
if len(sys.argv) == 2:
letter... |
aaf640d91f4ca9d7daa65739614d8d3f603275ee | luiseduardiazc/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,658 | 4.0625 | 4 | #!/usr/bin/python3
class Square:
def __init__(self, size=0, position=(0, 0)):
self.size = size
self.position = position
@property
def size(self):
return self.__size
@size.setter
def size(self, size):
if type(size) is not int:
raise TypeError('size must b... |
c494d22b1458a1e9d8cb9f644963866fc92550cc | luiseduardiazc/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 3,525 | 3.625 | 4 | #!/usr/bin/python3
""" module class Rectangle """
from models.base import Base
class Rectangle(Base):
""" Rectangle class """
def __init__(self, width, height, x=0, y=0, id=None):
""" constructor """
self.width = width
self.height = height
self.x = x
self.y = y
... |
48781bbd9d2b7b741a7ff8079bca314a8195a8dd | luiseduardiazc/holbertonschool-higher_level_programming | /0x11-python-network_1/2-post_email.py | 583 | 3.796875 | 4 | #!/usr/bin/python3
'''
Write a Python script that takes in a URL and an email,
sends a POST request to the passed URL with the email as a parameter,
and displays the body of the response (decoded in utf-8)
'''
import urllib.request
import urllib.parse
import sys
if __name__ == '__main__':
if len(sys.argv) == 3:
... |
74d79aee6f9fcf0820acd7fd6b20805f56d94800 | luiseduardiazc/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 325 | 3.765625 | 4 | #!/usr/bin/python3
"""
Python - Inheritance
"""
def inherits_from(obj, a_class):
""" returns True if the object is an instance
of a class that inherited (directly or indirectly)
from the specified class otherwise False """
if type(obj) is a_class:
return False
return isinstance(obj, a_cl... |
d881962f800de6f8eed331a6c0425eea3d92a526 | briankracoff/MoodMusic | /song/song.py | 2,254 | 3.5625 | 4 | '''
Song Module, Defines classes to represent songs in the library and infomation
about them
'''
import os
import sys
from data.DB_Helper import DB_Helper
class Song:
def __init__(self, filePath, attributes, moods):
'''
Constructor
'''
self.filepath = filePath
sel... |
88656902cee42a35713b5a3676d23cd521e81615 | anfederico/Bioinformatics-Algorithms | /Genomic Suffix Tree.py | 1,969 | 3.640625 | 4 | class Node(object):
def __init__(self, value, ID):
self.value = value
self.children = {}
self.ID = ID #Label nodes with ID
class Trie(object):
def __init__(self):
self.root = Node(None, 0) #Root is labeled 0
def AddString(self, pattern, ID):
current ... |
3d5f20e54e228e68706d660125b775edcd61869b | elenpetri/Fatec-ADS | /algoritmo e logica de programacao prof masanori/Exercicios/lista de exercicios III/Lista de exercicios III.py | 2,484 | 3.984375 | 4 | # 1- Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue
# pedindo até que o usuário informe um valor válido.
n = float(input('Insira a nota de 0 a 10: '))
while n < 0 or n > 10:
print(f'O valor inserido é inválido. Por favor digite um número de 0 a 10')
... |
2e591e5946371a960fea915ff806c27ba3adc7c4 | eguzman1/389Rfall18 | /week/9/writeup/part1.py | 1,090 | 3.640625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# importing a useful library -- feel free to add any others you find necessary
import hashlib
import string
# this will work if you place this script in your writeup folder
wordlist = open("probable-v2-top1575.txt", 'r')
# a string equal to 'abcdefghijklmnopqrstuvwxyz'.
sa... |
0f79d62416a93e04b1a816a2b4659d558a06499c | Humanot/ZeBrains | /1.py | 1,495 | 4.09375 | 4 | #1
# Написать функцию, которая по переданной строке (например: "Тест"), возвращает словарь ({1: Т, 2: е, 3: c, 4: т}),
# ключами которого будут порядковый номер буквы в строке, а значением буква из строки
def testing(test):
result = []
for i in enumerate(test, start=1):
result.append(i)
return resu... |
423e1e13f3cd3948acefd8047da4b8f6ca6042d9 | nathanbeddes/Project-Euler | /Python/Problem2.py | 168 | 3.59375 | 4 | #! /usr/local/bin/python3.1
sum = 0
fib1 = 1
fib2 = 2
while fib1 < 4000000:
if ((fib1%2) == 0):
sum += fib1
fib1, fib2 = fib2, fib1 + fib2
print(sum)
|
21de86820c2be1453d65221ef50082f7bc4b6464 | orlandosaraivajr/dojo | /2020_MAR_10/dojo.py | 568 | 3.609375 | 4 | def abnt(nome_autor):
nome = 'Orlando Saraiva do Nascimento'
nome_separado = nome.split()
sobrenome = nome_separado[-1].upper()
primeiro_nome = nome_separado[0].capitalize()
nome_final = sobrenome + ', ' + primeiro_nome
return nome_final
# nome_autor = nome_autor.split()
#sobre = nome_... |
f0cda95eb470ade2f345059130da0ed4c6d0dc24 | willtuna/enc_practice | /Dev_Python/test.py | 5,830 | 3.5625 | 4 | #! /usr/bin/python3
import random
import numpy as np
from numpy.polynomial import Polynomial as P
random.seed(100)
# print ("current state of prng: " + str(random.getstate()) )
# undone customize exception handling
'''
class Param_Error (Exception):
def __init__(self,message, errors):
super().__init__(me... |
eab52c1e0ab489adc966b180b650e8eaf5e4b073 | jobobobobobo/callofcthulhu | /interfaces.py | 1,406 | 3.671875 | 4 | from dice import Die
from abc import ABCMeta, abstractmethod
class Addable(object,metaclass=ABCMeta):
def __init__(self, score):
self.score = score
def __add__(self, x):
return self.score + x
def __radd__(self, x):
return self.score + x
def __sub__(self, x):
return se... |
3fccab2996d05c3ace94ec2793ad7ca91bcd8843 | shovalf/CheapNode2Vec | /undirected_cheap_node2vec.py | 13,719 | 3.59375 | 4 | import numpy as np
import networkx as nx
from node2vec import Node2Vec
import time
import heapq
def user_print(item, user_wish):
"""
a function to show the user the state of the code. If you want a live update of the current state of the code and
some details: set user wish to True else False
... |
1b075fbf07cdf1895944608e115b59e6e8cd3a15 | Fiskmes/Calculator | /calculator.py | 636 | 4.09375 | 4 | def plus(x, y):
print(x + y)
def minus(x, y):
print(x - y)
def multiply(x, y):
print(x * y)
def divide(x, y):
if num2 == 0:
print("Error")
else:
print(x / y)
print("Välj vad du vill göra")
print("1. Plus")
print("2. Minus")
print("3. Multiply")
print("4. Divide... |
3b42f498eb7229988658139d83f7304963f9ac7e | max-santiago/School-of-AI-CDMX | /Data Structures/data_structures.py | 404 | 3.78125 | 4 | '''
Implementación de varias estructuras de datos en Python
'''
class Stack:
def _init_(self):
return 'a'
class Queue:
def _init_(self):
return 'a'
class Set:
def _init_(self):
return 'a'
class LinkedList:
def _init_(self):
return 'a'
class BinaryTree:
def _init_(... |
0ef8fa77e002a9af3a2b7375c7964d52c0007bc7 | LouisYLWang/datamining-projects | /Self-organizing maps/somutils.py | 10,173 | 3.703125 | 4 | """
Homework: Self-organizing maps
Course : Data Mining II (636-0019-00L)
Auxiliary functions to help in the implementation of an online version
of the self-organizing map (SOM) algorithm.
"""
# Author: Dean Bodenham, May 2016
# Modified by: Damian Roqueiro, May 2017
from sklearn import datasets
import matplotlib.py... |
f79154a78e168633989cc3d9f7c61f6fd46d1877 | AayushQ/SampleRepo | /3.py | 267 | 4.46875 | 4 | """
3.Write a program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
"""
def last(n):
return n[-1]
def sort(tuples):
return sorted(tuples,key = last)
a = input("Enter a list of tuples:")
print("Sorted:")
print(sort(a))
|
e20de9d0b0715488ebc1db1767dce9c72a80b239 | AayushQ/SampleRepo | /Assignment/2.py | 218 | 3.890625 | 4 | """ 2.Write a program to demonstrate printing pattern of alphabets
A
B C
D E F
G H I J
K L M N O
"""
num = 65
for i in range(0,5):
for j in range(0,i+1):
ch = chr(num)
print(ch) ,
num = num +1
print("\r") |
704219aa058cb50d46b7e6533ed6b2f35cc337d9 | AayushQ/SampleRepo | /Assessment/9.py | 761 | 4.09375 | 4 | """
9.Write a PYTHON program to check the validity of a password chosen by a user. To be considered valid, a password
"""
import re
p= input("Input your password")
def validate(s):
x = True
while x:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not... |
24eee2acbc8f2299313cbee4c8d64660017ef3ef | adityamohta/Algorithms | /Problems/TowersOfHanoi.py | 1,189 | 4.1875 | 4 | """
---------- Tower of Hanoi Problem ----------
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists o... |
f00ebac04a52c877da3510c01ad590d6c369e80d | AcidicNic/old_CS-1.2-Intro-Data-Structures | /tokenize.py | 1,422 | 4 | 4 | def get_word_list(source_text):
''' Splits text_str into a list of lowercase words
Creates an empty dictionary.
For every word in the list that was passed in:
If it's already in the dictionary, increase it's value by one.
Otherwise, add it to the dictionary and set it's value... |
264c037d967b42a6f11d9f233645e44aa9241584 | DENISH220/C-Program | /For loop.py | 119 | 3.890625 | 4 | # Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
|
b751db813621c101cbfdb31c2667bce5b0fa1f26 | mkhi26/inventarioSimple | /python/prueba.py | 415 | 3.78125 | 4 | from nucleo.LinkedList import *
l = LinkedList()
l.LinkedListAdd("Gato")
l.LinkedListAdd("Perro")
l.LinkedListAdd("Pez")
l.LinkedListAdd("Vaca")
l.LinkedListAdd("Pato")
p=l.LinkedListPrint()
print("Los elementos en la lista son: %s"%(p))
n = l.LinkedListSearch("Vaca")
print(n)
print("Se elimina el elemento %s"%(l.... |
054b62ee0fc06950d770a5c928e13ffc727ec2bc | justsimransingh/Python-List-Questions | /07.py | 161 | 4.0625 | 4 | '''
7. Write a Python program to split a list into different variables
'''
l=['red','green','blue']
var1,var2,var3=l
print(var1)
print(var2)
print(var3)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.