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 |
|---|---|---|---|---|---|---|
d05e4f23885e7af63a2d20631ed36113a19b1d91 | ali1vegeta/Pythonprojects | /9.stringfunctions.py | 424 | 3.640625 | 4 | story = "once upon a time there was a guy named harry who uploaded virus on our office network!"
#string functions
print(len(story))
print(story.endswith("network!"))
print(story.count("on"))
print(story.capitalize())
print(story.find("who"))
print(story.replace("harry", "ali"))
###ESCAPE SEQUENCES \n-newli... |
4cfd7a84f0ca32c674c7353554b19010160ccd07 | kadarsh2k00/python-exercise | /Python GitHub/Q7.py | 165 | 3.59375 | 4 |
X,Y=input().split(',')
X=int(X)
Y=int(Y)
A=[]
for i in range(0,X):
B=[]
for j in range(0,Y):
B.append(int(j*i))
A.append(B)
print(A)
|
5974f76399ed6c1203bd4658703a376714177c5b | kadarsh2k00/python-exercise | /Python GitHub/Q11.py | 105 | 3.546875 | 4 | s=input().split(',')
l=[]
for x in s:
if int(x,2)%5==0:
l.append(x)
print(','.join(l))
|
817175141fc23dd36545c12af83a150c25c2f650 | kadarsh2k00/python-exercise | /Python GitHub/Q9.py | 185 | 3.625 | 4 | ##import sys
##Q=sys.stdin.read()
##print(Q.upper())
##
d=[]
while(1):
s=input()
if s:
d.append(s.upper())
else:
break
for x in d:
print(x)
|
510bea3cf89f0af23a66b3df53ed475e8e60487d | kadarsh2k00/python-exercise | /Python GitHub/Q68.py | 191 | 3.71875 | 4 | def even(n):
for i in range(1,n+1):
if i%2==0:
yield i
m=int(input())
x=even(m)
p=list(x)
for i in range(len(p)):
p[i]=str(p[i])
print(','.join(p))
|
3daf2bd05ac6c4732b13de098ecdc788e2a9fd14 | kadarsh2k00/python-exercise | /Python GitHub/Q14.py | 220 | 3.640625 | 4 | s=input().split(' ')
c=0
d=0
for i in range (0,len(s)):
for k in s[i]:
if k.isupper():
c=c+1
elif k.islower():
d=d+1
print('LOWER CASE:',d)
print('UPPER CASE:',c)
|
b14d6a7060f121cbfbf791feba4f43a6934a14b0 | kadarsh2k00/python-exercise | /Python GitHub/Q22.py | 192 | 3.578125 | 4 | s=input()
p=s.split(' ')
p.sort()
new=[]
for x in p:
if x not in new:
new.append(x)
for i in range(0,len(new)):
print(new[i],':',s.count(new[i]),sep="")
|
1cb42c500692eb1303ff95d5d87ca45abe9fb413 | KornavitCS36KU81/lab_python | /lab_python/lab10.py | 2,770 | 3.84375 | 4 | """
1
scores = []
while True:
score = int(input("Enter score: "))
if score > 10 or score < 0:
print("Score is out of range.")
else:
scores.append(score)
if len(scores) == 20:
break
print("Original list:")
print(scores)
for i in range(11):
count = 0
... |
4c6dc7ef2e8d91ca246b535e4ab1e8c53e3140a7 | AliciaAsmarian/reservation_system- | /rss.py | 3,903 | 4.15625 | 4 | import json
def load_rs_setup():
with open('rs_setup.json') as data_file:
data = json.load(data_file)
cafeteria_tables = data["cafeteria_tables"]
return cafeteria_tables
cafeteria_tables = load_rs_setup()
print ("Hi, this is a cafeteria reservation program!")
print ("This caf... |
447850fd37249fc7e61e435c8823d86a73c42512 | sprajjwal/CS-2.1-Trees-Sorting | /Code/sorting_iterative.py | 2,700 | 4.25 | 4 | #!python
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n) because we iterate through the loop once
Memory usage: O(1) because we check in place"""
# Check that all adjacent items are in order, return early if so
if len(items) < 2:
... |
a895476473a9c610b719c7ff2fa8cc7f89992ade | stevencharleshuang/python-sandbox | /lists.py | 1,119 | 3.65625 | 4 | # my_list = [1, 2, 3]
# my_list = ['asdf', 1, 'two', 3, ['a', 'b', 'c']]
# print(len(my_list))
# print(my_list)
my_list = ['a', 'b', 'c', 'd', 'e']
print('my_list: ', my_list[0])
print('my_list: ', my_list[-1])
print('my_list: ', my_list[1:])
print('my_list: ', my_list[:3])
print('my_list: ', my_list[1:3])
# Lists a... |
e73e3bbcc35c323f3c8ce8c73b23b075ad921ae2 | Jesuisjavert/Algorithm | /39.square_chance_count.py | 393 | 3.53125 | 4 | import sys
sys.stdin = open('input.txt','r')
T = int(input())
def square(n):
if n == 1:
return 1
elif n ==2:
return 3
elif n == 3:
return 5
elif n >3:
result = square(n - 1) + square(n - 2) * 2
return result
for testcase in range(1, T + 1):
N = int(input())
... |
36ab7be719a06ec64b2d81b925e688f6ac1ba348 | rohitpatel0011/python-1 | /socket-demo/socket-demo.py | 1,468 | 3.703125 | 4 | """
验证 accept 得到的是 connection, 不是消息
"""
from socket import socket, AF_INET, SOCK_STREAM
def pick_a_message(conn):
msg = ""
data = conn.recv(1024)
data = data.decode("utf-8")
while not data.endswith("\n"):
msg = msg + data
data = conn.recv(1024)
data = data.decode("utf-8")
... |
7f662d11f3d717bce966e2fe460fcdc8db595e9f | rohitpatel0011/python-1 | /grammar/args-kwargs-demo.py | 346 | 3.8125 | 4 | def fun(*args, **kwargs):
for arg in args:
print(arg)
for kwarg in kwargs:
print(kwarg)
if __name__ == '__main__':
args = ["arg_{i}".format(i=i) for i in range(3)]
kwargs = dict(zip(args, range(3)))
fun(args, kwargs)
fun(*args, **kwargs)
fun("arg_0", "arg_1", "arg_2", nam... |
b10c2d538ad0f5b84997132b002549c9a8a88668 | rohitpatel0011/python-1 | /thread_pool.py | 2,592 | 3.9375 | 4 | """
自定义 thread pool。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. 使用 Queue 在主线程和 Executor 之间传递参数。(自己实现线程间通
讯是很难的,而且每种语言几乎都自带了实现线程间通信的 API, 使用现成
的 API 是最优的实现。有空读读 Queue 的源码,加深对于线程间通讯的理
解。)
2. 这个实现,没有给出线程调度机制。把多线程拆成 Executor 和 Task
两个概念,就是为了方便地使用不同的线程调度机制。所以这个实现,只是
个练习。实际编程不要使用这个 `MyThreadPool`。
... |
5c57643cc0425dd4d999089e5717ab848d47879c | EdwaRen/Competitve-Programming | /Leetcode/190.reverse-bits.py | 412 | 3.59375 | 4 | class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
# Bit manipulation, adds the last digit of n, then reduces n by a bit so that
# it is added to res in reverse
res = 0
for i in range(32):
res = (res << 1) + (n & 1)
... |
c9ba301290db913ea7ece19588785bd738686425 | EdwaRen/Competitve-Programming | /Leetcode/78-Subsets.py | 432 | 3.578125 | 4 | class Solution:
def subsets(self, nums):
return self.iterate(nums)
def iterate(self, nums):
res = [[]]
for i in nums:
res+=[ item + [i] for item in res]
return res
def dfs(self, nums, index, path, res):
res.append(path)
for i in range(index, len(... |
3f9e81b8ab8e6d91c2619f1a6c36a8f698d679d6 | EdwaRen/Competitve-Programming | /Leetcode/460-LFU-cache.py | 4,600 | 3.78125 | 4 | import collections
import pdb
class LLNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
class DoubleLL:
def __init__(self):
"""
A custom class for doubly linked lists.
We define our custom sentin... |
31277d08530e330be1fbe3b435171d519ece503e | EdwaRen/Competitve-Programming | /Leetcode/84.largest-rectangle-in-histogram.py | 456 | 3.59375 | 4 | class Solution(object):
def largestRectangleArea(self, heights):
heights.append(0)
stack = [-1]
max_area = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
a = stack.pop()
max_area = max(max_area, heights[a] * (i - sta... |
3c0b44368089b0bef4753c9dbd044d00719fa224 | EdwaRen/Competitve-Programming | /Leetcode/141-Linked_list_cycle.py | 591 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def hasCycle(self, head):
try:
walker = head
runner = head.next
while walker is not runner:
walk... |
094223d221f95ab9692c90fdf2e6eb4fdb9e1323 | EdwaRen/Competitve-Programming | /Leetcode/1428-leftmost_col_with_one.py | 1,117 | 3.6875 | 4 | # """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, row, col):
# """
# :type row : int, col : int
# :rtype int
# """
#
# def dimensions:
# """
# :rtype list[]... |
9117b37c142d05805f71372d7582f5fe639bae91 | EdwaRen/Competitve-Programming | /Leetcode/166-Fraction_recurring.py | 1,062 | 3.59375 | 4 | import math
class Solution:
def fractionToDecimal(self, numerator, denominator):
if denominator == 0:
return
if numerator == 0:
return "0"
s_num = (numerator > 0) == True
s_den = (denominator > 0) == True
numerator = abs(numerator)
denominator ... |
f9fbe68a6bfeacf561c44eb4e654d19bca50ffc6 | EdwaRen/Competitve-Programming | /Leetcode/295.find-median-from-data-stream.py | 1,084 | 3.578125 | 4 | from heapq import heappush, heappop, heappushpop
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.min_h = [] # Elements ABOVE median, minheap
self.max_h = [] # Elements BELOW median, maxHeap
def addNum(self, num... |
8c9a41d6198ea24068b044abad5f687f206c475e | EdwaRen/Competitve-Programming | /Leetcode/721.accounts-merge.py | 1,222 | 3.671875 | 4 | import collections
class Solution(object):
def find(self, parents, email):
if parents[email] != email:
parents[email] = self.find(parents, parents[email])
return parents[email]
def union(self, parents, email_a, email_b):
parents[self.find(parents, email_a)] = self.find(... |
cbd8c92502110a21b035a4699ef5cc7cab863da2 | EdwaRen/Competitve-Programming | /Leetcode/251.flatten-2d-vector.py | 924 | 3.578125 | 4 | class Vector2D(object):
def __init__(self, v):
# Flatten the matrix
self.flatten = []
for i in v:
self.flatten += i
# Record length of the flattened array
self.len_flat = len(self.flatten)
# Turn the array into an iterator
self.flat = iter(self... |
604718c7a77bd10aa363ed03611835b50ea4cd1d | EdwaRen/Competitve-Programming | /Leetcode/26.remove-duplicates-from-sorted-array.py | 721 | 3.53125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
# Handle edge case
if not nums or len(nums) == 0:
return 0
# Use crawler and runner
left = 0
left_run = 1
# Go through all elements in num
while left_run < len(nums):
... |
bc4b820618576f16d4fa6ba797cc41ee4064130f | EdwaRen/Competitve-Programming | /Leetcode/155-Min_Stack.py | 678 | 3.671875 | 4 | import math
class MinStack:
def __init__(self):
self.min = None
self.arr = []
self.minArr = []
def push(self, x):
self.arr.append(x)
if self.minArr:
cur_min = self.minArr[-1]
self.minArr.append(min(cur_min, x))
else:
self.min... |
4c820a61e4fe29a7becb7c8306790959c3f0988c | EdwaRen/Competitve-Programming | /Leetcode/317.shortest-distance-from-all-buildings.py | 2,522 | 3.625 | 4 | import collections
class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# Handle empty graph
if not grid or len(grid) == 0:
return -1
M, N = len(grid), len(grid[0])
# We use 2... |
31d254811ae3d27ed285b6cbf33c6c299cb0d48d | EdwaRen/Competitve-Programming | /Leetcode/545.boundary-of-binary-tree.py | 1,871 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import collections
class Solution(object):
def boundaryOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: List[int]
... |
984c39084bdaddc395983e9b8e5da1c54e2deab7 | EdwaRen/Competitve-Programming | /Leetcode/74-search_2d_matrix.py | 1,296 | 3.671875 | 4 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
Double binary search, applied the DRY principle by passing in conditions
to the binary search algorithm instead of having 2 very similar ... |
3384f4d997d25e3e6e0d5803a29170b4adbd0c37 | EdwaRen/Competitve-Programming | /Leetcode/819-Most_Common_words.py | 711 | 3.703125 | 4 | from collections import defaultdict
class Solution():
def mostCommonWord(self, sentence, banned):
exclude = set([a for a in "?!',;."])
map = {}
map = defaultdict(lambda:0, map)
sentence = ''.join(ch for ch in sentence if ch not in exclude)
for word in sentence.split():
... |
f571a62f293c21d6bad5f894c22e0317c51e31af | EdwaRen/Competitve-Programming | /Leetcode/55.jump-game.py | 527 | 3.59375 | 4 | class Solution(object):
def canJump_good(self, nums):
# Max jump keeps track of the furthest reach, since users can jump to all range(0, n) levels
max_jump = nums[0]
for i in range(len(nums)):
# The current index cannot be reached
if i > max_jump:
re... |
b93144ddd1170ffed7f749e9f2819d6b26b450a9 | EdwaRen/Competitve-Programming | /Leetcode/33-Search_Rotated_Array.py | 870 | 3.53125 | 4 | class Solution:
def search(self, nums, target):
if not nums:
return -1
lo = 0
hi = len(nums)-1
while lo <= hi:
mid = lo+((hi-lo)//2)
# print("mid", mid, lo, hi)
temp = 0
if target < nums[0]:
if nums[mid] ... |
c1ce2009246ee894778f328e7b1c8c80e2d27e28 | EdwaRen/Competitve-Programming | /Leetcode/130.surrounded-regions.py | 1,465 | 3.703125 | 4 | class Solution(object):
def solve(self, board):
# Handle base case
if len(board) == 0 or len(board[0]) == 0:
return board
# Get Mark all Os on the edge and their connected Os
for i in range(len(board)):
for j in range(len(board[0])):
if i == ... |
5c76cd7d878b39c357e94c52907a84d337b90657 | EdwaRen/Competitve-Programming | /Leetcode/305.number-of-islands-ii.py | 1,959 | 3.546875 | 4 | import collections
class Solution(object):
# Find in Union Find
def find(self, parents, loc1):
# Use path compression for amortized O(1)
if parents[loc1] != loc1:
parents[loc1] = parents[parents[loc1]]
return self.find(parents, parents[loc1])
return loc1
# ... |
f7a392da2c54c43846310aadff32126a4e3d7ca0 | EdwaRen/Competitve-Programming | /Leetcode/125.valid-palindrome.py | 895 | 3.84375 | 4 | class Solution(object):
def isPalindrome(self, s):
# Handle edge case
if not s:
return True
# Initialize the two pointers
left = 0
right = len(s) -1
# check every element single pass
while left <= right:
# Ski... |
cbe2c1b334165b24b1c175e56e545408a0e45f98 | EdwaRen/Competitve-Programming | /Leetcode/380-Get_Random.py | 986 | 3.84375 | 4 | from random import randint
class RandomizedSet:
def __init__(self):
self.dict = {}
self.arr = []
def insert(self, val):
if val in self.dict:
return False
self.dict[val] = len(self.arr)
self.arr.append(val)
return True
def remove(self, val):
... |
601e396d9943c9498395e23372396dc7a5aeef31 | EdwaRen/Competitve-Programming | /Leetcode/332.reconstruct-itinerary.py | 677 | 3.640625 | 4 | import collections
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = collections.defaultdict(list)
for ticket in sorted(tickets)[::-1]:
graph[ticket[0]].append(ticket[1])
... |
b3ff0e06ec859e5ab8bee9d974b06778e3b5d1d0 | EdwaRen/Competitve-Programming | /Leetcode/230.kth-smallest-element-in-a-bst.py | 1,327 | 3.765625 | 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):
def kthSmallest(self, root, k):
cur = root
count = 0
stack = [root]
# Iterative inorder ... |
f6a010cfb54333c482dc33167350745bd73e6247 | EdwaRen/Competitve-Programming | /Leetcode/445.add-two-numbers-ii.py | 1,734 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def init_stacks(self, l1, l2, s1, s2):
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
... |
d30d8c4d700bd6d458351c5c45d0ec911c7353dd | nightphoenix13/PythonClassProjects | /DegreeHours.py | 574 | 4.0625 | 4 | # Logic Design COSC 1309-2001
# Written by Zack Rosales
# Output for program description
print ("This program calculates the number of credit hours remaining for your degree.")
# Getting data from user
name = input("\nEnter your name: ")
major = input("Enter your major of study: ")
totalHours = int(input("How many ho... |
cf33043df637dff1470547b466ded6b71d4cd434 | nightphoenix13/PythonClassProjects | /FinalExamQuestion31.py | 1,412 | 4.125 | 4 | def main():
month = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]
highs = [0] * 12
lows = [0] * 12
for temps in range(len(month)):
highs[temps] = int(input("Enter the highest temperature for " +
... |
b36b52841f7e33f6a6b849a1ba3d14a6545b31ce | MariDoes/PC-2019-02 | /ejercicio3.py | 1,056 | 4.1875 | 4 | 3 #Escriba un programa que registre las inscripciones de un curso de natación.
#El curso solo acepta 5 personas y se debe preguntar 3 datos: nombre, sexo y edad.
#El programa solo debe permitir inscripciones de edades entre 5 y 17 años.
# El programa debe terminar cuando se tenga a las 5 personas que cumplan los req... |
315afdef1cf5358129850bdde97fe7498e6c5816 | tejas-rane/Codelets-Python | /iterators&generators.py | 872 | 4 | 4 | class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index -1
return self.data[self.index]
def revers... |
1427f3086f4300d72cc9c884d51bfe23429e0e4d | tejas-rane/Codelets-Python | /inheritence.py | 990 | 3.984375 | 4 |
class Pet:
def __init__(self,name,age):
self.name=name
self.age=age
def talk(self):
raise NotImplementedError("subclass must implement absrtact method")
class Cat(Pet):
def __init__(self,name,age):
super().__init__(name, age)
def talk(self):
return "Meow... |
c5d2d129497d76681f901f57db50502899f5a1ba | michaelsanchez11/CODE2040_API | /step5.py | 1,778 | 3.671875 | 4 | #Problem: Solve the dating game, by adding the seconds to the date and returning the new date.
#import requests for the json request
#import ast to change from unicode to ascii dictionary
#import datetime to use the date time functions and object
import requests
import ast
import datetime
#requested call
requestCall... |
1caea8f36ea11c258084268f17d2f3f5934d3730 | crj32/python_general_scripts | /swapfilenamesusingfile.py | 674 | 3.53125 | 4 | #!/usr/bin/python
import os
os.chdir("./")
filelist = open('swapmappings.csv', 'r')
# add file names to swap to a dictionary
myfiledict = {}
for line in filelist:
original = line.split(',')[0]
print(original)
replacement = line.split(',')[1]
print(replacement)
myfiledict[original] = replacement
... |
198adc0fc1d828b76f03f6abce06034a5855ae37 | Allaye/Data-Structure-and-Algorithms | /Linked List/cycle_check.py | 416 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
def check_cycle(node):
'''
check if current node next node points to imediate past node
'''
cur_node = node
if(cur_node.next == None):
return
while(True):
temp = cur_node
cur_node = cur_node.next
if(cur_node.next =... |
f6076d80cbf22a0af11337a6a329fe64df60477e | Allaye/Data-Structure-and-Algorithms | /Linked List/reverse_linked_list.py | 615 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from linked_list import LinkedList
L = LinkedList(10)
def reverse(L):
'''
reverse a linked list nodes, this reverse implementation made use of linked list implemented before
'''
lenght = L.length()
if(lenght == 0):
raise IndexError('The lis... |
edfba19244397e3c444e910b9650de1a855633b3 | Allaye/Data-Structure-and-Algorithms | /Stacks/balancedParen.py | 2,399 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from Stack import Stack # personal implementation of stack using python list
# In[12]:
def check_balance(string, opening='('):
'''
a function to check if parenthesis used in a statement is balanced
this solution used a custom implementation of a stack u... |
8bf632c64ee8a89f9ed48aa0da5cdf2f973d5592 | mukilvoltz/GUVi-codes | /jokeQ54.py | 67 | 3.6875 | 4 | a=int(input())
b=a-1
if a % 2 ==0:
print(a)
else:
print(b)
|
f071c0e319df27d7b69aa149f04fa33c14cd60fe | mukilvoltz/GUVi-codes | /nonuminword.py | 158 | 3.609375 | 4 | a=input()
num=["1","2","3","4","5","6","7","8","9","0"]
letters=list(a)
c=0
for l in letters:
for n in num:
if l == n:
c=c+1
print(c)
|
40950a23a51b2560ad1f931e3fb8f4866615edb2 | mukilvoltz/GUVi-codes | /pop.py | 107 | 3.625 | 4 | a=int(input())
for i in range (0,a):
for j in range (0,i+1):
print("*",end="")
print("\r")
|
e9b830f5a8338523efdc22c15a8677060087f696 | Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning | /Controle de fluxo/3. Condicioanais(quiz Qual e o premio).py | 1,727 | 3.78125 | 4 | # Quiz: Qual é o prêmio
# A tabela abaixo apresenta qual é o prêmio que um concorrente de uma competição ganharia com uma determinada quantidade de pontos. Escreva uma declaração
# if que permite que um concorrente saiba qual destes prêmios ganhou, com base no número de pontos marcado (no código, representada pela vari... |
83ec8968625803240349a9187a081f0fc66ee18d | Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning | /Controle de fluxo/Iterando dicionários com loops for.py | 766 | 4.375 | 4 | # Todo: Quando você iterar um dicionário usando um loop for,
# fazer do jeito normal (for n in some_dict) vai apenas dar acesso às chaves do dicionário - que é o que queremos em algumas situações.
# Em outros casos, queremos iterar as _chaves_e_valores_ do dicionário. Vamos ver como isso é feito a partir de um exemplo.... |
101b12e4915bd4c2dddc11215fa80e02633ad586 | Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning | /Operacoes.py | 1,439 | 4.09375 | 4 | carrots = 24
rabbits = 8
crs_per_rab = carrots/rabbits
rabbits = 12
print(crs_per_rab)
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area
mais_densa = (san_francisco_pop_density > rio... |
a4ac445dab9a10302d57fe822da0bfad49eabe7e | Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning | /Script/Quiz Lidando com erros.py | 2,020 | 4.125 | 4 | # Todo: Quiz Lidando com a divisão por zero
# Neste momento, executar o código abaixo causará um erro durante a segunda recorrência à função create_groups porque ela
# se depara com uma exceção ZeroDivisionError.
#
# Edite a função abaixo para lidar com esta exceção. Se ela se depara com a exceção durante a primeira li... |
67ec21d2cd1447fa2d301611bac998345aaf0e54 | danakendybayeva/WebDev2020 | /week8/informatics/5/5c.py | 239 | 3.78125 | 4 | def xor(x, y):
if (x == 1) and (y == 0):
return True
elif (x == 0) and (y == 1):
return True
else:
return False
a, b = input().split()
if xor(int(a), int(b)) == True:
print("1")
else:
print("0") |
8022d10942939c455d82c5ceb9d6f87565ae1a54 | danakendybayeva/WebDev2020 | /week8/informatics/5/5a.py | 149 | 3.765625 | 4 | import math
def min(a, b):
if a < b: return a
else: return b
a, b, c, d = input().split()
mini = min(min(a, b), min(c, d))
print(str(mini)) |
e912ff437fed6e3dda58536270f25767bf89217b | KUST-Cheng/blockchain_reputation_system | /graph/graph.py | 297 | 3.515625 | 4 | #!/usr/bin/python
#Participants = [A,B,C,D,E,F,G]
outGoingA = ['C','E']
outGoingC = ['D','A','B']
outGoingE = ['F','G','D']
honest = 'false'
# check if A is honest node
for i in outGoingA :
for j in outGoingC:
if j not in outGoingA:
honest = 'true'
print (honest)
|
f3aff00e0aed258435600025346bc2eade688f8c | alecrajeev/Bayesian-Networks | /RandomVariable.py | 289 | 3.640625 | 4 | from Domain import Domain
class RandomVariable(object):
"""
This class is used to represent a single random variable.
It will contain the name of the variable, and its domain.
"""
def __init__(self, name, domain):
self.name = name
self.domain = domain |
10bb0415a311e6b69e0b9b3982eee6b172094877 | wnsdud1302/doitpython | /정렬/shell_sort.py | 964 | 3.734375 | 4 | import random
a = list(random.randint(0,50) for i in range(0,20))
b = a.copy()
print("list a : ", a)
print("list b : ", b)
def shell_sort(list):
length = len(list)
h = int(len(list) / 2)
while h > 0 :
for i in range(int(h),length):
tmp = list[i]
j = i
while j > ... |
29101984c6d877e5378c51b99b2548da67525459 | wnsdud1302/doitpython | /main.py | 2,035 | 3.734375 | 4 |
def main1():
print("세정수의 최댓값을 구합니다.")
a = input("a : ")
b = input("b : ")
c = input("c : ")
max = a
if b > max:
max = b
elif c > max:
max = c
print('최대값은 ', max, '입니다.')
return 0
def main2():
i = 0
sum = 0
print("1부터 n까지의 숫자합을 구합니다.")
n = int(input(... |
bedc8089b31c69ba198321d399ebad95f7b60f4b | nansleeper/miptlaby2021 | /laba2/t11.py | 511 | 4.15625 | 4 | import turtle
import numpy as np
def circle(r):
for i in range(0, 360):
turtle.forward(np.pi * r / 180)
turtle.left(1)
for i in range(0, 360):
turtle.forward(np.pi * r / 180)
turtle.right(1)
#для начала работы требуется ввести желаемое количество "крыльев" у ... |
f0c37197681932ed66662da67f577689e3f0748c | nansleeper/miptlaby2021 | /laba2/t10.py | 588 | 4.28125 | 4 | import turtle
import numpy as np
def circle(r):
for i in range(0, 360):
turtle.forward(np.pi * r / 180)
turtle.left(1)
for i in range(0, 360):
turtle.forward(np.pi * r / 180)
turtle.right(1)
def flower(r, n):
for j in range(3):
circle(r)
... |
5c2175c2fa672dfb25218ab0aafb59258944d5d0 | Marcelove/Python-Tarefas-caro | /QUESTÃO 2 LISTA 3.py | 883 | 3.6875 | 4 | #QUESTÃO 2
ver = 0
senha = input('Digite a senha desejada:')
a = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split()
b = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split()
c = '0 1 2 3 4 5 6 7 8 9'.split()
d = '$ # @'.split()
for car in senha:
if car in a:
ver = 1
for ca... |
75b5f5b8da4326b00d7de5d7c613039ecd1c4d25 | Marcelove/Python-Tarefas-caro | /QUESTÃO 4 LISTA 2.py | 897 | 4.21875 | 4 | #Checando triângulos e dizendo suas propiedads
while True:
print ('Olá! Vamos ver se você consegue formar um triângulo com 3 valores de retas.')
fi = int(input('Digite o valor da primeira reta:\n'))
se = int(input('Digite o número da segunda reta:\n'))
th = int(input('Digite o número da ... |
7bd605b4d066dfd0e154155f9a694d0c96bf2a0d | geek-ninja/machine_learning-_basics | /machine_learning/ann.py | 2,009 | 3.53125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn import preprocessing
from sklearn.compose import ColumnTransformer
dataset = pd.read_csv('Dataset/Churn_Modelling.csv')
x = dataset.iloc[:,3:13].values
y = dataset.iloc[:,13 ].values
encoderx =... |
0559addaf1e916896dd0777421d5508bb6ae7292 | ermidebebe/Python | /direct convolution.py | 593 | 3.5625 | 4 | def convolution(h,x):
y=[]
sum=0
try:
for n in range(len(h)+len(x)-1):
for k in range(max(0,n-(len(x)-1)),min(n,len(h)-1)+1):
sum=sum+int(h[k])*int(x[n-k])
y.append(sum)
sum=0;
except:
print('please enter your values correctly')
... |
69d519afa488f950227a8a79e121b6293982d580 | ermidebebe/Python | /text wrap.py | 303 | 3.890625 | 4 | def wrap(string, max_width):
string2=[]
i=0
while i<=len(string):
string2.append(string[i:i+max_width])
i+=max_width
return '\n'.join(string2)
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
|
9f2e2ba82c36c9153741ff834f1f8ebd1dfa8fa3 | ermidebebe/Python | /palidrome.py | 293 | 4.0625 | 4 | number=int(input("number=:"))
count=0
sum=0
num=number
while num>0:
count=count+1
num=num//10
num=number
for i in range(count-1,-1,-1):
sum+=(num%10)*10**i
num=num//10
if sum==number:
print("the number is palindrome")
else:
print("the number is not palindrome")
|
824aaffea03ac704841b544a5611e106916b49cc | ermidebebe/Python | /students grade.py | 668 | 3.921875 | 4 | def inputing():
score=[]
print('please enter the number of subjects')
len=int(input('subjects:'))
print('please enter students score')
for i in range(len):
score.append(int(input('subject'+str(i+1)+"=")))
return score
def total():
score=inputing()
total=0;
for i in range(len(... |
dad4eb7659f670f0c00f673e495e7b95fb7e8dbb | ermidebebe/Python | /payRol.py | 265 | 4.09375 | 4 | pay_Rate=float(input("pay_rate="))
Hours_worked=int(input("total_hours_worked="))
if(Hours_worked<=40):
print("your total salar=%15.2f"%(pay_Rate*Hours_worked))
else:
print("your total salary=%15.2f"%(pay_Rate*Hours_worked+(Hours_worked-40)*pay_Rate*1.5))
|
84b325a3e1af492638eaf92945a6298b93ad57e8 | ermidebebe/Python | /american flag.py | 132 | 3.625 | 4 | for i in range(4):
print('* '*6+'='*38)
print(' *'*5+' '+'='*38)
print('* '*6+'='*38)
for i in range(6):
print('='*50)
|
c936e82665d980027092337ad8a6ff1836e46c85 | ermidebebe/Python | /Strip comments.py | 846 | 3.6875 | 4 | def solution(string,markers):
strip=''
valid=True
for i in range(len(string.split('\n'))):
for j in range(len(markers)):
if string.split('\n')[i].find(markers[j])!=-1:
text=string.split('\n')[i].replace(markers[j],'er')
if i==0:
strip+... |
93bdedec31041219ea055de8b76fe2dfac4151c0 | ermidebebe/Python | /Random number writer.py | 268 | 3.671875 | 4 | import random
def main():
print('please enter of random numbers you want to be written')
n=int(input('N:='))
file=open('random.txt','a')
for i in range(n):
file.write(str(random.randrange(1,500))+'\n')
file.close()
main()
|
b3462a5e73c0851fd5d47ab85c733cb62b443abe | ermidebebe/Python | /BlackJack.py | 2,499 | 3.75 | 4 | import random
class Card:
__name=""
__number=0
__value=0
def __init__(self,name,number,value):
self.__name=name
self.__number=number
self.__value=value
def __init__(self):
pass
def setName(self,name):
self.__name=name
def setNumber(self,number):
... |
cc6b56b8c951d7aab983940c8f766ed6d24e0359 | ermidebebe/Python | /largest odd.py | 725 | 4.28125 | 4 | x=int(input("X="))
y=int(input("y="))
z=int(input("z="))
if(x%2!=0):
print("x is Odd")
if(y%2!=0):
print("y is Odd")
if(z%2!=0):
print("z is Odd")
if(x%2!=0 and y%2!=0 and z%2!=0 ):
if(x>y and x>z):
print("x is the greatest of all")
elif(y>x and y>z):
print("y is the greatest")
else :
... |
b22b58875a37b650318f6d80334178ae6904e7b5 | sunithasu/sunitha | /vowel&constant.py | 196 | 4.03125 | 4 | ch=input ("enter your character:")
if(ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' or ch=='A' or ch=='E' or ch=='I' OR ch=='O' or ch=='U')
print(ch,"is vowel")
else
print(ch,"is constant")
|
099335e50f8a9ca84439b05749e95719e5203532 | sunithasu/sunitha | /natural.py | 165 | 3.859375 | 4 | int i, num, sum = 0;
print("Enter an integer number \n");
for (i = 1; i <= num; i++)
{
sum = sum + i;
}
print("Sum of first %d natural numbers = %d\n", num, sum);
}
|
55381fc8e485d46a94699e5b441c3e02350ffd77 | tsaomao/BankOCRKataWithPythonAndNose | /ocr.py | 6,911 | 3.65625 | 4 | from more_itertools import chunked
"""Module to implement Bank OCR Kata. See README.md for more information.
Bank OCR kata implements a thing that reads and validates example OCR numbers."""
class OcrNumeral:
"""OcrNumeral tracks each digit in an OCR application."""
asciiValue = ""
numeralValue = -1
alternate... |
cfcf85b40806e49c8cfaf1a51b78b1aa5c96ca18 | bislara/MOS-Simulator | /Initial work/input_type.py | 728 | 4.25 | 4 | name = raw_input("What's your name? ")
print("Nice to meet you " + name + "!")
age = raw_input("Your age? ")
print("So, you are already " + str(age) + " years old, " + name + "!")
#The input of the user will be interpreted. If the user e.g. puts in an integer value, the input function returns this integer value. If th... |
36906e07dd7a95969fcfbfb24bc566af77d6c290 | w0nko/hello_world | /parameters_and_arguments.py | 301 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 18:20:48 2017
@author: wonko
"""
def power(base, exponent): # Add your parameters here!
result = base ** exponent
print ("%d to the power of %d is %d.") % (base, exponent, result)
power(37, 4) # Add your arguments here! |
83440e5e1344edd80cbedeae36267cbe2b640b92 | ecaterinacatargiu/AI | /Lab3-4/Swarm.py | 1,371 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 16:11:41 2020
@author: Cati
"""
from random import randint
from Patrticle import Particle
class Swarm:
def __init__(self, sizeParticle, sizeSwarm):
self.sizeSwarm = sizeSwarm #n will be the size of the swarm, the size of the population of particles
... |
1a9d22a733e0f710f8b3460ea15c37ca5b3e58be | ecaterinacatargiu/AI | /Lab2/Lab2Bun/ui.py | 1,532 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 12:11:51 2020
@author: Cati
"""
from state import State
from problem import Problem
from controller import Controller
class UI:
def __init__(self, controller: Controller):
self.controller = controller
def printMenu(self):
... |
a9b9f217008ce163b7ad16d82551d94778241c01 | lazidge/maps_test | /db.py | 1,724 | 3.796875 | 4 | import sqlite3
from store import Node
def create_db(name):
"""
Function that tries to create a database with a given name
"""
conn = sqlite3.connect(name + '.db')
cursor = conn.cursor()
try:
cursor.execute('''CREATE TABLE ''' + name + \
'''(id int, lat decimal, long decimal, nei... |
eae7be03bf15e59f1afa4dc7671b2e69c0dc84dd | xFingerlinKx/Phonebook_test | /PhoneBook.py | 4,288 | 3.53125 | 4 | import pickle
from password import password_func
'''Phonebook'''
'''before use of 'phone.dat' file requared to fill and pickle
object(dictionary - keys(names) : values(phonenumbers)) by 'data.py' file'''
def title():
'''Функция выводит заголовок'''
print('''
#################################################... |
371abb24718e289a13958d4e0512a9dac790f6a7 | VeenaNalluri/Course_Scheduler | /Scheduler.py | 12,947 | 3.75 | 4 | import course_dictionary
import copy
import time
import pprint
from collections import namedtuple
#Main Function
#def course_scheduler(Dict, goalCourses, initialCourses)
def course_scheduler(Dict, goalCourses, initialCourses) :
#Dict: Dictionary storing course information
goalCourses = Goal
init... |
0f5303db94235b52d9edb4cd481ca7d6721967cc | dhince/dsa_using_python | /collision handling.py | 2,038 | 3.921875 | 4 | from doubly_linkedList import *
class HashTable:
def __init__(self):
#self.main_bus = LinkedList()
self.main_bus_head = None
def get_hash(self, key):
hash = 0
for element in key:
hash += ord(element)
return hash
def __setitem__(self, key, value):
... |
da26f1701f96a59d5277bc238d71f80ba2bedfcc | dhince/dsa_using_python | /multi_threading.py | 674 | 3.953125 | 4 | from time import sleep
from threading import Thread
class Hello(Thread):
def run(self): #You always need to use name of function as run cz it is built-in
for _ in range(5):
print('Hello')
sleep(1)
class Hi(Thread):
def run(self):
for _ in range(5):
pri... |
b0d375ffb427b4d00df991ce261a98afdd889a30 | btrekkie/WrapAsYouType | /util.py | 1,627 | 3.59375 | 4 | import numbers
import re
import sublime
class Util(object):
"""Provides static utility methods."""
# Equivalent value is contractual
_WHITESPACE_REGEX = re.compile(r'\s*')
@staticmethod
def is_string(obj):
"""Return whether "obj" is a string.
In Python 2, instances of str and u... |
bb21d460a800def3b50708218376ed4638a0a841 | chenqunfeng/python | /demo1_最简单抓包.py | 796 | 4.21875 | 4 | # 关与urllib和urllib2之间的区别
# http://www.hacksparrow.com/python-difference-between-urllib-and-urllib2.html
# 在pythob3.x中urllib2被改为urllib.request
import urllib.request
# urlopen(url, data, timeout)
# @param {string} url 操作的url
# @param {any} data 访问url时要传送的数据
# @param {number} timeout 超时时间
response = urllib.re... |
450e35b353de696beefcdd73936cc2344066dca1 | iamharshitc/login-page- | /login_form.py | 768 | 3.609375 | 4 | from tkinter import *
from tkinter import messagebox as ms
import os
root=Tk()
def submit():
ms.showinfo("Submit","Welcome")
def cancel():
ms.showinfo("Cancel","Bye Bye!!!")
root.destroy()
os.system("py login_form.py")
lb=Label(root,text="Login")
lb.grid(row=0,column=0,columnspan=2)
l=Label(root,text... |
605da9d34445172663414ba2de5654986bd1955f | aks861999/Steganography_With_PyPy_Akash | /Extract.py | 1,641 | 3.71875 | 4 | import cv2
import numpy as np
import random
def decrypt():
# Read the encrypted image generated by hiding the QR code in the image #
img = cv2.imread('output.png')
width = img.shape[0]
height = img.shape[1]
# img1 is a blank image #
img1 = np.zeros((width, height, 3), np.uint8)
... |
c7d48accad41991d63feb27bdbe67e6d1def2250 | bethanymbaker/arch | /leetcode/car_pooling.py | 667 | 3.625 | 4 | from typing import List
from collections import defaultdict
def carPooling(trips: List[List[int]], capacity: int) -> bool:
trips = sorted(trips, key=lambda l: int(str(l[1]) + str(l[2])))
d = defaultdict(int)
for trip in trips:
num_passengers = trip[0]
start = trip[1]
end = trip[2]
... |
362efdf1c427676758bc9cdb59497f567081861c | bethanymbaker/arch | /daily_interview_pro/unival_tree.py | 356 | 3.75 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_unival_subtrees(root):
pass
a = Node(0)
a.left = Node(1)
a.right = Node(0)
a.right.left = Node(1)
a.right.right = Node(0)
a.right.left.left = Node(1)
a.right.left.right = Node(1)
... |
b24b9be7c8f47ca1055b8adb9e9613eab3f3e80e | bethanymbaker/arch | /scripts/anagrams.py | 476 | 3.65625 | 4 | import re
def is_match(str1, str2, schars=[]):
if len(schars) > 0:
pattern = f"[{''.join(schars)}]"
str1 = re.sub(pattern, '', str1)
str2 = re.sub(pattern, '', str2)
if len(str1) != len(str2):
return False
l1 = sorted(list(str1))
l2 = sorted(list(str2))
return ''.jo... |
54b9afc58df1aa2d3e86e1e7e6973f42b0a356a3 | bethanymbaker/arch | /scripts/minesweeper.py | 959 | 3.875 | 4 | #!/usr/bin/env python3
import numpy as np
import sys
class Board:
def __init__(self, n_rows=10, n_cols=10, n_mines=10):
self.num_rows = n_rows
self.num_cols = n_cols
self.num_mines = n_mines
self.size = n_rows * n_cols
self.board = np.zeros(self.size)
self.board[n... |
84a7925e7222ea797298a363fef0eb9bf9aefb45 | bethanymbaker/arch | /daily_interview_pro/first_and_last_indices.py | 578 | 3.625 | 4 | import numpy as np
def find_indices(arr, target):
first_index = np.inf
last_index = -np.inf
found = False
for idx, val in enumerate(arr):
if val == target:
found = True
first_index = np.min([first_index, idx])
last_index = np.max([last_index, idx])
if ... |
53aec4bbd39e3889c5878bdbe38a9e0b95d4e485 | xxxxxmanlyh/format | /price.py | 1,743 | 3.609375 | 4 | import time
datetime = time.strftime('%Y年%m月%d日',time.localtime(time.time()))
print("名字:")
name = input()
print("动态钱包美元:")
missUSD = input()
print("静态钱包美元:")
rewardUSD = input()
print("扣除推荐奖:")
losttuijian = input()
print("获得推荐奖")
gettuijian= input()
rewardRMB = float(rewardUSD) * 6.8
allUSD = float(missUSD) + float(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.