blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
3d7a0e3a35de1daaee1c1d4d57bc6d2b1cfb778a
XavierKoen/cp1404_practicals
/prac_02/files.py
1,023
3.828125
4
""" Do-from-scratch Exercises: Files section The 4 different tasks are outlined in blocks of code. """ # User enters name, which is written into name.txt file. name = input("Please enter name: ") out_file_name = open("name.txt", "w") print(name, file=out_file_name) out_file_name.close() # name.txt is opened and read,...
15dbca45f3fbb904d3f747d4f165e7dbca46c684
XavierKoen/cp1404_practicals
/prac_01/loops.py
924
4.5
4
""" Programs to display different kinds of lists (numerical and other). """ #Basic list of odd numbers between 1 and 20 (inclusive). for i in range(1, 21, 2): print(i, end=' ') print() #Section a: List counting in 10s from 0 to 100. for i in range(0, 101, 10): print(i, end=' ') print() #Section b: List count...
e1e5bdeab07475e95a766701d6feb6e14fe83494
XavierKoen/cp1404_practicals
/prac_02/password_checker.py
2,067
4.53125
5
""" CP1404/CP5632 - Practical Password checker code """ MIN_LENGTH = 2 MAX_LENGTH = 6 SPECIAL_CHARS_REQUIRED = False SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\" def main(): """Program to get and check a user's password.""" print("Please enter a valid password") print("Your password must be betw...
8b42879e37d01ff9e85cfbb135b8e0b2df6f9882
XavierKoen/cp1404_practicals
/prac_06/guitars.py
1,353
3.96875
4
""" Program to store information on all of the user's guitars. """ from prac_06.guitar import Guitar def main(): """ User continually prompted to input guitar make and model name, year of manufacturing, and cost until a blank name is entered. Information for each guitar is stored as an instance of th...
5e687f495c8671d1534c6d74793fee0ad95b66d9
kaminee1jan/logical-q.py
/count_space_in_string.py
578
3.734375
4
# def check_space(string): # count = 0 # i=0 # while i<len(string): # if string[i] == " ": # count=count+1 # i=i+1 # return count # string = input("enter the string,,,,,,,,") # print("number of spaces ",check_space(string)) list1=[10,11,12,13,14,17,18,19] num=30 i=0 empty=[]...
63bb6dd21f15341732cb88f32e75779ea3dfd0c8
marcinsztajn/BlackJackGame
/black_jack.py
5,507
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 26 21:13:10 2020 Black jack game in Python @author: Marcin """ import random suites = ["Clubs","Hearts","Diamonds","Spades"] ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'] values = {"Two":2, 'Three':3, 'Four...
91b0fa7a85059b9db6200d4a4b75d79dfaa4c3ae
TigranDanielyan/eng-115-2020-Calendar-Suggestion-System-master-version2
/engs-2020-Calendar-Suggestion-System-master/administrator.py
428
4.03125
4
import HashTable3 def main(): print("you as an administrator body can add and delete students for the start of the cycle of exam day starts") type = input("if you need to add student from list please enter Add in opposite case please enter Delete") if type == "Add": HashTable3.creator() elif t...
3bf05089d63d1e641e6db6a2893e8402ca724d1f
pcrease/song_lyrics_scraper
/scraper.py
5,107
3.59375
4
''' Created on 05.03.2013 @author: Paul Crease ''' from bs4 import BeautifulSoup import re import psycopg2 import urllib2 def addToDatabase(dataObject): conn_string = "host='localhost' dbname='postgres' user='postgres' password='platinum'" # print the connection string we will use to connect #print...
2c07c48685a9095b8297232833e2c7b04a754155
r25ta/USP_python_2
/semana4/lista_ordenada.py
451
3.859375
4
def ordenada(lista): for i in range(len(lista)): if i == 0: item = lista[i] if item <= lista[i]: item = lista[i] else: return False return True if __name__ == "__main__": lista_ordenada=[1,2,2,3,4,5,6,7,8...
8e741eb397889dbbdd86f4a5ecd393af8be1cbaa
r25ta/USP_python_2
/semana1/matriz_mult.py
715
4
4
def sao_multiplicaveis(m1,m2): # RETORNA AS DIMENSÕES DA MATRIZ E TRANSFORMA O RESULTADO EM STRING d_m1 = str(dimensoes(m1)) d_m2 = str(dimensoes(m2)) # print(d_m1) # print(d_m2) # COMPARA QTDE DE COLUNAS DA PRIMEIRA MATRIZ COM A QTDE LINHAS DA SEGUNDA MATRIZ if(d_m1[-1] == d_m2[0]): return T...
078ef482518125cdd4b8112c3588673a7c0d8000
r25ta/USP_python_2
/semana4/busca_binaria.py
772
3.78125
4
def busca_binaria(lista, elemento): first = 0 last = len(lista)-1 while first <= last: midpoint = (first+last)//2 if(elemento == lista[midpoint]): return midpoint else: if(elemento < lista[midpoint]): last = midpoint - 1 ...
9a40b5f82378e106390ab354e7ab593cf6f6ac97
r25ta/USP_python_2
/semana6/elefantes.py
797
3.859375
4
def incomodam(n,item=1, palavra=""): if(n>=item): palavra +="incomodam " return incomodam(n, item+1, palavra) else: return palavra def elefantes(n, item=1, frase=""): if(n>=item): if(item==1): frase= "Um elefante incomoda muita gente\n" retur...
2909d4e2b046922afd6f981cdd246e6789edc88a
pizzafreak5/battleship
/battleship_board.py
1,913
3.984375
4
EMPTY = 'EMPTY' MISS = 'MISS' SHIP = 'SHIP' HIT = 'HIT' class Board: def __init__ (self, size = 10): self.board = [] self.last_change = (EMPTY, 0, 0) self.size = size for i in range(size): elem = [] for i in range(size): elem.append(EMPTY)...
3e80845a2e0031bfb21d4585976c1a67c9fdd201
2411Shravan/learn-python
/token.py
243
3.828125
4
token=0 name=True while(name): token=token+1 print("Token number ",token," please enter the doctor's cabin.") print("Do you wish to continue ? (0/1)") n=int(input()) if(n==0): name=False else: continue
fec261ea779041d06edb0ef725956afa8f6b2967
2411Shravan/learn-python
/binarysearchrecursion.py
504
3.765625
4
def bin_search(l,x,start,end): if(start==end): if(l[start]==x): return start else: return -1 else: mid=int((start+end)/2) if(l[mid]==x): return mid elif(l[mid]>x): return bin_search(l,x,start,mid-1) else: ...
afc92911c5f9a06b7b98747a91b229e5ec9f8c5c
2411Shravan/learn-python
/dobblegame.py
795
3.625
4
import string import random symbols=[] symbols=list(string.ascii_letters) card1=[0]*5 card2=[0]*5 pos1=random.randint(0,4) pos2=random.randint(0,4) sames=random.choice(symbols) symbols.remove(sames) print(pos1,pos2) if(pos1==pos2): card2[pos1]=sames card1[pos1]=sames else: card1[pos1]=sames card2[pos2]=sames ...
00d9d82ee8e5b1da815dd3b91ee642ec416f10c7
WoohyunSHIN/Python_Libraries
/SqlLite3/02.sqlite-test.py
1,286
3.65625
4
import sqlite3 conn =sqlite3.connect('sqlite3/example.db') c = conn.cursor() # Never do this -- insecure! # target = 'RHAT' # c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % target) # 관계형 데이터베이스에서, 1 row == 1 case(data) == 1 record 라고 말한다. # WHERE 포함 이후의 부분은 조건절이다. 1 record 기준으로 뽑아낸다. # 데이터를 가져올땐 fecth()를 사...
a416e1b0bba21374835bfb16f79bb92459ad97ab
WoohyunSHIN/Python_Libraries
/DeepLearning/Chapter2/01.perceptron.py
1,257
3.578125
4
# 인간이 인공적으로 정해주는 부분은 w1, w2와 theta 와 같은 임계값을 정의해준다. import numpy as np # AND Logic without numpy def AND(x1,x2): w1, w2, theta = 0.5, 0.5, 0.7 tmp = x1*w1 + x2*w2 if tmp <= theta: return 0 elif tmp > theta: return 1 # AND Logic with numpy x = np.array([0,1]) # 입력값 w = np.array([0.5, 0...
fca18d05aa62db66d84ae0b21cb81bd5fcc8f0c5
WoohyunSHIN/Python_Libraries
/Crawling/09_bs4_bugs.py
297
3.625
4
from bs4 import BeautifulSoup import urllib.request url = 'https://music.bugs.co.kr/chart' response = urllib.request.urlopen(url) soup = BeautifulSoup(response,'html.parser') results = soup.select('th>p.title > a') print(results) print('______') for result in results: print(result.string)
43fe267d6f460592d7b81c598acf7736df8441a5
Marcuswkds/ICP1
/Q1.py
519
4.0625
4
#Question 1 #Differences between Python 2 and Python 3 #1) The print keyword in Python 2 is replaced by the print() function in Python 3 #2) In Python 2 implicit str type is ASCII. But in Python 3 implicit str type is Unicode. #3) In Python 2, if you write a number without any digits after the decimal point, it rou...
a7a0812e5b5b0d7da40eae8a942bf6460ee964b6
lucas-m98/cdo_project
/post.py
1,241
3.515625
4
class RedditPost(): # Initializer for a single reddit post class def __init__(self, input): try: self.title = input["title"] self.score = input["score"] self.url = input["permalink"] # Some posts do not contain thumbnails, so it is necessary to check for...
27caf6e1854a5e2795ac48e430b4c1edc60b52e2
jps27CSE/Data-Structures-and-Algorithms
/Python/Linear Search.py
435
3.953125
4
n=int(input("Enter number of elements:")) count=0 list=[] for i in range(0,n): elements=int(input()) list.append(elements) search=int(input("Enter the number you want to search:")) for i in range(0,n): if list[i]==search: print("number is present at index:",i+1) count...
1051d5d57ba7c8c7cc5d2fd0eac24f15eff265b6
abhinavk454/Dynamic-Programming-python-code
/01 Knapsack problems/SubsetSumReccursive.py
279
3.609375
4
def subset(arr, k): if sum(arr) == k: return True if not arr: return False elif arr[-1] <= k: return (subset(arr[:-1], k-arr[-1])) or (subset(arr[:-1], k)) elif arr[-1] > k: return subset(arr[:-1], k) print(subset([1, 2, 3], 4))
b1c33417df30b02f42b8769064907be79d4d1b31
I-bluebeard-I/Python-Study
/Lesson_1/part01_lesson01_task04.py
989
4.03125
4
""" ЗАДАНИЕ 4 Склонение слова Реализовать склонение слова «процент» во фразе «N процентов». Вывести эту фразу на экран отдельной строкой для каждого из чисел в интервале от 1 до 100: 1 процент 2 процента 3 процента 4 процента 5 процентов 6 процентов ... 100 процентов """ number = 0 percent = { '0': 'процентов', ...
bdc7cac6740c94c1cea4d3c9c9b9246be176139c
pykili/py-204-hw1-Dyachkova519
/task_1/solution_1.py
98
3.546875
4
# your code here a = input() ma = 0 for i in a: if int(i) > ma: ma = int(i) print(ma)
537548a401a27984bfe6c089468fdeb6664b661c
job4Greymore/Python_Structural_Programming
/Topics/Num Rounding.py
286
3.796875
4
#Rounding function a float to an integer. n = 3.912 p = 2 #Default rounding function without decimal place declaration # round(n)-rounds to the nearest whole number r1 = round(n) print(r1) #Declaration of decimal place declaration r2 = round(n, p) print(r2) r3 = round(145/2) print(r3)
7cf8b93de077f55a20d4df7f4904a6ca29dbfe45
Pedro312/character
/character.py
1,151
3.65625
4
class Character(object): def __init__(self, name, hp, damage, attack_speed, armor): self.name = name self.damage = damage self.health = hp self.attack_speed = attack_speed self.bag = [] self.armor = armor def pick_up(self, item): self.bag.append(i...
ea1dd61656c1c1ab607e1cef9988cf66488e1061
edmolten/codevita2016
/c.py
1,143
3.96875
4
#!/usr/bin/env python # x1 rigth curves # y1 left curves # por cada curva derecha x1 gana x2 metros # por cada curva izquierda y1 gana y2 metros # la velocidad es S km # La carrera tiene Z km # Cada Z1 km ambos conductores paran y tardan x3 e y3 segundos (slo pasa si la distancia faltante es mayor al pit, NO si son ...
b2621c9c0430fd518718226a1aa0684d00e1b2b7
jeremyyew/tech-prep-jeremy.io
/code/topics/2-lists-dicts-and-strings/E13-roman-to-integer.py
872
3.859375
4
''' - For each roman numeral, if the current value is less than the next numeral's value, we are at a 'boundary' number e.g. 4, 9, 40, 90, etc. - If so, then instead of adding the value, we simply subtract that value. ''' class Solution: def romanToInt(self, s) -> int: res = 0 r_to_i = { ...
c68bae850584f142a9aee88eb538dfb8276d4fd6
jeremyyew/tech-prep-jeremy.io
/code/topics/8-tries/M211-add-and-search-word.py
1,649
3.625
4
''' If `word[i] == '.'`, then return the result of a search from each existing child, beginning from `word[i+1]`, as if that was the correct child. ''' class TrieNode: def __init__(self): self.children = [None]*26 self.isEnd = False def contains(self, child): return self.children[chi...
d83f455031e2c87eb424d713d71c0b25c0f08119
jeremyyew/tech-prep-jeremy.io
/code/techniques/7-BFS/H126-word-ladder-ii.py
2,122
3.546875
4
''' - Store paths instead of path length. It does seem like a lot of space, but even if you use pointers its the same amount of space. - Once there is a min path, terminate any other path that is the same length. - Do not use a global visited - we need all paths, including paths that use the same nodes. Instead, che...
5a8c2f4cb9c5932b9c5c231070546011e0f8b4bf
jeremyyew/tech-prep-jeremy.io
/code/techniques/14-dynamic-programming/M516-longest-palindromic-subsequence.py
2,285
3.546875
4
''' For each new element, traverse the string backwards looking for elements to form new symmetries with, deriving the new length from the length of inner palindromes. Start from `0`, and every time you shift `i` to the right, shift `j` backwards from `i-1` to `0`. 1. Let `dp(j, i)` be the length of the longest pal...
dc804c10e9cff208ff56ae4380c3112a014a4496
jeremyyew/tech-prep-jeremy.io
/code/topics/2-lists-dicts-and-strings/E283-move-zeroes.py
763
3.953125
4
''' - If zero, add to zeros, which is the number of consecutive zeroes directly before index i. - If non-zero and we have no consecutive zeros: pass. - If non-zero and we have at least one zero before i: - swap the first zero(at index i - zeros) with the current value. - note that the number of consecutive zero...
13966d924e45e21f69b44bf5059ce6c21837300e
jeremyyew/tech-prep-jeremy.io
/code/techniques/2-two-pointers/M15-three-sum.py
5,336
3.609375
4
import itertools from typing import List # My version of someone else's solution below. For modularity, I abstract the two-sum scan, and pass it an array slice instead of indices. # We simply require the twoSum to return the values that add up to the target (instead of indices), with no duplicates, and it cannot assu...
04825716476c0340ee05c32b6d373a32a365f312
jeremyyew/tech-prep-jeremy.io
/code/fb-prep/M287-find-duplicate-number.py
1,095
3.6875
4
class Solution: def findDuplicate(self, nums): i = 0 while i != nums[i]: print(i) k = nums[i] nums[i] = i i = k # [1]: nums[i], i = i, nums[i] print(nums) return i r = Solution().findDuplicate([1, 1, 2, 3, 4]) print(r)...
ac0145ec2c124e57de681fddb861c116a0a3ec9d
jeremyyew/tech-prep-jeremy.io
/code/topics/4-trees-and-graphs/E104-maximum-depth-of-binary-tree.py
1,021
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class SolutionRec: def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 else: return max(self.ma...
d6ddba1536a4377251089a3df2ad91fb87b987b8
jeremyyew/tech-prep-jeremy.io
/code/techniques/8-DFS/M341-flatten-nested-list-iterator.py
606
4
4
''' - Only pop and unpack what is necessary. - Pop and unpack when `hasNext` is called - it ensures there is a next available for `next`, if there really is a next. - At the end only need to check if stack is nonempty - stack nonempty and last element not integer is not possible. ''' class NestedIterator(object): ...
ef7e005111123d2a239cbfd8a1e9f0e75fd435f4
jeremyyew/tech-prep-jeremy.io
/code/techniques/4-merge-intervals/M57-insert-interval.py
3,586
3.859375
4
''' - We present a simple linear solution. - It is possible to do binary search, but deceivingly tricky to decide what to return or the indexes to insert at. - An attempt is done below. ''' from typing import List class SolutionLinear: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> Li...
72a5f79be816896fcdfbab8dd0a54f1588d25551
jeremyyew/tech-prep-jeremy.io
/code/topics/1-searching-and-sorting/M148-sorted-list.py
1,589
4.125
4
Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sortList(self, head): pass # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(self, head): current_size = 1 left = he...
0cc2d611995b7dea4b0a25b0c712472a59b0f2b5
ravitejaseelam/Shell
/JsonActions.py
5,187
3.5
4
import json import sys import os import os.path def ask_which_to_keep(each1, each2, dic): print("\nSame priority is encountered Plz handle by giving which one to keep\n") print(json.dumps(each1, indent=4)) print(json.dumps(each2, indent=4)) name = input("Enter name to be inserted") if each1["name"...
065004e81dc28ae4d4a6acee52d3808bb8498841
vgattani-ds/programming_websites
/hackerrank/10_days_of_Statistics/day_7_spearmans_rank_correlation_coefficient.py
803
3.6875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys def get_rank(X): indices = list(range(len(X))) indices.sort(key=lambda x: X[x]) rank = [0] * len(indices) for i, x in enumerate(indices): rank[x] = i return rank def correlation(*args): X = args...
4536c7d2256fa95c62720c0f12eb5e9a2b952937
vgattani-ds/programming_websites
/leetcode/1081_smallestSubsequence.py
665
3.640625
4
class Solution: def smallestSubsequence(self, s: str) -> str: last_index = {} for index, char in enumerate(s): last_index[char] = index result = [] for index, char in enumerate(s): if char not in result: ...
416883b316d6201e6d052e74dad1f21876179d52
vgattani-ds/programming_websites
/leetcode/0229_majorityElement.py
1,123
3.875
4
from typing import List class Solution: def majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) if n <= 1: return nums cand1=None cand2=None count1=0 count2=0 for num in nums: ...
2cf57cec07d96fb6187b12d51bdb0d54d9b69d7d
vgattani-ds/programming_websites
/hackerrank/python_practice/second_lowest_grade.py
814
3.75
4
if __name__ == '__main__': nested_list = [] for _ in range(int(input())): name = input() score = float(input()) nested_list.append([name,-score]) max_v = float("-inf") runner_v = float("-inf") runner_stu = [] max_stu = [] for name, score in nested_list: if...
9ecf0251760eb7dea1897f5c73ca64715de98785
vgattani-ds/programming_websites
/leetcode/0414_thirdMax.py
917
3.9375
4
from typing import List class Solution: def thirdMax(self, nums: List[int]) -> int: max_num = set() for num in nums: max_num.add(num) if len(max_num) > 3: max_num.remove(min(max_num)) if len(max_num) < 3: ...
cf2076024b465c84689f6ba78cdd675c7b3f518c
vgattani-ds/programming_websites
/leetcode/0905_sortArrayByParity.py
784
3.546875
4
from typing import List class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: odd = [] insert_index = 0 for i in A: if i%2 == 0: A[insert_index] = i insert_index += 1 else: ...
849cc598ac09b5f899b312e95245d93d88ac4d79
vgattani-ds/programming_websites
/hackerrank/10_days_of_Statistics/day_6_clt_3.py
520
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT # Enter your code here. Read input from STDIN. Print output to STDOUT # Enter your code here. Read input from STDIN. Print output to STDOUT import sys import math lines = iter(sys.stdin) n = int(next(lines)) mean = float(next(lines)) std = flo...
e6947f9fb72f38a30cd59a50d38d6112b978a625
vgattani-ds/programming_websites
/leetcode/1352_ProductOfNumbers.py
1,595
3.5
4
from functools import reduce from math import prod class ProductOfNumbers: def __init__(self): self.nums=list() def add(self, num: int) -> None: self.nums.append(num) return if not self.nums: self.nums.append(num) return last_number = self.nums[-...
081c39e989688e3bce6a6eee4fc2df42e3fe756d
zhichaoZhang/hotfix_patch
/zzc-python3-webapp/www/db/Connect2MysqlTest.py
800
3.734375
4
# coding=utf-8 # 导出MySql驱动 import mysql.connector # 设置用户名、密码、数据库名 conn = mysql.connector.connect(user='root', password='admin_zzc', host='127.0.0.1', database='test') cursor = conn.cursor() # 创建user表 cursor.execute('create t...
02303308d186f5f0b89eba92cf9728f06835b859
eluke66/checkers
/python/python/src/Move.py
3,044
3.546875
4
''' Created on Apr 9, 2017 @author: luke ''' from Coordinate import Coordinate from KingPiece import KingPiece class Move(object): def __init__(self, piece, board, moveFrom, moveTo): self.piece = piece self.board = board self.moveFrom = moveFrom self.moveTo = moveTo d...
9a6002e2d82d75a10a1df8a68fad30ed8fa6325f
PrathushaKoouri/Competitive-Coding-6
/80_LoggerRateLimiter(359).py
1,776
3.890625
4
# To implement double linked list we need a Node, created Node. class Node: def __init__(self, timestamp, message): self.timestamp = timestamp self.message = message self.prev = None self.next = None class Logger: # Here, initialized all the pointers in double linked li...
30c3168bef3c13592401b05f3e140cb35a239484
yanviegas/small_codes
/teste_1_quadrado.py
160
3.796875
4
side = float(input("Digite o valor correspondente ao lado de um quadrado: ")) peri = 4*side area = side**2 print("perímetro:", peri, "- área:", area)
6b2ca73b9e5ccf01fa7ab8a4c1c54cc793b4feba
yanviegas/small_codes
/teste_1_fatorial.py
160
3.984375
4
num = int(input("Digite o valor de n: ")) if num != 0: fat = num else: fat = 1 while num > 1: num = num - 1 fat = fat * num print(fat)
fe99c8ccc57283cfb6daf8f39f4c507e8730957c
yanviegas/small_codes
/exer_2_inverte_seq.py
253
3.875
4
def main(): x = int(input("Digite um número: ")) lista = [] while x != 0: lista.append(x) x = int(input("Digite um número: ")) for y in range(len(lista) - 1, -1, -1): print(lista[y]) main()
0de0d10a0c66f4248d12cbe59f506f49e08d796c
pallavineelamraju/MyEffort
/PythonPrograms/hackerrankprograms/countsubstr.py
345
3.984375
4
def count_substring(string,sub_string): l=len(sub_string) count=0 for i in range(0,len(string)): if(string[i:i+len(sub_string)] == sub_string ): count+=1 return count str=input() if(1<=len(str)<=200): substr=input() print(count_substring(str,substr)) else: print("string ...
ed24a3bdc6d9260988b8e5bc8a247b1c7ab9dc7b
sachin1005singh/complete-python
/python_program/all program/15list_use.py
249
4
4
i = 0 numbers = [] while i<6: print("At the top i is %d" %i) numbers.append(i) i += 1 print("Numbers now:", numbers) print("At bottom i is %d" %i) print("The number :") for num in numbers: print(num)
e01ebd5c8a72ea703ef839b4260d792a819d9089
sachin1005singh/complete-python
/python_program/all program/8reading_file.py
873
3.90625
4
from sys import argv script, filename = argv txt = open(filename) print("Here's your file %s" %filename) print(txt.read()) print("Type filname again :") file_again = input("$") txt_again = open(file_again) print(txt_again.read()) # use of file read and write print("We're going to erase %r" %file...
902738dec190609def2231db3b3b2a42506b7ff9
sachin1005singh/complete-python
/python_program/fabonic series.py
166
3.5
4
# use of fabonic series def fab(n): res = [] a, b = 0,1 while a<n: res.append(a) a,b = b, a+b return res fa = fab(100)
73bac6a349743b14c5a7e78f1aacbe2b460e3fb8
sachin1005singh/complete-python
/python_program/function use.py
173
3.921875
4
#use of function def greet(name,msg): """ this function is for basic use of function.""" print("hello", name + ',', msg) greet("sachin","good morning!")
5ccb88df6a21f7a105c7c08d2551412c4cc307bb
sachin1005singh/complete-python
/python_program/findvowel.py
218
4.28125
4
#vowels program use of for loop vowel = "aeiouAEIOU" while True: v = input("enter a vowel :") if v in vowel: break print("this in not a vowel ! try again !!") print("thank you")
5a5b44d7f3f64701e827a9e1c2bc072ceeebff79
Meormy/PIAIC_Assignments_1
/InterestCalculator.py
436
3.875
4
# A = Total Accrued Amount (principal + interest) # P = Principal Amount # I = Interest Amount # r = Rate of Interest per year in decimal; r = R/100 # R = Rate of Interest per year as a percent; R = r * 100 # t = Time Period involved in months or years # Equation: # A = P(1 + rt) P = int(input("Enter Amount : ")) R = ...
81fa7d68ab70c6319c299caadb885b5f34e162b0
zhou-jia-ming/Learn-AI
/ch1/prog1.py
1,640
3.59375
4
# -*- encoding: utf-8 -*- # @FileName: prog1.py # @Author: Zhou Jiaming # @Time: 8/25/21 10:36 PM """ 三个门后边有两个门空的,一个有奖 要求: 选择一个门,争取获得奖品 你选中一个门,还没有打开门。 然后主持人打开另一个空的门。 此时你换一个门会得到更大的概率吗? """ import random def DoorAndPrizeSim(switch, loopNum): """ 模拟各种情况下的中奖概率 :param switch: :param loopNum: :return...
23196f4de3a93497995f5f55cd58455bd024c7d5
w4995-dl-colorization/Colorization-with-Attention
/ops.py
4,475
3.625
4
import tensorflow as tf def _variable(name, shape, initializer): """Helper to create a Variable stored on CPU memory. Args: name: name of the Variable shape: list of ints initializer: initializer of Variable Returns: Variable Tensor """ var = tf.get_variable(name, shape, ...
b7767437a8b10ab79584dee7c62d6dcc312a0df3
vvarga007/linux_tools
/python/examples/Math.py
1,313
3.515625
4
from unittest import TestCase """ Example code to demonstrate Sphinx capabilities. Sphinx uses reStructuredText as its markup language, and many of its strengths come from the power and straightforwardness of reStructuredText and its parsing and translating suite, the Docutils. """ class Math: """ Methods for ar...
be933bc97528fe0e1dac8c5e4adff84032070dac
ssd338/Python-leaning
/function/function3.py
188
3.625
4
def p_plus(a, b): print(a + b) def r_plus(a, b): return a + b p_result = p_plus(2, 3) r_result = r_plus(2, 3) print(p_result, r_result) #return 값이 없으므로 p_result는 none
ddef902f4d6dbab328949b2fe67854e3afd2c01a
kartsridhar/Problem-Solving
/HackerRank/10-Days-of-Statistics/Day0/weightedMean.py
246
3.84375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) x = list(map(float, input().split())) w = list(map(float, input().split())) weighted = sum(i*j for i, j in zip(x, w)) avg = weighted/sum(w) print('%.1f' % avg)
74a079f8a0c40df56f5412dd4723cb2368b3759a
kartsridhar/Problem-Solving
/halindrome.py
1,382
4.25
4
""" Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if AT LEAST one of the following conditions satisfy: 1. S is a palindrome and of length S >= 2 2. S1 is a halindrome 3. S2 is a halindrome In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1] Example 1: input: harshk ou...
408d751896467c077d7dbc1ac9ffe6239fed474d
kartsridhar/Problem-Solving
/HackerRank/Problem-Solving/Basic-Certification/unexpectedDemand.py
1,630
4.40625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'filledOrders' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY order # 2. INTEGER k # """ A widget manufacturer is facing unexpectedly high d...
dfc62ddbade85590df3743bc838e458f120f0259
kartsridhar/Problem-Solving
/Ocado/necklaceProblem.py
883
4.0625
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # You have a list where each number points to another.Find the length of the longest necklace # A[0] = 5 # A[1] = 4 # A[2] = 3 # A[3] = 0 # A[4] = 1 # A[5] = 2 def solution(A): # write your code in Python 3.6 if len(A) =...
4d6c6e1aae0f3a6163b541ebd08e1353c22cf496
kartsridhar/Problem-Solving
/HackerRank/Problem-Solving/Strings/strongPassword.py
1,257
3.734375
4
#!/bin/python3 import math import os import random import re import sys # Complete the minimumNumber function below. def minimumNumber(n, password): # Return the minimum number of characters to make the password strong count = 0 numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" uppe...
0bb4a60d97bd89abc8f458373ae62035e6d35ff7
kartsridhar/Problem-Solving
/findLargestNumber.py
471
3.890625
4
def isSorted(num): digits = list(str(num)) unique = list(set(digits)) if digits != unique: return False else: return digits == list(sorted(digits)) def findLargestNumber(num): if num < 10: return num while num > 9: if not isSorted(num): num -= 1 ...
23e05ad2a184f9427b0750391ae2c8626a904c11
kartsridhar/Problem-Solving
/angryIntegers.py
743
3.640625
4
# count the number of angry numbers less than the current number # angry number = an integer of the form a^x + b^y # upper bound = 100000 def computeAxBy(a, b): upperBound = 9223372036854775806 result = [] x = 1 y = 1 while x <= upperBound: while y <= upperBound: if x + y <= ...
0974094bbfa2495cf4b67090c11c708eaa303443
kartsridhar/Problem-Solving
/2sigma/substrings.py
935
3.96875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'findSubstrings' function below. # # The function accepts STRING s as parameter. # def findSubstrings(s): # Write your code here # start iterating from the 0th index of the string. if it is a vowel, start a new loop fr...
ae2873c9c7a2ed57885f647fcba53c80f1fc4ba5
kartsridhar/Problem-Solving
/HackerRank/Problem-Solving/Dynamic-Programming/fibonacciModifiedMem.py
746
3.71875
4
#!/bin/python3 import math import os import random import re import sys # Complete the fibonacciModified function below. def fib(t1, t2, n, dp): if dp[n] != None: return dp[n] result = 0 if n == 1: result = t1 elif n == 2: result = t2 else: result = fib(t1,t2,n-2,d...
870e96663b255d9dde315db16b386a95e2370ba3
kartsridhar/Problem-Solving
/HackerRank/10-Days-of-Statistics/Day6/centralLimitTh1.py
313
3.5625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math maxWt = float(input()) n = float(input()) mean = float(input()) std = float(input()) mean *= n std = std * math.sqrt(n) phi = lambda m, v, val : 0.5 * (1+math.erf((val-m)/(v*math.sqrt(2)))) print(round(phi(mean, std, maxWt), 4))
60be71eb81f110604599a4feec973cbd1042dbe6
jin-sj/git_ci_test
/koreantools/utils/audio_utils.py
1,827
3.640625
4
""" Utily functions to process audio files """ import os import sys import wave def pcm_to_wave(pcm_file_path, num_channels=1, num_bytes=2, frame_rate=16000, nframes=0, comp_type="NONE", comp_name="NONE"): """ Converts a raw .pcm file to .wav file Args: pcm_file_path (str): Fu...
fd3d933e3a214e1378851cd253bea6850d41f9b0
jingd16/python-challenge
/PyPoll/main.py
3,693
3.890625
4
import os import csv #Set path to read and write CSV file csvpath = os.path.join("Resources", "election_data.csv") output_file = os.path.join("analysis", "PyPoll.txt") Total_vote = 0 Newlist =[] Newlist2=[] voterID_List = [] Location_List = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimi...
2852f25cf0c6b440307fc5af947f2bbcbe83496a
akshaykhadka/My-Projects
/_1_Cricket_Game.py
5,610
4.03125
4
import random def toss_coin(): coin = input("Choose 'E' for Even and 'O' for odd -> ") print(" ") your_num = int(input("Now select a number between 0-5: ")) random_num = random.randint(0, 5) print(" ") print("your number {} and computer's number {}".format(your_num, random_num)) random_su...
914c7c8db0d3d316d22d899ba6756368ae4eb392
pythonmite/Daily-Coding-Problem
/problem_6_medium.py
514
4.1875
4
""" Company Name : DropBox Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6] secondlargestelement >>> [5] """ def findSecondLargestNum(arr:list): max = arr[0] for num in arr: if num > max: max = num secondlargest = 0 f...
c08a00b4024394ba9514e576d8382edb74ae62a5
anonomity/PolynomialPopulation
/src/population.py
3,112
3.515625
4
from src.DNA import DNA from matplotlib import pyplot as plt import random class population: def __init__(self, d, amount, cluster1, cluster2,mutation): self.d = d self.amount = amount self.cluster1 = cluster1 self.cluster2 = cluster2 self.generations = 0 self.muta...
a8878ae25f45e5513652a7db6145af19c2055d3c
okayell/Scikit-learn_practice
/LinearRegression_1.py
1,663
3.78125
4
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression # ------簡單線性迴歸模型 y = a + bX(只有一個解釋變數)------ # # 建立 氣溫 與 營業額 陣列資料 temperatures = np.array([29,28,34,31, 25,29,32,31, 24,33,25,31, 26,30]) drink_sales =...
6de65ef6542225345787c1472099ac24fe4f2192
sf19pb1-hardeep-leyl/homework
/name_game.py
404
3.53125
4
""" name_game.py Translate the input name to the Name song """ import sys while True: try: name = input("Please type a name: ") except EOFError: sys.exit(0) rest = name[1:] nameGame = name + "," + name + ",bo-b" + rest + "\n" nameGame += "Banana-fana fo-f" + rest + "\n" name...
df7bcf4e2fef6069d52de88a7b9e456851bf9bd7
patelkajal18/textAdventure
/islandandme.py
3,002
4.25
4
#Start print("You were having a great summer by yourself alone in the middle of the ocean on a boat. You take a little nap to take a break from your self pity session. When you wake up, you find yourself on an island and your boat is broken. You are really hungry but you also need shelter. Will you find food or shelte...
87439d1bf08409b01de0bff41cd6e4789ea36ef9
rsarwas/aoc
/2019-19/answers.py
3,312
3.78125
4
import sys from computer import Computer def solve(intcode): # Simple brute force solution # we could print the 10 by 10 results to see if there is a cone pattern # and limit the edges of the cone, but this is just too easy. # While not stated clearly in the instructions, the program halts after #...
ae3cf1c9686d5ab5d23aa88f657305857ff21015
rsarwas/aoc
/2022-08/answers.py
3,640
3.8125
4
# Data Model: # =========== # lines is a list of "\n" terminated strings from the input file def part1(lines): map = parse(lines) trees = visible(map) # display(trees,len(map)) return len(trees) def part2(lines): data = parse(lines) # print(scenic_score(1,2,data)) # print(scenic_score(3,...
61f9cb0446e9aabc4181fe436e2768d854c1e7ad
rsarwas/aoc
/2018-15/answers.py
7,841
3.828125
4
# Data Model: # =========== # lines is a list of "\n" terminated strings from the input file # map is a dictionary keyed with a (row,col) tuple, containing values # indicating the contents of the location '.' open floor, ('G',hp) or ('E',hp) POWER = 3 HP = 200 WALL = "#" OPEN = "." GOBLIN = "G" ELF = "E" def part1(li...
2bede8133579085185e2fe8b9794e2fe4562878a
rsarwas/aoc
/2022-18/answers.py
5,217
3.515625
4
# Data Model: # =========== # lines is a list of "\n" terminated strings from the input file def part1(lines): data = parse(lines) # data = [(1,1,1), (2,1,1)] # testg data; result should be 10 result = solve(data) return result def part2(lines): data = parse(lines) result = solve2(data) ...
fe56b2aba085594a6530eeb7b432d1c3ae812ca1
rsarwas/aoc
/2015-03/answers.py
2,242
3.578125
4
# Data Model: # =========== # input is a single line of 4 characters {<,>,^,v} # visits is a dictionary with an (x,y) tuple for the key # and value is the number of times visited def part1(line): visits = {} (x,y) = (0,0) visits[(x,y)] = 1 for move in line: if move == 'v': y -= 1 ...
fbb5b5aaca9032c33b9030eed7bf35e7faed16c0
rsarwas/aoc
/2022-01/answers.py
1,932
4.03125
4
"""A solution to an Advent of Code puzzle.""" # Data Model: # =========== # _lines_ is a list of "\n" terminated strings from the input file. # Each line is an integer or empty (just a newline). # There is no empty line at the end # _totals_ is list of integers. Each one is the sum of a group of # integers in the inpu...
e79922fcc84dd252f76cd4e5a8e9de9486187f77
rsarwas/aoc
/2022-25/answers.py
1,103
3.9375
4
"""A solution to an Advent of Code puzzle.""" def part1(lines): """Solve part 1 of the problem.""" total = 0 for line in lines: total += to_decimal(line.strip()) return to_snafu(total) SNAFU = {"2": 2, "1": 1, "0": 0, "-": -1, "=": -2} DECIMAL = {2: "2", 1: "1", 0: "0", -1: "-", -2: "="} ...
523d5b0a7100e8efc1b6432b8955ddb19b6d9722
Imperiopolis/ccmakers-python
/Day 1/03 formatStrings.py
395
3.96875
4
print "There are %d types of people." % 10 print "Those who know %s and those who %s." % ('binary', "don't") print "Isn't that joke so funny?! %r" % False print "This is the left side of..." + "a string with a right side." print "This is the left side of...", "a string with a right side." # what happens if you use %...
9df42cc268791c01464b91358474059c4b9a27d5
Kranek/BlockBuster
/blocks.py
3,596
3.671875
4
""" This file contains block variants used in the BlockBuster """ from pygame.sprite import Sprite from gamedata import Assets class Block(Sprite): """ Basic block type """ WIDTH = 30 HEIGHT = 15 def __init__(self, x, y, color): """ Initialize with coordinates and block "color...
cfa1d639c413d97d0cedfb6fe6881ba9c7d52dae
Kranek/BlockBuster
/blockbuster.py
1,614
3.515625
4
""" The main file of the BlockBuster. Run it to play and have fun! """ from gamedata import Assets from gameclock import GameClock from pygame import init from pygame.display import set_caption, set_icon, set_mode, get_surface, flip from pygame.event import get from constants import LEVEL_WIDTH, LEVEL_HEIGHT from GameS...
dfda4d8dd6f8e90f15c6247636eaf7a83358d61b
ALXlixiong/Python
/2019.8.7/test.py
115
3.90625
4
#coding:UTF-8 num =10 if num == 8: print("8") elif num == 6: print("6") else: print("10") print("end")
cf5b7929308ea1f2343e9f0a905eee8599a5209c
osakhsa/FirstAPI
/v3/create_tables.py
511
3.671875
4
import sqlite3 con = sqlite3.connect('data.db') cur = con.cursor() cur.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY ASC, name TEXT UNIQUE, price REAL)') cur.execute('INSERT INTO items VALUES (null, "chair", 1500)') cur.execute('INSERT INTO items VALUES (null, "cupboard", 3000)') cur.execute('CREATE...
6699cc593e0ff334ac5fe9e1ed574bc51f5528a9
Ph0en1xGSeek/ACM
/LeetCode/56.py
775
3.71875
4
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if len(intervals) == 0: ...
d352eb5219c39d38076d2d46690e9853bf1ea574
Ph0en1xGSeek/ACM
/LeetCode/21.py
848
3.9375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...
a6e9d4dd78bb918d56b6c77333cc96dab3070081
Ph0en1xGSeek/ACM
/LeetCode/189.py
562
3.5625
4
class Solution(object): def reverse(self, nums, l, r): while(l < r): nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nu...
85a564273e14acc4a430aa1d0bcabf09105e5f5b
Ph0en1xGSeek/ACM
/LeetCode/20.py
802
3.75
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ arr = [] for i in s: if i == '(' or i == '[' or i == '{': arr.append(i) elif i == ')': if len(arr) > 0 and arr[-1] == '(': ...
51a700adff1571f3b83ce7ef30cc83772ae8f354
Ph0en1xGSeek/ACM
/LeetCode/108.py
1,420
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode ...