blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
068620bf628fd12f81355f5cee48641033f0cc09 | Yucheng7713/CodingPracticeByYuch | /Easy/448_findAllNumbersDisappearedInArray.py | 905 | 3.625 | 4 | class Solution:
# With extra space
# Time complexity : O(n)
# Space complexity : O(n)
def findDisappearedNumbers(self, nums):
d_nums = [0] * len(nums)
for i in range(len(nums)):
d_nums[nums[i] - 1] = 1
return [k+1 for k in range(len(d_nums)) if d_nums[k] == 0]
# ... |
6933418e55272ee6bfe1afb9214420c53b82b10e | Yucheng7713/CodingPracticeByYuch | /Medium/82_removeDuplicateFromSortedList_II.py | 760 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
# Add a dummy head for convenient ( in case duplica... |
eda8f74d093435ad008fa6dbfc9eba2da8073e9a | Yucheng7713/CodingPracticeByYuch | /Medium/48_rotateImage.py | 508 | 3.890625 | 4 | class Solution:
def rotate(self, matrix):
# Transpose the matrix
for i in range(len(matrix)):
for j in range(i+1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row in the matrix
for lst in matrix:
lst.reve... |
29a53c219f27425f0a65e8397500bef8014e9008 | Yucheng7713/CodingPracticeByYuch | /Medium/229_majorityElement_II.py | 1,499 | 3.90625 | 4 | # Key constraints : Time complexity : O(N), Space complexity : O(1)
# -> Run in linear time without altering the array and no extra list storing
# -> Boyer-Moore Majority Vote Algorithm
# Key concept : Remove paired elements and see what elements are left : these elements
# can have a chance to be majority -> need a se... |
fd226248d5a13fcbdb6714d887504e2a546d6f44 | Yucheng7713/CodingPracticeByYuch | /Medium/147_insertionSortList.py | 1,634 | 4.15625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Sort by creating a new linked list
class Solution:
def insertionSortList(self, head: 'ListNode') -> 'ListNode':
sorted_list = ListNode(float('-inf'))
while head:
... |
7e49b3938f834465be5a6f21ce93237531d982eb | Yucheng7713/CodingPracticeByYuch | /Easy/844_backspaceStringCompare.py | 388 | 3.765625 | 4 | class Solution:
def backSpacing(self, s):
result = []
for l in s:
if l != '#':
result.append(l)
elif l == '#' and result != []:
result.pop()
return ''.join(result)
def backspaceCompare(self, S, T):
return self.backSpacing(S)... |
cdccc30f373c632c80618e2d094ad948d34e4b41 | Yucheng7713/CodingPracticeByYuch | /Easy/204_countPrime.py | 1,575 | 3.921875 | 4 | from math import floor, sqrt
class Solution(object):
# Check each number which is smaller than the square of n - TLE
# Time compleixty : O(sqrt(n)*n)
# Space complexity : O(1)
def countPrimes(self, n: int) -> int:
def isPrime(n):
k = floor(sqrt(n))
for i in range(2, k ... |
fcc38089a94abccb89d8e32d7bf48872ed4a283f | Yucheng7713/CodingPracticeByYuch | /Practice/ratioOfCommon&Unique.py | 462 | 3.5625 | 4 | from collections import Counter
def ratioOfCommonAndUnique(str_1: str, str_2: str):
counter_1 = Counter(list(str_1))
counter_2 = Counter(list(str_2))
numOfUnique = len(set(list(str_1) + list(str_2)))
numOfCommon = 0
for word in counter_1:
if word in counter_2:
numOfCommon += mi... |
a150e9f2f7ef33807bbabc7dad3f24b4c6210511 | Yucheng7713/CodingPracticeByYuch | /Medium/31_nextPermutation.py | 1,471 | 3.734375 | 4 | import sys
class Solution:
def findFirstDescend(self, nums):
# if nums == None:
# return None
# if len(nums) == 1:
# return nums[0]
result = -1
firstDes = nums[-1]
for i in range(len(nums) - 2, -1, -1):
if firstDes > nums[i]:
... |
7f0777f7f855f8c552d7246479747695182c05ee | Yucheng7713/CodingPracticeByYuch | /DataStructure/HashMap.py | 3,212 | 3.9375 | 4 | try:
from DataStructure.LinkedList import LinkedList
except ImportError:
print("Module not found")
class HashLinkedList(LinkedList):
def containKey(self, key):
temp = self.head
while temp:
if temp.val[0] == key:
return True
temp = temp.next
r... |
6b90284eb81a7ac75ede9a915e8f09d1af4817f6 | Yucheng7713/CodingPracticeByYuch | /Medium/368_largestDivisibleSubset.py | 1,370 | 3.515625 | 4 | class Solution:
def largestDivisibleSubset(self, nums: 'List[int]') -> 'List[int]':
count = [0] * len(nums)
parent = [0] * len(nums)
nums.sort()
max_n, index = 0, -1
for i in range(len(nums)):
# count[i] : store the size of divisible subset ending with nums[i]
... |
10ece7ab0f6631b91525e16c5499bfa5b3553449 | Yucheng7713/CodingPracticeByYuch | /Medium/560_subarraySumEqualsK.py | 2,523 | 3.53125 | 4 | class Solution:
# 暴力解法 -> 找出每個 subarray 並計算其總和,之後看是否 = k
# Time complexity : O(n^3)
# Space complexity : O(1)
def subarraySum_bruteForce(self, nums, k):
res = 0
for i in range(len(nums)):
for j in range(i+1, len(nums) + 1):
if sum(nums[i:j]) == k:
... |
ebbb913baf188c3b8d6ea27a3e4334398aa0464d | Yucheng7713/CodingPracticeByYuch | /Hard/336_palindromePairs.py | 2,178 | 3.796875 | 4 | class Solution:
# Brute Force - Check out all possible pairs
# Time complexity : O(n^2k)
# Space complexity : O(n)
def palindromePairs_I(self, words):
def checkPalindromic(word):
mid = len(word) // 2
right = mid
left = mid if len(word) % 2 == 1 else mid - 1
... |
7c9cf0a71b5a142a0522bd47a0cb44062f86161c | Yucheng7713/CodingPracticeByYuch | /Hard/4_medianOfSortedArray.py | 3,308 | 3.71875 | 4 | class Solution:
# The time complexity has to be in O(log(m + n))
# The first intuitive thought will be merging two sorted list then finding the median
# By doing so, the time complexity will be O(m + n) and so does the space complexity
# But that way the sorted property of two arrays won't be leverged.
... |
58a6006114cb6c4a299dd9501bd89b5e5f4b2df1 | Yucheng7713/CodingPracticeByYuch | /Medium/593_validSquare.py | 745 | 3.671875 | 4 | class Solution:
# Calculate the distances between each point and see if those distances satisfy properties of a valid square
# A valid square has :
# - 4 edges with same length
# - 2 diagnal edges with same length
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: Li... |
530ea0d870927a7e5b3e156cd5048b723bae128f | Yucheng7713/CodingPracticeByYuch | /Easy/101_symmetricTree.py | 616 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
if root is None:
return True
return self.isMirror(root.left, root.right)
def... |
53265a619fdcc285da171c29850cb5aaa246e7ea | Yucheng7713/CodingPracticeByYuch | /Medium/208_implementTrie.py | 1,318 | 4.0625 | 4 | # Class for Trie's node
class TrieNode:
def __init__(self):
self.links = collections.defaultdict(TrieNode)
self.isEnd = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: 'str') ->... |
8d7a92ec774d21c2382e305eae96aa8f3a72c022 | Yucheng7713/CodingPracticeByYuch | /Easy/412_fizzBuzz.py | 426 | 3.6875 | 4 | class Solution:
def fizzBuzz(self, n):
nums = []
for i in range(1, n + 1):
if i % 3 == 0 or i % 5 == 0:
s = ""
if i % 3 == 0:
s = "Fizz"
if i % 5 == 0:
s += "Buzz"
nums.append(s)
... |
2f2f681c32e265bb24dd413727b19f34380a001c | Yucheng7713/CodingPracticeByYuch | /Medium/207_courseSchedule.py | 2,389 | 3.6875 | 4 | import collections
# Topological sort with BFS
class Solution_I:
def canFinish(self, numCourses: 'int', prerequisites: 'List[List[int]]') -> 'bool':
indegrees = collections.defaultdict(int)
outdegrees = collections.defaultdict(list)
# Construct graph
# indegrees : number of in-degre... |
8a59e785b36cd6056bbcc7e3a0a075b84c7dc5ae | marianodominguez/pythonLab | /characters.py | 845 | 3.703125 | 4 | # -*- coding: iso-8859-1 -*-
def countChars(s):
count = []
letters = []
for k in s:
if k in letters:
i = letters.index(k)
num = count[i]
num += 1
count[i] = num
else:
letters.append(k)
count.append(0)
return le... |
397c7275429f4b3b568bb469227424fe8515fee7 | jeevy222/Dynamic-Programming | /equal_subset_sum.py | 732 | 3.765625 | 4 | '''Given a set of positive numbers, find if we can partition it into two subsets such that the sum of elements in both the subsets is equal.
Example 1: #
Input: {1, 2, 3, 4}
Output: True
Explanation: The given set can be partitioned into two subsets with equal sum: {1, 4} & {2, 3}'''
def subset_partition(nums):
S ... |
1a0d16946ea72ee6302daf8e968976ff7dcc51b0 | Niharika-Arora/TicTacToe | /tictactoe.py | 4,319 | 3.65625 | 4 | import sys
import random
moves = list(int(i) for i in '1 2 3 4 5 6 7 8 9'.split(" "))
corners = [1, 3, 7, 9]
sides = [2, 4, 6, 8]
center = 5
def tac_board(board):
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-----------')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
... |
04a79d514bf75d07e198759fe289769eab14fb54 | giho-sung/programming_language | /computer_algorithm/problems/dart_game.py | 1,371 | 3.53125 | 4 | '''
This dart game problem is just to handle string.
This problem is in programmer.co.kr
It is called dart game(다트 게임)
'''
def chop_int(string):
for i in range(len(string)):
if '0' <= string[i] <= '9':
pass
else:
break
integer = int(''.join(string[:i]))
for j in ra... |
48f350fdcf7a981fec27963c1f0be7303bfc8142 | zhengheng36/PythonTests | /ProjectEuler/180115_9.py | 726 | 4.0625 | 4 |
# Special Pythagorean triplet
# Problem 9
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
# It: 利用数学方法,首先做了一个因式分解,简化问题
b = ... |
0067a42cc4c0f4be73f63e6f104c1eb75b1df3de | zhengheng36/PythonTests | /180108_Advanced_IterableAndIterator.py | 577 | 4.125 | 4 | ## 所有可以用for的,都是Iterable
## 所有可以用next的,都是Iterator
# for 其实相当于不断的调用next()
from collections import Iterable
from collections import Iterator
print(isinstance((x for x in range(10)), Iterable))
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterable))
print(isinstance([], Iterator))
print(isin... |
778a61c9056f17c4117c7135dee1a5a5a0477936 | zhengheng36/PythonTests | /180108_LabelVariable.py | 164 | 3.828125 | 4 | # think variable as a lable
# created value first, the put the variable name as lable to the value
a = 'ABC'
b = a
a = 'CDE'
print('b is:', b)
print('a is: ' + a) |
f4bf037b50f2d834bc060b2761187ebf132d6920 | zhengheng36/PythonTests | /ProjectEuler/180111_3.py | 947 | 3.671875 | 4 | # //Largest prime factor
# //Problem 3
# //The prime factors of 13195 are 5, 7, 13 and 29.
# //
# //What is the largest prime factor of the number 600851475143 ?
def GetListPrimeNums(L):
ListPrimeNew = []
for num in L:
Cnt = 2
while Cnt < num:
if num % Cnt == 0:
... |
dcc4db48821a326c9a38392b9174728a7c00840e | zhengheng36/PythonTests | /180109_OOP_1_Basic.py | 1,134 | 4.03125 | 4 | ## ref: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431864715651c99511036d884cf1b399e65ae0d27f7e000
## Object Oriented Programming,简称OOP
# KEY: define a class: if not input parameter for class, keep 'object'
class NewClass(object):
# KEY: Construct Function
def __i... |
f8a488fbf123dc2f99911d10674a87f7af5c9502 | sydenham/CourseraPython | /Assignments/file1.py | 164 | 3.5 | 4 | def main():
fname = input("Enter file name: ")
fh = open(fname)
file = fh.read()
print(file.upper().rstrip())
if __name__ == "__main__":
main() |
865814ddd546cf9242e8db7155f18a47382f3730 | alexcflorea/electronics_code | /chapter_6_code.py | 699 | 3.78125 | 4 | import math
kind = input("Are you calculateing dB for a Power reference or Voltage reference; Type \"P\" for Power, or \"V\" for voltage: ")
if kind == "P":
reference = float(input("Enter your reference value in Watts now: "))
actual = float(input("Enter your actual value in Watts now: "))
dBp = 10*math... |
f2ff7e2b91fc8ef52f16709911b0f1eb63a04162 | rahlocutnacigra/SATsolver | /boolean.py | 8,006 | 3.921875 | 4 | # 9-13 March: Boolean formulas
# Build classes representing Boolean formulas (which may contain variables).
# Take 'T', 'F', 'and', 'or', 'neg' as basic logical connectives. Implication is translated to this connectives.
class Boolean:
def __init__(self, typ, pars=None):
self.typ = typ if typ in ["T", "F"... |
5278b7db271065148c46264fc70b5a5ceb7e795a | zahranorozzadeh/Python-Course | /Assignment 03/sort or not sort.py | 275 | 3.75 | 4 | a = list(input('Enter your list and separate them with , :').split(','))
f= True
for i in range(len(a)):
a[i]=int(a[i])
for i in range(len(a)-1):
if a[i] > a[i+1]:
f = False
break
if f :
print('sort!')
else:
print('not sort!')
|
04f7a3c133b287f387256e34a65b991cf4d2ed3d | zahranorozzadeh/Python-Course | /Assignment 04/Multiplication table.py | 216 | 3.921875 | 4 | def multiplication_table(m,n):
for i in range(1,m+1):
for j in range(1,n+1):
print(i*j,'\t',end='')
print('\n')
m = int(input())
n = int(input())
multiplication_table(m,n) |
9e368ddfd37f215c130ebf1f83c92ed2231c38e7 | NilayNaik/CS440-Projects | /AIMineSweeper/plottingTools/BasicAgentPlotter.py | 747 | 3.671875 | 4 | #file serves to plot our results with matplotlib
import BasicProbabilityHelper
import matplotlib.pyplot as plt
result = BasicProbabilityHelper.basicProbabilityHelper(40, 25)
# now performing matplotlib logic to generate the graph
#including data points
plt.scatter(*zip(*result))
plt.plot(*zip(*result... |
596dcb7c7acf39a8b24ca8bed1b5597bede707f7 | schakalakka/Washboard-Road-Simulation | /smoothing.py | 9,729 | 4 | 4 | import numpy as np
from road import Road
from wheel import Wheel
import sys
from utils import print_road_surface
import random
# Idea: pass as maxh the current maximum height of the road
def wind_smoothing(road: Road, maxh: int):
"""
Global max/wind smoothing function.
Takes all the grains above a thresh... |
04f42ce82cae76edf4b517887b14735244e99428 | juandausa/CompetitiveProgrammingCoreSkills | /Semana 1/erasingMaximum/erasing_maximum.py | 605 | 3.65625 | 4 | def eraseMaxValue(values, n):
if (n < 2):
raise Exception('Bad input')
if (len(values) != n):
raise Exception('Bad input')
dist = dict()
max = 0
for i in range(n):
if (values[i] in dist.keys()):
dist[values[i]].append(i)
else:
di... |
e6899ebfd6d9f6200be3ab97e636d682a6f09503 | WillSchick/LeetCode-Solutions | /Array/3sum.py | 1,525 | 3.609375 | 4 | ## 3Sum
## Will Schick
## 9/30/2019
# ---
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
# The solution set must not contain duplicate triplets.
# ---
def threeSum(nums):
outpu... |
d2beda821c850d1a57eb84e1b1058b69ceb4bcf3 | seunghk1206/Series_of_timer | /SAT_timer/timer.py | 1,976 | 3.796875 | 4 | from tkinter import * #Tkinter lib take all * = all
import time
import pygame
#package (lib)불러올땐 맨위에 작성
count = 0
pygame.mixer.init()
alarm = pygame.mixer.Sound('./SAT_timer/alarm(wav).wav')
ui = Tk() # class = book, we use ui variable to clarify
ui.title("SAT_timer") # our ui's title = calculator
ui.resizable(False,... |
ddb0c326a96de3c31aad8def3e4303d99f693d72 | rwangsc18/quiz_system | /exercise.py | 1,767 | 3.984375 | 4 | """2+2=4
8-4=4
task description:
- read from `questions.txt`
- for each question, print out the question and and wait for the user's answer
for example, for the first question, print out: `1+1=`
- after the user answers all the questions, calculate her score and write it to the `result.txt` file
the result shou... |
54bea9112d102dba92b671072f42492169789fb1 | Leonardo2901/jogo-da-forca1 | /Forca.py | 4,134 | 3.8125 | 4 | from random import choice
center = 0
# ---------------------------------------------------------------------------
# ------------------NAO USE ACENTOS NAS LETRAS!
def ClearScreen():
print()
def ChangeLetter():
global letra, palavra, letrasEncontradas
return_tmp = ""
for p, l in ... |
ffedefbae5e0ec9d810d437de88c336be56941b4 | mrbazzan/oo_design | /dice.py | 2,583 | 3.65625 | 4 | import random
class Die:
def __init__(self):
self.sides = 6
self.value = None
self.roll()
def roll(self):
self.value = random.randint(1, self.sides)
def get_roll(self):
return self.value
def __repr__(self):
return f"Die({self.value})"
... |
47a92e3670e074a3ffb77d4abdeff8c199949606 | mrbazzan/oo_design | /rpscissors.py | 2,026 | 4.15625 | 4 | import random
"""ROCK-PAPER-SCISSORS GAME"""
class Play:
def __init__(self):
self.options = ['rock', 'paper', 'scissors']
self.choice = None
def return_choice(self):
return self.choice
class Player(Play):
def __init__(self, name, pick):
super(Player, sel... |
6e1914b6a9e94d0b5eb06ee2cb69dfb80ce2a4d5 | gllewellyn19/maap-jupyter-ide | /ipycmc/ipycmc/loadGeotiffs/extractInfoLinks.py | 6,839 | 3.609375 | 4 | """
This file extracts information from the links that the user passed to load_geotiffs. Some of the functionality of these functions include
extracting the geotiff links from a folder, extracting the bucket name, and extracting the file ending from links.
Written by: Grace Llewellyn, grace.a.llewellyn@jpl.nasa.gov
""... |
4dc3fa016f9815837738a8ed5398926596eef516 | saket324/Hangman-with-Python- | /Hangman.py | 1,591 | 4.46875 | 4 | import random
# library in order to choose random words
name = input("What is your name? ") #Asking user for their name
print("Good Luck ! ", name)
words = ['apple', 'python', 'basketball', 'swimming',
'java', 'programming', 'player', 'dictionary',
'banana', 'canada', 'goose', 'geeks'] ... |
9abe36d213357cdc7fcb2a182ac6b450ccc1e2ea | yanbrasiliano/discovery-host | /discovery.py | 565 | 3.546875 | 4 |
"""
Created by: Yan Brasiliano Silva Penalva
Objective: discover hosts - addres ip of the websites.
"""
print()
print('Author: Yan Brasiliano Silva Penalva - hiyan')
print()
import socket as s
from time import sleep
while True:
# host #
host = str(input('Enter a valid host: '))
# ping #
ip = s.gethostbynam... |
f70b2fdd5faf8e513dc977fed88d3489f01a9e6a | CompThinking20/python-project-elianapuschett | /pythonprojectfinal.py | 1,849 | 3.78125 | 4 | import random
nouns = ["rose", "cathedral", "body", "sky", "lover", "friend"]
def create_poem(words):
poem = ""
word_number = random.randint (1, 3)
for item in range(0, word_number):
word_to_pop = random.randint(0, len(words) - 1)
poem +- words.pop(word_to_pop) + " "
return poem
print create_poem(no... |
f14390ee5d4a5bb5077c59898779edb750c0fe5c | Anoopcb/Map_function1 | /Map_function1.py | 302 | 3.96875 | 4 | ## map() function
numbers = [1, 2, 3, 4]
#def square(a):
#return a**2
squares = list(map(lambda a: a**2, numbers))
print(squares)
## by list comprehension
squares1 = [i**2 for i in numbers]
print(squares1)
name =["abc", "abcd", "abcde"]
length = map(len, name)
for i in length:
print(i) |
cb2d415b492854d3512446c9b406cd34b6b883b4 | vaibhavjain9e/Pilot-scooter-program | /Code.py | 3,838 | 3.71875 | 4 | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.insert(0, item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return l... |
af008bcb12a0b8304c86e384ab692bb6ea1cde74 | vivek738/vivek | /10 number in ascending order.py | 422 | 3.96875 | 4 | lst[]
num=int(input("how many number "))
for n in range (num):
num=int(input("enter number: "))
list.append(num)
print(lst)
if num>1:
for n in range(2,num):
if (num%1)==0
print(num,"is not a prime number")
print(n,"times",a//i,"is",a)
el... |
c8a49a35c428fb27a8379078e5efe15624f7942a | vivek738/vivek | /lab ex 2 Q.no 1.py | 489 | 3.75 | 4 | sub1 =int(input("enter marks of the first subject: "))
sub2 =int(input("enter mark of the second subject: "))
sub3 =int(input("enter mark of the third subject: "))
sub4 =int(input("enter mark of the third subject: "))
avg=(sub1+sub2+sub3+sub4)/4
if (avg>=70) and (avg<=100):
print("grade:distinction")
elif(av... |
2806bf5267b29a9ef4538be87d76de2d63800978 | vivek738/vivek | /simple interest.py | 151 | 3.515625 | 4 | p=float(input("enter principal amount: "))
r=float(input("enter rate: "))
t=float(input("enter time: "))
si=p*t*r/100
print("simple intrest is",si) |
ee64d5843f3b2c8fea0b7eaaaab34bb0a1017cbc | ThomasMatlak/istopics | /majors/convert_majors_to_html.py | 380 | 3.546875 | 4 | #Script to convert the list of majors in majors.txt to an HTML list
#Input File
infile = open("majors.txt", "r")
#Output File
outfile = open("majors.html","w")
outfile.write("<select>\n")
for line in infile:
major = line.strip("\n")
outfile.write(" <option value=\"%s\">%s</option>\n" % (major, major))
o... |
74fb87db5af564c32cffb62290b3fb973533c857 | bhuvangupta008/Document-Summarization | /util.py | 837 | 4.21875 | 4 | import csv
import pickle
def csv_dict_reader(csv_data):
reader = csv.DictReader(csv_data)
return reader
def save_to_disk(data,file_name):
"""
A function to save any data structure to a file using pickle module
:param data: data structure that needs to be saved to disk
:param file_name: name o... |
ecd71ffbe1d37a044cf9a9b97a000c319a40a15d | gjing/PHYS202-S13 | /Week10/CurveFitting.py | 1,574 | 3.71875 | 4 | import numpy as np
def LinearLeastSquaresFit(x,y):
"""Take in arrays representing (x,y) values for a set of linearly varying data and an array of weights w.
perform a linear least squares regression. Return the resulting slope and intercept
parameters of the best fit line with their uncertainties"""
n... |
a2ead561778888fe1a3edea8f46e0db2367b8667 | IAmBlackHacker/Algorithms | /python/BST.py | 679 | 4.0625 | 4 | from collections import namedtuple
Node=namedtuple('Node','value left right')
class BST():
def __init__(self):
self.root=None
def createNode(self,value):
n=Node(value,None,None)
return n
def addNode(self,node,root):
if root[0]==None:
root[0]=node
elif node.value>root[0].value:
self.addNod... |
d02d80269b9f178c8c8128496670a9209a660914 | IAmBlackHacker/Algorithms | /python/Raise Error.py | 475 | 3.828125 | 4 | class LengthError(Exception):
def __init__(self,length,limit):
Exception.__init__(self)
self.length=length
self.limit=limit
try:
st=str(input("Enter String : "))
if len(st)<8:
raise LengthError(len(st),8)
except ValueError:
print("Enter Wrong Value")
except L... |
b5f5c47230283c248417a0dce1e3993f961a39ba | IAmBlackHacker/Algorithms | /python/MergeSort.py | 412 | 3.734375 | 4 | def MergeSort(seq):
mid=len(seq)//2
lft,rgt=seq[:mid],seq[mid:]
if len(lft)>1:
lft=MergeSort(lft)
if len(rgt)>1:
rgt=MergeSort(rgt)
res=[]
while lft and rgt:
if lft[0]<=rgt[0]:
res.append(lft.pop(0))
else:
res.append(rgt.pop(0))... |
305a7fdfed9bcad13203d51dd8824de02b264c3f | rajsinghparihar/PsypherX | /store.py | 339 | 3.671875 | 4 | import csv
data = [["PASSWORD","KEY","PLATFORM USED"]]
def store_data(password: str, key: str, platform: str):
data.append([password,key,platform])
return data
def saveToCSV():
with open('passwords.csv', 'a') as csv_file:
writer = csv.writer(csv_file)
for item in data[1:]:
wr... |
db37903e4d9f155fac14e6571bd404d1eea2c751 | EnezMutluoglu/1st-class-coding | /exam/arayüz.py | 568 | 3.5625 | 4 | from tkinter import *
def yaz():
# print("Butona basıldı")
return yazi2.config(text="butona basıldı")
pencere=Tk()
pencere.geometry("500x300+400+300")
pencere.title("GUI uygulaması")
button=Button(text="tamam",width=20,height=5,command=yaz)
button.pack()
yazi1=Label(pencere,text="arayüz uygulaması")
yazi1.pack(... |
980abcddbd4daa159f7eceb0f8e65233fb85d4d0 | wolfdigit/class.wolfdigit.ga | /html/Cpp-programming/b15.py | 407 | 3.75 | 4 | #!/usr/bin/env python3
print("輸入一正整數,列出此數的所有正因數,並判斷此數字是否為質數")
n = int(input("請輸入一個數字:"))
print(n, "的因數有:", sep='', end='')
count = 0
for i in range(1, n):
if n%i==0:
count += 1
print(i, end=' ')
count += 1
print(n)
if count==2:
print(n, "為質數", sep='')
else:
print(n, "不為質數", sep='') |
a616f879c9386ca5e754ade0b3db22b08e585622 | ayazabbas/python-exercises | /solutions/3/3.py | 1,798 | 4.4375 | 4 | import random
responses = ["rock", "paper", "scissors"] # create a list with the possible responses the program gives
# This function will take the user's input and assign a numerical value if it's rock (1),
# paper (2), and scissors (3), randomly choose a response (negative 1,2,3) then add the
# scores to determi... |
4f7f53db8defdba46b79e86492eb4278c8fc1bb6 | Shaileshkumar99/Airlines_Fyers | /maxSumSubMatrix.py | 704 | 3.5 | 4 | def maxSumSubMatrix(arr, row, col):
max = float("-inf")
for left in range(col):
temp = [0] * row
for right in range(left,col):
for i in range(row):
temp[i] = temp[i] + arr[i][right]
kadanemax = kadane(temp)
if max < kadanemax:
... |
470af4681750535e6e4cf47aa88499cd1ec08cea | contactengine/python-training-nlp-public | /word_vectors.py | 2,173 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Loading and using the GloVe word vectors from first principles.
"""
import numpy as np
# setting a variable at the top of the script so that we can change the
# dimension at any time
glove_dim = 300
# load the glove vectors line by line as a python dictionary
glove ... |
c56f4de83ce3aa56de43b13fc298a42fca1a9079 | Sa1tYan/csv-to-sql | /csvtosql.py | 1,421 | 3.8125 | 4 | import csv
from tqdm import tqdm
'''
This script takes a CSV file with a mandatory header and a sql tablename and converts the data in the csv file into
an SQL INSERT statement.
'''
class CsvToSql(object):
def __init__(self):
# sql data will generate in your file_path.
file_path = inp... |
a732c3ce23f7a68e64f3e4bf41a4fd1c314e5dbd | BabyMochi/HackDavis-AI-Cancer-Detection | /InterviewPrep/LinkedList.py | 1,756 | 4.1875 | 4 | from nodes import Node
class LinkedList:
# Function to iniatize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
# Create new node
new_node = Node(new_data)
# Make next of new node as head
new_... |
dc24ab493d8fa422bfe69f0457070aec23fb046a | staskur/infa_2020 | /labs/2/lab2-12.py | 305 | 3.875 | 4 | # пружуна
import turtle
window = turtle.Screen()
window.title(u"пружина")
turtle.shape('turtle')
n = 6 # количество витков
r = 30 # радиус большой
turtle.left(90)
for i in range(n):
turtle.circle(-r,180)
turtle.circle(-r/5,180)
turtle.exitonclick()
|
056202de1605de363b664b5b42a4b100b11502a7 | LeninRomero/CEC-PYTHON-LENIN-ROMERO | /ejercicio 19 pruebas.py | 189 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 1 10:24:21 2020
@author: CEC
"""
def fun (x):
if x%2 == 0:
return 1
else:
return 2 print (fun (fun (2))) |
5c5c53e6c0aaf7c187fd4cfe0a9d7c30df8d2b2e | LeninRomero/CEC-PYTHON-LENIN-ROMERO | /ejercicos 2_preguntas con edad.py | 384 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 19:23:28 2020
@author: CEC
"""
firstname=input ("what is your first name?")
lastname=input ("what is your last name?")
print("hello "+ firstname,lastname + "!")
age=int(input("What is your age?"))
if age >= 1 and age <=15:
print("niño")
elif age >=16 ... |
1d6c3e0d8b832f28230b513f62434122d0eef33f | Yash-Gupta/coupon-proj | /item.py | 382 | 3.84375 | 4 | from balance import Category
class Item:
"""
An Item is part of the Store's database and represents an item's name, category and price.
"""
def __init__(self, name: str, category: Category, price: int) -> None:
self.name = name
self.category = category
self.price = price
def __repr__(self) -> st... |
646638a5274675f73fd4cf6e9317d2f559ae3b89 | Miguel619/cs50 | /pset6/Cash/cash.py | 452 | 3.828125 | 4 | change = float(0)
while (change <= 0):
change = input("Change owned: ")
try:
change = float(change) * 100
except ValueError:
change = 0
coins = change / 25
coins = int(coins)
change -= coins * 25
coins += change / 10
coins = int(coins)
change -= int(change / 10) * 10
coins += change / 5
c... |
362bd2e9598cb09351ef0a658b403c3c1982ceb3 | Klotz95/VierGewinntMalAnders | /tests/GameCheckTest/GameCheck.py | 5,115 | 3.53125 | 4 | """ This module checks the gamestate of "vier gewinnt (mal anders)"
"""
__author__ = "6345060 Nico Kotlenga, 6404053: Tim Geier"
__copyright__ = "Copyright 2016 – EPR-Goethe-Uni"
__email__ = "nico.kotlenga@stud.uni-frankfurt.de, uni@tim-geier.de"
class GameCheck:
def __init__(self, currentGameField):
"... |
65934c6bff6acac41a4dc060568869be808e5056 | alaindebecker/foresee | /Python/Stat.py | 3,889 | 3.515625 | 4 | import pandas
class ReadError(Exception) :
''' Exception raised for errors while reading files '''
pass
class Stat(pandas.DataFrame) :
def read_csv(file, **kwargs) :
''' Same as pandas.read_csv except encoding default is 'ANSI'. '''
if 'encoding' not in kwargs :
... |
4b332ab9cc4ecd484602c43859674db09311e590 | draconian9908/summer18_cs | /Module 1/hw0/phonebook/hw0pr1a.py | 3,440 | 4.21875 | 4 | #
# hw0pr1.py
#
# An example function
#
def plus1( N ):
""" returns a number one larger than its input """
return N+1
# An example loop (just with a printed countdown)
#
import time
def countdown( N ):
""" counts downward from N to 0 printing only """
for i in range(N,-1,-1):
print("i ==", ... |
dd15878306d5ab9f8c31603bb16e33a737a6a67b | draconian9908/summer18_cs | /Module 1/hw1&hw2/cs35_hw2_starterfiles/hw2pr2.py | 5,095 | 4.46875 | 4 | #
# starter file for hw1pr2, cs35 spring 2017...
#
import csv
from collections import *
#
# readcsv is a starting point - it returns the rows from a standard csv file...
#
def readcsv( csv_file_name ):
""" readcsv takes as
+ input: csv_file_name, the name of a csv file
and returns
+ out... |
d13607cd88b43e22ddf33496b85a7fa88c954543 | juhee3403/python_ruby | /Comment/1.py | 267 | 3.625 | 4 | # -*- coding: utf-8 -*-
str1 = '''
print(1)
print(2)
한글
日本語
'''
print(str1)
input = 11
real_egoing = 11
real_k8805 = "ab"
if real_egoing == input:
print("hello, egoing")
elif real_k8805 == input:
print("hello, k8805")
else:
print("who are you")
|
dd9dd00de3cc98a522cd02416d225b53934b2ff1 | juhee3403/python_ruby | /Input_Output/2.py | 263 | 3.578125 | 4 | # -*- coding: utf-8 -*-
in_str = input("ID를 입력해주세요. \n")
# print(type(in_str))
real_egoing = "11"
real_k8805 = "ab"
if real_egoing == in_str:
print("hello, egoing")
elif real_k8805 == in_str:
print("hello, k8805")
else:
print("who are you")
|
d365fda017e36615b8ae1c04135b8012210dbfe3 | juhee3403/python_ruby | /Conditional/5.py | 221 | 3.609375 | 4 | # -*- coding: utf-8 -*-
input = 11
real_egoing = 11
real_k8805 = "ab"
# 한글 오케이?
if real_egoing == input:
print("hello, egoing")
elif real_k8805 == input:
print("hello, k8805")
else:
print("who are you")
|
1689d45ad593039d0858e9afeaf2acfcec0b452f | lgtateos/gis540 | /example_scripts/add.py | 459 | 3.84375 | 4 | # add.py
# Purpose: Add two input numbers, print the results.
# Example input: 5 6
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
c = a + b
print(f"The sum is {c}")
##To toggle block comments in PyCharm, select multiple lines and use Ctrl+/
# print(f"SUM: sys.argv[1] + sys.argv[2] = {sys.argv[1] + ... |
725121fbc8339bc7b109dbf5503698d611be8275 | lgtateos/gis540 | /example_scripts/callExcelInClass.py | 1,376 | 3.5625 | 4 | #Purpose: practice calling class object from another class
### 1. add code here so that you can use module excel_lib
#Example of creating an ExcelDocument object called exO1. This one sets visibility to False
exO1 = excel_lib.ExcelDocument(False)
exO1.quit() #Quit this excel session.
### 2. add code to cr... |
dc10289a3818e5a4b43a8aeacdca1415f64315a2 | yj7o5/puzzles | /leetcode/regular_expression_10/regex_dp.py | 1,285 | 3.703125 | 4 | """
DP implementation
'.' matches any single character
'*' matches zero or more of the preceding element
"""
def is_match(input, pattern):
if len(pattern)==0:
return len(input)==0
if len(pattern)>1 and pattern[1] == "*":
return is_match(input, pattern[2:]) or (len(input)!=0 and (pattern[0]=="... |
1f7c4969b68441689e2902f722052e408eb593a7 | yj7o5/puzzles | /leetcode/regular_expression_10/regex_slow.py | 2,732 | 3.515625 | 4 | """
'.' matches any single character
'*' matches zero or more of the preceding element
Uses Thompsons construction technique to generate the DFA.
Time: O(2^n)
Space: O(1)
NFA State Machine
"ab*c"
q0 -> E -> q1
q1 -> a -> q2
q2 -> b -> q2
q2 -> E -> q3
q3 -> c -> qf
"""
EPSILON = "EPSILON"
KLEENE_STAR = "*"
class F... |
8eafdc03600d8519278e5dd137214964264bceaa | IhsanE/ProjectEulerSolutions | /Euler_41.py | 298 | 3.640625 | 4 | import itertools
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if (n%i==0):
return False
return True
for i in (sorted([int(i) for i in [''.join(i) for i in list(itertools.permutations('1234567',7))]])[::-1]):
if (isPrime(i)):
print (i)
break
|
f84ebfad39217a4520da8271e0b66828d8b8d0fc | IhsanE/ProjectEulerSolutions | /Euler_25.py | 164 | 3.609375 | 4 | def ff(n):
a=1
b=1
count=3
while (count<n):
a,b=a+b,a
count+=1
return a+b
n=3
while((len(str(ff(n))))<1000):
n+=1
print (n)
|
65998f3c3dda70f5e2bc8075812a26d81cad0c67 | shoe-bham-cries/ping-pong-game | /score.py | 1,262 | 3.8125 | 4 | from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.pu()
self.hideturtle()
self.l_score = 0
self.r_score = 0
self.change()
def change(self):
self.clear()
self.goto... |
d7e63fd8b28f8be4f6f30c54a84eac43c53b189c | BCheng-KH/Wacky-Chess | /ERBasic.py | 9,403 | 3.78125 | 4 |
def getMoves(board, piece):
role = piece.role
if role == "rook":
return rookMoves(board, piece)
elif role == "knight":
return knightMoves(board, piece)
elif role == "bishop":
return bishopMoves(board, piece)
elif role == "queen":
return queenMoves(board, pi... |
05e919adba47357437057f418871a64d9d16f26f | constantinpape/3d-cnn | /src/python/filereaders/cvs.py | 572 | 3.546875 | 4 | import csv
import numpy as np
def read_motl_from_csv(path_to_csv_motl: str):
"""
Output: array whose first entries are the rows of the motif list
Usage example:
motl = read_motl_from_csv(path_to_csv_motl)
list_of_max=[row[0] for row in motl]
"""
motl = []
with open(path_to_csv_motl, ... |
d5a9d816cd860caa4232d70a37515567bd3452cb | LiraelDianne/project-euler | /euler/quadratic_primes.py | 405 | 3.875 | 4 | def isprime(n):
for number in range(2, n/2+1):
if n % number == 0:
return False
return True
def how_many(a, b):
n = 0
while isprime(abs(n**2+a*n+b)):
n += 1
return n
most = 1
amost = 0
bmost = 0
for a in range(999, -1000, -2):
for b in range(-999, 1000, 2):
primes = how_many(a, b)
if primes > most:
... |
c821bd3f772db27a74c75d9d0e53e367cd21e18a | PetroSidliar/Lab-3 | /Orest Lab3/2z.py | 102 | 3.875 | 4 | n = int(input('Enter an integer greater than 1: '))
s = 0
for i in range(1, n+1):
s += i
print(s)
|
51070d800292d86afec06c5013c96d9e26fbcf85 | PetroSidliar/Lab-3 | /Stas Lab3/8.py | 161 | 3.8125 | 4 | import math
n = int(input("Enter number of months: "))
def savings(n_months):
return n_months*100 + math.floor(n_months/6)*500 + 300
print(savings(n))
|
d360698f12f548a5f5f89a1987884e9f81a93335 | Yosombo/python-syntax | /words.py | 257 | 4.125 | 4 | def print_upper_words(list, must_start_with):
""" This functions prints every sinngle word"""
for word in list:
for letter in must_start_with:
if word.startswith(letter):
print(word.upper())
break
|
4ac0da6ea7f0e5b17c015a72e0af853a03db8d3f | ArtySem/ForGB | /2exercise1.py | 1,016 | 3.9375 | 4 | print('Операции со списком')
my_list = [1, 3.2, [7, 2], 'A', {18, 1}]
print(type(my_list))
print(my_list)
my_list.append(9)
print(my_list)
my_list.append(9)
print(my_list[0])
for i in range(0, len(my_list)):
if type(my_list[i]) == int:
print(f'{my_list[i]} - целое число')
if type(my_list[i]) == float:... |
77a84b96f89d0d35231e897d0b2ef87467da6013 | BillyChao/leetcode | /56-剑指-数组中数字出现的次数/solution.py | 935 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/7/23 下午2:05
@Author : mc
@File : solution.py
@Software: PyCharm
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
来源:力扣(LeetCode)
链接:https://leetc... |
0d8ac591031cd90d341438f34b5021252d855ae0 | BillyChao/leetcode | /46-全排列/solution.py | 536 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/3/3 10:38 上午
@Author : mc
@File : solution.py
@Software: PyCharm
"""
class Solution:
def permute(self, nums: list) -> list:
res = []
def dfs(x):
if x == len(nums) - 1:
res.append(nums[:])
for i in range(x, le... |
e2b2cb2620bd37161e70bae275509df7baef73db | BillyChao/leetcode | /长度为n的数组查找出现一半次数/solution.py | 501 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/2/26 12:05 下午
@Author : mc
@File : solution.py
@Software: PyCharm
"""
def findHalfNum(nums: list):
if not nums:
return None
count, cadidate = 1, nums[0]
for i in range(1, len(nums)):
if nums[i] != cadidate:
count -= 1
... |
6d361c8b7fd777df243eca4d9f89d0b99d200f45 | BillyChao/leetcode | /876-链表的中间节点/solution.py | 472 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/2/21 11:06 上午
@Author : mc
@File : solution.py
@Software: PyCharm
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
... |
35b4a3e45017159537b969c7c0364895bb6e92ed | BillyChao/leetcode | /7-剑指-重建二叉树/solution.py | 987 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/3/21 10:39 下午
@Author : mc
@File : solution.py
@Software: PyCharm
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preor... |
b2c4267e1b308f34e9bf50b42528b8225df03232 | BillyChao/leetcode | /57-剑指-和为s的两个数字/soluiton.py | 1,067 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/7/22 下午8:13
@Author : mc
@File : soluiton.py
@Software: PyCharm
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
来源:力扣(LeetC... |
e16b5d4333084d6d2c76ae35cec832e30a3bfa6d | TheDUZER/challenges | /27 - fibonacci.py | 217 | 3.75 | 4 | def fib(n):
a = 0
b = 1
while a < n:
print (a)
a = b
b = a + b
while True:
fib(int(input()))
a = input("Any key to continue")
if a == 'quit':
quit()
|
f3c958fee5919b2db5d5904db869cfcf6c271317 | melihcanyardi/Python-Crash-Course-2e-Part-I | /ch7/movie_tickets.py | 181 | 4.0625 | 4 | age = int(input("Please enter your age: "))
if age < 3:
print("The ticket is free.")
elif age < 12:
print("The ticket costs $10.")
else:
print("The ticket costs $15.")
|
1d0548de9530bf7ecbb83fba5f58278cc247d65d | melihcanyardi/Python-Crash-Course-2e-Part-I | /ch4/my_pizzas_your_pizzas.py | 293 | 4.21875 | 4 | pizzas = ['broccoli', 'pineapple', 'bbq']
friend_pizzas = pizzas[:]
pizzas.append('margarita')
friend_pizzas.append('neopolitan')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.