blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
206de95ed94e47b3e7acc0adaf20fd8ebb29462a | BristolTopGroup/DailyPythonScripts | /dps/legacy/tools/Table.py | 407 | 3.59375 | 4 |
#Class to represent a table and manipulate the string representation
class Table():
#create a table with a header (first row) and a footer (last row)
def __init__(self, header = True, footer = False):
self.rows = []
def addrow(self, row):
self.rows.append(row)
def ... |
372c97891bd42376a5a6b85714c63222117709e7 | tofritz/example-work | /py4e/Ch10/ex_10_01.py | 462 | 3.8125 | 4 | fname = input('Enter a filename:')
try:
fhand = open(fname, 'r')
except:
print('Invalid filename:', fname)
quit()
emails = dict()
for line in fhand:
words = line.split()
if len(words) >= 2 and words[0] == 'From':
emails[words[1]] = emails.get(words[1], 0) + 1
lst = list()
for address, co... |
e138469afc2da8d9df1085e028a7b101db8c567e | Success2014/Leetcode | /implementStrStr.py | 1,084 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 18:32:18 2015
Implement strStr().
Returns the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
@author: Neo
"""
class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
""... |
7c2a0890e57c867a441ad2cfd318c8240d1a7554 | JohnGoure/leetcode-solutions | /addLinkedList.py | 815 | 3.65625 | 4 | from singlyLinkedList import LinkedList as ListNode
def addTwoNumbers(L1, L2):
arr1 = []
arr2 = []
while(L1.val != None):
arr1.append(L1.val.data)
L1.val = L1.val.next
while(L2.val != None):
arr2.append(L2.val.data)
L2.val = L2.val.next
# no reverse if numbers are... |
44815240466575dd95ddf8149c7b222d96acb083 | IzumiHoshi/My-Python-Code | /test_code/erciyuan.py | 196 | 3.609375 | 4 | import math
def quadratic(a, b, c):
temp = math.sqrt((b * b - 4 * a * c) / 4 * a * a)
x1 = -(b / 2 * a) - temp
x2 = -(b / 2 * a) + temp
return x1, x2
print(quadratic(1, 2, 1))
|
501d44a42e9482d1177051b5d0733a8575b21922 | cah835/Data-Structures | /Homework 7/#9 sql.py | 488 | 3.84375 | 4 | # Open the database
import sqlite3
connection = sqlite3.connect('mcu.db')
# Display the all customers
cursor = connection.cursor()
cursor.execute("SELECT distinct characters.name from characters, teamUps where characters.name = 'Howard Stark' and member1 = characters.id or member2 = characters.id intersect SELECT disti... |
0d680536267450fedcf13d6eff6f7c07caa28d1d | augustedupin123/python_practice | /p54_without_using_pow.py | 333 | 4.25 | 4 | #If a number is power of another no. without using pow
def function1(a,b):
prod = 1
while(prod<b):
prod *=a
if(prod == b):
print('the no. is a power')
else:
print('the no. is not a power')
m = int(input('enter a'))
n = int(input('enter b'))
print (func... |
b010fe28626c6cfcd354329d0517cc688ea9e852 | wtrnash/LeetCode | /python/047全排列II/047全排列II.py | 1,121 | 3.609375 | 4 | """
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
"""
# 解答:类似046题,主要需要去重,所以每次交换,对于同样的数字,只交换一次,所以需要判断前面有没有相同的,有则不做交换
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
... |
cf3fd09a7531ff09326b58d4a6c1d40ebaad86c0 | juncid/RWProyects-Python-3x | /Working with Email/3_2-working_with_external_files.py | 445 | 3.53125 | 4 |
f = open("contacts.txt", 'w')
f.write("Mickey Mouse|mickey.mouse@disney.com|Y\n")
f.close()
f = open("contacts.txt", 'a')
f.write("Donald Duck|donald.duck@disney.com|Y\n")
f.close()
f = open("contacts.txt", 'r')
contacts = f.read()
print(contacts)
def read_contacts(file_name):
f = open("contacts.txt", 'r')
... |
6046370ac8bc486d0473a0d8b4b533f7dc42b7d9 | zywangzy/fun_with_flags | /source/funwithflags/gateways/db_gateway_abc.py | 464 | 3.5 | 4 | """Module for the DbGateway abstract base class."""
from abc import ABC, abstractmethod
from typing import Any
class DbGateway(ABC):
"""Abstract base class for DbGateway defining the interfaces to interact with
a database, including read / write / update / delete database table entries.
"""
@abstract... |
ac0637e7df2f0f05c8abb73e72c21467e67a0cf7 | ysjin0715/python-practice | /chapter9/supermarket.py | 673 | 3.625 | 4 | #편의점 재고 관리
import sys
item={'종이컵':2,'우유':1}
item['커피음료']=7
item['펜']=3
item['책']=5
item['콜라']=4
print('재고관리시스템을 실행합니다')
key=input('물건의 이름을 입력하시오: ')
print(item[key])
s= input('변경하고자 하는 재고를 입력하시오: ')
print('선택된 물품:',s)
v= int(input('재고의 증가/감소량을 적어주세요: '))
if item[s]+v<0:
print('재고의 양은 0미만으로 설정될 수 없습니다.')
prin... |
042b4a70bfc566523636678d7a511ae70c10c70a | WhaleGirl/practice | /Shizhan.py | 1,025 | 3.8125 | 4 | #moc_tn = "百年孤独是什么样的一种孤独"
#print(moc_tn)
#a = input()
#b = input()
#if a>b:max=a
#print(max)
#num=5
#if num == 5:
# print("ok")
#a = 10
#b=20
#r=a if a>b else b
#print(r)
#str="百年孤独"
#for s in str:
# print(s)
# 九九乘法表
#for i in range(1, 9):
# for j in range(1, 9):
# print(str(i) + "*"+ str(j)+"="+st... |
85fb9b8bdc062def2974608ca45d25fee411e3f0 | CalvinNeo/LeetCode | /python/leetcode.230.py | 1,301 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from utils import *
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
... |
6beb653a6248cd84eb0e91e33710c29c989202fb | daniel-reich/turbo-robot | /tftN3EdkSPfXxzWpi_5.py | 1,033 | 3.796875 | 4 | """
Create a function that returns the sentence that contains the word at index
`n`. Remember to include the full stop at the end.
### Worked Example
txt = "I have a dog. I have a log. There is no stopping me now."
sentence_searcher(txt, 7) ➞ "I have a log."
# The word at index 7 is "log".
# T... |
546d6c35b8d0a8f63d1507ff9521ab64fd3d9495 | irving2/leetcode | /leetcode/1009. Complement of Base 10 Integer.py | 770 | 3.609375 | 4 | #!/usr/bin/env python
# coding=utf-8
# Project: leetcode
# Author : chenwen_hust@qq.com
# Date : 2019/5/11
class Solution(object):
def bitwiseComplement(self, N):
"""
:type N: int
:rtype: int
"""
def binary( x):
if x < 2:
return str(x)
... |
b020ed42daecf995c3ebbcb4e6048c4650c4d71e | nikhil1699/cracking-the-coding-interview | /python_solutions/chapter_02_linked_lists/SinglyLinkedNode.py | 445 | 3.578125 | 4 | class SinglyLinkedNode:
def __init__(self, value, next_node):
self.value = value
self.next_node = next_node
def stringify_linked_list(head):
display_str = ''
while head is not None:
display_str += str(head.value) + ","
head = head.next_node
return display_str
def list... |
8ba3e7a0119e55080aef1ee02ed67fe7945f0cc4 | SandraAlcaraz/FundamentosProgramacion | /parcial3problema3.py | 496 | 3.9375 | 4 | def Factorial (x):
v=x
m=1
if x==0:
return 1
while v>1:
m=v*m
v=v-1
return m
tr=True
while tr==True:
x=int(input("Dame el valor de x"))
v=0
f=0
r=0
while f<101:
v=v+1
y=Factorial(f)
w=(x**f)/y
... |
02df84da527f122ac6a32c835b5c8dc8082cdaae | utkarshbhardwaj22/TRAINING1 | /venv/Practice46.py | 490 | 3.703125 | 4 | """
Misc concepts in python
"""
class Point:
def __init__(self,x,y):
self._x = x # _x means protected in python -> x must not be accessed directly [warning]
self.__y = y # __y means private in pyhton -> cannot be accessed [error]
def show(self):
print("Points is {} | {}".format(self._... |
4b373a77fcc381d3f00f6eba2bac5e4b5bfb7930 | jim0409/PythonLearning-DataStructureLearning | /StatisticProblem/StatisticalInference/probabilityDistGen/poisson.py | 517 | 3.671875 | 4 | import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
rate = 2
n = np.arange(0, 10)
y = stats.poisson.pmf(n, rate)
print(y)
plt.plot(n, y)
plt.show()
# # 使用rvs作圖
# data = stats.poisson.rvs(mu=2, loc=0, size=1000)
# print("Mean: %g" % np.mean(data))
# print("SD: %g" % np.std(data, ddof=1))
#
... |
f5baca5b809b5da2dca2f542fb3f2103783ee46c | danxie1999/python_test | /absolute_v3.py | 280 | 4.40625 | 4 | #!/usr/bin/env python 3
num=input('Please input a number:\n')
try:
num=float(num)
except ValueError:
print('Your input is not a number.')
exit()
if num > 0:
print('The absolute value of',num,'is:',num)
else:
print('The absolute value of',num,'is:',-num) |
1270e19c41319f54e4c2c85723f5fda2a4fc7204 | Mustafasavran/Machine-learning | /LinearRegressionWithGradientDescentandvectorization.py | 1,191 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 22:17:59 2018
@author: mustafa
"""
##Linear regression with one variable and vectorization
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot(theta,filename):#theta is matris
x,y=get_attribütes_from_file(filenam... |
f869280cafd9caf9ac0ae294030bd2c93ed5a0b0 | ahtif/Bioinformatics-Algorithms | /nwa.py | 4,132 | 3.5 | 4 | import sys
from collections import OrderedDict
from termcolor import colored
symbols = set(["A", "C", "G", "T"])
MATCH_SCORE = 1
MISMATCH_SCORE = -0.5
"""
The scoring matrix provided in the assignment sheet as a function.
"""
def score(x, y):
if x == y:
return MATCH_SCORE
if x == "-" or y == "-":
... |
318c075c7f5fcfc51a3056bc6358760d2f62e992 | k0syan/Kattis | /82.py | 267 | 3.546875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def deleteDuplicates(self, head: ListNode) -> ListNode:
c = head
p = head
n = head.next
print(c, p, n)
while n is not None:
c = n
n = c.next |
55d58e7eac0137841de2e7660c5c053f5e4e08c0 | dao-keer/python2.7_study | /6-3.py | 443 | 3.640625 | 4 | personInfo = {
'name': 'dao-keer',
'age': 20,
'sex': 'male',
'city': 'wuhan',
'firstName': 'dao',
'lastName': 'keer'
}
for i, v in personInfo.items():
print i + ': ' + str(v)
for i in personInfo.keys():
print i
for v in personInfo.values():
print v
keys = ['name', 'age', 'weight']
for i in personI... |
34a838271bfebb4949302b8bd759cf6e359251f3 | keithoma/GdP | /Praktikum-Aufgabe-4/prime_sums.py | 1,153 | 3.828125 | 4 | #! /usr/bin/env python3
from math import factorial
class PrimeSums:
@staticmethod
def is_prime(p):
return p >= 2 and factorial(p - 1) % p - p == -1 # TODO: maybe sieve me
@staticmethod
def next_prime(p):
p += 1
while PrimeSums.is_prime(p) is False: # TODO Sieve me
p... |
d8efdfea7e4a8ee7d2029c733999b7ec1d79d423 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.3.py | 1,062 | 4.1875 | 4 | # Write a program that adds all numbers from 2 to 10,000 to a list.
# Then remove the multiples of 2 (but not 2), multiples of 3 (but not 3),
# and so on, up to the multiples of 100. Print the remaining values.
# FUNCTIONS
def fillList(list):
for i in range(2, 10001):
list.append(i)
return list
def r... |
3c18947f075257b17d0c660a1ca41d28c9eccf87 | antoinealb/master-thesis | /scripts/bib_sorter.py | 4,085 | 3.5625 | 4 | #!/usr/bin/env python3
"""
Sorts a tex bibliography according to the order they are cited.
"""
import argparse
import re
import logging
def parse_cite(line):
"""
Parses a line, returning a list of citation keys.
>>> parse_cite("Paxos\cite{kernelpaxos} is an \cite{attempt} to.")
['kernelpaxos', 'att... |
622dd5adb3de1ce349951f67a2c0c62295dbd73e | kuldeepsinghshekhawat/CodeVita_preparation | /Europian_Iteration.py | 1,268 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 28 15:23:13 2020
@author: Kuldeep Singh Shekhawat
Topic: Europian Iteration
Based on the Roman Numbers
"""
def roman(number):
digits=[1,4,5,9,10,40,50,90,100,400,500,900,1000]
symbols=['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M']
ans=''
... |
967a36660556f00f73899e63a4d993b70aa53225 | attard-andrew/automate-the-boring-stuff | /chapter_projects/11_feeling_lucky/lucky.py | 1,290 | 3.5625 | 4 | #! python3
# lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4
print('Googling...') # display text while downloading the Google page
# Defines a variable which will store the response from the Google search results
# page where the search term is sliced from the the argument provid... |
6479a0d515c51c9d48a681a3a26cd454dcd07b64 | rjmarshall17/miscellaneous | /reviews_keywords.py | 2,531 | 4.0625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
"""
Given a list of reviews, a list of keywords and an integer k. Find the most popular
k keywords in order of most to least frequently mentioned. The comparison of strings
is case-insensitive.
Multiple occurrences of a keyword in a review should be consider... |
4e583f24dd2e777e4a78b862b3aa048bc7e2c094 | magedu-python24/homework | /P24005-lmy/08-week/cat.py | 1,019 | 3.953125 | 4 | # 实现cat命令(支持查看内容和-n参数功能即可)
import argparse
parser = argparse.ArgumentParser(prog='cat',
description='concatenate file(s), or standard input, to standard output.',
add_help=False
)
parser.add_argument('file',
... |
9203bbac6cae6ce989c82e2a05b1d6c5413925be | rochafialvin/Python-Summarecon | /PYTHON/fundamental.py | 4,765 | 4.0625 | 4 | # Untuk menampilkan teks (komentar)
# print('My first code')
# Variable
# Untuk menyimpan sebuah data
# Tidak bisa diawali dengan angka
# string, tipe data yg menyimpan teks = 'Vinales'
# number , float : desimal (0.25, 3.14), integer : bulat (3, 5, 6)
# camelCase
firstName = 'Vinales'
lastName = 'John'
age = 32
# Fu... |
05f372ce9bd2b7ee0e17b4c6ae7ba0d2121a1ee7 | MackleBJ/Learning-Python | /Words_Used_In_File.py | 677 | 4.15625 | 4 | #Open file, .split() lines into words, .append() to another list, then check for any duplicates.
file_name = input("Enter file name: ") #Requests what file to open
file_handle = open(file_name)
line_split = []
bank = []
for line in file_handle: #Splits each word, in the line, into individual... |
55e8b6432093549ae8b0c2d21974874f3ce2751c | vishwanathj/python_learning | /python_hackerrank/Collections/word_order.py | 1,282 | 4.21875 | 4 | '''
You are given n words. Some words may repeat. For each word, output its number of occurrences.
The output order should correspond with the input order of appearance of the word.
See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
Constraints:
1 <= n <= 100000
The sum ... |
0e7f08dcf8b4126d096dc1bb964e39a85fb5cfe7 | devesh-bhushan/python-assignments | /tasks/task5.py | 4,330 | 3.859375 | 4 | """
this a menu driven python program to add ,display
search ,delete ,update a employee management system storing data in a database
"""
import pymysql
def create(): # function to create the table
cur = obj.cursor()
qry = """create table if not exists employees(
... |
ca4e578a9c2ce5de05a7c7b712e03f91276fdeb9 | hubbm-bbm101/assignment-4-2018-b21726971 | /assignment4.py | 4,922 | 3.59375 | 4 | import sys
myFile = open(sys.argv[1], "r")
myFile = myFile.readlines()
myDict = {}
counter = 1
mylist = []
mylist2 = []
final_list = []
for poland in myFile:
another_one = []
for prussia in poland:
try:
another_one.append(int(prussia))
except ValueError:
pas... |
5d23ce0a48b30dfdbdfaf4956da4116ee6e7afd5 | chicocheco/automate_the_boring_stuff | /docx_reading.py | 344 | 3.59375 | 4 | #! python3
import docx
def get_text(filename):
doc = docx.Document(filename)
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
# Return one long string of joined separate paragraphs with '\n' so each paragraph starts on a new line.
return '\n'.join(full_text)
print(... |
ce10d07b6fce7e49b991fdb9843b03a8d91cffc4 | developer22-university/pythonista | /bfs-search.py | 1,245 | 3.84375 | 4 | #bfs-search
import collections
import queue
from typing import Optional
import igraph
def depth_first_search(graph: igraph.Graph,
start: int,
val: int
) -> Optional[int]:
"""
Implementation of the Breadth First Search algorithm on a
non... |
e315eb66eba1c0b3b0300f07fa681eae00b1ce17 | M1-2000-2020/ICTPRG-Python | /Week05-Arrays_and_Lists/Quiz.Q6.py | 361 | 4.125 | 4 | '''
Write a program that asks the user for a large number, and then sums all of the digits in that number: Example:
Enter a large number: 29834892
Sum of the digits: 2 + 9 + 8 + 3 + 4 + 8 + 9 + 2 = 45
'''
num1 = input("Please enter a large number, more than six digits long: ")
digits = [int(x) for x in str(... |
002d6da83a394822bdf32c2808273bc520e045d4 | arjun289/eopi | /data_structures/linked_list/overlapping_list.py | 2,615 | 3.96875 | 4 | from list import ListNode, MyList
def iterate_and_find_overlap(bigger_list, smaller_list, skip_length):
large_iter, small_iter = bigger_list.head, smaller_list.head
for _ in range(skip_length):
large_iter = large_iter.next
while large_iter and small_iter:
if large_iter is small_iter:
... |
c785e50b43e0fd0d5b5f5eac0d1d8470dbab48ee | yangchi/LCPractice | /SearchInsertPosition.py | 579 | 3.78125 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
return self.binarySearchInsert(A, 0, len(A), target)
def binarySearchInsert(self, A, begin, end, target):
if begin >= end:
r... |
0df6cadbb9eaa946f804032bb91092aa8d80691d | arnjr1986/Curso-Python-3 | /aula08.py | 555 | 3.859375 | 4 | #Modulos / Biblioteca/ import
#import math (importa tudo: ceil(arredonda pra cima), floor(arredonda pra baixo
#trunc(trunca o numero para numero inteiro), pow(exponencial), sqrt, factorial
# from math import sqrt, ceil (vai importar somente sqrt e ceil da biblioteca Math) importação otimizada
import math
#from m... |
35fe94e081db1e396fff8e7ea7af24739596a83b | JavaPhish/holbertonschool-interview | /0x1F-pascal_triangle/0-pascal_triangle.py | 282 | 3.71875 | 4 | #!/usr/bin/python3
"""
Basic pascal triangle algo
"""
def pascal_triangle(n):
""" Main function """
final = []
row = [1]
temp = [0]
for x in range(n):
final.append(row)
row = [l + r for l, r in zip(row + temp, temp + row)]
return final
|
addc6915f4f7dcb2daada6858c1e4f708749023b | gnorgol/Python_Exercice | /Exercice 43.py | 165 | 3.53125 | 4 | def InsertEtoile(s) :
resultat = ""
for each in s:
resultat = resultat + each + "*"
return resultat
s = "Python"
print(InsertEtoile(s))
|
6a6ec231d1b29335c8b5a05dfd24113544d2d5b4 | nicolasgasco/CodingNomads_Labs | /07_classes_objects_methods/CLIgame_characters.py | 1,196 | 4.03125 | 4 | import random
# create two classes for hero and opponent
class Hero:
"Class for the hero of the game"
def __init__(self, name, level, gender):
self.name = name
self.level = level
self.gender = gender
def attack(self, opponent):
print(f"{self.name} attacks {opponent.name}!\n... |
ef1f0d090d91d6f78eb1e770ceb946e41a635f7f | devdesai-work/suduku_with_backtracking_visualization | /solve.py | 1,673 | 3.53125 | 4 | matrix = [[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, ... |
4fdae6d3749fbf4d6905905160426534ee3b489f | ani07/Starting_Out_with_Pythoni | /Rectangle_area_3_2.py | 374 | 4.03125 | 4 | L1 = float(input('Enter length of 1st rectangle'))
B1 = float(input('Enter the breadth of 1st rectangle'))
L2 = float(input('Enter length of 2nd rectangle'))
B2 = float(input('Enter breadth of 2nd rectangle'))
A1 = L1*B1
A2 = L2*B2
if A1 > A2:
print('First rectangle is bigger')
elif A2 > A1:
print('Second re... |
cd65c9a055b50bb2ad3964f447453bafce167d89 | dm36/interview-practice | /leetcode/majority_element.py | 3,957 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html
# - Know if a value is present in a list for more than half of the elements
# in that list
# Fault-tolerant computing- multiple redundant computations nad verify that
# a majority of results agree
# Sort the list- if the... |
a7ef2f04b328fc4538359059520759cabbdbea1d | ender8848/the_fluent_python | /chapter_19/demo_19_15.py | 1,341 | 3.765625 | 4 | '''
假设有个销售散装有机食物的电商应用,客户可以按重量订购坚果、干果或杂粮。
在这个系统中,每个订单中都有一系列商品,而每个商品都可以使用示例 19-15 中的类表示。
示例 19-15 bulkfood_v1:最简单的 LineItem 类
'''
class LineItem:
def __init__(self, description, weight, price):
self.description = description
# 这里已经使用特性的设值方法了,确保所创建实例的 weight 属性不能为负值
self.weight = weight
self.price = price
... |
e0d6bf3d710e67607420d96d3a27865ea0d60f9f | rinAkhm/task_for_analytics | /task5.py | 2,143 | 3.8125 | 4 | from datetime import datetime
from datetime import timedelta
'''The Moscow Times - Wednesday, October 2, 2002
The Guardian - Friday, 11.10.13
Daily News - Thursday, 18 August 1977'''
format1 ='Wednesday, October 2, 2002'
day1 = datetime.strptime(format1, "%A, %B %d, %Y")
print(day1,type(day1))
format2 ='Friday, 11... |
746867a4b7ae573b5a8998bf77b3d7a145973747 | shenqidecaonima/python_tutorial | /Week1-2/1.11Python面向对象/2.py | 507 | 4.0625 | 4 | #构造函数:__init__()
'''
class A:
def __init__(self):
print("AAAAAAAA")
def fun(self):
print("class A...")
a = A()
'''
class Person:
name=""
age=0
def __init__(this,name,age):
this.name=name
this.age = age
def getInfo(self):
pri... |
bfdb50d8dcddf515f8f606ab1e1534bcb6a81c93 | ZachChuba/Tic-Tac-Toe-App | /models.py | 512 | 3.5 | 4 | '''
Model for DB
'''
def define_database_class(database_session):
'''
Returns class Player that is a model for the db
'''
class Player(database_session.Model):
'''
Database Player table format
'''
username = database_session.Column(database_session.String(80), primary_key... |
b5a53e3308ff3a8950cbd1c9b70bf59fb7d9dc54 | YanjiaSun/leetcode-3 | /code/993_solution.py | 838 | 3.765625 | 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
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
queue = collections.deque([root])
... |
17a65e2160a8eb3bfa7d74cff44c51686ae69a50 | vicamu/test | /test.py | 84 | 3.609375 | 4 | a =[1,2,3,4]
for num in a:
print(num)
print("Línea nueva 2")
print("Hola hola") |
f358fdd80c85823c322ed71b846e629980d8fddc | annaxarkhipova/coursepy | /homework for 11 March/with_proccess.py | 1,312 | 3.890625 | 4 |
# Также запустите ее три раза с теми же аргументами, но каждую в отдельной потоке с помощью multiprocessing.Process.
# Не забудьте стартануть процессы и дождаться их окончания.
import multiprocessing
import time
v = time.time()
def odd_primes(end, start):
print('Старт вычислений, начиная с {}'.format(end))
... |
34055a4fe950c03e9b14fbf71245f7018cd9a95f | quyixiao/python_lesson | /function1/function11.py | 803 | 3.578125 | 4 | def foo(xyz=None,u = 'abc',z = 123):
if xyz is None:
xyz = []
xyz.append(1)
print(xyz)
return xyz
foo()
print(1,foo.__defaults__)
foo()
print(2,foo.__defaults__)
foo([10])
print(3,foo.__defaults__)
foo([10,5])
print(4,foo.__defaults__)
lst = [5]
lst = foo(lst)
print(lst)
print(5,foo.__default... |
53839d9c460d47315f4760fa1fd1fa0a4949d5e4 | evrenkaraarslan/LeetCode-Codewars | /BitCounting.py | 384 | 4.125 | 4 | ## Bit Counting ##
def countBits(n):
a="{0:b}".format(n).count("1")
return a
'''
Write a function that takes an integer as input, and returns the number of bits that are equal to one
in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 i... |
df2391c5d28acf81ce931ca77a3924df79ff0a3b | lorak127/University-Courses | /FP/Utils/Simulare_217_1/Domain/Medicine.py | 1,164 | 3.515625 | 4 | '''
Created on 11 dec. 2017
@author: USER
'''
import unittest
class Medicine():
def __init__(self,name,price):
"""
Initializeaza un obiect de tip Medicine
:param: name - string
:param: price - float
"""
self.__name=name
self.__price=price
... |
30d6fab4a2b8d322350ffe09f6f830d1cc671f5d | theydonthaveit/python-training | /api_frameworks/hug_test.py | 811 | 3.53125 | 4 | """A basic (single function) API written using hug"""
import hug
@hug.get('/hug_test')
def happy_birthday(name, age:hug.types.number=1):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
@hug.get('/greet/{event}')
def greet(event: str):
"""Greets appropriately (... |
65883fcadfd179420f6103b09df6de0962ce6f41 | Saber307/My-University-Life-Learning | /52 programming problems/problem 3.py | 107 | 3.5625 | 4 | for x in range (1000,0,-5):
for y in range(x,x-5,-1):
print(f"{y}\t",end='')
print("\n")
|
595df1012223cd8f440c3e4130dac31c4bf26b74 | IsseBisse/adventcode20 | /6/CustomCustoms.py | 625 | 3.53125 | 4 | def get_data(path):
with open(path) as file:
data = file.read().split("\n\n")
for i, entry in enumerate(data):
data[i] = entry.split("\n")
return data
def part_one():
data = get_data("input.txt")
total_sum = 0
for i, entry in enumerate(data):
temp = "".join(entry)
temp = set(temp)
total_sum += len... |
2648c617d019ec7e274c0f387430b1e1c4ed989a | chenshaoping2015/pygame | /python_pratice/game/game_round1.py | 894 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# @Time :2020/11/18 17:04
# @Author: stevenchen
'''
一个回合制游戏,每个角色都有hp 和 power ,hp代表血量,power代表攻击力
hp的初始值为1000,power的初始值为200,
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
'''
#定义fight函数实现游戏逻辑
def fight():
#定义四个变量存放初始数据
my_hp = 1000... |
53a4ec70b346d1dc35d0299ec8ac2eef9ad385f5 | saadhasanuit/Assignment-2 | /pp 3.8.py | 305 | 4.15625 | 4 | print("MUHAMMAD SAAD HASAN 18B-117-CS SECTION:-A")
print("ASSIGNMENT # 3")
print("PRACTICE PROBLEM 3.8")
## A function perimeter() that takes, as input, the radius of a circle (a nonnegative number) and returns the perimeter of the circle
import math
def perimeter(r):
r = (2 * math.pi * r)
return r
|
b1479277d1367eddc76178534804291e254bd6b2 | RidgeHood/Mashupstacks-Projects | /python/python-lab-5/Project-3.py | 418 | 3.671875 | 4 | import csv
with open('projectcsv.csv','r') as car:
car_read=csv.reader(car)
csvlist=[]
header=[]
for x in car_read:
csvlist.append(x)
print('\nThird row is--\n',csvlist[2])
print('\n2nd column is---\n')
for i in range(len(csvlist)):
print(csvlist[i][1])
... |
65a2b09ea57281e4a75f4de83efeaf7b5e027e44 | Alegruz/Game-AI-Track | /3_2/CSE304_ALGORITHM_ANALYSIS/Homeworks/hw1.py | 1,362 | 3.859375 | 4 | import time
def algorithm_recursive(n: int) -> int:
if n == 1 or n == 2:
return 1
else:
sum: int = 0
for i in range(1, n):
sum += algorithm_recursive(i)
return sum
def algorithm(n: int) -> int:
count: int = 0
data: list[int] = [0] * (n + 1)
data[1] = 1... |
c936b1d86ddc4acfaeaacf0e276b19dd2a92408b | ethanrweber/ProjectEulerPython | /Problems/101-200/131-140/Problem135.py | 948 | 3.53125 | 4 | def method():
print("for values of a number n from 1 to 1 million, determine the number of solutions for n in which n can be "
"expressed as z^2-y^2-x^2 in exactly 10 unique ways, where x,y,z are terms in a series of "
"arithmetic progression")
print()
print(arithmetic_progression_sums(... |
61be562379cfdbc84bb85d5eb3f4f294887714c3 | orlovska/python | /The_start/Divide.py | 878 | 4.0625 | 4 | # Given two positive integers, compute their quotient,
# using only the addition, subtraction, and shifting operators.
# Hint:Relate x/y to (x - y)/y.
def divide (x , y) :
# divide(9, 3) (1001, 11)
result, power = 0, 32
y_power = y << power
# y_power = 110000000000000000000000000000000...
while ... |
480c9bb1d75f5180c77139407444f3d70b37d41f | kbmulligan/cs545-a1 | /perceptron.py | 10,039 | 4.28125 | 4 | import numpy as np
from matplotlib import pyplot as plt
class Perceptron :
"""An implementation of the perceptron algorithm.
Note that this implementation does not include a bias term"""
def __init__(self, max_iterations=100, learning_rate=0.2) :
self.max_iterations = max_iterations
self... |
6d4e1fbe3bd8329a5d7b3213261a960123cb8cbf | GustavMH29/Python | /Code/Math/Equations/Square.py | 450 | 3.96875 | 4 | # Written by RF
while True:
Q=float(input("What number would you like to square? "))
H=float(input("How many times would you like to square it? "))
S=((Q)**H)
print("The", H, "square is", S)
while True:
answer = str(input('Anything else? (y/n): '))
if answer in ('y', 'n'):
... |
792a70d666f23881f20c1a77706696cedd724449 | csj561/python | /code/list/list.py | 1,060 | 3.59375 | 4 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
import random
'''
序号 函数
1 cmp(list1, list2)
比较两个列表的元素
2 len(list)
列表元素个数
3 max(list)
返回列表元素最大值
4 min(list)
返回列表元素最小值
5 list(seq)
将元组转换为列表
序号 方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(o... |
c1e4afa7990b5a925d61eeaab1ac9a8dd290151f | Devu17/luminar | /venv/armstrong.py | 118 | 3.96875 | 4 | num=int(input("enter number"))
sum=0
while(num!=0):
digit=num%10
sum=sum+(digit**3)
num=num//10
print(sum) |
f08f4b0fb31e757b8328726fda198dddd2865ea8 | jell0720/Python27_Sublime_Dondon | /src/ClassContens/firstClass/Dictionary.py | 355 | 3.703125 | 4 | #coding=utf-8
dic = {'a':100, 'b':"yes", 'c':0.98, 'a':600}
print dic['c']
print dic.keys()
print dic.values()
print dic.get('c')
dic2 = dic
print dic2
dic['d'] = 811
print dic
dic.update({'e':'string'})
print dic
for key in dic:
print key,dic[key]
print dic2
def func(x):
return {'a': 1... |
946968c7c03af1f1e363f62538061cba3e0b6b36 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Arrays/189_rotate_array.py | 1,496 | 4.3125 | 4 | # Given an array, rotate the array to the right by k steps, where k is non-negative.
#
# Example 1:
#
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
#... |
9dca59febb70dbeff743ba49cf108fb9faa1a803 | bsivavenu/Machine-Learning | /Advanced python 7 - 8/Exception/Demo4.py | 442 | 4.09375 | 4 | # WAP to Validate User Given AGE
# Age must be in B/W 23 to 40
def validate_age(given_age):
if((given_age>=23) and (given_age<=40)):
print("Valid Age")
else:
raise ValueError("Invalid Age")
#raise throw an Exception
age = int(input("Enter Age : "))
try:
validate_age(age)
except Va... |
3fd57122f8c3933df471cfc70adeba612ce58945 | srinicoder035/Programming-Paradigms | /Assignment1/list.py | 1,286 | 3.921875 | 4 | class Node:
def __init__(self, val):
self.data = val
self.next = None
class List:
def __init__(self):
self.head = None
def addNode(self,val):
temp = Node(val)
if self.head == None:
self.head = temp
return
last = self.head
... |
b18dc5583aeef8ad434ff6860fdc59a3348c5f41 | etscrivner/dse | /lib/integration.py | 4,648 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
lib.integration
~~~~~~~~~~~~~~~
Module for handling numerical integration.
Integrator: Interface that uses Simpson's Rule to numerically integrate a
function.
is_even(): Indicates whether or not the given integer value is even.
derivative(): Return a function... |
9328570129da614a62d08bb5467b1a7f1cb53bc0 | pko89403/Python-Study | /ProgrammingPattern/FactoryPattern/SimpleFactoryMethod-Job.py | 553 | 3.96875 | 4 | from abc import ABCMeta, abstractmethod
class Job(metaclass=ABCMeta):
@abstractmethod
def do_something(self):
pass
class Student(Job):
def do_something(self):
print("Let's do the study")
class Worker(Job):
def do_something(self):
print("Let's do the work")
class SimpleFactor... |
d1b735688abf2611abecb56fad87cbc045bf56b9 | Sultanggg/codeabbey | /q30.py | 435 | 3.671875 | 4 | #neumanns random generator
mylist = ['7735', '2754', '3453', '746', '3234', '4421' ,'3017' ,'2663', '9348', '6694']
def neumanns(mystr):
n = int(mystr)
first = n**2
pad = "%08d"%(first)
newstr = str(pad)
nextstr = pad[2:6]
return nextstr
for i in mylist:
emptylist = [i]
x = neum... |
929e4781b38840be62cc7354067e346d2235a9a5 | Judahmeek/OldCode | /Python/Python 2/sum_power_max.py | 2,803 | 3.546875 | 4 | ''' https://www.hackerrank.com/contests/world-codesprint-april/challenges/little-alexey-and-sum-of-maximums
Alexey is playing with an array, AA, of nn integers. His friend, Ivan, asks him to calculate the sum of the maximum values for all subsegments of AA.
More formally, he wants Alexey to find F(A)=∑l=1n∑r=ln maxl≤x≤... |
18574229d4e7d819b2d64a3d5b01dcb4e0e43bf6 | bhojnikhil/LeetCodeProblems | /Grokking/Sliding Window/smallest_subarry.py | 1,066 | 4.03125 | 4 | # smallest contiguous subarray whose sum is greater than or equal to ‘S’
# Input: [2, 1, 5, 2, 3, 2], S=7
# Output: 2
# Explanation: The smallest subarray with a sum greater than or equal to '7' is [5, 2]
# arr=[2, 1, 5, 2, 3, 2]
# s=7
# N = len(arr)
def smallest_subarray_with_given_sum(s, arr):
shortestLen = 9... |
e02a472a9f52e2ddb6662c3bac4ee4a59c08dbfc | i8cake/querygeneration | /genquery.py | 3,678 | 3.59375 | 4 | #program to create queries
def gen(*stmts):
global flag
k=len(stmts) #find number of list in argument
if k==1:
q,s=simple(stmts[0]) #it is a simple query
print(s)
else:
flag=1
multi(stmts) #uses and/or
#function to generate simple queries... |
ee380a976456d801d3deb70ff266d62c960e8d97 | dn1eper/genetic-trading | /mutator.py | 5,151 | 3.65625 | 4 |
from copy import deepcopy
from abc import ABC, abstractmethod
import random as rand
import math
class Mutator(ABC):
@abstractmethod
def mutate(self) -> list:
pass
class RandomGeneChainMutator(Mutator):
def __init__(self, n:int):
if n > 0:
self._n = n
else:
... |
accc852cf4c460d0d9e52b1601e9e03437574d1f | flatlining/ProjectEuler | /p0004.py | 923 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Matias Schertel (flatlining@ProjectEuler) - mschertel@gmail.com
# Most simple one
def SimpleSolution():
large = 0
for n in range(999, 99, -1):
for m in range(n, 99, -1):
if str(m*n) == str(m*n)[::-1] and m*n > large:
large = m*... |
43fea607dac8a649240031774cfcefd008b40dcb | pschafhalter/Johann | /voice_leading/helpers.py | 3,006 | 3.703125 | 4 | from music21 import interval
def is_lower_note(expected_lower, expected_upper):
"""Given two notes, returns whether the first note is lower or equal to the second note.
>>> from music21 import note
>>> is_lower_note(note.Note('C3'), note.Note('D3'))
True
>>> is_lower_note(note.Note('C3'), note.No... |
71037955dee0e6d9dd809c7bb47a561396cd3175 | daisy0x00/LeetCode_Python | /LeetCode628/LeetCode628.py | 536 | 3.890625 | 4 | #coding:utf-8
class Solution():
def maximumProduct(self, nums):
"""
:param nums: List[int]
:return: int
"""
if len(nums) < 3:
return 0
numsSorted = sorted(nums)
result1 = numsSorted[-1] * numsSorted[-2] * numsSorted[-3]
result2 = numsSort... |
f64506c28f6fd883e0375ea9899496afedbb58da | MosaicOrange/Portfolio | /Python/pydev/HackerRank - Miscellaneous/compress_the_string.py | 457 | 3.625 | 4 | x = input().strip() + "x"
return_list = list()
last_value = ""
tmp_inc = 1
for c in x:
if c is "x":
return_list.append((tmp_inc, int(last_value)))
break
if last_value:
if int(last_value) == int(c):
tmp_inc += 1
else:
return_list.append((tmp_inc, int(last_... |
91bcd6886a825494f0013eb115ee3f8ac5871ec8 | LialinMaxim/Toweya | /league_table.py | 2,866 | 4.21875 | 4 | """
The LeagueTable class tracks the score of each player in a league.
After each game, the player records their score with the record_result function.
The player's rank in the league is calculated using the following logic:
* The player with the highest score is ranked first (rank 1). The player with the lowest score... |
6732cc904880abe386974c871a3e8c5d599cb6bc | TheFibonacciEffect/interviewer-hell | /palindromes/is_palindrome.py | 1,551 | 3.65625 | 4 | """
Determines whether a string is a palindrome.
Requires the third-party 'regex' library; to obtain, 'pip install
regex'. See https://pypi.python.org/pypi/regex for details.
"""
import sys
import unicodedata
import unittest
import regex
def is_palindrome(s):
"""
Determines whether a given string is a pal... |
70e771665ca4363716fa54df09e224190e6e4aea | ChirantanTech/wordcounter | /wordcounter.py | 218 | 4.09375 | 4 | print("Welcome to the word counter software.")
a = input("Type the article you want to count the words : ")
print("Number of words in these string is:",len(a))
#Desc
A simple beginner project created in python.
|
ef71a581e9b955e55434c7447b2326483d42c528 | sarathkumar1981/MYWORK | /Python/AdvPython/Files/stringcheckfile.py | 215 | 3.65625 | 4 | with open('filecore.txt','w') as fob:
print("please enter the text\n")
str= None
while (str!='@'):
str = input()
if (str !='@'):
fob.write(str + '\n')
#print(fob.read()) |
bb286e11918e609c9755157e17f64ed373b918fe | IshmaelDojaquez/Python | /Python101/NestedLoops.py | 290 | 4.28125 | 4 | for x in range(4):
for y in range(3):
print(f"{x},{y}") # nesting a for loop in a for loop to make coordinate values
# Practice
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ''
for count in range(x_count):
output += 'x'
print(output) |
27a8d1b4d72f520cfa44f6bed9807be50beed1c2 | lucianoww/Python | /pybrexer0007.py | 542 | 4.34375 | 4 | '''
Solução para exercicios https://wiki.python.org.br/EstruturaSequencial
#07) Faça um Programa que calcule a área de um quadrado,
em seguida mostre o dobro desta área para o usuário.
'''
comprimentox=float(input('Digite o comprimento :'))
largurax=float(input('Digite a largura :'))
areax=com... |
42c119150aa13a3ab523d8012db81eab139ecacb | Greilfang/OS | /FileSystem/code/basics.py | 2,140 | 3.515625 | 4 | #超级块,记录文件系统信息
class SuperBlock(object):
def __init__(self):
self.file_system_name = "GreilOS"
self.bit = 8
self.file_system_size = 1024*1024*1024 #1G的文件大小
self.block_index_size = 4 #块索引的大小
self.node_size = 128 #每一个数据块的大小
self.node_num = 120 #最多存储120个文件
self.da... |
44e5807fad722b84076472ba42f1871a22bccc22 | Ayushmanglani/competitive_coding | /leetcode/May/LC_M7_BinaryTreeCousins.py | 1,053 | 3.90625 | 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
def level(root, a, l):
if root is None:
return 0
if root.val == a:
return l
lv = level(root.left,a... |
f3eaba6966eaa390fbdcdf4592c8d9bd96195a6a | jakubpulaczewski/codewars | /8-kyu/reversed-words.py | 726 | 4.21875 | 4 | """
Reversed Words
The link: https://www.codewars.com/kata/51c8991dee245d7ddf00000e
Problem Description:
Complete the solution so that it reverses all of the words within the string passed in.
Examples:
reverseWords("The greatest victory is that which requires no battle")
should return "battle no re... |
d25bece5be6109e24fd77541f6c79afcba55c7ad | JustinDoghouse/LeetcodeAnswer | /Swap Nodes in Pairs.py | 581 | 3.765625 | 4 | __author__ = 'burger'
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
if not head or not head.next:
return head
... |
173b24af94ddf098fc0a8788059cdfb177b60e85 | ctc316/algorithm-python | /Lintcode/Tag_String/421. Simplify Path.py | 453 | 3.796875 | 4 | class Solution:
"""
@param path: the original path
@return: the simplified path
"""
def simplifyPath(self, path):
cmds = path.strip().split("/")
dirs = []
for c in cmds:
if c == '' or c == '.':
continue
elif c == '..':
i... |
195060f0693a50422ddcfc32430a5ef645df3630 | zhxgigi/toolkids | /python/singleton.py | 438 | 3.65625 | 4 |
class Singleton(object):
def __new__(cls, *args, **argkw):
if not hasattr(cls, "_instance"):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **argkw)
return cls._instance
class MyClass(Singleton):
def __init__(self):
self.name = "zhang"
... |
3c534b9c97f4bbcaee7e7deeee185d262436ae00 | colin-bethea/competitive-programming | /codeforces/A_Boy_or_Girl.py | 243 | 3.65625 | 4 | __author__ = 'Colin Bethea'
def main(name):
charset = set()
for char in name:
charset.add(char)
return 'CHAT WITH HER!' if len(charset) % 2 == 0 else 'IGNORE HIM!'
if __name__ == "__main__":
name = input()
print(main(name))
|
237c921c9d5702544ca8abe11a85e353ee998a3d | Gio1609/Python_Basic | /chap-1_Arrays_and_Strings/1.9.py | 370 | 4.0625 | 4 | # Given two strings s1 and s2, write code to check if s2
# is a rotation of s1 using only one call to isSubstring
def isRotation(s1, s2):
if len(s1) == len(s2) and len(s1) > 0:
s1s1 = ''.join([s1, s1])
if s2 in s1s1:
return True
return False
if __name__ == "__main__":
import s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.