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 |
|---|---|---|---|---|---|---|
5a36f965e2541e6ce30f6fd3377dd57daab2bf7a | uschwell/DI_Bootcamp | /Week4 (18.7-22.7)/Day4 (21.7)/InClass.py | 140 | 3.53125 | 4 |
def calculation(a,b):
add=(a+b);
sub=(a-b);
return {'add':add, 'sub':sub};
res=calculation(5,10);
print('Hello');
print(res); |
645c55df56bb35c989298bedbd8d055613ad5667 | thandosi/recursion | /main1.py | 335 | 4.09375 | 4 | # defining
def recur_fibo(n):
if n ==0:
return 0
if n==1 or n==2:
return 1
else:
return recur_fibo(n - 1) + recur_fibo(n - 2)
# ask user for how many numbers
numbers=int(input("how many numbers"))
for x in range(0, numbers):
print(recur_fibo(x), end=" ")
# use end= to put the on... |
7cb9c0d0c6c94c8dcd65f3dea603ae8ea8580156 | Karlar14/lab-10-more-loops | /hanoi.py | 395 | 3.859375 | 4 | # this is the hanoi code
def hanoi(n,f,h,t): # n = number of disks, f = from position, h = helper positioq, t = target position
if n==0: # if the number is 0, then stop the program
return
hanoi(n-1,f,t,h)
print("move disk", n, "from", f, "to", t)
hanoi(n-1,h,f,t)
n = 4
hanoi(n,"a,","b","c"... |
490219f0295e2227a56b4ffa128205a20944b4ef | eera-l/Brexit_classifier | /fleiss.py | 1,550 | 3.5625 | 4 | # From https://github.com/Shamya/FleissKappa
'''
Created on Aug 1, 2016
@author: skarumbaiah
Computes Fleiss' Kappa
Joseph L. Fleiss, Measuring Nominal Scale Agreement Among Many Raters, 1971.
'''
def checkInput(rate, n):
"""
Check correctness of the input matrix
@param rate - ratings matrix
@return n... |
eaa0b6cc680df34251e35cae6a369f08a8a0e8fc | Provence-w/pyprimer3 | /fileutils.py | 2,773 | 3.515625 | 4 | """File utilities for the pyprimer3 Flask app.
Handles reading CSV and Excel files into dictionaries.
Includes a routine to write Primer data to CSV.
"""
import csv
import xlrd
from pclass import Primer
__author__ = "Joe Carli"
__copyright__ = "Copyright 2014"
__credits__ = ["Joe Carli"]
__license__ = "GPL"
__versi... |
14fb2fc6ed66c1107b0ac1a270b69de65acb6687 | alecgg/ctci | /object_oriented/object_oriented.py | 572 | 3.796875 | 4 | from enum import Enum
from random import shuffle
class Suit(Enum):
SPADE = 1
CLUB = 2
DIAMOND = 3
HEART = 4
class Rank(Enum):
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 11
QUEEN = 12
KING = 13
ACE = 14
... |
a969b55f3a2ffd6c8aa80813a7ca44cf4e922fc8 | alecgg/ctci | /bit_manipulation/bit_manipulation.py | 5,547 | 4.375 | 4 | # 5.1 Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and
# j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You
# can assume that the bits j through i have enough space to fit all of M. That is, if
# M = 10011, you can assume that there are at least ... |
925222a45a9d2d22375a0ccd9da3206bc43630b9 | annagi98/python-exercises | /sieve_of_atkin.py | 1,083 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 11 17:09:06 2017
@author: Ania
"""
#writing out prime numbers up to a certain number
import math
is_prime = list()
limit = int(input("Write out prime numbers up to a number: "))
import time
start_time = time.time()
is_prime = [False] * (limit + 1)
for x in ... |
3f7d5cc212695f3f9459c5dca44d05d5a318c61c | vyanphan/codingchallenges | /reverse_linked_list.py | 1,270 | 4.21875 | 4 | '''
Reversing a singly linked list in-place.
You should be able to do this in O(n) time.
Do not put the items into an array, reverse the
array, and put them back into the linked list.
'''
'''
For testing purposes.
'''
class LinkedNode(object):
data = None
next = None
def __init__(self, data):
sel... |
47c52239a862d693010207f8477f58140a372fe7 | vyanphan/codingchallenges | /regex.py | 1,940 | 4.28125 | 4 | '''
Make a simple regex function that matches * and +
+ matches any single or empty character
* matches any sequence (including empty)
text: 'baaabab'
regex: 'baa*a++' True
regex: 'ba*a+' True
regex: 'a*ab' False
'''
def regex_match_recursive(string, regex):
if string == '' and regex == '':
retur... |
7e1ee7e29c833986cc626cbfd8cb720e45bdeecb | marcelomoreira291/Avalia-o-1 | /Questão 2.py | 252 | 3.96875 | 4 | #Questão 2
num1 = int (input ('Digite o primeiro número: '))
num2 = int (input ('Digite o segundo número: '))
def produto (num1, num2):
resultado = (num1 **4) / (num2 **2)
return resultado
print (f'O resultado é: {produto(num1, num2)}') |
4c02fdc239f755240c9a0cedd1e4e9eab57173bf | Tushaar28/CodeForces | /785A.py | 441 | 3.859375 | 4 | def countFaces(arr):
cnt = 0
for ele in arr:
if(ele == "Icosahedron"):
cnt += 20
elif(ele == "Cube"):
cnt += 6
elif(ele == "Octahedron"):
cnt += 8
elif(ele == "Dodecahedron"):
cnt += 12
else:
cnt += 4... |
1d88c2fe7cb94364285050cda21f20fc9c025146 | Tushaar28/CodeForces | /938A.py | 620 | 3.84375 | 4 | def makeSafe(arr):
done = False
while(not done):
index = []
if(len(arr) == 1):
return arr
for i in range(len(arr)-1):
global s
if(arr[i] in s and arr[i+1] in s):
index.append(i+1)
break
else:
... |
66864409d5857f9bc5b8eaf17fe78b4a2d42c8a8 | Tushaar28/CodeForces | /520A.py | 221 | 3.8125 | 4 | n = int(input())
s = input()
if(n < 26):
print("NO")
else:
se = set()
s = s.lower()
for char in s:
se.add(char)
if(len(se) == 26):
print("YES")
else:
print("NO") |
8c94f02eebe383790c8c48ff9842952c7b544553 | Tushaar28/CodeForces | /405A.py | 165 | 3.625 | 4 | def func(arr, n):
arr = sorted(arr)
for ele in arr:
print(ele, end = " ")
n = int(input())
arr = list(map(int, input().split()))
func(arr, n) |
de1af237694d34a0f8e2e6bf3b46384d904d4c22 | lzxysf/python | /算法与数据结构/数据结构/003.双向链表的实现.py | 3,300 | 4.0625 | 4 | # 定义链表中的节点
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
self.prev = None
# 定义双向链表
class DoLinkedlist(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head == None
def length(self):
... |
0e2cc31f8b44d787a8ca62f3ac5d90ec735a78ae | lzxysf/python | /cli/python_003_variable.py | 2,991 | 4.09375 | 4 | # coding=utf-8
# python的数据类型:数字、字符串、复数,列表、元组、字典
import json
a = b = c = 1
a, b, c = 1, 3.4, 'alice'
s = "hello world!"
x = '你好'
print(s[1:7]) # 前包含后不包含
print(s[1:])
print(s[-1:-5]) # 倒着数时候是前不包含后包含
print(s[:-1])
print(s+x)
print(x*2)
# 列表可以包含数字、字符串、另一个列表
# 列表用[]表示,元素之间用,隔开
list = ['runoob', 786, 2.23, 'john', 70.2]... |
016a3e160fc88d0477e0cf5bb126d8249c22e44d | lzxysf/python | /cli/python_009_dictionary.py | 1,728 | 4.0625 | 4 | # coding=utf-8
dict1 = {1: 'apple', "two": 'banana', '3': 'orange'}
print(dict1)
# 更新和添加字典元素
dict1[1] = 'pear' # 更新元素
dict1['four'] = 'ele' # 添加元素
print(dict1)
# 删除元素和删除字典定义
del dict1[1] # 删除某个元素
print(dict1)
dict1.clear() # 删除字典中的所有元素
print(dict1)
del dict1 # 删除... |
455be077602735e9346e23dc29689428a0ab9296 | lzxysf/python | /cli/python_027_threading.py | 2,593 | 3.84375 | 4 | import threading
import time
'''
threading.currentThread:返回当前的线程变量
threading.enumerate:返回一个当前正在运行的线程的list
threading.activeCount:返回正在运行的线程的数量,与len(threading.enumerate)有相同的结果
Thread类的方法
run() 用以表示线程活动的方法
start() 启动线程活动
join([time]) 等待线程终止
isAlive() 返回线程是否活动
getName() 返回线程名称
setName() ... |
736ae15482e3dca79f1e7820d17810aa7cc089ce | lzxysf/python | /cli/python_014_data_structure.py | 1,630 | 3.765625 | 4 | # coding=utf-8
# 堆栈是一个后进先出的数据结构
# 把列表当作堆栈使用,使用列表的append方法在堆栈顶插入元素,使用列表的pop方法在堆栈顶删除元素
import collections
stack = [3, 4, 5]
stack.append(9)
stack.append(10)
print(stack)
stack.pop()
print(stack)
# 队列是一个先进先出的数据结构
# 不可直接把列表当作队列使用,因为列表操作末尾数据进行添加删除比较容易,但
# 操作开头的数据进行添加和删除需要将列表中的元素一个个移动位置,因此效率是很低的
queue = collections.deque([... |
21360bf9fec454ffe7b9c05e97e6c26f328ec225 | lzxysf/python | /cli/python_043_dynamic.py | 2,333 | 4.3125 | 4 | # python是动态语言
# 动态语言是运行时可以改变其结构的语言
# C、C++是静态语言
import types
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{} is {} years old".format(name, age))
def eat(self):
print("i am eating")
p = Person('liming', 15) # liming is 15 years old
print(p... |
7fc4cf3ba22b9c533ef13b750c3245062f775fd5 | lzxysf/python | /算法与数据结构/数据结构/002.单向循环链表的实现.py | 4,025 | 3.921875 | 4 | # 定义链表中的节点
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
# 定义单向循环链表
class SinCycLinkedlist(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head == None
def length(self):
if... |
3b462dbfbfb1d5d3c1ae2847edf665aec3d3c844 | judong93/TIL | /algorithm/0824~/글자수.py | 283 | 3.625 | 4 | T = int(input())
for tc in range(1, T+1):
part = input()
text = input()
max_val = 0
for i in part:
cnt = 0
for j in text:
if i == j:
cnt += 1
if max_val < cnt:
max_val = cnt
print(f'#{tc} {max_val}')
|
20f9150fbe06132391f25ac0132b34da5b70ebc9 | KunwarBisht/Python-Assignment-L1 | /10_Solution.py | 312 | 4.0625 | 4 | ##Create a suitable object type to eliminate the duplicate elements
def remove_duplicates(numbers):
newlist = []
for number in numbers:
if number not in newlist:
newlist.append(number)
return newlist
newlist=remove_duplicates([1,2,3,4,5,5,5,6,3,2])
print( newlist)
|
a4486bd7fbad806237f4de0cda851c49a03ea809 | phdevs1/Comprogram | /uri/uri1021-recursive-fail.py | 755 | 3.5625 | 4 | a = float(input());
#new_value = "{:.2f}".format(value)
mount = [100,50,20,10,5,2,1,0.5,0.25,0.10,0.05,0.01];
def quantity_list(val,pos):
div = val/mount[pos];
mod = val%mount[pos];
mod = round(mod,2);
if pos==6:
print("MOEDAS:")
if pos< 6:
print("%i nota(s) de R$ %0.2f" % (int(div),mount[pos]))
else:
p... |
e95a996f670ed097d636f8034a33d66191e05136 | grodino/musclo-transfo | /optimisation.py | 1,122 | 3.84375 | 4 | import numpy as np
def cuvette(x, centre=0, tolerance=1):
"""
Fonction avec un mur de potentiel de chaque coté de de l'abscisse centre
avec une largeur de 2*tolerance
"""
return max(-1/(x-tolerance-centre), 1/(x+tolerance-centre))
def mur(x, position=0, direction='droite'):
"""
Fonction... |
81d93c8e9818b7c173f12545e3b8fb1fbc70ecf5 | JamieCass/pynotes | /searcher.py | 1,326 | 4.0625 | 4 | def search(lookup, file):
'''
Function to search through notes for certain phrase
Params
---------------
lookup: str
file: location of the file we are searching through
'''
with open(file) as f:
datafile = f.readlines()
function_lookup = [x for ... |
97b24b42b14a8a1e572c6271efa70b462ff393d6 | JamieCass/pynotes | /notes_searcher.py | 2,496 | 3.84375 | 4 |
import pandas as pd
import numpy as np
def check(lookup, file):
'''
Function to search notes for certain phrase
Params
------------------
lookup: str
file: location of file you are searching for
'''
with open(file) as f:
datafile = f.readlines()
retur... |
b84432a9236c94395f69f5b2842b883e078aec11 | JamieCass/pynotes | /robot_tests.py | 813 | 4.03125 | 4 | import unittest
from robot import Robot
class RobotTests(unittest.TestCase):
def setUp(self): # we setup a robot called Mega Man and then we can use this robot in every test below
self.mega_man = Robot("Mega Man", battery=50)
def test_charge(self): # a test that will check if charge will make batery... |
f9a606be81019cf9b6d13554758830f578f6e27f | Tarique-web/Sort-Algorithm | /Insorting Sort/Insertion_sort.py | 241 | 3.765625 | 4 | def insertion(list1):
for i in range(1,len(list1)):
temp = list1[i]
j=i-1
while j>=0 and list1[j]>temp:
list1[j+1] = list1[j]
j-=1
list1[j+1]=temp
return list1
list1 = list(map(int,input().split()))
print(insertion(list1))
|
f91db3604e04209e335ca55c923c65a6ea042689 | HackerSpot2001/Voilent-Python-with-Python3 | /checking_access_granted_or_not.py | 1,215 | 3.765625 | 4 | #! /usr/bin/python3
import os
filename = "new.txt"
# # print(file.write("This is from popen"))
# try:
# with open(filename,"r") as f:
# print(f.readlines())
# except IOError as e:
# print("Problem :- {}".format(e))
# if not os.access(filename,os.R_OK):
# print("Access Denied")
# else:
# pri... |
63ac99c24c8d23cbc598d0c29c8cb0f7ea348604 | HackerSpot2001/Voilent-Python-with-Python3 | /hash_cracker.py | 942 | 3.75 | 4 | #! /usr/bin/python3
import hashlib
def encryptHash(text):
encryptedHash1 = hashlib.sha512(text.encode()).hexdigest()
# print("{} :- {}".format(text,encryptedHash1))
return encryptedHash1
# encryptedHash2 = hashlib.md5(text).hexdigest()
# print(f"SHA512 :- {encryptedHash1}")
# print(f"MD5 :- {e... |
dc62822485a30e840d8f3f20c2148f413a697e18 | cs50/lectures | /6/src6/4/phonebook1.py | 270 | 4 | 4 | # Saves names and numbers to a CSV file
import csv
# Get name and number
name = input("Name: ")
number = input("Number: ")
# Open CSV file
with open("phonebook.csv", "a") as file:
# Print to file
writer = csv.writer(file)
writer.writerow([name, number])
|
d2234dab85f2fe4903aedebac989e0cbc2a8cbac | cs50/lectures | /7/src7/favorites/favorites4.py | 574 | 3.90625 | 4 | # Counts favorites using variables
import csv
# Open CSV file
with open("favorites.csv", "r") as file:
# Create DictReader
reader = csv.DictReader(file)
# Counts
scratch, c, python = 0, 0, 0
# Iterate over CSV file, counting favorites
for row in reader:
favorite = row["language"]
... |
ada3d4af2a46d69aaf500a69f7ec85d93793c63f | cs50/lectures | /6/src6/2/uppercase0.py | 152 | 4.4375 | 4 | # Uppercases string one character at a time
before = input("Before: ")
print("After: ", end="")
for c in before:
print(c.upper(), end="")
print()
|
f3aea61ace67cc701f4623a6919b344358e075ea | cs50/lectures | /6/src6/1/hello1.py | 141 | 3.53125 | 4 | # get_string and print, with concatenation
from cs50 import get_string
answer = get_string("What's your name? ")
print("hello, " + answer)
|
5e00780d49ac7f0cdb3c056cd367de5634254ba1 | cs50/lectures | /6/src6/1/mario2.py | 295 | 4 | 4 | # Prints a column of bricks, using a helper function to get input
from cs50 import get_int
def main():
height = get_height()
for i in range(height):
print("#")
def get_height():
while True:
n = get_int("Height: ")
if n > 0:
return n
main()
|
3d258ae10550904506cd95ae4faf9a74f64dff6d | BronsonLotty/SelfProjects | /mystudy/sort201810.py | 4,601 | 3.84375 | 4 | '''冒泡排序'''
import copy as cy
class BubbleSort(object):
def __init__(self):
pass
def swap(self,L,i,j):
temp = cy.deepcopy(L[j])
L[j] = cy.deepcopy(L[i])
L[i] = cy.deepcopy(temp)
return L
def bubblesort(self,L):
self.length = len(L)
for j in range(self.... |
c2f2da6c6eaa12070fa5ffcfff398f6581815c56 | BronsonLotty/SelfProjects | /mystudy/mysort.py | 9,394 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 07:51:39 2018
@author: xutingxi
"""
# 周三下午/晚上:树和图的遍历,插入删除
# 周四:数据库/查找
# 周五+周末:深度学习:自然语音处理/推荐算法/图像处理
# 18,19,20:深度学习/机器学习
# 21:30:论文写作
#冒泡排序初级-交换排序
#class struct():
# def __intial__(self,l):
# self.length=len(l)
#
# def s... |
9da9f1726be65f3b9634e75f1a9331d9daeed72b | ElasticDuckCode/project107_spring2018 | /capacitorFunctions.py | 7,082 | 3.609375 | 4 | #!/usr/bin/env python3
import math
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# Global Variables
Eo = 8.85e-12 # of free space
def printTitle():
print("\nWritten by Jake Millhiser and Lina Yi.",
"\nECE 107 Project: Discrete Capacitance of Square Capacitor... |
19f63cc48e31d066ff3af417e52df596571b6ec2 | Audarya07/99problems | /P06.py | 573 | 4.09375 | 4 | # Find out whether a list is a palindrome.
from LL import init_ll
def is_palindrome(LL):
curr = LL.head
ispalin = True
stack = []
while curr:
stack.append(curr.data)
curr = curr.next
while LL.head:
node = stack.pop()
if LL.head.data == node:
ispalin ... |
bc5a2f1f7114718e5cc4406e165f252bdde907be | Audarya07/99problems | /P33.py | 344 | 4.1875 | 4 | # Determine whether two positive integer numbers are coprime.
def gcd(a, b) :
if b == 0:
return a
return gcd(b, a%b)
num1 = int(input("Enter first number : "))
num2 = int(input("Enter Second number : "))
if gcd(num1, num2) == 1:
print("Given numbers ARE co-primes")
else :
print("Given num... |
307280ece36ccc8da01c1c2d20980cc30cb02ff8 | Audarya07/99problems | /P15.py | 565 | 3.984375 | 4 | # Replicate the elements of a list a given number of times.
from LL import init_char_ll, Node, LinkedList
def replicate(LL, k):
curr = LL.head
while curr:
for i in range(k-1):
node = Node(curr.data)
node.next = curr.next
curr.next = node
curr = node
... |
88b55522c9ed4b6670ea268c6a9adeb1b95be3fd | Audarya07/99problems | /P23.py | 1,094 | 4.09375 | 4 | # Extract a given number of randomly selected elements from a list.
from random import randint
from P03 import Kth_element
from P04 import length
from LL import init_char_ll, Node, LinkedList
def random_select(LL, n):
'''A function to extract a given number of randomly selected elements from a list
and return ... |
38b08a3205e61662c82c1fce1aa055514e2f926c | SeggevHaimovich/Python-projects | /Aestroids/asteroid.py | 2,520 | 4.75 | 5 | ###############################################################################
# FILE : asteroid.py
# WRITER : ShirHadad Seggev Haimovich, seggev shirhdd
# EXERCISE : intro2cs2 ex10 2021
# DESCRIPTION: the class: Asteroid
###############################################################################
import ma... |
fb7d8c1ec23bae1efef194428b871723d0e14cdd | AakashPawanGPS/Python-basics | /test/test_apppend_list.py | 419 | 3.625 | 4 | import unittest
from src.appending_list import append_list
class TestAppending(unittest.TestCase):
def test1(self):
result = append_list()
self.assertEqual([1, -2, 3, -4], result)
def test2(self):
result = append_list()
self.assertEqual(['ab', 'cd', 'ef', 'gh'], result)
... |
05897eaec2947169a906d1a092d5bc38f398d0ac | AakashPawanGPS/Python-basics | /test/test_identify_string_in_string.py | 627 | 3.546875 | 4 | import unittest
from src.identify_string_in_string import find_string
class MyTestCase(unittest.TestCase):
def test1(self):
result = find_string("Hell", "Hello world")
self.assertEqual("Exact match found", result)
def test2(self):
result = find_string("hell", "Hello world")
se... |
53b780c2588ea3478f4d32807859201b65abc0ab | AakashPawanGPS/Python-basics | /test/testdivision.py | 494 | 3.5 | 4 | import unittest
from src.division import div
class Divisiontest(unittest.TestCase):
def testdivision(self):
result=div(8,2)
self.assertEqual(4,result)
def testdivision_by_zero(self):
result=div(8,0)
self.assertEqual("Infinity",result)
def testdivision_by_float(self):
... |
1e54114f0bc67686c0473285a4ac9674ed49a087 | mmoshabe/hangman | /submission_002-hangman-loops/hangman.py | 4,130 | 4.15625 | 4 | import random
def read_file(file_name):
file = open(file_name,'r')
return file.readlines()
def get_user_input():
return input('Guess the missing letter: ')
def ask_file_name():
file_name = input("Words file? [leave empty to use short_words.txt] : ")
if not file_name:
return 'short_word... |
72c10bf3c3c19d0cba4749c6054f1928b369eec0 | oscar1234456/ntueIRC_Example | /constructor/initdefault.py | 353 | 3.609375 | 4 | class CRectangle(object):
width = 0.0
height = 0.0
def __init__(self,iWidth=3.0,iHeight=5.0):
self.width = iWidth
self.height = iHeight
def getWidth(self):
return self.width
def getHeight(self):
return self.height
rect1 = CRectangle(2.0)
print(rect1.get... |
68854d9053bfae82d37af8f6f57dd68dcad199f0 | guiguoershao/mine | /python3/turtle/5star_new.py | 309 | 3.78125 | 4 | # import turtle
# turtle.pensize(5)
# turtle.hideturtle()
# size = 200
# for i in range(5):
# turtle.forward(size)
# turtle.right(144)
# print(i)
# turtle.bgcolor('black')
# turtle.color('red')
# turtle.pensize(3)
# for i in range(24) :
# turtle.circle(100)
# turtle.right(15)
|
72d6b4325f57472dd12e761c53122eaa26a27a26 | wwr1227/ProjectEuler | /7.py | 195 | 3.6875 | 4 | import math
def is_prime(n):
for i in range(2,n):
if n%i == 0 :
return False
return True
count = 0
i = 2
while True:
if is_prime(i):
count+=1
if count == 10001:
break
i+=1
print i
|
2e9a701aba364eea59f9b466c78aae20e3d2098f | mike1130/02-Intr_Pens_Compu_Python | /fibonacci.py | 206 | 4.09375 | 4 | def fibonacci (n):
if n == 0 or n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
n = int(input('Escribe un entero: '))
print(f'La serie de Fibonacci para {n} es de {fibonacci(n)}')
|
5da4981dff9f0f3f04809630eb830b572f3ba9bd | zhang-ru/learn-Python | /codewars_Dec05 norepeating.py | 195 | 3.625 | 4 | def first_non_repeating_letter(s):
#your code here
t = s.upper()
for key, val in enumerate(t):
if len(t.split(val)) ==2:
return s[key]
break
else:
return ''
|
3bd47fdad8d7c36ddf0951188542f11f003a5650 | zhang-ru/learn-Python | /codewars_Dec02 sudu.py | 602 | 3.671875 | 4 | correct = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def validSolution(board):
# check rows
for row in board:
if sorted(row) != correct:
return False
# check columns
for column in zip(*board):
if sorted(column) != correct:
return False
# check regions
for i in... |
01c14cd7288260cba4b49232f6f2a700cda0b7e6 | gurmeetkhehra/python-practice | /tuple with different data types..py | 184 | 4.03125 | 4 | # 13. Write a Python program to create a tuple with different data types.
data_type = ("jasmine", True, 36, 5.1)
print(data_type)
tuple = ("Connie", 38, 'married', True)
print(tuple) |
1dcdafb730f5addeef92b23d02184f30de3bef2d | gurmeetkhehra/python-practice | /Listhomwork4.py | 614 | 4.25 | 4 | # 4. Write a Python program to check a list is empty or not. Take few lists with one of them empty.
fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana']
fruits1 = []
fruits2 = ['mango', 'strawberry', 'peach']
# print (fruits[3])
# print (fruits[-2])
# print (fruits[1])
# #
# print (fruits[0])
# print (fruits)
#
# f... |
7b26ca1f94edf461a9d7cbb57ad265ff700fdb81 | gurmeetkhehra/python-practice | /khivibicycle.py | 2,623 | 3.71875 | 4 | # cars =[ 'honda', 'toyota', 'volvo']
# friends =[ 'khivi', 'methab', 'heidi', 'aadhi']
# first_name = "khivi"
# last_name = "dhindsa"
# full_name = first_name + " " + last_name
# print ("Hello " + full_name.title() + "!")
# # print ("Hello" + full_name + "!")
#
# message = "My best friend is a " + friends [0].title ()... |
e6da2f83d04762dc1f9bac21fb6ad386ed3a94f8 | gurmeetkhehra/python-practice | /Square.py | 186 | 4.0625 | 4 | # 10. Write a Python function to return square of number provided by calling code
squared = 1
def square(n):
squared = n ** 2
return squared
print (square(10))
print (squared) |
a5425979739b98cbc08bc60c07ccfb200fbc2e09 | gurmeetkhehra/python-practice | /concatenate following dictionaries.py | 362 | 3.578125 | 4 | # 8. Write a Python script to concatenate following dictionaries to create a new one.
# Sample Dictionary :
# dic1={1:10, 2:20}
# dic2={3:30, 4:40}
# dic3={5:50,6:60}
# Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dic1 = {1:00, 2:20}
dic2 = {3:30, 4:40}
dic3 = {5:50, 6:60}
dic4 = {}
for d in (dic1,... |
b7636d70dee830d8fc3768790c4c264689f72808 | gurmeetkhehra/python-practice | /multiply all the items in a dictionary..py | 319 | 3.890625 | 4 | # 11. Write a Python program to multiply all the items in a dictionary
my_dict = {'data1':10,'data2':4,'data3':27}
answer = 1
for key in my_dict:
answer = answer* my_dict[key]
print (answer)
million = {'a': 40, 'b': 6, 'c':9}
total = 1
for key in million:
total = total * million[key]
print (total)
|
7a4bbf2f4340ee9f0cecb7080e9bb207fc207d18 | gurmeetkhehra/python-practice | /calculator.py | 462 | 3.8125 | 4 | def add(number1, number2):
return number1 + number2
def sub(number1, number2):
return number1 - number2
def multi(number1 , number2):
return number1 * number2
def div(number1, number2):
return number1 / number2
# addition_result = add(3, 5)
# print(addition_result)
#
# sub_result = sub(8, 6)
# p... |
960e7bb299837c370faec78d80f720de0c47a708 | gurmeetkhehra/python-practice | /magician.py | 2,059 | 4.09375 | 4 | # magicians = ['alica', 'david', 'carolina']
# for magicians in magicians:
# print (magicians)
# print (magicians.title() + ", the was a great trick! " )
# print ( "I can't wait to see you next trick, " + magicians.title() + ". \n")
# print ("Thank you everyone, that was a great magic show!")
for valu... |
608309973a1b4917b47c610e571f5c14b0fe521b | gurmeetkhehra/python-practice | /list after removing.py | 383 | 4.3125 | 4 | # 7. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
# Go to the editor
# Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
# Expected Output : ['Green', 'White', 'Black']
colors = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
colors.remove('Red... |
a29f0ca42991b52d22f538584f6cbc0b53587823 | mateusers/Homeworks-PYTHON | /matrix.py | 2,268 | 4.125 | 4 | print("Добро пожаловать в вычисление матриц!")
operacia = input("Вас интересует сложение или умножение матриц?\nЕсли сложение, то введите: +\nЕсли умножение, то введите: *\n")
x = int(input("1 число 'первой' матрицы: "))
y = int(input("2 число 'первой' матрицы: "))
z = int(input("3 число 'первой' матрицы: "))
m... |
c3f857293fef7eb413eddb18e629026bcbb4a653 | TasyaHarwati/PRAKALPRO | /LAB-10- Dictionary.py | 1,082 | 3.875 | 4 | #Tasya Setyo Harwati
#soal 1
'''kamu seorang mahasiswa teknik informatika sedang mengisi waktu luang. kamu
ingin menambahkan nama negara pada seseorang dengan tipe data menggunakan
dictionary '''
my_dict = {'nama':'Zerolima', 'umur':25}
my_dict['umur'] = 25
print(my_dict)
my_dict['Negara'] = 'Indones... |
35dda696593ffd0ce88bb61019e98b18f7a6847d | TasyaHarwati/PRAKALPRO | /LAB-7-String.py | 549 | 3.5 | 4 | #Tasya Setyo Harwatii
#soal 1
'''kamu sebagai mahasiswa teknik informatika diminta bantuan
oleh temanmu untuk membuat program yang dapat menghitung huruf
hidup pada suatu kalimat'''
a_string = "tasya seharwa"
lowercase = a_string.lower()
total = 0
for x in "atsy":
jml = lowercase.count(x)
total += jml
... |
65baab258df9b19e23fd361a087536b1c3464d5c | ticotheps/Intro-Python-II | /examples/rps.py | 1,003 | 4.09375 | 4 | import random
wins = 0
losses = 0
ties = 0
cmds = ["r", "p", "s"]
def compare_answers(player_choice, computer_choice):
if player_choice == computer_choice:
return 0
elif (player_choice == "r" and computer_choice == "s") or \
(player_choice == "p" and computer_choice == "r") or \
(play... |
509aaf973855d6106324fa36fa3b95a33ff79896 | marioeid/Machine-Learning-Random-Forest-Regression | /random_forest_regression.py | 1,821 | 3.8125 | 4 | # importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing our data set
dataset=pd.read_csv('Position_Salaries.csv')
X=dataset.iloc[:,1:2].values # x should always be a matrix try to change it to [:,1] you will see the differnece
y=dataset.iloc[:,2].values
# Splitti... |
522237f16f2ea405b0cb2afa37b95331bc9294b3 | gokayozcoban/3.b.g.-Data-Types---Strings---Metodlar---find-ve-index---aranan-harfi-kelimeyi-sayar-metin-icinde | /3.b.g. Data Types - Strings - Metodlar - find() ve index()- aranan harfi kelimeyi sayar, metin içinde kaçıncı sırada olduğunu.py | 1,115 | 4.125 | 4 | # find() ve index()
# Aranan karakterin veya kelimenin yerini bulurlar. Ama bunu sayı ile verir.
# Yani metin değişkeni içerisinde bir kelime ya da karakter arıyorsak
# find() ve index() metodları bize onun kaçıncı karakterde başladığını söyler.
# karakterleri saymaya 0'dan başlarlar. 0,1,2,3... gibi:
metin = """B... |
0a0675e97f9b903c4e125cd344f8ffe557d81047 | wudizhangzhi/leetcode | /easy/find-if-path-exists-in-graph.py | 821 | 3.796875 | 4 | from typing import List
class Solution:
def validPath(
self, n: int, edges: List[List[int]], source: int, destination: int
) -> bool:
if not edges:
return True
visisted = set()
adjList = [[] for _ in range(n)]
for a, b in edges:
adjList[a].appe... |
77fdaddab93cb6f55e9821e4ee10030ca66028b3 | wudizhangzhi/leetcode | /easy/same-tree.py | 1,496 | 4.03125 | 4 | """
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1... |
159759cbf6b45d8055eee09e730f96bfc646663a | wudizhangzhi/leetcode | /medium/reverse-linked-list-ii.py | 1,116 | 3.90625 | 4 | from typing import List, Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self) -> str:
return f"{self.val} -> {self.next}"
class Solution:
Flag = None
def reverseBetween(
... |
8826bc5f409fdecc7218f0c2762665f5e23a9d66 | wudizhangzhi/leetcode | /easy/array-partition-i.py | 858 | 3.765625 | 4 | # coding=utf8
from deco import runningtime
'''
Given an array of 2n integers, your task is to group these integers
into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn)
which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, a... |
7f3358088eeaf94a02d211f25752c3b4db17d9a8 | wudizhangzhi/leetcode | /easy/invert-binary-tree.py | 3,040 | 3.765625 | 4 | # coding=utf8
from deco import runningtime
'''
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), b... |
adfaa681f523adf1804ee31bed864039bff4752d | wudizhangzhi/leetcode | /easy/find-the-difference.py | 2,504 | 3.609375 | 4 | # coding=utf8
from deco import runningtime
'''
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation... |
f25df7963a9a9c81d8b28186b223350cf8d9ba87 | wudizhangzhi/leetcode | /medium/merge-two-binary-trees.py | 2,296 | 4.40625 | 4 | # -*- coding:utf8 -*-
"""
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of th... |
f34fbe0d735f70ed80f01f6e6120895a8907037b | wudizhangzhi/leetcode | /easy/excel-sheet-column-number.py | 838 | 3.765625 | 4 | # -*- coding:utf8 -*-
"""
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
"""
class Solution(object):
def titleToNumber(self, s):
... |
435320fa8c91c82ffeb4d8104f335b6682be40d2 | hdvos/medrxiv_metadata_crawler | /medrxiv_downloader.py | 6,211 | 3.625 | 4 | """Crawls https://www.medrxiv.org/ for metadata given search terms.
usage: python medrxiv_downloader.py -i search_terms.txt -o output.csv
Takes a text file as input (-i) and a csv file as output.
Input file is a text file that contains 1 search term per line.
Output file is a csv file (tabs separated (\t)). All data... |
3bf33ea29c7be60b481bd090792d878bf08ec7c0 | overpack/main.py | /main.py | 14,321 | 4.03125 | 4 | # Task 17: Import the modules csv, tui and visual
# TODO: Your code here
# Importing other modules and files from this project
import csv
import json
import tui
import visual
# Task 18: Create an empty list named 'records'.
# This will be used to store the date read from the source data file.
# TODO: Your code here
# ... |
4a8d00d0f7826ca96f0c5e4ed4060fc9cbad2cf6 | AlexBadProgrammer/PYTHON100 | /Slayd10GAME.py | 678 | 3.5625 | 4 | import random
zanovo = 'да'
z = 0
while zanovo == 'да':
zagadannoe = random.randint(1, 100)
user_input = int(input('Игра " быдло-угадайка"\nЧИСЛО ДАВАЙ\n '))
z += 1
while user_input != zagadannoe and z != 5:
if user_input < zagadannoe:
user_input = int(input('ЧЕ ТАК мало\n'))
... |
0bd6aa8e5840b76e75d8c4fa626772f50c530020 | marivsteo/Fundamentals-of-Programming | /Assignment 5-7/entities/book.py | 1,238 | 3.5625 | 4 | '''
Created on 28 Nov 2018
@author: Marius
'''
class Book:
def __init__(self, bookId, title, author, description):
self._bookId = bookId
self._title = title
self._author = author
self._description = description
def get_book_id(self):
return self._bookId
def g... |
7c3aff489da4588f17f92ff5993fa925f9588bf1 | ayratzay/ml_algo | /algo.py | 4,338 | 3.546875 | 4 | __author__ = 'Freeman'
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import expit
def linear_regression(x0, x1, theta0, theta1):
return x0 * theta0 + x1 * theta1
def squared_delta(h_x, y):
return (h_x - y) ** 2
def mse(ds, t0, t1):
sqe = [squared_delta(linear_reg... |
1439bc889447ad8727c8467f4c2bc0b64cb623f4 | jahnavij4/python_datastructures | /sortedArray.py | 745 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 6 11:25:59 2019
@author: jahnavi
"""
import array
def Arraysort(array1,num):
mid= int((len(array1)-1)/2)
#print(mid)
index=0
if num<=mid:
for i in range(0, mid):
if int(array1[i])==int(num):
index=i
... |
aba3ebf7f548a2cb9035ed39f9cf880f16dc6d33 | aique/machinelearning | /chapter2/scripts/adaline/after_normalization.py | 648 | 3.578125 | 4 | """
Coste del algoritmo Adaline después de la normalización de datos de entrada.
La convergencia es mucho mayor que en el ejemplo previo a la normalización,
a pesar de que el rango de aprendizaje es 0.01.
"""
import matplotlib.pyplot as plt
from chapter2.algorithms.adaline import Adaline
from chapter2.data.data impor... |
e5eb22c08fe1b9d83e8af1e83188eea7ea4f32d6 | AmyWagarCinch/python-challenge | /PyBank/main.py | 3,477 | 3.828125 | 4 | #modules
import os
import csv
# Set path for file
csvpath = os.path.join(".", "Resources", "budget_data.csv")
#reading the csv file
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
#The net total amount of "Profit/Losses" over the entire period
#t... |
d3ef5ca33e653a1d2aecdf35eaace92c443f8c45 | EricShiqiangLiang/BasicCalculator | /BasicCalculator.py | 4,139 | 4.25 | 4 | # Calculator.py
# This program uses an expression tree to create a basic integer calculator app.
# 1.Input the expression.
# 2.Extract numbers and operator from input
# 3.Generate Token list. Token has two types: number, and operator.
# Input Processing
class Buffer(object):
# Constructor
def __init__(self,... |
db51802c838d74faeaf8ec7eb6683dfa3b8de8e4 | magladde/code-wars | /python/8-kyu/will-you-make-it.py | 242 | 3.578125 | 4 | def zero_fuel(distance_to_pump, mpg, fuel_left):
distance_able_to_travel = mpg * fuel_left
if distance_able_to_travel >= distance_to_pump:
return True
else:
return False
result = zero_fuel(50, 25, 2)
print(result) |
acd16cada83fceed1f2ecbac211937dab89949c0 | magladde/code-wars | /python/7-kyu/youre-a-square.py | 171 | 3.984375 | 4 | def is_square(n):
if n < 0:
return False
elif (n ** 0.5) % 1 != 0:
return False
else:
return True
result = is_square(-1)
print(result) |
044d121008b09c80c6be6831c328f2d8a20520c3 | magladde/code-wars | /python/6-kyu/iq-test.py | 454 | 3.75 | 4 | def iq_test(numbers):
number_list = numbers.split(" ")
number_list = [int(i) for i in number_list]
sum = 0
for i in number_list:
sum = sum + (i % 2)
if sum > 1:
for i in number_list:
if i % 2 == 0:
return number_list.index(i) + 1
else:
for i in... |
49b8b5929b494f056034d39fb29cdbd4cc1a2974 | reidwil/songbank | /src/parser.py | 885 | 3.828125 | 4 | """
Parse input arguments and route downloads to necessary places
"""
import argparse
parser = argparse.ArgumentParser(description='Youtube downloader')
# Add the arguments
parser.add_argument(
'-i',
'--input',
help="""
The text file with youtube urls to be downloaded.
Note: If there is no .txt f... |
2c8eea9be7b8b5de96a5c44cf1d3c8e365eda746 | ChrisMatthewLee/Lab-9 | /lab9-70pt.py | 847 | 4.25 | 4 | ############################################
# #
# 70pt #
# #
############################################
# Create a celcius to fahrenheit calculator.
# Multiply by 9, then divide by 5, then add 32 t... |
7744e3e3e05b257341ca70cf059a3b7f0eaa54ee | opitt/advent-of-code-2020 | /day2/day2.py | 781 | 3.78125 | 4 | # https://adventofcode.com/2020/day/2
# part 1
with open("input_day2.txt", encoding="utf-8") as input:
pwd_lines = input.readlines()
valid = 0
for line in pwd_lines:
min_max, letter, pwd = line.strip().split(" ")
min, max = map(int,min_max.split("-"))
letter_count = pwd.count(letter[0])
if letter_c... |
8cef1b1e50423ad153d6cc0b7a097ae4b2921323 | bapillai/python-learning-excercises | /python-excercises/excercise-5.py | 1,542 | 3.9375 | 4 | #Dictionary
contacts = { 'Jason': '555-0123', 'Carl': '555-0987'}
contacts['Tony'] = '555-0570'
print(contacts)
print(len(contacts))
#Deleting an element from Dictionary
del contacts['Jason']
print(contacts)
#Creating dictionary with additonal spaces in between elements
contacts = {
'Jason': ['555-0123','555-0000... |
af9a4bf76c57ff01738eb1da830f494c302ac830 | ranie2019/PythonLivro | /ex3.15.py | 200 | 3.609375 | 4 | cigarro = int(input('quantidade de cigarros por dia: '))
anos = int(input('quantos anos: '))
soma1 = anos * 365 * cigarro * 10
soma2 = soma1 / (60 * 24)
print(f'voce perdeu {soma2:.0f} Dias de vida') |
d89f3e1dc6dbce3504a8939e7e49dd669322993a | ranie2019/PythonLivro | /ex4.2.py | 216 | 3.921875 | 4 | carro = int(input('digite a velocidade do carro: '))
if carro > 80:
print('voce foi multado')
multa = (carro - 80) * 5
print(f'voce deve pagar uma multa de {multa}')
else:
print('dirija com cuidado') |
5bad54782599929bed71a41af320055bf2751ebd | ranie2019/PythonLivro | /ex3.9.py | 355 | 3.671875 | 4 | dia = int(input('quantidades de dias: '))
horas = int(input('quantidades de horas: '))
minutos = int(input('quantidades de minutos: '))
segundos = int(input('quantidades de segundos: '))
segundos = segundos * 1
minutos = minutos * 60
horas = horas * 3600
dia = dia * 86400
soma = segundos + minutos + horas + dia
prin... |
93ed0f3ceef0a0fa18cb59080ff6542697db2335 | KyleKing/dash_charts | /dash_charts/equations.py | 2,691 | 4.4375 | 4 | """Equations used in scipy fit calculations."""
import numpy as np
def linear(x_values, factor_a, factor_b):
"""Return result(s) of linear equation with factors of a and b.
`y = a * x + b`
Args:
x_values: single number of list of numbers
factor_a: number, slope
factor_b: number,... |
c5b4be42e67cf8085bbd824c7d1ed1b5c259d88d | KyleKing/dash_charts | /dash_charts/coordinate_chart.py | 13,968 | 3.78125 | 4 | """Coordinate chart.
Creates a grid of tiles with consistently spaced x/y positions. Provided data is plotted as a marker at each position
unless None. This can be used to create all sorts of visualizations that have spatially related data, such as calendars
"""
import calendar
import cmath
import math
from itertool... |
6796e0b8112723802dba5753514d3e0766bd62b1 | YoungAdvance/training | /math/lcm.py | 276 | 3.671875 | 4 | """
Calculate LCM (lowest common multiple)
"""
def gcd(a,b):
divident = max(a,b)
divisor = min(a,b)
while (divisor):
divident, divisor = divisor, divident % divisor
return divident
def lcm( a, b ):
gcdAB = gcd(a,b)
return a*b/gcdAB
assert( lcm(48, 180) == 720 )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.