blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2188d1d163483a69e48b74ba08531f5cdbccfca2 | ICESDHR/Bear-and-Pig | /Practice/Interview/12.矩阵中的路径.py | 2,107 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# 矩形中是否存在包含某字符串的路径
# TODO 需要好好看看,自己想了好久才想出来一个很麻烦的方案
def hasPath(matrix, rows, cols, path):
for i, s in enumerate(matrix):
if s==path[0] and visit([(i//cols, i%cols)], matrix, rows, cols, path):
return True
return False
def visit(ans, matrix, rows, cols, path):
i... |
57d704ed878922cca593c1f20db0bfdd48d3253d | ICESDHR/Bear-and-Pig | /Practice/Interview/17.打印从1到最大的n位数.py | 279 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# 输入n,打印从1到最大的n位数
def Print(pre,n):
if n < 1:
if pre > '0':
print(int(pre))
return
for i in range(10):
Print(pre+str(i),n-1)
if __name__ == '__main__':
test = [3, -1, 0]
for n in test:
print('n =',n)
Print('', n) |
987dc44588b92c0db14ca21def89ab5aad3e22d5 | ICESDHR/Bear-and-Pig | /Practice/Sort/HeapSort.py | 778 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# 本代码为建立大根堆
def HeapAdjust(heap,length,i):
min = i
if 2*i+1 < length and heap[2*i+1] > heap[min]:
min = 2*i+1
if 2*i+2 < length and heap[2*i+2] > heap[min]:
min = 2*i+2
if min != i:
heap[i],heap[min] = heap[min],heap[i]
HeapAdjust(heap,length,min)
... |
6e8ac507b80dd1641922f895a1d06bba718065c3 | ICESDHR/Bear-and-Pig | /笨蛋为面试做的准备/leetcode/Algorithms and Data Structures/sort/bubble_sort.py | 343 | 4.15625 | 4 | def bubble_sort(lists):
if len(lists) <= 1:
return lists
for i in range(0, len(lists)):
for j in range(i + 1, len(lists)):
if lists[i] > lists[j]:
lists[j], lists[i] = lists[i], lists[j]
return lists
if __name__ == "__main__":
lists = [9, 8, 7, 6, 5]
pri... |
0ff9201f5970cca2af58757d2d855446994e0335 | ICESDHR/Bear-and-Pig | /Practice/Interview/16.数值的整数次方.py | 1,054 | 4.3125 | 4 | # -*- coding:utf-8 -*-
# 看似简单,但是情况要考虑周全
def Pow(base,exponent):
if exponent == 0:
return 1
elif exponent > 0:
ans = base
for i in range(exponent-1):
ans *= base
return ans
else:
if base == 0:
return 'Error!'
else:
ans = base
for i in range(-exponent-1):
ans *= base
return 1/ans
# 对算法... |
583808a25f0bed187352495d1e9d4e239a1e989d | ICESDHR/Bear-and-Pig | /Practice/Interview/10-2.青蛙跳台阶问题.py | 1,292 | 4 | 4 | # -*- coding:utf-8 -*-
# TODO 难点是发现这是一个Fibonacci问题
def JumpFloor(number):
count = [1,2]
if number > 2:
for i in range(2,number):
count.append(count[i-1]+count[i-2])
return count[number-1]
# 变态跳台阶问题 青蛙一次可跳无数节台阶
# TODO 不仅可以找出简单的递归规律;还可以变为组合问题,对其进行总结计算
def JumpFloorII(number):
count =... |
571400657495936c96d31a67b1bc2afeeeaa1bf6 | ICESDHR/Bear-and-Pig | /Practice/Interview/24.反转链表.py | 1,016 | 4.34375 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self,value):
self.value = value
self.next = None
# 没思路
def ReverseList(root):
pNode,parent,pHead = root,None,None
while pNode:
child = pNode.next
if child is None:
pHead = pNode
pNode.next = parent
parent = pNode
pNode = child
return pHead
# 递归... |
b432f5b8f81d0f56fdd591415233a374aea94c78 | davistardif/ist4-pcp | /old/tandem/dup.py | 3,187 | 4.09375 | 4 | class Dup(object):
"""
Dup is a binary string that can be duplicated recursively
"""
def __init__(self, val_in, distance_in):
"""
seed_in: (string) starting seed for string
self.distance: (int) how many mutations/duplications from seed
self.val: (string) string after muta... |
492ce186a2dd6508446c900e06806601be40bd39 | hemanthkumarbattula/python-tasks | /Python-basics/2-PartD_1.py | 153 | 3.625 | 4 | a_list=list(range(1000,2001))
result_list=[]
for item in a_list:
if item%7 == 0 and item%5 != 0:
result_list.append(item)
print(result_list)
|
a41531f880884df1712ee311a2b41095ffcd1fd5 | hemanthkumarbattula/python-tasks | /Python-basics/AssignmentA4_partB.py | 1,013 | 3.640625 | 4 | import nltk
def count_words(text):
d={}
for i in text:
if not i in d:
d[i] = text.count(i)
return d
def fraction_dist(numerator_dist,denominator_dist):
temp_dict={}
for key in denominator_dist.keys():
if key in numerator_dist:
temp_dict[key]=numerator_dist[key... |
c6b04d386907dea30e837a546627754edf90c294 | ChristianJdeVries/Phycharm | /Week_2/Exercises.py | 365 | 4.09375 | 4 | print(5 % 2)
print(12%15)
print(0%7)
print((14+51)%24)
current_time_str = input("What is the time now?")
current_time_int = int(current_time_str)
waiting_time_str = input("How long do you have to wait?")
waiting_time_int = int(waiting_time_str)
time_after = (current_time_int+waiting_time_int) % 24
print("After the ... |
c247ba288604b38dafbb692aa49acf8b74ebd353 | izdomi/python | /exercise10.py | 482 | 4.25 | 4 | # Take two lists
# and write a program that returns a list that contains only the elements that are common between the lists
# Make sure your program works on two lists of different sizes. Write this using at least one list comprehension.
# Extra:
# Randomly generate two lists to test this
import random
list1 = random... |
086daed19d3d5115b9be43430c74c52d4cda4e15 | izdomi/python | /exercise24.py | 1,385 | 4.375 | 4 | # Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s
# print statement.
def board_draw(height, width):
top = "┌" + "┬".join(["─"*4]*width) + "┐\n"
bottom = "└" + "┴".join(["─"*4]*width) + "┘"
middle = "├" + "┼".join(["─"*4]*width) + "┤\n"
print(top +
... |
698212d5376c53e07b4c5410dfd77aac16e97bd2 | izdomi/python | /exercise5.py | 703 | 4.21875 | 4 | # Take two lists,
# and write a program that returns a list that contains only the elements that are common between the lists.
# Make sure your program works on two lists of different sizes.
# Extras:
# Randomly generate two lists to test this
# Write this in one line of Python
lst1 = []
lst2 = []
num1 = int(input("l... |
98750a28db7b40433921a21fdcaa04c3d720df41 | ggteixeira/Plural-Generator | /plural-generator.py | 1,040 | 4.03125 | 4 | from desacentuador import desacento
palavra = str(input("Digite: \n"))
# Letras que formam substantivos plurais em PB:
a = ["s"]
e = ["s"]
i = ["s"]
m = ["ns"]
n = ["s"]
o = ["s"]
r = ["es"]
s = ["es"]
u = ["s"]
z = ["es"]
''' Casos especiais:
Segundo HUBACK (2017), plurais terminados em "ão" ("avião" / "aviões"),
e... |
42ab31504a289208aaa7c94f0f3bb77dc25f4bb7 | chriswilde/GuiZero | /LED_Button.py | 514 | 3.546875 | 4 | from guizero import App, PushButton
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
GPIO.output(3, GPIO.LOW)
def light_Switch():
if GPIO.input(3):
GPIO.output(3, GPIO.LOW)
LED_Control["text"] = "SWITCH LED ON"
print("LED is now off")
else:
GPIO.output(3, GPIO.HIGH)
LE... |
901157751c3e3ece45cc47225bc6fdb046976892 | ivanoviicrm/pdf_to_txt_py | /main.py | 1,319 | 3.546875 | 4 | import PyPDF2
from os import listdir
def ask_path():
path = input("Introduce CARPETA para pasar TODOS los documentos PDF a TXT:\n")
return path
def get_files_in_path(path):
pdf_files = []
for file in listdir(path):
if file.endswith("pdf"):
pdf_files.append(file)
... |
7430632ea4b68e882041666683aac0988146ce6b | luvkrai/learnings | /hash_map_with_List_Node.py | 1,135 | 3.5 | 4 | class Node:
def __init__(self,key,value):
self.key = key
self.value = value
class myhash():
def __init__(self):
self.store = [None for _ in range(16)]
self.size = 16
def get(self,key):
index = self._hash(key)
if self.store[index] is None:
return None
else:
found = False
... |
b57c5e402e5a1c8f34536da10f3440825c0033bf | luvkrai/learnings | /multiprocessing_Sync_2.py | 600 | 3.984375 | 4 | #https://www.geeksforgeeks.org/synchronization-pooling-processes-python/
import multiprocessing
def add(balance):
for i in range(10000):
balance.value += 1
def withdraw(balance):
for i in range(10000):
balance.value -= 1
# This variable is shared between the processes p1 p2
balance = multiprocessing.Val... |
dc1c450c70c473c22cc66f1b76c854f113d5aa08 | luvkrai/learnings | /second_maximum.py | 220 | 3.71875 | 4 | arr = [1,2,3,4,5,6,7]
max1=max2=-1
for i in range(0,len(arr)):
if arr[i] > max1:
max2 = max1
max1 = arr[i]
elif arr[i] < max1 and arr[i] > max2 and arr[i] != max2:
max2 = arr[i]
print(max2)
|
adc35b4cad40e5e6ac3788e8ed0696f7858eeabf | luvkrai/learnings | /iterator.py | 910 | 3.96875 | 4 | class my:
def __init__(self):
self.l = [1,2,3,4,5]
self.index = -1
def __iter__(self):
# When iter() is called on the object of this class, and iterator is returned
return self
def __next__(self):
self.index+=1
if self.index < len(self.l):
return self.l[self.index]
else:
rais... |
bbe7ebd67d6d3e90ac238ceb47d4446e8905e22c | luvkrai/learnings | /Hourglass.py | 681 | 3.625 | 4 | #https://www.hackerrank.com/challenges/30-2d-arrays/problem
A = [[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 0, 2, 4, 4, 0],
[0, 0, 0, 2, 0, 0],
[0, 0, 1, 2, 4, 0]]
def calculate_hour_glass(A,row_start,row_end,col_start,col_end):
t_sum = 0
row=1
for l in range(row_sta... |
61494f69e465e8da2c0193823e18f08c0ad0ba59 | muyisanshuiliang/python | /leet_code/643. 子数组最大平均数 I.py | 1,236 | 3.6875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : 643. 子数组最大平均数 I.py
@Contact : muyisanshuiliang@hotmail.com
@Modify Time @Author @Version
------------ ------- --------
2021/2/4 12:06 muyisanshuiliang 3.9
@Desciption:
------------------------... |
0ddf4a4c5226563201b4ed3de4aba5f3acb0e2d2 | muyisanshuiliang/python | /leet_code/24. 两两交换链表中的节点.py | 1,227 | 3.609375 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# # 中间节点,记录
pre = ListNode()
pre.next = temp_head = head
while temp_head and temp_head.next :
pre.ne... |
810d32aa878a2f114ee57200d6747d35a4a045e1 | muyisanshuiliang/python | /leet_code/217. 存在重复元素.py | 558 | 3.765625 | 4 | class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
length = len(nums)
if length == 1:
return False
nums_dict = {}
for item in nums:
... |
ebe72f3cbb58dba2d08cbffbb0eb0766f43d22f7 | muyisanshuiliang/python | /leet_code/1356. 根据数字二进制下 1 的数目排序.py | 1,070 | 3.515625 | 4 | from typing import List
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
# 原始方法
# 针对每个数字统计1的个数
def count_one(num) -> [int, int]:
# 用于统计1的数量
count = 0
temp = num
if num == 0:
return [num, count]
wh... |
c6c19fd1306d112560e1b663ee095fb54d75765f | muyisanshuiliang/python | /leet_code/LCP 01. 猜数字.py | 1,326 | 3.640625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : LCP 01. 猜数字.py
@Contact : muyisanshuiliang@hotmail.com
@Modify Time @Author @Version
------------ ------- --------
2021/3/12 12:22 muyisanshuiliang 3.9
@Description:
--------------------------... |
34519d2fe10929981a8d84e2e5a10e81ec5fbb9c | muyisanshuiliang/python | /leet_code/547. 省份数量.py | 9,681 | 3.703125 | 4 | EXTEND = [1].extend([])
class Solution(object):
# def findCircleNum(self, isConnected):
# """
# :type isConnected: List[List[int]]
# :rtype: int
# """
# if isConnected is None or len(isConnected) == 0:
# return 0
# length = len(isConnected)
# nei... |
7b9a073898d2fcd5854326707e0ce0bd464449e1 | muyisanshuiliang/python | /function/param_demo.py | 2,612 | 4.1875 | 4 | # 函数的参数分为形式参数和实际参数,简称形参和实参:
#
# 形参即在定义函数时,括号内声明的参数。形参本质就是一个变量名,用来接收外部传来的值。
#
# 实参即在调用函数时,括号内传入的值,值可以是常量、变量、表达式或三者的组合:
# 定义位置形参:name,age,sex,三者都必须被传值,school有默认值
def register(name, age, sex, school='Tsinghua'):
print('Name:%s Age:%s Sex:%s School:%s' % (name, age, sex, school))
def foo(x, y, z=3, *args):
print(... |
142ccd55e9c47a386005d77ba332334e6c9d18ab | muyisanshuiliang/python | /leet_code/面试题 17.07. 婴儿名字.py | 6,702 | 3.671875 | 4 | """
每年,政府都会公布一万个最常见的婴儿名字和它们出现的频率,也就是同名婴儿的数量。有些名字有多种拼法
例如,John 和 Jon 本质上是相同的名字,但被当成了两个名字公布出来。给定两个列表,一个是名字及对应的频率,
另一个是本质相同的名字对。设计一个算法打印出每个真实名字的实际频率。
注意,如果 John 和 Jon 是相同的,并且 Jon 和 Johnny 相同,则 John 与 Johnny 也相同,即它们有传递和对称性。
在结果列表中,选择 字典序最小 的名字作为真实名字。
示例:
输入:names = ["John(15)","Jon(12)","Chris(13)","Kris(4)","Christopher(... |
b593a711496277b0d6e07c9737e65be58398bdd1 | muyisanshuiliang/python | /leet_code/203. 移除链表元素.py | 739 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
sentinel = ListNode(0)
sentinel.next = head
prev, curr = sentinel, head
whi... |
271be56c8d2ef15d8833c1e73d38bf1277696112 | muyisanshuiliang/python | /leet_code/179. 最大数.py | 673 | 3.75 | 4 | import functools
from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
if not nums:
return ''
class LargerNumKey(str):
def sort_key(a, b):
return a + b > b + a
# nums.sort(key=functools.cmp_to_key(sort_key))
... |
73b964bcfd79d45c732188ef41e7bb073547a0bc | muyisanshuiliang/python | /leet_code/56. 合并区间.py | 1,090 | 3.609375 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals or len(intervals) == 1:
return intervals
# 对元素的根据收个元素进行排序
intervals.sort(key=lambda item: item[0])
result = []
pre = None
max_index =... |
94d80b130c10f27a1b8f6c19ec872870a13d0e66 | muyisanshuiliang/python | /leet_code/674. 最长连续递增序列.py | 1,324 | 3.671875 | 4 | """
给定一个未经排序的整数数组,找到最长且连续递增的子序列,并返回该序列的长度。
连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,
那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。
示例 1:
输入:nums = [1,3,5,4,7]
输出:3
解释:最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。
示例 2:
输入:nums = [... |
01c6bce8f39004fd8285a1db0bca6d8d2fdf10e0 | muyisanshuiliang/python | /leet_code/189. 旋转数组.py | 1,591 | 3.59375 | 4 | class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
# 1、python技巧
# if nums is None or len(nums) == 0 or k == 0:
# return nums
# ind... |
ab46aed706af71ae97b65481899722a0c5f96c99 | muyisanshuiliang/python | /function/002-FunctionalProgramDemo.py | 5,162 | 4 | 4 | from functools import reduce
print("===============函数式编程===============")
print("===============1、map函数===============")
def power(x):
return x * x
# map()传入的第一个参数是f,即函数对象本身
list_number = [1, 2, 3, 4, 5]
# 结果iterator是一个Iterator,Iterator是惰性序列
iterator = map(power, list_number)
# 通过list()函数让它把整个序列都计算出来并返回一个list... |
1633d5677fbf97155489dc3cb2be67eb5a67af4c | muyisanshuiliang/python | /leet_code/976. 三角形的最大周长.py | 418 | 3.8125 | 4 | from typing import List
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
if not A:
return 0
A.sort()
r_inx = len(A) - 3
while r_inx >= 0:
if A[r_inx] + A[r_inx + 1] > A[r_inx + 2]:
return sum(A[r_inx:r_inx + 3])
el... |
1a0607a83d8a5b4b3a1769f78b62a1383aa8c664 | a-rhodes-vcu/Python-Physical-Implementation-of-Databases | /Project3.py | 3,907 | 4.21875 | 4 | import sys
import time
class Binary_Search_Tree:
"""Base Class representing a Binary Search Tree Structure"""
# Jet fuel can't melt binary trees #
class _BST_Node:
"""Private class for storing linked nodes with values and references to their siblings"""
def __init__(self, value):
... |
a06b7d3f65cfd52de14c87a537df8178c19e91ae | TheCDC/arcade | /arcade/utils.py | 2,252 | 4.03125 | 4 | import math
import random
from pymunk import Vec2d
def lerp(v1: float, v2: float, u: float) -> float:
"""linearly interpolate between two values"""
return v1 + ((v2 - v1) * u)
def vec_lerp(v1: Vec2d, v2: Vec2d, u: float) -> Vec2d:
return Vec2d(
lerp(v1.x, v2.x, u),
lerp(v1.y, v2.y, u)
... |
cedacc649bba0403d67724a7eefe65007ac84f4d | spiewakm/SuDoKu | /sudoku/AboutGame.py | 3,101 | 4.03125 | 4 | """
Class with game's information
"""
about = """\
SuDoKu is a simple Sudoku game, developed by Martyna Śpiewak in Python.
"""
keys = [
('Up arrow', 'Move cursor up'),
('Down arrow', 'Move cursor down '),
('Right arrow', 'Move cursor right'),
('Left arrow', 'Move cursor left'),
('Backspace/Delet... |
3a53ab12f8144942fbfcb56bbb56d407c32bdf3e | autumnalfog/computing-class | /Week 2/a21_input_int.py | 345 | 4.21875 | 4 | def input_int(a, b):
x = 0
while x != "":
x = input()
if x.isdigit():
if int(x) >= a and int(x) <= b:
return x
print("You should input a number between " + str(a) + " and " + str(b) + "!")
print("Try once more or input empty line to cancel input check.... |
82e3a0d0c83396db73fada0aec0c57c6d8885104 | MatthieuDasnoy/python-developer-roadmap | /Automate the Boring Stuff/Chapter 05 – Dictionaries and Structuring Data/fantasy_game_inventory.py | 634 | 3.75 | 4 | player_inventory = {'gold coin': 42, 'rope': 1}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(some_dict):
items_total = 0
print('Inventory:')
for k, v in some_dict.items():
print(v, k)
items_total += v
print('Total nu... |
fe36781d1eb5e83a0019831ed114b6faf242e87c | MatthieuDasnoy/python-developer-roadmap | /Automate the Boring Stuff/Chapter 10 – Debugging/debugging_coin_toss.py | 900 | 3.609375 | 4 | import random, logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
guess = ''
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails: ')
guess = input()
logging.debug('guess = ' ... |
283bac14f295c0e353eac3d97d435d48520b87fe | Kzarama/LabIA | /01-python/Strassen/strassen.py | 1,086 | 3.578125 | 4 | import numpy as np
def strassen(A, B):
if type(A) is not np.ndarray or type(B) is not np.ndarray:
raise Exception('Inputs are not numpy ndarrays')
# if :
# raise Exception('Inputs are not bidimensional')
# if True:
# raise Exception('Matrices are not squared')
# if True:
# raise Ex... |
b82f8105ecb02e6681e1fcbddc3a5ca6054f3908 | Natnaelh/Algorithm-Problems | /Data Structures/Stack.py | 1,209 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 10:26:32 2020
@author: natnem
"""
class Stack(object):
def __init__(self, stacksize):
self.stacksize = stacksize
self.array = [0]*stacksize
self.size = 0
def isFull(self):
return self.size == self... |
32aedfa5bf23dffc98aa06e1b7cf028e5e285448 | Natnaelh/Algorithm-Problems | /Dynamic Programming/TextJustification.py | 907 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 23:41:59 2020
@author: natnem
"""
mytext = 'helo there this'
words = mytext.split(" ")
n = len(words)
memo = {}
parent = {}
def textjust(i):
if i >= n:
return 0
elif i in memo:
return memo[i]
else:
bad = fl... |
dadffe77bb6d8d8f4e1eda4db97cd3d41bec4307 | Natnaelh/Algorithm-Problems | /Graph Algorithms/dfs.py | 2,235 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 13:50:34 2020
@author: natnem
"""
#class graph(object):
# def __init__(self):
# self.adj = {"a":["s","z"], "s":["x"],"z":["a"],"x":["d","c"],
# "d":["c","f"],"c":["f","v"],"f":["v"],"v":["g"],"n":["m"]}
# def itervertice... |
3ef1f0c470ef47b14c3dbd303edc8adf0078df15 | Natnaelh/Algorithm-Problems | /Data Structures/Stack_Two.py | 3,902 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 12:01:58 2020
@author: natnem
"""
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def stacksize(self):
return len(self.items)
def pop(self):
if s... |
ee5d68a33596446738ea4f73f65c43e2efbbf55d | Natnaelh/Algorithm-Problems | /Document Distance/Document DistnaceFirst.py | 905 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 14:42:39 2019
@author: natnem
"""
import math
D1 = ["the" , "cat" , "was" , "outside"]
D2 = ["the" , "cat" , "is" , "outside"]
def CountFreq(l):
count = {}
for word in l:
if word in count:
count[word] += 1
el... |
c1e7ce19fac8f6d3ee4e8005d69e054aac8d4f64 | Natnaelh/Algorithm-Problems | /Data Structures/DoublyLinkedList.py | 2,524 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 13:26:06 2020
@author: natnem
"""
""" IMPLMENTATION OF AN UNSORTED DOUBLY LINKED LIST"""
class Node(object):
def __init__(self, key):
self.key = key
self.next = None
self.prev = None
def getPrev(self):
retu... |
714acb7788822dec6a517513db12e584b4fd2f78 | AquaMagnet/python | /armstrong-numbers/armstrong_numbers.py | 188 | 3.890625 | 4 | def is_armstrong_number(number):
number = str(number)
armstrong = 0
for item in number:
armstrong += int(item)**len(number)
return(armstrong == int(number))
|
9fdc839e30c4eccbb829abfa30178545f2f3f7b3 | sheayork/02A-Control-Structures | /E02a-Control-Structures-master/main06.py | 719 | 4.5 | 4 | #!/usr/bin/env python3
import sys
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!')
color = input("What is my favorite color? ")
if (color.lower().strip() == 'red'):
print('Correct!')
else:
print('Sorry, try again.')
##BEFORE: Same as before, but some people ma... |
6959a455d7027b83f7d3f08b699ba3833c513bfa | larspli/bug-free-happiness | /sirkelberegning.py | 289 | 3.90625 | 4 | import math
radius=input("Verdien til radius?\n>")
radius=float(radius)
diameter= 2*radius
areal=math.pi*radius*radius
omkrets=2*math.pi*radius
print("\nDiameter: {0: .2f}".format(diameter))
print("Areal: {0: .2f}".format(areal))
print("Omkrets: {0: .2f}".format(omkrets))
|
55663511a862c190b307d3f19d9423e95f860ce1 | wjosew1984/python | /funcion7.py | 446 | 3.84375 | 4 | #lo hice con dos "for"
def mayormenor(lista):
k=lista[0]
for x in range(len(lista)):
if lista[x]>k:
k=lista[x]
z=lista[0]
for x in range(len(lista)):
if lista[x]<z:
z=lista[x]
print("El elemento mayor es", k," y el elemento menor es ",z)
... |
289f3eb1ea1df526769a1a39423882c493b03953 | wjosew1984/python | /practicaoperaciones.py | 497 | 3.96875 | 4 | n1 = 5
n2 = 20
resultado = (n1 + n2)
print("La suma es ", + resultado)
n1 = 5
n2 = 20
resultado = (n1 - n2)
print("La resta es ", + resultado)
n1 = 5
n2 = 20
resultado = (n1 / n2)
print("La division es ", + resultado)
n1 = 5
n2 = 20
resultado = (n1 * n2)
print("La multiplicacion es ", + res... |
5365df676239be0b5c4690b6cc95d4b4b3e2eb7d | wjosew1984/python | /diccionario7.py | 1,135 | 3.703125 | 4 |
def carga():
responde="si"
productos={}
while responde=="si":
codigo=input("ingrese codigo de producto: ")
desc=input("ingrese nombre producto: ")
prec=int(input("ingrese precio producto: "))
stock=int(input("ingrese cantidad en stock: "))
productos[codigo]=... |
14707821e0ad81c599c7e2c7d9c8011c2eda550a | wjosew1984/python | /ejerc7.py | 148 | 3.828125 | 4 | n1=float(input("ingresar n1: "))
n2=float(input("ingresar n2: "))
if n1>n2:
print("n1 es mayor a n2")
else:
print("n2 es mayor a n1")
|
c6597db9f0e60f4813b3d5f9b678dddeb4e6a1bc | wjosew1984/python | /nuevobis.py | 473 | 3.96875 | 4 | """
sueldo=int(input("Ingrese su sueldo burto por favor"))
if>30000:
print("Debe pagar impuesto a las ganancias")
else<29999
print("Debe pagar impuesto a las ganancias")
#####
nombre_alumno = input("Escriba el nombre de un alumno: ")
if nombre_alumno == "":
print("Error: no ha ingresado un ... |
458490153bd4f387052ac9e6efe0462611c8ae65 | wjosew1984/python | /lista_26_4.py | 674 | 3.765625 | 4 | #Crear y cargar una lista con 5 enteros por teclado, mostrar el menor valor de la lista y la posición doónde se encuentra:
lista=[]
t=0
for x in range(5):
v = int(input("Ingrese entero: "))
lista.append(v)
t=t+lista[x]
print(f"La lista contiene {lista} y {[len(lista)]} elementos")
k=lista[0]#nom... |
36065308743f3347b51f0284367a2fe1de392474 | wjosew1984/python | /clase1.py | 8,646 | 4.0625 | 4 | Introducción a la programación:
Un poco de Historia e introducción al Lenguaje
Surge en los años 90. Creado por el Holandes Guido van Rossum.
Lenguaje alto nivel: Cercano al ser humano.
Lenguaje de bajo nivel: Cercano a codigo binario. 1 y ceros.
Python esta orientado a objetos tal como Java. Lo único que mas se... |
deaa298d5be9815b2fba7560a11f046b2cadf194 | wjosew1984/python | /pedir2ntecladoymostrarnumerospares.py | 184 | 3.859375 | 4 | numero1 = int(input("Introduce el primer numero: "))
numero2 = int(input("Introudce el segundo numero: "))
for n in range(numero1, numero2+1):
if n % 2 == 0:
print(n) |
02eb2a3b3528e57b0217f2ec2e1586c249115639 | wjosew1984/python | /main.py | 1,764 | 3.9375 | 4 | """a=2
b=3
c=a+b
print("El resultado es", c)
nombre="Adrian"
apellido="Jusid"
print(nombre+" "+apellido)
print(nombre, apellido)
edad=36
print("soy" , nombre , apellido , "y tengo ", edad , "años")
a=100
b=1000
c=10000
print(a>b)
print(True and True)
print(True and False)
print(False a... |
6616b708b1aab6bb1b9db91e5d42094fc3597b68 | wjosew1984/python | /ejerc15.py | 486 | 3.671875 | 4 | cantp=int(input("ingrese la cantidad de personas: "))
km=int(input("ingrese la cantidad de km por recorrer: "))
micro=input("ingrese el tipo de micro: a, c ó b ")
if micro=="a":
pkg=km*2
else:
if micro=="b":
pm=km*2*5
else:
pm=km*3
preciototal=pm*cantp
if cantp>20:
precioind=... |
e9f735bcf71d70e868e32e16705e07cc12ef8e92 | wjosew1984/python | /ejerc4.py | 118 | 3.5 | 4 | vd=int(input("ingrese un valor: "))
cp=int(input("ingrese un valor: "))
td=cp/vd
print("El total dolar es :",td)
|
6951f7e3f45c70a2cb4b542ba6ec2df0bd6eabbb | wjosew1984/python | /funcion10.py | 849 | 3.75 | 4 | def carga():
sueldo=[]
for x in range(3):
f=int(input("Ingrese valor: "))
sueldo.append(f)
return sueldo
def impsueldo(sueldo):
print("lista de sueldos: ")
for x in range(len(sueldo)):
print(sueldo[x])
def mayor40k(sueldo):
tot=0
for x in... |
36357b7e13e3e49b7dc1d0eea90f19c0c383502d | YanrongXu/Leetcode | /Binary Search/230. Kth Smallest Element in a BST.py | 941 | 3.546875 | 4 | # In-order Traversal
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.tree_list = []
self.inOrder(root)
if k <= 0:
return None
print(self.tree_list)
return self.tree_list[k-1]
def inOrder(self, root):
if... |
c27f9020cb6bfa7ce8e03fbec2eeb6b4983ba19d | aimemalaika/intro-to-python | /basics I/dataconversion.py | 175 | 3.515625 | 4 | a = 100
# convert to string
b = str(a)
print(a)
print(type(a))
print(b)
print(type(b))
# convert to int
a = 100
# convert to string
c = int(b)
print(c)
print(type(c)) |
d17fcba1a1a7a73b08bf6e3c8208318b4661d148 | manuelklug/learning | /Python UNSAM/Clase 2/tabla_informe.py | 1,791 | 3.53125 | 4 | # tabla_informe.py
import csv
# Funcion leer_camion
def leer_camion(nombre_archivo):
camion = []
with open(nombre_archivo) as file:
rows = csv.reader(file)
headers = next(rows)
for row in rows:
record = dict(zip(headers, row))
cajon = {
'nombre':... |
5800638df7e06468ddfaf0fc870fbcae926b5838 | ptetalicoder/Final-Project--CIS2348 | /Homework 3 - 11.22.py | 183 | 3.5625 | 4 | #Pranav Tetali
#ID 1541822
#Homework 3 11.22
words = input().split()
for word in words:
count = 0
for w in words:
if w == word:
count += 1
print(word, count) |
240ef926f2383e9a91f63c086c02b32d7d36b13b | ptetalicoder/Final-Project--CIS2348 | /Homework 3 - 10.17 Part 1.py | 1,562 | 4.03125 | 4 | #Pranav Tetali
#ID 1541822
#Homework 3 10.17
class ItemToPurchase:
# EX #1
def __init__(self):
# variables
# given values
self.item_name = "none"
self.item_price = 0
self.item_quantity = 0
#items
def print_item_cost(self):
#It should display the item... |
50b76bec203e5922cc4419fff9deb5ddd5e6cb62 | braraki/logical-options-framework | /simulator/object.py | 10,367 | 3.75 | 4 | import numpy as np
from numpy.random import randint
from collections import OrderedDict
import random
"""
Author: Brandon Araki
This file contains classes that describe "objects" in the environment.
Objects have a state space, a state, and update rules.
"""
# describe the Agent as an object
class AgentObj(object):
... |
7cff6fe881137bc81dcc5540efc806eb8ab75bc4 | maxsolberg/ORSuite | /or_suite/envs/ambulance/ambulance_metric.py | 7,150 | 3.53125 | 4 | '''
Implementation of a basic RL environment for continuous spaces.
Includes three test problems which were used in generating the figures.
'''
import numpy as np
import gym
from gym import spaces
import math
from .. import env_configs
#------------------------------------------------------------------------------
''... |
b93667bb58dfc610850d6ffa407ee418af6f44b0 | Mamedefmf/Python-Dev-Course-2021 | /magic_number/main.py | 1,233 | 4.15625 | 4 | import random
def ask_number (min, max):
number_int = 0
while number_int == 0:
number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ")
try:
number_int = int(number_str)
except:
print("INPUT ERROR: You need to type a valid numbe... |
e8b2e2de913f442512a58987a99cce6371849ae9 | pranavkaul/Coursera_Python_for_Everybody_Specialization | /Course-3-Using Python to Access Web Data/Assignment7-JSON.py | 1,739 | 3.9375 | 4 | #In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that un... |
2a2ae134cceba04732db0f61fb19f83221ca3f1d | pranavkaul/Coursera_Python_for_Everybody_Specialization | /Course-1-Programming for everybody-(Getting started with Python/Assignment_6.py | 999 | 4.3125 | 4 | #Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
#Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
#Put the logic to do the computation of pay in a function called computepay() and use the funct... |
1fd47db24f772cf140ea6cf2ee5808b4398fcbed | annafleming/Python-Training | /Recursion/exercises/tests/examples_test.py | 660 | 3.890625 | 4 | import unittest
from .. import examples
class RecursionExamplesTestCase(unittest.TestCase):
def test_should_return_true_if_value_is_found(self):
sequence = [1, 4, 6, 7, 8, 9, 10]
self.assertTrue(examples.in_list(sequence, 9))
sequence = [1, 4, 6, 7, 8, 9, 10, 11]
self.assertTrue(e... |
d955e9fa46e5738527334d40c6c068eb1e81abe1 | annafleming/Python-Training | /Python Primer/exercises/reinforcement.py | 628 | 3.734375 | 4 | from random import randrange
def is_multiple(n, m):
return n % m == 0
def is_even(n):
while n >= 2:
n -= 2
return False if n == 1 else True
def minmax(data):
min_item = max_item = data[0]
for item in data:
if item < min_item:
min_item = item
if item > max_ite... |
b6be97451439d9a72f9304e49a0164c3e3a74ea0 | gabriel-portuga/Exercicios_Python | /ex067_tabuada.py | 418 | 3.71875 | 4 | while True:
num = int(input('Quer ver a tabuada de qual valor: '))
if num < 0:
break
print('-'*20)
for i in range(1, 11):
print(f'{num} x {i:>2} = {num * i}')
print('-'*20)
continua = 's'
while continua in 'sS':
continua = str(input('Deseja continua? [S/N] ')).strip()... |
d7855d43a0db8895af9eb431fe334c3369bce5d1 | gabriel-portuga/Exercicios_Python | /ex038_comparandonumeros.py | 399 | 3.671875 | 4 | print('\033[7;30m-=\033[m'*15)
print(' \033[7;30m Bem vindo ao APP Go!Sys \033[m')
print('\033[7;30m-=\033[m'*15)
# Inico do condigo
n1 = int(input(('\nDigite um número: ')))
n2 = int(input('Digite outro valor: '))
if n1 > n2:
print('O primeiro valor é maior!')
elif n2 > n1:
print('O segundo número é maior!'... |
00e4fb1dca49a8e5dcd5657b43edc6e4691ba45a | gabriel-portuga/Exercicios_Python | /ex065_maioremenor.py | 1,050 | 4.0625 | 4 | """
num = soma = cont = media = maior = menor = i = 0
while i != 1:
num = int(input('Digite um número: '))
soma += num
cont += 1
media = float(soma / cont)
if cont == 1:
menor = num
if num > maior:
maior = num
elif num < menor:
menor = num
i = int(input('Digite um... |
10fd72a743b1d9398be5d213f88cc7f927b12a3f | gabriel-portuga/Exercicios_Python | /ex062_superprogressao.py | 828 | 3.9375 | 4 | """ ERRADO
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razão da PA: '))
termo = primeiro
cont = 1
escolha: int = 1
while escolha != 0:
while cont <= 10:
print('{} -> '.format(termo), end='')
termo += razao
cont += 1
escolha = int(input('Deseja mostrar mais quantos termos... |
eee62591903f3920aea6dbbfeb6c4966f5714966 | gabriel-portuga/Exercicios_Python | /ex080_ListaOrdenada.py | 514 | 4.03125 | 4 | numeros = list()
for i in range(0, 5):
n = int(input('Digite um valor: '))
if i == 0 or n > numeros[-1]:
numeros.append(n)
print('Adicionado ao final da lista...')
else:
posicao = 0
while posicao < len(numeros):
if n <= numeros[posicao]:
numeros.i... |
bf394547b09f92d6ef9fa0133d3385f2edba8d99 | gabriel-portuga/Exercicios_Python | /ex064_tratandovalores.py | 298 | 3.828125 | 4 | """num: int = 0
cont: int = 0
soma: int = 0"""
num = cont = soma = 0
while num != 999:
num = int(input('Digite um número[999 para parar]: '))
if num != 999:
soma += num
cont += 1
print('Foram digitador {} números e a soma entre eles é: {}.'
''. format(cont, soma))
|
15bc4f04dfb5dafdb153a7a060a21bb1602492ff | gabriel-portuga/Exercicios_Python | /ex030_pariouimpar.py | 223 | 3.78125 | 4 | from time import sleep
num = int(input('Me diga um número qualquer: '))
print('Processando...')
sleep(2)
if num % 2 == 0:
print('O número {} é PAR!'.format(num))
else:
print('O número {} é IMPAR!'.format(num))
|
fdaa9ff1d96bf5473826045d769273d40e25428a | gabriel-portuga/Exercicios_Python | /ex013_reajustesalarial.py | 198 | 3.765625 | 4 | s1 = float(input('Digite o salário do funcionário para aplicar o aumento: R$'))
print('O funcionário recebia R${:.2f} e agora recebera com o aumento de 15%, R${:.2f}.'.format(s1, s1+(s1*15/100))) |
afcae7c47574afbac769255bbee6b21acb085b54 | raubana/Pancake_Script_Tests | /V5/pancake/compiler/subroutine_finder.py | 3,755 | 3.640625 | 4 | """
The purpose of the gotoifyer is to place TYPE_GOTO tokens into the script where they're needed. TYPE_GOTO tokens are
necessary for if-else chains, while loops, and breaks to work.
"""
from tokenizer import Token
from constants import *
from common import find_endblock_token_index, find_startblock_token_index, incr... |
95f1961772e9d4f09bf91100b0ca469d99fcf156 | raubana/Pancake_Script_Tests | /V2/pancake/compiler/blocker.py | 1,358 | 3.765625 | 4 | """
The purpose of the blocker is to substitute TYPE_ENCLOSED tokens with their appropriate
TYPE_BLOCK_START/TYPE_BLOCK_END pairs. It also checks that every block token is properly paired.
"""
from .. constants import *
from .. error_format import error_format
class Blocker(object):
@staticmethod
def process(tokenl... |
e67b78aa433f74d475e110d7633deeb3ea34afdc | raubana/Pancake_Script_Tests | /V2/pancake/compiler/line_blocker.py | 879 | 3.734375 | 4 | """
The purpose of the line blocker is to block off sections of code that are their own line. This prevents the shunter
from reordering sections of code that must remain in a particular order.
"""
from tokenizer import Token
from .. constants import *
class LineBlocker(object):
@staticmethod
def process(tokenlist)... |
878a3b806fb1efae157947753a116ea04ee76958 | reynld/Sorting | /project/recursive_sorting.py | 2,429 | 4.09375 | 4 | ### helper function
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
a = 0
b = 0
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
for i in range( 0, elements ):
if a >= len(arrA): # all eleme... |
412e2228c42ecdd818ffc52c0ebad6ef7e5035ad | vid083/dsa | /Python_Youtube/type.py | 241 | 4.1875 | 4 | value = int(input('Input a value: '))
if type(value) == str:
print(value, 'is a string')
elif type(value) == int:
print(value, 'is a integer')
elif type(value) == list:
print(value, 'is a list')
else:
print(value, 'is none') |
867bf977490089e4db47ac7a29b7e45d03fd9e1e | vid083/dsa | /Python_Youtube/nested.py | 105 | 3.734375 | 4 | my_list = [[1,2,3], [4,5,6], [7,8,9]]
for lists in my_list:
for items in lists:
print(items) |
4423c0ea9eaf1e1b798a5dae8cac898b430f20b1 | vid083/dsa | /Python_Youtube/basic_cal.py | 248 | 4.03125 | 4 | n1 = int(input('Enter first number: '))
n2 = int(input('Enter second number: '))
op = input('enter operation to perform: ')
if op == '+':
print(n1+n2)
if op == '-':
print(n1-n2)
if op == '*':
print(n1*n2)
if op == '/':
print(n1/n2) |
a9752d243a82bb69b7a35132b80c53d3236b725b | vid083/dsa | /Greeks4greeks/Recursion/decimal_to_binary.py | 117 | 4 | 4 | # Decimal to binary conversion:-
def fun(n):
if n>0:
fun(n//2)
print(n%2)
n=int(input())
fun(n) |
1d204736ae60d0d946e4cd8bbbff364a7d491e21 | Abreu-Ricardo/IC | /clivar.py | 872 | 3.578125 | 4 | # Programador: Ricardo Abreu
# Inicio da clivagem de algoritmos
from LCS import LCS
arquivo = open("entrada.txt", "r")
# Criando objetos
pept1 = LCS()
pept2 = LCS()
resultado = None
for aux in arquivo:
try:
if aux[0] == '>':
continue
else:
pept1.string = aux
if... |
6aa060874a60746319bc27f40fd0a00f9108fdbd | JonReinhold/FrenchLearningTool | /History/rebuild.py | 1,210 | 3.640625 | 4 | import random
from fuzzywuzzy import fuzz
frenchList = [['yes','oui',0],['no','non',0],['hello','bonjour',0],['not','pas',0],['you','vous',0],['in','dans',0],['dictionary', 'dictionnaire', 0]]
orderedFrenchList = []
def wordFeed():
index = random.randint(0,len(frenchList)-1)
global word
word = ... |
839dea017945129886e7ba7b985bcd887cfc42d5 | Leviosar/ufsc | /19.2/INE5404/exercicios/ex1/q25.py | 205 | 3.796875 | 4 | from math import sqrt
def isPrime(n):
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
for i in range(100001):
if isPrime(i):
print(i) |
5373b0122d3797c39579237ea0c5d4ef42abc5da | HerndonE/CST-311-Intro-to-Computer-Networks | /Homework/Week 9/Programming_Assignment_3_TCP_Client_Server_Team4/PA3_Server_Team4.py | 4,132 | 4.25 | 4 | # Ethan Herndon
# Mustafa Memon
# Maria Leftheriotis
# Alvin Liang
# Programming Assignment 3: TCP Client Server
'''
-Explain why you need multithreading to solve this problem. Put this in a comment at the top of your server code-
For this code you need to have a multithreaded server so you are be able to have two co... |
e7fe2e55d6f9c213a05a4620b3150d227712d5d7 | zhouyuhangnju/freshLeetcode | /Add Binary.py | 1,080 | 3.59375 | 4 | def addBinary(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = list(a)[::-1]
b = list(b)[::-1]
print a, b
carry = '0'
if len(a) > len(b):
a, b = b, a
minlen = len(a)
res = [bb for bb in b]
for i in range(minlen):
if a[i] == '0' and b[i] ==... |
bdfc13c8a720a1846ace858343959f44afd41f3a | zhouyuhangnju/freshLeetcode | /LetterCombinationsofaPhoneNumber.py | 1,045 | 3.5 | 4 | def letterCombinations(digits):
"""
:type digits: str
:rtype: List[str]
"""
digitletterdict = {"0": "0", "1": "1", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv",
"9": "wxyz"}
# strlist = []
#
# for digit in digits:
# letters = digitlet... |
050611de1ceb8e48c8ee2f79ca721147e5a4f0cb | zhouyuhangnju/freshLeetcode | /Sort Colors.py | 1,153 | 4.21875 | 4 | def sortColors(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
def quicksort(nums):
def subquicksort(nums, start, end):
if start >= end:
return
p = nums[start]
i, j, di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.