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 |
|---|---|---|---|---|---|---|
b546685565b7aa025a045a0516f342b1eb824ff4 | lgdean/python-code-test | /unit.py | 720 | 3.59375 | 4 | import unittest
from program import *
class TestVariousThings(unittest.TestCase):
def test_parse_gender(self):
self.assertEqual("Androgynous", parse_gender("Androgynous"))
self.assertEqual("Bigender", parse_gender("bigender")) # might as well
def test_parse_gender_special_cases(self):
... |
2207dca766e3c8c20822aebbcddafe8f444f6f03 | DanniiOs/Exercims_python | /bob/bob.py | 378 | 3.671875 | 4 | def response(hey_bob):
hey_bob = hey_bob.strip()
if hey_bob.endswith("?") and hey_bob.isupper():
return "Calm down, I know what I'm doing!"
elif str.isupper(hey_bob):
return("Whoa, chill out!")
elif hey_bob.endswith("?"):
return "Sure."
elif hey_bob == "":
return ("Fi... |
a1e02f654caebbf7faab3a3e3e6435770cf4cdee | DanniiOs/Exercims_python | /acronym/acronym.py | 166 | 3.796875 | 4 | import re
def abbreviate(words):
words = re.sub(r"[^a-zA-Z' ]", " ", words.upper())
acronym = ''.join(word[0] for word in words.split())
return acronym
|
f18f46b10616daaef7ee4a3fc9fc6c0a13edf0ed | Ragama11/logicalOperaators | /builtInMethod.py | 367 | 3.609375 | 4 | students = [
{ "name": "Dossy",
"age" : 24,
"gender": "m",},
{ "name": "Derrick",
"age" : 24,
"gender": "m",},
{ "name": "Brian",
"age" : 24,
"gender": "m",},
{ "name": "John",
"age" : 24,
"gender": "m",},
]
for student in students:
print(studen... |
90dd5da3a0922f5dcbdfc6a61e0b358f0ed7a707 | mjester93/CodeWars | /python/Duplicate Encoder.py | 350 | 3.640625 | 4 | def duplicate_encode(word):
final_array = []
count = {}
for s in word:
if s.lower() in count:
count[s.lower()] += 1
else:
count[s.lower()] = 1
for s in word:
if count[s.lower()] > 1:
final_array.append(')')
else:
final_array.append('(')
ret... |
ff05e64c12fcd101e675421bd90b2a538386e8b5 | sandyjswl/advent-of-code-2019 | /day_2.py | 4,442 | 3.65625 | 4 | import copy
def read_input():
with open('day_5.txt', 'r') as f:
content = f.readlines()
# print(content)
inputs = content[0].split(",")
inputs = [int(x) for x in inputs]
return inputs
# TRUE = IMMEDIATE_MODE
def replace_numbers(inputs_array, noun, verb):
inputs_array[1] = noun
in... |
2b9d4c7bd4d01cd5c5547dd5b0bd45a206afe19f | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e16_transform/src/transform.py | 393 | 4.125 | 4 | #!/usr/bin/env python3
def transform(s1, s2):
#convert to list of integers
s1_int = map(int, s1.split())
s2_int = map(int, s2.split())
#multiplicate elements and add to one list
zipped = zip(s1_int, s2_int)
L = []
for i in zipped:
L.append(i[0]*i[1])
return L
def main():
pr... |
effb29545027f8813bf3a29e8eae06d52088fc58 | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e15_two_dice_comprehension/src/two_dice_comprehension.py | 220 | 3.53125 | 4 | #!/usr/bin/env python3
def main():
L = [(x,y) for x in range(1,7)
for y in range(1,7)
if x + y == 5]
for i in L:
print(i)
if __name__ == "__main__":
main()
|
1380cb2dbe1054d06ae066d7f65b75d7e6be5fcf | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part04-e01_cities/src/cities.py | 451 | 4.03125 | 4 | #!/usr/bin/env python3
import pandas as pd
def cities():
populations = [643272, 279044, 231853, 223027, 201810]
areas = [715.48, 528.03, 689.59, 240.35, 3817.52]
columns = ["Population", "Total area"]
indices = ["Helsinki", "Espoo", "Tampere", "Vantaa", "Oulu"]
df = pd.DataFrame(list(zip(populatio... |
b5095427c93bd8c91831c7f18475c9641ed62796 | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-summer-2019/part03-e04_matrix_power/src/matrix_power.py | 462 | 3.859375 | 4 | #!/usr/bin/env python3
import numpy as np
from functools import reduce
def multiply_arrays(a, b):
return a@b
def matrix_power(a, n):
if n == 0:
return np.eye(a.shape[0])
if n < 0:
a = np.linalg.inv(a)
n = -1*n
A = reduce(multiply_arrays, (a for i in range(n)))
return A
de... |
5386e9c955c7aa7fbf4e3b8daa3c57706f421605 | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e06_triple_square/src/triple_square.py | 331 | 4 | 4 | #!/usr/bin/env python3
def main():
for i in range(1,11):
trip = triple(i)
squa = square(i)
if squa > trip:
break;
print("triple({})=={} square({})=={}".format(i, trip, i, squa))
def triple(x):
return x*3
def square(x):
return x**2
if __name__ == "__main__":
... |
324a22534f107a044d7b9d7b40bfd1fd19624df3 | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e13_reverse_dictionary/src/reverse_dictionary.py | 462 | 4.375 | 4 | #!/usr/bin/env python3
def reverse_dictionary(d):
reversed = {}
for key in d.keys():
for fin in d[key]:
if fin in reversed.keys():
reversed[fin].append(key)
else:
reversed[fin] = [key]
return reversed
def main():
d={'move': ['liikuttaa'],... |
a1b6e6ab495cfbdfd3e81416936626c7c70345fa | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-spring-2019-OLD/part01-e09_merge/src/merge.py | 595 | 4.09375 | 4 | #!/usr/bin/env python3
def merge(L1, L2):
list1 = L1.copy()
list2 = L2.copy()
merged_list = []
while True:
if (not list1) and (not list2):
break;
elif not list1:
merged_list.append(list2.pop(0))
elif not list2:
merged_list.append(list1.pop(0))... |
e49ca6b4cb697897d6a500808d7516e488ffc52c | shidocchi/primes | /primes.py | 1,770 | 3.515625 | 4 | import array
from itertools import count, islice
__version__ = '0.4.1'
class Prime:
"""class about prime numbers"""
def __init__(self, level=200, typecode='L'):
self.level = level
self.typecode = typecode
self.init_sieve()
def init_sieve(self):
"""initial state of sieve"""
self.table = [... |
05fa83c55f48e53717764a83e3d4678f5b095bdb | ParulProgrammingHub/assignment-1-strangerraj | /a1p6.py | 107 | 3.984375 | 4 | x=int(input('Enter the value of Base:'))
y=float(input('Enter the value of Power:'))
print 'Result =',x**y
|
a29f8fc4b160b71e5a42b5a7619c8cceec8873d5 | YiddishKop/python_simple_study | /Networking1_tcpServer.py | 3,003 | 3.71875 | 4 | # Networking
# Python3 Advanced #5
# What is Net Code?
# Networking is a huge field, so we will stick to high level concepts that are important for programming.
# Networking is the concept of two programs communicating across a network. Whether it be from client-client, client-server or even client to itself.
# Client... |
9fe2a9bfef5f0fb489691cff8686ace67753d5bd | YiddishKop/python_simple_study | /generator/generator2.py | 1,581 | 4.03125 | 4 | """
本节讲解 generator --- 生成器函数, 用于产生一列东西的函数
生成器函数的定义必须满足如下规则:
1. 必须 yield 其实元素(起点)
2. 必须 yield 每次步进叠加后的结果(足记)
3. 一般情况下都包含一个 while 循环, 用于叠加步进, yield 叠加结果
生成器的使用:
1. 一般使用 next(生成器函数引用) 来产生下一个'脚印'
2. 可以使用 [i for i in 生成器] 来得到所有'足记'并转换成 list
"""
# 例一
# 我们经常使用的一个生成器是, 整数顺序生成器 range(start, stop, step)
for _ in range(0, 9, 1)... |
17f8beb9bb16ad49e62d0f4637d99862c3169bc5 | YiddishKop/python_simple_study | /OO/interface_absmethods_overriding.py | 2,335 | 4.3125 | 4 | """
python 想使用接口或是抽象类, 要比 java 多做一些工作,
需要引入 abc 包中的 ABCMeta 函数和 abstractmethod 标签
"""
# [知识点]
# 想使用接口/抽象类等定义,必须引入这个包
from abc import ABCMeta, abstractmethod
# Interface
class Shape(object):
# [知识点]
# 当你希望把这个类声明为接口or抽象类,并且其中的两个函数必须被
# 子类实现的时候,就必须在该类中
# 1. 声明 __metaclass__ 字段为 ABCMeta
# 2. 抽象函数头添加... |
77b495b6217fb32c63053693529e00e292f418b8 | SjorsVanGelderen/Graduation | /python_3/data_structures/linked_list.py | 1,309 | 3.9375 | 4 | """Linked list data structure
Copyright 2016, Sjors van Gelderen
"""
# Empty list
class Empty:
def __init__(self):
self.is_empty = True
# List segment
class Segment:
def __init__(self, _value, _tail):
self.value = _value
self.tail = _tail
self.is_empty = False
# Full lis... |
a1b1b2983bf4721f26de6b1cf85468509703bc46 | SjorsVanGelderen/Graduation | /python_3/features/classes.py | 1,010 | 4.125 | 4 | """Classes example
Copyright 2016, Sjors van Gelderen
"""
from enum import Enum
# Enumeration for different book editions
class Edition(Enum):
hardcover = 0
paperback = 1
# Simple class for a book
class Book:
def __init__(self, _title, _author, _edition):
self.title = _title
self.author =... |
5e3ddff55f3f21d6c53e6d29d81f44dbdb72f7df | SjorsVanGelderen/Graduation | /python_3/features/higher_order_functions.py | 573 | 3.890625 | 4 | """Higher order functions with lambdas
Copyright 2016, Sjors van Gelderen
"""
list_words = ["Game", "Genie", "By", "Galoob"]
list_numbers = [1, 2, 3, 4]
def custom_iter(function, collection):
for element in collection:
function(element)
def custom_map(function, collection):
for index, element in enum... |
2ca32f96b6019a806d9d90f41b258ac3670ba683 | SjorsVanGelderen/Graduation | /python_3/algorithms/dijkstra.py | 3,871 | 4.375 | 4 | """Dijkstra's algorithm example
Finds shortest paths from a given vertex
to all other vertices in a graph
Copyright 2016, Sjors van Gelderen
"""
from math import inf
from random import randrange, sample
# Edge connected to a node in a graph
class Edge:
def __init__(self, target_id, distance):
self.targ... |
4af21ec2eca63219a96c2ff85eda9932b2a1bbba | pipjiang/Python-CommonCode | /python算法/8.5如何进行快速排序.py | 1,149 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 10:14:03 2020
@author: Administrator
"""
"""
快速排序:取一个key,然后对后面的数据分成两部分,左半部分都比key小,右半部分都比key大.
"""
def QuickSort(seq , left , right):
# 对seq序列从left到right排序
if left >= right:
return seq
key = seq[left]
low = left # 记录下left的初始值.
... |
18813336a43f58ebeb33c4f589fd32e69ff347e3 | pipjiang/Python-CommonCode | /python算法/8.4如何进行归并排序.py | 1,085 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 21:23:57 2020
@author: Administrator
"""
"""
归并排序:将数组分成两部分,分别对左右两部分进行排序,然后将排序好的两个子序列合并即可.
"""
def MergeSort(seq , start , end):
# 对seq进行排序,start和end分别是左闭右开
if start >= end - 1:
return seq
mid = int((end + start) / 2)
seq = Merg... |
a1c2aaccf0f9070509910d7ed6b5df910d36295e | pipjiang/Python-CommonCode | /python算法/11如何在只给定单链表中某个结点的指针的情况下删除该节点.py | 1,241 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 13:29:51 2019
@author: wenbin
"""
"""
假设给定链表1->2->3->4->5->6->7中指向第5个元素的指针,要求把结点5删掉,删除后链表变为1->2->3->4->6->7
"""
class LNode:
def __init__(self , x = 0 , y = None):
self.Data = x
self.Next = y
def ConstructLL(k):
Head = LNode(... |
978e2d0ad2a11d4ffe89fb7ab2ed0c9e4b7ef58a | pipjiang/Python-CommonCode | /python算法/3.6如何把二叉树转换为双向链表.py | 3,792 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 4 11:11:47 2020
@author: Administrator
"""
"""
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表.要求不能创建任何新的结点,只能调整结点的指向.
比如下述的这棵树:
4
2 6
1 3 5 7
transfer to the doubly linked list like the following:
1-2-3-4-5-6-7
"""
class BiTNode:
# the... |
21839e3fb20eef061ddd2e69e80defc8e5898e22 | pipjiang/Python-CommonCode | /python算法/7.5如何等概率地从大小为n的数组中选取m个整数.py | 599 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 20:11:35 2020
@author: Administrator
"""
"""
随机地从大小为n的数组中选取m个整数,要求每个元素被选中的概率相等.
"""
import random
def GetmEle(Num , n , m):
GetNum = []
for i in range(m):
index = random.randint(0 , n - i - 1)
GetNum.append(Num[index])
... |
fd816b1cd5162957ff16007cd03b8efc93956fa9 | pipjiang/Python-CommonCode | /python算法/6.1如何判断一个自然数是否是某个数的平方.py | 972 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 11:51:03 2020
@author: Administrator
"""
"""
设计一个算法,判断给定的一个数n是否是某个数的平方,不能使用开放运算.例如,16就满足条件,因为它是4的平方;
而15则不满足条件,因为不存在一个数使其平方值为15.
"""
def isSquare(n):
low = 1 ; high = n
while True:
tmp = int((low + high) / 2)
if tmp ** 2 == n:
... |
b3d02a2f21ec0e10d545acc6e70a6e726c9cf1c8 | pipjiang/Python-CommonCode | /python算法/6.8如何求有序数列的第1500个数的值.py | 1,032 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 09:34:31 2020
@author: Administrator
"""
"""
一个有序数列,序列中的每一个值都能被2或者3或者5所整除,1是这个序列的第一个元素.求第1500个值是多少.
"""
def Get1500Ele():
count = 1
number = 1
while True:
number += 1
if number % 2 == 0 or number % 3 == 0 or number % 5 == 0... |
059e916f822cc2368472a8cc87f4178d1c81ef8d | pipjiang/Python-CommonCode | /python算法/6.10如何求二进制数中1的个数.py | 532 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 10:25:20 2020
@author: Administrator
"""
"""
给定一个整数,输出这个整数的二进制表示中1的个数.例如,给定整数7,其二进制表示为111,因此输出结果为3.
"""
def count1(n):
obn = bin(n)[2:]
count = 0
for i in range(len(obn)):
if obn[i] == '1':
count += 1
return count
... |
a9c3673c63d727e41f744bb533a872a10757abcf | pipjiang/Python-CommonCode | /python算法/5.8如何判断字符串是否是整数.py | 654 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 09:57:01 2020
@author: Administrator
"""
"""
写一个方法,检查字符串是否是整数,如果是整数,那么返回其整数值.
"""
def JudInt(s):
if s[0] == '-':
s = s[1:]
if len(s) == 1:
if s >= '0' and s <= '9':
return True
else:
return Fal... |
9f8ed28bce6fdf514418b44717979cea634ab504 | pipjiang/Python-CommonCode | /python算法/4.6如何找出数组中第k小的数.py | 1,649 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 13:40:20 2020
@author: Administrator
"""
"""
给定一个整数数组,如何快速地求出该数组中第k小的数.假如数组为[4 , 0 , 1 , 0 , 2 , 3],那么第3小的元素是1.
引申问题,如何在O(N)时间复杂度内查找数组中前三名.
"""
def MergeSort(array , start , end):
# merge sort the array from index start to end. Note that start is inc... |
f89d83219974e7719cbf7ecc87940a3286279aca | pipjiang/Python-CommonCode | /python算法/5.11如何按照给定的字母序列对字符数组排序.py | 1,338 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 11:01:17 2020
@author: Administrator
"""
"""
已知字母序列[d,g,e,c,f,b,o,a],请实现一个方法,要求对输入的一组字符串input=["bed" , "dog" , "dear" , "eye"]
按照字母顺序排序并打印.本例的输出顺序为:dear,dog,eye,bed.
"""
def GetNum(seq , s):
lens = len(str(len(seq)))
for i in range(len(seq)):
... |
e9e60d0e90f1583b60192907103249a52848365c | pipjiang/Python-CommonCode | /python算法/2.6如何用两个栈模拟队列操作.py | 2,626 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 19:43:12 2019
@author: wenbin
"""
"""
题目要求用两个栈来模拟队列,假设使用栈A和栈B模拟队列Q,A为插入栈,B为弹出栈,以实现队列Q.
再假设A和B都为空,可以认为栈A提供入队列的功能,栈B提供出队列的功能.
要入队列,入栈A即可,而出队列则需要分两种情况考虑:
如果栈B不为空,则直接弹出栈B的数据.
如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据.
"""
class MyStack:
def __init__(self):
... |
7800b5bf847008e3dd64f62def5bb4ffab44d592 | pipjiang/Python-CommonCode | /python算法/2.2如何实现队列(数组实现).py | 1,485 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 19:34:48 2019
@author: wenbin
"""
"""
实现一个队列的数据结构,使其具有入队列,出队列,查看队列首尾元素,查看队列大小等功能
数组实现队列.
"""
class MyQueue:
def __init__(self):
self.arr = []
self.front = 0 #队尾头
self.rear = 0 #队尾尾
# 判断队列是否为空
def isEmpty(self):
... |
0bd65214debedc77a11060691d49d1a2a193f416 | wonjunknag/python | /.history/web_server/004_20200711111445.py | 474 | 3.515625 | 4 | import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Seoul_Metropolitan_Subway"
resp = requests.get(url)
html_src = resp.text
print(html_src)
# soup = BeautifulSoup(html_src, 'html.parser')
# print(type(soup))
# print("\n")
# print(soup.head)
# print("\n")
# print(soup.body)
# print("\n... |
f9984054ddd7b47df296b3e9b0e09c42dd86e488 | Cnoized/Euler-Project | /Problem6.py | 240 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 21:46:43 2021
@author: Cnoized
"""
Natural = range(1,101)
N = sum(Natural)
print(N)
print(N*N)
Mul = [a*a for a in Natural]
M = sum(Mul)
print(M)
print('Answer: ', N*N-M)
|
47bb70877e7b90fd45b40159313fa697313b6c55 | Cnoized/Euler-Project | /Problem29.py | 250 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 21:53:37 2021
@author: Cnoized
"""
#This is for problem 29
N = set()
print([j for j in range(2,100)])
for a in range(2,101):
for b in range(2,101):
N.add(a**b)
print(len(N)) |
8e59b160de229750e79538f2c0dbf2764697446c | Cnoized/Euler-Project | /Problem7.py | 504 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 21:53:37 2021
@author: Cnoized
"""
#This is for problem 7
# import numpy as np
import math
Primes = [2]
n=3
while len(Primes)<10001:
Root = math.sqrt(n)
Root = math.floor(Root)
print(Root)
Dead = 0
while Root>1:
... |
23c0d628cf4eb3c0b347c149a1c90e89eb159866 | BohdanHamulets/LearnPython3 | /ThinkPython/newfile1.py | 2,816 | 4.125 | 4 | #!/usr/bin/env python3
import time
import turtle
# some_text = input("What fo you want to print?\n")
def print_user(some_text):
if len(some_text) > 0:
print(">>> ", some_text)
else:
pass
# print_user(some_text)
def my_get_time():
seconds = time.time()
days = 60 * 60 * 24
days_... |
60374d17b1d539c831821e65c17edc422bc6b0de | BohdanHamulets/LearnPython3 | /Selenium_course/using_with_as.py | 388 | 3.515625 | 4 | #
# Using With and As Methods - this makes .close() function deprecated - no need for it
#
print("With As Write Start")
with open("firstFile.bla", 'w') as with_as_write_object:
with_as_write_object.write("This is and example of writing to file")
print()
print("With as Read Permission")
with open("firstFile.bla",... |
a0064e24f5aa652198dd63be6c8e39a0d99feb55 | BohdanHamulets/LearnPython3 | /Selenium_course/taxtax.py | 318 | 3.671875 | 4 | def calculate_tax(amount):
if int(amount) > 200000:
return amount * 0.25
elif int(amount) > 500000:
return int(amount) * 0.3
elif int(amount) > 1000000:
return int(amount) * 0.5
else:
return int(amount) * 0.1
print(calculate_tax(201000.99))
bla = "string"
bla.upper() |
2a1123c92388c6e23e6424f17bd70f197ed1aee9 | seufitele/dsa-avaliacao | /others/scrapper.py | 2,204 | 3.546875 | 4 | from bs4 import BeautifulSoup
import requests
import re
#codigo para fazer scraping em pagina web
#scraping do "https://onelinefun.com/"
def scrap():
fileToSave = "scrapper.txt"
arquivo = open("./scrapper.txt", "w", encoding="utf8")
for idx in range(1, 533):
url = "https://onelinefun.com/"... |
a8c0ce1a99fbfd5e6ac46c705c3d9f3b02e9fd65 | BrandynR/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 188 | 3.765625 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictonary):
new_dictonary = {}
for key in a_dictonary.keys():
new_dictonary[key] = (a_dictonary[key] * 2)
return (new_dictonary)
|
d1ec2bb93b00a2a33a9526a25a0694393f6ee7dd | BrandynR/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 563 | 3.578125 | 4 | #!/usr/bin/python3
"""
script that lists all cities from the database hbtn_0e_4_usa
"""
import MySQLdb
import sys
if __name__ == "__main__":
db = MySQLdb.connect(
host='localhost',
port=3306,
user=sys.argv[1],
passwd=sys.argv[2],
db=sys.argv[3]
)
cursor = db.cursor()... |
356587e9d90581e781241daa22a9771cd6f23606 | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/google_internship_query.py | 1,252 | 3.65625 | 4 | words = ["cat", "map", "bat", "man", "pen"]
queries = ["?at", "ma?", "?a?", "??n"]
class TrieNode:
def __init__(self):
self.children = {}
self.EndOfWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word):
cur = self.root
for c in w... |
93713686747dacbbb3bf30d9b9acc8b96129c726 | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/.idea/BFS.py | 618 | 3.734375 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def bfs(self, s):
q = [s]
visited = {}
visited[q[0]] = True
while len(q) != 0:
a =q.pop(0)
... |
8b1dcf73f931a4fe5a08b27c568057d5deb9cc77 | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/all_permutation.py | 394 | 3.5 | 4 | ini_str = "abc"
result = []
def permute(data, i, length):
if i == length:
result.append(''.join(data))
else:
for j in range(i, length):
# swap
data[i], data[j] = data[j], data[i]
permute(data, i + 1, length)
data[i], data[j] = data[j], data[i]
... |
96242ab69b51407c7703886111ac4672b458bd29 | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/sum_of_linkedlist.py | 1,029 | 3.5625 | 4 | class Solution:
def addOne(self, head):
# Returns new head of linked List.
def rev(head):
nex = None
prev = None
cur = head
while cur != None:
nex = cur.next
cur.next = prev
prev = cur
cu... |
863b8f19521135d0c83c8b7ba8c38a49db3ddfcb | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/car_coat.py | 400 | 3.84375 | 4 | class Car:
def __init__(self, s, u):
self.s = s
self.u = u
def __repr__(self):
m = 'Car with the maximum speed of ' + str(self.s) + " " + str(self.u)
return repr(m)
class Boat:
def __init__(self, s, ):
self.s = s
def __repr__(self):
m = 'Boat with the ... |
98a235f6b996e30852527066cc96422b48d26f2b | Yashwant94308/Yashwant94308-DSA-450-Question-in-Python | /DSA450/commom_elements.py | 539 | 3.609375 | 4 | A = [1, 1, 1, 20, 40, 80]
B = [1, 1, 20, 80, ]
C = [1, 1, 15, 20, 1, 70, 80, 120]
# A = [3, 3, 3]
# B = [3, 3, 3]
# C = [3, 3, 3]
n1 = len(A)
n2 = len(B)
n3 = len(C)
common = []
i = 0
j = 0
k = 0
while i < n1 and j < n2 and k < n3:
if A[i] == B[j] == C[k]:
if A[i] not in common:
common.append(A[... |
6a33fc24a8ebcbae955ef6e91e6cd5f6d918596c | ankit1765/Hangman-and-other-fundamental-programs | /HIghScores.py | 700 | 4.15625 | 4 | #This program asks is a high score displayer.
#It asks the user how many entries they would like to input
#and how many top scores it should display
scores = []
numentries = int(raw_input("How many entries would you like to Enter? "))
numtop = int(raw_input("How many top scores would you like to display? "))
count =... |
b8e80dfcc89b97613bc31c39345e814f8b81440f | jsgounot/PyPan | /pypan/pysegs/segments.py | 8,287 | 3.609375 | 4 | class Segment() :
def __init__(self, start, stop) :
self.start, self.stop = sorted((int(start), int(stop)))
def __str__(self) :
return "Segment(%i - %i)" %(self.start, self.stop)
def __repr__(self) :
return str(self)
def __contains__(self, value) :
return self.ove... |
0f0b014889d47d3fbe49cfbde41c91f2b1493d83 | cnc99/Collab | /sqdlist.py | 580 | 3.78125 | 4 |
def sqdlist(l):
i=0
while(i<len(l)):
l[i]=(l[i])**2
i=i+1
return l
#trace of a matrix
def trace(m):
if len(m)!= len(m[0]):
print('matrix is non-square')
else:
i=0
a=0
while i<len(m[0]):
a=a+m[i][i]
i=i+1
return a
#c... |
0a1368459c2fe122c165bafabc50c9aaf9c8570e | JahnaviKommaraju/DSP-LAB | /4.py | 1,631 | 4.03125 | 4 | # # a. by swapping the values in the SLL without relocating the nodes
class Node:
def __init__(self, data):
self.data = data
self.next = None
def print_list(t):
print('The SLL contains :')
while(t):
print(t.data)
t = t.next
def Reverse(t):
temp = head
... |
7237df4609187c95a2c8c640d267795964508fe8 | JahnaviKommaraju/DSP-LAB | /key.py | 262 | 3.78125 | 4 | key=int(input('enter key: '))
distance=int(input('enterdistance: '))
print('ENter elements: ')
l=[int(i) for i in input().split(' ')]
s=set(l)
a=list(s)
for i in range(len(a)-1):
if((key-distance==a[i]) or (key+distance==a[i])):
print(a[i])
|
24528fb0762bc05a322ad420bab99e86dcd250f3 | JahnaviKommaraju/DSP-LAB | /5.py | 507 | 3.875 | 4 | # 5. count the number of nodes in the list
class Node:
def __init__(self, data):
self.data = data
self.next = None
def print_list(t):
c=1
while(t!=None):
c+=1
t=t.next
print('The number of elemnts in the list are:',c-1)
head = None
n=int(input('No. of elem... |
6fdcff56d4e14ea93abf3e5e4367d5df4cadec41 | JahnaviKommaraju/DSP-LAB | /csd_lab_03_2.py | 867 | 3.703125 | 4 | # program for searching an elemnet in dll
# node creation of an DLL
class Node:
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
# function for print the nodes in a SLL
def search(t):
x=int(input("enter the element to be searched"))
c=1
... |
69ee06a3cb2ba8f7c20c488fe460374a2594ff60 | JahnaviKommaraju/DSP-LAB | /p7.py | 322 | 3.796875 | 4 | # Move all the negative elements to one side of the array
n=int(input('Enter no. of elements: '))
l=[]
for i in range(n):
l.append(int(input('enter element: ')))
for i in range(0,len(l)):
for j in range(i,len(l)) :
if l[i]>l[j]:
t=l[i]
l[i]=l[j]
l[j]=t
print(... |
23d2a282b25f267f6a0f4f61a69e1510a18d9fd8 | TyroneBulger97/DS-CW2 | /DS-CW2.py | 1,442 | 3.578125 | 4 | import twitter,json,csv
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
# setup a file to write to
csvfile = open('WWIII_twee... |
59809770870b0cd2b7f77a209987aa9d94900feb | DavidCichy/w05_si | /exercises.py | 3,244 | 4.28125 | 4 | import poker_hand_logic
def most_frequent_number_in_array(array):
'''
Check what is the most frequent number in an array.
>>> most_frequent_number_in_array([3, 3, 3, 2, 2, 2, 4, 4])
3
>>> most_frequent_number_in_array([3, 3, 3, 5, 5, 5, 7, 7, 0, 2, 2, 2])
5
'''
array.sort()
dict_... |
faf3d77e6ebe77d6f41f41ab30eabcd6f9f1e801 | Mikko1o/Binary_trees | /binarytree.py | 1,072 | 3.625 | 4 | import node
def inorder(tree):
assert isinstance(tree, node.Node)
if tree.left is not None:
inorder(tree.left)
# Do something
print(tree.val)
if tree.right is not None:
inorder(tree.right)
def preorder(tree):
assert isinstance(tree, node.Node)
# Do something
print(tre... |
c2fc1fc83c13dd8568e931d56caac06baacda7a7 | jvdmosel/FastaDB | /src/fastas/fasta.py | 3,026 | 3.75 | 4 | class Fasta:
"""Fasta class represents a .fasta datum
"""
def __init__(self, gen, spec, subs, fact, clas):
"""Constructor of Fasta class, initializes new
Fasta datum with description and sequence lines
Arguments:
gen {str} -- genus e.g. Canis
... |
53d18abb35f4f38140d1977014833f9214c3e89a | MichaelHarrison87/Python-Concurrency | /Multiprocessing/multiprocessing_map.py | 676 | 3.5 | 4 | import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping for {seconds} seconds...')
time.sleep(seconds)
return f'Done sleeping... {seconds}'
# Use ProcessPoolExecutor
# Can use submit() of a PoolExecutor to run individual tasks (but still concurrently... |
bbe4d570e2510f7ceb60494e6277f138115e6aa2 | nasima-akter-tania/Leet-code | /ClassOne/two_sum.py | 2,321 | 3.78125 | 4 | """ get sum of two number from a given array return two number index"""
from typing import List
#first approach
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# complexity o(n*n)
end = len(nums)
for i in range(end):
sum = 0 # hold the two number s... |
2fbd24b73b0c81c57a49a167f75a9013824c7993 | tywallace/dev-sprint4 | /chap10.py | 550 | 3.859375 | 4 | #Ch10
#Tyler Wallace
#10.7
def is_anagram(str1,str2):
a = list(str1)
b = list(str2)
a.sort()
b.sort()
if a == b:
return True
else:
return False
fin = open('words.txt')
line = fin.readline()
word_list = []
for line in fin:
word = line.strip()
word_list.append(word)
inter_list = []
def is_interlock(st... |
bd7efd4a9dc063f8721a94fcca72da74de9ea36e | TadayoshiCarvajal/EvoSchedule | /evoschedule/app/heuristic.py | 3,088 | 3.921875 | 4 | class Heuristic:
def __init__(self, H, genome, time_windows):
""" An object which tells us information about what constitutes
a good sequence. A good sequence will have a fitness that is closer
to the global maximum as given by the Hungarian Algorithm."""
self.H = H
... |
52be4c1530c73f0a4ab988e325f5ddd980c7b0eb | LiuYuan8aa/2048-api | /sample.py | 1,566 | 3.703125 | 4 | # 这是一个简单的全连接神经网络的例子。
from keras.layers import Input, Dense, Dropout, Activation,Conv2D,concatenate,Flatten,BatchNormalization
from keras.models import Model
import numpy as np
trainData=np.load('trainData.npy')
trainLabel=np.load('trainLabel.npy')
inputs = Input((4, 4, 16))
conv = inputs
FILTERS = 128
conv41 = Conv2... |
c838d8701727936b9b7134468b879573e9fd3cd3 | solandmedotru/Python_Tutorials | /useless_trivia.py | 942 | 4.15625 | 4 | # Программа бесполезные факты
#
name = input("Привет. Как тебя зовут? ")
age = int(input("Сколько тебе лет? "))
weight = int(input("И последний вопрос. Сколько ты весишь в кг? "))
print("\nЕсли бы маленький ребенок захотел привлечь твое внимание.")
print("Он произнес бы твое имя так: " + name * 5)
seconds = age * 36... |
9356b6e526bcd56d70ffd25f53964dd89f4e4c6b | hayo0o0o0/AdventofCode2019 | /Day2/part1.py | 823 | 3.6875 | 4 | def int_code(sequence):
split_sequence = sequence.split(',')
split_sequence[1] = '12'
split_sequence[2] = '2'
int_array = list(map(int, split_sequence))
length_array = len(int_array)
for x in range(0, length_array, 4):
if x+3 <= length_array:
process_opt_code(x, int_array)
... |
ccc21fb283e7535cdca52c7b240b35614b31c3a7 | acmachado14/ListasCCF110 | /Lista09/16.py | 775 | 3.828125 | 4 | #16. Crie um algoritmo que leia uma matriz A[2x2] e calcule a respectiva inversa A-1.
matriz = [[0 for j in range(2)] for i in range(2)]
matrizIn = [[0 for j in range(2)] for i in range(2)]
for i in range(len(matriz)):
for j in range(len(matriz[i])):
matriz[i][j] = int(input(f"Digite o valor para o índice... |
251f03445bafaa6b0b5466d0ef19d529c51c9971 | acmachado14/ListasCCF110 | /Lista07/12.py | 1,010 | 3.671875 | 4 | #12. Fazer um algoritmo que:
#Leia um conjunto de valores inteiros correspondentes a 80 notas dos alunos de uma turma, notas estas que variam de 0 a 10;
#Calcule a frequência absoluta e a frequência relativa de cada nota;
#Escreva uma tabela contendo os valores das notas (de 0 a 10) e suas respectivas frequências absol... |
5372c31a3873eb2d05312817a937f4fc902f8bbd | acmachado14/ListasCCF110 | /Lista09/08.py | 1,192 | 3.890625 | 4 | #8. Crie um algoritmo que leia e armazene os elementos de uma matriz inteira
#M[10x10] e escrevê-la. Troque, na ordem a seguir:
# ● A segunda linha pela oitava linha;
# ● A quarta coluna pela décima coluna;
# ● A diagonal principal pela diagonal secundária;
matriz = [[0 for j in range(10)] for i in range(10)]
f... |
94fcc18a0b3265087ebbfb6e224c898e95364a9d | acmachado14/ListasCCF110 | /Lista10/06.py | 1,714 | 4.25 | 4 | #6. Faça um programa que funciona como uma agenda telefônica. A agenda deve
#ser guardada em uma lista com o seguinte formato: [[‘Ana’, ‘99999-1234’], [‘Bia’,
#‘99999-5678’]]. (Não utilize esses dados. Isso é só um exemplo da estrutura. Leia
#todos os dados do teclado). O programa deve ter um menu que tenha as seguinte... |
14c454ac575deb1236d2e3aad96f01737282c182 | acmachado14/ListasCCF110 | /Lista08/06.py | 516 | 3.90625 | 4 | #6. Crie um algoritmo que leia os elementos de uma matriz inteira 10 x 10 e escreva
#a soma dos elementos que estão acima da diagonal principal.
matriz = [[0 for j in range(10)] for i in range(10)]
for i in range(len(matriz)):
for j in range(len(matriz[i])):
matriz[i][j] = int(input(f"Digite o valor para ... |
3991e2ccb19762b795950b72d1a01a2a0cbd3369 | OsamaBinNaughty-hub/BasistechniekenComputerSimulaties | /Hoofdstuk2/methodeVanDeVasteRichting.py | 903 | 3.671875 | 4 | from datetime import datetime
startTime = datetime.now()
def newton(f, Df, x0, epsilon, max_iter):
'''
Parameters
------------
f: Functie waar we de oplossing f(x)=0 voor zoeken
Df: Afgeleide van f(x)
x0: Eerste gok voor de oplossing van f(x)=0
epsilon: Stop-crit... |
728ce2dfe5b7e1b5e00f5e9b0681d843c7a8d5f4 | chrike-platinum/tensorflow | /img/testdiff.py | 212 | 3.53125 | 4 | __author__ = 'christiaan'
def differences(a, b):
if len(a) != len(b):
raise ValueError("Lists of different length.")
return sum(i != j for i, j in zip(a, b))
print(differences([1,0,1],[1,0,0])) |
c56f487b3f68ff8f38cacbc8ed1be27661b6bd7f | nikhilc1527/Algorithms | /src/main/python/bitmanipulation/problems/poweroftwo/power_of_two.py | 150 | 3.71875 | 4 | def power_of_two(num):
return num > 0 and (num - 1) & num == 0
if __name__ == "__main__":
print(power_of_two(2))
print(power_of_two(5))
|
b6b0a83cebc7bec6484c9166e94ecc021a4cc5ef | amberdoctor/code_exercises | /brand_style_guide/code_sample.py | 8,270 | 4.5 | 4 | #!/usr/bin/python
from __future__ import print_function
import re
#Instructions
# This exercise is meant to test your technical skills and level of Python familiarity.
#Please complete the task below.
#This exercise should take no more than 1 hour.
#
#Task
#In accordance with our brand styleguide, we need to convert a... |
9b9e7ba4422ef488770308714cfacf65741a28c3 | qagroup-py/python-october-2016-test-Olhaa | /OOP_shapes.py | 1,010 | 3.71875 | 4 | # coding: utf-8
"""
Implement class structure/hierarchy for following classes:
Ball (куля)
Circle (коло)
Cone (конус)
Cube (куб)
Ellipse (еліпс)
Hexagon (шестикутник)
Line (пряма)
Point (точка)
Pyramid (піраміда)
Rectangle (прямокутник)
Round (круг)
Sphere (сфера)
Square (квадрат)
Tetrahedron (тетраедр)
Triangle (трик... |
efb19772b51c75a959a50e5f7e55019e2f616710 | EladVaknin/Computer-network | /final project/part a/UDPPingerServer.py | 2,018 | 3.515625 | 4 | # UDPPingerServer.py
# We will need the following module to generate randomized lost packets
#! /usr/bin/python
import random
from socket import *
import time
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket... |
5714d43a4fbc62aa1c24d15f7f5cd34fbf20b1e2 | MaksymBorovets/Pycore_homeworks | /Homeworks/HW_7/HW_7.2.py | 425 | 3.5625 | 4 | import re
a = input("Password: ")
b = True
while a:
if (len(a)<6 or len(a)>16):
break
elif not re.search("[a-z]",a):
break
elif not re.search("[A-Z]",a):
break
elif not re.search("[0-9]",a):
break
elif not re.search("[$#@]",a):
break
else:
... |
098e64f36552a53e4c2e57e513b2ac5307e69366 | MaksymBorovets/Pycore_homeworks | /Homeworks/HW_4/HW_4.2.py | 90 | 3.625 | 4 | lst = [1,2,3,4,5]
for i in range(len(lst)):
lst[i] = float(lst[i])
print(lst) |
fddba824166568a96fc958b50f0fc5754d2b335b | ibacaraujo/pytorch-learning | /getting_started/deep-learning-with-pytorch/what_is_pytorch.py | 1,593 | 3.6875 | 4 | # What is PyTorch?
# Replacement for NumPy to use the power of GPUs
# Deep learning research platform
from __future__ import print_function
import torch
# 5x3 matrix, uninitialized
x = torch.empty(5, 3)
print(x)
# randomly initialized matrix
x = torch.rand(5, 3)
print(x)
# matrix filled with zeros and of dtype lon... |
5ab08aac77253e21f9fb082e6b049e83a85043f2 | SadiaZahin/smart-cache-prototype | /src/endpoints.py | 1,171 | 3.671875 | 4 | from src.server import Server
import random
import time
"""
The EndPoint class denotes an endpoint call of a server.
It will contain its server instance and also the list of dependency instances.
"""
class EndPoint():
def __init__(self, server_name, min_request_time, max_request_time, dependency_objects)... |
56e5e9b050ab399e70f9b25f4dcf0f34623bcd09 | yunyusha/xunxibiji | /month1/week1/Python_class2/branch.py | 3,014 | 4.3125 | 4 | # 分支结构
"""
if分支结构:适用于只有一种选择的时候
if 条件:
代码操作
if-else:分支结构适用于两种选择情况
语法结构
if 条件:
执行语句
else 条件:
执行语句
注意:else是对if条件的否定,即当if条件不成立时执行
if-elif-elif-elif...else: 用于计算机需要从多余
两个条件的结果中做出选择
语法结构:
if 条件1:
执行语句1
elif 条件2:
执行语句2
elif...
else:
执行语句n
"""
# num = int(input("输入一个整数"))
#
# if num & 1 == 0:
# ... |
0bebacb9af1f25936cc5e182912f34f7b3809f8a | yunyusha/xunxibiji | /month1/week3/class7/oop3.py | 2,056 | 3.890625 | 4 | """"""
"""
多继承
"""
# 新式类
class Tool(object):
def __init__(self, **kw):
print('当前正在执行tool的初始化操作')
self.__name = kw['name']
self.__weight = kw['weight']
self.__speed = kw['speed']
@property
def name(self):
return self.__name
class Ship(Tool):
def __init__(self, ... |
0a6fb77aeeda9414643f17fa5263c08eeb7a13a7 | yunyusha/xunxibiji | /text/like/p68.py | 744 | 3.703125 | 4 | # 排序算法之:侏儒排序法
# 每次比较两个数
def gnomessort(seq):
i = 0
while i < len(seq):
if i == 0 or seq[i-1] <= seq[i]:
i += 1
else:
seq[i], seq[i-1] = seq[i-1], seq[i]
i-=1
# 排序算法:归并排序法
def mergesort(seq):
mid = len(seq)//2
lft, rgt = seq[:mid], seq[mid:] # [:mid]表... |
ab3c787d8ffdaf44cf5061822cf0a5b3bd6fcea8 | yunyusha/xunxibiji | /month1/week2/class1/text.py | 241 | 3.6875 | 4 | import re
tt = "Tina is a good girl, she is cool,clever,and so on"
rr = re.compile(r'\w*oo\w*')
print(rr.findall(tt)) # 查找所有包含'oo'的单词
a = re.search(r'(tina)(fei)haha\2', 'tinafeihahafei tinafeihahatina').group()
print(a)
|
e90654fc4a5adc2f7b53093258145e5690795ab0 | yunyusha/xunxibiji | /month1/week2/class4/fun_sys.py | 1,260 | 3.953125 | 4 | import functools
# 获取绝对值
print(abs(-5))
# 列表遍历
def callback(num):
num **= 2
return num
x = map(callback,[1,2,3,4,5])
print(list(x))
result = map(lambda x: x**2, [1, 2, 3, 4, 56])
print(list(result))
"""
map(fun, list):map用来完成对列表list的遍历操作
每一次遍历都会自动调用fun函数完成对本次遍历
所得元素的计算,当遍历结束之后返回一个map对象.
"""
"""
列表过滤:
filt... |
7e96edca6d5e4db162448baa8d633b4896098cb1 | EdwinTinoco/Python-Course | /password_encryption/delete_employee.py | 279 | 3.625 | 4 | import sqlite3
conn = sqlite3.connect("employees.db")
print("Opened DB connection")
user_id = input("Enter an ID to delete: ")
conn.execute(f"DELETE FROM EMPLOYEES where ID = {user_id}")
conn.commit()
print("Data deletion successful")
conn.close()
print("connection close")
|
a22b9688d1a69f7acc9a95c46bcf6a42164b5311 | EdwinTinoco/Python-Course | /Strings/challenge_homework.py | 4,475 | 4.09375 | 4 | # Challenge 1: Find the Length of a String
# ex: "The" => 3
def lenght_string(string):
return len(string)
print(lenght_string('Some string'))
# --------------------------------------------------------------------------------------------------------
# Challenge 2: Create One String From Multiple Strings
# ex:
# ... |
d9f05e12a02778f3ecc9a202ec5fb7a37c8500b2 | EdwinTinoco/Python-Course | /Dictionaries/homework3.py | 1,744 | 4.0625 | 4 | # Create a dictionary called 'filter_genre'. 'filter_genre' should have 3 keys: action, romance and comedy.
# Each genre will have 2 channels (also dictionaries). Each channel will have a LIST of 2 tv shows.
###
# filter_genre
# action
# HBO - "The Pacific", "Watchmen"
# TNT - "Top Gun", "Terminator"
# r... |
0ee0d2873e2aec1ab8e74319127281ac81eb79c6 | Arween/PythonMIT-lessons | /Lecture-test/lect2_t2.py | 753 | 4.25 | 4 | outstandingBalance = float(raw_input("Enter the outstanding balance on your credit card: "));
interestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "));
monthlyPayment = 0;
monthlyInterestRate = interestRate/12;
balance = outstandingBalance;
while balance > 0:
monthlyPayment +=... |
906a4109d8c04588230658253f5ab970280c4f2b | HarshRangwala/Artificial-Intelligence-algorithms | /NQueens.py | 1,234 | 3.9375 | 4 | def isSafe (board, row, col):
# check left row
for y in range(col):
if board[row][y] == 1:
return False
# check diagonal left top
for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
if board[x][y] == 1:
return False
# check diagonal left bottom
for x,... |
69e965c0e3e6099ba9fc07f3f23cced796986f1d | TATimo/544NLP-project | /Homework-2/hw2.starter code/soundex.py | 5,425 | 3.703125 | 4 | from fst import FST
import string, sys
from fsmutils import composechars, trace
def letters_to_numbers():
"""
Returns an FST that converts letters to numbers as specified by
the soundex algorithm
"""
## tmp = raw_input().strip()
avoid = ["a","e","i","o","u","h","w","y"]
g1 = ["b","f","p","v"... |
e7882b86f088c99f3f9d264ba77d3850384df5e0 | gield/aoc2019 | /day04/solution2.py | 314 | 3.515625 | 4 | def is_valid_password(n: int) -> bool:
s = str(n)
# not decreasing
if list(s) != sorted(s):
return False
# adjacent doubles are not part of a larger group of matching digits
return 2 in [s.count(i) for i in set(s)]
print(sum(1 for n in range(136760, 595731) if is_valid_password(n)))
|
e185874bba605e3edd52aac4474747ff5e9e9e22 | gield/aoc2019 | /day12/solution2_original.py | 3,069 | 3.5625 | 4 | import math
from copy import deepcopy
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
def lcm3(a, b, c):
x = lcm(a, b)
return lcm(x, c)
class Point:
def __init__(self, x: int = 0, y: int = 0, z: int = 0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
re... |
1b721fef687d0be51cb4d71fe2c7ad5c62c8c061 | ImwaterP/learn-Python | /Python note/数值列表.py | 490 | 4.03125 | 4 | """
数值列表
"""
#range()函数【左闭右开】
for i in range(1,11):
print(i)
#list函数与range函数结合
num = list(range(1,11))
print(num)
#生成1到10的偶数
values=[]
for i in range(1,6):
value = 2*i
values.append(value)
# print(value)
print(values)
for i in range(2,11,2):
print(i)
#计算数字1到10的平方和
result = []
for i in range(1,1... |
7be77dd4270fe327f26de4080ffd26cc976735b1 | ImwaterP/learn-Python | /Python_work/sorted的排序与大小写问题.py | 1,252 | 4.09375 | 4 | '''
今天我在对字典里的键用sorted排序时发现并没有按照预期排序
研究后发现字母大小写会影响排序
'''
#创建一个字典,键里面的首字母有大写有小写
favorite_digit = {
'john' : 4,
'Tom' : 5,
'Lisa' : 9,
'liu' : 5,
'alice' : 0,
}
for name in sorted(favorite_digit.keys()):
print(name.title())
#运行后发现与预期不符合
#我不使用title函数又进行排序
for name in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.