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 |
|---|---|---|---|---|---|---|
2050102913720260d4bbeb2c1c6f8f100197d373 | chengtianle1997/algs4_princeton | /All Sorting Algorithms/ShellSort.py | 342 | 3.640625 | 4 | # Shell Sort
def ShellSort(alist):
n = len(alist)
h = 1
while (h < int(n/3)):
h = 3*h + 1
while(h >= 1):
for i in range(h, n):
for j in range(i, h-1, -h):
if alist[j] < alist[j-h]:
alist[j], alist[j-h] = alist[j-h], alist[j]
h = int... |
2bd349af00daa489b0304d10ce1354b5629fb804 | oleksandrpodran/bigadatatraining | /week1/file_read.py | 437 | 3.578125 | 4 | import os.path
while True:
filename = input('Filename:')
if not os.path.isfile(filename):
print('File:', filename, ' is not exists')
continue
file = open(filename, 'r')
while True:
line = file.readline()
if not line:
print('No lines left')
... |
5b4c76dd91d24260d624afff5567033eae5a41b1 | sixthgear/tradewars-server | /tw/util/files.py | 1,093 | 3.84375 | 4 | import os
import random
def random_line(filename):
"""
Generator to open a large file and yield random lines from it.
This should be very memory efficent and quick, since we do
not read the whole file, just seek to a random spot and return
the next full line.
"""
used = set()
with o... |
cd1cb81857b9ac5f40257db90cf2c7882649d0cf | mustafahavan/.vscode | /Sqlite.py | 682 | 3.609375 | 4 | # import sqlite3 as sql
# db = sql.connect(r"D:\muratHANCI\iedb.db")
# cursor = db.cursor()
# cursor.execute("SELECT * FROM V_HESAP")
def SozlukGetir(tabloid):
import sqlite3 as sql
db = sql.connect(r"D:\muratHANCI\iedb.db")
cursor = db.cursor()
cursor.execute("SELECT sozluk_id,sozluk_adi FROM HSP_SOZL... |
f1b8e7c49e6d55353678a2bb24bd102a225a8e4f | toferrari/Linear_regression | /estimate.py | 522 | 3.828125 | 4 | #!/usr/bin/env python3
import csv
import matplotlib as plt
km = 0
while km <= 0:
try:
km = int(input("Enter your Km ?\n"))
if km <= 0:
print("Please use positive number")
except:
print("Please use a number")
continue
theta = list()
try:
data = csv.reader(open("theta.csv", "r"))
for row in data:
try:
... |
278942c8419ff38e9fe29adfb040ab2607afa0f7 | geekmj/fml | /python-programming/panda/accessing_elements_pandas_dataframes.py | 2,626 | 4.21875 | 4 | import pandas as pd
items2 = [{'bikes': 20, 'pants': 30, 'watches': 35},
{'watches': 10, 'glasses': 50, 'bikes':15,'pants': 5 }
]
store_items = pd.DataFrame(items2, index = ['Store 1', 'Store 2'])
print(store_items)
## We can access rows, columns, or individual elements of the DataFrame
# by usin... |
900ff84b08de1fb33a0262702f2e79dd11125470 | geekmj/fml | /python-programming/panda/accessing_deleting_elements_series.py | 2,231 | 4.75 | 5 | import pandas as pd
# Creating a Panda Series that stores a grocerry list
groceries = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['eggs', 'apples', 'milk', 'bread'])
print(groceries)
# We access elements in Groceries using index labels:
# We use a single index label
print('How many eggs do we need to buy:', groc... |
ce99aabf507f468aa5f57cfdb7c31470496f031a | geekmj/fml | /python-programming/bikeshare_project/bikeshare.py | 7,345 | 3.84375 | 4 | import pandas as pd
import stats as st
import utilities as ut
# City & File Mapping
CITY_DATA = {
'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'
}
# Cities List Constant
CITIES_LIST = ('chicago', 'new york city', 'washington')
# Months List Constant
MONTHS_LI... |
65022765ef2ada624c150e8d7c47215b4f13a4ce | Jyotirm0y/kattis | /whatdoesthefoxsay.py | 437 | 3.515625 | 4 | n = int(input())
for i in range(n):
recording = input().split()
s = input()
a = []
while s != 'what does the fox say?':
s = s.split()
if s[2] not in a:
a.append(s[2])
s = input()
result = ""
for w in recording:
if w not in a:
i... |
9fcc2d937115a9e2835b6511d9f68207565c17af | Jyotirm0y/kattis | /consecutivesums.py | 676 | 3.5625 | 4 | t = int(input())
for _ in range(t):
n = int(input())
if n % 2 == 1:
if n == 1:
print('IMPOSSIBLE')
else:
print(f'{n} = {(n-1)//2} + {(n+1)//2}')
continue
done = False
num = 3
while num*(num+1)/2 <= n:
sum = num*(num+1)//2
if (n - sum) ... |
140ef007d2fc65d23e69d7463ee45cc5cae338cd | Jyotirm0y/kattis | /twostones.py | 82 | 3.671875 | 4 | n = int(input())
if int(n/2)*2 == n:
print("Bob")
else:
print("Alice") |
8f59711acbbe68321ca497570c4de5df6ff6d6a0 | Jyotirm0y/kattis | /eligibility.py | 668 | 3.578125 | 4 | n = int(input())
for i in range(n):
s = input().split()
name = s[0]
startdate = s[1]
birthdate = s[2]
numcourses = int(s[3])
eligible = False
ineligible = False
petition = False
if int(startdate[:4]) >= 2010:
eligible = True
if int(birthdate[:4]) >= 1991:
... |
c46041427a241b8ea7af6cf0e77c7d6a783083b6 | Jyotirm0y/kattis | /guessinggame.py | 518 | 3.96875 | 4 | lower = 0
upper = 11
dishonest = False
g = int(input())
while g != 0:
s = input()
if s == 'too high':
upper = min(upper, g)
elif s == 'too low':
lower = max(lower, g)
if upper - lower < 2:
dishonest = True
if s == 'right on':
if (dishonest or g >= upper o... |
796a06acb20429c0ca3aca959e3d92ed175cbb2d | Jyotirm0y/kattis | /inversefactorial.py | 273 | 3.5 | 4 | import math
x = input()
l = len(x)
if x == '1':
print(1)
elif l < 10:
x = int(x)
n = 0
while x > 1:
n += 1
x /= n
print(n)
else:
n = 0
s = 0
while math.floor(s) + 1 < l:
n += 1
s += math.log10(n)
print(n)
|
746fcd42e69317574603e2f4622c18f588290dd4 | Jyotirm0y/kattis | /touchscreenkeyboard.py | 873 | 3.78125 | 4 | def dist(w1, w2):
board = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
distance = 0
w1r, w1c, w2r, w2c = 0, 0, 0, 0
for i in range(len(w1)):
x = w1[i]
y = w2[i]
for row in range(3):
if x in board[row]:
w1r = row
w1c = board[row].index(x)
... |
719d765c42dad36593af436cb541d457b99819de | Jyotirm0y/kattis | /provincesandgold.py | 355 | 3.5625 | 4 | l = input().split()
g = int(l[0])
s = int(l[1])
c = int(l[2])
buy = 3*g + 2*s + c
if buy >= 8:
v = "Province"
elif buy >= 5:
v = "Duchy"
elif buy >= 2:
v = "Estate"
else:
v = ""
if buy >= 6:
t = "Gold"
elif buy >= 3:
t = "Silver"
else:
t = "Copper"
if v == "":
print(t... |
fda2a58f877bc1b36771bad168a4d463f3212b99 | Jyotirm0y/kattis | /tgif.py | 630 | 3.5 | 4 | days = {'SAT':0, 'SUN':1, 'MON':2, 'TUE':3, 'WED':4, 'THU':5, 'FRI':6}
months = {'JAN':0, 'FEB':1, 'MAR':2, 'APR':3, 'MAY':4, 'JUN':5,
'JUL':6, 'AUG':7, 'SEP':8, 'OCT':9, 'NOV':10, 'DEC':11}
monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
monthdaysleap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 3... |
a1b52025e152eedb1a358fb9338ea5dd1fb15e42 | Jyotirm0y/kattis | /fractalarea.py | 307 | 3.625 | 4 | import math
t = int(input())
for _ in range(t):
r, n = map(int, input().split())
area = math.pi * r**2
if n > 1:
area *= 2
x = r/4
k = 4
for __ in range(3, n+1):
area += 3 * k * (math.pi * x**2)
x /= 2
k *= 3
print(area)
|
541a03026b19a4235c6ddc320419738782fa38ba | Jyotirm0y/kattis | /tripletexting.py | 124 | 3.71875 | 4 | s = input()
n = len(s)//3
a = s[:n]
b = s[n:2*n]
c = s[2*n:3*n]
if a == b or a == c:
print(a)
elif b == c:
print(b)
|
2087f6e89b2aebb028bb78c7cb83812d40ed0fa6 | Jyotirm0y/kattis | /bossbattle.py | 64 | 3.515625 | 4 | n = int(input())
if n > 2:
print(n-2)
else:
print(1) |
dc0168556ef464beab6eb6371d24d7a726a08df0 | ads2100/pythonProject | /72.mysql3.py | 1,748 | 4.15625 | 4 | # 71 . Python MySql p2
"""
# The ORDER BY statement to sort the result in ascending or descending order.
# The ORDER BY keyword sorts the result ascending by default. To sort the result in
descending order, use the DESC keyword
# Delete: delete records from an existing table by using the "DELETE FROM" statement
# ... |
e3476d68e724f57e66131177f595e38d0ec492fe | ads2100/pythonProject | /15.list.py | 658 | 4.34375 | 4 | # 15. List In python 3
"""
# List Methods
len() the length of items
append() add item to the list
insert() add item in specific position
remove() remove specified item
pop() remove specified index, remove last item if index is not specified
clear() remove all items
"""
print("Lesson 15: List M... |
61a30c2c64aa88706a32b898c7fca786775c8ae1 | ads2100/pythonProject | /59.regularexpression3.py | 994 | 4.4375 | 4 | # 59. Regular Expressions In Python p3
"""
# The sub() function replaces the matches with the text of your choice:
# You can control the number of replacements by specifying the count parameter. sub('','',string,no)
# Match Object: A Match Object is as object containing information about the search and the result.... |
4c36b5214ebd5c63b66233c33a2c3bc59701e770 | ads2100/pythonProject | /16.tuple.py | 655 | 4.1875 | 4 | # 16. Tuple in Python
"""
# A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets ().
# if the tuple has just one item... ("item",)
# acces item in tuple with referring [index]
# You cannot change its values. Tuples are unchangeable.
# You cannot add item... |
727e4c1d1cd9d7567b19bc6270acacdcab3adbd9 | ads2100/pythonProject | /62.pip.py | 1,007 | 3.703125 | 4 | # 62 . Python PIP
"""
# PIP is a package manager for Python packages, or modules if you like.
# Note: If you have Python version 3.4 or later, PIP is included by default.
# Package? A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project
# Downloadi... |
bdf950534b06930459c8c68c712183f29127add3 | ads2100/pythonProject | /48.scope.py | 826 | 4.03125 | 4 | # 48. Scope In Python
"""
# A variable is only available from inside the region it is created. This is called scope.
➢ Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function
➢ Global Scope
A variable created in the main bod... |
aa31af745d1e529b99fc8d78c403d3c1dd76b52d | ads2100/pythonProject | /73.mysql4.py | 2,099 | 4.03125 | 4 | # 73 . Python MySql p4
"""
# Update Table: You can update existing records in a table by using the "UPDATE" statement.
# Important!: Notice the statement: mydb.commit() It is required to make the changes,
otherwise no changes are made to the table.
# Notice the WHERE clause in the UPDATE syntax: The WHERE clause s... |
dc843ffc90076065372aa44081833888e3ee2553 | ads2100/pythonProject | /68.week10_challenge_Q2.py | 231 | 3.8125 | 4 | # 68 . Week Challenge Q2
# use format() method to print "Dear Ahmad Ali, Your current balance is 53.44 $"
txt = "Dear {fname} {lname}, Your current balance is {balance} $"
print(txt.format(fname="Ahmad", lname="Ali", balance=53.44))
|
dc4a47157d0f2cf78a4bdfd6188b0507dd5bbdec | ads2100/pythonProject | /14.list2.py | 407 | 4 | 4 | # 14. List In python 2
"""
# Print part of list using index [2:5]
# Check if Item Exists. if "search" in list: do somthing
# Repeat item in list
"""
a = ["A", 4, "C", 2.5]
print("To print a part of list we use index, for ex: [1:3] index:3 won't be printting=> "+str(a[1:3]))
if "A" in a:
print("Search for \"A\"... |
18b70da208d41fe7a13a99414deabccb55f063c8 | cyx0329/python-practices | /Serialization.py | 1,014 | 4.09375 | 4 | import json
#To encode a data structure to JSON, use the "dumps" method.
#This method takes an object and returns a String:
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print json_string
#To load JSON back to a data structure, use the "loads" method.
#This method takes a string and turns it back into the js... |
dd1b1dec1ce698d110c5d775308a2493486356b6 | Sublimestyle91/Computational_linguistics | /Computational linguistics/Swindall_Nathan_hw4.py | 4,439 | 3.578125 | 4 | # Name: Nathan Swindall
# Ut EID:Nts279
#########
# Problem 1:
# P(both Alice and Bob put the same tag for a word) = P(Alice(Dt) and Bob(Dt))+ P(Alice(NN) and Bob(NN)) + P(Alice(VB) and Bob(VB))=
# (.5)(.5) + (.3)(.3) + (.2)(.2) = .38
# The probability that both use the same tag for a word is 38%.
#########
# ... |
7a0730887a5294b3f2400106050588ff153fdec7 | Muilton/sandbox | /RocketBall/Level.py | 8,342 | 3.65625 | 4 | import pygame
import sys
from Config import *
from Brick import Brick
from Ball import Ball
from Platform import Platform
import math
class Level:
def __init__(self):
self.bricks_list = pygame.sprite.Group()
self.ball = Ball()
self.platform = Platform()
self.collision_list = None
... |
edb4492846b640b6e4c8a9a77cd9edbd56c8c42a | tianyunzqs/LeetCodePractise | /leetcode_61_80/68_fullJustify.py | 4,106 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/2 16:55
# @Author : tianyunzqs
# @Description :
"""
68. Text Justification
Hard
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words ... |
4054eb15aa4e1c1a406a7766e5874288d321232b | tianyunzqs/LeetCodePractise | /leetcode_61_80/69_mySqrt.py | 956 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/3 9:44
# @Author : tianyunzqs
# @Description :
"""
69. Sqrt(x)
Easy
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and... |
738ab1fe07bdb193c1e9a9e5a187086259081e85 | tianyunzqs/LeetCodePractise | /leetcode_81_100/95_generateTrees.py | 2,897 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/19 17:19
# @Author : tianyunzqs
# @Description :
"""
95. Unique Binary Search Trees II
Medium
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
... |
2aed295fded09b722c3faba5d34643752828321a | tianyunzqs/LeetCodePractise | /leetcode_21_40/34_searchRange.py | 564 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/18 16:45
# @Author : tianyunzqs
# @Description :
def searchRange(nums, target: int):
if not nums or target < nums[0] or target > nums[-1]:
return [-1, -1]
left, right = 0, len(nums) - 1
while left <= right:
if nums[left] < target:
... |
148c6601669006bca4331d27fb44eb8fd32d1687 | tianyunzqs/LeetCodePractise | /array_sort/bubble_sort.py | 469 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/15 10:52
# @Author : tianyunzqs
# @Description :
def bubble_sort(nums):
n = len(nums)
for i in range(n):
flag = False
for j in range(n-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
... |
17dbd6c053c5d9b03897b3ebbcd30caf92e3434b | tianyunzqs/LeetCodePractise | /leetcode_41_60/42_trap.py | 2,287 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/25 9:25
# @Author : tianyunzqs
# @Description :
"""
42. Trapping Rain Water
Hard
Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining.
The above elevation map is rep... |
7eed19d8675227c947b74aa3143c0745126f08b8 | tianyunzqs/LeetCodePractise | /leetcode_61_80/74_searchMatrix.py | 2,010 | 4.375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/9 10:43
# @Author : tianyunzqs
# @Description :
"""
74. Search a 2D Matrix
Medium
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first in... |
5a152c20830b1a406169c422d72807d8a1f1a86e | tianyunzqs/LeetCodePractise | /DynamicProgramming/188_maxProfit.py | 2,093 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/7/8 18:45
# @Author : tianyunzqs
# @Description :
"""
188. Best Time to Buy and Sell Stock IV
Hard
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k tra... |
c9881c443002fd0a79b33f5c3d02884d678d76d4 | tianyunzqs/LeetCodePractise | /leetcode_41_60/56_merge_57_insert.py | 996 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/1 9:12
# @Author : tianyunzqs
# @Description :
def merge(intervals):
if len(intervals) <= 1:
return intervals
intervals.sort()
new_intervals = [intervals[0]]
for interval in intervals[1:]:
if new_intervals[-1][1] >= interval[0]:
... |
37c93a8573625f93b6db2ae0e528d68cd45c4837 | tianyunzqs/LeetCodePractise | /leetcode_81_100/83_deleteDuplicates.py | 1,418 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/17 18:07
# @Author : tianyunzqs
# @Description :
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def build_linklist(val_list: list) -> ListNode:
if not val_list:
return Non... |
b3a376554a3096903b01bbc42e805890bc4fdfcc | tianyunzqs/LeetCodePractise | /tree/101_isSymmetric.py | 4,823 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/4/27 19:26
# @Author : tianyunzqs
# @Description :
"""
https://leetcode-cn.com/problems/symmetric-tree/
101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
... |
8ef6c38f47337169b4745cf98f75b352570365c3 | tianyunzqs/LeetCodePractise | /leetcode_1_20/10_44_isMatch.py | 4,745 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/12 10:12
# @Author : tianyunzqs
# @Description :
"""
10. Regular Expression Matching
Hard
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more ... |
7b84f7324064b41904ff0304a2cf5c208c81b8d8 | PranayKotian/TFSSComputerScienceClub | /WeeklyLessons/Python/PythonBasics/Variables.py | 1,119 | 3.984375 | 4 | #VARIABLES in PYTHON
#Increment and Decrement Operators in Python
#Increment and decrement operators are not allowed in python
#You don't write code like this:
#for (int i = 0; i < 5; i++)
#In Python you would write:
#Sample Python program to show loop (unlike other languages it doesnt u... |
6ed00de9dce1cdef2dae8d753769ad372448d973 | malachi-hale/python-exercises | /list_comprehensions.py | 2,522 | 4.03125 | 4 | fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
#Exercise 1
uppercased_fruit = [fruit.upper() for fruit in fruits]
print(uppercased_fruit)
#Exercise 2
capitalized_fruits = [fruit.title() for fruit in ... |
ca680c2f972a2c212653e4ceb27e76e7ab0e04df | sstevenson66/programming_big_data_1743573 | /spellcheckerobj.py | 1,192 | 3.625 | 4 | class SpellChecker(object):
def __init__(self):
self.words = []
def load_file(self, file_name):
return map(lambda x: x.strip().lower(), open(file_name).readlines())
def load_words(self, file_name):
self.words = self.load_file(file_name)
def check_word(self, word):
return word.lower().strip(... |
162cd4f7a4587d20ae88e8059f474ee0af6a1297 | KareimGazer/Algorithmic-tool-box | /mSortV2.py | 916 | 3.953125 | 4 | def merge(lst1, lst2):
lst1_len = len(lst1)
lst2_len = len(lst2)
index1, index2 = 0, 0
result = list()
while(index1<lst1_len or index2<lst2_len):
if(index1>=lst1_len):
result.append(lst2[index2])
index2 = index2 + 1
elif(index2>=lst2_len):
result.a... |
09928416633eba29a1caab52dfe2f93362cc5d22 | hans/Maze | /maze_automate/lexicon_generator.py | 8,798 | 4.03125 | 4 | '''Functions related to building word to frequency lookups and lists of possible distractor words '''
import gzip
import csv
import math
import re
import json
from ast import literal_eval
def make_word_list(output="word_list.json", source="words.txt", exclude="exclude.txt"):
'''Makes a list of valid (distractor) ... |
838d1549b06f4852a0eb7d0e38fe1fcfbfd39fe3 | Mamadpalang/Game | /Bullets.py | 684 | 3.828125 | 4 | import turtle
class Bullets:
bullet = turtle.Turtle()
def __init__(self, x, y,angle):
self.bullet = turtle.Turtle()
self.bullet.shape("circle")
self.bullet.color("yellow")
self.bullet.shapesize(0.75)
self.bullet.penup()
self.bullet.left(angle)
self.bullet.... |
5142c784146e67ae789110f9a45030b09c6231e5 | Alfimenko/Python_1 | /task_2.py | 624 | 4.03125 | 4 | print("Calculate area of the room in square meters")
def askInput():
a = input("Width of the room in meters: ")
try:
a = float(a)
except:
err()
else:
pass
b = input("Length of the room in meters: ")
try:
b = float(b)
except:
err()
els... |
b0db10802a3e7f216a0e55cbda2778770cfa11c5 | fgassert-pub/flood_notebooks | /floodpickle2csv.py | 2,104 | 3.546875 | 4 | #!/usr/bin/env python
import pandas as pd
import pickle
import sys
def p2c(pickle_in, csv_out):
"""resaves a pickle file with a list of identically structured dictionaries as a csv"""
with open(pickle_in) as f:
dat = pickle.load(f)[0]
dicts_to_df(dat).to_csv(csv_out)
def dicts_to_df(dat):
"""... |
f87328e58228e7fd3e3d16ffd999638ff38cf8f9 | AlanRufuss007/Iceberg | /python day1.py | 319 | 4.125 | 4 | num1 = 10
num2 = 20
sum = num1+num2
print("sum of {0} and {1} is {2}".format(num1,num2,sum))
num1 = input("Enter the number:")
num2 = input("/n Enetr the number:")
sum = float(num1)+float(num2)
print("The sum of {0} and {1} is {2}".format(num1,num2,sum))
a = 10
b = 20
maximum = max(a,b)
print(maximum)
|
c8e1b5c8aad45dd45013b84d0d8a5f23d0e6ccea | leiwond/doorlck | /open.py | 396 | 3.515625 | 4 | #import the library
from pyA20.gpio import gpio
from pyA20.gpio import port
from time import sleep
#initialize the gpio module
gpio.init()
port = port.PA7
#setup the port (same as raspberry pi's gpio.setup() function)
gpio.setcfg(port, gpio.OUTPUT)
#now we do something (light up the LED)
gpio.output(port, gpio.HIGH)... |
7c5f361c86a1a5ff0fecf7332736912aa9bc7fde | Hong-ying-Young/leecode | /No104_Maximum_Depth_of_Binary_Tree.py | 387 | 3.796875 | 4 | #No. 104 Maximum Depth of Binary Tree
#Given a binary tree, find its maximum depth.
#The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
class Solution:
def maxDepth(self, root):
if root == None:
return 0
else:
re... |
b9e9101f97b0d8613010bb918d7ab9b74616b075 | Hong-ying-Young/leecode | /python_Basics.py | 3,601 | 3.828125 | 4 | #Python Algorithms book, chapter 2: Basics
#python Basics, try out thoese short basics and get a sense of python
num = [4,6,8,1]
num.append(1)
num.insert(0,1)
s = 0
for x in num:
s +=x
square = [x**x for x in num]
s=0
for x in num:
for y in num:
s += x*y
seq1 = [[0, 1], [2], [3, 4, 5]]
s=0
for seq2 in seq1:
f... |
3909185c401c36d2fafb5a96c24f51448b7b98b0 | iosdouble/pythonlearn | /day10/s2.py | 3,654 | 3.953125 | 4 | # number = 9%2;
# print(number)
#
# number = 9//2;
# print(number)
# name = "我是大帅哥"
# if "我大" in name:
# print("OK")
# else:
# print("ERROR")
# while True:
# print("死循环")
#
# if 1==1:
# print("1")
# else:
# print("2")
# v = 1==1;
# print(type(v))
# v = 1==1;
# print(v);
# v = 1>1;
# print(v);
... |
90654dcbdee6d81c7489a964caf5731ac26b0e8e | iosdouble/pythonlearn | /day13/s1.py | 1,723 | 3.734375 | 4 | # 字典
#dict
# info={
# "k1":"v1",
# "k2":"v2"
# }
#
# info={
# "k1":12,
# "k2":True,
# "k3":[11,22,33,{"kk1":"vv1"}],
# "k4":(11,22,33,44)
# }
# info ={
# 1:"nihui",
# "k1":"nihui",
# True:"123",
# # [12,13]:123,
# ("tet","123"):"nihui",
# {12,23}:"th"
# }
# print(info... |
1ada85c8a7552f7728f9a383a048540165788f34 | cafrinko/Skills-Assessment-Week-2-Object-Orientation | /assessment.py | 5,214 | 4.625 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
Encapsulation - instead of separating the function from the data in separate
files, modules, etc, you can define and organically create the data with a
class.
Ab... |
4cf4cf445a8e011f0c56433114372a5d72d4402b | gabriellpr/estudo-python-ads-1semestre | /4AlgoritmosOrdenacao/bubblesort.py | 309 | 3.96875 | 4 | """
"""
def executar_bubble_sort(lista):
n = len(lista)
3 for i in range(n-1):
4 for j in range(n-1):
5 if lista[j] > lista[j + 1]:
6 lista[j], lista[j + 1] = lista[j + 1], lista[j]
7 return lista
8
9 lista = [10, 8, 7, 3, 2, 1]
10 executar_bubble_sort(lista) |
25f5109ff3e8198822e04ea7ec144af02e6ef439 | gabriellpr/estudo-python-ads-1semestre | /3AlgoritmosDeBusca/algoritmoBuscaBinaria.py | 1,047 | 3.921875 | 4 | """
1 - Encontra o item no meio da sequência.
2 - Se o valor procurado for igual ao item do meio, a busca encerra.
3 - Se não, verifica se o valor buscado é maior ou menor que o valor central.
4 - Se for maior, então a busca acontecerá na metade superior da sequência (a inferior é descartada), se não for maior, a busca... |
7a73b4cc0bf28dbdd9d93081954f5772494e1725 | gabriellpr/estudo-python-ads-1semestre | /3AlgoritmosDeBusca/buscaSequencial1.py | 247 | 3.609375 | 4 | def BuscaSeq(list, item):
pos=0
x=False
while pos<len(list) and not x:
if list[pos] == item:
return True
else:
pos = pos + 1
return x
lista = [5, 6, 8, 12, 1, 5, 7]
print(BuscaSeq(lista, 8))
print(BuscaSeq(lista, 13)) |
638f9d69e62340cc7adf7ebe239f1d98b4bb8f0f | busFred/csce330_presentation_demo | /src/python/demo00.py | 111 | 3.59375 | 4 | # %%
# a is int
a = 0
print(a)
print(type(a))
# a all of a sudden becomes float
a = 3.0
print(a)
print(type(a)) |
ac9b5679a18ab8e12c2325c8a0cae4737db51870 | junchen1992/InitialJ | /DSA/LeetCode/daily_practice/113_Path_Sum_II.py | 1,229 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
... |
21b24a78843e5498d515820b2a07ebd990be1bd6 | junchen1992/InitialJ | /DSA/coding_interview/q_03.py | 786 | 3.765625 | 4 | class MaxQueue:
def __init__(self):
self.data = []
self.max_vals = []
def max_value(self) -> int:
if not self.data:
return -1
return self.max_vals[-1]
def push_back(self, value: int) -> None:
self.data.append(value)
if not self.max_vals or self.... |
d45ce899b5044c040dccc216db9b87e61cde0dcc | Osman808/lab_3 | /individual.py | 192 | 3.625 | 4 | s = int(input("Площадь (кв. км.): "))
n = int(input("Кол-во жителей: "))
print("Плотность населения: " + str(s/n) + " человек на кв. км.") |
f7c446009fd894559fb63c4a6b928ad6fc4a61e1 | eddy-v/flotsam-and-jetsam | /checkaba.py | 1,114 | 4.21875 | 4 | # eddy@eddyvasile.us
# how to check validity of bank routing number (aba)
# multiply the first 8 digits with the sequence 3, 7, 1, 3, 7, 1, 3, 7 and add the results
# the largest multiple of 10 of the sum calculated above must be equal to the 9th digit (checkDigit)
import math
def validateABA(aba):
checkDigit=int(a... |
992259ece1e690d91cdb5a885eb3c4620add315a | NicolasAG/ML-assignment1 | /a1q1e.py | 1,569 | 3.5625 | 4 | import numpy as np
###
# QUESTION 1.e)
# - Re-format data by feeding each of the input variables (except the bias term) through a set of Gaussian basis functions:
# - use 5 univariate basis functions with means evenly spaced between -10 and 10 and variance sigma in [0.1, 0.5, 1, 5, 10]
###
def reformat(x_train, x_te... |
ce5a7713292c4d77ee2f518732d43dfe0bcbb34b | stemaan/isapykrk6 | /Day3/examples/zadanie2.py | 615 | 3.75 | 4 | # podaj ocenę na podstawie progu procentowego
# 5 od 90%, 4+ od 80, 4 od 70, 3+ od 60, 3 od 50
# przyjmij dane od uzytkownika
# zweryfikuj dane - czy liczby
dane = str(input("Podaj procent: "))
if dane.isdigit():
procent = int(dane)
if procent >= 90:
print("5")
elif procent >= 80:
... |
fa6d293a6cb040a7d0443a8872c6a3b19bd55829 | stemaan/isapykrk6 | /Day5/source_code/lists_example_2.py | 299 | 3.890625 | 4 | start = int(input('Podaj start: '))
end = int(input('Podaj stop: '))
my_list = list(range(start, end))
value = int(input('Podaj poszukiwana wartosc: '))
for element in my_list:
if element == value:
print('Znaleziono:', value)
break
else:
print('Kiedy to sie wyswietli?')
|
a2c1245b22470a37489c9bb8b1a003a34d065820 | stemaan/isapykrk6 | /Day4/source_code/range_examples.py | 877 | 3.90625 | 4 | # # przyklad nr 1, gdzie podana jest tylko wartosc koncowa
# for element in range(10):
# print(element)
#
# # przyklad nr 2, podana wartosc poczatkowa i koncowa
# for element in range(15, 46):
# print(element)
#
# #przyklad nr 3, wartosc poczatkowa, koncowa i krok
# for element in range(1, 101, 7):
# print(... |
781aa2de15852088036a41ec30f1ef08e0177d9d | stemaan/isapykrk6 | /Day12/source_code/accounting.py | 2,181 | 3.734375 | 4 | class Account:
def __init__(self, holder_name, bank):
self.account_holder = holder_name
self.bank = bank
self.funds = 0
def withdraw(self, amount):
if self.funds >= amount:
self.funds -= amount
return True
else:
return False
def d... |
afec289772d8a97e78662901a6babf55bb6dbce9 | stemaan/isapykrk6 | /Day2/source_code/if_statements.py | 325 | 3.765625 | 4 | # %
user_input = input('Podaj liczbe calkowita: ')
# user_input = int(user_input)
if user_input.isdigit():
input_as_int = int(user_input)
if input_as_int % 2:
print(input_as_int, 'jest nieparzyste')
else:
print(input_as_int, 'jest parzyste')
else:
print('podales niepoprawne dane wejscio... |
aba82deaa05c0f38a4acf815f2bc4f8728c97c1e | stemaan/isapykrk6 | /Day5/source_code/lists_example_3.py | 340 | 3.75 | 4 | coins = [5, 2, 1, 0.5, 0.2, 0.1]
coins_amounts = [0, 0, 0, 0, 0, 0]
to_pay = 12.5
cash = 20
rest = cash - to_pay
for index, coin in enumerate(coins):
if coin <= rest:
quantity = rest // coin
coins_amounts[index] = quantity
# rest = rest - quantity * coin
rest -= quantity * coin
pr... |
4e52edf6e11e83b9ea1c92f067dc05f7e4aedb51 | ZemiosLemon/HillelPythonBasic | /homework_07/task_2_v2.py | 1,215 | 4.0625 | 4 | temp = float(input('Введите температуру:'))
type_temp = input('Введите тип температуры:')
def celsius(temperature: float, type_temperature: str) -> float:
if type_temperature == 'C':
return temperature
elif type_temperature == 'K':
return temperature + 273.15
elif type_temperature == 'F':
... |
cadf7d318027c123f13ec9f79d4d2de19d05ef0f | ZemiosLemon/HillelPythonBasic | /homework_03/Ex_4_List_of_Six.py | 126 | 3.640625 | 4 | list_of_six = list(range(100, 197, 6))
for num in list_of_six:
if num % 5 == 0 and num < 151:
print(num, end=' ')
|
dd5cf8f5c166339f617cb0265a33f6af3b1004a5 | ZemiosLemon/HillelPythonBasic | /homework_06/task_2.py | 348 | 3.96875 | 4 | import time
def countdown(func):
def return_time():
num = 3
while num:
print(num)
time.sleep(1)
num -= 1
result = func()
return result
return return_time
@countdown
def what_time_is_it_now() -> str:
return time.strftime('%H:%M')
p... |
49e8a2646939bf9f4138bf50ccda0df0b67751e0 | ZemiosLemon/HillelPythonBasic | /homework_03/Ex_6_Chess.py | 1,163 | 3.890625 | 4 | start_position = input('Введите координаты клетки\n'
'(a-z,1-8 без пробелов, например: a1 или h8):\n'
'Введите начальную позицию фигуры:\n')
final_position = input('Введите конечную позицию фигуры:\n')
start_position_latter = int(ord(list(start_position)[0]))
start_position... |
795aaaa131a4ffcb3e75cecf2dfbd303f5a33a0a | ZemiosLemon/HillelPythonBasic | /homework_13/task_1.py | 2,145 | 3.625 | 4 | import csv
class Product:
def __init__(self, product_name, product_type, price):
self.prod_name = product_name
self.prod_type = product_type
self.price = price
def __str__(self):
return f'{self.prod_type}: {self.prod_name} - price:{self.price}.'
def __repr__(self):
... |
27598a4f5fdaedc3fff355c892e049784bd1641c | reybahl/PythonPrograms | /linkedlist.py | 527 | 4 | 4 | class LinkedList():
def __init__(self):
self.headnode = None
class Node():
def __init__(self, value):
self.value = value
self.next = None
def insert(self, value):
if self.headnode is None:
self.headnode = self.Node(value)
sel... |
cb6a17303130bdfe3f9dc9571ffcdf1ee4f1586e | reybahl/PythonPrograms | /animate.py | 119 | 3.59375 | 4 | import time
text = "Hello how are you?"
for char in text:
print(char, end="")
time.sleep(0.05)
x=1
print() |
9e15b96aff82accea201860297ff40389e5b2510 | elenerandarill/python_games | /Throne_game/Throne_game7.py | 4,097 | 3.75 | 4 | import turtle
import random
my_wn = turtle.Screen()
my_pen = turtle.Turtle() #my turtle
my_pen.speed(0)
my_wn.bgcolor("grey")
my_wn.tracer(0, 10)
class Game():
g1x = 50 #start pos
g1y = 50
g2x = -50 #start pos
g2y = -50
dx = 0 #wektor przesuniecia
dy = 10
d2x = 0
d2y = -10
speed = 300 #tyle milisekund ... |
399181b6fb66c1cc5126cc9afc647296b4eee295 | elenerandarill/python_games | /Snake/my_turtle4.py | 2,771 | 3.84375 | 4 | import turtle
import random
my_wn = turtle.Screen()
my_pen = turtle.Turtle()
my_wn.tracer(False)
my_pen.speed(10)
my_wn.delay(0)
class Game():
sx = 0
sy = 0
dx = 0
dy = 10
gx = random.randint(-10, 10) * 10
gy = random.randint(-10, 10) * 10
b_size = 20
snake = [(0, 0)]
game = Game()
def teleport(x,y):
my_... |
c9adb214a3bf6222833dc1cf9ca4f1801f4ba5cf | gmzyyzgh/Learn_Python3_the_hard_way | /ex18.py | 493 | 3.75 | 4 | # this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# ok that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
def print_one(arg1):
print(f"arg1:{arg1}")
... |
acf9b029ab99b1b978b2e6a41fc2c7feb9cb4f36 | gdiman/flask | /sql/sqljoin.py | 710 | 4.15625 | 4 | import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
try:
c.execute("""CREATE TABLE regions (city TEXT, region TEXT)""")
except:
print("Exists!")
cities = [
('San Franciso', 'Far West'),
('New York City', 'Northeast'),
('Chicago', 'Northcentral'),
('Phoenix', 'Southwest'),
... |
01549308c7264d298d0873667542f36cc3bc6911 | Riham-Ali/100days | /week2.py | 1,030 | 3.90625 | 4 | # day-6-
A = int('4')
B = float(5)
C = str(19.5)
print(A)
print(B)
print(C)
# day-7-
print('this with a single quotation')
print("this with a double quotation")
D = "Hi"
print(D)
E = """ this example
for multiline """
print(E)
C = "hello"
print(C[3])
print(C[1:4])
# day-8-
F = " Hello , World "... |
53e2583030bfa808c69fce79b688b3bf18892252 | abdulrafaykhan/Bus-Booking-Bot | /modules/yes_or_no.py | 810 | 3.96875 | 4 | ##########################################
##########################################
## ##
## This is just a module for taking a ##
## yes or no input from the user. ##
## No other function, just a yes or ##
## no :P ##
## ... |
c01242268f879054027f31316ef2d8a99e9620e6 | richardsheridan/foobar | /zombie_monitoring.py | 2,301 | 3.8125 | 4 | def answer(intervals):
''' Produce the total time that is covered by at least one interval
in a list of intervals.
The intervals are (start, end) pairs where start < end.
'''
# sorting the list uncovers redundancy
# reversed sort facilitates efficient popping of earliest-startin... |
d917c2ae2d8a4f62a219a03df7605081735fa50c | mihaip/adventofcode | /2019/06/part1.py | 648 | 3.671875 | 4 | #!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.txt") as f:
for line in f... |
83f8a00faa521690d10bbdaad856ddf588a1806b | mihaip/adventofcode | /2019/04/part1.py | 466 | 3.671875 | 4 | #!/usr/local/bin/python3
min = 347312
max = 805915
count = 0
for combination in range(min, max + 1):
digits = [int(d) for d in str(combination)]
has_double = False
increasing = True
for i in range(5):
if digits[i] == digits[i + 1]:
has_double = True
elif digits[i] > digits[... |
f3aebbf31abee010e1efb3c6e05e5af4132126de | mihaip/adventofcode | /2019/11/part1.py | 6,827 | 3.515625 | 4 | #!/usr/local/bin/python3
import collections
IN = 1
OUT = 2
with open("input.txt") as f:
program = [int(word) for word in f.readline().split(",")]
class VM(object):
def __init__(self, program, input=None):
self.program = collections.defaultdict(int)
for i, instruction in enumerate(program.cop... |
6d0cbca4dd45b4afab401d6c30400488b5ae8c3a | mihaip/adventofcode | /2019/14/part1.py | 2,245 | 3.828125 | 4 | #!/usr/local/bin/python3
import collections
reactions_by_output = {}
class Reaction:
def __init__(self, inputs, output_name, output_quantity):
self.inputs = inputs
self.output_name = output_name
self.output_quantity = output_quantity
def parse_str(s):
quantity_str, name = s.split(" ")... |
a7afc6a09121307a8d661cdf97feb4fb14a71e3b | mihaip/adventofcode | /2018/01/part2.py | 428 | 3.6875 | 4 | #!/usr/local/bin/python3
with open("input.txt") as f:
changes = [int(l) for l in f.readlines()]
saw_duplicate = False
seen_frequencies = set()
frequency = 0
while True:
for change in changes:
frequency += change
if frequency in seen_frequencies:
print(frequency)
saw_dup... |
fa345eb686ef7ee41f4dee311a604fae0879238d | victoriapenasmiro/proyectopython | /comprobarEmpateVertical.py | 1,377 | 3.5625 | 4 | def comprobarEmpateVertical(jugador):
global fin
contador_espacios=0
contador_ficha=0
while (contador_espacios+contador_ficha==4):
for i in range(len(lista_tablero)):#verificacion vertical
if i==0 or i==1 or i==2:#si i es 3,4 o 5 hay 4 huecos para ganar
for j in range... |
5b8b193df1b15f4630eeedda9395fea7196f7c76 | rodhapansari/PyProject | /number gueesing project.py | 833 | 4.03125 | 4 | import random
def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)
for _ in range(rounds):
guess = input("Enter an inte... |
04d3bf2e069c52d636fe81e2b68ad8edbc5a9586 | LogicStarDust/my_learn_for_python | /computer_vision/homework_2_mnist_tf/tf_mnist.py | 4,879 | 3.5625 | 4 | # coding: utf-8
# # Logistic Regression with TensorFlow
# By Ivan
# ## 0. Imports
# In[ ]:
import time
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# ## 1. Download MNIST dataset
# In[ ]:
# Using Tensorflow's default tools to fetch data, this... |
084af05776f7ae422b74a67e08f68046b7acbd8c | AhirraoShubham/ML-with-Python | /variables.py | 1,771 | 4.65625 | 5 | ##########################################################################
# Variabels in Python
#
# * Variables are used to store information to be referenced and
# manipulated in computer program. They also provide a way of labeling
# data with a decriptive name, so our progams can be understood more
# cle... |
aad5b38105a67db87150ec39cd51c2d42e8fddfc | eszepto/tictactoe_cli | /tictactoe_oop.py | 3,466 | 3.84375 | 4 | from __future__ import print_function
from IPython.display import clear_output
import random
class TicTacToe:
board = [" "] * 10
player = 0
def display_board(self):
for i in range(9):
print(" %s "%(str(self.board[i])),end="")
if(i in [2,5,8]):
print()
... |
8a1e7a0478d6451e5496e7d6e6b117ebb508bdab | atferver/BIOL5153 | /parseGFF.py | 940 | 3.5625 | 4 | #! /usr/bin/env python3
import csv
import argparse
from Bio import SeqIO
# inputs: 1) GFF file, 2)corresponding genome sequence
# create an argument parser object
parser = argparse.ArgumentParser(description='This script will parse GFF file and extract each feature from the genome')
# add positional arguments
parse... |
5c9f2f739c5b9e48daf3eccbd0d0aed9ae88c9ed | CagriDK/Signal-Prediction | /Regression.py | 6,922 | 3.828125 | 4 | """
First we checked the idea of the system which we need to predict the signal strength
with using distance feature and this is more likely seems like an supervised Learning:
Regression problem.
In this type of problem we can choose between speed or accuracy for the method we will use.
For speed we can choose Decisio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.