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 |
|---|---|---|---|---|---|---|
79699f6e7d3ab0c9ad08ad75dcf510fae492166d | Shwebs/Python-practice | /ControlStructure/List/List-operation.py | 1,186 | 4.53125 | 5 | #The item at a certain index in a list can be reassigned.
#In the below example , we are re-assigned List[2] to "Bull"
nums = [7, 8, 9, 10, "spring"]
nums[2] = "Bull"
print(nums)
print("===================================")
#What is the result of this code?
nums = [1, 2, 3, 4, 5]
nums[3] = nums[1] # We are re-as... |
18f795a10eb2da066a1599fd909069e2d00216fc | Shwebs/Python-practice | /ControlStructure/List/List-method-insert.py | 797 | 4.25 | 4 | #The insert method is similar to append,
#except that it allows you to insert a new item at any position in the list,
#as opposed to just at the end.
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print (words)
print("================================")
nums = [1,2,3,5,6,7]
index = 3
nums.insert(index,... |
fba81294a158815848dded2ca40206fb46b6ccd5 | Shwebs/Python-practice | /BasicConcepts/3.strings/string-methods/string-is-check.py | 1,386 | 4.21875 | 4 | str=input("Enter a String: ")
#isalnum()
#Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
print('Checking If it is an alphanumeric :-',str.isalnum())
#isalpha()
#Returns true if string has at least 1 character and all characters are alphabetic and false otherwis... |
292b8675c84630e557c9282cf2fc4567a3cd68c5 | alessandrogums/Desafios-Python_Variaveis_compostas-listas- | /Exercicio.86_CV.py | 468 | 4.25 | 4 | # Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
matriz=[[],[],[]]
for l in range(0,3):
for c in range(0,3):
num=int(input('digite um número:'))
matriz[c].append(num)
print('='*15)
fo... |
324c3c5892c27bc78bafebb42cf3c6a748cfd85a | jdcast/cracking-the-coding-interview | /ch_2/p2_2.py | 1,237 | 4.03125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
###
#Time = O(n)
#Space = O(1)
###
class Node:
def __init__(self, data):
self.data = data
self.next = None
def appendToTail(self, d):
end = Node(d)
n = self
while n.next != None:
n = n.next
n.next = e... |
c224c730c2946c3906729b6d0d9b2cb6134fed31 | jjas3/my-isc-work | /list.py | 196 | 4.1875 | 4 | forward=[]
backward=[]
values=["a","b","c"]
for i in values:
forward.append(i)
backward.insert(0,i)
print forward, backward
forward.reverse()
print forward, backward
print forward==backward
|
cb13ce28b6364691e8c292908baae8b1120de3bb | jjas3/my-isc-work | /loop_string_as_sequence.py | 419 | 4.03125 | 4 | #s ="I Love working in Python"
#split_s=s.split()
#
#print split_s
#
#for word in split_s:
# if word.find("i") > -1:
# print "I found 'i' in: '{0}'".format(word)
#exploring useful aspects of strings
something = "completely different"
print dir(something)
print something.count("t")
print something.find("pl... |
5c8165a739dc7a53e4514348d5b2d034aea151e9 | 40586/Selection | /Selection_statements_devEx3.py | 528 | 4 | 4 | #kieran burnett
#3-10-2014
#selection-devEx3
hours = int(input(" Please enter the hours you worked this week: "))
pay = int(input(" Please enter your hourly rate: "))
pay_and_half = pay * 1.5
if hours > 60 or hours < 0:
print(" Nuber entered out of range (0-60)")
elif hours <= 40:
earned = pay * ho... |
71708817257fed908e9cad082a7f6cf7ac2967ec | doctorqueen/hello-world | /ex_03_01.py | 1,099 | 3.640625 | 4 | sh = input("Enter Hours: ")
sr = input("Enter Rate: ")
fr = float(sr)
fh = float(sh)
#xp = float(xh) * float(xr)
#print(fh,fr)
#xp = fh * fr
#print("pay:", xp)
if fh > 40 :
#print("overtime") 사실 출력문을 쓸 때는 프로그래머들이 주석처리를 한다. 마치 html과 css에서 특유의 방식으로 주석 처리하면서 확인하는 부분이 있듯이
# 파이썬 작업할 때도 반드시 이렇게 한다.
re... |
19266019ee6dda3ff02d387989bdddfe3034adac | akash7883/Tkinter-Tutorials | /icons,images.py | 454 | 3.71875 | 4 | from tkinter import *
from PIL import ImageTk,Image
root=Tk()
root.title("Akash Tkinter")
#set icon for my project
root.iconbitmap('2.ico')
#use of images in tkinter
'''
to use images in tkinter we need to use pillow package
'''
my_image=ImageTk.PhotoImage(Image.open("Capture.PNG"))
labl=Label(root,image=m... |
4ecb47fb06cbb9cbbe20299ff4c2d17a9472ebfa | Jacobsmi/DiscordPyBot | /app/bot.py | 3,968 | 3.671875 | 4 | from location_db_controller import Database
import discord
from discord.ext import commands
import os
def run_bot():
print("Running bot")
# Create an instance of the database that will store information for the project
loc_db = Database()
loc_db.create_connection()
# Create an instance of a bo... |
563546f5b953d8a2b7b512856a99df5b88aef108 | mmrraju/Coding-interview-preparation | /Arrays and Strings/06_findAinBOfString.py | 852 | 3.5625 | 4 | """ Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote """
magazine = input()
ransomNote = input()
def isMagazineInRansomNote(magazine, ransomNote):
d = {}
for ch in maga... |
5cc3a6c2e8b4cd7e7272d3a440e1491b0eeb25a2 | christinajoice/begin-set9 | /printnum.py | 92 | 3.78125 | 4 | #christinajoice
str=input()
num=''
for i in str:
if i.isdigit():
num=num+i
print(num)
|
305d3d4352d56f64a897cba97d4da6ef5712b81b | keppnisforritun/reiknirit | /Blossom algorithm/tests/generate.py | 1,017 | 3.546875 | 4 | from sys import argv
from random import randint
graphtype = argv[1]
if graphtype == "complete":
n = int(argv[2])
print(n, n*(n-1)//2)
for i in range(n):
for j in range(i+1,n):
print(i,j)
elif graphtype == "complete-bipartite":
n, m = map(int, argv[2:4])
print(n+m, m*n)
for ... |
d36b1b15e1dcf5e1b54812e7dcaabcee118445de | debdevops/LearningResources | /Python/array/palindrome.py | 596 | 4.03125 | 4 |
# Check Palindrome
def palindrome_check(str):
input_string = str
reverse_string = reverseString(str)
if(reverse_string == input_string):
return True
return False
def reverseString(str):
str =list(str)
start_index = 0
end_index = len(str) -1
while end_index > start_index:
... |
07d4c2cc9f4891e0ffd4afad23d55d3092a4270f | Alice-Scholze/IAA-python | /exercises/palindrome.py | 155 | 4.25 | 4 | # 2. Write a function that recognize palindromes
def palindrome_recongnize(word):
word = word.lower()
contrary = word[::-1]
return word == contrary |
7a33ee3d407ac8ec09a4898cd2cfd53eca320f1f | Abeelha/Udemy | /Curso Udemy/ex1.py | 1,334 | 4.25 | 4 | #Idade
Idade = int(input("Digite sua idade "))
#Condição da idade
if Idade >= 18:
print("Maior de idade")
elif 0 < Idade < 18:
print ("Menor de idade")
else:
print("idade inválida")
#Notas
Nota1 = float(input("Digite sua nota em Matemática "))
Nota2 = float(input("Digite sua nota em Filosofia "))
#Mé... |
d9bee8e9841bc183e4f4f4551b36d1b1d3d99c37 | Mystery-2-Dev/Programming_Hub | /Arrayss.py | 833 | 3.609375 | 4 | public class Arrayss:
def rotateSubArray(self, arr, l, r):
temp = arr[r]
for j in range(r, l-1, -1):
arr[j] = arr[j-1]
arr[l] = temp
return arr
def moveNegative(self, arr):
last_negative_index = -1
for i in range(len(arr)):
if arr[i] < ... |
8ddb8b39b814ae031e49a9ca998aab07127e8a33 | IlyaTroshchynskyi/python_education_troshchynskyi | /OOP_1/transport_additional_2.py | 7,051 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""calc
Implements the Transport and Engine
"""
import time
from abc import ABC, abstractmethod
class TransportInterface(ABC):
"""
Interface of Transport
"""
@abstractmethod
def start_drive(self):
"""
Interface start driving
"""
...
... |
9539c945b6063ffdcd398710f03d371056ec52f7 | IlyaTroshchynskyi/python_education_troshchynskyi | /algoritms/algoritms.py | 2,512 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""calc
Implements algorithms:
- Binary search
- Quick sort (iterative)
- Recursive factorial
"""
def factorial(number):
"""
Define factorial certain number.
"""
if number <= 0:
return 1
return number * factorial(number-1)
print(factorial(50))
tes... |
cb912718e0b5494a24bde392beee25915729e409 | IlyaTroshchynskyi/python_education_troshchynskyi | /python_advanced/iterator_.py | 687 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implements simple iterator
"""
class MyIterator:
"""
Implements simple iterator
"""
def __init__(self, value):
self.data = value
self.index = 0
def __getitem__(self, index):
return self.data[index]
def __iter__(self):
return ... |
923c07242420638d006efde8ef142f8e2c0ec607 | prachi126/digipodium_programs | /oops.py | 1,614 | 3.59375 | 4 | class Book:
def __init__(self,bid,btitle,aname,btype,bprice,stat):
self.bookID=bid
self.bookTitle=btitle
self.authorName=aname
self.bookType=btype
self.bookprice=bprice
self.status=stat
class Library:
def __init__(self,blist):
self.bookList=blist
def i... |
cf60a2657b46d2e0f00d1a38dca1cea382452f8c | HamzaTUC/Web_Development | /lecture_11_security/array.py | 226 | 4 | 4 |
numberList = []
n = int(input("Enter the list size : "))
print("\n")
for i in range(0, n):
print("Enter number at location", i, ":")
item = int(input())
numberList.append(item)
print("User List is ", numberList) |
b1ef5b492c523de9806dae5ba5e8afafb40f8f4c | danse-inelastic/DrChops | /histogrammode/reduction/vectorCompat/Normalizer.py | 2,232 | 3.578125 | 4 | #!/usr/bin/env python
# Jiao Lin Copyright (c) 2006 All rights reserved
class Normalizer( object):
def normalize( self, dataset, outputDataset, error, outputError,
tempVector = None):
"""normalize( dataset, outputDataset, error, outputError,
tempVector = None) -> (... |
b218f98f73996a2386343f7862ebcfd7a5f6c326 | lionheart1022/Python_Numpy_MultiProcessing | /textProcessing.py | 6,228 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 22:05:28 2018
@author: seniortasse
"""
class TextProcessor(object):
def __init__(self, text, phraseMaxLength):
self.text = text
self.phraseMaxLength = phraseMaxLength
self.clauses = []
self.phraseCount = dict()
... |
7f342286d61244c9fcaf48c93f055bb412e4026c | Hefados/Simple-Calculator | /main.py | 97 | 3.984375 | 4 | print("Simple Calculator")
number = input("Enter first number: ")
print("You entered " + number) |
e4b018aa44483d0eeed003818634cd3d785c2714 | Zahidsqldba07/python_exercises-1 | /exercise_7.py | 348 | 4.4375 | 4 | '''
Write a Python program to accept a filename from the user and print the extension of that. Go to the editor
Sample filename : abc.java
Output: java
'''
file_name = input('Enter file name with extension, example: abc.java')
if file_name == '':
file_name = 'abc.java'
name = file_name.split('.')[0]
ext = file_name... |
bf05c9d550f76d73b4331223ef7276e82bf25e17 | farahnorma/Homework3 | /randN.py | 434 | 4.09375 | 4 | #Norma
#randN
import random
numRolls = int(input("Number: "))
def rand():
sum = 0
for count in range(numRolls):
number = random.randint(1, 7)
print("Number rolled: ", number)
sum += number
return sum
z = rand()
print("Total sum: ",z)
a = z/numRolls
print("Average: ", a)
#A... |
330abc78fed65e08ce09afe4156b4970249f935c | AppzA7/wuxia | /wuxia.py | 1,163 | 3.546875 | 4 | import sqlite3
import sqls
class WuxiaWorld:
def __init__(self, db_file_path='./wuxiaworld.db'):
self.db_file = db_file_path;
self.baseUrl = "https://www.wuxiaworld.com/"
self.conn=None
self.createConnection()
self.__create_databases__()
def createConnection(self):
... |
09afea3d6f9583707a1d4df67214d273b676ff11 | chartbeat-labs/textacy | /src/textacy/preprocessing/normalize.py | 3,057 | 3.890625 | 4 | """
Normalize
---------
:mod:`textacy.preprocessing.normalize`: Normalize aspects of raw text that may vary
in problematic ways.
"""
import re
import unicodedata
from typing import Literal
from . import resources
def bullet_points(text: str) -> str:
"""
Normalize all "fancy" bullet point symbols in ``text``... |
3d1dbd2bc80da02e15615e838dabb12df5ef2446 | chartbeat-labs/textacy | /src/textacy/preprocessing/replace.py | 1,932 | 3.546875 | 4 | """
Replace
-------
:mod:`textacy.preprocessing.replace`: Replace parts of raw text that are semantically
important as members of a group but not so much in the individual instances. Can also
be used to remove such parts by specifying ``repl=""`` in function calls.
"""
from . import resources
def currency_symbols(te... |
3adb4f9cae5a36b16c8d8ef95c26f00c6fcbb65d | 2019jeetdas/global-volcanoes | /volcano.py | 13,999 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
# Reading and converting to CSV file
df = pd.read_table('/home/jeet/Desktop/all_volcano.txt')
df.to_csv("/home/jeet/Desktop/all_volcano.csv", encoding='utf-8',sep=',',index=False)
# Reading the newly created ... |
98be0b2790e4056f72e6f6638b1c29e507717187 | lubosz/wiithon | /estadistica.py | 5,979 | 3.8125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8 :
# miércoles, 21 de octubre de 2009
import math
from math import sqrt
##################### GENERAL #############################
def factorial(n):
if n == 0:
return 1.0
else:
return n * factorial(n-1)
def produ... |
74a66a073c511467d16f6f16145bccf253b40c96 | iluvmonster/python_tutorials | /day01/day01.py | 477 | 3.8125 | 4 |
def fibonacci(n):
a, b = 0, 1
for num in xrange(0, n):
a, b = b, a+b
# loop ends here
print a
words = ['cat', 'bat', 'rat']
for w in words:
print w
for i in range(len(words)):
if i == (len(words) - 1):
print words[i]
else:
print words[i] + ',',
for i in range(-len... |
5991392b7cbe7976892b782521d623c538c3d02e | eesiwoo/algorism | /answer/baekjoon2748_answer.py | 688 | 4 | 4 | ''' 후기
나는 처음 풀 때 정석을 몰랐고... 내 생각대로 풀었다.
나중에 찾아보면서 피보나치의 정석은 재귀함수를 이용하는 것이라고 알게 되었고, 그렇게 풀면 백준에서는 정답이 아니라는 것도 알게 되었다ㅋㅋㅋ
'''
def solve():
random = int(input())
if random == 0 :
print(0)
elif random == 1 :
print(1)
else :
Fibonacci(random)
def Fibonacci(random)... |
6910ab238319c3b2647ffe14e4981d73382e0d76 | eesiwoo/algorism | /answer/baekjoon2447_answer.py | 700 | 3.78125 | 4 | '''후기
재귀 또는 분할 정복으로 푸는 문제였다.
빈 공간의 경우 3으로 나눈 나머지값이 1인 경우 빈 공간인 규칙이였다.
생각을 구현하는게 꽤 어려워서 인터넷의 도움을 받았다.
'''
n = int(input())
k = 0
while n != 3:
n = int(n / 3)
k += 1
def stars(star):
matrix=[]
for i in range(3 * len(star)):
print(i)
if i // len(star) == 1:
matrix.append(star... |
2125dc610dd1e8b147741267f73ac7b4f556bc00 | frantzmiccoli/locax | /src/locax/location_generator/LocationGenerator.py | 5,582 | 3.734375 | 4 | import random
import time
import datetime
class LocationGenerator:
"""
This class should generate a location history for a single person.
A person has a dwelling / home which is their base point
A person has between 3 to 4 key points of interest
A person has 10 secondary points of interest
""... |
909cd0b2dc47998d69c5f507b1bbb139f872791a | J-A-S-0-N/1DAY-1COMMIT | /stack study/study3.py | 938 | 3.921875 | 4 | class stack:
def __init__(self):
self.stack_list = []
def push(self, data):
self.stack_list.insert(0,data)
def pop(self):
if self.stack_list == []:
return -1
else:
res = self.stack_list[-1]
del self.stack_list[-1]
... |
59610cf9272b126b9c1333efd0decdd4121f6683 | anhuafeng123/python | /过年9.py | 338 | 3.671875 | 4 | '''
g = list(range(1,1000001))
print(g)
'''
for i in range(1,21):
print(i)
s = list(range(1,1000001))
print(min(s))
print(max(s))
print(sum(s))
d = list(range(1,21,2))
print(d)
f = list(range(3,31,3))
for i in f:
print(i)
g = []
for a in range(1,11):
h = a**3
g.append(h)
print(g)
k = [j**3 for j in rang... |
1e458aedbf185ce1d1a843e78d12f0c451641862 | anhuafeng123/python | /过年6.py | 1,092 | 3.90625 | 4 |
list = ["朱宇程","路顺利","金红蕾","邓子林","刘亚楠",'宰俊培','宰俊仙','宰相的宰']
for i in list:
print("我将邀请%s和我共进晚餐\n"%i)
sd = len(list)
print("总共邀请了%s位与我共进晚餐"%sd)
ad = list[2]
print("%s无法参加参加晚餐"%ad)
list[2]=input("请输入重新要邀请的人:")
for i in list:
print("我将邀请%s和我共进晚餐\n"%i)
print("当前有一个大的餐桌,还有三个空位")
name1 = input("您要邀请的第一位是:")
name2 =... |
5d8d3b731675f2659369629168ec018fa798599b | anhuafeng123/python | /九九乘法表2.py | 220 | 3.578125 | 4 | for i in range(1,10):#从1开始循环,循环九次
count = 1#计数器从一开始
while count <= i :#
print("%d*%d=%d"%(count,i,count*i),end="\t")
count+=1#循环一次加一
print("")
|
5f6bb76bc267af3a1ada99721556bc61637bc229 | anhuafeng123/python | /王者荣耀1.py | 336 | 4.125 | 4 | num = 0
while num<3:
weizhi = input("请输入一个位置")
if weizhi == "ABC":
print("后裔,黄忠,虞姬")
elif weizhi == "肉盾":
print("程咬金,亚瑟")
elif weizhi =="法师":
print("王昭君,妲己")
elif weizhi == "刺客":
print("兰陵王,阿科")
num+=1
|
833131f89a19612946284285bb91a845b438b793 | anhuafeng123/python | /吃鸡鸡.py | 367 | 3.515625 | 4 |
def panduan(accont,passwd):
if len(account) <= 8 and len(passwd) <= 6:
print("登录成功")
else:
print("登录失败")
biaoti = "不会吃鸡"
print(biaoti.center(60,"*"))
def denglujiemian():
account = input("请输入账号:")
passwd = input("请输入密码:")
panduan(account,passwd)
denglijiemian(... |
603e9f3fa129154d6f17e95cb025be297327db4d | anhuafeng123/python | /过年17.py | 464 | 3.84375 | 4 | #租聘汽车
car = input("请输入您要租聘的汽车品牌:")
print("让我看看能不能找到您要租聘的%s"%car)
yongcan = int(input("请问有多少人用餐:"))
if yongcan >= 8:
print("对不起,没有空的餐桌了")
else:
print("有空的餐桌!祝您用餐愉快!")
ss = int(input("请输入您要输入的数字:"))
if ss % 10 == 0:
print("您输入的%s是10的倍数"%ss)
else:
print("您输入的%s不是10的倍数"%ss)
|
a863d14c55538ac451a63fd1d0f23f39f9964b5f | aynella/Function | /c.py | 195 | 3.8125 | 4 | import math
def IsPointInSquare(x, y):
if(abs(x)<=1 and abs(y)<=1):
return "YES"
else:
return "NO"
x=float(input())
y=float(input())
print(IsPointInSquare(x, y)) |
cb783fb7e61ca6d541f3b414a060d2e636810dc6 | ejette/flu_surveil | /county_level/find_max_r2.py | 1,739 | 3.53125 | 4 | def find_max_r2(deaths, covar_df, candidates_df):
# this function runs regression for the formula deaths ~ covar_df +
# one variable from candidates_df at a time
# then it finds the candidate covariate that gave the highest R^2
# and returns the R^2 value associated with the highest R^2
# and the ... |
7ab731812e62b8a74ae7d0bb26b76a9c7ee8976c | hozza94/Programers_Q | /sol.py | 809 | 3.765625 | 4 | def solution(bridge_length,weight,truck_weights):
answer = 0
bridge_on = [0]* bridge_length
curr_weight = 0
while truck_weights:
answer += 1
bridge_out = bridge_on.pop(0)
curr_weight -= bridge_out
if curr_weight + truck_weights[0] > weight:
bridge_on.append(... |
f2b50ed88af86cac1c6ecfc2f562754facd4983b | hozza94/Programers_Q | /월간코드챌린지2104/q.04.py | 473 | 3.671875 | 4 | from pprint import pprint
def solution(n, z, roads, queries):
answer = []
w = [[0 for _ in range(n)] for _ in range(n)]
v = set()
roads.sort()
for r in roads:
v.add(r[0])
v.add(r[1])
w[r[0]][r[1]] = r[2]
v = list(v)
pprint(w)
print(v)
return answer
n =... |
b3c6d63e1aef1a7bfda6277bd811af7f1450fb12 | hozza94/Programers_Q | /완전탐색/모의고사.py | 1,118 | 3.609375 | 4 | # 1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
# 2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
# 3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...
# answers = [1,2,3,4,5]
# return = [1] //
# answers = [1,3,2,4,2]
# return = [1,2,3]
def solution(answers):
answe... |
1c2b9b103e1647dc5e09dbcb1742f95536ac1d18 | tohungsze/Python | /interactive_python/memory_game.py | 3,899 | 3.640625 | 4 | # implementation of card game - Memory
import simplegui
from random import shuffle
# global variable
n = 16
cards = [i for i in range(8)] * 2 # boolean, not string
exposed = [False for i in range(16)]
state = 0
counter = 0
exposed = [False for i in range(16)]
line_width = 800 / n
counter_skip = 0
# helper function... |
31e0794ad9981a270497e4cd91c2b9dbe52ea0f3 | tohungsze/Python | /other_python/palindrome.py | 869 | 4.1875 | 4 | '''
check if a given word is a palindrome
'''
def main():
input = ['abcba', 'abc1cba', 'abcba ', 'abc1cba1']
for word in input:
if is_palindrome(word):
print('\'%s\' is a palindrome'%word)
else:
print('\'%s\' is a NOT palindrome'%word)
def is_palindrome(input): #... |
9ce0cec8b92e20b92a39e6e5d1af707c3db4fb27 | tohungsze/Python | /other_python/fibonacci.py | 1,139 | 4.28125 | 4 | # demonstrate fibonacci with and without caching
'''
# this is really slow, can't handle more than 30 ish numbers
def fibonacci_n(n):
if n == 0 or n ==1:
return 1
else:
return fibonacci_n(n-1) + fibonacci_n(n-2)
for i in range(1, 11):
print("fibonacci(", i, ") is:", fibonacci_n(i))
'''
''... |
e87123d6807b100e5eef89b005a3948142c47854 | fqlovetu/likou_python | /38外观数列/solution1.py | 1,697 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time :2020/7/8 9:44
# @Author :Sheng Chen
# @Email :sheng.chen@inossem.com
import sys
sys.path.append(r'/home/chensheng/likou')
from typing import List
# 给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。
#
# 注意:整数序列中的每一项将表示为一个字符串。
#
# # 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如... |
912336eb0a16a0885bb9b646cad1fa93195255bb | lexpol/python_homework | /lesson08/lesson08-1.py | 1,386 | 3.96875 | 4 | # 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата
# «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать
# число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, долже... |
9a4bc37bfa274429ca02bbb6e5f24c36a22aefdf | lexpol/python_homework | /lesson01/lesson01-4.py | 552 | 4.0625 | 4 | # 4. Пользователь вводит целое положительное число. Найдите самую большую
# цифру в числе. Для решения используйте цикл while и арифметические операции.
number = input("Введите целое положительное число >>>")
max = 0
i = 0
while i <= len(number) - 1:
if int(number[i]) > max:
max = int(number[i])
i += 1... |
6dd63bae1456b965f6548f6192725cbc6b669b52 | lexpol/python_homework | /lesson04/lesson04-6.py | 1,793 | 3.90625 | 4 | # 6. Реализовать два небольших скрипта:
#
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
#
# Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл
# не должен быть бесконеч... |
6bc8b50244e525be040766cfd8aa99f35b747366 | AlbertStebbins/tlpipe | /tlpipe/rfi/winsorized_stats.py | 1,705 | 3.640625 | 4 | """This implements some Winsorized statistical methods.
A sample :math:`x_1, \\cdots, x_n` is sorted in ascending order. For the
chosen :math:`0 \\le \\gamma \\le 0.5` and :math:`k = [\\gamma n]`
winsorization of the sorted data consists of setting
.. math:: W_i = \\left \\{ \\begin{array}{lll}
x_{(k+1)}, & ... |
ff7c0a83280f5080fcef88e288d96fbeda29289e | prashantkgajjar/Machine-Learning-Essentials | /16. Hierarchical Clustering.py | 2,929 | 4.15625 | 4 | # Hierarchical Clustering
'''
1. Agglomerative Hierarchical Clustering (Many single clusters to one single cluster)
1. Make each data point as a single point Cluster.
2. Take the two closest datapoints, and make them one cluster.
3. Take to closest clusters, and make them one cluster.
4. Repeat STEP 3 ... |
d69286401257b48868831dd3c698916c33313fd7 | denaumenko/Python-Bash-interaction-with-os | /4 chapter/somescript.py | 264 | 3.65625 | 4 | #!/usr/bin/env python3
import sys
import os
filename = sys.argv[1]
if not os.path.exists(filename):
with open(filename,"w") as f:
f.write("New file created\n")
else:
print("Error, the file {} already exists!".format(filename))
sys.exit(1)
|
a37060def6b1333ff99fef976a78199d6b9603da | Jahishigh/TTR-python | /For Loop.py | 724 | 4.25 | 4 | # for prend une condition en variable, à chaque passage de la loop la variable va changer jusqu'à arriver à la condition
# la variable après le for peut avoir n'importe quel nom, c'est la condition final qui compte
for letter in "Hello":
print(letter)
list_de_value = [1, 2, 3]
for value_in_list in list_de_value:
... |
0337c7b7184b786c89548f4d3d3a6b3ef241b843 | HsiaoT/Python-Tutorial | /numpy/example1.py | 1,083 | 3.5 | 4 |
# -*- coding: utf-8 -*-
import numpy as np
# ndim 維度
# shape。形狀
# dtype 數值類型
np1 = np.array([1,2,3])
print(np1.ndim, np1.shape, np1.dtype) # 一維, 三個元素, int64
print("\n========\n")
# 矩陣相加
np1 = np.array([1, 2, 3])
np2 = np.array([4, 5, 6])
print(np1 + np2)
print("\n========\n")
# 改變維度
np1 = np.array([1, 2, 3,... |
46f00d7477c651dfad113fa2dd6591fa3519efd7 | HsiaoT/Python-Tutorial | /file_handling/txt/example_txt.py | 554 | 3.765625 | 4 |
# Open a text file and read all the file
fh = open("hello.txt", "r")
res1 = fh.read()
print(res1)
fh.close()
print("\n ================== \n")
# read one line at a time
fh = open("hello.txt", "r")
res2 = fh.readlines()
print(res2)
fh.close()
print("\n ================== \n")
# read one line at a time
fh = open(... |
18202ef9f99fe1c84f9ead4192d7539271646fc6 | HsiaoT/Python-Tutorial | /pytorch/9_dataloaders/9_dataloaders.py | 7,217 | 4.25 | 4 | # -*- coding: utf-8 -*-
# refer to https://pytorch.org/tutorials/beginner/data_loading_tutorial.html
"""
pytorch.ipynb
Automatically generated by Colaboratory.
"""
import pandas as pd
import numpy as np
# PART 1: read CSV and reshape annotations into 68x2 Array
# ==================================
landmarks_frame = ... |
5f4d01e512104db3e264784891663d304937ed96 | HsiaoT/Python-Tutorial | /data_structure/Sorting/Selection_sort.py | 802 | 4.28125 | 4 |
# The selection sort algorithm sorts an array by repeatedly finding the
# minimum element (considering ascending order) from unsorted part and
# putting it at the beginning. The algorithm maintains two subarrays in a given array.
# Time complexity (average): O(n^2)
# Time complexit (best): O(n^2) (list already sor... |
d9bc14d8ae35cb2475bb92bcc8d99446694bc590 | sunDalik/Information-Security-Labs | /lab1/frequency_analysis.py | 2,879 | 4.3125 | 4 | import argparse
# Relative letter frequencies in the English language texts
# Data taken from https://en.wikipedia.org/wiki/Letter_frequency
theory_frequencies = {'A': 8.2, 'B': 1.5, 'C': 2.8, 'D': 4.3, 'E': 13.0, 'F': 2.2, 'G': 2.0, 'H': 6.1, 'I': 7.0,
'J': 0.15, 'K': 0.77, 'L': 4.0, 'M': 2... |
a54af5802101341b5778deb2d704ba6d8101a888 | luckychummy/practice | /DLLImplementation.py | 2,575 | 3.75 | 4 | import gc
class Node:
def __init__(self, data):
self.data=data
self.next=None
self.prev=None
class DoublyLinkedList:
def __init__(self):
self.head=None
def push(self, data): # insert a new node to the front of the list
newNode=Node(data)
newNode.next=self.head
if self.head is not None... |
f7d769dd2e4fc9862f83a208c6a765ac8887928f | luckychummy/practice | /insertionSort.py | 304 | 3.984375 | 4 | def insertionSort(arr):
n = len(arr)
for i in range(1, n):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
A=[12, 11, 13, 5, 6]
print(insertionSort(A))
#i=1, j=0 11, 12, 13, 5, 6, key=11
#i=2, j=1 11, 12, 13, 5, 6, key=
#i=3, j=2 key=5
|
43d13ff7618da5d40d799670b7ead03063bff851 | luckychummy/practice | /StringPermutaion.py | 121 | 3.703125 | 4 | def permutations(str):
str1="ABC"
return str1.lower() == str.lower()
def main():
print (permutations("abc"))
main() |
ccd17da0c20a05b47deb8abe5432dbf439627036 | luckychummy/practice | /bubbleSort.py | 214 | 3.953125 | 4 | def bubbleSort(arr):
n=len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j+1]<arr[j]:
arr[j+1], arr[j] = arr[j],arr[j+1]
return arr
A=[5,3,4,2,1]
print(bubbleSort(A))
#i=1, j=0, 3<5, |
50d5314cda34ce36b4af6d37acdc81b3a87a17f8 | luckychummy/practice | /queueUsingStack.py | 1,222 | 4.28125 | 4 | from queue import LifoQueue
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1=LifoQueue()
self.q2=LifoQueue()
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
... |
d4a44ea867300893183f6e98e5c128663a125205 | aj112358/data_structures_advanced | /Selection/quick_select.py | 900 | 3.9375 | 4 | """An implementation to find the k-th smallest element in a collection.
Created By: AJ Singh
Date: March 29, 2021
"""
from random import choice
def quick_select(s, k):
"""Return the k-th smallest element from the list 's'."""
if not 1 <= k <= len(s):
raise ValueError("Value of k must be positive in... |
6abd19f313bcebbb0ce08dac1227402598776d2c | aj112358/data_structures_advanced | /Hash_Tables/hash_map_separate_chaining.py | 1,569 | 3.875 | 4 | """Implementing a hash map using separate chaining for collision handling, taken from book.
Created By: AJ Singh
Date: April 16, 2021
"""
from unsorted_map import UnsortedMap
from hash_map_base_class import HashMapBase
class ChainHashMap(HashMapBase):
"""A hash map implementation using separate chaining for col... |
e429189d135e942e502e5dab5b828d59dc760d26 | aj112358/data_structures_advanced | /Hash_Tables/sorted_map.py | 5,513 | 3.953125 | 4 | """An implementation of a "sorted map", where the keys are sorted using the natural ordering on the keys, taken from
book.
Created By: AJ Singh
Date: April 18, 2021
"""
from hash_map_base_class import MapBase
class SortedTableMap(MapBase):
"""A map implementation using a sorted array."""
# ----- Non-Public... |
a880f23612eef14a97027ff9bd4437b96596c8d3 | aj112358/data_structures_advanced | /Priority_Queues/heap_priority_queue.py | 2,864 | 3.640625 | 4 | """An implementation of a heap-based priority queue, using an array as the underlying data structure.
Created By: AJ Singh
Date: April 27, 2021
"""
from priority_queue_base_class import PriorityQueueBase
class Empty(Exception):
"""The error to raise when attempting to access an element from an empty priority qu... |
dc07a93d841ac95387a1562817fe24108bd3c266 | aj112358/data_structures_advanced | /Arrays/time_complexity_array_methods.py | 1,387 | 3.984375 | 4 | """This module investigates the time complexity of various array/list methods.
Some of the code is taken from the 'evaluate_append_operation.py' module.
Created By: AJ Singh
Date: Feb 18, 2021
"""
from time import time
from tabulate import tabulate
from Arrays.dynamic_array_implementation import DynamicArray
# prin... |
74205124e18c0b31694be66cd32381931ec150af | amarish-kumar/Hackerearth-Problems | /Basic Programming/Strange Addition.Py | 319 | 3.90625 | 4 | '''https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/the-reversed-numbers/description/'''
t=int(input())
for i in range(t):
s1,s2=input().split()
s1=s1[::-1]
s2=s2[::-1]
s3=int(s1)+int(s2)
s3=str(s3)[::-1]
print(int(s3))
|
c76d014cd88eccd7f5bebbed7196038cfd374116 | PetrNikiforov14041995/polish-notation | /notaotion.py | 1,489 | 3.953125 | 4 | def user_input():
user = input('Что-бы реализовать польскую нотацию введите знак операции и через пробел два числа \n(Пример: + 2 2) \n')
return user
def calc(self):
function_length = len(self.split())
sign = self.split()[0]
if function_length != 3:
print('Не верный ввод! Повторите!')
print(len(se... |
018653cc1dc122295f7c0ff093de6ca94aae5692 | rsigogne/brand_image | /script/twitter_streaming_hashtag.py | 1,945 | 3.546875 | 4 | # Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# Variables that contains the user credentials to access Twitte... |
08425a619af5755f6ed9bada0118b66e295b9f01 | tony-ml/algs200x-4 | /fibonacci_last_digit/solution.py | 368 | 4.03125 | 4 | def fibonacci_last_digit(n):
previous_to_last_digit = 0 # F(0) = 0
last_digit = 1 # F(1) = 1
for ind in range(2,n+1):
temp = last_digit
last_digit = (last_digit + previous_to_last_digit) % 10
previous_to_last_digit = temp
return last_digit
if __name__ == '__main__':
n = int(... |
0490aadbd1ad9867125da762b31557a61d901434 | tony-ml/algs200x-4 | /fibonacci-sum-last-digit/solution.py | 587 | 4.1875 | 4 | def fibonacciSumLastDigit(n):
KNOWN_VALUES = [0, 1, 2, 4, 7, 2, 0, 3, 4, 8,
3, 2, 6, 9, 6, 6, 3, 0, 4, 5,
0, 6, 7, 4, 2, 7, 0, 8, 9, 8,
8, 7, 6, 4, 1, 6, 8, 5, 4, 0,
5, 6, 2, 9, 2, 2, 5, 8, 4, 3,
8, 2, 1, 4, 6, 1, 8,... |
9bef8e5e35bf8e3188ae4b76e9e4ab3110a1b9ba | tony-ml/algs200x-4 | /fibonacci/test.py | 877 | 3.5625 | 4 | import random
import time
import unittest
from naive import fibonacci as fibonacciNaive
from solution import fibonacci as fibonacciSolution
TIME_LIMIT_SECONDS = 5
class FibonacciTest(unittest.TestCase):
def test_trivial_case(self):
self.assertEqual(5, fibonacciNaive(5))
self.assertEqual(55, fibon... |
9a184efb35bd7f0c7ca5a5add099a836a06cb4db | tony-ml/algs200x-4 | /max_pairwise_product/solution.py | 468 | 3.640625 | 4 | def computeMaxPairwiseProduct(integers):
numbers = list(integers)
product = 1
for dummy_ind in range(2):
max_index = numbers.index(max(numbers))
max_number = numbers.pop(max_index)
product *= max_number
return product
if __name__ == '__main__':
total_nums = int(raw_inpu... |
1e06955658ba293bb719b60b9dab72b75bbab7c4 | norcimo5/cenv | /cenv/path.py | 2,462 | 4.0625 | 4 | """Manipulates path."""
import os
import typing as t # NOQA
def get_path_seperator():
# type: () -> str
"""Returns character that seperates directories in the PATH env variable"""
if 'nt' == os.name:
return ';'
else:
return ':'
def get_paths():
# type: () -> t.List[str]
"""... |
fbf425c54ecd9fb82c40629eac26ca39981f7434 | ICTKevinWong/webservices-samples | /authentication/login.py | 3,972 | 3.78125 | 4 | """
Examples of authenticating to the API.
Usage:
login <username> <password> <server>
login -h
Arguments:
username ID to provide for authentication
password Password corresponding to specified userid.
server API endpoint.
Options:
-h --help Show this screen.
--version Show version.
Descrip... |
7f3bd3291e9f51b7c2b5594c8e7006ba39588119 | lfeathe/gor-purdue | /src/agent/goal.py | 2,028 | 3.765625 | 4 | """
Goal class
This describes and stores (sub-)goals and their relationships
Types,
Conjunctive: achieving both sub goal A and B can attain the parent goal
Disjunctive: achieving more than one of the sub goals satisfies attainment of the parent goal
"""
'''
Create a goal from a given ... |
bdd9576f630c8089dcc5b5a1e39b84da3e10e592 | JustsomeOtaku/oyakata-sama | /Tag 4.py | 320 | 3.90625 | 4 | Zahl = []
try:
while Zahl != str:
Zahl.append(int(input("Geben sie eine Zahl")))
print(Zahl)
except:
print("Die Größte Zahl ist:", max(Zahl),"Die kleinste Zahl ist: ",min(Zahl),"Der durchschnitt beträgt",sum(Zahl)/len(Zahl) )
Zahl.sort()
print("Sotiert lautet die Liste:",Zahl) |
a25a3b1c65625ba9e2195eeb777c18556b80cb62 | SHAANBHAYA/LeetCodeSolutions | /5. Longest Palindromic Substring/solution.py | 1,317 | 3.5625 | 4 | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
len_of_s = len(s)
is_Palindrome=[]
for i in range(len_of_s):
list=[]
for j in range(len_of_s):
if i==j:
list.append(1)
... |
2249565cc0b01acac114ba5b593f1c648eedca49 | maoyan1997/AID1911my | /static/fork.py | 489 | 3.75 | 4 | """
fork 进程基础演示
"""
import os
import time
print("============================")
a = 1
pid = os.fork()
if pid < 0:
print("创建进程失败")
elif pid == 0:
time.sleep(2)
print("创建新的进程")
print("a = ",a) # 父进程在fork前开辟的空间子进程也拥有
a = 10000
else:
time.sleep(3)
print("这是老进程")
print("a:",a) #子进程改变不会影响父进程... |
66619ccaa3c0cccb9e1045a5eb1dba74907b7683 | r2dtu/AdventOfCode2016 | /Day 19/Day19(2)_AnElephantNamedJoseph.py | 1,248 | 3.84375 | 4 | """
Implemented as a doubly-linked list. This is more efficient than
the Day19.py, because that uses list's remove(), which as a very
bad worst case runtime. Thank you Gary from CSE 12 and CSE 15L.
"""
# Generic Doubly Linked List Node
class Node:
# Add Node
def __init__(self, data):
self.nxt = None
self.prv ... |
8e06c6607e21df58b8571b900656b93b8870370e | Kalnoch/coding_exercise | /number_guesser.py | 2,034 | 3.9375 | 4 | __author__ = 'Stuart Glassett'
# Write a program to guess a number in a given range in at most 1 + log2n
# Print welcome message
print("Welcome to the guessing game! In this game, you think of a number, 1 to n, and I will try to guess it."
"After each guess, enter 'h' if my guess is too high, 'l' if it is too l... |
85ea58c4bc78227183f63faaa0c1c57fa752df1e | phunc20/codelearn | /train/sell-candies01/python/03_sol_divide_conquer.py | 1,213 | 3.65625 | 4 | def sellCandies1(n):
def sellCandies0(k, small=9, big=20):
max_ = k // small
if small*max_ == k:
return max_
else:
for s in range(max_-1,-1,-1): # i.e. s = max_-1, max_-2, ..., 2, 1, 0
b_float = (k - s*small) / big
b_int = int(b_float)... |
52f4da0e1d6efed40e7a15c58f8d0df979dc3cbb | phunc20/codelearn | /train/t-primes/python/01_prime_square.py | 732 | 3.921875 | 4 | def collect(a,b):
import math
def is_prime(n):
if n == 1:
return False
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def is_prime_squared(n):
sqrt = math.sqrt(n)
if sqrt != math.floor(sqrt... |
395d7b7d7cbae7e5c6df83a9e214b06ba5c22449 | phunc20/codelearn | /train/redundancy-number/python/01_sol.py | 1,201 | 3.875 | 4 | def redundancy_number(n):
if n <= 0:
return n
import math
def is_redundant(k):
# --------------------------------------
# Implementation 01: Too slow, probably
# --------------------------------------
#somme = 0
#for i in range(1, k):
# if k % i ==... |
57ce543b0c4c8d1db1b89846b81bb0ab3ccd1135 | eslopezag/book_recommendations | /Test data/insert_test_data.py | 3,051 | 3.5625 | 4 | """
This script inserts the `test data in `reviews_to_insert.csv` to the database
through the API by signing up users (with random usernames provided by the
Random User API) and registering their book reviews.
To run this script, the mongoDB container must have its 27017 port exposed and
mapped to the host's own 27017... |
b43811818ecd2c28c319c029d55ea53ebbb9b8fa | tuanchancutehotme/Mia-Assistant | /data/main_lib.py | 583 | 3.8125 | 4 | while True:
num = input("Vui lòng nhập vào một con số nhé! ")
try:
val = int(num)
print("Dữ liệu bạn nhập vào là số.")
print("Giá trị của nó là: ", val)
break; # Thoát khỏi vòng lặp
except ValueError:
try:
val = float(num)
print("Dữ liệu nhập v... |
86d3c24cdf7437e60a7d298e502b724725ae4ba4 | veraposeidon/CodeCraft2019-Python | /src/utils.py | 3,117 | 3.59375 | 4 | # coding:utf-8
def read_road(road_path):
"""
道路信息读取
format: (id,length,speed,channel,from,to,isDuplex)
:param road_path:
:return:
"""
roads_dict = dict()
with open(str(road_path), 'r') as f:
for line in f.readlines():
if line.startswith('#'):
continu... |
c379cda7b0dc49085d495069d924f801ce50093c | kaakash29/Python-Dev | /Python/projects/Principles Of Computing/wk02/2048_Complete.py | 9,103 | 3.796875 | 4 | """
Clone of 2048 game.
"""
import poc_2048_gui
import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1,0),
LEFT: (0, 1),
RIGHT:(0,-1)}... |
9723e7e1c7d0d34df067f566742505709710a00b | ncsurfus/cp-parse | /cp_parse/token.py | 3,316 | 3.703125 | 4 | """Provides methods for reading tokens from the Check Point configuration format."""
import collections
import enum
Token = collections.namedtuple("Token", ["value", "type", "offset"])
class TokenType(enum.Enum):
"""Represents the type of token."""
OBJECT_NAME = 1
OBJECT_OPEN = 2
OBJECT_CLOSE = 3
... |
a64758fe031650546617310d9a3a9f9b0f4644b9 | Aasmin/UWO | /CS 1026/Assignment 3/sentiment_analysis.py | 6,482 | 3.8125 | 4 | ##
# TA: Aasminpreet Singh Kainth
# This sentiment_analysis module contains the functions necessary for reading tweets and determining
# the happiness values of them. It also determines time-zones and calculates averages.
# Import all punctuation symbols from "string" module
from string import punctuation
#
... |
1834e0fbbf1605a5daa614d2ad59a50a3d1e69ff | washucode/Password_Locker | /usercredentials.py | 2,212 | 3.921875 | 4 | import pyperclip
import random
import string
global list_user
class users:
'''
class to create users and save their information
'''
list_user = []
def __init__(self, firstname, secondname,username,password):
'''
method to initialize properties that each user object will hold
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.