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
5dcd4ecb21ea884d867ae0da562288cd134cf53b
DanielSouzaBertoldi/codewars-solutions
/Python/6kyu/Decode the Morse Code/solution.py
253
3.625
4
def decodeMorse(morse_code): text = '' for words in morse_code.strip().split(" "): for word in words.split(' '): if word: text += MORSE_CODE[word] else: text += ' ' return text
54d680dd511ab2a30b62009399c1b2a3cd8f2a6d
ethiapath/code-challenges
/bstarray.py
1,028
3.984375
4
# bst from array # take in a sorted array # find the middle index # check if your target value is greater then or less then the index in the array # pass in the the upperhalf or the lowerhalf recursivly # if you found it return # hieght value class BinaryTreeNode: def ___init__(self, value): self.value = value...
349e59ea76e42d9f37051eee5e795f8209f9f964
saiporuri92/Python_coding_solutions
/power_of_x.py
188
3.984375
4
def power(x,n): if n == 1: return x if n % 2 == 0: return power(x,n//2) * power(x,n//2) else: return power(x,n//2) * power(x,n//2) * x print(power(3,5))
219e2be563c408a13a0515c499529c2a39100366
nickjourjine/peromyscus-pup-vocal-evolution
/src/parameters.py
5,147
3.6875
4
#this file contains functions for writing and reading parameters and dealing with directories and #dataframes for keeping track of different parameter choices for a given analysis #filesystem import os #data import json import pandas as pd from datetime import date, datetime def get_date_time(): """ Uses d...
987cd219292bf42ce9aba7c3aaa06419e6a4ce51
lucikol/KiwiCurrencyConverter
/tests/test_converter.py
1,406
3.609375
4
""" Tests of currency_converter.py """ import unittest import currency_converter class TestConverter(unittest.TestCase): # (Instances of the TestCase class represent the logical test units) def test_converter(self): converter = currency_converter.Converter(100, 'EUR', 'CZK') data = converter.conv...
49145349aab01c1c64f56078232f88e42941b38a
Bhaveshsingh022000/CGPA-Calculator
/login.py
2,198
3.71875
4
from tkinter import * cal=Tk() cal.geometry("1600x720") cal.title("Login") Label(cal,font=('helvetica',50,'bold'),text="CGPA CALCULATOR",bd=10,fg="white",background="Dodgerblue4").place(x=320,y=0) cal.configure(background="Dodgerblue4") from tkinter import messagebox def skip(): cal.destroy() import cgpa.py ...
4d78f6b34b25912e804888180df5ff0d1c18b69c
RamaryUp/codingame
/Python/numberoflettersinnumber.py
1,590
3.71875
4
# Codingame challenge # Name : Number of letters in a number - binary # Category : Community puzzles # URL : https://www.codingame.com/training/community/number-of-letters-in-a-number---binary # Selected programming language : Python 3.5.3 ''' ---------------------------------------------------------------------------...
0c91e93a6f39024c0c90e613100dfa788d75ace0
RamaryUp/codingame
/Python/these_romans_are_crazy.py
2,861
3.921875
4
# Codingame challenge # Name : Laser and mirrors # Category : Community puzzles # URL : https://www.codingame.com/training/community/these-romans-are-crazy! ''' You are given 2 expressions representing 2 numbers written in roman numerals. You have to provide the result of the sum of these 2 numbers, also in roman nume...
563808938f7f0b1876f65f42f91ded4f8bff5d0a
RamaryUp/codingame
/Python/shadowsoftheknight1.py
4,311
3.90625
4
# Codingame challenge # Name : Shadows of the Knight - Episode 1 # Category : Classic puzzle - medium level # URL : https://www.codingame.com/training/medium/shadows-of-the-knight-episode-1 # Selected programming language : Python 3.5.3 ''' ------------------------------------------------------------------------------...
46bb49c32a647d15b781bcd99080aa5d576bd93f
libbyh/upst
/words.py
2,506
3.65625
4
#! /usr/bin/env python import re from configparser import SafeConfigParser import os from nltk.corpus import stopwords # Create list of lower case words # define words as `stuff between whitespace(s)' # \s+ --> match any whitespace(s) def create_word_list(textfile, remove_stop_words="true"): with open(textfile, 'r...
0f8cfb18843af00879e449588b3541b85c9e93d1
Manasikotalpur1999/JISAssasins
/Q17.py
320
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[7]: #Question 17 x= input('enter the set of numbers :(enter space seperatedvalue):') list1= x.split(" ") res=[] for i in list1: n = int(i) for j in range(2,int(n/2)): if(n%j == 0): break else: res.append(n) print(res) # In[ ]:
7b13ee27bed4b529cb0ab9e1b51dd3e9d8d46f05
Manasikotalpur1999/JISAssasins
/Q6.py
212
3.984375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #Question 6 names=[] n=5 for x in range(1,n+1,1): names.append(input("Enter the names:")) names.sort() print("Names after sorting are",names) # In[ ]:
f1dca175776b1b0eb3e59cb0925941b553e11650
kpushkar10/CodeChef
/World_Record.py
303
3.640625
4
import numpy as np def bolt(): k1,k2,k3,v = input().split() k1,k2,k3,v = float(k1),float(k2),float(k3),float(v) distance = 100 speed = k1*k2*k3*v time = np.round(distance/speed,2) if time < 9.58: print("Yes") else: print("No") t = int(input().strip()) for t in range(0,t): bolt()
52276fe9be46ace42044e521db9e4d2f3b1f7599
getmenova/PlayingWithPy
/cs50/noswitch.py
199
4.03125
4
# Logical operators from cs50 import get_char # Prompt user for answer c = get_char("answer: ") # Check answer if c == "Y" or c == "y": print("yes") elif c == "N" or c == "n": print("no")
c84fd1cf624b073a3cc528fceeeeef0c1516a068
getmenova/PlayingWithPy
/cs50/compare3.py
339
3.671875
4
# Compares two strings for equality while checking (succinctly) for errors import sys from cs50 import get_string # Get a string s = get_string("s: ") if not s: sys.exit(1) # Get another string t = get_string("t: ") if not t: sys.exit(1) # Compare strings for equality if s == t: print("same") else: ...
13e32fe35f5393a629efb231d10bbffce1c3ddad
passerby139/python-
/集合.py
161
3.546875
4
setname=set([1,2,3,4,5,6,7,8]) tran_setname=set([1,2,3,4,5,6,7,8]) #set函数可以将列表或元祖直接转换为字典 print(setname) print(tran_setname)
8241401a2964f7f1461b37caf5acdd993c919e09
passerby139/python-
/排序练习.py
136
3.5625
4
list=[85,22,61,31,65,34,56,28,61] print("原列表",list) list.sort() print("升序",list) list.sort(reverse=True) print("降序",list)
f30dedf6cdf43474279a809742e37b47a8f7137b
HuXiao-THU/Reinforcement-Learning-2nd-Exercise
/4.7 Jacks Car Rental/World.py
1,800
3.890625
4
""" This is the world model can be used for other training methods """ import numpy as np class world(object): """ the world model """ def __init__(self): super().__init__() self.num_station1 = 10 self.num_station2 = 10 def observation(self): """ r...
65aef2d23117097495b7f58ab5522e649d84b81b
AndrewOwens121/OOP-Python-CA1
/CA1.py
13,965
3.640625
4
import time # Time imported to add delays class Student: # initialise Student Class, assigning the required parameters to attributes as per below def __init__(self, new_fname, new_lname, new_dob, new_address, new_email, new_mobilenum, new_studentnum, new_status): self.fname = new_fna...
28f89ab9edb0fdaccef351a1273514a70e5e134b
ekaan/CS301-Introduction-to-Algorithms
/CS301-HW3/Cs301_Hw3.py
6,266
3.734375
4
import sys import time import matplotlib.pyplot as plt import random ''' *** AUTHOR : ADNAN KAAN EKIZ *** Example Sample: 0 0 0 | 0th level 0 1 0 | 1st level 0 0 0 | 2nd level 1 0 1 | 3rd level 0 0 1 | 4th level 0 0 0 | 5th level 1 0 0 | 6th level 0 0 0 | 7th level 0 --> represe...
0f600b7f03058e8e89f933bdc1ebf52b934e306a
gyeong07/Hello_Python
/practice.py
564
3.859375
4
# 숫자 자료형 # print(5) # print(-10) # print(3.14) # print(5+3) # print(2*8) # 문자열 자료형 # print('풍선') # print("나비") # print("z"*9) # boolean 자료형 # print(5>10) # print(5<10) # print(not (5>10)) # 변수 # 애완동물을 소개해 주세요~ animal = "강아지" name = "연탄이" age = 4 hobby = "산책" is_adult = age >= 3 print("우리집 " + animal + "의 이름은 " + nam...
09f2ce29941cda1486813ccbbdc7c00f83f36a62
ytterdorr/GameJam2017
/game_jam_2017.py
3,402
3.515625
4
import pygame pygame.init() class Player(pygame.sprite.Sprite): def __init__(self, *groups): super(Player, self).__init__(*groups) self.image = pygame.image.load("player.png") self.rect = pygame.rect.Rect((320, 240), self.image.get_size()) # Handle gravity self.resting = False #Resting on surface self.dy...
1ba49a3171addef70319e30bd91fec74658bd6d3
friouimeher1/python
/TK_inter.py
208
3.703125
4
# # # def alive_day(name,age): day_alive=('%s alive %d day'%(name,age*365)) return day_alive age=input('Give me your Age \n') age =int(age) name=input('Give me Name\n') print(alive_day(name,age))
b00f3b39b430a91cad31d08add4396b5cd718b66
Aklauser1/Drews-Python-Assignments
/dynamic_typography.py
589
3.875
4
messageInput = input("Enter your dynamic message: ") import graphics as g win = g.GraphWin ("dynamic", 1000, 200) win.setBackground("light green") xValue = 10 # used the ordinal value for the y value of the character for letters in messageInput: text = g.Text(g.Point(xValue,ord(letters)), letters) text.setS...
b20046be773df17575d2c87213cc2c55aa70e186
n8951577/scrapy
/factorial.py
253
4.1875
4
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1) try: n = int(input("enter a number to find the factorial of a digit")) print ("The factorial of n is %d" % factorial(n)) except: print("Invalid")
2c5cb3d55f02e42aac330f87cc251ccbb451df18
n8951577/scrapy
/tuple.py
304
4
4
a=(1,2,3,'hai',-68,0.8) print(a) print(a[2]) #del(a[2]) print(a[-2]) print(a[2:5]) #Update a tuple x=(10,20,30,40) y=(50,60,70) z=x+y print(x,y,z) print(z) #We cant able to update any items from the tuple because it is an immutable list- Can't be Modified. #Delete an Entire tuple del(x) print(x)
8613899225289db875b1417057bd464409bbd32e
n8951577/scrapy
/Character_chk.py
191
4.28125
4
ch=input('Enter a Character') if ((ch>='a' and ch<='z')or(ch>='A' and ch<='Z')): print(ch, 'is a Valid Character') else: print(ch, 'is not a valid Character Please check it...')
00d2a8785f9a19aa2f552ae5ca7166cdb097e5a2
n8951577/scrapy
/iterators.py
149
3.828125
4
for i in range(10): print (i) my_list = [4, 7, 0, 3] my_iter = iter(my_list) print(next(my_iter)) next(my_iter) print(my_iter.next())
dc0d64d1c54a204ecebbb0a589f354f13447c876
priyanshi1996/Advanced_Python_Course
/Ex_Files_Adv_Python/Exercise Files/04 Collections/defaultdict_finished.py
1,272
4.5
4
# Demonstrate the usage of defaultdict objects from collections import defaultdict def main(): # define a list of items that we want to count fruits = ['apple', 'pear', 'orange', 'banana', 'apple', 'grape', 'banana', 'banana'] fruitCount = {} # Count the elements in the list # This...
76383646f662ec5a0b1145cd226ae7d889f7be4c
amar-jain123/PythonLoop
/function/p1.py
866
3.765625
4
# def sum(a,b): # return a+b # # a = sum(10,20) # print('Sum of a and b', a) # # def add(a,b): # return a + b # print(add(10,50)) # my name is amar # string = input('enter the string') # pangram = 'abcdefghijklmnopqrstuvwxyz' # s = string.lower() # lst1 = [] # lst2 = list(pangram) # for i in pangram: # for...
b280bd5a269bb2a6f7e00c40b8f3d6c205118ff3
willgraham0/gradient_descent
/descent.py
5,353
4.03125
4
"""This module provides the gradient descent functionality.""" from collections import OrderedDict from itertools import product from typing import List, Tuple import matplotlib.pyplot as plt import numpy as np from utils import diff class GradientDescent: def __init__(self, function, x: np.array, y: np.array...
de48e5f40d746eef493846ea721c93e688e113e6
kris10nicole/kelly_kristen_python
/HW3_KristenKelly.py
6,623
3.953125
4
import pandas as pd #We import pandas which allows us to use descriptive statistics when analyzing data import numpy as np #We use numpy as it is a module that allows the user to work with multi-set arrays and perform functions on them import matplotlib.pyplot as py #We import matplotlib which enables us to us...
1a26eccecd87511cc7e6f54dcff0862808b28741
csakai/EightPuzzle
/numpuzz.py
6,143
3.59375
4
class NumPuzz: #notes for instantiation: size is to be the dimension of the puzzle ie a 3x3 simply # calls for an input of 3. Order is an array for representing the state of the puzzle # I am trusting for now that one using this would give proper inputs as opposed to # trying to break my code. prev is a...
82e07502d992e975fcd74892d391917f8237d65f
MahirKothari/swappingFiles
/swappingFile.py
308
3.671875
4
def swappingFile(): file1 = "test.txt" file2 = "test2.txt" with open(file1,'r')as a: dataa = a.read() with open(file2,'r')as b: datab = b.read() with open(file1,'w')as a: a.write(datab) with open(file2,'w')as b: b.write(dataa) swappingFile()
c513d03a202d689b450d8ae68a196660315990eb
tuanma123/Voma_Notifications
/Database.py
13,319
4.46875
4
import _sqlite3 from User import User connection = _sqlite3.connect("Master.db") connection.text_factory = str cursor = connection.cursor() def create_table (): """ Creates a table named users :return: Void. """ cursor.execute("CREATE TABLE IF NOT EXISTS users(firstName TEXT, lastName TEXT, email TEX...
5af4158a8ff3d270b35e6b6b02332ca3cb82ce43
IfthikarAliA/python
/Beginner/3.py
261
4.125
4
#User input no. of Element a=int(input("Enter the number of Element: ")) #Empty List l=[] #Function to get list of input for i in range(a): l.append(int(input(f"Enter the {i+1} item: "))) #Iterator over a list for i in l: if(i%2==0): print(i)
649b7c6283754178c8917373e10bb0d817f6c965
rwson/Python-starter
/3/4.py
1,077
3.75
4
#coding=utf-8 ''' 字符串常见操作 ''' aStr = "hello Python, my name is srw" # center/ljust/rjust: 中/左/右对齐显示 print(aStr.center(100)) # lstrip/rstrip: 去除左/右空白字符 lStr = " hello Python" print(lStr.lstrip()) rStr = "hello Python " print(rStr.rstrip() + ", my name is srw") # strip: 去除左右空白字符 sStr = " hello Python ...
c9bf8c6b2ce4a428e0469c1fdeed1736a3afa49c
rwson/Python-starter
/2/2.py
400
3.71875
4
#coding=utf-8 num = int(input("请输入一个数字: ")) if not (num >= 4 and num <= 10): print("中奖啦!") else: print("你没中奖!") scroe = int(input("你考了多少分? ")) if (scroe >= 90): print("哇!太棒了!") elif (scroe < 90 and scroe >= 80): print("还不错, 挺好的!") elif (scroe < 80 and scroe >= 60): print("下次继续努力!") else: print("回去要挨打了!")
1b7ecb1d2bba0cdcddca678af3eb45870b1bc74f
rwson/Python-starter
/1/2.py
621
3.9375
4
#coding=utf-8 ''' 格式化输出 %(xxx, yyy)取出多个变量的值 常用的格式符: %c 字符的ASC码 %s 通过str()字符串换来格式化 %i 有符号的十进制数 %u 无符号的十进制数 %o 八进制整数 %x 十六进制整数(小写) %X 十六进制整数(大写) %e 索引符号(小'e') %E 索引符号(大'E') %f 浮点实数 %g %f和%e的简写 %G %F和%E的简写 ''' name = "rwson" age = 24 print("name is %s"%name) print("---------------") print("m...
c46dc6785a4acd59693347d96be12aa5ba8552f7
adgarciaar/HackerRankInterviewPreparationExercises
/Greedy Algorithms/Greedy_Florist.py
1,063
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 29 00:40:32 2020 @author: adgar """ #!/bin/python3 import math import os import random import re import sys # Complete the getMinimumCost function below. def getMinimumCost(k, c): c = sorted(c) dictionary1 = {} dictionary2 = {} purchase =...
f49352dc3780f2e4adbca448c49346b55a5c752d
ioluwayo/hackerank_challenge
/fibonanci_with _memoization.py
685
4.0625
4
# Created by ioluwayo on 2017-02-05. """ Used a dictionary to store solutions to sub problems "fib(n-1) fib(n-2)" in computing the Nth fibonacci number The basic algorithm has an exponential time complexity. However, with very simple memoization the time complexity is about O(n). Since calls to fib(n-1) and fib(n-2) ma...
ca428dab4fc7c72eb755456fe6949b62097aa748
madamiak/advent-of-code
/2017/Day07.py
2,917
3.546875
4
class TowerTree(object): def __init__(self) -> None: self.root = None self.unbalanced = None self.towers = [] def balance_tree(self, puzzle): towers = [Node(row) for row in str.split(puzzle, '\n')] root_candidates = towers[::] for parent in list(filter(lambda x: ...
c04249088f821ea4556bbde59dfd2f9b49f9774c
madamiak/advent-of-code
/2016/days7-25/puzzle09.py
850
3.515625
4
import re class Puzzle09: def __init__(self): pass @staticmethod def solve(puzzle, solution_1=True): marker_regex = re.compile(r'\((\d+)x(\d+)\)') if marker_regex.search(puzzle) is None: return len(puzzle) index = 0 res = str(puzzle) while marke...
f707d8fc6cf42c70d569c187792d1fa674f17bc0
austindrenski/GEGM-Programming-Meetings
/ProgrammingMeeting1_Python/Example.py
428
4.125
4
class Example: """Represents an example.""" def __init__(self, value): self.value = value def increase_value(self, amount): """Increases the value by the specified amount.""" self.value = self.value + amount return self.value > 0 def __repr__(self): """Returns a...
16b2801ea7b221c87f31cf66ecd7022b9007bb77
p4ckysm4cky/blackjack-CLI
/card_deck.py
4,146
3.84375
4
from random import shuffle class Card: def __init__(self, rank, suit, hidden=False): self.rank = rank self.suit = suit self.hidden = hidden # this determines if the card is flipped over or not def set_hidden(self, bool): self.hidden = bool def __str__(self): ...
1c9e2f1352d86253c97f5c0cdebc2a4642956310
ayangacann/hicheel4
/Dasgaluud/9.py
215
3.75
4
# 9. Өгөгдсөн тэмдэгт мөрийн бүх үсгийг том болго. a = input("Жижиг үсгээр бичсэн хүссэн үгээ оруул: ") print(str("хариу: ") + (a.upper()))
b9c58f37c6caa09c68ba89cd79c04b1ba30c9ee2
AndreyRubtsov/algorithmi
/Lesson3/Lesson3_1.py
466
3.5625
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. array2_99 = [i for i in range(2, 100)] array2_9 = [i for i in range(2, 10)] for j in array2_9: count = 0 for i in array2_99: if i % j == 0: count += 1 print(f'кратны {j} ...
444f6bed4f207937c0af2a50d8e8a9c9525c5202
AndreyRubtsov/algorithmi
/Lesson3/Lesson3_2.py
738
3.984375
4
# Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями # 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля), # т.к. именно в этих позициях первого массива стоят четные числа. import random SIZE = 10 MIN_ITEM = ...
06fc1caad5e034efcfcac40e97b241493cd801f9
shohei/algorithm-data-structure
/graph/bfs.py
472
3.65625
4
#!/usr/bin/env python def bfs(G,s): N = len(G) dist = [-1]*N que = [] dist[0] = 0 que.append(0) while(que!=[]): #queue -> breadth-first search v = que[0] que = que[1:] for x in G[v]: if (dist[x]!=-1): continue dist...
164eeccb633913ea917adc82f7e53c5e3ff0d6ce
rupali23-singh/loop_question
/perfect.py
187
3.84375
4
i=2 sum=1 n=int(input("enter the number")) while i<=n//2: if n%i==0: sum+=i i+=1 if sum==n: print(n,"is perfect number=") else: print(n,"is not a perfect number=")
f7759c521e4179cffbdda9af447432ac0262e7a5
rupali23-singh/loop_question
/armstrong.py
208
3.859375
4
num=int(input("enter the number")) i=num sum=0 count=len(str(num)) while i>0: rem=i%10 sum=sum+rem**count i=i//10 if sum==num: print("it is armstrong=") else: print("it is not armstrong=")
0df334680bf354591de05f66056fd5f478ac04d5
Wandaaabrar/Wanda-Aulia-Abrar_I0320109_Andhika_Tugas2
/I0320109_Solal1_Tugas2.py
876
3.53125
4
#menghitung luas persegi panjang print("luas persegi panjang") p = 25 l = 10 luas_persegi_panjang = p * l print("panjang: ",p) print("luas: ", l) print("luas persegi panjang: ", luas_persegi_panjang) #menghitung luas lingkaran print("luas lingkaran") r = 21 Luas_lingkaran = 3.14 * (r ** 2) pri...
932abc940cc465c4e74859b171295fd13a7ff481
dheerajdlalwani/PythonPracticals
/Experiment2/code/question3.py
238
3.90625
4
userInput = input("Please enter a string: ") ans = "" cnt = 0 for ch in userInput: if(ch == 'a'): cnt += 1 if(cnt > 1): ans += '@' else: ans += ch else: ans += ch print(ans)
663c8604ccf16d20dd92c597ba4b5f33fd26bb39
austinrhode/SI-Practical-3
/shortest_word.py
488
4.4375
4
""" Write a function that given a list of word, will return a dictionary of the shortest word that begins will each letter of the alphabet. For example, if the list is ["Hello", "hi", "Goodbye", "ant", "apple"] your dictionary would be { h: "Hi", g: "Goodbye", a: "ant" } because those are the shortest wo...
0ea757ff04c81a1a53a6cba0275cc12433cc0c36
ikhlestov/computational_geometry
/algorithms/predicates.py
783
4.125
4
from algorithms.primitives import Point, LineSegment def cross_product(u, v): return u.x * v.y - u.y * v.x def points_turn_value(a: Point, b: Point, c: Point) -> float: return cross_product(b - a, c - a) def line_segments_turn_value(l1: LineSegment, l2: LineSegment) -> float: return cross_product(l1.p...
3f63aac86bed8b98276e9850fbb00421121d6eae
BridgitA/Week10
/mod3.py
713
4.125
4
maximum_order = 150.00 minimum_order = 5.00 def cheese_program(order_amount): if order_amount.isdigit() == False: print("Enter a numeric value") elif float(order_amount) > maximum_order: print(order_amount, "is more than currently available stock") elif float(order_amount) < minimum_order...
a75a98f1ae75caba0c53ef2c2106ee82c487520d
WalterVetrivel/python_algorithms
/algorithms/search_algorithms/binary_search_recursive.py
473
4.03125
4
def binary_search(n, arr, start, end): if start > end: return -1 mid = (start + end) // 2 if arr[mid] == n: return mid elif arr[mid] < n: return binary_search(n, arr, mid + 1, end) else: return binary_search(n, arr, start, mid - 1) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, ...
2fe96d7e2a98699e88c75ca3d47cbdac0314a788
kristiansantos11/tardigrades
/Shopee Workshop/LCCL Python Intermediate/hands-on-6.py
292
3.921875
4
# Hands on 6 # Write a function, repeats, that take a string. It outputs the number of characters # that occur more than once in that string. Ignore casing. def repeats(s): return len([c for c in set(s.lower()) if s.lower().count(c) > 1]) print(repeats('aaaa')) print(repeats('abcba'))
1fd452cdebe5fda54dd89c4fb5e7731ed7ecd07a
kristiansantos11/tardigrades
/Shopee Workshop/LCCL Python Intermediate/code/06-exception.py
566
3.828125
4
# by LCCL Coding Academy, www.LccLcoding.com # for Shopee Code League 2020 # EXCEPTION HANDLING # ====================== print() try: # code may raise exception a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) except ValueError: # there is an exception, run this code pri...
d26fe0e83b37bc6344444d360dc6a2d1f7206748
kristiansantos11/tardigrades
/Shopee Workshop/LCCL Python Intermediate/hands-on-2.py
500
3.828125
4
# Hands on -2 # Take an input string and report groups of words that start with the same letter. def report(s): d = dict() s = s.lower().split() for word in s: key = word[0].upper() d[key] = d.get(key, set() | {word}) return d input_string = report(''' Someday I'll wish upon ...
39253977c5532d0ee2c1c432c913ffd4f1e97b7e
12YTC09/fluentPython
/ch07/promotion.py
1,093
3.53125
4
#以promotion修飾器來填充promos串列 promos = [] def promotion(promo_func): print("promos(%s)"% promo_func) promos.append(promo_func) return promo_func @promotion def fidelity(order): """5% discount for customers with 1000 or more fidelity points""" return order.total() * .5 if order.customer.fidelity >= ...
1801d641e5a7ea8a0e2d992296e14bd91e479588
hatsem78/practica_python
/clases.py
495
3.5625
4
#primera clase concepto de instancia, propiedades y metodos class Coche(): #propiedades largoChacis = 250 anchoChacis = 120 rueda = 4 enMarcha = False #metodos def arrancar(cls): cls.enMarcha = True def estado(cls): if cls.enMarcha: return 'El coche esta e...
14df138a99cc9e420d5c3161e4958e1320e9d376
jiajie999/funny-checkio
/electronic_station/e7_weak_point.py
1,399
3.828125
4
# -*- coding: utf-8 -*- def weak_point(matrix): """From this task, you can learn how to use min(*args,key=fun) :param matrix: :return: """ v = {} h = {} for i in xrange(len(matrix)): v[i] = sum(matrix[i]) h[i] = sum(matrix[j][i] for j in xrange(len(matrix))) return min(v....
b78d3031fb9db4229035dd551044a0d6f3c5f965
harsh2995/Python-1
/Assignment1_5.py
195
3.96875
4
x=int(input("Enter any number")) # if x>=10 and x<=50: # else: # print("yes I am in range") # print("oops") if x in range(10,50): print("yes I am in range") else: print("oops")
e9feb3024d26274a56cefd310f62b507115d4ba8
MDKola/bucketlist
/tests/test_bucket.py
2,646
3.84375
4
from unittest import TestCase from classes.buckets import Buckets class TestBucket(TestCase): def setUp(self): """Instantiate the Buckets class""" self.bucket = Buckets("first bucket") def test_bucket_created(self): """test if a bucket is created successfully""" self.assert...
a3f2873b171c45681c5955de18dbbbed40d4a6c5
michellesanchez-lpsr/class-sampless
/msanchez/problemset3.py
380
3.734375
4
print("Welcome to PumaPix!") print("Enter your 5 favorite TV shows.") usersList = [] i = 0 while i <5: print("Enter a show name:") x = raw_input() i = i + 1 usersList.append(x) print("Ok, here's what you entered:") print(usersList) print(" We've added a couple of important ones. ") usersList.append("CSI") user...
4752c7c4fd3fe522a6f88c76269e950efc4cdc9e
michellesanchez-lpsr/class-sampless
/msanchez/partner.py
188
3.890625
4
print(" What is your favorite number?") fav = int(raw_input()) while fav != 14: print("try again") fav = (input()) if fav == 14: print("that's the best number!")
e8fdf0402758ba46af3abe5f908e940fb5bf6cdf
michellesanchez-lpsr/class-sampless
/msanchez/gitttt.py
832
3.8125
4
import turtle def drawTriangle (myTurtle): side_count = 0 while side_count < 3: myTurtle.forward(10) myTurtle.right(120) side_count = side_count + 1 def drawlineoftriangles (myturtle): trry = 0 while trry < 8: if trry >= ...
f8293c7294cc10da6dab7dfedf7328c865f899fe
michellesanchez-lpsr/class-sampless
/4-2WritingFiles/haikuGenerator.py
794
4.3125
4
# we are writing a program that ask a user for each line of haiku print("Welcome to the Haiku generator!") print("Provide the first line of your haiku:") # create a list to write to my file firstL = raw_input() print(" ") print("Provide the second line of your haiku:") secondL = raw_input() print(" ") print("Provide...
9e20d9bab577aba6e39590e3365b56b9325dd32a
michellesanchez-lpsr/class-sampless
/msanchez/university.py
584
4.1875
4
# print statements print(" How many miles away do you live from richmond state?") miles = raw_input() miles = int(miles) #if else and print statements if miles <=30: print("You need atleast 2.5 gpa to get in") else: print("You need atleast 2.0 gpa to get in") print(" What is your gpa?") gpa = float(raw_input()) gpa...
472272a1c043614ffb7a5a0abf4c64b7f248c2ad
tarod13/MetComp
/LAB_exercises/Python/Hamlet_ejercicio_lectura.py
764
3.5
4
#1. Cargar y leer file = open('pg1524.txt','r') lines = file.readlines() file.close() #2. Separar en palabras words = list() for line in lines: words_in_line = line.split() words = words + words_in_line #3. Contar palabras de 9 letras nine_characters_words = 0 for word in words: number_characters = l...
3a6bed00fc615621f32c9a0c1dbe54556e020b69
MrSaral/kg_MrSaral_2020
/main.py
610
3.765625
4
import sys def mapper(s1,s2): # Function to check for one-to-one mapping between # two strings. # # Takes 2 strings as input and boolean output if(not s1 or len(s1)<=1): # Boundary cases return True; d={} # Dictionary for i in range(len(s1)): # Looping over all characters of first string c1...
822313364fa742c61d21fc5ea1f39bb2753fbf4e
LeandroCastroAlves/Clique-aqui-para-aprender-Python-para-Analise-de-Dados
/calculo_ir.py
617
3.921875
4
#Calculo RI salario = float(input("Insira o salario: ")) if salario <= 1903.98: print("Isento") elif 1903.99 <= salario <= 2826.65: aliquota = 0.075 deduzir = salario*aliquota print(f"Parcela a deduzir: {deduzir}") elif 2826.66 <= salario <= 3751.05: aliquota = 0.15 deduzir = salario * aliquot...
c76c3e5f15c1a1a70667fcbfec44ccde883376f5
LeandroCastroAlves/Clique-aqui-para-aprender-Python-para-Analise-de-Dados
/busca_letra_texto.py
885
3.953125
4
texto = "A inserção de comentários no código do programa é uma prática normal. Em função disso, toda linguagem de programação tem alguma maneira de permitir que comentários sejam inseridos nos programas. O objetivo é adicionar descrições em partes do código, seja para documentá-lo ou para adicionar uma descrição do alg...
a3c5b6abca04e11bf478d7a023ee577d0f2d4220
robertrowe1013/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
463
3.859375
4
#!/usr/bin/python3 """text conversion""" def text_indentation(text): """text conversion""" if type(text) != str: raise TypeError("text must be a string") new_text = text.replace(". ", ".") new_text = new_text.replace("? ", "?") new_text = new_text.replace(": ", ":") new_text = new_text...
8d0147288c63212015988528487cbcca78858f58
robertrowe1013/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,137
3.8125
4
#!/usr/bin/python3 """divide a matrix""" def matrix_divided(matrix, div): """divide a matrix""" if type(div) != int and type(div) != float: raise TypeError("div must be a number") for row in range(len(matrix) - 1): if len(matrix[row]) != len(matrix[row + 1]): raise TypeErro...
f61ab4bc57b820a8ccb100589382c72008d84caf
benjaminrall/rock-paper-scissors
/main.py
12,545
4.09375
4
import random #229 lines, 10 endings, 3 cheat codes print("----------WELCOME TO ROCK PAPER SCISSORS GAME----------") #code 1: loseallmoney - makes you lose all money on your next turn, regardless, so...
a9ad465a680004bc1d0cad2e0b383402e22c4b76
cheliequan/LinuxSysAudit
/lib/utils/utils.py
234
3.859375
4
import re def find_in_list(target,str): ans=list() for i in target: if i.find(str)!=-1: #print "string has been find in target" ans.append(i) return ans def find_in_str(target,str): pass def tran_dic_to_list(dic): pass
2b882fb0d276ec88797227cbdaf13de4012a1e42
yyjlincoln/HotWaterSims
/kmp.py
2,865
3.625
4
# Thanks to the tutorial at: # https://www.youtube.com/watch?v=dgPabAsTFa8 # Code written by Lincoln def prefix_table(pattern: [str, bytes]) -> list: # Start from which character. Here is the second one as the first one (len=0) must be 0. i = 1 l = 0 # Length of the prefix / suffix prefix = [] # ...
5ff742b0b2ec95157cc738b9668d911db3ee6e7e
ceden95/self.py
/temperature.py
445
4.46875
4
#the program convert degrees from F to C and the opposite. temp = input("Insert the temperature you would like to convert(with a 'C' or 'F' mark):") temp_type = temp[-1].upper() temp_number = float(temp[:-1]) C_to_F = str(((9*temp_number)+(160))/5) F_to_C = str((5*temp_number-160)/9) if (temp_type == "C"): pr...
76f0e060b29af72dd5420918b10a0b2034073891
ceden95/self.py
/9.3.1.fileFor_listOfSongs.py
2,791
4.34375
4
#the program uses the data of file made from a list of songs details in the following structure: #song name;artist\band name;song length. #the function my_mp3_playlist in the program returns a tuple of the next items: #(name of the longest song, number of songs in the file, the most played artist) def main(): ...
266f1eef9643832e942c30fec52406331b26b8ae
ceden95/self.py
/for_loop.py
816
4.3125
4
#the program creates a new list(from the list the user created) of numbers bigger then the number the user choosed. def main(): list1 = input('type a sequence of random numbers devided by the sign ",": ') my_list = list1.split(",") n = int(input("type a number which represent the smallest number in yo...
f55a6562de4c30e76723c61ef0a3a60ef178bec2
ceden95/self.py
/shift_left.py
713
4.4375
4
#the program prints the new list of the user when the first item moving to the last on the list. def shift_left(my_list): """the func receives a list, replace the items on the list with the item on the left :param my_list: list from user. :type my_list: list. :return: my_shift_list :rtype: l...
a840b3093757889fb34c8aaf13df449ea52dc3d0
ceden95/self.py
/dates_to_days.py
559
4.4375
4
#the program prints back the day of the date the user choosed. date = input(" please write a date which contains dd/mm/yyyy:") dd = int(date[:2]) mm = int(date[3:5]) yyyy = int(date[-4:]) import calendar what_day = calendar.weekday(yyyy, mm, dd) if what_day == 0: print("monday") elif what_day == 1: ...
f0456cc52bcaa5c91d38a2633b9e220b414cff5b
ansaridanishali/Engineering-Practical-Experiments
/Semester 4/Analysis of Algorithm/FinalProjectMiniMax.py
3,711
3.796875
4
from tkinter import Tk, Label, Frame, messagebox from time import sleep board = [" "] * 9 turn = "X" combos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] computer = "O" human = "X" Labels = {} def inv(player): return "X" if player == "O" else "O" def avai...
eb6f699d518d37f25e71b3707c4f9259e2e94854
LiuLabIUPUI/cellquantifier
/function_description_format.py
4,138
3.734375
4
def blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0, overlap=.5, *, exclude_border=False): """ Finds blobs in the given grayscale image. Blobs are found using the Difference of Gaussian (DoG) method [1]_. For each blob found, the method returns its coordinates and ...
040a262c0bd5148f48f9db9dd646105195945b80
CarlOmega/LinkedWords
/Code/s5084150_linked_words.py
19,583
3.71875
4
import time import sys import random from collections import deque # ///////////////////////////////////////////////////////////////////////////////////////////////// # Global Variables Start # ///////////////////////////////////////////////////////////////////////////////////////////////// # Both ins/outs are used to...
7bb3900607e7f2bcf5d4566428c3bdd9b1062254
cschmi14/Platform-Based-Computing
/In-Class Python/Week 1/common_algorithms.py
563
3.90625
4
def average(list): avg = 0 for x in list: avg += x return (avg / len(list)) list1 = [1, 2, 3, 4, 0, 5, 6, 7, 8, 9, 10] print(average(list1)) def find_minimum(list): min = list[0] for x in list: if x < min: min = x return min print(find_minimum(list1)) def find_max...
c32e466c8f7004bc5e9b8fd23cfe9714d39cad09
Andrewctrl/Final_project
/Visting_Mom.py
744
4.25
4
import Visting_mom_ending import Getting_help def choice(): print("You get dressed up quicky as you rush out to visit your mom in the hospital. " + "You visit your mom in the hospital, she is doing well. But you have a pile of bills. You get a job working at In-and-Out. Balancing work and school is hard, your grad...
76b17f03db4bf135e0ec494a5b4c53c005d440fe
octavio-navarro/ObjectOrientedThinking
/CodeSamples/PythonCode/02. areaEsfera.py
430
3.875
4
# Area y volumen de una esfera import math def area_esfera(radio): return 4 * math.pi * (radio ** 2) def volumen_esfera(radio): return (4/3) * math.pi * (radio ** 3) def main(): print("Calculo de area y volumen") radio = float(input("Dame el radio de la esfera: ")) area = area_esfera(radio)...
6f37d4440e381cd5f0c390e1d559b0dd561251e7
octavio-navarro/ObjectOrientedThinking
/CodeSamples/PythonCode/06. circunferencia.py
782
4.0625
4
# Punto dentro o fuera de una circunferencia import math def dentro_fuera(punto_x, punto_y, centro_x, centro_y, radio): distancia = math.sqrt((punto_x-centro_x)**2 + (punto_y-centro_y)**2) if distancia > radio: print("Fuera de la circunferencia") elif distancia < radio: print("Dentro de l...
6d26ae13fae0c1941e39c94e3ca59f48fdf471cf
tototo31/cmpsci122
/testPrograms/tree.py
917
4
4
class Node: def __init__(self, item): self.left = None self.right = None self.value = item class binaryTree: def __init__(self): self.root = None def insert(self, value, node=None): if node == None: # is there a Root? self.root = Node(value) else...
0b8160aed78bca8dd957b4b926dedf88448fa017
tototo31/cmpsci122
/testPrograms/recursion/recursion1.py
1,286
3.953125
4
def listsum(numbers): # an interative version total = 0 for item in numbers: total += item return total def listSumRec(list_num): if len(list_num) == 1: return list_num[0] else: return list_num[0] + listSumRec(list_num[1:]) def factorial(n): total = 1 for i in ran...
ea3d69ce820eee9afc74a358a1fac0ed5b10969b
tototo31/cmpsci122
/testPrograms/classes/subClass.py
1,220
4.0625
4
class Animal: number_of_legs = 0 def __init__(self, name, age): self.name = name self.age = age def eat(self): print( "{} is eating".format(self.name)) def sleep(self): print("{} is sleeping".format(self.name)) def run(self): print("{} is running".format(s...
737475da70f0661a7d8f932a7feb5cc1a96e3ca2
PeetersY/Python
/mindstorms.py
1,230
4.0625
4
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("red") #create the turtle Brad - Draw a square brad = turtle.Turtle() brad.shape("turtle") br...
a1373af009801966c55d5f3af27811a9ae1eb037
halekyl/261-accumulationOfWork
/bst.py
29,078
4.09375
4
# Course: CS261 - Data Structures # Student Name: Kylee Hale # Assignment: #4 bst # Description: Implement a BST class with methods add(), contains(), remove() # # get_first(), remove_first(), pre_order_traversal(), in_order_traversal() # # post_order_traversal(), by_level_traversal(), size(), height() # # count_leaves...
51f7c28bfd5779120a84ff4ac00643469db21bb3
dcherian/animatplot
/animatplot/blocks/lineplots.py
5,143
3.5
4
from .base import Block from animatplot.util import parametric_line import numpy as np class Line(Block): """Animates lines Parameters ---------- x : list of 1D numpy arrays or a 2D numpy array The x data to be animated. y : list of 1D numpy arrays or a 2D numpy array The y data t...
ea5a201812b6f4ad9ba49505a53e99bcbf207a42
ar021/control-flow-lab
/exercise-2.py
305
4.15625
4
# exercise-02 Length of Phrase while True: phrase = input('Please enter a word or phrase or "quite" to Exit:') if phrase == 'quite': print('Goodbye') break else: phrase_length = len(phrase) print(f'What you entered is {phrase_length} characters long')
3e0f31038651471fe62836d93f2cc6d705381e5e
Enzo5oh/CSE111
/chemistry.py
9,772
4.21875
4
from collections import namedtuple def init_periodic_table(): """Create, initialize, and return a dictionary that contains all known elements. Each key value pair in the dictionary is in this form: symbol : (name, symbol, atomic_mass) The unit for atomic mass is atomic mass units (amu) someti...
d2cc0691e0e05128e98144d19206b7a6f2df3f70
EVgates/VSAproject
/proj02/proj02_02.py
1,100
4.3125
4
# Name: # Date: # proj02_02: Fibonaci Sequence """ Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13....