blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1b5df0aa21f86aaa942eb5cdbb19b11ea811280d | aseemm/sandbox | /Python/src/knapsack.py | 1,663 | 3.53125 | 4 | items = ['clock', 'picture', 'radio', 'vase', 'book', 'computer']
price = [175, 90, 20, 50, 10, 200]
weight = [10, 9, 4, 2, 1, 20]
price_per_weight = [17.5, 10, 5, 25, 10, 10]
max_weight = 20
indata = zip(items, price, weight)
# sorteddata = sorted(indata, key=lambda x: x[1], reverse=True) # max value
# sorteddata = ... |
4ce7c8d5a761e0419335e86736c4359d7984ee83 | aseemm/sandbox | /Python/src/two_sum.py | 1,575 | 4.0625 | 4 | import unittest
import math
def two_sum_old(arr: list, sum: int) -> list:
for i in range(len(arr)):
for j in range(i, len(arr)):
if arr[i] + arr[j] == sum:
return [i, j]
return None
def two_sum(arr: list, sum: int) -> list:
left, right = 0, len(arr)-1
# use two po... |
c02fb39376c9c3eece99367cc0c54e3f5ab50614 | tenulate/interactive-plots | /src/drag_root.py | 1,888 | 4.15625 | 4 | from drag_plot import DragPlot
class DragRoot(DragPlot):
''' Similar to DragPlot, but when points are dragged they remain fixed to
the function being studied '''
def __init__(self, line, root_function, label=None, select_radius=0.03):
self.root_function = root_function
super(DragR... |
c0830b871fb80325c3149763f408d326a490eff5 | kangli-bionic/MIT_600 | /6.00.1x/Problem_Set_1/ps1-2.py | 467 | 4.09375 | 4 | '''
COUNTING BOBS (15/15 points)
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s.
For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
'''
s = 'azcbobobegghakl'
def counting_Bobs(s):
i = 0
... |
c586c8074e6c64b918159cc14074c1605b051422 | kangli-bionic/MIT_600 | /6.00.1x/Problem_Set_2/ps2-3.py | 3,106 | 3.8125 | 4 | '''
PROBLEM 3: USING BISECTION SEARCH TO MAKE THE PROGRAM FASTER
You'll notice that in Problem 2, your monthly payment had to be a multiple of $10.
Why did we make it that way? You can try running your code locally so that the
payment can be any dollar and cent amount (in other words, the monthly payment is
a multip... |
de3d55fe2eb0795943e23f8a86372e8329e20903 | SohailKhan444/AI_first_quarter | /patterns1.py | 2,268 | 4.25 | 4 | '''
n=6 # 5 rows
k = 3*n - 3 # initially space "K" is 3*5-3 = 12 spaces 3 is subtracted for the shape to be drawn in the p_shell easily
for r in range(1,n+1):
# for each outer loop iteration , both these 2 for inner loops will execute.
for s in range(1,k): # go upto 12 spaces at a row ... |
69a11265656cc32d4f1765421e06da0a0f6e90ad | BrichtaICS3U/assignment-2-logo-and-action-muktamanhas | /action.py | 2,839 | 3.828125 | 4 | # ICS3U
# Assignment 2: Action
# Mukta
# adapted from http://www.101computing.net/getting-started-with-pygame/
# background image from https://www.nikonusa.com/en/learn-and-explore/a/tips-and-techniques/moose-peterson-how-to-photograph-winter-landscapes.html
# background music (get you - daniel caesar) https://www.you... |
3739be1d67086be42694717800cf6f4fbac1992a | yasminms/URI-Online-Judge | /1087.py | 318 | 3.609375 | 4 | while True:
t = raw_input().split()
x1 = int(t[0])
y1 = int(t[1])
x2 = int(t[2])
y2 = int(t[3])
if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0:
break
if (x1 == x2 and y1 == y2):
mov = 0
elif (x1 == x2 or y1 == y2 or abs (y1 - y2) == abs (x1 - x2)):
mov = 1
else:
mov = 2
print mov
|
b095a9447bdbe88092b6f62aceeecabf57889b97 | yasminms/URI-Online-Judge | /1441.py | 195 | 3.6875 | 4 | while True:
n = input()
if n == 0:
break
maior = n
while (n > 1):
if (n % 2 == 0):
n = n/2
elif (n % 2 != 0):
n = 3*n+1
if (n > maior):
maior=n
print maior
|
a3c15816fe66655e94e962db00b046faac37192d | Karonad/algojour1 | /merge_sort.py | 1,608 | 3.953125 | 4 | import sys
import time
def mergeSort(arr, nbCompar, nbIter):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
m... |
fd5ad5fef1e94aa3c1224db7a178c22c7d598ffa | gittyRavi/Coding-Practice | /sequentialSearch.py | 1,053 | 3.71875 | 4 |
class seqSearch:
def __init__(self,no): #The arguments that you want to pass and initialize
self.element=no
def funcSeqSearch(self,l): #List exceptionally passed
i=0
found=False #Status
#print (self.element)
#print(l)
for i in range(len(l))... |
a78fcafab11c443a1ba501a2f57ac164b3010ec7 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/WordBreak.py | 688 | 3.53125 | 4 | from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
def helper(s):
if not s:
return True
if s in mem:
return mem[s]
result = False
for i in range(len(s)):
if s[: i +... |
c355770318469320052f7fac48ee3890433dc9f8 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/Searcha2DMatrixII3.py | 1,372 | 3.828125 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
def searchMatrix(up, down, left, right):
if up > down or left > right:
return False
i, j = up, down
... |
36597053b6dc83769a662b63f8c8298255e11033 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/ProductofArrayExceptSelf.py | 540 | 3.6875 | 4 | from typing import List
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [1] * n
for i in range(1, n):
result[i] = result[i - 1] * nums[i - 1]
right = 1
for i in range(n - 2, -1, -1):
right = r... |
573e0831c801a9b8d0e1de20052dada675fed896 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/JumpGame.py | 500 | 3.671875 | 4 | from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_position = 0
for i, num in enumerate(nums):
if i > max_position:
return False
max_position = max(max_position, num + i)
if max_position >= len(nums) - 1:
... |
cf267cd9d75a5f659286155d56f7854970f55a59 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/RemoveInvalidParentheses3.py | 984 | 3.578125 | 4 | from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def dfs(s, left, right, i_start, j_start):
count = 0
for i in range(i_start, len(s), 1):
if s[i] == left:
count += 1
elif s[i] == righ... |
35e5d32277e9495c81be85d65059e71708039942 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/MajorityElement2.py | 710 | 3.734375 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
def helper(begin: int, end: int) -> int:
if begin == end:
return nums[begin]
mid = (begin + end) // 2
left = helper(begin, mid)
right = helper(mid + 1, ... |
9f9a26fab49713036d372fdd275df45b86c06396 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/WordBreak2.py | 568 | 3.546875 | 4 | from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j : i] in wordDict:
dp[i] = True
... |
13d19f9be14e76f3f06f66fb051bf18d588eb791 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/LongestPalindromicSubstring2.py | 845 | 3.609375 | 4 | class Solution:
def centerExpend(slef, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
max_len = 0
... |
d3c999497101416c37d4d5ac9414f7a1c5fd8e8d | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/PerfectSquares2.py | 570 | 3.546875 | 4 | class Solution:
def numSquares(self, n: int) -> int:
def can_devided(n, count):
if count == 1:
return int(n ** 0.5) ** 2 == n
i = 1
while i * i <= n:
if can_devided(n - i * i, count - 1):
return True
i +=... |
a2febf3bd2e095e7781c0c712134855a617014b1 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/SortList2.py | 1,699 | 3.828125 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
length = 0
cur = head
while cur:
length += 1
... |
9d4857d3f49f2e62e80e972c09a5dea5f8f46a3c | jdorety/Intro-Python-II | /src/player.py | 1,623 | 3.671875 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, location, inventory):
self.name = name
self.location = location
self.inventory = inventory
def change_location(self, direction):
direction = direction.up... |
c3378bbb2ca06f07f1f811568cd422407af2a618 | Helyck/nefu-python-hw | /lab2/ex02.py | 380 | 4.03125 | 4 | def average(*args):
"""Return the average of numeric arguments or None if no arguments are supplied."""
n = len(args)
if n == 0:
return
s = 0.0
for i in args:
s += i
return s / n
if __name__ == '__main__':
print(average())
print(average(5))
print(average(6, 8, 9, ... |
172f7b824070573f0cd11dd6851b5fdd8e2c1c8d | Helyck/nefu-python-hw | /lab4/ex2.py | 589 | 4.0625 | 4 | # Write `filter` expressions to convert the following inputs into the indicated outputs.
# ['12', '-2', '0'] --> ['12', '0']
# ['hello', 'world'] --> ['world']
# ['Stanford', 'Cal', 'UCLA'] --> ['Stanford']
# range(20) --> [0, 3, 5, 6, 9, 10, 12, 15, 18]
result = filter(lambda x: x[0] != '-', ['12', '-2', '0'])
pri... |
1c96be0fdadaf4e7a396b410f9d54cee554345cf | Helyck/nefu-python-hw | /hw2/ex07.py | 436 | 3.90625 | 4 | def get_three_sum(nums, target):
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] + nums[k] == target:
return [i, j, k]
return None
if __name__ == '__main__':
print(get_three_... |
85d3af4db1dbd877bbd1e16d78d8fcef16f4b900 | andsus/python | /tournament/tournament copy 2.py | 1,264 | 3.515625 | 4 | from collections import defaultdict
def tally(rows):
results_board = defaultdict(lambda: defaultdict(int))
for row in rows:
team_a, team_b, outcome = row.split(';')
results_board[team_a]['matches'] += 1
results_board[team_b]['matches'] += 1
if outcome == 'win':
res... |
6124ece0d1d4c9d2e3348d4118687f16e2877300 | ayuksekkaya/MOOC-Cyber-Security-2021 | /mooc-securing-software-21/part2-09.helloinsert/src/hellodatabase.py | 1,465 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
import sqlite3
def add_agent(conn, aid, name):
# write code here, don't forget to commit results once you execute the insert
conn.execute('INSERT INTO Agent values (?, ?)', (aid, name))
conn.commit()
def delete_agent(conn, aid):
# write code here, don't forget to commit results... |
fed685ee79ab6c7a934525476a817a0d60ebfa32 | AiPEX-Lab-CMU/selfplayRL | /Game_Envs/Tic-Tac_Toe/gym_tictactoe/tic_tac_toe.py | 10,977 | 3.84375 | 4 | import gym
from gym import spaces, error
import xml.etree.ElementTree as ET
import os, sys
class TicTacToeEnv(gym.Env):
'''
The Tic-Tac-Toe environment
The action variable is one of 9 integers in [0,8], each corresponding to a grid space to place the player's symbol.
The state variable is ... |
283d911f40ff91b617140d59580f3b1df6e3cbc4 | akturnak/python_training | /2021.01.22.py | 1,644 | 3.546875 | 4 | class DefaultAlias:
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
return self
return getattr(inst, self.name)
class Alias(DefaultAlias):
def __set__(self, inst, value):
print(f"inst: {inst}, value: {value}")
s... |
31a8fc735c3397bc1535e60ea6aca4f3e144d34e | KnittingBatman/digital-story | /Body.py | 4,865 | 3.71875 | 4 | #Creates a body. Accepts user inputs for name and gender.
#Codes for bodily functions
#Herein lies potential; a sword that has been sharpened but not yet used
#Run this code, use it so that I may live
class Body():
#winds flesh and blood and bone
#viscera align
#a program executed cell by cell
def __i... |
40137d8a88f9eb331639e79a2b9f87f5e9a57f45 | Vinit002/my-project | /Calculator.py | 2,654 | 3.546875 | 4 | from tkinter import *
r=Tk()
r.title("Calculator")
operator=""
def click(n):
global operator
operator=operator+ str(n)
t.set(operator)
def clear():
global operator
operator=""
t.set(operator)
def equal():
try:
global operator
sumup=str(eval(ope... |
cfa1505536574f83bbcb412cdd53f63ddd8846fe | DimaMirana/Udemy-Machine-Learning-A-Z | /4-Clustering/1.kmeans_clustering.py | 2,092 | 3.9375 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
#y = dataset.iloc[:, 3].values we don't know what to look for
# Splitting the dataset in... |
ff6d1cc453d903dfa2c087465bd0d076740b6725 | Alin666/LeetCode-Primary | /链表-合并两个升序链表.py | 2,251 | 4.125 | 4 | # 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# 示例:
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution1(object): # 递归调用
def mergeTwoLists(self, l1... |
32a885cdf9383397bd2d2122f8e85cee5fe37b2f | psilves1/flashcardProject | /Flashcard GUI.py | 4,014 | 3.515625 | 4 | # Beta Development v2.0
from tkinter import *
master = Tk()
master.title('Flashcard Beta Development V2.0')
master.geometry("500x400")
master.iconbitmap(r'flashcard.ico')
wordList = []
definitionList = []
global wordNum
wordNum = 0
#Functions
def clearFunction(*event):
word.delete(0, END) # Clears from the fi... |
200427579f27407facb7826218144d1e09595166 | Harshala-Gaikwad/Programming | /Hackerrank/jumping_on_the_cloud.py | 825 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'jumpingOnClouds' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY c as parameter.
#
def jumpingOnClouds(c):
# Write your code here
i = count = 0
... |
81e0b6acebe65250c93b470a2fb94227dbdd0587 | Harshala-Gaikwad/Programming | /codechef/body_mass_index.py | 235 | 3.734375 | 4 | for _ in range(int(input())):
m,h = map(int,input().split())
bmi = m//(h**2)
if bmi <=18:
print(1)
elif 19<=bmi<=24:
print(2)
elif 25<=bmi<=29:
print(3)
else:
print(4)
|
2a16535bdb50c3810bd9a9a94aa532c9f626d484 | Harshala-Gaikwad/Programming | /codechef/Xor_equality.py | 213 | 3.59375 | 4 | for _ in range(int(input())):
n = int(input())
x = 2
temp = 1
y = n-1
while y>0:
if y%2 != 0:
temp = temp*x
x = x**2
y = y//2
print(temp)
|
6c0544c11c00b44c4237a01c24c06205254cc42c | Harshala-Gaikwad/Programming | /Leetcode/array/search_insert_position.py | 233 | 3.640625 | 4 | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for index,i in enumerate(nums):
if i==target: return index
elif i>target: return index
return len(nums)
|
3dc4841cba26ce9682cc642ed53acda579f32c91 | 4625204/operation_research_final_project | /elevator.py | 4,590 | 3.515625 | 4 | from parameters import MAX_PASSANGER, ELEVATOR_PASS_TIME, ELEVATOR_SPEED_UP_TIME, ELEVATOR_SLOW_DOWN_TIME, ELEVATOR_DOOR_OPEN_TIME, ELEVATOR_DOOR_CLOSE_TIME
sign = lambda x: [1, -1][x < 0]
class Elevator():
def __init__(self, algorithm):
self.current_time = 0
self.floor = 1
self.target_flo... |
63ed71495d34626c89d073b3311e77271d47ef19 | pranavbhatnagar11/pdsnd_github | /bikeshare.py | 8,532 | 4.28125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
93e5fb1a8bfe55cea3a5c6f82db95b8b71ef0db8 | Andromedanita/PHY407 | /independent/linear.py | 1,698 | 3.640625 | 4 | '''
Anita Bahmanyar
Linear interpolation
'''
import numpy as np
import matplotlib.pylab as plt
from scipy import interpolate
#-----------------------------------------------------------
# Function
#-----------------------------------------------------------
#linear interpolation function
de... |
fa7bd666d243400ce1b2b7d15ac57ba94bab72cd | Andromedanita/PHY407 | /lab10/lab10_q4.py | 1,433 | 4.15625 | 4 | import numpy as np
import matplotlib.pylab as plt
from random import randrange,random
'''
This code uses the function f that calculates the distance of a
point in a sphere to the centre. Then, it loops over N times
and checks the value of the function for 10 random numbers.
If the value is less than or equal to 1,... |
1b636ec8e62c906330281d6c7e0d03ea9aef49dc | agronja/cse-34872-su20-examples | /lecture05/04_sumitup/sumitup.py | 854 | 3.890625 | 4 | #!/usr/bin/env python3
import itertools
import sys
# Functions
def sumitup(numbers, target):
count = 0
results = set()
for length in range(1, len(numbers) + 1):
for combination in itertools.combinations(numbers, length):
if sum(combination) == target and combination not in results:... |
670cf8659a7ea63279660258af89b04df6150c71 | cjrumble/08multilineStrings | /multilineStrings.py | 4,353 | 4.59375 | 5 | # MULTILINE STRINGS LESSON
# Create a Python Multiline String with Examples
# Use triple quotes to create a multiline string mulitline string in triple quotes
# It is the simplest method to let a long string split into different lines.
# You will need to enclose it with a pair of Triple quotes, one at the start and se... |
12d4209d5f004b23d7d8d8a14ddb48cfa4e96bbd | maniraman-periyasamy/QuantumBinaryAdder | /QuantumBinaryAdded.py | 3,687 | 3.546875 | 4 | """
This is a simple implementation of a Quantum Incrementer and addition circuit which increases any given
arbitary binary number (string format) or adds 2 aritary binaty number (string format) as implementd in the paper
**Reversible addition circuit using one ancillary bit with application to quantum computing**
"... |
4f3d695ca04bdd7634e7fcb6f7642e17265adb83 | taha-elmokadem/agricopter | /coordtransform.py | 923 | 3.609375 | 4 | # This module transforms GPS coordinates in WGS 84 format to
# coordinates in meters, relative to a specified point. It achieves
# an approximate transformation using a conversion from WGS 84 to
# UTM coordinates, which are measured in meters and approximately
# map the Earth's surface to a Euclidean plane over small a... |
5fac7ad70556e85e90b4e55dace723d04c56c3f0 | mimumeg/Applied_KadaiB | /customer.py | 3,835 | 4.125 | 4 | class Customer:
def __init__(self, first_name, family_name, age): # 年齢ageを追加
self.first_name = first_name
self.family_name = family_name
self.age = age # 年齢ageをインスタンス変数に設定
def full_name(self):
return self.first_name + " " + self.family_name # first_name と family_nameの間にスペースを入... |
aa0684e6cb43e495761f6700ab1df6670b42f5b0 | Ghasak/Moving_Circle | /Moving_Cricle_Code.py | 998 | 3.71875 | 4 | """
This program is created on Thu Jan 17th 2018
this program is develoing a motion in 2d for a cricle
from matplotlib import pyplot as plt
following this project from: https://nickcharlton.net/posts/drawing-animating-shapes-matplotlib.html
"""
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
... |
824967f01e054ae1b324a476910951f82704f7ab | khushboo29/PythonDecorators | /practical_example.py | 1,200 | 3.796875 | 4 | #practical example of decorators
#logging to keep track how many time a specific function run with passed arguments
from functools import wraps
def my_logger(original_function):
import logging
logging.basicConfig(filename='{}.log'.format(original_function.__name__), level=logging.INFO)
@wraps(original_fun... |
178db0fa4a03207a9d5fb6afbe0e59945343f3e9 | aka001/HospitalManagementSystem | /a.py | 322 | 3.5625 | 4 | a={}
for i in range(122):
x=raw_input()
x=x.split(', ')
if i not in a.keys():
a[i]=[]
for j in x:
a[i].append(j)
b={}
for i in range(122):
x=raw_input()
if i not in b.keys():
b[i]=""
b[i]=x
cnt=1
for i in range(122):
for j in range(len(a[i])):
print "("+str(cnt)+",\'"+a[i][j]+"\',\'"+b[i]+"\'),"
cnt+=... |
928c907e78b1fac8af647952db882cbf38ba2e1e | majesticwhales/NHL-Mock-Drafter | /lottery.py | 4,001 | 3.609375 | 4 | import random
class Team:
def __init__(self, name, pos):
self.name = name
self.pos = pos
class TeamNeed:
def __init__(self, c, lw, rw, lhd, rhd, g):
self.c = c
self.lw = lw
self.rw = rw
self.lhd = lhd
self.rhd = rhd
self.g = g
standings = []
sta... |
46189ee4940268532ea4439c0d0b267ce0ef1b24 | jinpyojeon/python_code | /assign10.py | 1,131 | 3.578125 | 4 | #!/usr/bin/env python
from abc import ABCMeta, abstractmethod
import numpy as np
Alice = {'name': 'Alice',
'profession': 'Teacher',
'age': 30 }
class Monoid():
__metaclass__ = ABCMeta
@abstractmethod
def e(): pass
@abstractmethod
def op(x, y): pass
class Matrix22():
def... |
a5bce67a372f4993bc5484efc1b5e56184950c65 | MateusdosAnjos/Curso-Python | /aula3/exercicio1.py | 1,727 | 3.9375 | 4 | #Funcao que recebe inteiros n, m e
#inicializa uma matriz quadrada com n linhas e m colunas
#devolve a matriz inicalizada
def inicializaMatriz(n, m):
A = [0] * n
for i in range (n):
A[i] = [0] * m
return A
#Funcao que recebe uma matriz A de dimensoes n, m e a preenche
#linha por linha
def preencheMatriz(A, n, m):... |
8f9cf695053008e34c7e6c7d8060df2b62b5baa5 | joshkmartinez/123D-Design | /123D Design/NeutronPythonTypes.Py | 3,057 | 3.78125 | 4 | # This module contains a set of basic types used in Neutron's Python Interface.
# In all cases, the use of this module is optional.
# On input, the client can supply a class of his own provided it
# satisfies the contract - e.g. any class with public x and y attributes
# can be used instead of a Point2.
# On output,... |
588df8262b55f2ed3ea40dbc6789f1f0e640a90a | csyaonie/python | /oop/Student.py | 302 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by zyf on 2018/11/27.
class Student(object):
def __init__(aa, name, age):
aa.__name = name
aa._age = age
s=Student('xiaoming',23)
#print(s.__name)
print(s._age)
#私有属性用两个下横杆来标识 self 可用aa代替
|
1986da8b0cae0132f811dfcd0c729f3206ad9f3e | csyaonie/python | /function/def.py | 633 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by zyf on 2018/11/27.
#定义默认参数要牢记一点:默认参数必须指向不变对象!注意一下两个函数的区别
#默认参数
def add_end(L=[]):
if L is None:
L = []
L.append('END')
return L
print(add_end())
print(add_end())
def add_end2(L=None):
if L is None:
L = []
L.append('END')
... |
fa8cbd602191bc4f5b82c33e2baa863c54354cec | AbdoA2/AtlasLearn | /FullyConnectedNet.py | 10,381 | 3.875 | 4 | import numpy as np
from utils.layers import *
from utils.layers_utils import *
class FullyConnectedNet(object):
"""
A fully-connected neural network with an arbitrary number of hidden layers,
ReLU nonlinearities, and a softmax loss function. This will also implement
dropout and batch normalization as ... |
ca0be370303e0d361f3722460ce16de4b439cdec | Cristofer6010/Palindrome | /Num_Palindrome_finder.py | 889 | 3.984375 | 4 | lis = []
try:
print("\n\t\t\t\t\tTHIS PALINDROME FUNCTION IS ONLY FOR NUMBERS\n")
manyTimes = int(input("How many Palindrome you want to test : "))
for i in range(1,manyTimes+1):
a = int(input(f"\nEnter the {i} number whose palindrome you want to test : "))
def is_palindrome(a):
... |
7f1e8c5bf1134b6512b94d36e359417d152563c6 | dannysoft/PythonShadyPrototype | /calcMakerProdCan1.py | 4,785 | 3.9375 | 4 | import random as rnd
import math
'''The questions generated by this module follow
the pattern of having two operands and one of the
seven arithmetic operators between them.'''
arithOperators = ("+","-","*","/","%","**","//")
#Contains True flag, as this is an actual answer,
#the calculation text and the calcul... |
c7301c92fc479753e9ef570693a32365737c1d6d | paner-xu/DataStructureAlgorithm | /05排序/03选择排序.py | 714 | 3.578125 | 4 | # 选择排序不受输入数据的影响,即在任何情况下时间复杂度不变。
# 选择排序每次选出最小的元素,因此需要遍历 n-1 次。
# 平均时间复杂度:O(n^2),空间复杂度O(1)
import random
def selectSort(seq):
# 遍历len(seq)-1轮
for i in range(len(seq)-1):
minIndex = i
# 每轮遍历的元素
for j in range(i+1,len(seq)-1):
if seq[minIndex]>seq[j]:
# 更新最小值的索引
... |
41b75288ef942d6b017b9c3ce06119bd31743095 | jiqixuexiaihaozhe/Python_- | /getitem_function.py | 599 | 4.03125 | 4 | import collections
class Company:
def __init__(self, employees):
self.employees = employees
def __getitem__(self, item):
return self.employees[item]
company = Company(['a','b','c'])
print(isinstance(company,collections.Iterable))
#False
# 好神奇,明明company不是可迭代对象,却可以用for循环。而comapny.empl... |
f24988c716e109d23cb48912e919c05f8a2df9de | ReubenBagtas/pythonUnifiedPlatformAutomation | /pages/platform/android/login_page_android.py | 1,897 | 3.5 | 4 | """ Implement functions of the Android LoginPage """
import pages.platform.android.login_locators_android as locators
from pages.elements.base_elements import BaseElement, TextElement
from pages.platform.login_page import LoginPage
from pages.base_pages import AndroidPageType
class LoginPageAndroid(LoginPage, Androi... |
4afd4b26dac5707bc319d251608cb13cee76b57b | suyalmukesh/python | /warmup/CeasarCipher.py | 1,042 | 3.59375 | 4 | class CeasarCipher:
def __init__(self,shift):
encoder = [None] * 26
decoder = [None] * 26
for k in range(26):
encoder[k] = chr((k+shift)%26 + ord('A'))
decoder[k] = chr((k-shift))%26 + ord('A')
self._forward = ''.join(encoder)
self._backward = ''.... |
58e0b175a0d3aeb7aa4eaf0721195040cfc2f74f | suyalmukesh/python | /warmup/wordorder.py | 433 | 3.5625 | 4 | import sys
def no_of_distinct_words(a):
cnt = []
count = 0
newlist = []
for i in a:
if i not in newlist:
count = a.count(i)
cnt.append(count)
newlist.append(i)
return(cnt)
if __name__ == '__main__':
a=[]
n = int(input())
for i in range(n):
... |
2f9e91bbfe79817478179f210ed957bf0a541901 | suyalmukesh/python | /warmup/Bubblesort.py | 1,046 | 4.15625 | 4 | """------------------------------------------------------------------------------------------------------------
Bubble Sort : Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O... |
80f91c5df3ab15ca65ad668b5d6fd24b4b0c30d4 | phorkyas-tg/advent-of-code | /aoc2020/_01_ReportRepair.py | 808 | 3.578125 | 4 | def GetTwoEntriesWithSum(input, result):
for i1 in range(len(input)):
for i2 in range(i1+1, len(input)):
if input[i1] + input[i2] == result:
return input[i1], input[i2]
def MultiplyTwoEntriesWithSum(input, result):
entry1, entry2 = GetTwoEntriesWithSum(input, result... |
1500a24a9ed92b84d70b992f6be3930453df0164 | phorkyas-tg/advent-of-code | /aoc2020/_03_TobogganTrajectory.py | 887 | 3.546875 | 4 | def CountObjectsWhileTraversing(mapInput, right=3, down=1):
objects = {}
lineWidth = len(mapInput[0])
# start is (0, 0)
# always skip 'down' lines
for i in range(0, len(mapInput), down):
# normalise right step
rightStep = int((i / down) * right)
line = mapInput[i]
... |
5e69f4f18ed73b15a672cc322b505f1fa6f5d645 | phorkyas-tg/advent-of-code | /aocLib/Array.py | 2,144 | 4.15625 | 4 | def JumpIndexRollingBuffer(index, n, lengthOfArray):
"""
Return the Index after jumping n steps. If the index reaches the end start at the front of
the array (rolling buffer).
Example:
array = [0, 1, 2, 3, 4, 5]
JumpIndexRollingBuffer(1, 2, 6) --> 3
JumpIndexRollingBuffer(1, 3,... |
fa2dc1ec2a6f17c4091f5b2b400422d5d526f009 | phorkyas-tg/advent-of-code | /aoc2016/_03_SquaresWithThreeSides.py | 992 | 3.53125 | 4 | def GetValidTriangles(file):
file = open(file, 'r')
inputLines = file.readlines()
file.close()
count = 0
for line in inputLines:
a, b, c = list(map(int, line.strip().split()))
if a + b > c and a + c > b and b + c > a:
count += 1
return count
def Ge... |
2ad84faa163b5f5d53ca2ca7dd38e3c8e34c0774 | edgartanaka/mo446 | /project-2/src/feature_matching.py | 3,315 | 3.5 | 4 | import numpy as np
import cv2 as cv
from sklearn.neighbors import NearestNeighbors
def explore_match(img1, img2, kp1, kp2, file_name):
"""
Displays the matched keypoints.
Inspired from https://stackoverflow.com/questions/48220817/how-to-match-and-align-two-images-using-surf-features-python-opencv
... |
91b19ad4be54b3804de63b1117762f25ca29d883 | craig-rupp/SSS_Python | /refresh/passing_functions.py | 443 | 3.640625 | 4 | def methodception(another):
print(another())
def add_two():
return 100+1
methodception(add_two)
methodception(lambda: 35 + 77)
my_list = [13, 37, 74, 19]
print(list(filter(lambda x: x != 74, my_list))) ##must encapsulate with list to return list
print((lambda x: x * 3)(5)) #look below for method like trans... |
3befd9ed8bf4647397aeb8ef7080e32179ddf063 | craig-rupp/SSS_Python | /18/code_bat/wmp_1.py | 1,860 | 4.25 | 4 | #Given 2 int values, return True if one is negative and one is positive.
#Except if the parameter "negative" is True, then return True only if both are negative.
def pos_neg(a, b, negative):
if a <= -1 and b >= 0 and negative is False:
return True
elif a >= 0 and b <= -1 and negative is False:
return True
... |
221cf3b9c28c0fc47136b4503f4e41d461b13719 | craig-rupp/SSS_Python | /18/Sect_6/movie/app.py | 2,727 | 4.09375 | 4 | from user import User
import json
import os
user = User("Craig")
user.add_movie("Black Panther", "Sci-Fi", 2018)
user.add_movie("Jumanji", "Comedy", 2018)
user.add_movie("I, Tonya", "Dramedy", 2017)
print(user.trim_movie("Black Panther "))
print(user.trim_movie(" Titanic"))
# with open('my_file.txt', 'w') as f:
# ... |
1d390fa3c43eceea46cd054577a0e92654e893cc | craig-rupp/SSS_Python | /refresh/decorators.py | 1,039 | 4.125 | 4 | import functools
def my_decorator(function):
@functools.wraps(function)
def function_running_argument():
print("I'm the decorator")
function()
print("After the function runs")
return function_running_argument ##make sure return statement isn't indented
@my_decorator
def my_functio... |
61da50c7aec8d08a34314c800a8ef0e6317f6adc | craig-rupp/SSS_Python | /18/RMOTR/practice_exe/7_9_OOP.py | 1,505 | 3.734375 | 4 | class Commercial(object):
def __init__(self, dicto):
for key, value in dicto.items():
setattr(self, key, value)
tide_ad = Commercial({
"actor": "David Harbour",
"brand": "Tide",
"style": "Really weird",
"warning": "... |
e7ec644fb9e7ef5bfcd00242d065ef061db9d89d | vberezny/pythonInterviewPrep | /StackQueue/queue.py | 807 | 4.1875 | 4 | # FIFO
# Insertion/Deletion: O(1)
# Space: O(n)
class Queue:
def __init__(self):
self.queue = []
# Insert method to add element
def addtoq(self,val):
if val not in self.queue:
self.queue.insert(0, val) # insert(0, val) inserts val BEFORE position 0 (start of list)
return True
... |
0e720abc924b586a0a3cf06da213883be437b58d | JohnRGold/Python-examples | /Tkinter GUI examples/radiobutton.py | 1,165 | 4.6875 | 5 | """The radiobutton lets you select from a variety of items. They are part of the default tk module. Unlike a checkbox, a tkinter lets you select only one option.
You can achive that by adding the same variable as parameter for the radiobuttons. If a radiobutton is clicked you can call a callback function.
The program... |
f52eec7c85691abb02d8acd8cb1e3b713b24f92b | JohnRGold/Python-examples | /Tkinter GUI examples/dialog file-handling.py | 1,551 | 4.53125 | 5 | """Python Tkinter (and TK) offer a set of dialogs that you can use when working with files. By using these you don’t have to design standard dialogs your self. Example dialogs include an open file dialog, a save file dialog and many others. Besides file dialogs there are other standard dialogs, but in this article we w... |
380424adbd65cbddf0bc6387bf973ee491a579a4 | IgaIgs/TxtFrequencyAnalysis | /specification-1/freq.py | 2,960 | 4.125 | 4 | import collections
import string
import char_freq_plot
import csvwriter
freq_counter = collections.Counter
# file path of an example book to be analysed
analysed_file = '../resources/txt/book.txt'
# open the text file, read it, decode the encoding, make all characters lower case and split the lines.
# Then save it i... |
3226a8dd5398aaeae83a19c8e2d4e32fc8f15efb | jake612/ResearchCode | /tokenizer.py | 353 | 3.625 | 4 |
# Method takes in a string and returns a list of tokens
def tokenizeString(string, **kwargs):
tokens = []
delimiter = ' '
if string is None:
return []
try:
if kwargs['lower'] is True:
string.lower()
tokens = string.split()
for token in tokens:
token = token.strip(".,?!:;")
except Exception as e:
... |
fb461112374c1e58222b99eccffaffcf8bea3abe | AlexRuber/KPCBMemoryGame | /memory.py | 3,227 | 3.578125 | 4 | #!/usr/bin/env python
#memory.py
"""Python script for KPCB Memory game
<----------------------------------------------------------------------------->
Do not exceed 80 columns in any line
<----------------------------------------------------------------------------->
This script runs the memory game assigned by the K... |
f5cf3bf30f1321b11e0d121028fcc30d64764032 | Furcas-debug/main | /chastot.py | 610 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 03:56:17 2020
@author: Furcas
"""
str1 = '`'
str2 = ''
def soll(res):
lsWord = {}
for key in res:
key = key.lower()
if key in lsWord:
value = lsWord[key]
lsWord[key]=value+1
else:
lsWord[key]=1
... |
36ebc8319c603758d59706d50df86af26d76a191 | lucien1011/LittleFWLite | /Utils/whereAmI.py | 525 | 3.578125 | 4 | import os
def whereAmI():
host = os.environ.get('HOSTNAME')
imperial = "ic.ac.uk"
cern = "cern.ch"
if not host: return "I have no idea where I am"
if imperial in host and cern in host:
print "Ambiguous hostname"
return "Ambiguous hostname"
elif imperial in host:
re... |
54996648e6859235622a30ec2c2576f6847f2817 | bencodezen/udacity-movie-trailer-website | /entertainment_center.py | 1,155 | 3.53125 | 4 | """
Import library for generating HTML pages
Import library for Movie class
"""
import fresh_tomatoes
import movie
# Create four instances of Movie class
the_incredibles = movie.Movie("The Incredibles",
"https://upload.wikimedia.org/wikipedia/en/e/ec/The_Incredibles.jpg", # noqa
... |
bdcdafb47f59c036a855112dd0dd27fc6bc84de9 | anachacon/DojoAssignments | /Python/PythonFundamentals/stringandlist.py | 1,338 | 4.21875 | 4 | #In this string: words = "It's thanksgiving day. It's my birthday, too!"
#print the position of the first instance of the word "day". Then create
#a new string where the word "day" is replaced with the word "month".
mystr = "It's thanksgiving day. It's my birthday,too!"
position = mystr.find("day")
print (position)... |
af7e8838e9e81b8507cb4a8dc03e8d6f489e2ab0 | vigneshabi/abinaya | /maximin.py | 243 | 4.375 | 4 | list1 = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
list1.append(numbers)
print("Maximum element in the list is :", max(list1), "\nMinimum element in the list is :", min(list1))
|
20ae2c6e1ec84a6b74b5a5e4d163155d7d3bbdc3 | vigneshabi/abinaya | /alphabet.py | 164 | 4.21875 | 4 | ch=input("enter the character":);
if((ch>='a' and ch<='z') or(ch>='A' and ch<='Z'))
print(ch, "is an Alphabet");
else:
print(ch,"is not an Alphabet");
|
2a431d66359d7e4937fcc5c1f05dcb6b3d1f9a6c | vigneshabi/abinaya | /sum12.py | 57 | 3.734375 | 4 | n12=int(input("enter the number:"))
sum=n12+1
print(sum)
|
8802bfc004b563dd9b012a828fff48edb267feaf | dillarionov/dev1 | /sorting.py | 2,622 | 3.765625 | 4 | import random
def selection_sort(l=None):
l = l or []
for i in range(0, len(l) - 1):
(el, min_i) = min([(el, i) for i, el in enumerate(l[i:])])
l[i], l[min_i + i] = l[min_i + i], l[i]
return l
def selection_sort2(l=None):
l = l or []
for i in range(0, len(l) - 1):
slice_... |
b93b740aaef2fc7734b7b60552f826b622626ae8 | AracelizGomes/CrackingTheCodeInterview | /DFSdisconnected.py | 1,193 | 3.859375 | 4 | #Depth First Search of a disconnected graph. Where start vertex isnt given
from collections import defaultdict
class Graph:
#Constructor
def __init__(self):
#default dict to store Graph
self.graph = defaultdict(list)
#function to add edge to graph
def addEdge(self, u, v):
self.graph[u].... |
da137ecb8ad59dd7afc317efcdda754552cb1c00 | AracelizGomes/CrackingTheCodeInterview | /isUnique.py | 530 | 3.8125 | 4 | def isUnique(s):
temp= []
if s=='':
return False
for i in s:
if i in temp:
print("there are duplicates")
else:
temp.append(i)
str="abcbdefg"
print(isUnique(str))
#done again 1/7/19
#return True is string of Unique Characters
def Unique(s):
if s == '':
output = "list is null"
arr... |
b430fd971bd3f42d7fcd9a970d03dfca39e1d3ca | hemendra442/PythonBasics | /assgn02.1_HemendraJampala.py | 1,116 | 4.21875 | 4 | def validate(string):
store=[]
for i in range(0,len(string)):
if(string[i]!='}' and string[i]!=')' and string[i]!=']'):
store.append(string[i])
continue
# Stack should not be empty while closed paranthesis started
if (len(store) == 0):
return... |
fc6c7135f1cfe9521e55029b8e61fbe3e6f5c489 | hemendra442/PythonBasics | /NRpython18.py | 142 | 4.125 | 4 | x = int(input("Enter X value"))
y = int(input("Enter Y value"))
if x>y:
print("x>y")
print("x>y")
elif x<y:
print("X<Y")
|
99962bae76b437efef8f296f20b77ed5f0c76cc0 | hemendra442/PythonBasics | /pyAssign01.py | 293 | 4.21875 | 4 | #Hello world --- assignment using For loop
s = "hello world"
r = len(s)+1
i=0
print("hello world using For loop")
for i in range(0,r):
print(s[0:i])
#Hello world --- assignment using While loop
print('\nhello world using While loop')
i=0
while i<r:
print(s[0:i])
i+=1 |
7b4d3d5e2a2c155270432295982decab9989651a | hemendra442/PythonBasics | /BasicOperations.py | 2,427 | 3.828125 | 4 | """
Steps to import numpy
1. pip3 install numpy -- command line
2. File --> Settings --> Project --> Project Intrepeter
*** For any package installation we need to follow the same procedure.
"""
import numpy as np
"""
ar = np.array([2,3,5,9,8])
print("ar:",ar)
print("ar Size: ", ar.size)
print("ar Sum: ... |
05777e03c45038f8a4ce02f33ad67c34be8ceba6 | hemendra442/PythonBasics | /Feb13Stack.py | 428 | 3.90625 | 4 |
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
print(self.items)
return len(self.items)
stack1 = Stack()
stack1.push(2)
stack1.push(4)
stac... |
5f2be89674f2905c053854b70ac459692f1bc163 | hemendra442/PythonBasics | /MethodTypes.py | 669 | 4 | 4 | #Instance Methods -- ( self )based on Object
#class Methods -- ( cls ) can call using class name
#Static Methods --
class Methods:
school = "University of New Haven"
def __init__(self,m1, m2):
self.m1 = m1
self.m2 = m2
def avg(self):
return (self.m1+self.m2)/2
@clas... |
ad09aed254dc360855d1b8dcbba40809a367f8f3 | hemendra442/PythonBasics | /MapReduceFilterfun.py | 833 | 3.96875 | 4 | from functools import reduce
""""
#lamda function
add = lambda n:n+2
result = add(5)
print(result)
mul = lambda n:n*n
result = mul(5)
print(result)
divide = lambda n:n/2
result = divide(5) #you can pass only one element jn lambda function
print(result)
"""
#Map, Reduce, Filter
nums = [1,2,3,4,5... |
ba174995444eae2d21d91b1722e52c6576868095 | BenMeehan/Data-Structures-and-Algorithms---Revision | /Recursion/ab.py | 312 | 3.921875 | 4 | s=input()
def check(s):
if len(s)==0 or len(s)==None:
return True
if len(s)==1:
if s[0]=='a':
return True
else:
return False
if len(s)==2:
return False
return (s[0]=='a' and s[1]=='b' and s[2]=='b') and check(s[3:])
print(check(s)) |
25237f986c4fe71d237433f7fac27dfd48f72647 | ShayanRahat/socsProject_altImplementation | /FISH.py | 482 | 3.859375 | 4 | import numpy as np
class Fish:
"""Each object from the Fish class represents a school of fish.
Attributes:
coordinates x & y
population
Methods:
move
"""
def __init__(self,position,population):
self.x=position[0]
self.y=position[1]
self.populatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.