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 |
|---|---|---|---|---|---|---|
ca96436efca7c0b171625683d122951b8ba4b833 | YashMeh/HCI-Project | /image_operations.py | 739 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 28 19:25:56 2018
@author: yash
"""
import numpy as np
import cv2
#Usually people perform analysis on grayscale image
#then export the result on coloured image
img=cv2.imread('tejas.jpg',cv2.IMREAD_COLOR)
###Referencing a particular pixel
px=img[... |
37940d1160cc5a78595a58676589eca91d3d7fdc | AlanaMina/CodeInPlace2020 | /Assignment1/TripleKarel.py | 1,268 | 4.28125 | 4 | from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample w... |
3da0242e36ee059b8471559ae4491a435b90e234 | AlanaMina/CodeInPlace2020 | /Assignment5/word_guess.py | 2,881 | 4.1875 | 4 | """
File: word_guess.py
-------------------
Fill in this comment.
"""
import random
LEXICON_FILE = "Lexicon.txt" # File to read word list from
INITIAL_GUESSES = 8 # Initial number of guesses player starts with
def play_game(secret_word):
"""
Add your code (remember to delete the "pass" below)
"""
... |
fbd5d7800af041a8e69102609f84bba5d8b6c63f | AlanaMina/CodeInPlace2020 | /Assignment5/credit_card_total.py | 1,036 | 3.984375 | 4 | """
File: credit_card_total.py
--------------------------
This program totals up a credit card bill based on
how much was spent at each store on the bill.
"""
INPUT_FILE = 'bill1.txt'
def main():
"""
Add your code (remember to delete the "pass" below)
"""
dict = {}
name = ""
num = ""
wit... |
46f4a78818e9ff35199700107f193ce49587569c | SpiralBL0CK/Programming-solutions-from-codeforces | /asu_3_cup.py | 230 | 3.53125 | 4 | x = int(raw_input())
y = int(raw_input())
command = raw_input()
for i in command:
if i == 'U':
y = y + 1
if i == 'D':
y = y -1
if i == 'L':
x = x-1
if i == 'R':
x = x+1
print(x,y)
|
6033405dc1913c086c43a57b8ed06e70a481a8c1 | mrahmed0116/Practise1 | /sortbasedonvalues.py | 429 | 4.28125 | 4 | '''
Sort dictionary based on keys
'''
dict1= {'x':4,'y':3,'z':2,'a':1,'b':1, 'c':0}
s1 = sorted(dict1.keys())
print(s1)
output={}
for s in s1:
for i in dict1:
if i == s:
output[i] = dict1[i]
print(output)
'''
Sort dictionary based on values
'''
s2 = sorted(dict1.values())
print(s2)
output1={}... |
6946898e4785bc0dca8b2f0e4284a9bd51b4b24d | ckid/LeetCode | /AddTwo.py | 1,405 | 3.921875 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
@staticmethod
def addTwoNumbers( l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
datareturn = ListNode(0)
cur... |
0857fa157a39ff743884d00466b885fadb02e17d | cduhaney1/ubiquitous-fiesta | /prompt_user.py | 154 | 3.953125 | 4 | print("hello")
user_input = int(input("Give me a number! "))
result = int (user_input) * int(user_input)
print (result)
name = input ('What is your name') |
bb91dc84c3520303d5ccc1dfc29615d6a85a3dd9 | cduhaney1/ubiquitous-fiesta | /Hello.py | 70 | 3.625 | 4 | user_name = input('What is your name?')
print('hello, %s' %user_name)
|
cf7a0769baca60bd80d8fe5c6e1af2eb07c1273c | li-MacBook-Pro/li | /static/Mac/play/调用/累加/累加.py | 401 | 3.890625 | 4 | def sum_numbers(num):
if num == 1:
return 1
temp = sum_numbers(num - 1)
return num + temp
print(sum_numbers(3))
def sum_numbers(num):
if num == 3:
return 3
temp = sum_numbers(num + 1)
return num + temp
print(sum_numbers(1))
def my_sum(i):
if i < 0:
raise ValueError
elif i <= 1:
re... |
51adf901afcf2ff68f2b82d4c28c19e8074bd715 | li-MacBook-Pro/li | /static/Mac/play/调用/器/迭代器.py | 1,016 | 4.09375 | 4 | # 可迭代对象
# 可通过for…in 进行遍历的数据类型包括 list,tuple, dict, set, str;以及生成器generator,及带yield的生成器函数
# 这些可直接作用于for循环的对象统称为可迭代对象:Iterable
# from collections import Iterable
# print(isinstance('abc',Iterable))
# print(isinstance((x for x in range(10)),Iterable))
# print(isinstance(100,Iterable))
# 迭代器
# Iterator,无限大数据流,内部定义__next__... |
347c26e4de6383598ea3a21ca20ff027713b3e8f | li-MacBook-Pro/li | /static/Mac/play/调用/二分树/小偷偷钱.py | 1,101 | 3.828125 | 4 | #定义一个二叉房子类,包括当前节点、左节点和右节点
class House():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
#定义一个函数,返回根节点最后的偷值和不偷值较大那个
def rob(root):
a = helper(root)
print(max(a[0], a[1]))
#定义一个辅助函数,递归算出根节点偷值和不偷值
def helper(root):
if(root == None):
return... |
5612738c34956713a04a55923765d1718fdcd934 | li-MacBook-Pro/li | /static/Mac/play/调用/长方体/changfangxing.py | 2,251 | 3.8125 | 4 | #第一种
import random
class cube:
def define(self):
global x,y,z
x=self.x = random.randint(1,5)
y=self.y = random.randint(1,5)
z=self.z = random.randint(1,5)
return x,y,z
def Cuboid_Area(self):
global Area
Area=(2*(self.x * self.y + self.x * self.z + self.y *... |
e93fdc9cee0fa4388f92877ceaee733624c3900a | tveebot/organizer | /tveebot_organizer/matcher.py | 1,919 | 3.75 | 4 | import re
from tveebot_organizer.dataclasses import Episode, TVShow
class Matcher:
"""
The Matcher is one of the sub-components of the *Organizer*. An organizer is associated with a
single matcher. The matcher is used to match an episode name, using some pre-defined format,
to an episode object.
... |
46a808d1c32ca99e7672ed19389480728ee21b6b | CooperNederhood/spring2018_project | /data_processing/model0.py | 1,663 | 3.734375 | 4 | from keras import layers
from keras import models
'''
From Chapter 5, create a simple CNN model from scratch
'''
model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(128, 128, 3)))
model.add(layers.MaxPooling2D( (2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
... |
662afa79e92cac1dab547c962292fa42efca4e57 | MrCordero/testgithub2 | /ejercicio_7.py | 410 | 4 | 4 | #Contador de numeros
cont_num = 0
#Contador de vueltas
cont_vueltas = 0
#Acumulador de numeros
acu_num = 0
while(True):
num = int(input("Ingrese numero : "))
#Suma
acu_num += num
cont_vueltas = cont_vueltas + 1}
prom = acu_num / cont_vueltas
if(cont_vueltas == -1):
break
p... |
712b6de931dcfe6fcdce13e16c4edf5e16b7fc94 | KontextuellEnergivisualisering/Priority-Calculations | /Algorithms.py | 1,521 | 3.6875 | 4 | import time
# Calculates the minimum power in the combined list with old data ('points') and new data ('lastHourData')
def min(points, lastHourData):
min = -1
# Check if points are from database
if not isinstance(points[0][1], int):
# If points come from database, loop through every point until a p... |
a2942eea4bbccc41c49f0a87b00324f23b93fb40 | pisa-engine/pisa | /script/bp/generate_config.py | 1,394 | 3.703125 | 4 | #!/usr/bin/env python
import argparse
import sys
def generate_recursive(lvl, first, last, out):
if last - first < 2:
return
left_range = (first, first + (last - first) // 2)
right_range = (left_range[1], last)
print(lvl, 20, left_range[0], left_range[1],
right_range[0], right_range[1... |
7b16f62b068e3f5de037781f496881846d025fa3 | XiaoyuZhou1106/CSC108-Introduction-to-Computer-Programming | /a3/tweets.py | 14,057 | 3.953125 | 4 | """Assignment 3: Tweet Analysis"""
from typing import List, Dict, TextIO, Tuple
HASH_SYMBOL = '#'
MENTION_SYMBOL = '@'
URL_START = 'http'
# Order of data in the file
FILE_DATE_INDEX = 0
FILE_LOCATION_INDEX = 1
FILE_SOURCE_INDEX = 2
FILE_FAVOURITE_INDEX = 3
FILE_RETWEET_INDEX = 4
# Order of data in a tweet tuple
TWE... |
a2c11f8cdd280ce12b1d56ad3745fff0b19f456c | osamaawadallah/AlgorithmicToolbox | /week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.py | 1,028 | 3.875 | 4 | # python3
from random import randrange
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise... |
e7a2aeeaece89d8091827c210ba333275b31c263 | Xudoge/PythonStudy | /Python/BaseKnowledge/inherit/inherit.py | 433 | 3.71875 | 4 |
class A:
def __init__(self,value,name):
self.value=value
self.name=name
print("这是一个父类方法")
def hihi():
print(self.name)
class B(A):
def __init__(self,value,name):
#A.__init__(self,value=1,name="a")
super().__init__(value,name)
print("这是一个子类类方法1"... |
15a0cde2ab30d5ed1d4eaf04cac7af6d6f3faf31 | bjmyers/prtp | /Combination.py | 15,540 | 3.75 | 4 | import numpy as np
from prtp.Rays import Rays
import astropy.units as u
import prtp.transformationsf as trans
class Combination:
'''
Class Combination:
A combination object is a group of several components that the user wants to
group together
When Rays are traced to a Combination Object, they... |
692e4f7a9df5800599d2492b20a732b65e7e7c60 | keerthz/luminardjango | /Luminarpython/collections/listdemo/prgmforsearching.py | 232 | 3.84375 | 4 | lst=[10,12,13,14,15]
element=int(input("enter the element for search"))
flg=0
for i in lst:
if(i==element):
flg=1
break
else:
flg=0
if(flg==1):
print("element found")
else:
print("not found") |
ff64e2214caf2f674365a5cacd003b9afe7b1d0d | keerthz/luminardjango | /Luminarpython/languagefundamentals/sumof6.py | 87 | 4.0625 | 4 | num=int(input("enter the num"))
sum=0
for i in range(0,num+1):
sum=sum+i
print(sum) |
6ed8de9512fcf7f26e356d1e8def736dfe7e5051 | keerthz/luminardjango | /Luminarpython/languagefundamentals/secondlargest.py | 353 | 4.1875 | 4 | num1=int(input("enter num1"))
num2=int(input("enter num2"))
num3=int(input("enter num3"))
if((num2>num1) & (num1>num3)):
print("num1 is largest",num1)
elif((num3>num2) & (num2>num1)):
print("num2 is largest",num2)
elif((num1>num3) & (num3>num2)):
print("num3 is largest",num3)
elif((num1==num2) & (num2==num3... |
8c9824e79adaffc0d82b70faf2fbf5cd8b5fc11e | keerthz/luminardjango | /Luminarpython/collections/listdemo/pattern.py | 170 | 3.65625 | 4 | lst=[3,5,8]#output[13,11,8]
#3+5+8=16
#16-3=13
#16-5=11
#16-8=8
output=[]
total=sum(lst)
for item in lst:
num=total-item#16-3=13
output.append(num)
print(output)
|
b83ddc757ec963dbe30a142285ed68655fbc93b5 | keerthz/luminardjango | /Luminarpython/languagefundamentals/vowels.py | 167 | 3.734375 | 4 | string=input("enter a word")
list=["a","e","i","o","u"]
count=0
for i in list:
if(i in string):
count+=1
print(count,i)
else:
break
|
009248f4014b9f8ce04bf4701c45e2ec4ecd46c2 | keerthz/luminardjango | /Luminarpython/oops/polymorphism/empl1.py | 484 | 3.859375 | 4 | class employee:
def __init__(self,id,name,salary):
self.id=id
self.name=name
self.salary=int(salary)
#def printValues(self):
# print(self.id)
# print(self.name)
# print(self.salary)
obj=employee(1001,"ayay",25000)
obj2=employee(1002,"arun",30000)
obj3=employee(1003... |
832f2cb1ee730068f1865f9c0655e38472a9fab0 | keerthz/luminardjango | /Luminarpython/regularexpression/quantifiers.py | 251 | 4 | 4 | import re
#pattern="a+"
#pattern="a*"
#pattern="a?"
#pattern="a{2}"
pattern="a{2,3}"
matcher=re.finditer(pattern,"aabaaaabbaaaaaabaaabb")
count=0
for match in matcher:
print(match.start())
print(match.group())
count+=1
print("count",count) |
d15700beffef5f6f30597d848d67c736c9673182 | Yuji-Takai/switchIn | /website/switchinweb/modules/utility.py | 708 | 4.03125 | 4 | from datetime import datetime
""" converts the string extracted from text to date
:param date: string representing the date
:returns: datetime for the string
"""
def convertDateFormat(date):
if (len(date) == 8):
month = date[0:2]
day = date[3:5]
year = date[6:len(date)]
yea... |
4f06365db3bb2fdfa5e6c62e722e03f1ca916a7b | twillis209/algorithmsAndDataStructures | /arraySearchAndSort/insertionSort/insertionSort.py | 422 | 4.125 | 4 | def insertionSort(lst):
"""
Executes insertion sort on input.
Parameters
----------
lst : list
List to sort.
Returns
-------
List.
"""
if not lst:
return lst
sortedLst = lst[:]
i = 1
while i < len(sortedLst):
j = i - 1
while j >= 0 and sortedLst[j] > sortedLst[j+1]:
temp = sortedLst[... |
18290f2b984ca71bdbc4c147ec052ba17e246ad0 | twillis209/algorithmsAndDataStructures | /arraySearchAndSort/timsort/timsort.py | 1,029 | 4.25 | 4 | import pythonCode.algorithmsAndDataStructures.arraySearchAndSort.insertionSort as insertionSort
def timsort():
pass
def reverseDescendingRuns(lst):
"""
Reverses order of descending runs in list.
Modifies list in place.
Parameters
---------
lst : list
List to sort.
Returns
-------
List.
"""
runStack... |
e47c62abda3b57756034c72860b47ebeef96f4dc | luoyun/LuoYunCloud | /lyweb/lib/SQLAlchemy-0.8.2/examples/association/__init__.py | 922 | 3.515625 | 4 | """
Examples illustrating the usage of the "association object" pattern,
where an intermediary class mediates the relationship between two
classes that are associated in a many-to-many pattern.
This directory includes the following examples:
* basic_association.py - illustrate a many-to-many relationship between an
... |
227ffd15cf6fd13ac446c356d96c0761e1932f4d | ruteshr/python | /string_palindraome.py | 243 | 4.15625 | 4 | #String is Palindrome
string=list(str(input("enter a String :")))
a=""
for i in string:
a=i+a
if("".join(string)==a):
print('{} is palindrome'.format("".join(string)) )
else:
print('{} is not palindrome'.format("".join(string)) )
|
a7947ff5b7e90e1996753e5c05c0fbe3ff0f582d | ruteshr/python | /pattern_diamond.py | 2,697 | 3.75 | 4 | n=5
for i in range(n):
for j in range(n-i-1):
print(end=" ")
for j in range(2*i+1):
print("*",end="")
print()
for i in range(1,n):#for i in range(n)-->for 10 line
for j in range(i):
print(end=" ")
for j in range(2*n-(2*i+1)):
print("*",end="")
print()
'''
OUTPUT:
*
***
*****
******... |
df296049dd2cd2d136f15afdf3d8f1ebec49871d | wulianer/LeetCode_Solution | /062_Unique_Paths.py | 902 | 4.25 | 4 | """
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Ab... |
4e88fc3f4a0a63fbc41f29b2dc27ae7690190719 | wulianer/LeetCode_Solution | /025_Reverse_Nodes_in_k_Group.py | 2,023 | 3.96875 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in... |
43e7ef8659037e36c7e61b0e3c5b3c6766e1bda4 | wulianer/LeetCode_Solution | /128_Longest_Consecutive_Sequence.py | 772 | 3.9375 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
class Solution(object):
def longes... |
4b367305f53d32a184f9260916827e26a6896c42 | wulianer/LeetCode_Solution | /041_First_Missing_Positive.py | 1,112 | 3.796875 | 4 | """
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3, --> lower: 2, upper: 2
and [3,4,-1,1] return 2. --> lower: 1, upper: 3
nums: 1 5 4 2 3 6 8
lower: 1 1 1 2 3
upper: 1 5 4 4
Your algorithm should run in O(n) time and uses constant space.
"""
class... |
70f0a5a7ee0fd7b6d75193be8bde2978db720f7d | wulianer/LeetCode_Solution | /076_Minimum_Window_Substring.py | 1,001 | 4.09375 | 4 | """
Given a string S and a string T, find the minimum window in S which will
contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there are multipl... |
81437f168b3fa1c08f38fffa627e0567263482be | wulianer/LeetCode_Solution | /050_Pow(x, n).py | 532 | 3.78125 | 4 | """
Implement pow(x, n).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
"""
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
i... |
d7eb6774c273c399562026528da66b35a05d89f7 | wulianer/LeetCode_Solution | /078_Subsets.py | 688 | 3.984375 | 4 | """
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
class Solution(object):
def subsets(self, n... |
b6783ba65e1f3c7e793e8eb36ad695ba2007015b | vishwanathvishu95/Python-games | /madlibs.generator.py | 613 | 3.953125 | 4 | #prompts for a series of input
programmer = input("Someones Name: ")
company = input("A Company Name: ")
language1 = input("A Programming Language: ")
hr = input("Someone else's Name: ")
language2 = input("Another Programming Language: ")
#printing the story with the given inputs
print("-----------------------... |
3af7d990e3433ff03e3a62368f454d627efe4c35 | Kezuo0605/Python | /Lesson1.py | 4,667 | 4.34375 | 4 | # 1.Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
number = 1205
word = "START"
print(f'Планируем начать обучение {number} {word} course Python')
number = int(input('Напишите, когда хотите начать курс в фор... |
4e72c806834109e6ac6810e7b6706af02b5a6f22 | tzmhuang/GaussianProcess | /GP_regression.py | 2,140 | 3.609375 | 4 | '''
based on: Machine learning -- Introduction to Gaussian Processes, Nando de Freitas
'''
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(seed = 1010)
n = 5
data_x = np.linspace(3,5,n).reshape(-1,1)
def kernel(a,b): #define kernel
sqr_dist = np.sum(a**2,1).reshape(-1,1)+ np.sum(b**2,1) - 2*n... |
d8e7568483e6583d0157bced6a93fd3672d67c34 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section1/intro.py | 174 | 3.703125 | 4 | from turtle import *
shape("turtle")
speed(0)
for i in range(300):
for j in range (4):
forward(200)
left(90)
right(7)
mainloop() |
55cab638287d2ff91e594c7e2111123ed2b4c4ac | shadowstep666/phamminhhoang-fundamental-c4e25 | /section3/homework_day3/turtle2.py | 300 | 3.8125 | 4 | from turtle import *
colors = [ 'red','blue','brown','yellow','gray']
for index , colour in enumerate(colors):
color(colour)
begin_fill()
for i in range(2):
forward(50)
left(90)
forward(100)
left(90)
forward(50)
end_fill()
mainloop() |
33eaa474c2cf5191c44e189987c0de0d1fef4bc1 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section3/menu.py | 679 | 3.78125 | 4 | # item1= " bun dau mam tom"
# item2="pho"
# item3="banh my"
# item4 = "lau"
# items = [] # empty list
# print(type(items))
# items = [ " bun dau"]
# print(items)
items = ["bun dau mam tom ", "pho","banh mi", "lau"]
# print(items)# print la mot loai read nhung chi doc ket qua
# items.append("banh ny") #... |
c68bf1082ec0684aef2788848101c283c88cb508 | shadowstep666/phamminhhoang-fundamental-c4e25 | /section2/homeworkDay2/n_start.py | 88 | 3.515625 | 4 | xs = "* "
n = int(input("nhap vao n :" ))
for i in range(n):
print(xs, end=" ")
|
4d09e92399cffd253ec767fa52db207f28521079 | ChihaoFeng/Leetcode | /20. Valid Parentheses.py | 541 | 3.796875 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for p in s:
if p == '(':
stack.append(')')
elif p == '[':
stack.append(']')
elif p == '{':
stack.appe... |
273c9140794b49bd00f600c924355d478b4580b3 | ChihaoFeng/Leetcode | /74. Search a 2D Matrix.py | 682 | 3.78125 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
x, y = len(matrix), len(matrix[0])
i, j = 0, x * y - 1
while i... |
62f5eec73b9300a69398ba171c6daa4444fbf416 | ChihaoFeng/Leetcode | /52. N-Queens II.py | 1,600 | 3.515625 | 4 | def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
def dfs(row):
if row == n:
self.ret += 1
return
for col in range(n):
if cols[col] or d1[col - row + n - 1] or d2[row + col]:
continue
cols[col] = d1[col - row ... |
520410658429bb33202f390ea275b2393e154f5e | ChihaoFeng/Leetcode | /9. Palindrome Number.py | 755 | 3.90625 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x and not x % 10):
return False
y = 0
while x > y:
y = y * 10 + x % 10
x //= 10
return x == y or x == y // 10
"""
we first ne... |
a0fc54a4a0ef4f59666707712ed0f16318e9f512 | ChihaoFeng/Leetcode | /37. Sudoku Solver.py | 1,824 | 3.703125 | 4 | class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def pre_process():
for i in range(9):
for j in range(9):
if board[i][j] == '.... |
078fe3fd6e966d82b68b0be61dd2ad73223a0b7f | ChihaoFeng/Leetcode | /103. Binary Tree Zigzag Level Order Traversal.py | 745 | 3.90625 | 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
... |
1fb90380a3e2c19219922cb9d46e2cf8aa520344 | ChihaoFeng/Leetcode | /69. Sqrt(x).py | 403 | 3.609375 | 4 | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
i, j = 0, x
while i <= j:
m = (i + j) // 2
if m * m == x:
return m
elif m * m < x:
i = m + 1
else:
j =... |
2c231997492be2f5c53c01e6e3469e7d735e0af3 | JuliandroR/Atividades-IFMS | /python/bin4dec.py | 243 | 3.65625 | 4 | entrada = input("A sequência em binário, please")
a = int(entrada[:7], 2)
b = int(entrada[8:15], 2)
c = int(entrada[16:23], 2)
d = int(entrada[24:31], 2)
print("A sequẽncia informada convertida é: {} . {} . {} . {}".format(a, b, c, d)) |
c9364b322396ef9d1c140ba5c8e6c184acf6a41c | chenchals/interview_prep | /amazon/copy_linked_list_with_random_pointer.py | 882 | 3.703125 | 4 | # Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: Rando... |
db082c1d53e70879e26a3d2d1cc9d08f85e38d2c | chenchals/interview_prep | /algorithms/tree_traversal.py | 1,857 | 3.625 | 4 | import math
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def PreOrderTraversal(root, cb):
cb(root.value, end=' ')
if root.left is not None:
PreOrderTraversal(root.left, cb)
if root.right is not None:
PreOrderTraversal(root.right, cb)
return cb
def... |
a2aba7dc8d55e05aa6b7ce31cbc456bed61e946b | chenchals/interview_prep | /amazon/intersection_of_linked_list.py | 1,258 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or no... |
33ce2afb61fca3b33bd2439f9b12d1d09f41436f | chenchals/interview_prep | /linked_list/merge_two_sorted_linked_list.py | 1,303 | 3.96875 | 4 | class Node(object):
def __init__(self):
self.__v = None
self.next = None
def next(self, Node):
self.next = Node
@property
def v(self):
return self.__v
@v.setter
def v(self, v):
self.__v = v
def build_linked_list_from_list(li):
head = Node()
hea... |
6f6010cd508110c20469513733cac735f6313694 | chenchals/interview_prep | /algorithms/dijkstra.py | 462 | 3.8125 | 4 | class Vertex(object):
def __init__(self, x, distance):
# 2-dim tuple (x, y)
self.key = x
# distance[(1,2)] = distance -> coord to cost dict
self.distance = distance
self.parent = None
def Dijkstra(graph, start, end):
# set of visited coord
for i in range(len(graph)):
for j in range(len(graph[0])):
... |
f75ae19fcc5b53606004ffe42edd406d0264c7ae | Catherine1000/PythonExercises | /AverageGrades.py | 560 | 4.0625 | 4 | bio_score = float(input("Enter your biology score: "))
chem_score = float(input("Enter your chemistry score: "))
physics_score = float(input("Enter your physics score: "))
if bio_score < 40:
print("Fail")
elif chem_score < 40:
print("Fail")
elif physics_score < 40:
print("Fail")
else:
score = (bio_sco... |
fb10a2f3e98da33e6f5cbbe1f1d08f41dc452855 | vincenttchang90/think-python | /chapter_1/chapter_1_exercises.py | 1,190 | 4.375 | 4 | #chapter 1 exercises
#1-1
# In a print statement, what happens if you leave out one of the parentheses, or both?
## print 'hello') or print('hello' return errors
# If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
## print('hello) or print(hello') return errors wh... |
4919605e133d383f8a7c848efa3eaf1405a58a96 | bharatanand/B.Tech-CSE-Y2 | /applied-statistics/python-revisited/intermediate-concepts/list-comprehension/gen-n-even-nos.py | 91 | 3.796875 | 4 | n = int(input("Display even numbers below: "))
ls = [i for i in range(0, n, 2)]
print(ls) |
526886cff12e987b705d2443cd0bc1741a552f36 | bharatanand/B.Tech-CSE-Y2 | /applied-statistics/lab/experiment-3/version1.py | 955 | 4.28125 | 4 | # Code by Desh Iyer
# TODO
# [X] - Generate a random sample with mean = 5, std. dev. = 2.
# [X] - Plot the distribution.
# [X] - Give the summary statistics
import numpy as np
import matplotlib.pyplot as plt
import random
# Input number of samples
numberSamples = int(input("Enter number of samples in the sample lis... |
5ad337bd7a7d4d10ee0fec4a1e2e1f8806039911 | sjrathod/learning-python | /crackingTheCodingInterview/arrayAndStrings/oneAway.py | 844 | 3.65625 | 4 | #!/usr/bin/python
def oneAway(str1, str2):
i = 0
j = 0
edited = False
diff = len(str1) - len(str2)
if diff < -1 or diff > 1:
return False
s1 = str1 if (len(str1) > len(str2)) else str2
s2 = str2 if (len(str1) > len(str2)) else str1
if diff == 0:
while(i < len(s1) and j < len(s2))... |
1f45cddab2c6b1ac0f4c7b4b24415815c8c24df1 | sjrathod/learning-python | /crackingTheCodingInterview/linkedLists/partition.py | 952 | 3.828125 | 4 | #! /usr/bin/python
from basicLinkedList import *
import pdb
def partition(current, k):
beforeLL = LinkedList()
afterLL = LinkedList()
while current:
if current.data < k :
beforeLL.insertAtTail(current.data)
else:
afterLL.insertAtTail(current.data)
current = current.nex... |
fa57f7fed7a1b413b04d7f7e331794660b15a2bd | haema5/python_level_1 | /hw01_easy.py | 2,447 | 3.9375 | 4 | __author__ = 'Пашков Игорь Владимирович'
import random
# Задача-1: Дано произвольное целое число (число заранее неизвестно).
# Вывести поочередно цифры исходного числа (порядок вывода цифр неважен).
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании решите задачу с при... |
b8f822a44c8b35e6d1e40a6c04c3afdac0989219 | LBHukan/Clima | /clima.py | 1,176 | 3.671875 | 4 | import requests
import json
name_city = str(input("Digite Sua Cidade: "))
name_state = str(input("Digite Seu Estado Abreviado: "))
def ID(cidade, estado):
city = str(cidade)
state = str(estado)
requisicao = requests.get("https://api.hgbrasil.com/weather?key=40acff95&city_name="+ name_city +","+ name_state... |
c5d76587c717609f3a2f3da3a9136f92b3fee367 | bmgarness/school_projects | /lab2_bmg74.py | 755 | 4.125 | 4 | seconds = int(input('Enter number of seconds to convert: '))
output = '{} day(s), {} hour(s), {} minute(s), and {} second(s).'
secs_in_min = 60
secs_in_hour = secs_in_min * 60 # 60 minutes per hour
secs_in_day = secs_in_hour * 24 # 24 hours per day
days = 0
hours = 0
minutes = 0
if seconds >= secs_in_day:
days ... |
285c7fe0c7af03f251dd0b45dfc1d2cb0d66fced | B7504C/ichw | /pyassign4/wcount.py | 1,823 | 3.75 | 4 | #!/usr/bin/env python3
"""wcount.py: count words from an Internet file.
__author__ = "Bai Yuchen"
__pkuid__ = "1800011798"
__email__ = "1800011798@pku.edu.cn"
"""
import sys
from urllib.request import urlopen
def wcount(lines, topn):
"""count words from lines of text string, then sort by their counts
in ... |
9e905216e5e04d4b1b21d0f30afa26115da84044 | ayeshaghoshal/learn-python-the-hard-way | /ex29.py | 1,607 | 4.03125 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 29 - What if"
people = 200
cats = 45
dogs = 100
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The w... |
ec32d18f39290dc135c190a49764ae585be27ccd | ayeshaghoshal/learn-python-the-hard-way | /ex14.py | 1,252 | 4.5 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 14 - Prompting and Passing"
# Using the 'argv' and 'raw_input' commands together to ask the user something specific
# 'sys' module to import the argument from
from sys import argv
# define the number of arguments that need to be defined on the command line
script, ... |
8c787b221b005f2f997f7d927a008d3ff9fa1514 | ayeshaghoshal/learn-python-the-hard-way | /ex19.py | 2,520 | 4.40625 | 4 | # -*- coding: utf-8 -*-
print "EXERCISE 19 - Functions and Variables"
# defining the function that commands the following strings to be printed out
# there are 2 parameters that have to be defined in brackets
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# use of the parameters is the same method ... |
a4757d33b940e4cfcb580a0d18cb9f7117384929 | giuschil/Python-Essentials | /sorting algorithms/bubblesort.py | 1,214 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 11:36:50 2019
@author: giuse
"""
def swap(a,b):
tmp = b
b = a
a = tmp
return a,b
def random_array():
import random
n= int(input("How many numbers you want to generate? "))
m= int(input("Number Max for choice? "))
... |
77bac9d5c187722aba0582983c074af89176dbfa | giuschil/Python-Essentials | /Hello.py | 251 | 3.9375 | 4 | "Write the numbers from 1 to 10"
lista = []
for i in range(0,11):
lista.append(i)
print("il numero è: ",i)
print("La lista è: ",lista)
print("/n")
for i in lista:
print("il numero nella lista è: ",lista[i])
|
c5ee299d12ea8ad5e50aec5dcc1fcde6a5b789cb | juletats/LabsNMPy | /lab3.2.py | 5,264 | 3.875 | 4 | def NullMatrix(n):
"""Создание нулевой матрицы"""
nullM = [0] * (n);
for i in range(n):
nullM[i] = [0] * (n)
return nullM
def MultiplyMM(matrix1, matrix2):
"""Умножение матрицы на матрицу"""
n = len(matrix1);
result = NullMatrix(n);
for i in range(n):
for j in range(n... |
cce19d5079460040e6174142d487e9fac7a22adf | jamesfeng1994/ORIE5270 | /HW2/tree/tree_print.py | 2,454 | 4.15625 | 4 | class Tree(object):
def __init__(self, root):
self.root = root
def get_depth(self, current, n):
"""
This function is to get the depth of the tree using recursion
parameters:
current: current tree node
n: current level of the tree
return: the dept... |
6ecb1094565598ff59b837c26a0af6ff7d802067 | EnriqueDev01/be_semana_01 | /Reto_01.py | 723 | 3.765625 | 4 | '''
BIENVENIDA
Para este reto tendremos que hacer lo siguiente:
1) Ingresar un nombre y su edad.
2) Si es menor de edad que indique que dependiendo de la hora (si es mas de las 6pm) debe ir a dormir y si no hacer la tarea.
3) Si es mayor de edad que indique que no esta obligado a hacer nada.
'''
import datetime as dt
... |
5dd1ad88e8daabdd120c401431088fe8326d86ff | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-10_Debugging/personalnotes.py | 3,054 | 3.671875 | 4 | #! python3
import logging
logging.basicConfig(filename=r'C:\delicious\logfile.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
# logging.disable(logging.CRITICAL) # Comment this out to disable logging messages to be diplayed
# I'll be writing the author's suggestion and notes in this co... |
dab565b2e260dadc9fb14543fee9df41c84c904a | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-9_Organizing-Files/renamepictures.py | 1,491 | 3.8125 | 4 | #! python3
# renamepictures.py - The code will go through a directory tree and will rename all the pictures
# based on it's creation date.
# For now the code will just identify '.jpg' files. Any other formats will remain unchanged, although
# their filenames will be written in the 'rejected.txt' file. By doing this, y... |
180595fd0f78376e8b9d3da6af980876a743fcda | Vandeilsonln/Python_Automate_Boring_Stuff_Exercises | /Chapter-9_Organizing-Files/selective_copy.py | 1,268 | 4.125 | 4 | #! python3
# selective_copy.py - Once given a folder path, the program will walk through the folder tree
# and will copy a specific type of file (e.g. .txt or .pdf). They will be copied to a new folder.
import os, shutil
def copy_files(folderPath, destinyPath, extension):
"""
Copy files from 'folderPath' to ... |
26d42973cb952c3c2af0cddba3d4772c34b2d788 | Liam-Hearty/ICS3U-Unit2-03-Python | /circumference_finder.py | 493 | 4.625 | 5 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: September 2019
# This program will calculate the circumference of a determined circle radius.
import constants
def main():
# this function will calculate the circumference
# input
radius = int(input("Enter the radius of circle (mm): "))
... |
8c22a3529adcc775f3178ebe0c2a500e2ba98d74 | Snehitkale/pythonprogramminglab | /lab_function.py | 658 | 4.09375 | 4 | def armn(x): #define a function
sum=0 #then assign variables for values
t=x #using while loop assign a condition
while(t>0): #using a variable d assign a condition of input num... |
748da75ce2505e4ea7c3a099ce23016174eced4c | Ziqi-Li/Cracking-the-code-for-interview | /Ch4. Trees and Graphs /4.2.py | 1,148 | 3.921875 | 4 | '''
Ziqi Li
8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.
'''
from collections import deque
def BFS(g,start,... |
df06470e115da8ebaa8e2e9435c68d4595dec9e4 | Ziqi-Li/Cracking-the-code-for-interview | /Ch2. Linked List/2.3.py | 902 | 4.0625 | 4 | '''
Ziqi Li
2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node 'c' from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
'''
class node(object):
def __init__(self,data,ne... |
e579216c6a8e871f956dcfab2c3902e182a75017 | Ziqi-Li/Cracking-the-code-for-interview | /Ch8. Recursion/8.2.py | 1,230 | 4.09375 | 4 | '''
Ziqi Li
8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.
'''
def robotWalk(m, n):
if m == 1 or n == 1:
... |
28fb6e72d2529ad57810ed6545e84db41f4a4471 | Ziqi-Li/Cracking-the-code-for-interview | /Ch1. Arrays and Strings/1.6.py | 730 | 3.890625 | 4 | '''
Ziqi Li
1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
'''
def rotate(img,n):
for i in range (0,n):
for j in range (i+1,n):
img[i][j], img[j][i] = img[j][i], img[i][j]
... |
b478e1623d95f0cc868f41ba52824423a8e2fc93 | petef4/payg | /footnote.py | 1,054 | 3.65625 | 4 | from textwrap import fill
def definitions(footnotes):
"""Convert JSON footnotes into a format suitable for Jinja2.
In JSON a footnote is a list.
The first element is the id.
Other elements are either string or list, concatenated to make the text.
A list is a grade (e.g. poor) followed by a string... |
0d36514e5d069335e7e00b9f1ce6f88635624b65 | eleven2021/xor | /xor.py | 544 | 3.6875 | 4 | def crypto_text_to_hex(src_text, key):
xor_code = key
while len(src_text) > len(xor_code):
xor_code += key
return "".join([chr(ord(data) ^ ord(code))
for (data, code) in zip(src_text, xor_code)]).encode().hex()
def decrypto_hex_to_text(hex_text, key):
crypt_data = bytes.from... |
57d65fa197e6ad4672a2f5cc5cfc049c9de3af0b | ronyu21/data-analysis-app | /src/DataAnalysisApp.py | 5,434 | 3.96875 | 4 | from typing import List
import matplotlib.pyplot as plt
from src.FileHandling import load_csv_to_2d_list, save_data_to_csv
if __name__ == "__main__":
# load from csv file and save as a list
data_list = load_csv_to_2d_list('./resource/Emissions.csv')
# transform the list to become dictionary
# with ... |
eac543f52b8e273aaa54942592edc2e1d0680759 | dudu9999/Tkinter_Projects_dudu9999 | /03 - muda label Funcionou/main.py | 366 | 3.671875 | 4 | from tkinter import *
def bt_click():
print("Botao clicado")
lb['text'] = 'Funcionou'
janela = Tk()
janela.title("Janela Principal")
janela["bg"] = "purple"
lb = Label(janela, text="Texto Label")
lb.place(x=120, y=100)
bt = Button(janela, width=20, text='OK', command=bt_click )
bt.place(x=80, y=150)
janel... |
2b37622cd4de1d5beb32d3e3734ebd704f5582e2 | bipins867/Python-Server-Clinet-Remote-Controlling | /Encode.py | 1,412 | 3.53125 | 4 | #Encoder
from collections import OrderedDict
from re import sub
def encode(text):
'''
Doctest:
>>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')
'12W1B12W3B24W1B14W'
'''
return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1),
... |
32f56e3193bb85c6b23213a1e09332aef8f5ac17 | bjrubinstein/PyHSPF | /examples/evapotranspiration/etexample01.py | 9,200 | 3.65625 | 4 | # etexample01.py
#
# David J. Lampert (djlampert@gmail.com)
#
# last updated: 03/15/2015
#
# this example shows how to use the ETCalculator class to compute daily
# reference evapotranspiration from the other time series after using the
# ClimateProcessor class to extract and aggregate the climate data from the
# Worl... |
c9497ad2a313d2664ee99f371138776ab980f1f4 | hugovk/wotdbot | /wotdbot.py | 3,644 | 3.609375 | 4 | #!/usr/bin/env python
"""
Pick a random [Finnish] word from a word list,
open its Wiktionary page and tweet it
"""
import argparse
import random
import sys
import webbrowser
from urllib.parse import quote
import yaml # pip install pyyaml
from twitter import OAuth, Twitter # pip install twitter
def load_yaml(filena... |
cfbb448e37e667067f98ffcfbf1c7972b807f85e | xiawq1/leetcode-c- | /leetcode/stack.py | 4,902 | 3.5625 | 4 | #coding:gbk
#ջźƥ䣬ųջжջǷΪգΪΪTrueΪFalse.
class Solution:
def isValid(self, s):
stack = [] #ڴſ
mapping = {')':'(', '}':'{', ']':'['} #ɢбƥ
for char in s:
if char in mapping:
if len(stack) != 0:
tmp = stack.pop()
if mapping[char]... |
8f8b1f239de525c01abfce4e556caed1f12a9300 | JensMellberg/Neural-Networks-Exercise-2 | /Exercise2.py | 6,083 | 3.65625 | 4 |
# coding: utf-8
# # Tensorflow Tutorial (MNIST with one hidden layer)
# ## Neural Networks (TU Graz 2018)
# (Adapted from the documentation of tensorflow, find more at: www.tensorflow.org)
#
#
# Improving the MNIST tutorial by adding one hidden layer
#
# <img src="hidden_layer.png" style="width: 200px;" />
# In[1]:
... |
71fecce0bba7ea6072ac11c0c7e82466480c5015 | EdgeLord836/229 | /Labs_Mat_Vec_etc/Lab3_229.py | 490 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 15:48:46 2017
@author: Sam
"""
print('P1')
s = [1,2,3,4]
def cubes(arg): return [x**3 for x in s if x % 2 == 0]
print(cubes(s))
print('\nP2')
dct = {0:'A', 1:'B', 2:'C'}
keylist = [1,2,0]
def dict2list(dct, keylist): return [dct[i] for i in keylist]
print(dict2l... |
d97f49825c56c71f1f6864c46840bbe7f71237f8 | OldSchoolWeaver/WeatherGeneratorApp | /Run.py | 2,725 | 3.609375 | 4 | #!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import numpy as np
import datetime
import random
import sys
from Aux import *
from WeatherSimulator import *
from WeatherDataGenerator import *
def RunSimulation():
"""
This function will create an instance of a simulation and will save the outp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.