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 |
|---|---|---|---|---|---|---|
550d489f9d41b73f7db0db8e7e96dcdcc609dc6f | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/Templates/Merge Sort Linked List.py | 813 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeSort(self, head):
"""
input: ListNode head
return: ListNode
"""
if not head or not head.next:
return head
l1, l... |
5f6cdf7935e247ee5e50f90367d200facee7afc8 | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/Templates/Quick Sort Linked List.py | 2,103 | 3.96875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def get_tail(self, node):
while node.next:
node = node.next
return node
def quickSort(self, head):
"""
input: ListNode head
... |
dd218fb6289c7aa0a9b9cd65c690147a8cac399e | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/Templates/Sort In Specified Order.py | 851 | 3.921875 | 4 | '''
Given two integer arrays A1 and A2, sort A1 in such a way that the relative order among the elements will be same as those are in A2.
For the elements that are not in A2, append them in the right end of the A1 in an ascending order.
Assumptions:
A1 and A2 are both not null.
There are no duplicate elements in A2.... |
712336accf391c82d867555d1cd8fa3e4207cd7c | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/147.insertion-sort-list.py | 2,185 | 4.03125 | 4 | #
# @lc app=leetcode id=147 lang=python3
#
# [147] Insertion Sort List
#
# https://leetcode.com/problems/insertion-sort-list/description/
#
# algorithms
# Medium (41.20%)
# Likes: 683
# Dislikes: 601
# Total Accepted: 189.6K
# Total Submissions: 457.8K
# Testcase Example: '[4,2,1,3]'
#
# Sort a linked list using... |
9e7ade5c7deccd32219807490f213984b6e2e400 | XinheLIU/Coding-Interview | /Python/Algorithm/Devide and Conquer/Binary Search/852.peak-index-in-a-mountain-array.py | 1,548 | 3.6875 | 4 | #
# @lc app=leetcode id=852 lang=python3
#
# [852] Peak Index in a Mountain Array
#
# https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
#
# algorithms
# Easy (71.64%)
# Likes: 740
# Dislikes: 1233
# Total Accepted: 173.7K
# Total Submissions: 242.3K
# Testcase Example: '[0,1,0]'
#
# Let's... |
e3134ab92c775676754277191999a884b62f93bb | XinheLIU/Coding-Interview | /Python/Data Structure/String/Hashable/290.word-pattern.py | 1,530 | 3.609375 | 4 | #
# @lc app=leetcode id=290 lang=python3
#
# [290] Word Pattern
#
# https://leetcode.com/problems/word-pattern/description/
#
# algorithms
# Easy (37.00%)
# Likes: 1203
# Dislikes: 155
# Total Accepted: 196.2K
# Total Submissions: 529.8K
# Testcase Example: '"abba"\n"dog cat cat dog"'
#
# Given a pattern and a s... |
d32d298db12019d3826efa8b40f25b7ec4ad0926 | XinheLIU/Coding-Interview | /Python/Data Structure/Linear List/Stack/85.maximal-rectangle.py | 2,651 | 3.609375 | 4 | #
# @lc app=leetcode id=85 lang=python3
#
# [85] Maximal Rectangle
#
# https://leetcode.com/problems/maximal-rectangle/description/
#
# algorithms
# Hard (37.84%)
# Likes: 3066
# Dislikes: 71
# Total Accepted: 186.5K
# Total Submissions: 492K
# Testcase Example: '[["1","0","1","0","0"],["1","0","1","1","1"],["1"... |
0c97d54326a4eb661b1a15e6aaf3adb09251855c | XinheLIU/Coding-Interview | /Python/Algorithm/Sorting/215.kth-largest-element-in-an-array.py | 1,641 | 3.703125 | 4 | #
# @lc app=leetcode id=215 lang=python3
#
# [215] Kth Largest Element in an Array
#
# https://leetcode.com/problems/kth-largest-element-in-an-array/description/
#
# algorithms
# Medium (50.46%)
# Likes: 2928
# Dislikes: 208
# Total Accepted: 522.6K
# Total Submissions: 999.9K
# Testcase Example: '[3,2,1,5,6,4]\... |
e167a07deb09c1053bc4015943229feafb983468 | XinheLIU/Coding-Interview | /Python/Data Structure/Binary Tree/Kth Smallest Element in a BST.py | 790 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
p, stack, ret = root,[],[]
while p or len(stack):
w... |
57bb40f8600a8f18db904c9a766124a168376dc4 | XinheLIU/Coding-Interview | /Python/Data Structure/Linear List/Linked List/Operations/206.reverse-linked-list.py | 833 | 3.953125 | 4 |
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, c... |
5033093522e482f4ea0f0b41890670be2cf1675d | XinheLIU/Coding-Interview | /Python/Data Structure/Binary Tree/Binary Search Tree/Recover Binary Search Tree.py | 1,625 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# Morris Traversal
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not ... |
8a1d49b9d4ad048e3ba05e57db892d828e5e6f33 | XinheLIU/Coding-Interview | /Python/Data Structure/String/Palindrome/5.longest-palindromic-substring.py | 2,213 | 3.625 | 4 | #
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# https://leetcode.com/problems/longest-palindromic-substring/description/
#
# algorithms
# Medium (29.50%)
# Likes: 7738
# Dislikes: 565
# Total Accepted: 1M
# Total Submissions: 3.4M
# Testcase Example: '"babad"'
#
# Given a string ... |
48479aa89d5f610f0a767ef18111911d236a0e68 | XinheLIU/Coding-Interview | /Python/Data Structure/String/Palindrome/125.valid-palindrome.py | 1,007 | 3.71875 | 4 | #
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
# @lc code=start
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
while l < r and self.skip(s[l]):
l += 1
while l < r and self.skip(s[r]):
... |
cc0a796cabd7257a6c2f4b8c51c9f711d78e4d1c | Mostafa-At-GitHub/Data-Structures-and-Algorithms-codes | /CS_LAB_MA252/graphalgorithms/dijekstra/dijekstra.py | 1,079 | 3.71875 | 4 | import math
from priortyqueue import *
time=0
class vertex:
def __init__(self,name,i):
self.name=name
self.i=i
self.d=math.inf
self.p=None
class edge:
def __init__(self,v,w):
self.v=v
self.w=w
class graph:
def __init__(self,v,aj):
self.v=v
self.aj=aj
def relax(self,p,u,v,w):
#print(u.d+w)
... |
fd582a9d6d7cb601b14703c7e95fe49b39de09b3 | Mostafa-At-GitHub/Data-Structures-and-Algorithms-codes | /CS_LAB_MA252/graphalgorithms/Bellmanford/bellmanford.py | 1,153 | 3.53125 | 4 | import math
import sys
import operator
import random
import string
class vertex:
def __init__(self,name,i):
self.p=None
self.i=i
self.d=math.inf
self.name=name
class edges:
def __init__(self,u,v,weight):
self.u=u
self.v=v
self.weight=weight
def relax(self):
if self.u.d+self.weight<self.v.d:
se... |
ed03a3ce65f80edb740db20c85ad17661658424c | yuliia-mykhailova/python-education | /algorithms/python_data_structures/algorithms_data_structures/data_structures/binary_search_tree.py | 4,978 | 4.1875 | 4 | """Module for Tree realization"""
class Node:
"""Class for binary search tree node implementation"""
def __init__(self, data):
"""Constructor"""
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
"""Class for binary search tree implementation"""
... |
e77fbcc5efd9e4439ff0ade9d1ff7620a7512873 | yuliia-mykhailova/python-education | /algorithms/python_data_structures/algorithms_data_structures/data_structures/graph.py | 1,914 | 4.0625 | 4 | """Module for Graph realization"""
from algorithms_data_structures.data_structures.linked_list import LinkedList, Node
class Vertex:
def __init__(self, data):
self.data = data
self.edges = LinkedList()
def delete_edge(self, node):
"""Deletes edge node from the list of edges"""
... |
450489a948440661755c9c8d0d506c592309626a | yuliia-mykhailova/python-education | /algorithms/algorithms_practice/algorithms/algorithms.py | 1,224 | 3.921875 | 4 | """Module for binary search, quick sort and factorial realization"""
def binary_search(array: list, value: int) -> int:
"""binary search of element in list"""
low = 0
high = len(array) - 1
while low <= high:
middle = int((low + high) / 2)
if array[middle] == value:
return m... |
29d58758c33b74d57e58aed9c8f84b8c157415da | alison99/python | /function.py | 358 | 4.25 | 4 | def print_multiples(n):
i=1
output=""
while i <= 6:
output += str(n*i) + "\t"
i += 1
print(output)
#function called print_multiples
#while loop looks similar
#printing happens here IN the function
#print_multiples(3)
def print_square():
return [n**2 for n in range(10)]
#for n in rang... |
6ad82ffb8dfc549dd9c51920f3c7d1f5cb83d9d1 | alison99/python | /lists.py | 539 | 3.828125 | 4 | listdemo = [1, 2.0, "three", (2**2)]
print listdemo[2]
print type(listdemo)
emptylist = []
print str(len(emptylist))
print str(len(listdemo))
#deletes item from list
del listdemo[0]
print listdemo[0]
if 'three' in listdemo:
print "found you"
print listdemo[-1]
#first element is always 0 - can't refer to it as -4
#... |
5295e580750c71237ee79e311ab866b46a79359f | atom1zer/kripto | /Kripto_1.py | 9,360 | 3.546875 | 4 | from __future__ import print_function
# импортируем библиотеку tkinter всю сразу
from tkinter import *
from tkinter import messagebox as mb
import random
# главное окно приложения
window = Tk()
# заголовок окна
window.title('Курсовая работа по криптографии Самсонов Д.Л. (вариант 20)')
# размер окна
window.geometry('85... |
ecf5b2ce350a36d19b7c82d3051b84cc8ff49509 | mndimitrov92/Python_Scripts | /TicTakToe/logic_v2.py | 2,343 | 3.890625 | 4 | '''
Main logic module for the Tic Tac Toe game.
It is not optionized for a quality game, it simply
generates random moves and checks the result of a
move for a winning line. Rewritten with class.
Exposed Functions:
newGame()
saveGame()
restoreGame()
userMove()
botMove()
'''
import os
import random
import data
class G... |
e7a5a1d0072c3290d74908559ff0c8daa50cc906 | zkoebler/Zephrom-DSA-solutions | /Cracking the coding Interview/Arrays&StringsPg90/palindromePermutation.py | 565 | 3.5625 | 4 | #O(n) time and O(n) space
def isPalindromePerm(string):
mymap = {}
stringA = string.replace(" ", "")
for char in stringA:
if char not in mymap:
mymap[char] = 1
else:
mymap[char] = mymap[char] + 1
offense = 0
for char in mymap:
currentCharNum = mymap[ch... |
d1cecff4a95ed1507862e0e0fc3fb57a3b9d7cfd | Blu3spirits/MTU-Transfer-Course-Gatherer | /scraper/transfers/file_utils.py | 2,826 | 3.828125 | 4 | #!/usr/bin/env python3
import csv
from .data_types import Class_Object
from ..Logger import Logger
class File_Utils(object):
"""
File utilities for writing and reading data from files
"""
def __init__(self):
"""
Blank init
"""
self.log = Logger(self.__class__.__name... |
3fe91143e788f42401d8ec6a8e08fe39eeff479d | Blu3spirits/MTU-Transfer-Course-Gatherer | /scraper/transfers/data_types.py | 4,678 | 3.921875 | 4 | #!/usr/bin/env python3
class Class_Object(object):
"""
Object containing relational information between transferable classes
and MTU's counts for them.
"""
transfering_state_code = ""
transfering_state_name = ""
transfering_college_code = ""
transferring_college_name = ""
transfe... |
011f04127eee015c03781e4e720188933b55c993 | Zurubabel/Python | /Aula8_TrabalhandoComVetores.py | 555 | 4.34375 | 4 | # Aula 8 - Trabalhando com arrays
# Cachaça, coxinha, isqueiro, cigarro, ficha da sinuca (produtos)
produtos = ["Cachaça", "Coxinha", "Isqueiro", "Cigarro", "Ficha da Sinuca"]
# Endereçamento
# produtos[0] = "Pingado"
# produtos[5] = "Pingado"
# Funções
# append - Insiro um elemento no final do vetor
# produtos.app... |
9b998f46160532a9fa287d938ec6794f73e1a316 | JoaoMisutaniAlves/URI_problems | /beginner/1035.py | 271 | 3.78125 | 4 | # -*- coding: utf-8 -*-
numbers = input().split(" ")
A, B, C, D = numbers
A = int(A)
B = int(B)
C = int(C)
D = int(D)
if( B > C and D > A and ( C + D > A + B ) and C > 0 and D > 0 and ( A % 2 == 0 ) ):
print("Valores aceitos")
else:
print("Valores nao aceitos") |
85af06228f6bd17bf616b8292c2a2c8e6274eaa2 | JoaoMisutaniAlves/URI_problems | /beginner/1098.py | 299 | 3.6875 | 4 | # -*- coding: utf-8 -*-
I = 0
while I < 2.1:
for J in range(3):
if I == 0 or I == 1:
print("I=%d J=%d"%(I,I+J+1))
elif ( I > 1.9 and round(I) == 2):
print("I=%d J=%d"%(round(I),I+J+1))
else:
print("I=%.1f J=%.1f"%(I,I+J+1))
I+=0.2 |
a13c299f2faa350f4be9469278916cea5fc08432 | JoaoMisutaniAlves/URI_problems | /beginner/1066.py | 424 | 4.03125 | 4 | # -*- coding: utf-8 -*-
even = 0
odd = 0
positive = 0
negative = 0
for i in range(5):
A = float(input())
if (A % 2) == 0:
even +=1
elif (A%2) != 0 and A != 0:
odd+=1
if A > 0:
positive +=1
elif A < 0:
negative +=1
print("%i valor(es) par(es)"%even)
print("%i valor(es... |
efa4e5aa52a67aef0ee358f38ef9ce2f12cfde18 | JoaoMisutaniAlves/URI_problems | /beginner/1059.py | 98 | 3.765625 | 4 | # -*- coding: utf-8 -*-
for i in range(100):
if ( i + 1 ) % 2 == 0:
print("%i"%(i+1)) |
8eb0912d15f29c38bbc3311b6e71aa5fbd1eaf8c | JoaoMisutaniAlves/URI_problems | /beginner/1010.py | 259 | 3.75 | 4 | # -*- coding: utf-8 -*-
product1 = input().split(" ")
product2 = input().split(" ")
_, qtde1, valor1 = product1
_, qtde2, valor2 = product2
TOTAL = ( int( qtde1 ) * float( valor1 ) ) + ( int( qtde2 ) * float( valor2 ) )
print ("VALOR A PAGAR: R$ %.2f"%TOTAL) |
3c750c6477b1913b54d78d8f89e86e3644305c91 | JoaoMisutaniAlves/URI_problems | /beginner/1174.py | 126 | 3.578125 | 4 | # -*- coding: utf-8 -*-
for i in range(100):
a = float(input())
if(a <= 10):
print("A[%d] = %.1f" %(i,a)) |
90a3fcb628fd436ca7698b46c706fd26a72fa8dd | JoaoMisutaniAlves/URI_problems | /beginner/1037.py | 323 | 4.03125 | 4 | # -*- coding: utf-8 -*-
value = float(input())
if 0 > value or value > 100:
print("Fora de intervalo")
elif 0 <= value <=25:
print("Intervalo [0,25]")
elif 25 < value <= 50:
print("Intervalo (25,50]")
elif 50 < value <= 75:
print("Intervalo (50,75]")
elif 75 < value <= 100:
print("Intervalo (75,100... |
3b4184677bfd97066e5f49b628fa10bd69f2a314 | JoaoMisutaniAlves/URI_problems | /beginner/1101.py | 465 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def print_in_line(list_range):
a = ""
for i in list_range:
a = a +"%i " %i
print(a + "Sum=%i"%sum(list_range))
A, B = input().split(" ")
A = int(A)
B = int(B)
result = []
while A > 0 and B > 0:
if A > B:
list_to_sum = range(B, A+1)
else:
list_to_sum... |
4b7633e4826ca953716542ab4784adeedb6e8deb | JoaoMisutaniAlves/URI_problems | /beginner/1070.py | 144 | 3.6875 | 4 | # -*- coding: utf-8 -*-
A = int(input())
if (A % 2) != 0:
A-=1
for i in range(A,A+12):
if ( i + 1 ) % 2 != 0:
print("%i"%(i+1)) |
e5f0ea850042cb2ad8dc5c8c6c8802429a73f878 | JoaoMisutaniAlves/URI_problems | /beginner/1159.py | 335 | 3.609375 | 4 | # -*- coding: utf-8 -*-
result = []
num1 = int(input())
while num1 != 0:
soma = 0
cont = 0
while cont < 5:
if (num1 % 2 == 0):
soma += num1
num1 += 1
cont += 1
else:
num1 += 1
result.append(soma)
num1 = int(input())
for i in result:
... |
acedb12139557a253c927fa27356717c1bea5157 | Emrys-Hong/pdtb3-mapper | /api/process_tree.py | 1,635 | 3.75 | 4 | from ete3 import TreeNode
class ProcessTree:
def __init__(self):
pass
def _simplify_tree(self, tree):
# tree.label is the word
# tree.name is arg1 arg2 or pos tag
temp = []
if len(tree.children) == 0:
return tree.label
for c in tree.children:... |
9a764277fa8a27405a401b5ce082227792345bdd | jamesfallon99/CA117 | /week04/swap_v1_042.py | 136 | 3.71875 | 4 | #!/usr/bin/env python3
def swap_keys_values(d):
new_d = {}
for k, v in d.items():
new_d[v] = k
return new_d
|
70fcac21036fb48601c49e32c4ecbbe249e4abd9 | jamesfallon99/CA117 | /week06/perfect_062.py | 520 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
def sumFac(num):
lis = []
for i in range(1, int(num), 1):
if int(num) % i == 0 and i != num:
lis.append(i)
return sum(lis)
def isperfect(num):
if num == 33550336:
return True
elif num == sumFac(num):
return True
... |
673decdca960e5f2fd66d036c69e1b28d0cc5e1c | jamesfallon99/CA117 | /week11/triathlete_v2_111.py | 590 | 3.625 | 4 | #!/usr/bin/env python3
class Triathlete(object):
def __init__(self, name, tid):
self.name = name
self.tid = tid
self.times = {}
self.race_time = 0
def add_time(self, sport, time):
self.times[sport] = time
self.race_time += time
def get_time(s... |
1b8a13634bf5e0136814cb12f325276fc5f0941c | jamesfallon99/CA117 | /week08/time_082.py | 1,296 | 4 | 4 | #!/usr/bin/env python3
class Time(object):
def __init__(self, h=0, m=0, s=0):
self.hour = h
self.minute = m
self.second = s
def __str__(self):
return "The time is {:02d}:{:02d}:{:02d}".format(self.hour, self. minute, self.second)
def __eq__(self, other):
return (s... |
e4bfb7ee8be167a13beedb4365734c81f13384cb | jamesfallon99/CA117 | /week02/beststudents_022.py | 660 | 3.78125 | 4 | #!/usr/bin/env python3
import sys
def main():
try:
with open(sys.argv[1]) as f:
bestmark = -1
for line in f:
mark, name = line.strip().split(" ", 1)
if int(mark) > int(bestmark):
bestmark, beststudents = int(mark), name
... |
e8e5801ff400fd9e7e8df43f61c0812853b8f049 | jamesfallon99/CA117 | /week10/reverse_102.py | 198 | 4.0625 | 4 | #!/usr/bin/env python3
def reverse_list(l):
if len(l) == 0:
new_lis = []
return new_lis
new_lis = reverse_list(l[1:])
new_lis.append(l[0])
return new_lis
|
21a34dcd8837c42f9ea42b7bc1e4e5db25cfe7a5 | jamesfallon99/CA117 | /week09/employee_091.py | 858 | 3.796875 | 4 | #!/usr/bin/env python3
class Employee(object):
def __init__(self, name, number):
self.name = name
self.number = number
def wages(self):
return 0
def __str__(self):
l = []
l.append("Name: {}".format(self.name))
l.append("Number: {}".format(self.number))
... |
c7c27bb22d9516753f2e10af5f119b245fe9948f | jamesfallon99/CA117 | /week03/numcomps_031.py | 1,150 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
def three(N):
return [n for n in range(1, N + 1) if n % 3 == 0]
def squares(N):
return[n ** 2 for n in range(1, N + 1) if n % 3 == 0]
def double(N):
return[n * 2 for n in range(1, N + 1) if n % 4 == 0]
def three_or_four(N):
return[n for n in range(1, N + 1) if n % ... |
5b14da052d7a1c00ffa9443341c87eff2e605afc | jamesfallon99/CA117 | /week10/maximum_102.py | 200 | 3.828125 | 4 | #!/usr/bin/env python3
def maximum(l):
if len(l) == 1:
return l[0]
maximum_num = maximum(l[:-1])
if l[-1] > maximum_num:
return l[-1]
else:
return maximum_num
|
75341a9e36988311c1477fbabdf9c68944b305bd | jamesfallon99/CA117 | /week02/readnum_022.py | 320 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
def main():
for line in sys.stdin:
line = line.strip()
try:
print("Thank you for {}".format(int(line)))
break
except ValueError:
print("{} is not a number".format(line))
if __name__ == '__main__':
main()
|
bab227ae6d5b3874f8c84a1c20f4b916faa333f4 | jamesfallon99/CA117 | /week07/contacts_072.py | 940 | 3.96875 | 4 | #!/usr/bin/env python3
class Contact(object):
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def __str__(self):
return "{} {} {}".format(self.name, self.phone, self.email)
class ContactList(object):
def __init... |
a27c2e5584bb76cc9c84e02b7fada1ac1b188b2e | fugenfirowa/stepik---auto-tests-course | /lesson3_step3.py | 307 | 3.578125 | 4 | def test_substring(full_string, substring):
# ваша реализация, напишите assert и сообщение об ошибке
assert substring in full_string, f"expected {substring} to be substring of {full_string}"
return "as expected"
print(test_substring("blablabla", "bla5"))
|
b8eb07e732f80f4303e5020aecb26f7711e93d1d | PederBG/sorting_algorithms | /InsertionSort.py | 510 | 4.25 | 4 | """ Sorting the list by iterating upwards and moving each element back in the list until it's sorted with respect on
the elements that comes before.
RUNTIME: Best: Ω(n), Average: Θ(n^2), Worst: O(n^2) """
def InsertionSort(A):
for i in range(1, len(A)):
key = A[i]
j = i - 1
while j > ... |
04715d6ba832e058a54c07f454e90218cb1c4650 | quynhanh299/abcd | /baiconrua.py | 324 | 4.21875 | 4 | # from turtle import*
# shape("turtle")
# for i in range (3):
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# forward(200)
# left(90)
# mainloop()
# # bai tap ve 9 hinh tron
from turtle import*
shape("turtle")
for i in range (9):
circle(40)
right(... |
708c3f290a705b46dc828a704a3d4e2a431fee51 | zadadam/algorithms-python | /sort/bubble.py | 1,066 | 4.125 | 4 | import unittest
def bubble_sort(list):
"""Sort list using Bubble Sort algorithm
Arguments:
list {integer} -- Unsorted list
Returns:
list {integer} -- Sorted list
"""
swap=True
test ="It is a bad code";
while swap:
swap = False
for n in range(len(li... |
1ba87d6ab75f92a47b034f564d6fc6db6e0ecd9a | nchauhan890/extended-abc | /errors.py | 562 | 3.59375 | 4 | # error formatting for extended-abc
class AbstractClassError(Exception):
"""Custom Exception raised to list errors encountered.
Raised with list of NotImplementedErrors and TypeErrors
"""
pass
def formaterror(dct):
"""Format dict: name: [list of errors]
Raises AbstractClassError
"""
... |
2b5321221aac2bc3883de2d7987be9d0dabfda7a | dannguyen99/natural_language_processing | /problem1/execute.py | 4,242 | 3.53125 | 4 | from collections import defaultdict
import math
def train_bigram(train_file, model_file):
"""Train trigram language model and save to model file
"""
counts = defaultdict(int) # count the n-gram
context_counts = defaultdict(int) # count the context
with open(train_file) as f:
for line in ... |
dfc1b5623c7340787ec64b89eb116ee058caf2db | sonamk15/Basic_python | /list_que/list8.py | 88 | 3.796875 | 4 | l = [1,2,3,3]
if not l:
print("List is empty")
else:
print("List is not empty")
|
74df523802bfc161a2abd958b7458dc25abe47ce | sonamk15/Basic_python | /sum_dic_value.py | 95 | 3.546875 | 4 |
input={'a': 100, 'b':200, 'c':300}
i=0
s=0
while i<len(input):
print (input[i])
i=i+1
|
b347f52e31d9e0690c68754bfb2b1099a366fd12 | sonamk15/Basic_python | /dryrun.py | 176 | 3.5 | 4 | n=6
i=0
while(i<n):
if (i==n-1 and i>0):
n=n-1
print "$"*i
i=i-1
continue
elif (i==0):
break
print (i*"$")
i=i+1 |
61897c800cd296eb14ac3606f0ae158f05662e58 | edvardvb/tdt4136 | /assignment-3/task_3_1.py | 5,533 | 4.15625 | 4 | """
Expanding on the previous task, implementing both BFS and Dijkstras by changing a few
lines of code. In addition add vizualization of closed and open nodes
from GUI import draw_path
"""
import GUI_3_1
class Cell:
"""
One 'node' or element in the given string/board.
"""
def __init__(self, x, y, wal... |
fc81125da3e7962ed42bca6cbc70b96d187f9cdd | FilipNilsson/adventofcode2019 | /day8/day8-2.py | 2,480 | 4.03125 | 4 | """
Now you're ready to decode the image. The image is rendered by stacking the layers and aligning the pixels with the same positions in each layer. The digits indicate the color of the corresponding pixel: 0 is black, 1 is white, and 2 is transparent.
The layers are rendered with the first layer in front and the las... |
109ec4c8b4316cc46479ab9cfe93f2fe7a9f817d | vishul/Python-Basics | /openfile.py | 500 | 4.53125 | 5 | # this program opens a file and prints its content on terminal.
#files name is entered as a command line argument to the program.
#this line is needed so we can use command line arguments in our program.
from sys import argv
#the first command line argument i.e program call is saved in name and the
#second CLA is stor... |
7af70a6769178e4076a6a247a5956dd2e7807dab | bsextion/CodingPractice_Py | /MS/Linked List/remove_dup.py | 1,259 | 3.890625 | 4 | # This is an input class. Do not edit.
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeDuplicatesFromLinkedList(linkedList):
if not linkedList:
return linkedList
head = linkedList
#map to store oc... |
2e3924cd0819ea47b3d5081e4d24647a31ea19fa | bsextion/CodingPractice_Py | /MS/Fast Slow Pointer/rearrange_linkedlist.py | 1,332 | 4.15625 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(str(temp.value) + " ", end='')
temp = temp.next
print()
def reorder(head):
middle = find_middle(head)
reversed_middle = reverse_... |
20589c4c39922ef8b14f1daa7bd8ef190949625f | bsextion/CodingPractice_Py | /Misc/Dynamic Programming/memoization/bestSum.py | 549 | 3.6875 | 4 |
results = []
def bestSum(targetSum, numbers):
if targetSum == 0: return []
if targetSum < 0: return None
shortestCombo = None
for num in numbers:
remainder = targetSum - num
remainderArr = bestSum(remainder, numbers)
if remainderArr is not None:
combination = [*rem... |
a074f9da1967f64f151cd159bd0f36f39a7ee575 | bsextion/CodingPractice_Py | /Misc/GTCI/Two Pointer/target_sum.py | 1,014 | 3.921875 | 4 | #**Problem**#
#Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target.
#Solution 1
#1) create left pointer pointer to first el, right pointer pointing to last el
#2) loop through array and check if sum of left and right pointers equal target
#3) if sum equal... |
369057547a5b566698c0b19db73582f98621b00b | bsextion/CodingPractice_Py | /Misc/Data Structures/Tree/InOrderSucessor.py | 356 | 3.546875 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_successor_bst(root, d):
list = inorder_successor_bst(root.left)
list.append(root.val)
list = inorder_successor_bst(root.right)
ret... |
8bf25a1c13013459afa43cdf2871621ad5485e43 | bsextion/CodingPractice_Py | /Misc/Modules/Mod 3/SearchTree/bst.py | 1,326 | 3.859375 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
curr_node = self.root
while(curr_node):
... |
5d5672856c78ff5544ef57e0dd0e963a2857559a | bsextion/CodingPractice_Py | /Misc/Algorithim/reverse.py | 392 | 3.65625 | 4 | class Solution:
def reverse(self, x: int) -> int:
num = x
if x < 0:
isNegative = True
num = abs(x)
wordNum = str(num)
num = int(wordNum[::-1])
if isNegative:
num *= -1
if num <= pow(2, -31) or num >= pow(2,31)-1:
... |
77fc10d712d8651e5b1b74c67e04591a89ec873f | bsextion/CodingPractice_Py | /Misc/Modules/Mod 3/palindrome_permutation.py | 787 | 3.78125 | 4 | def permutation(phrase):
phrase = phrase.replace(" ", "")
phrase = phrase.lower()
map = dict()
for letter in phrase: #map to keep track of how many times a letter appears
if letter in map:
map[letter] += 1
else:
map[letter] = 1
isEven = True if len(phras... |
88ba535bbf7f7d253ab9816d880e6ab7bd80c3b3 | bsextion/CodingPractice_Py | /Misc/Dynamic Programming/memoization/canSum.py | 270 | 3.890625 | 4 |
def canSum(targetSum, numbers):
if targetSum == 0: return True
if targetSum < 0: return False
for num in numbers:
remain = targetSum - num
if canSum(remain, numbers) == True:
return True
return False
print(canSum(7, [2,3])) |
40b616abfa2a62a5fb1a60fcb13e08cefc029491 | bsextion/CodingPractice_Py | /Misc/Modules/Mod 2/abstract_class.py | 437 | 4.0625 | 4 | from abc import ABC,abstractmethod
class Shape(ABC): # Shape is a child class of ABC
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return po... |
de78a868d31da2d6667ea510c35c87bcb1791b58 | bsextion/CodingPractice_Py | /Misc/Modules/Mod 3/Dictionaries/operations.py | 797 | 3.828125 | 4 | # #Updating entries
# phone_book = {"Batman": 468426,
# "Cersei": 237734,
# "Ghostbusters": 44678}
# phone_book["Batman"] = 2
# #deleting
# del phone_book["Cersei"]
# print(phone_book)
# #Check existence
# print("Batman" in phone_book)
#update the contents
# phone_book = {"Batman": 46842... |
21a05ae519ae57f69550a7119551b5307476d778 | bsextion/CodingPractice_Py | /Misc/Data Structures/LongestIncreasingSubsequence.py | 629 | 3.546875 | 4 | # result array to store length, set first value to 1
# counter starting at 1
# for loop starting at index 1
# if i-1 is less than i, increment counter and append to result
# else counter = 1, append to result
# sort list and return last value
class Solution:
def lengthOfLIS(self, nums) -> int:
result, co... |
7d7959077f66351a961153e1655de51ba4aea898 | bsextion/CodingPractice_Py | /Misc/Data Structures/DynamicProgramming/max_subarr.py | 365 | 3.734375 | 4 | def find_max_sum_sub_array(A):
max_sum = A[0]
result_arr = [max_sum]
for i in range(1, len(A)):
if max_sum + A[i] > A[i]:
max_sum += A[i]
else:
max_sum = A[i]
result_arr.append(max_sum)
result_arr = sorted(result_arr)
return result_arr[-1]
print(fi... |
4c5761f987c88512f2b4f0a3240f71ae39f10101 | bsextion/CodingPractice_Py | /Google/L1/challenge.py | 1,215 | 4.34375 | 4 | # Due to the nature of the space station's outer paneling, all of its solar panels must be squares.
# Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors,
# and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares.
# For ex... |
24126ab6741187b124ee439036eb351c1c180700 | bsextion/CodingPractice_Py | /Misc/GTCI/Two Pointer/triple_sum_zero.py | 1,066 | 3.90625 | 4 | #**Problem**#
#Given an array of unsorted numbers, find all unique triplets in it that add up to zero.
#1)Sort the array
#2)left and right pointer
#3) In a foor loop, i < len(-2)
#4) while loop, left is less than right
#5) if triplet equal 0, add to array
#6) outside of while loop, set left to i and left to last
def s... |
4ebd1b4c4f372287f061468aeae06ffa8798ad77 | bsextion/CodingPractice_Py | /Misc/Learning/forLoop.py | 231 | 3.90625 | 4 | friends = ["Ross" , "Phoebe", "Joey", "Monica", "Chandler", "Rachel"]
# for friend in friends:
# print(friend)
for index in range(5):
if index == 0:
print("First Friend")
else:
print(friends[index])
|
2dec0c9a2afc0fc76c13dd9941f4900b4f4c2cb4 | suchit94/pythonApp2 | /mapping.py | 1,908 | 3.734375 | 4 | #import libraries here:
import folium
import pandas
#open file and assign to variable here:
data = pandas.read_csv("Volcanoes.txt")
#python lists of all longitudinal and latitudinal coordinates and elevations saved to variables:
lon = list(data["LON"])
lat = list(data["LAT"])
elev = list(data["ELEV"])
name... |
2c0be676aa96bf071a92a21f9010ce24adbb58c4 | seekingpeace/fsdse-python-assignment-31 | /build.py | 255 | 3.71875 | 4 | import itertools
def solution(dic):
list_of_combinations = []
for k in itertools.product(*sorted(dic.values())):
list_of_combinations.append(k[0]+k[1])
return list_of_combinations
print(solution({'one':['a','b'], 'two':['c','d']}))
|
63c40bd68269dfea6974174bf46fe7f5e8d931cb | reneMX/Distribuidos-Hilos-Procesos-Senales | /ScriptsIntro/UACM/ScriptsIntro/persona.py | 345 | 3.875 | 4 | #!/usr/bin/python3
class persona:
__nombre =" "
def __init__(self,nombre):
self.nombre = nombre
def damenombre(self):
return self.nombre
def definenombre(self, nombre):
self.nombre = nombre
def __str__ (self):
return self.nombre
p = persona("Arnoldo")
print(p)
p.defineno... |
92d07ee7645877b9a813b09d9cdb04c24241e275 | iskyzh/potential-octo-lamp | /main.py | 655 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
import argparse
parser = argparse.ArgumentParser(description='Text File to Python List')
parser.add_argument('--input', help='text file path')
parser.add_argument('--output', help='python file path')
args = parser.parse_args()
in_file = open(args.input, "rt")
out_file = open(args.... |
29a9810a414c4ad868a4873d2bc9c0b3f57f340c | wandershow/Python | /ex073.py | 992 | 3.765625 | 4 | #crie uma tupla preenchida com os 20 primeiros times em ordem de classificação do brasileirão 2018
#mostre os 5 primeiros
#os ultimos 4 da tabela
#uma lista com os times em ordem alfabetica
# em que posição esta o time da chapecoense
br = ('palmeiras', 'flamengo', 'inter', 'gremio', 'são paulo', 'atletico mg', 'atleti... |
4c99802487a355cb83acb08c52012dc1cbf9af94 | wandershow/Python | /ex031.py | 376 | 3.703125 | 4 | # Pergunte a distancia de uma viagem em km, e calcule o preço da passagem cobrando R$0.50 por km para viagens de ate
# 200 km e R$0.45 para viagens mais longas.
d = int(input('Qual a distancia da viagem? '))
if d <200:
v = d * 0.50
print('o valor da passagem é de R${:.2f}'.format(v))
else:
v = d * 0.45
... |
263dd31d9d26e3f99047e0cbf6c25101835c3f8d | wandershow/Python | /ex089.py | 1,037 | 3.9375 | 4 | '''Crie um programa que leia nome e duas notas de varios alunos e guarde tudo em uma lista composta.
no final mostre um boletin contendo a media de cada um e permita que o usuario possa mostrar as notas de cada aluno
individualment2'''
boletim = list()
nota = list()
aluno = list()
while True:
nome = str(input('Nom... |
8513c30cfd6b8fc19b6bd992e27bbd8e04160ad7 | wandershow/Python | /ex059.py | 1,237 | 4.21875 | 4 | # crie um programa que leia dois numeros e mostre um menu na tela
#[1] somar
#[2] multiplicar
#[3] maior
#[4] novos numeros
#[5] sair do programa
#seu programa devera realizar a operação solicitada em cada caso
n1 = int(input('Digite o 1º numero: '))
n2 = int(input('Digite o 2º numero: '))
opcao = 0
while opcao != 5:
... |
778fcce3f07cec2275c23a2121df2081ae29c63b | wandershow/Python | /ex024.py | 252 | 3.828125 | 4 | # crie um programa que leia o nome de uma cidade e diga se ela começa com a palavra 'santo'
cidade = input('Digite o nome da cidade: ')
inicio = cidade.lower().split()
print('existe a palavra santo no inicio do nome da cidade? ','santo' in inicio[0]) |
1307113e3f6d2c27359fa4e081d452795f546158 | wandershow/Python | /ex052.py | 277 | 3.71875 | 4 | # Faça um programa que leia um numero inteiro e diga se ele é ou nao primo
n = int(input('Digite um numero: '))
a = 0
for c in range(2, n+1):
if n % c == 0:
a += 1
if a > 1:
print('{} Não é primo'.format(n))
else:
print('{} É primo'.format(n))
|
c5e75f53785f47de9a6762d800daf359fab7730b | wandershow/Python | /ex068.py | 769 | 3.75 | 4 | '''Faça um programa que jogue par ou impar com o computador. o jogo sera interrompido quando o jogador perder.
mostrando o total de vitorias consecutivas que ele conquistou no final do jogo'''
from random import choice
comp = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
e = choice(comp)
count = 0
while True:
print('+'*50)
... |
12faef7d930dd13cef95ebd9c7c336bdba55ccf9 | wandershow/Python | /ex008.py | 204 | 3.796875 | 4 | # leia um valor em metros e o exiba convertido em centimetros e milimetros
n = int(input('Digite quantos metros:'))
print('{} metro equivale a {} centimetros e a {} milimetros'.format(n, n *100, n*1000)) |
314e30531c946c80ffbe95d6b5aa36eb93dbf972 | wandershow/Python | /ex075.py | 1,490 | 4.125 | 4 | '''Desenvolva um programa que leia 4 valores do teclado e guarde os em uma tupla e mostre
quantas vezes apareceu o valor 9
Em que posição foi digitado o valor 3 pela primeira vez
Quais foram os numeros pares
'''
cont = 0
pos = 0
par = 0
numero = (int(input('Digite um numero: ')), int(input('Digite outro numero: ')), in... |
ba1bc19f20ad71e6c18c7b1bcd1a352b2b19c230 | wandershow/Python | /ex044.py | 923 | 3.875 | 4 | # elabore um programa que calcule o valor a ser pago por um produto, considerando sua condição de pagamento
# Dinheiro ou cheque 10% de desconto
# A vista no cartão 5% de desconto
# em ate 2x no cartão preço normal
# 3x ou mais no cartão 20% de juros
produto = float(input('Digite o valor do produto? '))
pagamento = i... |
68076363a17fb650c4ed2c9798684c938b540e51 | wandershow/Python | /ex084.py | 1,022 | 3.75 | 4 | '''Faça um programa que leia o nome e peso de varias pessoas, guardando tudo em uma lista. no final, mostre:
quantas pessoas foram cadastradas
uma listagem com as pessoas mais pesadas
uma listagem com as pessoas mais leves'''
dado = list()
lista = list()
maisleve = maispesado = 0
while True:
dado.append(str(input... |
5f524fcb9778f13d835c844e8d1d36827550cb95 | wandershow/Python | /ex013.py | 228 | 3.640625 | 4 | # leia o salario de um funcionario, e mostre com 15% de aumento
s = float(input('Digite o valor do salario: '))
print(' Esse e o seu salario R${:.2f} \n Esse e o seu novo salario com 15% de aumento R${:.2f}'.format(s, s *1.15)) |
edd3e9b8a3fd44b3bd67a04d6465b7a0cd67ea5d | wandershow/Python | /ex054.py | 462 | 4.09375 | 4 | # crie um programa que leia o ano de nascimento de sete pessoas. no final mostre quantas delas ainda não atingiram a
# maioridade e quantas ja sao maiores
from datetime import date
ano = date.today().year
maior = 0
menor = 0
for c in range(0, 7):
n = int(input('Digite o ano de nascimento: '))
if (ano - n) >= 18... |
914b0279c70689584ebf13b94a5022d90f5c6414 | sawk1/Python_bases | /Lesson_4/hw04_hard.py | 2,348 | 3.890625 | 4 | # Задание-1:
# Матрицы в питоне реализуются в виде вложенных списков:
# Пример. Дано:
"""
matrix = [[1, 0, 8],
[3, 4, 1],
[0, 4, 2]]
"""
# Выполнить поворот (транспонирование) матрицы
# Пример. Результат:
# matrix_rotate = [[1, 3, 0],
# [0, 4, 4],
# [8, 1, 2]]
# Су... |
a44b3cc82561eb64d06c489199bfefea515ae212 | lipewinning/pythonBasic | /basic/for.py | 207 | 3.734375 | 4 | friends = ['Felipe', 'Alex', 'Rafael', 'Dudu']
for friend in friends:
print(friend)
for index in range(5):
if index == 0:
print('first interaction')
else:
print('not first')
|
33b3e4c819e6269a38b09bca4c95e43468370687 | limbermontano/PROYECTO-RESTAURANT | /RestaurantSabor.py | 10,568 | 3.84375 | 4 | class restaurantSab:
def __init__(self):
self.codigo=[]
self.nombre=[]
self.precio=[]
self.descripcionC=[]
self.tipoC=[]
self.descuento=[]
self.habilitado=[]
self.auto=0
def pregunta(self):
preg=input('DESEA VOLVER AL MENU PRINCIPAL:y/n \n... |
f470741516552324c6765beda29bc2b83ddc5533 | mcellteam/libMCellPP | /api_prototype/mariam/Surface_class_a.py | 591 | 3.546875 | 4 | import PyMcell as pm
#create the world
world = pm.create_world()
#create the box
box = world.boundaries(x>-1 and x<1 and y>-1 and y<1 and z>-1 and z<1)
#creat the class
class surface(): #a region defined by the function f, and boundaries
def __init(f(x,y,z), x1, y1, z1, x2, y2, z2, p, side):
self.f(x,y,z) = f(x,... |
15bf25be4ce9ad3ed5ad34b3313ee31dbb36c510 | zftan0709/AuE-8930-HPC | /Homework3/Q3A.py | 1,326 | 3.671875 | 4 | import multiprocessing as mp
import threading
import time
if __name__ == '__main__':
### Original Implementation Target Function ###
def add():
global var
var = var + 1
def minus():
global var
var = var - 1
### Original Implementation ###
print("\n### Original Impleme... |
f2caf8d459884be1955fcfde641f651171d558e9 | hamzatahir007/Python_chap3 | /chap3_ex5_59.py | 316 | 3.609375 | 4 | name = input("Enter your full name: ")
name = name.lower()
#output
# h : 0
# a : 1
# m : 2
# z : 3
# a : 4
tem_var = ""
i = 0
while i < len(name):
if name[i] not in tem_var:
tem_var = name[i] + tem_var
print (f"{name[i]} : {name.count(name[i])} ")
i = i +1
|
d32fd889b9e8b4124175a17851f33f98100bbdd4 | suman30380/Python | /TicTacToeGame.py | 142 | 3.640625 | 4 | game = ([0,0,0],
[0,0,0],
[0,0,0])
#print(game)
print(" 0, 1, 2")
for counter, row in enumerate(game):print(counter, row)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.