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
bd432f53037d74b956cbfa99284981f7e4d13e04
runopti/parity_experiment
/results/test/experiment1-2016-07-03-23:36:15/getData.py
948
3.65625
4
import numpy as np np.random.seed(0) def createTargetData(digit_list): """ generate len(digit_list) vector, whose i th element is the corresponding parity upto the ith element of the input.""" sum_ = 0 parity_list = [] # check the first digit sum_ = digit_list[0] if sum_ % 2 == 0: ...
0a0c101703b97b8a12ee170093947afd4638c1fa
slourdenadin/Python-ASRBD
/script.py
972
3.765625
4
#!/usr/bin/pyton.3.6 ''' texte = "je suis du texte" print (texte * 3) txt= "HEllo! Wolrd!!!" print (len(txt)) print (txt[1]) print (txt[0:5]) print("bonjour %s je m'appelle " % ("Medhi")) text = "je suis du \"texte\"" print(text) maListe=["1er","deuxieme","troisieme"] secondList = maListe[:] maListe[0]="toto...
fc9754350bacea837273841d8bd7523b49721793
Miloxing/test
/tongxunlu.py
1,186
3.734375
4
print('欢迎进入通讯录程序\n1:查询联系人资料\n2:插入新的联系人\n3:删除已有联系人\n4:退出通讯录程序\n') mingdan=dict() while 1: get=int(input('请输入相关的指令代码:')) if get == 4: print('感谢使用通讯录程序') break elif get == 2: name=input('请输入联系人姓名:') if name not in mingdan: mingdan[name]=input('请输入用户联系电话:'...
3368770258469eacad4a73cefbd20daa8da78ee1
to-olx/team-3-rm-recommendations-app
/recommenders/collaborative_based.py
5,293
3.546875
4
""" Collaborative-based filtering for item recommendation. Author: Explore Data Science Academy. Note: --------------------------------------------------------------------- Please follow the instructions provided within the README.md file located within the root of this repository for guidanc...
a72b8412d9b2ca109436ac39d7dc3dcc021a8d75
jsvn91/example_python
/eg/getting_max_from_str_eg.py
350
4.15625
4
# Q.24. In one line, show us how you’ll get the max alphabetical character from a string. # # For this, we’ll simply use the max function. # print (max('flyiNg')) # ‘y’ # # The following are the ASCII values for all the letters of this string- # # f- 102 # # l- 108 # # because y is greater amongst all y- 121 # # i- 105...
7196477329330b8797f00a744ee2ae7d55ea32e5
decadenza/SecurFace
/database.py
964
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Author: Pasquale Lafiosca # Date: 20 July 2017 # import os import sqlite3 as sql class Database: def __init__(self,p): if not os.path.exists(os.path.dirname(p)): #if folder does not exists os.makedirs(os.path.dirname(p)) #create it ...
a8491883d0cb47411b30397e87e84b98cd281368
t0mm4rx/ft_linear_regression
/functions.py
1,035
3.515625
4
""" This module contains useful functions used globally. """ import numpy as np import pandas as pd from typing import Tuple def prepare_data(data: pd.DataFrame) -> Tuple[float, float]: """Normalize data, so both axis have a similar scale.""" max_km = data["km"].max() max_price = data["price"].max() data["km"] =...
f52112864ac6ebb6d9ca47c1538c9d98a49bac32
yopiyama/Tools
/mybase64.py
2,621
3.515625
4
#!/usr/bin/env python #coding:utf-8 """ Base64 Script """ import inspect def str_to_bin(text): """ str -> binary """ bin_text = "" for i in text: i_bin = format(ord(i), "b") bin_text += (i_bin if len(i_bin) == 8 else ("0" * (8 - len(i_bin))) + i_bin) return bin_text def bin_to_str(bin_text): """ binary -> s...
4b16c70b8cbf99dcefd01d144e6e1479e88a3dfd
AntonioCR99/Programaci-n-avanzada
/escribecsv.py
1,671
3.609375
4
# Escritura de archivo texto plano # Modulo para trabajar con el sistema operativo import os # Modulo para trabajar con archivos csv import csv # Se declara clase Contacto # <<clase Contacto>> sirve para poblar una lista que perimte manejar en memoria los datos. # La lista se vaciía al archivo csv final de...
5935356da274001c362f979a7405c61f71cdef0b
Zhaokun1997/2020T1
/comp9321/labs/week2/activity_2.py
1,596
4.4375
4
import sqlite3 import pandas as pd from pandas.io import sql def read_csv(csv_file): """ :param csv_file: the path of csv file :return: a dataframe out of the csv file """ return pd.read_csv(csv_file) def write_in_sqlite(data_frame, database_file, table_name): """ :param data_frame: the ...
449e11de328f39c61ad66d664df6af960fbb14de
Zhaokun1997/2020T1
/comp9321/labs/week3/activity_3.py
1,187
3.828125
4
import pandas as pd def print_data_frame(data_frame, print_columns=True, print_rows=True): if print_columns: print(",".join(data_frame.columns)) if print_rows: for index, row in data_frame.iterrows(): print(",".join([str(row[column]) for column in data_frame])) def data_cleaning(...
81873fbcbd1279ebe655ce86aa9dd35803bd1d41
Lioheart/Alien-Invaders
/alien_invasion.py
1,834
3.515625
4
""" Wyświetla okno PyGame """ import pygame as pygame from pygame.sprite import Group import game_functions as gf from button import Button from game_stats import GameStats from scoreboard import Scoreboard from settings import Settings from ship import Ship def run_game(): """ Inicjalizacja gry """ ...
1c7206129917825245706ef49a83cb50fe51b893
hanok2/national_pastime
/utils/utilities.py
1,132
3.875
4
import random import heapq class PriorityQueue: def __init__(self): self.elements = [] def empty(self): return len(self.elements) == 0 def put(self, item, priority): heapq.heappush(self.elements, (priority, item)) def get(self): return heapq.heappop(self.elements)[1]...
ebd1beec3027159b644104cbb2efc334f13b0c69
hanok2/national_pastime
/baseball/manager.py
1,124
3.75
4
import random from career import ManagerCareer from strategy import Strategy class Manager(object): """The baseball-manager layer of a person's being.""" def __init__(self, person, team): """Initialize a Manager object.""" self.person = person # The person in whom this manager layer embeds ...
33c871d344b9fad6b7eddc12caa8338290e22fd3
hanok2/national_pastime
/events/__init__.py
1,477
3.71875
4
import random class Event(object): """A superclass that all event subclasses inherit from.""" def __init__(self, cosmos): """Initialize an Event object.""" self.year = cosmos.year if self.year < cosmos.config.year_worldgen_begins: # This event is being retconned; generate a random da...
e4070ff2588f938c67c53480a12309c62db79a52
hanok2/national_pastime
/people/body.py
10,826
3.875
4
import random from random import normalvariate as normal # TODO implement dynamics of aging class Body(object): """A person's body.""" def __init__(self, person): """Initialize a Body object. Objects of this class hold people's physical attributes, most of which will be baseball-ce...
a85d00e5d21027f79b7d4f6211f46304e0ed30f7
xyz-09/codinggames
/easy/py/easy-power-of-thor-episode-1.py
941
3.84375
4
# EASY: https://www.codingame.com/training/easy/power-of-thor-episode-1 import sys import math # Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders. # light_x: the X position of the light of power # light_y: the Y position of the light of power # initial_tx: Tho...
6beb87732a05a21be5686c6d29395c58c4a0563b
mrjoechen/PythonFromZero
/init/26/lambda_test.py
319
3.734375
4
def add(x, y): return x + y print(add(1, 2)) a = lambda x,y : x+y print(a(1, 2)) alist = list(filter(lambda x:True if x % 3 == 0 else False, range(100))) print(alist) adict = {1:'a', 2:'b', 3:'c'} for a in adict.items(): print(a[1]) alam = lambda item:item[1] for a in adict.items(): print(alam(a))
2a6a4a1db387fc79ff44912175cb4d27b7e29c15
Sharonbosire4/hacker-rank
/Python/Contests/Project Euler/euler_007/python_pe_007/__main__.py
1,104
3.546875
4
from __future__ import print_function import sys class PE_007: def __init__(self, max_size=100000): self.primes = [] self.collect_primes(max_size) def find_prime(self, index): if len(self.primes) == index: collect_primes(index*2) if index < 1 or index >= len(self.p...
44dddcfb5d819b565d4168e0df67951609b648e9
Sharonbosire4/hacker-rank
/Python/Contests/week_of_code_36/acid_naming/__main__.py
558
3.65625
4
import sys from enum import Enum class Acid(Enum): NON_METAL = 'non-metal acid' POLYATOMIC = 'polyatomic acid' NOT_ACID = 'not an acid' def name_acid(text: str) -> Acid: hydro = text.startswith('hydro') poly = text.endswith('ic') if hydro and poly: return Acid.NON_METAL elif pol...
b5ef32acae6f59590e4cd373b2368eb4414bf12f
Sharonbosire4/hacker-rank
/Python/Algorithms/Warmup/Staircase/python_staircase/__main__.py
392
4.125
4
from __future__ import print_function import sys def staircase(height): lines = [] for n in range(height): string = '' for i in range(height): string += '#' if i >= n else ' ' lines.append(string) return reversed(lines) def main(): T = int(input()) for line in s...
9596f6ca7ea898f08d603b81be5a3608fa45d9ea
SHARADDUHOON/sharad-1st-day
/main.py
607
4.09375
4
print("hello world\nhello world \nhello world") print("Day 1 - String Manipultion") print("Concactenation is done with "+"sign,") print('eg = print("hello" + "world")') print("New line will be created by using a backslash and n") print("hello"+" "+ input("wht is your name?\n")) print(len(input(" what is your name?"))) ...
dc903ba5999763753228f8d9c2942718ddd3fe69
magicmitra/obsidian
/discrete.py
1,190
4.46875
4
#---------------------------------------------------------------------------------- # This is a function that will calculate the interest rate in a discrete manner. # Wirh this, interest is compounded k times a year and the bank will only add # interest to the pricipal k times a year. # The balance will then be return...
7ec45e973a15a4a72ff5cd017832cec2d8efec3c
gitKrystan/LearnPython
/solver.py
2,384
3.828125
4
import argparse def validity(word, rack_list): rack_test = list(rack_list) w_rd = "" for l in word: if l in rack_test: rack_test.remove(l) w_rd += l elif "*" in rack_test: rack_test.remove("*") w_rd += "*" else: return Fals...
6692e4cfda720450ad1e6e7f7de95e85eeb02e8a
BrianDouglas/bucketFill
/test.py
313
3.53125
4
from arrayFill import * canvas = create2dArray(int(input("Specify number of Columns: ")), int(input("Specify number of Rows: "))) print2dArray(canvas) canvas = diag2dArray(canvas) print2dArray(canvas) fillBucket(canvas,int(input("Specify Y coord: ")),int(input("Specify X coord: ")),0,2) print2dArray(canvas)
2e2e07b1851ffde8d853cbf8ff5a08f41c4e3c60
haocs/leetcode
/python/2-add-two-numbers.py
791
3.625
4
# source: https://leetcode.com/problems/add-two-numbers/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): carry = 0 result = ListNode(0) ptr...
5ebb13b8d29cc1592e24bbc742d5e1610debc5c3
haocs/leetcode
/python/15-3sum.py
943
3.703125
4
# source: https://leetcode.com/problems/3sum/ class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ def twoSum(nums, l, r, target): # -> pairs sums = [] while l < r: if nums[l] + nums[r...
5e5997eee1736e29f142e996daac201864e0e263
haocs/leetcode
/python/87-scramble-string.py
1,062
3.59375
4
# source: https://leetcode.com/problems/scramble-string/ class Solution(object): def __init__(self): self.cache = {} # str -> bool def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ """ for a string AB, it's sc...
48eb6175bfb5cd98001d480ddf060d01677e20ac
ajay-8192/competitive_program
/Algos/EulerTotient_Algo.py
328
3.5
4
def gcd(a, b): if (a == 0): return b return gcd(b % a, a) def phi(n): result = 1 for i in range(2, n): if (gcd(i, n) == 1): result+=1 return result def main(): for n in range(1, 11): print("phi(",n,") = ",phi(n), sep = "") if __name__ == "__main__": ...
abe55ef8d442b221121d22ee7d4fd3a5916fb49c
Bharat0550/Mini-Projects
/Display Calender_month_year.py
124
3.515625
4
# To display the calender of any month and year import calendar print(calendar.month(2021, 9)) print(calender.month(2077,1)
097a63c09d55dc17208b953b948229ccc960c751
Onyiee/DeitelExercisesInPython
/circle_area.py
486
4.4375
4
# 6.20 (Circle Area) Write an application that prompts the user for the radius of a circle and uses # a method called circleArea to calculate the area of the circle. def circle_area(r): pi = 3.142 area_of_circle = pi * r * r return area_of_circle if __name__ == '__main__': try: r = int(input...
bccd0d8074473316cc7eb69671929cf14ea5c1ac
Onyiee/DeitelExercisesInPython
/Modified_guess_number.py
1,472
4.1875
4
# 6.31 (Guess the Number Modification) Modify the program of Exercise 6.30 to count the number of guesses # the player makes. If the number is 10 or fewer, display Either you know the secret # or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret! # If the player makes more th...
69a5b4659af04434e43c9f243ce1f5dedfae28d5
SIlverAries12/Level-zero-coding-challenges
/python_level_0.5.py
122
3.625
4
def area (a,b,c): s = 0.5*(a + b + c) output = (s*((s-a)*(s-b)*(s-c))) ** 0.5 print(str(output)) area(3, 4, 5)
d047baac4b4a5df847345e204f0a66e248edea7c
pappyhammer/pattern_discovery
/tools/signal.py
3,682
4
4
import numpy as np def smooth_convolve(x, window_len=11, window='hanning'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in ...
ddd5fba066bf1ac38c9aabd333ba8c9cb56c17b9
pappyhammer/pattern_discovery
/tools/loss_function.py
9,525
3.515625
4
import numpy as np import pattern_discovery.tools.trains as trains_module def loss_function_with_sliding_window(spike_nums, time_inter_seq, min_duration_intra_seq, spike_train_mode=False, debug_mode=False): """ Return a float from 0 to 1, representing the loss function. ...
e40e37b0133967a13836699f678471a364a324e2
rhjohnstone/random
/euler_580_v4.py
1,928
3.65625
4
# count the number of Hilbert numbers that are NOT squarefree # because these can be directly constructed, instead of checking every Hilbert number for the squarefree property # a Hilbert number (4k+1) squared is also a Hilbert number # for m(4k+1) to be a Hilbert number, m must also be a Hilbert number import time ...
17a98a8108322114e8c6c2b688103d728edbaa56
rhjohnstone/random
/euler_581.py
1,407
3.640625
4
import math import numpy as np def primes_up_to_N(N): x = np.arange(3,N+1,2) lenx = len(x) for i in xrange(int(np.sqrt(N))-1): a = x[i] if (a==0): continue else: x[np.arange(a/2-1+a,lenx,a)] = 0 x = x[np.where(x>0)] x = np.insert(x,0,2) return x ...
67713e5baf078dfc305085081c7d393bba19d680
Caleb-Ellis/CS50x
/pset6/sentiments/test.py
240
3.65625
4
import nltk from nltk.tokenize import TweetTokenizer s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." tknzr = TweetTokenizer() tokens = tknzr.tokenize(s) tokens = [str.lower() for str in tokens] print(tokens[1]) print(tokens)
3b26b40c9619c6b0eee0a36096688aeb57819f10
Subharanjan-Sahoo/Practice-Questions
/Problem_34.py
810
4.15625
4
''' Single File Programming Question Your little brother has a math assignment to find whether the given number is a power of 2. If it is a power of 2 then he has to find the sum of the digits. If it is not a power of 2, then he has to find the next number which is a power of 2. He asks for your help to validate his w...
0bbb5802a3cfb9cd06a9a458bc77403689dad0ca
Subharanjan-Sahoo/Practice-Questions
/Problem_33.py
1,040
4.375
4
''' Write a program to calculate and return the sum of distances between the adjacent numbers in an array of positive integers Note: You are expected to write code in the find TotalDistance function only which will receive the first parameter as the number of items in the array and second parameter as the array itsel...
565c480183eca3b0e75cd60eb72c92b7cf6909de
Subharanjan-Sahoo/Practice-Questions
/Problem_14.py
363
3.75
4
def numdiv(input1): First = [] Second = [] input2 = list(map(int, input("Enter the Elements: ").strip().split(",")))[:input1] input3 = int(input("Enter the number: ")) First = input2[:input3] Second = input2[input3:] Combine = Second + First print(Combine) input1 = int(input("Ente...
461225afe709aa1b1f4233177376ffee74692506
Subharanjan-Sahoo/Practice-Questions
/Problem_2.py
919
3.984375
4
# Most use Vowel in the String def FindMostFrequentVowel(str): a=0 e=0 x=0 o=0 u=0 for i in range(len(str)): if str[i] == "a" or str[i] == "A": a = a+1 elif str[i] == "e" or str[i] == "E": e= e+1 elif str[i] == "i" or str[i] == "I": ...
9fbe0aabf82ee6efb8730d98edfedfbf88b45a75
Subharanjan-Sahoo/Practice-Questions
/InfyTQ Question/Problem_9.py
270
3.859375
4
def OddEven(input1): a = 0 b = 0 for i in range(len(input1)): if i % 2 == 0: a = a + int(input1[i]) else: b = b + int(input1[i]) print(str((b - a))[1:]) input1 = input("Enter the number: ") OddEven(input1)
97c1bac183bf1c744eb4d1f05b6e0253b1455f10
Subharanjan-Sahoo/Practice-Questions
/Problem_13.py
733
4.21875
4
''' Write a function to find all the words in a string which are palindrome Note: A string is said to be a palindrome if the reverse of the string is the same as string. For example, "abba" is a palindrome, but "abbe" is not a palindrome. Input Specification: input1: string input2: Length of the String Output Spe...
6bd590a16c53b37ddc7d2d484e58fad08c1ce2ce
shivaram93/datasciencecoursera
/Booleans and If Statements-153.py
1,130
4.03125
4
## 1. Booleans ## cat=True dog=False print(cat) type(cat) ## 2. Boolean Operators ## print(cities) first_alb = (cities[0] == "Albuquerque") second_alb = (cities[1] == "Albuquerque") last_element_index = len(cities) - 1 first_last = (cities[0] == cities[last_element_index]) ## 3. Booleans with "Greater Than" ## pri...
4a92944af852b227c6a6d491eaa514d7906f8266
otherness/sec-code-snippets
/byte-to-hex.py
459
3.8125
4
#!/usr/local/bin/python byte_list = [['09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09'], ['54', '68', '65', '20', '4d', '61', '67', '69', '63', '20', '57', '6f', '72', '64', '73', '20']] byte_list.reverse() print "ANSWER in hex:", byte_list #convert byte array to string a...
ae0109f998da6415824a245c51fd5c3b3188424e
MaxwellAllee/PythonPractice
/third_day/carGame.py
638
3.96875
4
command = "" carStatus = False while True: command = input("> ").lower() if command == "start": if carStatus: print("Car is already started") else: carStatus = True print("Car started...") elif command == "stop": if carStatus: print("Ca...
53a43a6b8d98c3742033417b172ad84bc25c0d30
rbbastos/Weather_Processing_App
/db_operations.py
4,626
3.625
4
"""Module: Creates a DBOperations class with functions.""" import sqlite3 import urllib.request import datetime from scrape_weather import WeatherScraper class DBOperations(): """This class contains working with db functions.""" def create_db(self): """Create the table in db.""" try: ...
d30504a329fd5bcb59a284b5e28b89b6d21107e3
lada8sztole/Bulochka-s-makom
/1_5_1.py
479
4.1875
4
# Task 1 # # Make a program that has some sentence (a string) on input and returns a dict containing # all unique words as keys and the number of occurrences as values. # a = 'Apple was sweet as apple' # b = a.split() a = input('enter the string ') def word_count(str): counts = dict() words = str.split() ...
cdc0c71ee2fd47586fca5c145f2c38905919cff5
lada8sztole/Bulochka-s-makom
/1_6_3.py
613
4.25
4
# Task 3 # # Words combination # # Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string. # # For example, the program obtained the word ‘hello’, so it should print 5 random strings(words) # that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’...
687a269e6625f81a45a3dda760e8d202b3f5d61e
dxcv/Contrarian
/Codes/Debug/Rename 3-1.py
1,559
3.625
4
import os; path = os.getcwd() os.chdir("Result") file_name_list = os.listdir() # for old_file_name in file_name_list: # if "-" not in old_file_name: # print(old_file_name) # splitted_file_name = old_file_name.split() # splitted_file_name.insert(-1, "3-1") # new_file_name = " ".join...
85a540b820796e70d969ecf8d89ebf0a163969bb
laravignotto/books_exercises
/Data_Science_Essentials_in_Python/ex_3-1_broken_link_detector.py
933
3.828125
4
''' Given a URL address, this program returns the broken links in the page. This works faster than the solution in the book by making asynchronous requests with grequests (https://github.com/spyoungtech/grequests) ''' import grequests from urllib.request import urlopen from bs4 import BeautifulSoup #get the url page...
434b88f21162613faf3efdbd3deb3812b46788c8
malay190/Assignment_Solutions
/assignment4/ass4_1.py
142
4
4
#Que.Find the length of tuples x=int(input("enter any number")) y=int(input("enter any number")) t=(1,2,"a",1.2,9,x,y) print(t) print(len(t))
dbd3eb8899b9049bef93836c194b4046070d4ce8
malay190/Assignment_Solutions
/assignment18/ass18_1.py
937
4.09375
4
#Q1. Create a dict with name and mobile number.Define a GUI interface using tkinter and pack the label and create a scrollbar #to scroll the list of keys in the dictionary. import tkinter from tkinter import * import sys dic={"rahul":95943053548,"mohit":84593745722,"malay":94524592345,"rajan":87654322678,"nih...
5438b1928dc780927363d3d7622ca0d00247a5c2
malay190/Assignment_Solutions
/assignment9/ass9_5.py
599
4.28125
4
# Q.5- Create a class Expenditure and initialize it with expenditure,savings.Make the following methods. # 1. Display expenditure and savings # 2. Calculate total salary # 3. Display salary class expenditure: def __init__(self,expenditure,savings): self.expenditure=expenditure self.savings=savings def total_s...
8fd0a4330efa1c12a7e10a3f554cd610e98d03e3
malay190/Assignment_Solutions
/assignment11/ass11_1.py
410
3.75
4
#Q1. Create a threading process such that it sleeps for 5 seconds and then prints out a message. #method-1 import threading from threading import Thread import time def display(): print("child thread:",threading.current_thread().getName()) bt=time.time() time.sleep(3) print("child thread:",threading.current_threa...
40ffc248e21edc12a7ca63fb6746fb0836508580
malay190/Assignment_Solutions
/assignment11/ass11_4.py
286
3.8125
4
#Q4. Call factorial function using thread. import threading from threading import Thread import time class factorial(Thread): def run(self): n=int(input("enter any number:")) fact=1 for i in range(1,n+1): fact = fact * i print("factorial:",fact) t=factorial() t.start()
7e34f98134d443a2ad9655cad2ff12e5a6d9ca14
malay190/Assignment_Solutions
/assignmrnt7/ass7_3.py
137
4.15625
4
#Q.3- Print multiplication table of 12 using recursion. def rec(x,y): if y<=10: t=x*y print(t) y+=1 rec(x,y) rec(12,1)
d4c987322a7e4c334bfb78920c52009101a1ba13
malay190/Assignment_Solutions
/assignment6/ass6_4.py
291
4.15625
4
#Q.4- From a list containing ints, strings and floats, make three lists to store them separately l=[1,'a',2,3,3.2,5,8.2] li=[] lf=[] ls=[] for x in l: if type(x)==int: li.append(x) elif type(x)==float: lf.append(x) elif type(x)==str: ls.append(x) print(li) print(lf) print(ls)
e0802d175e1bac66ec466e4d22374d5ef5632c6a
malay190/Assignment_Solutions
/assignmrnt7/ass7_2.py
368
4.0625
4
#Q.2- Write a function “perfect()” that determines if parameter number is a perfect number. #Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. def perfect(num): sum=0 for x in range(1,num): if num%x==0: sum=sum+x if sum==num: print(num,":is a perfect num...
72a8086b765c8036b7f30853e440550a020d7602
bradger68/daily_coding_problems
/dailycodingprob66.py
1,182
4.375
4
"""Assume you have access to a function toss_biased() which returns 0 or 1 with a probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of the coin. Write a function to simulate an unbiased coin toss. """ import random unknown_ratio_heads = random.randint(1,100) unknown_rati...
c604721615c9c30eaa2c089e980a445cace69b93
bradger68/daily_coding_problems
/dailycodingprob70.py
981
4.09375
4
"""A number is considered perfect if its digits sum up to exactly 10. Given a positive integer n, return the n-th perfect number. For example, given 1, you should return 19. Given 2, you should return 28.""" def find_nth_perfnum(n): temporary_sum = 0 for digit in str(n): temporary_sum += int(digit) return...
6292484e4b091e497ef7ecc221d6ba3f1b8cb39f
azakordonets/HandyScripts
/Python/Tasks solving/test3.py
1,455
4.0625
4
# def main(): # text = raw_input("Please type yor text: ") # #example of count of big letters # big_letters_amount = [] # for char in text: # if char >= "A" and char <= "Z": # big_letters_amount.append(char) # print "amount of big letters in text is %s" % len(big_letters_amount) # sentences = 0 #write ...
8a3413b2ee61cc85927b812d71e3a697afb73f37
wooght/HandBook
/python/w_math/base_array.py
2,412
3.796875
4
# -*- coding: utf-8 -*- # # @method : python list,tuple,dict # @Time : 2017/11/17 # @Author : wooght # @File : base_array.py # 词条:reverse [rɪˈvɜ:s] 颠倒 import random from math import * from echo import f f('基础方法') n = random.randrange(1, 5) print(n) n = random.random() print(n) print(floor(10 * n)) print(c...
c4f5f260a9b0a650c5bdd7c2d2f9fce665938380
guyguyguyguyguyguyguy/emergent_scopes
/simple/composition_behaviours.py
10,809
3.59375
4
from __future__ import annotations from abc import abstractclassmethod, abstractmethod, ABC import random import numpy as np from itertools import combinations from typing import List, Tuple from operator import add import helper import agent def in_bounds(agent: agent.Agent) -> None: """ Keep agent in bo...
4e94c69fbf7dd24a64dccd3e429b3569eb608fc2
yahoo17/LearningNotes
/python_demo/demo5.py
963
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'a test module' __author__ ='Michael Yan' import sys def test(): args=sys.argv if len(args)==1: print('Hello world') elif len(args)==2: print('Hello ,%s'%args[1]) else: print("tooo many arguments") if __name__=='__main__': te...
1bf5e323ccfa2ab78392e670907066dd56d2072c
Nishant183/lp1
/lp1/PN/LP1/4/knn_05.py
1,708
3.765625
4
import matplotlib.pyplot as plt import math import sys #using points: is a dictionary of lists of point belonging to region 0 and 1 #using p: the point entered by the user #using k=3 : as default nearest number of neighbours #func - clissify the points using euclidean distances def classify(points,p,k=3): dist = [] ...
8704750b30ff7fe865eec661e1f6661649bd98fd
appfr3d/AdventOfCode2017
/Day 12/day12b.py
853
3.625
4
def connectedWith(index): for n in range(0,len(pipes[index])): if pipes[index][n] not in groups[-1]: groups[-1].append(pipes[index][n]) connectedWith(pipes[index][n]) puzzle = open('day12Input.txt', 'r') pipes = [] for line in puzzle: # remove unwanted data line = line.replace(' <-> ', ' ').replace(', ', ' ...
37932064c09b48f69c8e56460948e0593410b0b9
appfr3d/AdventOfCode2017
/Day 6/day6.py
627
3.609375
4
from copy import deepcopy puzzle = [4, 10, 4, 1, 8, 4, 9, 14, 5, 1, 14, 15, 0, 15, 3, 5]; previous = [puzzle] seenBefore = False count = 0 while not seenBefore: # print(previous) count = count + 1; p = deepcopy(puzzle) maxValue = max(p) maxIndex = p.index(maxValue) p[maxIndex] = 0 for i in range(1,maxValue+1): ...
fbf5c89020b88cd90dbd965950a4822ef00c330e
koffe0522/designpattern
/Main.py
393
3.84375
4
from iterator.book import Book, BookShelf def startMain(): bookShelf = BookShelf() bookShelf.append(Book(name="Aroun d the World in 80 days")) bookShelf.append(Book(name="Bible")) bookShelf.append(Book(name="Cinderella")) bookShelf.append(Book(name="Daddy-Long-Legs")) for book in bookShelf: ...
dd4a53b4417f5315c9f879a1f331b459780408f7
UmaViswa/OOPS-Assignment
/Class_example.py
870
3.875
4
class math_operations(object): class_attribute_example="Something" def __init__(self,a,b): #print ("Called constructor of math operations") self.a=a self.b=b def addition(self): sumof = self.a + self.b #print(sumof) return sumof def subtraction(self): ...
fb3cb37c4ac52c966ebe55dfee1111b0a9da2fdc
boaventura16/Boaventura16
/Estudos/Desafio019.py
624
3.953125
4
c = 0 lista = list() while True: print('='*30) n = int(input('Digite um número: ')) lista.append(n) r = input('Quer Continuar? [S/N]: ').upper().strip() c += 1 if r not in 'SN': print('Opção invalida.') r = input('Quer continuar? [S/N]: ') if r == 'N': if 5 in lista: ...
a0e6389d6fcd10b9e8f2d5883c791205ff9e33d0
boaventura16/Boaventura16
/Estudos/Desafio028.py
265
3.890625
4
estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = input('Unidade Federativa: ') estado['sigla'] = input('Sigla do estado: ') brasil.append(estado.copy()) for e in brasil: for v in e.values(): print(v, end=' ') print()
e42f5c255e8fa3deb966b3cc39f39f3f4c65fa76
boaventura16/Boaventura16
/Estudos/Desafio021.py
373
3.90625
4
ex = input('Digite uma expressão matematica:\n') lista = [] for simb in ex: if simb == '(': lista.append('(') elif simb == ')': if len(lista) > 0: lista.pop() else: lista.append(')') break if len(lista) == 0: print('Sua expressão está correta.') el...
fab286c962d89de446548c23754e33b19809e8ad
boaventura16/Boaventura16
/Estudos/#Desafio 007.py
126
3.734375
4
#Desafio 007 n1 = int(input('Nota 1: ')) n2 = int(input('Nota 2: ')) m = (n1+n2)/2 print('A media do aluno é: {}'.format(m))
57fd96cb2a00a6dd36d2ae683de83cb661717d3c
Aniket762/Hack-Gujarat-
/Unity_to_python_socket/Unity_to_python_socket/Udp_Server_File.py
1,210
3.71875
4
import socket # Here we define the UDP IP address as well as the port number that we have # already defined in the client python script. UDP_IP_ADDRESS = "127.0.0.1" UDP_PORT_NO = 1234 # declare our serverSocket upon which # we will be listening for UDP messages serverSock = socket.socket(socket.AF_INET, socket.SOCK_D...
c6d0f553a3b5297eb49d2fecde49e51d2e9fe641
ColemanHaley/JSALT2019-FST-lab
/fstutils.py
5,067
4.09375
4
def remove_epsilons(string, epsilon='@_EPSILON_SYMBOL_@'): """Removes the epsilon transitions from the string along a path from hfst. Args: string (str): The string (e.g. input path, output form) from which the epsilons should be deleted. epsilon (str, optional): The epsilon string to remove. ...
68c281e253778c4c3640a5c67d2e7948ca8e150a
farahhhag/Python-Projects
/Grade & Attendance Calculator (+Data Validation).py
2,363
4.21875
4
data_valid = False while data_valid == False: grade1 = input("Enter the first grade: ") try: grade1 = float(grade1) except: print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.") continue if grade1 <0 or grade1 > 10: print("...
6e85b53b38083b361d3d6d3a43b2b6fbc9d82ba9
farahhhag/Python-Projects
/Age Comparison.py
226
4.21875
4
my_age = 26 your_age = int( input("Please type your age: ") ) if(my_age > your_age): print("I'm older than you") elif(my_age == your_age): print("We are the same age") else: print("You're older than me")
5e86a0009b9772cdb7db30b4fe9c30fa188b81c3
TaehoLi/Elementary-Python
/list_tuple/listcat.py
125
3.765625
4
list1 = [1, 2, 3, 4, 5] list2 = [10, 11] listadd = list1 + list2 print(listadd) listmulti = list2 * 3 print(listmulti)
85a6a8a1a40d384a727b0c51dd1f8d1a66e4cb0a
TaehoLi/Elementary-Python
/decorator/localfunc.py
171
3.75
4
def calcsum(n): def add(a,b): return a+b sum = 0 for i in range(n+1): sum = add(sum, i) return sum print('~10 =', calcsum(10))
3de5bc62ff32f07ca9ced0af29f66b3616d791c9
TaehoLi/Elementary-Python
/list_tuple/listreplace.py
100
3.609375
4
nums = [0,1,2,3,4,5,6,7,8,9] nums[2:5] = [20,30,40] print(nums) nums[6:] = [90,91] print(nums)
92f70d0e38bc2ac662888167e7b93dc544fe5e39
TaehoLi/Elementary-Python
/graphic/askstring.py
507
3.640625
4
from tkinter import * import tkinter.messagebox import tkinter.simpledialog main = Tk() def btnclick(): name = tkinter.simpledialog.askstring("질문", "이름을 입력하시오") age = tkinter.simpledialog.askinteger("질문", "나이를 입력하시오") if name and age: tkinter.messagebox.showwarning("환영", str(age) + "세 " ...
07ce2b737b3702cb761caf5cd0571c09de096150
sahirabibi/pong
/paddle.py
719
4.0625
4
# create paddle class in order to generate paddles for Pong from turtle import Turtle class Paddle(Turtle): def __init__(self, position): super().__init__() self.shape("square") self.penup() self.setheading(90) self.color("white") self.shapesize(stretch_len=5) ...
87fa091ab9c42b1bf8bb44125810496358f49e08
dlewis2017/PyGame
/board.py
645
3.578125
4
import pygame from spritesheet import spritesheet from pygame.locals import * import numpy """1 is water, 2 is ship, 3 is HIT, 4 is miss, 5 is opponent ship""" class Board(object): def __init__(self): self.Matrix = [[1 for x in range(10)] for y in range(10)] self.opp_ship_spaces = 10 def setSpace(self,x,y,new...
82f5a480a9535f15d17700480c94782aed2a34ba
5l1v3r1/robots1
/xcommandx.py
746
3.5625
4
import sys def spl(string, length): return ' '.join(string[i:i+length] for i in xrange(0,len(string),length)) def binS2int(string): # print string num=0 count=1 for i in range (0,8): num += int(string[i])*(128/count) count=count*2 return num fname="beepboop.txt" f=open(fname) lines=f.readlines()...
2506f6e4867d35f16b8fb00293236b7dd00d5cb8
BR610/calculator-2
/calculator_pre.py
1,476
4.09375
4
def calculator_pre(): """pre-fix calculator, takes in input and performs requested operations""" input_lst2 = [] input_op = raw_input("Please enter your choice: ") input_lst = input_op.split(" ") if input_lst[0] == "q" or input_lst[0] == "quit": return "Quitting function" else: ...
95c0cfdf0cac0422afe0bbe8c76a4c766b696b84
DieusGD/Proyecto-web-python
/Practicas/DatosEnListas.py
1,565
3.96875
4
def datSim(): #esta es una lista DatoSimple cuenta = int(input("cuantos datos deseas procesar? \n")) datos = [] conteo=1 while conteo <= cuenta: dato = input("dato a procesar: \n") datos.append(dato) conteo = conteo + 1 else: print(datos) def datMed(): #este ...
985d57c54dceec13b20e89aa4904c1f0263474cc
tintin10q/RandomPythonProjects
/btw.py
460
4.0625
4
# # # done = False # # while done is not True: # number_input = input("Give a price:") # try: # number_input = int(number_input) # if number_input <= 0: # print('Number needs to be more then 0') # else: # print("Price with btw is:", number_input * 1.21) # ...
ac18a73fbbabb18d704701f3b379a370b2bd69e9
besnik/pycon2017-closures
/python/09_closure_over_func.py
918
3.59375
4
# closure over function def counter(func): count = 0 def inc_count(): func() nonlocal count count += 1 print(" Called", count, "times") return inc_count def hello(): print("Hi PyCon") inc = counter(hello) inc() inc() inc() # closures over func def create_logic(func)...
a36be10c97b7e350aa41cb95df56e33af380febd
ivangonekrazy/colorgame
/solver/cell.py
858
3.71875
4
class Cell(object): """ Stores the possible Pieces for any given Cell. """ def __init__(self, height): self.height = height self.colors = list("RGBPYO") self.proposal = None def set_color(self, color): if not color in self.colors: raise Exception("color already ...
c68084826badc09dd3f037098bfcfbccb712ee15
kayazdan/exercises
/chapter-5.2/ex-5-15.py
2,923
4.40625
4
# Programming Exercise 5-15 # # Program to find the average of five scores and output the scores and average with letter grade equivalents. # This program prompts a user for five numerical scores, # calculates their average, and assigns letter grades to each, # and outputs the list and average as a table on the sc...
ed61c43c7ab9b7ea26b890a00a08d2ed52ba3e47
kayazdan/exercises
/chapter-3/exercise-3-1.py
1,209
4.65625
5
# Programming Exercise 3-1 # # Program to display the name of a week day from its number. # This program prompts a user for the number (1 to 7) # and uses it to choose the name of a weekday # to display on the screen. # Variables to hold the day of the week and the name of the day. # Be sure to initialize the ...
06e879dd6a2657fc014a95194c21d46ade187750
joaolucas1337/Calculadora-em-python
/Calculadora.py
909
4.09375
4
def soma(n1, n2): return n1 + n2 def subtracao(n1, n2): return n1 - n2 def multiplicacao(n1, n2): return n1 * n2 def divisao(n1, n2): return n1 / n2 cont = True while cont: n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) ca...
32df186638244d5e02772da98c81b58a7f311c6d
adhikarchaudhary12/oop_python
/decorator3.py
294
3.71875
4
#decorating function with parameters def smart_divide(func): def inner(a,b): if b == 0: print("Cannot divide by zero") return None return func(a,b) return inner @smart_divide def divide(a,b): return a/b result = divide(6,2) print(result)
bfed62786fe29f26293669c97b39f2f58d153030
adhikarchaudhary12/oop_python
/class_example6.py
179
3.84375
4
#object copying import copy class Point: def __init__(self,x,y): self.x=x self.y=y p=Point(1,2) q = copy.copy(p) q.x = 2 print(p==q) print(p.x) print(q.x)
228027932cf3a8efa42d8824053a6131b372e963
nandhakumarv5858/Nandha
/prime number.py
192
4.21875
4
prime=int(input("Enter your number\n")) if prime>1: for i in range(prime): if (prime % 2)==0: print(prime,"is not a prime number") break else: print(prime," It is a prime number")
233fee092f2443c9f5a7afa6b9e3ff5f6947f22f
PointerFLY/LeetCode-Python3
/6_zigzag_conversion.py
778
3.515625
4
class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s rows = [''] * numRows str_idx = 0 i = 0 down = True while str_idx < len(s): r...
3f93cce60f09f0174fa3dcfa141f279a16926457
iggirex/pythonHardWay
/ex2.py
246
3.890625
4
print "I will now count my chickens" print "Roosters", 100 - 25 * 3 / 4 print "Now I will count the eggs" print float(3 + 2 + 1 - 5 + 40 % 2) print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", float(3 + 2.5)
627396617109d519b142a2e8299ba0d0e9890e90
Luk390/Alien-Game
/ship.py
1,202
3.796875
4
import pygame from pygame.sprite import Sprite class Ship(Sprite): """Manages the ship""" def __init__(self, ai_game): super().__init__() self.screen = ai_game.screen self.screen_rect = ai_game.screen.get_rect() self.settings = ai_game.settings # Load the ship image to the rect self.image = pygame.image...